java/sql-dk/src/info/globalcode/sql/dk/CLIStarter.java
author František Kučera <franta-hg@frantovo.cz>
Thu, 26 Dec 2013 21:18:54 +0100
branchv_0
changeset 69 0befec5034c2
parent 64 fcc499518dc7
child 70 02c8eaa425e8
permissions -rw-r--r--
InfoLister, InfoType: switch → enum
     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 			for (InfoLister.InfoType infoType : options.getShowInfo()) {
   102 				infoType.showInfo(infoLister);
   103 			}
   104 		}
   105 
   106 		switch (mode) {
   107 			case QUERY_NOW:
   108 				processQueryNow();
   109 				break;
   110 			case PREPARE_BATCH:
   111 				processPrepareBatch();
   112 				break;
   113 			case EXECUTE_BATCH:
   114 				processExecuteBatch();
   115 				break;
   116 			case JUST_SHOW_INFO:
   117 				// already done above
   118 				break;
   119 			default:
   120 				log.log(Level.SEVERE, "Unsupported mode: {0}", mode);
   121 				break;
   122 		}
   123 	}
   124 
   125 	private void processQueryNow() throws ConfigurationException, SQLException, FormatterException {
   126 		DatabaseDefinition dd = getConfiguration().getDatabase(options.getDatabaseName());
   127 		if (dd == null) {
   128 			throw new ConfigurationException("Database is not configured: " + options.getDatabaseName());
   129 		} else {
   130 			FormatterDefinition fd = configuration.getFormatter(options.getFormatterName());
   131 			if (fd == null) {
   132 				throw new ConfigurationException("Formatter is not configured: " + options.getFormatterName());
   133 			} else {
   134 				try (DatabaseConnection c = dd.connect()) {
   135 					log.log(Level.FINE, "Database connected");
   136 					Formatter f = fd.getInstance(new FormatterContext(options.getOutputStream()));
   137 					c.executeQuery(options.getSQLCommand(), f);
   138 				}
   139 			}
   140 		}
   141 	}
   142 
   143 	private void processPrepareBatch() {
   144 	}
   145 
   146 	private void processExecuteBatch() {
   147 	}
   148 
   149 	@Override
   150 	public Configuration getConfiguration() throws ConfigurationException {
   151 		if (configuration == null) {
   152 			configuration = loadConfiguration();
   153 		}
   154 		return configuration;
   155 	}
   156 
   157 	private void installDefaultConfiguration() throws ConfigurationException {
   158 		Constants.DIR.mkdir();
   159 
   160 		if (Constants.CONFIG_FILE.exists()) {
   161 			log.log(Level.FINER, "Config file already exists: {0}", Constants.CONFIG_FILE);
   162 		} else {
   163 			try {
   164 				Functions.installResource(Constants.EXAMPLE_CONFIG_FILE, Constants.CONFIG_FILE);
   165 				log.log(Level.FINE, "Installing default config file: {0}", Constants.CONFIG_FILE);
   166 			} catch (IOException e) {
   167 				throw new ConfigurationException("Unable to write example configuration to " + Constants.CONFIG_FILE, e);
   168 			}
   169 		}
   170 	}
   171 
   172 	private Configuration loadConfiguration() throws ConfigurationException {
   173 		try {
   174 			JAXBContext jaxb = JAXBContext.newInstance(Configuration.class);
   175 			Unmarshaller u = jaxb.createUnmarshaller();
   176 			return (Configuration) u.unmarshal(Constants.CONFIG_FILE);
   177 		} catch (Exception e) {
   178 			throw new ConfigurationException("Unable to load configuration from " + Constants.CONFIG_FILE, e);
   179 		}
   180 	}
   181 }