java/sql-dk/src/info/globalcode/sql/dk/InfoLister.java
author František Kučera <franta-hg@frantovo.cz>
Thu, 26 Dec 2013 21:18:54 +0100
branchv_0
changeset 69 0befec5034c2
parent 67 10c9b9e54622
child 70 02c8eaa425e8
permissions -rw-r--r--
InfoLister, InfoType: switch → enum
     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 static info.globalcode.sql.dk.Functions.rpad;
    26 import info.globalcode.sql.dk.formatting.ColumnsHeader;
    27 import info.globalcode.sql.dk.formatting.Formatter;
    28 import info.globalcode.sql.dk.formatting.FormatterContext;
    29 import info.globalcode.sql.dk.formatting.FormatterException;
    30 import java.io.BufferedReader;
    31 import java.io.InputStreamReader;
    32 import java.io.PrintStream;
    33 import java.sql.SQLException;
    34 import java.util.List;
    35 import java.util.logging.Level;
    36 import java.util.logging.Logger;
    37 import javax.sql.rowset.RowSetMetaDataImpl;
    38 
    39 /**
    40  * Displays info like help, version etc.
    41  *
    42  * @author Ing. František Kučera (frantovo.cz)
    43  */
    44 public class InfoLister {
    45 
    46 	private static final Logger log = Logger.getLogger(InfoLister.class.getName());
    47 	private PrintStream out;
    48 	private ConfigurationProvider configurationProvider;
    49 	private CLIOptions options;
    50 
    51 	public InfoLister(PrintStream out, ConfigurationProvider configurationProvider, CLIOptions options) {
    52 		this.out = out;
    53 		this.configurationProvider = configurationProvider;
    54 		this.options = options;
    55 	}
    56 
    57 	public void listFormatters() throws ConfigurationException {
    58 		for (FormatterDefinition fd : configurationProvider.getConfiguration().getBuildInFormatters()) {
    59 			log.log(Level.INFO, "Built-in formatter:   {0} implemented by class: {1}", new Object[]{rpad(fd.getName(), 16), fd.getClassName()});
    60 		}
    61 		List<FormatterDefinition> configuredFormatters = configurationProvider.getConfiguration().getFormatters();
    62 		for (FormatterDefinition fd : configuredFormatters) {
    63 			log.log(Level.INFO, "Configured formatter: {0} implemented by class: {1}", new Object[]{rpad(fd.getName(), 16), fd.getClassName()});
    64 		}
    65 		if (configuredFormatters.isEmpty()) {
    66 			log.log(Level.INFO, "No other formatters are configured");
    67 		}
    68 		String configuredDefaultFormatter = configurationProvider.getConfiguration().getDefaultFormatter();
    69 		if (configuredDefaultFormatter == null) {
    70 			log.log(Level.INFO, "Built-in default formatter: {0}", Configuration.DEFAULT_FORMATTER);
    71 		} else {
    72 			log.log(Level.INFO, "Configured default formatter: {0}", configuredDefaultFormatter);
    73 		}
    74 	}
    75 
    76 	public void listTypes() throws FormatterException {
    77 	}
    78 
    79 	public void listDatabases() throws ConfigurationException {
    80 		final List<DatabaseDefinition> configuredDatabases = configurationProvider.getConfiguration().getDatabases();
    81 		if (configuredDatabases.isEmpty()) {
    82 			log.log(Level.WARNING, "No databases are configured.");
    83 		} else {
    84 			for (DatabaseDefinition dd : configuredDatabases) {
    85 				log.log(Level.INFO, "Configured database: {0}", dd.getName());
    86 			}
    87 		}
    88 	}
    89 
    90 	public void testConnection() {
    91 		boolean connectionTestResult = false;
    92 		String dbName = options.getDatabaseNameToTest();
    93 		log.log(Level.FINE, "Testing connection to database: {0}", dbName);
    94 		try {
    95 			DatabaseDefinition dd = configurationProvider.getConfiguration().getDatabase(dbName);
    96 			if (dd == null) {
    97 				log.log(Level.SEVERE, "No database with this name is configured: {0}", dbName);
    98 			} else {
    99 				log.log(Level.FINE, "Database definition was loaded from configuration");
   100 				DatabaseConnection dc = dd.connect();
   101 				connectionTestResult = dc.test();
   102 			}
   103 		} catch (ConfigurationException | SQLException e) {
   104 			log.log(Level.SEVERE, "Error during testing connection", e);
   105 		}
   106 		log.log(Level.INFO, "Connection test result: {0}", connectionTestResult ? "success" : "failure");
   107 	}
   108 
   109 	public void printResource(String fileName) {
   110 		try (BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream(fileName)))) {
   111 			while (true) {
   112 				String line = reader.readLine();
   113 				if (line == null) {
   114 					break;
   115 				} else {
   116 					println(line);
   117 				}
   118 			}
   119 		} catch (Exception e) {
   120 			log.log(Level.SEVERE, "Unable to print this info. Please see our website for it: " + Constants.WEBSITE, e);
   121 		}
   122 	}
   123 
   124 	private void println(String line) {
   125 		out.println(line);
   126 	}
   127 
   128 	private void printTable(Formatter formatter, ColumnsHeader header, List<Object[]> data) throws ConfigurationException, FormatterException {
   129 		formatter.writeStartResultSet();
   130 		formatter.writeColumnsHeader(header);
   131 
   132 		for (Object[] row : data) {
   133 			formatter.writeStartRow();
   134 			for (Object cell : row) {
   135 				formatter.writeColumnValue(cell);
   136 			}
   137 			formatter.writeEndRow();
   138 		}
   139 
   140 		formatter.writeEndResultSet();
   141 	}
   142 
   143 	private Formatter getFormatter() throws ConfigurationException, FormatterException {
   144 		FormatterDefinition fd = configurationProvider.getConfiguration().getFormatter(options.getFormatterName());
   145 		FormatterContext context = new FormatterContext(out);
   146 		return fd.getInstance(context);
   147 	}
   148 
   149 	private ColumnsHeader constructHeader(HeaderField... fields) throws FormatterException {
   150 		try {
   151 			RowSetMetaDataImpl metaData = new RowSetMetaDataImpl();
   152 			metaData.setColumnCount(fields.length);
   153 
   154 			for (int i = 0; i < fields.length; i++) {
   155 				HeaderField hf = fields[i];
   156 				int sqlIndex = i + 1;
   157 				metaData.setColumnName(sqlIndex, hf.name);
   158 				metaData.setColumnLabel(sqlIndex, hf.name);
   159 				metaData.setColumnType(sqlIndex, hf.type.getCode());
   160 				metaData.setColumnTypeName(sqlIndex, hf.type.name());
   161 			}
   162 
   163 			return new ColumnsHeader(metaData);
   164 		} catch (SQLException e) {
   165 			throw new FormatterException("Error while constructing table headers", e);
   166 		}
   167 	}
   168 
   169 	private static class HeaderField {
   170 
   171 		String name;
   172 		SQLType type;
   173 
   174 		public HeaderField(String name, SQLType type) {
   175 			this.name = name;
   176 			this.type = type;
   177 		}
   178 	}
   179 
   180 	public enum InfoType {
   181 
   182 		HELP {
   183 			@Override
   184 			public void showInfo(InfoLister infoLister) {
   185 				infoLister.printResource(Constants.HELP_FILE);
   186 			}
   187 		},
   188 		VERSION {
   189 			@Override
   190 			public void showInfo(InfoLister infoLister) {
   191 				infoLister.printResource(Constants.VERSION_FILE);
   192 			}
   193 		},
   194 		LICENSE {
   195 			@Override
   196 			public void showInfo(InfoLister infoLister) {
   197 				infoLister.printResource(Constants.LICENSE_FILE);
   198 			}
   199 		},
   200 		FORMATTERS {
   201 			@Override
   202 			public void showInfo(InfoLister infoLister) throws ConfigurationException {
   203 				infoLister.listFormatters();
   204 			}
   205 		},
   206 		TYPES {
   207 			@Override
   208 			public void showInfo(InfoLister infoLister) throws FormatterException {
   209 				infoLister.listTypes();
   210 			}
   211 		},
   212 		DATABASES {
   213 			@Override
   214 			public void showInfo(InfoLister infoLister) throws ConfigurationException {
   215 				infoLister.listDatabases();
   216 			}
   217 		},
   218 		CONNECTION {
   219 			@Override
   220 			public void showInfo(InfoLister infoLister) {
   221 				infoLister.testConnection();
   222 			}
   223 		};
   224 
   225 		public abstract void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException;
   226 	}
   227 }