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.logging.Level;
47 import java.util.logging.Logger;
48 import javax.sql.rowset.RowSetMetaDataImpl;
51 * Displays info like help, version etc.
53 * @author Ing. František Kučera (frantovo.cz)
55 public class InfoLister {
57 private static final Logger log = Logger.getLogger(InfoLister.class.getName());
59 * Fake database name for output formatting
61 public static final String CONFIG_DB_NAME = "sqldk_configuration";
62 private PrintStream out;
63 private ConfigurationProvider configurationProvider;
64 private CLIOptions options;
65 private Formatter formatter;
67 public InfoLister(PrintStream out, ConfigurationProvider configurationProvider, CLIOptions options) {
69 this.configurationProvider = configurationProvider;
70 this.options = options;
73 public void showInfo() throws ConfigurationException, FormatterException {
74 EnumSet<InfoType> commands = options.getShowInfo();
76 boolean formattinNeeded = false;
78 for (InfoType infoType : commands) {
86 formattinNeeded = true;
91 if (formattinNeeded) {
92 try (Formatter f = getFormatter()) {
94 formatter.writeStartBatch();
95 DatabaseDefinition dd = new DatabaseDefinition();
96 dd.setName(CONFIG_DB_NAME);
97 formatter.writeStartDatabase(dd);
99 formatter.writeEndDatabase();
100 formatter.writeEndBatch();
108 private void showInfos(EnumSet<InfoType> commands) throws ConfigurationException, FormatterException {
109 for (InfoType infoType : commands) {
110 infoType.showInfo(this);
114 private void listFormatters() throws ConfigurationException, FormatterException {
115 ColumnsHeader header = constructHeader(
116 new HeaderField("name", SQLType.VARCHAR),
117 new HeaderField("built_in", SQLType.BOOLEAN),
118 new HeaderField("default", SQLType.BOOLEAN),
119 new HeaderField("class_name", SQLType.VARCHAR),
120 new HeaderField("valid", SQLType.BOOLEAN));
121 List<Object[]> data = new ArrayList<>();
123 String defaultFormatter = configurationProvider.getConfiguration().getDefaultFormatter();
124 defaultFormatter = defaultFormatter == null ? Configuration.DEFAULT_FORMATTER : defaultFormatter;
126 for (FormatterDefinition fd : configurationProvider.getConfiguration().getBuildInFormatters()) {
127 data.add(new Object[]{fd.getName(), true, defaultFormatter.equals(fd.getName()), fd.getClassName(), isInstantiable(fd)});
130 for (FormatterDefinition fd : configurationProvider.getConfiguration().getFormatters()) {
131 data.add(new Object[]{fd.getName(), false, defaultFormatter.equals(fd.getName()), fd.getClassName(), isInstantiable(fd)});
134 printTable(formatter, header, data, "-- configured and built-in output formatters", null);
137 private boolean isInstantiable(FormatterDefinition fd) {
139 try (ByteArrayOutputStream testStream = new ByteArrayOutputStream()) {
140 fd.getInstance(new FormatterContext(testStream, new Properties(0)));
143 } catch (Exception e) {
144 log.log(Level.SEVERE, "Unable to create an instance of formatter: " + fd.getName(), e);
149 public void listTypes() throws FormatterException, ConfigurationException {
150 ColumnsHeader header = constructHeader(new HeaderField("name", SQLType.VARCHAR), new HeaderField("code", SQLType.INTEGER));
151 List<Object[]> data = new ArrayList<>();
152 for (SQLType sqlType : SQLType.values()) {
153 data.add(new Object[]{sqlType.name(), sqlType.getCode()});
155 printTable(formatter, header, data, "-- data types", null);
156 log.log(Level.INFO, "Type names in --types option are case insensitive");
159 public void listDatabases() throws ConfigurationException, FormatterException {
160 ColumnsHeader header = constructHeader(
161 new HeaderField("database_name", SQLType.VARCHAR),
162 new HeaderField("user_name", SQLType.VARCHAR),
163 new HeaderField("database_url", SQLType.VARCHAR));
164 List<Object[]> data = new ArrayList<>();
166 final List<DatabaseDefinition> configuredDatabases = configurationProvider.getConfiguration().getDatabases();
167 if (configuredDatabases.isEmpty()) {
168 log.log(Level.WARNING, "No databases are configured.");
170 for (DatabaseDefinition dd : configuredDatabases) {
171 data.add(new Object[]{dd.getName(), dd.getUserName(), dd.getUrl()});
175 printTable(formatter, header, data, "-- configured databases", null);
178 public void listJdbcDrivers() throws FormatterException, ConfigurationException {
179 ColumnsHeader header = constructHeader(
180 new HeaderField("class", SQLType.VARCHAR),
181 new HeaderField("version", SQLType.VARCHAR),
182 new HeaderField("major", SQLType.INTEGER),
183 new HeaderField("minor", SQLType.INTEGER),
184 new HeaderField("jdbc_compliant", SQLType.BOOLEAN));
185 List<Object[]> data = new ArrayList<>();
187 final ServiceLoader<Driver> drivers = ServiceLoader.load(Driver.class);
188 for (Driver d : drivers) {
189 data.add(new Object[]{
190 d.getClass().getName(),
191 d.getMajorVersion() + "." + d.getMinorVersion(),
198 printTable(formatter, header, data, "-- discovered JDBC drivers (available on the CLASSPATH)", null);
201 public void listJdbcProperties() throws FormatterException, ConfigurationException {
202 for (String dbName : options.getDatabaseNamesToListProperties()) {
203 ColumnsHeader header = constructHeader(
204 new HeaderField("property_name", SQLType.VARCHAR),
205 new HeaderField("required", SQLType.BOOLEAN),
206 new HeaderField("choices", SQLType.ARRAY),
207 new HeaderField("configured_value", SQLType.VARCHAR),
208 new HeaderField("description", SQLType.VARCHAR));
209 List<Object[]> data = new ArrayList<>();
211 DatabaseDefinition dd = configurationProvider.getConfiguration().getDatabase(dbName);
213 Driver driver = findDriver(dd);
215 if (driver == null) {
216 log.log(Level.WARNING, "No JDBC driver was found for DB: {0} with URL: {1}", new Object[]{dd.getName(), dd.getUrl()});
218 log.log(Level.INFO, "For DB: {0} was found JDBC driver: {1}", new Object[]{dd.getName(), driver.getClass().getName()});
221 DriverPropertyInfo[] propertyInfos = driver.getPropertyInfo(dd.getUrl(), dd.getProperties().getJavaProperties());
223 Set<String> standardProperties = new HashSet<>();
225 for (DriverPropertyInfo pi : propertyInfos) {
226 Array choices = new FakeSqlArray(pi.choices, SQLType.VARCHAR);
227 data.add(new Object[]{
230 choices.getArray() == null ? "" : choices,
231 pi.value == null ? "" : pi.value,
234 standardProperties.add(pi.name);
237 for (Property p : dd.getProperties()) {
238 if (!standardProperties.contains(p.getName())) {
239 data.add(new Object[]{
246 log.log(Level.WARNING, "Your configuration contains property „{0}“ not declared by the JDBC driver.", p.getName());
250 } catch (SQLException e) {
251 log.log(Level.WARNING, "Error during getting property infos.", e);
254 List<Parameter> parameters = new ArrayList<>();
255 parameters.add(new NamedParameter("databgase", dbName, SQLType.VARCHAR));
256 parameters.add(new NamedParameter("driver_class", driver.getClass().getName(), SQLType.VARCHAR));
257 parameters.add(new NamedParameter("driver_major_version", driver.getMajorVersion(), SQLType.INTEGER));
258 parameters.add(new NamedParameter("driver_minor_version", driver.getMinorVersion(), SQLType.INTEGER));
260 printTable(formatter, header, data, "-- configured and configurable JDBC driver properties", parameters);
266 private Driver findDriver(DatabaseDefinition dd) {
267 final ServiceLoader<Driver> drivers = ServiceLoader.load(Driver.class);
268 for (Driver d : drivers) {
270 if (d.acceptsURL(dd.getUrl())) {
273 } catch (SQLException e) {
274 log.log(Level.WARNING, "Error during finding JDBC driver for: " + dd.getName(), e);
280 public void testConnection() throws FormatterException, ConfigurationException {
281 ColumnsHeader header = constructHeader(
282 new HeaderField("database_name", SQLType.VARCHAR),
283 new HeaderField("configured", SQLType.BOOLEAN),
284 new HeaderField("connected", SQLType.BOOLEAN));
285 List<Object[]> data = new ArrayList<>();
287 for (String dbName : options.getDatabaseNamesToTest()) {
288 data.add(testConnection(dbName));
291 printTable(formatter, header, data, "-- database configuration and connectivity test", null);
294 public Object[] testConnection(String dbName) {
295 log.log(Level.FINE, "Testing connection to database: {0}", dbName);
297 boolean succesfullyConnected = false;
298 boolean succesfullyConfigured = false;
301 DatabaseDefinition dd = configurationProvider.getConfiguration().getDatabase(dbName);
302 log.log(Level.FINE, "Database definition was loaded from configuration");
303 succesfullyConfigured = true;
304 try (DatabaseConnection dc = dd.connect(options.getDatabaseProperties())) {
305 succesfullyConnected = dc.test();
307 log.log(Level.FINE, "Database connection test was successful");
308 } catch (ConfigurationException | SQLException e) {
309 log.log(Level.SEVERE, "Error during testing connection", e);
312 return new Object[]{dbName, succesfullyConfigured, succesfullyConnected};
315 public void printResource(String fileName) {
316 try (BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream(fileName)))) {
318 String line = reader.readLine();
325 } catch (Exception e) {
326 log.log(Level.SEVERE, "Unable to print this info. Please see our website for it: " + Constants.WEBSITE, e);
330 private void println(String line) {
334 private void printTable(Formatter formatter, ColumnsHeader header, List<Object[]> data, String sql, List<Parameter> parameters) throws ConfigurationException, FormatterException {
335 formatter.writeStartStatement();
338 formatter.writeQuery(sql);
339 if (parameters != null) {
340 formatter.writeParameters(parameters);
344 formatter.writeStartResultSet(header);
346 for (Object[] row : data) {
347 formatter.writeStartRow();
348 for (Object cell : row) {
349 formatter.writeColumnValue(cell);
351 formatter.writeEndRow();
354 formatter.writeEndResultSet();
355 formatter.writeEndStatement();
358 private Formatter getFormatter() throws ConfigurationException, FormatterException {
359 String formatterName = options.getFormatterName();
360 formatterName = formatterName == null ? Configuration.DEFAULT_FORMATTER_PREFETCHING : formatterName;
361 FormatterDefinition fd = configurationProvider.getConfiguration().getFormatter(formatterName);
362 FormatterContext context = new FormatterContext(out, options.getFormatterProperties());
363 return fd.getInstance(context);
366 private ColumnsHeader constructHeader(HeaderField... fields) throws FormatterException {
368 RowSetMetaDataImpl metaData = new RowSetMetaDataImpl();
369 metaData.setColumnCount(fields.length);
371 for (int i = 0; i < fields.length; i++) {
372 HeaderField hf = fields[i];
373 int sqlIndex = i + 1;
374 metaData.setColumnName(sqlIndex, hf.name);
375 metaData.setColumnLabel(sqlIndex, hf.name);
376 metaData.setColumnType(sqlIndex, hf.type.getCode());
377 metaData.setColumnTypeName(sqlIndex, hf.type.name());
380 return new ColumnsHeader(metaData);
381 } catch (SQLException e) {
382 throw new FormatterException("Error while constructing table headers", e);
386 private static class HeaderField {
391 public HeaderField(String name, SQLType type) {
397 public enum InfoType {
401 public void showInfo(InfoLister infoLister) {
402 infoLister.printResource(Constants.HELP_FILE);
407 public void showInfo(InfoLister infoLister) {
408 infoLister.printResource(Constants.VERSION_FILE);
413 public void showInfo(InfoLister infoLister) {
414 infoLister.printResource(Constants.LICENSE_FILE);
419 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
420 infoLister.listFormatters();
425 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
426 infoLister.listTypes();
431 public void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException {
432 infoLister.listJdbcDrivers();
437 public void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException {
438 infoLister.listJdbcProperties();
443 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
444 infoLister.listDatabases();
449 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
450 infoLister.testConnection();
454 public abstract void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException;