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.EnumSet;
43 import java.util.HashSet;
44 import java.util.List;
45 import java.util.ServiceLoader;
47 import java.util.concurrent.ExecutorService;
48 import java.util.concurrent.Executors;
49 import java.util.concurrent.TimeUnit;
50 import java.util.logging.Level;
51 import java.util.logging.LogRecord;
52 import java.util.logging.Logger;
53 import javax.sql.rowset.RowSetMetaDataImpl;
56 * Displays info like help, version etc.
58 * @author Ing. František Kučera (frantovo.cz)
60 public class InfoLister {
62 private static final Logger log = Logger.getLogger(InfoLister.class.getName());
64 * Fake database name for output formatting
66 public static final String CONFIG_DB_NAME = "sqldk_configuration";
67 private final PrintStream out;
68 private final ConfigurationProvider configurationProvider;
69 private final CLIOptions options;
70 private Formatter formatter;
72 public InfoLister(PrintStream out, ConfigurationProvider configurationProvider, CLIOptions options) {
74 this.configurationProvider = configurationProvider;
75 this.options = options;
78 public void showInfo() throws ConfigurationException, FormatterException {
79 EnumSet<InfoType> commands = options.getShowInfo();
81 boolean formattinNeeded = false;
83 for (InfoType infoType : commands) {
91 formattinNeeded = true;
96 if (formattinNeeded) {
97 try (Formatter f = getFormatter()) {
99 formatter.writeStartBatch();
100 DatabaseDefinition dd = new DatabaseDefinition();
101 dd.setName(CONFIG_DB_NAME);
102 formatter.writeStartDatabase(dd);
104 formatter.writeEndDatabase();
105 formatter.writeEndBatch();
113 private void showInfos(EnumSet<InfoType> commands) throws ConfigurationException, FormatterException {
114 for (InfoType infoType : commands) {
115 infoType.showInfo(this);
119 private void listFormatters() throws ConfigurationException, FormatterException {
120 ColumnsHeader header = constructHeader(
121 new HeaderField("name", SQLType.VARCHAR),
122 new HeaderField("built_in", SQLType.BOOLEAN),
123 new HeaderField("default", SQLType.BOOLEAN),
124 new HeaderField("class_name", SQLType.VARCHAR),
125 new HeaderField("valid", SQLType.BOOLEAN));
126 List<Object[]> data = new ArrayList<>();
128 String defaultFormatter = configurationProvider.getConfiguration().getDefaultFormatter();
129 defaultFormatter = defaultFormatter == null ? Configuration.DEFAULT_FORMATTER : defaultFormatter;
131 for (FormatterDefinition fd : configurationProvider.getConfiguration().getBuildInFormatters()) {
132 data.add(new Object[]{fd.getName(), true, defaultFormatter.equals(fd.getName()), fd.getClassName(), isInstantiable(fd)});
135 for (FormatterDefinition fd : configurationProvider.getConfiguration().getFormatters()) {
136 data.add(new Object[]{fd.getName(), false, defaultFormatter.equals(fd.getName()), fd.getClassName(), isInstantiable(fd)});
139 printTable(formatter, header, "-- configured and built-in output formatters", null, data);
142 private boolean isInstantiable(FormatterDefinition fd) {
144 try (ByteArrayOutputStream testStream = new ByteArrayOutputStream()) {
145 fd.getInstance(new FormatterContext(testStream, new Properties(0)));
148 } catch (Exception e) {
149 log.log(Level.SEVERE, "Unable to create an instance of formatter: " + fd.getName(), e);
154 public void listTypes() throws FormatterException, ConfigurationException {
155 ColumnsHeader header = constructHeader(new HeaderField("name", SQLType.VARCHAR), new HeaderField("code", SQLType.INTEGER));
156 List<Object[]> data = new ArrayList<>();
157 for (SQLType sqlType : SQLType.values()) {
158 data.add(new Object[]{sqlType.name(), sqlType.getCode()});
160 printTable(formatter, header, "-- data types", null, data);
161 log.log(Level.INFO, "Type names in --types option are case insensitive");
164 public void listDatabases() throws ConfigurationException, FormatterException {
165 ColumnsHeader header = constructHeader(
166 new HeaderField("database_name", SQLType.VARCHAR),
167 new HeaderField("user_name", SQLType.VARCHAR),
168 new HeaderField("database_url", SQLType.VARCHAR));
169 List<Object[]> data = new ArrayList<>();
171 final List<DatabaseDefinition> configuredDatabases = configurationProvider.getConfiguration().getDatabases();
172 if (configuredDatabases.isEmpty()) {
173 log.log(Level.WARNING, "No databases are configured.");
175 for (DatabaseDefinition dd : configuredDatabases) {
176 data.add(new Object[]{dd.getName(), dd.getUserName(), dd.getUrl()});
180 printTable(formatter, header, "-- configured databases", null, data);
183 public void listJdbcDrivers() throws FormatterException, ConfigurationException {
184 ColumnsHeader header = constructHeader(
185 new HeaderField("class", SQLType.VARCHAR),
186 new HeaderField("version", SQLType.VARCHAR),
187 new HeaderField("major", SQLType.INTEGER),
188 new HeaderField("minor", SQLType.INTEGER),
189 new HeaderField("jdbc_compliant", SQLType.BOOLEAN));
190 List<Object[]> data = new ArrayList<>();
192 final ServiceLoader<Driver> drivers = ServiceLoader.load(Driver.class);
193 for (Driver d : drivers) {
194 data.add(new Object[]{
195 d.getClass().getName(),
196 d.getMajorVersion() + "." + d.getMinorVersion(),
203 printTable(formatter, header, "-- discovered JDBC drivers (available on the CLASSPATH)", null, data);
206 public void listJdbcProperties() throws FormatterException, ConfigurationException {
207 for (String dbName : options.getDatabaseNamesToListProperties()) {
208 ColumnsHeader header = constructHeader(
209 new HeaderField("property_name", SQLType.VARCHAR),
210 new HeaderField("required", SQLType.BOOLEAN),
211 new HeaderField("choices", SQLType.ARRAY),
212 new HeaderField("configured_value", SQLType.VARCHAR),
213 new HeaderField("description", SQLType.VARCHAR));
214 List<Object[]> data = new ArrayList<>();
216 DatabaseDefinition dd = configurationProvider.getConfiguration().getDatabase(dbName);
218 Driver driver = findDriver(dd);
220 if (driver == null) {
221 log.log(Level.WARNING, "No JDBC driver was found for DB: {0} with URL: {1}", new Object[]{dd.getName(), dd.getUrl()});
223 log.log(Level.INFO, "For DB: {0} was found JDBC driver: {1}", new Object[]{dd.getName(), driver.getClass().getName()});
226 DriverPropertyInfo[] propertyInfos = driver.getPropertyInfo(dd.getUrl(), dd.getProperties().getJavaProperties());
228 Set<String> standardProperties = new HashSet<>();
230 for (DriverPropertyInfo pi : propertyInfos) {
231 Array choices = new FakeSqlArray(pi.choices, SQLType.VARCHAR);
232 data.add(new Object[]{
235 choices.getArray() == null ? "" : choices,
236 pi.value == null ? "" : pi.value,
239 standardProperties.add(pi.name);
242 for (Property p : dd.getProperties()) {
243 if (!standardProperties.contains(p.getName())) {
244 data.add(new Object[]{
251 log.log(Level.WARNING, "Your configuration contains property „{0}“ not declared by the JDBC driver.", p.getName());
255 } catch (SQLException e) {
256 log.log(Level.WARNING, "Error during getting property infos.", e);
259 List<Parameter> parameters = new ArrayList<>();
260 parameters.add(new NamedParameter("database", dbName, SQLType.VARCHAR));
261 parameters.add(new NamedParameter("driver_class", driver.getClass().getName(), SQLType.VARCHAR));
262 parameters.add(new NamedParameter("driver_major_version", driver.getMajorVersion(), SQLType.INTEGER));
263 parameters.add(new NamedParameter("driver_minor_version", driver.getMinorVersion(), SQLType.INTEGER));
265 printTable(formatter, header, "-- configured and configurable JDBC driver properties", parameters, data);
271 private Driver findDriver(DatabaseDefinition dd) {
272 final ServiceLoader<Driver> drivers = ServiceLoader.load(Driver.class);
273 for (Driver d : drivers) {
275 if (d.acceptsURL(dd.getUrl())) {
278 } catch (SQLException e) {
279 log.log(Level.WARNING, "Error during finding JDBC driver for: " + dd.getName(), e);
286 * Parallelism for connection testing – maximum concurrent database connections.
288 private static final int TESTING_THREAD_COUNT = 64;
290 * Time limit for all connection testing threads – particular timeouts per connection will be
293 private static final long TESTING_AWAIT_LIMIT = 1;
294 private static final TimeUnit TESTING_AWAIT_UNIT = TimeUnit.DAYS;
296 public void testConnections() throws FormatterException, ConfigurationException {
297 ColumnsHeader header = constructHeader(
298 new HeaderField("database_name", SQLType.VARCHAR),
299 new HeaderField("configured", SQLType.BOOLEAN),
300 new HeaderField("connected", SQLType.BOOLEAN));
302 log.log(Level.FINE, "Testing DB connections in {0} threads", TESTING_THREAD_COUNT);
304 ExecutorService es = Executors.newFixedThreadPool(TESTING_THREAD_COUNT);
306 final Formatter currentFormatter = formatter;
308 printHeader(currentFormatter, header, "-- database configuration and connectivity test", null);
310 for (final String dbName : options.getDatabaseNamesToTest()) {
311 preloadDriver(dbName);
314 for (final String dbName : options.getDatabaseNamesToTest()) {
315 es.submit(new Runnable() {
316 // TODO: Java 8 – lambda
319 final Object[] row = testConnection(dbName);
320 synchronized (currentFormatter) {
321 printRow(currentFormatter, row);
330 log.log(Level.FINEST, "Waiting for test results: {0} {1}", new Object[]{TESTING_AWAIT_LIMIT, TESTING_AWAIT_UNIT.name()});
331 boolean finished = es.awaitTermination(TESTING_AWAIT_LIMIT, TESTING_AWAIT_UNIT);
333 log.log(Level.FINEST, "All testing threads finished in time limit.");
335 throw new FormatterException("Exceeded total time limit for test threads – this should never happen");
337 } catch (InterruptedException e) {
338 throw new FormatterException("Interrupted while waiting for test results", e);
341 printFooter(currentFormatter);
345 * JDBC driver classes should be preloaded in single thread to avoid deadlocks while doing
346 * {@linkplain DriverManager#registerDriver(java.sql.Driver)} during parallel connections.
350 private void preloadDriver(String dbName) {
352 DatabaseDefinition dd = configurationProvider.getConfiguration().getDatabase(dbName);
353 Driver driver = findDriver(dd);
354 if (driver == null) {
355 log.log(Level.WARNING, "No Driver found for DB: {0}", dbName);
357 log.log(Level.FINEST, "Driver preloading for DB: {0} was successfull", dbName);
359 } catch (Exception e) {
360 LogRecord r = new LogRecord(Level.WARNING, "Failed to preload the Driver for DB: {0}");
361 r.setParameters(new Object[]{dbName});
367 public Object[] testConnection(String dbName) {
368 log.log(Level.FINE, "Testing connection to database: {0}", dbName);
370 boolean succesfullyConnected = false;
371 boolean succesfullyConfigured = false;
374 DatabaseDefinition dd = configurationProvider.getConfiguration().getDatabase(dbName);
375 log.log(Level.FINE, "Database definition was loaded from configuration");
376 succesfullyConfigured = true;
377 try (DatabaseConnection dc = dd.connect(options.getDatabaseProperties())) {
378 succesfullyConnected = dc.test();
380 log.log(Level.FINE, "Database connection test was successful");
381 } catch (ConfigurationException | SQLException | RuntimeException e) {
382 log.log(Level.SEVERE, "Error during testing connection " + dbName, e);
385 return new Object[]{dbName, succesfullyConfigured, succesfullyConnected};
388 public void printResource(String fileName) {
389 try (BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream(fileName)))) {
391 String line = reader.readLine();
398 } catch (Exception e) {
399 log.log(Level.SEVERE, "Unable to print this info. Please see our website for it: " + Constants.WEBSITE, e);
403 private void println(String line) {
407 private void printTable(Formatter formatter, ColumnsHeader header, String sql, List<Parameter> parameters, List<Object[]> data) throws ConfigurationException, FormatterException {
408 printHeader(formatter, header, sql, parameters);
410 for (Object[] row : data) {
411 printRow(formatter, row);
414 printFooter(formatter);
417 private void printHeader(Formatter formatter, ColumnsHeader header, String sql, List<Parameter> parameters) {
418 formatter.writeStartStatement();
420 formatter.writeQuery(sql);
421 if (parameters != null) {
422 formatter.writeParameters(parameters);
425 formatter.writeStartResultSet(header);
428 private void printRow(Formatter formatter, Object[] row) {
429 formatter.writeStartRow();
430 for (Object cell : row) {
431 formatter.writeColumnValue(cell);
433 formatter.writeEndRow();
436 private void printFooter(Formatter formatter) {
437 formatter.writeEndResultSet();
438 formatter.writeEndStatement();
441 private Formatter getFormatter() throws ConfigurationException, FormatterException {
442 String formatterName = options.getFormatterName();
443 formatterName = formatterName == null ? Configuration.DEFAULT_FORMATTER_PREFETCHING : formatterName;
444 FormatterDefinition fd = configurationProvider.getConfiguration().getFormatter(formatterName);
445 FormatterContext context = new FormatterContext(out, options.getFormatterProperties());
446 return fd.getInstance(context);
449 private ColumnsHeader constructHeader(HeaderField... fields) throws FormatterException {
451 RowSetMetaDataImpl metaData = new RowSetMetaDataImpl();
452 metaData.setColumnCount(fields.length);
454 for (int i = 0; i < fields.length; i++) {
455 HeaderField hf = fields[i];
456 int sqlIndex = i + 1;
457 metaData.setColumnName(sqlIndex, hf.name);
458 metaData.setColumnLabel(sqlIndex, hf.name);
459 metaData.setColumnType(sqlIndex, hf.type.getCode());
460 metaData.setColumnTypeName(sqlIndex, hf.type.name());
463 return new ColumnsHeader(metaData);
464 } catch (SQLException e) {
465 throw new FormatterException("Error while constructing table headers", e);
469 private static class HeaderField {
474 public HeaderField(String name, SQLType type) {
480 public enum InfoType {
484 public void showInfo(InfoLister infoLister) {
485 infoLister.printResource(Constants.HELP_FILE);
490 public void showInfo(InfoLister infoLister) {
491 infoLister.printResource(Constants.VERSION_FILE);
496 public void showInfo(InfoLister infoLister) {
497 infoLister.printResource(Constants.LICENSE_FILE);
502 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
503 infoLister.listFormatters();
508 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
509 infoLister.listTypes();
514 public void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException {
515 infoLister.listJdbcDrivers();
520 public void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException {
521 infoLister.listJdbcProperties();
526 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
527 infoLister.listDatabases();
532 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
533 infoLister.testConnections();
537 public abstract void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException;