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