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

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

Introduction

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

Prototype

public Option[] getOptions() 

Source Link

Document

Returns an array of the processed Option s.

Usage

From source file: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());
    }//  ww w .  j  a  va  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());
    }//from  w  w w .  jav a 2s .  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 w  w.  j a v a 2 s.  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 a  va 2  s  . c  o 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.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
 *//*w  w  w  .j a  v  a2 s .co  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.hadoop.ha.HAAdmin.java

private int failover(CommandLine cmd) throws IOException, ServiceFailedException {
    boolean forceFence = cmd.hasOption(FORCEFENCE);
    boolean forceActive = cmd.hasOption(FORCEACTIVE);

    int numOpts = cmd.getOptions() == null ? 0 : cmd.getOptions().length;
    final String[] args = cmd.getArgs();

    if (numOpts > 3 || args.length != 2) {
        errOut.println("failover: incorrect arguments");
        printUsage(errOut, "-failover");
        return -1;
    }// w  w w  .j a v  a  2 s.  c  om

    HAServiceTarget fromNode = resolveTarget(args[0]);
    HAServiceTarget toNode = resolveTarget(args[1]);

    // Check that auto-failover is consistently configured for both nodes.
    Preconditions.checkState(fromNode.isAutoFailoverEnabled() == toNode.isAutoFailoverEnabled(),
            "Inconsistent auto-failover configs between %s and %s!", fromNode, toNode);

    if (fromNode.isAutoFailoverEnabled()) {
        if (forceFence || forceActive) {
            // -forceActive doesn't make sense with auto-HA, since, if the node
            // is not healthy, then its ZKFC will immediately quit the election
            // again the next time a health check runs.
            //
            // -forceFence doesn't seem to have any real use cases with auto-HA
            // so it isn't implemented.
            errOut.println(FORCEFENCE + " and " + FORCEACTIVE + " flags not "
                    + "supported with auto-failover enabled.");
            return -1;
        }
        try {
            return gracefulFailoverThroughZKFCs(toNode);
        } catch (UnsupportedOperationException e) {
            errOut.println("Failover command is not supported with " + "auto-failover enabled: "
                    + e.getLocalizedMessage());
            return -1;
        }
    }

    FailoverController fc = new FailoverController(getConf(), requestSource);

    try {
        fc.failover(fromNode, toNode, forceFence, forceActive);
        out.println("Failover from " + args[0] + " to " + args[1] + " successful");
    } catch (FailoverFailedException ffe) {
        errOut.println("Failover failed: " + ffe.getLocalizedMessage());
        return -1;
    }
    return 0;
}

From source file:org.apache.helix.task.TaskDriver.java

/** Attempts to parse options for given command, printing usage under failure */
private static CommandLine parseOptions(String[] args, Options options, String cmdStr) {
    CommandLineParser cliParser = new GnuParser();
    CommandLine cmd = null;

    try {/*from  w ww  . j  av a  2 s . c  o  m*/
        cmd = cliParser.parse(options, args);
    } catch (ParseException pe) {
        LOG.error("CommandLineClient: failed to parse command-line options: " + pe.toString());
        printUsage(options, cmdStr);
        System.exit(1);
    }
    boolean ret = checkOptionArgsNumber(cmd.getOptions());
    if (!ret) {
        printUsage(options, cmdStr);
        System.exit(1);
    }

    return cmd;
}

From source file:org.apache.helix.tools.JmxDumper.java

public static int processCommandLineArgs(String[] cliArgs) throws Exception {
    CommandLineParser cliParser = new GnuParser();
    Options cliOptions = constructCommandLineOptions();
    CommandLine cmd = null;

    try {//from   w  w w. j a  v a2s .  c o m
        cmd = cliParser.parse(cliOptions, cliArgs);
    } catch (ParseException pe) {
        System.err.println("CommandLineClient: failed to parse command-line options: " + pe.toString());
        printUsage(cliOptions);
        System.exit(1);
    }
    boolean ret = checkOptionArgsNumber(cmd.getOptions());
    if (ret == false) {
        printUsage(cliOptions);
        System.exit(1);
    }

    String portStr = cmd.getOptionValue(jmxUrl);
    // int portVal = Integer.parseInt(portStr);

    String periodStr = cmd.getOptionValue(period);
    int periodVal = Integer.parseInt(periodStr);

    String domainStr = cmd.getOptionValue(domain);
    String classNameStr = cmd.getOptionValue(className);
    String patternStr = cmd.getOptionValue(pattern);
    String fieldsStr = cmd.getOptionValue(fields);
    String operationsStr = cmd.getOptionValue(operations);
    String resultFile = cmd.getOptionValue(outputFile);
    String sampleCountStr = cmd.getOptionValue(sampleCount, "-1");
    int sampleCount = Integer.parseInt(sampleCountStr);

    List<String> fields = Arrays.asList(fieldsStr.split(","));
    List<String> operations = Arrays.asList(operationsStr.split(","));

    JmxDumper dumper = null;
    try {
        dumper = new JmxDumper(portStr, domainStr, classNameStr, patternStr, periodVal, fields, operations,
                resultFile, sampleCount);
        synchronized (dumper) {
            dumper.wait();
        }
    } finally {
        if (dumper != null) {
            dumper.flushFile();
        }
    }
    return 0;
}

From source file:org.apache.heron.healthmgr.HealthManager.java

public static void main(String[] args) throws Exception {
    CommandLineParser parser = new DefaultParser();
    Options slaManagerCliOptions = constructCliOptions();

    // parse the help options first.
    Options helpOptions = constructHelpOptions();
    CommandLine cmd = parser.parse(helpOptions, args, true);
    if (cmd.hasOption("h")) {
        usage(slaManagerCliOptions);/*from   w  w  w.  j  a  v  a 2  s. c o m*/
        return;
    }

    try {
        cmd = parser.parse(slaManagerCliOptions, args);
    } catch (ParseException e) {
        usage(slaManagerCliOptions);
        throw new RuntimeException("Error parsing command line options: ", e);
    }

    HealthManagerMode mode = HealthManagerMode.cluster;
    if (hasOption(cmd, CliArgs.MODE)) {
        mode = HealthManagerMode.valueOf(getOptionValue(cmd, CliArgs.MODE));
    }

    Config config;
    switch (mode) {
    case cluster:
        config = Config.toClusterMode(Config.newBuilder().putAll(ConfigLoader.loadClusterConfig())
                .putAll(commandLineConfigs(cmd)).build());
        break;

    case local:
        if (!hasOption(cmd, CliArgs.HERON_HOME) || !hasOption(cmd, CliArgs.CONFIG_PATH)) {
            throw new IllegalArgumentException("Missing heron_home or config_path argument");
        }
        String heronHome = getOptionValue(cmd, CliArgs.HERON_HOME);
        String configPath = getOptionValue(cmd, CliArgs.CONFIG_PATH);
        config = Config.toLocalMode(
                Config.newBuilder().putAll(ConfigLoader.loadConfig(heronHome, configPath, null, null))
                        .putAll(commandLineConfigs(cmd)).build());
        break;

    default:
        throw new IllegalArgumentException("Invalid mode: " + getOptionValue(cmd, CliArgs.MODE));
    }

    setupLogging(cmd, config);

    LOG.fine(Arrays.toString(cmd.getOptions()));

    // Add the SystemConfig into SingletonRegistry
    SystemConfig systemConfig = SystemConfig.newBuilder(true).putAll(Context.systemFile(config), true)
            .putAll(Context.overrideFile(config), true).build();
    SingletonRegistry.INSTANCE.registerSingleton(SystemConfig.HERON_SYSTEM_CONFIG, systemConfig);

    LOG.info("Static Heron config loaded successfully ");
    LOG.fine(config.toString());

    // load the default config value and override with any command line values
    String metricSourceClassName = config.getStringValue(PolicyConfigKey.METRIC_SOURCE_TYPE.key());
    metricSourceClassName = getOptionValue(cmd, CliArgs.METRIC_SOURCE_TYPE, metricSourceClassName);

    String metricsUrl = config.getStringValue(PolicyConfigKey.METRIC_SOURCE_URL.key());
    metricsUrl = getOptionValue(cmd, CliArgs.METRIC_SOURCE_URL, metricsUrl);

    // metrics reporting thread
    HealthManagerMetrics publishingMetrics = new HealthManagerMetrics(
            Integer.valueOf(getOptionValue(cmd, CliArgs.METRICSMGR_PORT)));

    AbstractModule module = buildBaseModule(metricsUrl, metricSourceClassName, publishingMetrics);
    HealthManager healthManager = new HealthManager(config, module);

    LOG.info("Initializing health manager");
    healthManager.initialize();

    LOG.info("Starting Health Manager");
    PoliciesExecutor policyExecutor = new PoliciesExecutor(healthManager.healthPolicies);
    ScheduledFuture<?> future = policyExecutor.start();

    LOG.info("Starting Health Manager metric posting thread");
    new Thread(publishingMetrics).start();

    try {
        future.get();
    } finally {
        policyExecutor.destroy();
        publishingMetrics.close();
    }
}

From source file:org.apache.ivory.cli.IvoryCLI.java

private void instanceCommand(CommandLine commandLine) throws IvoryCLIException, IOException {
    String ivoryUrl = validateIvoryUrl(commandLine);
    IvoryClient client = new IvoryClient(ivoryUrl);

    Set<String> optionsList = new HashSet<String>();
    for (Option option : commandLine.getOptions()) {
        optionsList.add(option.getOpt());
    }/*from   w  w  w.java 2  s.  co  m*/

    String result = null;
    String type = commandLine.getOptionValue(ENTITY_TYPE_OPT);
    String entity = commandLine.getOptionValue(ENTITY_NAME_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);

    validateInstanceCommands(optionsList, entity, type, start, end, filePath);

    if (optionsList.contains(RUNNING_OPT)) {
        result = client.getRunningInstances(type, entity);
    } else if (optionsList.contains(STATUS_OPT)) {
        result = client.getStatusOfInstances(type, entity, start, end, runid);
    } else if (optionsList.contains(KILL_OPT)) {
        result = client.killInstances(type, entity, start, end);
    } else if (optionsList.contains(SUSPEND_OPT)) {
        result = client.suspendInstances(type, entity, start, end);
    } else if (optionsList.contains(RESUME_OPT)) {
        result = client.resumeInstances(type, entity, start, end);
    } else if (optionsList.contains(RERUN_OPT)) {
        result = client.rerunInstances(type, entity, start, end, filePath);
    } else {
        throw new IvoryCLIException("Invalid command");
    }
    OUT_STREAM.println(result);

}