Example usage for org.apache.commons.cli DefaultParser DefaultParser

List of usage examples for org.apache.commons.cli DefaultParser DefaultParser

Introduction

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

Prototype

DefaultParser

Source Link

Usage

From source file:io.silverware.microservices.Boot.java

/**
 * Creates initial context pre-filled with system properties, command line arguments, custom property file and default property file.
 *
 * @param args Command line arguments./*from w w  w  . ja  v a2s .  com*/
 * @return Initial context pre-filled with system properties, command line arguments, custom property file and default property file.
 */
@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 DefaultParser();

    System.getProperties().forEach((key, value) -> contextProperties.put((String) key, value));

    options.addOption(Option.builder(PROPERTY_LETTER).argName("property=value").numberOfArgs(2).valueSeparator()
            .desc("system properties").build());
    options.addOption(Option.builder(PROPERTY_FILE_LETTER).longOpt("properties").desc("Custom property file")
            .hasArg().argName("PROPERTY_FILE").build());

    try {
        final CommandLine commandLine = commandLineParser.parse(options, args);
        commandLine.getOptionProperties(PROPERTY_LETTER)
                .forEach((key, value) -> contextProperties.put((String) key, value));

        // process custom properties file
        if (commandLine.hasOption(PROPERTY_FILE_LETTER)) {
            final File propertiesFile = new File(commandLine.getOptionValue(PROPERTY_FILE_LETTER));
            if (propertiesFile.exists()) {
                final Properties props = loadProperties();
                props.forEach((key, val) -> contextProperties.putIfAbsent(key.toString(), val));
            } else {
                log.error("Specified property file %s does not exists.", propertiesFile.getAbsolutePath());
            }
        }
    } catch (ParseException pe) {
        log.error("Cannot parse arguments: ", pe);
        new HelpFormatter().printHelp("SilverWare usage:", options);
        System.exit(1);
    }

    // now add in default properties from silverware.properties on a classpath
    loadProperties().forEach((key, val) -> contextProperties.putIfAbsent(key.toString(), val));

    context.getProperties().put(Executor.SHUTDOWN_HOOK, "true");

    return context;
}

From source file:com.github.butterbrother.s2s_connection_checker.CmdLine.CmdLineParser.java

/**
 * ,    ?/*from  ww  w  .j  a  v  a 2 s  .c o m*/
 *
 * @param args   ?
 * @return ?  ?
 */
public boolean requiredHelp(String... args) {
    try {
        CommandLine helpCmdLine = new DefaultParser().parse(onlyHelpOptions, args, false);

        return helpCmdLine.hasOption('h');

    } catch (ParseException ignore) {
        return false;
    }
}

From source file:com.github.dmyersturnbull.transformations.CommandLineHelper.java

/**
 *
 * @return {@code Optional.empty()} if the command line should not be run, or the values parsed otherwise
 */// w  w  w. j a  v a 2s  .  c  o  m
@Nonnull
public Optional<ExtendedCommandLine> parse(@Nonnull String... args) {

    ExtendedCommandLine cli;

    try {

        CommandLine x = new DefaultParser().parse(m_options, args);
        cli = new ExtendedCommandLine(x);

    } catch (ParseException e) {
        sf_logger.error("Couldn't parse command-line arguments", e);
        printHelp(FileTransformationUtils.stderr());
        return Optional.empty();
    }

    if (cli.has("h")) {
        printHelp(FileTransformationUtils.stdout());
        return Optional.empty();
    } else {
        return Optional.of(cli);
    }
}

From source file:kr.ac.kaist.wala.hybridroid.command.CommandArguments.java

public CommandArguments(String[] args) {
    CommandLineParser parser = new DefaultParser();
    try {/* www.  j  ava2  s. co  m*/
        cmd = parser.parse(options, args, false);

        if (!computeDependency()) {
            usage();
            System.exit(-1);
        }
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        System.out.println("parsing error: " + e);
        usage();
        System.exit(-1);
    }
}

