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