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
franta-hg@16
     1
/**
franta-hg@16
     2
 * SQL-DK
franta-hg@16
     3
 * Copyright © 2013 František Kučera (frantovo.cz)
franta-hg@16
     4
 *
franta-hg@16
     5
 * This program is free software: you can redistribute it and/or modify
franta-hg@16
     6
 * it under the terms of the GNU General Public License as published by
franta-hg@250
     7
 * the Free Software Foundation, version 3 of the License.
franta-hg@16
     8
 *
franta-hg@16
     9
 * This program is distributed in the hope that it will be useful,
franta-hg@16
    10
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
franta-hg@16
    11
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
franta-hg@16
    12
 * GNU General Public License for more details.
franta-hg@16
    13
 *
franta-hg@16
    14
 * You should have received a copy of the GNU General Public License
franta-hg@16
    15
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
franta-hg@16
    16
 */
franta-hg@1
    17
package info.globalcode.sql.dk;
franta-hg@1
    18
franta-hg@26
    19
import info.globalcode.sql.dk.configuration.ConfigurationProvider;
franta-hg@20
    20
import info.globalcode.sql.dk.CLIOptions.MODE;
franta-hg@146
    21
import info.globalcode.sql.dk.batch.Batch;
franta-hg@146
    22
import info.globalcode.sql.dk.batch.BatchDecoder;
franta-hg@144
    23
import info.globalcode.sql.dk.batch.BatchException;
franta-hg@144
    24
import info.globalcode.sql.dk.batch.BatchEncoder;
franta-hg@26
    25
import info.globalcode.sql.dk.configuration.Configuration;
franta-hg@33
    26
import info.globalcode.sql.dk.configuration.ConfigurationException;
franta-hg@34
    27
import info.globalcode.sql.dk.configuration.DatabaseDefinition;
franta-hg@34
    28
import info.globalcode.sql.dk.configuration.FormatterDefinition;
franta-hg@189
    29
import info.globalcode.sql.dk.configuration.Loader;
franta-hg@80
    30
import info.globalcode.sql.dk.configuration.NameIdentified;
franta-hg@220
    31
import info.globalcode.sql.dk.configuration.PropertyDeclaration;
franta-hg@34
    32
import info.globalcode.sql.dk.formatting.Formatter;
franta-hg@34
    33
import info.globalcode.sql.dk.formatting.FormatterContext;
franta-hg@34
    34
import info.globalcode.sql.dk.formatting.FormatterException;
franta-hg@179
    35
import info.globalcode.sql.dk.jmx.ConnectionManagement;
franta-hg@179
    36
import info.globalcode.sql.dk.jmx.ManagementUtils;
franta-hg@80
    37
import java.io.File;
franta-hg@80
    38
import java.io.FileNotFoundException;
franta-hg@33
    39
import java.io.IOException;
franta-hg@64
    40
import java.io.PrintStream;
franta-hg@80
    41
import java.io.PrintWriter;
franta-hg@34
    42
import java.sql.SQLException;
franta-hg@80
    43
import java.util.Collection;
franta-hg@220
    44
import java.util.Collections;
franta-hg@220
    45
import java.util.List;
franta-hg@13
    46
import java.util.logging.Level;
franta-hg@63
    47
import java.util.logging.LogRecord;
franta-hg@13
    48
import java.util.logging.Logger;
franta-hg@13
    49
franta-hg@1
    50
/**
franta-hg@155
    51
 * Entry point of the command line interface of SQL-DK.
franta-hg@1
    52
 *
franta-hg@1
    53
 * @author Ing. František Kučera (frantovo.cz)
franta-hg@1
    54
 */
franta-hg@20
    55
public class CLIStarter implements ConfigurationProvider {
franta-hg@1
    56
franta-hg@96
    57
	// help:exit-codes
franta-hg@95
    58
	public static final int EXIT_SUCCESS = 0; // doc:success
franta-hg@95
    59
	public static final int EXIT_UNEXPECTED_ERROR = 1; // doc:unexpected error (probably bug)
franta-hg@155
    60
	// 2 is reserved: http://www.tldp.org/LDP/abs/html/exitcodes.html#EXITCODESREF
franta-hg@95
    61
	public static final int EXIT_SQL_ERROR = 3; // doc:SQL error
franta-hg@95
    62
	public static final int EXIT_CLI_PARSE_ERROR = 4; // doc:CLI options parse error
franta-hg@95
    63
	public static final int EXIT_CLI_VALIDATE_ERROR = 5; // doc:CLI options validation error
franta-hg@95
    64
	public static final int EXIT_CONFIGURATION_ERROR = 6; // doc:configuration error
franta-hg@95
    65
	public static final int EXIT_FORMATTING_ERROR = 7; // doc:formatting error
franta-hg@149
    66
	public static final int EXIT_BATCH_ERROR = 8; // doc:batch error
franta-hg@13
    67
	private static final Logger log = Logger.getLogger(CLIStarter.class.getName());
franta-hg@189
    68
	private final CLIOptions options;
franta-hg@189
    69
	private final Loader configurationLoader = new Loader();
franta-hg@20
    70
	private Configuration configuration;
franta-hg@13
    71
franta-hg@1
    72
	public static void main(String[] args) {
franta-hg@55
    73
		log.log(Level.FINE, "Starting " + Constants.PROGRAM_NAME);
franta-hg@95
    74
		int exitCode;
franta-hg@63
    75
franta-hg@21
    76
		if (args.length == 0) {
franta-hg@21
    77
			args = new String[]{CLIParser.Tokens.INFO_HELP};
franta-hg@21
    78
		}
franta-hg@21
    79
franta-hg@13
    80
		try {
franta-hg@13
    81
			CLIParser parser = new CLIParser();
franta-hg@166
    82
			CLIOptions options = parser.parseOptions(args, System.in);
franta-hg@14
    83
			options.validate();
franta-hg@20
    84
			CLIStarter starter = new CLIStarter(options);
franta-hg@21
    85
			starter.installDefaultConfiguration();
franta-hg@20
    86
			starter.process();
franta-hg@55
    87
			log.log(Level.FINE, "All done");
franta-hg@56
    88
			exitCode = EXIT_SUCCESS;
franta-hg@13
    89
		} catch (CLIParserException e) {
franta-hg@14
    90
			log.log(Level.SEVERE, "Unable to parse CLI options", e);
franta-hg@95
    91
			exitCode = EXIT_CLI_PARSE_ERROR;
franta-hg@14
    92
		} catch (InvalidOptionsException e) {
franta-hg@14
    93
			log.log(Level.SEVERE, "Invalid CLI options", e);
franta-hg@48
    94
			for (InvalidOptionsException.OptionProblem p : e.getProblems()) {
franta-hg@63
    95
				LogRecord r = new LogRecord(Level.SEVERE, "Option problem: {0}");
franta-hg@63
    96
				r.setThrown(p.getException());
franta-hg@63
    97
				r.setParameters(new Object[]{p.getDescription()});
franta-hg@63
    98
				log.log(r);
franta-hg@48
    99
			}
franta-hg@95
   100
			exitCode = EXIT_CLI_VALIDATE_ERROR;
franta-hg@34
   101
		} catch (ConfigurationException e) {
franta-hg@34
   102
			log.log(Level.SEVERE, "Configuration problem", e);
franta-hg@95
   103
			exitCode = EXIT_CONFIGURATION_ERROR;
franta-hg@34
   104
		} catch (SQLException e) {
franta-hg@34
   105
			log.log(Level.SEVERE, "SQL problem", e);
franta-hg@56
   106
			exitCode = EXIT_SQL_ERROR;
franta-hg@34
   107
		} catch (FormatterException e) {
franta-hg@34
   108
			log.log(Level.SEVERE, "Formatting problem", e);
franta-hg@95
   109
			exitCode = EXIT_FORMATTING_ERROR;
franta-hg@144
   110
		} catch (BatchException e) {
franta-hg@144
   111
			log.log(Level.SEVERE, "Batch problem", e);
franta-hg@149
   112
			exitCode = EXIT_BATCH_ERROR;
franta-hg@13
   113
		}
franta-hg@56
   114
franta-hg@56
   115
		System.exit(exitCode);
franta-hg@4
   116
	}
franta-hg@20
   117
franta-hg@20
   118
	public CLIStarter(CLIOptions options) {
franta-hg@20
   119
		this.options = options;
franta-hg@20
   120
	}
franta-hg@20
   121
franta-hg@144
   122
	private void process() throws ConfigurationException, SQLException, FormatterException, BatchException {
franta-hg@64
   123
		MODE mode = options.getMode();
franta-hg@64
   124
franta-hg@20
   125
		/** Show info */
franta-hg@20
   126
		if (!options.getShowInfo().isEmpty()) {
franta-hg@64
   127
			PrintStream infoOut = mode == MODE.JUST_SHOW_INFO ? System.out : System.err;
franta-hg@69
   128
			InfoLister infoLister = new InfoLister(infoOut, this, options);
franta-hg@70
   129
			infoLister.showInfo();
franta-hg@20
   130
		}
franta-hg@20
   131
franta-hg@20
   132
		switch (mode) {
franta-hg@20
   133
			case QUERY_NOW:
franta-hg@34
   134
				processQueryNow();
franta-hg@20
   135
				break;
franta-hg@20
   136
			case PREPARE_BATCH:
franta-hg@34
   137
				processPrepareBatch();
franta-hg@20
   138
				break;
franta-hg@20
   139
			case EXECUTE_BATCH:
franta-hg@34
   140
				processExecuteBatch();
franta-hg@20
   141
				break;
franta-hg@20
   142
			case JUST_SHOW_INFO:
franta-hg@20
   143
				// already done above
franta-hg@20
   144
				break;
franta-hg@20
   145
			default:
franta-hg@20
   146
				log.log(Level.SEVERE, "Unsupported mode: {0}", mode);
franta-hg@20
   147
				break;
franta-hg@20
   148
		}
franta-hg@80
   149
franta-hg@80
   150
		generateBashCompletion();
franta-hg@20
   151
	}
franta-hg@20
   152
franta-hg@34
   153
	private void processQueryNow() throws ConfigurationException, SQLException, FormatterException {
franta-hg@34
   154
		DatabaseDefinition dd = getConfiguration().getDatabase(options.getDatabaseName());
franta-hg@75
   155
		FormatterDefinition fd = configuration.getFormatter(options.getFormatterName());
franta-hg@179
   156
		ConnectionManagement jmxBean = ManagementUtils.registerMBean(dd.getName());
franta-hg@179
   157
franta-hg@179
   158
		try (DatabaseConnection c = dd.connect(options.getDatabaseProperties(), jmxBean)) {
franta-hg@75
   159
			log.log(Level.FINE, "Database connected");
franta-hg@246
   160
			try (Formatter f = fd.getInstance(new FormatterContext(options.getOutputStream(), options.getFormatterProperties(), options.getRelationNames()))) {
franta-hg@101
   161
				c.executeQuery(options.getSQLCommand(), f);
franta-hg@101
   162
			}
franta-hg@34
   163
		}
franta-hg@34
   164
	}
franta-hg@34
   165
franta-hg@144
   166
	private void processPrepareBatch() throws BatchException {
franta-hg@144
   167
		BatchEncoder enc = new BatchEncoder();
franta-hg@144
   168
		int length = enc.encode(options.getSQLCommand(), options.getOutputStream());
franta-hg@144
   169
		log.log(Level.FINE, "Prepared batch size: {0} bytes", length);
franta-hg@34
   170
	}
franta-hg@34
   171
franta-hg@146
   172
	private void processExecuteBatch() throws ConfigurationException, SQLException, FormatterException, BatchException {
franta-hg@146
   173
		BatchDecoder dec = new BatchDecoder();
franta-hg@146
   174
		Batch b = dec.decode(options.getInputStream());
franta-hg@146
   175
franta-hg@146
   176
		DatabaseDefinition dd = getConfiguration().getDatabase(options.getDatabaseName());
franta-hg@146
   177
		FormatterDefinition fd = configuration.getFormatter(options.getFormatterName());
franta-hg@179
   178
		ConnectionManagement jmxBean = ManagementUtils.registerMBean(dd.getName());
franta-hg@179
   179
franta-hg@179
   180
		try (DatabaseConnection c = dd.connect(options.getDatabaseProperties(), jmxBean)) {
franta-hg@146
   181
			log.log(Level.FINE, "Database connected");
franta-hg@246
   182
			try (Formatter f = fd.getInstance(new FormatterContext(options.getOutputStream(), options.getFormatterProperties(), options.getRelationNames()))) {
franta-hg@146
   183
				c.executeBatch(b, f);
franta-hg@146
   184
			}
franta-hg@146
   185
		}
franta-hg@34
   186
	}
franta-hg@34
   187
franta-hg@20
   188
	@Override
franta-hg@33
   189
	public Configuration getConfiguration() throws ConfigurationException {
franta-hg@20
   190
		if (configuration == null) {
franta-hg@189
   191
			configuration = configurationLoader.loadConfiguration();
franta-hg@20
   192
		}
franta-hg@20
   193
		return configuration;
franta-hg@20
   194
	}
franta-hg@20
   195
franta-hg@34
   196
	private void installDefaultConfiguration() throws ConfigurationException {
franta-hg@33
   197
		Constants.DIR.mkdir();
franta-hg@33
   198
franta-hg@33
   199
		if (Constants.CONFIG_FILE.exists()) {
franta-hg@55
   200
			log.log(Level.FINER, "Config file already exists: {0}", Constants.CONFIG_FILE);
franta-hg@33
   201
		} else {
franta-hg@33
   202
			try {
franta-hg@33
   203
				Functions.installResource(Constants.EXAMPLE_CONFIG_FILE, Constants.CONFIG_FILE);
franta-hg@55
   204
				log.log(Level.FINE, "Installing default config file: {0}", Constants.CONFIG_FILE);
franta-hg@33
   205
			} catch (IOException e) {
franta-hg@34
   206
				throw new ConfigurationException("Unable to write example configuration to " + Constants.CONFIG_FILE, e);
franta-hg@33
   207
			}
franta-hg@33
   208
		}
franta-hg@20
   209
	}
franta-hg@20
   210
franta-hg@80
   211
	private void generateBashCompletion() {
franta-hg@80
   212
		if (configuration == null) {
franta-hg@80
   213
			log.log(Level.FINER, "Not writing Bash completion helper files. In order to generate these files please run some command which requires configuration.");
franta-hg@80
   214
		} else {
franta-hg@80
   215
			try {
franta-hg@80
   216
				File dir = new File(Constants.DIR, "bash-completion");
franta-hg@80
   217
				dir.mkdir();
franta-hg@80
   218
				writeBashCompletionHelperFile(configuration.getDatabases(), new File(dir, "databases"));
franta-hg@80
   219
				writeBashCompletionHelperFile(configuration.getAllFormatters(), new File(dir, "formatters"));
franta-hg@220
   220
				writeBashCompletionHelperFileForFormatterProperties(new File(dir, "formatter-properties"));
franta-hg@80
   221
			} catch (Exception e) {
franta-hg@80
   222
				log.log(Level.WARNING, "Unable to generate Bash completion helper files", e);
franta-hg@80
   223
			}
franta-hg@80
   224
		}
franta-hg@80
   225
	}
franta-hg@80
   226
franta-hg@80
   227
	private void writeBashCompletionHelperFile(Collection<? extends NameIdentified> items, File target) throws FileNotFoundException {
franta-hg@80
   228
		if (Constants.CONFIG_FILE.lastModified() > target.lastModified()) {
franta-hg@80
   229
			try (PrintWriter fw = new PrintWriter(target)) {
franta-hg@80
   230
				for (NameIdentified dd : items) {
franta-hg@80
   231
					fw.println(dd.getName());
franta-hg@80
   232
				}
franta-hg@80
   233
				fw.close();
franta-hg@80
   234
				log.log(Level.FINE, "Bash completion helper file was written: {0}", target);
franta-hg@80
   235
			}
franta-hg@80
   236
		} else {
franta-hg@80
   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});
franta-hg@80
   238
		}
