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

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

Introduction

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

Prototype

public String getOpt() 

Source Link

Document

Retrieve the name of this Option.

Usage

From source file:com.databasepreservation.cli.CLI.java

private static boolean isImportModuleOption(Option option) {
    final String type = "i";
    if (StringUtils.isNotBlank(option.getOpt())) {
        return option.getOpt().startsWith(type);
    } else if (StringUtils.isNotBlank(option.getLongOpt())) {
        return option.getLongOpt().startsWith(type);
    }//from  www.  j av  a  2s . c om
    return false;
}

From source file:com.databasepreservation.cli.CLI.java

private static boolean isExportModuleOption(Option option) {
    final String type = "e";
    if (StringUtils.isNotBlank(option.getOpt())) {
        return option.getOpt().startsWith(type);
    } else if (StringUtils.isNotBlank(option.getLongOpt())) {
        return option.getLongOpt().startsWith(type);
    }/*from w  w w.  ja v a  2 s .  c  o m*/
    return false;
}

From source file:net.sf.markov4jmeter.m4jdslmodelgenerator.CommandLineArgumentsHandler.java

/**
 * Reads the value for a given option from the specified command-line as
 * <code>int</code>./*w ww . j a  v  a2  s  . c o  m*/
 * 
 * @param commandLine
 *            command-line which provides the values.
 * @param option
 *            option whose value shall be read from command-line.
 * 
 * @return an <code>int</code> value which is 0, if the option's value is
 *         optional and undefined.
 * 
 * @throws NullPointerException
 *             in case the value is required, but could not be read as
 *             <code>int</code>.
 * @throws NumberFormatException
 *             if the parsed value does not denote an <code>int</code>
 *             value.
 */
private static boolean readOptionValueAsBoolean(final CommandLine commandLine, final Option option,
        final boolean defaultValue) throws NullPointerException {

    boolean value; // to be returned;

    final String opt = option.getOpt();

    // build an instance for reading "typed" options from command-line;
    final CmdlOptionsReader cmdlOptionsReader = new CmdlOptionsReader(commandLine);

    try {

        // might throw a NullPointerException;
        value = cmdlOptionsReader.readOptionValueAsBoolean(opt);

    } catch (final Exception ex) {

        if (option.isRequired()) {

            throw ex;

        } else {

            value = defaultValue;
        }
    }

    return value;
}

From source file:com.basistech.lucene.tools.LuceneQueryTool.java

private static void validateOptions(Options options, String[] args)
        throws org.apache.commons.cli.ParseException {
    Set<String> optionNames = Sets.newHashSet();

    // non-generic forced by commons.cli api
    for (Object o : options.getOptions()) {
        Option option = (Option) o;
        optionNames.add(option.getLongOpt());
        String shortOpt = option.getOpt();
        if (shortOpt != null) {
            optionNames.add(shortOpt);//from  w ww. ja  v a 2  s .c  o  m
        }
    }
    for (String arg : args) {
        if (arg.startsWith("-")) {
            String argName = arg.replaceFirst("-+", "");
            if (!optionNames.contains(argName)) {
                throw new org.apache.commons.cli.ParseException("Unrecognized option: " + arg);
            }
        }
    }
}

From source file:com.blockwithme.longdb.tools.DBTool.java

/** Retrieve value for specified option from command line. return null if
 * optional is true *//*from w  ww  .j av  a  2  s  .co  m*/
@CheckForNull
private static String optionVal(final Option theOptions, final boolean isOptional) {
    if (!isOptional && !CMD_LN.hasOption(theOptions.getOpt()))
        invalidCommand("Required option -" + theOptions.getOpt() + " is missing.");
    return CMD_LN.getOptionValue(theOptions.getOpt());
}

From source file:com.google.api.ads.adwords.keywordoptimizer.KeywordOptimizer.java

/**
 * Creates the seed generator based on the command line options.
 *
 * @param cmdLine the parsed command line parameters
 * @param context holding shared objects during the optimization process
 * @return a {@link SeedGenerator} object
 * @throws KeywordOptimizerException in case of an error constructing the seed generator
 *//*from   ww  w  . ja  va  2  s . c om*/
