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 {
50 public static final int EXIT_SUCCESS = 0; // doc:success
51 public static final int EXIT_UNEXPECTED_ERROR = 1; // doc:unexpected error (probably bug)
52 public static final int EXIT_SQL_ERROR = 3; // doc:SQL error
53 public static final int EXIT_CLI_PARSE_ERROR = 4; // doc:CLI options parse error
54 public static final int EXIT_CLI_VALIDATE_ERROR = 5; // doc:CLI options validation error
55 public static final int EXIT_CONFIGURATION_ERROR = 6; // doc:configuration error
56 public static final int EXIT_FORMATTING_ERROR = 7; // doc:formatting error
57 private static final Logger log = Logger.getLogger(CLIStarter.class.getName());
58 private CLIOptions options;
59 private Configuration configuration;
61 public static void main(String[] args) {
62 log.log(Level.FINE, "Starting " + Constants.PROGRAM_NAME);
65 if (args.length == 0) {
66 args = new String[]{CLIParser.Tokens.INFO_HELP};
70 CLIParser parser = new CLIParser();
71 CLIOptions options = parser.parseOptions(args);
73 CLIStarter starter = new CLIStarter(options);
74 starter.installDefaultConfiguration();
76 log.log(Level.FINE, "All done");
77 exitCode = EXIT_SUCCESS;
78 } catch (CLIParserException e) {
79 log.log(Level.SEVERE, "Unable to parse CLI options", e);
80 exitCode = EXIT_CLI_PARSE_ERROR;
81 } catch (InvalidOptionsException e) {
82 log.log(Level.SEVERE, "Invalid CLI options", e);
83 for (InvalidOptionsException.OptionProblem p : e.getProblems()) {
84 LogRecord r = new LogRecord(Level.SEVERE, "Option problem: {0}");
85 r.setThrown(p.getException());
86 r.setParameters(new Object[]{p.getDescription()});
89 exitCode = EXIT_CLI_VALIDATE_ERROR;
90 } catch (ConfigurationException e) {
91 log.log(Level.SEVERE, "Configuration problem", e);
92 exitCode = EXIT_CONFIGURATION_ERROR;
93 } catch (SQLException e) {
94 log.log(Level.SEVERE, "SQL problem", e);
95 exitCode = EXIT_SQL_ERROR;
96 } catch (FormatterException e) {
97 log.log(Level.SEVERE, "Formatting problem", e);
98 exitCode = EXIT_FORMATTING_ERROR;
101 System.exit(exitCode);
104 public CLIStarter(CLIOptions options) {
105 this.options = options;
108 private void process() throws ConfigurationException, SQLException, FormatterException {
109 MODE mode = options.getMode();
112 if (!options.getShowInfo().isEmpty()) {
113 PrintStream infoOut = mode == MODE.JUST_SHOW_INFO ? System.out : System.err;
114 InfoLister infoLister = new InfoLister(infoOut, this, options);
115 infoLister.showInfo();
123 processPrepareBatch();
126 processExecuteBatch();
129 // already done above
132 log.log(Level.SEVERE, "Unsupported mode: {0}", mode);
136 generateBashCompletion();
139 private void processQueryNow() throws ConfigurationException, SQLException, FormatterException {
140 DatabaseDefinition dd = getConfiguration().getDatabase(options.getDatabaseName());
141 FormatterDefinition fd = configuration.getFormatter(options.getFormatterName());
142 try (DatabaseConnection c = dd.connect(options.getDatabaseProperties())) {
143 log.log(Level.FINE, "Database connected");
144 try (Formatter f = fd.getInstance(new FormatterContext(options.getOutputStream(), options.getFormatterProperties()))) {
145 c.executeQuery(options.getSQLCommand(), f);
150 private void processPrepareBatch() {
153 private void processExecuteBatch() {
157 public Configuration getConfiguration() throws ConfigurationException {
158 if (configuration == null) {
159 configuration = loadConfiguration();
161 return configuration;
164 private void installDefaultConfiguration() throws ConfigurationException {
165 Constants.DIR.mkdir();
167 if (Constants.CONFIG_FILE.exists()) {
168 log.log(Level.FINER, "Config file already exists: {0}", Constants.CONFIG_FILE);
171 Functions.installResource(Constants.EXAMPLE_CONFIG_FILE, Constants.CONFIG_FILE);
172 log.log(Level.FINE, "Installing default config file: {0}", Constants.CONFIG_FILE);
173 } catch (IOException e) {
174 throw new ConfigurationException("Unable to write example configuration to " + Constants.CONFIG_FILE, e);
179 private Configuration loadConfiguration() throws ConfigurationException {
181 JAXBContext jaxb = JAXBContext.newInstance(Configuration.class);
182 Unmarshaller u = jaxb.createUnmarshaller();
183 return (Configuration) u.unmarshal(Constants.CONFIG_FILE);
184 } catch (Exception e) {
185 throw new ConfigurationException("Unable to load configuration from " + Constants.CONFIG_FILE, e);
189 private void generateBashCompletion() {
190 if (configuration == null) {
191 log.log(Level.FINER, "Not writing Bash completion helper files. In order to generate these files please run some command which requires configuration.");
194 File dir = new File(Constants.DIR, "bash-completion");
196 writeBashCompletionHelperFile(configuration.getDatabases(), new File(dir, "databases"));
197 writeBashCompletionHelperFile(configuration.getAllFormatters(), new File(dir, "formatters"));
198 } catch (Exception e) {
199 log.log(Level.WARNING, "Unable to generate Bash completion helper files", e);
204 private void writeBashCompletionHelperFile(Collection<? extends NameIdentified> items, File target) throws FileNotFoundException {
205 if (Constants.CONFIG_FILE.lastModified() > target.lastModified()) {
206 try (PrintWriter fw = new PrintWriter(target)) {
207 for (NameIdentified dd : items) {
208 fw.println(dd.getName());
211 log.log(Level.FINE, "Bash completion helper file was written: {0}", target);
214 log.log(Level.FINER, "Not writing Bash completion helper file: {0} because configuration {1} has not been changed", new Object[]{target, Constants.CONFIG_FILE});