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.lilyproject.cli.OptionUtil.java

public static String getStringOption(CommandLine cmd, Option option, String defaultValue) {
    String opt = option.getOpt() == null ? option.getLongOpt() : option.getOpt();
    if (cmd.hasOption(opt)) {
        return cmd.getOptionValue(opt);
    } else {//ww w . ja  va 2  s .  c  om
        return defaultValue;
    }
}

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

public static String getStringOption(CommandLine cmd, Option option) {
    String opt = option.getOpt() == null ? option.getLongOpt() : option.getOpt();
    if (cmd.hasOption(opt)) {
        return cmd.getOptionValue(opt);
    } else {/*from   w w  w .  j a va  2  s . c  o m*/
        throw new CliException("Missing value for option " + opt);
    }
}

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

public static <T extends Enum<T>> T getEnum(CommandLine cmd, Option option, T defaultValue,
        Class<T> enumClass) {
    String value = getStringOption(cmd, option, null);
    if (value == null) {
        return defaultValue;
    }/*from   ww w  .  j  a  v  a 2  s . c  om*/
    try {
        return Enum.valueOf(enumClass, value.toUpperCase());
    } catch (IllegalArgumentException e) {
        throw new CliException("Invalid value for option " + option.getLongOpt() + ": " + value);
    }
}

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

public static <T extends Enum<T>> T getEnum(CommandLine cmd, Option option, Class<T> enumClass) {
    String value = getStringOption(cmd, option);
    try {//w w  w.j  av  a 2 s . c  om
        return Enum.valueOf(enumClass, value.toUpperCase());
    } catch (IllegalArgumentException e) {
        throw new CliException("Invalid value for option " + option.getLongOpt() + ": " + value);
    }
}

From source file:org.linqs.psl.cli.Launcher.java

private static HelpFormatter getHelpFormatter() {
    HelpFormatter helpFormatter = new HelpFormatter();

    // Hack the option ordering to put argumentions without options first and then required options first.
    // infer and learn go first, then required, then just normal.
    helpFormatter.setOptionComparator(new Comparator<Option>() {
        @Override//from  ww w .j  av  a2s  .  co  m
        public int compare(Option o1, Option o2) {
            String name1 = o1.getOpt();
            if (name1 == null) {
                name1 = o1.getLongOpt();
            }

            String name2 = o2.getOpt();
            if (name2 == null) {
                name2 = o2.getLongOpt();
            }

            if (name1.equals(OPERATION_INFER)) {
                return -1;
            }

            if (name2.equals(OPERATION_INFER)) {
                return 1;
            }

            if (name1.equals(OPERATION_LEARN)) {
                return -1;
            }

            if (name2.equals(OPERATION_LEARN)) {
                return 1;
            }

            if (o1.isRequired() && !o2.isRequired()) {
                return -1;
            }

            if (!o1.isRequired() && o2.isRequired()) {
                return 1;
            }

            return name1.compareTo(name2);
        }
    });

    helpFormatter.setWidth(100);

    return helpFormatter;
}

From source file:org.mitre.scap.xccdf.XCCDFInterpreter.java

/**
 * @param args the command line arguments
 *//*from  w  ww .j  a  va 2  s .  c  om*/
