Example usage for org.apache.commons.cli OptionBuilder hasArg

List of usage examples for org.apache.commons.cli OptionBuilder hasArg

Introduction

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

Prototype

public static OptionBuilder hasArg() 

Source Link

Document

The next Option created will require an argument value.

Usage

From source file:org.teavm.cli.TeaVMTestRunner.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    Options options = new Options();
    options.addOption(OptionBuilder.withArgName("directory").hasArg()
            .withDescription("a directory where to put generated files (current directory by default)")
            .withLongOpt("targetdir").create('d'));
    options.addOption(OptionBuilder.withDescription("causes TeaVM to generate minimized JavaScript file")
            .withLongOpt("minify").create("m"));
    options.addOption(OptionBuilder.withArgName("number").hasArg()
            .withDescription("how many threads should TeaVM run").withLongOpt("threads").create("t"));
    options.addOption(OptionBuilder.withArgName("class name").hasArg()
            .withDescription("qualified class name of test adapter").withLongOpt("adapter").create("a"));
    options.addOption(OptionBuilder.hasArg().hasOptionalArgs().withArgName("class name")
            .withDescription("qualified class names of transformers").withLongOpt("transformers").create("T"));

    if (args.length == 0) {
        printUsage(options);//from  w w  w  .ja va2s .  c  o  m
        return;
    }
    CommandLineParser parser = new PosixParser();
    CommandLine commandLine;
    try {
        commandLine = parser.parse(options, args);
    } catch (ParseException e) {
        printUsage(options);
        return;
    }

    TeaVMTestTool tool = new TeaVMTestTool();
    tool.setOutputDir(new File(commandLine.getOptionValue("d", ".")));
    tool.setMinifying(commandLine.hasOption("m"));
    try {
        tool.setNumThreads(Integer.parseInt(commandLine.getOptionValue("t", "1")));
    } catch (NumberFormatException e) {
        System.err.println("Invalid number specified for -t option");
        printUsage(options);
        return;
    }
    if (commandLine.hasOption("a")) {
        tool.setAdapter(instantiateAdapter(commandLine.getOptionValue("a")));
    }
    if (commandLine.hasOption("T")) {
        for (String transformerType : commandLine.getOptionValues("T")) {
            tool.getTransformers().add(instantiateTransformer(transformerType));
        }
    }
    args = commandLine.getArgs();
    if (args.length == 0) {
        System.err.println("You did not specify any test classes");
        printUsage(options);
        return;
    }
    tool.getTestClasses().addAll(Arrays.asList(args));

    tool.setLog(new ConsoleTeaVMToolLog());
    tool.getProperties().putAll(System.getProperties());
    long start = System.currentTimeMillis();
    try {
        tool.generate();
    } catch (TeaVMToolException e) {
        e.printStackTrace(System.err);
        System.exit(-2);
    }
    System.out.println("Operation took " + (System.currentTimeMillis() - start) + " milliseconds");
}

From source file:org.tonguetied.server.Server.java

/**
 * Read and process command line arguments when the server is run.
 * //from w w w .j  a  va 2 s . com
 * @param args the arguments to process
 * @throws IllegalArgumentException if the arguments fail to be initialized
 *         correctly
 */
private static void readArguments(String[] args) throws IllegalArgumentException {
    final Option help = new Option("help", "print this message");
    OptionBuilder.withArgName("file");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("the name and location of the properties file to use");
    final Option propertiesFile = OptionBuilder.create("p");

    Options options = new Options();
    options.addOption(help);
    options.addOption(propertiesFile);

    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        // has the properties file argument been passed?
        if (line.hasOption("p")) {
            // initialise the member variable
            propsFile = line.getOptionValue("p");
        }
        if (line.hasOption("help")) {
            printHelp(options, 0);
        }
    } catch (ParseException pe) {
        // oops, something went wrong
        System.err.println("Parsing failed. Reason: " + pe.getMessage());
        printHelp(options, 1);
    }
}

From source file:org.transitime.applications.GtfsFileProcessor.java

/**
 * Processes all command line options using Apache CLI. Further info at
 * http://commons.apache.org/proper/commons-cli/usage.html . Returns the
 * CommandLine object that provides access to each arg. Exits if there is a
 * parsing problem.// www .j a  v  a2s.  c o  m
 * 
 * @param args
 *            The arguments from the command line
 * @return CommandLine object that provides access to all the args
 * @throws ParseException
 */
