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:com.hablutzel.cmdline.CommandLineApplication.java

/**
 * Method for running the command line application.
 *
 * @param args The arguments passed into main()
 * @throws CommandLineException/*from w  w w.j a va  2 s . com*/
 */
public void parseAndRun(String args[]) throws CommandLineException {

    // Configure our environment
    configure();

    // Make sure there is a main helper
    if (mainHelper == null) {
        throw new CommandLineException("You must specify the main method with @CommandLineMain");
    }
    CommandLine line = null;
    CommandLineParser parser = null;

    try {
        // Parse the command line
        parser = new DefaultParser();
        line = parser.parse(options, args);
    } catch (ParseException e) {
        throw new CommandLineException("Unable to parse command line", e);
    } finally {
        parser = null;
    }

    // Assume we're continuing
    boolean runMain = true;

    // Loop through all our known options
    for (Map.Entry<Option, CommandLineMethodHelper> entry : optionHelperMap.entrySet()) {

        // See if this option was specified
        Option option = entry.getKey();
        CommandLineMethodHelper helper = entry.getValue();
        boolean present = option.getOpt() == null || option.getOpt().equals("")
                ? line.hasOption(option.getLongOpt())
                : line.hasOption(option.getOpt());
        if (present) {

            // The user specified this option. Now we have to handle the
            // values, if it has any
            if (option.hasArg()) {
                String[] arguments = option.getOpt() == null || option.getOpt().equals("")
                        ? line.getOptionValues(option.getLongOpt())
                        : line.getOptionValues(option.getOpt());
                runMain = helper.invokeMethod(this, arguments) && runMain;
            } else {
                runMain = helper.invokeMethod(this, new String[] {}) && runMain;
            }
        }
    }

    // Now handle all the extra arguments. In order to clean up memory,
    // we get rid of the structures that we needed in order to parse
    if (runMain) {

        // Get a reference to the arguments
        String[] arguments = line.getArgs();

        // Clean up the parsing variables
        line = null;
        optionHelperMap = null;

        // Now call the main method. This means we have to keep
        // the main helper around, but that's small
        mainHelper.invokeMethod(this, arguments);
    }
}

From source file:com.zuehlke.sbdfx.utils.CampApplBase.java

protected Long getOptionValueAsLong(final Option option, final Long defaultValue) {
    final String optionValueString = getOptionValue(option,
            defaultValue != null ? String.valueOf(defaultValue) : ""); //$NON-NLS-1$
    if (StringUtils.isNotBlank(optionValueString)) {
        try {//ww w . java 2  s .  c  o  m
            return Long.parseLong(optionValueString);
        } catch (final Exception e) {
            throw new IllegalArgumentException(
                    MessageFormat.format("Failed to parse option {0} as integer: {1}", //$NON-NLS-1$
                            option.getLongOpt(), optionValueString));
        }
    } else {
        return defaultValue;
    }
}

From source file:eu.stratosphere.pact.client.CliFrontend.java

/**
 * Displays exceptions./* w w  w .ja va  2s  .c  o m*/
 * 
 * @param e the exception to display.
 */
@SuppressWarnings({ "unchecked" })
private void handleError(Throwable t) {
    if (t instanceof UnrecognizedOptionException) {

        Options generalOptions = this.options.get(GENERAL_OPTS);
        boolean generalOption = false;
        for (Option o : (Collection<Option>) generalOptions.getOptions()) {
            if (t.getMessage().startsWith("Unrecognized option: -" + o.getOpt())
                    || t.getMessage().contains("Unrecognized option: -" + o.getLongOpt())) {
                generalOption = true;
            }
        }
        if (generalOption) {
            System.err.println("ERROR: General args must be placed directly after action.");
        } else {
            System.err.println("ERROR: " + t.getMessage());
        }
        printHelp();
    } else {
        System.err.println("ERROR: " + t.getMessage());
        if (this.verbose) {
            t.printStackTrace();
        } else {
            System.out.println("For a more detailed error message use the '-v' option");
        }
    }
    System.exit(1);
}

