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

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

Introduction

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

Prototype

public CommandLine parse(Options options, String[] arguments) throws ParseException 

Source Link

Usage

From source file:com.github.cereda.arara.langchecker.LanguageUtils.java

/**
 * Parses the command line arguments./*w ww  .  j  av  a2 s.com*/
 * @param arguments An array containing the command line arguments.
 * @return A pair containing a boolean value and the file reference.
 */
public static File parse(String[] arguments) {

    // command line options
    Options options = new Options();

    try {

        // create the parse
        DefaultParser parser = new DefaultParser();
        CommandLine line = parser.parse(options, arguments);

        // check if there is a
        // file for reference
        if (line.getArgList().size() != 1) {
            throw new ParseException("Quack");
        }

        // return the file
        return new File(line.getArgList().get(0));

    } catch (ParseException exception) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("langchecker file", options);
        System.exit(1);
    }

    // never reach it
    return null;

}

From source file:net.lldp.checksims.ChecksimsCommandLine.java

/**
 * Parse a given set of CLI arguments into a Commons CLI CommandLine.
 *
 * @param args Arguments to parse/*w  w  w . j a v a 2s .c  o m*/
 * @param anyRequired Whether arguments should be required
 * @return CommandLine from parsed arguments
 * @throws ParseException Thrown on error parsing arguments
 */
static CommandLine parseOpts(String[] args, boolean anyRequired) throws ParseException {
    checkNotNull(args);

    DefaultParser parser = new DefaultParser();

    // Parse the CLI args
    return parser.parse(getOpts(anyRequired), args);
}

From source file:com.booleanworks.peacockmantisshrimp.CommandLineTool.java

private void execute(String[] args) {

    Options options = new Options();

    options.addOption(Option.builder().argName("createDefaultConfig").longOpt("createDefaultConfig").desc(
            "Create a default configuration file at the given location. (--createDefaultConfig <location>)")
            .hasArg(true).type(String.class).required(false).build());

    DefaultParser defaultParser = new DefaultParser();
    try {//from  w w w  . ja  va  2 s . c  o  m
        CommandLine commandLine = defaultParser.parse(options, args);

        if (commandLine.hasOption("createDefaultConfig")) {
            this.createDefaultConfig(commandLine.getOptionValue("createDefaultConfig", "config.xml"));
        }

    } catch (ParseException ex) {
        Logger.getLogger(CommandLineTool.class.getName()).log(Level.SEVERE, null, ex);

        HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.printHelp("java -jar hibernate-ogm-helper.jar [options]", options);
    }

}

From source file:de.elomagic.mag.MAG.java

private void run(String[] args) {
    Path configurationFile = Paths.get(System.getProperty("user.dir"), "conf", "configuration.properties");

    DefaultParser parser = new DefaultParser();
    try {//from w w  w.j a v a 2 s . c  o  m
        CommandLine commandLine = parser.parse(options, args);
        if (commandLine.hasOption(optionHelp.getOpt())) {
            printHelp();
        } else if (commandLine.hasOption(optionEncrypt.getOpt())) {
            if (commandLine.hasOption(optionConfig.getOpt())) {
                String file = commandLine.getOptionValue(optionConfig.getOpt());
                configurationFile = Paths.get(file);
            }
            encryptConfiguration(configurationFile);
        } else {
            boolean initCreateOfConfig = false;
            if (commandLine.hasOption(optionConfig.getOpt())) {
                String file = commandLine.getOptionValue(optionConfig.getOpt());
                configurationFile = Paths.get(file);

                LOGGER.info("Using configuration file \"" + file + "\".");
            } else if (Files.notExists(configurationFile)) {
                System.out.println("Creating default configuration file \"" + configurationFile + "\".");
                try (InputStream in = getClass().getResourceAsStream(Configuration.DEFAULT_PROPERTIES_FILE)) {
                    Files.createDirectories(configurationFile.getParent());
                    Files.copy(in, configurationFile, StandardCopyOption.REPLACE_EXISTING);
                }
                System.out
                        .println("Configure file \"" + configurationFile + "\" as your needs and start again.");
                initCreateOfConfig = true;
            }

            if (!initCreateOfConfig) {
                Configuration.loadConfiguration(configurationFile);
                System.out.println("Use ctrl + c to terminate MAG....");
                createCamelMain().run();
                System.out.println("MAG was terminated....");
            }
        }
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    } catch (ParseException e) {
        LOGGER.error("Parameter syntax error.", e);
        printHelp();
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
    }

}

