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