From source file:calculadora.controlador.ControladorComandos.java

/**
 * Controlo si un comando con posix largo se escribio a la vez que otro
 * posix largo como puede ser (--help) junto con --(seno) de error.
 *
 * Controlo si un comando posix largo se escribio a la vez que otro de posix
 * corto que no sean --help y -D(ya que si ocurriera esto mostraria la
 * ayuda), y viceversa tiene que dar error.
 *
 * @param opt dos opciones// ww w .jav  a  2  s .c  o m
 * @see Option
 * @throws ParseException Demasiados comandos
 */
private void hasBuenosComandos(Option[] opt) throws ParseException {
    //Obtengo la primera y la segunda opcion
    Option op1 = opt[0];
    Option op2 = opt[1];

    boolean isLongOpt1 = op1.hasLongOpt();
    boolean isLongOpt2 = op2.hasLongOpt();

    //Si los dos comandos son posix largo error
    if (isLongOpt1 && isLongOpt2) {
        throw errorComandos(); //Error de comandos
        //Si el primero es posix largo y el segundo no pero son el comando
        //-help y -D no debe ocurrir nada
    } else if ((isLongOpt1 && !isLongOpt2 && op1.getLongOpt().equals(HELP) && op2.getOpt().equals(PROPERTY))) {
        //No debe hacer nada importante esto vacio.
        //Si el primero es poxis largo y el segundo posix corto y viceversa
    } else if (isLongOpt1 && !isLongOpt2 || !isLongOpt1 && isLongOpt2) {
        throw errorComandos(); //Error de comandos
    }
}

From source file:com.google.api.codegen.GeneratorMain.java

public static void gapicGeneratorMain(ArtifactType artifactType, String[] args) throws Exception {
    Options options = new Options();
    options.addOption("h", "help", false, "show usage");
    options.addOption(DESCRIPTOR_SET_OPTION);
    options.addOption(SERVICE_YAML_OPTION);
    // TODO make required after artman passes this in
    options.addOption(LANGUAGE_NONREQUIRED_OPTION);
    options.addOption(GAPIC_YAML_OPTION);
    options.addOption(PACKAGE_YAML2_OPTION);
    options.addOption(OUTPUT_OPTION);/*w  w w .j  ava2 s . c  o  m*/
    Option enabledArtifactsOption = Option.builder().longOpt("enabled_artifacts")
            .desc("Optional. Artifacts enabled for the generator. "
                    + "Currently supports 'surface' and 'test'.")
            .hasArg().argName("ENABLED_ARTIFACTS").required(false).build();
    options.addOption(enabledArtifactsOption);

    CommandLine cl = (new DefaultParser()).parse(options, args);
    if (cl.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("GapicGeneratorTool", options);
    }

    ToolOptions toolOptions = ToolOptions.create();
    toolOptions.set(ToolOptions.DESCRIPTOR_SET, cl.getOptionValue(DESCRIPTOR_SET_OPTION.getLongOpt()));
    toolOptions.set(ToolOptions.CONFIG_FILES,
            Lists.newArrayList(cl.getOptionValues(SERVICE_YAML_OPTION.getLongOpt())));
    toolOptions.set(GapicGeneratorApp.LANGUAGE, cl.getOptionValue(LANGUAGE_NONREQUIRED_OPTION.getLongOpt()));
    toolOptions.set(GapicGeneratorApp.OUTPUT_FILE, cl.getOptionValue(OUTPUT_OPTION.getLongOpt(), ""));
    toolOptions.set(GapicGeneratorApp.GENERATOR_CONFIG_FILES,
            Lists.newArrayList(cl.getOptionValues(GAPIC_YAML_OPTION.getLongOpt())));
    toolOptions.set(GapicGeneratorApp.PACKAGE_CONFIG2_FILE,
            cl.getOptionValue(PACKAGE_YAML2_OPTION.getLongOpt()));

    checkFile(toolOptions.get(ToolOptions.DESCRIPTOR_SET));
    checkFiles(toolOptions.get(ToolOptions.CONFIG_FILES));
    checkFiles(toolOptions.get(GapicGeneratorApp.GENERATOR_CONFIG_FILES));
    if (!Strings.isNullOrEmpty(toolOptions.get(GapicGeneratorApp.PACKAGE_CONFIG2_FILE))) {
        checkFile(toolOptions.get(GapicGeneratorApp.PACKAGE_CONFIG2_FILE));
    }

    if (cl.getOptionValues(enabledArtifactsOption.getLongOpt()) != null) {
        toolOptions.set(GapicGeneratorApp.ENABLED_ARTIFACTS,
                Lists.newArrayList(cl.getOptionValues(enabledArtifactsOption.getLongOpt())));
    }
    GapicGeneratorApp codeGen = new GapicGeneratorApp(toolOptions, artifactType);
    int exitCode = codeGen.run();
    System.exit(exitCode);
}

