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