java/sql-dk/src/info/globalcode/sql/dk/InfoLister.java
author František Kučera <franta-hg@frantovo.cz>
Sat, 15 Aug 2015 11:52:38 +0200
branchv_0
changeset 212 d154d6012cbe
parent 211 b5148f646278
child 214 1fb3c7953d8a
permissions -rw-r--r--
property annotations: first version (inherited properties are not working yet)
franta-hg@16
     1
/**
franta-hg@16
     2
 * SQL-DK
franta-hg@16
     3
 * Copyright © 2013 František Kučera (frantovo.cz)
franta-hg@16
     4
 *
franta-hg@16
     5
 * This program is free software: you can redistribute it and/or modify
franta-hg@16
     6
 * it under the terms of the GNU General Public License as published by
franta-hg@16
     7
 * the Free Software Foundation, either version 3 of the License, or
franta-hg@16
     8
 * (at your option) any later version.
franta-hg@16
     9
 *
franta-hg@16
    10
 * This program is distributed in the hope that it will be useful,
franta-hg@16
    11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
franta-hg@16
    12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
franta-hg@16
    13
 * GNU General Public License for more details.
franta-hg@16
    14
 *
franta-hg@16
    15
 * You should have received a copy of the GNU General Public License
franta-hg@16
    16
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
franta-hg@16
    17
 */
franta-hg@14
    18
package info.globalcode.sql.dk;
franta-hg@14
    19
franta-hg@203
    20
import info.globalcode.sql.dk.configuration.CommandArgument;
franta-hg@67
    21
import info.globalcode.sql.dk.configuration.Configuration;
franta-hg@65
    22
import info.globalcode.sql.dk.configuration.ConfigurationException;
franta-hg@26
    23
import info.globalcode.sql.dk.configuration.ConfigurationProvider;
franta-hg@65
    24
import info.globalcode.sql.dk.configuration.DatabaseDefinition;
franta-hg@67
    25
import info.globalcode.sql.dk.configuration.FormatterDefinition;
franta-hg@160
    26
import info.globalcode.sql.dk.configuration.Properties;
franta-hg@159
    27
import info.globalcode.sql.dk.configuration.Property;
franta-hg@212
    28
import info.globalcode.sql.dk.configuration.PropertyDeclaration;
franta-hg@212
    29
import info.globalcode.sql.dk.configuration.PropertyDeclarations;
franta-hg@203
    30
import info.globalcode.sql.dk.configuration.TunnelDefinition;
franta-hg@69
    31
import info.globalcode.sql.dk.formatting.ColumnsHeader;
franta-hg@212
    32
import info.globalcode.sql.dk.formatting.CommonProperties;
franta-hg@159
    33
import info.globalcode.sql.dk.formatting.FakeSqlArray;
franta-hg@69
    34
import info.globalcode.sql.dk.formatting.Formatter;
franta-hg@69
    35
import info.globalcode.sql.dk.formatting.FormatterContext;
franta-hg@69
    36
import info.globalcode.sql.dk.formatting.FormatterException;
franta-hg@17
    37
import java.io.BufferedReader;
franta-hg@160
    38
import java.io.ByteArrayOutputStream;
franta-hg@17
    39
import java.io.InputStreamReader;
franta-hg@14
    40
import java.io.PrintStream;
franta-hg@159
    41
import java.sql.Array;
franta-hg@158
    42
import java.sql.Driver;
franta-hg@196
    43
import java.sql.DriverManager;
franta-hg@159
    44
import java.sql.DriverPropertyInfo;
franta-hg@65
    45
import java.sql.SQLException;
franta-hg@70
    46
import java.util.ArrayList;
franta-hg@201
    47
import java.util.Collections;
franta-hg@201
    48
import java.util.Comparator;
franta-hg@70
    49
import java.util.EnumSet;
franta-hg@159
    50
import java.util.HashSet;
franta-hg@66
    51
import java.util.List;
franta-hg@200
    52
import java.util.Map.Entry;
franta-hg@158
    53
import java.util.ServiceLoader;
franta-hg@159
    54
import java.util.Set;
franta-hg@183
    55
import java.util.concurrent.ExecutorService;
franta-hg@183
    56
import java.util.concurrent.Executors;
franta-hg@183
    57
import java.util.concurrent.TimeUnit;
franta-hg@17
    58
import java.util.logging.Level;
franta-hg@196
    59
import java.util.logging.LogRecord;
franta-hg@17
    60
import java.util.logging.Logger;
franta-hg@69
    61
import javax.sql.rowset.RowSetMetaDataImpl;
franta-hg@14
    62
franta-hg@14
    63
/**
franta-hg@14
    64
 * Displays info like help, version etc.
franta-hg@14
    65
 *
franta-hg@14
    66
 * @author Ing. František Kučera (frantovo.cz)
franta-hg@14
    67
 */
franta-hg@14
    68
