Example usage for org.apache.commons.cli Option getValuesList

List of usage examples for org.apache.commons.cli Option getValuesList

Introduction

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

Prototype

public List getValuesList() 

Source Link

Usage

From source file:com.github.horrorho.inflatabledonkey.args.ArgsManager.java

String parse(Option option, UnaryOperator<String> parser) {
    if (option.hasArgs()) {
        return option.getValuesList().stream().map(u -> parse(option.getLongOpt(), u, parser))
                .collect(Collectors.joining(" "));
    }/* www  .  j  av a2 s  .c  o m*/
    if (option.hasArg()) {
        return parse(option.getLongOpt(), option.getValue(), parser);
    }
    return Boolean.TRUE.toString();
}

From source file:com.github.horrorho.inflatabledonkey.args.PropertyLoader.java

void testIntegers(Option option) {
    if (!"int".equals(option.getArgName())) {
        return;/*from   w ww  . j  a va  2 s .  com*/
    }
    option.getValuesList().forEach(v -> testInteger(option.getLongOpt(), v));
}

From source file:com.github.horrorho.inflatabledonkey.args.PropertyLoader.java

String parse(Option option) {
    testIntegers(option);//from  w ww. j  a v a2s  .c  om

    if (option.hasArgs()) {
        // Array
        return option.getValuesList().stream().collect(Collectors.joining(" "));
    }
    if (option.hasArg()) {
        // Value
        return option.getValue();
    }
    // Boolean
    return Boolean.TRUE.toString();
}

From source file:ch.cyberduck.cli.TerminalOptionsInputValidator.java

public boolean validate(final CommandLine input) {
    for (Option o : input.getOptions()) {
        if (Option.UNINITIALIZED == o.getArgs()) {
            continue;
        }/*from w w  w  . j a v a2 s.  com*/
        if (o.hasOptionalArg()) {
            continue;
        }
        if (o.getArgs() != o.getValuesList().size()) {
            console.printf("Missing argument for option %s%n", o.getLongOpt());
            return false;
        }
    }
    final TerminalAction action = TerminalActionFinder.get(input);
    if (null == action) {
        console.printf("%s%n", "Missing argument");
        return false;
    }
    if (input.hasOption(TerminalOptionsBuilder.Params.existing.name())) {
        final String arg = input.getOptionValue(TerminalOptionsBuilder.Params.existing.name());
        if (null == TransferAction.forName(arg)) {
            final Set<TransferAction> actions = new HashSet<TransferAction>(
                    TransferAction.forTransfer(Transfer.Type.download));
            actions.add(TransferAction.cancel);
            console.printf("Invalid argument '%s' for option %s. Must be one of %s%n", arg,
                    TerminalOptionsBuilder.Params.existing.name(), Arrays.toString(actions.toArray()));
            return false;
        }
        switch (action) {
        case download:
            if (!validate(arg, Transfer.Type.download)) {
                return false;
            }
            break;
        case upload:
            if (!validate(arg, Transfer.Type.upload)) {
                return false;
            }
            break;
        case synchronize:
            if (!validate(arg, Transfer.Type.sync)) {
                return false;
            }
            break;
        case copy:
            if (!validate(arg, Transfer.Type.copy)) {
                return false;
            }
            break;
        }
    }
    // Validate arguments
    switch (action) {
    case list:
    case download:
        if (!validate(input.getOptionValue(action.name()))) {
            return false;
        }
        break;
    case upload:
    case copy:
    case synchronize:
        if (!validate(input.getOptionValue(action.name()))) {
            return false;
        }
        break;
    }
    return true;
}

From source file:com.googlecode.jmxtrans.cli.CommonsCliArgumentParser.java

/** Parse the options given on the command line. */
@Nonnull/*w  ww. java2s.  co  m*/
@Override
public JmxTransConfiguration parseOptions(@Nonnull String[] args)
        throws OptionsException, org.apache.commons.cli.ParseException {
    CommandLineParser parser = new GnuParser();
    CommandLine cl = parser.parse(getOptions(), args);
    Option[] options = cl.getOptions();

    JmxTransConfiguration configuration = new JmxTransConfiguration();

    for (Option option : options) {
        if (option.getOpt().equals("c")) {
            configuration.setContinueOnJsonError(Boolean.parseBoolean(option.getValue()));
        } else if (option.getOpt().equals("j")) {
            File jsonDir = new File(option.getValue());
            if (jsonDir.exists() && jsonDir.isDirectory()) {
                configuration.setJsonDir(jsonDir);
            } else {
                throw new OptionsException("Path to json directory is invalid: " + jsonDir);
            }
        } else if (option.getOpt().equals("f")) {
            File jsonFile = new File(option.getValue());
            if (jsonFile.exists() && jsonFile.isFile()) {
                configuration.setJsonFile(jsonFile);
            } else {
                throw new OptionsException("Path to json file is invalid: " + jsonFile);
            }
        } else if (option.getOpt().equals("e")) {
            configuration.setRunEndlessly(true);
        } else if (option.getOpt().equals("q")) {
            File quartzConfigFile = new File(option.getValue());
            if (quartzConfigFile.exists() && quartzConfigFile.isFile()) {
                configuration.setQuartzPropertiesFile(quartzConfigFile);
            } else {
                throw new OptionsException("Could not find path to the quartz properties file: "
                        + quartzConfigFile.getAbsolutePath());
            }
        } else if (option.getOpt().equals("s")) {
            try {
                configuration.setRunPeriod(Integer.parseInt(option.getValue()));
            } catch (NumberFormatException nfe) {
                throw new OptionsException("Seconds between server job runs must be an integer");
            }
        } else if (option.getOpt().equals("a")) {
            configuration.setAdditionalJars(option.getValuesList());
        } else if (option.getOpt().equals("h")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("java -jar jmxtrans-all.jar", getOptions());
            configuration.setHelp(true);
        }
    }
    if ((!configuration.isHelp()) && (configuration.getJsonDirOrFile() == null)) {
        throw new OptionsException("Please specify either the -f or -j option.");
    }
    return configuration;
}