From source file:gate.plugin.learningframework.engines.Parms.java

/**
 * Create a Parms object that contains the parsed values from the parmString.
 * The names are strings which consist of three parts, separated by colons: a short name,
 * a long name, and one of /*from   w w  w .j av a 2 s  .  co  m*/
 * b if the parameter is boolean and does not have a value, 
 * s if the parameter has a string  value,
 * d if the parameter has a double value or i if the parameter has an integer value.
 * B is used for a parameter with an excplicit boolean value.
 * If the value cannot be parsed to the given type, it is equivalent to the parameter missing.
 * @param names
 * @param parmString
 * @return 
 */
public Parms(String parmString, String... names) {
    // just treat a parmString of null equal to the empty string: do nothing
    if (parmString == null || parmString.isEmpty())
        return;
    List<String> longNames = new ArrayList<String>();
    List<String> types = new ArrayList<String>();
    Options options = new Options();
    for (String name : names) {
        String[] info = name.split(":");
        longNames.add(info[1]);
        types.add(info[2]);
        options.addOption(info[0], info[1], info[2].equals("b") ? false : true, "");
    }
    DefaultParser parser = new DefaultParser();
    parser.setIgnoreUnknownOptions(true);
    CommandLine cli = null;
    try {
        cli = parser.parse(options, parmString.split("\\s+"));
    } catch (ParseException ex) {
        //System.err.println("Parsing error");
        //ex.printStackTrace(System.err);
        logger.error("Could not parse parameters: " + parmString, ex);
    }
    if (cli != null) {
        for (int i = 0; i < longNames.size(); i++) {
            String longName = longNames.get(i);
            String type = types.get(i);
            Object value = null;
            boolean haveIt = cli.hasOption(longName);
            String optVal = cli.getOptionValue(longName);
            //System.err.println("OPTION value for "+longName+" is "+optVal+" class is "+((optVal==null)? "null" : optVal.getClass())+" have it: "+haveIt);
            if (haveIt) {
                if (type.equals("b")) {
                    value = haveIt;
                } else if (type.equals("s")) {
                    value = optVal;
                } else if (type.equals("d")) {
                    try {
                        value = Double.parseDouble(optVal);
                    } catch (Exception ex) {
                        System.err.println("Parms: cannot parse value as double, setting to null: " + optVal);
                    }
                } else if (type.equals("i")) {
                    try {
                        value = Integer.parseInt(optVal);
                    } catch (Exception ex) {
                        System.err.println("Parms: cannot parse value as int, setting to null: " + optVal);
                    }
                } else if (type.equals("B")) {
                    value = Boolean.parseBoolean(optVal);
                } else {
                    throw new GateRuntimeException("Not a valid type indicator for Parrms: " + type);
                }
            }
            parmValues.put(longName, value);
        }
    }
}

From source file:gobblin.cli.JobCommand.java

@Override
public void execute(Cli.GlobalOptions globalOptions, String[] otherArgs) {
    this.options = createCommandLineOptions();
    DefaultParser parser = new DefaultParser();
    AdminClient adminClient = null;/*from  w  w  w  .j ava 2 s.c  o m*/

    try {
        CommandLine parsedOpts = parser.parse(options, otherArgs);
        int resultLimit = parseResultsLimit(parsedOpts);
        adminClient = new AdminClient(globalOptions.getAdminServerHost(), globalOptions.getAdminServerPort());
        try {
            getAction(parsedOpts).execute(parsedOpts, adminClient, resultLimit);
        } catch (CommandException e) {
            printHelpAndExit(e.getMessage());
        }
    } catch (ParseException e) {
        printHelpAndExit("Failed to parse jobs arguments: " + e.getMessage());
    } finally {
        if (adminClient != null)
            adminClient.close();
    }
}

From source file:net.jsign.PESignerCLI.java

