java/sql-dk/src/info/globalcode/sql/dk/InfoLister.java
author František Kučera <franta-hg@frantovo.cz>
Sat, 15 Aug 2015 14:35:27 +0200
branchv_0
changeset 216 0eb9aec16bf4
parent 215 42880d38ad3e
child 220 0bc544b38cfa
permissions -rw-r--r--
--list-formatter-properties: optional column declared_in

Usage:
sql-dk --list-formatter-properties tabular --list-formatter-properties xml --list-formatter-properties xhtml --list-formatter-properties tex --formatter xhtml --formatter-property InfoLister:print:declared_in true > formatter-properties.xhtml
     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 			// currently only for debugging purposes
   207 			// TODO: introduce --info-lister-property or generic filtering capability in printTable() ?
   208 			boolean printDeclaredIn = options.getFormatterProperties().getBoolean("InfoLister:print:declared_in", false);
   209 
   210 			List<HeaderField> headerFields = new ArrayList<>();
   211 			headerFields.add(new HeaderField("name", SQLType.VARCHAR));
   212 			headerFields.add(new HeaderField("type", SQLType.VARCHAR));
   213 			headerFields.add(new HeaderField("default", SQLType.VARCHAR));
   214 			headerFields.add(new HeaderField("description", SQLType.VARCHAR));
   215 			if (printDeclaredIn) {
   216 				headerFields.add(new HeaderField("declared_in", SQLType.VARCHAR));
   217 			}
   218 
   219 			ColumnsHeader header = constructHeader(headerFields.toArray(new HeaderField[0]));
   220 
   221 			Map<String, Object[]> data = new HashMap<>();
   222 			Class<Formatter> formatterClass = (Class<Formatter>) Class.forName(fd.getClassName());
   223 			List<Class<? extends Formatter>> hierarchy = Functions.getClassHierarchy(formatterClass, Formatter.class);
   224 			Collections.reverse(hierarchy);
   225 			hierarchy.stream().forEach((c) -> {
   226 				for (PropertyDeclaration p : getPropertyDeclarations(c)) {
   227 					data.put(p.name(), propertyDeclarationToRow(p, c, printDeclaredIn));
   228 				}
   229 			});
   230 
   231 			List<Parameter> parameters = new ArrayList<>();
   232 			parameters.add(new NamedParameter("formatter", formatterName, SQLType.VARCHAR));
   233 
   234 			printTable(formatter, header, "-- formatter properties", parameters, new ArrayList<>(data.values()));
   235 		} catch (ClassNotFoundException e) {
   236 			throw new ConfigurationException("Unable to find class " + fd.getClassName() + " of formatter" + fd.getName(), e);
   237 		}
   238 	}
   239 
   240 	private static Object[] propertyDeclarationToRow(PropertyDeclaration p, Class formatterClass, boolean printDeclaredIn) {
   241 		List list = new ArrayList();
   242 
   243 		list.add(p.name());
   244 		list.add(CommonProperties.getSimpleTypeName(p.type()));
   245 		list.add(p.defaultValue());
   246 		list.add(p.description());
   247 		if (printDeclaredIn) {
   248 			list.add(formatterClass.getName());
   249 		}
   250 
   251 		return list.toArray();
   252 	}
   253 
   254 	private void listTypes() throws FormatterException, ConfigurationException {
   255 		ColumnsHeader header = constructHeader(new HeaderField("name", SQLType.VARCHAR), new HeaderField("code", SQLType.INTEGER));
   256 		List<Object[]> data = new ArrayList<>();
   257 		for (SQLType sqlType : SQLType.values()) {
   258 			data.add(new Object[]{sqlType.name(), sqlType.getCode()});
   259 		}
   260 		printTable(formatter, header, "-- data types", null, data);
   261 		log.log(Level.INFO, "Type names in --types option are case insensitive");
   262 	}
   263 
   264 	private void listDatabases() throws ConfigurationException, FormatterException {
   265 		ColumnsHeader header = constructHeader(
   266 				new HeaderField("database_name", SQLType.VARCHAR),
   267 				new HeaderField("user_name", SQLType.VARCHAR),
   268 				new HeaderField("database_url", SQLType.VARCHAR));
   269 		List<Object[]> data = new ArrayList<>();
   270 
   271 		final List<DatabaseDefinition> configuredDatabases = configurationProvider.getConfiguration().getDatabases();
   272 		if (configuredDatabases.isEmpty()) {
   273 			log.log(Level.WARNING, "No databases are configured.");
   274 		} else {
   275 			for (DatabaseDefinition dd : configuredDatabases) {
   276 				data.add(new Object[]{dd.getName(), dd.getUserName(), dd.getUrl()});
   277 
   278 				final TunnelDefinition tunnel = dd.getTunnel();
   279 				if (tunnel != null) {
   280 					log.log(Level.INFO, "Tunnel command: {0}", tunnel.getCommand());
   281 					for (CommandArgument ca : Functions.notNull(tunnel.getArguments())) {
   282 						log.log(Level.INFO, "\targument: {0}/{1}", new Object[]{ca.getType(), ca.getValue()});
   283 					}
   284 				}
   285 
   286 			}
   287 		}
   288 
   289 		printTable(formatter, header, "-- configured databases", null, data);
   290 	}
   291 
   292 	private void listJdbcDrivers() throws FormatterException, ConfigurationException {
   293 		ColumnsHeader header = constructHeader(
   294 				new HeaderField("class", SQLType.VARCHAR),
   295 				new HeaderField("version", SQLType.VARCHAR),
   296 				new HeaderField("major", SQLType.INTEGER),
   297 				new HeaderField("minor", SQLType.INTEGER),
   298 				new HeaderField("jdbc_compliant", SQLType.BOOLEAN));
   299 		List<Object[]> data = new ArrayList<>();
   300 
   301 		final ServiceLoader<Driver> drivers = ServiceLoader.load(Driver.class);
   302 		for (Driver d : drivers) {
   303 			data.add(new Object[]{
   304 				d.getClass().getName(),
   305 				d.getMajorVersion() + "." + d.getMinorVersion(),
   306 				d.getMajorVersion(),
   307 				d.getMinorVersion(),
   308 				d.jdbcCompliant()
   309 			});
   310 		}
   311 
   312 		printTable(formatter, header, "-- discovered JDBC drivers (available on the CLASSPATH)", null, data);
   313 	}
   314 
   315 	private void listJdbcProperties() throws FormatterException, ConfigurationException {
   316 		for (String dbName : options.getDatabaseNamesToListProperties()) {
   317 			ColumnsHeader header = constructHeader(
   318 					new HeaderField("property_name", SQLType.VARCHAR),
   319 					new HeaderField("required", SQLType.BOOLEAN),
   320 					new HeaderField("choices", SQLType.ARRAY),
   321 					new HeaderField("configured_value", SQLType.VARCHAR),
   322 					new HeaderField("description", SQLType.VARCHAR));
   323 			List<Object[]> data = new ArrayList<>();
   324 
   325 			DatabaseDefinition dd = configurationProvider.getConfiguration().getDatabase(dbName);
   326 
   327 			Driver driver = findDriver(dd);
   328 
   329 			if (driver == null) {
   330 				log.log(Level.WARNING, "No JDBC driver was found for DB: {0} with URL: {1}", new Object[]{dd.getName(), dd.getUrl()});
   331 			} else {
   332 				log.log(Level.INFO, "For DB: {0} was found JDBC driver: {1}", new Object[]{dd.getName(), driver.getClass().getName()});
   333 
   334 				try {
   335 					DriverPropertyInfo[] propertyInfos = driver.getPropertyInfo(dd.getUrl(), dd.getProperties().getJavaProperties());
   336 
   337 					Set<String> standardProperties = new HashSet<>();
   338 
   339 					for (DriverPropertyInfo pi : propertyInfos) {
   340 						Array choices = new FakeSqlArray(pi.choices, SQLType.VARCHAR);
   341 						data.add(new Object[]{
   342 							pi.name,
   343 							pi.required,
   344 							choices.getArray() == null ? "" : choices,
   345 							pi.value == null ? "" : pi.value,
   346 							pi.description
   347 						});
   348 						standardProperties.add(pi.name);
   349 					}
   350 
   351 					for (Property p : dd.getProperties()) {
   352 						if (!standardProperties.contains(p.getName())) {
   353 							data.add(new Object[]{
   354 								p.getName(),
   355 								"",
   356 								"",
   357 								p.getValue(),
   358 								""
   359 							});
   360 							log.log(Level.WARNING, "Your configuration contains property „{0}“ not declared by the JDBC driver.", p.getName());
   361 						}
   362 					}
   363 
   364 				} catch (SQLException e) {
   365 					log.log(Level.WARNING, "Error during getting property infos.", e);
   366 				}
   367 
   368 				List<Parameter> parameters = new ArrayList<>();
   369 				parameters.add(new NamedParameter("database", dbName, SQLType.VARCHAR));
   370 				parameters.add(new NamedParameter("driver_class", driver.getClass().getName(), SQLType.VARCHAR));
   371 				parameters.add(new NamedParameter("driver_major_version", driver.getMajorVersion(), SQLType.INTEGER));
   372 				parameters.add(new NamedParameter("driver_minor_version", driver.getMinorVersion(), SQLType.INTEGER));
   373 
   374 				printTable(formatter, header, "-- configured and configurable JDBC driver properties", parameters, data);
   375 			}
   376 		}
   377 
   378 	}
   379 
   380 	private Driver findDriver(DatabaseDefinition dd) {
   381 		final ServiceLoader<Driver> drivers = ServiceLoader.load(Driver.class);
   382 		for (Driver d : drivers) {
   383 			try {
   384 				if (d.acceptsURL(dd.getUrl())) {
   385 					return d;
   386 				}
   387 			} catch (SQLException e) {
   388 				log.log(Level.WARNING, "Error during finding JDBC driver for: " + dd.getName(), e);
   389 			}
   390 		}
   391 		return null;
   392 	}
   393 
   394 	/**
   395 	 * Parallelism for connection testing – maximum concurrent database connections.
   396 	 */
   397 	private static final int TESTING_THREAD_COUNT = 64;
   398 	/**
   399 	 * Time limit for all connection testing threads – particular timeouts per connection will be
   400 	 * much smaller.
   401 	 */
   402 	private static final long TESTING_AWAIT_LIMIT = 1;
   403 	private static final TimeUnit TESTING_AWAIT_UNIT = TimeUnit.DAYS;
   404 
   405 	private void testConnections() throws FormatterException, ConfigurationException {
   406 		ColumnsHeader header = constructHeader(
   407 				new HeaderField("database_name", SQLType.VARCHAR),
   408 				new HeaderField("configured", SQLType.BOOLEAN),
   409 				new HeaderField("connected", SQLType.BOOLEAN));
   410 
   411 		log.log(Level.FINE, "Testing DB connections in {0} threads", TESTING_THREAD_COUNT);
   412 
   413 		ExecutorService es = Executors.newFixedThreadPool(TESTING_THREAD_COUNT);
   414 
   415 		final Formatter currentFormatter = formatter;
   416 
   417 		printHeader(currentFormatter, header, "-- database configuration and connectivity test", null);
   418 
   419 		for (final String dbName : options.getDatabaseNamesToTest()) {
   420 			preloadDriver(dbName);
   421 		}
   422 
   423 		for (final String dbName : options.getDatabaseNamesToTest()) {
   424 			es.submit(() -> {
   425 				final Object[] row = testConnection(dbName);
   426 				synchronized (currentFormatter) {
   427 					printRow(currentFormatter, row);
   428 				}
   429 			}
   430 			);
   431 		}
   432 
   433 		es.shutdown();
   434 
   435 		try {
   436 			log.log(Level.FINEST, "Waiting for test results: {0} {1}", new Object[]{TESTING_AWAIT_LIMIT, TESTING_AWAIT_UNIT.name()});
   437 			boolean finished = es.awaitTermination(TESTING_AWAIT_LIMIT, TESTING_AWAIT_UNIT);
   438 			if (finished) {
   439 				log.log(Level.FINEST, "All testing threads finished in time limit.");
   440 			} else {
   441 				throw new FormatterException("Exceeded total time limit for test threads – this should never happen");
   442 			}
   443 		} catch (InterruptedException e) {
   444 			throw new FormatterException("Interrupted while waiting for test results", e);
   445 		}
   446 
   447 		printFooter(currentFormatter);
   448 	}
   449 
   450 	/**
   451 	 * JDBC driver classes should be preloaded in single thread to avoid deadlocks while doing
   452 	 * {@linkplain DriverManager#registerDriver(java.sql.Driver)} during parallel connections.
   453 	 *
   454 	 * @param dbName
   455 	 */
   456 	private void preloadDriver(String dbName) {
   457 		try {
   458 			DatabaseDefinition dd = configurationProvider.getConfiguration().getDatabase(dbName);
   459 			Driver driver = findDriver(dd);
   460 			if (driver == null) {
   461 				log.log(Level.WARNING, "No Driver found for DB: {0}", dbName);
   462 			} else {
   463 				log.log(Level.FINEST, "Driver preloading for DB: {0} was successfull", dbName);
   464 			}
   465 		} catch (Exception e) {
   466 			LogRecord r = new LogRecord(Level.WARNING, "Failed to preload the Driver for DB: {0}");
   467 			r.setParameters(new Object[]{dbName});
   468 			r.setThrown(e);
   469 			log.log(r);
   470 		}
   471 	}
   472 
   473 	private Object[] testConnection(String dbName) {
   474 		log.log(Level.FINE, "Testing connection to database: {0}", dbName);
   475 
   476 		boolean succesfullyConnected = false;
   477 		boolean succesfullyConfigured = false;
   478 
   479 		try {
   480 			DatabaseDefinition dd = configurationProvider.getConfiguration().getDatabase(dbName);
   481 			log.log(Level.FINE, "Database definition was loaded from configuration");
   482 			succesfullyConfigured = true;
   483 			try (DatabaseConnection dc = dd.connect(options.getDatabaseProperties())) {
   484 				succesfullyConnected = dc.test();
   485 			}
   486 			log.log(Level.FINE, "Database connection test was successful");
   487 		} catch (ConfigurationException | SQLException | RuntimeException e) {
   488 			log.log(Level.SEVERE, "Error during testing connection " + dbName, e);
   489 		}
   490 
   491 		return new Object[]{dbName, succesfullyConfigured, succesfullyConnected};
   492 	}
   493 
   494 	private void printResource(String fileName) {
   495 		try (BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream(fileName)))) {
   496 			while (true) {
   497 				String line = reader.readLine();
   498 				if (line == null) {
   499 					break;
   500 				} else {
   501 					println(line);
   502 				}
   503 			}
   504 		} catch (Exception e) {
   505 			log.log(Level.SEVERE, "Unable to print this info. Please see our website for it: " + Constants.WEBSITE, e);
   506 		}
   507 	}
   508 
   509 	private void println(String line) {
   510 		out.println(line);
   511 	}
   512 
   513 	private void printTable(Formatter formatter, ColumnsHeader header, String sql, List<Parameter> parameters, List<Object[]> data) throws ConfigurationException, FormatterException {
   514 		printTable(formatter, header, sql, parameters, data, null);
   515 	}
   516 
   517 	private void printTable(Formatter formatter, ColumnsHeader header, String sql, List<Parameter> parameters, List<Object[]> data, final Integer sortByColumn) throws ConfigurationException, FormatterException {
   518 		printHeader(formatter, header, sql, parameters);
   519 
   520 		if (sortByColumn != null) {
   521 			Collections.sort(data, new Comparator<Object[]>() {
   522 
   523 				@Override
   524 				public int compare(Object[] o1, Object[] o2) {
   525 					String s1 = String.valueOf(o1[sortByColumn]);
   526 					String s2 = String.valueOf(o2[sortByColumn]);
   527 					return s1.compareTo(s2);
   528 				}
   529 			});
   530 		}
   531 
   532 		for (Object[] row : data) {
   533 			printRow(formatter, row);
   534 		}
   535 
   536 		printFooter(formatter);
   537 	}
   538 
   539 	private void printHeader(Formatter formatter, ColumnsHeader header, String sql, List<Parameter> parameters) {
   540 		formatter.writeStartStatement();
   541 		if (sql != null) {
   542 			formatter.writeQuery(sql);
   543 			if (parameters != null) {
   544 				formatter.writeParameters(parameters);
   545 			}
   546 		}
   547 		formatter.writeStartResultSet(header);
   548 	}
   549 
   550 	private void printRow(Formatter formatter, Object[] row) {
   551 		formatter.writeStartRow();
   552 		for (Object cell : row) {
   553 			formatter.writeColumnValue(cell);
   554 		}
   555 		formatter.writeEndRow();
   556 	}
   557 
   558 	private void printFooter(Formatter formatter) {
   559 		formatter.writeEndResultSet();
   560 		formatter.writeEndStatement();
   561 	}
   562 
   563 	private Formatter getFormatter() throws ConfigurationException, FormatterException {
   564 		String formatterName = options.getFormatterName();
   565 		formatterName = formatterName == null ? Configuration.DEFAULT_FORMATTER_PREFETCHING : formatterName;
   566 		FormatterDefinition fd = configurationProvider.getConfiguration().getFormatter(formatterName);
   567 		FormatterContext context = new FormatterContext(out, options.getFormatterProperties());
   568 		return fd.getInstance(context);
   569 	}
   570 
   571 	private ColumnsHeader constructHeader(HeaderField... fields) throws FormatterException {
   572 		try {
   573 			RowSetMetaDataImpl metaData = new RowSetMetaDataImpl();
   574 			metaData.setColumnCount(fields.length);
   575 
   576 			for (int i = 0; i < fields.length; i++) {
   577 				HeaderField hf = fields[i];
   578 				int sqlIndex = i + 1;
   579 				metaData.setColumnName(sqlIndex, hf.name);
   580 				metaData.setColumnLabel(sqlIndex, hf.name);
   581 				metaData.setColumnType(sqlIndex, hf.type.getCode());
   582 				metaData.setColumnTypeName(sqlIndex, hf.type.name());
   583 			}
   584 
   585 			return new ColumnsHeader(metaData);
   586 		} catch (SQLException e) {
   587 			throw new FormatterException("Error while constructing table headers", e);
   588 		}
   589 	}
   590 
   591 	private static class HeaderField {
   592 
   593 		String name;
   594 		SQLType type;
   595 
   596 		public HeaderField(String name, SQLType type) {
   597 			this.name = name;
   598 			this.type = type;
   599 		}
   600 	}
   601 
   602 	public enum InfoType {
   603 
   604 		HELP {
   605 					@Override
   606 					public void showInfo(InfoLister infoLister) {
   607 						infoLister.printResource(Constants.HELP_FILE);
   608 					}
   609 				},
   610 		VERSION {
   611 					@Override
   612 					public void showInfo(InfoLister infoLister) {
   613 						infoLister.printResource(Constants.VERSION_FILE);
   614 					}
   615 				},
   616 		LICENSE {
   617 					@Override
   618 					public void showInfo(InfoLister infoLister) {
   619 						infoLister.printResource(Constants.LICENSE_FILE);
   620 					}
   621 				},
   622 		JAVA_PROPERTIES {
   623 					@Override
   624 					public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
   625 						infoLister.listJavaProperties();
   626 					}
   627 				},
   628 		ENVIRONMENT_VARIABLES {
   629 					@Override
   630 					public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
   631 						infoLister.listEnvironmentVariables();
   632 					}
   633 				},
   634 		FORMATTERS {
   635 					@Override
   636 					public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
   637 						infoLister.listFormatters();
   638 					}
   639 				},
   640 		FORMATTER_PROPERTIES {
   641 					@Override
   642 					public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
   643 						infoLister.listFormatterProperties();
   644 					}
   645 				},
   646 		TYPES {
   647 					@Override
   648 					public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
   649 						infoLister.listTypes();
   650 					}
   651 				},
   652 		JDBC_DRIVERS {
   653 					@Override
   654 					public void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException {
   655 						infoLister.listJdbcDrivers();
   656 					}
   657 				},
   658 		JDBC_PROPERTIES {
   659 					@Override
   660 					public void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException {
   661 						infoLister.listJdbcProperties();
   662 					}
   663 				},
   664 		DATABASES {
   665 					@Override
   666 					public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
   667 						infoLister.listDatabases();
   668 					}
   669 				},
   670 		CONNECTION {
   671 					@Override
   672 					public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
   673 						infoLister.testConnections();
   674 					}
   675 				};
   676 
   677 		public abstract void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException;
   678 	}
   679 }