java/sql-dk/src/main/java/info/globalcode/sql/dk/CLIStarter.java
author František Kučera <franta-hg@frantovo.cz>
Thu, 24 Oct 2019 21:43:08 +0200
branchv_0
changeset 250 aae5009bd0af
parent 246 277c18b48762
permissions -rw-r--r--
fix license version: GNU GPLv3
     1 /**
     2  * SQL-DK
     3  * Copyright © 2013 František Kučera (frantovo.cz)
     4  *
     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.
     8  *
     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.
    13  *
    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/>.
    16  */
    17 package info.globalcode.sql.dk;
    18 
    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;
    37 import java.io.File;
    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;
    49 
    50 /**
    51  * Entry point of the command line interface of SQL-DK.
    52  *
    53  * @author Ing. František Kučera (frantovo.cz)
    54  */
    55 public class CLIStarter implements ConfigurationProvider {
    56 
    57 	// help:exit-codes
    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;
    71 
    72 	public static void main(String[] args) {
    73 		log.log(Level.FINE, "Starting " + Constants.PROGRAM_NAME);
    74 		int exitCode;
    75 
    76 		if (args.length == 0) {
    77 			args = new String[]{CLIParser.Tokens.INFO_HELP};
    78 		}
    79 
    80 		try {
    81 			CLIParser parser = new CLIParser();
    82 			CLIOptions options = parser.parseOptions(args, System.in);
    83 			options.validate();
    84 			CLIStarter starter = new CLIStarter(options);
    85 			starter.installDefaultConfiguration();
    86 			starter.process();
    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()});
    98 				log.log(r);
    99 			}
   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;
   113 		}
   114 
   115 		System.exit(exitCode);
   116 	}
   117 
   118 	public CLIStarter(CLIOptions options) {
   119 		this.options = options;
   120 	}
   121 
   122 	private void process() throws ConfigurationException, SQLException, FormatterException, BatchException {
   123 		MODE mode = options.getMode();
   124 
   125 		/** Show info */
   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();
   130 		}
   131 
   132 		switch (mode) {
   133 			case QUERY_NOW:
   134 				processQueryNow();
   135 				break;
   136 			case PREPARE_BATCH:
   137 				processPrepareBatch();
   138 				break;
   139 			case EXECUTE_BATCH:
   140 				processExecuteBatch();
   141 				break;
   142 			case JUST_SHOW_INFO:
   143 				// already done above
   144 				break;
   145 			default:
   146 				log.log(Level.SEVERE, "Unsupported mode: {0}", mode);
   147 				break;
   148 		}
   149 
   150 		generateBashCompletion();
   151 	}
   152 
   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());
   157 
   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);
   162 			}
   163 		}
   164 	}
   165 
   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);
   170 	}
   171 
   172 	private void processExecuteBatch() throws ConfigurationException, SQLException, FormatterException, BatchException {
   173 		BatchDecoder dec = new BatchDecoder();
   174 		Batch b = dec.decode(options.getInputStream());
   175 
   176 		DatabaseDefinition dd = getConfiguration().getDatabase(options.getDatabaseName());
   177 		FormatterDefinition fd = configuration.getFormatter(options.getFormatterName());
   178 		ConnectionManagement jmxBean = ManagementUtils.registerMBean(dd.getName());
   179 
   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);
   184 			}
   185 		}
   186 	}
   187 
   188 	@Override
   189 	public Configuration getConfiguration() throws ConfigurationException {
   190 		if (configuration == null) {
   191 			configuration = configurationLoader.loadConfiguration();
   192 		}
   193 		return configuration;
   194 	}
   195 
   196 	private void installDefaultConfiguration() throws ConfigurationException {
   197 		Constants.DIR.mkdir();
   198 
   199 		if (Constants.CONFIG_FILE.exists()) {
   200 			log.log(Level.FINER, "Config file already exists: {0}", Constants.CONFIG_FILE);
   201 		} else {
   202 			try {
   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);
   207 			}
   208 		}
   209 	}
   210 
   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.");
   214 		} else {
   215 			try {
   216 				File dir = new File(Constants.DIR, "bash-completion");
   217 				dir.mkdir();
   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);
   223 			}
   224 		}
   225 	}
   226 
   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());
   232 				}
   233 				fw.close();
   234 				log.log(Level.FINE, "Bash completion helper file was written: {0}", target);
   235 			}
   236 		} else {
   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});
   238 		}
   239 	}
   240 
   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();
   248 
   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());
   255 						propertyDir.mkdir();
   256 						File choicesFile = new File(propertyDir, "choices");
   257 						try (PrintWriter fw = new PrintWriter(choicesFile)) {
   258 							// TODO: refactor, move
   259 							if (p.type() == Boolean.class) {
   260 								fw.println("true");
   261 								fw.println("false");
   262 							}
   263 						}
   264 					}
   265 				}
   266 			}
   267 			log.log(Level.FINE, "Bash completion helper files was written in: {0}", formattersDir);
   268 		} else {
   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});
   270 		}
   271 
   272 	}
   273 }