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.batch.Batch;
23 import info.globalcode.sql.dk.batch.BatchDecoder;
24 import info.globalcode.sql.dk.batch.BatchException;
25 import info.globalcode.sql.dk.batch.BatchEncoder;
26 import info.globalcode.sql.dk.configuration.Configuration;
27 import info.globalcode.sql.dk.configuration.ConfigurationException;
28 import info.globalcode.sql.dk.configuration.DatabaseDefinition;
29 import info.globalcode.sql.dk.configuration.FormatterDefinition;
30 import info.globalcode.sql.dk.configuration.NameIdentified;
31 import info.globalcode.sql.dk.formatting.Formatter;
32 import info.globalcode.sql.dk.formatting.FormatterContext;
33 import info.globalcode.sql.dk.formatting.FormatterException;
35 import java.io.FileNotFoundException;
36 import java.io.IOException;
37 import java.io.PrintStream;
38 import java.io.PrintWriter;
39 import java.sql.SQLException;
40 import java.util.Collection;
41 import java.util.logging.Level;
42 import java.util.logging.LogRecord;
43 import java.util.logging.Logger;
44 import javax.xml.bind.JAXBContext;
45 import javax.xml.bind.Unmarshaller;
49 * @author Ing. František Kučera (frantovo.cz)
51 public class CLIStarter implements ConfigurationProvider {
54 public static final int EXIT_SUCCESS = 0; // doc:success
55 public static final int EXIT_UNEXPECTED_ERROR = 1; // doc:unexpected error (probably bug)
56 public static final int EXIT_SQL_ERROR = 3; // doc:SQL error
57 public static final int EXIT_CLI_PARSE_ERROR = 4; // doc:CLI options parse error
58 public static final int EXIT_CLI_VALIDATE_ERROR = 5; // doc:CLI options validation error
59 public static final int EXIT_CONFIGURATION_ERROR = 6; // doc:configuration error
60 public static final int EXIT_FORMATTING_ERROR = 7; // doc:formatting error
61 private static final Logger log = Logger.getLogger(CLIStarter.class.getName());
62 private CLIOptions options;
63 private Configuration configuration;
65 public static void main(String[] args) {
66 log.log(Level.FINE, "Starting " + Constants.PROGRAM_NAME);
69 if (args.length == 0) {
70 args = new String[]{CLIParser.Tokens.INFO_HELP};
74 CLIParser parser = new CLIParser();
75 CLIOptions options = parser.parseOptions(args);
77 CLIStarter starter = new CLIStarter(options);
78 starter.installDefaultConfiguration();
80 log.log(Level.FINE, "All done");
81 exitCode = EXIT_SUCCESS;
82 } catch (CLIParserException e) {
83 log.log(Level.SEVERE, "Unable to parse CLI options", e);
84 exitCode = EXIT_CLI_PARSE_ERROR;
85 } catch (InvalidOptionsException e) {
86 log.log(Level.SEVERE, "Invalid CLI options", e);
87 for (InvalidOptionsException.OptionProblem p : e.getProblems()) {
88 LogRecord r = new LogRecord(Level.SEVERE, "Option problem: {0}");
89 r.setThrown(p.getException());
90 r.setParameters(new Object[]{p.getDescription()});
93 exitCode = EXIT_CLI_VALIDATE_ERROR;
94 } catch (ConfigurationException e) {
95 log.log(Level.SEVERE, "Configuration problem", e);
96 exitCode = EXIT_CONFIGURATION_ERROR;
97 } catch (SQLException e) {
98 log.log(Level.SEVERE, "SQL problem", e);
99 exitCode = EXIT_SQL_ERROR;
100 } catch (FormatterException e) {
101 log.log(Level.SEVERE, "Formatting problem", e);
102 exitCode = EXIT_FORMATTING_ERROR;
103 } catch (BatchException e) {
104 log.log(Level.SEVERE, "Batch problem", e);
105 exitCode = EXIT_FORMATTING_ERROR;
108 System.exit(exitCode);
111 public CLIStarter(CLIOptions options) {
112 this.options = options;
115 private void process() throws ConfigurationException, SQLException, FormatterException, BatchException {
116 MODE mode = options.getMode();
119 if (!options.getShowInfo().isEmpty()) {
120 PrintStream infoOut = mode == MODE.JUST_SHOW_INFO ? System.out : System.err;
121 InfoLister infoLister = new InfoLister(infoOut, this, options);
122 infoLister.showInfo();
130 processPrepareBatch();
133 processExecuteBatch();
136 // already done above
139 log.log(Level.SEVERE, "Unsupported mode: {0}", mode);
143 generateBashCompletion();
146 private void processQueryNow() throws ConfigurationException, SQLException, FormatterException {
147 DatabaseDefinition dd = getConfiguration().getDatabase(options.getDatabaseName());
148 FormatterDefinition fd = configuration.getFormatter(options.getFormatterName());
149 try (DatabaseConnection c = dd.connect(options.getDatabaseProperties())) {
150 log.log(Level.FINE, "Database connected");
151 try (Formatter f = fd.getInstance(new FormatterContext(options.getOutputStream(), options.getFormatterProperties()))) {
152 c.executeQuery(options.getSQLCommand(), f);
157 private void processPrepareBatch() throws BatchException {
158 BatchEncoder enc = new BatchEncoder();
159 int length = enc.encode(options.getSQLCommand(), options.getOutputStream());
160 log.log(Level.FINE, "Prepared batch size: {0} bytes", length);
163 private void processExecuteBatch() throws ConfigurationException, SQLException, FormatterException, BatchException {
164 BatchDecoder dec = new BatchDecoder();
165 Batch b = dec.decode(options.getInputStream());
167 DatabaseDefinition dd = getConfiguration().getDatabase(options.getDatabaseName());
168 FormatterDefinition fd = configuration.getFormatter(options.getFormatterName());
169 try (DatabaseConnection c = dd.connect(options.getDatabaseProperties())) {
170 log.log(Level.FINE, "Database connected");
171 try (Formatter f = fd.getInstance(new FormatterContext(options.getOutputStream(), options.getFormatterProperties()))) {
172 c.executeBatch(b, f);
178 public Configuration getConfiguration() throws ConfigurationException {
179 if (configuration == null) {
180 configuration = loadConfiguration();
182 return configuration;
185 private void installDefaultConfiguration() throws ConfigurationException {
186 Constants.DIR.mkdir();
188 if (Constants.CONFIG_FILE.exists()) {
189 log.log(Level.FINER, "Config file already exists: {0}", Constants.CONFIG_FILE);
192 Functions.installResource(Constants.EXAMPLE_CONFIG_FILE, Constants.CONFIG_FILE);
193 log.log(Level.FINE, "Installing default config file: {0}", Constants.CONFIG_FILE);
194 } catch (IOException e) {
195 throw new ConfigurationException("Unable to write example configuration to " + Constants.CONFIG_FILE, e);
200 private Configuration loadConfiguration() throws ConfigurationException {
202 JAXBContext jaxb = JAXBContext.newInstance(Configuration.class);
203 Unmarshaller u = jaxb.createUnmarshaller();
204 return (Configuration) u.unmarshal(Constants.CONFIG_FILE);
205 } catch (Exception e) {
206 throw new ConfigurationException("Unable to load configuration from " + Constants.CONFIG_FILE, e);
210 private void generateBashCompletion() {
211 if (configuration == null) {
212 log.log(Level.FINER, "Not writing Bash completion helper files. In order to generate these files please run some command which requires configuration.");
215 File dir = new File(Constants.DIR, "bash-completion");
217 writeBashCompletionHelperFile(configuration.getDatabases(), new File(dir, "databases"));
218 writeBashCompletionHelperFile(configuration.getAllFormatters(), new File(dir, "formatters"));
219 } catch (Exception e) {
220 log.log(Level.WARNING, "Unable to generate Bash completion helper files", e);
225 private void writeBashCompletionHelperFile(Collection<? extends NameIdentified> items, File target) throws FileNotFoundException {
226 if (Constants.CONFIG_FILE.lastModified() > target.lastModified()) {
227 try (PrintWriter fw = new PrintWriter(target)) {
228 for (NameIdentified dd : items) {
229 fw.println(dd.getName());
232 log.log(Level.FINE, "Bash completion helper file was written: {0}", target);
235 log.log(Level.FINER, "Not writing Bash completion helper file: {0} because configuration {1} has not been changed", new Object[]{target, Constants.CONFIG_FILE});