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

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

Introduction

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

Prototype

public String getLongOpt() 

Source Link

Document

Retrieve the long name of this Option.

Usage

From source file:org.finra.dm.core.ArgumentParserTest.java

@Test
public void testGetIntegerValue() throws ParseException {
    final Integer testDefaultValue = 500;
    final Integer testMinValue = 0;
    final Integer testMaxValue = 1000;

    ArgumentParser argParser = new ArgumentParser("");
    Option intOpt = argParser.addArgument("i", "int", true, "Some integer parameter", false);
    Integer inputValue;/*  w ww.j  a v  a2  s.  c om*/
    Integer resultValue;

    final String shortIntOpt = String.format("-%s", intOpt.getOpt());
    final String longIntOpt = String.format("--%s", intOpt.getLongOpt());

    argParser.parseArguments(new String[] {});
    assertNull(argParser.getIntegerValue(intOpt));
    assertEquals(testDefaultValue, argParser.getIntegerValue(intOpt, testDefaultValue));

    inputValue = 123;
    argParser.parseArguments(new String[] { shortIntOpt, inputValue.toString() });
    resultValue = argParser.getIntegerValue(intOpt);
    assertNotNull(resultValue);
    assertEquals(inputValue, resultValue);

    inputValue = 456;
    argParser.parseArguments(new String[] { shortIntOpt, inputValue.toString() });
    resultValue = argParser.getIntegerValue(intOpt, testDefaultValue);
    assertNotNull(resultValue);
    assertEquals(inputValue, resultValue);

    inputValue = 789;
    argParser.parseArguments(new String[] { longIntOpt, inputValue.toString() });
    resultValue = argParser.getIntegerValue(intOpt);
    assertNotNull(resultValue);
    assertEquals(inputValue, resultValue);

    // The "happy path" test case for the minimum and maximum allowed values.
    inputValue = 234;
    argParser.parseArguments(new String[] { longIntOpt, inputValue.toString() });
    resultValue = argParser.getIntegerValue(intOpt, testDefaultValue, testMinValue, testMaxValue);
    assertNotNull(resultValue);
    assertEquals(inputValue, resultValue);

    // The default value test case the minimum and maximum allowed values.
    argParser.parseArguments(new String[] {});
    resultValue = argParser.getIntegerValue(intOpt, testDefaultValue, testMinValue, testMaxValue);
    assertNotNull(resultValue);
    assertEquals(testDefaultValue, resultValue);

    // The edge test case for the minimum allowed value.
    argParser.parseArguments(new String[] { longIntOpt, testMinValue.toString() });
    resultValue = argParser.getIntegerValue(intOpt, testDefaultValue, testMinValue, testMaxValue);
    assertNotNull(resultValue);
    assertEquals(testMinValue, resultValue);

    // The edge test case for the maximum allowed value.
    argParser.parseArguments(new String[] { longIntOpt, testMaxValue.toString() });
    resultValue = argParser.getIntegerValue(intOpt, testDefaultValue, testMinValue, testMaxValue);
    assertNotNull(resultValue);
    assertEquals(testMaxValue, resultValue);

    // The edge test case for the minimum and maximum allowed values.
    argParser.parseArguments(new String[] { longIntOpt, testDefaultValue.toString() });
    resultValue = argParser.getIntegerValue(intOpt, testDefaultValue, testDefaultValue, testDefaultValue);
    assertNotNull(resultValue);
    assertEquals(testDefaultValue, resultValue);

    // Try to get an option value what is less than the minimum allowed value.
    inputValue = testMinValue - 1;
    argParser.parseArguments(new String[] { longIntOpt, inputValue.toString() });
    try {
        argParser.getIntegerValue(intOpt, testDefaultValue, testMinValue, testMaxValue);
        fail("Suppose to throw an IllegalArgumentException when option value is less than the minimum allowed value.");
    } catch (IllegalArgumentException e) {
        assertEquals(String.format("The %s option value %d is less than the minimum allowed value of %d.",
                intOpt.getLongOpt(), inputValue, testMinValue), e.getMessage());
    }

    // Try to get an option value what is greater than the maximum allowed value.
    inputValue = testMaxValue + 1;
    argParser.parseArguments(new String[] { longIntOpt, inputValue.toString() });
    try {
        argParser.getIntegerValue(intOpt, testDefaultValue, testMinValue, testMaxValue);
        fail("Suppose to throw an IllegalArgumentException when option value is greater than the maximum allowed value.");
    } catch (IllegalArgumentException e) {
        assertEquals(String.format("The %s option value %d is bigger than maximum allowed value of %d.",
                intOpt.getLongOpt(), inputValue, testMaxValue), e.getMessage());
    }
}