From source file:org.apache.activemq.apollo.util.cli.CommonsCLISupport.java

/**
 *///  w w  w . j  av  a2 s.c  o  m
static public String[] setOptions(Object target, CommandLine cli) {
    Option[] options = cli.getOptions();
    for (Option option : options) {
        String name = option.getLongOpt();
        if (name == null)
            continue;

        String propName = convertOptionToPropertyName(name);

        String value = option.getValue();
        if (value != null) {
            Class<?> type = IntrospectionSupport.getPropertyType(target, propName);
            if (type.isArray()) {
                IntrospectionSupport.setProperty(target, propName, option.getValues());
            } else if (type.isAssignableFrom(ArrayList.class)) {
                IntrospectionSupport.setProperty(target, propName, new ArrayList(option.getValuesList()));
            } else if (type.isAssignableFrom(HashSet.class)) {
                IntrospectionSupport.setProperty(target, propName, new HashSet(option.getValuesList()));
            } else {
                IntrospectionSupport.setProperty(target, propName, value);
            }
        } else {
            IntrospectionSupport.setProperty(target, propName, true);
        }
    }
    return cli.getArgs();
}

From source file:org.apache.ambari.servicemonitor.utils.OptionHelper.java

public static String buildParsedOptionList(CommandLine commandLine) {

    StringBuilder builder = new StringBuilder();
    for (Option option : commandLine.getOptions()) {
        builder.append(option.getOpt());
        if (option.getLongOpt() != null) {
            builder.append("/").append(option.getLongOpt());
        }//from   w ww  .j ava2 s .  co m
        builder.append(": ");
        List valuesList = option.getValuesList();
        builder.append("[");
        int count = 0;
        for (Object elt : valuesList) {
            if (count > 0) {
                builder.append(", ");
            }
            builder.append('"').append(elt.toString()).append("\"");
        }
        builder.append("]\n");
    }
    return builder.toString();
}

From source file:org.apache.blur.shell.QueryCommandHelper.java

