java/sql-dk/src/info/globalcode/sql/dk/InfoLister.java
author František Kučera <franta-hg@frantovo.cz>
Wed, 15 Jan 2014 18:15:55 +0100
branchv_0
changeset 158 770b5009ec42
parent 155 eb3676c6929b
child 159 9632b23df30c
permissions -rw-r--r--
InfoLister: print list of available JDBC drivers: --list-jdbc-drivers
     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.formatting.ColumnsHeader;
    26 import info.globalcode.sql.dk.formatting.Formatter;
    27 import info.globalcode.sql.dk.formatting.FormatterContext;
    28 import info.globalcode.sql.dk.formatting.FormatterException;
    29 import java.io.BufferedReader;
    30 import java.io.InputStreamReader;
    31 import java.io.PrintStream;
    32 import java.sql.Driver;
    33 import java.sql.SQLException;
    34 import java.util.ArrayList;
    35 import java.util.EnumSet;
    36 import java.util.List;
    37 import java.util.ServiceLoader;
    38 import java.util.logging.Level;
    39 import java.util.logging.Logger;
    40 import javax.sql.rowset.RowSetMetaDataImpl;
    41 
    42 /**
    43  * Displays info like help, version etc.
    44  *
    45  * @author Ing. František Kučera (frantovo.cz)
    46  */
    47 public class InfoLister {
    48 
    49 	private static final Logger log = Logger.getLogger(InfoLister.class.getName());
    50 	private PrintStream out;
    51 	private ConfigurationProvider configurationProvider;
    52 	private CLIOptions options;
    53 	private Formatter formatter;
    54 
    55 	public InfoLister(PrintStream out, ConfigurationProvider configurationProvider, CLIOptions options) {
    56 		this.out = out;
    57 		this.configurationProvider = configurationProvider;
    58 		this.options = options;
    59 	}
    60 
    61 	public void showInfo() throws ConfigurationException, FormatterException {
    62 		EnumSet<InfoType> commands = options.getShowInfo();
    63 
    64 		boolean formattinNeeded = false;
    65 
    66 		for (InfoType infoType : commands) {
    67 			switch (infoType) {
    68 				case CONNECTION:
    69 				case JDBC_DRIVERS:
    70 				case DATABASES:
    71 				case FORMATTERS:
    72 				case TYPES:
    73 					formattinNeeded = true;
    74 					break;
    75 			}
    76 		}
    77 
    78 		if (formattinNeeded) {
    79 			try (Formatter f = getFormatter()) {
    80 				formatter = f;
    81 				formatter.writeStartBatch();
    82 				formatter.writeStartDatabase(new DatabaseDefinition());
    83 				formatter.writeStartStatement();
    84 				showInfos(commands);
    85 				formatter.writeEndStatement();
    86 				formatter.writeEndDatabase();
    87 				formatter.writeEndBatch();
    88 				formatter.close();
    89 			}
    90 		} else {
    91 			showInfos(commands);
    92 		}
    93 	}
    94 
    95 	private void showInfos(EnumSet<InfoType> commands) throws ConfigurationException, FormatterException {
    96 		for (InfoType infoType : commands) {
    97 			infoType.showInfo(this);
    98 		}
    99 	}
   100 
   101 	private void listFormatters() throws ConfigurationException, FormatterException {
   102 		ColumnsHeader header = constructHeader(
   103 				new HeaderField("name", SQLType.VARCHAR),
   104 				new HeaderField("built_in", SQLType.BOOLEAN),
   105 				new HeaderField("default", SQLType.BOOLEAN),
   106 				new HeaderField("class_name", SQLType.VARCHAR));
   107 		List<Object[]> data = new ArrayList<>();
   108 
   109 		String defaultFormatter = configurationProvider.getConfiguration().getDefaultFormatter();
   110 		defaultFormatter = defaultFormatter == null ? Configuration.DEFAULT_FORMATTER : defaultFormatter;
   111 
   112 		for (FormatterDefinition fd : configurationProvider.getConfiguration().getBuildInFormatters()) {
   113 			data.add(new Object[]{fd.getName(), true, defaultFormatter.equals(fd.getName()), fd.getClassName()});
   114 		}
   115 
   116 		for (FormatterDefinition fd : configurationProvider.getConfiguration().getFormatters()) {
   117 			data.add(new Object[]{fd.getName(), false, defaultFormatter.equals(fd.getName()), fd.getClassName()});
   118 		}
   119 
   120 		printTable(formatter, header, data);
   121 
   122 
   123 	}
   124 
   125 	public void listTypes() throws FormatterException, ConfigurationException {
   126 		ColumnsHeader header = constructHeader(new HeaderField("name", SQLType.VARCHAR), new HeaderField("code", SQLType.INTEGER));
   127 		List<Object[]> data = new ArrayList<>();
   128 		for (SQLType sqlType : SQLType.values()) {
   129 			data.add(new Object[]{sqlType.name(), sqlType.getCode()});
   130 		}
   131 		printTable(formatter, header, data);
   132 		log.log(Level.INFO, "Type names in --types option are case insensitive");
   133 	}
   134 
   135 	public void listDatabases() throws ConfigurationException, FormatterException {
   136 		ColumnsHeader header = constructHeader(
   137 				new HeaderField("database_name", SQLType.VARCHAR),
   138 				new HeaderField("user_name", SQLType.VARCHAR),
   139 				new HeaderField("database_url", SQLType.VARCHAR));
   140 		List<Object[]> data = new ArrayList<>();
   141 
   142 		final List<DatabaseDefinition> configuredDatabases = configurationProvider.getConfiguration().getDatabases();
   143 		if (configuredDatabases.isEmpty()) {
   144 			log.log(Level.WARNING, "No databases are configured.");
   145 		} else {
   146 			for (DatabaseDefinition dd : configuredDatabases) {
   147 				data.add(new Object[]{dd.getName(), dd.getUserName(), dd.getUrl()});
   148 			}
   149 		}
   150 
   151 		printTable(formatter, header, data);
   152 	}
   153 
   154 	public void listJdbcDrivers() throws FormatterException, ConfigurationException {
   155 		ColumnsHeader header = constructHeader(
   156 				new HeaderField("class", SQLType.VARCHAR),
   157 				new HeaderField("version", SQLType.VARCHAR),
   158 				new HeaderField("major", SQLType.INTEGER),
   159 				new HeaderField("minor", SQLType.INTEGER),
   160 				new HeaderField("jdbc_compliant", SQLType.BOOLEAN));
   161 		List<Object[]> data = new ArrayList<>();
   162 
   163 		final ServiceLoader<Driver> drivers = ServiceLoader.load(Driver.class);
   164 		for (Driver d : drivers) {
   165 			data.add(new Object[]{
   166 				d.getClass().getName(),
   167 				d.getMajorVersion() + "." + d.getMinorVersion(),
   168 				d.getMajorVersion(),
   169 				d.getMinorVersion(),
   170 				d.jdbcCompliant()});
   171 		}
   172 
   173 		printTable(formatter, header, data);
   174 
   175 	}
   176 
   177 	public void testConnection() throws FormatterException, ConfigurationException {
   178 		ColumnsHeader header = constructHeader(
   179 				new HeaderField("database_name", SQLType.VARCHAR),
   180 				new HeaderField("configured", SQLType.BOOLEAN),
   181 				new HeaderField("connected", SQLType.BOOLEAN));
   182 		List<Object[]> data = new ArrayList<>();
   183 
   184 		for (String dbName : options.getDatabaseNamesToTest()) {
   185 			data.add(testConnection(dbName));
   186 		}
   187 
   188 		printTable(formatter, header, data);
   189 	}
   190 
   191 	public Object[] testConnection(String dbName) {
   192 		log.log(Level.FINE, "Testing connection to database: {0}", dbName);
   193 
   194 		boolean succesfullyConnected = false;
   195 		boolean succesfullyConfigured = false;
   196 
   197 		try {
   198 			DatabaseDefinition dd = configurationProvider.getConfiguration().getDatabase(dbName);
   199 			log.log(Level.FINE, "Database definition was loaded from configuration");
   200 			succesfullyConfigured = true;
   201 			try (DatabaseConnection dc = dd.connect(options.getDatabaseProperties())) {
   202 				succesfullyConnected = dc.test();
   203 			}
   204 			log.log(Level.FINE, "Database connection test was successful");
   205 		} catch (ConfigurationException | SQLException e) {
   206 			log.log(Level.SEVERE, "Error during testing connection", e);
   207 		}
   208 
   209 		return new Object[]{dbName, succesfullyConfigured, succesfullyConnected};
   210 	}
   211 
   212 	public void printResource(String fileName) {
   213 		try (BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream(fileName)))) {
   214 			while (true) {
   215 				String line = reader.readLine();
   216 				if (line == null) {
   217 					break;
   218 				} else {
   219 					println(line);
   220 				}
   221 			}
   222 		} catch (Exception e) {
   223 			log.log(Level.SEVERE, "Unable to print this info. Please see our website for it: " + Constants.WEBSITE, e);
   224 		}
   225 	}
   226 
   227 	private void println(String line) {
   228 		out.println(line);
   229 	}
   230 
   231 	private void printTable(Formatter formatter, ColumnsHeader header, List<Object[]> data) throws ConfigurationException, FormatterException {
   232 		formatter.writeStartResultSet(header);
   233 
   234 		for (Object[] row : data) {
   235 			formatter.writeStartRow();
   236 			for (Object cell : row) {
   237 				formatter.writeColumnValue(cell);
   238 			}
   239 			formatter.writeEndRow();
   240 		}
   241 
   242 		formatter.writeEndResultSet();
   243 	}
   244 
   245 	private Formatter getFormatter() throws ConfigurationException, FormatterException {
   246 		String formatterName = options.getFormatterName();
   247 		formatterName = formatterName == null ? Configuration.DEFAULT_FORMATTER_PREFETCHING : formatterName;
   248 		FormatterDefinition fd = configurationProvider.getConfiguration().getFormatter(formatterName);
   249 		FormatterContext context = new FormatterContext(out, options.getFormatterProperties());
   250 		return fd.getInstance(context);
   251 	}
   252 
   253 	private ColumnsHeader constructHeader(HeaderField... fields) throws FormatterException {
   254 		try {
   255 			RowSetMetaDataImpl metaData = new RowSetMetaDataImpl();
   256 			metaData.setColumnCount(fields.length);
   257 
   258 			for (int i = 0; i < fields.length; i++) {
   259 				HeaderField hf = fields[i];
   260 				int sqlIndex = i + 1;
   261 				metaData.setColumnName(sqlIndex, hf.name);
   262 				metaData.setColumnLabel(sqlIndex, hf.name);
   263 				metaData.setColumnType(sqlIndex, hf.type.getCode());
   264 				metaData.setColumnTypeName(sqlIndex, hf.type.name());
   265 			}
   266 
   267 			return new ColumnsHeader(metaData);
   268 		} catch (SQLException e) {
   269 			throw new FormatterException("Error while constructing table headers", e);
   270 		}
   271 	}
   272 
   273 	private static class HeaderField {
   274 
   275 		String name;
   276 		SQLType type;
   277 
   278 		public HeaderField(String name, SQLType type) {
   279 			this.name = name;
   280 			this.type = type;
   281 		}
   282 	}
   283 
   284 	public enum InfoType {
   285 
   286 		HELP {
   287 			@Override
   288 			public void showInfo(InfoLister infoLister) {
   289 				infoLister.printResource(Constants.HELP_FILE);
   290 			}
   291 		},
   292 		VERSION {
   293 			@Override
   294 			public void showInfo(InfoLister infoLister) {
   295 				infoLister.printResource(Constants.VERSION_FILE);
   296 			}
   297 		},
   298 		LICENSE {
   299 			@Override
   300 			public void showInfo(InfoLister infoLister) {
   301 				infoLister.printResource(Constants.LICENSE_FILE);
   302 			}
   303 		},
   304 		FORMATTERS {
   305 			@Override
   306 			public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
   307 				infoLister.listFormatters();
   308 			}
   309 		},
   310 		TYPES {
   311 			@Override
   312 			public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
   313 				infoLister.listTypes();
   314 			}
   315 		},
   316 		JDBC_DRIVERS {
   317 			@Override
   318 			public void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException {
   319 				infoLister.listJdbcDrivers();
   320 			}
   321 		},
   322 		DATABASES {
   323 			@Override
   324 			public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
   325 				infoLister.listDatabases();
   326 			}
   327 		},
   328 		CONNECTION {
   329 			@Override
   330 			public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
   331 				infoLister.testConnection();
   332 			}
   333 		};
   334 
   335 		public abstract void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException;
   336 	}
   337 }