From source file:org.finra.dm.core.ArgumentParserTest.java

@Test
public void testGetFileValue() throws ParseException {
    File testDefaultValue = new File("default_file_name");

    ArgumentParser argParser = new ArgumentParser("");
    Option fileOpt = argParser.addArgument("f", "file", true, "Source file name", false);
    File inputValue;//from w w  w.j a  va  2  s  . c  o m
    File resultValue;

    final String shortFileOpt = String.format("-%s", fileOpt.getOpt());
    final String longFileOpt = String.format("--%s", fileOpt.getLongOpt());

    argParser.parseArguments(new String[] { "" });
    assertNull(argParser.getFileValue(fileOpt));
    assertEquals(testDefaultValue, argParser.getFileValue(fileOpt, testDefaultValue));

    inputValue = new File("folder/file_name_1");
    argParser.parseArguments(new String[] { shortFileOpt, inputValue.toString() });
    resultValue = argParser.getFileValue(fileOpt);
    assertNotNull(resultValue);
    assertEquals(inputValue, resultValue);

    inputValue = new File("folder/file_name_2");
    argParser.parseArguments(new String[] { shortFileOpt, inputValue.toString() });
    resultValue = argParser.getFileValue(fileOpt, testDefaultValue);
    assertNotNull(resultValue);
    assertEquals(inputValue, resultValue);

    inputValue = new File("file_name_3");
    argParser.parseArguments(new String[] { longFileOpt, inputValue.toString() });
    resultValue = argParser.getFileValue(fileOpt);
    assertNotNull(resultValue);
    assertEquals(inputValue, resultValue);
}

From source file:org.finra.dm.core.ArgumentParserTest.java

/**
 * Dump state of the Option object instance, suitable for debugging and comparing Options as Strings.
 *
 * @param option the Option object instance to dump the state of
 *
 * @return Stringified form of this Option object instance
 *///from  w  w w  . ja  v a  2s.  co  m
private String optionToString(Option option) {
    StringBuilder buf = new StringBuilder();

    buf.append("[ option: ");
    buf.append(option.getOpt());

    if (option.getLongOpt() != null) {
        buf.append(" ").append(option.getLongOpt());
    }

    buf.append(" ");

    if (option.hasArg()) {
        buf.append(" [ARG]");
    }

    buf.append(" :: ").append(option.getDescription());

    if (option.isRequired()) {
        buf.append(" [REQUIRED]");
    }

    buf.append(" ]");

    return buf.toString();
}

From source file:org.finra.herd.core.ArgumentParserTest.java

@Test
public void testGetUsageInformation() {
    List<Option> optionsIn = new ArrayList<>();
    optionsIn.add(new Option("a", "some_flag", false, "Some flag parameter"));
    optionsIn.add(new Option("b", "some_parameter", true, "Some parameter with an argument"));

    ArgumentParser argParser = new ArgumentParser("TestApp");
    argParser.addArgument(optionsIn.get(0), false);
    argParser.addArgument(optionsIn.get(1), true);

    String usage = argParser.getUsageInformation();

    assertNotNull(usage);//  w w w . j  a v a2s .co  m
    assertTrue(usage.contains(String.format("usage: %s", argParser.getApplicationName())));

    for (Option option : optionsIn) {
        assertTrue(usage.contains(String.format("-%s,", option.getOpt())));
        assertTrue(usage.contains(String.format("--%s", option.getLongOpt())));
        assertTrue(usage.contains(option.getDescription()));
        assertTrue(!option.hasArg() || usage.contains("<arg>"));
    }
}

From source file:org.g_node.srv.CliOptionServiceTest.java

/**
 * Main assertions of all option arguments.
 * @param opt The actual {@link Option}.
 * @param shortOpt Short commandline argument of the current option.
 * @param longOpt Long commandline argument of the current option.
 * @param desc Description text of the current option.
 * @param isRequired Whether the current option is a required commandline argument.
 * @param hasArguments Whether the current option requires an additional argument.
 *///from  www  . j  a v a 2 s  .c o m
private void assertOption(final Option opt, final String shortOpt, final String longOpt, final String desc,
        final Boolean isRequired, final Boolean hasArgument, final Boolean hasArguments) {
    assertThat(opt.getOpt()).isEqualToIgnoringCase(shortOpt);
    assertThat(opt.getLongOpt()).isEqualToIgnoringCase(longOpt);
    assertThat(opt.getDescription()).contains(desc);
    assertThat(opt.isRequired()).isEqualTo(isRequired);
    assertThat(opt.hasArg()).isEqualTo(hasArgument);
    assertThat(opt.hasArgs()).isEqualTo(hasArguments);
}

From source file:org.janusgraph.codepipelines.AwsCodePipelinesCi.java

private String getOptionValue(Option option) {
    return cmd.getOptionValue(option.getLongOpt());
}

From source file:org.jumpmind.symmetric.AbstractCommandLauncher.java

public void execute(String args[]) {
    PosixParser parser = new PosixParser();
    Options options = new Options();
    buildOptions(options);//from   w  ww.  jav a  2s.  c om
    try {
        CommandLine line = parser.parse(options, args);

        if (line.hasOption(HELP) || (line.getArgList().contains(HELP)) || ((args == null || args.length == 0)
                && line.getOptions().length == 0 && printHelpIfNoOptionsAreProvided())) {
            printHelp(line, options);
            System.exit(2);
        }

        configureLogging(line);
        configurePropertiesFile(line);

        if (line.getOptions() != null) {
            for (Option option : line.getOptions()) {
                log.info("Option: name={}, value={}",
                        new Object[] { option.getLongOpt() != null ? option.getLongOpt() : option.getOpt(),
                                ArrayUtils.toString(option.getValues()) });
            }
        }

        executeWithOptions(line);

    } catch (ParseException e) {
        System.err.println(e.getMessage());
        printUsage(options);
        System.exit(4);
    } catch (Exception e) {
        System.err.println("-------------------------------------------------------------------------------");
        System.err.println("An exception occurred.  Please see the following for details:");
        System.err.println("-------------------------------------------------------------------------------");

        ExceptionUtils.printRootCauseStackTrace(e, System.err);
        System.err.println("-------------------------------------------------------------------------------");
        System.exit(1);
    }
}

From source file:org.ldmud.jldmud.CommandLineArguments.java

/**
 * Parse the commandline and set the associated globals.
 *
 * @return {@code true} if the main program should exit; in that case {@link @getExitCode()} provides the suggest exit code.
 *//*from  w w w  .  j ava2  s  .co m*/