@SuppressWarnings("static-access")
// Needed for using OptionBuilder
private static CommandLine processCommandLineOptions(String[] args) {
    // Specify the options
    Options options = new Options();

    options.addOption("h", false, "Display usage and help info.");

    options.addOption(OptionBuilder.withArgName("notes").hasArg()
            .withDescription("Description of why processing the GTFS data").withLongOpt("notes").create("n"));

    options.addOption(
            OptionBuilder.withArgName("configFile").hasArg()
                    .withDescription("Specifies configuration file to read in. "
                            + "Needed for specifying how to connect to database.")
                    .withLongOpt("config").create("c"));

    options.addOption(OptionBuilder.hasArg().withArgName("url").withDescription(
            "URL where to get GTFS zip file from. It will " + "be copied over, unzipped, and processed.")
            .create("gtfsUrl"));

    options.addOption(OptionBuilder.hasArg().withArgName("zipFileName")
            .withDescription(
                    "Local file name where the GTFS zip file is. " + "It will be unzipped and processed.")
            .create("gtfsZipFileName"));

    options.addOption(OptionBuilder.hasArg().withArgName("dirName").withDescription(
            "For when unzipping GTFS files. If set then " + "the resulting files go into this subdirectory.")
            .create("unzipSubdirectory"));

    options.addOption(OptionBuilder.hasArg().withArgName("dirName")
            .withDescription("Directory where unzipped GTFS file are. Can "
                    + "be used if already have current version of GTFS data " + "and it is already unzipped.")
            .create("gtfsDirectoryName"));

    options.addOption(OptionBuilder.hasArg().withArgName("dirName")
            .withDescription("Directory where supplemental GTFS files can be "
                    + "found. These files are combined with the regular GTFS "
                    + "files. Useful for additing additional info such as " + "routeorder and hidden.")
            .create("supplementDir"));

    options.addOption(OptionBuilder.hasArg().withArgName("fileName")
            .withDescription("File that contains pairs or regex and "
                    + "replacement text. The names in the GTFS files are "
                    + "processed using these replacements to fix up spelling "
                    + "mistakes, capitalization, etc.")
            .create("regexReplaceFile"));

    options.addOption(OptionBuilder.hasArg().withArgName("meters")
            .withDescription("When set then the shapes from shapes.txt are "
                    + "offset to the right by this distance in meters. Useful "
                    + "for when shapes.txt is street centerline data. By "
                    + "offsetting the shapes then the stopPaths for the two "
                    + "directions won't overlap when zoomed in on the map. "
                    + "Can use a negative distance to adjust stopPaths to the "
                    + "left instead of right, which could be useful for "
                    + "countries where one drives on the left side of the road.")
            .create("pathOffsetDistance"));

    options.addOption(OptionBuilder.hasArg().withArgName("meters")
            .withDescription("How far a stop can be away from the stopPaths. "
                    + "If the stop is further away from the distance then "
                    + "a warning message will be output and the path will "
                    + "be modified to include the stop.")
            .create("maxStopToPathDistance"));

    options.addOption(OptionBuilder.hasArg().withArgName("meters")
            .withDescription("For consolidating vertices for a path. If "
                    + "have short segments that line up then might as combine "
                    + "them. If a vertex is off the rest of the path by only "
                    + "the distance specified then the vertex will be removed, "
                    + "thereby simplifying the path. Value is in meters. "
                    + "Default is 0.0m, which means that no vertices will be " + "eliminated.")
            .create("maxDistanceForEliminatingVertices"));

    options.addOption(OptionBuilder.hasArg().withArgName("msec")
            .withDescription("For initial travel times before AVL data "
                    + "used to refine them. Specifies how long vehicle is " + "expected to wait at the stop. "
                    + "Default is 10,000 msec (10 seconds).")
            .create("defaultWaitTimeAtStopMsec"));

    options.addOption(OptionBuilder.hasArg().withArgName("kph")
            .withDescription("For initial travel times before AVL data "
                    + "used to refine them. Specifies maximum speed " + "a vehicle can go between stops when "
                    + "determining schedule based travel times. " + "Default is 97kph (60mph).")
            .create("maxSpeedKph"));

    options.addOption(
            OptionBuilder.hasArg().withArgName("meters")
                    .withDescription("For determining how many travel time "
                            + "segments should have between a pair of stops. "
                            + "Default is 200.0m, which means that many stop stopPaths "
                            + "will have only a single travel time segment between " + "stops.")
                    .create("maxTravelTimeSegmentLength"));

    options.addOption("storeNewRevs", false,
            "Stores the config and travel time revs into ActiveRevisions " + "in database.");

    options.addOption("trimPathBeforeFirstStopOfTrip", false,
            "For trimming off path from shapes.txt for before the first "
                    + "stops of trips. Useful for when the shapes have problems "
                    + "at the beginning, which is suprisingly common.");

    // Parse the options
    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        // There was a parse problem so log the problem,
        // display the command line options so user knows
        // what is needed, and exit since can't continue.
        logger.error(e.getMessage());
        System.err.println(e.getMessage());
        displayCommandLineOptions(options);
        System.exit(0);
    }

    // Handle help option
    if (cmd.hasOption("h")) {
        displayCommandLineOptions(options);
        System.exit(0);
    }

    // Return the CommandLine so that arguments can be accessed
    return cmd;
}