public static void main(String[] args) throws IOException, XmlException, URISyntaxException {
    XCCDFInterpreter.generateExecutionTimeStr();
    BuildProperties buildProperties = BuildProperties.getInstance();

    //System.out.println();
    //System.out.println( buildProperties.getApplicationName()+" v"+ buildProperties.getApplicationVersion()+" build "+buildProperties.getApplicationBuild());
    //System.out.println("--------------------");
    //outputOsProperties();
    //System.out.println("--------------------");
    //System.out.println();

    // Define the commandline options
    @SuppressWarnings("static-access")
    Option help = OptionBuilder.withDescription("display usage").withLongOpt("help").create('h');

    @SuppressWarnings("static-access")
    Option workingDir = OptionBuilder.hasArg().withArgName("FILE").withDescription("use result directory FILE")
            .withLongOpt("result-dir").create('R');

    @SuppressWarnings("static-access")
    Option xccdfResultFilename = OptionBuilder.hasArg().withArgName("FILENAME")
            .withDescription("use result filename FILENAME").withLongOpt("xccdf-result-filename").create("F");

    @SuppressWarnings("static-access")
    Option nocpe = OptionBuilder.withDescription("do not process CPE references").withLongOpt("no-cpe")
            .create();

    @SuppressWarnings("static-access")
    Option noresults = OptionBuilder.withDescription("do not display rule results").withLongOpt("no-results")
            .create();

    @SuppressWarnings("static-access")
    Option nocheck = OptionBuilder.withDescription("do not process checks").withLongOpt("no-check").create();

    @SuppressWarnings("static-access")
    Option profile = OptionBuilder.hasArg().withArgName("PROFILE").withDescription("use given profile id")
            .withLongOpt("profile-id").create('P');

    @SuppressWarnings("static-access")
    Option ssValidation = OptionBuilder.hasArg().withArgName("SS-VALIDATION")
            .withDescription("use given validation id").withLongOpt("ssValidation-id").create("S");

    @SuppressWarnings("static-access")
    Option cpeDictionary = OptionBuilder.hasArg().withArgName("FILE")
            .withDescription("use given CPE 2.0 Dictionary file").withLongOpt("cpe-dictionary").create('C');

    @SuppressWarnings("static-access")
    Option cpeOVALDefinition = OptionBuilder.hasArg().withArgName("FILE")
            .withDescription("use given CPE OVAL definition file for CPE evaluation").withLongOpt("cpe-oval")
            .create('c');

    @SuppressWarnings("static-access")
    Option verbose = OptionBuilder.withDescription("produce verbose output").create("v");

    // Build the options list
    Options options = new Options();
    options.addOption(help);
    options.addOption(workingDir);
    options.addOption(xccdfResultFilename);
    options.addOption(profile);
    options.addOption(ssValidation);
    options.addOption(nocpe);
    options.addOption(noresults);
    options.addOption(nocheck);
    options.addOption(cpeDictionary);
    options.addOption(cpeOVALDefinition);
    options.addOption(verbose);

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

        String[] remainingArgs = line.getArgs();

        if (line.hasOption("help") || remainingArgs.length != 1) {
            if (remainingArgs.length != 1) {
                System.err.print("Invalid arguments: ");
                for (String arg : remainingArgs) {
                    System.err.print("'" + arg + "' ");
                }
                System.out.println();
            }

            // automatically generate the help statement
            System.out.println();
            showHelp(options);
            System.exit(0);
        }

        File xccdfFile = new File(remainingArgs[0]);

        if (!xccdfFile.exists()) {
            System.err.println(
                    "!! the specified XCCDF file '" + xccdfFile.getAbsolutePath() + "' does not exist!");
            System.exit(1);
        }

        XCCDFInterpreter interpreter = new XCCDFInterpreter(xccdfFile.getCanonicalFile());

        //System.out.println("** validating XCCDF content");

        if (!interpreter.validate()) {
            System.err.println("!! the XCCDF document is invalid. aborting.");
            System.exit(8);
        }

        if (line.hasOption(verbose.getOpt())) {
            verboseOutput = true;
            interpreter.setVerboseOutput(true);
        }

        if (line.hasOption(workingDir.getOpt())) {
            String lineOpt = line.getOptionValue(workingDir.getOpt());
            String workingDirValue = (lineOpt == null) ? "" : lineOpt;

            File f = new File(workingDirValue);
            if (!f.exists()) {
                if (verboseOutput)
                    System.out.println("** creating directory: " + f.getAbsolutePath());
                if (!f.mkdirs()) {
                    System.err.println("!! unable to create the result directory: " + f.getAbsolutePath());
                    System.exit(2);
                }
            }

            if (!f.isDirectory()) {
                System.err.println("!! the path specified for the result directory is not a directory: "
                        + f.getAbsolutePath());
                System.exit(3);
            }

            if (!f.canWrite()) {
                System.err.println("!! the path specified for the result directory is not writable: "
                        + f.getAbsolutePath());
                System.exit(4);
            }
            interpreter.setResultDirectory(f);
        }

        if (line.hasOption(xccdfResultFilename.getOpt())) {
            interpreter.setXccdfResultsFilename(line.getOptionValue(xccdfResultFilename.getOpt()));
        }

        if (line.hasOption(profile.getOpt())) {
            interpreter.setProfileId(line.getOptionValue(profile.getOpt()));
        }

        if (line.hasOption(ssValidation.getOpt())) {
            interpreter.setssValidationId(line.getOptionValue(ssValidation.getOpt()));
        }

        if (line.hasOption(nocpe.getLongOpt())) {
            interpreter.setProcessCPE(false);
        }

        if (line.hasOption(noresults.getLongOpt())) {
            interpreter.setDisplayResults(false);
        }

        if (line.hasOption(nocheck.getLongOpt())) {
            interpreter.setProcessChecks(false);
        }

        if (interpreter.processCPE == true) {

            if (line.hasOption(cpeDictionary.getOpt())) {
                String lineOpt = line.getOptionValue(cpeDictionary.getOpt());
                String cpeDict = (lineOpt == null) ? "" : lineOpt;

                File f = new File(cpeDict);

                if (!f.exists()) {
                    System.err.println("The CPE dictionary file does not exist: " + f.getAbsolutePath());
                    System.exit(5);
                }

                if (!f.isFile()) {
                    System.err.println("The path specified for the CPE dictionary file is not a file: "
                            + f.getAbsolutePath());
                    System.exit(6);
                }

                if (!f.canRead()) {
                    System.err.println("The path specified for the CPE dictionary file is not readable: "
                            + f.getAbsolutePath());
                    System.exit(7);
                }
                interpreter.setCPEDictionaryFile(f);
            }

            if (line.hasOption(cpeOVALDefinition.getOpt())) {
                String lineOpt = line.getOptionValue(cpeOVALDefinition.getOpt());
                String cpeOVAL = (lineOpt == null) ? "" : lineOpt;

                File f = new File(cpeOVAL);

                if (!f.exists()) {
                    System.err.println(
                            "!! the CPE OVAL inventory definition file does not exist: " + f.getAbsolutePath());
                    System.exit(5);
                }

                if (!f.isFile()) {
                    System.err.println(
                            "!! the path specified for the CPE OVAL inventory definition file is not a file: "
                                    + f.getAbsolutePath());
                    System.exit(6);
                }

                if (!f.canRead()) {
                    System.err.println(
                            "!! the path specified for the CPE OVAL inventory definition file is not readable: "
                                    + f.getAbsolutePath());
                    System.exit(7);
                }
                interpreter.setCPEOVALDefinitionFile(f);
            }

        } // END IF processCPE

        interpreter.process();

    } catch (ParseException ex) {
        System.err.println("!! parsing failed : " + ex.getMessage());
        System.out.println();
        showHelp(options);
    } catch (ProfileNotFoundException ex) {
        if (verboseOutput == true)
            ex.printStackTrace();
        else
            System.err.println("!! checklist processing failed : " + ex.getMessage());
    } catch (CircularReferenceException ex) {
        System.err.println("!! checklist processing failed : " + ex.getMessage());
        if (verboseOutput == true)
            ex.printStackTrace();
        else
            System.err.println("!! checklist processing failed : " + ex.getMessage());
    } catch (ExtensionScopeException ex) {
        if (verboseOutput == true)
            ex.printStackTrace();
        else
            System.err.println("!! checklist processing failed : " + ex.getMessage());
    } catch (ItemNotFoundException ex) {
        if (verboseOutput == true)
            ex.printStackTrace();
        else
            System.err.println("!! checklist processing failed : " + ex.getMessage());
    } catch (PropertyNotFoundException ex) {
        if (verboseOutput == true)
            ex.printStackTrace();
        else
            System.err.println("!! checklist processing failed : " + ex.getMessage());
    } catch (CPEEvaluationException ex) {
        if (verboseOutput == true)
            ex.printStackTrace();
        else
            System.err.println("!! checklist processing failed : " + ex.getMessage());
    } catch (Exception ex) {
        if (verboseOutput == true)
            ex.printStackTrace();
        else
            System.err.println("!! checklist processing failed : " + ex.getMessage());
    }

}

