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