List of usage examples for org.apache.commons.cli Options Options
Options
From source file:com.addthis.bark.ZkCmdLine.java
public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption("h", "help", false, "something helpful."); options.addOption("z", "zk", true, "zk servers,port"); options.addOption("c", "chroot", true, "chroot"); options.addOption("n", "znode", true, "znode"); options.addOption("d", "dir", true, "directory root"); options.addOption("p", "put-data", true, "directory root"); // for copying options.addOption("", "to-zk", true, "zk servers,port"); options.addOption("", "to-chroot", true, "chroot"); options.addOption("", "to-znode", true, "znode"); CommandLineParser parser = new PosixParser(); CommandLine cmdline = null;/* w w w. j ava 2s . co m*/ try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Parsing failed. Reason: " + exp.getMessage()); System.exit(0); } HelpFormatter formatter = new HelpFormatter(); if (cmdline.hasOption("help") || cmdline.getArgList().size() < 1) { System.out.println("commands: get jclean jcleanrecur kids grandkids"); formatter.printHelp("ZkCmdLine", options); System.exit(0); } ZkCmdLine zkcl = new ZkCmdLine(cmdline); zkcl.runCmd((String) cmdline.getArgList().get(0)); }
From source file:dk.netarkivet.harvester.tools.CreateIndex.java
/** * The main method that does the parsing of the commandline, and makes the actual index request. * * @param args the arguments// w w w.j a v a2s . c o m */ public static void main(String[] args) { Options options = new Options(); CommandLineParser parser = new PosixParser(); CommandLine cmd = null; Option indexType = new Option("t", "type", true, "Type of index"); Option jobList = new Option("l", "jobids", true, "list of jobids"); indexType.setRequired(true); jobList.setRequired(true); options.addOption(indexType); options.addOption(jobList); try { // parse the command line arguments cmd = parser.parse(options, args); } catch (MissingOptionException e) { System.err.println("Some of the required parameters are missing: " + e.getMessage()); dieWithUsage(); } catch (ParseException exp) { System.err.println("Parsing of parameters failed: " + exp.getMessage()); dieWithUsage(); } String typeValue = cmd.getOptionValue(INDEXTYPE_OPTION); String jobidsValue = cmd.getOptionValue(JOBIDS_OPTION); String[] jobidsAsStrings = jobidsValue.split(","); Set<Long> jobIDs = new HashSet<Long>(); for (String idAsString : jobidsAsStrings) { jobIDs.add(Long.valueOf(idAsString)); } JobIndexCache cache = null; String indexTypeAstring = ""; if (typeValue.equalsIgnoreCase("CDX")) { indexTypeAstring = "CDX"; cache = IndexClientFactory.getCDXInstance(); } else if (typeValue.equalsIgnoreCase("DEDUP")) { indexTypeAstring = "DEDUP"; cache = IndexClientFactory.getDedupCrawllogInstance(); } else if (typeValue.equalsIgnoreCase("CRAWLLOG")) { indexTypeAstring = "CRAWLLOG"; cache = IndexClientFactory.getFullCrawllogInstance(); } else { System.err.println("Unknown indextype '" + typeValue + "' requested."); dieWithUsage(); } System.out.println("Creating " + indexTypeAstring + " index for ids: " + jobIDs); Index<Set<Long>> index = cache.getIndex(jobIDs); JMSConnectionFactory.getInstance().cleanup(); }
From source file:net.sf.mpaxs.test.ImpaxsExecution.java
/** * * @param args/*from w w w . j av a2 s. com*/ */ public static void main(String[] args) { Options options = new Options(); Option[] optionArray = new Option[] { OptionBuilder.withArgName("nhosts").hasArg() .withDescription("Number of hosts for parallel processing").create("n"), OptionBuilder.withArgName("mjobs").hasArg().withDescription("Number of jobs to run in parallel") .create("m"), OptionBuilder.withArgName("runmode").hasArg() .withDescription("The mode in which to operate: one of <ALL,LOCAL,DISTRIBUTED>") .create("r"), // OptionBuilder.withArgName("gui"). // withDescription("Create gui for distributed execution").create("g") }; for (Option opt : optionArray) { options.addOption(opt); } if (args.length == 0) { HelpFormatter hf = new HelpFormatter(); hf.printHelp(StartUp.class.getCanonicalName(), options, true); System.exit(1); } GnuParser gp = new GnuParser(); int nhosts = 1; int mjobs = 10; boolean gui = false; Mode mode = Mode.ALL; try { CommandLine cl = gp.parse(options, args); if (cl.hasOption("n")) { nhosts = Integer.parseInt(cl.getOptionValue("n")); } if (cl.hasOption("m")) { mjobs = Integer.parseInt(cl.getOptionValue("m")); } if (cl.hasOption("r")) { mode = Mode.valueOf(cl.getOptionValue("r")); } // if (cl.hasOption("g")) { // gui = true; // } } catch (Exception ex) { Logger.getLogger(StartUp.class.getName()).log(Level.SEVERE, null, ex); HelpFormatter hf = new HelpFormatter(); hf.printHelp(StartUp.class.getCanonicalName(), options, true); System.exit(1); } String version; try { version = net.sf.mpaxs.api.Version.getVersion(); System.out.println("Running mpaxs " + version); File computeHostJarLocation = new File(System.getProperty("user.dir"), "mpaxs.jar"); if (!computeHostJarLocation.exists() || !computeHostJarLocation.isFile()) { throw new IOException("Could not locate mpaxs.jar in " + System.getProperty("user.dir")); } final PropertiesConfiguration cfg = new PropertiesConfiguration(); //set default execution type cfg.setProperty(ConfigurationKeys.KEY_EXECUTION_MODE, ExecutionType.DRMAA); //set location of compute host jar cfg.setProperty(ConfigurationKeys.KEY_PATH_TO_COMPUTEHOST_JAR, computeHostJarLocation); //do not exit to console when master server shuts down cfg.setProperty(ConfigurationKeys.KEY_MASTER_SERVER_EXIT_ON_SHUTDOWN, false); //limit the number of used compute hosts cfg.setProperty(ConfigurationKeys.KEY_MAX_NUMBER_OF_CHOSTS, nhosts); cfg.setProperty(ConfigurationKeys.KEY_NATIVE_SPEC, ""); cfg.setProperty(ConfigurationKeys.KEY_GUI_MODE, gui); cfg.setProperty(ConfigurationKeys.KEY_SILENT_MODE, true); cfg.setProperty(ConfigurationKeys.KEY_SCHEDULE_WAIT_TIME, "500"); final int maxJobs = mjobs; final int maxThreads = nhosts; final Mode runMode = mode; printMessage("Run mode: " + runMode); Executors.newSingleThreadExecutor().submit(new Runnable() { @Override public void run() { if (runMode == Mode.ALL || runMode == Mode.LOCAL) { printMessage("Running Within VM Execution"); /* * LOCAL within VM execution */ WithinVmExecution lhe = new WithinVmExecution(maxJobs, maxThreads); try { Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.INFO, "Sum is: " + lhe.call()); } catch (Exception ex) { Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.SEVERE, null, ex); } } if (runMode == Mode.ALL || runMode == Mode.DISTRIBUTED) { printMessage("Running Distributed Host RMI Execution"); /* * Grid Engine (DRMAA API) or local host distributed RMI execution */ DistributedRmiExecution de = new DistributedRmiExecution(cfg, maxJobs); try { Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.INFO, "Sum is: " + de.call()); } catch (Exception ex) { Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.SEVERE, null, ex); } } System.exit(0); } }); } catch (IOException ex) { Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.galois.fiveui.HeadlessRunner.java
/** * @param args list of headless run description filenames * @throws IOException//from w ww. ja va2s .c om * @throws URISyntaxException * @throws ParseException */ @SuppressWarnings("static-access") public static void main(final String[] args) throws IOException, URISyntaxException, ParseException { // Setup command line options Options options = new Options(); Option help = new Option("h", "print this help message"); Option output = OptionBuilder.withArgName("outfile").hasArg().withDescription("write output to file") .create("o"); Option report = OptionBuilder.withArgName("report directory").hasArg() .withDescription("write HTML reports to given directory").create("r"); options.addOption(output); options.addOption(report); options.addOption("v", false, "verbose output"); options.addOption("vv", false, "VERY verbose output"); options.addOption(help); // Parse command line options CommandLineParser parser = new GnuParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.err.println("Command line option parsing failed. Reason: " + e.getMessage()); System.exit(1); } // Display help if requested if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("headless <input file 1> [<input file 2> ...]", options); System.exit(1); } // Set logging levels BasicConfigurator.configure(); Logger fiveuiLogger = Logger.getLogger("com.galois.fiveui"); Logger rootLogger = Logger.getRootLogger(); if (cmd.hasOption("v")) { fiveuiLogger.setLevel(Level.DEBUG); rootLogger.setLevel(Level.ERROR); } else if (cmd.hasOption("vv")) { fiveuiLogger.setLevel(Level.DEBUG); rootLogger.setLevel(Level.DEBUG); } else { fiveuiLogger.setLevel(Level.ERROR); rootLogger.setLevel(Level.ERROR); } // Setup output file if requested PrintWriter outStream = null; if (cmd.hasOption("o")) { String outfile = cmd.getOptionValue("o"); try { outStream = new PrintWriter(new BufferedWriter(new FileWriter(outfile))); } catch (IOException e) { System.err.println("Could not open outfile for writing: " + cmd.getOptionValue("outfile")); System.exit(1); } } else { outStream = new PrintWriter(new BufferedWriter(new PrintWriter(System.out))); } // Setup HTML reports directory before the major work happens in case we // have to throw an exception. PrintWriter summaryFile = null; PrintWriter byURLFile = null; PrintWriter byRuleFile = null; if (cmd.hasOption("r")) { String repDir = cmd.getOptionValue("r"); try { File file = new File(repDir); if (!file.exists()) { file.mkdir(); logger.info("report directory created: " + repDir); } else { logger.info("report directory already exists!"); } summaryFile = new PrintWriter(new FileWriter(repDir + File.separator + "summary.html")); byURLFile = new PrintWriter(new FileWriter(repDir + File.separator + "byURL.html")); byRuleFile = new PrintWriter(new FileWriter(repDir + File.separator + "byRule.html")); } catch (IOException e) { System.err.println("could not open report directory / files for writing"); System.exit(1); } } // Major work: process input files ImmutableList<Result> results = null; for (String in : cmd.getArgs()) { HeadlessRunDescription descr = HeadlessRunDescription.parse(in); logger.debug("invoking headless run..."); BatchRunner runner = new BatchRunner(); results = runner.runHeadless(descr); logger.debug("runHeadless returned " + results.size() + " results"); // write results to the output stream as we go for (Result result : results) { outStream.println(result.toString()); } outStream.flush(); } outStream.close(); // Write report files if requested if (cmd.hasOption("r") && results != null) { Reporter kermit = new Reporter(results); summaryFile.write(kermit.getSummary()); summaryFile.close(); byURLFile.write(kermit.getByURL()); byURLFile.close(); byRuleFile.write(kermit.getByRule()); byRuleFile.close(); } }
From source file:com.versusoft.packages.jodl.gui.CommandLineGUI.java
public static void main(String args[]) throws SAXException, IOException { Handler fh = new FileHandler(LOG_FILENAME_PATTERN); fh.setFormatter(new SimpleFormatter()); //removeAllLoggersHandlers(Logger.getLogger("")); Logger.getLogger("").addHandler(fh); Logger.getLogger("").setLevel(Level.FINEST); Options options = new Options(); Option option1 = new Option("in", "ODT file (required)"); option1.setRequired(true);//from w w w . j a va 2s. com option1.setArgs(1); Option option2 = new Option("out", "Output file (required)"); option2.setRequired(false); option2.setArgs(1); Option option3 = new Option("pic", "extract pics"); option3.setRequired(false); option3.setArgs(1); Option option4 = new Option("page", "enable pagination processing"); option4.setRequired(false); option4.setArgs(0); options.addOption(option1); options.addOption(option2); options.addOption(option3); options.addOption(option4); CommandLineParser parser = new BasicParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e) { printHelp(); return; } if (cmd.hasOption("help")) { printHelp(); return; } File outFile = new File(cmd.getOptionValue("out")); OdtUtils utils = new OdtUtils(); utils.open(cmd.getOptionValue("in")); //utils.correctionStep(); utils.saveXML(outFile.getAbsolutePath()); try { if (cmd.hasOption("page")) { OdtUtils.paginationProcessing(outFile.getAbsolutePath()); } OdtUtils.correctionProcessing(outFile.getAbsolutePath()); } catch (ParserConfigurationException ex) { logger.log(Level.SEVERE, null, ex); } catch (SAXException ex) { logger.log(Level.SEVERE, null, ex); } catch (IOException ex) { logger.log(Level.SEVERE, null, ex); } catch (TransformerConfigurationException ex) { logger.log(Level.SEVERE, null, ex); } catch (TransformerException ex) { logger.log(Level.SEVERE, null, ex); } if (cmd.hasOption("pic")) { String imageDir = cmd.getOptionValue("pic"); if (!imageDir.endsWith("/")) { imageDir += "/"; } try { String basedir = new File(cmd.getOptionValue("out")).getParent().toString() + System.getProperty("file.separator"); OdtUtils.extractAndNormalizeEmbedPictures(cmd.getOptionValue("out"), cmd.getOptionValue("in"), basedir, imageDir); } catch (SAXException ex) { logger.log(Level.SEVERE, null, ex); } catch (ParserConfigurationException ex) { logger.log(Level.SEVERE, null, ex); } catch (TransformerConfigurationException ex) { logger.log(Level.SEVERE, null, ex); } catch (TransformerException ex) { logger.log(Level.SEVERE, null, ex); } } }
From source file:cloudlens.cli.Main.java
public static void main(String[] args) throws Exception { final CommandLineParser optionParser = new DefaultParser(); final HelpFormatter formatter = new HelpFormatter(); final Option lens = Option.builder("r").longOpt("run").hasArg().argName("lens file").desc("Lens file.") .required(true).build();// ww w .j ava2 s. c o m final Option log = Option.builder("l").longOpt("log").hasArg().argName("log file").desc("Log file.") .build(); final Option jsonpath = Option.builder().longOpt("jsonpath").hasArg().argName("path") .desc("Path to logs in a json object.").build(); final Option js = Option.builder().longOpt("js").hasArg().argName("js file").desc("Load JS file.").build(); final Option format = Option.builder("f").longOpt("format").hasArg() .desc("Choose log format (text or json).").build(); final Option streaming = Option.builder().longOpt("stream").desc("Streaming mode.").build(); final Option history = Option.builder().longOpt("history").desc("Store history.").build(); final Options options = new Options(); options.addOption(log); options.addOption(lens); options.addOption(format); options.addOption(jsonpath); options.addOption(js); options.addOption(streaming); options.addOption(history); try { final CommandLine cmd = optionParser.parse(options, args); final String jsonPath = cmd.getOptionValue("jsonpath"); final String[] jsFiles = cmd.getOptionValues("js"); final String[] lensFiles = cmd.getOptionValues("run"); final String[] logFiles = cmd.getOptionValues("log"); final String source = cmd.getOptionValue("format"); final boolean stream = cmd.hasOption("stream") || !cmd.hasOption("log"); final boolean withHistory = cmd.hasOption("history") || !stream; final CL cl = new CL(System.out, System.err, stream, withHistory); try { final InputStream input = (cmd.hasOption("log")) ? FileReader.readFiles(logFiles) : System.in; if (source == null) { cl.source(input); } else { switch (source) { case "text": cl.source(input); break; case "json": cl.json(input, jsonPath); break; default: input.close(); throw new CLException("Unsupported format: " + source); } } for (final String jsFile : FileReader.fullPaths(jsFiles)) { cl.engine.eval("CL.loadjs('file://" + jsFile + "')"); } final List<ASTElement> top = ASTBuilder.parseFiles(lensFiles); cl.launch(top); } catch (final CLException | ASTException e) { cl.errWriter.println(e.getMessage()); } finally { cl.outWriter.flush(); cl.errWriter.flush(); } } catch (final ParseException e) { System.err.println(e.getMessage()); formatter.printHelp("cloudlens", options); } }
From source file:de.bayern.gdi.App.java
/** * @param args the command line arguments *///from ww w .j a v a 2 s .c o m public static void main(String[] args) { Options options = new Options(); Option help = Option.builder("?").hasArg(false).longOpt("help").desc("Print this message and exit.") .build(); Option headless = Option.builder("h").hasArg(false).longOpt("headless").desc("Start command line tool.") .build(); Option conf = Option.builder("c").hasArg(true).longOpt("config") .desc("Directory to overwrite default configuration.").build(); Option user = Option.builder("u").hasArg(true).longOpt("user").desc("User name for protected services.") .build(); Option password = Option.builder("p").hasArg(true).longOpt("password") .desc("Password for protected services.").build(); options.addOption(help); options.addOption(headless); options.addOption(conf); options.addOption(user); options.addOption(password); CommandLineParser parser = new DefaultParser(); try { CommandLine line = parser.parse(options, args); if (line.hasOption("?")) { usage(options, 0); } if (line.hasOption("h")) { // First initialize log4j for headless execution final String pid = getProcessId("0"); System.setProperty("logfilename", "logdlc-" + pid + ".txt"); } // use configuration for gui and headless mode initConfig(line.getOptionValue("c")); if (line.hasOption("h")) { System.exit(Headless.main(line.getArgs(), line.getOptionValue("u"), line.getOptionValue("p"))); } startGUI(); } catch (ParseException pe) { System.err.println("Cannot parse input: " + pe.getMessage()); usage(options, 1); } }
From source file:de.citec.csra.highlight.HighlightService.java
public static void main(String[] args) throws InitializeException, RSBException, InterruptedException, ParseException { Options opts = new Options(); opts.addOption("scope", true, "RSB scope for highlight targets.\nDefault: '" + scope + "'"); opts.addOption("server", true, "RSB server for configuration, e.g., tokens.\nDefault: '" + cfg + "'"); opts.addOption("help", false, "Print this help and exit"); String footer = null;//from w ww .ja v a2 s . c o m // String footer = "\nThe following sub-scopes are registered automatically:\n" // + "\n.../preset for color presets:\n" + Arrays.toString(ColorConfig.values()) // + "\n.../color for color values:\n" + "HSV (comma separated)" // + "\n.../power for power states:\n" + Arrays.toString(PowerState.State.values()) // + "\n.../history for history commands:\n" + Arrays.toString(ColorHistory.values()); CommandLineParser parser = new BasicParser(); CommandLine cmd = parser.parse(opts, args); if (cmd.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("csra-highlight-service [OPTION...]", "where OPTION includes:", opts, footer); System.exit(0); } if (System.getenv().containsKey(SCOPEVAR)) { scope = System.getenv(SCOPEVAR); } String s = cmd.getOptionValue("scope"); if (s != null) { scope = s; } scope = scope.replaceAll("/$", ""); String c = cmd.getOptionValue("cfg"); if (c != null) { cfg = c; } cfg = cfg.replaceAll("/$", ""); Defaults.loadDefaults(); ExecutorService exec = Executors.newFixedThreadPool(2); exec.submit(() -> { try { ConfigServer cfgServer = new ConfigServer(cfg); cfgServer.execute(); } catch (RSBException ex) { LOG.log(Level.SEVERE, "Config server failed", ex); } }); exec.submit(() -> { try { TaskServer server = new TaskServer(scope, new HighlightTaskHandler()); server.execute(); } catch (RSBException | InterruptedException ex) { LOG.log(Level.SEVERE, "Task server failed", ex); } }); }
From source file:com.github.codingtogenomic.CodingToGenomic.java
public static void main(String[] args) throws Exception { //parse commandline Options options = new Options(); CommandLineParser parser = new PosixParser(); String gene = new String(); String transcript = new String(); String species = "human"; boolean mapCdna = false; String coordinate = new String(); StringBuilder errorMsg = new StringBuilder(); try {/*from w w w . j ava 2 s . co m*/ options = getOptions(args); } catch (org.apache.commons.cli.ParseException ex) { System.err.println("Parsing failed. Reason: " + ex.getMessage()); System.exit(1); } CommandLine line = parser.parse(options, args); if (line.hasOption("help")) { showHelp(options); } if (line.hasOption("gene")) { gene = line.getOptionValue("gene"); } else { if (!line.hasOption("transcript")) { errorMsg.append("Either --gene or --transcript argument is required\n"); } } if (line.hasOption("transcript")) { if (line.hasOption("gene")) { errorMsg.append("Please specify only one of " + "--gene or --transcript arguments, not both\n"); } else { transcript = line.getOptionValue("transcript"); if (line.hasOption("species")) { System.out.println("Ignoring --species option when using --transcript argument"); } } } if (line.hasOption("coordinate")) { coordinate = line.getOptionValue("coordinate"); } else { errorMsg.append("--coordinate argument is required\n"); } if (line.hasOption("species")) { species = line.getOptionValue("species").replaceAll("\\s+", "_"); } if (line.hasOption("b37")) { if (species.equalsIgnoreCase("human") || species.equalsIgnoreCase("homo sapiens")) { SERVER = GRCh37Server; } else { System.out.println("--b37 argument will be ignored - it can only be " + "used when human is the species of interest. Current species" + " is " + species + ".\n"); } } if (line.hasOption("noncoding")) { mapCdna = true; } if (errorMsg.length() > 0) { showHelp(options, errorMsg.toString(), 2); } int c = 0; boolean threePrimeUtr = false; String prefix = "c."; if (mapCdna) { prefix = "n."; try { c = Integer.parseInt(coordinate); } catch (NumberFormatException ex) { showHelp(options, "--coordinate argument '" + coordinate + "' could not " + "be parsed as an integer", 2); } } else if (coordinate.startsWith("*")) { threePrimeUtr = true; prefix = "c.*"; String coord = coordinate.replaceFirst("\\*", ""); try { c = Integer.parseInt(coord); } catch (NumberFormatException ex) { showHelp(options, "--coordinate argument '" + coordinate + "' could not " + "be parsed as an integer or UTR coordinate", 2); } } else { try { c = Integer.parseInt(coordinate); } catch (NumberFormatException ex) { showHelp(options, "--coordinate argument '" + coordinate + "' could not " + "be parsed as an integer", 2); } } //got arguments String result; String header = "Input\tSymbol\tEnsemblGene\tEnsemblTranscript\tGenomicCoordinate"; if (!gene.isEmpty()) { IdParser idParser = new IdParser(gene); System.out.println("Interpretting " + gene + " as of type " + idParser.getIdentifierType()); if (idParser.isEnsemblId()) { if (line.hasOption("species")) { System.out.println("Ignoring --species option when searching Ensembl ID."); } if (idParser.isTranscript()) { result = codingToGenomicTranscript(gene, c, threePrimeUtr, mapCdna); } else if (idParser.isEnsp()) { result = codingToGenomicEnsp(gene, c, threePrimeUtr, mapCdna); } else { result = codingToGenomicId(gene, c, threePrimeUtr, mapCdna); } } else { if (idParser.isTranscript()) { //append user input to beginning result = codingToGenomicXrefTranscript(species, gene, c, threePrimeUtr, mapCdna); } else { result = codingToGenomicXref(species, gene, c, threePrimeUtr, mapCdna); } } if (idParser.isTranscript() || idParser.isEnsp()) { result = gene + ":" + prefix + c + "\t" + result; } else { result = convertGeneResult(result, gene, c, prefix); } } else { System.out.println("Searching for " + transcript + " as Ensembl transcript ID"); result = codingToGenomicTranscript(transcript, c, threePrimeUtr, mapCdna); //append user input to beginning result = transcript + ":" + prefix + c + "\t" + result; } System.out.println(header); System.out.println(result); }
From source file:com.sludev.mssqlapplylog.MSSQLApplyLogMain.java
public static void main(String[] args) { CommandLineParser parser = new DefaultParser(); Options options = new Options(); // Most of the following defaults should be changed in // the --conf or "conf.properties" file String sqlURL = null;/*from w w w . j a v a2 s . com*/ String sqlUser = null; String sqlPass = null; String sqlDb = null; String sqlHost = "127.0.0.1"; String backupDirStr = null; String laterThanStr = ""; String fullBackupPathStr = null; String fullBackupPatternStr = "(?:[\\w_-]+?)(\\d+)\\.bak"; String fullBackupDatePatternStr = "yyyyMMddHHmm"; String sqlProcessUser = null; String logBackupPatternStr = "(.*)\\.trn"; String logBackupDatePatternStr = "yyyyMMddHHmmss"; boolean doFullRestore = false; Boolean useLogFileLastMode = null; Boolean monitorLogBackupDir = null; options.addOption(Option.builder().longOpt("conf").desc("Configuration file.").hasArg().build()); options.addOption(Option.builder().longOpt("laterthan").desc("'Later Than' file filter.").hasArg().build()); options.addOption(Option.builder().longOpt("restore-full") .desc("Restore the full backup before continuing.").build()); options.addOption(Option.builder().longOpt("use-lastmod") .desc("Sort/filter the log backups using their File-System 'Last Modified' date.").build()); options.addOption(Option.builder().longOpt("monitor-backup-dir") .desc("Monitor the backup directory for new log backups, and apply them.").build()); CommandLine line = null; try { try { line = parser.parse(options, args); } catch (ParseException ex) { throw new MSSQLApplyLogException(String.format("Error parsing command line.'%s'", ex.getMessage()), ex); } String confFile = null; // Process the command line arguments Iterator cmdI = line.iterator(); while (cmdI.hasNext()) { Option currOpt = (Option) cmdI.next(); String currOptName = currOpt.getLongOpt(); switch (currOptName) { case "conf": // Parse the configuration file confFile = currOpt.getValue(); break; case "laterthan": // "Later Than" file date filter laterThanStr = currOpt.getValue(); break; case "restore-full": // Do a full backup restore before restoring logs doFullRestore = true; break; case "monitor-backup-dir": // Monitor the backup directory for new logs monitorLogBackupDir = true; break; case "use-lastmod": // Use the last-modified date on Log Backup files for sorting/filtering useLogFileLastMode = true; break; } } Properties confProperties = null; if (StringUtils.isBlank(confFile) || Files.isReadable(Paths.get(confFile)) == false) { throw new MSSQLApplyLogException( "Missing or unreadable configuration file. Please specify --conf"); } else { // Process the conf.properties file confProperties = new Properties(); try { confProperties.load(Files.newBufferedReader(Paths.get(confFile))); } catch (IOException ex) { throw new MSSQLApplyLogException("Error loading properties file", ex); } sqlURL = confProperties.getProperty("sqlURL", ""); sqlUser = confProperties.getProperty("sqlUser", ""); sqlPass = confProperties.getProperty("sqlPass", ""); sqlDb = confProperties.getProperty("sqlDb", ""); sqlHost = confProperties.getProperty("sqlHost", ""); backupDirStr = confProperties.getProperty("backupDir", ""); if (StringUtils.isBlank(laterThanStr)) { laterThanStr = confProperties.getProperty("laterThan", ""); } fullBackupPathStr = confProperties.getProperty("fullBackupPath", fullBackupPathStr); fullBackupPatternStr = confProperties.getProperty("fullBackupPattern", fullBackupPatternStr); fullBackupDatePatternStr = confProperties.getProperty("fullBackupDatePattern", fullBackupDatePatternStr); sqlProcessUser = confProperties.getProperty("sqlProcessUser", ""); logBackupPatternStr = confProperties.getProperty("logBackupPattern", logBackupPatternStr); logBackupDatePatternStr = confProperties.getProperty("logBackupDatePattern", logBackupDatePatternStr); if (useLogFileLastMode == null) { String useLogFileLastModeStr = confProperties.getProperty("useLogFileLastMode", "false"); useLogFileLastMode = Boolean .valueOf(StringUtils.lowerCase(StringUtils.trim(useLogFileLastModeStr))); } if (monitorLogBackupDir == null) { String monitorBackupDirStr = confProperties.getProperty("monitorBackupDir", "false"); monitorLogBackupDir = Boolean .valueOf(StringUtils.lowerCase(StringUtils.trim(monitorBackupDirStr))); } } } catch (MSSQLApplyLogException ex) { try (StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw)) { pw.append(String.format("Error : '%s'\n\n", ex.getMessage())); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(pw, 80, "\njava -jar mssqlapplylog.jar ", "\nThe MSSQLApplyLog application can be used in a variety of options and modes.\n", options, 0, 2, " All Rights Reserved.", true); System.out.println(sw.toString()); } catch (IOException iex) { LOGGER.debug("Error processing usage", iex); } System.exit(1); } MSSQLApplyLogConfig config = MSSQLApplyLogConfig.from(backupDirStr, fullBackupPathStr, fullBackupDatePatternStr, laterThanStr, fullBackupPatternStr, logBackupPatternStr, logBackupDatePatternStr, sqlHost, sqlDb, sqlUser, sqlPass, sqlURL, sqlProcessUser, useLogFileLastMode, doFullRestore, monitorLogBackupDir); MSSQLApplyLog logProc = MSSQLApplyLog.from(config); BasicThreadFactory thFactory = new BasicThreadFactory.Builder().namingPattern("restoreThread-%d").build(); ExecutorService mainThreadExe = Executors.newSingleThreadExecutor(thFactory); Future<Integer> currRunTask = mainThreadExe.submit(logProc); mainThreadExe.shutdown(); Integer resp = 0; try { resp = currRunTask.get(); } catch (InterruptedException ex) { LOGGER.error("Application 'main' thread was interrupted", ex); } catch (ExecutionException ex) { LOGGER.error("Application 'main' thread execution error", ex); } finally { // If main leaves for any reason, shutdown all threads mainThreadExe.shutdownNow(); } System.exit(resp); }