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