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.DriverPropertyInfo;
39 import java.sql.SQLException;
40 import java.util.ArrayList;
41 import java.util.EnumSet;
42 import java.util.HashSet;
43 import java.util.List;
44 import java.util.ServiceLoader;
46 import java.util.concurrent.ExecutorService;
47 import java.util.concurrent.Executors;
48 import java.util.concurrent.TimeUnit;
49 import java.util.logging.Level;
50 import java.util.logging.Logger;
51 import javax.sql.rowset.RowSetMetaDataImpl;
54 * Displays info like help, version etc.
56 * @author Ing. František Kučera (frantovo.cz)
58 public class InfoLister {
60 private static final Logger log = Logger.getLogger(InfoLister.class.getName());
62 * Fake database name for output formatting
64 public static final String CONFIG_DB_NAME = "sqldk_configuration";
65 private final PrintStream out;
66 private final ConfigurationProvider configurationProvider;
67 private final CLIOptions options;
68 private Formatter formatter;
70 public InfoLister(PrintStream out, ConfigurationProvider configurationProvider, CLIOptions options) {
72 this.configurationProvider = configurationProvider;
73 this.options = options;
76 public void showInfo() throws ConfigurationException, FormatterException {
77 EnumSet<InfoType> commands = options.getShowInfo();
79 boolean formattinNeeded = false;
81 for (InfoType infoType : commands) {
89 formattinNeeded = true;
94 if (formattinNeeded) {
95 try (Formatter f = getFormatter()) {
97 formatter.writeStartBatch();
98 DatabaseDefinition dd = new DatabaseDefinition();
99 dd.setName(CONFIG_DB_NAME);
100 formatter.writeStartDatabase(dd);
102 formatter.writeEndDatabase();
103 formatter.writeEndBatch();
111 private void showInfos(EnumSet<InfoType> commands) throws ConfigurationException, FormatterException {
112 for (InfoType infoType : commands) {
113 infoType.showInfo(this);
117 private void listFormatters() throws ConfigurationException, FormatterException {
118 ColumnsHeader header = constructHeader(
119 new HeaderField("name", SQLType.VARCHAR),
120 new HeaderField("built_in", SQLType.BOOLEAN),
121 new HeaderField("default", SQLType.BOOLEAN),
122 new HeaderField("class_name", SQLType.VARCHAR),
123 new HeaderField("valid", SQLType.BOOLEAN));
124 List<Object[]> data = new ArrayList<>();
126 String defaultFormatter = configurationProvider.getConfiguration().getDefaultFormatter();
127 defaultFormatter = defaultFormatter == null ? Configuration.DEFAULT_FORMATTER : defaultFormatter;
129 for (FormatterDefinition fd : configurationProvider.getConfiguration().getBuildInFormatters()) {
130 data.add(new Object[]{fd.getName(), true, defaultFormatter.equals(fd.getName()), fd.getClassName(), isInstantiable(fd)});
133 for (FormatterDefinition fd : configurationProvider.getConfiguration().getFormatters()) {
134 data.add(new Object[]{fd.getName(), false, defaultFormatter.equals(fd.getName()), fd.getClassName(), isInstantiable(fd)});
137 printTable(formatter, header, "-- configured and built-in output formatters", null, data);
140 private boolean isInstantiable(FormatterDefinition fd) {
142 try (ByteArrayOutputStream testStream = new ByteArrayOutputStream()) {
143 fd.getInstance(new FormatterContext(testStream, new Properties(0)));
146 } catch (Exception e) {
147 log.log(Level.SEVERE, "Unable to create an instance of formatter: " + fd.getName(), e);
152 public void listTypes() throws FormatterException, ConfigurationException {
153 ColumnsHeader header = constructHeader(new HeaderField("name", SQLType.VARCHAR), new HeaderField("code", SQLType.INTEGER));
154 List<Object[]> data = new ArrayList<>();
155 for (SQLType sqlType : SQLType.values()) {
156 data.add(new Object[]{sqlType.name(), sqlType.getCode()});
158 printTable(formatter, header, "-- data types", null, data);
159 log.log(Level.INFO, "Type names in --types option are case insensitive");
162 public void listDatabases() throws ConfigurationException, FormatterException {
163 ColumnsHeader header = constructHeader(
164 new HeaderField("database_name", SQLType.VARCHAR),
165 new HeaderField("user_name", SQLType.VARCHAR),
166 new HeaderField("database_url", SQLType.VARCHAR));
167 List<Object[]> data = new ArrayList<>();
169 final List<DatabaseDefinition> configuredDatabases = configurationProvider.getConfiguration().getDatabases();
170 if (configuredDatabases.isEmpty()) {
171 log.log(Level.WARNING, "No databases are configured.");
173 for (DatabaseDefinition dd : configuredDatabases) {
174 data.add(new Object[]{dd.getName(), dd.getUserName(), dd.getUrl()});
178 printTable(formatter, header, "-- configured databases", null, data);
181 public void listJdbcDrivers() throws FormatterException, ConfigurationException {
182 ColumnsHeader header = constructHeader(
183 new HeaderField("class", SQLType.VARCHAR),
184 new HeaderField("version", SQLType.VARCHAR),
185 new HeaderField("major", SQLType.INTEGER),
186 new HeaderField("minor", SQLType.INTEGER),
187 new HeaderField("jdbc_compliant", SQLType.BOOLEAN));
188 List<Object[]> data = new ArrayList<>();
190 final ServiceLoader<Driver> drivers = ServiceLoader.load(Driver.class);
191 for (Driver d : drivers) {
192 data.add(new Object[]{
193 d.getClass().getName(),
194 d.getMajorVersion() + "." + d.getMinorVersion(),
201 printTable(formatter, header, "-- discovered JDBC drivers (available on the CLASSPATH)", null, data);
204 public void listJdbcProperties() throws FormatterException, ConfigurationException {
205 for (String dbName : options.getDatabaseNamesToListProperties()) {
206 ColumnsHeader header = constructHeader(
207 new HeaderField("property_name", SQLType.VARCHAR),
208 new HeaderField("required", SQLType.BOOLEAN),
209 new HeaderField("choices", SQLType.ARRAY),
210 new HeaderField("configured_value", SQLType.VARCHAR),
211 new HeaderField("description", SQLType.VARCHAR));
212 List<Object[]> data = new ArrayList<>();
214 DatabaseDefinition dd = configurationProvider.getConfiguration().getDatabase(dbName);
216 Driver driver = findDriver(dd);
218 if (driver == null) {
219 log.log(Level.WARNING, "No JDBC driver was found for DB: {0} with URL: {1}", new Object[]{dd.getName(), dd.getUrl()});
221 log.log(Level.INFO, "For DB: {0} was found JDBC driver: {1}", new Object[]{dd.getName(), driver.getClass().getName()});
224 DriverPropertyInfo[] propertyInfos = driver.getPropertyInfo(dd.getUrl(), dd.getProperties().getJavaProperties());
226 Set<String> standardProperties = new HashSet<>();
228 for (DriverPropertyInfo pi : propertyInfos) {
229 Array choices = new FakeSqlArray(pi.choices, SQLType.VARCHAR);
230 data.add(new Object[]{
233 choices.getArray() == null ? "" : choices,
234 pi.value == null ? "" : pi.value,
237 standardProperties.add(pi.name);
240 for (Property p : dd.getProperties()) {
241 if (!standardProperties.contains(p.getName())) {
242 data.add(new Object[]{
249 log.log(Level.WARNING, "Your configuration contains property „{0}“ not declared by the JDBC driver.", p.getName());
253 } catch (SQLException e) {
254 log.log(Level.WARNING, "Error during getting property infos.", e);
257 List<Parameter> parameters = new ArrayList<>();
258 parameters.add(new NamedParameter("databgase", dbName, SQLType.VARCHAR));
259 parameters.add(new NamedParameter("driver_class", driver.getClass().getName(), SQLType.VARCHAR));
260 parameters.add(new NamedParameter("driver_major_version", driver.getMajorVersion(), SQLType.INTEGER));
261 parameters.add(new NamedParameter("driver_minor_version", driver.getMinorVersion(), SQLType.INTEGER));
263 printTable(formatter, header, "-- configured and configurable JDBC driver properties", parameters, data);
269 private Driver findDriver(DatabaseDefinition dd) {
270 final ServiceLoader<Driver> drivers = ServiceLoader.load(Driver.class);
271 for (Driver d : drivers) {
273 if (d.acceptsURL(dd.getUrl())) {
276 } catch (SQLException e) {
277 log.log(Level.WARNING, "Error during finding JDBC driver for: " + dd.getName(), e);
284 * Parallelism for connection testing – maximum concurrent database connections.
286 private static final int TESTING_THREAD_COUNT = 64;
288 * Time limit for all connection testing threads – particular timeouts per connection will be
291 private static final long TESTING_AWAIT_LIMIT = 1;
292 private static final TimeUnit TESTING_AWAIT_UNIT = TimeUnit.DAYS;
294 public void testConnections() throws FormatterException, ConfigurationException {
295 ColumnsHeader header = constructHeader(
296 new HeaderField("database_name", SQLType.VARCHAR),
297 new HeaderField("configured", SQLType.BOOLEAN),
298 new HeaderField("connected", SQLType.BOOLEAN));
300 log.log(Level.FINE, "Testing DB connections in {0} threads", TESTING_THREAD_COUNT);
302 ExecutorService es = Executors.newFixedThreadPool(TESTING_THREAD_COUNT);
304 final Formatter currentFormatter = formatter;
306 printHeader(currentFormatter, header, "-- database configuration and connectivity test", null);
308 for (final String dbName : options.getDatabaseNamesToTest()) {
309 es.submit(new Runnable() {
310 // TODO: Java 8 – lambda
313 final Object[] row = testConnection(dbName);
314 synchronized (currentFormatter) {
315 printRow(currentFormatter, row);
324 log.log(Level.FINEST, "Waiting for test results: {0} {1}", new Object[]{TESTING_AWAIT_LIMIT, TESTING_AWAIT_UNIT.name()});
325 boolean finished = es.awaitTermination(TESTING_AWAIT_LIMIT, TESTING_AWAIT_UNIT);
327 log.log(Level.FINEST, "All testing threads finished in time limit.");
329 throw new FormatterException("Exceeded total time limit for test threads – this should never happen");
331 } catch (InterruptedException e) {
332 throw new FormatterException("Interrupted while waiting for test results", e);
335 printFooter(currentFormatter);
338 public Object[] testConnection(String dbName) {
339 log.log(Level.FINE, "Testing connection to database: {0}", dbName);
341 boolean succesfullyConnected = false;
342 boolean succesfullyConfigured = false;
345 DatabaseDefinition dd = configurationProvider.getConfiguration().getDatabase(dbName);
346 log.log(Level.FINE, "Database definition was loaded from configuration");
347 succesfullyConfigured = true;
348 try (DatabaseConnection dc = dd.connect(options.getDatabaseProperties())) {
349 succesfullyConnected = dc.test();
351 log.log(Level.FINE, "Database connection test was successful");
352 } catch (ConfigurationException | SQLException e) {
353 log.log(Level.SEVERE, "Error during testing connection " + dbName, e);
356 return new Object[]{dbName, succesfullyConfigured, succesfullyConnected};
359 public void printResource(String fileName) {
360 try (BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream(fileName)))) {
362 String line = reader.readLine();
369 } catch (Exception e) {
370 log.log(Level.SEVERE, "Unable to print this info. Please see our website for it: " + Constants.WEBSITE, e);
374 private void println(String line) {
378 private void printTable(Formatter formatter, ColumnsHeader header, String sql, List<Parameter> parameters, List<Object[]> data) throws ConfigurationException, FormatterException {
379 printHeader(formatter, header, sql, parameters);
381 for (Object[] row : data) {
382 printRow(formatter, row);
385 printFooter(formatter);
388 private void printHeader(Formatter formatter, ColumnsHeader header, String sql, List<Parameter> parameters) {
389 formatter.writeStartStatement();
391 formatter.writeQuery(sql);
392 if (parameters != null) {
393 formatter.writeParameters(parameters);
396 formatter.writeStartResultSet(header);
399 private void printRow(Formatter formatter, Object[] row) {
400 formatter.writeStartRow();
401 for (Object cell : row) {
402 formatter.writeColumnValue(cell);
404 formatter.writeEndRow();
407 private void printFooter(Formatter formatter) {
408 formatter.writeEndResultSet();
409 formatter.writeEndStatement();
412 private Formatter getFormatter() throws ConfigurationException, FormatterException {
413 String formatterName = options.getFormatterName();
414 formatterName = formatterName == null ? Configuration.DEFAULT_FORMATTER_PREFETCHING : formatterName;
415 FormatterDefinition fd = configurationProvider.getConfiguration().getFormatter(formatterName);
416 FormatterContext context = new FormatterContext(out, options.getFormatterProperties());
417 return fd.getInstance(context);
420 private ColumnsHeader constructHeader(HeaderField... fields) throws FormatterException {
422 RowSetMetaDataImpl metaData = new RowSetMetaDataImpl();
423 metaData.setColumnCount(fields.length);
425 for (int i = 0; i < fields.length; i++) {
426 HeaderField hf = fields[i];
427 int sqlIndex = i + 1;
428 metaData.setColumnName(sqlIndex, hf.name);
429 metaData.setColumnLabel(sqlIndex, hf.name);
430 metaData.setColumnType(sqlIndex, hf.type.getCode());
431 metaData.setColumnTypeName(sqlIndex, hf.type.name());
434 return new ColumnsHeader(metaData);
435 } catch (SQLException e) {
436 throw new FormatterException("Error while constructing table headers", e);
440 private static class HeaderField {
445 public HeaderField(String name, SQLType type) {
451 public enum InfoType {
455 public void showInfo(InfoLister infoLister) {
456 infoLister.printResource(Constants.HELP_FILE);
461 public void showInfo(InfoLister infoLister) {
462 infoLister.printResource(Constants.VERSION_FILE);
467 public void showInfo(InfoLister infoLister) {
468 infoLister.printResource(Constants.LICENSE_FILE);
473 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
474 infoLister.listFormatters();
479 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
480 infoLister.listTypes();
485 public void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException {
486 infoLister.listJdbcDrivers();
491 public void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException {
492 infoLister.listJdbcProperties();
497 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
498 infoLister.listDatabases();
503 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
504 infoLister.testConnections();
508 public abstract void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException;