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