@SuppressWarnings("static-access")
public boolean parseCommandline(String[] args) {

    try {
        Option configSetting = OptionBuilder.withLongOpt("config").withArgName("setting=value").hasArgs(2)
                .withValueSeparator()
                .withDescription(
                        "Set the configuration setting to the given value (overrides any setting in the <config settings> file). Unsupported settings are ignored.")
                .create("C");
        Option help = OptionBuilder.withLongOpt("help").withDescription("Print the help text and exits.")
                .create("h");
        Option helpConfig = OptionBuilder.withLongOpt("help-config")
                .withDescription("Print the <config settings> help text and exits.").create();
        Option version = OptionBuilder.withLongOpt("version")
                .withDescription("Print the driver version and exits").create("V");
        Option printConfig = OptionBuilder.withLongOpt("print-config")
                .withDescription("Print the effective configuration settings to stdout and exit.").create();
        Option printLicense = OptionBuilder.withLongOpt("license")
                .withDescription("Print the software license and exit.").create();

        Options options = new Options();
        options.addOption(help);
        options.addOption(helpConfig);
        options.addOption(version);
        options.addOption(configSetting);
        options.addOption(printConfig);
        options.addOption(printLicense);

        CommandLineParser parser = new PosixParser();
        CommandLine line = parser.parse(options, args);

        /* Handle the print-help-and-exit options first, to allow them to be chained in a nice way. */

        boolean helpOptionsGiven = false;

        if (line.hasOption(version.getOpt())) {
            System.out.println(
                    Version.DRIVER_NAME + " " + Version.getVersionString() + " - a LPMud Game Driver.");
            System.out.println(Version.Copyright);
            System.out.print(Version.DRIVER_NAME + " is licensed under the " + Version.License + ".");
            if (!line.hasOption(printLicense.getLongOpt())) {
                System.out.print(" Use option --license for details.");
            }
            System.out.println();
            helpOptionsGiven = true;
        }

        if (line.hasOption(printLicense.getLongOpt())) {
            if (helpOptionsGiven) {
                System.out.println();
            }
            printLicense();
            helpOptionsGiven = true;
        }

        if (line.hasOption(help.getOpt())) {
            final PrintWriter systemOut = new PrintWriter(System.out, true);

            HelpFormatter formatter = new HelpFormatter();

            if (helpOptionsGiven) {
                System.out.println();
            }
            System.out.println("Usage: " + Version.DRIVER_NAME + " [options] [<config settings>]");
            System.out.println();
            formatter.printWrapped(systemOut, formatter.getWidth(),
                    "The <config settings> is a file containing the game settings; if not specified, it defaults to '"
                            + GameConfiguration.DEFAULT_SETTINGS_FILE + "'. "
                            + "The settings file must exist if no configuration setting is specified via commandline argument.");
            System.out.println();
            formatter.printOptions(systemOut, formatter.getWidth(), options, formatter.getLeftPadding(),
                    formatter.getDescPadding());
            helpOptionsGiven = true;
        }

        if (line.hasOption(helpConfig.getLongOpt())) {
            if (helpOptionsGiven) {
                System.out.println();
            }
            GameConfiguration.printTemplate();
            helpOptionsGiven = true;
        }

        if (helpOptionsGiven) {
            exitCode = 0;
            return true;
        }

        /* Parse the real options */

        /* TODO: If we get many real options, it would be useful to implement a more general system like {@link GameConfiguration#SettingBase} */

        if (line.hasOption(configSetting.getLongOpt())) {
            configSettings = line.getOptionProperties(configSetting.getLongOpt());
        }

        if (line.hasOption(printConfig.getLongOpt())) {
            printConfiguration = true;
        }

        if (line.getArgs().length > 1) {
            throw new ParseException("Too many arguments");
        }

        if (line.getArgs().length == 1) {
            settingsFilename = line.getArgs()[0];
        }

        return false;
    } catch (ParseException e) {
        System.err.println("Error: " + e.getMessage());
        exitCode = 1;
        return true;
    }
}

From source file:org.lilyproject.cli.OptionUtil.java

public static int getIntOption(CommandLine cmd, Option option, int defaultValue) {
    String opt = option.getOpt() == null ? option.getLongOpt() : option.getOpt();
    if (cmd.hasOption(opt)) {
        try {// ww  w.j  a  v a2 s. co  m
            return Integer.parseInt(cmd.getOptionValue(opt));
        } catch (NumberFormatException e) {
            throw new CliException(
                    "Invalid value for option " + option.getLongOpt() + ": " + cmd.getOptionValue(opt));
        }
    }
    return defaultValue;
}

From source file:org.lilyproject.cli.OptionUtil.java

public static long getLongOption(CommandLine cmd, Option option, long defaultValue) {
    String opt = option.getOpt() == null ? option.getLongOpt() : option.getOpt();
    if (cmd.hasOption(opt)) {
        try {/*from   w ww .  j a  v  a2  s  .com*/
            return Long.parseLong(cmd.getOptionValue(opt));
        } catch (NumberFormatException e) {
            throw new CliException(
                    "Invalid value for option " + option.getLongOpt() + ": " + cmd.getOptionValue(opt));
        }
    }
    return defaultValue;
}