From source file:com.greenpepper.maven.runner.CommandLineRunner.java

@SuppressWarnings("unchecked")
private List<String> parseCommandLine(String[] args)
        throws ArgumentMissingException, IOException, ParseException {
    List<String> parameters = new ArrayList<String>();
    CommandLine commandLine = argumentsParser.parse(args);
    if (commandLine != null) {
        Option[] options = commandLine.getOptions();
        for (Option option : options) {
            if ("v".equals(option.getOpt())) {
                isDebug = true;/*  ww w  .  j  av a  2 s  .  c  o  m*/
                parameters.add("--debug");
            } else if ("p".equals(option.getOpt())) {
                projectDependencyDescriptor = option.getValue();
            } else if ("m".equals(option.getOpt())) {
                usingScopes(option.getValue());
            } else if ("o".equals(option.getOpt())) {
                parameters.add("-" + option.getOpt());
                parameters.add(option.getValue());
            } else if ("r".equals(option.getOpt())) {
                parameters.add("-" + option.getOpt());
                parameters.add(option.getValue());
            } else {
                parameters.add("--" + option.getLongOpt());
                if (option.hasArg()) {
                    parameters.add(option.getValue());
                }
            }
        }
        parameters.addAll(commandLine.getArgList());
    }
    return parameters;
}

From source file:kieker.tools.traceAnalysis.TraceAnalysisTool.java

/**
 * This method dumps the configuration on the screen.
 *//*from   w w w  . ja v  a  2 s . com*/