From source file:com.yahoo.athenz.example.ntoken.HttpExampleClient.java

private static CommandLine parseCommandLine(String[] args) {

    Options options = new Options();

    Option domain = new Option("d", "domain", true, "domain name");
    domain.setRequired(true);/*from   ww  w.j  a  v  a 2s. c o m*/
    options.addOption(domain);

    Option service = new Option("s", "service", true, "service name");
    service.setRequired(true);
    options.addOption(service);

    Option privateKey = new Option("p", "pkey", true, "private key path");
    privateKey.setRequired(true);
    options.addOption(privateKey);

    Option keyId = new Option("k", "keyid", true, "key identifier");
    keyId.setRequired(true);
    options.addOption(keyId);

    Option url = new Option("u", "url", true, "request url");
    url.setRequired(true);
    options.addOption(url);

    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd = null;

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        formatter.printHelp("http-example-client", options);
        System.exit(1);
    }

    return cmd;
}

From source file:de.topobyte.utilities.apache.commons.cli.commands.ArgumentParser.java

private ExecutionData parse(String name, CommonsCliExeOptions commonsOptions, String[] args,
        Delegate delegate) {//from www . j a  va2 s  .  com
    Options options = commonsOptions.getOptions();
    try {
        CommandLine line = new DefaultParser().parse(options, args);
        CommonsCliArguments arguments = new CommonsCliArguments(commonsOptions, line);
        return new ExecutionData(name, arguments, delegate);
    } catch (ParseException e) {
        error(e, commonsOptions, name);
        return null;
    }
}

From source file:gobblin.util.CLIPasswordEncryptor.java

private static CommandLine parseArgs(String[] args) throws ParseException {
    initOptions(CLI_OPTIONS);/* w w  w .  j  a v a2s  .com*/
    return new DefaultParser().parse(CLI_OPTIONS, args);
}

From source file:com.yahoo.athenz.example.zts.tls.client.ZTSTLSClient.java

private static CommandLine parseCommandLine(String[] args) {

    Options options = new Options();

    Option domain = new Option("d", "domain", true, "domain name");
    domain.setRequired(true);/*from  w  ww. j  a  v a2s  . c  o  m*/
    options.addOption(domain);

    Option service = new Option("s", "service", true, "service name");
    service.setRequired(true);
    options.addOption(service);

    Option keyId = new Option("i", "keyid", true, "key id");
    keyId.setRequired(true);
    options.addOption(keyId);

    Option key = new Option("k", "key", true, "private key path");
    key.setRequired(true);
    options.addOption(key);

    Option cert = new Option("c", "cert", true, "certficate path");
    cert.setRequired(true);
    options.addOption(cert);

    Option trustStore = new Option("t", "trustStorePath", true, "CA TrustStore path");
    trustStore.setRequired(true);
    options.addOption(trustStore);

    Option trustStorePassword = new Option("p", "trustStorePassword", true, "CA TrustStore password");
    trustStorePassword.setRequired(true);
    options.addOption(trustStorePassword);

    Option ztsUrl = new Option("z", "ztsurl", true, "ZTS Server url");
    ztsUrl.setRequired(true);
    options.addOption(ztsUrl);

    Option proxyUrl = new Option("x", "proxy", true, "Proxy Server url");
    proxyUrl.setRequired(false);
    options.addOption(proxyUrl);

    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd = null;

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        formatter.printHelp("zts-tls-client", options);
        System.exit(1);
    }

    return cmd;
}

From source file:com.haulmont.cuba.uberjar.ServerRunner.java