void execute(String... args) throws SignerException {
    DefaultParser parser = new DefaultParser();
    try {/* w w  w  . j a v  a  2s  .  com*/
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("help") || args.length == 0) {
            printHelp();
            return;
        }

        File keystore = cmd.hasOption("keystore") ? new File(cmd.getOptionValue("keystore")) : null;
        String storepass = cmd.getOptionValue("storepass");
        String storetype = cmd.getOptionValue("storetype");
        String alias = cmd.getOptionValue("alias");
        String keypass = cmd.getOptionValue("keypass");
        File keyfile = cmd.hasOption("keyfile") ? new File(cmd.getOptionValue("keyfile")) : null;
        File certfile = cmd.hasOption("certfile") ? new File(cmd.getOptionValue("certfile")) : null;
        String tsaurl = cmd.getOptionValue("tsaurl");
        String tsmode = cmd.getOptionValue("tsmode");
        String algorithm = cmd.getOptionValue("alg");
        String name = cmd.getOptionValue("name");
        String url = cmd.getOptionValue("url");
        File file = cmd.getArgList().isEmpty() ? null : new File(cmd.getArgList().get(0));

        if (keystore != null && storetype == null) {
            // guess the type of the keystore from the extension of the file
            String filename = keystore.getName().toLowerCase();
            if (filename.endsWith(".p12") || filename.endsWith(".pfx")) {
                storetype = "PKCS12";
            } else {
                storetype = "JKS";
            }
        }

        PrivateKey privateKey;
        Certificate[] chain;

        // some exciting parameter validation...
        if (keystore == null && keyfile == null && certfile == null) {
            throw new SignerException("keystore option, or keyfile and certfile options must be set");
        }
        if (keystore != null && (keyfile != null || certfile != null)) {
            throw new SignerException("keystore option can't be mixed with keyfile or certfile");
        }

        if (keystore != null) {
            // JKS or PKCS12 keystore 
            KeyStore ks;
            try {
                ks = KeyStore.getInstance(storetype);
            } catch (KeyStoreException e) {
                throw new SignerException("keystore type '" + storetype + "' is not supported", e);
            }

            if (!keystore.exists()) {
                throw new SignerException("The keystore " + keystore + " couldn't be found");
            }
            FileInputStream in = null;
            try {
                in = new FileInputStream(keystore);
                ks.load(in, storepass != null ? storepass.toCharArray() : null);
            } catch (Exception e) {
                throw new SignerException("Unable to load the keystore " + keystore, e);
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException e) {
                    // ignore
                }
            }

            if (alias == null) {
                throw new SignerException("alias option must be set");
            }

            try {
                chain = ks.getCertificateChain(alias);
            } catch (KeyStoreException e) {
                throw new SignerException(e.getMessage(), e);
            }
            if (chain == null) {
                throw new SignerException(
                        "No certificate found under the alias '" + alias + "' in the keystore " + keystore);
            }

            char[] password = keypass != null ? keypass.toCharArray() : storepass.toCharArray();

            try {
                privateKey = (PrivateKey) ks.getKey(alias, password);
            } catch (Exception e) {
                throw new SignerException("Failed to retrieve the private key from the keystore", e);
            }

        } else {
            // separate private key and certificate files (PVK/SPC)
            if (keyfile == null) {
                throw new SignerException("keyfile option must be set");
            }
            if (!keyfile.exists()) {
                throw new SignerException("The keyfile " + keyfile + " couldn't be found");
            }
            if (certfile == null) {
                throw new SignerException("certfile option must be set");
            }
            if (!certfile.exists()) {
                throw new SignerException("The certfile " + certfile + " couldn't be found");
            }

            // load the certificate chain
            try {
                chain = loadCertificateChain(certfile);
            } catch (Exception e) {
                throw new SignerException("Failed to load the certificate from " + certfile, e);
            }

            // load the private key
            try {
                privateKey = PVK.parse(keyfile, keypass);
            } catch (Exception e) {
                throw new SignerException("Failed to load the private key from " + keyfile, e);
            }
        }

        if (algorithm != null && DigestAlgorithm.of(algorithm) == null) {
            throw new SignerException("The digest algorithm " + algorithm + " is not supported");
        }

        if (file == null) {
            throw new SignerException("missing file argument");
        }
        if (!file.exists()) {
            throw new SignerException("The file " + file + " couldn't be found");
        }

        PEFile peFile;
        try {
            peFile = new PEFile(file);
        } catch (IOException e) {
            throw new SignerException("Couldn't open the executable file " + file, e);
        }

        // and now the actual work!
        PESigner signer = new PESigner(chain, privateKey).withProgramName(name).withProgramURL(url)
                .withDigestAlgorithm(DigestAlgorithm.of(algorithm))
                .withTimestamping(tsaurl != null || tsmode != null)
                .withTimestampingMode(TimestampingMode.of(tsmode)).withTimestampingAutority(tsaurl);

        try {
            System.out.println("Adding Authenticode signature to " + file);
            signer.sign(peFile);
        } catch (Exception e) {
            throw new SignerException("Couldn't sign " + file, e);
        } finally {
            try {
                peFile.close();
            } catch (IOException e) {
                System.err.println("Couldn't close " + file);
                e.printStackTrace(System.err);
            }
        }

    } catch (ParseException e) {
        e.printStackTrace();
    }
}

From source file:org.apache.ranger.policyengine.RangerPluginPerfTester.java

static boolean parseArguments(final String[] args) {

    boolean ret = false;

    options.addOption("h", "help", false, "show help.");
    options.addOption("s", "service-type", true, "Service-Type");
    options.addOption("n", "service-name", true, "Ranger service-name ");
    options.addOption("a", "app-id", true, "Application-Id");
    options.addOption("r", "ranger-host", true, "Ranger host-name");
    options.addOption("t", "socket-read-timeout", true, "Read timeout on socket in milliseconds");
    options.addOption("p", "polling-interval", true, "Polling Interval in milliseconds");
    options.addOption("c", "policy-cache-dir", true, "Policy-Cache directory ");
    options.addOption("e", "policy-evaluator-type", true, "Policy-Evaluator-Type (Cached/Other");

    DefaultParser commandLineParser = new DefaultParser();

    try {/*from w  ww  .  ja  v a2s  .c  o  m*/
        CommandLine commandLine = commandLineParser.parse(options, args);

        if (commandLine.hasOption("h")) {
            showUsage();
            return false;
        }

        serviceType = commandLine.getOptionValue("s");
        serviceName = commandLine.getOptionValue("n");
        appId = commandLine.getOptionValue("a");
        rangerHostName = commandLine.getOptionValue("r");
        policyCacheDir = commandLine.getOptionValue("c");

        try {
            String pollingIntervalStr = commandLine.getOptionValue("p");
            pollingInterval = Integer.parseInt(pollingIntervalStr);
        } catch (NumberFormatException exception) {
            // Ignore
        }

        String useCachedPolicyEvaluatorStr = commandLine.getOptionValue("e");
        if (StringUtils.equalsIgnoreCase(useCachedPolicyEvaluatorStr, "cache")) {
            useCachedPolicyEvaluator = true;
        }

        try {
            String socketReadTimeoutStr = commandLine.getOptionValue("t");
            socketReadTimeout = Integer.parseInt(socketReadTimeoutStr);
        } catch (NumberFormatException exception) {
            // Ignore
        }

        ret = true;

    } catch (ParseException exception) {
        System.err.println("Failed to parse arguments:" + exception);
    }

    return ret;
}

From source file:org.apache.tika.eval.reports.ResultsReporter.java

