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:com.paxxis.cornerstone.messaging.service.shell.ServiceShell.java

private boolean processShutdown(CommandLine cmd) throws Exception {
    String[] vals = cmd.getOptionValues("sh");
    if (vals != null) {
        if (vals.length != 2) {
            throw new ParseException("Invalid argument for shutdown option");
        }/*from w w  w . jav  a2 s . com*/
        doShutdown(vals);
        return true;
    }
    return false;
}

From source file:ca.appbox.monitoring.jmx.jmxbox.commons.context.parser.JmxContextParserImpl.java

private void addInvokeOperationCommands(JmxContext context, CommandLine commandLine) throws JmxException {

    String[] invokeCommands = commandLine.getOptionValues(CommandLineOptions.INVOKE);

    if (invokeCommands != null) {

        for (String invokeCommandParameter : Arrays.asList(invokeCommands)) {

            String[] splittedReadCommand = invokeCommandParameter.split(";");

            // Has to be at least mBean;operationName
            if (splittedReadCommand.length < 2) {
                throw new JmxException(
                        "MBean invoke operation has to specifty at least the name of the mBean and the operation to invoke.");
            } else {

                JmxCommand invokeCommand = new JmxInvokeOperationCommandImpl(splittedReadCommand[0],
                        splittedReadCommand[1]);

                List<String> mBeanAttributes = Arrays
                        .asList(Arrays.copyOfRange(splittedReadCommand, 2, splittedReadCommand.length));

                for (String commandAttribute : mBeanAttributes) {
                    ((JmxInvokeOperationCommandImpl) invokeCommand).addParameter(commandAttribute);
                }//  w  w  w.  j  ava 2s .  c om

                context.addCommand(invokeCommand);
            }
        }
    }
}

From source file:ca.appbox.monitoring.jmx.jmxbox.commons.context.parser.JmxContextParserImpl.java

private void addReadAttributeCommands(JmxContext context, CommandLine commandLine) throws JmxException {

    String[] readAttributeCommands = commandLine.getOptionValues(CommandLineOptions.READ_ATTRIBUTE);

    if (readAttributeCommands != null) {

        for (String readCommandParameter : Arrays.asList(readAttributeCommands)) {

            String[] splittedReadCommand = readCommandParameter.split(";");

            // Has to be at least mBean;attribute
            if (splittedReadCommand.length < 2) {
                throw new JmxException("MBean read attribute has to specify at least one attribute name.");
            } else {

                List<String> mBeanAttributes = Arrays
                        .asList(Arrays.copyOfRange(splittedReadCommand, 1, splittedReadCommand.length));

                for (String commandAttribute : mBeanAttributes) {
                    context.addCommand(//from   w  ww. jav  a  2  s  . c  o m
                            new JmxReadAttributeCommandImpl(splittedReadCommand[0], commandAttribute));
                }
            }
        }
    }
}

From source file:net.ripe.rpki.validator.cli.CommandLineOptions.java

private void parsePrefetchURIs(CommandLine commandLine) {
    if (commandLine.hasOption(PREFETCH)) {
        for (String prefetchUri : commandLine.getOptionValues(PREFETCH)) {
            try {
                if (!prefetchUri.endsWith("/")) {
                    prefetchUri += "/";
                }//from w  ww .ja  va 2s.  c o m
                URI uri = new URI(prefetchUri);
                prefetchUris.add(uri);
            } catch (URISyntaxException e) {
                LOG.warn("unrecognized prefetch URI '" + prefetchUri + "' ignored");
            }
        }
    }
}

From source file:info.mikaelsvensson.devtools.analysis.shared.AbstractAnalyzer.java

public void run(String[] args, String usageHelp, Option... commandLineOptions) throws Exception {
    List<Option> options = CommandLineUtil.getInstance().getOptions(this);
    if (commandLineOptions != null && commandLineOptions.length > 0) {
        options.addAll(Arrays.asList(commandLineOptions));
    }//from  w w  w .  j  a va2 s.c  o m

    try {
        final CommandLine commandLine = CommandLineUtil.getInstance().parseArgs(args, usageHelp,
                this.getClass(), options.toArray(new Option[options.size()]));

        String reportFileName = commandLine.getOptionValue(OPT_REPORT_FILE_NAME);
        String[] files = commandLine.getOptionValues(OPT_FILES);
        runImpl(commandLine, files, reportFileName);
    } catch (CommandLineException e) {
        System.out.println(e.getHelpText());
    }
}

From source file:net.ripe.rpki.validator.cli.CommandLineOptions.java