From source file:org.mitre.secretsharing.cli.cmd.AbstractCommand.java

protected String checkArgument(CommandLine cmd, Option o) {
    String invalid = "";
    if (!requiredArguments().contains(o))
        return invalid;
    if ((o.getOpt() == null || !cmd.hasOption(o.getOpt().charAt(0))) && !cmd.hasOption(o.getLongOpt())) {
        if (o.getOpt() != null)
            invalid += "-" + o.getOpt() + ",";
        invalid += "--" + o.getLongOpt();
        if (o.hasArg())
            invalid += " <" + o.getArgName() + ">";
        invalid += " is missing.\n";
    }//from www .j  av  a2 s  .c  o m
    return invalid;
}

From source file:org.mitre.secretsharing.cli.cmd.RootCommand.java

@Override
public void showHelp(PrintStream out) {
    super.showHelp(out);

    out.println();/*from   ww w . ja va2 s  .  c  o  m*/

    Options cmds = new Options();
    for (Command c : Commands.subCommands()) {
        cmds.addOption(null, c.getName(), false, c.getDescription());
    }

    HelpFormatter h = new HelpFormatter();
    h.setSyntaxPrefix("");
    h.setLongOptPrefix("");
    h.setOptionComparator(new Comparator<Option>() {
        @Override
        public int compare(Option o1, Option o2) {
            Integer p1 = Commands.names().indexOf(o1.getLongOpt());
            Integer p2 = Commands.names().indexOf(o2.getLongOpt());
            return p1.compareTo(p2);
        }
    });
    h.printHelp(new PrintWriter(out, true), 80, "Valid Commands:", "", cmds, 12, 12, getActualHelpFooter());
    out.flush();
}

