Example usage for org.apache.commons.cli ParseException toString

List of usage examples for org.apache.commons.cli ParseException toString

Introduction

In this page you can find the example usage for org.apache.commons.cli ParseException toString.

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:io.mindmaps.graql.GraqlShell.java

public static void runShell(String[] args, String version, GraqlClient client) {

    Options options = new Options();
    options.addOption("n", "name", true, "name of the graph");
    options.addOption("e", "execute", true, "query to execute");
    options.addOption("f", "file", true, "graql file path to execute");
    options.addOption("u", "uri", true, "uri to connect to engine");
    options.addOption("h", "help", false, "print usage message");
    options.addOption("v", "version", false, "print version");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd;//  w ww.j a  v  a  2 s .  c o  m

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        return;
    }

    String query = cmd.getOptionValue("e");
    String filePath = cmd.getOptionValue("f");

    // Print usage message if requested or if invalid arguments provided
    if (cmd.hasOption("h") || !cmd.getArgList().isEmpty()) {
        HelpFormatter helpFormatter = new HelpFormatter();
        PrintWriter printWriter = new PrintWriter(System.out);
        int width = helpFormatter.getWidth();
        int leftPadding = helpFormatter.getLeftPadding();
        int descPadding = helpFormatter.getDescPadding();
        helpFormatter.printHelp(printWriter, width, "graql.sh", null, options, leftPadding, descPadding, null);
        printWriter.flush();
        return;
    }

    if (cmd.hasOption("v")) {
        System.out.println(version);
        return;
    }

    String namespace = cmd.getOptionValue("n", DEFAULT_NAMESPACE);
    String uriString = cmd.getOptionValue("u", DEFAULT_URI);

    try (GraqlShell shell = new GraqlShell(namespace)) {
        client.connect(shell, new URI("ws://" + uriString + REMOTE_SHELL_URI));

        if (filePath != null) {
            query = loadQuery(filePath);
        }

        if (query != null) {
            shell.executeQuery(query);
            shell.commit();
        } else {
            shell.executeRepl();
        }
    } catch (IOException | InterruptedException | ExecutionException | URISyntaxException e) {
        System.err.println(e.toString());
    } finally {
        client.close();
    }
}

From source file:biomine.bmvis2.Vis.java

