Example usage for org.apache.commons.cli Options getOption

List of usage examples for org.apache.commons.cli Options getOption

Introduction

In this page you can find the example usage for org.apache.commons.cli Options getOption.

Prototype

public Option getOption(String opt) 

Source Link

Document

Retrieve the Option matching the long or short name specified.

Usage

From source file:org.apache.flink.table.client.config.entries.DeploymentEntry.java

/**
 * Parses the given command line options from the deployment properties. Ignores properties
 * that are not defined by options.//w  ww  . j  a  va 2  s  . com
 */
public CommandLine getCommandLine(Options commandLineOptions) throws Exception {
    final List<String> args = new ArrayList<>();

    properties.asMap().forEach((k, v) -> {
        // only add supported options
        if (commandLineOptions.hasOption(k)) {
            final Option o = commandLineOptions.getOption(k);
            final String argument = "--" + o.getLongOpt();
            // options without args
            if (!o.hasArg()) {
                final Boolean flag = Boolean.parseBoolean(v);
                // add key only
                if (flag) {
                    args.add(argument);
                }
            }
            // add key and value
            else if (!o.hasArgs()) {
                args.add(argument);
                args.add(v);
            }
            // options with multiple args are not supported yet
            else {
                throw new IllegalArgumentException("Option '" + o + "' is not supported yet.");
            }
        }
    });

    return CliFrontendParser.parse(commandLineOptions, args.toArray(new String[args.size()]), true);
}

From source file:org.apache.hadoop.hbase.regionserver.DataBlockEncodingTool.java

/**
 * A command line interface to benchmarks. Parses command-line arguments and
 * runs the appropriate benchmarks./*from  ww  w.  j a  v a2s  .  com*/
 * @param args Should have length at least 1 and holds the file path to HFile.
 * @throws IOException If you specified the wrong file.
 */
public static void main(final String[] args) throws IOException {
    // set up user arguments
    Options options = new Options();
    options.addOption(OPT_HFILE_NAME, true, "HFile to analyse (REQUIRED)");
    options.getOption(OPT_HFILE_NAME).setArgName("FILENAME");
    options.addOption(OPT_KV_LIMIT, true, "Maximum number of KeyValues to process. A benchmark stops running "
            + "after iterating over this many KV pairs.");
    options.getOption(OPT_KV_LIMIT).setArgName("NUMBER");
    options.addOption(OPT_MEASURE_THROUGHPUT, false, "Measure read throughput");
    options.addOption(OPT_OMIT_CORRECTNESS_TEST, false, "Omit corectness tests.");
    options.addOption(OPT_ENCODING_ALGORITHM, true, "What kind of compression algorithm use for comparison.");
    options.addOption(OPT_BENCHMARK_N_TIMES, true,
            "Number of times to run each benchmark. Default value: " + DEFAULT_BENCHMARK_N_TIMES);
    options.addOption(OPT_BENCHMARK_N_OMIT, true, "Number of first runs of every benchmark to exclude from "
            + "statistics (" + DEFAULT_BENCHMARK_N_OMIT + " by default, so that " + "only the last "
            + (DEFAULT_BENCHMARK_N_TIMES - DEFAULT_BENCHMARK_N_OMIT) + " times are included in statistics.)");

    // parse arguments
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println("Could not parse arguments!");
        System.exit(-1);
        return; // avoid warning
    }

    int kvLimit = Integer.MAX_VALUE;
    if (cmd.hasOption(OPT_KV_LIMIT)) {
        kvLimit = Integer.parseInt(cmd.getOptionValue(OPT_KV_LIMIT));
    }

    // basic argument sanity checks
    if (!cmd.hasOption(OPT_HFILE_NAME)) {
        LOG.error("Please specify HFile name using the " + OPT_HFILE_NAME + " option");
        printUsage(options);
        System.exit(-1);
    }

    String pathName = cmd.getOptionValue(OPT_HFILE_NAME);
    String compressionName = DEFAULT_COMPRESSION.getName();
    if (cmd.hasOption(OPT_ENCODING_ALGORITHM)) {
        compressionName = cmd.getOptionValue(OPT_ENCODING_ALGORITHM).toLowerCase();
    }
    boolean doBenchmark = cmd.hasOption(OPT_MEASURE_THROUGHPUT);
    boolean doVerify = !cmd.hasOption(OPT_OMIT_CORRECTNESS_TEST);

    if (cmd.hasOption(OPT_BENCHMARK_N_TIMES)) {
        benchmarkNTimes = Integer.valueOf(cmd.getOptionValue(OPT_BENCHMARK_N_TIMES));
    }
    if (cmd.hasOption(OPT_BENCHMARK_N_OMIT)) {
        benchmarkNOmit = Integer.valueOf(cmd.getOptionValue(OPT_BENCHMARK_N_OMIT));
    }
    if (benchmarkNTimes < benchmarkNOmit) {
        LOG.error("The number of times to run each benchmark (" + benchmarkNTimes
                + ") must be greater than the number of benchmark runs to exclude " + "from statistics ("
                + benchmarkNOmit + ")");
        System.exit(1);
    }
    LOG.info("Running benchmark " + benchmarkNTimes + " times. " + "Excluding the first " + benchmarkNOmit
            + " times from statistics.");

    final Configuration conf = HBaseConfiguration.create();
    try {
        testCodecs(conf, kvLimit, pathName, compressionName, doBenchmark, doVerify);
    } finally {
        (new CacheConfig(conf)).getBlockCache().shutdown();
    }
}

From source file:org.apache.hadoop.yarn.client.cli.ApplicationCLI.java

@Override
public int run(String[] args) throws Exception {
    Options opts = new Options();
    String title = null;/*from   w w w. j a va  2s.  c  o  m*/
    if (args.length > 0 && args[0].equalsIgnoreCase(APPLICATION)) {
        title = APPLICATION;
        opts.addOption(STATUS_CMD, true, "Prints the status of the application.");
        opts.addOption(LIST_CMD, false,
                "List applications. " + "Supports optional use of -appTypes to filter applications "
                        + "based on application type, "
                        + "and -appStates to filter applications based on application state.");
        opts.addOption(MOVE_TO_QUEUE_CMD, true, "Moves the application to a " + "different queue.");
        opts.addOption(QUEUE_CMD, true,
                "Works with the movetoqueue command to" + " specify which queue to move an application to.");
        opts.addOption(HELP_CMD, false, "Displays help for all commands.");
        Option appTypeOpt = new Option(APP_TYPE_CMD, true, "Works with -list to "
                + "filter applications based on " + "input comma-separated list of application types.");
        appTypeOpt.setValueSeparator(',');
        appTypeOpt.setArgs(Option.UNLIMITED_VALUES);
        appTypeOpt.setArgName("Types");
        opts.addOption(appTypeOpt);
        Option appStateOpt = new Option(APP_STATE_CMD, true,
                "Works with -list " + "to filter applications based on input comma-separated list of "
                        + "application states. " + getAllValidApplicationStates());
        appStateOpt.setValueSeparator(',');
        appStateOpt.setArgs(Option.UNLIMITED_VALUES);
        appStateOpt.setArgName("States");
        opts.addOption(appStateOpt);
        opts.addOption(APP_ID, true, "Specify Application Id to be operated");
        opts.addOption(UPDATE_PRIORITY, true,
                "update priority of an application. ApplicationId can be" + " passed using 'appId' option.");
        Option killOpt = new Option(KILL_CMD, true,
                "Kills the application. " + "Set of applications can be provided separated with space");
        killOpt.setValueSeparator(' ');
        killOpt.setArgs(Option.UNLIMITED_VALUES);
        killOpt.setArgName("Application ID");
        opts.addOption(killOpt);
        opts.getOption(MOVE_TO_QUEUE_CMD).setArgName("Application ID");
        opts.getOption(QUEUE_CMD).setArgName("Queue Name");
        opts.getOption(STATUS_CMD).setArgName("Application ID");
        opts.getOption(APP_ID).setArgName("Application ID");
        opts.getOption(UPDATE_PRIORITY).setArgName("Priority");
    } else if (args.length > 0 && args[0].equalsIgnoreCase(APPLICATION_ATTEMPT)) {
        title = APPLICATION_ATTEMPT;
        opts.addOption(STATUS_CMD, true, "Prints the status of the application attempt.");
        opts.addOption(LIST_CMD, true, "List application attempts for application.");
        opts.addOption(FAIL_CMD, true, "Fails application attempt.");
        opts.addOption(HELP_CMD, false, "Displays help for all commands.");
        opts.getOption(STATUS_CMD).setArgName("Application Attempt ID");
        opts.getOption(LIST_CMD).setArgName("Application ID");
        opts.getOption(FAIL_CMD).setArgName("Application Attempt ID");
    } else if (args.length > 0 && args[0].equalsIgnoreCase(CONTAINER)) {
        title = CONTAINER;
        opts.addOption(STATUS_CMD, true, "Prints the status of the container.");
        opts.addOption(LIST_CMD, true, "List containers for application attempt.");
        opts.addOption(HELP_CMD, false, "Displays help for all commands.");
        opts.getOption(STATUS_CMD).setArgName("Container ID");
        opts.getOption(LIST_CMD).setArgName("Application Attempt ID");
        opts.addOption(SIGNAL_CMD, true,
                "Signal the container. The available signal commands are "
                        + java.util.Arrays.asList(SignalContainerCommand.values())
                        + " Default command is OUTPUT_THREAD_DUMP.");
        opts.getOption(SIGNAL_CMD).setArgName("container ID [signal command]");
        opts.getOption(SIGNAL_CMD).setArgs(3);
    }

    int exitCode = -1;
    CommandLine cliParser = null;
    try {
        cliParser = new GnuParser().parse(opts, args);
    } catch (MissingArgumentException ex) {
        sysout.println("Missing argument for options");
        printUsage(title, opts);
        return exitCode;
    }

    if (cliParser.hasOption(STATUS_CMD)) {
        if (args.length != 3) {
            printUsage(title, opts);
            return exitCode;
        }
        if (args[0].equalsIgnoreCase(APPLICATION)) {
            exitCode = printApplicationReport(cliParser.getOptionValue(STATUS_CMD));
        } else if (args[0].equalsIgnoreCase(APPLICATION_ATTEMPT)) {
            exitCode = printApplicationAttemptReport(cliParser.getOptionValue(STATUS_CMD));
        } else if (args[0].equalsIgnoreCase(CONTAINER)) {
            exitCode = printContainerReport(cliParser.getOptionValue(STATUS_CMD));
        }
        return exitCode;
    } else if (cliParser.hasOption(LIST_CMD)) {
        if (args[0].equalsIgnoreCase(APPLICATION)) {
            allAppStates = false;
            Set<String> appTypes = new HashSet<String>();
            if (cliParser.hasOption(APP_TYPE_CMD)) {
                String[] types = cliParser.getOptionValues(APP_TYPE_CMD);
                if (types != null) {
                    for (String type : types) {
                        if (!type.trim().isEmpty()) {
                            appTypes.add(StringUtils.toUpperCase(type).trim());
                        }
                    }
                }
            }

            EnumSet<YarnApplicationState> appStates = EnumSet.noneOf(YarnApplicationState.class);
            if (cliParser.hasOption(APP_STATE_CMD)) {
                String[] states = cliParser.getOptionValues(APP_STATE_CMD);
                if (states != null) {
                    for (String state : states) {
                        if (!state.trim().isEmpty()) {
                            if (state.trim().equalsIgnoreCase(ALLSTATES_OPTION)) {
                                allAppStates = true;
                                break;
                            }
                            try {
                                appStates.add(
                                        YarnApplicationState.valueOf(StringUtils.toUpperCase(state).trim()));
                            } catch (IllegalArgumentException ex) {
                                sysout.println("The application state " + state + " is invalid.");
                                sysout.println(getAllValidApplicationStates());
                                return exitCode;
                            }
                        }
                    }
                }
            }
            listApplications(appTypes, appStates);
        } else if (args[0].equalsIgnoreCase(APPLICATION_ATTEMPT)) {
            if (args.length != 3) {
                printUsage(title, opts);
                return exitCode;
            }
            listApplicationAttempts(cliParser.getOptionValue(LIST_CMD));
        } else if (args[0].equalsIgnoreCase(CONTAINER)) {
            if (args.length != 3) {
                printUsage(title, opts);
                return exitCode;
            }
            listContainers(cliParser.getOptionValue(LIST_CMD));
        }
    } else if (cliParser.hasOption(KILL_CMD)) {
        if (args.length < 3 || hasAnyOtherCLIOptions(cliParser, opts, KILL_CMD)) {
            printUsage(title, opts);
            return exitCode;
        }
        return killApplication(cliParser.getOptionValues(KILL_CMD));
    } else if (cliParser.hasOption(MOVE_TO_QUEUE_CMD)) {
        if (!cliParser.hasOption(QUEUE_CMD)) {
            printUsage(title, opts);
            return exitCode;
        }
        moveApplicationAcrossQueues(cliParser.getOptionValue(MOVE_TO_QUEUE_CMD),
                cliParser.getOptionValue(QUEUE_CMD));
    } else if (cliParser.hasOption(FAIL_CMD)) {
        if (!args[0].equalsIgnoreCase(APPLICATION_ATTEMPT)) {
            printUsage(title, opts);
            return exitCode;
        }
        failApplicationAttempt(cliParser.getOptionValue(FAIL_CMD));
    } else if (cliParser.hasOption(HELP_CMD)) {
        printUsage(title, opts);
        return 0;
    } else if (cliParser.hasOption(UPDATE_PRIORITY)) {
        if (!cliParser.hasOption(APP_ID)) {
            printUsage(title, opts);
            return exitCode;
        }
        updateApplicationPriority(cliParser.getOptionValue(APP_ID), cliParser.getOptionValue(UPDATE_PRIORITY));
    } else if (cliParser.hasOption(SIGNAL_CMD)) {
        if (args.length < 3 || args.length > 4) {
            printUsage(title, opts);
            return exitCode;
        }
        final String[] signalArgs = cliParser.getOptionValues(SIGNAL_CMD);
        final String containerId = signalArgs[0];
        SignalContainerCommand command = SignalContainerCommand.OUTPUT_THREAD_DUMP;
        if (signalArgs.length == 2) {
            command = SignalContainerCommand.valueOf(signalArgs[1]);
        }
        signalToContainer(containerId, command);
    } else {
        syserr.println("Invalid Command Usage : ");
        printUsage(title, opts);
    }
    return 0;
}

From source file:org.apache.hadoop.yarn.client.cli.LogsCLI.java

@Override
public int run(String[] args) throws Exception {

    Options opts = new Options();
    opts.addOption(HELP_CMD, false, "Displays help for all commands.");
    Option appIdOpt = new Option(APPLICATION_ID_OPTION, true, "ApplicationId (required)");
    appIdOpt.setRequired(true);//from   ww w .  j a  v  a 2  s .c om
    opts.addOption(appIdOpt);
    opts.addOption(CONTAINER_ID_OPTION, true,
            "ContainerId. " + "By default, it will only print syslog if the application is runing."
                    + " Work with -logFiles to get other logs.");
    opts.addOption(NODE_ADDRESS_OPTION, true, "NodeAddress in the format " + "nodename:port");
    opts.addOption(APP_OWNER_OPTION, true, "AppOwner (assumed to be current user if not specified)");
    Option amOption = new Option(AM_CONTAINER_OPTION, true,
            "Prints the AM Container logs for this application. "
                    + "Specify comma-separated value to get logs for related AM Container. "
                    + "For example, If we specify -am 1,2, we will get the logs for "
                    + "the first AM Container as well as the second AM Container. "
                    + "To get logs for all AM Containers, use -am ALL. "
                    + "To get logs for the latest AM Container, use -am -1. "
                    + "By default, it will only print out syslog. Work with -logFiles " + "to get other logs");
    amOption.setValueSeparator(',');
    amOption.setArgs(Option.UNLIMITED_VALUES);
    amOption.setArgName("AM Containers");
    opts.addOption(amOption);
    Option logFileOpt = new Option(CONTAINER_LOG_FILES, true,
            "Work with -am/-containerId and specify comma-separated value "
                    + "to get specified container log files. Use \"ALL\" to fetch all the "
                    + "log files for the container.");
    logFileOpt.setValueSeparator(',');
    logFileOpt.setArgs(Option.UNLIMITED_VALUES);
    logFileOpt.setArgName("Log File Name");
    opts.addOption(logFileOpt);

    opts.getOption(APPLICATION_ID_OPTION).setArgName("Application ID");
    opts.getOption(CONTAINER_ID_OPTION).setArgName("Container ID");
    opts.getOption(NODE_ADDRESS_OPTION).setArgName("Node Address");
    opts.getOption(APP_OWNER_OPTION).setArgName("Application Owner");
    opts.getOption(AM_CONTAINER_OPTION).setArgName("AM Containers");

    Options printOpts = new Options();
    printOpts.addOption(opts.getOption(HELP_CMD));
    printOpts.addOption(opts.getOption(CONTAINER_ID_OPTION));
    printOpts.addOption(opts.getOption(NODE_ADDRESS_OPTION));
    printOpts.addOption(opts.getOption(APP_OWNER_OPTION));
    printOpts.addOption(opts.getOption(AM_CONTAINER_OPTION));
    printOpts.addOption(opts.getOption(CONTAINER_LOG_FILES));

    if (args.length < 1) {
        printHelpMessage(printOpts);
        return -1;
    }
    if (args[0].equals("-help")) {
        printHelpMessage(printOpts);
        return 0;
    }
    CommandLineParser parser = new GnuParser();
    String appIdStr = null;
    String containerIdStr = null;
    String nodeAddress = null;
    String appOwner = null;
    boolean getAMContainerLogs = false;
    String[] logFiles = null;
    List<String> amContainersList = new ArrayList<String>();
    try {
        CommandLine commandLine = parser.parse(opts, args, true);
        appIdStr = commandLine.getOptionValue(APPLICATION_ID_OPTION);
        containerIdStr = commandLine.getOptionValue(CONTAINER_ID_OPTION);
        nodeAddress = commandLine.getOptionValue(NODE_ADDRESS_OPTION);
        appOwner = commandLine.getOptionValue(APP_OWNER_OPTION);
        getAMContainerLogs = commandLine.hasOption(AM_CONTAINER_OPTION);
        if (getAMContainerLogs) {
            String[] amContainers = commandLine.getOptionValues(AM_CONTAINER_OPTION);
            for (String am : amContainers) {
                boolean errorInput = false;
                if (!am.trim().equalsIgnoreCase("ALL")) {
                    try {
                        int id = Integer.parseInt(am.trim());
                        if (id != -1 && id <= 0) {
                            errorInput = true;
                        }
                    } catch (NumberFormatException ex) {
                        errorInput = true;
                    }
                    if (errorInput) {
                        System.err.println("Invalid input for option -am. Valid inputs are 'ALL', -1 "
                                + "and any other integer which is larger than 0.");
                        printHelpMessage(printOpts);
                        return -1;
                    }
                    amContainersList.add(am.trim());
                } else {
                    amContainersList.add("ALL");
                    break;
                }
            }
        }
        if (commandLine.hasOption(CONTAINER_LOG_FILES)) {
            logFiles = commandLine.getOptionValues(CONTAINER_LOG_FILES);
        }
    } catch (ParseException e) {
        System.err.println("options parsing failed: " + e.getMessage());
        printHelpMessage(printOpts);
        return -1;
    }

    if (appIdStr == null) {
        System.err.println("ApplicationId cannot be null!");
        printHelpMessage(printOpts);
        return -1;
    }

    ApplicationId appId = null;
    try {
        appId = ApplicationId.fromString(appIdStr);
    } catch (Exception e) {
        System.err.println("Invalid ApplicationId specified");
        return -1;
    }

    LogCLIHelpers logCliHelper = new LogCLIHelpers();
    logCliHelper.setConf(getConf());

    if (appOwner == null || appOwner.isEmpty()) {
        appOwner = UserGroupInformation.getCurrentUser().getShortUserName();
    }

    YarnApplicationState appState = YarnApplicationState.NEW;
    try {
        appState = getApplicationState(appId);
        if (appState == YarnApplicationState.NEW || appState == YarnApplicationState.NEW_SAVING
                || appState == YarnApplicationState.SUBMITTED) {
            System.out.println("Logs are not avaiable right now.");
            return -1;
        }
    } catch (IOException | YarnException e) {
        System.err.println(
                "Unable to get ApplicationState." + " Attempting to fetch logs directly from the filesystem.");
    }

    // To get am logs
    if (getAMContainerLogs) {
        // if we do not specify the value for CONTAINER_LOG_FILES option,
        // we will only output syslog
        if (logFiles == null || logFiles.length == 0) {
            logFiles = new String[] { "syslog" };
        }
        // If the application is running, we will call the RM WebService
        // to get the AppAttempts which includes the nodeHttpAddress
        // and containerId for all the AM Containers.
        // After that, we will call NodeManager webService to get the
        // related logs
        if (appState == YarnApplicationState.ACCEPTED || appState == YarnApplicationState.RUNNING) {
            return printAMContainerLogs(getConf(), appIdStr, amContainersList, logFiles, logCliHelper, appOwner,
                    false);
        } else {
            // If the application is in the final state, we will call RM webservice
            // to get all AppAttempts information first. If we get nothing,
            // we will try to call AHS webservice to get related AppAttempts
            // which includes nodeAddress for the AM Containers.
            // After that, we will use nodeAddress and containerId
            // to get logs from HDFS directly.
            if (getConf().getBoolean(YarnConfiguration.APPLICATION_HISTORY_ENABLED,
                    YarnConfiguration.DEFAULT_APPLICATION_HISTORY_ENABLED)) {
                return printAMContainerLogs(getConf(), appIdStr, amContainersList, logFiles, logCliHelper,
                        appOwner, true);
            } else {
                System.out.println("Can not get AMContainers logs for the application:" + appId);
                System.out.println("This application:" + appId + " is finished."
                        + " Please enable the application history service. Or Using "
                        + "yarn logs -applicationId <appId> -containerId <containerId> "
                        + "--nodeAddress <nodeHttpAddress> to get the container logs");
                return -1;
            }
        }
    }

    int resultCode = 0;
    if (containerIdStr != null) {
        // if we provide the node address and the application is in the final
        // state, we could directly get logs from HDFS.
        if (nodeAddress != null && isApplicationFinished(appState)) {
            // if user specified "ALL" as the logFiles param, pass null
            // to logCliHelper so that it fetches all the logs
            List<String> logs;
            if (logFiles == null) {
                logs = null;
            } else if (fetchAllLogFiles(logFiles)) {
                logs = null;
            } else {
                logs = Arrays.asList(logFiles);
            }
            return logCliHelper.dumpAContainersLogsForALogType(appIdStr, containerIdStr, nodeAddress, appOwner,
                    logs);
        }
        try {
            // If the nodeAddress is not provided, we will try to get
            // the ContainerReport. In the containerReport, we could get
            // nodeAddress and nodeHttpAddress
            ContainerReport report = getContainerReport(containerIdStr);
            String nodeHttpAddress = report.getNodeHttpAddress()
                    .replaceFirst(WebAppUtils.getHttpSchemePrefix(getConf()), "");
            String nodeId = report.getAssignedNode().toString();
            // If the application is not in the final state,
            // we will provide the NodeHttpAddress and get the container logs
            // by calling NodeManager webservice.
            if (!isApplicationFinished(appState)) {
                if (logFiles == null || logFiles.length == 0) {
                    logFiles = new String[] { "syslog" };
                }
                printContainerLogsFromRunningApplication(getConf(), appIdStr, containerIdStr, nodeHttpAddress,
                        nodeId, logFiles, logCliHelper, appOwner);
            } else {
                String[] requestedLogFiles = logFiles;
                if (fetchAllLogFiles(logFiles)) {
                    requestedLogFiles = null;
                }
                // If the application is in the final state, we will directly
                // get the container logs from HDFS.
                printContainerLogsForFinishedApplication(appIdStr, containerIdStr, nodeId, requestedLogFiles,
                        logCliHelper, appOwner);
            }
            return resultCode;
        } catch (IOException | YarnException ex) {
            System.err.println(
                    "Unable to get logs for this container:" + containerIdStr + "for the application:" + appId);
            if (!getConf().getBoolean(YarnConfiguration.APPLICATION_HISTORY_ENABLED,
                    YarnConfiguration.DEFAULT_APPLICATION_HISTORY_ENABLED)) {
                System.out.println("Please enable the application history service. Or ");
            }
            System.out.println("Using " + "yarn logs -applicationId <appId> -containerId <containerId> "
                    + "--nodeAddress <nodeHttpAddress> to get the container logs");
            return -1;
        }
    } else {
        if (nodeAddress == null) {
            resultCode = logCliHelper.dumpAllContainersLogs(appId, appOwner, System.out);
        } else {
            System.out.println("Should at least provide ContainerId!");
            printHelpMessage(printOpts);
            resultCode = -1;
        }
    }
    return resultCode;
}

