java/sql-dk/src/info/globalcode/sql/dk/InfoLister.java
author František Kučera <franta-hg@frantovo.cz>
Wed, 15 Jan 2014 21:26:15 +0100
branchv_0
changeset 160 84ea4a819fb2
parent 159 9632b23df30c
child 161 385929a50dd9
permissions -rw-r--r--
InfoLister: option --list-formatters also tests, if formatter class can be instantiated (thus is valid)
     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.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;
    46 import java.util.Set;
    47 import java.util.logging.Level;
    48 import java.util.logging.Logger;
    49 import javax.sql.rowset.RowSetMetaDataImpl;
    50 
    51 /**
    52  * Displays info like help, version etc.
    53  *
    54  * @author Ing. František Kučera (frantovo.cz)
    55  */
    56 public class InfoLister {
    57 
    58 	private static final Logger log = Logger.getLogger(InfoLister.class.getName());
    59 	/**
    60 	 * Fake database name for output formatting
    61 	 */
    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;
    67 
    68 	public InfoLister(PrintStream out, ConfigurationProvider configurationProvider, CLIOptions options) {
    69 		this.out = out;
    70 		this.configurationProvider = configurationProvider;
    71 		this.options = options;
    72 	}
    73 
    74 	public void showInfo() throws ConfigurationException, FormatterException {
    75 		EnumSet<InfoType> commands = options.getShowInfo();
    76 
    77 		boolean formattinNeeded = false;
    78 
    79 		for (InfoType infoType : commands) {
    80 			switch (infoType) {
    81 				case CONNECTION:
    82 				case JDBC_DRIVERS:
    83 				case JDBC_PROPERTIES:
    84 				case DATABASES:
    85 				case FORMATTERS:
    86 				case TYPES:
    87 					formattinNeeded = true;
    88 					break;
    89 			}
    90 		}
    91 
    92 		if (formattinNeeded) {
    93 			try (Formatter f = getFormatter()) {
    94 				formatter = f;
    95 				formatter.writeStartBatch();
    96 				DatabaseDefinition dd = new DatabaseDefinition();
    97 				dd.setName(CONFIG_DB_NAME);
    98 				formatter.writeStartDatabase(dd);
    99 				showInfos(commands);
   100 				formatter.writeEndDatabase();
   101 				formatter.writeEndBatch();
   102 				formatter.close();
   103 			}
   104 		} else {
   105 			showInfos(commands);
   106 		}
   107 	}
   108 
   109 	private void showInfos(EnumSet<InfoType> commands) throws ConfigurationException, FormatterException {
   110 		for (InfoType infoType : commands) {
   111 			infoType.showInfo(this);
   112 		}
   113 	}
   114 
   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<>();
   123 
   124 		String defaultFormatter = configurationProvider.getConfiguration().getDefaultFormatter();
   125 		defaultFormatter = defaultFormatter == null ? Configuration.DEFAULT_FORMATTER : defaultFormatter;
   126 
   127 		for (FormatterDefinition fd : configurationProvider.getConfiguration().getBuildInFormatters()) {
   128 			data.add(new Object[]{fd.getName(), true, defaultFormatter.equals(fd.getName()), fd.getClassName(), isInstantiable(fd)});
   129 		}
   130 
   131 		for (FormatterDefinition fd : configurationProvider.getConfiguration().getFormatters()) {
   132 			data.add(new Object[]{fd.getName(), false, defaultFormatter.equals(fd.getName()), fd.getClassName(), isInstantiable(fd)});
   133 		}
   134 
   135 		printTable(formatter, header, data, "-- configured and built-in output formatters", null);
   136 	}
   137 
   138 	private boolean isInstantiable(FormatterDefinition fd) {
   139 		try {
   140 			try (ByteArrayOutputStream testStream = new ByteArrayOutputStream()) {
   141 				fd.getInstance(new FormatterContext(testStream, new Properties(0)));
   142 				return true;
   143 			}
   144 		} catch (Exception e) {
   145 			log.log(Level.SEVERE, "Unable to create an instance of formatter: " + fd.getName(), e);
   146 			return false;
   147 		}
   148 	}
   149 
   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()});
   155 		}
   156 		printTable(formatter, header, data, "-- data types", null);
   157 		log.log(Level.INFO, "Type names in --types option are case insensitive");
   158 	}
   159 
   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<>();
   166 
   167 		final List<DatabaseDefinition> configuredDatabases = configurationProvider.getConfiguration().getDatabases();
   168 		if (configuredDatabases.isEmpty()) {
   169 			log.log(Level.WARNING, "No databases are configured.");
   170 		} else {
   171 			for (DatabaseDefinition dd : configuredDatabases) {
   172 				data.add(new Object[]{dd.getName(), dd.getUserName(), dd.getUrl()});
   173 			}
   174 		}
   175 
   176 		printTable(formatter, header, data, "-- configured databases", null);
   177 	}
   178 
   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<>();
   187 
   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(),
   193 				d.getMajorVersion(),
   194 				d.getMinorVersion(),
   195 				d.jdbcCompliant()
   196 			});
   197 		}
   198 
   199 		printTable(formatter, header, data, "-- discovered JDBC drivers (available on the CLASSPATH)", null);
   200 	}
   201 
   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<>();
   211 
   212 			DatabaseDefinition dd = configurationProvider.getConfiguration().getDatabase(dbName);
   213 
   214 			Driver driver = findDriver(dd);
   215 
   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()});
   218 			} else {
   219 				log.log(Level.INFO, "For DB: {0} was found JDBC driver: {1}", new Object[]{dd.getName(), driver.getClass().getName()});
   220 
   221 				try {
   222 					DriverPropertyInfo[] propertyInfos = driver.getPropertyInfo(dd.getUrl(), dd.getProperties().getJavaProperties());
   223 
   224 					Set<String> standardProperties = new HashSet<>();
   225 
   226 					for (DriverPropertyInfo pi : propertyInfos) {
   227 						Array choices = new FakeSqlArray(pi.choices, SQLType.VARCHAR);
   228 						data.add(new Object[]{
   229 							pi.name,
   230 							pi.required,
   231 							choices.getArray() == null ? "" : choices,
   232 							pi.value == null ? "" : pi.value,
   233 							pi.description
   234 						});
   235 						standardProperties.add(pi.name);
   236 					}
   237 
   238 					for (Property p : dd.getProperties()) {
   239 						if (!standardProperties.contains(p.getName())) {
   240 							data.add(new Object[]{
   241 								p.getName(),
   242 								"",
   243 								"",
   244 								p.getValue(),
   245 								""
   246 							});
   247 							log.log(Level.WARNING, "Your configuration contains property „{0}“ not declared by the JDBC driver.", p.getName());
   248 						}
   249 					}
   250 
   251 				} catch (SQLException e) {
   252 					log.log(Level.WARNING, "Error during getting property infos.", e);
   253 				}
   254 
   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));
   260 
   261 				printTable(formatter, header, data, "-- configured and configurable JDBC driver properties", parameters);
   262 			}
   263 		}
   264 
   265 	}
   266 
   267 	private Driver findDriver(DatabaseDefinition dd) {
   268 		final ServiceLoader<Driver> drivers = ServiceLoader.load(Driver.class);
   269 		for (Driver d : drivers) {
   270 			try {
   271 				if (d.acceptsURL(dd.getUrl())) {
   272 					return d;
   273 				}
   274 			} catch (SQLException e) {
   275 				log.log(Level.WARNING, "Error during finding JDBC driver for: " + dd.getName(), e);
   276 			}
   277 		}
   278 		return null;
   279 	}
   280 
   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<>();
   287 
   288 		for (String dbName : options.getDatabaseNamesToTest()) {
   289 			data.add(testConnection(dbName));
   290 		}
   291 
   292 		printTable(formatter, header, data, "-- database configuration and connectivity test", null);
   293 	}
   294 
   295 	public Object[] testConnection(String dbName) {
   296 		log.log(Level.FINE, "Testing connection to database: {0}", dbName);
   297 
   298 		boolean succesfullyConnected = false;
   299 		boolean succesfullyConfigured = false;
   300 
   301 		try {
   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();
   307 			}
   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);
   311 		}
   312 
   313 		return new Object[]{dbName, succesfullyConfigured, succesfullyConnected};
   314 	}
   315 
   316 	public void printResource(String fileName) {
   317 		try (BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream(fileName)))) {
   318 			while (true) {
   319 				String line = reader.readLine();
   320 				if (line == null) {
   321 					break;
   322 				} else {
   323 					println(line);
   324 				}
   325 			}
   326 		} catch (Exception e) {
   327 			log.log(Level.SEVERE, "Unable to print this info. Please see our website for it: " + Constants.WEBSITE, e);
   328 		}
   329 	}
   330 
   331 	private void println(String line) {
   332 		out.println(line);
   333 	}
   334 
   335 	private void printTable(Formatter formatter, ColumnsHeader header, List<Object[]> data, String sql, List<Parameter> parameters) throws ConfigurationException, FormatterException {
   336 		formatter.writeStartStatement();
   337 
   338 		if (sql != null) {
   339 			formatter.writeQuery(sql);
   340 			if (parameters != null) {
   341 				formatter.writeParameters(parameters);
   342 			}
   343 		}
   344 
   345 		formatter.writeStartResultSet(header);
   346 
   347 		for (Object[] row : data) {
   348 			formatter.writeStartRow();
   349 			for (Object cell : row) {
   350 				formatter.writeColumnValue(cell);
   351 			}
   352 			formatter.writeEndRow();
   353 		}
   354 
   355 		formatter.writeEndResultSet();
   356 		formatter.writeEndStatement();
   357 	}
   358 
   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);
   365 	}
   366 
   367 	private ColumnsHeader constructHeader(HeaderField... fields) throws FormatterException {
   368 		try {
   369 			RowSetMetaDataImpl metaData = new RowSetMetaDataImpl();
   370 			metaData.setColumnCount(fields.length);
   371 
   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());
   379 			}
   380 
   381 			return new ColumnsHeader(metaData);
   382 		} catch (SQLException e) {
   383 			throw new FormatterException("Error while constructing table headers", e);
   384 		}
   385 	}
   386 
   387 	private static class HeaderField {
   388 
   389 		String name;
   390 		SQLType type;
   391 
   392 		public HeaderField(String name, SQLType type) {
   393 			this.name = name;
   394 			this.type = type;
   395 		}
   396 	}
   397 
   398 	public enum InfoType {
   399 
   400 		HELP {
   401 			@Override
   402 			public void showInfo(InfoLister infoLister) {
   403 				infoLister.printResource(Constants.HELP_FILE);
   404 			}
   405 		},
   406 		VERSION {
   407 			@Override
   408 			public void showInfo(InfoLister infoLister) {
   409 				infoLister.printResource(Constants.VERSION_FILE);
   410 			}
   411 		},
   412 		LICENSE {
   413 			@Override
   414 			public void showInfo(InfoLister infoLister) {
   415 				infoLister.printResource(Constants.LICENSE_FILE);
   416 			}
   417 		},
   418 		FORMATTERS {
   419 			@Override
   420 			public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
   421 				infoLister.listFormatters();
   422 			}
   423 		},
   424 		TYPES {
   425 			@Override
   426 			public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
   427 				infoLister.listTypes();
   428 			}
   429 		},
   430 		JDBC_DRIVERS {
   431 			@Override
   432 			public void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException {
   433 				infoLister.listJdbcDrivers();
   434 			}
   435 		},
   436 		JDBC_PROPERTIES {
   437 			@Override
   438 			public void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException {
   439 				infoLister.listJdbcProperties();
   440 			}
   441 		},
   442 		DATABASES {
   443 			@Override
   444 			public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
   445 				infoLister.listDatabases();
   446 			}
   447 		},
   448 		CONNECTION {
   449 			@Override
   450 			public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
   451 				infoLister.testConnection();
   452 			}
   453 		};
   454 
   455 		public abstract void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException;
   456 	}
   457 }