private void dumpConfiguration() {
    LOG.debug("#");
    LOG.debug("# Configuration");
    for (final Option o : Constants.SORTED_OPTION_LIST) {
        final String longOpt = o.getLongOpt();
        String val = "<null>";
        if (longOpt.equals(Constants.CMD_OPT_NAME_INPUTDIRS)) {
            val = Constants.stringArrToStringList(this.inputDirs);
        } else if (longOpt.equals(Constants.CMD_OPT_NAME_OUTPUTDIR)) {
            val = this.outputDir;
        } else if (longOpt.equals(Constants.CMD_OPT_NAME_OUTPUTFNPREFIX)) {
            val = this.outputFnPrefix;
        } else if (longOpt.equals(Constants.CMD_OPT_NAME_TASK_ALLOCATIONEQUIVCLASSREPORT)
                || longOpt.equals(Constants.CMD_OPT_NAME_TASK_ASSEMBLYEQUIVCLASSREPORT)
                || longOpt.equals(Constants.CMD_OPT_NAME_TASK_PLOTALLOCATIONSEQDS)
                || longOpt.equals(Constants.CMD_OPT_NAME_TASK_PLOTASSEMBLYSEQDS)
                || longOpt.equals(Constants.CMD_OPT_NAME_TASK_PLOTALLOCATIONCOMPONENTDEPG)
                || longOpt.equals(Constants.CMD_OPT_NAME_TASK_PLOTASSEMBLYCOMPONENTDEPG)
                || longOpt.equals(Constants.CMD_OPT_NAME_TASK_PLOTCONTAINERDEPG)
                || longOpt.equals(Constants.CMD_OPT_NAME_TASK_PLOTALLOCATIONOPERATIONDEPG)
                || longOpt.equals(Constants.CMD_OPT_NAME_TASK_PLOTASSEMBLYOPERATIONDEPG)
                || longOpt.equals(Constants.CMD_OPT_NAME_TASK_PLOTAGGREGATEDALLOCATIONCALLTREE)
                || longOpt.equals(Constants.CMD_OPT_NAME_TASK_PLOTAGGREGATEDASSEMBLYCALLTREE)
                || longOpt.equals(Constants.CMD_OPT_NAME_TASK_PLOTCALLTREES)
                || longOpt.equals(Constants.CMD_OPT_NAME_TASK_PRINTEXECTRACES)
                || longOpt.equals(Constants.CMD_OPT_NAME_TASK_PRINTINVALIDEXECTRACES)
                || longOpt.equals(Constants.CMD_OPT_NAME_TASK_PRINTMSGTRACES)
                || longOpt.equals(Constants.CMD_OPT_NAME_TASK_PRINTSYSTEMMODEL)
                || longOpt.equals(AbstractCommandLineTool.CMD_OPT_NAME_DEBUG_LONG)
                || longOpt.equals(AbstractCommandLineTool.CMD_OPT_NAME_VERBOSE_LONG)
                || longOpt.equals(AbstractCommandLineTool.CMD_OPT_NAME_HELP_LONG)) {
            val = this.cmdl.hasOption(longOpt) ? "true" : "false"; // NOCS
        } else if (longOpt.equals(Constants.CMD_OPT_NAME_SELECTTRACES)) {
            if (this.selectedTraces != null) {
                val = this.selectedTraces.toString();
            } else {
                val = "<select all>";
            }

        } else if (longOpt.equals(Constants.CMD_OPT_NAME_FILTERTRACES)) {
            if (this.selectedTraces != null) {
                val = this.selectedTraces.toString();
            } else {
                val = "<filter none>";
            }

        } else if (longOpt.equals(Constants.CMD_OPT_NAME_SHORTLABELS)) {
            val = this.shortLabels ? "true" : "false"; // NOCS
        } else if (longOpt.equals(Constants.CMD_OPT_NAME_INCLUDESELFLOOPS)) {
            val = this.includeSelfLoops ? "true" : "false"; // NOCS
        } else if (longOpt.equals(Constants.CMD_OPT_NAME_IGNORE_ASSUMED)) {
            val = this.ignoreAssumedCalls ? "true" : "false"; // NOCS
        } else if (longOpt.equals(Constants.CMD_OPT_NAME_IGNOREINVALIDTRACES)) {
            val = this.ignoreInvalidTraces ? "true" : "false"; // NOCS
        } else if (longOpt.equals(Constants.CMD_OPT_NAME_REPAIR_EVENT_BASED_TRACES)) {
            val = this.repairEventBasedTraces ? "true" : "false"; // NOCS
        } else if (longOpt.equals(Constants.CMD_OPT_NAME_MAXTRACEDURATION)) {
            val = this.maxTraceDurationMillis + " ms";
        } else if (longOpt.equals(Constants.CMD_OPT_NAME_IGNOREEXECUTIONSBEFOREDATE)) {
            val = LoggingTimestampConverter
                    .convertLoggingTimestampToUTCString(this.ignoreExecutionsBeforeTimestamp) + " ("
                    + LoggingTimestampConverter.convertLoggingTimestampLocalTimeZoneString(
                            this.ignoreExecutionsBeforeTimestamp)
                    + ")";
        } else if (longOpt.equals(Constants.CMD_OPT_NAME_IGNOREEXECUTIONSAFTERDATE)) {
            val = LoggingTimestampConverter
                    .convertLoggingTimestampToUTCString(this.ignoreExecutionsAfterTimestamp) + " ("
                    + LoggingTimestampConverter.convertLoggingTimestampLocalTimeZoneString(
                            this.ignoreExecutionsAfterTimestamp)
                    + ")";
        } else if (Constants.CMD_OPT_NAME_TRACE_COLORING.equals(longOpt)) {
            val = this.cmdl.getOptionValue(Constants.CMD_OPT_NAME_TRACE_COLORING);
            if (val == null) {
                val = "";
            }
        } else if (Constants.CMD_OPT_NAME_ADD_DESCRIPTIONS.equals(longOpt)) {
            val = this.cmdl.getOptionValue(Constants.CMD_OPT_NAME_ADD_DESCRIPTIONS);
            if (val == null) {
                val = "";
            }
        } else {
            val = Arrays.toString(this.cmdl.getOptionValues(longOpt));
            LOG.warn("Unformatted configuration output for option " + longOpt);
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("--" + longOpt + ": " + val);
        }
    }
}