@SuppressWarnings("unchecked")
public static BlurQuery getBlurQuery(CommandLine commandLine) {
    Option[] options = commandLine.getOptions();
    Query query = new Query();
    if (commandLine.hasOption(QUERY)) {
        String queryString = join(Arrays.asList(commandLine.getOptionValues(QUERY)), " ");
        query.setQuery(queryString);/*w  ww  .ja v  a  2s. c  om*/
    }
    if (commandLine.hasOption(DISABLE_ROW_QUERY)) {
        query.setRowQuery(false);
    }
    if (commandLine.hasOption(SCORE_TYPE)) {
        String scoreTypeStr = commandLine.getOptionValue(SCORE_TYPE);
        ScoreType scoreType = ScoreType.valueOf(scoreTypeStr.toUpperCase());
        query.setScoreType(scoreType);
    }
    if (commandLine.hasOption(RECORD_FILTER)) {
        String recordFilter = commandLine.getOptionValue(RECORD_FILTER);
        query.setRecordFilter(recordFilter);
    }
    if (commandLine.hasOption(ROW_FILTER)) {
        String rowFilter = commandLine.getOptionValue(ROW_FILTER);
        query.setRecordFilter(rowFilter);
    }

    // String recordFilter;
    // String rowFilter;
    // String rowId;
    // long start;
    // int fetch;
    // long maxQueryTime;
    // long minimumNumberOfResults;
    // List<Facet> facets;
    // List<SortField> sortFields;

    BlurQuery blurQuery = new BlurQuery();
    blurQuery.setQuery(query);
    Selector selector = new Selector(Main.selector);
    if (!query.isRowQuery()) {
        selector.setRecordOnly(true);
    }
    blurQuery.setSelector(selector);
    blurQuery.setCacheResult(false);
    blurQuery.setUseCacheIfPresent(false);

    if (commandLine.hasOption(START)) {
        String startStr = commandLine.getOptionValue(START);
        blurQuery.setStart(Long.parseLong(startStr));
    }
    if (commandLine.hasOption(FETCH)) {
        String fetchStr = commandLine.getOptionValue(FETCH);
        blurQuery.setFetch(Integer.parseInt(fetchStr));
    }
    if (commandLine.hasOption(MAX_QUERY_TIME)) {
        String maxQueryTimeStr = commandLine.getOptionValue(MAX_QUERY_TIME);
        blurQuery.setMaxQueryTime(Long.parseLong(maxQueryTimeStr));
    }
    if (commandLine.hasOption(MINIMUM_NUMBER_OF_RESULTS)) {
        String minNumbResultsStr = commandLine.getOptionValue(MINIMUM_NUMBER_OF_RESULTS);
        blurQuery.setMinimumNumberOfResults(Long.parseLong(minNumbResultsStr));
    }
    if (commandLine.hasOption(ROW_ID)) {
        String rowId = commandLine.getOptionValue(ROW_FILTER);
        blurQuery.setRowId(rowId);
    }
    List<Facet> facets = new ArrayList<Facet>();
    for (Option option : options) {
        if (option.getOpt().equals(FACET)) {
            List<String> valuesList = option.getValuesList();
            Facet facet = new Facet();
            facet.setQueryStr(join(valuesList, " "));
            facets.add(facet);
        }
    }
    if (!facets.isEmpty()) {
        blurQuery.setFacets(facets);
    }

    List<SortField> sortFields = new ArrayList<SortField>();
    for (Option option : options) {
        if (option.getOpt().equals(SORT)) {
            List<String> valuesList = option.getValuesList();
            if (valuesList.size() == 2) {
                sortFields.add(new SortField(valuesList.get(0), valuesList.get(1), false));
            } else if (valuesList.size() == 3) {
                sortFields.add(new SortField(valuesList.get(0), valuesList.get(1),
                        Boolean.parseBoolean(valuesList.get(2))));
            } else {
                throw new RuntimeException("Sort take 2 or 3 parameters.");
            }
        }
    }
    if (!sortFields.isEmpty()) {
        blurQuery.setSortFields(sortFields);
    }

    if (Main.highlight) {
        blurQuery.getSelector().setHighlightOptions(new HighlightOptions());
    }

    return blurQuery;
}

From source file:org.ppojo.ArgumentsParser.java

private static void parseTemplateFileArgs(CommandLine line, ArrayList<ITemplateFileQuery> queries)
        throws ParseException {
    if (line.hasOption(OptionNames.SEARCH)) {
        Option[] options = line.getOptions();
        for (Option option : options) {
            if (option.getOpt() == OptionNames.SEARCH) {
                List<String> values = option.getValuesList();
                if (values == null || values.size() != 2)
                    throw new ParseException(
                            "Invalid values for search option. Expected two arguments for option.");
                boolean isRecursive = parserIsRecursive(values.get(0));

                String fileFilter = FolderTemplateFileQuery.getDefaultFileFilter();
                String folderPath = null;
                File file = (new File(values.get(1))).getAbsoluteFile();
                boolean exists = file.exists();
                boolean isDirectory = file.isDirectory();
                if (exists) {
                    if (isDirectory) //folder path specification with omitted pattern
                        folderPath = file.getAbsolutePath();
                    else if (file.isFile()) { //the pattern resolves to a specific file
                        TemplateFileQuery templateFileQuery = new TemplateFileQuery(file.getAbsolutePath(),
                                true);// w ww  . j  a va  2  s  .  c  o  m
                        queries.add(templateFileQuery);
                    } else
                        throw new ParseException(
                                "Invalid value for search option. Existing path value is neither a file or directory");

                } else {
                    File parentFile = file.getParentFile();
                    if (!parentFile.exists())
                        throw new FolderNotFoundException("Invalid value for search option. The folder path "
                                + parentFile.getAbsolutePath() + " does not exist");
                    if (!parentFile.isDirectory())
                        throw new InvalidFolderPathException("Invalid value for search option. The folder path "
                                + parentFile.getAbsolutePath() + " is not a folder");
                    String replaceStr = parentFile.toString();
                    if (!replaceStr.endsWith(File.separator))
                        replaceStr += File.separator;
                    fileFilter = file.toString().replace(replaceStr, "");
                    folderPath = parentFile.getAbsolutePath();
                }
                if (!Helpers.IsNullOrEmpty(folderPath)) {
                    folderPath = Paths.get(folderPath).normalize().toString();
                    FolderTemplateFileQuery query = new FolderTemplateFileQuery(folderPath, fileFilter,
                            isRecursive);
                    queries.add(query);
                }
            }
        }

    }

}