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 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;
56 public static void main(String[] args) {
57 log.log(Level.FINE, "Starting " + Constants.PROGRAM_NAME);
58 int exitCode = EXIT_EXPECTED_ERROR;
60 if (args.length == 0) {
61 args = new String[]{CLIParser.Tokens.INFO_HELP};
65 CLIParser parser = new CLIParser();
66 CLIOptions options = parser.parseOptions(args);
68 CLIStarter starter = new CLIStarter(options);
69 starter.installDefaultConfiguration();
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()});
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);
92 System.exit(exitCode);
95 public CLIStarter(CLIOptions options) {
96 this.options = options;
99 private void process() throws ConfigurationException, SQLException, FormatterException {
100 MODE mode = options.getMode();
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();
114 processPrepareBatch();
117 processExecuteBatch();
120 // already done above
123 log.log(Level.SEVERE, "Unsupported mode: {0}", mode);
127 generateBashCompletion();
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);
140 private void processPrepareBatch() {
143 private void processExecuteBatch() {
147 public Configuration getConfiguration() throws ConfigurationException {
148 if (configuration == null) {
149 configuration = loadConfiguration();
151 return configuration;
154 private void installDefaultConfiguration() throws ConfigurationException {
155 Constants.DIR.mkdir();
157 if (Constants.CONFIG_FILE.exists()) {
158 log.log(Level.FINER, "Config file already exists: {0}", Constants.CONFIG_FILE);
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);
169 private Configuration loadConfiguration() throws ConfigurationException {
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);
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.");
184 File dir = new File(Constants.DIR, "bash-completion");
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);
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());
201 log.log(Level.FINE, "Bash completion helper file was written: {0}", target);
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});