private void createGUI(String title) {
    //        try {
    //            System.setProperty("com.apple.macosx.AntiAliasedTextOn", "false");
    //            System.setProperty("com.apple.macosx.AntiAliasedGraphicsOn",
    //                    "false");
    //        } catch (Throwable t) {
    //            // Ignore property exceptions
    //        }/*  w w w .j  a va  2s .com*/
    //        try {
    //            System.setProperty("sun.java2d.opengl", "true");
    //        } catch (Throwable t) {
    //            // Ignore property exceptions
    //        }

    this.setLayout(new GridLayout());
    this.tabs = new TabbedPaneHiddenBar();
    this.getContentPane().add(tabs);
    this.tabs.setVisible(true);

    tabs.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent arg0) {
            GraphTab tab = (GraphTab) tabs.getSelectedComponent();
            if (tab == null) {
                Logging.info("ui", "No graphs open, creating the default menu.");
                Vis.this.setJMenuBar(getDefaultMenu());
            } else {
                Vis.this.setJMenuBar(tab.getMenuBar());
            }
        }
    });

    if (appletContext == null) {
        Options opts = new Options();
        CommandLineParser parser = new PosixParser();
        CommandLine cmd = null;

        opts.addOption("h", "help", false, "Show help.");
        opts.addOption("s", "simple", false, "Show simple UI without side panes");
        opts.addOption("logcategories", true, "Logging categories delimited by spaces, all for all");
        opts.addOption("loglevel", true, "Logging level: 0 for debug, 1 for info, 2 for warning, 3 for error");
        opts.addOption("d", "debug", false, "Shorthand for logcategories all, loglevel -1");

        try {
            cmd = parser.parse(opts, args);
        } catch (ParseException e) {
            System.err.println(e.getLocalizedMessage());
            System.err.println();
            Vis.printCmdLineHelp(opts);
            System.exit(1);
        }

        if (cmd.hasOption("-h") || cmd.getArgList().size() == 0) {
            Vis.printCmdLineHelp(opts);
            System.exit(0);
        }

        if (cmd.hasOption("-s"))
            this.properties.put("simple", "true");

        if (cmd.hasOption("-d")) {
            Logging.init(new ArrayList<String>(Arrays.asList("all")), -1);
        } else {
            ArrayList<String> logCategories = null;
            Integer logLevel = null;
            if (cmd.hasOption("logcategories"))
                logCategories = new ArrayList<String>(
                        Arrays.asList(cmd.getOptionValue("logcategories").split(",")));
            if (cmd.hasOption("loglevel"))
                logLevel = Integer.parseInt(cmd.getOptionValue("loglevel"));

            if (logCategories != null || logLevel != null)
                Logging.init(logCategories, logLevel);
        }

        VisFrame frame = new VisFrame("BMVIS II");
        this.visFrame = frame;
        frame.add(this);

        boolean noneOpened = true;
        for (Object arg : cmd.getArgList()) {
            if (this.openTab((String) arg) != null)
                noneOpened = false;
        }

        if (noneOpened && cmd.getArgList().size() > 0) {
            String message = "No files could be opened! Exiting.";
            Logging.error("graph_reading", message);
            JOptionPane.showMessageDialog(this, message);
            System.exit(1);
        }

        this.visFrame.setVisible(true);

    } else {
        // Applet operation goes here...
        this.setVisible(true);

        try {
            if (getParameter("graph") != null) {
                String graphFile = getParameter("graph");

                URL u = new URL(getCodeBase(), graphFile);
                InputStream graphStream = u.openConnection().getInputStream();
                BMGraph bm = BMGraphUtils.readBMGraph(graphStream);
                graphStream.close();
                this.openTab(new FileGraphSource(bm));
            }
            if (getParameter("json") != null) {
                String jsonFile = getParameter("json");
                URL u = new URL(getCodeBase(), jsonFile);
                InputStream jsonStream = u.openConnection().getInputStream();

                openJSONTab(StreamToString.convertStreamToString(jsonStream), jsonFile);
            }
        } catch (IOException e) {
            Logging.error("graph_reading", e.toString());
            JOptionPane.showMessageDialog(this, e.getMessage());
        }
    }
}

From source file:org.apache.hadoop.registry.cli.RegistryCli.java

@SuppressWarnings("unchecked")
public int mknode(String[] args) {
    Options mknodeOption = new Options();
    CommandLineParser parser = new GnuParser();
    try {//from   w w  w . ja  v a  2  s .  c o  m
        CommandLine line = parser.parse(mknodeOption, args);

        List<String> argsList = line.getArgList();
        if (argsList.size() != 2) {
            return usageError("mknode requires exactly one path argument", MKNODE_USAGE);
        }
        if (!validatePath(argsList.get(1))) {
            return -1;
        }

        try {
            registry.mknode(args[1], false);
            return 0;
        } catch (Exception e) {
            syserr.println(analyzeException("mknode", e, argsList));
        }
        return -1;
    } catch (ParseException exp) {
        return usageError("Invalid syntax " + exp.toString(), MKNODE_USAGE);
    }
}

From source file:org.apache.hadoop.registry.cli.RegistryCli.java

@SuppressWarnings("unchecked")
public int rm(String[] args) {
    Option recursive = OptionBuilder.withArgName("recursive").withDescription("delete recursively").create("r");

    Options rmOption = new Options();
    rmOption.addOption(recursive);//from  www .  ja v a  2  s . c  om

    boolean recursiveOpt = false;

    CommandLineParser parser = new GnuParser();
    try {
        CommandLine line = parser.parse(rmOption, args);

        List<String> argsList = line.getArgList();
        if (argsList.size() != 2) {
            return usageError("RM requires exactly one path argument", RM_USAGE);
        }
        if (!validatePath(argsList.get(1))) {
            return -1;
        }

        try {
            if (line.hasOption("r")) {
                recursiveOpt = true;
            }

            registry.delete(argsList.get(1), recursiveOpt);
            return 0;
        } catch (Exception e) {
            syserr.println(analyzeException("rm", e, argsList));
        }
        return -1;
    } catch (ParseException exp) {
        return usageError("Invalid syntax " + exp.toString(), RM_USAGE);
    }
}