From source file:org.apache.hadoop.yarn.client.cli.NodeCLI.java

@Override
public int run(String[] args) throws Exception {

    Options opts = new Options();
    opts.addOption(HELP_CMD, false, "Displays help for all commands.");
    opts.addOption(STATUS_CMD, true, "Prints the status report of the node.");
    opts.addOption(LIST_CMD, false,/*w  ww.jav  a2 s  . c om*/
            "List all running nodes. " + "Supports optional use of -states to filter nodes "
                    + "based on node state, all -all to list all nodes, "
                    + "-showDetails to display more details about each node.");
    Option nodeStateOpt = new Option(NODE_STATE_CMD, true,
            "Works with -list to filter nodes based on input comma-separated " + "list of node states. "
                    + getAllValidNodeStates());
    nodeStateOpt.setValueSeparator(',');
    nodeStateOpt.setArgs(Option.UNLIMITED_VALUES);
    nodeStateOpt.setArgName("States");
    opts.addOption(nodeStateOpt);
    Option allOpt = new Option(NODE_ALL, false, "Works with -list to list all nodes.");
    opts.addOption(allOpt);
    Option showDetailsOpt = new Option(NODE_SHOW_DETAILS, false,
            "Works with -list to show more details about each node.");
    opts.addOption(showDetailsOpt);
    opts.getOption(STATUS_CMD).setArgName("NodeId");

    if (args != null && args.length > 0) {
        for (int i = args.length - 1; i >= 0; i--) {
            if (args[i].equalsIgnoreCase("-" + NODE_ALL)) {
                args[i] = "-" + NODE_ALL;
            }
        }
    }

    int exitCode = -1;
    CommandLine cliParser = null;
    try {
        cliParser = new GnuParser().parse(opts, args);
    } catch (MissingArgumentException ex) {
        sysout.println("Missing argument for options");
        printUsage(opts);
        return exitCode;
    }

    if (cliParser.hasOption("status")) {
        if (args.length != 2) {
            printUsage(opts);
            return exitCode;
        }
        printNodeStatus(cliParser.getOptionValue("status"));
    } else if (cliParser.hasOption("list")) {
        Set<NodeState> nodeStates = new HashSet<NodeState>();
        if (cliParser.hasOption(NODE_ALL)) {
            for (NodeState state : NodeState.values()) {
                nodeStates.add(state);
            }
        } else if (cliParser.hasOption(NODE_STATE_CMD)) {
            String[] types = cliParser.getOptionValues(NODE_STATE_CMD);
            if (types != null) {
                for (String type : types) {
                    if (!type.trim().isEmpty()) {
                        try {
                            nodeStates.add(NodeState
                                    .valueOf(org.apache.hadoop.util.StringUtils.toUpperCase(type.trim())));
                        } catch (IllegalArgumentException ex) {
                            sysout.println("The node state " + type + " is invalid.");
                            sysout.println(getAllValidNodeStates());
                            return exitCode;
                        }
                    }
                }
            }
        } else {
            nodeStates.add(NodeState.RUNNING);
        }

        // List all node details with more information.
        if (cliParser.hasOption(NODE_SHOW_DETAILS)) {
            listDetailedClusterNodes(nodeStates);
        } else {
            listClusterNodes(nodeStates);
        }
    } else if (cliParser.hasOption(HELP_CMD)) {
        printUsage(opts);
        return 0;
    } else {
        syserr.println("Invalid Command Usage : ");
        printUsage(opts);
    }
    return 0;
}

From source file:org.apache.hadoop.yarn.client.cli.QueueCLI.java

@Override
public int run(String[] args) throws Exception {
    Options opts = new Options();

    opts.addOption(STATUS_CMD, true, "List queue information about given queue.");
    opts.addOption(HELP_CMD, false, "Displays help for all commands.");
    opts.getOption(STATUS_CMD).setArgName("Queue Name");

    CommandLine cliParser = null;/*from   w w  w . j  av  a 2 s  . c om*/
    try {
        cliParser = new GnuParser().parse(opts, args);
    } catch (MissingArgumentException ex) {
        sysout.println("Missing argument for options");
        printUsage(opts);
        return -1;
    }

    if (cliParser.hasOption(STATUS_CMD)) {
        if (args.length != 2) {
            printUsage(opts);
            return -1;
        }
        return listQueue(cliParser.getOptionValue(STATUS_CMD));
    } else if (cliParser.hasOption(HELP_CMD)) {
        printUsage(opts);
        return 0;
    } else {
        syserr.println("Invalid Command Usage : ");
        printUsage(opts);
        return -1;
    }
}

From source file:org.apache.openmeetings.cli.OmHelpFormatter.java

private LinkedHashMap<String, List<OmOption>> getOptions(Options opts, int leftPad) {
    final String longOptSeparator = " ";
    final String lpad = createPadding(leftPad);
    final String lpadParam = createPadding(leftPad + 2);
    List<OmOption> reqOptions = getReqOptions(opts);
    LinkedHashMap<String, List<OmOption>> map = new LinkedHashMap<String, List<OmOption>>(reqOptions.size());
    map.put(GENERAL_OPTION_GROUP, new ArrayList<OmOption>());
    for (OmOption o : reqOptions) {
        map.put(o.getOpt(), new ArrayList<OmOption>());
    }//from ww w. ja  va2  s . c  om
    for (Option _o : opts.getOptions()) {
        OmOption o = (OmOption) _o;
        //TODO need better check (required option should go first and should not be duplicated
        boolean skipOption = map.containsKey(o.getOpt());
        boolean mainOption = skipOption || o.getGroup() == null;

        // 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
        StringBuilder optBuf = new StringBuilder();
        if (o.getOpt() == null) {
            optBuf.append(mainOption ? lpad : lpadParam).append("   ").append(getLongOptPrefix())
                    .append(o.getLongOpt());
        } else {
            optBuf.append(mainOption ? lpad : lpadParam).append(getOptPrefix()).append(o.getOpt());

            if (o.hasLongOpt()) {
                optBuf.append(',').append(getLongOptPrefix()).append(o.getLongOpt());
            }
        }

        if (o.hasArg()) {
            String argName = o.getArgName();
            if (argName != null && argName.length() == 0) {
                // if the option has a blank argname
                optBuf.append(' ');
            } else {
                optBuf.append(o.hasLongOpt() ? longOptSeparator : " ");
                optBuf.append("<").append(argName != null ? o.getArgName() : getArgName()).append(">");
            }
        }

        o.setHelpPrefix(optBuf);
        maxPrefixLength = Math.max(optBuf.length(), maxPrefixLength);

        if (skipOption) {
            //TODO need better check (required option should go first and should not be duplicated
            continue;
        }
        String grp = o.getGroup();
        grp = grp == null ? GENERAL_OPTION_GROUP : grp;
        String[] grps = grp.split(",");
        for (String g : grps) {
            map.get(g).add(o);
        }
    }
    for (Map.Entry<String, List<OmOption>> me : map.entrySet()) {
        final String key = me.getKey();
        List<OmOption> options = me.getValue();
        Collections.sort(options, new Comparator<OmOption>() {
            @Override
            public int compare(OmOption o1, OmOption o2) {
                boolean o1opt = !o1.isOptional(key);
                boolean o2opt = !o2.isOptional(key);
                return (o1opt && o2opt || !o1opt && !o2opt) ? (o1.getOpt() == null ? 1 : -1) : (o1opt ? -1 : 1);
            }

        });
        if (opts.hasOption(key)) {
            options.add(0, (OmOption) opts.getOption(key));
        }
    }
    return map;
}

From source file:org.apache.stratos.cli.commands.AddApplicationSignupCommand.java

@Override
public int execute(StratosCommandContext context, String[] args, Option[] alreadyParsedOpts)
        throws CommandException {
    if (log.isDebugEnabled()) {
        log.debug("Executing command: ", getName());
    }//  w w w.  j  av a  2  s.  c  o m

    if ((args == null) || (args.length <= 0)) {
        context.getStratosApplication().printUsage(getName());
        return CliConstants.COMMAND_FAILED;
    }
    String applicationId = args[0];

    try {
        CommandLineParser parser = new GnuParser();
        CommandLine commandLine = parser.parse(options, args);
        //merge newly discovered options with previously discovered ones.
        Options opts = mergeOptionArrays(alreadyParsedOpts, commandLine.getOptions());
        if (opts.hasOption(CliConstants.RESOURCE_PATH)) {
            String resourcePath = opts.getOption(CliConstants.RESOURCE_PATH).getValue();
            if (resourcePath == null) {
                context.getStratosApplication().printUsage(getName());
                return CliConstants.COMMAND_FAILED;
            }
            String resourceFileContent = CliUtils.readResource(resourcePath);
            RestCommandLineService.getInstance().addApplicationSignup(resourceFileContent, applicationId);
            return CliConstants.COMMAND_SUCCESSFULL;
        } else {
            context.getStratosApplication().printUsage(getName());
            return CliConstants.COMMAND_FAILED;
        }
    } catch (ParseException e) {
        log.error("Error parsing arguments", e);
        System.out.println(e.getMessage());
        return CliConstants.COMMAND_FAILED;
    } catch (IOException e) {
        System.out.println("Invalid resource path");
        return CliConstants.COMMAND_FAILED;
    } catch (Exception e) {
        String message = "Unknown error occurred: " + e.getMessage();
        System.out.println(message);
        log.error(message, e);
        return CliConstants.COMMAND_FAILED;
    }
}

From source file:org.apache.stratos.cli.commands.AddAutoscalingPolicyCommand.java

public int execute(StratosCommandContext context, String[] args, Option[] alreadyParsedOpts)
        throws CommandException {
    if (log.isDebugEnabled()) {
        log.debug("Executing {} command...", getName());
    }/*w ww  .  ja  v a2 s .c  o  m*/

    if (args != null && args.length > 0) {
        String resourcePath = null;
        String resourceFileContent = null;

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

        try {
            commandLine = parser.parse(options, args);
            //merge newly discovered options with previously discovered ones.
            Options opts = mergeOptionArrays(alreadyParsedOpts, commandLine.getOptions());

            if (log.isDebugEnabled()) {
                log.debug("Autoscaling policy deployment");
            }

            if (opts.hasOption(CliConstants.RESOURCE_PATH)) {
                if (log.isTraceEnabled()) {
                    log.trace("Resource path option is passed");
                }
                resourcePath = opts.getOption(CliConstants.RESOURCE_PATH).getValue();
                resourceFileContent = CliUtils.readResource(resourcePath);
            }

            if (resourcePath == null) {
                context.getStratosApplication().printUsage(getName());
                return CliConstants.COMMAND_FAILED;
            }

            RestCommandLineService.getInstance().addAutoscalingPolicy(resourceFileContent);
            return CliConstants.COMMAND_SUCCESSFULL;

        } catch (ParseException e) {
            log.error("Error parsing arguments", e);
            System.out.println(e.getMessage());
            return CliConstants.COMMAND_FAILED;
        } catch (IOException e) {
            System.out.println("Invalid resource path");
            return CliConstants.COMMAND_FAILED;
        }
    } else {
        context.getStratosApplication().printUsage(getName());
        return CliConstants.COMMAND_FAILED;
    }
}

From source file:org.apache.stratos.cli.commands.AddCartridgeCommand.java

public int execute(StratosCommandContext context, String[] args, Option[] alreadyParsedOpts)
        throws CommandException {
    if (log.isDebugEnabled()) {
        log.debug("Executing {} command...", getName());
    }/* w  ww .  j a  va2 s.c  o  m*/

    if (args != null && args.length > 0) {
        String resourcePath = null;
        String resourceFileContent = null;

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

        try {
            commandLine = parser.parse(options, args);
            //merge newly discovered options with previously discovered ones.
            Options opts = mergeOptionArrays(alreadyParsedOpts, commandLine.getOptions());

            if (log.isDebugEnabled()) {
                log.debug("Cartridge deployment");
            }

            if (opts.hasOption(CliConstants.RESOURCE_PATH)) {
                if (log.isTraceEnabled()) {
                    log.trace("Resource path option is passed");
                }
                resourcePath = opts.getOption(CliConstants.RESOURCE_PATH).getValue();
                resourceFileContent = CliUtils.readResource(resourcePath);
            }

            if (resourcePath == null) {
                context.getStratosApplication().printUsage(getName());
                return CliConstants.COMMAND_FAILED;
            }

            RestCommandLineService.getInstance().addCartridge(resourceFileContent);
            return CliConstants.COMMAND_SUCCESSFULL;

        } catch (ParseException e) {
            log.error("Error parsing arguments", e);
            System.out.println(e.getMessage());
            return CliConstants.COMMAND_FAILED;
        } catch (IOException e) {
            System.out.println("Invalid resource path");
            return CliConstants.COMMAND_FAILED;
        }

    } else {
        context.getStratosApplication().printUsage(getName());
        return CliConstants.COMMAND_FAILED;
    }
}