private void parseTrustAnchorFile(CommandLine commandLine) {
    trustAnchorLocators = new ArrayList<TrustAnchorLocator>();
    for (String optionValue : commandLine.getOptionValues(TAL)) {
        TrustAnchorLocator tal = TrustAnchorLocator.fromFile(new File(optionValue));
        trustAnchorLocators.add(tal);/*from  w  ww.j a  v a 2  s .  c  om*/
        prefetchUris.addAll(tal.getPrefetchUris());
    }
}

From source file:eu.stratosphere.myriad.driver.MyriadDriverFrontend.java

/**
 * @param args//from   w  w w  .ja  v a  2s . com
 * @return
 */
private ParsedOptions parseOptions(String[] args) throws ParseException {
    ParsedOptions parsedOptions = new ParsedOptions();

    if (args.length < 1) {
        throw new ParseException("Missing dgen-install-dir argument");
    }

    parsedOptions.setFile("dgen-install-dir", new File(args[0]));

    // parse the command line arguments
    CommandLineParser parser = new PosixParser();
    CommandLine line = parser.parse(this.options, Arrays.copyOfRange(args, 1, args.length));

    if (line.hasOption('x')) {
        parsedOptions.setStringArray("execute-stage", line.getOptionValues('x'));
    } else {
        parsedOptions.setErrorMessage("execute-stage",
                "You should provide at least one data generator stage to be executed");
    }

    try {
        parsedOptions.setFloat("scaling-factor", Float.parseFloat(line.getOptionValue('s', "1.0")));
    } catch (NumberFormatException e) {
        parsedOptions.setErrorMessage("scaling-factor", e.getMessage());
    }

    try {
        parsedOptions.setShort("node-count", Short.parseShort(line.getOptionValue('N', "1")));
    } catch (NumberFormatException e) {
        parsedOptions.setErrorMessage("node-count", e.getMessage());
    }

    parsedOptions.setString("dataset-id", line.getOptionValue('m', "default-dataset"));
    parsedOptions.setFile("output-base", new File(line.getOptionValue('o', "/tmp")));

    return parsedOptions;
}

From source file:com.facebook.presto.accumulo.examples.TpcHClerkSearch.java

