List of usage examples for org.apache.commons.cli CommandLine getOptionProperties
public Properties getOptionProperties(String opt)
From source file:org.bonitasoft.platform.setup.PlatformSetupApplication.java
private void configureApplication(CommandLine line) { Properties systemProperties = line.getOptionProperties("D"); for (Map.Entry<Object, Object> systemProperty : systemProperties.entrySet()) { System.setProperty(systemProperty.getKey().toString(), systemProperty.getValue().toString()); }//from w w w. jav a 2s . co m }
From source file:org.commonjava.maven.ext.cli.Cli.java
public int run(String[] args) { Options options = new Options(); options.addOption("h", false, "Print this help message."); options.addOption(Option.builder("d").longOpt("debug").desc("Enable debug").build()); options.addOption(Option.builder("t").longOpt("trace").desc("Enable trace").build()); options.addOption(Option.builder("h").longOpt("help").desc("Print help").build()); options.addOption(Option.builder("f").longOpt("file").hasArgs().numberOfArgs(1).desc("POM file").build()); options.addOption(//from www . ja v a 2s.c o m Option.builder().longOpt("log-context").desc("Add log-context ID").numberOfArgs(1).build()); options.addOption( Option.builder("l").longOpt("log").desc("Log file to output logging to").numberOfArgs(1).build()); options.addOption(Option.builder("s").longOpt("settings").hasArgs().numberOfArgs(1) .desc("Optional settings.xml file").build()); options.addOption(Option.builder("P").longOpt("activeProfiles") .desc("Comma separated list of active profiles.").numberOfArgs(1).build()); options.addOption(Option.builder("o").longOpt("outputFile") .desc("outputFile to output dependencies to. Only used with '-p' (Print all project dependencies)") .numberOfArgs(1).build()); options.addOption(Option.builder("p").longOpt("printDeps").desc("Print all project dependencies").build()); options.addOption(Option.builder().longOpt("printGAVTC").desc( "Print all project dependencies in group:artifact:version:type:classifier with scope information") .build()); options.addOption( Option.builder("D").hasArgs().numberOfArgs(2).valueSeparator('=').desc("Java Properties").build()); options.addOption( Option.builder("x").hasArgs().numberOfArgs(2).desc("XPath tester ( file : xpath )").build()); CommandLineParser parser = new DefaultParser(); CommandLine cmd; try { cmd = parser.parse(options, args); } catch (ParseException e) { logger.debug("Caught problem parsing ", e); System.err.println(e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("...", options); return 10; } if (cmd.hasOption('h')) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("...", options); System.exit(0); } if (cmd.hasOption('D')) { userProps = cmd.getOptionProperties("D"); } if (cmd.hasOption('f')) { target = new File(cmd.getOptionValue('f')); } if (cmd.hasOption('s')) { settings = new File(cmd.getOptionValue('s')); } if (cmd.hasOption("log-context")) { String mdc = cmd.getOptionValue("log-context"); if (isNotEmpty(mdc)) { // Append a space to split up level and log-context markers. MDC.put("LOG-CONTEXT", mdc + ' '); } } createSession(target, settings); final Logger rootLogger = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); final ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) rootLogger; if (cmd.hasOption('l')) { LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); loggerContext.reset(); PatternLayoutEncoder ple = new PatternLayoutEncoder(); ple.setPattern("%mdc{LOG-CONTEXT}%level %logger{36} %msg%n"); ple.setContext(loggerContext); ple.start(); FileAppender<ILoggingEvent> fileAppender = new FileAppender<>(); fileAppender.setEncoder(ple); fileAppender.setContext(loggerContext); fileAppender.setName("fileLogging"); fileAppender.setAppend(false); fileAppender.setFile(cmd.getOptionValue("l")); fileAppender.start(); root.addAppender(fileAppender); root.setLevel(Level.INFO); } // Set debug logging after session creation else we get the log filled with Plexus // creation stuff. if (cmd.hasOption('d')) { root.setLevel(Level.DEBUG); } if (cmd.hasOption('t')) { root.setLevel(Level.TRACE); } if (!session.isEnabled()) { logger.info("Manipulation engine disabled via command-line option"); return 0; } if (!target.exists()) { logger.info("Manipulation engine disabled. Project {} cannot be found.", target); return 10; } // Don't bother skipping if we're just trying to analyse deps. else if (new File(target.getParentFile(), ManipulationManager.MARKER_FILE).exists() && !cmd.hasOption('p')) { logger.info("Skipping manipulation as previous execution found."); return 0; } try { Properties config = new ConfigIO().parse(target.getParentFile()); String value = session.getUserProperties().getProperty("allowConfigFilePrecedence"); if (isNotEmpty(value) && "true".equalsIgnoreCase(value)) { session.getUserProperties().putAll(config); } else { for (String key : config.stringPropertyNames()) { if (!session.getUserProperties().containsKey(key)) { session.getUserProperties().setProperty(key, config.getProperty(key)); } } } } catch (ManipulationException e) { logger.error("POM Manipulation failed: Unable to read config file ", e); return 10; } try { // Note : don't print out settings information earlier (like when we actually read it) as the logging // isn't setup then. logger.debug( "Using local repository \n{} and found global settings file in {} with contents \n{} and user settings file in {} with contents \n{}", session.getLocalRepository(), DEFAULT_GLOBAL_SETTINGS_FILE, DEFAULT_GLOBAL_SETTINGS_FILE.exists() ? FileUtils.readFileToString(DEFAULT_GLOBAL_SETTINGS_FILE) : "** File does not exist **", settings, (settings != null && settings.exists()) ? FileUtils.readFileToString(settings) : "** File does not exist **"); manipulationManager.init(session); Set<String> activeProfiles = null; if (cmd.hasOption('P')) { activeProfiles = new HashSet<>(); Collections.addAll(activeProfiles, cmd.getOptionValue('P').trim().split(",")); session.getUserProperties().setProperty(PROFILE_SCANNING, "true"); session.getActiveProfiles().addAll(activeProfiles); } if (cmd.hasOption('x')) { String[] params = cmd.getOptionValues('x'); if (params.length != 2) { throw new ManipulationException( "Invalid number of parameters (" + params.length + "); should be <file> <xpath>"); } XMLIO xmlIO = new XMLIO(); Document doc = xmlIO.parseXML(new File(params[0])); XPath xPath = XPathFactory.newInstance().newXPath(); NodeList nodeList = (NodeList) xPath.evaluate(params[1], doc, XPathConstants.NODESET); logger.info("Found {} node", nodeList.getLength()); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); logger.info("Found node {} and value {} ", node.getNodeName(), node.getTextContent()); } } else if (cmd.hasOption('p') || cmd.hasOption("printGAVTC")) { Set<ArtifactRef> ts = RESTCollector.establishAllDependencies(session, pomIO.parseProject(session.getPom()), activeProfiles); logger.info("Found {} dependencies. {}", ts.size(), ts); File output = null; if (cmd.hasOption('o')) { output = new File(cmd.getOptionValue('o')); output.delete(); } for (ArtifactRef a : ts) { String scope = null; if (a instanceof SimpleScopedArtifactRef) { scope = ((SimpleScopedArtifactRef) a).getScope(); } if (cmd.hasOption('o')) { if (cmd.hasOption("printGAVTC")) { FileUtils.writeStringToFile(output, String.format("%-80s%10s\n", a, scope), true); } else { FileUtils.writeStringToFile(output, a.asProjectVersionRef().toString() + '\n', true); } } else { if (cmd.hasOption("printGAVTC")) { System.out.format("%-80s%10s\n", a, scope); } else { System.out.println(a.asProjectVersionRef()); } } } } else { manipulationManager.scanAndApply(session); } } catch (ManipulationException e) { logger.error("POM Manipulation failed; original error is {}", e.getMessage()); logger.debug("POM Manipulation error trace is", e); return 10; } catch (RestException e) { logger.error("REST communication with {} failed. {}", userProps.getProperty("restURL"), e.getMessage()); logger.trace("Exception trace is", e); return 100; } catch (Exception e) { logger.error("POM Manipulation failed.", e); return 100; } return 0; }
From source file:org.commonjava.maven.ext.manip.Cli.java
public int run(String[] args) { Options options = new Options(); options.addOption("h", false, "Print this help message."); options.addOption(Option.builder("d").longOpt("debug").desc("Enable debug").build()); options.addOption(Option.builder("t").longOpt("debug").desc("Enable trace").build()); options.addOption(Option.builder("h").longOpt("help").desc("Print help").build()); options.addOption(Option.builder("f").longOpt("file").hasArgs().numberOfArgs(1).desc("POM file").build()); options.addOption(// w w w . j a v a 2s .c o m Option.builder().longOpt("log-context").desc("Add log-context ID").numberOfArgs(1).build()); options.addOption( Option.builder("l").longOpt("log").desc("Log file to output logging to").numberOfArgs(1).build()); options.addOption(Option.builder("s").longOpt("settings").hasArgs().numberOfArgs(1) .desc("Optional settings.xml file").build()); options.addOption(Option.builder("P").longOpt("activeProfiles") .desc("Comma separated list of active profiles.").numberOfArgs(1).build()); options.addOption(Option.builder("o").longOpt("outputFile") .desc("outputFile to output dependencies to. Only used with '-p' (Print all project dependencies)") .numberOfArgs(1).build()); options.addOption(Option.builder("p").longOpt("printDeps").desc("Print all project dependencies").build()); options.addOption(Option.builder().longOpt("printGAVTC").desc( "Print all project dependencies in group:artifact:version:type:classifier with scope information") .build()); options.addOption(Option.builder().longOpt("printUnusedDepMgmt") .desc("Print unused managed dependencies in group:artifact:version format").build()); options.addOption( Option.builder("D").hasArgs().numberOfArgs(2).valueSeparator('=').desc("Java Properties").build()); options.addOption( Option.builder("x").hasArgs().numberOfArgs(2).desc("XPath tester ( file : xpath )").build()); CommandLineParser parser = new DefaultParser(); CommandLine cmd; try { cmd = parser.parse(options, args); } catch (ParseException e) { logger.debug("Caught problem parsing ", e); System.err.println(e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("...", options); return 10; } if (cmd.hasOption('h')) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("...", options); System.exit(0); } if (cmd.hasOption('D')) { userProps = cmd.getOptionProperties("D"); } if (cmd.hasOption('f')) { target = new File(cmd.getOptionValue('f')); } if (cmd.hasOption('s')) { settings = new File(cmd.getOptionValue('s')); } if (cmd.hasOption("log-context")) { String mdc = cmd.getOptionValue("log-context"); if (isNotEmpty(mdc)) { // Append a space to split up level and log-context markers. MDC.put("LOG-CONTEXT", mdc + ' '); } } createSession(target, settings); final ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory .getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); if (cmd.hasOption('l')) { LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); loggerContext.reset(); PatternLayoutEncoder ple = new PatternLayoutEncoder(); ple.setPattern("%mdc{LOG-CONTEXT}%level %logger{36} %msg%n"); ple.setContext(loggerContext); ple.start(); FileAppender<ILoggingEvent> fileAppender = new FileAppender<>(); fileAppender.setEncoder(ple); fileAppender.setContext(loggerContext); fileAppender.setName("fileLogging"); fileAppender.setAppend(false); fileAppender.setFile(cmd.getOptionValue("l")); fileAppender.start(); root.addAppender(fileAppender); root.setLevel(Level.INFO); } // Set debug logging after session creation else we get the log filled with Plexus // creation stuff. if (cmd.hasOption('d')) { root.setLevel(Level.DEBUG); } if (cmd.hasOption('t')) { root.setLevel(Level.TRACE); } if (!session.isEnabled()) { logger.info("Manipulation engine disabled via command-line option"); return 0; } if (!target.exists()) { logger.info("Manipulation engine disabled. Project {} cannot be found.", target); return 10; } // Don't bother skipping if we're just trying to analyse deps. else if (new File(target.getParentFile(), ManipulationManager.MARKER_FILE).exists() && !cmd.hasOption('p')) { logger.info("Skipping manipulation as previous execution found."); return 0; } try { Properties config = new ConfigIO().parse(target.getParentFile()); String value = session.getUserProperties().getProperty("allowConfigFilePrecedence"); if (isNotEmpty(value) && "true".equalsIgnoreCase(value)) { session.getUserProperties().putAll(config); } else { for (String key : config.stringPropertyNames()) { if (!session.getUserProperties().containsKey(key)) { session.getUserProperties().setProperty(key, config.getProperty(key)); } } } } catch (ManipulationException e) { logger.error("POM Manipulation failed: Unable to read config file ", e); return 10; } try { // Note : don't print out settings information earlier (like when we actually read it) as the logging // isn't setup then. if (settings != null) { logger.debug("Found settings file {} with contents \n{}", settings, settings.exists() ? FileUtils.readFileToString(settings) : "** File does not exist **"); } manipulationManager.init(session); Set<String> activeProfiles = null; if (cmd.hasOption('P')) { activeProfiles = new HashSet<>(); Collections.addAll(activeProfiles, cmd.getOptionValue('P').trim().split(",")); if (session.getActiveProfiles() != null) { session.getActiveProfiles().addAll(activeProfiles); } } if (cmd.hasOption('x')) { String[] params = cmd.getOptionValues('x'); if (params.length != 2) { throw new ManipulationException( "Invalid number of parameters (" + params.length + "); should be <file> <xpath>"); } XMLIO xmlIO = new XMLIO(); Document doc = xmlIO.parseXML(new File(params[0])); XPath xPath = XPathFactory.newInstance().newXPath(); NodeList nodeList = (NodeList) xPath.evaluate(params[1], doc, XPathConstants.NODESET); logger.info("Found {} node", nodeList.getLength()); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); logger.info("Found node {} and value {} ", node.getNodeName(), node.getTextContent()); } } else if (cmd.hasOption('p') || cmd.hasOption("printGAVTC") || cmd.hasOption("printUnusedDepMgmt")) { Set<ArtifactRef> ts = RESTManipulator.establishAllDependencies(pomIO.parseProject(session.getPom()), activeProfiles); logger.info("Found {} dependencies.", ts.size()); File output = null; if (cmd.hasOption('o')) { output = new File(cmd.getOptionValue('o')); output.delete(); } if (cmd.hasOption("printUnusedDepMgmt")) { Set<ArtifactRef> nonMangedDeps = RESTManipulator .establishNonManagedDependencies(pomIO.parseProject(session.getPom()), activeProfiles); logger.info("Found {} non-managed dependencies.", nonMangedDeps.size()); // As the managed dependencies may have versions versus the non-managed strip off the versions to see what is left. Set<ProjectRef> tsNoV = new TreeSet<>(); for (ArtifactRef ar : ts) { tsNoV.add(ar.asProjectRef()); } Set<ProjectRef> nonManagedNoV = new TreeSet<>(); for (ArtifactRef ar : nonMangedDeps) { nonManagedNoV.add(ar.asProjectRef()); } tsNoV.removeAll(nonManagedNoV); for (ProjectRef pr : tsNoV) { if (cmd.hasOption('o')) { FileUtils.writeStringToFile(output, pr.toString(), true); } else { System.out.println(pr.toString()); } } } else { for (ArtifactRef a : ts) { String scope = null; if (a instanceof SimpleScopedArtifactRef) { scope = ((SimpleScopedArtifactRef) a).getScope(); } if (cmd.hasOption('o')) { if (cmd.hasOption("printGAVTC")) { FileUtils.writeStringToFile(output, String.format("%-80s%10s\n", a, scope), true); } else { FileUtils.writeStringToFile(output, a.asProjectVersionRef().toString() + '\n', true); } } else { if (cmd.hasOption("printGAVTC")) { System.out.format("%-80s%10s\n", a, scope); } else { System.out.println(a.asProjectVersionRef()); } } } } } else { manipulationManager.scanAndApply(session); } } catch (ManipulationException e) { logger.error("POM Manipulation failed; original error is {}", e.getMessage()); logger.debug("POM Manipulation error trace is", e); return 10; } catch (RestException e) { logger.error("REST communication with {} failed. {}", userProps.getProperty("restURL"), e.getMessage()); logger.trace("Exception trace is", e); return 100; } catch (Exception e) { logger.error("POM Manipulation failed.", e); return 100; } return 0; }
From source file:org.cryptomator.cli.Args.java
public Args(CommandLine commandLine) throws ParseException { this.bindAddr = commandLine.getOptionValue("bind", "localhost"); this.port = Integer.parseInt(commandLine.getOptionValue("port", "0")); this.vaultPaths = commandLine.getOptionProperties("vault"); this.vaultPasswords = commandLine.getOptionProperties("password"); this.vaultPasswordFiles = commandLine.getOptionProperties("passwordfile"); }
From source file:org.dcm4che3.tool.qidors.QidoRS.java
public static void main(String[] args) { CommandLine cl = null; try {// www . java2 s. com QidoRS main = new QidoRS(); cl = parseComandLine(args); main.setQuery(cl.getOptionProperties("m")); if (cl.hasOption("out-dir")) main.setOutDir(new File(cl.getOptionValue("out-dir"))); if (cl.hasOption("out-file")) main.setOutFileName(cl.getOptionValue("out-file", cl.getOptionValue("out-file"))); else main.setOutFileName(cl.getOptionValue("out-file", "qidoResponse")); if (cl.hasOption("x")) main.setXsltFile(new File(cl.getOptionValue("x"))); if (cl.hasOption("J")) { main.setJSON(true); main.parserType = ParserType.JSON; main.setOutFileName(main.getOutFileName() + ".json"); } else { main.setJSON(false); main.parserType = ParserType.XML; main.setOutFileName(main.getOutFileName() + ".xml"); } if (cl.hasOption("fuzzy")) main.setFuzzy(true); if (cl.hasOption("timezone")) main.setTimezone(true); if (cl.hasOption("limit")) main.setLimit(cl.getOptionValue("limit")); if (cl.hasOption("offset")) main.setOffset(cl.getOptionValue("offset")); main.setXmlIndent(cl.hasOption("I")); main.setXmlIncludeKeyword(!cl.hasOption("K")); main.setIncludeField(cl.getOptionValues("includefield")); if (cl.hasOption("request-timeout")) main.setRequestTimeOut(cl.getOptionValue("request-timout")); main.setUrl(cl.getArgs()[0]); String response = null; try { response = qido(main, true); } catch (IOException e) { System.out.print("Error during request {}" + e); } System.out.print(response); } catch (Exception e) { LOG.error("qidors: " + e.getMessage()); System.err.println(rb.getString("try")); System.exit(2); } }
From source file:org.eclipse.virgo.bundlor.commandline.internal.Configuration.java
public Configuration(CommandLine commandLine) { this.inputPath = commandLine.getOptionValue("i"); this.outputPath = commandLine.getOptionValue("o"); this.manifestTemplatePath = commandLine.getOptionValue("m"); this.osgiProfilePath = commandLine.getOptionValue("p"); this.propertiesPath = commandLine.getOptionValue("r"); this.properties = commandLine.getOptionProperties("D"); }
From source file:org.esa.cci.sst.tools.BasicTool.java
public final boolean setCommandLineArgs(String[] args) { final CommandLineParser parser = new PosixParser(); try {//from w w w . ja v a 2 s.c o m final CommandLine commandLine = parser.parse(getOptions(), args); setSilent(commandLine.hasOption("silent")); setDebug(commandLine.hasOption("debug")); if (commandLine.hasOption("version")) { printVersion(); return false; } if (commandLine.hasOption("help")) { printHelp(); return false; } final String configurationFilePath = commandLine.getOptionValue(CONFIG_FILE_OPTION_NAME); if (configurationFilePath != null) { final File configurationFile = new File(configurationFilePath); addConfigurationProperties(configurationFile); config.put(Configuration.KEY_MMS_CONFIGURATION, configurationFile.getPath()); } final Properties optionProperties = commandLine.getOptionProperties("D"); config.add(optionProperties); final Properties privateProperties = new Properties(); privateProperties.load(BasicTool.class.getResourceAsStream("PRIVATE.properties")); config.add(privateProperties); } catch (ParseException e) { throw new ToolException(e.getMessage(), e, ToolException.COMMAND_LINE_ARGUMENTS_PARSE_ERROR); } catch (IOException e) { throw new ToolException(e.getMessage(), e, ToolException.TOOL_ERROR); } return true; }
From source file:org.evosuite.CommandLineParameters.java
/** * Validate all the "-" options set on the command line and all * the already handled -D ones in Properties * //from w w w . j a v a 2 s. c om * @param line */ public static void validateInputOptionsAndParameters(CommandLine line) throws IllegalArgumentException { /* * TODO: here there is lot more that could be added */ java.util.Properties properties = line.getOptionProperties("D"); String cut = line.getOptionValue("class"); if (cut != null) { if (cut.endsWith(".java")) { throw new IllegalArgumentException( "The target -class should be a JVM qualifying name (e.g., org.foo.SomeClass) and not a source file"); } if (cut.endsWith(".class")) { throw new IllegalArgumentException( "The target -class should be a JVM qualifying name (e.g., org.foo.SomeClass) and not a bytecode file"); } } if (!line.hasOption(Continuous.NAME) && !line.hasOption("startedByCtg")) { for (Object p : properties.keySet()) { if (p.toString().startsWith("ctg_")) { throw new IllegalArgumentException( "Option " + p + " is only valid in '-" + Continuous.NAME + "' mode"); } } } String junitSuffix = properties.getProperty("junit_suffix"); if (junitSuffix != null && !junitSuffix.endsWith("Test")) { throw new IllegalArgumentException("A JUnit suffix should always end with a 'Test'"); } }
From source file:org.evosuite.CommandLineParameters.java
/** * Add all the properties that were set with -D * /* www. j av a 2 s . co m*/ * @param javaOpts * @param line * @throws Error */ public static void addJavaDOptions(List<String> javaOpts, CommandLine line) throws Error { java.util.Properties properties = line.getOptionProperties("D"); Set<String> propertyNames = new HashSet<>(Properties.getParameters()); for (String propertyName : properties.stringPropertyNames()) { if (!propertyNames.contains(propertyName)) { LoggingUtils.getEvoLogger().error("* Unknown property: " + propertyName); throw new Error("Unknown property: " + propertyName); } String propertyValue = properties.getProperty(propertyName); javaOpts.add("-D" + propertyName + "=" + propertyValue); System.setProperty(propertyName, propertyValue); try { Properties.getInstance().setValue(propertyName, propertyValue); } catch (Exception e) { throw new Error("Invalid value for property " + propertyName + ": " + propertyValue + ". Exception " + e.getMessage(), e); } } }
From source file:org.evosuite.CommandLineParameters.java
public static void handleClassPath(CommandLine line) { String DCP = null;//from w w w. jav a2 s.c om java.util.Properties properties = line.getOptionProperties("D"); for (String propertyName : properties.stringPropertyNames()) { if (propertyName.equals("CP")) { DCP = properties.getProperty(propertyName); } } if (line.hasOption("projectCP") && DCP != null) { throw new IllegalArgumentException("Ambiguous classpath: both -projectCP and -DCP are defined"); } String[] cpEntries = null; if (line.hasOption("projectCP")) { cpEntries = line.getOptionValue("projectCP").split(File.pathSeparator); } else if (DCP != null) { cpEntries = DCP.split(File.pathSeparator); } if (cpEntries != null) { ClassPathHandler.getInstance().changeTargetClassPath(cpEntries); } if (line.hasOption("target")) { String target = line.getOptionValue("target"); /* * let's just add the target automatically to the classpath. * This is useful for when we do not want to specify the classpath, * and so just typing '-target' on command line * */ ClassPathHandler.getInstance().addElementToTargetProjectClassPath(target); } if (line.hasOption("evosuiteCP")) { String entry = line.getOptionValue("evosuiteCP"); String[] entries = entry.split(File.pathSeparator); ClassPathHandler.getInstance().setEvoSuiteClassPath(entries); } }