From source file:org.mitre.secretsharing.cli.cmd.SplitCommand.java

@Override
protected String checkArgument(CommandLine cmd, Option o) {
    String invalid = super.checkArgument(cmd, o);
    if (!invalid.isEmpty())
        return invalid;
    if (TOTAL == o) {
        try {/*from w w w .ja v a  2  s. c o  m*/
            int i = Integer.parseInt(cmd.getOptionValue(o.getLongOpt()));
            if (i <= 0)
                throw new RuntimeException();
        } catch (RuntimeException e) {
            invalid += "--" + TOTAL.getLongOpt() + " must be provided a positive integer";
        }
    }
    if (REQUIRED == o) {
        try {
            int i = Integer.parseInt(cmd.getOptionValue(o.getLongOpt()));
            if (i <= 0)
                throw new RuntimeException();
        } catch (RuntimeException e) {
            invalid += "--" + REQUIRED.getLongOpt() + " must be provided a positive integer";
        }
    }
    return invalid;
}

From source file:org.nuunframework.cli.NuunCliPlugin.java

private Map<Class<?>, Options> createOptions(Collection<Class<?>> collection) {
    Set<String> shortOptions = Sets.newHashSet();
    Set<String> longOptions = Sets.newHashSet();

    Map<Class<?>, Options> optionsMap = Maps.newHashMap();

    for (Class<?> class1 : collection) {
        logger.info("CLASS " + class1.getSimpleName());
        Set<Field> fields = annotatedFields(class1, NuunOption.class);
        Options internalOptions = new Options();
        for (Field field : fields) {
            logger.info("Class : " + field.getDeclaringClass().getSimpleName() + " / " + field.getName());
            Option option = createOptionFromField(field);

            if (!Strings.isNullOrEmpty(option.getOpt()) && shortOptions.contains(option.getOpt())) {
                exception("Short option " + option.getOpt() + " already exists!");
            }/*from   w w  w .  j  av a 2  s .  c  om*/

            if (!Strings.isNullOrEmpty(option.getLongOpt()) && longOptions.contains(option.getLongOpt())) {
                exception("Long option " + option.getLongOpt() + " already exists!");
            }

            if (Strings.isNullOrEmpty(option.getOpt()) && Strings.isNullOrEmpty(option.getLongOpt())) {
                exception("NuunOption defined on " + field + " has no opt nor longOpt.");
            }

            internalOptions.addOption(option);
            // global one
            optionsAggregated.addOption(option);

            shortOptions.add(option.getOpt());
            longOptions.add(option.getLongOpt());
        }

        optionsMap.put(class1, internalOptions);

    }

    return optionsMap;
}