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