public static void main(String[] args) throws Exception {

    DefaultParser defaultCLIParser = new DefaultParser();
    CommandLine commandLine = null;//from ww w. j  av  a 2s . c o m
    try {
        commandLine = defaultCLIParser.parse(OPTIONS, args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        USAGE();
        return;
    }
    JDBCUtil dbUtil = null;
    if (commandLine.hasOption("db")) {
        Path db = Paths.get(commandLine.getOptionValue("db"));
        if (!H2Util.databaseExists(db)) {
            throw new RuntimeException("I'm sorry, but I couldn't find this h2 database: " + db
                    + "\nMake sure not to include the .mv.db at the end.");
        }
        dbUtil = new H2Util(db);
    } else if (commandLine.hasOption("jdbc")) {
        String driverClass = null;
        if (commandLine.hasOption("jdbcdriver")) {
            driverClass = commandLine.getOptionValue("jdbcdriver");
        }
        dbUtil = new JDBCUtil(commandLine.getOptionValue("jdbc"), driverClass);
    } else {
        System.err.println("Must specify either -db for the default in-memory h2 database\n"
                + "or -jdbc for a full jdbc connection string");
        USAGE();
        return;
    }
    try (Connection c = dbUtil.getConnection()) {
        Path tmpReportsFile = null;
        try {
            ResultsReporter resultsReporter = null;
            String reportsFile = commandLine.getOptionValue("rf");
            if (reportsFile == null) {
                tmpReportsFile = getDefaultReportsConfig(c);
                resultsReporter = ResultsReporter.build(tmpReportsFile);
            } else {
                resultsReporter = ResultsReporter.build(Paths.get(reportsFile));
            }

            Path reportsRootDirectory = Paths.get(commandLine.getOptionValue("rd", "reports"));
            if (Files.isDirectory(reportsRootDirectory)) {
                LOG.warn("'Reports' directory exists.  Will overwrite existing reports.");
            }

            resultsReporter.execute(c, reportsRootDirectory);
        } finally {
            if (tmpReportsFile != null) {
                Files.delete(tmpReportsFile);
            }
        }
    }
}

From source file:org.apache.tika.eval.TikaEvalCLI.java

private void handleProfile(String[] subsetArgs) throws Exception {
    List<String> argList = new ArrayList(Arrays.asList(subsetArgs));

    boolean containsBC = false;
    String inputDir = null;//from ww w  .jav a2s.com
    String extracts = null;
    String alterExtract = null;
    //confirm there's a batch-config file
    for (int i = 0; i < argList.size(); i++) {
        String arg = argList.get(i);
        if (arg.equals("-bc")) {
            containsBC = true;
        } else if (arg.equals("-inputDir")) {
            if (i + 1 >= argList.size()) {
                System.err.println("Must specify directory after -inputDir");
                ExtractProfiler.USAGE();
                return;
            }
            inputDir = argList.get(i + 1);
            i++;
        } else if (arg.equals("-extracts")) {
            if (i + 1 >= argList.size()) {
                System.err.println("Must specify directory after -extracts");
                ExtractProfiler.USAGE();
                return;
            }
            extracts = argList.get(i + 1);
            i++;
        } else if (arg.equals("-alterExtract")) {
            if (i + 1 >= argList.size()) {
                System.err.println("Must specify type 'as_is', 'first_only' or "
                        + "'concatenate_content' after -alterExtract");
                ExtractComparer.USAGE();
                return;
            }
            alterExtract = argList.get(i + 1);
            i++;
        }
    }

    if (alterExtract != null && !alterExtract.equals("as_is") && !alterExtract.equals("concatenate_content")
            && !alterExtract.equals("first_only")) {
        System.out.println("Sorry, I don't understand:" + alterExtract
                + ". The values must be one of: as_is, first_only, concatenate_content");
        ExtractProfiler.USAGE();
        return;
    }

    //need to specify each in this commandline
    //if only extracts is passed to tika-batch,
    //the crawler will see no inputDir and start crawling "input".
    //this allows the user to specify either extracts or inputDir
    if (extracts == null && inputDir != null) {
        argList.add("-extracts");
        argList.add(inputDir);
    } else if (inputDir == null && extracts != null) {
        argList.add("-inputDir");
        argList.add(extracts);
    }

    Path tmpBCConfig = null;
    try {
        tmpBCConfig = Files.createTempFile("tika-eval-profiler", ".xml");
        if (!containsBC) {
            Files.copy(this.getClass().getResourceAsStream("/tika-eval-profiler-config.xml"), tmpBCConfig,
                    StandardCopyOption.REPLACE_EXISTING);
            argList.add("-bc");
            argList.add(tmpBCConfig.toAbsolutePath().toString());
        }

        String[] updatedArgs = argList.toArray(new String[argList.size()]);
        DefaultParser defaultCLIParser = new DefaultParser();
        try {
            CommandLine commandLine = defaultCLIParser.parse(ExtractProfiler.OPTIONS, updatedArgs);
            if (commandLine.hasOption("db") && commandLine.hasOption("jdbc")) {
                System.out.println("Please specify either the default -db or the full -jdbc, not both");
                ExtractProfiler.USAGE();
                return;
            }
        } catch (ParseException e) {
            System.out.println(e.getMessage() + "\n");
            ExtractProfiler.USAGE();
            return;
        }

        FSBatchProcessCLI.main(updatedArgs);
    } finally {
        if (tmpBCConfig != null && Files.isRegularFile(tmpBCConfig)) {
            Files.delete(tmpBCConfig);
        }
    }
}