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 public static final int EXIT_BATCH_ERROR = 8; // doc:batch error
62 private static final Logger log = Logger.getLogger(CLIStarter.class.getName());
63 private CLIOptions options;
64 private Configuration configuration;
66 public static void main(String[] args) {
67 log.log(Level.FINE, "Starting " + Constants.PROGRAM_NAME);
70 if (args.length == 0) {
71 args = new String[]{CLIParser.Tokens.INFO_HELP};
75 CLIParser parser = new CLIParser();
76 CLIOptions options = parser.parseOptions(args);
78 CLIStarter starter = new CLIStarter(options);
79 starter.installDefaultConfiguration();
81 log.log(Level.FINE, "All done");
82 exitCode = EXIT_SUCCESS;
83 } catch (CLIParserException e) {
84 log.log(Level.SEVERE, "Unable to parse CLI options", e);
85 exitCode = EXIT_CLI_PARSE_ERROR;
86 } catch (InvalidOptionsException e) {
87 log.log(Level.SEVERE, "Invalid CLI options", e);
88 for (InvalidOptionsException.OptionProblem p : e.getProblems()) {
89 LogRecord r = new LogRecord(Level.SEVERE, "Option problem: {0}");
90 r.setThrown(p.getException());
91 r.setParameters(new Object[]{p.getDescription()});
94 exitCode = EXIT_CLI_VALIDATE_ERROR;
95 } catch (ConfigurationException e) {
96 log.log(Level.SEVERE, "Configuration problem", e);
97 exitCode = EXIT_CONFIGURATION_ERROR;
98 } catch (SQLException e) {
99 log.log(Level.SEVERE, "SQL problem", e);
100 exitCode = EXIT_SQL_ERROR;
101 } catch (FormatterException e) {
102 log.log(Level.SEVERE, "Formatting problem", e);
103 exitCode = EXIT_FORMATTING_ERROR;
104 } catch (BatchException e) {
105 log.log(Level.SEVERE, "Batch problem", e);
106 exitCode = EXIT_BATCH_ERROR;
109 System.exit(exitCode);
112 public CLIStarter(CLIOptions options) {
113 this.options = options;
116 private void process() throws ConfigurationException, SQLException, FormatterException, BatchException {
117 MODE mode = options.getMode();
120 if (!options.getShowInfo().isEmpty()) {
121 PrintStream infoOut = mode == MODE.JUST_SHOW_INFO ? System.out : System.err;
122 InfoLister infoLister = new InfoLister(infoOut, this, options);
123 infoLister.showInfo();
131 processPrepareBatch();
134 processExecuteBatch();
137 // already done above
140 log.log(Level.SEVERE, "Unsupported mode: {0}", mode);
144 generateBashCompletion();
147 private void processQueryNow() throws ConfigurationException, SQLException, FormatterException {
148 DatabaseDefinition dd = getConfiguration().getDatabase(options.getDatabaseName());
149 FormatterDefinition fd = configuration.getFormatter(options.getFormatterName());
150 try (DatabaseConnection c = dd.connect(options.getDatabaseProperties())) {
151 log.log(Level.FINE, "Database connected");
152 try (Formatter f = fd.getInstance(new FormatterContext(options.getOutputStream(), options.getFormatterProperties()))) {
153 c.executeQuery(options.getSQLCommand(), f);
158 private void processPrepareBatch() throws BatchException {
159 BatchEncoder enc = new BatchEncoder();
160 int length = enc.encode(options.getSQLCommand(), options.getOutputStream());
161 log.log(Level.FINE, "Prepared batch size: {0} bytes", length);
164 private void processExecuteBatch() throws ConfigurationException, SQLException, FormatterException, BatchException {
165 BatchDecoder dec = new BatchDecoder();
166 Batch b = dec.decode(options.getInputStream());
168 DatabaseDefinition dd = getConfiguration().getDatabase(options.getDatabaseName());
169 FormatterDefinition fd = configuration.getFormatter(options.getFormatterName());
170 try (DatabaseConnection c = dd.connect(options.getDatabaseProperties())) {
171 log.log(Level.FINE, "Database connected");
172 try (Formatter f = fd.getInstance(new FormatterContext(options.getOutputStream(), options.getFormatterProperties()))) {
173 c.executeBatch(b, f);
179 public Configuration getConfiguration() throws ConfigurationException {
180 if (configuration == null) {
181 configuration = loadConfiguration();
183 return configuration;
186 private void installDefaultConfiguration() throws ConfigurationException {
187 Constants.DIR.mkdir();
189 if (Constants.CONFIG_FILE.exists()) {
190 log.log(Level.FINER, "Config file already exists: {0}", Constants.CONFIG_FILE);
193 Functions.installResource(Constants.EXAMPLE_CONFIG_FILE, Constants.CONFIG_FILE);
194 log.log(Level.FINE, "Installing default config file: {0}", Constants.CONFIG_FILE);
195 } catch (IOException e) {
196 throw new ConfigurationException("Unable to write example configuration to " + Constants.CONFIG_FILE, e);
201 private Configuration loadConfiguration() throws ConfigurationException {
203 JAXBContext jaxb = JAXBContext.newInstance(Configuration.class);
204 Unmarshaller u = jaxb.createUnmarshaller();
205 return (Configuration) u.unmarshal(Constants.CONFIG_FILE);
206 } catch (Exception e) {
207 throw new ConfigurationException("Unable to load configuration from " + Constants.CONFIG_FILE, e);
211 private void generateBashCompletion() {
212 if (configuration == null) {
213 log.log(Level.FINER, "Not writing Bash completion helper files. In order to generate these files please run some command which requires configuration.");
216 File dir = new File(Constants.DIR, "bash-completion");
218 writeBashCompletionHelperFile(configuration.getDatabases(), new File(dir, "databases"));
219 writeBashCompletionHelperFile(configuration.getAllFormatters(), new File(dir, "formatters"));
220 } catch (Exception e) {
221 log.log(Level.WARNING, "Unable to generate Bash completion helper files", e);
226 private void writeBashCompletionHelperFile(Collection<? extends NameIdentified> items, File target) throws FileNotFoundException {
227 if (Constants.CONFIG_FILE.lastModified() > target.lastModified()) {
228 try (PrintWriter fw = new PrintWriter(target)) {
229 for (NameIdentified dd : items) {
230 fw.println(dd.getName());
233 log.log(Level.FINE, "Bash completion helper file was written: {0}", target);
236 log.log(Level.FINER, "Not writing Bash completion helper file: {0} because configuration {1} has not been changed", new Object[]{target, Constants.CONFIG_FILE});