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

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

Introduction

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

Prototype

public String[] getOptionValues(char opt) 

Source Link

Document

Retrieves the array of values, if any, of an option.

Usage

From source file:be_uclouvain_ingi2145_lab05.GiraphJobRunner.java

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

    GiraphConfiguration gconf = new GiraphConfiguration(conf);
    //gconf.setVertexClass(SimpleShortestPathsComputation.class);
    /*gconf.setVertexInputFormatClass(
        SimpleShortestPathsVertexInputFormat.class);
    gconf.setVertexOutputFormatClass(//from  w w w .  j  av a  2  s  .co m
        SimpleShortestPathsVertexOutputFormat.class);
    */
    CommandLine cmd = ConfigurationUtils.parseArgs(gconf, strings);
    if (null == cmd) {
        return 0;
    }

    //GiraphYarnClient job = new GiraphYarnClient(gconf,gconf.getClass().getName());
    GiraphJob job = new GiraphJob(gconf, getClass().getName());
    job.getInternalJob().setJarByClass(getClass());
    if (cmd.hasOption("vof") || cmd.hasOption("eof")) {
        if (cmd.hasOption("op")) {
            Path outputPath = new Path(cmd.getOptionValue("op"));

            FileSystem fs = FileSystem.get(outputPath.toUri(), conf);
            /*Check if output path (args[1])exist or not*/
            if (fs.exists(outputPath)) {
                /*If exist delete the output path*/
                fs.delete(outputPath, true);
            }

            FileOutputFormat.setOutputPath(job.getInternalJob(), outputPath);
        }
    }
    /*
    if (cmd.hasOption("vif") || cmd.hasOption("eif")) {
      if (cmd.hasOption("vip")) {
          FileInputFormat.addInputPath(job.getInternalJob(), new Path(cmd.getOptionValue("op")));
      }
    }*/
    //If there is a custom option specified
    if (cmd.hasOption("ca")) {
        String[] args = cmd.getOptionValues("ca");
        LOG.fatal("" + Arrays.toString(args));

        gconf.set("ca", args[0].split("=")[1]);
        LOG.fatal("" + gconf.get("ca"));
        gconf.setWorkerConfiguration(Integer.parseInt(cmd.getOptionValue("w")),
                Integer.parseInt(cmd.getOptionValue("w")), 100.0f);
    }
    /*
    if (cmd.hasOption("cf")) {
      DistributedCache.addCacheFile(new URI(cmd.getOptionValue("cf")),
          job.getConfiguration());
    }
    */
    return job.run(true) ? 0 : -1;
}

From source file:com.emc.ecs.sync.source.FilesystemSource.java

@Override
public void parseCustomOptions(CommandLine line) {
    if (!sourceUri.startsWith(FILE_PREFIX))
        throw new ConfigurationException("source must start with " + FILE_PREFIX);

    try {/* w w  w. ja v a  2  s .c  o  m*/
        rootFile = new File(new URI(sourceUri));
    } catch (URISyntaxException e) {
        throw new ConfigurationException("Invalid URI", e);
    }

    useAbsolutePath = line.hasOption(ABSOLUTE_PATH_OPT);

    if (line.hasOption(DELETE_OLDER_OPT)) {
        deleteOlderThan = Long.parseLong(line.getOptionValue(DELETE_OLDER_OPT));
    }
    if (line.hasOption(DELETE_CHECK_OPT)) {
        deleteCheckScript = new File(line.getOptionValue(DELETE_CHECK_OPT));
    }

    followLinks = line.hasOption(FOLLOW_LINKS_OPT);

    if (line.hasOption(EXCLUDE_FILENAMES_OPT)) {
        log.warn(EXCLUDE_FILENAMES_OPT + " is deprected; please use " + EXCLUDE_PATHS_OPT);
        excludedFilenames = Arrays.asList(line.getOptionValues(EXCLUDE_FILENAMES_OPT));
    }

    if (line.hasOption(EXCLUDE_PATHS_OPT)) {
        excludedPaths = Arrays.asList(line.getOptionValues(EXCLUDE_PATHS_OPT));
    }
}

From source file:com.comcast.oscar.cli.CommandRun.java

/**
 * Checks all the commands from the user. Order is IMPORTANT. Do not rearrange without full understanding.
 * @param args//from  w w w.  j  a v a2 s  .co  m
 */
public void run(String[] args) {
    BasicParser parser = new BasicParser();
    Options options = new Options();
    BuildOptions.run(options);

    try {
        CommandLine line = parser.parse(options, args);
        HelpFormatter hf = new HelpFormatter();
        hf.setWidth(180);
        hf.setLeftPadding(5);
        hf.setDescPadding(5);

        if (line.hasOption("h")) {
            hf.printHelp(Constants.OSCAR_CLI_USAGE, options);
        }

        if (line.hasOption("version")) {
            System.out.println(Constants.APACHE_20_LICENCE_DISCLAIMER);
            System.out.println(Constants.OSCAR_VERSION);
        }

        if (line.hasOption("s")) {
            comSpecification.setValues(line.getOptionValues("s"));

            if (comSpecification.getConfigurationFileType() == -1) {
                System.err.println(Specification.ERROR);
                System.exit(1);
            }

            if (comSpecification.getTlvDisassemble() == null) {
                System.err.println(Specification.ERROR);
                System.exit(1);
            }
        }

        if (line.hasOption("i")) {
            comInput = new Input(line.getOptionValues("i"));

            if (!comInput.hasInput()) {
                System.err.println(Input.ERROR);
                System.exit(1);
            }
        }

        if (line.hasOption("o")) {
            comOutput = new Output(line.getOptionValues("o"));
        }

        if (line.hasOption("k")) {
            comKey.setKey(line.getOptionValues("k"));
        }

        if (line.hasOption("mbb")) {
            comMergeBulk = new MergeBulk(line.getOptionValues("mbb"));

            if (comMergeBulk.hasInputDir()) {
                comMergeBulk.mergeFiles(comSpecification.getConfigurationFileType(), comKey.getKey());
            } else {
                System.err.println(MergeBulk.ERROR);
                System.exit(1);
            }
        }

        if (line.hasOption("f")) {
            comFirmware = new Firmware(line.getOptionValues("f"));
        }

        if (line.hasOption("T")) {
            comTFTPServer = new TFTPServer(line.getOptionValues("T"));

            if (!comTFTPServer.hasAddress()) {
                System.err.println(TFTPServer.ERROR);
                System.exit(1);
            }
        }

        if (line.hasOption("m")) {
            comMaxCPE = new MaxCPE(line.getOptionValues("m"));
        }

        if (line.hasOption("df")) {
            comDownstreamFrequency = new DownstreamFrequency(line.getOptionValues("df"));
        }

        if (line.hasOption("cvc")) {
            comCVC = new CVC(line.getOptionValues("cvc"));

            if (!comCVC.hasCVC()) {
                System.err.println(CVC.ERROR);
                System.exit(1);
            }
        }

        if (line.hasOption("t")) {
            comTLV = new TLV(line.getOptionValues("t"));
        }

        if (line.hasOption("dm")) {
            comDigitmapInsert = new DigitmapInsert(line.getOptionValues("dm"));

            if (!comDigitmapInsert.hasDigitmap()) {
                System.err.println(DigitmapInsert.ERROR);
                System.exit(1);
            }
        }

        if (line.hasOption("O")) {
            comOID = new OID(line.getOptionValues("O"));

            if (!comOID.hasOID()) {
                System.err.println(OID.ERROR);
                System.exit(1);
            }
        }

        if (line.hasOption("d")) {
            comDecompile = new Decompile(line.getOptionValues("d"));
            decompile();
        }

        if (line.hasOption("c")) {
            compile();
        }

        if (line.hasOption("b")) {
            String[] optionValues = line.getOptionValues("b");

            if (optionValues.length >= 3) {
                bulkBuild(optionValues[0]);
                bulkBuildCommand(new File(optionValues[1]), new File(optionValues[2]));
            } else if (optionValues.length >= 2) {
                bulkBuild(optionValues[0]);
                bulkBuildCommand(new File(optionValues[1]));
            } else {
                System.err.println(Constants.ERR_MIS_PAR);
                hf.printHelp(Constants.OSCAR_CLI_USAGE, options);
            }
        }

        if (line.hasOption("ftd")) {
            comFullTLVDisplay.printFullTLVDisplay(comSpecification.getConfigurationFileType());
        }

        if (line.hasOption("x")) {
            comHexDisplay = new HexDisplay(line.getOptionValues("x"));

            if (comInput.hasInput()) {
                if (comInput.isBinary()) {
                    comHexDisplay.printHexDisplayFromBinary(comInput.getInput());
                } else {
                    comHexDisplay.printHexDisplayFromText(comInput.getInput(),
                            comSpecification.getConfigurationFileType());
                }
            } else {
                System.err.println(Input.ERROR);
                System.exit(1);
            }
        }

        if (line.hasOption("j")) {
            if (comInput.hasInput()) {
                if (comInput.isBinary()) {
                    comJSONDisplay.printJSONDisplayFromBinary(comInput.getInput(),
                            comSpecification.getTlvDisassemble(), comSpecification.getConfigurationFileType());
                } else {
                    comJSONDisplay.printJSONDisplayFromText(comInput.getInput(),
                            comSpecification.getTlvDisassemble());
                }
            } else {
                System.err.println(Input.ERROR);
                System.exit(1);
            }
        }

        if (line.hasOption("ddm")) {
            if (comInput.hasInput()) {
                if (comInput.isBinary()) {
                    comDigitmapDisplay.printDigitmapDisplayFromBinary(comInput.getInput());
                } else {
                    comDigitmapDisplay.printDigitmapDisplayFromText(comInput.getInput());
                }
            }
        }

        if (line.hasOption("j2t")) {
            comJSONtoTLV = new JSONtoTLV(line.getOptionValues("j2t"));

            if (comJSONtoTLV.fileExists()) {
                comJSONtoTLV.printTLV();
            } else {
                System.err.println(JSONtoTLV.ERROR);
            }
        }

        if (line.hasOption("t2j")) {
            comTLVtoJSON = new TLVtoJSON(line.getOptionValues("t2j"));
            comTLVtoJSON.printJSON(comSpecification.getTlvDisassemble());
        }

        if (line.hasOption("td")) {
            comTLVDescription = new TLVDescription(line.getOptionValues("td"));
            comTLVDescription.printTLVDescription(comSpecification.getConfigurationFileType());
        }

        if (line.hasOption("tr")) {
            comTranslate = new Translate(line.getOptionValues("tr"));
            comTranslate.translate();
        }
    } catch (ParseException exp) {
        System.err.println("Parsing failed. Reason: " + exp.getMessage());
    }
}

