Example usage for org.apache.commons.cli CommandLine getOptions

List of usage examples for org.apache.commons.cli CommandLine getOptions

Introduction

In this page you can find the example usage for org.apache.commons.cli CommandLine getOptions.

Prototype

public Option[] getOptions() 

Source Link

Document

Returns an array of the processed Option s.

Usage

From source file:es.ua.alex952.main.MainBatch.java

/**
 * Main constructor that parses all arguments from the command line
 * /*from ww w  .j  a v a 2s .  c  o m*/
 * @param args Command line arguments
 */
public MainBatch(String[] args) {

    //Operation creation for usage print      
    Option create = OptionBuilder.withLongOpt("create").withDescription("switch for creating a job")
            .create("c");

    Option daemon = OptionBuilder.withArgName("id").withLongOpt("daemon")
            .withDescription("daemon mode for monitorizing the job after its creation").hasOptionalArg()
            .create("d");

    Option configfile = OptionBuilder.withArgName("config.properties").withLongOpt("configfile")
            .withDescription("the properties config file that has all the program specific configurations")
            .hasArg().create("cf");

    Option parametersfile = OptionBuilder.withArgName("parameters.properties").withLongOpt("parametersfile")
            .withDescription(
                    "properties paramters file that has all the job specific parameters for its creation")
            .hasArg().create("pf");

    Option sourcelanguage = OptionBuilder.withArgName("sl.txt").withLongOpt("sourcelanguage")
            .withDescription("text file containing all the sentences to be translated").hasArg().create("sl");

    Option referencetranslations = OptionBuilder.withArgName("rt.txt").withLongOpt("referencetranslations")
            .withDescription("text file with a translation of reference for each source language sentence")
            .hasArg().create("rt");

    Option gold = OptionBuilder.withArgName("gold.txt").withLongOpt("gold").withDescription(
            "text file with the gold standards given for the job. It has a three lines format that is composed by one line for the source language sentence, one for the reference translation, and the last one for the correct translation")
            .hasArg().create("g");

    Option daemonfrecuency = OptionBuilder.withArgName("daemon frecuency").withLongOpt("daemonfrecuency")
            .withDescription("daemon check frecuency").hasArg().create("df");

    Option help = OptionBuilder.withLongOpt("help").withDescription("shows this help message").create("h");

    options.addOption(create);
    options.addOption(daemon);
    options.addOption(daemonfrecuency);
    options.addOption(configfile);
    options.addOption(parametersfile);
    options.addOption(sourcelanguage);
    options.addOption(referencetranslations);
    options.addOption(gold);
    options.addOption(help);

    //Option parsing
    CommandLineParser clp = new BasicParser();
    try {
        CommandLine cl = clp.parse(options, args);
        if (cl.hasOption("help") || cl.getOptions().length == 0) {
            HelpFormatter hf = new HelpFormatter();
            hf.setWidth(100);
            hf.printHelp("CrowdFlowerTasks", options);
            op = Operation.QUIT;

            return;
        }

        if (cl.hasOption("daemon") && !cl.hasOption("c")) {
            if (cl.getOptionValue("daemon") == null) {
                logger.error("The daemon option must have a job id if it isn't along with create option");
                op = Operation.QUIT;

                return;
            } else if (!cl.hasOption("configfile")) {
                logger.error("The config file is mandatory");
                op = Operation.QUIT;

                return;
            }

            try {
                Integer.parseInt(cl.getOptionValue("daemon"));

                this.id = cl.getOptionValue("daemon");
                this.configFile = cl.getOptionValue("configfile");
                this.op = Operation.DAEMON;

                if (cl.hasOption("daemonfrecuency")) {
                    try {
                        Long l = Long.parseLong(id);
                        this.frecuency = l;
                    } catch (NumberFormatException e) {
                        this.logger.info("The frecuency is not a number. Setting to default: 10 sec");
                    }
                } else {
                    this.logger.info("Daemon frecuency not set. Setting to default: 10 sec");
                }
            } catch (NumberFormatException e) {
                this.logger.error("The id following daemon option must be an integer");
                this.op = Operation.QUIT;

                return;
            }
        } else {
            if (!cl.hasOption("gold") || !cl.hasOption("configfile") || !cl.hasOption("parametersfile")
                    || !cl.hasOption("referencetranslations") || !cl.hasOption("sourcelanguage")) {
                logger.error(
                        "The files gold, tr, lo, config.properties and parameters.properties are mandatory for creating jobs");
                this.op = Operation.QUIT;

                return;
            } else {
                if (cl.hasOption("daemon"))
                    this.daemon = true;
                else {
                    if (cl.hasOption("daemonfrecuency"))
                        this.logger.info(
                                "Daemon frecuency parameter found, ignoring it as there's not a daemon option");
                }

                this.configFile = cl.getOptionValue("configfile");
                this.parametersFile = cl.getOptionValue("parametersfile");
                this.pathGold = cl.getOptionValue("gold");
                this.pathLO = cl.getOptionValue("sourcelanguage");
                this.pathTR = cl.getOptionValue("referencetranslations");

                this.op = Operation.CREATE;
            }
        }

    } catch (ParseException ex) {
        logger.error("Failed argument parsing", ex);
    }
}

From source file:com.cloudera.csd.tools.MetricDescriptorGeneratorTool.java

private MapConfiguration generateAndValidateConfig(CommandLine cmdLine) throws ParseException {
    Preconditions.checkNotNull(cmdLine);
    MapConfiguration ret = new MapConfiguration(Maps.<String, Object>newHashMap());

    for (Option option : cmdLine.getOptions()) {
        ret.addProperty(option.getLongOpt(), option.getValue());
    }/*from  www .ja  va  2 s .  c  o  m*/

    if (null == ret.getProperty(OPT_INPUT_MDL.getLongOpt())) {
        throw new ParseException("MetricGeneratorTool missing mdl file " + "location");
    } else {
        String fileName = ret.getString(OPT_INPUT_MDL.getLongOpt());
        File file = new File(fileName);
        if (!file.exists()) {
            throw new ParseException("MDL file '" + fileName + "' does not " + "exist");
        } else if (!file.isFile()) {
            throw new ParseException("MDL file '" + fileName + "' is not a " + "file");
        }
    }

    if (null == ret.getProperty(OPT_INPUT_FIXTURE.getLongOpt())) {
        throw new ParseException("MetricGeneratorTool missing fixture file " + "location");
    } else {
        String fileName = ret.getString(OPT_INPUT_FIXTURE.getLongOpt());
        File file = new File(fileName);
        if (!file.exists()) {
            throw new ParseException("Fixture file '" + fileName + "' does not " + "exist");
        } else if (!file.isFile()) {
            throw new ParseException("Fixture file '" + fileName + "' is not a " + "file");
        }
    }

    if (null != ret.getProperty(OPT_INPUT_CONVENTIONS.getLongOpt())) {
        String fileName = ret.getString(OPT_INPUT_CONVENTIONS.getLongOpt());
        File file = new File(fileName);
        if (!file.exists()) {
            throw new ParseException("Conventions file '" + fileName + "' does " + "not exist");
        } else if (!file.isFile()) {
            throw new ParseException("Conventions file '" + fileName + "' is " + "not a file");
        }
    }

    if (null == ret.getProperty(OPT_ADAPTER_CLASS.getLongOpt())) {
        throw new ParseException("MetricGeneratorTool missing adapter class");
    } else {
        String className = ret.getString(OPT_ADAPTER_CLASS.getLongOpt());
        try {
            Class<?> adapterClass = this.getClass().getClassLoader().loadClass(className);
            if (!MetricFixtureAdapter.class.isAssignableFrom(adapterClass)) {
                throw new ParseException("Adapter class " + className + "is of the " + "wrong type");
            }
            ret.addProperty(ADAPTER_CLASS_CONFIG, adapterClass);
        } catch (ClassNotFoundException e) {
            throw new ParseException("Unknown metric adapter " + className);
        }
    }
    return ret;
}

From source file:mitm.application.djigzo.tools.ProxyManager.java

private void handleCommandline(String[] args) throws Exception {
    CommandLineParser parser = new BasicParser();

    Options options = createCommandLineOptions();

    HelpFormatter formatter = new HelpFormatter();

    CommandLine commandLine;

    try {//from   www.j  av  a  2  s .  c o m
        commandLine = parser.parse(options, args);
    } catch (ParseException e) {
        formatter.printHelp(COMMAND_NAME, options, true);

        throw e;
    }

    if (commandLine.getOptions().length == 0 || commandLine.hasOption("help")) {
        formatter.printHelp(COMMAND_NAME, options, true);

        System.exit(2);
    }

    user = commandLine.getOptionValue("user");

    password = commandLine.getOptionValue("password");

    if (commandLine.hasOption("pwd")) {
        System.err.println("Please enter password: ");
        password = new jline.ConsoleReader().readLine(new Character('*'));
    }

    if (commandLine.hasOption("get")) {
        handleGet();
    }
}

From source file:mitm.common.tools.PfxTool.java

private void handleCommandline(String[] args) throws Exception {
    CommandLineParser parser = new BasicParser();

    Options options = createCommandLineOptions();

    HelpFormatter formatter = new HelpFormatter();

    CommandLine commandLine;

    try {/*from   www.ja  v  a2 s . c  o m*/
        commandLine = parser.parse(options, args);
    } catch (ParseException e) {
        formatter.printHelp(COMMAND_NAME, options, true);

        throw e;
    }

    if (commandLine.getOptions().length == 0) {
        formatter.printHelp(COMMAND_NAME, options, true);

        System.exit(1);

        return;
    }

    if (commandLine.getOptions().length == 0 || commandLine.hasOption(helpOption.getOpt())) {
        formatter.printHelp(COMMAND_NAME, options, true);

        return;
    }

    inPassword = inPasswordOption.getValue();
    destPassword = destPasswordOption.getValue();
    inFile = inOption.getValue();
    destFile = destOption.getValue();
    retainAliases = commandLine.hasOption(retainAliasesOption.getOpt());

    if (commandLine.hasOption(mergeOption.getOpt())) {
        mergePfx();
    }

    if (commandLine.hasOption(listOption.getOpt())) {
        listPfx();
    }
}

From source file:com.fuerve.villageelder.client.commandline.commands.Version.java

@Override
public int execute(final String[] args) {
    StringBuilder result = new StringBuilder();
    boolean afterNumber = false;

    if (args.length == 0) {
        addLabel(result);//from w ww . ja  v  a 2s. co m
        addAll(result);
    } else {
        CommandLine commandLine = parseCommandLine(args);
        if (commandLine.hasOption("?")) {
            printHelp(true);
            return 0;
        }
        if (commandLine.hasOption("a")) {
            addLabel(result);
            addAll(result);
        } else if (commandLine.hasOption("s") && commandLine.getOptions().length == 1) {
            addAll(result);
        } else {
            if (!commandLine.hasOption("s")) {
                addLabel(result);
            }

            if (commandLine.hasOption("M")) {
                addMajor(result);
                afterNumber = true;
            }

            if (commandLine.hasOption("m")) {
                result = afterNumber ? addDelimiter(result) : addNothing(result);
                addMinor(result);
                afterNumber = true;
            }

            if (commandLine.hasOption("u")) {
                result = afterNumber ? addDelimiter(result) : addNothing(result);
                addUpdate(result);
                afterNumber = true;
            }

            if (commandLine.hasOption("h")) {
                result = afterNumber ? addDelimiter(result) : addNothing(result);
                addHotfix(result);
                afterNumber = true;
            }

            if (commandLine.hasOption("b")) {
                result = afterNumber ? addDelimiter(result) : addNothing(result);
                addBuild(result);
                afterNumber = true;
            }
        }

    }

    System.out.println(result.toString());
    return 0;
}

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;//from   w w w .  ja va2 s .c om
                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:hivemall.ftvec.pairing.FeaturePairsUDTF.java