private static SeedGenerator getSeedGenerator(CommandLine cmdLine, OptimizationContext context)
        throws KeywordOptimizerException {
    Option seedOption = getOnlySeedOption(cmdLine);

    if ("sk".equals(seedOption.getOpt())) {
        String[] keywords = cmdLine.getOptionValues("sk");

        SimpleSeedGenerator seedGenerator = new SimpleSeedGenerator();
        for (String keyword : keywords) {
            log("Using seed keyword: " + keyword);
            seedGenerator.addKeyword(keyword);
        }

        return seedGenerator;
    } else if ("skf".equals(seedOption.getOpt())) {
        List<String> keywords = loadFromFile(cmdLine.getOptionValue("skf"));

        SimpleSeedGenerator seedGenerator = new SimpleSeedGenerator();
        for (String keyword : keywords) {
            log("Using seed keyword: " + keyword);
            seedGenerator.addKeyword(keyword);
        }

        return seedGenerator;
    } else if ("st".equals(seedOption.getOpt())) {
        String[] keywords = cmdLine.getOptionValues("st");

        TisSearchTermsSeedGenerator seedGenerator = new TisSearchTermsSeedGenerator(context, null);
        for (String keyword : keywords) {
            log("Using seed search term: " + keyword);
            seedGenerator.addSearchTerm(keyword);
        }

        return seedGenerator;
    } else if ("stf".equals(seedOption.getOpt())) {
        List<String> terms = loadFromFile(cmdLine.getOptionValue("skf"));

        TisSearchTermsSeedGenerator seedGenerator = new TisSearchTermsSeedGenerator(context, null);
        for (String term : terms) {
            log("Using seed serach term: " + term);
            seedGenerator.addSearchTerm(term);
        }

        return seedGenerator;
    } else if ("su".equals(seedOption.getOpt())) {
        String[] urls = cmdLine.getOptionValues("su");

        TisUrlSeedGenerator seedGenerator = new TisUrlSeedGenerator(context, null);
        for (String url : urls) {
            log("Using seed url: " + url);
            seedGenerator.addUrl(url);
        }

        return seedGenerator;
    } else if ("suf".equals(seedOption.getOpt())) {
        List<String> urls = loadFromFile(cmdLine.getOptionValue("suf"));

        TisUrlSeedGenerator seedGenerator = new TisUrlSeedGenerator(context, null);
        for (String url : urls) {
            log("Using seed url: " + url);
            seedGenerator.addUrl(url);
        }

        return seedGenerator;
    } else if ("sc".equals(seedOption.getOpt())) {
        int category = Integer.parseInt(seedOption.getValue());
        log("Using seed category: " + category);
        TisCategorySeedGenerator seedGenerator = new TisCategorySeedGenerator(context, category, null);
        return seedGenerator;
    }

    throw new KeywordOptimizerException("Seed option " + seedOption.getOpt() + " is not supported yet");
}

From source file:com.databasepreservation.cli.CLI.java

private static String getUniqueOptionIdentifier(Option option) {
    // some string that should never occur in option shortName nor longName
    final String delimiter = "\r\f\n";
    return new StringBuilder().append(delimiter).append(option.getOpt()).append(delimiter)
            .append(option.getLongOpt()).append(delimiter).toString();
}

From source file:com.google.api.ads.adwords.keywordoptimizer.KeywordOptimizer.java

/**
 * Prints the help screen./*from  w w  w.  j a v  a  2  s .  c  om*/
 *
 * @param options the expected command line parameters
 */
private static void printHelp(Options options) {
    // Automatically generate the help statement.
    HelpFormatter formatter = new HelpFormatter();
    formatter.setWidth(LINE_MAX_WIDTH);

    // Comparator to show non-argument options first.
    formatter.setOptionComparator(new Comparator<Option>() {
        @Override
        public int compare(Option o1, Option o2) {
            if (o1.hasArg() && !o2.hasArg()) {
                return 1;
            }
            if (!o1.hasArg() && o2.hasArg()) {
                return -1;
            }

            return o1.getOpt().compareTo(o2.getOpt());
        }
    });

    System.out.println("Keyword Optimizer - BETA");
    System.out.println("------------------------");
    System.out.println();
    System.out.println("This utility can be used creating a optimizing and finding a set of "
            + "'good' keywords. It uses the TargetingIdeaService / \n"
            + "TrafficEstimatorService of the AdWords API to first obtain a set "
            + "of seed keywords and then perform a round-based \nprocess for " + "optimizing them.");
    System.out.println();
    formatter.printHelp("keyword-optimizer", options);
    System.out.println();
}

From source file:com.emc.vipr.sync.ViPRSync.java

/**
 * Loads and configures plugins based on command line options.
 *//* w w w.  ja va  2s. c om*/