From source file:org.transitime.applications.ScheduleGenerator.java

/**
 * Processes all command line options using Apache CLI.
 * Further info at http://commons.apache.org/proper/commons-cli/usage.html .
 * Returns the CommandLine object that provides access to each arg.
 * Exits if there is a parsing problem.//from   ww w. j  a va  2  s.c om
 * 
 * @param args The arguments from the command line
 * @return CommandLine object that provides access to all the args
 * @throws ParseException
 */
@SuppressWarnings("static-access") // Needed for using OptionBuilder
private static CommandLine processCommandLineOptions(String[] args) {
    // Specify the options
    Options options = new Options();

    options.addOption("h", false, "Display usage and help info.");

    options.addOption(OptionBuilder.hasArg().withArgName("dirName").isRequired()
            .withDescription("Directory where unzipped GTFS file are. Can "
                    + "be used if already have current version of GTFS data " + "and it is already unzipped.")
            .create("gtfsDirectoryName"));

    options.addOption(
            OptionBuilder.hasArg().withArgName("MM-dd-yyyy").isRequired()
                    .withDescription("Begin date for reading arrival/departure "
                            + "times from database. Format is MM-dd-yyyy, " + "such as 9-20-2014.")
                    .create("b"));

    options.addOption(OptionBuilder.hasArg().withArgName("MM-dd-yyyy")
            .withDescription("Optional end date for reading arrival/departure "
                    + "times from database. Format is MM-dd-yyyy, "
                    + "such as 9-20-2014. Will read up to current " + "time if this option is not set.")
            .create("e"));

    options.addOption(OptionBuilder.hasArg().withArgName("fraction").isRequired()
            .withDescription("Specifies fraction of times that should. " + "Good value is probably 0.2")
            .create("f"));

    options.addOption(
            OptionBuilder.hasArg().withArgName("secs")
                    .withDescription("How many seconds arrival/departure must be "
                            + "within mean for the trip/stop to not be filtered out.")
                    .create("allowableFromMean"));

    options.addOption(OptionBuilder.hasArg().withArgName("secs")
            .withDescription("How many seconds arrival/departure must be "
                    + "within original schedule time for the trip/stop to " + "not be filtered out.")
            .create("allowableFromOriginal"));

    options.addOption(OptionBuilder.hasArg().withArgName("minutes")
            .withDescription("For providing schedule adherence information. "
                    + "Specifies how many minutes a vehicle can be ahead of "
                    + "the schedule and still be considered on time. Default " + "is 1 minute.")
            .create("allowableEarly"));

    options.addOption(OptionBuilder.hasArg().withArgName("minutes")
            .withDescription("For providing schedule adherence information. "
                    + "Specifies how many minutes a vehicle can be behind "
                    + "schedule and still be considered on time. Default is " + "5 minutes.")
            .create("allowableLate"));

    options.addOption("updateFirstStopOfTrip", false,
            "Set if should modify time even for first stops of trips.");

    // Parse the options
    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        // There was a parse problem so log the problem,
        // display the command line options so user knows
        // what is needed, and exit since can't continue.
        logger.error(e.getMessage());
        displayCommandLineOptions(options);
        System.exit(0);
    }

    // Handle help option
    if (cmd.hasOption("h")) {
        displayCommandLineOptions(options);
        System.exit(0);
    }

    // Get project ID from VM param transitime.core.agencyId
    agencyId = AgencyConfig.getAgencyId();
    if (agencyId == null) {
        displayCommandLineOptions(options);
        System.exit(0);
    }

    // Determine if should update even the first stops of trips.
    // Default is to no update the times for those stops.
    doNotUpdateFirstStopOfTrip = !cmd.hasOption("updateFirstStopOfTrip");

    // Set variables based on the command line args
    gtfsDirectoryName = cmd.getOptionValue("gtfsDirectoryName");

    // Time zones are complicated. Need to create both timeForUsingCalendar
    // and also set the system timezone so that times are processed 
    // correctly when read from the database. NOTE: must set default
    // timezone before calling anything from Time.java so that when the
    // SimpleDateFormat objects are created when the Time class is
    // initialized they will get the correct timezone.
    String timeZoneStr = GtfsAgencyReader.readTimezoneString(gtfsDirectoryName);
    TimeZone.setDefault(TimeZone.getTimeZone(timeZoneStr));
    timeForUsingCalendar = new Time(timeZoneStr);

    // Get the fraction early "e" command line option
    String fractionEarlyStr = cmd.getOptionValue("f");
    try {
        desiredFractionEarly = Double.parseDouble(fractionEarlyStr);
    } catch (NumberFormatException e1) {
        System.err.println("Paramater -f \"" + desiredFractionEarly + "\" could not be parsed.");
        System.exit(-1);
    }
    if (desiredFractionEarly < 0.0 || desiredFractionEarly > 0.5) {
        System.err.println("Paramater -f \"" + desiredFractionEarly + "\" must be between 0.0 and 0.5");
        System.exit(-1);

    }

    // Get the beginTime "b" command line option
    String beginDateStr = cmd.getOptionValue("b");
    try {
        beginTime = Time.parseDate(beginDateStr);

        // If specified time is in the future then reject
        if (beginTime.getTime() > System.currentTimeMillis()) {
            System.err.println("Paramater -b \"" + beginDateStr + "\" is in the future and therefore invalid!");
            System.exit(-1);
        }
    } catch (java.text.ParseException e) {
        System.err.println(
                "Paramater -b \"" + beginDateStr + "\" could not be parsed. Format must be \"MM-dd-yyyy\"");
        System.exit(-1);
    }

    // Get the optional endTime "e" command line option
    if (cmd.hasOption("e")) {
        String endDateStr = cmd.getOptionValue("e");
        try {
            // Get the end date specified and add 24 hours since want to 
            // load data up to the end of the date
            endTime = new Date(Time.parseDate(endDateStr).getTime() + 24 * Time.MS_PER_HOUR);

        } catch (java.text.ParseException e) {
            System.err.println(
                    "Paramater -e \"" + endDateStr + "\" could not be parsed. Format must be \"MM-dd-yyyy\"");
            System.exit(-1);
        }
    } else {
        // End time not specified so simply uses current time
        endTime = new Date();
    }

    // Get the optional "allowableFromMean" command line option.
    // Default is 15 minutes.
    allowableDifferenceFromMeanSecs = 15 * Time.SEC_PER_MIN;
    if (cmd.hasOption("allowableFromMean")) {
        String param = cmd.getOptionValue("allowableFromMean");
        try {
            allowableDifferenceFromMeanSecs = Integer.parseInt(param);
        } catch (NumberFormatException e) {
            System.err.println(
                    "Option -allowableFromMean value \"" + param + "\" could not be parsed into an integer.");
            System.exit(-1);
        }
    }

    // Get the optional "allowableFromOriginal" command line option
    // Default is 30 minutes.
    allowableDifferenceFromOriginalTimeSecs = 30 * Time.SEC_PER_MIN;
    if (cmd.hasOption("allowableFromOriginal")) {
        String param = cmd.getOptionValue("allowableFromOriginal");
        try {
            allowableDifferenceFromOriginalTimeSecs = Integer.parseInt(param);
        } catch (NumberFormatException e) {
            System.err.println("Option -allowableFromOriginal value \"" + param
                    + "\" could not be parsed into an integer.");
            System.exit(-1);
        }
    }

    // Get the optional "allowableEarly" and "allowableLate" command
    // line options. Default is 1 minute early and 5 minutes late.
    allowableEarlySecs = 1 * Time.SEC_PER_MIN;
    if (cmd.hasOption("allowableEarly")) {
        String param = cmd.getOptionValue("allowableEarly");
        try {
            allowableEarlySecs = (int) (Double.parseDouble(param) * Time.SEC_PER_MIN);
        } catch (NumberFormatException e) {
            System.err.println("Option -allowableEarly value \"" + param + "\" could not be parsed.");
            System.exit(-1);
        }
    }
    allowableLateSecs = 5 * Time.SEC_PER_MIN;
    if (cmd.hasOption("allowableLate")) {
        String param = cmd.getOptionValue("allowableLate");
        try {
            allowableLateSecs = (int) (Double.parseDouble(param) * Time.SEC_PER_MIN);
        } catch (NumberFormatException e) {
            System.err.println("Option -allowableLate value \"" + param + "\" could not be parsed.");
            System.exit(-1);
        }
    }

    // Return the CommandLine so that arguments can be further accessed
    return cmd;
}