@Override
public int run(AccumuloConfig config, CommandLine cmd) throws Exception {
    String[] searchTerms = cmd.getOptionValues(CLERK_ID);

    ZooKeeperInstance inst = new ZooKeeperInstance(config.getInstance(), config.getZooKeepers());
    Connector conn = inst.getConnector(config.getUsername(), new PasswordToken(config.getPassword()));

    // Ensure both tables exists
    validateExists(conn, DATA_TABLE);//from w ww  .jav  a2 s  . co m
    validateExists(conn, INDEX_TABLE);

    long start = System.currentTimeMillis();

    // Create a scanner against the index table
    BatchScanner idxScanner = conn.createBatchScanner(INDEX_TABLE, new Authorizations(), 10);
    LinkedList<Range> searchRanges = new LinkedList<Range>();

    // Create a search Range from the command line args
    for (String searchTerm : searchTerms) {
        if (clerkRegex.matcher(searchTerm).matches()) {
            searchRanges.add(new Range(searchTerm));
        } else {
            throw new InvalidParameterException(
                    format("Search term %s does not match regex Clerk#[0-9]{9}", searchTerm));
        }
    }

    // Set the search ranges for our scanner
    idxScanner.setRanges(searchRanges);

    // A list to hold all of the order IDs
    LinkedList<Range> orderIds = new LinkedList<Range>();
    String orderId;

    // Process all of the records returned by the batch scanner
    for (Map.Entry<Key, Value> record : idxScanner) {
        // Get the order ID and add it to the list of order IDs
        orderIds.add(new Range(record.getKey().getColumnQualifier()));
    }

    // Close the batch scanner
    idxScanner.close();

    // If clerkIDs is empty, log a message and return 0
    if (orderIds.isEmpty()) {
        System.out.println("Found no orders with the given Clerk ID(s)");
        return 0;
    } else {
        System.out.println(format("Searching data table for %d orders", orderIds.size()));
    }

    // Initialize the batch scanner to scan the data table with
    // the previously found order IDs as the ranges
    BatchScanner dataScanner = conn.createBatchScanner(DATA_TABLE, new Authorizations(), 10);
    dataScanner.setRanges(orderIds);
    dataScanner.addScanIterator(new IteratorSetting(1, WholeRowIterator.class));

    Text row = new Text(); // The row ID
    Text colQual = new Text(); // The column qualifier of the current record

    Long orderkey = null;
    Long custkey = null;
    String orderstatus = null;
    Double totalprice = null;
    Date orderdate = null;
    String orderpriority = null;
    String clerk = null;
    Long shippriority = null;
    String comment = null;

    int numTweets = 0;
    // Process all of the records returned by the batch scanner
    for (Map.Entry<Key, Value> entry : dataScanner) {
        entry.getKey().getRow(row);
        orderkey = decode(Long.class, row.getBytes(), row.getLength());
        SortedMap<Key, Value> rowMap = WholeRowIterator.decodeRow(entry.getKey(), entry.getValue());
        for (Map.Entry<Key, Value> record : rowMap.entrySet()) {
            // Get the column qualifier from the record's key
            record.getKey().getColumnQualifier(colQual);

            switch (colQual.toString()) {
            case CUSTKEY_STR:
                custkey = decode(Long.class, record.getValue().get());
                break;
            case ORDERSTATUS_STR:
                orderstatus = decode(String.class, record.getValue().get());
                break;
            case TOTALPRICE_STR:
                totalprice = decode(Double.class, record.getValue().get());
                break;
            case ORDERDATE_STR:
                orderdate = decode(Date.class, record.getValue().get());
                break;
            case ORDERPRIORITY_STR:
                orderpriority = decode(String.class, record.getValue().get());
                break;
            case CLERK_STR:
                clerk = decode(String.class, record.getValue().get());
                break;
            case SHIPPRIORITY_STR:
                shippriority = decode(Long.class, record.getValue().get());
                break;
            case COMMENT_STR:
                comment = decode(String.class, record.getValue().get());
                break;
            default:
                throw new RuntimeException("Unknown column qualifier " + colQual);
            }
        }

        ++numTweets;
        // Write the screen name and text to stdout
        System.out.println(format("%d|%d|%s|%f|%s|%s|%s|%d|%s", orderkey, custkey, orderstatus, totalprice,
                orderdate, orderpriority, clerk, shippriority, comment));

        custkey = null;
        shippriority = null;
        orderstatus = null;
        orderpriority = null;
        clerk = null;
        comment = null;
        totalprice = null;
        orderdate = null;
    }

    // Close the batch scanner
    dataScanner.close();

    long finish = System.currentTimeMillis();

    System.out.format("Found %d orders in %s ms\n", numTweets, (finish - start));
    return 0;
}

From source file:net.sourceforge.jencrypt.CommandLineHelper.java

/**
 * Check and store jEncrypt command line options
 * /* ww  w . j  a  va 2s.c  om*/
 * @param commandLine
 */
private void getCommandlineOptions(CommandLine commandLine) {

    // Read and check command-line options
    String[] cipherOptionsEnc = commandLine.getOptionValues("enc");
    String[] cipherOptionsDec = commandLine.getOptionValues("dec");

    // Only encrypt or decrypt not both at the same time
    if (cipherOptionsEnc != null ^ cipherOptionsDec != null) {

        // Options -enc takes 2 arguments and -dec takes 1 or 2 arguments
        if (cipherOptionsEnc != null && cipherOptionsEnc.length == 2) {
            cipherMode = Cipher.ENCRYPT_MODE;
            cipherOptions = cipherOptionsEnc;
        } else if (cipherOptionsDec != null && (cipherOptionsDec.length < 3)) {
            cipherMode = Cipher.DECRYPT_MODE;

            // If no second argument was given assume current directory
            if (cipherOptionsDec.length == 1) {
                cipherOptions = new String[] { cipherOptionsDec[0], "." };
            } else {
                cipherOptions = cipherOptionsDec;
            }
        }

        if (cipherOptions != null) {
            sourceFileOrFolder = cipherOptions[0];
            targetPath = cipherOptions[1];
        }
    }
    configFileString = commandLine.getOptionValue("ini");
    passwordString = commandLine.getOptionValue("pwd");
}

From source file:at.ac.tuwien.ims.latex2mobiformulaconv.app.Main.java

