List of usage examples for org.apache.commons.cli CommandLine getOptionProperties
public Properties getOptionProperties(String opt)
From source file:org.grouplens.lenskit.eval.cli.EvalCLIOptions.java
private EvalCLIOptions(CommandLine cmd) { String[] cpadds = cmd.getOptionValues("C"); if (cpadds != null) { classpathUrls = new URL[cpadds.length]; for (int i = 0; i < cpadds.length; i++) { URL url = null;// ww w . j av a 2 s . co m try { File f = new File(cpadds[i]); url = f.toURI().toURL(); } catch (MalformedURLException e) { logger.error("malformed classpath URL {}", url); throw new RuntimeException("invalid classpath entry", e); } logger.info("adding {} to classpath", url); classpathUrls[i] = url; } } if (cmd.hasOption("f")) { configFile = new File(cmd.getOptionValue("f")); } props = cmd.getOptionProperties("D"); force = cmd.hasOption("F"); if (cmd.hasOption("j")) { String n = cmd.getOptionValue("j"); if (n == null) { nthreads = 0; } else { nthreads = Integer.parseInt(n); } } args = cmd.getArgs(); }
From source file:org.hawkular.wildfly.agent.installer.InstallerConfiguration.java
public InstallerConfiguration(CommandLine commandLine) throws Exception { this.properties = new Properties(); // we allow the user to set system properties through the -D argument Properties sysprops = commandLine.getOptionProperties("D"); for (Map.Entry<Object, Object> sysprop : sysprops.entrySet()) { System.setProperty(sysprop.getKey().toString(), sysprop.getValue().toString()); }// ww w . ja va2s .c o m // seed our properties with the installer config properties file String installerConfig = commandLine.getOptionValue(OPTION_INSTALLER_CONFIG, "classpath:/hawkular-wildfly-agent-installer.properties"); log.debug("Installer configuration file: " + installerConfig); if (installerConfig.startsWith("classpath:")) { installerConfig = installerConfig.substring(10); if (!installerConfig.startsWith("/")) { installerConfig = "/" + installerConfig; } properties.load(InstallerConfiguration.class.getResourceAsStream(installerConfig)); } else if (installerConfig.matches("(http|https|file):.*")) { URL installerConfigUrl = new URL(installerConfig); try (InputStream is = installerConfigUrl.openStream()) { properties.load(is); } } else { File installerConfigFile = new File(installerConfig); try (FileInputStream fis = new FileInputStream(installerConfigFile)) { properties.load(fis); } } // now we override the defaults with options the user provided us setProperty(properties, commandLine, OPTION_ENABLED); setProperty(properties, commandLine, OPTION_TARGET_LOCATION); setProperty(properties, commandLine, OPTION_MODULE_DISTRIBUTION); setProperty(properties, commandLine, OPTION_TARGET_CONFIG); setProperty(properties, commandLine, OPTION_SUBSYSTEM_SNIPPET); setProperty(properties, commandLine, OPTION_MANAGED_SERVER_NAME); setProperty(properties, commandLine, OPTION_SERVER_URL); setProperty(properties, commandLine, OPTION_KEYSTORE_PATH); setProperty(properties, commandLine, OPTION_KEYSTORE_PASSWORD); setProperty(properties, commandLine, OPTION_KEY_PASSWORD); setProperty(properties, commandLine, OPTION_KEY_ALIAS); setProperty(properties, commandLine, OPTION_USERNAME); setProperty(properties, commandLine, OPTION_PASSWORD); setProperty(properties, commandLine, OPTION_SECURITY_KEY); setProperty(properties, commandLine, OPTION_SECURITY_SECRET); }
From source file:org.ldmud.jldmud.CommandLineArguments.java
/** * Parse the commandline and set the associated globals. * * @return {@code true} if the main program should exit; in that case {@link @getExitCode()} provides the suggest exit code. *//*from w ww.j a v a 2s .c om*/ @SuppressWarnings("static-access") public boolean parseCommandline(String[] args) { try { Option configSetting = OptionBuilder.withLongOpt("config").withArgName("setting=value").hasArgs(2) .withValueSeparator() .withDescription( "Set the configuration setting to the given value (overrides any setting in the <config settings> file). Unsupported settings are ignored.") .create("C"); Option help = OptionBuilder.withLongOpt("help").withDescription("Print the help text and exits.") .create("h"); Option helpConfig = OptionBuilder.withLongOpt("help-config") .withDescription("Print the <config settings> help text and exits.").create(); Option version = OptionBuilder.withLongOpt("version") .withDescription("Print the driver version and exits").create("V"); Option printConfig = OptionBuilder.withLongOpt("print-config") .withDescription("Print the effective configuration settings to stdout and exit.").create(); Option printLicense = OptionBuilder.withLongOpt("license") .withDescription("Print the software license and exit.").create(); Options options = new Options(); options.addOption(help); options.addOption(helpConfig); options.addOption(version); options.addOption(configSetting); options.addOption(printConfig); options.addOption(printLicense); CommandLineParser parser = new PosixParser(); CommandLine line = parser.parse(options, args); /* Handle the print-help-and-exit options first, to allow them to be chained in a nice way. */ boolean helpOptionsGiven = false; if (line.hasOption(version.getOpt())) { System.out.println( Version.DRIVER_NAME + " " + Version.getVersionString() + " - a LPMud Game Driver."); System.out.println(Version.Copyright); System.out.print(Version.DRIVER_NAME + " is licensed under the " + Version.License + "."); if (!line.hasOption(printLicense.getLongOpt())) { System.out.print(" Use option --license for details."); } System.out.println(); helpOptionsGiven = true; } if (line.hasOption(printLicense.getLongOpt())) { if (helpOptionsGiven) { System.out.println(); } printLicense(); helpOptionsGiven = true; } if (line.hasOption(help.getOpt())) { final PrintWriter systemOut = new PrintWriter(System.out, true); HelpFormatter formatter = new HelpFormatter(); if (helpOptionsGiven) { System.out.println(); } System.out.println("Usage: " + Version.DRIVER_NAME + " [options] [<config settings>]"); System.out.println(); formatter.printWrapped(systemOut, formatter.getWidth(), "The <config settings> is a file containing the game settings; if not specified, it defaults to '" + GameConfiguration.DEFAULT_SETTINGS_FILE + "'. " + "The settings file must exist if no configuration setting is specified via commandline argument."); System.out.println(); formatter.printOptions(systemOut, formatter.getWidth(), options, formatter.getLeftPadding(), formatter.getDescPadding()); helpOptionsGiven = true; } if (line.hasOption(helpConfig.getLongOpt())) { if (helpOptionsGiven) { System.out.println(); } GameConfiguration.printTemplate(); helpOptionsGiven = true; } if (helpOptionsGiven) { exitCode = 0; return true; } /* Parse the real options */ /* TODO: If we get many real options, it would be useful to implement a more general system like {@link GameConfiguration#SettingBase} */ if (line.hasOption(configSetting.getLongOpt())) { configSettings = line.getOptionProperties(configSetting.getLongOpt()); } if (line.hasOption(printConfig.getLongOpt())) { printConfiguration = true; } if (line.getArgs().length > 1) { throw new ParseException("Too many arguments"); } if (line.getArgs().length == 1) { settingsFilename = line.getArgs()[0]; } return false; } catch (ParseException e) { System.err.println("Error: " + e.getMessage()); exitCode = 1; return true; } }
From source file:org.onebusaway.quickstart.webapp.BootstrapWebApplicationContext.java
private void configureGtfsRealtimeBeanDefinition(CommandLine cli, Map<String, BeanDefinition> beanDefinitions) { boolean tripUpdates = cli.hasOption(WebappCommon.ARG_GTFS_REALTIME_TRIP_UPDATES_URL); boolean vehiclePositions = cli.hasOption(WebappCommon.ARG_GTFS_REALTIME_VEHICLE_POSITIONS_URL); boolean alertsUrl = cli.hasOption(WebappCommon.ARG_GTFS_REALTIME_ALERTS_URL); if (tripUpdates || vehiclePositions || alertsUrl) { BeanDefinitionBuilder bean = BeanDefinitionBuilder.genericBeanDefinition( "org.onebusaway.transit_data_federation.impl.realtime.gtfs_realtime.GtfsRealtimeSource"); if (tripUpdates) bean.addPropertyValue("tripUpdatesUrl", cli.getOptionValue(WebappCommon.ARG_GTFS_REALTIME_TRIP_UPDATES_URL)); if (vehiclePositions) bean.addPropertyValue("vehiclePositionsUrl", cli.getOptionValue(WebappCommon.ARG_GTFS_REALTIME_VEHICLE_POSITIONS_URL)); if (alertsUrl) bean.addPropertyValue("alertsUrl", cli.getOptionValue(WebappCommon.ARG_GTFS_REALTIME_ALERTS_URL)); if (cli.hasOption(WebappCommon.ARG_GTFS_REALTIME_REFRESH_INTERVAL)) { String refreshInterval = cli.getOptionValue(WebappCommon.ARG_GTFS_REALTIME_REFRESH_INTERVAL); bean.addPropertyValue("refreshInterval", refreshInterval); }//from ww w. j av a 2 s.co m beanDefinitions.put("gtfsRealtimeSource", bean.getBeanDefinition()); System.out.println("=== GTFS REALTIME! ============================"); } if (cli.hasOption("P")) { Properties props = cli.getOptionProperties("P"); BeanDefinitionBuilder propertyOverrides = BeanDefinitionBuilder .genericBeanDefinition("org.onebusaway.container.spring.PropertyOverrideConfigurer"); propertyOverrides.addPropertyValue("properties", props); beanDefinitions.put("myCustomPropertyOverrides", propertyOverrides.getBeanDefinition()); } }
From source file:org.onebusaway.transit_data_federation.bundle.FederatedTransitDataBundleCreatorMain.java
public void run(String[] args) throws Exception { try {/*from w w w. j ava 2 s . c o m*/ Parser parser = new GnuParser(); Options options = new Options(); buildOptions(options); CommandLine commandLine = parser.parse(options, args); String[] remainingArgs = commandLine.getArgs(); if (remainingArgs.length < 2) { printUsage(); System.exit(-1); } FederatedTransitDataBundleCreator creator = new FederatedTransitDataBundleCreator(); Map<String, BeanDefinition> beans = new HashMap<String, BeanDefinition>(); creator.setContextBeans(beans); List<GtfsBundle> gtfsBundles = new ArrayList<GtfsBundle>(); List<String> contextPaths = new ArrayList<String>(); for (int i = 0; i < remainingArgs.length - 1; i++) { File path = new File(remainingArgs[i]); if (path.isDirectory() || path.getName().endsWith(".zip")) { GtfsBundle gtfsBundle = new GtfsBundle(); gtfsBundle.setPath(path); gtfsBundles.add(gtfsBundle); } else { contextPaths.add("file:" + path); } } if (!gtfsBundles.isEmpty()) { BeanDefinitionBuilder bean = BeanDefinitionBuilder.genericBeanDefinition(GtfsBundles.class); bean.addPropertyValue("bundles", gtfsBundles); beans.put("gtfs-bundles", bean.getBeanDefinition()); } if (commandLine.hasOption(ARG_USE_DATABASE_FOR_GTFS)) { contextPaths.add("classpath:org/onebusaway/gtfs/application-context.xml"); } else { BeanDefinitionBuilder bean = BeanDefinitionBuilder .genericBeanDefinition(GtfsRelationalDaoImpl.class); beans.put("gtfsRelationalDaoImpl", bean.getBeanDefinition()); } if (commandLine.hasOption(ARG_DATASOURCE_URL)) { String dataSourceUrl = commandLine.getOptionValue(ARG_DATASOURCE_URL); BeanDefinitionBuilder bean = BeanDefinitionBuilder .genericBeanDefinition(DriverManagerDataSource.class); bean.addPropertyValue("url", dataSourceUrl); if (commandLine.hasOption(ARG_DATASOURCE_DRIVER_CLASS_NAME)) bean.addPropertyValue("driverClassName", commandLine.getOptionValue(ARG_DATASOURCE_DRIVER_CLASS_NAME)); if (commandLine.hasOption(ARG_DATASOURCE_USERNAME)) bean.addPropertyValue("username", commandLine.getOptionValue(ARG_DATASOURCE_USERNAME)); if (commandLine.hasOption(ARG_DATASOURCE_PASSWORD)) bean.addPropertyValue("password", commandLine.getOptionValue(ARG_DATASOURCE_PASSWORD)); beans.put("dataSource", bean.getBeanDefinition()); } if (commandLine.hasOption(ARG_OSM)) { File osmPath = new File(commandLine.getOptionValue(ARG_OSM)); BeanDefinitionBuilder bean = BeanDefinitionBuilder .genericBeanDefinition(FileBasedOpenStreetMapProviderImpl.class); bean.addPropertyValue("path", osmPath); beans.put("osmProvider", bean.getBeanDefinition()); } File outputPath = new File(remainingArgs[remainingArgs.length - 1]); if (commandLine.hasOption(ARG_ONLY_IF_DNE) && outputPath.exists()) { System.err.println("Bundle path already exists. Exiting..."); System.exit(0); } if (commandLine.hasOption(ARG_RANDOMIZE_CACHE_DIR)) creator.setRandomizeCacheDir(true); if (commandLine.hasOption(ARG_BUNDLE_KEY)) { String key = commandLine.getOptionValue(ARG_BUNDLE_KEY); creator.setBundleKey(key); } /** * Optionally override any system properties (ok this duplicates existing * functionality, yes, but it allows for -D arguments after the main * class) */ if (commandLine.hasOption("D")) { Properties props = commandLine.getOptionProperties("D"); for (Object key : props.keySet()) { String propName = (String) key; String propValue = props.getProperty(propName); System.setProperty(propName, propValue); } } /** * Optionally override any system properties (ok this duplicates existing * functionality, yes, but it allows for -D arguments after the main * class) */ if (commandLine.hasOption("P")) { Properties props = commandLine.getOptionProperties("P"); creator.setAdditionalBeanPropertyOverrides(props); } setStagesToSkip(commandLine, creator); creator.setOutputPath(outputPath); creator.setContextPaths(contextPaths); try { if (commandLine.hasOption(ARG_ADDITIONAL_RESOURCES_DIRECTORY)) { File additionalResourceDirectory = new File( commandLine.getOptionValue(ARG_ADDITIONAL_RESOURCES_DIRECTORY)); copyFiles(additionalResourceDirectory, outputPath); } creator.run(); } catch (Exception ex) { _log.error("error building transit data bundle", ex); System.exit(-1); } } catch (ParseException ex) { System.err.println(ex.getLocalizedMessage()); printUsage(); System.exit(-1); } System.exit(0); }
From source file:org.silverware.microservices.Boot.java
/** * Creates initial context pre-filled with system properties and command line arguments. * @param args Command line arguments.//w ww. j a v a 2s.c o m * @return Initial context pre-filled with system properties and command line arguments. */ @SuppressWarnings("static-access") private static Context getInitialContext(final String... args) { final Context context = new Context(); final Map<String, Object> contextProperties = context.getProperties(); final Options options = new Options(); final CommandLineParser commandLineParser = new GnuParser(); System.getProperties().forEach((key, value) -> contextProperties.put((String) key, value)); options.addOption(OptionBuilder.withArgName("property=value").hasArgs(2).withValueSeparator() .withDescription("system properties").create(PROPERTY_LETTER)); try { final CommandLine commandLine = commandLineParser.parse(options, args); commandLine.getOptionProperties(PROPERTY_LETTER) .forEach((key, value) -> contextProperties.put((String) key, value)); } catch (ParseException pe) { log.error("Cannot parse arguments: ", pe); System.exit(1); } return context; }
From source file:org.tolven.appserverproperties.AppServerPropertiesPlugin.java
@Override public void execute(String[] args) { logger.info("*** execute ***"); CommandLine commandLine = getCommandLine(args); AppServerProperties loadServerProperties = getAppServerProperties(); if (commandLine.hasOption(CMD_LINE_DISPLAY_OPTION)) { logger.info("Displaying server properties..."); loadServerProperties.displayProperties(); } else if (commandLine.hasOption(CMD_LINE_LOAD_OPTION)) { logger.info("Importing server properties..."); List<File> propertiesFiles = getPropertiesFiles(); loadServerProperties.uploadPropertiesFiles(propertiesFiles); } else if (commandLine.hasOption(CMD_LINE_FIND_OPTION)) { String property = commandLine.getOptionValue(CMD_LINE_FIND_OPTION); logger.info("Find server property: " + property); String value = loadServerProperties.findProperty(property); System.out.println(value); } else if (commandLine.hasOption(CMD_LINE_SET_OPTION)) { Properties optionProperties = commandLine.getOptionProperties(CMD_LINE_SET_OPTION); String propertyName = (String) optionProperties.keys().nextElement(); String propertyValue = optionProperties.getProperty(propertyName); logger.info("Setting server property: " + propertyName); loadServerProperties.setProperty(propertyName, propertyValue); } else if (commandLine.hasOption(CMD_LINE_REMOVE_OPTION)) { String property = commandLine.getOptionValue(CMD_LINE_REMOVE_OPTION); logger.info("Removing server property: " + property); loadServerProperties.removeProperty(property); } else if (commandLine.hasOption(CMD_LINE_GUI_OPTION)) { logger.info("Starting the appserver properties gui..."); //getPropertiesUI().setVisible(true); } else {//ww w . j a va 2s .c o m throw new RuntimeException("Unrecognized command line option:" + commandLine); } logger.info("server properties completed"); }
From source file:org.trancecode.xproc.cli.CommandLineExecutor.java
protected int execute(final String[] args, final InputStream stdin, final PrintStream stdout, final PrintStream stderr) { final GnuParser parser = new GnuParser(); try {/*from www . ja v a2s .c o m*/ final CommandLine commandLine = parser.parse(options, args); if (commandLine.hasOption(helpOption.getOpt())) { printHelp(stderr); return 0; } if (commandLine.hasOption(versionOption.getOpt())) { stderr.println(Tubular.productInformation()); return 0; } if (commandLine.hasOption(verboseOption.getOpt())) { Logger.getRootLogger().setLevel(Level.DEBUG); } final PipelineConfiguration configurationPipelineContext = new PipelineConfiguration(); final URIResolver uriResolver = configurationPipelineContext.getUriResolver(); final PipelineProcessor pipelineProcessor = new PipelineProcessor(configurationPipelineContext); final String[] libraries = commandLine.getOptionValues(librariesOption.getOpt()); if (libraries != null) { for (final String library : libraries) { // FIXME this will not really have any effect has the parsed // library is returned and the pipeline processor stays // unchanged pipelineProcessor.buildPipelineLibrary( newSource(uriResolver, library, "Cannot read library from %s", library)); } } // configurationPipelineContext.registerStepProcessor(null); final String xplValue = commandLine.getOptionValue(xplOption.getOpt()); if (xplValue == null) { stderr.println("Required pipeline given using the --" + xplOption.getLongOpt() + " option."); printHelp(stderr); return 2; } else { final Source xplSource = newSource(uriResolver, xplValue, "Cannot read pipeline from %s", xplValue); if (xplSource != null) { final Pipeline buildPipeline = pipelineProcessor.buildPipeline(xplSource); final RunnablePipeline runnablePipeline = buildPipeline.load(); final Properties portBindingProperties = commandLine .getOptionProperties(portBindingOption.getOpt()); for (final String portBindingName : portBindingProperties.stringPropertyNames()) { final String portBindingValue = portBindingProperties.getProperty(portBindingName); if (runnablePipeline.getPipeline().getPort(portBindingName).isInput()) { LOG.debug("input port binding: {} = {}", portBindingName, portBindingValue); runnablePipeline.bindSourcePort(portBindingName, newSource(uriResolver, portBindingValue, "Cannot bind port to resource from %s", portBindingValue)); } } final Properties optionProperties = commandLine.getOptionProperties(optionOption.getOpt()); for (final String optionName : optionProperties.stringPropertyNames()) { final String optionValue = optionProperties.getProperty(optionName); runnablePipeline.withOption(new QName(optionName), optionValue); } final Properties paramProperties = commandLine.getOptionProperties(paramOption.getOpt()); for (final String paramName : paramProperties.stringPropertyNames()) { final String paramValue = paramProperties.getProperty(paramName); runnablePipeline.withParam(new QName(paramName), paramValue); } final PipelineResult pipelineResult = runnablePipeline.run(); final Port primaryOutputPort = pipelineResult.getPipeline().getPrimaryOutputPort(); if (primaryOutputPort != null && !portBindingProperties.stringPropertyNames() .contains(primaryOutputPort.getPortName())) { final XdmNode node = Iterables .getOnlyElement(pipelineResult.readNodes(primaryOutputPort.getPortName()), null); if (node != null) { stdout.println(node); } } } else { stderr.println("Argument given to option --xpl is neither a URL nor or a file."); printHelp(stderr); return 3; } } } catch (final ParseException ex) { printHelp(stderr); return 1; } return 0; }
From source file:org.zgif.converter.ui.shell.ShellMain.java
/** * @param args//from w ww . j a v a 2s . c om * @throws Exception */ public static void main(String[] args) throws Exception { PatternLayout layout = new PatternLayout("%d{ISO8601} %-5p [%t] %c: %m%n"); ConsoleAppender consoleAppender = new ConsoleAppender(layout); logger.addAppender(consoleAppender); logger.setLevel(Level.ALL); Options options = new Options(); Option guiOption = Option.builder("g").longOpt("gui").desc("start the GUI").build(); Option pluginOption = Option.builder("p").longOpt("plugin").required().argName("plugin=classpath") .numberOfArgs(2).valueSeparator().desc("set classpath for plugins (import and export)").build(); Option importOption = Option.builder("i").longOpt("import").numberOfArgs(2).valueSeparator() .desc("config for import plugin").build(); Option exportOption = Option.builder("e").longOpt("export").numberOfArgs(2).valueSeparator() .desc("config for export plugin").build(); options.addOption(guiOption); options.addOption(pluginOption); options.addOption(importOption); options.addOption(exportOption); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); Properties pluginProps = cmd.getOptionProperties("plugin"); String importPluginClassName = pluginProps.getProperty("import"); IImportPlugin importPlugin = null; try { importPlugin = (IImportPlugin) Class.forName(importPluginClassName).newInstance(); } catch (ClassNotFoundException e) { logger.fatal("unable to load import plugin", e); } catch (InstantiationException e) { logger.fatal("unable to load import plugin", e); } catch (IllegalAccessException e) { logger.fatal("unable to load import plugin", e); } String exportPluginClassName = pluginProps.getProperty("export"); IExportPlugin exportPlugin = null; try { exportPlugin = (IExportPlugin) Class.forName(exportPluginClassName).newInstance(); } catch (ClassNotFoundException e) { logger.fatal("unable to load export plugin", e); } catch (InstantiationException e) { logger.fatal("unable to load export plugin", e); } catch (IllegalAccessException e) { logger.fatal("unable to load export plugin", e); } if (importPlugin != null && exportPlugin != null) { Properties importProps = cmd.getOptionProperties("import"); ImportPluginConfiguration importConfig = ImportPluginConfiguration.getConfigFromProperties(importProps); importPlugin.load(importConfig); ZGif zgif = importPlugin.getZgif(); importPlugin.unload(); Properties exportProps = cmd.getOptionProperties("export"); ExportPluginConfiguration exportConfig = ExportPluginConfiguration.getConfigFromProperties(exportProps); exportPlugin.load(exportConfig, zgif); exportPlugin.unload(); } }
From source file:pw.phylame.gaf.cli.CFetchProperties.java
@Override public void perform(CApplication app, CommandLine cmd) { app.getContext().put(option, cmd.getOptionProperties(option)); }