@Override
protected CommandLine processOptions(ObjectInspector[] argOIs) throws UDFArgumentException {
    CommandLine cl = null;
    if (argOIs.length == 2) {
        String args = HiveUtils.getConstString(argOIs[1]);
        cl = parseOptions(args);//from   w w  w  . j  a  v a 2  s  . c  o  m

        Preconditions.checkArgument(cl.getOptions().length <= 3, UDFArgumentException.class,
                "Too many options were specified: " + cl.getArgList());

        if (cl.hasOption("kpa")) {
            this._type = Type.kpa;
        } else if (cl.hasOption("ffm")) {
            this._type = Type.ffm;
            this._numFeatures = Primitives.parseInt(cl.getOptionValue("num_features"), -1);
            if (_numFeatures == -1) {
                int featureBits = Primitives.parseInt(cl.getOptionValue("feature_hashing"), -1);
                if (featureBits != -1) {
                    if (featureBits < 18 || featureBits > 31) {
                        throw new UDFArgumentException(
                                "-feature_hashing MUST be in range [18,31]: " + featureBits);
                    }
                    this._numFeatures = 1 << featureBits;
                }
            }
            this._numFields = Primitives.parseInt(cl.getOptionValue("num_fields"), Feature.DEFAULT_NUM_FIELDS);
            if (_numFields <= 1) {
                throw new UDFArgumentException("-num_fields MUST be greater than 1: " + _numFields);
            }
        } else {
            throw new UDFArgumentException("Unsupported option: " + cl.getArgList().get(0));
        }
    } else {
        throw new UDFArgumentException("MUST provide -kpa or -ffm in the option");
    }

    return cl;
}

From source file:com.imgur.backup.SnapshotS3Util.java

/**
 * Get args /*  w w w  .j  a v  a 2s.  c om*/
 * @param args
 * @throws Exception
 */
private void getAndCheckArgs(String[] args) throws Exception {
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    cmd = parser.parse(getOptions(), args);

    for (Option option : cmd.getOptions()) {
        switch (option.getId()) {
        case 'c':
            createSnapshot = true;
            break;
        case 'x':
            createSnapshot = true;
            exportSnapshot = true;
            break;
        case 'e':
            exportSnapshot = true;
            break;
        case 'i':
            importSnapshot = true;
            break;
        case 't':
            tableName = option.getValue();
            break;
        case 'n':
            snapshotName = option.getValue();
            break;
        case 'k':
            accessKey = option.getValue();
            break;
        case 's':
            accessSecret = option.getValue();
            break;
        case 'b':
            bucketName = option.getValue();
            break;
        case 'p':
            s3Path = option.getValue();
            break;
        case 'd':
            hdfsPath = option.getValue();
            break;
        case 'm':
            mappers = Long.parseLong(option.getValue());
            break;
        case 'a':
            s3protocol = S3N_PROTOCOL;
            break;
        case 'l':
            snapshotTtl = Long.parseLong(option.getValue());
            break;
        default:
            throw new IllegalArgumentException("unexpected option " + option);
        }
    }

    if (createSnapshot && StringUtils.isEmpty(tableName)) {
        throw new IllegalArgumentException("Need a table name");
    }

    if ((importSnapshot || (exportSnapshot && !createSnapshot)) && StringUtils.isEmpty(snapshotName)) {
        throw new IllegalArgumentException("Need a snapshot name");
    }
}

From source file:com.github.lindenb.jvarkit.util.command.CommandFactory.java

public int instanceMain(final String args[]) {
    /* create a new  empty Command  */
    Command cmd = null;//from ww  w. j av  a2  s  . c om

    try {
        /* cmd line */
        final StringBuilder sb = new StringBuilder();
        for (String s : args) {
            if (sb.length() != 0)
                sb.append(" ");
            sb.append(s);
        }
        /* create new options  */
        final Options options = new Options();
        /* get all options and add it to options  */
        fillOptions(options);
        /* create a new CLI parser */
        final CommandLineParser parser = new DefaultParser();
        final CommandLine cli = parser.parse(options, args);

        /* loop over the processed options */
        for (final Option opt : cli.getOptions()) {
            if (opt.hasArg() && !opt.hasOptionalArg() && opt.getValue() == null) {
                LOG.warn("OPTION ####" + opt);
            }
            final Status status = visit(opt);
            switch (status) {
            case EXIT_FAILURE:
                return -1;
            case EXIT_SUCCESS:
                return 0;
            default:
                break;
            }
        }
        cmd = createCommand();

        final Date startDate = new Date();
        LOG.info("Starting JOB at " + startDate + " " + getClass().getName() + " version=" + getVersion() + " "
                + " built=" + getCompileDate());
        LOG.info("Command Line args : "
                + (cmd.getProgramCommandLine().isEmpty() ? "(EMPTY/NO-ARGS)" : cmd.getProgramCommandLine()));
        String hostname = "";
        try {
            hostname = InetAddress.getLocalHost().getHostName();
        } catch (Exception err) {
            hostname = "host";
        }
        LOG.info("Executing as " + System.getProperty("user.name") + "@" + hostname + " on "
                + System.getProperty("os.name") + " " + System.getProperty("os.version") + " "
                + System.getProperty("os.arch") + "; " + System.getProperty("java.vm.name") + " "
                + System.getProperty("java.runtime.version"));

        LOG.debug("initialize " + cmd);
        final Collection<Throwable> initErrors = cmd.initializeKnime();
        if (!(initErrors == null || initErrors.isEmpty())) {
            for (Throwable err : initErrors) {
                LOG.error(err);
            }
            LOG.fatal("Command initialization failed ");
            return -1;
        }

        LOG.debug("calling " + cmd);
        final Collection<Throwable> errors = cmd.call();
        if (!(errors == null || errors.isEmpty())) {
            for (Throwable err : errors) {
                LOG.error(err);
            }
            LOG.fatal("Command failed ");
            return -1;
        }
        LOG.debug("success " + cmd);
        cmd.disposeKnime();
        final Date endDate = new Date();
        final double elapsedMinutes = (endDate.getTime() - startDate.getTime()) / (1000d * 60d);
        final String elapsedString = new DecimalFormat("#,##0.00").format(elapsedMinutes);
        LOG.info("End JOB  [" + endDate + "] " + getName() + " done. Elapsed time: " + elapsedString
                + " minutes.");
        return 0;
    } catch (org.apache.commons.cli.UnrecognizedOptionException err) {
        LOG.fatal("Unknown command (" + err.getOption() + ") , please check your input.", err);
        return -1;
    } catch (Throwable err) {
        LOG.fatal("cannot build command", err);
        return -1;
    } finally {
        if (cmd != null)
            cmd.cleanup();
    }
}

From source file:de.uni_koblenz.ist.utilities.option_handler.OptionHandler.java

/**
 * Checks if all required options are present in the given CommandLine
 * according to the internal Map.//from   w  w w.  j  a  va 2s.c o  m
 * 
 * @param comLine
 *            the commandLine to check.
 * @return true if the given CommandLine contains all required options.
 */
public boolean containsAllRequiredOptions(CommandLine comLine) {
    boolean ok = true;
    Option[] setOptions = comLine.getOptions();

    Set<Option> setOptionsSet = new HashSet<>();
    for (Option current : setOptions) {
        setOptionsSet.add(current);
    }

    for (Option current : optionList) {
        if (isOptionRequired(current)) {
            ok &= setOptionsSet.contains(current);
            if (!ok) {
                break;
            }
        }
    }
    // if all required options are set and there are required OptionGroups,
    // check them
    return ok && !requiredOptionGroups.isEmpty() ? ok && containsAllRequiredOptionGroups(setOptions) : ok;
}