private static void parseCli(String[] args) {
    CommandLineParser parser = new PosixParser();
    try {/*  w w w. j a v a  2s. co  m*/
        CommandLine cmd = parser.parse(options, args);

        // Show usage, ignore other parameters and quit
        if (cmd.hasOption('h')) {
            usage();
            logger.debug("Help called, main() exit.");
            System.exit(0);
        }

        if (cmd.hasOption('d')) {
            // Activate debug markup only - does not affect logging!
            debugMarkupOutput = true;
        }

        if (cmd.hasOption('m')) {
            exportMarkup = true;
        }

        if (cmd.hasOption('t')) {
            title = cmd.getOptionValue('t');
        }

        if (cmd.hasOption('f')) {
            filename = cmd.getOptionValue('f');
        }

        if (cmd.hasOption('n')) {
            exportMarkup = true; // implicit markup export
            noMobiConversion = true;
        }

        if (cmd.hasOption('i')) {
            String[] inputValues = cmd.getOptionValues('i');
            for (String inputValue : inputValues) {
                inputPaths.add(Paths.get(inputValue));
            }
        } else {
            logger.error("You have to specify an inputPath file or directory!");
            usage();
            System.exit(1);
        }

        if (cmd.hasOption('o')) {
            String outputDirectory = cmd.getOptionValue('o');

            outputPath = Paths.get(outputDirectory).toAbsolutePath();
            logger.debug("Output path: " + outputPath.toAbsolutePath().toString());
            if (!Files.isDirectory(outputPath) && Files.isRegularFile(outputPath)) {
                logger.error("Given output directory is a file! Exiting...");

                System.exit(1);
            }

            if (!Files.exists(outputPath)) {
                Files.createDirectory(outputPath);
            }

            if (!Files.isWritable(outputPath)) {
                logger.error("Given output directory is not writable! Exiting...");
                logger.debug(outputPath.toAbsolutePath().toString());
                System.exit(1);
            }
            logger.debug("Output path: " + outputPath.toAbsolutePath().toString());

        } else {
            // Set default output directory if none is given
            outputPath = workingDirectory;
        }

        // If set, replace LaTeX Formulas with PNG images, created by
        if (cmd.hasOption("r")) {
            logger.debug("Picture Flag set");
            replaceWithPictures = true;
        }

        if (cmd.hasOption("u")) {
            logger.debug("Use calibre instead of kindlegen");
            useCalibreInsteadOfKindleGen = true;
        }

        // Executable configuration
        LatexToHtmlConverter latexToHtmlConverter = (LatexToHtmlConverter) applicationContext
                .getBean("latex2html-converter");
        if (cmd.hasOption(latexToHtmlConverter.getExecOption().getOpt())) {
            String execValue = cmd.getOptionValue(latexToHtmlConverter.getExecOption().getOpt());
            logger.info("LaTeX to HTML Executable argument was given: " + execValue);
            Path execPath = Paths.get(execValue);
            latexToHtmlConverter.setExecPath(execPath);
        }

        String htmlToMobiConverterBean = KINDLEGEN_HTML2MOBI_CONVERTER;
        if (useCalibreInsteadOfKindleGen) {
            htmlToMobiConverterBean = CALIBRE_HTML2MOBI_CONVERTER;
        }

        HtmlToMobiConverter htmlToMobiConverter = (HtmlToMobiConverter) applicationContext
                .getBean(htmlToMobiConverterBean);
        Option htmlToMobiOption = htmlToMobiConverter.getExecOption();
        if (cmd.hasOption(htmlToMobiOption.getOpt())) {
            String execValue = cmd.getOptionValue(htmlToMobiOption.getOpt());
            logger.info("HTML to Mobi Executable argument was given: " + execValue);
            try {
                Path execPath = Paths.get(execValue);
                htmlToMobiConverter.setExecPath(execPath);
            } catch (InvalidPathException e) {
                logger.error("Invalid path given for --" + htmlToMobiOption.getLongOpt() + " <"
                        + htmlToMobiOption.getArgName() + ">");
                logger.error("I will try to use your system's PATH variable...");
            }
        }

    } catch (MissingOptionException m) {

        Iterator<String> missingOptionsIterator = m.getMissingOptions().iterator();
        while (missingOptionsIterator.hasNext()) {
            logger.error("Missing required options: " + missingOptionsIterator.next() + "\n");
        }
        usage();
        System.exit(1);
    } catch (MissingArgumentException a) {
        logger.error("Missing required argument for option: " + a.getOption().getOpt() + "/"
                + a.getOption().getLongOpt() + "<" + a.getOption().getArgName() + ">");
        usage();
        System.exit(2);
    } catch (ParseException e) {
        logger.error("Error parsing command line arguments, exiting...");
        logger.error(e.getMessage(), e);
        System.exit(3);
    } catch (IOException e) {
        logger.error("Error creating output path at " + outputPath.toAbsolutePath().toString());
        logger.error(e.getMessage(), e);
        logger.error("Exiting...");
        System.exit(4);
    }
}