InfoLister: list configured and configurable JDBC driver properties – option: --list-jdbc-properties
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.Property;
26 import info.globalcode.sql.dk.formatting.ColumnsHeader;
27 import info.globalcode.sql.dk.formatting.FakeSqlArray;
28 import info.globalcode.sql.dk.formatting.Formatter;
29 import info.globalcode.sql.dk.formatting.FormatterContext;
30 import info.globalcode.sql.dk.formatting.FormatterException;
31 import java.io.BufferedReader;
32 import java.io.InputStreamReader;
33 import java.io.PrintStream;
34 import java.sql.Array;
35 import java.sql.Driver;
36 import java.sql.DriverPropertyInfo;
37 import java.sql.SQLException;
38 import java.util.ArrayList;
39 import java.util.EnumSet;
40 import java.util.HashSet;
41 import java.util.List;
42 import java.util.ServiceLoader;
44 import java.util.logging.Level;
45 import java.util.logging.Logger;
46 import javax.sql.rowset.RowSetMetaDataImpl;
49 * Displays info like help, version etc.
51 * @author Ing. František Kučera (frantovo.cz)
53 public class InfoLister {
55 private static final Logger log = Logger.getLogger(InfoLister.class.getName());
57 * Fake database name for output formatting
59 public static final String CONFIG_DB_NAME = "sqldk_configuration";
60 private PrintStream out;
61 private ConfigurationProvider configurationProvider;
62 private CLIOptions options;
63 private Formatter formatter;
65 public InfoLister(PrintStream out, ConfigurationProvider configurationProvider, CLIOptions options) {
67 this.configurationProvider = configurationProvider;
68 this.options = options;
71 public void showInfo() throws ConfigurationException, FormatterException {
72 EnumSet<InfoType> commands = options.getShowInfo();
74 boolean formattinNeeded = false;
76 for (InfoType infoType : commands) {
84 formattinNeeded = true;
89 if (formattinNeeded) {
90 try (Formatter f = getFormatter()) {
92 formatter.writeStartBatch();
93 DatabaseDefinition dd = new DatabaseDefinition();
94 dd.setName(CONFIG_DB_NAME);
95 formatter.writeStartDatabase(dd);
97 formatter.writeEndDatabase();
98 formatter.writeEndBatch();
106 private void showInfos(EnumSet<InfoType> commands) throws ConfigurationException, FormatterException {
107 for (InfoType infoType : commands) {
108 infoType.showInfo(this);
112 private void listFormatters() throws ConfigurationException, FormatterException {
113 ColumnsHeader header = constructHeader(
114 new HeaderField("name", SQLType.VARCHAR),
115 new HeaderField("built_in", SQLType.BOOLEAN),
116 new HeaderField("default", SQLType.BOOLEAN),
117 new HeaderField("class_name", SQLType.VARCHAR));
118 List<Object[]> data = new ArrayList<>();
120 String defaultFormatter = configurationProvider.getConfiguration().getDefaultFormatter();
121 defaultFormatter = defaultFormatter == null ? Configuration.DEFAULT_FORMATTER : defaultFormatter;
123 for (FormatterDefinition fd : configurationProvider.getConfiguration().getBuildInFormatters()) {
124 data.add(new Object[]{fd.getName(), true, defaultFormatter.equals(fd.getName()), fd.getClassName()});
127 for (FormatterDefinition fd : configurationProvider.getConfiguration().getFormatters()) {
128 data.add(new Object[]{fd.getName(), false, defaultFormatter.equals(fd.getName()), fd.getClassName()});
131 printTable(formatter, header, data, "-- configured and built-in output formatters", null);
136 public void listTypes() throws FormatterException, ConfigurationException {
137 ColumnsHeader header = constructHeader(new HeaderField("name", SQLType.VARCHAR), new HeaderField("code", SQLType.INTEGER));
138 List<Object[]> data = new ArrayList<>();
139 for (SQLType sqlType : SQLType.values()) {
140 data.add(new Object[]{sqlType.name(), sqlType.getCode()});
142 printTable(formatter, header, data, "-- data types", null);
143 log.log(Level.INFO, "Type names in --types option are case insensitive");
146 public void listDatabases() throws ConfigurationException, FormatterException {
147 ColumnsHeader header = constructHeader(
148 new HeaderField("database_name", SQLType.VARCHAR),
149 new HeaderField("user_name", SQLType.VARCHAR),
150 new HeaderField("database_url", SQLType.VARCHAR));
151 List<Object[]> data = new ArrayList<>();
153 final List<DatabaseDefinition> configuredDatabases = configurationProvider.getConfiguration().getDatabases();
154 if (configuredDatabases.isEmpty()) {
155 log.log(Level.WARNING, "No databases are configured.");
157 for (DatabaseDefinition dd : configuredDatabases) {
158 data.add(new Object[]{dd.getName(), dd.getUserName(), dd.getUrl()});
162 printTable(formatter, header, data, "-- configured databases", null);
165 public void listJdbcDrivers() throws FormatterException, ConfigurationException {
166 ColumnsHeader header = constructHeader(
167 new HeaderField("class", SQLType.VARCHAR),
168 new HeaderField("version", SQLType.VARCHAR),
169 new HeaderField("major", SQLType.INTEGER),
170 new HeaderField("minor", SQLType.INTEGER),
171 new HeaderField("jdbc_compliant", SQLType.BOOLEAN));
172 List<Object[]> data = new ArrayList<>();
174 final ServiceLoader<Driver> drivers = ServiceLoader.load(Driver.class);
175 for (Driver d : drivers) {
176 data.add(new Object[]{
177 d.getClass().getName(),
178 d.getMajorVersion() + "." + d.getMinorVersion(),
185 printTable(formatter, header, data, "-- discovered JDBC drivers (available on the CLASSPATH)", null);
188 public void listJdbcProperties() throws FormatterException, ConfigurationException {
189 for (String dbName : options.getDatabaseNamesToListProperties()) {
190 ColumnsHeader header = constructHeader(
191 new HeaderField("property_name", SQLType.VARCHAR),
192 new HeaderField("required", SQLType.BOOLEAN),
193 new HeaderField("choices", SQLType.ARRAY),
194 new HeaderField("configured_value", SQLType.VARCHAR),
195 new HeaderField("description", SQLType.VARCHAR));
196 List<Object[]> data = new ArrayList<>();
198 DatabaseDefinition dd = configurationProvider.getConfiguration().getDatabase(dbName);
200 Driver driver = findDriver(dd);
202 if (driver == null) {
203 log.log(Level.WARNING, "No JDBC driver was found for DB: {0} with URL: {1}", new Object[]{dd.getName(), dd.getUrl()});
205 log.log(Level.INFO, "For DB: {0} was found JDBC driver: {1}", new Object[]{dd.getName(), driver.getClass().getName()});
208 DriverPropertyInfo[] propertyInfos = driver.getPropertyInfo(dd.getUrl(), dd.getProperties().getJavaProperties());
210 Set<String> standardProperties = new HashSet<>();
212 for (DriverPropertyInfo pi : propertyInfos) {
213 Array choices = new FakeSqlArray(pi.choices, SQLType.VARCHAR);
214 data.add(new Object[]{
217 choices.getArray() == null ? "" : choices,
218 pi.value == null ? "" : pi.value,
221 standardProperties.add(pi.name);
224 for (Property p : dd.getProperties()) {
225 if (!standardProperties.contains(p.getName())) {
226 data.add(new Object[]{
233 log.log(Level.WARNING, "Your configuration contains property „{0}“ not declared by the JDBC driver.", p.getName());
237 } catch (SQLException e) {
238 log.log(Level.WARNING, "Error during getting property infos.", e);
241 List<Parameter> parameters = new ArrayList<>();
242 parameters.add(new NamedParameter("databgase", dbName, SQLType.VARCHAR));
243 parameters.add(new NamedParameter("driver_class", driver.getClass().getName(), SQLType.VARCHAR));
244 parameters.add(new NamedParameter("driver_major_version", driver.getMajorVersion(), SQLType.INTEGER));
245 parameters.add(new NamedParameter("driver_minor_version", driver.getMinorVersion(), SQLType.INTEGER));
247 printTable(formatter, header, data, "-- configured and configurable JDBC driver properties", parameters);
253 private Driver findDriver(DatabaseDefinition dd) {
254 final ServiceLoader<Driver> drivers = ServiceLoader.load(Driver.class);
255 for (Driver d : drivers) {
257 if (d.acceptsURL(dd.getUrl())) {
260 } catch (SQLException e) {
261 log.log(Level.WARNING, "Error during finding JDBC driver for: " + dd.getName(), e);
267 public void testConnection() throws FormatterException, ConfigurationException {
268 ColumnsHeader header = constructHeader(
269 new HeaderField("database_name", SQLType.VARCHAR),
270 new HeaderField("configured", SQLType.BOOLEAN),
271 new HeaderField("connected", SQLType.BOOLEAN));
272 List<Object[]> data = new ArrayList<>();
274 for (String dbName : options.getDatabaseNamesToTest()) {
275 data.add(testConnection(dbName));
278 printTable(formatter, header, data, "-- database configuration and connectivity test", null);
281 public Object[] testConnection(String dbName) {
282 log.log(Level.FINE, "Testing connection to database: {0}", dbName);
284 boolean succesfullyConnected = false;
285 boolean succesfullyConfigured = false;
288 DatabaseDefinition dd = configurationProvider.getConfiguration().getDatabase(dbName);
289 log.log(Level.FINE, "Database definition was loaded from configuration");
290 succesfullyConfigured = true;
291 try (DatabaseConnection dc = dd.connect(options.getDatabaseProperties())) {
292 succesfullyConnected = dc.test();
294 log.log(Level.FINE, "Database connection test was successful");
295 } catch (ConfigurationException | SQLException e) {
296 log.log(Level.SEVERE, "Error during testing connection", e);
299 return new Object[]{dbName, succesfullyConfigured, succesfullyConnected};
302 public void printResource(String fileName) {
303 try (BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream(fileName)))) {
305 String line = reader.readLine();
312 } catch (Exception e) {
313 log.log(Level.SEVERE, "Unable to print this info. Please see our website for it: " + Constants.WEBSITE, e);
317 private void println(String line) {
321 private void printTable(Formatter formatter, ColumnsHeader header, List<Object[]> data, String sql, List<Parameter> parameters) throws ConfigurationException, FormatterException {
322 formatter.writeStartStatement();
325 formatter.writeQuery(sql);
326 if (parameters != null) {
327 formatter.writeParameters(parameters);
331 formatter.writeStartResultSet(header);
333 for (Object[] row : data) {
334 formatter.writeStartRow();
335 for (Object cell : row) {
336 formatter.writeColumnValue(cell);
338 formatter.writeEndRow();
341 formatter.writeEndResultSet();
342 formatter.writeEndStatement();
345 private Formatter getFormatter() throws ConfigurationException, FormatterException {
346 String formatterName = options.getFormatterName();
347 formatterName = formatterName == null ? Configuration.DEFAULT_FORMATTER_PREFETCHING : formatterName;
348 FormatterDefinition fd = configurationProvider.getConfiguration().getFormatter(formatterName);
349 FormatterContext context = new FormatterContext(out, options.getFormatterProperties());
350 return fd.getInstance(context);
353 private ColumnsHeader constructHeader(HeaderField... fields) throws FormatterException {
355 RowSetMetaDataImpl metaData = new RowSetMetaDataImpl();
356 metaData.setColumnCount(fields.length);
358 for (int i = 0; i < fields.length; i++) {
359 HeaderField hf = fields[i];
360 int sqlIndex = i + 1;
361 metaData.setColumnName(sqlIndex, hf.name);
362 metaData.setColumnLabel(sqlIndex, hf.name);
363 metaData.setColumnType(sqlIndex, hf.type.getCode());
364 metaData.setColumnTypeName(sqlIndex, hf.type.name());
367 return new ColumnsHeader(metaData);
368 } catch (SQLException e) {
369 throw new FormatterException("Error while constructing table headers", e);
373 private static class HeaderField {
378 public HeaderField(String name, SQLType type) {
384 public enum InfoType {
388 public void showInfo(InfoLister infoLister) {
389 infoLister.printResource(Constants.HELP_FILE);
394 public void showInfo(InfoLister infoLister) {
395 infoLister.printResource(Constants.VERSION_FILE);
400 public void showInfo(InfoLister infoLister) {
401 infoLister.printResource(Constants.LICENSE_FILE);
406 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
407 infoLister.listFormatters();
412 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
413 infoLister.listTypes();
418 public void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException {
419 infoLister.listJdbcDrivers();
424 public void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException {
425 infoLister.listJdbcProperties();
430 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
431 infoLister.listDatabases();
436 public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
437 infoLister.testConnection();
441 public abstract void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException;