java/sql-dk/src/info/globalcode/sql/dk/CLIStarter.java
author František Kučera <franta-hg@frantovo.cz>
Thu, 25 Sep 2014 17:50:40 +0200
branchv_0
changeset 179 236332caeb29
parent 166 5488c2dcf680
child 189 f4d879cbcee1
permissions -rw-r--r--
Basic JMX management/reporting – counters for commands and records
     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.ConfigurationProvider;
    21 import info.globalcode.sql.dk.CLIOptions.MODE;
    22 import info.globalcode.sql.dk.batch.Batch;
    23 import info.globalcode.sql.dk.batch.BatchDecoder;
    24 import info.globalcode.sql.dk.batch.BatchException;
    25 import info.globalcode.sql.dk.batch.BatchEncoder;
    26 import info.globalcode.sql.dk.configuration.Configuration;
    27 import info.globalcode.sql.dk.configuration.ConfigurationException;
    28 import info.globalcode.sql.dk.configuration.DatabaseDefinition;
    29 import info.globalcode.sql.dk.configuration.FormatterDefinition;
    30 import info.globalcode.sql.dk.configuration.NameIdentified;
    31 import info.globalcode.sql.dk.formatting.Formatter;
    32 import info.globalcode.sql.dk.formatting.FormatterContext;
    33 import info.globalcode.sql.dk.formatting.FormatterException;
    34 import info.globalcode.sql.dk.jmx.ConnectionManagement;
    35 import info.globalcode.sql.dk.jmx.ManagementUtils;
    36 import java.io.File;
    37 import java.io.FileNotFoundException;
    38 import java.io.IOException;
    39 import java.io.PrintStream;
    40 import java.io.PrintWriter;
    41 import java.sql.SQLException;
    42 import java.util.Collection;
    43 import java.util.logging.Level;
    44 import java.util.logging.LogRecord;
    45 import java.util.logging.Logger;
    46 import javax.xml.bind.JAXBContext;
    47 import javax.xml.bind.Unmarshaller;
    48 
    49 /**
    50  * Entry point of the command line interface of SQL-DK.
    51  *
    52  * @author Ing. František Kučera (frantovo.cz)
    53  */
    54 public class CLIStarter implements ConfigurationProvider {
    55 
    56 	// help:exit-codes
    57 	public static final int EXIT_SUCCESS = 0; // doc:success
    58 	public static final int EXIT_UNEXPECTED_ERROR = 1; // doc:unexpected error (probably bug)
    59 	// 2 is reserved: http://www.tldp.org/LDP/abs/html/exitcodes.html#EXITCODESREF
    60 	public static final int EXIT_SQL_ERROR = 3; // doc:SQL error
    61 	public static final int EXIT_CLI_PARSE_ERROR = 4; // doc:CLI options parse error
    62 	public static final int EXIT_CLI_VALIDATE_ERROR = 5; // doc:CLI options validation error
    63 	public static final int EXIT_CONFIGURATION_ERROR = 6; // doc:configuration error
    64 	public static final int EXIT_FORMATTING_ERROR = 7; // doc:formatting error
    65 	public static final int EXIT_BATCH_ERROR = 8; // doc:batch error
    66 	private static final Logger log = Logger.getLogger(CLIStarter.class.getName());
    67 	private CLIOptions options;
    68 	private Configuration configuration;
    69 
    70 	public static void main(String[] args) {
    71 		log.log(Level.FINE, "Starting " + Constants.PROGRAM_NAME);
    72 		int exitCode;
    73 
    74 		if (args.length == 0) {
    75 			args = new String[]{CLIParser.Tokens.INFO_HELP};
    76 		}
    77 
    78 		try {
    79 			CLIParser parser = new CLIParser();
    80 			CLIOptions options = parser.parseOptions(args, System.in);
    81 			options.validate();
    82 			CLIStarter starter = new CLIStarter(options);
    83 			starter.installDefaultConfiguration();
    84 			starter.process();
    85 			log.log(Level.FINE, "All done");
    86 			exitCode = EXIT_SUCCESS;
    87 		} catch (CLIParserException e) {
    88 			log.log(Level.SEVERE, "Unable to parse CLI options", e);
    89 			exitCode = EXIT_CLI_PARSE_ERROR;
    90 		} catch (InvalidOptionsException e) {
    91 			log.log(Level.SEVERE, "Invalid CLI options", e);
    92 			for (InvalidOptionsException.OptionProblem p : e.getProblems()) {
    93 				LogRecord r = new LogRecord(Level.SEVERE, "Option problem: {0}");
    94 				r.setThrown(p.getException());
    95 				r.setParameters(new Object[]{p.getDescription()});
    96 				log.log(r);
    97 			}
    98 			exitCode = EXIT_CLI_VALIDATE_ERROR;
    99 		} catch (ConfigurationException e) {
   100 			log.log(Level.SEVERE, "Configuration problem", e);
   101 			exitCode = EXIT_CONFIGURATION_ERROR;
   102 		} catch (SQLException e) {
   103 			log.log(Level.SEVERE, "SQL problem", e);
   104 			exitCode = EXIT_SQL_ERROR;
   105 		} catch (FormatterException e) {
   106 			log.log(Level.SEVERE, "Formatting problem", e);
   107 			exitCode = EXIT_FORMATTING_ERROR;
   108 		} catch (BatchException e) {
   109 			log.log(Level.SEVERE, "Batch problem", e);
   110 			exitCode = EXIT_BATCH_ERROR;
   111 		}
   112 
   113 		System.exit(exitCode);
   114 	}
   115 
   116 	public CLIStarter(CLIOptions options) {
   117 		this.options = options;
   118 	}
   119 
   120 	private void process() throws ConfigurationException, SQLException, FormatterException, BatchException {
   121 		MODE mode = options.getMode();
   122 
   123 		/** Show info */
   124 		if (!options.getShowInfo().isEmpty()) {
   125 			PrintStream infoOut = mode == MODE.JUST_SHOW_INFO ? System.out : System.err;
   126 			InfoLister infoLister = new InfoLister(infoOut, this, options);
   127 			infoLister.showInfo();
   128 		}
   129 
   130 		switch (mode) {
   131 			case QUERY_NOW:
   132 				processQueryNow();
   133 				break;
   134 			case PREPARE_BATCH:
   135 				processPrepareBatch();
   136 				break;
   137 			case EXECUTE_BATCH:
   138 				processExecuteBatch();
   139 				break;
   140 			case JUST_SHOW_INFO:
   141 				// already done above
   142 				break;
   143 			default:
   144 				log.log(Level.SEVERE, "Unsupported mode: {0}", mode);
   145 				break;
   146 		}
   147 
   148 		generateBashCompletion();
   149 	}
   150 
   151 	private void processQueryNow() throws ConfigurationException, SQLException, FormatterException {
   152 		DatabaseDefinition dd = getConfiguration().getDatabase(options.getDatabaseName());
   153 		FormatterDefinition fd = configuration.getFormatter(options.getFormatterName());
   154 		ConnectionManagement jmxBean = ManagementUtils.registerMBean(dd.getName());
   155 
   156 		try (DatabaseConnection c = dd.connect(options.getDatabaseProperties(), jmxBean)) {
   157 			log.log(Level.FINE, "Database connected");
   158 			try (Formatter f = fd.getInstance(new FormatterContext(options.getOutputStream(), options.getFormatterProperties()))) {
   159 				c.executeQuery(options.getSQLCommand(), f);
   160 			}
   161 		}
   162 	}
   163 
   164 	private void processPrepareBatch() throws BatchException {
   165 		BatchEncoder enc = new BatchEncoder();
   166 		int length = enc.encode(options.getSQLCommand(), options.getOutputStream());
   167 		log.log(Level.FINE, "Prepared batch size: {0} bytes", length);
   168 	}
   169 
   170 	private void processExecuteBatch() throws ConfigurationException, SQLException, FormatterException, BatchException {
   171 		BatchDecoder dec = new BatchDecoder();
   172 		Batch b = dec.decode(options.getInputStream());
   173 
   174 		DatabaseDefinition dd = getConfiguration().getDatabase(options.getDatabaseName());
   175 		FormatterDefinition fd = configuration.getFormatter(options.getFormatterName());
   176 		ConnectionManagement jmxBean = ManagementUtils.registerMBean(dd.getName());
   177 
   178 		try (DatabaseConnection c = dd.connect(options.getDatabaseProperties(), jmxBean)) {
   179 			log.log(Level.FINE, "Database connected");
   180 			try (Formatter f = fd.getInstance(new FormatterContext(options.getOutputStream(), options.getFormatterProperties()))) {
   181 				c.executeBatch(b, f);
   182 			}
   183 		}
   184 	}
   185 
   186 	@Override
   187 	public Configuration getConfiguration() throws ConfigurationException {
   188 		if (configuration == null) {
   189 			configuration = loadConfiguration();
   190 		}
   191 		return configuration;
   192 	}
   193 
   194 	private void installDefaultConfiguration() throws ConfigurationException {
   195 		Constants.DIR.mkdir();
   196 
   197 		if (Constants.CONFIG_FILE.exists()) {
   198 			log.log(Level.FINER, "Config file already exists: {0}", Constants.CONFIG_FILE);
   199 		} else {
   200 			try {
   201 				Functions.installResource(Constants.EXAMPLE_CONFIG_FILE, Constants.CONFIG_FILE);
   202 				log.log(Level.FINE, "Installing default config file: {0}", Constants.CONFIG_FILE);
   203 			} catch (IOException e) {
   204 				throw new ConfigurationException("Unable to write example configuration to " + Constants.CONFIG_FILE, e);
   205 			}
   206 		}
   207 	}
   208 
   209 	private Configuration loadConfiguration() throws ConfigurationException {
   210 		try {
   211 			JAXBContext jaxb = JAXBContext.newInstance(Configuration.class);
   212 			Unmarshaller u = jaxb.createUnmarshaller();
   213 			return (Configuration) u.unmarshal(Constants.CONFIG_FILE);
   214 		} catch (Exception e) {
   215 			throw new ConfigurationException("Unable to load configuration from " + Constants.CONFIG_FILE, e);
   216 		}
   217 	}
   218 
   219 	private void generateBashCompletion() {
   220 		if (configuration == null) {
   221 			log.log(Level.FINER, "Not writing Bash completion helper files. In order to generate these files please run some command which requires configuration.");
   222 		} else {
   223 			try {
   224 				File dir = new File(Constants.DIR, "bash-completion");
   225 				dir.mkdir();
   226 				writeBashCompletionHelperFile(configuration.getDatabases(), new File(dir, "databases"));
   227 				writeBashCompletionHelperFile(configuration.getAllFormatters(), new File(dir, "formatters"));
   228 			} catch (Exception e) {
   229 				log.log(Level.WARNING, "Unable to generate Bash completion helper files", e);
   230 			}
   231 		}
   232 	}
   233 
   234 	private void writeBashCompletionHelperFile(Collection<? extends NameIdentified> items, File target) throws FileNotFoundException {
   235 		if (Constants.CONFIG_FILE.lastModified() > target.lastModified()) {
   236 			try (PrintWriter fw = new PrintWriter(target)) {
   237 				for (NameIdentified dd : items) {
   238 					fw.println(dd.getName());
   239 				}
   240 				fw.close();
   241 				log.log(Level.FINE, "Bash completion helper file was written: {0}", target);
   242 			}
   243 		} else {
   244 			log.log(Level.FINER, "Not writing Bash completion helper file: {0} because configuration {1} has not been changed", new Object[]{target, Constants.CONFIG_FILE});
   245 		}
   246 	}
   247 }