From source file:org.unigram.docvalidator.Main.java

public static void main(String[] args) throws DocumentValidatorException {
    Options options = new Options();
    options.addOption("h", "help", false, "help");

    OptionBuilder.withLongOpt("format");
    OptionBuilder.withDescription("input data format");
    OptionBuilder.hasArg();
    OptionBuilder.withArgName("FORMAT");
    options.addOption(OptionBuilder.create("f"));

    OptionBuilder.withLongOpt("input");
    OptionBuilder.withDescription("input file");
    OptionBuilder.hasOptionalArgs();/*from w w  w.j  av a2  s .c  o  m*/
    OptionBuilder.withArgName("INPUT FILE");
    options.addOption(OptionBuilder.create("i"));

    OptionBuilder.withLongOpt("conf");
    OptionBuilder.withDescription("configuration file");
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create("c"));

    OptionBuilder.withLongOpt("result-format");
    OptionBuilder.withDescription("output result format");
    OptionBuilder.hasArg();
    OptionBuilder.withArgName("RESULT FORMAT");
    options.addOption(OptionBuilder.create("r"));

    options.addOption("v", "version", false, "print the version information and exit");

    CommandLineParser parser = new BasicParser();
    CommandLine commandLine = null;

    try {
        commandLine = parser.parse(options, args);
    } catch (ParseException e) {
        LOG.error("Error occurred in parsing command line options ");
        printHelp(options);
        System.exit(-1);
    }

    String inputFormat = "plain";
    String[] inputFileNames = null;
    String configFileName = "";
    String resultFormat = "plain";
    Parser.Type parserType;
    Formatter.Type outputFormat;

    if (commandLine.hasOption("h")) {
        printHelp(options);
        System.exit(0);
    }
    if (commandLine.hasOption("v")) {
        System.out.println("1.0");
        System.exit(0);
    }
    if (commandLine.hasOption("f")) {
        inputFormat = commandLine.getOptionValue("f");
    }
    if (commandLine.hasOption("i")) {
        inputFileNames = commandLine.getOptionValues("i");
    }
    if (commandLine.hasOption("c")) {
        configFileName = commandLine.getOptionValue("c");
    }
    if (commandLine.hasOption("r")) {
        resultFormat = commandLine.getOptionValue("r");
    }

    ConfigurationLoader configLoader = new ConfigurationLoader();
    Configuration conf = configLoader.loadConfiguration(configFileName);
    if (conf == null) {
        LOG.error("Failed to initialize the DocumentValidator configuration.");
        System.exit(-1);
    }

    parserType = Parser.Type.valueOf(inputFormat.toUpperCase());
    outputFormat = Formatter.Type.valueOf(resultFormat.toUpperCase());

    DocumentCollection documentCollection = DocumentGenerator.generate(inputFileNames, conf, parserType);

    if (documentCollection == null) {
        LOG.error("Failed to create a DocumentCollection object");
        System.exit(-1);
    }
    ResultDistributor distributor = ResultDistributorFactory.createDistributor(outputFormat, System.out);

    DocumentValidator validator = new DocumentValidator.Builder().setConfiguration(conf)
            .setResultDistributor(distributor).build();

    validator.check(documentCollection);

    System.exit(0);
}

