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