From source file:nl.cyso.vcloud.client.config.Configuration.java

public static void load(CommandLine cli) {
    for (Option opt : cli.getOptions()) {
        if (cli.hasOption(opt.getLongOpt())) {
            if (opt.getLongOpt().equals("help")) {
                Configuration.setMode(ModeType.HELP);
                if (cli.getOptionValue(opt.getLongOpt()) != null) {
                    Configuration
                            .setHelpType(ModeType.valueOf(cli.getOptionValue(opt.getLongOpt()).toUpperCase()));
                }/*from   w w  w.  j av  a 2  s .  co m*/
            } else if (opt.getLongOpt().equals("version")) {
                Configuration.setMode(ModeType.VERSION);
            } else if (opt.getLongOpt().equals("list")) {
                Configuration.setMode(ModeType.LIST);
                Configuration.setListType(ListType.valueOf(cli.getOptionValue(opt.getLongOpt()).toUpperCase()));
            } else if (opt.getLongOpt().equals("add-vm")) {
                Configuration.setMode(ModeType.ADDVM);
            } else if (opt.getLongOpt().equals("remove-vm")) {
                Configuration.setMode(ModeType.REMOVEVM);
            } else if (opt.getLongOpt().equals("poweron-vm")) {
                Configuration.setMode(ModeType.POWERONVM);
            } else if (opt.getLongOpt().equals("poweroff-vm")) {
                Configuration.setMode(ModeType.POWEROFFVM);
            } else if (opt.getLongOpt().equals("shutdown-vm")) {
                Configuration.setMode(ModeType.SHUTDOWNVM);
            } else if (opt.getLongOpt().equals("resize-disk")) {
                Configuration.setMode(ModeType.RESIZEDISK);
            } else if (opt.getLongOpt().equals("consolidate-vm")) {
                Configuration.setMode(ModeType.CONSOLIDATEVM);
            } else if (opt.getLongOpt().equals("ip")) {
                try {
                    Configuration.setIp(cli.getOptionValue(opt.getLongOpt()));
                } catch (UnknownHostException uhe) {
                    Configuration.setIp((InetAddress) null);
                }
            } else if (opt.getLongOpt().equals("disk-size")) {
                Configuration.setDiskSize(cli.getOptionValue(opt.getLongOpt()));
            } else if (opt.getLongOpt().equals("ip-address-allocation-mode")) {
                Configuration.setIpAddressAllocationMode(cli.getOptionValue(opt.getLongOpt()));

            } else {
                Configuration.set(opt.getLongOpt(), cli.getOptionValue(opt.getLongOpt()));
            }
        }
    }
}

From source file:nl.cyso.vsphere.client.config.Configuration.java

