java/sql-dk/src/info/globalcode/sql/dk/CLIStarter.java
author František Kučera <franta-hg@frantovo.cz>
Thu, 26 Dec 2013 00:58:00 +0100
branchv_0
changeset 63 3b9ec9c23a37
parent 56 29f45ab3b959
child 64 fcc499518dc7
permissions -rw-r--r--
validation: test if prefix/suffix are valid regular expressions
     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.formatting.Formatter;
    27 import info.globalcode.sql.dk.formatting.FormatterContext;
    28 import info.globalcode.sql.dk.formatting.FormatterException;
    29 import java.io.IOException;
    30 import java.sql.SQLException;
    31 import java.util.logging.Level;
    32 import java.util.logging.LogRecord;
    33 import java.util.logging.Logger;
    34 import javax.xml.bind.JAXBContext;
    35 import javax.xml.bind.Unmarshaller;
    36 
    37 /**
    38  *
    39  * @author Ing. František Kučera (frantovo.cz)
    40  */
    41 public class CLIStarter implements ConfigurationProvider {
    42 
    43 	private static final Logger log = Logger.getLogger(CLIStarter.class.getName());
    44 	private static final int EXIT_SUCCESS = 0;
    45 	private static final int EXIT_EXPECTED_ERROR = 3;
    46 	private static final int EXIT_SQL_ERROR = 4;
    47 	private CLIOptions options;
    48 	private Configuration configuration;
    49 
    50 	public static void main(String[] args) {
    51 		log.log(Level.FINE, "Starting " + Constants.PROGRAM_NAME);
    52 		int exitCode = EXIT_EXPECTED_ERROR;
    53 
    54 		if (args.length == 0) {
    55 			args = new String[]{CLIParser.Tokens.INFO_HELP};
    56 		}
    57 
    58 		try {
    59 			CLIParser parser = new CLIParser();
    60 			CLIOptions options = parser.parseOptions(args);
    61 			options.validate();
    62 			CLIStarter starter = new CLIStarter(options);
    63 			starter.installDefaultConfiguration();
    64 			starter.process();
    65 			log.log(Level.FINE, "All done");
    66 			exitCode = EXIT_SUCCESS;
    67 		} catch (CLIParserException e) {
    68 			log.log(Level.SEVERE, "Unable to parse CLI options", e);
    69 		} catch (InvalidOptionsException e) {
    70 			log.log(Level.SEVERE, "Invalid CLI options", e);
    71 			for (InvalidOptionsException.OptionProblem p : e.getProblems()) {
    72 				LogRecord r = new LogRecord(Level.SEVERE, "Option problem: {0}");
    73 				r.setThrown(p.getException());
    74 				r.setParameters(new Object[]{p.getDescription()});
    75 				log.log(r);
    76 			}
    77 		} catch (ConfigurationException e) {
    78 			log.log(Level.SEVERE, "Configuration problem", e);
    79 		} catch (SQLException e) {
    80 			log.log(Level.SEVERE, "SQL problem", e);
    81 			exitCode = EXIT_SQL_ERROR;
    82 		} catch (FormatterException e) {
    83 			log.log(Level.SEVERE, "Formatting problem", e);
    84 		}
    85 
    86 		System.exit(exitCode);
    87 	}
    88 
    89 	public CLIStarter(CLIOptions options) {
    90 		this.options = options;
    91 	}
    92 
    93 	private void process() throws ConfigurationException, SQLException, FormatterException {
    94 		/** Show info */
    95 		if (!options.getShowInfo().isEmpty()) {
    96 			InfoLister infoLister = new InfoLister(System.err, this);
    97 			infoLister.showInfo(options);
    98 		}
    99 
   100 		MODE mode = options.getMode();
   101 		switch (mode) {
   102 			case QUERY_NOW:
   103 				processQueryNow();
   104 				break;
   105 			case PREPARE_BATCH:
   106 				processPrepareBatch();
   107 				break;
   108 			case EXECUTE_BATCH:
   109 				processExecuteBatch();
   110 				break;
   111 			case JUST_SHOW_INFO:
   112 				// already done above
   113 				break;
   114 			default:
   115 				log.log(Level.SEVERE, "Unsupported mode: {0}", mode);
   116 				break;
   117 		}
   118 	}
   119 
   120 	private void processQueryNow() throws ConfigurationException, SQLException, FormatterException {
   121 		DatabaseDefinition dd = getConfiguration().getDatabase(options.getDatabaseName());
   122 		if (dd == null) {
   123 			throw new ConfigurationException("Database is not configured: " + options.getDatabaseName());
   124 		} else {
   125 			FormatterDefinition fd = configuration.getFormatter(options.getFormatterName());
   126 			if (fd == null) {
   127 				throw new ConfigurationException("Formatter is not configured: " + options.getFormatterName());
   128 			} else {
   129 				try (DatabaseConnection c = dd.connect()) {
   130 					log.log(Level.FINE, "Database connected");
   131 					Formatter f = fd.getInstance(new FormatterContext(options.getOutputStream()));
   132 					c.executeQuery(options.getSQLCommand(), f);
   133 				}
   134 			}
   135 		}
   136 	}
   137 
   138 	private void processPrepareBatch() {
   139 	}
   140 
   141 	private void processExecuteBatch() {
   142 	}
   143 
   144 	@Override
   145 	public Configuration getConfiguration() throws ConfigurationException {
   146 		if (configuration == null) {
   147 			configuration = loadConfiguration();
   148 		}
   149 		return configuration;
   150 	}
   151 
   152 	private void installDefaultConfiguration() throws ConfigurationException {
   153 		Constants.DIR.mkdir();
   154 
   155 		if (Constants.CONFIG_FILE.exists()) {
   156 			log.log(Level.FINER, "Config file already exists: {0}", Constants.CONFIG_FILE);
   157 		} else {
   158 			try {
   159 				Functions.installResource(Constants.EXAMPLE_CONFIG_FILE, Constants.CONFIG_FILE);
   160 				log.log(Level.FINE, "Installing default config file: {0}", Constants.CONFIG_FILE);
   161 			} catch (IOException e) {
   162 				throw new ConfigurationException("Unable to write example configuration to " + Constants.CONFIG_FILE, e);
   163 			}
   164 		}
   165 	}
   166 
   167 	private Configuration loadConfiguration() throws ConfigurationException {
   168 		try {
   169 			JAXBContext jaxb = JAXBContext.newInstance(Configuration.class);
   170 			Unmarshaller u = jaxb.createUnmarshaller();
   171 			return (Configuration) u.unmarshal(Constants.CONFIG_FILE);
   172 		} catch (Exception e) {
   173 			throw new ConfigurationException("Unable to load configuration from " + Constants.CONFIG_FILE, e);
   174 		}
   175 	}
   176 }