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