public static void load(CommandLine cli) {
    for (Option opt : cli.getOptions()) {
        if (cli.hasOption(opt.getLongOpt())) {
            if (opt.getLongOpt().equals("help")) {
                Configuration.set("mode", "HELP");
                if (cli.getOptionValue(opt.getLongOpt()) != null) {
                    Configuration.set("help-type", cli.getOptionValue(opt.getLongOpt()));
                }/*  w w w.  jav  a  2s. c o m*/
            } else if (opt.getLongOpt().equals("version")) {
                Configuration.set("mode", "VERSION");
            } else if (opt.getLongOpt().equals("list")) {
                Configuration.set("mode", "LIST");
                Configuration.set("list-type", cli.getOptionValue(opt.getLongOpt()).toUpperCase());
            } else if (opt.getLongOpt().equals("add-vm")) {
                Configuration.set("mode", "ADDVM");
            } else if (opt.getLongOpt().equals("remove-vm")) {
                Configuration.set("mode", "REMOVEVM");
            } else if (opt.getLongOpt().equals("poweron-vm")) {
                Configuration.set("mode", "POWERONVM");
            } else if (opt.getLongOpt().equals("poweroff-vm")) {
                Configuration.set("mode", "POWEROFFVM");
            } else if (opt.getLongOpt().equals("shutdown-vm")) {
                Configuration.set("mode", "SHUTDOWNVM");
            } else if (opt.getLongOpt().equals("reboot-vm")) {
                Configuration.set("mode", "REBOOTVM");
            } else if (opt.getLongOpt().equals("modify-vm")) {
                Configuration.set("mode", "MODIFYVM");
            } else if (opt.getLongOpt().equals("upload-to-datastore")) {
                Configuration.set("mode", "UPLOADTODATASTORE");
            } else if (opt.getLongOpt().equals("ip")) {
                try {
                    Configuration.set("ip", InetAddress.getByName(cli.getOptionValue(opt.getLongOpt())));
                } catch (UnknownHostException uhe) {
                    Configuration.set("ip", (InetAddress) null);
                }
            } else {
                Configuration.set(opt.getLongOpt(), cli.getOptionValue(opt.getLongOpt()));
            }
        }
    }
}

From source file:nl.nekoconeko.glaciercmd.config.Configuration.java

public static void load(CommandLine cli) {
    for (Option opt : cli.getOptions()) {
        if (cli.hasOption(opt.getLongOpt())) {
            if (opt.getLongOpt().equals("help")) {
                Configuration.setMode(ModeType.HELP);
                if (cli.getOptionValue(opt.getLongOpt()) != null) {
                    Configuration
                            .setHelpType(ModeType.valueOf(cli.getOptionValue(opt.getLongOpt()).toUpperCase()));
                }//from  w w w . ja va 2s  . c  o m
            } else if (opt.getLongOpt().equals("version")) {
                Configuration.setMode(ModeType.VERSION);
            } else if (opt.getLongOpt().equals("list")) {
                Configuration.setMode(ModeType.LIST);
                Configuration.setListType(ListType.valueOf(cli.getOptionValue(opt.getLongOpt()).toUpperCase()));
            } else if (opt.getLongOpt().equals("init-inventory")) {
                Configuration.setMode(ModeType.INITIATEINVENTORY);
            } else if (opt.getLongOpt().equals("get-inventory")) {
                Configuration.setMode(ModeType.GETINVENTORY);
            } else if (opt.getLongOpt().equals("upload")) {
                Configuration.setMode(ModeType.UPLOAD);
            } else if (opt.getLongOpt().equals("download")) {
                Configuration.setMode(ModeType.DOWNLOAD);
            } else if (opt.getLongOpt().equals("init-download")) {
                Configuration.setMode(ModeType.INITIATEDOWNLOAD);
            } else if (opt.getLongOpt().equals("get-download")) {
                Configuration.setMode(ModeType.GETDOWNLOAD);
            } else if (opt.getLongOpt().equals("delete-archive")) {
                Configuration.setMode(ModeType.DELETEARCHIVE);
            } else if (opt.getLongOpt().equals("region")) {
                Configuration.setRegion(
                        AWSGlacierRegion.valueOf(cli.getOptionValue(opt.getLongOpt()).toUpperCase()));
            } else {
                Configuration.set(opt.getLongOpt(), cli.getOptionValue(opt.getLongOpt()));
            }
        }
    }
}