java/sql-dk/src/info/globalcode/sql/dk/InfoLister.java
author František Kučera <franta-hg@frantovo.cz>
Fri, 27 Dec 2013 17:51:05 +0100
branchv_0
changeset 81 847c83288d01
parent 75 43aa4625ab7e
child 89 98d18e9a357b
permissions -rw-r--r--
bash completion: perl + bash + ant for generating completion script
     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 		FormatterDefinition fd = configurationProvider.getConfiguration().getFormatter(options.getFormatterName());
   206 		FormatterContext context = new FormatterContext(out);
   207 		return fd.getInstance(context);
   208 	}
   209 
   210 	private ColumnsHeader constructHeader(HeaderField... fields) throws FormatterException {
   211 		try {
   212 			RowSetMetaDataImpl metaData = new RowSetMetaDataImpl();
   213 			metaData.setColumnCount(fields.length);
   214 
   215 			for (int i = 0; i < fields.length; i++) {
   216 				HeaderField hf = fields[i];
   217 				int sqlIndex = i + 1;
   218 				metaData.setColumnName(sqlIndex, hf.name);
   219 				metaData.setColumnLabel(sqlIndex, hf.name);
   220 				metaData.setColumnType(sqlIndex, hf.type.getCode());
   221 				metaData.setColumnTypeName(sqlIndex, hf.type.name());
   222 			}
   223 
   224 			return new ColumnsHeader(metaData);
   225 		} catch (SQLException e) {
   226 			throw new FormatterException("Error while constructing table headers", e);
   227 		}
   228 	}
   229 
   230 	private static class HeaderField {
   231 
   232 		String name;
   233 		SQLType type;
   234 
   235 		public HeaderField(String name, SQLType type) {
   236 			this.name = name;
   237 			this.type = type;
   238 		}
   239 	}
   240 
   241 	public enum InfoType {
   242 
   243 		HELP {
   244 			@Override
   245 			public void showInfo(InfoLister infoLister) {
   246 				infoLister.printResource(Constants.HELP_FILE);
   247 			}
   248 		},
   249 		VERSION {
   250 			@Override
   251 			public void showInfo(InfoLister infoLister) {
   252 				infoLister.printResource(Constants.VERSION_FILE);
   253 			}
   254 		},
   255 		LICENSE {
   256 			@Override
   257 			public void showInfo(InfoLister infoLister) {
   258 				infoLister.printResource(Constants.LICENSE_FILE);
   259 			}
   260 		},
   261 		FORMATTERS {
   262 			@Override
   263 			public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
   264 				infoLister.listFormatters();
   265 			}
   266 		},
   267 		TYPES {
   268 			@Override
   269 			public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
   270 				infoLister.listTypes();
   271 			}
   272 		},
   273 		DATABASES {
   274 			@Override
   275 			public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
   276 				infoLister.listDatabases();
   277 			}
   278 		},
   279 		CONNECTION {
   280 			@Override
   281 			public void showInfo(InfoLister infoLister) throws FormatterException, ConfigurationException {
   282 				infoLister.testConnection();
   283 			}
   284 		};
   285 
   286 		public abstract void showInfo(InfoLister infoLister) throws ConfigurationException, FormatterException;
   287 	}
   288 }