InfoLister: option --list-formatters also tests, if formatter class can be instantiated (thus is valid)
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.ByteArrayInputStream;
34 import java.io.ByteArrayOutputStream;
35 import java.io.InputStreamReader;
36 import java.io.PrintStream;
37 import java.sql.Array;
38 import java.sql.Driver;
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.logging.Level;
48 import java.util.logging.Logger;
49 import javax.sql.rowset.RowSetMetaDataImpl;
52 * Displays info like help, version etc.
54 * @author Ing. František Kučera (frantovo.cz)
56 public class InfoLister {
58 private static final Logger log = Logger.getLogger(InfoLister.class.getName());
60 * Fake database name for output formatting
62 public static final String CONFIG_DB_NAME = "sqldk_configuration";
63 private PrintStream out;
64 private ConfigurationProvider configurationProvider;
65 private CLIOptions options;
66 private Formatter formatter;
68 public InfoLister(PrintStream out, ConfigurationProvider configurationProvider, CLIOptions options) {
70 this.configurationProvider = configurationProvider;
71 this.options = options;
74 public void showInfo() throws ConfigurationException, FormatterException {
75 EnumSet<InfoType> commands = options.getShowInfo();
77 boolean formattinNeeded = false;
79 for (InfoType infoType : commands) {
87 formattinNeeded = true;
92 if (formattinNeeded) {
93 try (Formatter f = getFormatter()) {
95 formatter.writeStartBatch();
96 DatabaseDefinition dd = new DatabaseDefinition();
97 dd.setName(CONFIG_DB_NAME);
98 formatter.writeStartDatabase(dd);
100 formatter.writeEndDatabase();
101 formatter.writeEndBatch();
109 private void showInfos(EnumSet<InfoType> commands) throws ConfigurationException, FormatterException {
110 for (InfoType infoType : commands) {
111 infoType.showInfo(this);
115 private void listFormatters() throws ConfigurationException, FormatterException {
116 ColumnsHeader header = constructHeader(
117 new HeaderField("name", SQLType.VARCHAR),
118 new HeaderField("built_in", SQLType.BOOLEAN),
119 new HeaderField("default", SQLType.BOOLEAN),
120 new HeaderField("class_name", SQLType.VARCHAR),
121 new HeaderField("valid", SQLType.BOOLEAN));
122 List<Object[]> data = new ArrayList<>();
124 String defaultFormatter = configurationProvider.getConfiguration().getDefaultFormatter();
125 defaultFormatter = defaultFormatter == null ? Configuration.DEFAULT_FORMATTER : defaultFormatter;
127 for (FormatterDefinition fd : configurationProvider.getConfiguration().getBuildInFormatters()) {
128 data.add(new Object[]{fd.getName(), true, defaultFormatter.equals(fd.getName()), fd.getClassName(), isInstantiable(fd)});
131 for (FormatterDefinition fd : configurationProvider.getConfiguration().getFormatters()) {
132 data.add(new Object[]{fd.getName(), false, defaultFormatter.equals(fd.getName()), fd.getClassName(), isInstantiable(fd)});
135 printTable(formatter, header, data, "-- configured and built-in output formatters", null);
138 private boolean isInstantiable(FormatterDefinition fd) {
140 try (ByteArrayOutputStream testStream = new ByteArrayOutputStream()) {
141 fd.getInstance(new FormatterContext(testStream, new Properties(0)));
144 } catch (Exception e) {
145 log.log(Level.SEVERE, "Unable to create an instance of formatter: " + fd.getName(), e);
150 public void listTypes() throws FormatterException, ConfigurationException {
151 ColumnsHeader header = constructHeader(new HeaderField("name", SQLType.VARCHAR), new HeaderField("code", SQLType.INTEGER));
152 List<Object[]> data = new ArrayList<>();
153 for (SQLType sqlType : SQLType.values()) {
154 data.add(new Object[]{sqlType.name(), sqlType.getCode()});
156 printTable(formatter, header, data, "-- data types", null);
157 log.log(Level.INFO, "Type names in --types option are case insensitive");
160 public void listDatabases() throws ConfigurationException, FormatterException {
161 ColumnsHeader header = constructHeader(
162 new HeaderField("database_name", SQLType.VARCHAR),
163 new HeaderField("user_name", SQLType.VARCHAR),
164 new HeaderField("database_url", SQLType.VARCHAR));
165 List<Object[]> data = new ArrayList<>();
167 final List<DatabaseDefinition> configuredDatabases = configurationProvider.getConfiguration().getDatabases();
168 if (configuredDatabases.isEmpty()) {
169 log.log(Level.WARNING, "No databases are configured.");
171 for (DatabaseDefinition dd : configuredDatabases) {
172 data.add(new Object[]{dd.getName(), dd.getUserName(), dd.getUrl()});
176 printTable(formatter, header, data, "-- configured databases", null);
179 public void listJdbcDrivers() throws FormatterException, ConfigurationException {
180 ColumnsHeader header = constructHeader(
181 new HeaderField("class", SQLType.VARCHAR),
182 new HeaderField("version", SQLType.VARCHAR),
183 new HeaderField("major", SQLType.INTEGER),
184 new HeaderField("minor", SQLType.INTEGER),
185 new HeaderField("jdbc_compliant", SQLType.BOOLEAN));
186 List<Object[]> data = new ArrayList<>();
188 final ServiceLoader<Driver> drivers = ServiceLoader.load(Driver.class);
189 for (Driver d : drivers) {
190 data.add(new Object[]{
191 d.getClass().getName(),
192 d.getMajorVersion() + "." + d.getMinorVersion(),
199 printTable(formatter, header, data, "-- discovered JDBC drivers (available on the CLASSPATH)", null);
202 public void listJdbcProperties() throws FormatterException, ConfigurationException {
203 for (String dbName : options.getDatabaseNamesToListProperties()) {
204 ColumnsHeader header = constructHeader(
205 new HeaderField("property_name", SQLType.VARCHAR),
206 new HeaderField("required", SQLType.BOOLEAN),
207 new HeaderField("choices", SQLType.ARRAY),
208 new HeaderField("configured_value", SQLType.VARCHAR),
209 new HeaderField("description", SQLType.VARCHAR));
210 List<Object[]> data = new ArrayList<>();
212 DatabaseDefinition dd = configurationProvider.getConfiguration().getDatabase(dbName);
214 Driver driver = findDriver(dd);
216 if (driver == null) {
217 log.log(Level.WARNING, "No JDBC driver was found for DB: {0} with URL: {1}", new Object[]{dd.getName(), dd.getUrl()});
219 log.log(Level.INFO, "For DB: {0} was found JDBC driver: {1}", new Object[]{dd.getName(), driver.getClass().getName()});
222 DriverPropertyInfo[] propertyInfos = driver.getPropertyInfo(dd.getUrl(), dd.getProperties().getJavaProperties());
224 Set<String> standardProperties = new HashSet<>();
226 for (DriverPropertyInfo pi : propertyInfos) {
227 Array choices = new FakeSqlArray(pi.choices, SQLType.VARCHAR);
228 data.add(new Object[]{
231 choices.getArray() == null ? "" : choices,
232 pi.value == null ? "" : pi.value,
235 standardProperties.add(pi.name);
238 for (Property p : dd.getProperties()) {
239 if (!standardProperties.contains(p.getName())) {
240 data.add(new Object[]{
247 log.log(Level.WARNING, "Your configuration contains property „{0}“ not declared by the JDBC driver.", p.getName());
251 } catch (SQLException e) {
252 log.log(Level.WARNING, "Error during getting property infos.", e);
255 List<Parameter> parameters = new ArrayList<>();
256 parameters.add(new NamedParameter("databgase", dbName, SQLType.VARCHAR));
257 parameters.add(new NamedParameter("driver_class", driver.getClass().getName(), SQLType.VARCHAR));
258 parameters.add(new NamedParameter("driver_major_version", driver.getMajorVersion(), SQLType.INTEGER));
259 parameters.add(new NamedParameter("driver_minor_version", driver.getMinorVersion(), SQLType.INTEGER));
261 printTable(formatter, header, data, "-- configured and configurable JDBC driver properties", parameters);
267 private Driver findDriver(DatabaseDefinition dd) {
268 final ServiceLoader<Driver> drivers = ServiceLoader.load(Driver.class);
269 for (Driver d : drivers) {
271 if (d.acceptsURL(dd.getUrl())) {
274 } catch (SQLException e) {
275 log.log(Level.WARNING, "Error during finding JDBC driver for: " + dd.getName(), e);
281 public void testConnection() throws FormatterException, ConfigurationException {
282 ColumnsHeader header = constructHeader(
283 new HeaderField("database_name", SQLType.VARCHAR),
284 new HeaderField("configured", SQLType.BOOLEAN),
285 new HeaderField("connected", SQLType.BOOLEAN));
286 List<Object[]> data = new ArrayList<>();
288 for (String dbName : options.getDatabaseNamesToTest()) {
289 data.add(testConnection(dbName));
292 printTable(formatter, header, data, "-- database configuration and connectivity test", null);
295 public Object[] testConnection(String dbName) {
296 log.log(Level.FINE, "Testing connection to database: {0}", dbName);
298 boolean succesfullyConnected = false;
299 boolean succesfullyConfigured = false;
302 DatabaseDefinition dd = configurationProvider.getConfiguration().getDatabase(dbName);
303 log.log(Level.FINE, "Database definition was loaded from configuration");
304 succesfullyConfigured = true;
305 try (DatabaseConnection dc = dd.connect(options.getDatabaseProperties())) {
306 succesfullyConnected = dc.test();
308 log.log(Level.FINE, "Database connection test was successful");
309 } catch (ConfigurationException | SQLException e) {
310 log.log(Level.SEVERE, "Error during testing connection", e);
313 return new Object[]{dbName, succesfullyConfigured, succesfullyConnected};
316 public void printResource(String fileName) {
317 try (BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream(fileName)))) {
319 String line = reader.readLine();
326 } catch (Exception e) {
327 log.log(Level.SEVERE, "Unable to print this info. Please see our website for it: " + Constants.WEBSITE, e);
331 private void println(String line) {
335 private void printTable(Formatter formatter, ColumnsHeader header, List<Object[]> data, String sql, List<Parameter> parameters) throws ConfigurationException, FormatterException {
336 formatter.writeStartStatement();
339 formatter.writeQuery(sql);
340 if (parameters != null) {
341 formatter.writeParameters(parameters);
345 formatter.writeStartResultSet(header);
347 for (Object[] row : data) {
348 formatter.writeStartRow();
349 for (Object cell : row) {
350 formatter.writeColumnValue(cell);
352 formatter.writeEndRow();
355 formatter.writeEndResultSet();
356 formatter.writeEndStatement();
359 private Formatter getFormatter() throws ConfigurationException, FormatterException {
360 String formatterName = options.getFormatterName();
361 formatterName = formatterName == null ? Configuration.DEFAULT_FORMATTER_PREFETCHING : formatterName;
362 FormatterDefinition fd = configurationProvider.getConfiguration().getFormatter(formatterName);
363 FormatterContext context = new FormatterContext(out, options.getFormatterProperties());
364 return fd.getInstance(context);
367 private ColumnsHeader constructHeader(HeaderField... fields) throws FormatterException {
369 RowSetMetaDataImpl metaData = new RowSetMetaDataImpl();
370 metaData.setColumnCount(fields.length);
372 for (int i = 0; i < fields.length; i++) {
373 HeaderField hf = fields[i];
374 int sqlIndex = i + 1;
375 metaData.setColumnName(sqlIndex, hf.name);
376 metaData.setColumnLabel(sqlIndex, hf.name);
377 metaData.setColumnType(sqlIndex, hf.type.getCode());
378 metaData.setColumnTypeName(sqlIndex, hf.type.name());
381 return new ColumnsHeader(metaData);
382 } catch (SQLException e) {
383 throw new FormatterException("Error while constructing table headers", e);
387 private static class HeaderField {
392 public HeaderField(String name, SQLType type) {
398 public enum InfoType {
402 public void showInfo(InfoLister infoLister) {
403 infoLister.printResource(Constants.HELP_FILE);
408 public void showInfo(InfoLister infoLister) {
409 infoLister.printResource(Constants.VERSION_FILE);
414 public void showInfo(InfoLister infoLister) {
415 infoLister.printResource(Constants.LICENSE_FILE);
420 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
421 infoLister.listFormatters();
426 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
427 infoLister.listTypes();
432 public void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException {
433 infoLister.listJdbcDrivers();
438 public void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException {
439 infoLister.listJdbcProperties();
444 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
445 infoLister.listDatabases();
450 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
451 infoLister.testConnection();
455 public abstract void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException;