3 * Copyright © 2013 František Kučera (frantovo.cz)
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.
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.
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/>.
18 package info.globalcode.sql.dk;
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;
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;
45 * @author Ing. František Kučera (frantovo.cz)
47 public class CLIStarter implements ConfigurationProvider {
49 public static final int EXIT_SUCCESS = 0; // doc:success
50 public static final int EXIT_UNEXPECTED_ERROR = 1; // doc:unexpected error (probably bug)
51 public static final int EXIT_SQL_ERROR = 3; // doc:SQL error
52 public static final int EXIT_CLI_PARSE_ERROR = 4; // doc:CLI options parse error
53 public static final int EXIT_CLI_VALIDATE_ERROR = 5; // doc:CLI options validation error
54 public static final int EXIT_CONFIGURATION_ERROR = 6; // doc:configuration error
55 public static final int EXIT_FORMATTING_ERROR = 7; // doc:formatting error
56 private static final Logger log = Logger.getLogger(CLIStarter.class.getName());
57 private CLIOptions options;
58 private Configuration configuration;
60 public static void main(String[] args) {
61 log.log(Level.FINE, "Starting " + Constants.PROGRAM_NAME);
64 if (args.length == 0) {
65 args = new String[]{CLIParser.Tokens.INFO_HELP};
69 CLIParser parser = new CLIParser();
70 CLIOptions options = parser.parseOptions(args);
72 CLIStarter starter = new CLIStarter(options);
73 starter.installDefaultConfiguration();
75 log.log(Level.FINE, "All done");
76 exitCode = EXIT_SUCCESS;
77 } catch (CLIParserException e) {
78 log.log(Level.SEVERE, "Unable to parse CLI options", e);
79 exitCode = EXIT_CLI_PARSE_ERROR;
80 } catch (InvalidOptionsException e) {
81 log.log(Level.SEVERE, "Invalid CLI options", e);
82 for (InvalidOptionsException.OptionProblem p : e.getProblems()) {
83 LogRecord r = new LogRecord(Level.SEVERE, "Option problem: {0}");
84 r.setThrown(p.getException());
85 r.setParameters(new Object[]{p.getDescription()});
88 exitCode = EXIT_CLI_VALIDATE_ERROR;
89 } catch (ConfigurationException e) {
90 log.log(Level.SEVERE, "Configuration problem", e);
91 exitCode = EXIT_CONFIGURATION_ERROR;
92 } catch (SQLException e) {
93 log.log(Level.SEVERE, "SQL problem", e);
94 exitCode = EXIT_SQL_ERROR;
95 } catch (FormatterException e) {
96 log.log(Level.SEVERE, "Formatting problem", e);
97 exitCode = EXIT_FORMATTING_ERROR;
100 System.exit(exitCode);
103 public CLIStarter(CLIOptions options) {
104 this.options = options;
107 private void process() throws ConfigurationException, SQLException, FormatterException {
108 MODE mode = options.getMode();
111 if (!options.getShowInfo().isEmpty()) {
112 PrintStream infoOut = mode == MODE.JUST_SHOW_INFO ? System.out : System.err;
113 InfoLister infoLister = new InfoLister(infoOut, this, options);
114 infoLister.showInfo();
122 processPrepareBatch();
125 processExecuteBatch();
128 // already done above
131 log.log(Level.SEVERE, "Unsupported mode: {0}", mode);
135 generateBashCompletion();
138 private void processQueryNow() throws ConfigurationException, SQLException, FormatterException {
139 DatabaseDefinition dd = getConfiguration().getDatabase(options.getDatabaseName());
140 FormatterDefinition fd = configuration.getFormatter(options.getFormatterName());
141 try (DatabaseConnection c = dd.connect()) {
142 log.log(Level.FINE, "Database connected");
143 Formatter f = fd.getInstance(new FormatterContext(options.getOutputStream()));
144 c.executeQuery(options.getSQLCommand(), f);
148 private void processPrepareBatch() {
151 private void processExecuteBatch() {
155 public Configuration getConfiguration() throws ConfigurationException {
156 if (configuration == null) {
157 configuration = loadConfiguration();
159 return configuration;
162 private void installDefaultConfiguration() throws ConfigurationException {
163 Constants.DIR.mkdir();
165 if (Constants.CONFIG_FILE.exists()) {
166 log.log(Level.FINER, "Config file already exists: {0}", Constants.CONFIG_FILE);
169 Functions.installResource(Constants.EXAMPLE_CONFIG_FILE, Constants.CONFIG_FILE);
170 log.log(Level.FINE, "Installing default config file: {0}", Constants.CONFIG_FILE);
171 } catch (IOException e) {
172 throw new ConfigurationException("Unable to write example configuration to " + Constants.CONFIG_FILE, e);
177 private Configuration loadConfiguration() throws ConfigurationException {
179 JAXBContext jaxb = JAXBContext.newInstance(Configuration.class);
180 Unmarshaller u = jaxb.createUnmarshaller();
181 return (Configuration) u.unmarshal(Constants.CONFIG_FILE);
182 } catch (Exception e) {
183 throw new ConfigurationException("Unable to load configuration from " + Constants.CONFIG_FILE, e);
187 private void generateBashCompletion() {
188 if (configuration == null) {
189 log.log(Level.FINER, "Not writing Bash completion helper files. In order to generate these files please run some command which requires configuration.");
192 File dir = new File(Constants.DIR, "bash-completion");
194 writeBashCompletionHelperFile(configuration.getDatabases(), new File(dir, "databases"));
195 writeBashCompletionHelperFile(configuration.getAllFormatters(), new File(dir, "formatters"));
196 } catch (Exception e) {
197 log.log(Level.WARNING, "Unable to generate Bash completion helper files", e);
202 private void writeBashCompletionHelperFile(Collection<? extends NameIdentified> items, File target) throws FileNotFoundException {
203 if (Constants.CONFIG_FILE.lastModified() > target.lastModified()) {
204 try (PrintWriter fw = new PrintWriter(target)) {
205 for (NameIdentified dd : items) {
206 fw.println(dd.getName());
209 log.log(Level.FINE, "Bash completion helper file was written: {0}", target);
212 log.log(Level.FINER, "Not writing Bash completion helper file: {0} because configuration {1} has not been changed", new Object[]{target, Constants.CONFIG_FILE});