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.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;
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;
64 * Displays info like help, version etc.
66 * @author Ing. František Kučera (frantovo.cz)
68 public class InfoLister {
70 private static final Logger log = Logger.getLogger(InfoLister.class.getName());
72 * Fake database name for output formatting
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;
80 public InfoLister(PrintStream out, ConfigurationProvider configurationProvider, CLIOptions options) {
82 this.configurationProvider = configurationProvider;
83 this.options = options;
86 public void showInfo() throws ConfigurationException, FormatterException {
87 EnumSet<InfoType> commands = options.getShowInfo();
89 boolean formattinNeeded = false;
91 for (InfoType infoType : commands) {
98 case FORMATTER_PROPERTIES:
100 case JAVA_PROPERTIES:
101 case ENVIRONMENT_VARIABLES:
102 formattinNeeded = true;
107 if (formattinNeeded) {
108 try (Formatter f = getFormatter()) {
110 formatter.writeStartBatch();
111 DatabaseDefinition dd = new DatabaseDefinition();
112 dd.setName(CONFIG_DB_NAME);
113 formatter.writeStartDatabase(dd);
115 formatter.writeEndDatabase();
116 formatter.writeEndBatch();
124 private void showInfos(EnumSet<InfoType> commands) throws ConfigurationException, FormatterException {
125 for (InfoType infoType : commands) {
126 infoType.showInfo(this);
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()});
136 printTable(formatter, header, "-- Java system properties", null, data, 0);
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()});
145 printTable(formatter, header, "-- environment variables", null, data, 0);
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<>();
157 String defaultFormatter = configurationProvider.getConfiguration().getDefaultFormatter();
158 defaultFormatter = defaultFormatter == null ? Configuration.DEFAULT_FORMATTER : defaultFormatter;
160 for (FormatterDefinition fd : configurationProvider.getConfiguration().getBuildInFormatters()) {
161 data.add(new Object[]{fd.getName(), true, defaultFormatter.equals(fd.getName()), fd.getClassName(), isInstantiable(fd)});
164 for (FormatterDefinition fd : configurationProvider.getConfiguration().getFormatters()) {
165 data.add(new Object[]{fd.getName(), false, defaultFormatter.equals(fd.getName()), fd.getClassName(), isInstantiable(fd)});
168 printTable(formatter, header, "-- configured and built-in output formatters", null, data);
171 private boolean isInstantiable(FormatterDefinition fd) {
173 try (ByteArrayOutputStream testStream = new ByteArrayOutputStream()) {
174 fd.getInstance(new FormatterContext(testStream, new Properties(0)));
177 } catch (Exception e) {
178 log.log(Level.SEVERE, "Unable to create an instance of formatter: " + fd.getName(), e);
183 private void listFormatterProperties() throws FormatterException, ConfigurationException {
184 for (String formatterName : options.getFormatterNamesToListProperties()) {
185 listFormatterProperties(formatterName);
189 private void listFormatterProperties(String formatterName) throws FormatterException, ConfigurationException {
190 FormatterDefinition fd = configurationProvider.getConfiguration().getFormatter(formatterName);
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)
199 List<Object[]> data = new ArrayList<>();
201 Class<Formatter> formatterClass = (Class<Formatter>) Class.forName(fd.getClassName());
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);
209 for (PropertyDeclaration p : properties.value()) {
210 data.add(propertyDeclarationToRow(p));
214 // Single PropertyDeclaration
215 PropertyDeclaration property = formatterClass.getAnnotation(PropertyDeclaration.class);
216 if (property != null) {
217 data.add(propertyDeclarationToRow(property));
220 List<Parameter> parameters = new ArrayList<>();
221 parameters.add(new NamedParameter("formatter", formatterName, SQLType.VARCHAR));
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);
229 private static Object[] propertyDeclarationToRow(PropertyDeclaration p) {
232 CommonProperties.getSimpleTypeName(p.type()),
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()});
244 printTable(formatter, header, "-- data types", null, data);
245 log.log(Level.INFO, "Type names in --types option are case insensitive");
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<>();
255 final List<DatabaseDefinition> configuredDatabases = configurationProvider.getConfiguration().getDatabases();
256 if (configuredDatabases.isEmpty()) {
257 log.log(Level.WARNING, "No databases are configured.");
259 for (DatabaseDefinition dd : configuredDatabases) {
260 data.add(new Object[]{dd.getName(), dd.getUserName(), dd.getUrl()});
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()});
273 printTable(formatter, header, "-- configured databases", null, data);
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<>();
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(),
296 printTable(formatter, header, "-- discovered JDBC drivers (available on the CLASSPATH)", null, data);
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<>();
309 DatabaseDefinition dd = configurationProvider.getConfiguration().getDatabase(dbName);
311 Driver driver = findDriver(dd);
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()});
316 log.log(Level.INFO, "For DB: {0} was found JDBC driver: {1}", new Object[]{dd.getName(), driver.getClass().getName()});
319 DriverPropertyInfo[] propertyInfos = driver.getPropertyInfo(dd.getUrl(), dd.getProperties().getJavaProperties());
321 Set<String> standardProperties = new HashSet<>();
323 for (DriverPropertyInfo pi : propertyInfos) {
324 Array choices = new FakeSqlArray(pi.choices, SQLType.VARCHAR);
325 data.add(new Object[]{
328 choices.getArray() == null ? "" : choices,
329 pi.value == null ? "" : pi.value,
332 standardProperties.add(pi.name);
335 for (Property p : dd.getProperties()) {
336 if (!standardProperties.contains(p.getName())) {
337 data.add(new Object[]{
344 log.log(Level.WARNING, "Your configuration contains property „{0}“ not declared by the JDBC driver.", p.getName());
348 } catch (SQLException e) {
349 log.log(Level.WARNING, "Error during getting property infos.", e);
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));
358 printTable(formatter, header, "-- configured and configurable JDBC driver properties", parameters, data);
364 private Driver findDriver(DatabaseDefinition dd) {
365 final ServiceLoader<Driver> drivers = ServiceLoader.load(Driver.class);
366 for (Driver d : drivers) {
368 if (d.acceptsURL(dd.getUrl())) {
371 } catch (SQLException e) {
372 log.log(Level.WARNING, "Error during finding JDBC driver for: " + dd.getName(), e);
379 * Parallelism for connection testing – maximum concurrent database connections.
381 private static final int TESTING_THREAD_COUNT = 64;
383 * Time limit for all connection testing threads – particular timeouts per connection will be
386 private static final long TESTING_AWAIT_LIMIT = 1;
387 private static final TimeUnit TESTING_AWAIT_UNIT = TimeUnit.DAYS;
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));
395 log.log(Level.FINE, "Testing DB connections in {0} threads", TESTING_THREAD_COUNT);
397 ExecutorService es = Executors.newFixedThreadPool(TESTING_THREAD_COUNT);
399 final Formatter currentFormatter = formatter;
401 printHeader(currentFormatter, header, "-- database configuration and connectivity test", null);
403 for (final String dbName : options.getDatabaseNamesToTest()) {
404 preloadDriver(dbName);
407 for (final String dbName : options.getDatabaseNamesToTest()) {
409 final Object[] row = testConnection(dbName);
410 synchronized (currentFormatter) {
411 printRow(currentFormatter, row);
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);
423 log.log(Level.FINEST, "All testing threads finished in time limit.");
425 throw new FormatterException("Exceeded total time limit for test threads – this should never happen");
427 } catch (InterruptedException e) {
428 throw new FormatterException("Interrupted while waiting for test results", e);
431 printFooter(currentFormatter);
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.
440 private void preloadDriver(String dbName) {
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);
447 log.log(Level.FINEST, "Driver preloading for DB: {0} was successfull", dbName);
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});
457 private Object[] testConnection(String dbName) {
458 log.log(Level.FINE, "Testing connection to database: {0}", dbName);
460 boolean succesfullyConnected = false;
461 boolean succesfullyConfigured = false;
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();
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);
475 return new Object[]{dbName, succesfullyConfigured, succesfullyConnected};
478 private void printResource(String fileName) {
479 try (BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream(fileName)))) {
481 String line = reader.readLine();
488 } catch (Exception e) {
489 log.log(Level.SEVERE, "Unable to print this info. Please see our website for it: " + Constants.WEBSITE, e);
493 private void println(String line) {
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);
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);
504 if (sortByColumn != null) {
505 Collections.sort(data, new Comparator<Object[]>() {
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);
516 for (Object[] row : data) {
517 printRow(formatter, row);
520 printFooter(formatter);
523 private void printHeader(Formatter formatter, ColumnsHeader header, String sql, List<Parameter> parameters) {
524 formatter.writeStartStatement();
526 formatter.writeQuery(sql);
527 if (parameters != null) {
528 formatter.writeParameters(parameters);
531 formatter.writeStartResultSet(header);
534 private void printRow(Formatter formatter, Object[] row) {
535 formatter.writeStartRow();
536 for (Object cell : row) {
537 formatter.writeColumnValue(cell);
539 formatter.writeEndRow();
542 private void printFooter(Formatter formatter) {
543 formatter.writeEndResultSet();
544 formatter.writeEndStatement();
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);
555 private ColumnsHeader constructHeader(HeaderField... fields) throws FormatterException {
557 RowSetMetaDataImpl metaData = new RowSetMetaDataImpl();
558 metaData.setColumnCount(fields.length);
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());
569 return new ColumnsHeader(metaData);
570 } catch (SQLException e) {
571 throw new FormatterException("Error while constructing table headers", e);
575 private static class HeaderField {
580 public HeaderField(String name, SQLType type) {
586 public enum InfoType {
590 public void showInfo(InfoLister infoLister) {
591 infoLister.printResource(Constants.HELP_FILE);
596 public void showInfo(InfoLister infoLister) {
597 infoLister.printResource(Constants.VERSION_FILE);
602 public void showInfo(InfoLister infoLister) {
603 infoLister.printResource(Constants.LICENSE_FILE);
608 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
609 infoLister.listJavaProperties();
612 ENVIRONMENT_VARIABLES {
614 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
615 infoLister.listEnvironmentVariables();
620 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
621 infoLister.listFormatters();
624 FORMATTER_PROPERTIES {
626 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
627 infoLister.listFormatterProperties();
632 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
633 infoLister.listTypes();
638 public void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException {
639 infoLister.listJdbcDrivers();
644 public void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException {
645 infoLister.listJdbcProperties();
650 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
651 infoLister.listDatabases();
656 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
657 infoLister.testConnections();
661 public abstract void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException;