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