protected static ViPRSync cliBootstrap(String[] args) throws ParseException {
    ViPRSync sync = new ViPRSync();
    List<SyncPlugin> plugins = new ArrayList<>();

    CommandLine line = gnuParser.parse(mainOptions(), args, true);

    // find a plugin that can read from the source
    String sourceUri = line.getOptionValue(SOURCE_OPTION);
    if (sourceUri != null) {
        for (SyncSource source : sourceLoader) {
            if (source.canHandleSource(sourceUri)) {
                source.setSourceUri(sourceUri);
                sync.setSource(source);
                plugins.add(source);
                LogMF.info(l4j, "source: {0} ({1})", source.getName(), source.getClass());
                break;
            }
        }
    }

    String targetUri = line.getOptionValue(TARGET_OPTION);
    // find a plugin that can write to the target
    if (targetUri != null) {
        for (SyncTarget target : targetLoader) {
            if (target.canHandleTarget(targetUri)) {
                target.setTargetUri(targetUri);
                sync.setTarget(target);
                plugins.add(target);
                LogMF.info(l4j, "target: {0} ({1})", target.getName(), target.getClass());
                break;
            }
        }
    }

    // load filters
    List<SyncFilter> filters = new ArrayList<>();
    String filtersParameter = line.getOptionValue(FILTERS_OPTION);
    if (filtersParameter != null) {
        for (String filterName : filtersParameter.split(",")) {
            for (SyncFilter filter : filterLoader) {
                if (filter.getActivationName().equals(filterName)) {
                    filters.add(filter);
                    plugins.add(filter);
                    LogMF.info(l4j, "filter: {0} ({1})", filter.getName(), filter.getClass());
                    break;
                }
            }
        }
        sync.setFilters(filters);
    }

    // configure thread counts
    if (line.hasOption(QUERY_THREADS_OPTION))
        sync.setQueryThreadCount(Integer.parseInt(line.getOptionValue(QUERY_THREADS_OPTION)));
    if (line.hasOption(SYNC_THREADS_OPTION))
        sync.setSyncThreadCount(Integer.parseInt(line.getOptionValue(SYNC_THREADS_OPTION)));

    // configure timings display
    if (line.hasOption(TIMINGS_OPTION))
        sync.setTimingsEnabled(true);
    if (line.hasOption(TIMING_WINDOW_OPTION)) {
        sync.setTimingWindow(Integer.parseInt(line.getOptionValue(TIMING_WINDOW_OPTION)));
    }

    // configure recursive behavior
    if (line.hasOption(NON_RECURSIVE_OPTION))
        sync.setRecursive(false);

    // configure failed object tracking
    if (line.hasOption(FORGET_FAILED_OPTION))
        sync.setRememberFailed(false);

    // configure whether to delete source objects after they are successfully synced
    if (line.hasOption(DELETE_SOURCE_OPTION))
        sync.setDeleteSource(true);

    // logging options
    if (line.hasOption(DEBUG_OPTION)) {
        sync.setLogLevel(DEBUG_OPTION);
    }
    if (line.hasOption(VERBOSE_OPTION)) {
        sync.setLogLevel(VERBOSE_OPTION);
    }
    if (line.hasOption(QUIET_OPTION)) {
        sync.setLogLevel(QUIET_OPTION);
    }
    if (line.hasOption(SILENT_OPTION)) {
        sync.setLogLevel(SILENT_OPTION);
    }

    // Quick check for no-args
    if (sync.getSource() == null) {
        throw new ConfigurationException("source must be specified");
    }
    if (sync.getTarget() == null) {
        throw new ConfigurationException("target must be specified");
    }

    // Let the plugins parse their own options
    //   1. add common options and all the options from the plugins
    Options options = mainOptions();
    for (Object o : CommonOptions.getOptions().getOptions()) {
        options.addOption((Option) o);
    }
    for (SyncPlugin plugin : plugins) {
        for (Object o : plugin.getCustomOptions().getOptions()) {
            Option option = (Option) o;
            if (options.hasOption(option.getOpt())) {
                System.err.println(
                        "WARNING: The option " + option.getOpt() + " is being used by more than one plugin");
            }
            options.addOption(option);
        }
    }
    //   2. re-parse the command line based on these options
    line = gnuParser.parse(options, args);
    if (l4j.isDebugEnabled()) {
        for (Option option : line.getOptions()) {
            if (option.hasArg())
                LogMF.debug(l4j, "parsed option {0}: {1}", option.getLongOpt(),
                        line.getOptionValue(option.getLongOpt()));
            else
                LogMF.debug(l4j, "parsed option {0}", option.getLongOpt());
        }
    }
    //   3. pass the result to each plugin separately
    for (SyncPlugin plugin : plugins) {
        plugin.parseOptions(line);
    }

    return sync;
}

From source file:guru.nidi.raml.doc.OptionComparator.java

@Override
public int compare(Option o1, Option o2) {
    return options.indexOf(o1.getOpt().charAt(0)) - options.indexOf(o2.getOpt().charAt(0));
}