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

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

Introduction

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

Prototype

public void setRequired(boolean required) 

Source Link

Document

Sets whether this Option is mandatory.

Usage

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

/**
 * The only constructor of this class. It sets the toolString and the
 * versionString. In this constructor the two options -h and -v are created
 * and added. It also ensures that only -h or -v can be set.
 * /*from   w w w.j av  a  2s. c o m*/
 * @param toolString
 *            the name of the tool
 * @param versionString
 *            the version information of the tool
 */
public OptionHandler(String toolString, String versionString) {
    options = new Options();
    optionList = new ArrayList<>();
    optionGroupList = new ArrayList<>();
    requiredOptions = new HashSet<>();
    requiredOptionGroups = new HashSet<>();
    helpFormatter = new HelpFormatter();
    parserType = ParserType.GNU;
    this.toolString = toolString;
    this.versionString = versionString;

    Option help = new Option("h", "help", false, "(optional): print this help message.");
    help.setRequired(false);
    addOption(help);

    Option version = new Option("v", "version", false, "(optional): print version information");
    version.setRequired(false);
    addOption(version);

    OptionGroup mainOptions = new OptionGroup();
    mainOptions.setRequired(false);
    mainOptions.addOption(help);
    mainOptions.addOption(version);

    options.addOptionGroup(mainOptions);
    argumentCount = 0;
    argumentName = "parameter";
    optionalArgument = false;
}

From source file:info.mikaelsvensson.devtools.analysis.shared.CommandLineUtil.java

public List<Option> getOptions(Object owner) throws IllegalAccessException {
    List<Option> options = new ArrayList<Option>();
    Class<?> cls = owner.getClass();
    do {/*from  w  w w .  j a v a 2s .c  o m*/
        CliOptions cliOptions = cls.getAnnotation(CliOptions.class);
        if (cliOptions != null) {
            for (CliOptionConfig config : cliOptions.opts()) {

                if (config != null) {
                    Option option = new Option(config.name(), config.description());
                    if (config.longName().length() > 0) {
                        option.setLongOpt(config.longName());
                    }
                    if (config.numArgs() == OPTIONAL) {
                        option.setOptionalArg(true);
                    } else {
                        option.setArgs(config.numArgs());
                    }
                    option.setArgName(config.argsDescription());
                    option.setRequired(config.required());
                    option.setValueSeparator(config.separator());
                    options.add(option);
                }
            }
        }
    } while ((cls = cls.getSuperclass()) != null);
    return options;
}

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

/**
 * This method is used for adding a new Option. It stores the information if
 * the Option is required, sets this value to false and adds the Option to
 * the Options object.//w  w w.  j a  v a2  s  .c o m
 * 
 * @param o
 */
public void addOption(Option o) {
    // backup required Status and set it to false
    if (o.isRequired()) {
        requiredOptions.add(o);
        o.setRequired(false);
    }
    optionList.add(o);
    options.addOption(o);
}

From source file:com.zimbra.common.soap.SoapTestHarness.java

public void runTests(String args[]) throws HarnessException, IOException, ServiceException {

    CliUtil.toolSetup();//  w ww.  j av a  2 s  . c  o m
    SoapTransport.setDefaultUserAgent("SoapTestHarness", null);

    CommandLineParser parser = new GnuParser();
    Options options = new Options();

    options.addOption("h", "help", false, "print usage");
    options.addOption("d", "debug", false, "debug");
    options.addOption("s", "expandsystemprops", false, "exoand system properties");

    Option fileOpt = new Option("f", "file", true, "input document");
    fileOpt.setArgName("request-document");
    fileOpt.setRequired(true);
    options.addOption(fileOpt);

    CommandLine cl = null;
    boolean err = false;
    try {
        cl = parser.parse(options, args);
    } catch (ParseException pe) {
        System.err.println("error: " + pe.getMessage());
        err = true;
    }

    if (err || cl.hasOption("help"))
        usage(options);

    mDebug = cl.hasOption("d");
    String file = cl.getOptionValue("f");

    if (cl.hasOption("s"))
        expandSystemProperties();
    ;

    String docStr = new String(ByteUtil.getContent(new File(file)), "utf-8");
    doTests(Element.parseXML(docStr));

    //Element request = doc.getRootElement();
    //Element response = trans.invoke(request, isRaw);
    //System.out.println(DomUtil.toString(response, true));

    if (mTransport != null)
        mTransport.shutdown();
}

