java/sql-dk/src/info/globalcode/sql/dk/InfoLister.java
author František Kučera <franta-hg@frantovo.cz>
Thu, 26 Dec 2013 22:32:06 +0100
branchv_0
changeset 73 d32fd50d3c2c
parent 72 fc9fc1f26b88
child 74 a8444f6a54f3
permissions -rw-r--r--
formatted output for: --test-connection
     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 needs 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.VARCHAR),
   139 				new HeaderField("connected", SQLType.VARCHAR));
   140 		List<Object[]> data = new ArrayList<>();
   141 
   142 		/** TODO: support multiple DB to test */
   143 		String dbName = options.getDatabaseNameToTest();
   144 
   145 		data.add(testConnection(dbName));
   146 
   147 		printTable(formatter, header, data);
   148 	}
   149 
   150 	public Object[] testConnection(String dbName) {
   151 		log.log(Level.FINE, "Testing connection to database: {0}", dbName);
   152 
   153 		boolean succesfullyConnected = false;
   154 		boolean succesfullyConfigured = false;
   155 
   156 		try {
   157 			DatabaseDefinition dd = configurationProvider.getConfiguration().getDatabase(dbName);
   158 			if (dd == null) {
   159 				log.log(Level.FINE, "No database with this name is configured: {0}", dbName);
   160 			} else {
   161 				log.log(Level.FINE, "Database definition was loaded from configuration");
   162 				succesfullyConfigured = true;
   163 				try (DatabaseConnection dc = dd.connect()) {
   164 					succesfullyConnected = dc.test();
   165 				}
   166 				log.log(Level.FINE, "Database connection test was successful");
   167 			}
   168 		} catch (ConfigurationException | SQLException e) {
   169 			log.log(Level.SEVERE, "Error during testing connection", e);
   170 		}
   171 
   172 		return new Object[]{dbName, succesfullyConfigured, succesfullyConnected};
   173 	}
   174 
   175 	public void printResource(String fileName) {
   176 		try (BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream(fileName)))) {
   177 			while (true) {
   178 				String line = reader.readLine();
   179 				if (line == null) {
   180 					break;
   181 				} else {
   182 					println(line);
   183 				}
   184 			}
   185 		} catch (Exception e) {
   186 			log.log(Level.SEVERE, "Unable to print this info. Please see our website for it: " + Constants.WEBSITE, e);
   187 		}
   188 	}
   189 
   190 	private void println(String line) {
   191 		out.println(line);
   192 	}
   193 
   194 	private void printTable(Formatter formatter, ColumnsHeader header, List<Object[]> data) throws ConfigurationException, FormatterException {
   195 		formatter.writeStartResultSet();
   196 		formatter.writeColumnsHeader(header);
   197 
   198 		for (Object[] row : data) {
   199 			formatter.writeStartRow();
   200 			for (Object cell : row) {
   201 				formatter.writeColumnValue(cell);
   202 			}
   203 			formatter.writeEndRow();
   204 		}
   205 
   206 		formatter.writeEndResultSet();
   207 	}
   208 
   209 	private Formatter getFormatter() throws ConfigurationException, FormatterException {
   210 		FormatterDefinition fd = configurationProvider.getConfiguration().getFormatter(options.getFormatterName());
   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 }