From source file:org.usergrid.standalone.Server.java

public Options createOptions() {

    Options options = new Options();
    OptionBuilder.withDescription("Initialize database");
    Option initOption = OptionBuilder.create("init");

    OptionBuilder.withDescription("Start database");
    Option dbOption = OptionBuilder.create("db");

    OptionBuilder.withDescription("Http port");
    OptionBuilder.hasArg();
    OptionBuilder.withArgName("PORT");
    OptionBuilder.withLongOpt("port");
    OptionBuilder.withType(Number.class);
    Option portOption = OptionBuilder.create('p');

    options.addOption(initOption);/*from w  w  w.  ja v  a2 s .c o  m*/
    options.addOption(dbOption);
    options.addOption(portOption);

    return options;
}

From source file:org.vbossica.springbox.cliapp.ModuleLauncher.java

@SuppressWarnings("AccessStaticViaInstance")
private void process(final String[] args) {
    Options options = new Options()
            .addOption(OptionBuilder.withLongOpt(HELP_OPTION).withDescription("shows this help").create('h'))
            .addOption(OptionBuilder.hasArg().withArgName("name").withDescription("name of the package to scan")
                    .create(PACKAGE_OPTION))
            .addOption(OptionBuilder.withDescription("lists all registered modules").create(LIST_OPTION))
            .addOption(OptionBuilder.hasArg().withArgName("name")
                    .withDescription("name of the module to execute").create(MODULE_OPTION));

    String packageName = null;/*from  w  w w .  ja  va  2  s . co m*/

    try {
        CommandLine cmd = new PosixParser().parse(options, args, true);
        if (cmd.hasOption(HELP_OPTION) && !cmd.hasOption(MODULE_OPTION)) {
            printHelp(options);
            return;
        }
        if (cmd.hasOption(PACKAGE_OPTION)) {
            packageName = cmd.getOptionValue(PACKAGE_OPTION);
        }
        if (cmd.hasOption(LIST_OPTION)) {
            listModules(packageName, System.out);
            return;
        }
        if (cmd.hasOption(MODULE_OPTION)) {
            String tool = cmd.getOptionValue(MODULE_OPTION);
            initializeTool(packageName, cmd, tool);
        } else {
            System.err.println("missing module definition");
        }
    } catch (Exception ex) {
        System.err.println(ex.getMessage());
        printHelp(options);
    }
}