From source file:com.hablutzel.cmdline.CommandLineApplication.java

/**
 * This method scans the subclass for annotations
 * that denote the command line options and arguments,
 * and configures the systems so that the members that
 * have been annotated in that way are set up for calling
 * at command line processing time//from  w  w  w. jav a 2  s.  c  o m
 *
 */
private final void configure() throws CommandLineException {

    // Find all the fields in our subclass
    for (Method method : this.getClass().getDeclaredMethods()) {

        // If this method is marked with a  command line option, then configure
        // a corresponding commons-cli command line option here
        if (method.isAnnotationPresent(CommandLineOption.class)) {
            CommandLineOption commandLineOption = method.getDeclaredAnnotation(CommandLineOption.class);
            if (commandLineOption != null) {

                // Get the basic information about the option - the name and description
                String shortName = commandLineOption.shortForm().equals("") ? null
                        : commandLineOption.shortForm();
                String longName = commandLineOption.longForm().equals("") ? null : commandLineOption.longForm();
                String description = commandLineOption.usage();

                // If both the short and long name are null, then use the field name as the long name
                if (shortName == null && longName == null) {
                    longName = method.getName();
                }

                // The signature of the method determines what kind of command line
                // option is allowed. Basically, if the method does not take an argument,
                // then the option does not take arguments either. In this case, the
                // method is just called when the option is present.
                //
                // If the method does take argument, there are restrictions on the arguments
                // that are allowed. If there is a single argument, then the method will be
                // called for each argument supplied to the option. Generally in this case you
                // want the maximum number of option arguments to be 1, and you are just getting
                // the value of the argument. On the other hand, if the single argument is either
                // and array or a List<>, then the arguments will be passed in as an argument
                // or list respectively.
                //
                // Methods with more than 1 argument are not allowed. Methods with return types
                // other than boolean are not allowed. Methods that throw an exception other than
                // org.apache.commons.cli.CommandLineException are not allowed,
                //
                // If the method returns a boolean, and calling that method returns FALSE, then the
                // command line main function will not be called.
                //
                // The class of the argument has to be convertable using common-beanutils
                // conversion facilities
                CommandLineMethodHelper helper = getHelperForCommandOption(method, commandLineOption);

                // Now create and configure an option based on what the method is capable of handling
                // and the command line option parameters
                boolean allowsArguments = helper.methodType != MethodType.Boolean;
                Option option = new Option(shortName, longName, allowsArguments, description);

                // Configure it
                option.setRequired(commandLineOption.required());
                if (option.hasArg()) {
                    option.setType(helper.elementType);
                    option.setArgs(commandLineOption.maximumArgumentCount());
                    option.setValueSeparator(commandLineOption.argumentSeparator());
                    option.setOptionalArg(commandLineOption.optionalArgument());
                }

                // Remember it, both in the commons-cli options set and
                // in our list of elements for later post-processing
                options.addOption(option);
                optionHelperMap.put(option, helper);
            }

            // This was not a command line option method - is it the main command line method?
        } else if (method.isAnnotationPresent(CommandLineMain.class)) {

            // Make sure we only have one
            if (mainHelper != null) {
                throw new CommandLineException("Cannot have two main methods specified");
            } else {
                mainHelper = getHelperForCommandLineMain(method);
            }
        }
    }
}

From source file:com.github.braully.graph.BatchExecuteOperation.java

void processMain(String... args) {
    GraphCaratheodoryHeuristic.verbose = false;

    Options options = new Options();

    OptionGroup exec = new OptionGroup();
    exec.setRequired(false);//from   w  w w  .j  av a2s  .c  o  m
    IGraphOperation[] opers = getOperations();
    Option[] execs = new Option[opers.length];
    for (int i = 0; i < opers.length; i++) {
        IGraphOperation oper = opers[i];
        execs[i] = new Option("" + i, false, oper.getName());
        options.addOption(execs[i]);
    }
    //        options.addOptionGroup(exec);

    Option input = new Option("i", "input", true, "input file or directory");
    options.addOption(input);

    Option cont = new Option("c", "continue", false, "continue from last processing");
    cont.setRequired(false);
    options.addOption(cont);

    Option verb = new Option("v", "verbose", false, "verbose processing");
    options.addOption(verb);

    Option output = new Option("o", "output", true, "output file");
    output.setRequired(false);
    options.addOption(output);

    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd;

    //        input.setRequired(true);
    //        exec.setRequired(true);
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        formatter.printHelp("BatchExecuteOperation", options);
        System.exit(1);
        return;
    }

    boolean contProcess = false;

    String inputFilePath = cmd.getOptionValue("input");
    if (inputFilePath == null) {
        inputFilePath = getDefaultInput();
    }
    if (inputFilePath == null) {
        return;
    }

    if (cmd.hasOption("continue")) {
        contProcess = true;
    }

    if (cmd.hasOption("verbose")) {
        verbose = true;
    }

    List<IGraphOperation> operationsToExecute = new ArrayList<IGraphOperation>();
    for (int i = 0; i < opers.length; i++) {
        IGraphOperation oper = opers[i];
        String value = execs[i].getOpt();
        if (cmd.hasOption(value)) {
            operationsToExecute.add(oper);
        }
    }

    if (operationsToExecute.isEmpty()) {
        operationsToExecute.add(opers[0]);
        //            formatter.printHelp("BatchExecuteOperation", options);
        //            System.exit(1);
        //            return;
    }
    File dir = new File(inputFilePath);
    if (dir.isDirectory()) {
        processDirectory(operationsToExecute, inputFilePath, contProcess);
    } else if (inputFilePath.toLowerCase().endsWith(".mat")) {
        try {
            for (IGraphOperation operation : operationsToExecute) {
                processFileMat(operation, dir);
            }
        } catch (Exception ex) {
            Logger.getLogger(BatchExecuteOperation.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else if (inputFilePath.toLowerCase().endsWith(".g6")) {
        try {
            for (IGraphOperation operation : operationsToExecute) {
                processFileG6(operation, dir);
            }
        } catch (Exception ex) {
            Logger.getLogger(BatchExecuteOperation.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else if (inputFilePath.toLowerCase().endsWith(".g6.gz")) {
        try {
            for (IGraphOperation operation : operationsToExecute) {
                processFileG6GZ(operation, dir);
            }
        } catch (Exception ex) {
            Logger.getLogger(BatchExecuteOperation.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

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

/**
 * Returns the command-line options supported.
 * @return the command-line options/*from   w  w w .j  a  va 2  s . co  m*/
 */
private static Options getOptions() {
    Option tableName = new Option("t", "table", true,
            "The table name to create a snapshot from. Required for creating a snapshot");
    Option snapshotName = new Option("n", "snapshot", true,
            "The snapshot name. Required for importing from S3");
    Option accessId = new Option("k", "awsAccessKey", true, "The AWS access key");
    Option accessSecret = new Option("s", "awsAccessSecret", true, "The AWS access secret string");
    Option bucketName = new Option("b", "bucketName", true, "The S3 bucket name where snapshots are stored");
    Option s3Path = new Option("p", "s3Path", true, "The snapshot directory in S3. Default is '/hbase'");
    Option hdfsPath = new Option("d", "hdfsPath", true, "The snapshot directory in HDFS. Default is '/hbase'");
    Option mappers = new Option("m", "mappers", true,
            "The number of parallel copiers if copying to/from S3. Default: 1");
    Option useS3n = new Option("a", "s3n", false,
            "Use s3n protocol instead of s3. Might work better, but beware of 5GB file limit imposed by S3");
    Option snapshotTtl = new Option("l", "snapshotTtl", true,
            "Delete snapshots older than this value (seconds) from running HBase cluster");

    tableName.setRequired(false);
    snapshotName.setRequired(false);
    accessId.setRequired(true);
    accessSecret.setRequired(true);
    bucketName.setRequired(true);
    s3Path.setRequired(false);
    hdfsPath.setRequired(false);
    mappers.setRequired(false);
    useS3n.setRequired(false);
    snapshotTtl.setRequired(false);

    Option createSnapshot = new Option("c", "create", false, "Create HBase snapshot");
    Option createExportSnapshot = new Option("x", "createExport", false,
            "Create HBase snapshot AND export to S3");
    Option exportSnapshot = new Option("e", "export", false, "Export HBase snapshot to S3");
    Option importSnapshot = new Option("i", "import", false,
            "Import HBase snapshot from S3. May need to run as hbase user if importing into HBase");

    OptionGroup actions = new OptionGroup();
    actions.setRequired(true);
    actions.addOption(createSnapshot);
    actions.addOption(createExportSnapshot);
    actions.addOption(exportSnapshot);
    actions.addOption(importSnapshot);

    Options options = new Options();
    options.addOptionGroup(actions);
    options.addOption(tableName);
    options.addOption(snapshotName);
    options.addOption(accessId);
    options.addOption(accessSecret);
    options.addOption(bucketName);
    options.addOption(s3Path);
    options.addOption(hdfsPath);
    options.addOption(mappers);
    options.addOption(useS3n);
    options.addOption(snapshotTtl);

    return options;
}

From source file:edu.cornell.med.icb.geo.tools.Affy2InsightfulMiner.java

private void proccess(final String[] args) {
    // create the Options
    final Options options = new Options();

    // help//  ww w  .  j a  v a  2 s  . co m
    options.addOption("h", "help", false, "print this message");

    // input file name
    final Option inputOption = new Option("il", "input-list", true,
            "specify the name of the input file list. This file tab-separated with two columns. Each row must indicate: (1) filename for an Affymetrix text file for one sample, (2) sample ID.");
    inputOption.setArgName("input-file-list");
    inputOption.setRequired(true);
    options.addOption(inputOption);

    // output file name
    final Option outputOption = new Option("o", "output", true, "specify the destination file");
    outputOption.setArgName("file");
    outputOption.setRequired(true);
    options.addOption(outputOption);
    // label values
    final Option labelOptions = new Option("cl", "class-label", true,
            "specify how to set the label of samples");
    labelOptions.setArgName("attribute,value,label");
    labelOptions.setRequired(false);
    options.addOption(labelOptions);

    // group file names
    final Option groupOptions = new Option("sa", "sample-attributes", true,
            "specify a file that associates attributes to samples. The file is tab delimited. The first column of this file is the the sample ID. Additional columns indicate the value of the attributes named in the first line (name of sample ID is can be arbitrary and will be ignored).");
    groupOptions.setArgName("file");
    groupOptions.setRequired(false);
    options.addOption(groupOptions);

    // default label value
    final Option defaultLabelOption = new Option("dl", "default-label", true,
            "Specify the label to use for columns that are not identified by -l -g pairs. Default value is zero.");
    groupOptions.setArgName("double-value");
    groupOptions.setRequired(false);

    // platform description
    final Option platformDescriptionFileOption = new Option("pd", "platform-description", true,
            "The platform description is a GEO platform description file that is used to link probe set ids to genbank identifiers. When a platform description file is provided, the second column in the output will contain the desired indentifier (default genbank).");
    groupOptions.setArgName("file");
    groupOptions.setRequired(false);
    options.addOption(platformDescriptionFileOption);

    // parse the command line arguments
    CommandLine line = null;
    double defaultLabelValue = 0;
    try {
        // create the command line parser
        final CommandLineParser parser = new BasicParser();
        line = parser.parse(options, args, true);
        if ((line.hasOption("cl") && !line.hasOption("sa"))
                || (line.hasOption("sa") && !line.hasOption("cl"))) {
            System.err.println("Options -class-label and -sample-attributes must be used together.");
            System.exit(10);
        }

        if (line.hasOption("dl")) {
            defaultLabelValue = Double.parseDouble(line.getOptionValue("dl"));
        }

    } catch (ParseException e) {
        System.err.println(e.getMessage());
        usage(options);
        System.exit(1);
    }
    // print help and exit
    if (line.hasOption("h")) {
        usage(options);
        System.exit(0);
    }
    try {
        readInputList(line.getOptionValue("il"));
        readSampleAttributes(line.getOptionValue("sa"));
        final String platformFilename = line.getOptionValue("pd");
        System.out.println("Reading platformFileContent description file " + platformFilename);
        platform = new GEOPlatform();
        platform.read(platformFilename);
        System.out.println("Successfully read " + platform.getProbesetCount()
                + " probe set -> secondary identifier pairs.");

        readAndAssembleSamples(line.getOptionValues("cl"), defaultLabelValue, line.getOptionValue("o"));

        System.exit(0);
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(10);
    }
}

From source file:com.marklogic.contentpump.Command.java

static void configConnectionId(Options options) {
    Option username = OptionBuilder.withArgName(USERNAME).hasArg()
            .withDescription("User name of MarkLogic Server").create(USERNAME);
    options.addOption(username);/* w w w.j  a  v a2s.c o  m*/
    Option password = OptionBuilder.withArgName(PASSWORD).hasArg()
            .withDescription("Password of MarkLogic Server").create(PASSWORD);
    options.addOption(password);
    Option host = OptionBuilder.withArgName(HOST).hasArg().withDescription("Host of MarkLogic Server")
            .create(HOST);
    host.setRequired(true);
    options.addOption(host);
    Option port = OptionBuilder.withArgName(PORT).hasArg().withDescription("Port of MarkLogic Server")
            .create(PORT);
    options.addOption(port);
    Option db = OptionBuilder.withArgName(DATABASE).hasArg().withDescription("Database of MarkLogic Server")
            .create(DATABASE);
    options.addOption(db);
}

From source file:de.uni_koblenz.jgralab.utilities.tg2dot.Tg2Dot.java

@Override
protected void addAdditionalOptions(OptionHandler optionHandler) {

    Option pListLayout = new Option("p", "pListLayout", true,
            "(optional): declares a PList-layout file, which should be used to lay out the given graph.");
    pListLayout.setRequired(false);
    optionHandler.addOption(pListLayout);

    Option incidenceIndices = new Option("i", "incidenceIndices", false,
            "(optional): prints the incidence index to every edge.");
    incidenceIndices.setRequired(false);
    optionHandler.addOption(incidenceIndices);

    Option elementSequenceIndices = new Option("m", "elementSequenceIndices", false,
            "(optional): prints the element sequence index of every vertex and edge.");
    elementSequenceIndices.setRequired(false);
    optionHandler.addOption(elementSequenceIndices);

    Option gvFormat = new Option("t", "graphVizFormat", true,
            "(optional): determines the GraphViz output format");
    gvFormat.setRequired(false);/*from  www .  ja v a2s  . c o m*/
    optionHandler.addOption(gvFormat);

    Option gvLayouter = new Option("l", "graphVizLayouter", true,
            "(optional): determines the GraphViz layout program (default: 'dot')");
    gvLayouter.setRequired(false);
    optionHandler.addOption(gvLayouter);
}