From source file:org.apache.helix.mock.participant.DummyProcess.java

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

    try {/*from  w  ww.  j  ava2s.c o m*/
        return cliParser.parse(cliOptions, cliArgs);
    } catch (ParseException pe) {
        System.err.println("CommandLineClient: failed to parse command-line options: " + pe.toString());
        printUsage(cliOptions);
        System.exit(1);
    }
    return null;
}

From source file:org.apache.helix.rest.server.HelixRestMain.java

private static void processCommandLineArgs(String[] cliArgs) throws Exception {
    CommandLineParser cliParser = new GnuParser();
    Options cliOptions = constructCommandLineOptions();
    CommandLine cmd = null;/*from w  w  w . ja va  2s . c  om*/

    try {
        cmd = cliParser.parse(cliOptions, cliArgs);
    } catch (ParseException pe) {
        LOG.error("RestAdminApplication: failed to parse command-line options: " + pe.toString());
        printUsage(cliOptions);
        System.exit(1);
    }
    int port = DEFAULT_PORT;
    String zkAddr;
    List<HelixRestNamespace> namespaces = new ArrayList<>();
    if (cmd.hasOption(HELP)) {
        printUsage(cliOptions);
        return;
    } else {
        if (cmd.hasOption(PORT)) {
            port = Integer.parseInt(cmd.getOptionValue(PORT));
        }
        zkAddr = String.valueOf(cmd.getOptionValue(ZKSERVERADDRESS));
        namespaces.add(new HelixRestNamespace(zkAddr));
        if (cmd.hasOption(NAMESPACE_MANIFEST_FILE)) {
            constructNamespaceFromConfigFile(String.valueOf(cmd.getOptionValue(NAMESPACE_MANIFEST_FILE)),
                    namespaces);
        }
    }

    final HelixRestServer restServer = new HelixRestServer(namespaces, port, URI_PREFIX,
            Arrays.<AuditLogger>asList(new FileBasedAuditLogger()));

    try {
        restServer.start();
        restServer.join();
    } catch (HelixException ex) {
        LOG.error("Failed to start Helix rest server, " + ex);
    } finally {
        restServer.shutdown();
    }
}

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;/*from w w w  .  j  a  va2s  . co m*/

    try {
        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.ClusterSetup.java

public static int processCommandLineArgs(String[] cliArgs) throws Exception {
    CommandLineParser cliParser = new GnuParser();
    Options cliOptions = constructCommandLineOptions();
    CommandLine cmd = null;// ww w .  j a v  a  2 s  . c  o m

    try {
        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 = RebalanceMode.SEMI_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]);
        }

        int maxPartitionsPerNodeVal = -1;
        if (cmd.hasOption(maxPartitionsPerNode)) {
            maxPartitionsPerNodeVal = Integer.parseInt(cmd.getOptionValues(maxPartitionsPerNode)[0]);
        }
        setupTool.addResourceToCluster(clusterName, resourceName, partitions, stateModelRef, modeValue,
                bucketSizeVal, maxPartitionsPerNodeVal);
        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]);
        String keyPrefixVal = "";
        String instanceGroupTagVal = "";
        if (cmd.hasOption(resourceKeyPrefix)) {
            keyPrefixVal = cmd.getOptionValue(resourceKeyPrefix);
        }
        if (cmd.hasOption(instanceGroupTag)) {
            instanceGroupTagVal = cmd.getOptionValue(instanceGroupTag);
        }
        setupTool.rebalanceCluster(clusterName, resourceName, replicas, keyPrefixVal, instanceGroupTagVal);
        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, resource 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(enableResource)) {
        String clusterName = cmd.getOptionValues(enableResource)[0];
        String resourceName = cmd.getOptionValues(enableResource)[1];
        boolean enabled = Boolean.parseBoolean(cmd.getOptionValues(enableResource)[2].toLowerCase());
        setupTool.getClusterManagementTool().enableResource(clusterName, resourceName, enabled);
    } 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(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);
    }
    // set/get/remove config options
    else if (cmd.hasOption(setConfig)) {
        String values[] = cmd.getOptionValues(setConfig);
        ConfigScopeProperty type = ConfigScopeProperty.valueOf(values[0]);
        String scopeArgs = values[1];
        String keyValueMap = values[2];
        setupTool.setConfig(type, scopeArgs, keyValueMap);
    } else if (cmd.hasOption(getConfig)) {
        String values[] = cmd.getOptionValues(getConfig);
        ConfigScopeProperty type = ConfigScopeProperty.valueOf(values[0]);
        String scopeArgs = values[1];
        String keys = values[2];
        setupTool.getConfig(type, scopeArgs, keys);
    } else if (cmd.hasOption(removeConfig)) {
        String values[] = cmd.getOptionValues(removeConfig);
        ConfigScopeProperty type = ConfigScopeProperty.valueOf(values[0]);
        String scoepArgs = values[1];
        String keys = values[2];
        setupTool.removeConfig(type, scoepArgs, keys);
    }
    // set/get/remove constraint options
    else if (cmd.hasOption(setConstraint)) {
        String values[] = cmd.getOptionValues(setConstraint);
        String clusterName = values[0];
        String constraintType = values[1];
        String constraintId = values[2];
        String constraintAttributesMap = values[3];
        setupTool.setConstraint(clusterName, constraintType, constraintId, constraintAttributesMap);
    } else if (cmd.hasOption(getConstraints)) {
        String values[] = cmd.getOptionValues(getConstraints);
        String clusterName = values[0];
        String constraintType = values[1];
        setupTool.getConstraints(clusterName, constraintType);
    } else if (cmd.hasOption(removeConstraint)) {
        String values[] = cmd.getOptionValues(removeConstraint);
        String clusterName = values[0];
        String constraintType = values[1];
        String constraintId = values[2];
        setupTool.removeConstraint(clusterName, constraintType, constraintId);
    } else if (cmd.hasOption(addInstanceTag)) {
        String clusterName = cmd.getOptionValues(addInstanceTag)[0];
        String instanceName = cmd.getOptionValues(addInstanceTag)[1];
        String tag = cmd.getOptionValues(addInstanceTag)[2];
        setupTool.getClusterManagementTool().addInstanceTag(clusterName, instanceName, tag);
    } else if (cmd.hasOption(removeInstanceTag)) {
        String clusterName = cmd.getOptionValues(removeInstanceTag)[0];
        String instanceName = cmd.getOptionValues(removeInstanceTag)[1];
        String tag = cmd.getOptionValues(removeInstanceTag)[2];
        setupTool.getClusterManagementTool().removeInstanceTag(clusterName, instanceName, tag);
    }
    // help option
    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:org.apache.helix.tools.IntegrationTestUtil.java