From source file:org.waveprotocol.wave.examples.fedone.FlagBinder.java

/**
 * Parse command line arguments.// w ww  . ja  va 2s. co  m
 *
 * @param args argv from command line
 * @return a Guice module configured with flag support.
 * @throws ParseException on bad command line args
 */
public static Module parseFlags(String[] args, Class<?>... flagSettings) throws ParseException {
    Options options = new Options();

    List<Field> fields = new ArrayList<Field>();
    for (Class<?> settings : flagSettings) {
        fields.addAll(Arrays.asList(settings.getDeclaredFields()));
    }

    // Reflect on flagSettings class and absorb flags
    final Map<Flag, Field> flags = new LinkedHashMap<Flag, Field>();
    for (Field field : fields) {
        if (!field.isAnnotationPresent(Flag.class)) {
            continue;
        }

        // Validate target type
        if (!supportedFlagTypes.contains(field.getType())) {
            throw new IllegalArgumentException(
                    field.getType() + " is not one of the supported flag types " + supportedFlagTypes);
        }

        Flag flag = field.getAnnotation(Flag.class);
        OptionBuilder.withLongOpt(flag.name());
        OptionBuilder.hasArg();
        final OptionBuilder option = OptionBuilder.withArgName(flag.name().toUpperCase());
        if (flag.defaultValue().isEmpty()) {
            OptionBuilder.withDescription(flag.description());
        } else {
            OptionBuilder.withDescription(flag.description() + "(default: " + flag.defaultValue() + ")");
        }

        options.addOption(OptionBuilder.create());

        flags.put(flag, field);
    }

    // Parse up our cmd line
    CommandLineParser parser = new PosixParser();
    final CommandLine cmd = parser.parse(options, args);

    // Now validate them
    for (Flag flag : flags.keySet()) {
        if (flag.defaultValue().isEmpty()) {
            String help = !"".equals(flag.description()) ? flag.description() : flag.name();
            mandatoryOption(cmd, flag.name(), "must supply " + help, options);
        }
    }

    // bundle everything up in an injectable guice module
    return new AbstractModule() {

        @Override
        protected void configure() {
            // We must iterate the flags a third time when binding.
            // Note: do not collapse these loops as that will damage
            // early error detection. The runtime is still O(n) in flag count.
            for (Map.Entry<Flag, Field> entry : flags.entrySet()) {
                Class<?> type = entry.getValue().getType();
                Flag flag = entry.getKey();

                // Skip non-mandatory, missing flags.
                //          if (!flag.mandatory()) {
                //            continue;
                //          }

                String flagValue = cmd.getOptionValue(flag.name());
                // Coerce String flag or defaultValue into target type.
                // NOTE(dhanji): only supported types are int, String and boolean.
                if (flagValue == null ||
                // The empty string is a valid value for a string type.
                (flagValue.isEmpty() && (int.class.equals(type) || boolean.class.equals(type)))) {
                    // Use the default.
                    if (int.class.equals(type)) {
                        bindConstant().annotatedWith(Names.named(flag.name()))
                                .to(Integer.parseInt(flag.defaultValue()));
                    } else if (boolean.class.equals(type)) {
                        bindConstant().annotatedWith(Names.named(flag.name()))
                                .to(Boolean.parseBoolean(flag.defaultValue()));
                    } else {
                        bindConstant().annotatedWith(Names.named(flag.name())).to(flag.defaultValue());
                    }
                } else {
                    if (int.class.equals(type)) {
                        bindConstant().annotatedWith(Names.named(flag.name())).to(Integer.parseInt(flagValue));
                    } else if (boolean.class.equals(type)) {
                        bindConstant().annotatedWith(Names.named(flag.name()))
                                .to(Boolean.parseBoolean(flagValue));
                    } else {
                        bindConstant().annotatedWith(Names.named(flag.name())).to(flagValue);
                    }
                }
            }
        }
    };
}

