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