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