public class InfoLister {
franta-hg@14
    69
franta-hg@17
    70
	private static final Logger log = Logger.getLogger(InfoLister.class.getName());
franta-hg@159
    71
	/**
franta-hg@159
    72
	 * Fake database name for output formatting
franta-hg@159
    73
	 */
franta-hg@159
    74
	public static final String CONFIG_DB_NAME = "sqldk_configuration";
franta-hg@183
    75
	private final PrintStream out;
franta-hg@183
    76
	private final ConfigurationProvider configurationProvider;
franta-hg@183
    77
	private final CLIOptions options;
franta-hg@70
    78
	private Formatter formatter;
franta-hg@17
    79
franta-hg@69
    80
	public InfoLister(PrintStream out, ConfigurationProvider configurationProvider, CLIOptions options) {
franta-hg@17
    81
		this.out = out;
franta-hg@20
    82
		this.configurationProvider = configurationProvider;
franta-hg@69
    83
		this.options = options;
franta-hg@17
    84
	}
franta-hg@17
    85
franta-hg@70
    86
	public void showInfo() throws ConfigurationException, FormatterException {
franta-hg@70
    87
		EnumSet<InfoType> commands = options.getShowInfo();
franta-hg@70
    88
franta-hg@139
    89
		boolean formattinNeeded = false;
franta-hg@139
    90
franta-hg@70
    91
		for (InfoType infoType : commands) {
franta-hg@70
    92
			switch (infoType) {
franta-hg@70
    93
				case CONNECTION:
franta-hg@158
    94
				case JDBC_DRIVERS:
franta-hg@159
    95
				case JDBC_PROPERTIES:
franta-hg@70
    96
				case DATABASES:
franta-hg@70
    97
				case FORMATTERS:
franta-hg@210
    98
				case FORMATTER_PROPERTIES:
franta-hg@70
    99
				case TYPES:
franta-hg@200
   100
				case JAVA_PROPERTIES:
franta-hg@200
   101
				case ENVIRONMENT_VARIABLES:
franta-hg@139
   102
					formattinNeeded = true;
franta-hg@101
   103
					break;
franta-hg@70
   104
			}
franta-hg@70
   105
		}
franta-hg@139
   106
franta-hg@139
   107
		if (formattinNeeded) {
franta-hg@139
   108
			try (Formatter f = getFormatter()) {
franta-hg@139
   109
				formatter = f;
franta-hg@139
   110
				formatter.writeStartBatch();
franta-hg@159
   111
				DatabaseDefinition dd = new DatabaseDefinition();
franta-hg@159
   112
				dd.setName(CONFIG_DB_NAME);
franta-hg@159
   113
				formatter.writeStartDatabase(dd);
franta-hg@139
   114
				showInfos(commands);
franta-hg@139
   115
				formatter.writeEndDatabase();
franta-hg@139
   116
				formatter.writeEndBatch();
franta-hg@139
   117
				formatter.close();
franta-hg@139
   118
			}
franta-hg@139
   119
		} else {
franta-hg@139
   120
			showInfos(commands);
franta-hg@139
   121
		}
franta-hg@101
   122
	}
franta-hg@70
   123
franta-hg@101
   124
	private void showInfos(EnumSet<InfoType> commands) throws ConfigurationException, FormatterException {
franta-hg@70
   125
		for (InfoType infoType : commands) {
franta-hg@70
   126
			infoType.showInfo(this);
franta-hg@70
   127
		}
franta-hg@70
   128
	}
franta-hg@70
   129
franta-hg@200
   130
	private void listJavaProperties() throws FormatterException, ConfigurationException {
franta-hg@200
   131
		ColumnsHeader header = constructHeader(new HeaderField("name", SQLType.VARCHAR), new HeaderField("value", SQLType.VARCHAR));
franta-hg@200
   132
		List<Object[]> data = new ArrayList<>();
franta-hg@200
   133
		for (Entry<Object, Object> e : System.getProperties().entrySet()) {
franta-hg@200
   134
			data.add(new Object[]{e.getKey(), e.getValue()});
franta-hg@200
   135
		}
franta-hg@201
   136
		printTable(formatter, header, "-- Java system properties", null, data, 0);
franta-hg@200
   137
	}
franta-hg@200
   138
franta-hg@200
   139
	private void listEnvironmentVariables() throws FormatterException, ConfigurationException {
franta-hg@200
   140
		ColumnsHeader header = constructHeader(new HeaderField("name", SQLType.VARCHAR), new HeaderField("value", SQLType.VARCHAR));
franta-hg@200
   141
		List<Object[]> data = new ArrayList<>();
franta-hg@200
   142
		for (Entry<String, String> e : System.getenv().entrySet()) {
franta-hg@200
   143
			data.add(new Object[]{e.getKey(), e.getValue()});
franta-hg@200
   144
		}
franta-hg@201
   145
		printTable(formatter, header, "-- environment variables", null, data, 0);
franta-hg@200
   146
	}
franta-hg@200
   147
franta-hg@72
   148
	private void listFormatters() throws ConfigurationException, FormatterException {
franta-hg@72
   149
		ColumnsHeader header = constructHeader(
franta-hg@72
   150
				new HeaderField("name", SQLType.VARCHAR),
franta-hg@72
   151
				new HeaderField("built_in", SQLType.BOOLEAN),
franta-hg@72
   152
				new HeaderField("default", SQLType.BOOLEAN),
franta-hg@160
   153
				new HeaderField("class_name", SQLType.VARCHAR),
franta-hg@160
   154
				new HeaderField("valid", SQLType.BOOLEAN));
franta-hg@72
   155
		List<Object[]> data = new ArrayList<>();
franta-hg@72
   156
franta-hg@72
   157
		String defaultFormatter = configurationProvider.getConfiguration().getDefaultFormatter();
franta-hg@72
   158
		defaultFormatter = defaultFormatter == null ? Configuration.DEFAULT_FORMATTER : defaultFormatter;
franta-hg@72
   159
franta-hg@69
   160
		for (FormatterDefinition fd : configurationProvider.getConfiguration().getBuildInFormatters()) {
franta-hg@160
   161
			data.add(new Object[]{fd.getName(), true, defaultFormatter.equals(fd.getName()), fd.getClassName(), isInstantiable(fd)});
franta-hg@69
   162
		}
franta-hg@72
   163
franta-hg@72
   164
		for (FormatterDefinition fd : configurationProvider.getConfiguration().getFormatters()) {
franta-hg@160
   165
			data.add(new Object[]{fd.getName(), false, defaultFormatter.equals(fd.getName()), fd.getClassName(), isInstantiable(fd)});
franta-hg@69
   166
		}
franta-hg@72
   167
franta-hg@183
   168
		printTable(formatter, header, "-- configured and built-in output formatters", null, data);
franta-hg@160
   169
	}
franta-hg@72
   170
franta-hg@160
   171
	private boolean isInstantiable(FormatterDefinition fd) {
franta-hg@160
   172
		try {
franta-hg@160
   173
			try (ByteArrayOutputStream testStream = new ByteArrayOutputStream()) {
franta-hg@160
   174
				fd.getInstance(new FormatterContext(testStream, new Properties(0)));
franta-hg@160
   175
				return true;
franta-hg@160
   176
			}
franta-hg@160
   177
		} catch (Exception e) {
franta-hg@160
   178
			log.log(Level.SEVERE, "Unable to create an instance of formatter: " + fd.getName(), e);
franta-hg@160
   179
			return false;
franta-hg@160
   180
		}
franta-hg@69
   181
	}
franta-hg@67
   182
franta-hg@211
   183
	private void listFormatterProperties() throws FormatterException, ConfigurationException {
franta-hg@211
   184
		for (String formatterName : options.getFormatterNamesToListProperties()) {
franta-hg@211
   185
			listFormatterProperties(formatterName);
franta-hg@209
   186
		}
franta-hg@209
   187
	}
franta-hg@209
   188
franta-hg@211
   189
	private void listFormatterProperties(String formatterName) throws FormatterException, ConfigurationException {
franta-hg@212
   190
		FormatterDefinition fd = configurationProvider.getConfiguration().getFormatter(formatterName);
franta-hg@212
   191
		try {
franta-hg@211
   192
franta-hg@212
   193
			ColumnsHeader header = constructHeader(
franta-hg@212
   194
					new HeaderField("name", SQLType.VARCHAR),
franta-hg@212
   195
					new HeaderField("type", SQLType.VARCHAR),
franta-hg@212
   196
					new HeaderField("default", SQLType.VARCHAR),
franta-hg@212
   197
					new HeaderField("description", SQLType.VARCHAR)
franta-hg@212
   198
			);
franta-hg@212
   199
			List<Object[]> data = new ArrayList<>();
franta-hg@211
   200
franta-hg@212
   201
			Class<Formatter> formatterClass = (Class<Formatter>) Class.forName(fd.getClassName());
franta-hg@211
   202
franta-hg@212
   203
			// TOOD: formatterClass.getDeclaredAnnotation(PropertyDeclarations.class); and separate inherited properties
franta-hg@212
   204
			// Repeated PropertyDeclaration wrapped in PropertyDeclarations
franta-hg@212
   205
			PropertyDeclarations properties = formatterClass.getAnnotation(PropertyDeclarations.class);
franta-hg@212
   206
			if (properties == null) {
franta-hg@212
   207
				log.log(Level.WARNING, "Formatter „{0}“  has no declared properties", formatterName);
franta-hg@212
   208
			} else {
franta-hg@212
   209
				for (PropertyDeclaration p : properties.value()) {
franta-hg@212
   210
					data.add(propertyDeclarationToRow(p));
franta-hg@212
   211
				}
franta-hg@212
   212
			}
franta-hg@212
   213
franta-hg@212
   214
			// Single PropertyDeclaration
franta-hg@212
   215
			PropertyDeclaration property = formatterClass.getAnnotation(PropertyDeclaration.class);
franta-hg@212
   216
			if (property != null) {
franta-hg@212
   217
				data.add(propertyDeclarationToRow(property));
franta-hg@212
   218
			}
franta-hg@212
   219
franta-hg@212
   220
			List<Parameter> parameters = new ArrayList<>();
franta-hg@212
   221
			parameters.add(new NamedParameter("formatter", formatterName, SQLType.VARCHAR));
franta-hg@212
   222
franta-hg@212
   223
			printTable(formatter, header, "-- formatter properties", parameters, data);
franta-hg@212
   224
		} catch (ClassNotFoundException e) {
franta-hg@212
   225
			throw new ConfigurationException("Unable to find class " + fd.getClassName() + " of formatter" + fd.getName(), e);
franta-hg@212
   226
		}
franta-hg@212
   227
	}
franta-hg@212
   228
franta-hg@212
   229
	private static Object[] propertyDeclarationToRow(PropertyDeclaration p) {
franta-hg@212
   230
		return new Object[]{
franta-hg@212
   231
			p.name(),
franta-hg@212
   232
			CommonProperties.getSimpleTypeName(p.type()),
franta-hg@212
   233
			p.defaultValue(),
franta-hg@212
   234
			p.description()
franta-hg@212
   235
		};
franta-hg@211
   236
	}
franta-hg@211
   237
franta-hg@210
   238
	private void listTypes() throws FormatterException, ConfigurationException {
franta-hg@70
   239
		ColumnsHeader header = constructHeader(new HeaderField("name", SQLType.VARCHAR), new HeaderField("code", SQLType.INTEGER));
franta-hg@70
   240
		List<Object[]> data = new ArrayList<>();
franta-hg@70
   241
		for (SQLType sqlType : SQLType.values()) {
franta-hg@70
   242
			data.add(new Object[]{sqlType.name(), sqlType.getCode()});
franta-hg@70
   243
		}
franta-hg@183
   244
		printTable(formatter, header, "-- data types", null, data);
franta-hg@93
   245
		log.log(Level.INFO, "Type names in --types option are case insensitive");
franta-hg@69
   246
	}
franta-hg@67
   247
franta-hg@210
   248
	private void listDatabases() throws ConfigurationException, FormatterException {
franta-hg@72
   249
		ColumnsHeader header = constructHeader(
franta-hg@72
   250
				new HeaderField("database_name", SQLType.VARCHAR),
franta-hg@72
   251
				new HeaderField("user_name", SQLType.VARCHAR),
franta-hg@72
   252
				new HeaderField("database_url", SQLType.VARCHAR));
franta-hg@72
   253
		List<Object[]> data = new ArrayList<>();
franta-hg@72
   254
franta-hg@69
   255
		final List<DatabaseDefinition> configuredDatabases = configurationProvider.getConfiguration().getDatabases();
franta-hg@69
   256
		if (configuredDatabases.isEmpty()) {
franta-hg@69
   257
			log.log(Level.WARNING, "No databases are configured.");
franta-hg@69
   258
		} else {
franta-hg@69
   259
			for (DatabaseDefinition dd : configuredDatabases) {
franta-hg@72
   260
				data.add(new Object[]{dd.getName(), dd.getUserName(), dd.getUrl()});
franta-hg@203
   261
franta-hg@203
   262
				final TunnelDefinition tunnel = dd.getTunnel();
franta-hg@203
   263
				if (tunnel != null) {
franta-hg@203
   264
					log.log(Level.INFO, "Tunnel command: {0}", tunnel.getCommand());
franta-hg@203
   265
					for (CommandArgument ca : Functions.notNull(tunnel.getArguments())) {
franta-hg@203
   266
						log.log(Level.INFO, "\targument: {0}/{1}", new Object[]{ca.getType(), ca.getValue()});
franta-hg@203
   267
					}
franta-hg@203
   268
				}
franta-hg@203
   269
franta-hg@14
   270
			}
franta-hg@14
   271
		}
franta-hg@72
   272
franta-hg@183
   273
		printTable(formatter, header, "-- configured databases", null, data);
franta-hg@14
   274
	}
franta-hg@17
   275
franta-hg@210
   276
	private void listJdbcDrivers() throws FormatterException, ConfigurationException {
franta-hg@158
   277
		ColumnsHeader header = constructHeader(
franta-hg@158
   278
				new HeaderField("class", SQLType.VARCHAR),
franta-hg@158
   279
				new HeaderField("version", SQLType.VARCHAR),
franta-hg@158
   280
				new HeaderField("major", SQLType.INTEGER),
franta-hg@158
   281
				new HeaderField("minor", SQLType.INTEGER),
franta-hg@158
   282
				new HeaderField("jdbc_compliant", SQLType.BOOLEAN));
franta-hg@158
   283
		List<Object[]> data = new ArrayList<>();
franta-hg@158
   284
franta-hg@158
   285
		final ServiceLoader<Driver> drivers = ServiceLoader.load(Driver.class);
franta-hg@158
   286
		for (Driver d : drivers) {
franta-hg@158
   287
			data.add(new Object[]{
franta-hg@158
   288
				d.getClass().getName(),
franta-hg@158
   289
				d.getMajorVersion() + "." + d.getMinorVersion(),
franta-hg@158
   290
				d.getMajorVersion(),
franta-hg@158
   291
				d.getMinorVersion(),
franta-hg@159
   292
				d.jdbcCompliant()
franta-hg@159
   293
			});
franta-hg@158
   294
		}
franta-hg@158
   295
franta-hg@183
   296
		printTable(formatter, header, "-- discovered JDBC drivers (available on the CLASSPATH)", null, data);
franta-hg@159
   297
	}
franta-hg@158
   298
franta-hg@210
   299
	private void listJdbcProperties() throws FormatterException, ConfigurationException {
franta-hg@159
   300
		for (String dbName : options.getDatabaseNamesToListProperties()) {
franta-hg@159
   301
			ColumnsHeader header = constructHeader(
franta-hg@159
   302
					new HeaderField("property_name", SQLType.VARCHAR),
franta-hg@159
   303
					new HeaderField("required", SQLType.BOOLEAN),
franta-hg@159
   304
					new HeaderField("choices", SQLType.ARRAY),
franta-hg@159
   305
					new HeaderField("configured_value", SQLType.VARCHAR),
franta-hg@159
   306
					new HeaderField("description", SQLType.VARCHAR));
franta-hg@159
   307
			List<Object[]> data = new ArrayList<>();
franta-hg@159
   308
franta-hg@159
   309
			DatabaseDefinition dd = configurationProvider.getConfiguration().getDatabase(dbName);
franta-hg@159
   310
franta-hg@159
   311
			Driver driver = findDriver(dd);
franta-hg@159
   312
franta-hg@159
   313
			if (driver == null) {
franta-hg@159
   314
				log.log(Level.WARNING, "No JDBC driver was found for DB: {0} with URL: {1}", new Object[]{dd.getName(), dd.getUrl()});
franta-hg@159
   315
			} else {
franta-hg@159
   316
				log.log(Level.INFO, "For DB: {0} was found JDBC driver: {1}", new Object[]{dd.getName(), driver.getClass().getName()});
franta-hg@159
   317
franta-hg@159
   318
				try {
franta-hg@159
   319
					DriverPropertyInfo[] propertyInfos = driver.getPropertyInfo(dd.getUrl(), dd.getProperties().getJavaProperties());
franta-hg@159
   320
franta-hg@159
   321
					Set<String> standardProperties = new HashSet<>();
franta-hg@159
   322
franta-hg@159
   323
					for (DriverPropertyInfo pi : propertyInfos) {
franta-hg@159
   324
						Array choices = new FakeSqlArray(pi.choices, SQLType.VARCHAR);
franta-hg@159
   325
						data.add(new Object[]{
franta-hg@159
   326
							pi.name,
franta-hg@159
   327
							pi.required,
franta-hg@159
   328
							choices.getArray() == null ? "" : choices,
franta-hg@159
   329
							pi.value == null ? "" : pi.value,
franta-hg@159
   330
							pi.description
franta-hg@159
   331
						});
franta-hg@159
   332
						standardProperties.add(pi.name);
franta-hg@159
   333
					}
franta-hg@159
   334
franta-hg@159
   335
					for (Property p : dd.getProperties()) {
franta-hg@159
   336
						if (!standardProperties.contains(p.getName())) {
franta-hg@159
   337
							data.add(new Object[]{
franta-hg@159
   338
								p.getName(),
franta-hg@159
   339
								"",
franta-hg@159
   340
								"",
franta-hg@159
   341
								p.getValue(),
franta-hg@159
   342
								""
franta-hg@159
   343
							});
franta-hg@159
   344
							log.log(Level.WARNING, "Your configuration contains property „{0}“ not declared by the JDBC driver.", p.getName());
franta-hg@159
   345
						}
franta-hg@159
   346
					}
franta-hg@159
   347
franta-hg@159
   348
				} catch (SQLException e) {
franta-hg@159
   349
					log.log(Level.WARNING, "Error during getting property infos.", e);
franta-hg@159
   350
				}
franta-hg@159
   351
franta-hg@159
   352
				List<Parameter> parameters = new ArrayList<>();
franta-hg@197
   353
				parameters.add(new NamedParameter("database", dbName, SQLType.VARCHAR));
franta-hg@159
   354
				parameters.add(new NamedParameter("driver_class", driver.getClass().getName(), SQLType.VARCHAR));
franta-hg@159
   355
				parameters.add(new NamedParameter("driver_major_version", driver.getMajorVersion(), SQLType.INTEGER));
franta-hg@159
   356
				parameters.add(new NamedParameter("driver_minor_version", driver.getMinorVersion(), SQLType.INTEGER));
franta-hg@159
   357
franta-hg@183
   358
				printTable(formatter, header, "-- configured and configurable JDBC driver properties", parameters, data);
franta-hg@159
   359
			}
franta-hg@159
   360
		}
franta-hg@159
   361
franta-hg@159
   362
	}
franta-hg@159
   363
franta-hg@159
   364
	private Driver findDriver(DatabaseDefinition dd) {
franta-hg@159
   365
		final ServiceLoader<Driver> drivers = ServiceLoader.load(Driver.class);
franta-hg@159
   366
		for (Driver d : drivers) {
franta-hg@159
   367
			try {
franta-hg@159
   368
				if (d.acceptsURL(dd.getUrl())) {
franta-hg@159
   369
					return d;
franta-hg@159
   370
				}
franta-hg@159
   371
			} catch (SQLException e) {
franta-hg@159
   372
				log.log(Level.WARNING, "Error during finding JDBC driver for: " + dd.getName(), e);
franta-hg@159
   373
			}
franta-hg@159
   374
		}
franta-hg@159
   375
		return null;
franta-hg@158
   376
	}
franta-hg@158
   377
franta-hg@183
   378
	/**
franta-hg@183
   379
	 * Parallelism for connection testing – maximum concurrent database connections.
franta-hg@183
   380
	 */
franta-hg@183
   381
	private static final int TESTING_THREAD_COUNT = 64;
franta-hg@183
   382
	/**
franta-hg@183
   383
	 * Time limit for all connection testing threads – particular timeouts per connection will be
franta-hg@183
   384
	 * much smaller.
franta-hg@183
   385
	 */
franta-hg@183
   386
	private static final long TESTING_AWAIT_LIMIT = 1;
franta-hg@183
   387
	private static final TimeUnit TESTING_AWAIT_UNIT = TimeUnit.DAYS;
franta-hg@183
   388
franta-hg@210
   389
	private void testConnections() throws FormatterException, ConfigurationException {
franta-hg@73
   390
		ColumnsHeader header = constructHeader(
franta-hg@73
   391
				new HeaderField("database_name", SQLType.VARCHAR),
franta-hg@74
   392
				new HeaderField("configured", SQLType.BOOLEAN),
franta-hg@74
   393
				new HeaderField("connected", SQLType.BOOLEAN));
franta-hg@73
   394
franta-hg@183
   395
		log.log(Level.FINE, "Testing DB connections in {0} threads", TESTING_THREAD_COUNT);
franta-hg@183
   396
franta-hg@183
   397
		ExecutorService es = Executors.newFixedThreadPool(TESTING_THREAD_COUNT);
franta-hg@183
   398
franta-hg@183
   399
		final Formatter currentFormatter = formatter;
franta-hg@183
   400
franta-hg@183
   401
		printHeader(currentFormatter, header, "-- database configuration and connectivity test", null);
franta-hg@183
   402
franta-hg@183
   403
		for (final String dbName : options.getDatabaseNamesToTest()) {
franta-hg@196
   404
			preloadDriver(dbName);
franta-hg@196
   405
		}
franta-hg@196
   406
franta-hg@196
   407
		for (final String dbName : options.getDatabaseNamesToTest()) {
franta-hg@209
   408
			es.submit(() -> {
franta-hg@209
   409
				final Object[] row = testConnection(dbName);
franta-hg@209
   410
				synchronized (currentFormatter) {
franta-hg@209
   411
					printRow(currentFormatter, row);
franta-hg@183
   412
				}
franta-hg@209
   413
			}
franta-hg@209
   414
			);
franta-hg@74
   415
		}
franta-hg@73
   416
franta-hg@183
   417
		es.shutdown();
franta-hg@183
   418
franta-hg@183
   419
		try {
franta-hg@183
   420
			log.log(Level.FINEST, "Waiting for test results: {0} {1}", new Object[]{TESTING_AWAIT_LIMIT, TESTING_AWAIT_UNIT.name()});
franta-hg@183
   421
			boolean finished = es.awaitTermination(TESTING_AWAIT_LIMIT, TESTING_AWAIT_UNIT);
franta-hg@183
   422
			if (finished) {
franta-hg@183
   423
				log.log(Level.FINEST, "All testing threads finished in time limit.");
franta-hg@183
   424
			} else {
franta-hg@183
   425
				throw new FormatterException("Exceeded total time limit for test threads – this should never happen");
franta-hg@183
   426
			}
franta-hg@183
   427
		} catch (InterruptedException e) {
franta-hg@183
   428
			throw new FormatterException("Interrupted while waiting for test results", e);
franta-hg@183
   429
		}
franta-hg@183
   430
franta-hg@183
   431
		printFooter(currentFormatter);
franta-hg@73
   432
	}
franta-hg@73
   433
franta-hg@196
   434
	/**
franta-hg@196
   435
	 * JDBC driver classes should be preloaded in single thread to avoid deadlocks while doing
franta-hg@196
   436
	 * {@linkplain DriverManager#registerDriver(java.sql.Driver)} during parallel connections.
franta-hg@196
   437
	 *
franta-hg@196
   438
	 * @param dbName
franta-hg@196
   439
	 */
franta-hg@196
   440
	private void preloadDriver(String dbName) {
franta-hg@196
   441
		try {
franta-hg@196
   442
			DatabaseDefinition dd = configurationProvider.getConfiguration().getDatabase(dbName);
franta-hg@196
   443
			Driver driver = findDriver(dd);
franta-hg@196
   444
			if (driver == null) {
franta-hg@196
   445
				log.log(Level.WARNING, "No Driver found for DB: {0}", dbName);
franta-hg@196
   446
			} else {
franta-hg@196
   447
				log.log(Level.FINEST, "Driver preloading for DB: {0} was successfull", dbName);
franta-hg@196
   448
			}
franta-hg@196
   449
		} catch (Exception e) {
franta-hg@196
   450
			LogRecord r = new LogRecord(Level.WARNING, "Failed to preload the Driver for DB: {0}");
franta-hg@196
   451
			r.setParameters(new Object[]{dbName});
franta-hg@196
   452
			r.setThrown(e);
franta-hg@196
   453
			log.log(r);
franta-hg@196
   454
		}
franta-hg@196
   455
	}
franta-hg@196
   456
franta-hg@210
   457
	private Object[] testConnection(String dbName) {
franta-hg@69
   458
		log.log(Level.FINE, "Testing connection to database: {0}", dbName);
franta-hg@73
   459
franta-hg@73
   460
		boolean succesfullyConnected = false;
franta-hg@73
   461
		boolean succesfullyConfigured = false;
franta-hg@73
   462
franta-hg@69
   463
		try {
franta-hg@69
   464
			DatabaseDefinition dd = configurationProvider.getConfiguration().getDatabase(dbName);
franta-hg@75
   465
			log.log(Level.FINE, "Database definition was loaded from configuration");
franta-hg@75
   466
			succesfullyConfigured = true;
franta-hg@106
   467
			try (DatabaseConnection dc = dd.connect(options.getDatabaseProperties())) {
franta-hg@75
   468
				succesfullyConnected = dc.test();
franta-hg@69
   469
			}
franta-hg@75
   470
			log.log(Level.FINE, "Database connection test was successful");
franta-hg@196
   471
		} catch (ConfigurationException | SQLException | RuntimeException e) {
franta-hg@183
   472
			log.log(Level.SEVERE, "Error during testing connection " + dbName, e);
franta-hg@69
   473
		}
franta-hg@73
   474
franta-hg@73
   475
		return new Object[]{dbName, succesfullyConfigured, succesfullyConnected};
franta-hg@69
   476
	}
franta-hg@69
   477
franta-hg@210
   478
	private void printResource(String fileName) {
franta-hg@18
   479
		try (BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream(fileName)))) {
franta-hg@17
   480
			while (true) {
franta-hg@18
   481
				String line = reader.readLine();
franta-hg@17
   482
				if (line == null) {
franta-hg@17
   483
					break;
franta-hg@17
   484
				} else {
franta-hg@17
   485
					println(line);
franta-hg@17
   486
				}
franta-hg@17
   487
			}
franta-hg@17
   488
		} catch (Exception e) {
franta-hg@18
   489
			log.log(Level.SEVERE, "Unable to print this info. Please see our website for it: " + Constants.WEBSITE, e);
franta-hg@17
   490
		}
franta-hg@17
   491
	}
franta-hg@17
   492
franta-hg@17
   493
	private void println(String line) {
franta-hg@17
   494
		out.println(line);
franta-hg@17
   495
	}
franta-hg@69
   496
franta-hg@183
   497
	private void printTable(Formatter formatter, ColumnsHeader header, String sql, List<Parameter> parameters, List<Object[]> data) throws ConfigurationException, FormatterException {
franta-hg@201
   498
		printTable(formatter, header, sql, parameters, data, null);
franta-hg@201
   499
	}
franta-hg@201
   500
franta-hg@201
   501
	private void printTable(Formatter formatter, ColumnsHeader header, String sql, List<Parameter> parameters, List<Object[]> data, final Integer sortByColumn) throws ConfigurationException, FormatterException {
franta-hg@183
   502
		printHeader(formatter, header, sql, parameters);
franta-hg@183
   503
franta-hg@201
   504
		if (sortByColumn != null) {
franta-hg@201
   505
			Collections.sort(data, new Comparator<Object[]>() {
franta-hg@201
   506
franta-hg@201
   507
				@Override
franta-hg@201
   508
				public int compare(Object[] o1, Object[] o2) {
franta-hg@201
   509
					String s1 = String.valueOf(o1[sortByColumn]);
franta-hg@201
   510
					String s2 = String.valueOf(o2[sortByColumn]);
franta-hg@201
   511
					return s1.compareTo(s2);
franta-hg@201
   512
				}
franta-hg@201
   513
			});
franta-hg@201
   514
		}
franta-hg@201
   515
franta-hg@183
   516
		for (Object[] row : data) {
franta-hg@183
   517
			printRow(formatter, row);
franta-hg@183
   518
		}
franta-hg@183
   519
franta-hg@183
   520
		printFooter(formatter);
franta-hg@183
   521
	}
franta-hg@183
   522
franta-hg@183
   523
	private void printHeader(Formatter formatter, ColumnsHeader header, String sql, List<Parameter> parameters) {
franta-hg@159
   524
		formatter.writeStartStatement();
franta-hg@159
   525
		if (sql != null) {
franta-hg@159
   526
			formatter.writeQuery(sql);
franta-hg@159
   527
			if (parameters != null) {
franta-hg@159
   528
				formatter.writeParameters(parameters);
franta-hg@159
   529
			}
franta-hg@159
   530
		}
franta-hg@183
   531
		formatter.writeStartResultSet(header);
franta-hg@183
   532
	}
franta-hg@159
   533
franta-hg@183
   534
	private void printRow(Formatter formatter, Object[] row) {
franta-hg@183
   535
		formatter.writeStartRow();
franta-hg@183
   536
		for (Object cell : row) {
franta-hg@183
   537
			formatter.writeColumnValue(cell);
franta-hg@183
   538
		}
franta-hg@183
   539
		formatter.writeEndRow();
franta-hg@183
   540
	}
franta-hg@69
   541
franta-hg@183
   542
	private void printFooter(Formatter formatter) {
franta-hg@69
   543
		formatter.writeEndResultSet();
franta-hg@159
   544
		formatter.writeEndStatement();
franta-hg@69
   545
	}
franta-hg@69
   546
franta-hg@69
   547
	private Formatter getFormatter() throws ConfigurationException, FormatterException {
franta-hg@89
   548
		String formatterName = options.getFormatterName();
franta-hg@89
   549
		formatterName = formatterName == null ? Configuration.DEFAULT_FORMATTER_PREFETCHING : formatterName;
franta-hg@89
   550
		FormatterDefinition fd = configurationProvider.getConfiguration().getFormatter(formatterName);
franta-hg@104
   551
		FormatterContext context = new FormatterContext(out, options.getFormatterProperties());
franta-hg@69
   552
		return fd.getInstance(context);
franta-hg@69
   553
	}
franta-hg@69
   554
franta-hg@69
   555
	private ColumnsHeader constructHeader(HeaderField... fields) throws FormatterException {
franta-hg@69
   556
		try {
franta-hg@69
   557
			RowSetMetaDataImpl metaData = new RowSetMetaDataImpl();
franta-hg@69
   558
			metaData.setColumnCount(fields.length);
franta-hg@69
   559
franta-hg@69
   560
			for (int i = 0; i < fields.length; i++) {
franta-hg@69
   561
				HeaderField hf = fields[i];
franta-hg@69
   562
				int sqlIndex = i + 1;
franta-hg@69
   563
				metaData.setColumnName(sqlIndex, hf.name);
franta-hg@69
   564
				metaData.setColumnLabel(sqlIndex, hf.name);
franta-hg@69
   565
				metaData.setColumnType(sqlIndex, hf.type.getCode());
franta-hg@69
   566
				metaData.setColumnTypeName(sqlIndex, hf.type.name());
franta-hg@69
   567
			}
franta-hg@69
   568
franta-hg@69
   569
			return new ColumnsHeader(metaData);
franta-hg@69
   570
		} catch (SQLException e) {
franta-hg@69
   571
			throw new FormatterException("Error while constructing table headers", e);
franta-hg@69
   572
		}
franta-hg@69
   573
	}
franta-hg@69
   574
franta-hg@69
   575
	private static class HeaderField {
franta-hg@69
   576
franta-hg@69
   577
		String name;
franta-hg@69
   578
		SQLType type;
franta-hg@69
   579
franta-hg@69
   580
		public HeaderField(String name, SQLType type) {
franta-hg@69
   581
			this.name = name;
franta-hg@69
   582
			this.type = type;
franta-hg@69
   583
		}
franta-hg@69
   584
	}
franta-hg@69
   585
franta-hg@69
   586
	public enum InfoType {
franta-hg@69
   587
franta-hg@69
   588
		HELP {
franta-hg@183
   589
					@Override
franta-hg@183
   590
					public void showInfo(InfoLister infoLister) {
franta-hg@183
   591
						infoLister.printResource(Constants.HELP_FILE);
franta-hg@183
   592
					}
franta-hg@183
   593
				},
franta-hg@69
   594
		VERSION {
franta-hg@183
   595
					@Override
franta-hg@183
   596
					public void showInfo(InfoLister infoLister) {
franta-hg@183
   597
						infoLister.printResource(Constants.VERSION_FILE);
franta-hg@183
   598
					}
franta-hg@183
   599
				},
franta-hg@69
   600
		LICENSE {
franta-hg@183
   601
					@Override
franta-hg@183
   602
					public void showInfo(InfoLister infoLister) {
franta-hg@183
   603
						infoLister.printResource(Constants.LICENSE_FILE);
franta-hg@183
   604
					}
franta-hg@183
   605
				},
franta-hg@200
   606
		JAVA_PROPERTIES {
franta-hg@200
   607
					@Override
franta-hg@200
   608
					public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
franta-hg@200
   609
						infoLister.listJavaProperties();
franta-hg@200
   610
					}
franta-hg@200
   611
				},
franta-hg@200
   612
		ENVIRONMENT_VARIABLES {
franta-hg@200
   613
					@Override
franta-hg@200
   614
					public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
franta-hg@200
   615
						infoLister.listEnvironmentVariables();
franta-hg@200
   616
					}
franta-hg@200
   617
				},
franta-hg@69
   618
		FORMATTERS {
franta-hg@183
   619
					@Override
franta-hg@183
   620
					public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
franta-hg@183
   621
						infoLister.listFormatters();
franta-hg@183
   622
					}
franta-hg@183
   623
				},
franta-hg@209
   624
		FORMATTER_PROPERTIES {
franta-hg@209
   625
					@Override
franta-hg@209
   626
					public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
franta-hg@209
   627
						infoLister.listFormatterProperties();
franta-hg@209
   628
					}
franta-hg@209
   629
				},
franta-hg@69
   630
		TYPES {
franta-hg@183
   631
					@Override
franta-hg@183
   632
					public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
franta-hg@183
   633
						infoLister.listTypes();
franta-hg@183
   634
					}
franta-hg@183
   635
				},
franta-hg@158
   636
		JDBC_DRIVERS {
franta-hg@183
   637
					@Override
franta-hg@183
   638
					public void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException {
franta-hg@183
   639
						infoLister.listJdbcDrivers();
franta-hg@183
   640
					}
franta-hg@183
   641
				},
franta-hg@159
   642
		JDBC_PROPERTIES {
franta-hg@183
   643
					@Override
franta-hg@183
   644
					public void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException {
franta-hg@183
   645
						infoLister.listJdbcProperties();
franta-hg@183
   646
					}
franta-hg@183
   647
				},
franta-hg@69
   648
		DATABASES {
franta-hg@183
   649
					@Override
franta-hg@183
   650
					public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
franta-hg@183
   651
						infoLister.listDatabases();
franta-hg@183
   652
					}
franta-hg@183
   653
				},
franta-hg@69
   654
		CONNECTION {
franta-hg@183
   655
					@Override
franta-hg@183
   656
					public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
franta-hg@183
   657
						infoLister.testConnections();
franta-hg@183
   658
					}
franta-hg@183
   659
				};
franta-hg@69
   660
franta-hg@69
   661
		public abstract void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException;
franta-hg@69
   662
	}
franta-hg@14
   663
}