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