java/sql-dk/src/info/globalcode/sql/dk/InfoLister.java
author František Kučera <franta-hg@frantovo.cz>
Wed, 15 Jan 2014 21:06:12 +0100
branchv_0
changeset 159 9632b23df30c
parent 158 770b5009ec42
child 160 84ea4a819fb2
permissions -rw-r--r--
InfoLister: list configured and configurable JDBC driver properties – option: --list-jdbc-properties
     1 /**
     2  * SQL-DK
     3  * Copyright © 2013 František Kučera (frantovo.cz)
     4  *
     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.
     9  *
    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.
    14  *
    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/>.
    17  */
    18 package info.globalcode.sql.dk;
    19 
    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;
    43 import java.util.Set;
    44 import java.util.logging.Level;
    45 import java.util.logging.Logger;
    46 import javax.sql.rowset.RowSetMetaDataImpl;
    47 
    48 /**
    49  * Displays info like help, version etc.
    50  *
    51  * @author Ing. František Kučera (frantovo.cz)
    52  */
    53 public class InfoLister {
    54 
    55 	private static final Logger log = Logger.getLogger(InfoLister.class.getName());
    56 	/**
    57 	 * Fake database name for output formatting
    58 	 */
    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;
    64 
    65 	public InfoLister(PrintStream out, ConfigurationProvider configurationProvider, CLIOptions options) {
    66 		this.out = out;
    67 		this.configurationProvider = configurationProvider;
    68 		this.options = options;
    69 	}
    70 
    71 	public void showInfo() throws ConfigurationException, FormatterException {
    72 		EnumSet<InfoType> commands = options.getShowInfo();
    73 
    74 		boolean formattinNeeded = false;
    75 
    76 		for (InfoType infoType : commands) {
    77 			switch (infoType) {
    78 				case CONNECTION:
    79 				case JDBC_DRIVERS:
    80 				case JDBC_PROPERTIES:
    81 				case DATABASES:
    82 				case FORMATTERS:
    83 				case TYPES:
    84 					formattinNeeded = true;
    85 					break;
    86 			}
    87 		}
    88 
    89 		if (formattinNeeded) {
    90 			try (Formatter f = getFormatter()) {
    91 				formatter = f;
    92 				formatter.writeStartBatch();
    93 				DatabaseDefinition dd = new DatabaseDefinition();
    94 				dd.setName(CONFIG_DB_NAME);
    95 				formatter.writeStartDatabase(dd);
    96 				showInfos(commands);
    97 				formatter.writeEndDatabase();
    98 				formatter.writeEndBatch();
    99 				formatter.close();
   100 			}
   101 		} else {
   102 			showInfos(commands);
   103 		}
   104 	}
   105 
   106 	private void showInfos(EnumSet<InfoType> commands) throws ConfigurationException, FormatterException {
   107 		for (InfoType infoType : commands) {
   108 			infoType.showInfo(this);
   109 		}
   110 	}
   111 
   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<>();
   119 
   120 		String defaultFormatter = configurationProvider.getConfiguration().getDefaultFormatter();
   121 		defaultFormatter = defaultFormatter == null ? Configuration.DEFAULT_FORMATTER : defaultFormatter;
   122 
   123 		for (FormatterDefinition fd : configurationProvider.getConfiguration().getBuildInFormatters()) {
   124 			data.add(new Object[]{fd.getName(), true, defaultFormatter.equals(fd.getName()), fd.getClassName()});
   125 		}
   126 
   127 		for (FormatterDefinition fd : configurationProvider.getConfiguration().getFormatters()) {
   128 			data.add(new Object[]{fd.getName(), false, defaultFormatter.equals(fd.getName()), fd.getClassName()});
   129 		}
   130 
   131 		printTable(formatter, header, data, "-- configured and built-in output formatters", null);
   132 
   133 
   134 	}
   135 
   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()});
   141 		}
   142 		printTable(formatter, header, data, "-- data types", null);
   143 		log.log(Level.INFO, "Type names in --types option are case insensitive");
   144 	}
   145 
   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<>();
   152 
   153 		final List<DatabaseDefinition> configuredDatabases = configurationProvider.getConfiguration().getDatabases();
   154 		if (configuredDatabases.isEmpty()) {
   155 			log.log(Level.WARNING, "No databases are configured.");
   156 		} else {
   157 			for (DatabaseDefinition dd : configuredDatabases) {
   158 				data.add(new Object[]{dd.getName(), dd.getUserName(), dd.getUrl()});
   159 			}
   160 		}
   161 
   162 		printTable(formatter, header, data, "-- configured databases", null);
   163 	}
   164 
   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<>();
   173 
   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(),
   179 				d.getMajorVersion(),
   180 				d.getMinorVersion(),
   181 				d.jdbcCompliant()
   182 			});
   183 		}
   184 
   185 		printTable(formatter, header, data, "-- discovered JDBC drivers (available on the CLASSPATH)", null);
   186 	}
   187 
   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<>();
   197 
   198 			DatabaseDefinition dd = configurationProvider.getConfiguration().getDatabase(dbName);
   199 
   200 			Driver driver = findDriver(dd);
   201 
   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()});
   204 			} else {
   205 				log.log(Level.INFO, "For DB: {0} was found JDBC driver: {1}", new Object[]{dd.getName(), driver.getClass().getName()});
   206 
   207 				try {
   208 					DriverPropertyInfo[] propertyInfos = driver.getPropertyInfo(dd.getUrl(), dd.getProperties().getJavaProperties());
   209 
   210 					Set<String> standardProperties = new HashSet<>();
   211 
   212 					for (DriverPropertyInfo pi : propertyInfos) {
   213 						Array choices = new FakeSqlArray(pi.choices, SQLType.VARCHAR);
   214 						data.add(new Object[]{
   215 							pi.name,
   216 							pi.required,
   217 							choices.getArray() == null ? "" : choices,
   218 							pi.value == null ? "" : pi.value,
   219 							pi.description
   220 						});
   221 						standardProperties.add(pi.name);
   222 					}
   223 
   224 					for (Property p : dd.getProperties()) {
   225 						if (!standardProperties.contains(p.getName())) {
   226 							data.add(new Object[]{
   227 								p.getName(),
   228 								"",
   229 								"",
   230 								p.getValue(),
   231 								""
   232 							});
   233 							log.log(Level.WARNING, "Your configuration contains property „{0}“ not declared by the JDBC driver.", p.getName());
   234 						}
   235 					}
   236 
   237 				} catch (SQLException e) {
   238 					log.log(Level.WARNING, "Error during getting property infos.", e);
   239 				}
   240 
   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));
   246 
   247 				printTable(formatter, header, data, "-- configured and configurable JDBC driver properties", parameters);
   248 			}
   249 		}
   250 
   251 	}
   252 
   253 	private Driver findDriver(DatabaseDefinition dd) {
   254 		final ServiceLoader<Driver> drivers = ServiceLoader.load(Driver.class);
   255 		for (Driver d : drivers) {
   256 			try {
   257 				if (d.acceptsURL(dd.getUrl())) {
   258 					return d;
   259 				}
   260 			} catch (SQLException e) {
   261 				log.log(Level.WARNING, "Error during finding JDBC driver for: " + dd.getName(), e);
   262 			}
   263 		}
   264 		return null;
   265 	}
   266 
   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<>();
   273 
   274 		for (String dbName : options.getDatabaseNamesToTest()) {
   275 			data.add(testConnection(dbName));
   276 		}
   277 
   278 		printTable(formatter, header, data, "-- database configuration and connectivity test", null);
   279 	}
   280 
   281 	public Object[] testConnection(String dbName) {
   282 		log.log(Level.FINE, "Testing connection to database: {0}", dbName);
   283 
   284 		boolean succesfullyConnected = false;
   285 		boolean succesfullyConfigured = false;
   286 
   287 		try {
   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();
   293 			}
   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);
   297 		}
   298 
   299 		return new Object[]{dbName, succesfullyConfigured, succesfullyConnected};
   300 	}
   301 
   302 	public void printResource(String fileName) {
   303 		try (BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream(fileName)))) {
   304 			while (true) {
   305 				String line = reader.readLine();
   306 				if (line == null) {
   307 					break;
   308 				} else {
   309 					println(line);
   310 				}
   311 			}
   312 		} catch (Exception e) {
   313 			log.log(Level.SEVERE, "Unable to print this info. Please see our website for it: " + Constants.WEBSITE, e);
   314 		}
   315 	}
   316 
   317 	private void println(String line) {
   318 		out.println(line);
   319 	}
   320 
   321 	private void printTable(Formatter formatter, ColumnsHeader header, List<Object[]> data, String sql, List<Parameter> parameters) throws ConfigurationException, FormatterException {
   322 		formatter.writeStartStatement();
   323 
   324 		if (sql != null) {
   325 			formatter.writeQuery(sql);
   326 			if (parameters != null) {
   327 				formatter.writeParameters(parameters);
   328 			}
   329 		}
   330 
   331 		formatter.writeStartResultSet(header);
   332 
   333 		for (Object[] row : data) {
   334 			formatter.writeStartRow();
   335 			for (Object cell : row) {
   336 				formatter.writeColumnValue(cell);
   337 			}
   338 			formatter.writeEndRow();
   339 		}
   340 
   341 		formatter.writeEndResultSet();
   342 		formatter.writeEndStatement();
   343 	}
   344 
   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);
   351 	}
   352 
   353 	private ColumnsHeader constructHeader(HeaderField... fields) throws FormatterException {
   354 		try {
   355 			RowSetMetaDataImpl metaData = new RowSetMetaDataImpl();
   356 			metaData.setColumnCount(fields.length);
   357 
   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());
   365 			}
   366 
   367 			return new ColumnsHeader(metaData);
   368 		} catch (SQLException e) {
   369 			throw new FormatterException("Error while constructing table headers", e);
   370 		}
   371 	}
   372 
   373 	private static class HeaderField {
   374 
   375 		String name;
   376 		SQLType type;
   377 
   378 		public HeaderField(String name, SQLType type) {
   379 			this.name = name;
   380 			this.type = type;
   381 		}
   382 	}
   383 
   384 	public enum InfoType {
   385 
   386 		HELP {
   387 			@Override
   388 			public void showInfo(InfoLister infoLister) {
   389 				infoLister.printResource(Constants.HELP_FILE);
   390 			}
   391 		},
   392 		VERSION {
   393 			@Override
   394 			public void showInfo(InfoLister infoLister) {
   395 				infoLister.printResource(Constants.VERSION_FILE);
   396 			}
   397 		},
   398 		LICENSE {
   399 			@Override
   400 			public void showInfo(InfoLister infoLister) {
   401 				infoLister.printResource(Constants.LICENSE_FILE);
   402 			}
   403 		},
   404 		FORMATTERS {
   405 			@Override
   406 			public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
   407 				infoLister.listFormatters();
   408 			}
   409 		},
   410 		TYPES {
   411 			@Override
   412 			public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
   413 				infoLister.listTypes();
   414 			}
   415 		},
   416 		JDBC_DRIVERS {
   417 			@Override
   418 			public void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException {
   419 				infoLister.listJdbcDrivers();
   420 			}
   421 		},
   422 		JDBC_PROPERTIES {
   423 			@Override
   424 			public void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException {
   425 				infoLister.listJdbcProperties();
   426 			}
   427 		},
   428 		DATABASES {
   429 			@Override
   430 			public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
   431 				infoLister.listDatabases();
   432 			}
   433 		},
   434 		CONNECTION {
   435 			@Override
   436 			public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
   437 				infoLister.testConnection();
   438 			}
   439 		};
   440 
   441 		public abstract void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException;
   442 	}
   443 }