protected void execute(String[] args) {
    Options cliOptions = new Options();

    Option portOption = Option.builder("port").hasArg().desc("server port").argName("port").build();

    Option contextPathOption = Option.builder("contextName").hasArg().desc("application context name")
            .argName("contextName").build();

    Option frontContextPathOption = Option.builder("frontContextName").hasArg()
            .desc("front application context name").argName("frontContextName").build();

    Option portalContextPathOption = Option.builder("portalContextName").hasArg()
            .desc("portal application context name for single jar application").argName("portalContextName")
            .build();//from  w  w  w . j  a v a  2 s.c o  m

    Option jettyEnvPathOption = Option.builder("jettyEnvPath").hasArg().desc("jetty resource xml path")
            .argName("jettyEnvPath").build();

    Option jettyConfOption = Option.builder("jettyConfPath").hasArg().desc("jetty configuration xml path")
            .argName("jettyConfPath").build();

    Option stopPortOption = Option.builder("stopPort").hasArg()
            .desc("port number on which this server waits for a shutdown command").argName("stopPort").build();

    Option stopKeyOption = Option.builder("stopKey").hasArg().desc(
            "secret key on startup which must also be present on the shutdown command to enhance security")
            .argName("stopKey").build();

    Option helpOption = Option.builder("help").desc("print help information").build();

    Option stopOption = Option.builder("stop").desc("stop server").build();

    cliOptions.addOption(helpOption);
    cliOptions.addOption(stopOption);
    cliOptions.addOption(portOption);
    cliOptions.addOption(contextPathOption);
    cliOptions.addOption(frontContextPathOption);
    cliOptions.addOption(portalContextPathOption);
    cliOptions.addOption(jettyEnvPathOption);
    cliOptions.addOption(jettyConfOption);
    cliOptions.addOption(stopPortOption);
    cliOptions.addOption(stopKeyOption);

    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd;
    try {
        cmd = parser.parse(cliOptions, args);
    } catch (ParseException exp) {
        printHelp(formatter, cliOptions);
        return;
    }

    if (cmd.hasOption("help")) {
        printHelp(formatter, cliOptions);
    } else {
        int stopPort = -1;
        if (cmd.hasOption(stopPortOption.getOpt())) {
            try {
                stopPort = Integer.parseInt(cmd.getOptionValue(stopPortOption.getOpt()));
            } catch (NumberFormatException e) {
                System.out.println("stop port has to be number");
                printHelp(formatter, cliOptions);
                return;
            }
        }
        String stopKey = null;
        if (cmd.hasOption(stopKeyOption.getOpt())) {
            stopKey = cmd.getOptionValue(stopKeyOption.getOpt());
        }
        if (stopKey == null || stopKey.isEmpty()) {
            stopKey = DEFAULT_STOP_KEY;
        }
        if (cmd.hasOption("stop")) {
            if (stopPort <= 0) {
                System.out.println("stop port has to be a positive number");
                printHelp(formatter, cliOptions);
                return;
            }
            stop(stopPort, stopKey);
        } else {
            CubaJettyServer jettyServer = new CubaJettyServer();
            jettyServer.setStopPort(stopPort);
            jettyServer.setStopKey(stopKey);
            if (cmd.hasOption(portOption.getOpt())) {
                try {
                    jettyServer.setPort(Integer.parseInt(cmd.getOptionValue(portOption.getOpt())));
                } catch (NumberFormatException e) {
                    System.out.println("port has to be number");
                    printHelp(formatter, cliOptions);
                    return;
                }
            } else {
                jettyServer.setPort(getDefaultWebPort());
            }
            String contextPath = null;
            String frontContextPath = null;
            String portalContextPath = null;
            if (cmd.hasOption(contextPathOption.getOpt())) {
                String contextName = cmd.getOptionValue(contextPathOption.getOpt());
                if (contextName != null && !contextName.isEmpty()) {
                    if (PATH_DELIMITER.equals(contextName)) {
                        contextPath = PATH_DELIMITER;
                    } else {
                        contextPath = PATH_DELIMITER + contextName;
                    }
                }
            }
            if (cmd.hasOption(frontContextPathOption.getOpt())) {
                String contextName = cmd.getOptionValue(frontContextPathOption.getOpt());
                if (contextName != null && !contextName.isEmpty()) {
                    if (PATH_DELIMITER.equals(contextName)) {
                        frontContextPath = PATH_DELIMITER;
                    } else {
                        frontContextPath = PATH_DELIMITER + contextName;
                    }
                }
            }

            if (cmd.hasOption(portalContextPathOption.getOpt())) {
                String contextName = cmd.getOptionValue(portalContextPathOption.getOpt());
                if (contextName != null && !contextName.isEmpty()) {
                    if (PATH_DELIMITER.equals(contextName)) {
                        portalContextPath = PATH_DELIMITER;
                    } else {
                        portalContextPath = PATH_DELIMITER + contextName;
                    }
                }
            }

            if (contextPath == null) {
                String jarName = getJarName();
                if (jarName != null) {
                    jettyServer.setContextPath(PATH_DELIMITER + FilenameUtils.getBaseName(jarName));
                } else {
                    jettyServer.setContextPath(PATH_DELIMITER);
                }
            } else {
                jettyServer.setContextPath(contextPath);
            }
            if (frontContextPath == null) {
                if (PATH_DELIMITER.equals(contextPath)) {
                    jettyServer.setFrontContextPath(PATH_DELIMITER + "app-front");
                } else {
                    jettyServer.setFrontContextPath(jettyServer.getContextPath() + "-front");
                }
            } else {
                jettyServer.setFrontContextPath(frontContextPath);
            }
            if (portalContextPath == null) {
                if (PATH_DELIMITER.equals(contextPath)) {
                    jettyServer.setPortalContextPath(PATH_DELIMITER + "app-portal");
                } else {
                    jettyServer.setPortalContextPath(jettyServer.getContextPath() + "-portal");
                }
            } else {
                jettyServer.setPortalContextPath(frontContextPath);
            }

            if (cmd.hasOption(jettyEnvPathOption.getOpt())) {
                String jettyEnvPath = cmd.getOptionValue(jettyEnvPathOption.getOpt());
                if (jettyEnvPath != null && !jettyEnvPath.isEmpty()) {
                    File file = new File(jettyEnvPath);
                    if (!file.exists()) {
                        System.out.println("jettyEnvPath should point to an existing file");
                        printHelp(formatter, cliOptions);
                        return;
                    }
                    try {
                        jettyServer.setJettyEnvPathUrl(file.toURI().toURL());
                    } catch (MalformedURLException e) {
                        throw new RuntimeException("Unable to create jettyEnvPathUrl", e);
                    }
                }
            }

            if (cmd.hasOption(jettyConfOption.getOpt())) {
                String jettyConf = cmd.getOptionValue(jettyConfOption.getOpt());
                if (jettyConf != null && !jettyConf.isEmpty()) {
                    File file = new File(jettyConf);
                    if (!file.exists()) {
                        System.out.println("jettyConf should point to an existing file");
                        printHelp(formatter, cliOptions);
                        return;
                    }
                    try {
                        jettyServer.setJettyConfUrl(file.toURI().toURL());
                    } catch (MalformedURLException e) {
                        throw new RuntimeException("Unable to create jettyConfUrl", e);
                    }
                }
            } else {
                URL jettyConfUrl = getJettyConfUrl();
                if (jettyConfUrl != null) {
                    jettyServer.setJettyConfUrl(jettyConfUrl);
                }
            }
            System.out.println(format("Starting Jetty server on port: %s and contextPath: %s",
                    jettyServer.getPort(), jettyServer.getContextPath()));
            jettyServer.start();
        }
    }
}

From source file:de.uni_freiburg.informatik.ultimate.licence_manager.Main.java

private static CommandLine parseArguments(final String[] args, final Options cliOptions) {
    final CommandLineParser cliParser = new DefaultParser();
    try {//from  w  w  w  .j  a  v  a2s. c o m
        final CommandLine cmds = cliParser.parse(cliOptions, args);
        if (!cmds.getArgList().isEmpty()) {
            System.err.print("Superfluous arguments: " + String.join(",", cmds.getArgList()));
            return null;
        }
        return cmds;
    } catch (ParseException e) {
        System.err.println("Exception while parsing command line arguments: " + e.getMessage());
        printHelp(cliOptions);
        return null;
    }
}