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, version 3 of the License.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 package info.globalcode.sql.dk;
19 import info.globalcode.sql.dk.configuration.ConfigurationProvider;
20 import info.globalcode.sql.dk.CLIOptions.MODE;
21 import info.globalcode.sql.dk.batch.Batch;
22 import info.globalcode.sql.dk.batch.BatchDecoder;
23 import info.globalcode.sql.dk.batch.BatchException;
24 import info.globalcode.sql.dk.batch.BatchEncoder;
25 import info.globalcode.sql.dk.configuration.Configuration;
26 import info.globalcode.sql.dk.configuration.ConfigurationException;
27 import info.globalcode.sql.dk.configuration.DatabaseDefinition;
28 import info.globalcode.sql.dk.configuration.FormatterDefinition;
29 import info.globalcode.sql.dk.configuration.Loader;
30 import info.globalcode.sql.dk.configuration.NameIdentified;
31 import info.globalcode.sql.dk.configuration.PropertyDeclaration;
32 import info.globalcode.sql.dk.formatting.Formatter;
33 import info.globalcode.sql.dk.formatting.FormatterContext;
34 import info.globalcode.sql.dk.formatting.FormatterException;
35 import info.globalcode.sql.dk.jmx.ConnectionManagement;
36 import info.globalcode.sql.dk.jmx.ManagementUtils;
38 import java.io.FileNotFoundException;
39 import java.io.IOException;
40 import java.io.PrintStream;
41 import java.io.PrintWriter;
42 import java.sql.SQLException;
43 import java.util.Collection;
44 import java.util.Collections;
45 import java.util.List;
46 import java.util.logging.Level;
47 import java.util.logging.LogRecord;
48 import java.util.logging.Logger;
51 * Entry point of the command line interface of SQL-DK.
53 * @author Ing. František Kučera (frantovo.cz)
55 public class CLIStarter implements ConfigurationProvider {
58 public static final int EXIT_SUCCESS = 0; // doc:success
59 public static final int EXIT_UNEXPECTED_ERROR = 1; // doc:unexpected error (probably bug)
60 // 2 is reserved: http://www.tldp.org/LDP/abs/html/exitcodes.html#EXITCODESREF
61 public static final int EXIT_SQL_ERROR = 3; // doc:SQL error
62 public static final int EXIT_CLI_PARSE_ERROR = 4; // doc:CLI options parse error
63 public static final int EXIT_CLI_VALIDATE_ERROR = 5; // doc:CLI options validation error
64 public static final int EXIT_CONFIGURATION_ERROR = 6; // doc:configuration error
65 public static final int EXIT_FORMATTING_ERROR = 7; // doc:formatting error
66 public static final int EXIT_BATCH_ERROR = 8; // doc:batch error
67 private static final Logger log = Logger.getLogger(CLIStarter.class.getName());
68 private final CLIOptions options;
69 private final Loader configurationLoader = new Loader();
70 private Configuration configuration;
72 public static void main(String[] args) {
73 log.log(Level.FINE, "Starting " + Constants.PROGRAM_NAME);
76 if (args.length == 0) {
77 args = new String[]{CLIParser.Tokens.INFO_HELP};
81 CLIParser parser = new CLIParser();
82 CLIOptions options = parser.parseOptions(args, System.in);
84 CLIStarter starter = new CLIStarter(options);
85 starter.installDefaultConfiguration();
87 log.log(Level.FINE, "All done");
88 exitCode = EXIT_SUCCESS;
89 } catch (CLIParserException e) {
90 log.log(Level.SEVERE, "Unable to parse CLI options", e);
91 exitCode = EXIT_CLI_PARSE_ERROR;
92 } catch (InvalidOptionsException e) {
93 log.log(Level.SEVERE, "Invalid CLI options", e);
94 for (InvalidOptionsException.OptionProblem p : e.getProblems()) {
95 LogRecord r = new LogRecord(Level.SEVERE, "Option problem: {0}");
96 r.setThrown(p.getException());
97 r.setParameters(new Object[]{p.getDescription()});
100 exitCode = EXIT_CLI_VALIDATE_ERROR;
101 } catch (ConfigurationException e) {
102 log.log(Level.SEVERE, "Configuration problem", e);
103 exitCode = EXIT_CONFIGURATION_ERROR;
104 } catch (SQLException e) {
105 log.log(Level.SEVERE, "SQL problem", e);
106 exitCode = EXIT_SQL_ERROR;
107 } catch (FormatterException e) {
108 log.log(Level.SEVERE, "Formatting problem", e);
109 exitCode = EXIT_FORMATTING_ERROR;
110 } catch (BatchException e) {
111 log.log(Level.SEVERE, "Batch problem", e);
112 exitCode = EXIT_BATCH_ERROR;
115 System.exit(exitCode);
118 public CLIStarter(CLIOptions options) {
119 this.options = options;
122 private void process() throws ConfigurationException, SQLException, FormatterException, BatchException {
123 MODE mode = options.getMode();
126 if (!options.getShowInfo().isEmpty()) {
127 PrintStream infoOut = mode == MODE.JUST_SHOW_INFO ? System.out : System.err;
128 InfoLister infoLister = new InfoLister(infoOut, this, options);
129 infoLister.showInfo();
137 processPrepareBatch();
140 processExecuteBatch();
143 // already done above
146 log.log(Level.SEVERE, "Unsupported mode: {0}", mode);
150 generateBashCompletion();
153 private void processQueryNow() throws ConfigurationException, SQLException, FormatterException {
154 DatabaseDefinition dd = getConfiguration().getDatabase(options.getDatabaseName());
155 FormatterDefinition fd = configuration.getFormatter(options.getFormatterName());
156 ConnectionManagement jmxBean = ManagementUtils.registerMBean(dd.getName());
158 try (DatabaseConnection c = dd.connect(options.getDatabaseProperties(), jmxBean)) {
159 log.log(Level.FINE, "Database connected");
160 try (Formatter f = fd.getInstance(new FormatterContext(options.getOutputStream(), options.getFormatterProperties(), options.getRelationNames()))) {
161 c.executeQuery(options.getSQLCommand(), f);
166 private void processPrepareBatch() throws BatchException {
167 BatchEncoder enc = new BatchEncoder();
168 int length = enc.encode(options.getSQLCommand(), options.getOutputStream());
169 log.log(Level.FINE, "Prepared batch size: {0} bytes", length);
172 private void processExecuteBatch() throws ConfigurationException, SQLException, FormatterException, BatchException {
173 BatchDecoder dec = new BatchDecoder();
174 Batch b = dec.decode(options.getInputStream());
176 DatabaseDefinition dd = getConfiguration().getDatabase(options.getDatabaseName());
177 FormatterDefinition fd = configuration.getFormatter(options.getFormatterName());
178 ConnectionManagement jmxBean = ManagementUtils.registerMBean(dd.getName());
180 try (DatabaseConnection c = dd.connect(options.getDatabaseProperties(), jmxBean)) {
181 log.log(Level.FINE, "Database connected");
182 try (Formatter f = fd.getInstance(new FormatterContext(options.getOutputStream(), options.getFormatterProperties(), options.getRelationNames()))) {
183 c.executeBatch(b, f);
189 public Configuration getConfiguration() throws ConfigurationException {
190 if (configuration == null) {
191 configuration = configurationLoader.loadConfiguration();
193 return configuration;
196 private void installDefaultConfiguration() throws ConfigurationException {
197 Constants.DIR.mkdir();
199 if (Constants.CONFIG_FILE.exists()) {
200 log.log(Level.FINER, "Config file already exists: {0}", Constants.CONFIG_FILE);
203 Functions.installResource(Constants.EXAMPLE_CONFIG_FILE, Constants.CONFIG_FILE);
204 log.log(Level.FINE, "Installing default config file: {0}", Constants.CONFIG_FILE);
205 } catch (IOException e) {
206 throw new ConfigurationException("Unable to write example configuration to " + 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 writeBashCompletionHelperFileForFormatterProperties(new File(dir, "formatter-properties"));
221 } catch (Exception e) {
222 log.log(Level.WARNING, "Unable to generate Bash completion helper files", e);
227 private void writeBashCompletionHelperFile(Collection<? extends NameIdentified> items, File target) throws FileNotFoundException {
228 if (Constants.CONFIG_FILE.lastModified() > target.lastModified()) {
229 try (PrintWriter fw = new PrintWriter(target)) {
230 for (NameIdentified dd : items) {
231 fw.println(dd.getName());
234 log.log(Level.FINE, "Bash completion helper file was written: {0}", target);
237 log.log(Level.FINER, "Not writing Bash completion helper file: {0} because configuration {1} has not been changed", new Object[]{target, Constants.CONFIG_FILE});
241 private void writeBashCompletionHelperFileForFormatterProperties(File formattersDir) throws ClassNotFoundException, FileNotFoundException {
242 if (Constants.CONFIG_FILE.lastModified() > formattersDir.lastModified()) {
243 // TODO: delete old directory
244 formattersDir.mkdir();
245 for (FormatterDefinition fd : configuration.getAllFormatters()) {
246 File formatterDir = new File(formattersDir, fd.getName());
247 formatterDir.mkdir();
249 Class<Formatter> formatterClass = (Class<Formatter>) Class.forName(fd.getClassName());
250 List<Class<? extends Formatter>> hierarchy = Functions.getClassHierarchy(formatterClass, Formatter.class);
251 Collections.reverse(hierarchy);
252 for (Class<? extends Formatter> c : hierarchy) {
253 for (PropertyDeclaration p : Functions.getPropertyDeclarations(c)) {
254 File propertyDir = new File(formatterDir, p.name());
256 File choicesFile = new File(propertyDir, "choices");
257 try (PrintWriter fw = new PrintWriter(choicesFile)) {
258 // TODO: refactor, move
259 if (p.type() == Boolean.class) {
267 log.log(Level.FINE, "Bash completion helper files was written in: {0}", formattersDir);
269 log.log(Level.FINER, "Not writing Bash completion helper directory: {0} because configuration {1} has not been changed", new Object[]{formattersDir, Constants.CONFIG_FILE});