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.HashMap;
51 import java.util.HashSet;
52 import java.util.List;
54 import java.util.Map.Entry;
55 import java.util.ServiceLoader;
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;
66 * Displays info like help, version etc.
68 * @author Ing. František Kučera (frantovo.cz)
70 public class InfoLister {
72 private static final Logger log = Logger.getLogger(InfoLister.class.getName());
74 * Fake database name for output formatting
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;
82 public InfoLister(PrintStream out, ConfigurationProvider configurationProvider, CLIOptions options) {
84 this.configurationProvider = configurationProvider;
85 this.options = options;
88 public void showInfo() throws ConfigurationException, FormatterException {
89 EnumSet<InfoType> commands = options.getShowInfo();
91 boolean formattinNeeded = false;
93 for (InfoType infoType : commands) {
100 case FORMATTER_PROPERTIES:
102 case JAVA_PROPERTIES:
103 case ENVIRONMENT_VARIABLES:
104 formattinNeeded = true;
109 if (formattinNeeded) {
110 try (Formatter f = getFormatter()) {
112 formatter.writeStartBatch();
113 DatabaseDefinition dd = new DatabaseDefinition();
114 dd.setName(CONFIG_DB_NAME);
115 formatter.writeStartDatabase(dd);
117 formatter.writeEndDatabase();
118 formatter.writeEndBatch();
126 private void showInfos(EnumSet<InfoType> commands) throws ConfigurationException, FormatterException {
127 for (InfoType infoType : commands) {
128 infoType.showInfo(this);
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()});
138 printTable(formatter, header, "-- Java system properties", null, data, 0);
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()});
147 printTable(formatter, header, "-- environment variables", null, data, 0);
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<>();
159 String defaultFormatter = configurationProvider.getConfiguration().getDefaultFormatter();
160 defaultFormatter = defaultFormatter == null ? Configuration.DEFAULT_FORMATTER : defaultFormatter;
162 for (FormatterDefinition fd : configurationProvider.getConfiguration().getBuildInFormatters()) {
163 data.add(new Object[]{fd.getName(), true, defaultFormatter.equals(fd.getName()), fd.getClassName(), isInstantiable(fd)});
166 for (FormatterDefinition fd : configurationProvider.getConfiguration().getFormatters()) {
167 data.add(new Object[]{fd.getName(), false, defaultFormatter.equals(fd.getName()), fd.getClassName(), isInstantiable(fd)});
170 printTable(formatter, header, "-- configured and built-in output formatters", null, data);
173 private boolean isInstantiable(FormatterDefinition fd) {
175 try (ByteArrayOutputStream testStream = new ByteArrayOutputStream()) {
176 fd.getInstance(new FormatterContext(testStream, new Properties(0)));
179 } catch (Exception e) {
180 log.log(Level.SEVERE, "Unable to create an instance of formatter: " + fd.getName(), e);
185 private void listFormatterProperties() throws FormatterException, ConfigurationException {
186 for (String formatterName : options.getFormatterNamesToListProperties()) {
187 listFormatterProperties(formatterName);
191 private PropertyDeclaration[] getPropertyDeclarations(Class<? extends Formatter> formatterClass) {
192 PropertyDeclarations properties = formatterClass.getAnnotation(PropertyDeclarations.class);
194 if (properties == null) {
195 PropertyDeclaration p = formatterClass.getAnnotation(PropertyDeclaration.class);
196 return p == null ? new PropertyDeclaration[]{} : new PropertyDeclaration[]{p};
198 return properties.value();
202 private void listFormatterProperties(String formatterName) throws FormatterException, ConfigurationException {
203 FormatterDefinition fd = configurationProvider.getConfiguration().getFormatter(formatterName);
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)
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));
223 List<Parameter> parameters = new ArrayList<>();
224 parameters.add(new NamedParameter("formatter", formatterName, SQLType.VARCHAR));
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);
232 private static Object[] propertyDeclarationToRow(PropertyDeclaration p) {
235 CommonProperties.getSimpleTypeName(p.type()),
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()});
247 printTable(formatter, header, "-- data types", null, data);
248 log.log(Level.INFO, "Type names in --types option are case insensitive");
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<>();
258 final List<DatabaseDefinition> configuredDatabases = configurationProvider.getConfiguration().getDatabases();
259 if (configuredDatabases.isEmpty()) {
260 log.log(Level.WARNING, "No databases are configured.");
262 for (DatabaseDefinition dd : configuredDatabases) {
263 data.add(new Object[]{dd.getName(), dd.getUserName(), dd.getUrl()});
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()});
276 printTable(formatter, header, "-- configured databases", null, data);
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<>();
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(),
299 printTable(formatter, header, "-- discovered JDBC drivers (available on the CLASSPATH)", null, data);
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<>();
312 DatabaseDefinition dd = configurationProvider.getConfiguration().getDatabase(dbName);
314 Driver driver = findDriver(dd);
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()});
319 log.log(Level.INFO, "For DB: {0} was found JDBC driver: {1}", new Object[]{dd.getName(), driver.getClass().getName()});
322 DriverPropertyInfo[] propertyInfos = driver.getPropertyInfo(dd.getUrl(), dd.getProperties().getJavaProperties());
324 Set<String> standardProperties = new HashSet<>();
326 for (DriverPropertyInfo pi : propertyInfos) {
327 Array choices = new FakeSqlArray(pi.choices, SQLType.VARCHAR);
328 data.add(new Object[]{
331 choices.getArray() == null ? "" : choices,
332 pi.value == null ? "" : pi.value,
335 standardProperties.add(pi.name);
338 for (Property p : dd.getProperties()) {
339 if (!standardProperties.contains(p.getName())) {
340 data.add(new Object[]{
347 log.log(Level.WARNING, "Your configuration contains property „{0}“ not declared by the JDBC driver.", p.getName());
351 } catch (SQLException e) {
352 log.log(Level.WARNING, "Error during getting property infos.", e);
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));
361 printTable(formatter, header, "-- configured and configurable JDBC driver properties", parameters, data);
367 private Driver findDriver(DatabaseDefinition dd) {
368 final ServiceLoader<Driver> drivers = ServiceLoader.load(Driver.class);
369 for (Driver d : drivers) {
371 if (d.acceptsURL(dd.getUrl())) {
374 } catch (SQLException e) {
375 log.log(Level.WARNING, "Error during finding JDBC driver for: " + dd.getName(), e);
382 * Parallelism for connection testing – maximum concurrent database connections.
384 private static final int TESTING_THREAD_COUNT = 64;
386 * Time limit for all connection testing threads – particular timeouts per connection will be
389 private static final long TESTING_AWAIT_LIMIT = 1;
390 private static final TimeUnit TESTING_AWAIT_UNIT = TimeUnit.DAYS;
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));
398 log.log(Level.FINE, "Testing DB connections in {0} threads", TESTING_THREAD_COUNT);
400 ExecutorService es = Executors.newFixedThreadPool(TESTING_THREAD_COUNT);
402 final Formatter currentFormatter = formatter;
404 printHeader(currentFormatter, header, "-- database configuration and connectivity test", null);
406 for (final String dbName : options.getDatabaseNamesToTest()) {
407 preloadDriver(dbName);
410 for (final String dbName : options.getDatabaseNamesToTest()) {
412 final Object[] row = testConnection(dbName);
413 synchronized (currentFormatter) {
414 printRow(currentFormatter, row);
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);
426 log.log(Level.FINEST, "All testing threads finished in time limit.");
428 throw new FormatterException("Exceeded total time limit for test threads – this should never happen");
430 } catch (InterruptedException e) {
431 throw new FormatterException("Interrupted while waiting for test results", e);
434 printFooter(currentFormatter);
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.
443 private void preloadDriver(String dbName) {
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);
450 log.log(Level.FINEST, "Driver preloading for DB: {0} was successfull", dbName);
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});
460 private Object[] testConnection(String dbName) {
461 log.log(Level.FINE, "Testing connection to database: {0}", dbName);
463 boolean succesfullyConnected = false;
464 boolean succesfullyConfigured = false;
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();
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);
478 return new Object[]{dbName, succesfullyConfigured, succesfullyConnected};
481 private void printResource(String fileName) {
482 try (BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream(fileName)))) {
484 String line = reader.readLine();
491 } catch (Exception e) {
492 log.log(Level.SEVERE, "Unable to print this info. Please see our website for it: " + Constants.WEBSITE, e);
496 private void println(String line) {
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);
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);
507 if (sortByColumn != null) {
508 Collections.sort(data, new Comparator<Object[]>() {
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);
519 for (Object[] row : data) {
520 printRow(formatter, row);
523 printFooter(formatter);
526 private void printHeader(Formatter formatter, ColumnsHeader header, String sql, List<Parameter> parameters) {
527 formatter.writeStartStatement();
529 formatter.writeQuery(sql);
530 if (parameters != null) {
531 formatter.writeParameters(parameters);
534 formatter.writeStartResultSet(header);
537 private void printRow(Formatter formatter, Object[] row) {
538 formatter.writeStartRow();
539 for (Object cell : row) {
540 formatter.writeColumnValue(cell);
542 formatter.writeEndRow();
545 private void printFooter(Formatter formatter) {
546 formatter.writeEndResultSet();
547 formatter.writeEndStatement();
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);
558 private ColumnsHeader constructHeader(HeaderField... fields) throws FormatterException {
560 RowSetMetaDataImpl metaData = new RowSetMetaDataImpl();
561 metaData.setColumnCount(fields.length);
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());
572 return new ColumnsHeader(metaData);
573 } catch (SQLException e) {
574 throw new FormatterException("Error while constructing table headers", e);
578 private static class HeaderField {
583 public HeaderField(String name, SQLType type) {
589 public enum InfoType {
593 public void showInfo(InfoLister infoLister) {
594 infoLister.printResource(Constants.HELP_FILE);
599 public void showInfo(InfoLister infoLister) {
600 infoLister.printResource(Constants.VERSION_FILE);
605 public void showInfo(InfoLister infoLister) {
606 infoLister.printResource(Constants.LICENSE_FILE);
611 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
612 infoLister.listJavaProperties();
615 ENVIRONMENT_VARIABLES {
617 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
618 infoLister.listEnvironmentVariables();
623 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
624 infoLister.listFormatters();
627 FORMATTER_PROPERTIES {
629 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
630 infoLister.listFormatterProperties();
635 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
636 infoLister.listTypes();
641 public void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException {
642 infoLister.listJdbcDrivers();
647 public void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException {
648 infoLister.listJdbcProperties();
653 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
654 infoLister.listDatabases();
659 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
660 infoLister.testConnections();
664 public abstract void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException;