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

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

Introduction

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

Prototype

public String getOpt() 

Source Link

Document

Retrieve the name of this Option.

Usage

From source file:org.apache.falcon.cli.FalconInstanceCLI.java

public void instanceCommand(CommandLine commandLine, FalconClient client)
        throws FalconCLIException, IOException {
    Set<String> optionsList = new HashSet<String>();
    for (Option option : commandLine.getOptions()) {
        optionsList.add(option.getOpt());
    }// w ww.j  a v  a 2s.c o m

    String result;
    String type = commandLine.getOptionValue(TYPE_OPT);
    String entity = commandLine.getOptionValue(ENTITY_NAME_OPT);
    String instanceTime = commandLine.getOptionValue(INSTANCE_TIME_OPT);
    String start = commandLine.getOptionValue(START_OPT);
    String end = commandLine.getOptionValue(END_OPT);
    String filePath = commandLine.getOptionValue(FILE_PATH_OPT);
    String runId = commandLine.getOptionValue(RUNID_OPT);
    String colo = commandLine.getOptionValue(COLO_OPT);
    String clusters = commandLine.getOptionValue(CLUSTERS_OPT);
    String sourceClusters = commandLine.getOptionValue(SOURCECLUSTER_OPT);
    List<LifeCycle> lifeCycles = getLifeCycle(commandLine.getOptionValue(LIFECYCLE_OPT));
    String filterBy = commandLine.getOptionValue(FILTER_BY_OPT);
    String orderBy = commandLine.getOptionValue(ORDER_BY_OPT);
    String sortOrder = commandLine.getOptionValue(SORT_ORDER_OPT);
    String doAsUser = commandLine.getOptionValue(DO_AS_OPT);
    Integer offset = parseIntegerInput(commandLine.getOptionValue(OFFSET_OPT), 0, "offset");
    Integer numResults = parseIntegerInput(commandLine.getOptionValue(NUM_RESULTS_OPT), null, "numResults");

    colo = getColo(colo);
    String instanceAction = "instance";
    validateSortOrder(sortOrder);
    validateInstanceCommands(optionsList, entity, type, colo);

    if (optionsList.contains(TRIAGE_OPT)) {
        validateNotEmpty(colo, COLO_OPT);
        validateNotEmpty(start, START_OPT);
        validateNotEmpty(type, TYPE_OPT);
        validateEntityTypeForSummary(type);
        validateNotEmpty(entity, ENTITY_NAME_OPT);
        result = client.triage(type, entity, start, colo).toString();
    } else if (optionsList.contains(DEPENDENCY_OPT)) {
        validateNotEmpty(instanceTime, INSTANCE_TIME_OPT);
        InstanceDependencyResult response = client.getInstanceDependencies(type, entity, instanceTime, colo);
        result = ResponseHelper.getString(response);

    } else if (optionsList.contains(RUNNING_OPT)) {
        validateOrderBy(orderBy, instanceAction);
        validateFilterBy(filterBy, instanceAction);
        result = ResponseHelper.getString(client.getRunningInstances(type, entity, colo, lifeCycles, filterBy,
                orderBy, sortOrder, offset, numResults, doAsUser));
    } else if (optionsList.contains(STATUS_OPT) || optionsList.contains(LIST_OPT)) {
        validateOrderBy(orderBy, instanceAction);
        validateFilterBy(filterBy, instanceAction);
        result = ResponseHelper.getString(client.getStatusOfInstances(type, entity, start, end, colo,
                lifeCycles, filterBy, orderBy, sortOrder, offset, numResults, doAsUser));
    } else if (optionsList.contains(SUMMARY_OPT)) {
        validateOrderBy(orderBy, "summary");
        validateFilterBy(filterBy, "summary");
        result = ResponseHelper.getString(client.getSummaryOfInstances(type, entity, start, end, colo,
                lifeCycles, filterBy, orderBy, sortOrder, doAsUser));
    } else if (optionsList.contains(KILL_OPT)) {
        validateNotEmpty(start, START_OPT);
        validateNotEmpty(end, END_OPT);
        result = ResponseHelper.getString(client.killInstances(type, entity, start, end, colo, clusters,
                sourceClusters, lifeCycles, doAsUser));
    } else if (optionsList.contains(SUSPEND_OPT)) {
        validateNotEmpty(start, START_OPT);
        validateNotEmpty(end, END_OPT);
        result = ResponseHelper.getString(client.suspendInstances(type, entity, start, end, colo, clusters,
                sourceClusters, lifeCycles, doAsUser));
    } else if (optionsList.contains(RESUME_OPT)) {
        validateNotEmpty(start, START_OPT);
        validateNotEmpty(end, END_OPT);
        result = ResponseHelper.getString(client.resumeInstances(type, entity, start, end, colo, clusters,
                sourceClusters, lifeCycles, doAsUser));
    } else if (optionsList.contains(RERUN_OPT)) {
        validateNotEmpty(start, START_OPT);
        validateNotEmpty(end, END_OPT);
        boolean isForced = false;
        if (optionsList.contains(FORCE_RERUN_FLAG)) {
            isForced = true;
        }
        result = ResponseHelper.getString(client.rerunInstances(type, entity, start, end, filePath, colo,
                clusters, sourceClusters, lifeCycles, isForced, doAsUser));
    } else if (optionsList.contains(LOG_OPT)) {
        validateOrderBy(orderBy, instanceAction);
        validateFilterBy(filterBy, instanceAction);
        result = ResponseHelper.getString(client.getLogsOfInstances(type, entity, start, end, colo, runId,
                lifeCycles, filterBy, orderBy, sortOrder, offset, numResults, doAsUser), runId);
    } else if (optionsList.contains(PARARMS_OPT)) {
        // start time is the nominal time of instance
        result = ResponseHelper
                .getString(client.getParamsOfInstance(type, entity, start, colo, lifeCycles, doAsUser));
    } else if (optionsList.contains(LISTING_OPT)) {
        result = ResponseHelper.getString(client.getFeedListing(type, entity, start, end, colo, doAsUser));
    } else {
        throw new FalconCLIException("Invalid command");
    }

    OUT.get().println(result);
}

From source file:org.apache.falcon.cli.FalconMetadataCLI.java

public void metadataCommand(CommandLine commandLine, FalconClient client) throws FalconCLIException {
    Set<String> optionsList = new HashSet<String>();
    for (Option option : commandLine.getOptions()) {
        optionsList.add(option.getOpt());
    }/*www .  ja  v  a 2 s .c  o m*/

    String result;
    String dimensionType = commandLine.getOptionValue(TYPE_OPT);
    String cluster = commandLine.getOptionValue(CLUSTER_OPT);
    String dimensionName = commandLine.getOptionValue(NAME_OPT);
    String id = commandLine.getOptionValue(ID_OPT);
    String key = commandLine.getOptionValue(KEY_OPT);
    String value = commandLine.getOptionValue(VALUE_OPT);
    String direction = commandLine.getOptionValue(DIRECTION_OPT);
    String pipeline = commandLine.getOptionValue(PIPELINE_OPT);
    String doAsUser = commandLine.getOptionValue(FalconCLI.DO_AS_OPT);

    if (optionsList.contains(LINEAGE_OPT)) {
        validatePipelineName(pipeline);
        result = client.getEntityLineageGraph(pipeline, doAsUser).getDotNotation();
    } else if (optionsList.contains(LIST_OPT)) {
        validateDimensionType(dimensionType.toUpperCase());
        result = client.getDimensionList(dimensionType, cluster, doAsUser);
    } else if (optionsList.contains(RELATIONS_OPT)) {
        validateDimensionType(dimensionType.toUpperCase());
        validateDimensionName(dimensionName, RELATIONS_OPT);
        result = client.getDimensionRelations(dimensionType, dimensionName, doAsUser);
    } else if (optionsList.contains(VERTEX_CMD)) {
        validateId(id);
        result = client.getVertex(id, doAsUser);
    } else if (optionsList.contains(VERTICES_CMD)) {
        validateVerticesCommand(key, value);
        result = client.getVertices(key, value, doAsUser);
    } else if (optionsList.contains(VERTEX_EDGES_CMD)) {
        validateVertexEdgesCommand(id, direction);
        result = client.getVertexEdges(id, direction, doAsUser);
    } else if (optionsList.contains(EDGE_CMD)) {
        validateId(id);
        result = client.getEdge(id, doAsUser);
    } else {
        throw new FalconCLIException("Invalid metadata command");
    }

    OUT.get().println(result);
}

From source file:org.apache.falcon.cli.FalconRecipeCLI.java

public void recipeCommand(CommandLine commandLine, FalconClient client) throws FalconCLIException {
    Set<String> optionsList = new HashSet<String>();
    for (Option option : commandLine.getOptions()) {
        optionsList.add(option.getOpt());
    }/*from w  ww.  j av  a2s  . c om*/

    String recipeName = commandLine.getOptionValue(RECIPE_NAME);
    String recipeToolClass = commandLine.getOptionValue(RECIPE_TOOL_CLASS_NAME);
    String recipeOperation = commandLine.getOptionValue(RECIPE_OPERATION);
    String recipePropertiesFile = commandLine.getOptionValue(RECIPE_PROPERTIES_FILE);
    String doAsUser = commandLine.getOptionValue(DO_AS_OPT);

    validateNotEmpty(recipeName, RECIPE_NAME);
    validateNotEmpty(recipeOperation, RECIPE_OPERATION);
    validateRecipeOperations(recipeOperation);
    validateRecipePropertiesFile(recipePropertiesFile, recipeName);
    Boolean skipDryRun = null;
    if (optionsList.contains(SKIPDRYRUN_OPT)) {
        skipDryRun = true;
    }

    String result = client.submitRecipe(recipeName, recipeToolClass, recipeOperation, recipePropertiesFile,
            skipDryRun, doAsUser).toString();
    OUT.get().println(result);
}

From source file:org.apache.flex.compiler.clients.ASC.java

/**
 * Apache Common CLI did the lexer work. This function does the parser work
 * to construct an {@code ASC} job from the command-line options.
 * /*ww w .  j av  a  2  s  .co  m*/
 * @param line - the tokenized command-line
 * @return a new ASC client for the given command-line configuration; null
 * if no arguments were given.
 */
private Boolean createClient(final CommandLine line) throws ParseException {
    // First, process parsed command line options.
    final Option[] options = line.getOptions();

    if (options == null)
        return false;

    for (int i = 0; i < options.length; i++) {
        final Option option = options[i];
        final String shortName = option.getOpt();

        if ("import".equals(shortName)) {
            String[] imports = option.getValues();
            for (int j = 0; j < imports.length; j++) {
                this.addImportFilename(imports[j]);
            }
        } else if ("in".equals(shortName)) {
            String[] includes = option.getValues();
            for (int j = 0; j < includes.length; j++) {
                this.addIncludeFilename(includes[j]);
            }
        } else if ("swf".equals(shortName)) {
            String[] swfValues = option.getValue().split(",");
            if (swfValues.length < 3)
                throw new MissingArgumentException(
                        "The swf option requires three arguments, only " + swfValues.length + " were found.");

            for (int j = 0; j < swfValues.length; j++) {
                String value = swfValues[j];
                if (j == 0)
                    this.setSymbolClass(value);
                else if (j == 1)
                    this.setWidth(value);
                else if (j == 2)
                    this.setHeight(value);
                else if (j == 3)
                    this.setFrameRate(value);
            }
        } else if ("use".equals(shortName)) {
            String[] namespaces = option.getValues();
            for (String namespace : namespaces) {
                this.addNamespace(namespace);
            }
        } else if ("config".equals(shortName)) {
            String[] config = option.getValues();
            if (config.length == 2) {
                // The config option will have been split around '='
                // e.g. CONFIG::Foo='hi' will be split into
                // 2 values - 'CONFIG::Foo' and 'hi'
                String name = config[0];
                String value = config[1];
                value = fixupMissingQuote(value);
                this.putConfigVar(name, value);
            }
        } else if ("strict".equals(shortName) || "!".equals(shortName)) {
            this.setUseStaticSemantics(true);
        } else if ("d".equals(shortName)) {
            this.setEmitDebugInfo(true);
        } else if ("warnings".equals(shortName) || "coach".equals(shortName)) {
            if ("coach".equals(shortName))
                err.println("'coach' has been deprecated. Please use 'warnings' instead.");
            this.setShowWarnings(true);
        } else if ("log".equals(shortName)) {
            this.setShowLog(true);
        } else if ("md".equals(shortName)) {
            this.setEmitMetadata(true);
        } else if ("merge".equals(shortName)) {
            this.setMergeABCs(true);
        } else if ("language".equals(shortName)) {
            String value = option.getValue();
            this.setLocale(getLocaleForLanguage(value));
        } else if ("doc".equals(shortName)) {
            this.setEmitDocInfo(true);
        } else if ("avmtarget".equals(shortName)) {
            String value = option.getValue();
            this.setTargetAVM(value);
        } else if ("AS3".equals(shortName)) {
            this.setDialect("AS3");
        } else if ("ES".equals(shortName)) {
            this.setDialect("ES");
        } else if ("o".equalsIgnoreCase(shortName) || "optimize".equalsIgnoreCase(shortName)) {
            this.setOptimize(true);
        } else if ("o2".equalsIgnoreCase(shortName)) {
            this.setOptimize(true);
        } else if ("out".equalsIgnoreCase(shortName)) {
            this.setOutputBasename(option.getValue());
        } else if ("outdir".equalsIgnoreCase(shortName)) {
            this.setOutputDirectory(option.getValue());
        } else if ("abcfuture".equals(shortName)) {
            this.setABCFuture(true);
        } else if ("p".equals(shortName)) {
            this.setShowParseTrees(true);
        } else if ("i".equals(shortName)) {
            this.setShowInstructions(true);
        } else if ("m".equals(shortName)) {
            this.setShowMachineCode(true);
        } else if ("f".equals(shortName)) {
            this.setShowFlowGraph(true);
        } else if ("exe".equals(shortName)) {
            String exe = option.getValue();
            this.setAvmplusFilename(exe);
        } else if ("movieclip".equals(shortName)) {
            this.setMakeMovieClip(true);
        } else if ("ES4".equals(shortName)) {
            this.setDialect("ES4");
        } else if ("li".equals(shortName)) {
            this.internalLibraries.add(option.getValue());
        } else if ("le".equals(shortName)) {
            this.externalLibraries.add(option.getValue());
        } else if ("parallel".equals(shortName)) {
            this.setParallel(true);
        } else if ("inline".equals(shortName)) {
            this.setMergeABCs(true); // inlining requires merging of ABCs
            this.setEnableInlining(true);
        } else if ("removedeadcode".equals(shortName)) {
            this.setRemoveDeadCode(true);
        } else {
            throw new UnrecognizedOptionException("Unrecognized option '" + shortName + "'", shortName);
        }
    }

    // Then any remaining arguments that were not options are interpreted as
    // source files to compile.
    final String[] remainingArgs = line.getArgs();
    if (remainingArgs != null) {
        for (int i = 0; i < remainingArgs.length; i++) {
            this.addSourceFilename(remainingArgs[i]);
        }
    } else {
        throw new MissingArgumentException(
                "At least one source file must be specified after the list of options.");
    }

    return true;
}

From source file:org.apache.flink.runtime.jobmanager.JobManager.java

@SuppressWarnings("static-access")
public static JobManager initialize(String[] args) throws Exception {
    final Option configDirOpt = OptionBuilder.withArgName("config directory").hasArg()
            .withDescription("Specify configuration directory.").create("configDir");

    final Option executionModeOpt = OptionBuilder.withArgName("execution mode").hasArg()
            .withDescription("Specify execution mode.").create("executionMode");

    final Options options = new Options();
    options.addOption(configDirOpt);/*from  ww  w.j  a v a 2s  .  c  om*/
    options.addOption(executionModeOpt);

    CommandLineParser parser = new GnuParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, args);
    } catch (ParseException e) {
        LOG.error("CLI Parsing failed. Reason: " + e.getMessage());
        System.exit(FAILURE_RETURN_CODE);
    }

    final String configDir = line.getOptionValue(configDirOpt.getOpt(), null);
    final String executionModeName = line.getOptionValue(executionModeOpt.getOpt(), "local");

    ExecutionMode executionMode = null;
    if ("local".equals(executionModeName)) {
        executionMode = ExecutionMode.LOCAL;
    } else if ("cluster".equals(executionModeName)) {
        executionMode = ExecutionMode.CLUSTER;
    } else {
        System.err.println("Unrecognized execution mode: " + executionModeName);
        System.exit(FAILURE_RETURN_CODE);
    }

    // print some startup environment info, like user, code revision, etc
    EnvironmentInformation.logEnvironmentInfo(LOG, "JobManager");

    // First, try to load global configuration
    GlobalConfiguration.loadConfiguration(configDir);

    // Create a new job manager object
    JobManager jobManager = new JobManager(executionMode);

    // Set base dir for info server
    Configuration infoserverConfig = GlobalConfiguration.getConfiguration();
    if (configDir != null && new File(configDir).isDirectory()) {
        infoserverConfig.setString(ConfigConstants.FLINK_BASE_DIR_PATH_KEY, configDir + "/..");
    }
    GlobalConfiguration.includeConfiguration(infoserverConfig);
    return jobManager;
}

From source file:org.apache.flink.runtime.taskmanager.TaskManager.java

/**
 * Entry point for the TaskManager executable.
 * //from w w  w  .ja v a2s  . co m
 * @param args Arguments from the command line
 * @throws IOException 
 */
@SuppressWarnings("static-access")
public static void main(String[] args) throws IOException {
    Option configDirOpt = OptionBuilder.withArgName("config directory").hasArg()
            .withDescription("Specify configuration directory.").create("configDir");
    // tempDir option is used by the YARN client.
    Option tempDir = OptionBuilder.withArgName("temporary directory (overwrites configured option)").hasArg()
            .withDescription("Specify temporary directory.").create(ARG_CONF_DIR);
    configDirOpt.setRequired(true);
    tempDir.setRequired(false);
    Options options = new Options();
    options.addOption(configDirOpt);
    options.addOption(tempDir);

    CommandLineParser parser = new GnuParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println("CLI Parsing failed. Reason: " + e.getMessage());
        System.exit(STARTUP_FAILURE_RETURN_CODE);
    }

    String configDir = line.getOptionValue(configDirOpt.getOpt(), null);
    String tempDirVal = line.getOptionValue(tempDir.getOpt(), null);

    // First, try to load global configuration
    GlobalConfiguration.loadConfiguration(configDir);
    if (tempDirVal != null // the YARN TM runner has set a value for the temp dir
            // the configuration does not contain a temp directory
            && GlobalConfiguration.getString(ConfigConstants.TASK_MANAGER_TMP_DIR_KEY, null) == null) {
        Configuration c = GlobalConfiguration.getConfiguration();
        c.setString(ConfigConstants.TASK_MANAGER_TMP_DIR_KEY, tempDirVal);
        LOG.info("Setting temporary directory to " + tempDirVal);
        GlobalConfiguration.includeConfiguration(c);
    }

    // print some startup environment info, like user, code revision, etc
    EnvironmentInformation.logEnvironmentInfo(LOG, "TaskManager");

    // Create a new task manager object
    try {
        createTaskManager(ExecutionMode.CLUSTER);
    } catch (Throwable t) {
        LOG.error("Taskmanager startup failed: " + t.getMessage(), t);
        System.exit(STARTUP_FAILURE_RETURN_CODE);
    }

    // park the main thread to keep the JVM alive (all other threads may be daemon threads)
    Object mon = new Object();
    synchronized (mon) {
        try {
            mon.wait();
        } catch (InterruptedException ex) {
        }
    }
}

From source file:org.apache.flink.table.client.cli.CliOptionsParser.java

