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.obiba.genobyte.cli.BitwiseCli.java

/**
 * Adds a {@link CliCommand} to the set of registered commands. If a command
 * with the same short or long option string is already registered, an IllegalArgumentException is thrown.
 * @param command the command to register.
 * @throws IllegalArgumentException when a command with the same short option string already exists.
 *///from w  w  w .  j ava  2s . co  m
public void registerCommand(CliCommand command) {
    Option o = command.getOption();
    if (commandMap.containsKey(o.getLongOpt())) {
        throw new IllegalArgumentException(
                "A command with key [" + o.getLongOpt() + "] is already registered.");
    }
    if (o.getOpt() != null) {
        for (CliCommand c : commandMap.values()) {
            Option commandOption = c.getOption();
            if (commandOption.getOpt() != null && commandOption.getOpt().equals(o.getOpt())) {
                throw new IllegalArgumentException("Illegal option [" + o.getLongOpt()
                        + "] conflicts with existing option [" + commandOption.getLongOpt() + "].");
            }
        }
    }
    commandMap.put(o.getLongOpt(), command);
    options.addOption(o);
    if (command.requiresOpenStore() == false) {
        noStoreOptions.addOption(o);
    }
}

From source file:org.obiba.genobyte.cli.BitwiseCli.java

/**
 * Starts the CLI shell./* www  .j av a  2s.c  o m*/
 * 
 * @throws IOException when an error occurs while reading user input.
 */
public void execute() throws IOException {
    CliContext context = new CliContext(this.output);
    BufferedReader br = new BufferedReader(new InputStreamReader(input));
    BasicParser bp = new BasicParser();
    output.println("Type '-h' for help, '-q' to quit.");
    while (true) {
        prompt(context);
        boolean quit = false;
        String str = br.readLine();
        CommandLine cl = null;
        try {
            if (context.getStore() == null) {
                cl = bp.parse(noStoreOptions, str.split(" "));
            } else {
                cl = bp.parse(options, str.split(" "));
            }
        } catch (ParseException e) {
            quit = help.execute(null, context);
        }

        if (cl != null) {
            Iterator<Option> commands = cl.iterator();
            // We don't iterate to make sure we execute only one command
            if (commands.hasNext()) {
                Option o = commands.next();
                CliCommand c = commandMap.get(o.getLongOpt());
                if (c == null) {
                    throw new IllegalStateException(
                            "No CliCommand associated with option [" + o.getOpt() + "]");
                } else {
                    try {
                        quit = c.execute(o, context);
                    } catch (ParseException e) {
                        quit = help.execute(null, context);
                    } catch (Exception e) {
                        output.println(
                                "An unexpected error occurred while executing the command: " + e.getMessage());
                    }
                }
            }

            // Not handled by any command: it should be a query.
            String queryString = str;
            if (context.getStore() != null && (cl.getOptions() == null || cl.getOptions().length == 0)) {
                try {
                    QueryParser parser = new QueryParser();
                    long start = System.currentTimeMillis();
                    if (StringUtil.isEmptyString(queryString) == false) {
                        Query q = parser.parse(queryString);
                        QueryResult qr = q.execute(context.getActiveRecordStore().getStore());
                        String reference = context.addQuery(queryString, qr);
                        long end = System.currentTimeMillis();
                        output.println(reference + ": " + qr.count() + " results in " + (end - start)
                                + " milliseconds.");
                    }
                } catch (org.obiba.bitwise.query.UnknownFieldException e) {
                    output.println(e.getMessage());
                } catch (org.obiba.bitwise.query.ParseException e) {
                    output.println("The query [" + queryString
                            + "] is invalid. Please refer to the query syntax for more information.");
                } catch (Exception e) {
                    output.println(
                            "An unexpected error occurred while executing the query. The following data may be helpful to debug the problem.");
                    e.printStackTrace(output);
                }
            }
        }
        if (quit)
            break;
    }
}

From source file:org.openanzo.client.cli.AnzoConsole.java

AnzoConsole() {
    try {/*from w w w  .j a  v  a 2s  .com*/
        dcw = CommandLineInterface.DEFAULT_CONSOLE;
        if (dcw.cr != null) {
            dcw.cr.setBellEnabled(true);
            dcw.cr.setPrompt("Anzo>");
            dcw.cr.setHistoryEnabled(true);
        }
        dcw.writeOutput(
                "Anzo Command Line Client. \nCopyright (c) 2009 Cambridge Semantics Inc and others. All rights reserved.");
        String version = null;
        if (CommandLineInterface.class.getProtectionDomain() != null
                && CommandLineInterface.class.getProtectionDomain().getCodeSource() != null
                && CommandLineInterface.class.getProtectionDomain().getCodeSource().getLocation() != null) {
            ProtectionDomain domain = CommandLineInterface.class.getProtectionDomain();
            CodeSource source = domain.getCodeSource();
            URL location = source.getLocation();
            if (location != null) {
                File file = new File(location.toURI());
                if (file.exists() && file.getName().toLowerCase().endsWith(".jar")) {
                    JarFile jar = new JarFile(file);
                    version = jar.getManifest().getMainAttributes().getValue("Bundle-Version");
                    if (version == null) {
                        version = jar.getManifest().getMainAttributes().getValue("Implementation-Build");
                    }
                }
            }
        }
        if (version == null) {
            version = CommandLineInterface.class.getPackage().getImplementationVersion();
        }
        dcw.writeOutput("Version: " + ((version == null) ? "Unknown" : version));
        dcw.writeOutput("Type help for usage");

        HashMap<String, Completer> completers = new HashMap<String, Completer>();
        completers.put("exit", new NullCompleter());
        completers.put("quit", new NullCompleter());
        completers.put("connect", new NullCompleter());
        completers.put("disconnect", new NullCompleter());
        completers.put("trace", new StringsCompleter("on", "off"));
        Options global = CommandLineInterface.getGlobalOptions();
        for (SubCommand sc : CommandLineInterface.subcommands) {
            String command = sc.getName();
            ArrayList<String> subcommands = new ArrayList<String>();
            for (Object o : sc.getOptions().getOptions()) {
                Option options = (Option) o;
                subcommands.add("-" + options.getOpt());
                subcommands.add("--" + options.getLongOpt());
            }
            for (Object o : global.getOptions()) {
                Option options = (Option) o;
                subcommands.add("-" + options.getOpt());
                subcommands.add("--" + options.getLongOpt());
            }
            completers.put(command, new StringsCompleter(subcommands));
        }
        if (dcw.cr != null) {
            dcw.cr.addCompleter(new CLICompleter(completers));
        }
        boolean showStackTrace = false;
        while (true) {
            String command = dcw.readLine("Anzo>");
            if (command != null) {
                if (EXIT.toLowerCase().equals(command.trim().toLowerCase())
                        || QUIT.toLowerCase().equals(command.trim().toLowerCase())) {
                    if (context != null && context.client != null && context.client.isConnected()) {
                        context.client.disconnect();
                        context.client.close();
                        dcw.writeOutput("Disonnected from:" + context.host);
                    }
                    System.exit(0);
                }
                String arguments[] = stringToArgs(command);
                try {
                    if (arguments.length > 0) {
                        String subcommand = arguments[0];
                        if ("connect".equals(subcommand.toLowerCase())) {
                            Options options = new Options();
                            CommandLineInterface.appendGlobalOptions(options);
                            CommandLineParser parser = new PosixParser();
                            String[] subcommandArgs = (String[]) ArrayUtils.subarray(arguments, 1,
                                    arguments.length);
                            CommandLine cl = parser.parse(options, subcommandArgs);
                            if (context == null) {
                                context = CommandLineInterface.createContext(dcw, cl, options, arguments);
                            }
                            if (!context.client.isConnected()) {
                                context.client.connect();
                                dcw.writeOutput("Connected to:" + context.host);
                            }
                        } else if ("disconnect".equals(subcommand.toLowerCase())) {
                            if (context != null && context.client != null && context.client.isConnected()) {
                                context.client.disconnect();
                                context.client.close();
                                dcw.writeOutput("Disonnected from:" + context.host);
                            } else {
                                dcw.writeOutput("Not connected to:" + context.host);
                            }
                            context = null;
                        } else if ("trace".equals(subcommand.toLowerCase())) {
                            String[] subcommandArgs = (String[]) ArrayUtils.subarray(arguments, 1,
                                    arguments.length);
                            if (subcommandArgs.length == 0) {
                                dcw.writeOutput("Show Stack Trace:" + showStackTrace);
                            } else {
                                String flag = subcommandArgs[0];
                                if (flag.equals("on"))
                                    showStackTrace = true;
                                else if (flag.equals("off"))
                                    showStackTrace = false;
                                else
                                    showStackTrace = Boolean.parseBoolean(flag);
                            }
                            if (context != null) {
                                context.showTrace = showStackTrace;
                            }
                        } else if ("version".equals(subcommand.toLowerCase())) {
                            String header = CommandLineInterface.generateVersionHeader();
                            dcw.writeOutput(header);

                        } else {
                            CommandLineInterface.processCommand(context, false, arguments);
                        }
                    }
                } catch (AnzoException e) {
                    if (e.getErrorCode() == ExceptionConstants.COMBUS.JMS_CONNECT_FAILED) {
                        dcw.writeError("Connection failed.");
                        if (showStackTrace)
                            dcw.printException(e, showStackTrace);
                    } else {
                        dcw.printException(e, showStackTrace);
                    }
                } catch (AnzoRuntimeException e) {
                    dcw.printException(e, showStackTrace);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(0);
    }
}

From source file:org.openmainframe.ade.ext.main.AdeMaskLog.java

/**
 * Parse the input arguments//from   w w w.  j  a  va  2s .c om
 */
@SuppressWarnings("static-access")
protected void parseArgs(String[] args) throws AdeUsageException {

    Option helpOpt = new Option("h", "help", false,
            "Mask potentially sensitive information in Linux Log RFC 3164 format");
    options.addOption(helpOpt);

    Option outputFileOpt = OptionBuilder.withLongOpt("output").hasArg(true).withArgName("FILE")
            .isRequired(false).withDescription("Output file name ").create('o');
    options.addOption(outputFileOpt);

    Option inputFileOpt = OptionBuilder.withLongOpt("input").hasArg(true).withArgName("FILE").isRequired(false)
            .withDescription("Input file name").create('f');
    options.addOption(inputFileOpt);

    Option systemNameOpt = OptionBuilder.withLongOpt("systemname").hasArg(true).withArgName("SYSTEM_NAME")
            .isRequired(false).withDescription("String to replace system name").create('s');
    options.addOption(systemNameOpt);

    Option companyNameOpt = OptionBuilder.withLongOpt("companyname").hasArgs(2)
            .withArgName("COMPANY_NAME> <REPLACEMENT_COMPANY_NAME").isRequired(false)
            .withDescription("String to find company name and replacement company name").withValueSeparator(' ')
            .create('c');
    options.addOption(companyNameOpt);

    Option ipAddressMaskOpt = OptionBuilder.withLongOpt("maskIPAddress")
            .withDescription("Do not mask IP address with local host IP address").create('t');
    options.addOption(ipAddressMaskOpt);

    Option emailAddressMaskOpt = OptionBuilder.withLongOpt("maskEmailAddress")
            .withDescription("Do not Mask email address with gmail.com address").create('e');
    options.addOption(emailAddressMaskOpt);

    CommandLineParser parser = new GnuParser();
    CommandLine line = null;

    try {
        // parse the command line arguments
        line = parser.parse(options, args);
    } catch (MissingOptionException exp) {

        new HelpFormatter().printHelp(AdeMaskLog.class.getName(), options);
        throw new AdeUsageException("Command Line parsing failed", exp);

    } catch (ParseException exp) {
        // oops, something went wrong
        logger.error("Parsing failed", exp);
        throw new AdeUsageException("Argument Parsing failed", exp);
    }

    if (line.hasOption('h')) {
        new HelpFormatter().printHelp(this.getClass().getSimpleName(), options);
        System.exit(0);
    }
    if (line.hasOption(helpOpt.getLongOpt())) {
        new HelpFormatter().printHelp(getClass().getSimpleName(), options);
    }

    if (line.hasOption(outputFileOpt.getLongOpt())) {
        mOutputFile = new File(line.getOptionValue(outputFileOpt.getLongOpt()));
    } else {
        throw new AdeUsageException("Command Line parsing failed missing output file name");
    }

    if (line.hasOption(inputFileOpt.getLongOpt())) {
        mInputFile = new File(line.getOptionValue(inputFileOpt.getLongOpt()));
    } else {
        throw new AdeUsageException("Command Line parsing failed missing input file name");
    }

    if (line.hasOption(systemNameOpt.getLongOpt())) {
        mSystemName = line.getOptionValue(systemNameOpt.getLongOpt());
    }

    if (line.hasOption(companyNameOpt.getLongOpt())) {
        String[] workArg = line.getOptionValues(companyNameOpt.getLongOpt());
        mCompanyName = workArg[0];
        mCompanyNameNew = workArg[1];
    }

    if (line.hasOption(ipAddressMaskOpt.getLongOpt())) {
        mMaskTCPIPAddress = false;
    }

    if (line.hasOption(emailAddressMaskOpt.getLongOpt())) {
        mMaskEmailAddress = false;
    }
}

From source file:org.openmainframe.ade.ext.main.AdeUtilMain.java

/**
 * Parse the input arguments/*from w  w  w .jav  a  2 s .  c o  m*/
 */
@SuppressWarnings("static-access")
@Override
protected void parseArgs(String[] args) throws AdeUsageException {
    Options options = new Options();

    Option helpOpt = new Option("h", "help", false, "Print help message and exit");
    options.addOption(helpOpt);

    Option versionOpt = OptionBuilder.withLongOpt("version").hasArg(false).isRequired(false)
            .withDescription("Print current Ade version (JAR) and exit").create('v');
    options.addOption(versionOpt);

    Option dbVersionOpt = OptionBuilder.withLongOpt("db-version")
            .withDescription("Print current Ade DB version and exit").create('b');
    options.addOption(dbVersionOpt);

    Option outputFileOpt = OptionBuilder.withLongOpt("output").hasArg(true).withArgName("FILE")
            .isRequired(false).withDescription("Output file name (where relevant)").create('o');
    options.addOption(outputFileOpt);

    OptionGroup optGroup = new OptionGroup();
    optGroup.setRequired(false);

    Option DumpModelDebugOpt = OptionBuilder.withLongOpt("debugPrint").hasArg(true).withArgName("MODEL FILE")
            .isRequired(false).withDescription("Extract a text version of a model debug information and exit")
            .create('d');
    optGroup.addOption(DumpModelDebugOpt);

    Option verifyFlowOpt = OptionBuilder.withLongOpt("verifyFlow").hasArg(true).withArgName("FLOW FILE")
            .isRequired(false).withDescription("Verify the flow file matches the XSD standard and exit")
            .create('f');
    optGroup.addOption(verifyFlowOpt);

    options.addOptionGroup(optGroup);

    CommandLineParser parser = new GnuParser();
    CommandLine line = null;

    try {
        // parse the command line arguments
        line = parser.parse(options, args);
    } catch (MissingOptionException exp) {
        System.out.println("Command line parsing failed.  Reason: " + exp.getMessage());
        System.out.println();
        new HelpFormatter().printHelp(ControlDB.class.getName(), options);
        System.exit(0);
    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        throw new AdeUsageException("Argument Parsing failed", exp);
    }

    if (line.hasOption('h')) {
        new HelpFormatter().printHelp(this.getClass().getSimpleName(), options);
        System.exit(0);
    }
    if (line.hasOption(helpOpt.getLongOpt())) {
        new HelpFormatter().printHelp(getClass().getSimpleName(), options);
    }

    if (line.hasOption(outputFileOpt.getLongOpt())) {
        m_outputFile = new File(line.getOptionValue(outputFileOpt.getLongOpt()));
    }

    m_inputFile = null;

    m_cmd = null;

    if (line.hasOption('v')) {
        m_cmd = "version";
    }

    if (line.hasOption('b')) {
        m_cmd = "db-version";
    }

    if (line.hasOption('d')) {
        m_inputFile = new File(line.getOptionValue(DumpModelDebugOpt.getLongOpt()));
        m_cmd = "debugPrint";
    }

    if (line.hasOption('f')) {
        m_inputFilename = line.getOptionValue(verifyFlowOpt.getLongOpt());
        m_cmd = "verifyFlow";
    }

}

From source file:org.openmainframe.ade.main.AdeUtilMain.java

@SuppressWarnings("static-access")
@Override//w  w w.j ava  2 s. c  o m
protected void parseArgs(String[] args) throws AdeException {
    Options options = new Options();

    Option helpOpt = new Option("h", "help", false, "Print help message and exit");
    options.addOption(helpOpt);

    Option versionOpt = OptionBuilder.withLongOpt("version").hasArg(false).isRequired(false)
            .withDescription("Print current Ade version (JAR) and exit").create('V');
    options.addOption(versionOpt);

    Option dbVersionOpt = OptionBuilder.withLongOpt("db-version")
            .withDescription("Print current Ade DB version and exit").create();
    options.addOption(dbVersionOpt);

    Option outputFileOpt = OptionBuilder.withLongOpt("output").hasArg(true).withArgName("FILE")
            .isRequired(false).withDescription("Output file name (where relevant)").create('o');

    options.addOption(outputFileOpt);

    OptionGroup optGroup = new OptionGroup();
    optGroup.setRequired(false);

    Option DumpModelOpt = OptionBuilder.withLongOpt("model").hasArg(true).withArgName("MODEL FILE")
            .isRequired(false).withDescription("Extract a text version of a model (csv) and exit").create('m');
    optGroup.addOption(DumpModelOpt);

    Option DumpModelDebugOpt = OptionBuilder.withLongOpt("debugPrint").hasArg(true).withArgName("MODEL FILE")
            .isRequired(false).withDescription("Extract a text version of a model debug information and exit")
            .create('d');
    optGroup.addOption(DumpModelDebugOpt);

    Option verifyFlowOpt = OptionBuilder.withLongOpt("verifyFlow").hasArg(true).withArgName("FLOW FILE")
            .isRequired(false).withDescription("Verify the flow file matches the XSD standard and exit")
            .create('f');
    optGroup.addOption(verifyFlowOpt);

    options.addOptionGroup(optGroup);

    CommandLineParser parser = new GnuParser();
    CommandLine line = null;

    try {
        // parse the command line arguments
        line = parser.parse(options, args);
    } catch (MissingOptionException exp) {
        System.out.println("Command line parsing failed.  Reason: " + exp.getMessage());
        System.out.println();
        new HelpFormatter().printHelp(ControlDB.class.getName(), options);
        System.exit(0);
    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        throw new AdeUsageException("Argument Parsing failed", exp);
    }

    if (line.hasOption(helpOpt.getLongOpt())) {
        new HelpFormatter().printHelp(getClass().getSimpleName(), options);
        closeAll();
        System.exit(0);
    }
    if (line.hasOption(versionOpt.getLongOpt())) {
        System.out.println("Current Ade version (JAR): " + Ade.getAde().getVersion());
        closeAll();
        System.exit(0);
    }
    if (line.hasOption(dbVersionOpt.getLongOpt())) {
        System.out.println("Current Ade DB version: " + Ade.getAde().getDbVersion());
        closeAll();
        System.exit(0);
    }

    File outputFile = null;
    if (line.hasOption(outputFileOpt.getLongOpt())) {
        outputFile = new File(line.getOptionValue(outputFileOpt.getLongOpt()));
    }

    if (line.hasOption(DumpModelDebugOpt.getLongOpt())) {
        File modelFile = new File(line.getOptionValue(DumpModelDebugOpt.getLongOpt()));
        dumpModelDebug(modelFile, outputFile);
    }
    if (line.hasOption(verifyFlowOpt.getLongOpt())) {
        String flowFilename = line.getOptionValue(verifyFlowOpt.getLongOpt());
        File flowFile = new File(flowFilename);
        try {
            validateGood(flowFile);
        } catch (Exception e) {
            throw new AdeUsageException("Failed when verifiying " + flowFile.getName(), e);
        }
    }

}

From source file:org.openmainframe.ade.main.Train.java

@Override
protected void parseArgs(String[] args) throws AdeException {
    final Option helpOpt = new Option("h", "help", false, "Print help message and exit");

    OptionBuilder.withLongOpt(ALL_OPT);/*w  w  w .ja  v  a2s . co m*/
    OptionBuilder.isRequired(false);
    OptionBuilder.withDescription("All analysis groups");
    final Option allAnalysisGroupsOpt = OptionBuilder.create('a');

    OptionBuilder.withLongOpt(GROUPS_OPT);
    OptionBuilder.withArgName("ANALYSIs GROUPS");
    OptionBuilder.hasArgs();
    OptionBuilder.isRequired(false);
    OptionBuilder.withDescription("Selected analysis groups");
    final Option selectAnalysisGroupsOpt = OptionBuilder.create('s');

    final OptionGroup inputAnalysisGroupsOptGroup = new OptionGroup().addOption(allAnalysisGroupsOpt)
            .addOption(selectAnalysisGroupsOpt);
    inputAnalysisGroupsOptGroup.setRequired(true);

    OptionBuilder.withLongOpt(UNSELECT_OPT);
    OptionBuilder.withArgName("ANALYSIS GROUPS");
    OptionBuilder.hasArgs();
    OptionBuilder.isRequired(false);
    OptionBuilder.withDescription("Unselect analysis groups. Used only with '" + ALL_OPT + "'");
    final Option unselectAnalysisGroupsOpt = OptionBuilder.create('u');

    OptionBuilder.withLongOpt(DURATION_OPT);
    OptionBuilder.withArgName("DURATION (ISO 8601)");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg();
    OptionBuilder.withDescription(
            "Duration from/to start/end date. Defaults to infinity. Replaces either 'start-date' or 'end-date'");
    final Option periodOpt = OptionBuilder.create();

    OptionBuilder.withLongOpt(NUM_DAYS_OPT);
    OptionBuilder.withArgName("INT");
    OptionBuilder.hasArg();
    OptionBuilder.isRequired(false);
    OptionBuilder.withDescription("Number of days. same as '" + DURATION_OPT + "'");
    final Option numDaysOpt = OptionBuilder.create('n');

    final OptionGroup periodOptGroup = new OptionGroup().addOption(periodOpt).addOption(numDaysOpt);

    OptionBuilder.withLongOpt(START_DATE_OPT);
    OptionBuilder.withArgName("MM/dd/yyyy[ HH:mm][ Z]");
    OptionBuilder.hasArg();
    OptionBuilder.isRequired(false);
    OptionBuilder.withDescription(
            "Start of date range. Optional. Replaces 'duration'/'num-days' when used along with 'end-date'");
    final Option startDateOpt = OptionBuilder.create();

    OptionBuilder.withLongOpt(END_DATE_OPT);
    OptionBuilder.withArgName("MM/dd/yyyy[ HH:mm][ Z]");
    OptionBuilder.hasArg();
    OptionBuilder.isRequired(false);
    OptionBuilder
            .withDescription("End of date range. Defaults to this moment. Replaces 'duration'/'num-days' when"
                    + " used along with 'start-date'");
    final Option endDateOpt = OptionBuilder.create();

    final Options options = new Options();
    options.addOption(helpOpt);
    options.addOptionGroup(inputAnalysisGroupsOptGroup);
    options.addOption(unselectAnalysisGroupsOpt);
    options.addOptionGroup(periodOptGroup);
    options.addOption(endDateOpt);
    options.addOption(startDateOpt);

    final CommandLineParser parser = new GnuParser();
    CommandLine line;

    try {
        // parse the command line arguments
        line = parser.parse(options, args);
    } catch (MissingOptionException exp) {
        new HelpFormatter().printHelp(HELP + "\nOptions:", options);
        throw new AdeUsageException("Command line parsing failed", exp);
    } catch (ParseException exp) {
        // oops, something went wrong
        throw new AdeUsageException("Argument Parsing failed", exp);
    }

    if (line.hasOption(helpOpt.getLongOpt())) {
        new HelpFormatter().printHelp(HELP, options);
        closeAll();
        System.exit(0);
    }

    if (line.hasOption(UNSELECT_OPT) && !line.hasOption(ALL_OPT)) {
        throw new AdeUsageException("'" + UNSELECT_OPT + "' cannot be used without '" + ALL_OPT + "'");
    }

    final Set<Integer> allAnalysisGroups = Ade.getAde().getDataStore().sources().getAllAnalysisGroups();
    if (line.hasOption(ALL_OPT)) {
        System.out.println("Operating on all available analysis groups");
        if (!line.hasOption(UNSELECT_OPT)) {
            m_analysisGroups = allAnalysisGroups;
        } else {
            final Set<Integer> unselectedAnalysisGroups = parseAnalysisGroups(allAnalysisGroups,
                    line.getOptionValues(UNSELECT_OPT));
            final Set<String> unselectedGroupNames = getGroupNames(unselectedAnalysisGroups);
            System.out.println("Omitting analysis groups: " + unselectedGroupNames.toString());
            m_analysisGroups = new TreeSet<Integer>(allAnalysisGroups);
            m_analysisGroups.removeAll(unselectedAnalysisGroups);
        }
    } else if (line.hasOption(GROUPS_OPT)) {
        m_analysisGroups = parseAnalysisGroups(allAnalysisGroups, line.getOptionValues(GROUPS_OPT));
        final Set<String> operatingAnalysisGroups = getGroupNames(m_analysisGroups);
        System.out.println("Operating on analysis groups: " + operatingAnalysisGroups.toString());
    }

    if ((line.hasOption(NUM_DAYS_OPT) || line.hasOption(DURATION_OPT)) && line.hasOption(START_DATE_OPT)
            && line.hasOption(END_DATE_OPT)) {
        throw new AdeUsageException("Cannot use '" + DURATION_OPT + "'/'" + NUM_DAYS_OPT + "', '"
                + START_DATE_OPT + "' and '" + END_DATE_OPT + "' together");
    }
    if (line.hasOption(NUM_DAYS_OPT)) {
        final String numDaysStr = line.getOptionValue(NUM_DAYS_OPT);
        final int numDays = Integer.parseInt(numDaysStr);
        this.m_period = Period.days(numDays);
    }
    if (line.hasOption(DURATION_OPT)) {
        final String periodStr = line.getOptionValue(DURATION_OPT);
        this.m_period = ISOPeriodFormat.standard().parsePeriod(periodStr);
    }
    if (line.hasOption(START_DATE_OPT)) {
        m_startDate = parseDate(line.getOptionValue(START_DATE_OPT));
    }
    if (line.hasOption(END_DATE_OPT)) {
        m_endDate = parseDate(line.getOptionValue(END_DATE_OPT));
    }
}

From source file:org.opentestsystem.airose.optionCli.ArgOptions.java

private String optionToString(Option o) {
    return "-" + o.getOpt() + ", --" + o.getLongOpt();
}

From source file:org.pentaho.platform.plugin.services.importexport.CmdParser.java

private void handleToken(Options options, boolean stopAtNonOption, String token) {
    int pos = token.indexOf('=');
    String opt = pos == -1 ? token : token.substring(0, pos); // --foo

    if (!options.hasOption(opt)) {
        processNonOptionToken(token, stopAtNonOption);
    } else {//from  w  w w .  ja v a  2 s  .c o  m
        Option option = options.getOption(opt);
        boolean isLongOptAndExists = opt.startsWith("--")
                && option.getLongOpt().equals(opt.substring(2, opt.length()));
        boolean isShortOptAndExists = opt.startsWith("-")
                && option.getOpt().equals(opt.substring(1, opt.length()));
        if (isLongOptAndExists || isShortOptAndExists) {
            currentOption = option;
            tokens.add(opt);
            if (pos != -1) {
                tokens.add(token.substring(pos + 1));
            }
        } else {
            throw new IllegalArgumentException(Messages.getInstance()
                    .getErrorString("CommandLineProcessor.ERROR_0008_INVALID_PARAMETER", opt));
        }
    }
}

From source file:org.rhq.server.metrics.migrator.DataMigratorRunner.java

/**
 * Load the configuration options from file and overlay them on top of the default
 * options.//from  w ww  .j  a va2s  . c  o m
 *
 * @param file config file
 */
private void loadConfigFile(String file) {
    try {
        File configFile = new File(file);
        if (!configFile.exists()) {
            throw new FileNotFoundException("Configuration file not found!");
        }

        Properties configProperties = new Properties();
        FileInputStream stream = new FileInputStream(configFile);
        configProperties.load(stream);
        stream.close();

        for (Object optionObject : options.getOptions()) {
            Option option = (Option) optionObject;
            Object optionValue;

            if ((optionValue = configProperties.get(option.getLongOpt())) != null) {
                log.debug("Configuration option loaded: " + option.getLongOpt() + " (" + option.getType()
                        + ") -> " + optionValue);

                if (option.equals(cassandraHostsOption)) {
                    String[] cassandraHosts = parseCassandraHosts(optionValue.toString());
                    configuration.put(option, cassandraHosts);
                } else if (option.equals(sqlServerTypeOption)) {
                    if ("oracle".equals(optionValue)) {
                        configuration.put(option, DatabaseType.Oracle);
                    } else {
                        configuration.put(option, DatabaseType.Postgres);
                    }
                } else if (option.equals(sqlPostgresServerOption)) {
                    boolean value = tryParseBoolean(optionValue.toString(), true);
                    if (value == true) {
                        configuration.put(sqlServerTypeOption, DatabaseType.Postgres);
                    }
                } else if (option.equals(sqlOracleServerOption)) {
                    boolean value = tryParseBoolean(optionValue.toString(), true);
                    if (value == true) {
                        configuration.put(sqlServerTypeOption, DatabaseType.Oracle);
                    }
                } else if (option.getType().equals(Boolean.class)) {
                    configuration.put(option, tryParseBoolean(optionValue.toString(), true));
                } else if (option.getType().equals(Integer.class)) {
                    configuration.put(option, tryParseInteger(optionValue.toString(), 0));
                } else {
                    configuration.put(option, optionValue.toString());
                }
            }
        }
    } catch (Exception e) {
        log.error("Unable to load or process the configuration file.", e);
        System.exit(1);
    }
}