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