private static List<URL> checkUrls(CommandLine line, Option option) {
    if (line.hasOption(option.getOpt())) {
        final String[] urls = line.getOptionValues(option.getOpt());
        return Arrays.stream(urls).distinct().map((url) -> {
            try {
                return Path.fromLocalFile(new File(url).getAbsoluteFile()).toUri().toURL();
            } catch (Exception e) {
                throw new SqlClientException("Invalid path for option '" + option.getLongOpt() + "': " + url,
                        e);//from w  w  w  .  j  a  v  a2  s .  c  o  m
            }
        }).collect(Collectors.toList());
    }
    return null;
}

From source file:org.apache.flink.yarn.cli.FlinkYarnSessionCli.java

/**
 * Tries to load a Flink Yarn properties file and returns the Yarn application id if successful
 * @param cmdLine The command-line parameters
 * @param flinkConfiguration The flink configuration
 * @return Yarn application id or null if none could be retrieved
 *///from   w  ww  .java 2 s .  c o  m
private String loadYarnPropertiesFile(CommandLine cmdLine, Configuration flinkConfiguration) {

    String jobManagerOption = cmdLine.getOptionValue(ADDRESS_OPTION.getOpt(), null);
    if (jobManagerOption != null) {
        // don't resume from properties file if a JobManager has been specified
        return null;
    }

    for (Option option : cmdLine.getOptions()) {
        if (ALL_OPTIONS.hasOption(option.getOpt())) {
            if (!option.getOpt().equals(DETACHED.getOpt())) {
                // don't resume from properties file if yarn options have been specified
                return null;
            }
        }
    }

    // load the YARN properties
    File propertiesFile = getYarnPropertiesLocation(flinkConfiguration);
    if (!propertiesFile.exists()) {
        return null;
    }

    logAndSysout("Found YARN properties file " + propertiesFile.getAbsolutePath());

    Properties yarnProperties = new Properties();
    try {
        try (InputStream is = new FileInputStream(propertiesFile)) {
            yarnProperties.load(is);
        }
    } catch (IOException e) {
        throw new RuntimeException("Cannot read the YARN properties file", e);
    }

    // get the Yarn application id from the properties file
    String applicationID = yarnProperties.getProperty(YARN_APPLICATION_ID_KEY);
    if (applicationID == null) {
        throw new IllegalConfigurationException("Yarn properties file found but doesn't contain a "
                + "Yarn application id. Please delete the file at " + propertiesFile.getAbsolutePath());
    }

    try {
        // try converting id to ApplicationId
        ConverterUtils.toApplicationId(applicationID);
    } catch (Exception e) {
        throw new RuntimeException(
                "YARN properties contains an invalid entry for " + "application id: " + applicationID, e);
    }

    logAndSysout("Using Yarn application id from YARN properties " + applicationID);

    // configure the default parallelism from YARN
    String propParallelism = yarnProperties.getProperty(YARN_PROPERTIES_PARALLELISM);
    if (propParallelism != null) { // maybe the property is not set
        try {
            int parallelism = Integer.parseInt(propParallelism);
            flinkConfiguration.setInteger(ConfigConstants.DEFAULT_PARALLELISM_KEY, parallelism);

            logAndSysout("YARN properties set default parallelism to " + parallelism);
        } catch (NumberFormatException e) {
            throw new RuntimeException("Error while parsing the YARN properties: " + "Property "
                    + YARN_PROPERTIES_PARALLELISM + " is not an integer.");
        }
    }

    // handle the YARN client's dynamic properties
    String dynamicPropertiesEncoded = yarnProperties.getProperty(YARN_PROPERTIES_DYNAMIC_PROPERTIES_STRING);
    Map<String, String> dynamicProperties = getDynamicProperties(dynamicPropertiesEncoded);
    for (Map.Entry<String, String> dynamicProperty : dynamicProperties.entrySet()) {
        flinkConfiguration.setString(dynamicProperty.getKey(), dynamicProperty.getValue());
    }

    return applicationID;
}

From source file:org.apache.geronimo.cli.PrintHelper.java

public void printUsage(PrintWriter pw, int width, String app, Options options) {
    // create a list for processed option groups
    ArrayList list = new ArrayList();

    StringBuilder optionsBuff = new StringBuilder();

    // temp variable
    Option option;

    // iterate over the options
    for (Iterator i = options.getOptions().iterator(); i.hasNext();) {
        // get the next Option
        option = (Option) i.next();

        // check if the option is part of an OptionGroup
        OptionGroup group = options.getOptionGroup(option);

        // if the option is part of a group and the group has not already
        // been processed
        if (group != null && !list.contains(group)) {

            // add the group to the processed list
            list.add(group);//from  w  ww .  j ava  2 s.  com

            // get the names of the options from the OptionGroup
            Collection names = group.getNames();

            optionsBuff.append("[");

            // for each option in the OptionGroup
            for (Iterator iter = names.iterator(); iter.hasNext();) {
                optionsBuff.append(iter.next());
                if (iter.hasNext()) {
                    optionsBuff.append("|");
                }
            }
            optionsBuff.append("] ");
        } else if (group == null) {
            // if the Option is not part of an OptionGroup
            // if the Option is not a required option
            if (!option.isRequired()) {
                optionsBuff.append("[");
            }

            if (!" ".equals(option.getOpt())) {
                optionsBuff.append("-").append(option.getOpt());
            } else {
                optionsBuff.append("--").append(option.getLongOpt());
            }

            if (option.hasArg()) {
                optionsBuff.append(" ");
            }

            // if the Option has a value
            if (option.hasArg()) {
                optionsBuff.append(option.getArgName());
            }

            // if the Option is not a required option
            if (!option.isRequired()) {
                optionsBuff.append("]");
            }
            optionsBuff.append(" ");
        }
    }

    app = app.replace("$options", optionsBuff.toString());

    // call printWrapped
    printWrapped(pw, width, app.indexOf(' ') + 1, app);
}

From source file:org.apache.geronimo.cli.PrintHelper.java

protected StringBuilder renderOptions(StringBuilder sb, int width, Options options, int leftPad, int descPad,
        boolean displayDesc) {
    final String lpad = createPadding(leftPad);
    final String dpad = createPadding(descPad);

    //first create list containing only <lpad>-a,--aaa where -a is opt and --aaa is
    //long opt; in parallel look for the longest opt string
    //this list will be then used to sort options ascending
    int max = 0;//from  w  ww. j  a v a2s .c  o m
    StringBuilder optBuf;
    List prefixList = new ArrayList();
    Option option;
    List optList = new ArrayList(options.getOptions());
    Collections.sort(optList, new StringBuilderComparator());
    for (Iterator i = optList.iterator(); i.hasNext();) {
        option = (Option) i.next();
        optBuf = new StringBuilder(8);

        if (option.getOpt().equals(" ")) {
            optBuf.append(lpad).append("   " + defaultLongOptPrefix).append(option.getLongOpt());
        } else {
            optBuf.append(lpad).append(defaultOptPrefix).append(option.getOpt());
            if (option.hasLongOpt()) {
                optBuf.append(',').append(defaultLongOptPrefix).append(option.getLongOpt());
            }

        }

        if (option.hasArg()) {
            if (option.hasArgName()) {
                optBuf.append(" <").append(option.getArgName()).append('>');
            } else {
                optBuf.append(' ');
            }
        }

        prefixList.add(optBuf);
        max = optBuf.length() > max ? optBuf.length() : max;
    }
    int x = 0;
    for (Iterator i = optList.iterator(); i.hasNext();) {
        option = (Option) i.next();
        optBuf = new StringBuilder(prefixList.get(x++).toString());

        if (optBuf.length() < max) {
            optBuf.append(createPadding(max - optBuf.length()));
        }
        optBuf.append(dpad);

        if (displayDesc) {
            optBuf.append(option.getDescription());
        }
        int nextLineTabStop = max + descPad;
        renderWrappedText(sb, width, nextLineTabStop, optBuf.toString());
        if (i.hasNext()) {
            sb.append(defaultNewLine);
            if (displayDesc) {
                sb.append(defaultNewLine);
            }
        }
    }

    return sb;
}