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