java/sql-dk/src/main/java/info/globalcode/sql/dk/CLIStarter.java
branchv_0
changeset 238 4a1864c3e867
parent 221 e38910065d55
child 246 277c18b48762
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/java/sql-dk/src/main/java/info/globalcode/sql/dk/CLIStarter.java	Mon Mar 04 20:15:24 2019 +0100
     1.3 @@ -0,0 +1,274 @@
     1.4 +/**
     1.5 + * SQL-DK
     1.6 + * Copyright © 2013 František Kučera (frantovo.cz)
     1.7 + *
     1.8 + * This program is free software: you can redistribute it and/or modify
     1.9 + * it under the terms of the GNU General Public License as published by
    1.10 + * the Free Software Foundation, either version 3 of the License, or
    1.11 + * (at your option) any later version.
    1.12 + *
    1.13 + * This program is distributed in the hope that it will be useful,
    1.14 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
    1.15 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    1.16 + * GNU General Public License for more details.
    1.17 + *
    1.18 + * You should have received a copy of the GNU General Public License
    1.19 + * along with this program. If not, see <http://www.gnu.org/licenses/>.
    1.20 + */
    1.21 +package info.globalcode.sql.dk;
    1.22 +
    1.23 +import info.globalcode.sql.dk.configuration.ConfigurationProvider;
    1.24 +import info.globalcode.sql.dk.CLIOptions.MODE;
    1.25 +import info.globalcode.sql.dk.batch.Batch;
    1.26 +import info.globalcode.sql.dk.batch.BatchDecoder;
    1.27 +import info.globalcode.sql.dk.batch.BatchException;
    1.28 +import info.globalcode.sql.dk.batch.BatchEncoder;
    1.29 +import info.globalcode.sql.dk.configuration.Configuration;
    1.30 +import info.globalcode.sql.dk.configuration.ConfigurationException;
    1.31 +import info.globalcode.sql.dk.configuration.DatabaseDefinition;
    1.32 +import info.globalcode.sql.dk.configuration.FormatterDefinition;
    1.33 +import info.globalcode.sql.dk.configuration.Loader;
    1.34 +import info.globalcode.sql.dk.configuration.NameIdentified;
    1.35 +import info.globalcode.sql.dk.configuration.PropertyDeclaration;
    1.36 +import info.globalcode.sql.dk.formatting.Formatter;
    1.37 +import info.globalcode.sql.dk.formatting.FormatterContext;
    1.38 +import info.globalcode.sql.dk.formatting.FormatterException;
    1.39 +import info.globalcode.sql.dk.jmx.ConnectionManagement;
    1.40 +import info.globalcode.sql.dk.jmx.ManagementUtils;
    1.41 +import java.io.File;
    1.42 +import java.io.FileNotFoundException;
    1.43 +import java.io.IOException;
    1.44 +import java.io.PrintStream;
    1.45 +import java.io.PrintWriter;
    1.46 +import java.sql.SQLException;
    1.47 +import java.util.Collection;
    1.48 +import java.util.Collections;
    1.49 +import java.util.List;
    1.50 +import java.util.logging.Level;
    1.51 +import java.util.logging.LogRecord;
    1.52 +import java.util.logging.Logger;
    1.53 +
    1.54 +/**
    1.55 + * Entry point of the command line interface of SQL-DK.
    1.56 + *
    1.57 + * @author Ing. František Kučera (frantovo.cz)
    1.58 + */
    1.59 +public class CLIStarter implements ConfigurationProvider {
    1.60 +
    1.61 +	// help:exit-codes
    1.62 +	public static final int EXIT_SUCCESS = 0; // doc:success
    1.63 +	public static final int EXIT_UNEXPECTED_ERROR = 1; // doc:unexpected error (probably bug)
    1.64 +	// 2 is reserved: http://www.tldp.org/LDP/abs/html/exitcodes.html#EXITCODESREF
    1.65 +	public static final int EXIT_SQL_ERROR = 3; // doc:SQL error
    1.66 +	public static final int EXIT_CLI_PARSE_ERROR = 4; // doc:CLI options parse error
    1.67 +	public static final int EXIT_CLI_VALIDATE_ERROR = 5; // doc:CLI options validation error
    1.68 +	public static final int EXIT_CONFIGURATION_ERROR = 6; // doc:configuration error
    1.69 +	public static final int EXIT_FORMATTING_ERROR = 7; // doc:formatting error
    1.70 +	public static final int EXIT_BATCH_ERROR = 8; // doc:batch error
    1.71 +	private static final Logger log = Logger.getLogger(CLIStarter.class.getName());
    1.72 +	private final CLIOptions options;
    1.73 +	private final Loader configurationLoader = new Loader();
    1.74 +	private Configuration configuration;
    1.75 +
    1.76 +	public static void main(String[] args) {
    1.77 +		log.log(Level.FINE, "Starting " + Constants.PROGRAM_NAME);
    1.78 +		int exitCode;
    1.79 +
    1.80 +		if (args.length == 0) {
    1.81 +			args = new String[]{CLIParser.Tokens.INFO_HELP};
    1.82 +		}
    1.83 +
    1.84 +		try {
    1.85 +			CLIParser parser = new CLIParser();
    1.86 +			CLIOptions options = parser.parseOptions(args, System.in);
    1.87 +			options.validate();
    1.88 +			CLIStarter starter = new CLIStarter(options);
    1.89 +			starter.installDefaultConfiguration();
    1.90 +			starter.process();
    1.91 +			log.log(Level.FINE, "All done");
    1.92 +			exitCode = EXIT_SUCCESS;
    1.93 +		} catch (CLIParserException e) {
    1.94 +			log.log(Level.SEVERE, "Unable to parse CLI options", e);
    1.95 +			exitCode = EXIT_CLI_PARSE_ERROR;
    1.96 +		} catch (InvalidOptionsException e) {
    1.97 +			log.log(Level.SEVERE, "Invalid CLI options", e);
    1.98 +			for (InvalidOptionsException.OptionProblem p : e.getProblems()) {
    1.99 +				LogRecord r = new LogRecord(Level.SEVERE, "Option problem: {0}");
   1.100 +				r.setThrown(p.getException());
   1.101 +				r.setParameters(new Object[]{p.getDescription()});
   1.102 +				log.log(r);
   1.103 +			}
   1.104 +			exitCode = EXIT_CLI_VALIDATE_ERROR;
   1.105 +		} catch (ConfigurationException e) {
   1.106 +			log.log(Level.SEVERE, "Configuration problem", e);
   1.107 +			exitCode = EXIT_CONFIGURATION_ERROR;
   1.108 +		} catch (SQLException e) {
   1.109 +			log.log(Level.SEVERE, "SQL problem", e);
   1.110 +			exitCode = EXIT_SQL_ERROR;
   1.111 +		} catch (FormatterException e) {
   1.112 +			log.log(Level.SEVERE, "Formatting problem", e);
   1.113 +			exitCode = EXIT_FORMATTING_ERROR;
   1.114 +		} catch (BatchException e) {
   1.115 +			log.log(Level.SEVERE, "Batch problem", e);
   1.116 +			exitCode = EXIT_BATCH_ERROR;
   1.117 +		}
   1.118 +
   1.119 +		System.exit(exitCode);
   1.120 +	}
   1.121 +
   1.122 +	public CLIStarter(CLIOptions options) {
   1.123 +		this.options = options;
   1.124 +	}
   1.125 +
   1.126 +	private void process() throws ConfigurationException, SQLException, FormatterException, BatchException {
   1.127 +		MODE mode = options.getMode();
   1.128 +
   1.129 +		/** Show info */
   1.130 +		if (!options.getShowInfo().isEmpty()) {
   1.131 +			PrintStream infoOut = mode == MODE.JUST_SHOW_INFO ? System.out : System.err;
   1.132 +			InfoLister infoLister = new InfoLister(infoOut, this, options);
   1.133 +			infoLister.showInfo();
   1.134 +		}
   1.135 +
   1.136 +		switch (mode) {
   1.137 +			case QUERY_NOW:
   1.138 +				processQueryNow();
   1.139 +				break;
   1.140 +			case PREPARE_BATCH:
   1.141 +				processPrepareBatch();
   1.142 +				break;
   1.143 +			case EXECUTE_BATCH:
   1.144 +				processExecuteBatch();
   1.145 +				break;
   1.146 +			case JUST_SHOW_INFO:
   1.147 +				// already done above
   1.148 +				break;
   1.149 +			default:
   1.150 +				log.log(Level.SEVERE, "Unsupported mode: {0}", mode);
   1.151 +				break;
   1.152 +		}
   1.153 +
   1.154 +		generateBashCompletion();
   1.155 +	}
   1.156 +
   1.157 +	private void processQueryNow() throws ConfigurationException, SQLException, FormatterException {
   1.158 +		DatabaseDefinition dd = getConfiguration().getDatabase(options.getDatabaseName());
   1.159 +		FormatterDefinition fd = configuration.getFormatter(options.getFormatterName());
   1.160 +		ConnectionManagement jmxBean = ManagementUtils.registerMBean(dd.getName());
   1.161 +
   1.162 +		try (DatabaseConnection c = dd.connect(options.getDatabaseProperties(), jmxBean)) {
   1.163 +			log.log(Level.FINE, "Database connected");
   1.164 +			try (Formatter f = fd.getInstance(new FormatterContext(options.getOutputStream(), options.getFormatterProperties()))) {
   1.165 +				c.executeQuery(options.getSQLCommand(), f);
   1.166 +			}
   1.167 +		}
   1.168 +	}
   1.169 +
   1.170 +	private void processPrepareBatch() throws BatchException {
   1.171 +		BatchEncoder enc = new BatchEncoder();
   1.172 +		int length = enc.encode(options.getSQLCommand(), options.getOutputStream());
   1.173 +		log.log(Level.FINE, "Prepared batch size: {0} bytes", length);
   1.174 +	}
   1.175 +
   1.176 +	private void processExecuteBatch() throws ConfigurationException, SQLException, FormatterException, BatchException {
   1.177 +		BatchDecoder dec = new BatchDecoder();
   1.178 +		Batch b = dec.decode(options.getInputStream());
   1.179 +
   1.180 +		DatabaseDefinition dd = getConfiguration().getDatabase(options.getDatabaseName());
   1.181 +		FormatterDefinition fd = configuration.getFormatter(options.getFormatterName());
   1.182 +		ConnectionManagement jmxBean = ManagementUtils.registerMBean(dd.getName());
   1.183 +
   1.184 +		try (DatabaseConnection c = dd.connect(options.getDatabaseProperties(), jmxBean)) {
   1.185 +			log.log(Level.FINE, "Database connected");
   1.186 +			try (Formatter f = fd.getInstance(new FormatterContext(options.getOutputStream(), options.getFormatterProperties()))) {
   1.187 +				c.executeBatch(b, f);
   1.188 +			}
   1.189 +		}
   1.190 +	}
   1.191 +
   1.192 +	@Override
   1.193 +	public Configuration getConfiguration() throws ConfigurationException {
   1.194 +		if (configuration == null) {
   1.195 +			configuration = configurationLoader.loadConfiguration();
   1.196 +		}
   1.197 +		return configuration;
   1.198 +	}
   1.199 +
   1.200 +	private void installDefaultConfiguration() throws ConfigurationException {
   1.201 +		Constants.DIR.mkdir();
   1.202 +
   1.203 +		if (Constants.CONFIG_FILE.exists()) {
   1.204 +			log.log(Level.FINER, "Config file already exists: {0}", Constants.CONFIG_FILE);
   1.205 +		} else {
   1.206 +			try {
   1.207 +				Functions.installResource(Constants.EXAMPLE_CONFIG_FILE, Constants.CONFIG_FILE);
   1.208 +				log.log(Level.FINE, "Installing default config file: {0}", Constants.CONFIG_FILE);
   1.209 +			} catch (IOException e) {
   1.210 +				throw new ConfigurationException("Unable to write example configuration to " + Constants.CONFIG_FILE, e);
   1.211 +			}
   1.212 +		}
   1.213 +	}
   1.214 +
   1.215 +	private void generateBashCompletion() {
   1.216 +		if (configuration == null) {
   1.217 +			log.log(Level.FINER, "Not writing Bash completion helper files. In order to generate these files please run some command which requires configuration.");
   1.218 +		} else {
   1.219 +			try {
   1.220 +				File dir = new File(Constants.DIR, "bash-completion");
   1.221 +				dir.mkdir();
   1.222 +				writeBashCompletionHelperFile(configuration.getDatabases(), new File(dir, "databases"));
   1.223 +				writeBashCompletionHelperFile(configuration.getAllFormatters(), new File(dir, "formatters"));
   1.224 +				writeBashCompletionHelperFileForFormatterProperties(new File(dir, "formatter-properties"));
   1.225 +			} catch (Exception e) {
   1.226 +				log.log(Level.WARNING, "Unable to generate Bash completion helper files", e);
   1.227 +			}
   1.228 +		}
   1.229 +	}
   1.230 +
   1.231 +	private void writeBashCompletionHelperFile(Collection<? extends NameIdentified> items, File target) throws FileNotFoundException {
   1.232 +		if (Constants.CONFIG_FILE.lastModified() > target.lastModified()) {
   1.233 +			try (PrintWriter fw = new PrintWriter(target)) {
   1.234 +				for (NameIdentified dd : items) {
   1.235 +					fw.println(dd.getName());
   1.236 +				}
   1.237 +				fw.close();
   1.238 +				log.log(Level.FINE, "Bash completion helper file was written: {0}", target);
   1.239 +			}
   1.240 +		} else {
   1.241 +			log.log(Level.FINER, "Not writing Bash completion helper file: {0} because configuration {1} has not been changed", new Object[]{target, Constants.CONFIG_FILE});
   1.242 +		}
   1.243 +	}
   1.244 +
   1.245 +	private void writeBashCompletionHelperFileForFormatterProperties(File formattersDir) throws ClassNotFoundException, FileNotFoundException {
   1.246 +		if (Constants.CONFIG_FILE.lastModified() > formattersDir.lastModified()) {
   1.247 +			// TODO: delete old directory
   1.248 +			formattersDir.mkdir();
   1.249 +			for (FormatterDefinition fd : configuration.getAllFormatters()) {
   1.250 +				File formatterDir = new File(formattersDir, fd.getName());
   1.251 +				formatterDir.mkdir();
   1.252 +
   1.253 +				Class<Formatter> formatterClass = (Class<Formatter>) Class.forName(fd.getClassName());
   1.254 +				List<Class<? extends Formatter>> hierarchy = Functions.getClassHierarchy(formatterClass, Formatter.class);
   1.255 +				Collections.reverse(hierarchy);
   1.256 +				for (Class<? extends Formatter> c : hierarchy) {
   1.257 +					for (PropertyDeclaration p : Functions.getPropertyDeclarations(c)) {
   1.258 +						File propertyDir = new File(formatterDir, p.name());
   1.259 +						propertyDir.mkdir();
   1.260 +						File choicesFile = new File(propertyDir, "choices");
   1.261 +						try (PrintWriter fw = new PrintWriter(choicesFile)) {
   1.262 +							// TODO: refactor, move
   1.263 +							if (p.type() == Boolean.class) {
   1.264 +								fw.println("true");
   1.265 +								fw.println("false");
   1.266 +							}
   1.267 +						}
   1.268 +					}
   1.269 +				}
   1.270 +			}
   1.271 +			log.log(Level.FINE, "Bash completion helper files was written in: {0}", formattersDir);
   1.272 +		} else {
   1.273 +			log.log(Level.FINER, "Not writing Bash completion helper directory: {0} because configuration {1} has not been changed", new Object[]{formattersDir, Constants.CONFIG_FILE});
   1.274 +		}
   1.275 +
   1.276 +	}
   1.277 +}