InfoLister: sort rows in --list-java-properties and --list-environment-variables
3 * Copyright © 2013 František Kučera (frantovo.cz)
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.
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.
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/>.
18 package info.globalcode.sql.dk;
20 import info.globalcode.sql.dk.configuration.Configuration;
21 import info.globalcode.sql.dk.configuration.ConfigurationException;
22 import info.globalcode.sql.dk.configuration.ConfigurationProvider;
23 import info.globalcode.sql.dk.configuration.DatabaseDefinition;
24 import info.globalcode.sql.dk.configuration.FormatterDefinition;
25 import info.globalcode.sql.dk.configuration.Properties;
26 import info.globalcode.sql.dk.configuration.Property;
27 import info.globalcode.sql.dk.formatting.ColumnsHeader;
28 import info.globalcode.sql.dk.formatting.FakeSqlArray;
29 import info.globalcode.sql.dk.formatting.Formatter;
30 import info.globalcode.sql.dk.formatting.FormatterContext;
31 import info.globalcode.sql.dk.formatting.FormatterException;
32 import java.io.BufferedReader;
33 import java.io.ByteArrayOutputStream;
34 import java.io.InputStreamReader;
35 import java.io.PrintStream;
36 import java.sql.Array;
37 import java.sql.Driver;
38 import java.sql.DriverManager;
39 import java.sql.DriverPropertyInfo;
40 import java.sql.SQLException;
41 import java.util.ArrayList;
42 import java.util.Collections;
43 import java.util.Comparator;
44 import java.util.EnumSet;
45 import java.util.HashSet;
46 import java.util.List;
47 import java.util.Map.Entry;
48 import java.util.ServiceLoader;
50 import java.util.concurrent.ExecutorService;
51 import java.util.concurrent.Executors;
52 import java.util.concurrent.TimeUnit;
53 import java.util.logging.Level;
54 import java.util.logging.LogRecord;
55 import java.util.logging.Logger;
56 import javax.sql.rowset.RowSetMetaDataImpl;
59 * Displays info like help, version etc.
61 * @author Ing. František Kučera (frantovo.cz)
63 public class InfoLister {
65 private static final Logger log = Logger.getLogger(InfoLister.class.getName());
67 * Fake database name for output formatting
69 public static final String CONFIG_DB_NAME = "sqldk_configuration";
70 private final PrintStream out;
71 private final ConfigurationProvider configurationProvider;
72 private final CLIOptions options;
73 private Formatter formatter;
75 public InfoLister(PrintStream out, ConfigurationProvider configurationProvider, CLIOptions options) {
77 this.configurationProvider = configurationProvider;
78 this.options = options;
81 public void showInfo() throws ConfigurationException, FormatterException {
82 EnumSet<InfoType> commands = options.getShowInfo();
84 boolean formattinNeeded = false;
86 for (InfoType infoType : commands) {
95 case ENVIRONMENT_VARIABLES:
96 formattinNeeded = true;
101 if (formattinNeeded) {
102 try (Formatter f = getFormatter()) {
104 formatter.writeStartBatch();
105 DatabaseDefinition dd = new DatabaseDefinition();
106 dd.setName(CONFIG_DB_NAME);
107 formatter.writeStartDatabase(dd);
109 formatter.writeEndDatabase();
110 formatter.writeEndBatch();
118 private void showInfos(EnumSet<InfoType> commands) throws ConfigurationException, FormatterException {
119 for (InfoType infoType : commands) {
120 infoType.showInfo(this);
124 private void listJavaProperties() throws FormatterException, ConfigurationException {
125 ColumnsHeader header = constructHeader(new HeaderField("name", SQLType.VARCHAR), new HeaderField("value", SQLType.VARCHAR));
126 List<Object[]> data = new ArrayList<>();
127 for (Entry<Object, Object> e : System.getProperties().entrySet()) {
128 data.add(new Object[]{e.getKey(), e.getValue()});
130 printTable(formatter, header, "-- Java system properties", null, data, 0);
133 private void listEnvironmentVariables() throws FormatterException, ConfigurationException {
134 ColumnsHeader header = constructHeader(new HeaderField("name", SQLType.VARCHAR), new HeaderField("value", SQLType.VARCHAR));
135 List<Object[]> data = new ArrayList<>();
136 for (Entry<String, String> e : System.getenv().entrySet()) {
137 data.add(new Object[]{e.getKey(), e.getValue()});
139 printTable(formatter, header, "-- environment variables", null, data, 0);
142 private void listFormatters() throws ConfigurationException, FormatterException {
143 ColumnsHeader header = constructHeader(
144 new HeaderField("name", SQLType.VARCHAR),
145 new HeaderField("built_in", SQLType.BOOLEAN),
146 new HeaderField("default", SQLType.BOOLEAN),
147 new HeaderField("class_name", SQLType.VARCHAR),
148 new HeaderField("valid", SQLType.BOOLEAN));
149 List<Object[]> data = new ArrayList<>();
151 String defaultFormatter = configurationProvider.getConfiguration().getDefaultFormatter();
152 defaultFormatter = defaultFormatter == null ? Configuration.DEFAULT_FORMATTER : defaultFormatter;
154 for (FormatterDefinition fd : configurationProvider.getConfiguration().getBuildInFormatters()) {
155 data.add(new Object[]{fd.getName(), true, defaultFormatter.equals(fd.getName()), fd.getClassName(), isInstantiable(fd)});
158 for (FormatterDefinition fd : configurationProvider.getConfiguration().getFormatters()) {
159 data.add(new Object[]{fd.getName(), false, defaultFormatter.equals(fd.getName()), fd.getClassName(), isInstantiable(fd)});
162 printTable(formatter, header, "-- configured and built-in output formatters", null, data);
165 private boolean isInstantiable(FormatterDefinition fd) {
167 try (ByteArrayOutputStream testStream = new ByteArrayOutputStream()) {
168 fd.getInstance(new FormatterContext(testStream, new Properties(0)));
171 } catch (Exception e) {
172 log.log(Level.SEVERE, "Unable to create an instance of formatter: " + fd.getName(), e);
177 public void listTypes() throws FormatterException, ConfigurationException {
178 ColumnsHeader header = constructHeader(new HeaderField("name", SQLType.VARCHAR), new HeaderField("code", SQLType.INTEGER));
179 List<Object[]> data = new ArrayList<>();
180 for (SQLType sqlType : SQLType.values()) {
181 data.add(new Object[]{sqlType.name(), sqlType.getCode()});
183 printTable(formatter, header, "-- data types", null, data);
184 log.log(Level.INFO, "Type names in --types option are case insensitive");
187 public void listDatabases() throws ConfigurationException, FormatterException {
188 ColumnsHeader header = constructHeader(
189 new HeaderField("database_name", SQLType.VARCHAR),
190 new HeaderField("user_name", SQLType.VARCHAR),
191 new HeaderField("database_url", SQLType.VARCHAR));
192 List<Object[]> data = new ArrayList<>();
194 final List<DatabaseDefinition> configuredDatabases = configurationProvider.getConfiguration().getDatabases();
195 if (configuredDatabases.isEmpty()) {
196 log.log(Level.WARNING, "No databases are configured.");
198 for (DatabaseDefinition dd : configuredDatabases) {
199 data.add(new Object[]{dd.getName(), dd.getUserName(), dd.getUrl()});
203 printTable(formatter, header, "-- configured databases", null, data);
206 public void listJdbcDrivers() throws FormatterException, ConfigurationException {
207 ColumnsHeader header = constructHeader(
208 new HeaderField("class", SQLType.VARCHAR),
209 new HeaderField("version", SQLType.VARCHAR),
210 new HeaderField("major", SQLType.INTEGER),
211 new HeaderField("minor", SQLType.INTEGER),
212 new HeaderField("jdbc_compliant", SQLType.BOOLEAN));
213 List<Object[]> data = new ArrayList<>();
215 final ServiceLoader<Driver> drivers = ServiceLoader.load(Driver.class);
216 for (Driver d : drivers) {
217 data.add(new Object[]{
218 d.getClass().getName(),
219 d.getMajorVersion() + "." + d.getMinorVersion(),
226 printTable(formatter, header, "-- discovered JDBC drivers (available on the CLASSPATH)", null, data);
229 public void listJdbcProperties() throws FormatterException, ConfigurationException {
230 for (String dbName : options.getDatabaseNamesToListProperties()) {
231 ColumnsHeader header = constructHeader(
232 new HeaderField("property_name", SQLType.VARCHAR),
233 new HeaderField("required", SQLType.BOOLEAN),
234 new HeaderField("choices", SQLType.ARRAY),
235 new HeaderField("configured_value", SQLType.VARCHAR),
236 new HeaderField("description", SQLType.VARCHAR));
237 List<Object[]> data = new ArrayList<>();
239 DatabaseDefinition dd = configurationProvider.getConfiguration().getDatabase(dbName);
241 Driver driver = findDriver(dd);
243 if (driver == null) {
244 log.log(Level.WARNING, "No JDBC driver was found for DB: {0} with URL: {1}", new Object[]{dd.getName(), dd.getUrl()});
246 log.log(Level.INFO, "For DB: {0} was found JDBC driver: {1}", new Object[]{dd.getName(), driver.getClass().getName()});
249 DriverPropertyInfo[] propertyInfos = driver.getPropertyInfo(dd.getUrl(), dd.getProperties().getJavaProperties());
251 Set<String> standardProperties = new HashSet<>();
253 for (DriverPropertyInfo pi : propertyInfos) {
254 Array choices = new FakeSqlArray(pi.choices, SQLType.VARCHAR);
255 data.add(new Object[]{
258 choices.getArray() == null ? "" : choices,
259 pi.value == null ? "" : pi.value,
262 standardProperties.add(pi.name);
265 for (Property p : dd.getProperties()) {
266 if (!standardProperties.contains(p.getName())) {
267 data.add(new Object[]{
274 log.log(Level.WARNING, "Your configuration contains property „{0}“ not declared by the JDBC driver.", p.getName());
278 } catch (SQLException e) {
279 log.log(Level.WARNING, "Error during getting property infos.", e);
282 List<Parameter> parameters = new ArrayList<>();
283 parameters.add(new NamedParameter("database", dbName, SQLType.VARCHAR));
284 parameters.add(new NamedParameter("driver_class", driver.getClass().getName(), SQLType.VARCHAR));
285 parameters.add(new NamedParameter("driver_major_version", driver.getMajorVersion(), SQLType.INTEGER));
286 parameters.add(new NamedParameter("driver_minor_version", driver.getMinorVersion(), SQLType.INTEGER));
288 printTable(formatter, header, "-- configured and configurable JDBC driver properties", parameters, data);
294 private Driver findDriver(DatabaseDefinition dd) {
295 final ServiceLoader<Driver> drivers = ServiceLoader.load(Driver.class);
296 for (Driver d : drivers) {
298 if (d.acceptsURL(dd.getUrl())) {
301 } catch (SQLException e) {
302 log.log(Level.WARNING, "Error during finding JDBC driver for: " + dd.getName(), e);
309 * Parallelism for connection testing – maximum concurrent database connections.
311 private static final int TESTING_THREAD_COUNT = 64;
313 * Time limit for all connection testing threads – particular timeouts per connection will be
316 private static final long TESTING_AWAIT_LIMIT = 1;
317 private static final TimeUnit TESTING_AWAIT_UNIT = TimeUnit.DAYS;
319 public void testConnections() throws FormatterException, ConfigurationException {
320 ColumnsHeader header = constructHeader(
321 new HeaderField("database_name", SQLType.VARCHAR),
322 new HeaderField("configured", SQLType.BOOLEAN),
323 new HeaderField("connected", SQLType.BOOLEAN));
325 log.log(Level.FINE, "Testing DB connections in {0} threads", TESTING_THREAD_COUNT);
327 ExecutorService es = Executors.newFixedThreadPool(TESTING_THREAD_COUNT);
329 final Formatter currentFormatter = formatter;
331 printHeader(currentFormatter, header, "-- database configuration and connectivity test", null);
333 for (final String dbName : options.getDatabaseNamesToTest()) {
334 preloadDriver(dbName);
337 for (final String dbName : options.getDatabaseNamesToTest()) {
338 es.submit(new Runnable() {
339 // TODO: Java 8 – lambda
342 final Object[] row = testConnection(dbName);
343 synchronized (currentFormatter) {
344 printRow(currentFormatter, row);
353 log.log(Level.FINEST, "Waiting for test results: {0} {1}", new Object[]{TESTING_AWAIT_LIMIT, TESTING_AWAIT_UNIT.name()});
354 boolean finished = es.awaitTermination(TESTING_AWAIT_LIMIT, TESTING_AWAIT_UNIT);
356 log.log(Level.FINEST, "All testing threads finished in time limit.");
358 throw new FormatterException("Exceeded total time limit for test threads – this should never happen");
360 } catch (InterruptedException e) {
361 throw new FormatterException("Interrupted while waiting for test results", e);
364 printFooter(currentFormatter);
368 * JDBC driver classes should be preloaded in single thread to avoid deadlocks while doing
369 * {@linkplain DriverManager#registerDriver(java.sql.Driver)} during parallel connections.
373 private void preloadDriver(String dbName) {
375 DatabaseDefinition dd = configurationProvider.getConfiguration().getDatabase(dbName);
376 Driver driver = findDriver(dd);
377 if (driver == null) {
378 log.log(Level.WARNING, "No Driver found for DB: {0}", dbName);
380 log.log(Level.FINEST, "Driver preloading for DB: {0} was successfull", dbName);
382 } catch (Exception e) {
383 LogRecord r = new LogRecord(Level.WARNING, "Failed to preload the Driver for DB: {0}");
384 r.setParameters(new Object[]{dbName});
390 public Object[] testConnection(String dbName) {
391 log.log(Level.FINE, "Testing connection to database: {0}", dbName);
393 boolean succesfullyConnected = false;
394 boolean succesfullyConfigured = false;
397 DatabaseDefinition dd = configurationProvider.getConfiguration().getDatabase(dbName);
398 log.log(Level.FINE, "Database definition was loaded from configuration");
399 succesfullyConfigured = true;
400 try (DatabaseConnection dc = dd.connect(options.getDatabaseProperties())) {
401 succesfullyConnected = dc.test();
403 log.log(Level.FINE, "Database connection test was successful");
404 } catch (ConfigurationException | SQLException | RuntimeException e) {
405 log.log(Level.SEVERE, "Error during testing connection " + dbName, e);
408 return new Object[]{dbName, succesfullyConfigured, succesfullyConnected};
411 public void printResource(String fileName) {
412 try (BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream(fileName)))) {
414 String line = reader.readLine();
421 } catch (Exception e) {
422 log.log(Level.SEVERE, "Unable to print this info. Please see our website for it: " + Constants.WEBSITE, e);
426 private void println(String line) {
430 private void printTable(Formatter formatter, ColumnsHeader header, String sql, List<Parameter> parameters, List<Object[]> data) throws ConfigurationException, FormatterException {
431 printTable(formatter, header, sql, parameters, data, null);
434 private void printTable(Formatter formatter, ColumnsHeader header, String sql, List<Parameter> parameters, List<Object[]> data, final Integer sortByColumn) throws ConfigurationException, FormatterException {
435 printHeader(formatter, header, sql, parameters);
437 if (sortByColumn != null) {
438 Collections.sort(data, new Comparator<Object[]>() {
441 public int compare(Object[] o1, Object[] o2) {
442 String s1 = String.valueOf(o1[sortByColumn]);
443 String s2 = String.valueOf(o2[sortByColumn]);
444 return s1.compareTo(s2);
449 for (Object[] row : data) {
450 printRow(formatter, row);
453 printFooter(formatter);
456 private void printHeader(Formatter formatter, ColumnsHeader header, String sql, List<Parameter> parameters) {
457 formatter.writeStartStatement();
459 formatter.writeQuery(sql);
460 if (parameters != null) {
461 formatter.writeParameters(parameters);
464 formatter.writeStartResultSet(header);
467 private void printRow(Formatter formatter, Object[] row) {
468 formatter.writeStartRow();
469 for (Object cell : row) {
470 formatter.writeColumnValue(cell);
472 formatter.writeEndRow();
475 private void printFooter(Formatter formatter) {
476 formatter.writeEndResultSet();
477 formatter.writeEndStatement();
480 private Formatter getFormatter() throws ConfigurationException, FormatterException {
481 String formatterName = options.getFormatterName();
482 formatterName = formatterName == null ? Configuration.DEFAULT_FORMATTER_PREFETCHING : formatterName;
483 FormatterDefinition fd = configurationProvider.getConfiguration().getFormatter(formatterName);
484 FormatterContext context = new FormatterContext(out, options.getFormatterProperties());
485 return fd.getInstance(context);
488 private ColumnsHeader constructHeader(HeaderField... fields) throws FormatterException {
490 RowSetMetaDataImpl metaData = new RowSetMetaDataImpl();
491 metaData.setColumnCount(fields.length);
493 for (int i = 0; i < fields.length; i++) {
494 HeaderField hf = fields[i];
495 int sqlIndex = i + 1;
496 metaData.setColumnName(sqlIndex, hf.name);
497 metaData.setColumnLabel(sqlIndex, hf.name);
498 metaData.setColumnType(sqlIndex, hf.type.getCode());
499 metaData.setColumnTypeName(sqlIndex, hf.type.name());
502 return new ColumnsHeader(metaData);
503 } catch (SQLException e) {
504 throw new FormatterException("Error while constructing table headers", e);
508 private static class HeaderField {
513 public HeaderField(String name, SQLType type) {
519 public enum InfoType {
523 public void showInfo(InfoLister infoLister) {
524 infoLister.printResource(Constants.HELP_FILE);
529 public void showInfo(InfoLister infoLister) {
530 infoLister.printResource(Constants.VERSION_FILE);
535 public void showInfo(InfoLister infoLister) {
536 infoLister.printResource(Constants.LICENSE_FILE);
541 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
542 infoLister.listJavaProperties();
545 ENVIRONMENT_VARIABLES {
547 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
548 infoLister.listEnvironmentVariables();
553 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
554 infoLister.listFormatters();
559 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
560 infoLister.listTypes();
565 public void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException {
566 infoLister.listJdbcDrivers();
571 public void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException {
572 infoLister.listJdbcProperties();
577 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
578 infoLister.listDatabases();
583 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
584 infoLister.testConnections();
588 public abstract void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException;