Example usage for org.apache.commons.cli CommandLine getOptionValues

List of usage examples for org.apache.commons.cli CommandLine getOptionValues

Introduction

In this page you can find the example usage for org.apache.commons.cli CommandLine getOptionValues.

Prototype

public String[] getOptionValues(char opt) 

Source Link

Document

Retrieves the array of values, if any, of an option.

Usage

From source file:org.apache.maven.cli.NoSyspropChangingMavenCli.java

static void populateProperties(CommandLine commandLine, Properties systemProperties,
        Properties userProperties) {
    EnvironmentUtils.addEnvVars(systemProperties);

    // ----------------------------------------------------------------------
    // Options that are set on the command line become system properties
    // and therefore are set in the session properties. System properties
    // are most dominant.
    // ----------------------------------------------------------------------

    if (commandLine.hasOption(CLIManager.SET_SYSTEM_PROPERTY)) {
        String[] defStrs = commandLine.getOptionValues(CLIManager.SET_SYSTEM_PROPERTY);

        if (defStrs != null) {
            for (int i = 0; i < defStrs.length; ++i) {
                setCliProperty(defStrs[i], userProperties);
            }/*from  w w  w.j  a v  a2s.co m*/
        }
    }

    systemProperties.putAll(System.getProperties());

    // ----------------------------------------------------------------------
    // Properties containing info about the currently running version of Maven
    // These override any corresponding properties set on the command line
    // ----------------------------------------------------------------------

    Properties buildProperties = CLIReportingUtils.getBuildProperties();

    String mavenVersion = buildProperties.getProperty(CLIReportingUtils.BUILD_VERSION_PROPERTY);
    systemProperties.setProperty("maven.version", mavenVersion);

    String mavenBuildVersion = CLIReportingUtils.createMavenVersionString(buildProperties);
    systemProperties.setProperty("maven.build.version", mavenBuildVersion);
}

From source file:org.apache.maven.shared.release.exec.InvokerMavenExecutor.java

protected void setupRequest(InvocationRequest req, InvokerLogger bridge, String additionalArguments)
        throws MavenExecutorException {
    try {/*from w w  w.jav  a 2s  . com*/
        String[] args = CommandLineUtils.translateCommandline(additionalArguments);
        CommandLine cli = new PosixParser().parse(OPTIONS, args);

        if (cli.hasOption(SET_SYSTEM_PROPERTY)) {
            String[] properties = cli.getOptionValues(SET_SYSTEM_PROPERTY);
            Properties props = new Properties();
            for (int i = 0; i < properties.length; i++) {
                String property = properties[i];
                String name, value;
                int sep = property.indexOf("=");
                if (sep <= 0) {
                    name = property.trim();
                    value = "true";
                } else {
                    name = property.substring(0, sep).trim();
                    value = property.substring(sep + 1).trim();
                }
                props.setProperty(name, value);
            }

            req.setProperties(props);
        }

        if (cli.hasOption(OFFLINE)) {
            req.setOffline(true);
        }

        if (cli.hasOption(QUIET)) {
            // TODO: setQuiet() currently not supported by InvocationRequest
            req.setDebug(false);
        } else if (cli.hasOption(DEBUG)) {
            req.setDebug(true);
        } else if (cli.hasOption(ERRORS)) {
            req.setShowErrors(true);
        }

        if (cli.hasOption(REACTOR)) {
            req.setRecursive(true);
        } else if (cli.hasOption(NON_RECURSIVE)) {
            req.setRecursive(false);
        }

        if (cli.hasOption(UPDATE_SNAPSHOTS)) {
            req.setUpdateSnapshots(true);
        }

        if (cli.hasOption(ACTIVATE_PROFILES)) {
            String[] profiles = cli.getOptionValues(ACTIVATE_PROFILES);

            if (profiles != null) {
                req.setProfiles(Arrays.asList(profiles));
            }
        }

        if (cli.hasOption(FORCE_PLUGIN_UPDATES) || cli.hasOption(FORCE_PLUGIN_UPDATES2)) {
            getLogger().warn("Forcing plugin updates is not supported currently.");
        } else if (cli.hasOption(SUPPRESS_PLUGIN_UPDATES)) {
            req.setNonPluginUpdates(true);
        }

        if (cli.hasOption(SUPPRESS_PLUGIN_REGISTRY)) {
            getLogger().warn("Explicit suppression of the plugin registry is not supported currently.");
        }

        if (cli.hasOption(CHECKSUM_FAILURE_POLICY)) {
            req.setGlobalChecksumPolicy(InvocationRequest.CHECKSUM_POLICY_FAIL);
        } else if (cli.hasOption(CHECKSUM_WARNING_POLICY)) {
            req.setGlobalChecksumPolicy(InvocationRequest.CHECKSUM_POLICY_WARN);
        }

        if (cli.hasOption(ALTERNATE_USER_SETTINGS)) {
            req.setUserSettingsFile(new File(cli.getOptionValue(ALTERNATE_USER_SETTINGS)));
        }

        if (cli.hasOption(ALTERNATE_GLOBAL_SETTINGS)) {
            req.setGlobalSettingsFile(new File(cli.getOptionValue(ALTERNATE_GLOBAL_SETTINGS)));
        }

        if (cli.hasOption(FAIL_AT_END)) {
            req.setFailureBehavior(InvocationRequest.REACTOR_FAIL_AT_END);
        } else if (cli.hasOption(FAIL_FAST)) {
            req.setFailureBehavior(InvocationRequest.REACTOR_FAIL_FAST);
        }
        if (cli.hasOption(FAIL_NEVER)) {
            req.setFailureBehavior(InvocationRequest.REACTOR_FAIL_NEVER);
        }
        if (cli.hasOption(ALTERNATE_POM_FILE)) {
            if (req.getPomFileName() != null) {
                getLogger().info("pomFileName is already set, ignoring the -f argument");
            } else {
                req.setPomFileName(cli.getOptionValue(ALTERNATE_POM_FILE));
            }
        }

        if (cli.hasOption(THREADS)) {
            req.setThreads(cli.getOptionValue(THREADS));
        }

        if (cli.hasOption(BATCH_MODE)) {
            req.setInteractive(false);
        }

        if (cli.hasOption(ALTERNATE_USER_TOOLCHAINS)) {
            req.setToolchainsFile(new File(cli.getOptionValue(ALTERNATE_USER_TOOLCHAINS)));
        }

    } catch (Exception e) {
        throw new MavenExecutorException("Failed to re-parse additional arguments for Maven invocation.", e);
    }
}

From source file:org.apache.metron.maas.service.ApplicationMaster.java

/**
 * Parse command line options//from www . j a v a  2  s .co  m
 *
 * @param args Command line args
 * @return Whether init successful and run should be invoked
 * @throws ParseException
 * @throws IOException
 */
public boolean init(String[] args) throws ParseException, IOException {
    CommandLine cliParser = AMOptions.parse(new GnuParser(), args);

    //Check whether customer log4j.properties file exists
    if (fileExist(log4jPath)) {
        try {
            Log4jPropertyHelper.updateLog4jConfiguration(ApplicationMaster.class, log4jPath);
        } catch (Exception e) {
            LOG.warn("Can not set up custom log4j properties. " + e);
        }
    }

    if (AMOptions.HELP.has(cliParser)) {
        AMOptions.printHelp();
        return false;
    }

    zkQuorum = AMOptions.ZK_QUORUM.get(cliParser);
    zkRoot = AMOptions.ZK_ROOT.get(cliParser);
    appJarPath = new Path(AMOptions.APP_JAR_PATH.get(cliParser));

    Map<String, String> envs = System.getenv();

    if (!envs.containsKey(Environment.CONTAINER_ID.name())) {
        if (AMOptions.APP_ATTEMPT_ID.has(cliParser)) {
            String appIdStr = AMOptions.APP_ATTEMPT_ID.get(cliParser, "");
            appAttemptID = ConverterUtils.toApplicationAttemptId(appIdStr);
        } else {
            throw new IllegalArgumentException("Application Attempt Id not set in the environment");
        }
    } else {
        ContainerId containerId = ConverterUtils.toContainerId(envs.get(Environment.CONTAINER_ID.name()));
        appAttemptID = containerId.getApplicationAttemptId();
    }

    if (!envs.containsKey(ApplicationConstants.APP_SUBMIT_TIME_ENV)) {
        throw new RuntimeException(ApplicationConstants.APP_SUBMIT_TIME_ENV + " not set in the environment");
    }
    if (!envs.containsKey(Environment.NM_HOST.name())) {
        throw new RuntimeException(Environment.NM_HOST.name() + " not set in the environment");
    }
    if (!envs.containsKey(Environment.NM_HTTP_PORT.name())) {
        throw new RuntimeException(Environment.NM_HTTP_PORT + " not set in the environment");
    }
    if (!envs.containsKey(Environment.NM_PORT.name())) {
        throw new RuntimeException(Environment.NM_PORT.name() + " not set in the environment");
    }

    LOG.info("Application master for app" + ", appId=" + appAttemptID.getApplicationId().getId()
            + ", clustertimestamp=" + appAttemptID.getApplicationId().getClusterTimestamp() + ", attemptId="
            + appAttemptID.getAttemptId());

    if (cliParser.hasOption("shell_env")) {
        String shellEnvs[] = cliParser.getOptionValues("shell_env");
        for (String env : shellEnvs) {
            env = env.trim();
            int index = env.indexOf('=');
            if (index == -1) {
                shellEnv.put(env, "");
                continue;
            }
            String key = env.substring(0, index);
            String val = "";
            if (index < (env.length() - 1)) {
                val = env.substring(index + 1);
            }
            shellEnv.put(key, val);
        }
    }

    if (envs.containsKey(Constants.TIMELINEDOMAIN)) {
        domainId = envs.get(Constants.TIMELINEDOMAIN);
    }
    return true;
}

From source file:org.apache.metron.maas.service.Client.java

/**
 * Parse command line options//from w w w.  j a  v a  2  s  .c o  m
 * @param args Parsed command line options
 * @return Whether the init was successful to run the client
 * @throws ParseException
 */
public boolean init(String[] args) throws ParseException {

    CommandLine cli = ClientOptions.parse(new PosixParser(), args);

    if (LOG4J_PROPERTIES.has(cli)) {
        String log4jPath = LOG4J_PROPERTIES.get(cli);
        try {
            Log4jPropertyHelper.updateLog4jConfiguration(Client.class, log4jPath);
        } catch (Exception e) {
            LOG.warn("Can not set up custom log4j properties. " + e);
        }
    }

    keepContainers = false;
    zkQuorum = ZK_QUORUM.get(cli);
    zkRoot = ZK_ROOT.get(cli, "/metron/maas/config");
    appName = "MaaS";
    amPriority = 0;
    amQueue = QUEUE.get(cli, "default");
    amMemory = Integer.parseInt(MASTER_MEMORY.get(cli, "10"));
    amVCores = Integer.parseInt(MASTER_VCORE.get(cli, "1"));

    if (amMemory < 0) {
        throw new IllegalArgumentException(
                "Invalid memory specified for application master, exiting." + " Specified memory=" + amMemory);
    }
    if (amVCores < 0) {
        throw new IllegalArgumentException("Invalid virtual cores specified for application master, exiting."
                + " Specified virtual cores=" + amVCores);
    }

    if (!JAR.has(cli)) {
        try {
            appMasterJar = getJar(ApplicationMaster.class);
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException(
                    "No jar file specified for application master: " + e.getMessage(), e);
        }
    } else {
        appMasterJar = JAR.get(cli);
    }

    if (SHELL_ENV.has(cli)) {
        String envs[] = cli.getOptionValues(SHELL_ENV.option.getOpt());
        for (String env : envs) {
            env = env.trim();
            int index = env.indexOf('=');
            if (index == -1) {
                shellEnv.put(env, "");
                continue;
            }
            String key = env.substring(0, index);
            String val = "";
            if (index < (env.length() - 1)) {
                val = env.substring(index + 1);
            }
            shellEnv.put(key, val);
        }
    }

    nodeLabelExpression = NODE_LABEL_EXPRESSION.get(cli, null);

    clientTimeout = Integer.parseInt(TIMEOUT.get(cli, "600000"));

    attemptFailuresValidityInterval = -1;

    log4jPropFile = LOG4J_PROPERTIES.get(cli, "");

    // Get timeline domain options
    if (DOMAIN.has(cli)) {
        domainId = DOMAIN.get(cli);
        toCreateDomain = CREATE.has(cli);
        if (VIEW_ACLS.has(cli)) {
            viewACLs = VIEW_ACLS.get(cli);
        }
        if (MODIFY_ACLS.has(cli)) {
            modifyACLs = MODIFY_ACLS.get(cli);
        }
    }
    return true;
}

From source file:org.apache.nifi.toolkit.tls.standalone.TlsToolkitStandaloneCommandLine.java

@Override
protected CommandLine doParse(String... args) throws CommandLineParseException {
    CommandLine commandLine = super.doParse(args);
    String outputDirectory = commandLine.getOptionValue(OUTPUT_DIRECTORY_ARG, DEFAULT_OUTPUT_DIRECTORY);
    baseDir = new File(outputDirectory);

    dnPrefix = commandLine.getOptionValue(NIFI_DN_PREFIX_ARG, TlsConfig.DEFAULT_DN_PREFIX);
    dnSuffix = commandLine.getOptionValue(NIFI_DN_SUFFIX_ARG, TlsConfig.DEFAULT_DN_SUFFIX);
    domainAlternativeNames = commandLine.getOptionValue(SUBJECT_ALTERNATIVE_NAMES);

    Stream<String> globalOrderExpressions = null;
    if (commandLine.hasOption(GLOBAL_PORT_SEQUENCE_ARG)) {
        globalOrderExpressions = Arrays.stream(commandLine.getOptionValues(GLOBAL_PORT_SEQUENCE_ARG))
                .flatMap(s -> Arrays.stream(s.split(","))).map(String::trim);
    }/* w w w  . ja v  a2  s .com*/

    if (commandLine.hasOption(HOSTNAMES_ARG)) {
        instanceDefinitions = Collections.unmodifiableList(InstanceDefinition.createDefinitions(
                globalOrderExpressions,
                Arrays.stream(commandLine.getOptionValues(HOSTNAMES_ARG))
                        .flatMap(s -> Arrays.stream(s.split(",")).map(String::trim)),
                parsePasswordSupplier(commandLine, KEY_STORE_PASSWORD_ARG, passwordUtil.passwordSupplier()),
                parsePasswordSupplier(commandLine, KEY_PASSWORD_ARG,
                        commandLine.hasOption(DIFFERENT_KEY_AND_KEYSTORE_PASSWORDS_ARG)
                                ? passwordUtil.passwordSupplier()
                                : null),
                parsePasswordSupplier(commandLine, TRUST_STORE_PASSWORD_ARG, passwordUtil.passwordSupplier())));
    } else {
        instanceDefinitions = Collections.emptyList();
    }

    String[] clientDnValues = commandLine.getOptionValues(CLIENT_CERT_DN_ARG);
    if (clientDnValues != null) {
        clientDns = Collections.unmodifiableList(Arrays.stream(clientDnValues).collect(Collectors.toList()));
    } else {
        clientDns = Collections.emptyList();
    }

    clientPasswords = Collections.unmodifiableList(
            getPasswords(CLIENT_CERT_PASSWORD_ARG, commandLine, clientDns.size(), CLIENT_CERT_DN_ARG));
    clientPasswordsGenerated = commandLine.getOptionValues(CLIENT_CERT_PASSWORD_ARG) == null;
    overwrite = commandLine.hasOption(OVERWRITE_ARG);

    String nifiPropertiesFile = commandLine.getOptionValue(NIFI_PROPERTIES_FILE_ARG, "");
    try {
        if (StringUtils.isEmpty(nifiPropertiesFile)) {
            logger.info("No " + NIFI_PROPERTIES_FILE_ARG + " specified, using embedded one.");
            niFiPropertiesWriterFactory = new NiFiPropertiesWriterFactory();
        } else {
            logger.info("Using " + nifiPropertiesFile + " as template.");
            niFiPropertiesWriterFactory = new NiFiPropertiesWriterFactory(
                    new FileInputStream(nifiPropertiesFile));
        }
    } catch (IOException e) {
        printUsageAndThrow(
                "Unable to read nifi.properties from "
                        + (StringUtils.isEmpty(nifiPropertiesFile) ? "classpath" : nifiPropertiesFile),
                ExitCode.ERROR_READING_NIFI_PROPERTIES);
    }
    return commandLine;
}

From source file:org.apache.nifi.toolkit.tls.standalone.TlsToolkitStandaloneCommandLine.java

private List<String> getPasswords(String arg, CommandLine commandLine, int num, String numArg)
        throws CommandLineParseException {
    String[] optionValues = commandLine.getOptionValues(arg);
    if (optionValues == null) {
        return IntStream.range(0, num).mapToObj(operand -> passwordUtil.generatePassword())
                .collect(Collectors.toList());
    }//from   w  w  w .  ja va  2 s.  com
    if (optionValues.length == 1) {
        return IntStream.range(0, num).mapToObj(value -> optionValues[0]).collect(Collectors.toList());
    } else if (optionValues.length == num) {
        return Arrays.stream(optionValues).collect(Collectors.toList());
    }
    return printUsageAndThrow(
            "Expected either 1 value or " + num + " (the number of " + numArg + ") values for " + arg,
            ExitCode.ERROR_INCORRECT_NUMBER_OF_PASSWORDS);
}

From source file:org.apache.nifi.toolkit.tls.standalone.TlsToolkitStandaloneCommandLine.java

private Supplier<String> parsePasswordSupplier(CommandLine commandLine, String option,
        Supplier<String> defaultSupplier) {
    if (commandLine.hasOption(option)) {
        String[] values = commandLine.getOptionValues(option);
        if (values.length == 1) {
            return PasswordUtil.passwordSupplier(values[0]);
        } else {//from   w  w w . j a  v a  2 s.c o m
            return PasswordUtil.passwordSupplier("Provided " + option + " exhausted, please don't specify "
                    + option
                    + ", specify one value to be used for all NiFi instances, or specify one value for each NiFi instance.",
                    values);
        }
    } else {
        return defaultSupplier;
    }
}

From source file:org.apache.nutch.indexer.field.BasicFields.java

/**
 * Runs the BasicFields tool./*from  w  w  w  .j av  a 2  s  .c  om*/
 */
public int run(String[] args) throws Exception {

    Options options = new Options();
    Option helpOpts = OptionBuilder.withArgName("help").withDescription("show this help message")
            .create("help");
    Option outputOpts = OptionBuilder.withArgName("output").hasArg()
            .withDescription("the output index directory").create("output");
    Option webGraphOpts = OptionBuilder.withArgName("webgraphdb").hasArg()
            .withDescription("the webgraphdb to use").create("webgraphdb");
    Option segOpts = OptionBuilder.withArgName("segment").hasArgs().withDescription("the segment(s) to use")
            .create("segment");
    options.addOption(helpOpts);
    options.addOption(webGraphOpts);
    options.addOption(segOpts);
    options.addOption(outputOpts);

    CommandLineParser parser = new GnuParser();
    try {

        CommandLine line = parser.parse(options, args);
        if (line.hasOption("help") || !line.hasOption("webgraphdb") || !line.hasOption("output")
                || !line.hasOption("segment")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("BasicFields", options);
            return -1;
        }

        // get the command line options and all of the segments
        String webGraphDb = line.getOptionValue("webgraphdb");
        String output = line.getOptionValue("output");
        String[] segments = line.getOptionValues("segment");
        Path[] segPaths = new Path[segments.length];
        for (int i = 0; i < segments.length; i++) {
            segPaths[i] = new Path(segments[i]);
        }

        createFields(new Path(webGraphDb, WebGraph.NODE_DIR), segPaths, new Path(output));
        return 0;
    } catch (Exception e) {
        LOG.fatal("BasicFields: " + StringUtils.stringifyException(e));
        return -2;
    }
}

From source file:org.apache.nutch.indexer.field.CustomFields.java

/**
 * Runs the CustomFields job.//from   w w  w .j a v a2  s.c  o m
 */
public int run(String[] args) throws Exception {

    Options options = new Options();
    Option helpOpts = OptionBuilder.withArgName("help").withDescription("show this help message")
            .create("help");
    Option outputOpts = OptionBuilder.withArgName("output").hasArg()
            .withDescription("the output index directory").create("output");
    Option inputOpts = OptionBuilder.withArgName("input").hasArgs()
            .withDescription("the input directories with text field files").create("input");
    Option basicFieldOpts = OptionBuilder.withArgName("basicfields").hasArg()
            .withDescription("the basicfields to use").create("basicfields");
    options.addOption(helpOpts);
    options.addOption(inputOpts);
    options.addOption(basicFieldOpts);
    options.addOption(outputOpts);

    CommandLineParser parser = new GnuParser();
    try {

        CommandLine line = parser.parse(options, args);
        if (line.hasOption("help") || !line.hasOption("output") || !line.hasOption("basicfields")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("CustomFields", options);
            return -1;
        }

        String[] inputs = line.getOptionValues("input");
        Path[] inputPaths = new Path[inputs.length];
        for (int i = 0; i < inputs.length; i++) {
            inputPaths[i] = new Path(inputs[i]);
        }
        String output = line.getOptionValue("output");
        String basicFields = line.getOptionValue("basicfields");

        createFields(new Path(basicFields), inputPaths, new Path(output));
        return 0;
    } catch (Exception e) {
        LOG.fatal("CustomFields: " + StringUtils.stringifyException(e));
        return -2;
    }
}

From source file:org.azyva.dragom.util.Util.java

/**
 * Helper method to return a ReferenceGraphPathMatcherAnd that is built from the
 * ReferenceGraphPathMatcherOr specified by RootManager and a
 * ReferenceGraphPathMatcherOr built from the command line options
 * --reference-graph-path-matcher that specify ReferenceGraphPathMatcherByElement
 * literals.//from   ww  w . j  av a 2  s  . co  m
 *
 * @param commandLine CommandLine.
 * @return ReferenceGraphPathMatcher.
 */
public static ReferenceGraphPathMatcher getReferenceGraphPathMatcher(CommandLine commandLine) {
    String[] arrayStringReferenceGraphPathMatcher;
    ReferenceGraphPathMatcherOr referenceGraphPathMatcherOrCommandLine;
    ReferenceGraphPathMatcherAnd referenceGraphPathMatcherAnd;

    arrayStringReferenceGraphPathMatcher = commandLine.getOptionValues("reference-graph-path-matcher");

    if (arrayStringReferenceGraphPathMatcher == null) {
        throw new RuntimeExceptionUserError(
                "At least one --reference-graph-path-matcher option must be specified on the command line. Use the --help option to display help information.");
    }

    referenceGraphPathMatcherOrCommandLine = new ReferenceGraphPathMatcherOr();

    for (int i = 0; i < arrayStringReferenceGraphPathMatcher.length; i++) {
        referenceGraphPathMatcherOrCommandLine.addReferenceGraphPathMatcher(
                ReferenceGraphPathMatcherByElement.parse(arrayStringReferenceGraphPathMatcher[i]));
    }

    referenceGraphPathMatcherAnd = new ReferenceGraphPathMatcherAnd();

    referenceGraphPathMatcherAnd.addReferenceGraphPathMatcher(RootManager.getReferenceGraphPathMatcherOr());
    referenceGraphPathMatcherAnd.addReferenceGraphPathMatcher(referenceGraphPathMatcherOrCommandLine);

    return referenceGraphPathMatcherAnd;
}