From source file:org.wikidata.couchbase.CommandLineOptions.java

@SuppressWarnings("static-access")
public static Options get() {
    Options options = new Options();

    Option type = OptionBuilder.hasArg().withLongOpt(DB_TYPE_LONG)
            .withDescription("Database type: 'couchbae' or 'mongo' (default: mongo)").create(DB_TYPE);
    options.addOption(type);/*from w  w  w  . j  av  a  2 s.c o  m*/

    Option couchbaseUrls = OptionBuilder.hasArg().hasArgs().withValueSeparator(',').withLongOpt(DB_URLS_LONG)
            .withDescription(
                    "Database URL(s), separated by ',' (default: 'http://127.0.0.1:8091/pools' for Couchbase, 'localhost' for MongoDB)")
            .create(DB_URLS);
    options.addOption(couchbaseUrls);

    Option bucket = OptionBuilder.hasArg().withLongOpt(DB_LONG)
            .withDescription("Database / Bucket name (default: wikidata)").create(DB);
    options.addOption(bucket);

    Option firstId = OptionBuilder.hasArg().withLongOpt(FIRST_ID_LONG)
            .withDescription("First wikidata item id (default: 1)").create(FIRST_ID);
    options.addOption(firstId);

    Option lastId = OptionBuilder.hasArg().withLongOpt(LAST_ID_LONG)
            .withDescription("Last wikidata item id (default: first wikidata id)").create(LAST_ID);
    options.addOption(lastId);

    Option numberOfThreads = OptionBuilder.hasArg().withLongOpt(NUMBER_OF_THREADS_LONG)
            .withDescription("Number of parallel threads (default 5)").create(NUMBER_OF_THREADS);
    options.addOption(numberOfThreads);

    Option help = OptionBuilder.withLongOpt(HELP_LONG).withDescription("Show help").create(HELP);
    options.addOption(help);

    return options;
}

