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