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