static void processCommandLineArgs(String[] cliArgs) {
    CommandLineParser cliParser = new GnuParser();
    Options cliOptions = constructCommandLineOptions();
    CommandLine cmd = null;//from   ww w  .  ja  v a2s  .  c  o m
    try {
        cmd = cliParser.parse(cliOptions, cliArgs);
    } catch (ParseException pe) {
        System.err.println("failed to parse command-line args: " + Arrays.asList(cliArgs) + ", exception: "
                + pe.toString());
        printUsage(cliOptions);
        System.exit(1);
    }

    String zkServer = cmd.getOptionValue(zkSvr);

    ZkClient zkclient = new ZkClient(zkServer, ZkClient.DEFAULT_SESSION_TIMEOUT,
            ZkClient.DEFAULT_CONNECTION_TIMEOUT, new ZNRecordSerializer());
    IntegrationTestUtil util = new IntegrationTestUtil(zkclient);

    if (cmd != null) {
        if (cmd.hasOption(verifyExternalView)) {
            String[] args = cmd.getOptionValues(verifyExternalView);
            util.verifyExternalView(args);
        } else if (cmd.hasOption(verifyLiveNodes)) {
            String[] args = cmd.getOptionValues(verifyLiveNodes);
            util.verifyLiveNodes(args);
        } else if (cmd.hasOption(readZNode)) {
            String path = cmd.getOptionValue(readZNode);
            util.readZNode(path);
        } else if (cmd.hasOption(readLeader)) {
            String clusterName = cmd.getOptionValue(readLeader);
            PropertyKey.Builder keyBuilder = new PropertyKey.Builder(clusterName);
            util.readZNode(keyBuilder.controllerLeader().getPath());
        } else {
            printUsage(cliOptions);
        }
    }
}

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;/*  w w w  .  ja  va  2 s.co  m*/

    try {
        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;
}