List of usage examples for org.apache.commons.cli CommandLine getOptions
public Option[] getOptions()
From source file:com.databasepreservation.cli.CLI.java
/** * Obtains the arguments needed to create new import and export modules * * @param factoriesPair//from w w w . j a v a 2 s. c o m * A pair of DatabaseModuleFactory objects containing the selected * import and export module factories * @param args * The command line arguments * @return A DatabaseModuleFactoriesArguments containing the arguments to * create the import and export modules * @throws ParseException * If the arguments could not be parsed or are invalid */ private DatabaseModuleFactoriesArguments getModuleArguments(DatabaseModuleFactoriesPair factoriesPair, List<String> args) throws ParseException, OperationNotSupportedException { DatabaseModuleFactory importModuleFactory = factoriesPair.getImportModuleFactory(); DatabaseModuleFactory exportModuleFactory = factoriesPair.getExportModuleFactory(); // get appropriate command line options CommandLineParser commandLineParser = new DefaultParser(); CommandLine commandLine; Options options = new Options(); HashMap<String, Parameter> mapOptionToParameter = new HashMap<String, Parameter>(); for (Parameter parameter : importModuleFactory.getImportModuleParameters().getParameters()) { Option option = parameter.toOption("i", "import"); options.addOption(option); mapOptionToParameter.put(getUniqueOptionIdentifier(option), parameter); } for (ParameterGroup parameterGroup : importModuleFactory.getImportModuleParameters().getGroups()) { OptionGroup optionGroup = parameterGroup.toOptionGroup("i", "import"); options.addOptionGroup(optionGroup); for (Parameter parameter : parameterGroup.getParameters()) { mapOptionToParameter.put(getUniqueOptionIdentifier(parameter.toOption("i", "import")), parameter); } } for (Parameter parameter : exportModuleFactory.getExportModuleParameters().getParameters()) { Option option = parameter.toOption("e", "export"); options.addOption(option); mapOptionToParameter.put(getUniqueOptionIdentifier(option), parameter); } for (ParameterGroup parameterGroup : exportModuleFactory.getExportModuleParameters().getGroups()) { OptionGroup optionGroup = parameterGroup.toOptionGroup("e", "export"); options.addOptionGroup(optionGroup); for (Parameter parameter : parameterGroup.getParameters()) { mapOptionToParameter.put(getUniqueOptionIdentifier(parameter.toOption("e", "export")), parameter); } } Option importOption = Option.builder("i").longOpt("import").hasArg().optionalArg(false).build(); Option exportOption = Option.builder("e").longOpt("export").hasArg().optionalArg(false).build(); Option pluginOption = Option.builder("p").longOpt("plugin").hasArg().optionalArg(false).build(); options.addOption(importOption); options.addOption(exportOption); options.addOption(pluginOption); // new HelpFormatter().printHelp(80, "dbptk", "\nModule Options:", options, // null, true); // parse the command line arguments with those options try { commandLine = commandLineParser.parse(options, args.toArray(new String[] {}), false); if (!commandLine.getArgList().isEmpty()) { throw new ParseException("Unrecognized option: " + commandLine.getArgList().get(0)); } } catch (MissingOptionException e) { // use long names instead of short names in the error message List<String> missingShort = e.getMissingOptions(); List<String> missingLong = new ArrayList<String>(); for (String shortOption : missingShort) { missingLong.add(options.getOption(shortOption).getLongOpt()); } LOGGER.debug("MissingOptionException (the original, unmodified exception)", e); throw new MissingOptionException(missingLong); } // create arguments to pass to factory HashMap<Parameter, String> importModuleArguments = new HashMap<Parameter, String>(); HashMap<Parameter, String> exportModuleArguments = new HashMap<Parameter, String>(); for (Option option : commandLine.getOptions()) { Parameter p = mapOptionToParameter.get(getUniqueOptionIdentifier(option)); if (p != null) { if (isImportModuleOption(option)) { if (p.hasArgument()) { importModuleArguments.put(p, option.getValue(p.valueIfNotSet())); } else { importModuleArguments.put(p, p.valueIfSet()); } } else if (isExportModuleOption(option)) { if (p.hasArgument()) { exportModuleArguments.put(p, option.getValue(p.valueIfNotSet())); } else { exportModuleArguments.put(p, p.valueIfSet()); } } else { throw new ParseException("Unexpected parse exception occurred."); } } } return new DatabaseModuleFactoriesArguments(importModuleArguments, exportModuleArguments); }
From source file:com.emc.vipr.sync.ViPRSync.java
/** * Loads and configures plugins based on command line options. *//* www.ja v a 2s . c o m*/ protected static ViPRSync cliBootstrap(String[] args) throws ParseException { ViPRSync sync = new ViPRSync(); List<SyncPlugin> plugins = new ArrayList<>(); CommandLine line = gnuParser.parse(mainOptions(), args, true); // find a plugin that can read from the source String sourceUri = line.getOptionValue(SOURCE_OPTION); if (sourceUri != null) { for (SyncSource source : sourceLoader) { if (source.canHandleSource(sourceUri)) { source.setSourceUri(sourceUri); sync.setSource(source); plugins.add(source); LogMF.info(l4j, "source: {0} ({1})", source.getName(), source.getClass()); break; } } } String targetUri = line.getOptionValue(TARGET_OPTION); // find a plugin that can write to the target if (targetUri != null) { for (SyncTarget target : targetLoader) { if (target.canHandleTarget(targetUri)) { target.setTargetUri(targetUri); sync.setTarget(target); plugins.add(target); LogMF.info(l4j, "target: {0} ({1})", target.getName(), target.getClass()); break; } } } // load filters List<SyncFilter> filters = new ArrayList<>(); String filtersParameter = line.getOptionValue(FILTERS_OPTION); if (filtersParameter != null) { for (String filterName : filtersParameter.split(",")) { for (SyncFilter filter : filterLoader) { if (filter.getActivationName().equals(filterName)) { filters.add(filter); plugins.add(filter); LogMF.info(l4j, "filter: {0} ({1})", filter.getName(), filter.getClass()); break; } } } sync.setFilters(filters); } // configure thread counts if (line.hasOption(QUERY_THREADS_OPTION)) sync.setQueryThreadCount(Integer.parseInt(line.getOptionValue(QUERY_THREADS_OPTION))); if (line.hasOption(SYNC_THREADS_OPTION)) sync.setSyncThreadCount(Integer.parseInt(line.getOptionValue(SYNC_THREADS_OPTION))); // configure timings display if (line.hasOption(TIMINGS_OPTION)) sync.setTimingsEnabled(true); if (line.hasOption(TIMING_WINDOW_OPTION)) { sync.setTimingWindow(Integer.parseInt(line.getOptionValue(TIMING_WINDOW_OPTION))); } // configure recursive behavior if (line.hasOption(NON_RECURSIVE_OPTION)) sync.setRecursive(false); // configure failed object tracking if (line.hasOption(FORGET_FAILED_OPTION)) sync.setRememberFailed(false); // configure whether to delete source objects after they are successfully synced if (line.hasOption(DELETE_SOURCE_OPTION)) sync.setDeleteSource(true); // logging options if (line.hasOption(DEBUG_OPTION)) { sync.setLogLevel(DEBUG_OPTION); } if (line.hasOption(VERBOSE_OPTION)) { sync.setLogLevel(VERBOSE_OPTION); } if (line.hasOption(QUIET_OPTION)) { sync.setLogLevel(QUIET_OPTION); } if (line.hasOption(SILENT_OPTION)) { sync.setLogLevel(SILENT_OPTION); } // Quick check for no-args if (sync.getSource() == null) { throw new ConfigurationException("source must be specified"); } if (sync.getTarget() == null) { throw new ConfigurationException("target must be specified"); } // Let the plugins parse their own options // 1. add common options and all the options from the plugins Options options = mainOptions(); for (Object o : CommonOptions.getOptions().getOptions()) { options.addOption((Option) o); } for (SyncPlugin plugin : plugins) { for (Object o : plugin.getCustomOptions().getOptions()) { Option option = (Option) o; if (options.hasOption(option.getOpt())) { System.err.println( "WARNING: The option " + option.getOpt() + " is being used by more than one plugin"); } options.addOption(option); } } // 2. re-parse the command line based on these options line = gnuParser.parse(options, args); if (l4j.isDebugEnabled()) { for (Option option : line.getOptions()) { if (option.hasArg()) LogMF.debug(l4j, "parsed option {0}: {1}", option.getLongOpt(), line.getOptionValue(option.getLongOpt())); else LogMF.debug(l4j, "parsed option {0}", option.getLongOpt()); } } // 3. pass the result to each plugin separately for (SyncPlugin plugin : plugins) { plugin.parseOptions(line); } return sync; }
From source file:com.aliyun.odps.mapred.bridge.streaming.StreamJob.java
void parseArgv() { CommandLine cmdLine = null; try {/* w ww .j ava2 s . c o m*/ cmdLine = parser.parse(allOptions, argv_); } catch (Exception oe) { LOG.error(oe.getMessage()); exitUsage(argv_.length > 0 && "-info".equals(argv_[0])); } if (cmdLine == null) { exitUsage(argv_.length > 0 && "-info".equals(argv_[0])); return; } @SuppressWarnings("unchecked") List<String> args = cmdLine.getArgList(); if (args != null && args.size() > 0) { fail("Found " + args.size() + " unexpected arguments on the " + "command line " + args); } detailedUsage_ = cmdLine.hasOption("info"); if (cmdLine.hasOption("help") || detailedUsage_) { printUsage = true; return; } verbose_ = cmdLine.hasOption("verbose"); background_ = cmdLine.hasOption("background"); debug_ = cmdLine.hasOption("debug") ? debug_ + 1 : debug_; output_ = cmdLine.getOptionValue("output"); comCmd_ = cmdLine.getOptionValue("combiner"); redCmd_ = cmdLine.getOptionValue("reducer"); lazyOutput_ = cmdLine.hasOption("lazyOutput"); String[] values = cmdLine.getOptionValues("file"); SessionState ss = SessionState.get(); MetaExplorer metaExplorer = new MetaExplorerImpl(ss.getOdps()); Map<String, String> aliasToTempResource = new HashMap<String, String>(); String padding = "_" + UUID.randomUUID().toString(); if (values != null && values.length > 0) { for (int i = 0; i < values.length; i++) { String file = values[i]; packageFiles_.add(file); try { aliasToTempResource.put(FilenameUtils.getName(file), metaExplorer.addFileResourceWithRetry(file, Resource.Type.FILE, padding, true)); } catch (OdpsException e) { throw new RuntimeException(e); } } config_.set("stream.temp.resource.alias", JSON.toJSONString(aliasToTempResource)); String[] res = config_.getResources(); Set<String> resources = aliasToTempResource.keySet(); if (res != null) { config_.setResources(StringUtils.join(res, ",") + "," + StringUtils.join(resources, ",")); } else { config_.setResources(StringUtils.join(resources, ",")); } } additionalConfSpec_ = cmdLine.getOptionValue("additionalconfspec"); numReduceTasksSpec_ = cmdLine.getOptionValue("numReduceTasks"); partitionerSpec_ = cmdLine.getOptionValue("partitioner"); mapDebugSpec_ = cmdLine.getOptionValue("mapdebug"); reduceDebugSpec_ = cmdLine.getOptionValue("reducedebug"); ioSpec_ = cmdLine.getOptionValue("io"); String[] car = cmdLine.getOptionValues("cacheArchive"); if (null != car) { fail("no -cacheArchive option any more, please use -resources instead."); } String[] caf = cmdLine.getOptionValues("cacheFile"); if (null != caf) { fail("no -cacheFile option any more, please use -resources instead."); } mapCmd_ = cmdLine.getOptionValue("mapper"); String[] cmd = cmdLine.getOptionValues("cmdenv"); if (null != cmd && cmd.length > 0) { for (String s : cmd) { if (addTaskEnvironment_.length() > 0) { addTaskEnvironment_ += " "; } addTaskEnvironment_ += s; } } // per table input config Map<String, Map<String, String>> inputConfigs = new HashMap<String, Map<String, String>>(); String[] columns = null; for (Option opt : cmdLine.getOptions()) { if ("jobconf".equals(opt.getOpt())) { String[] jobconf = opt.getValues(); if (null != jobconf && jobconf.length > 0) { for (String s : jobconf) { String[] parts = s.split("=", 2); config_.set(parts[0], parts[1]); } } } else if ("columns".equals(opt.getOpt())) { String columnsValue = opt.getValue(); if (columnsValue.equals("ALL")) { columns = null; } else { columns = columnsValue.split(","); } } else if ("input".equals(opt.getOpt())) { values = opt.getValues(); if (values != null && values.length > 0) { for (String input : values) { TableInfo ti = parseTableInfo(input); if (columns != null) { ti.setCols(columns); } inputSpecs_.add(ti); String inputKey = (ti.getProjectName() + "." + ti.getTableName()).toLowerCase(); // XXX only apply once per table if (inputConfigs.get(inputKey) != null) { continue; } Map<String, String> inputConfig = new HashMap<String, String>(); inputConfig.put("stream.map.input.field.separator", config_.get("stream.map.input.field.separator", "\t")); // TODO other per table input config: cols, etc. inputConfigs.put(inputKey, inputConfig); } } } } try { config_.set("stream.map.input.configs", JSON.toJSONString(inputConfigs)); } catch (Exception e) { throw new RuntimeException("fail to set input configs"); } }
From source file:net.tjado.jcdbe.jcdbe.java
public static void main(String[] args) throws Exception { // print banner System.out.println("------------------------------------------"); System.out.println("| Java Central DataBase Engine v0.4 beta |"); System.out.println("------------------------------------------"); // path to the ini configuration String configPath = workingDir + "/config/jcdbe.ini"; // If the first CLI argument doesn't begin with "-" it must be a config file. // We need to do this, to have the possibility to specify other ini config files // The ini config file is necessary for the input/output classes, which again specify the // required CLI arguments if (args.length != 0 && !args[0].startsWith("-")) { configPath = args[0];//w ww . j a va2 s . c o m // remove first argument from CLI arguments array, so it won't be validated by CLI argument // parser args = Arrays.copyOfRange(args, 1, args.length); } // initialize the ini configuration to get required parameters Ini config = initConfig(configPath); // initialize Logger log.init(log4jPropertyFile); // setting jdbc property file DatabaseOracle.setPropertyFile(jdbcPropertyeFile); // declare the input/output classes Input input = (Input) Class.forName(inputClass).getDeclaredMethod("getInstance").invoke(null, (Object[]) null); Output output = (Output) Class.forName(outputClass).getDeclaredMethod("getInstance").invoke(null, (Object[]) null); // declare options and parser for the CLI arguments Options options = new Options(); CommandLineParser parser = new PosixParser(); // add "help" CLI argument options.addOption("h", "help", false, "print this usage information"); // add further CLI arguments by the input/output classes input.setCLI(options); output.setCLI(options); CommandLine cli = null; try { // parse the CLI arguments cli = parser.parse(options, args); if (cli.hasOption("help") || cli.getOptions().length == 0) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar jcdbe.jar [options]", options); System.exit(1); } } catch (ParseException e) { System.out.println(e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar jcdbe.jar [options]", options); System.exit(1); } // output engine config after initializing of Logger log.debug("[CONFIG] Working Directory: " + workingDir); log.debug("[CONFIG] Input class: " + inputClass); log.debug("[CONFIG] Output class: " + outputClass); log.debug("[CONFIG] JDBC URL prefix: " + jdbcPrefix); log.debug("[CONFIG] Java Library Path: " + System.getProperty("java.library.path")); log.debug("[CONFIG] Oracle SDU size: " + sduSize); log.debug("[CONFIG] Max. threads: " + threadMax); log.debug("[CONFIG] Max. running threads: " + threadRun); log.debug("[CONFIG] Thread idle timeout: " + threadTTL); log.debug("[CONFIG] Advanced Debugging: " + advDebugging); // validate Input arguments input.validateParameters(cli, config); // validate Output arguments output.validateParameters(cli, config); // start benchmark time measureTimeStart(); log.info("[INPUT] Initialization"); // run input init and check if it was successfull.... if (!input.init()) { log.fatal("Error during input init..."); System.exit(2); } log.info("[OUTPUT] Initialization"); // run output init and check if it was successfull.... if (!output.init()) { log.fatal("[OUTPUT] Error during output init..."); System.exit(3); } // init thread pool workQueue = new ArrayBlockingQueue<Runnable>(99999); ThreadPoolExecutor threads = new ThreadPoolExecutor(threadRun, threadMax, threadTTL, TimeUnit.SECONDS, workQueue); // get DatabaseList object which will manage all database infos (url, username, pw, status...) DatabaseList dbList = input.getDatabaseList(); if (dbList.size() == 0) { log.info("[QUEUE] database list is empty... nothing do to."); System.exit(1); } // get all SQL queries to execute // Integer = Query ID // String = SQL Text Map<Integer, String> queries = input.getQueries(); log.info("[QUEUE] Starting Threads"); // loop thru dbList to create & execute/queue all threads for (Integer id : dbList) { try { // create new runnable instance DatabaseThreadSlave slaveThread = new DatabaseThreadSlave(id, dbList, queries, output, jdbcPrefix, sduSize); // insert runnable instance into dbList dbList.setThread(id, slaveThread); // add runnable instance into thread pool queue threads.execute(slaveThread); } catch (Exception e) { advDebug(e); log.warn("Exception in thread-starter loop (DBID: " + id + "): " + e.getMessage()); } } // // waiting for all threads to complete // // the timeout handling will be done completely over JDBC // see docs for more information // while (!dbList.isFinished() || threads.getActiveCount() > 0) { Thread.sleep(500); } log.info("[QUEUE] Shutting down all threads"); threads.shutdown(); Thread.sleep(2000); log.info("[INPUT] close input..."); input.close(); log.info("[OUTPUT] close output..."); output.close(); // end time-benchmark and output measureTimeEnd(); // rc=0 System.exit(0); }
From source file:nl.cyso.vcloud.client.config.Configuration.java
public static void load(CommandLine cli) { for (Option opt : cli.getOptions()) { if (cli.hasOption(opt.getLongOpt())) { if (opt.getLongOpt().equals("help")) { Configuration.setMode(ModeType.HELP); if (cli.getOptionValue(opt.getLongOpt()) != null) { Configuration .setHelpType(ModeType.valueOf(cli.getOptionValue(opt.getLongOpt()).toUpperCase())); }/* w w w. j av a2 s . c om*/ } else if (opt.getLongOpt().equals("version")) { Configuration.setMode(ModeType.VERSION); } else if (opt.getLongOpt().equals("list")) { Configuration.setMode(ModeType.LIST); Configuration.setListType(ListType.valueOf(cli.getOptionValue(opt.getLongOpt()).toUpperCase())); } else if (opt.getLongOpt().equals("add-vm")) { Configuration.setMode(ModeType.ADDVM); } else if (opt.getLongOpt().equals("remove-vm")) { Configuration.setMode(ModeType.REMOVEVM); } else if (opt.getLongOpt().equals("poweron-vm")) { Configuration.setMode(ModeType.POWERONVM); } else if (opt.getLongOpt().equals("poweroff-vm")) { Configuration.setMode(ModeType.POWEROFFVM); } else if (opt.getLongOpt().equals("shutdown-vm")) { Configuration.setMode(ModeType.SHUTDOWNVM); } else if (opt.getLongOpt().equals("resize-disk")) { Configuration.setMode(ModeType.RESIZEDISK); } else if (opt.getLongOpt().equals("consolidate-vm")) { Configuration.setMode(ModeType.CONSOLIDATEVM); } else if (opt.getLongOpt().equals("ip")) { try { Configuration.setIp(cli.getOptionValue(opt.getLongOpt())); } catch (UnknownHostException uhe) { Configuration.setIp((InetAddress) null); } } else if (opt.getLongOpt().equals("disk-size")) { Configuration.setDiskSize(cli.getOptionValue(opt.getLongOpt())); } else if (opt.getLongOpt().equals("ip-address-allocation-mode")) { Configuration.setIpAddressAllocationMode(cli.getOptionValue(opt.getLongOpt())); } else { Configuration.set(opt.getLongOpt(), cli.getOptionValue(opt.getLongOpt())); } } } }
From source file:nl.cyso.vsphere.client.config.Configuration.java
public static void load(CommandLine cli) { for (Option opt : cli.getOptions()) { if (cli.hasOption(opt.getLongOpt())) { if (opt.getLongOpt().equals("help")) { Configuration.set("mode", "HELP"); if (cli.getOptionValue(opt.getLongOpt()) != null) { Configuration.set("help-type", cli.getOptionValue(opt.getLongOpt())); }/*from w w w. j a v a2 s . c om*/ } else if (opt.getLongOpt().equals("version")) { Configuration.set("mode", "VERSION"); } else if (opt.getLongOpt().equals("list")) { Configuration.set("mode", "LIST"); Configuration.set("list-type", cli.getOptionValue(opt.getLongOpt()).toUpperCase()); } else if (opt.getLongOpt().equals("add-vm")) { Configuration.set("mode", "ADDVM"); } else if (opt.getLongOpt().equals("remove-vm")) { Configuration.set("mode", "REMOVEVM"); } else if (opt.getLongOpt().equals("poweron-vm")) { Configuration.set("mode", "POWERONVM"); } else if (opt.getLongOpt().equals("poweroff-vm")) { Configuration.set("mode", "POWEROFFVM"); } else if (opt.getLongOpt().equals("shutdown-vm")) { Configuration.set("mode", "SHUTDOWNVM"); } else if (opt.getLongOpt().equals("reboot-vm")) { Configuration.set("mode", "REBOOTVM"); } else if (opt.getLongOpt().equals("modify-vm")) { Configuration.set("mode", "MODIFYVM"); } else if (opt.getLongOpt().equals("upload-to-datastore")) { Configuration.set("mode", "UPLOADTODATASTORE"); } else if (opt.getLongOpt().equals("ip")) { try { Configuration.set("ip", InetAddress.getByName(cli.getOptionValue(opt.getLongOpt()))); } catch (UnknownHostException uhe) { Configuration.set("ip", (InetAddress) null); } } else { Configuration.set(opt.getLongOpt(), cli.getOptionValue(opt.getLongOpt())); } } } }
From source file:nl.nekoconeko.glaciercmd.config.Configuration.java
public static void load(CommandLine cli) { for (Option opt : cli.getOptions()) { if (cli.hasOption(opt.getLongOpt())) { if (opt.getLongOpt().equals("help")) { Configuration.setMode(ModeType.HELP); if (cli.getOptionValue(opt.getLongOpt()) != null) { Configuration .setHelpType(ModeType.valueOf(cli.getOptionValue(opt.getLongOpt()).toUpperCase())); }/* w w w .ja v a 2 s.c om*/ } else if (opt.getLongOpt().equals("version")) { Configuration.setMode(ModeType.VERSION); } else if (opt.getLongOpt().equals("list")) { Configuration.setMode(ModeType.LIST); Configuration.setListType(ListType.valueOf(cli.getOptionValue(opt.getLongOpt()).toUpperCase())); } else if (opt.getLongOpt().equals("init-inventory")) { Configuration.setMode(ModeType.INITIATEINVENTORY); } else if (opt.getLongOpt().equals("get-inventory")) { Configuration.setMode(ModeType.GETINVENTORY); } else if (opt.getLongOpt().equals("upload")) { Configuration.setMode(ModeType.UPLOAD); } else if (opt.getLongOpt().equals("download")) { Configuration.setMode(ModeType.DOWNLOAD); } else if (opt.getLongOpt().equals("init-download")) { Configuration.setMode(ModeType.INITIATEDOWNLOAD); } else if (opt.getLongOpt().equals("get-download")) { Configuration.setMode(ModeType.GETDOWNLOAD); } else if (opt.getLongOpt().equals("delete-archive")) { Configuration.setMode(ModeType.DELETEARCHIVE); } else if (opt.getLongOpt().equals("region")) { Configuration.setRegion( AWSGlacierRegion.valueOf(cli.getOptionValue(opt.getLongOpt()).toUpperCase())); } else { Configuration.set(opt.getLongOpt(), cli.getOptionValue(opt.getLongOpt())); } } } }
From source file:nz.co.jsrsolutions.ds3.DataScraper3.java
public static void main(String[] args) { logger.info("Starting application [ ds3 ] ..."); ClassPathXmlApplicationContext context = null; try {//from ww w . ja v a2 s . c o m CommandLineParser parser = new GnuParser(); CommandLine commandLine = parser.parse(CommandLineOptions.Options, args); if (commandLine.getOptions().length > 0 && !commandLine.hasOption(CommandLineOptions.HELP)) { StringBuffer environment = new StringBuffer(); environment.append(SPRING_CONFIG_PREFIX); environment.append(commandLine.getOptionValue(CommandLineOptions.ENVIRONMENT)); environment.append(SPRING_CONFIG_SUFFIX); context = new ClassPathXmlApplicationContext(environment.toString()); context.registerShutdownHook(); if (commandLine.hasOption(CommandLineOptions.SCHEDULED)) { Scheduler scheduler = context.getBean(SCHEDULER_BEAN_ID, Scheduler.class); scheduler.start(); Object lock = new Object(); synchronized (lock) { lock.wait(); } } else { DataScraper3Controller controller = context.getBean(CONTROLLER_BEAN_ID, DataScraper3Controller.class); controller.executeCommandLine(commandLine); } } else { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("ds3", CommandLineOptions.Options); } } catch (DataScraper3Exception ds3e) { logger.error("Failed to execute command", ds3e); } catch (ParseException pe) { logger.error("Failed to parse command line", pe); } catch (Exception e) { logger.error("Failed to execute command", e); } finally { if (context != null) { context.close(); } } logger.info("Exiting application [ ds3 ] ..."); }
From source file:nz.co.jsrsolutions.tideservice.scraper.TideScraper.java
public static void main(String[] args) { logger.info("Starting application [ tide scraper ] ..."); GenericXmlApplicationContext context = null; try {/*from ww w . j a v a 2 s. c o m*/ CommandLineParser parser = new GnuParser(); CommandLine commandLine = parser.parse(CommandLineOptions.Options, args); if (commandLine.getOptions().length > 0 && !commandLine.hasOption(CommandLineOptions.HELP)) { context = new GenericXmlApplicationContext(); //ConfigurableEnvironment env = ctx.getEnvironment(); //env.setActiveProfiles("test1"); context.load(SPRING_CONFIG); context.refresh(); context.registerShutdownHook(); if (commandLine.hasOption(CommandLineOptions.SCHEDULED)) { Scheduler scheduler = context.getBean(SCHEDULER_BEAN_ID, Scheduler.class); scheduler.start(); Object lock = new Object(); synchronized (lock) { lock.wait(); } } else { TideScraperController controller = context.getBean(CONTROLLER_BEAN_ID, TideScraperController.class); controller.executeCommandLine(commandLine); } } else { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("ts", CommandLineOptions.Options); } } catch (TideScraperException tse) { logger.error("Failed to execute command", tse); } catch (ParseException pe) { logger.error("Failed to parse command line", pe); } catch (Exception e) { logger.error("Failed to execute command", e); } finally { if (context != null) { context.close(); } } logger.info("Exiting application [ tide scraper ] ..."); }
From source file:openlr.otk.options.CommandLineData.java
/** * Check required options./*from w w w. j av a 2 s.c om*/ * * @param cmdLine * the cmd line * @throws CommandLineParseException * the parse exception */ private void checkRequiredOptions(final CommandLine cmdLine) throws CommandLineParseException { for (Option opt : cmdLine.getOptions()) { if (opt.isRequired() && !cmdLine.hasOption(opt.getOpt())) { throw new CommandLineParseException("Missing mandatory parameter: " + opt.getOpt()); } } }