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