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