From source file:org.wikidata.wdtk.client.ClientConfiguration.java

/**
 * Builds a list of legal options and store them into the options objects.
 *//*from ww  w. j  a  v a2  s  . c  om*/
@SuppressWarnings("static-access")
private static void initOptions() {

    List<String> actions = new ArrayList<>(KNOWN_ACTIONS.keySet());
    Collections.sort(actions);
    Option action = OptionBuilder.hasArg().withArgName("action")
            .withDescription("define the action that should be performed; avaible actions: " + actions)
            .withLongOpt(OPTION_ACTION).create(CMD_OPTION_ACTION);

    Option destination = OptionBuilder.withArgName("path").hasArg()
            .withDescription("place the output into the file at <path>").withLongOpt(OPTION_OUTPUT_DESTINATION)
            .create(CMD_OPTION_OUTPUT_DESTINATION);

    Option dumplocation = OptionBuilder.hasArg().withArgName("path")
            .withDescription("set the location of the dump files").withLongOpt(OPTION_DUMP_LOCATION)
            .create(CMD_OPTION_DUMP_LOCATION);

    Option config = OptionBuilder.hasArg().withArgName("file")
            .withDescription("set a config file; use this to define multiple actions for a single run")
            .withLongOpt(OPTION_CONFIG_FILE).create(CMD_OPTION_CONFIG_FILE);

    Option rdfdump = OptionBuilder.hasArgs().withArgName("task").withDescription(
            "specify which data to include in RDF dump (use with action \"rdf\"); run with options \"-a rdf -n\" for help")
            .withLongOpt(OPTION_OUTPUT_RDF_TYPE).create();

    Option filterLanguages = OptionBuilder.hasArgs().withArgName("languages").withDescription(
            "specifies a list of language codes; if given, only terms in languages in this list will be processed; the value \"-\" denotes the empty list (no terms are processed)")
            .withLongOpt(OPTION_FILTER_LANGUAGES).create();

    Option filterSites = OptionBuilder.hasArgs().withArgName("sites").withDescription(
            "specifies a list of site keys; if given, only site links to sites in this list will be processed; the value \"-\" denotes the empty list (no site links are processed)")
            .withLongOpt(OPTION_FILTER_SITES).create();

    Option filterProperties = OptionBuilder.hasArgs().withArgName("ids").withDescription(
            "specifies a list of property ids; if given, only statements for properties in this list will be processed; the value \"-\" denotes the empty list (no statements are processed)")
            .withLongOpt(OPTION_FILTER_PROPERTIES).create();

    Option compressionExtention = OptionBuilder.hasArg().withArgName("type")
            .withDescription("define a compression format to be used for the output; possible values: "
                    + DumpProcessingOutputAction.COMPRESS_GZIP + ", " + DumpProcessingOutputAction.COMPRESS_BZ2)
            .withLongOpt(OPTION_OUTPUT_COMPRESSION).create(CMD_OPTION_OUTPUT_COMPRESSION);

    Option report = OptionBuilder.hasArg().withArgName("path")
            .withDescription("specifies a path to print a final report after dump generations.")
            .withLongOpt(OPTION_CREATE_REPORT).create(CMD_OPTION_CREATE_REPORT);

    options.addOption(config);
    options.addOption(action);
    options.addOption(CMD_OPTION_QUIET, OPTION_QUIET, false,
            "perform all actions quietly, without printing status messages to the console; errors/warnings are still printed to stderr");
    options.addOption(destination);
    options.addOption(dumplocation);
    options.addOption(filterLanguages);
    options.addOption(filterSites);
    options.addOption(filterProperties);
    options.addOption(compressionExtention);
    options.addOption(report);
    options.addOption(rdfdump);
    options.addOption(CMD_OPTION_OFFLINE_MODE, OPTION_OFFLINE_MODE, false,
            "execute all operations in offline mode, using only previously downloaded dumps");
    options.addOption(CMD_OPTION_HELP, OPTION_HELP, false, "print this message");

    options.addOption(CMD_OPTION_OUTPUT_STDOUT, OPTION_OUTPUT_STDOUT, false, "write output to stdout");
}