franta-hg@80
   239
	}
franta-hg@220
   240
franta-hg@221
   241
	private void writeBashCompletionHelperFileForFormatterProperties(File formattersDir) throws ClassNotFoundException, FileNotFoundException {
franta-hg@220
   242
		if (Constants.CONFIG_FILE.lastModified() > formattersDir.lastModified()) {
franta-hg@220
   243
			// TODO: delete old directory
franta-hg@220
   244
			formattersDir.mkdir();
franta-hg@220
   245
			for (FormatterDefinition fd : configuration.getAllFormatters()) {
franta-hg@220
   246
				File formatterDir = new File(formattersDir, fd.getName());
franta-hg@220
   247
				formatterDir.mkdir();
franta-hg@220
   248
franta-hg@220
   249
				Class<Formatter> formatterClass = (Class<Formatter>) Class.forName(fd.getClassName());
franta-hg@220
   250
				List<Class<? extends Formatter>> hierarchy = Functions.getClassHierarchy(formatterClass, Formatter.class);
franta-hg@220
   251
				Collections.reverse(hierarchy);
franta-hg@221
   252
				for (Class<? extends Formatter> c : hierarchy) {
franta-hg@220
   253
					for (PropertyDeclaration p : Functions.getPropertyDeclarations(c)) {
franta-hg@220
   254
						File propertyDir = new File(formatterDir, p.name());
franta-hg@220
   255
						propertyDir.mkdir();
franta-hg@221
   256
						File choicesFile = new File(propertyDir, "choices");
franta-hg@221
   257
						try (PrintWriter fw = new PrintWriter(choicesFile)) {
franta-hg@221
   258
							// TODO: refactor, move
franta-hg@221
   259
							if (p.type() == Boolean.class) {
franta-hg@221
   260
								fw.println("true");
franta-hg@221
   261
								fw.println("false");
franta-hg@221
   262
							}
franta-hg@221
   263
						}
franta-hg@220
   264
					}
franta-hg@221
   265
				}
franta-hg@220
   266
			}
franta-hg@220
   267
			log.log(Level.FINE, "Bash completion helper files was written in: {0}", formattersDir);
franta-hg@220
   268
		} else {
franta-hg@220
   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});
franta-hg@220
   270
		}
franta-hg@220
   271
franta-hg@220
   272
	}
franta-hg@1
   273
}