From source file:com.linkedin.helix.tools.ClusterSetup.java

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

    try {/*w  ww  .ja  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);
    }

    ClusterSetup setupTool = new ClusterSetup(cmd.getOptionValue(zkServerAddress));

    if (cmd.hasOption(addCluster)) {
        String clusterName = cmd.getOptionValue(addCluster);
        setupTool.addCluster(clusterName, false);
        return 0;
    }

    if (cmd.hasOption(activateCluster)) {
        String clusterName = cmd.getOptionValues(activateCluster)[0];
        String grandCluster = cmd.getOptionValues(activateCluster)[1];
        boolean enable = Boolean.parseBoolean(cmd.getOptionValues(activateCluster)[2]);
        setupTool.activateCluster(clusterName, grandCluster, enable);
        return 0;
    }

    if (cmd.hasOption(dropCluster)) {
        String clusterName = cmd.getOptionValue(dropCluster);
        setupTool.deleteCluster(clusterName);
        return 0;
    }

    if (cmd.hasOption(addInstance)) {
        String clusterName = cmd.getOptionValues(addInstance)[0];
        String InstanceAddressInfo = cmd.getOptionValues(addInstance)[1];
        String[] InstanceAddresses = InstanceAddressInfo.split(";");
        setupTool.addInstancesToCluster(clusterName, InstanceAddresses);
        return 0;
    }

    if (cmd.hasOption(addResource)) {
        String clusterName = cmd.getOptionValues(addResource)[0];
        String resourceName = cmd.getOptionValues(addResource)[1];
        int partitions = Integer.parseInt(cmd.getOptionValues(addResource)[2]);
        String stateModelRef = cmd.getOptionValues(addResource)[3];
        String modeValue = IdealStateModeProperty.AUTO.toString();
        if (cmd.hasOption(mode)) {
            modeValue = cmd.getOptionValues(mode)[0];
        }

        int bucketSizeVal = 0;
        if (cmd.hasOption(bucketSize)) {
            bucketSizeVal = Integer.parseInt(cmd.getOptionValues(bucketSize)[0]);
        }

        setupTool.addResourceToCluster(clusterName, resourceName, partitions, stateModelRef, modeValue,
                bucketSizeVal);
        return 0;
    }

    if (cmd.hasOption(rebalance)) {
        String clusterName = cmd.getOptionValues(rebalance)[0];
        String resourceName = cmd.getOptionValues(rebalance)[1];
        int replicas = Integer.parseInt(cmd.getOptionValues(rebalance)[2]);
        if (cmd.hasOption(resourceKeyPrefix)) {
            setupTool.rebalanceStorageCluster(clusterName, resourceName, replicas,
                    cmd.getOptionValue(resourceKeyPrefix));
            return 0;
        }
        setupTool.rebalanceStorageCluster(clusterName, resourceName, replicas);
        return 0;
    }

    if (cmd.hasOption(expandCluster)) {
        String clusterName = cmd.getOptionValues(expandCluster)[0];

        setupTool.expandCluster(clusterName);
        return 0;
    }

    if (cmd.hasOption(expandResource)) {
        String clusterName = cmd.getOptionValues(expandResource)[0];
        String resourceName = cmd.getOptionValues(expandResource)[1];
        setupTool.expandResource(clusterName, resourceName);
        return 0;
    }

    if (cmd.hasOption(dropInstance)) {
        String clusterName = cmd.getOptionValues(dropInstance)[0];
        String InstanceAddressInfo = cmd.getOptionValues(dropInstance)[1];
        String[] InstanceAddresses = InstanceAddressInfo.split(";");
        setupTool.dropInstancesFromCluster(clusterName, InstanceAddresses);
        return 0;
    }

    if (cmd.hasOption(listClusters)) {
        List<String> clusters = setupTool.getClusterManagementTool().getClusters();

        System.out.println("Existing clusters:");
        for (String cluster : clusters) {
            System.out.println(cluster);
        }
        return 0;
    }

    if (cmd.hasOption(listResources)) {
        String clusterName = cmd.getOptionValue(listResources);
        List<String> resourceNames = setupTool.getClusterManagementTool().getResourcesInCluster(clusterName);

        System.out.println("Existing resources in cluster " + clusterName + ":");
        for (String resourceName : resourceNames) {
            System.out.println(resourceName);
        }
        return 0;
    } else if (cmd.hasOption(listClusterInfo)) {
        String clusterName = cmd.getOptionValue(listClusterInfo);
        List<String> resourceNames = setupTool.getClusterManagementTool().getResourcesInCluster(clusterName);
        List<String> Instances = setupTool.getClusterManagementTool().getInstancesInCluster(clusterName);

        System.out.println("Existing resources in cluster " + clusterName + ":");
        for (String resourceName : resourceNames) {
            System.out.println(resourceName);
        }

        System.out.println("Instances in cluster " + clusterName + ":");
        for (String InstanceName : Instances) {
            System.out.println(InstanceName);
        }
        return 0;
    } else if (cmd.hasOption(listInstances)) {
        String clusterName = cmd.getOptionValue(listInstances);
        List<String> Instances = setupTool.getClusterManagementTool().getInstancesInCluster(clusterName);

        System.out.println("Instances in cluster " + clusterName + ":");
        for (String InstanceName : Instances) {
            System.out.println(InstanceName);
        }
        return 0;
    } else if (cmd.hasOption(listInstanceInfo)) {
        String clusterName = cmd.getOptionValues(listInstanceInfo)[0];
        String instanceName = cmd.getOptionValues(listInstanceInfo)[1];
        InstanceConfig config = setupTool.getClusterManagementTool().getInstanceConfig(clusterName,
                instanceName);

        String result = new String(new ZNRecordSerializer().serialize(config.getRecord()));
        System.out.println("InstanceConfig: " + result);
        return 0;
    } else if (cmd.hasOption(listResourceInfo)) {
        // print out partition number, db name and replication number
        // Also the ideal states and current states
        String clusterName = cmd.getOptionValues(listResourceInfo)[0];
        String resourceName = cmd.getOptionValues(listResourceInfo)[1];
        IdealState idealState = setupTool.getClusterManagementTool().getResourceIdealState(clusterName,
                resourceName);
        ExternalView externalView = setupTool.getClusterManagementTool().getResourceExternalView(clusterName,
                resourceName);

        if (idealState != null) {
            System.out.println("IdealState for " + resourceName + ":");
            System.out.println(new String(new ZNRecordSerializer().serialize(idealState.getRecord())));
        } else {
            System.out.println("No idealState for " + resourceName);
        }

        System.out.println();

        if (externalView != null) {
            System.out.println("ExternalView for " + resourceName + ":");
            System.out.println(new String(new ZNRecordSerializer().serialize(externalView.getRecord())));
        } else {
            System.out.println("No externalView for " + resourceName);
        }
        return 0;

    } else if (cmd.hasOption(listPartitionInfo)) {
        // print out where the partition master / slaves locates
        String clusterName = cmd.getOptionValues(listPartitionInfo)[0];
        String resourceName = cmd.getOptionValues(listPartitionInfo)[1];
        String partitionName = cmd.getOptionValues(listPartitionInfo)[2];
        IdealState idealState = setupTool.getClusterManagementTool().getResourceIdealState(clusterName,
                resourceName);
        ExternalView externalView = setupTool.getClusterManagementTool().getResourceExternalView(clusterName,
                resourceName);

        if (idealState != null) {
            ZNRecord partInfo = new ZNRecord(resourceName + "/" + partitionName);
            ZNRecord idealStateRec = idealState.getRecord();
            partInfo.setSimpleFields(idealStateRec.getSimpleFields());
            if (idealStateRec.getMapField(partitionName) != null) {
                partInfo.setMapField(partitionName, idealStateRec.getMapField(partitionName));
            }
            if (idealStateRec.getListField(partitionName) != null) {
                partInfo.setListField(partitionName, idealStateRec.getListField(partitionName));
            }
            System.out.println("IdealState for " + resourceName + "/" + partitionName + ":");
            System.out.println(new String(new ZNRecordSerializer().serialize(partInfo)));
        } else {
            System.out.println("No idealState for " + resourceName + "/" + partitionName);
        }

        System.out.println();

        if (externalView != null) {
            ZNRecord partInfo = new ZNRecord(resourceName + "/" + partitionName);
            ZNRecord extViewRec = externalView.getRecord();
            partInfo.setSimpleFields(extViewRec.getSimpleFields());
            if (extViewRec.getMapField(partitionName) != null) {
                partInfo.setMapField(partitionName, extViewRec.getMapField(partitionName));
            }
            if (extViewRec.getListField(partitionName) != null) {
                partInfo.setListField(partitionName, extViewRec.getListField(partitionName));
            }

            System.out.println("ExternalView for " + resourceName + "/" + partitionName + ":");
            System.out.println(new String(new ZNRecordSerializer().serialize(partInfo)));
        } else {
            System.out.println("No externalView for " + resourceName + "/" + partitionName);
        }
        return 0;

    } else if (cmd.hasOption(enableInstance)) {
        String clusterName = cmd.getOptionValues(enableInstance)[0];
        String instanceName = cmd.getOptionValues(enableInstance)[1];
        if (instanceName.contains(":")) {
            instanceName = instanceName.replaceAll(":", "_");
        }
        boolean enabled = Boolean.parseBoolean(cmd.getOptionValues(enableInstance)[2].toLowerCase());

        setupTool.getClusterManagementTool().enableInstance(clusterName, instanceName, enabled);
        return 0;
    } else if (cmd.hasOption(enablePartition)) {
        String[] args = cmd.getOptionValues(enablePartition);

        boolean enabled = Boolean.parseBoolean(args[0].toLowerCase());
        String clusterName = args[1];
        String instanceName = args[2];
        String resourceName = args[3];

        List<String> partitionNames = Arrays.asList(Arrays.copyOfRange(args, 4, args.length));
        setupTool.getClusterManagementTool().enablePartition(enabled, clusterName, instanceName, resourceName,
                partitionNames);
        return 0;
    } else if (cmd.hasOption(resetPartition)) {
        String[] args = cmd.getOptionValues(resetPartition);

        String clusterName = args[0];
        String instanceName = args[1];
        String resourceName = args[2];
        List<String> partitionNames = Arrays.asList(Arrays.copyOfRange(args, 3, args.length));

        setupTool.getClusterManagementTool().resetPartition(clusterName, instanceName, resourceName,
                partitionNames);
        return 0;
    } else if (cmd.hasOption(resetInstance)) {
        String[] args = cmd.getOptionValues(resetInstance);

        String clusterName = args[0];
        List<String> instanceNames = Arrays.asList(Arrays.copyOfRange(args, 1, args.length));

        setupTool.getClusterManagementTool().resetInstance(clusterName, instanceNames);
        return 0;
    } else if (cmd.hasOption(resetResource)) {
        String[] args = cmd.getOptionValues(resetResource);

        String clusterName = args[0];
        List<String> resourceNames = Arrays.asList(Arrays.copyOfRange(args, 1, args.length));

        setupTool.getClusterManagementTool().resetResource(clusterName, resourceNames);
        return 0;
    } else if (cmd.hasOption(enableCluster)) {
        String[] params = cmd.getOptionValues(enableCluster);
        String clusterName = params[0];
        boolean enabled = Boolean.parseBoolean(params[1].toLowerCase());
        setupTool.getClusterManagementTool().enableCluster(clusterName, enabled);

        return 0;
    } else if (cmd.hasOption(listStateModels)) {
        String clusterName = cmd.getOptionValues(listStateModels)[0];

        List<String> stateModels = setupTool.getClusterManagementTool().getStateModelDefs(clusterName);

        System.out.println("Existing state models:");
        for (String stateModel : stateModels) {
            System.out.println(stateModel);
        }
        return 0;
    } else if (cmd.hasOption(listStateModel)) {
        String clusterName = cmd.getOptionValues(listStateModel)[0];
        String stateModel = cmd.getOptionValues(listStateModel)[1];
        StateModelDefinition stateModelDef = setupTool.getClusterManagementTool().getStateModelDef(clusterName,
                stateModel);
        String result = new String(new ZNRecordSerializer().serialize(stateModelDef.getRecord()));
        System.out.println("StateModelDefinition: " + result);
        return 0;
    } else if (cmd.hasOption(addStateModelDef)) {
        String clusterName = cmd.getOptionValues(addStateModelDef)[0];
        String stateModelFile = cmd.getOptionValues(addStateModelDef)[1];

        ZNRecord stateModelRecord = (ZNRecord) (new ZNRecordSerializer().deserialize(readFile(stateModelFile)));
        if (stateModelRecord.getId() == null || stateModelRecord.getId().length() == 0) {
            throw new IllegalArgumentException("ZNRecord for state model definition must have an id");
        }
        setupTool.getClusterManagementTool().addStateModelDef(clusterName, stateModelRecord.getId(),
                new StateModelDefinition(stateModelRecord));
        return 0;
    } else if (cmd.hasOption(addIdealState)) {
        String clusterName = cmd.getOptionValues(addIdealState)[0];
        String resourceName = cmd.getOptionValues(addIdealState)[1];
        String idealStateFile = cmd.getOptionValues(addIdealState)[2];

        setupTool.addIdealState(clusterName, resourceName, idealStateFile);
        return 0;
    } else if (cmd.hasOption(addStat)) {
        String clusterName = cmd.getOptionValues(addStat)[0];
        String statName = cmd.getOptionValues(addStat)[1];

        setupTool.getClusterManagementTool().addStat(clusterName, statName);
    } else if (cmd.hasOption(addAlert)) {
        String clusterName = cmd.getOptionValues(addAlert)[0];
        String alertName = cmd.getOptionValues(addAlert)[1];

        setupTool.getClusterManagementTool().addAlert(clusterName, alertName);
    } else if (cmd.hasOption(dropStat)) {
        String clusterName = cmd.getOptionValues(dropStat)[0];
        String statName = cmd.getOptionValues(dropStat)[1];

        setupTool.getClusterManagementTool().dropStat(clusterName, statName);
    } else if (cmd.hasOption(dropAlert)) {
        String clusterName = cmd.getOptionValues(dropAlert)[0];
        String alertName = cmd.getOptionValues(dropAlert)[1];

        setupTool.getClusterManagementTool().dropAlert(clusterName, alertName);
    } else if (cmd.hasOption(dropResource)) {
        String clusterName = cmd.getOptionValues(dropResource)[0];
        String resourceName = cmd.getOptionValues(dropResource)[1];

        setupTool.getClusterManagementTool().dropResource(clusterName, resourceName);
    } else if (cmd.hasOption(swapInstance)) {
        String clusterName = cmd.getOptionValues(swapInstance)[0];
        String oldInstanceName = cmd.getOptionValues(swapInstance)[1];
        String newInstanceName = cmd.getOptionValues(swapInstance)[2];

        setupTool.swapInstance(clusterName, oldInstanceName, newInstanceName);
    } else if (cmd.hasOption(setConfig)) {
        String scopeStr = cmd.getOptionValues(setConfig)[0];
        String propertiesStr = cmd.getOptionValues(setConfig)[1];
        setupTool.setConfig(scopeStr, propertiesStr);
    } else if (cmd.hasOption(getConfig)) {
        String scopeStr = cmd.getOptionValues(getConfig)[0];
        String keysStr = cmd.getOptionValues(getConfig)[1];
        setupTool.getConfig(scopeStr, keysStr);
    } else if (cmd.hasOption(help)) {
        printUsage(cliOptions);
        return 0;
    } else if (cmd.hasOption(addResourceProperty)) {
        String clusterName = cmd.getOptionValues(addResourceProperty)[0];
        String resourceName = cmd.getOptionValues(addResourceProperty)[1];
        String propertyKey = cmd.getOptionValues(addResourceProperty)[2];
        String propertyVal = cmd.getOptionValues(addResourceProperty)[3];

        setupTool.addResourceProperty(clusterName, resourceName, propertyKey, propertyVal);
        return 0;
    } else if (cmd.hasOption(removeResourceProperty)) {
        String clusterName = cmd.getOptionValues(removeResourceProperty)[0];
        String resourceName = cmd.getOptionValues(removeResourceProperty)[1];
        String propertyKey = cmd.getOptionValues(removeResourceProperty)[2];

        setupTool.removeResourceProperty(clusterName, resourceName, propertyKey);
        return 0;
    }
    return 0;
}

From source file:kieker.tools.traceAnalysis.TraceAnalysisTool.java

/**
 * This method uses the (already parsed and stored) command line arguments to initialize the tool.
 * /*from   w ww  .  ja  v a2  s  .c  om*/
 * @param commandLine
 * 
 * @return true if and only if the tool has been initialized correctly.
 */
private boolean initFromArgs(final CommandLine commandLine) {
    this.inputDirs = commandLine.getOptionValues(Constants.CMD_OPT_NAME_INPUTDIRS);
    this.outputDir = commandLine.getOptionValue(Constants.CMD_OPT_NAME_OUTPUTDIR);
    this.outputFnPrefix = this.cmdl.getOptionValue(Constants.CMD_OPT_NAME_OUTPUTFNPREFIX, "");

    if (this.cmdl.hasOption(Constants.CMD_OPT_NAME_SELECTTRACES)
            && this.cmdl.hasOption(Constants.CMD_OPT_NAME_FILTERTRACES)) {
        LOG.error("Trace Id selection and filtering are mutually exclusive");
        return false;
    }

    if (this.cmdl.hasOption(Constants.CMD_OPT_NAME_SELECTTRACES)
            || this.cmdl.hasOption(Constants.CMD_OPT_NAME_FILTERTRACES)) { // Parse list of trace Ids
        this.invertTraceIdFilter = this.cmdl.hasOption(Constants.CMD_OPT_NAME_FILTERTRACES);
        final String[] traceIdList = this.cmdl
                .getOptionValues(this.invertTraceIdFilter ? Constants.CMD_OPT_NAME_FILTERTRACES // NOCS (Short if operator)
                        : Constants.CMD_OPT_NAME_SELECTTRACES);

        this.selectedTraces = new TreeSet<Long>();

        final int numSelectedTraces = traceIdList.length;
        try {
            for (final String idStr : traceIdList) {
                this.selectedTraces.add(Long.valueOf(idStr));
            }
            LOG.info(numSelectedTraces + " trace" + (numSelectedTraces > 1 ? "s" : "")
                    + (this.invertTraceIdFilter ? " filtered" : " selected")); // NOCS
        } catch (final Exception e) { // NOPMD NOCS (IllegalCatchCheck)
            LOG.error("Failed to parse list of trace IDs: " + Arrays.toString(traceIdList), e);
            return false;
        }
    }

    this.shortLabels = commandLine.hasOption(Constants.CMD_OPT_NAME_SHORTLABELS);
    this.includeSelfLoops = commandLine.hasOption(Constants.CMD_OPT_NAME_INCLUDESELFLOOPS);
    this.ignoreInvalidTraces = commandLine.hasOption(Constants.CMD_OPT_NAME_IGNOREINVALIDTRACES);
    this.ignoreAssumedCalls = commandLine.hasOption(Constants.CMD_OPT_NAME_IGNORE_ASSUMED);
    this.repairEventBasedTraces = commandLine.hasOption(Constants.CMD_OPT_NAME_REPAIR_EVENT_BASED_TRACES);

    final String maxTraceDurationStr = commandLine.getOptionValue(Constants.CMD_OPT_NAME_MAXTRACEDURATION,
            Integer.toString(this.maxTraceDurationMillis));
    try {
        this.maxTraceDurationMillis = Integer.parseInt(maxTraceDurationStr);
    } catch (final NumberFormatException exc) {
        LOG.error("Failed to parse int value of property " + Constants.CMD_OPT_NAME_MAXTRACEDURATION
                + " (must be an integer):" + maxTraceDurationStr, exc);
        return false;
    }

    final DateFormat dateFormat = new SimpleDateFormat(Constants.DATE_FORMAT_PATTERN, Locale.US);
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

    try {
        final String ignoreRecordsBeforeTimestampString = commandLine
                .getOptionValue(Constants.CMD_OPT_NAME_IGNOREEXECUTIONSBEFOREDATE, null);
        final String ignoreRecordsAfterTimestampString = commandLine
                .getOptionValue(Constants.CMD_OPT_NAME_IGNOREEXECUTIONSAFTERDATE, null);
        if (ignoreRecordsBeforeTimestampString != null) {
            long ignoreExecutionsBeforeTimestampTemp;
            try {
                ignoreExecutionsBeforeTimestampTemp = Long.parseLong(ignoreRecordsBeforeTimestampString);
                LOG.info("Ignoring records before " + ignoreExecutionsBeforeTimestampTemp);
            } catch (final NumberFormatException ex) {
                final Date ignoreBeforeDate = dateFormat.parse(ignoreRecordsBeforeTimestampString);
                ignoreExecutionsBeforeTimestampTemp = ignoreBeforeDate.getTime() * (1000 * 1000);
                LOG.info("Ignoring records before " + dateFormat.format(ignoreBeforeDate) + " ("
                        + ignoreExecutionsBeforeTimestampTemp + ")");
            }
            this.ignoreExecutionsBeforeTimestamp = ignoreExecutionsBeforeTimestampTemp;
        }
        if (ignoreRecordsAfterTimestampString != null) {
            long ignoreExecutionsAfterTimestampTemp;
            try {
                ignoreExecutionsAfterTimestampTemp = Long.parseLong(ignoreRecordsAfterTimestampString);
                LOG.info("Ignoring records after " + ignoreExecutionsAfterTimestampTemp);
            } catch (final NumberFormatException ex) {
                final Date ignoreAfterDate = dateFormat.parse(ignoreRecordsAfterTimestampString);
                ignoreExecutionsAfterTimestampTemp = ignoreAfterDate.getTime() * (1000 * 1000);
                LOG.info("Ignoring records after " + dateFormat.format(ignoreAfterDate) + " ("
                        + ignoreExecutionsAfterTimestampTemp + ")");
            }
            this.ignoreExecutionsAfterTimestamp = ignoreExecutionsAfterTimestampTemp;

        }
    } catch (final java.text.ParseException ex) {
        final String errorMsg = "Error parsing date/time string. Please use the following pattern: "
                + DATE_FORMAT_PATTERN_CMD_USAGE_HELP;
        LOG.error(errorMsg, ex);
        return false;
    }
    return true;
}

From source file:br.usp.poli.lta.cereda.macro.util.CLIParser.java

/**
 * Realiza a anlise dos argumentos de linha de comando e retorna um par
 * contendo o texto a ser expandido e o arquivo de sada.
 * @return Um par contendo o texto a ser expandido e o arquivo de sada.
 * @throws IOException Um dos arquivos de entrada no existe.
 *///  w w w  .  j av  a  2  s  .com
public Pair<String, File> parse() throws IOException {

    // opo de entrada
    Option input = OptionBuilder.withLongOpt("input").hasArgs().withArgName("lista de arquivos")
            .withDescription("arquivos de entrada").create("i");

    // opo de sada
    Option output = OptionBuilder.withLongOpt("output").hasArg().withArgName("arquivo")
            .withDescription("arquivo de sada").create("o");

    // opo do editor embutido
    Option ui = OptionBuilder.withLongOpt("editor").withDescription("editor grfico").create("e");

    Options options = new Options();
    options.addOption(input);
    options.addOption(output);
    options.addOption(ui);

    try {

        // parsing dos argumentos
        Parser parser = new BasicParser();
        CommandLine line = parser.parse(options, arguments);

        // verifica se  uma chamada ao editor e retorna em caso positivo
        if (line.hasOption("e")) {
            editor = true;
            return null;
        }

        // se no  uma chamada ao editor de macros,  necessrio verificar
        // se existe um arquivo de entrada
        if (!line.hasOption("i")) {
            throw new ParseException("");
        }

        // existem argumentos restantes, o que representa situao de erro
        if (!line.getArgList().isEmpty()) {
            throw new ParseException("");
        }

        String text = "";
        File out = line.hasOption("output") ? new File(line.getOptionValue("output")) : null;

        if (out == null) {
            logger.info("A sada ser gerada no terminal.");
        } else {
            logger.info("A sada ser gerada no arquivo '{}'.", out.getName());
        }

        // faz a leitura de todos os arquivos e concatena seu contedo em
        // uma varivel
        logger.info("Iniciando a leitura dos arquivos de entrada.");
        String[] files = line.getOptionValues("input");
        for (String file : files) {
            logger.info("Lendo arquivo '{}'.", file);
            text = text.concat(FileUtils.readFileToString(new File(file), Charset.forName("UTF-8")));
        }

        // retorna o par da varivel contendo o texto de todos os arquivos
        // e a referncia ao arquivo de sada (podendo este ser nulo)
        return new Pair<>(text, out);

    } catch (ParseException exception) {

        // imprime a ajuda
        HelpFormatter help = new HelpFormatter();
        help.printHelp("expander ( --editor | --input <lista de arquivos>" + " [ --output <arquivo> ] )",
                options);
    }

    // retorna um valor invlido indicando para no prosseguir com o
    // processo de expanso
    return null;

}

From source file:com.msd.gin.halyard.tools.HalyardParallelExport.java

@Override
public int run(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(newOption("h", null, "Prints this help"));
    options.addOption(newOption("v", null, "Prints version"));
    options.addOption(newOption("s", "source_htable", "Source HBase table with Halyard RDF store"));
    options.addOption(newOption("q", "sparql_query",
            "SPARQL tuple or graph query with use of '" + PARALLEL_SPLIT_FUNCTION_URI + "' function"));
    options.addOption(newOption("t", "target_url",
            "file://<path>/<file_name>{0}.<ext> or hdfs://<path>/<file_name>{0}.<ext> or jdbc:<jdbc_connection>/<table_name>"));
    options.addOption(newOption("p", "property=value", "JDBC connection properties"));
    options.addOption(newOption("l", "driver_classpath", "JDBC driver classpath delimited by ':'"));
    options.addOption(newOption("c", "driver_class", "JDBC driver class name"));
    try {/* ww  w . j  a v a2s.c  o m*/
        CommandLine cmd = new PosixParser().parse(options, args);
        if (args.length == 0 || cmd.hasOption('h')) {
            printHelp(options);
            return -1;
        }
        if (cmd.hasOption('v')) {
            Properties p = new Properties();
            try (InputStream in = HalyardExport.class
                    .getResourceAsStream("/META-INF/maven/com.msd.gin.halyard/hbasesail/pom.properties")) {
                if (in != null)
                    p.load(in);
            }
            System.out.println("Halyard Parallel Export version " + p.getProperty("version", "unknown"));
            return 0;
        }
        if (!cmd.getArgList().isEmpty())
            throw new ExportException("Unknown arguments: " + cmd.getArgList().toString());
        for (char c : "sqt".toCharArray()) {
            if (!cmd.hasOption(c))
                throw new ExportException("Missing mandatory option: " + c);
        }
        for (char c : "sqtlc".toCharArray()) {
            String s[] = cmd.getOptionValues(c);
            if (s != null && s.length > 1)
                throw new ExportException("Multiple values for option: " + c);
        }
        String source = cmd.getOptionValue('s');
        String query = cmd.getOptionValue('q');
        if (!query.contains(PARALLEL_SPLIT_FUNCTION_NAME)) {
            throw new ExportException("Parallel export SPARQL query must contain '"
                    + PARALLEL_SPLIT_FUNCTION_URI + "' function.");
        }
        String target = cmd.getOptionValue('t');
        if ((target.startsWith("file:") || target.startsWith("hdfs:")) && !target.contains("{0}")) {
            throw new ExportException(
                    "Parallel export file target must contain '{0}' counter in the file path or name.");
        }
        getConf().set(SOURCE, source);
        getConf().set(QUERY, query);
        getConf().set(TARGET, target);
        String driver = cmd.getOptionValue('c');
        if (driver != null) {
            getConf().set(JDBC_DRIVER, driver);
        }
        String props[] = cmd.getOptionValues('p');
        if (props != null) {
            for (int i = 0; i < props.length; i++) {
                props[i] = Base64.encodeBase64String(props[i].getBytes(UTF8));
            }
            getConf().setStrings(JDBC_PROPERTIES, props);
        }
        TableMapReduceUtil.addDependencyJars(getConf(), HalyardExport.class, NTriplesUtil.class, Rio.class,
                AbstractRDFHandler.class, RDFFormat.class, RDFParser.class, HTable.class,
                HBaseConfiguration.class, AuthenticationProtos.class, Trace.class);
        HBaseConfiguration.addHbaseResources(getConf());
        Job job = Job.getInstance(getConf(), "HalyardParallelExport " + source + " -> " + target);
        String cp = cmd.getOptionValue('l');
        if (cp != null) {
            String jars[] = cp.split(":");
            for (int i = 0; i < jars.length; i++) {
                File f = new File(jars[i]);
                if (!f.isFile())
                    throw new ExportException("Invalid JDBC driver classpath element: " + jars[i]);
                job.addFileToClassPath(new Path(f.toURI()));
                jars[i] = f.getName();
            }
            job.getConfiguration().setStrings(JDBC_CLASSPATH, jars);
        }
        job.setJarByClass(HalyardParallelExport.class);
        job.setMaxMapAttempts(1);
        job.setMapperClass(ParallelExportMapper.class);
        job.setMapOutputKeyClass(NullWritable.class);
        job.setMapOutputValueClass(Void.class);
        job.setNumReduceTasks(0);
        job.setInputFormatClass(IndexedInputFormat.class);
        job.setOutputFormatClass(NullOutputFormat.class);
        TableMapReduceUtil.initCredentials(job);
        if (job.waitForCompletion(true)) {
            LOG.info("Parallel Export Completed..");
            return 0;
        }
        return -1;
    } catch (RuntimeException exp) {
        System.out.println(exp.getMessage());
        printHelp(options);
        throw exp;
    }

}

From source file:com.mellanox.r4h.MiniDFSClusterManager.java

/**
 * Parses arguments and fills out the member variables.
 * /*from  www .j a v a2  s  .co  m*/
 * @param args
 *            Command-line arguments.
 * @return true on successful parse; false to indicate that the
 *         program should exit.
 */
private boolean parseArguments(String[] args) {
    Options options = makeOptions();
    CommandLine cli;
    try {
        CommandLineParser parser = new GnuParser();
        cli = parser.parse(options, args);
    } catch (ParseException e) {
        LOG.warn("options parsing failed:  " + e.getMessage());
        new HelpFormatter().printHelp("...", options);
        return false;
    }

    if (cli.hasOption("help")) {
        new HelpFormatter().printHelp("...", options);
        return false;
    }

    if (cli.getArgs().length > 0) {
        for (String arg : cli.getArgs()) {
            LOG.error("Unrecognized option: " + arg);
            new HelpFormatter().printHelp("...", options);
            return false;
        }
    }

    // HDFS
    numDataNodes = intArgument(cli, "datanodes", 1);
    nameNodePort = intArgument(cli, "nnport", 0);
    if (cli.hasOption("format")) {
        dfsOpts = StartupOption.FORMAT;
        format = true;
    } else {
        dfsOpts = StartupOption.REGULAR;
        format = false;
    }

    // Runner
    writeDetails = cli.getOptionValue("writeDetails");
    writeConfig = cli.getOptionValue("writeConfig");

    // General
    conf = new HdfsConfiguration();
    updateConfiguration(conf, cli.getOptionValues("D"));

    return true;
}

From source file:com.cloudera.seismic.segy.SegyLoader.java

@Override
public int run(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("cwproot", true, "The path to CWPROOT on this machine");
    options.addOption("input", true, "SEG-Y files to import into Hadoop");
    options.addOption("output", true, "The path of the sequence file to write in Hadoop");

    // Parse the commandline and check for required arguments.
    CommandLine cmdLine = new PosixParser().parse(options, args, false);
    if (!cmdLine.hasOption("input") || !cmdLine.hasOption("output")) {
        System.out.println("Mising required input/output arguments");
        new HelpFormatter().printHelp("SegyLoader", options);
        System.exit(1);/*w w  w .  j a  v  a  2s  . c  om*/
    }

    String cwproot = System.getenv("CWPROOT");
    if (cmdLine.hasOption("cwproot")) {
        cwproot = cmdLine.getOptionValue("cwproot");
    }
    if (cwproot == null || cwproot.isEmpty()) {
        System.out.println("Could not determine CWPROOT value, using /usr/local/su...");
        cwproot = "/usr/local/su";
    }

    // Assume any remaining args are for segyread
    List<String> segyReadArgs = Lists.newArrayList();
    for (String arg : cmdLine.getArgs()) {
        if (arg.contains("=")) {
            segyReadArgs.add(arg);
        }
    }

    // Open the output sequence file.
    Configuration conf = getConf();
    Path outputPath = new Path(cmdLine.getOptionValue("output"));
    SequenceFile.Writer writer = SequenceFile.createWriter(FileSystem.get(conf), conf, outputPath,
            NullWritable.class, BytesWritable.class, CompressionType.BLOCK);
    int rc = 0;
    SequenceFileCallback sfc = new SequenceFileCallback(writer);
    try {
        for (String filename : cmdLine.getOptionValues("input")) {
            System.out.println("Reading input file: " + filename);
            if (filename.endsWith(".su")) {
                SUReader reader = new SUReader(new BufferedInputStream(new FileInputStream(filename)),
                        ImmutableList.<SUCallback>of(sfc));
                reader.run();
                System.out.println("Bytes read: " + reader.getBytesRead());
            } else {
                SUProcess proc = new SUProcess(cwproot, "segyread");
                for (String arg : segyReadArgs) {
                    proc.addArg(arg);
                }
                proc.addArg(String.format("tape=%s", filename));
                proc.addCallback(sfc);
                proc.start();
                rc += proc.closeAndWait();
                System.out.println("Bytes read: " + proc.getTotalBytesRead());
            }
        }
        System.out.println("Bytes written: " + sfc.getBytesWritten());
    } catch (Throwable t) {
        t.printStackTrace();
        rc = 1;
    } finally {
        writer.close();
    }
    return rc;
}

From source file:com.falcon.orca.helpers.CommandHelper.java

public static RunDetails createRunDetails(final CommandLine commandLine)
        throws MissingArgumentException, MalformedURLException {
    RunDetails runDetails = new RunDetails();
    if (commandLine.hasOption("url") && !StringUtils.isBlank(commandLine.getOptionValue("url"))) {
        runDetails.setUrl(commandLine.getOptionValue("url"));
    } else {/*from  w  w  w .  j  a va 2  s.c o m*/
        throw new MissingArgumentException("--url Please provide URL to hit.");
    }
    if (commandLine.hasOption("dataFile") && commandLine.hasOption("template")) {
        runDetails.setBodyDynamic(true);
    }
    if ((commandLine.getOptionValue("url").contains("{{") && commandLine.hasOption("dataFile"))
            || (commandLine.getOptionValue("url").contains("@@") && commandLine.hasOption("dataFile"))) {
        runDetails.setUrlDynamic(true);
    }
    if (commandLine.hasOption("durationMode")) {
        runDetails.setDurationMode(Boolean.valueOf(commandLine.getOptionValue("durationMode")));
    } else {
        runDetails.setDurationMode(false);
    }
    if (runDetails.isDurationMode()) {
        if (commandLine.hasOption("duration")) {
            runDetails.setDuration(Long.valueOf(commandLine.getOptionValue("duration")));
        } else {
            throw new MissingArgumentException(
                    "--duration duration of run in  " + "seconds is required in duration mode");
        }
    } else {
        if (commandLine.hasOption("repeats")) {
            runDetails.setRepeats(Integer.valueOf(commandLine.getOptionValue("repeats")));
        } else {
            throw new MissingArgumentException("--repeats please provide number " + "of repeats to make");
        }
    }
    if (commandLine.hasOption("template")) {
        runDetails.setTemplateFilePath(commandLine.getOptionValue("template"));
    }
    if (commandLine.hasOption("dataFile")) {
        runDetails.setDataFilePath(commandLine.getOptionValue("dataFile"));
    }
    if (commandLine.hasOption("method")) {
        runDetails.setHttpMethod(commandLine.getOptionValue("method"));
    } else {
        runDetails.setHttpMethod("GET");
    }
    if (commandLine.hasOption("header")) {
        runDetails.setHeaders(Arrays.asList(commandLine.getOptionValues("header")));
    }
    if (commandLine.hasOption("cookie")) {
        runDetails.setCookies(Arrays.asList(commandLine.getOptionValues("cookie")));
    }
    if (commandLine.hasOption("data")) {
        runDetails.setData(Joiner.on(' ').join(commandLine.getOptionValues("data")));
    }
    if (commandLine.hasOption("concurrency")) {
        runDetails.setConcurrency(Integer.valueOf(commandLine.getOptionValue("concurrency")));
    } else {
        throw new MissingArgumentException("--concurrency Provide number of " + "users to simulate.");
    }
    return runDetails;
}