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.TunnelDefinition;
29 import info.globalcode.sql.dk.formatting.ColumnsHeader;
30 import info.globalcode.sql.dk.formatting.FakeSqlArray;
31 import info.globalcode.sql.dk.formatting.Formatter;
32 import info.globalcode.sql.dk.formatting.FormatterContext;
33 import info.globalcode.sql.dk.formatting.FormatterException;
34 import java.io.BufferedReader;
35 import java.io.ByteArrayOutputStream;
36 import java.io.InputStreamReader;
37 import java.io.PrintStream;
38 import java.sql.Array;
39 import java.sql.Driver;
40 import java.sql.DriverManager;
41 import java.sql.DriverPropertyInfo;
42 import java.sql.SQLException;
43 import java.util.ArrayList;
44 import java.util.Collections;
45 import java.util.Comparator;
46 import java.util.EnumSet;
47 import java.util.HashSet;
48 import java.util.List;
49 import java.util.Map.Entry;
50 import java.util.ServiceLoader;
52 import java.util.concurrent.ExecutorService;
53 import java.util.concurrent.Executors;
54 import java.util.concurrent.TimeUnit;
55 import java.util.logging.Level;
56 import java.util.logging.LogRecord;
57 import java.util.logging.Logger;
58 import javax.sql.rowset.RowSetMetaDataImpl;
61 * Displays info like help, version etc.
63 * @author Ing. František Kučera (frantovo.cz)
65 public class InfoLister {
67 private static final Logger log = Logger.getLogger(InfoLister.class.getName());
69 * Fake database name for output formatting
71 public static final String CONFIG_DB_NAME = "sqldk_configuration";
72 private final PrintStream out;
73 private final ConfigurationProvider configurationProvider;
74 private final CLIOptions options;
75 private Formatter formatter;
77 public InfoLister(PrintStream out, ConfigurationProvider configurationProvider, CLIOptions options) {
79 this.configurationProvider = configurationProvider;
80 this.options = options;
83 public void showInfo() throws ConfigurationException, FormatterException {
84 EnumSet<InfoType> commands = options.getShowInfo();
86 boolean formattinNeeded = false;
88 for (InfoType infoType : commands) {
95 case FORMATTER_PROPERTIES:
98 case ENVIRONMENT_VARIABLES:
99 formattinNeeded = true;
104 if (formattinNeeded) {
105 try (Formatter f = getFormatter()) {
107 formatter.writeStartBatch();
108 DatabaseDefinition dd = new DatabaseDefinition();
109 dd.setName(CONFIG_DB_NAME);
110 formatter.writeStartDatabase(dd);
112 formatter.writeEndDatabase();
113 formatter.writeEndBatch();
121 private void showInfos(EnumSet<InfoType> commands) throws ConfigurationException, FormatterException {
122 for (InfoType infoType : commands) {
123 infoType.showInfo(this);
127 private void listJavaProperties() throws FormatterException, ConfigurationException {
128 ColumnsHeader header = constructHeader(new HeaderField("name", SQLType.VARCHAR), new HeaderField("value", SQLType.VARCHAR));
129 List<Object[]> data = new ArrayList<>();
130 for (Entry<Object, Object> e : System.getProperties().entrySet()) {
131 data.add(new Object[]{e.getKey(), e.getValue()});
133 printTable(formatter, header, "-- Java system properties", null, data, 0);
136 private void listEnvironmentVariables() throws FormatterException, ConfigurationException {
137 ColumnsHeader header = constructHeader(new HeaderField("name", SQLType.VARCHAR), new HeaderField("value", SQLType.VARCHAR));
138 List<Object[]> data = new ArrayList<>();
139 for (Entry<String, String> e : System.getenv().entrySet()) {
140 data.add(new Object[]{e.getKey(), e.getValue()});
142 printTable(formatter, header, "-- environment variables", null, data, 0);
145 private void listFormatters() throws ConfigurationException, FormatterException {
146 ColumnsHeader header = constructHeader(
147 new HeaderField("name", SQLType.VARCHAR),
148 new HeaderField("built_in", SQLType.BOOLEAN),
149 new HeaderField("default", SQLType.BOOLEAN),
150 new HeaderField("class_name", SQLType.VARCHAR),
151 new HeaderField("valid", SQLType.BOOLEAN));
152 List<Object[]> data = new ArrayList<>();
154 String defaultFormatter = configurationProvider.getConfiguration().getDefaultFormatter();
155 defaultFormatter = defaultFormatter == null ? Configuration.DEFAULT_FORMATTER : defaultFormatter;
157 for (FormatterDefinition fd : configurationProvider.getConfiguration().getBuildInFormatters()) {
158 data.add(new Object[]{fd.getName(), true, defaultFormatter.equals(fd.getName()), fd.getClassName(), isInstantiable(fd)});
161 for (FormatterDefinition fd : configurationProvider.getConfiguration().getFormatters()) {
162 data.add(new Object[]{fd.getName(), false, defaultFormatter.equals(fd.getName()), fd.getClassName(), isInstantiable(fd)});
165 printTable(formatter, header, "-- configured and built-in output formatters", null, data);
168 private boolean isInstantiable(FormatterDefinition fd) {
170 try (ByteArrayOutputStream testStream = new ByteArrayOutputStream()) {
171 fd.getInstance(new FormatterContext(testStream, new Properties(0)));
174 } catch (Exception e) {
175 log.log(Level.SEVERE, "Unable to create an instance of formatter: " + fd.getName(), e);
180 private void listFormatterProperties() {
181 for (String name : options.getFormatterNamesToListProperties()) {
182 log.log(Level.SEVERE, "TODO: list formatter properties for {0}", name);
186 private void listTypes() throws FormatterException, ConfigurationException {
187 ColumnsHeader header = constructHeader(new HeaderField("name", SQLType.VARCHAR), new HeaderField("code", SQLType.INTEGER));
188 List<Object[]> data = new ArrayList<>();
189 for (SQLType sqlType : SQLType.values()) {
190 data.add(new Object[]{sqlType.name(), sqlType.getCode()});
192 printTable(formatter, header, "-- data types", null, data);
193 log.log(Level.INFO, "Type names in --types option are case insensitive");
196 private void listDatabases() throws ConfigurationException, FormatterException {
197 ColumnsHeader header = constructHeader(
198 new HeaderField("database_name", SQLType.VARCHAR),
199 new HeaderField("user_name", SQLType.VARCHAR),
200 new HeaderField("database_url", SQLType.VARCHAR));
201 List<Object[]> data = new ArrayList<>();
203 final List<DatabaseDefinition> configuredDatabases = configurationProvider.getConfiguration().getDatabases();
204 if (configuredDatabases.isEmpty()) {
205 log.log(Level.WARNING, "No databases are configured.");
207 for (DatabaseDefinition dd : configuredDatabases) {
208 data.add(new Object[]{dd.getName(), dd.getUserName(), dd.getUrl()});
210 final TunnelDefinition tunnel = dd.getTunnel();
211 if (tunnel != null) {
212 log.log(Level.INFO, "Tunnel command: {0}", tunnel.getCommand());
213 for (CommandArgument ca : Functions.notNull(tunnel.getArguments())) {
214 log.log(Level.INFO, "\targument: {0}/{1}", new Object[]{ca.getType(), ca.getValue()});
221 printTable(formatter, header, "-- configured databases", null, data);
224 private void listJdbcDrivers() throws FormatterException, ConfigurationException {
225 ColumnsHeader header = constructHeader(
226 new HeaderField("class", SQLType.VARCHAR),
227 new HeaderField("version", SQLType.VARCHAR),
228 new HeaderField("major", SQLType.INTEGER),
229 new HeaderField("minor", SQLType.INTEGER),
230 new HeaderField("jdbc_compliant", SQLType.BOOLEAN));
231 List<Object[]> data = new ArrayList<>();
233 final ServiceLoader<Driver> drivers = ServiceLoader.load(Driver.class);
234 for (Driver d : drivers) {
235 data.add(new Object[]{
236 d.getClass().getName(),
237 d.getMajorVersion() + "." + d.getMinorVersion(),
244 printTable(formatter, header, "-- discovered JDBC drivers (available on the CLASSPATH)", null, data);
247 private void listJdbcProperties() throws FormatterException, ConfigurationException {
248 for (String dbName : options.getDatabaseNamesToListProperties()) {
249 ColumnsHeader header = constructHeader(
250 new HeaderField("property_name", SQLType.VARCHAR),
251 new HeaderField("required", SQLType.BOOLEAN),
252 new HeaderField("choices", SQLType.ARRAY),
253 new HeaderField("configured_value", SQLType.VARCHAR),
254 new HeaderField("description", SQLType.VARCHAR));
255 List<Object[]> data = new ArrayList<>();
257 DatabaseDefinition dd = configurationProvider.getConfiguration().getDatabase(dbName);
259 Driver driver = findDriver(dd);
261 if (driver == null) {
262 log.log(Level.WARNING, "No JDBC driver was found for DB: {0} with URL: {1}", new Object[]{dd.getName(), dd.getUrl()});
264 log.log(Level.INFO, "For DB: {0} was found JDBC driver: {1}", new Object[]{dd.getName(), driver.getClass().getName()});
267 DriverPropertyInfo[] propertyInfos = driver.getPropertyInfo(dd.getUrl(), dd.getProperties().getJavaProperties());
269 Set<String> standardProperties = new HashSet<>();
271 for (DriverPropertyInfo pi : propertyInfos) {
272 Array choices = new FakeSqlArray(pi.choices, SQLType.VARCHAR);
273 data.add(new Object[]{
276 choices.getArray() == null ? "" : choices,
277 pi.value == null ? "" : pi.value,
280 standardProperties.add(pi.name);
283 for (Property p : dd.getProperties()) {
284 if (!standardProperties.contains(p.getName())) {
285 data.add(new Object[]{
292 log.log(Level.WARNING, "Your configuration contains property „{0}“ not declared by the JDBC driver.", p.getName());
296 } catch (SQLException e) {
297 log.log(Level.WARNING, "Error during getting property infos.", e);
300 List<Parameter> parameters = new ArrayList<>();
301 parameters.add(new NamedParameter("database", dbName, SQLType.VARCHAR));
302 parameters.add(new NamedParameter("driver_class", driver.getClass().getName(), SQLType.VARCHAR));
303 parameters.add(new NamedParameter("driver_major_version", driver.getMajorVersion(), SQLType.INTEGER));
304 parameters.add(new NamedParameter("driver_minor_version", driver.getMinorVersion(), SQLType.INTEGER));
306 printTable(formatter, header, "-- configured and configurable JDBC driver properties", parameters, data);
312 private Driver findDriver(DatabaseDefinition dd) {
313 final ServiceLoader<Driver> drivers = ServiceLoader.load(Driver.class);
314 for (Driver d : drivers) {
316 if (d.acceptsURL(dd.getUrl())) {
319 } catch (SQLException e) {
320 log.log(Level.WARNING, "Error during finding JDBC driver for: " + dd.getName(), e);
327 * Parallelism for connection testing – maximum concurrent database connections.
329 private static final int TESTING_THREAD_COUNT = 64;
331 * Time limit for all connection testing threads – particular timeouts per connection will be
334 private static final long TESTING_AWAIT_LIMIT = 1;
335 private static final TimeUnit TESTING_AWAIT_UNIT = TimeUnit.DAYS;
337 private void testConnections() throws FormatterException, ConfigurationException {
338 ColumnsHeader header = constructHeader(
339 new HeaderField("database_name", SQLType.VARCHAR),
340 new HeaderField("configured", SQLType.BOOLEAN),
341 new HeaderField("connected", SQLType.BOOLEAN));
343 log.log(Level.FINE, "Testing DB connections in {0} threads", TESTING_THREAD_COUNT);
345 ExecutorService es = Executors.newFixedThreadPool(TESTING_THREAD_COUNT);
347 final Formatter currentFormatter = formatter;
349 printHeader(currentFormatter, header, "-- database configuration and connectivity test", null);
351 for (final String dbName : options.getDatabaseNamesToTest()) {
352 preloadDriver(dbName);
355 for (final String dbName : options.getDatabaseNamesToTest()) {
357 final Object[] row = testConnection(dbName);
358 synchronized (currentFormatter) {
359 printRow(currentFormatter, row);
368 log.log(Level.FINEST, "Waiting for test results: {0} {1}", new Object[]{TESTING_AWAIT_LIMIT, TESTING_AWAIT_UNIT.name()});
369 boolean finished = es.awaitTermination(TESTING_AWAIT_LIMIT, TESTING_AWAIT_UNIT);
371 log.log(Level.FINEST, "All testing threads finished in time limit.");
373 throw new FormatterException("Exceeded total time limit for test threads – this should never happen");
375 } catch (InterruptedException e) {
376 throw new FormatterException("Interrupted while waiting for test results", e);
379 printFooter(currentFormatter);
383 * JDBC driver classes should be preloaded in single thread to avoid deadlocks while doing
384 * {@linkplain DriverManager#registerDriver(java.sql.Driver)} during parallel connections.
388 private void preloadDriver(String dbName) {
390 DatabaseDefinition dd = configurationProvider.getConfiguration().getDatabase(dbName);
391 Driver driver = findDriver(dd);
392 if (driver == null) {
393 log.log(Level.WARNING, "No Driver found for DB: {0}", dbName);
395 log.log(Level.FINEST, "Driver preloading for DB: {0} was successfull", dbName);
397 } catch (Exception e) {
398 LogRecord r = new LogRecord(Level.WARNING, "Failed to preload the Driver for DB: {0}");
399 r.setParameters(new Object[]{dbName});
405 private Object[] testConnection(String dbName) {
406 log.log(Level.FINE, "Testing connection to database: {0}", dbName);
408 boolean succesfullyConnected = false;
409 boolean succesfullyConfigured = false;
412 DatabaseDefinition dd = configurationProvider.getConfiguration().getDatabase(dbName);
413 log.log(Level.FINE, "Database definition was loaded from configuration");
414 succesfullyConfigured = true;
415 try (DatabaseConnection dc = dd.connect(options.getDatabaseProperties())) {
416 succesfullyConnected = dc.test();
418 log.log(Level.FINE, "Database connection test was successful");
419 } catch (ConfigurationException | SQLException | RuntimeException e) {
420 log.log(Level.SEVERE, "Error during testing connection " + dbName, e);
423 return new Object[]{dbName, succesfullyConfigured, succesfullyConnected};
426 private void printResource(String fileName) {
427 try (BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream(fileName)))) {
429 String line = reader.readLine();
436 } catch (Exception e) {
437 log.log(Level.SEVERE, "Unable to print this info. Please see our website for it: " + Constants.WEBSITE, e);
441 private void println(String line) {
445 private void printTable(Formatter formatter, ColumnsHeader header, String sql, List<Parameter> parameters, List<Object[]> data) throws ConfigurationException, FormatterException {
446 printTable(formatter, header, sql, parameters, data, null);
449 private void printTable(Formatter formatter, ColumnsHeader header, String sql, List<Parameter> parameters, List<Object[]> data, final Integer sortByColumn) throws ConfigurationException, FormatterException {
450 printHeader(formatter, header, sql, parameters);
452 if (sortByColumn != null) {
453 Collections.sort(data, new Comparator<Object[]>() {
456 public int compare(Object[] o1, Object[] o2) {
457 String s1 = String.valueOf(o1[sortByColumn]);
458 String s2 = String.valueOf(o2[sortByColumn]);
459 return s1.compareTo(s2);
464 for (Object[] row : data) {
465 printRow(formatter, row);
468 printFooter(formatter);
471 private void printHeader(Formatter formatter, ColumnsHeader header, String sql, List<Parameter> parameters) {
472 formatter.writeStartStatement();
474 formatter.writeQuery(sql);
475 if (parameters != null) {
476 formatter.writeParameters(parameters);
479 formatter.writeStartResultSet(header);
482 private void printRow(Formatter formatter, Object[] row) {
483 formatter.writeStartRow();
484 for (Object cell : row) {
485 formatter.writeColumnValue(cell);
487 formatter.writeEndRow();
490 private void printFooter(Formatter formatter) {
491 formatter.writeEndResultSet();
492 formatter.writeEndStatement();
495 private Formatter getFormatter() throws ConfigurationException, FormatterException {
496 String formatterName = options.getFormatterName();
497 formatterName = formatterName == null ? Configuration.DEFAULT_FORMATTER_PREFETCHING : formatterName;
498 FormatterDefinition fd = configurationProvider.getConfiguration().getFormatter(formatterName);
499 FormatterContext context = new FormatterContext(out, options.getFormatterProperties());
500 return fd.getInstance(context);
503 private ColumnsHeader constructHeader(HeaderField... fields) throws FormatterException {
505 RowSetMetaDataImpl metaData = new RowSetMetaDataImpl();
506 metaData.setColumnCount(fields.length);
508 for (int i = 0; i < fields.length; i++) {
509 HeaderField hf = fields[i];
510 int sqlIndex = i + 1;
511 metaData.setColumnName(sqlIndex, hf.name);
512 metaData.setColumnLabel(sqlIndex, hf.name);
513 metaData.setColumnType(sqlIndex, hf.type.getCode());
514 metaData.setColumnTypeName(sqlIndex, hf.type.name());
517 return new ColumnsHeader(metaData);
518 } catch (SQLException e) {
519 throw new FormatterException("Error while constructing table headers", e);
523 private static class HeaderField {
528 public HeaderField(String name, SQLType type) {
534 public enum InfoType {
538 public void showInfo(InfoLister infoLister) {
539 infoLister.printResource(Constants.HELP_FILE);
544 public void showInfo(InfoLister infoLister) {
545 infoLister.printResource(Constants.VERSION_FILE);
550 public void showInfo(InfoLister infoLister) {
551 infoLister.printResource(Constants.LICENSE_FILE);
556 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
557 infoLister.listJavaProperties();
560 ENVIRONMENT_VARIABLES {
562 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
563 infoLister.listEnvironmentVariables();
568 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
569 infoLister.listFormatters();
572 FORMATTER_PROPERTIES {
574 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
575 infoLister.listFormatterProperties();
580 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
581 infoLister.listTypes();
586 public void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException {
587 infoLister.listJdbcDrivers();
592 public void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException {
593 infoLister.listJdbcProperties();
598 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
599 infoLister.listDatabases();
604 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
605 infoLister.testConnections();
609 public abstract void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException;