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