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