Example usage for org.apache.commons.cli GnuParser parse

List of usage examples for org.apache.commons.cli GnuParser parse

Introduction

In this page you can find the example usage for org.apache.commons.cli GnuParser parse.

Prototype

public CommandLine parse(Options options, String[] arguments, Properties properties) throws ParseException 

Source Link

Document

Parse the arguments according to the specified options and properties.

Usage

From source file:com.linkedin.databus2.client.util.DbusClientClusterUtil.java

/**
 * @param args/*from  w  ww  .  j a v a 2 s  .c  om*/
 * DbusClientClusterUtil -s <serverList> -n <namespace> -g <group> -d <dir>     members
 *                                                     leader 
 *                                                    keys 
 *                                                    readSCN <key> 
 *                                                    writeSCN <key> SCN [OFFSET]
 *                                                 remove <key>
 *                                                 readLastTS
 *                                                 writeLastTS TIMESTAMP            
 */
public static void main(String[] args) {
    try {
        GnuParser cmdLineParser = new GnuParser();
        Options options = new Options();
        options.addOption("n", true, "Zookeeper namespace  [/DatabusClient")
                .addOption("g", true, "Groupname [default-group-name] ")
                .addOption("d", true, "Shared directory name [shareddata] ")
                .addOption("s", true, "Zookeeper server list [localhost:2181] ").addOption("h", false, "help");
        CommandLine cmdLineArgs = cmdLineParser.parse(options, args, false);

        if (cmdLineArgs.hasOption('h')) {
            usage();
            System.exit(0);
        }

        String namespace = cmdLineArgs.getOptionValue('n');
        if (namespace == null || namespace.isEmpty()) {
            namespace = "/DatabusClient";
        }
        String groupname = cmdLineArgs.getOptionValue('g');
        if (groupname == null || groupname.isEmpty()) {
            groupname = "default-group-name";
        }
        String sharedDir = cmdLineArgs.getOptionValue('d');
        if (sharedDir == null || sharedDir.isEmpty()) {
            sharedDir = "shareddata";
        }
        String serverList = cmdLineArgs.getOptionValue('s');
        if (serverList == null || serverList.isEmpty()) {
            serverList = "localhost:2181";
        }
        String[] fns = cmdLineArgs.getArgs();
        if (fns.length < 1) {
            usage();
            System.exit(1);
        }
        String function = fns[0];
        String arg1 = (fns.length > 1) ? fns[1] : null;
        String arg2 = (fns.length > 2) ? fns[2] : null;
        try {
            String memberName = "cmd-line-tool";
            DatabusClientNode clusterNode = new DatabusClientNode(new DatabusClientNode.StaticConfig(true,
                    serverList, 2000, 5000, namespace, groupname, memberName, false, sharedDir));
            DatabusClientGroupMember member = clusterNode.getMember(namespace, groupname, memberName);
            if (member == null || !member.joinWithoutLeadershipDuties()) {
                System.err.println("Initialization failed for: " + member);
                System.exit(1);
            }

            if (function.equals("members")) {
                List<String> mlist = member.getMembers();
                for (String m : mlist) {
                    System.out.println(m);
                }

            } else if (function.equals("leader")) {
                String leader = member.getLeader();
                System.out.println(leader);

            } else if (function.equals("keys")) {
                List<String> keyList = member.getSharedKeys();
                if (keyList != null) {
                    for (String m : keyList) {
                        System.out.println(m);
                    }
                }
            } else if (function.equals("readSCN")) {
                List<String> keyList;
                if (arg1 == null) {
                    keyList = member.getSharedKeys();
                } else {
                    keyList = new ArrayList<String>();
                    keyList.add(arg1);
                }
                if (keyList != null) {
                    for (String k : keyList) {
                        if (!k.equals(DatabusClientDSCUpdater.DSCKEY)) {
                            Checkpoint cp = (Checkpoint) member.readSharedData(k);
                            if (cp != null) {
                                System.out.println(k + " " + cp.getWindowScn() + " " + cp.getWindowOffset());
                            } else {
                                System.err.println(k + " null null");
                            }
                        }
                    }
                }

            } else if (function.equals("writeSCN")) {
                if (arg1 != null && arg2 != null) {
                    Checkpoint cp = new Checkpoint();
                    cp.setConsumptionMode(DbusClientMode.ONLINE_CONSUMPTION);
                    cp.setWindowScn(Long.parseLong(arg2));
                    if (fns.length > 3) {
                        cp.setWindowOffset(Integer.parseInt(fns[3]));
                    } else {
                        cp.setWindowOffset(-1);
                    }
                    if (member.writeSharedData(arg1, cp)) {
                        System.out.println(arg1 + " " + cp.getWindowScn() + " " + cp.getWindowOffset());
                    } else {
                        System.err.println("Write failed! " + member + " couldn't write key=" + arg1);
                        System.exit(1);
                    }
                } else {
                    usage();
                    System.exit(1);
                }
            } else if (function.equals("readLastTs")) {
                Long timeInMs = (Long) member.readSharedData(DatabusClientDSCUpdater.DSCKEY);
                if (timeInMs != null) {
                    System.out.println(DatabusClientDSCUpdater.DSCKEY + " " + timeInMs.longValue());
                } else {
                    System.err.println(DatabusClientDSCUpdater.DSCKEY + " null");
                }
            } else if (function.equals("writeLastTs")) {
                if (arg1 != null) {
                    Long ts = Long.parseLong(arg1);
                    if (member.writeSharedData(DatabusClientDSCUpdater.DSCKEY, ts)) {
                        System.out.println(DatabusClientDSCUpdater.DSCKEY + " " + ts);
                    } else {
                        System.err.println("Write failed! " + member + " couldn't write key="
                                + DatabusClientDSCUpdater.DSCKEY);
                        System.exit(1);
                    }

                } else {
                    usage();
                    System.exit(1);
                }
            } else if (function.equals("remove")) {
                if (!member.removeSharedData(arg1)) {
                    System.err.println("Remove failed! " + arg1);
                    System.exit(1);
                }
            } else if (function.equals("create")) {
                if (!member.createPaths()) {
                    System.err.println("Create path failed!");
                    System.exit(1);
                }

            } else {
                usage();
                System.exit(1);
            }
        } catch (InvalidConfigException e) {
            e.printStackTrace();
            usage();
            System.exit(1);
        }

    } catch (ParseException e) {
        usage();
        System.exit(1);
    }

}

From source file:com.linkedin.databus2.client.util.DatabusClusterUtil.java

/**
 * @param args//from www . j  a v a2s.c  om
 *            DbusClusterUtil -z <zookeper-server> -c <cluster-name> [-p
 *            <partitionNumber] partitions readSCN writeSCN SCN remove
 *            clients
 */
public static void main(String[] args) {
    try {
        GnuParser cmdLineParser = new GnuParser();
        Options options = new Options();
        options.addOption("z", true, "zk-server").addOption("c", true, "cluster-name ")
                .addOption("p", true, "partition").addOption("l", false, "legacy")
                .addOption("h", false, "help");
        CommandLine cmdLineArgs = cmdLineParser.parse(options, args, false);

        if (cmdLineArgs.hasOption('h')) {
            usage();
            System.exit(0);
        }

        if (!cmdLineArgs.hasOption('c')) {
            usage();
            System.exit(1);
        }
        String clusterName = cmdLineArgs.getOptionValue('c');
        String zkServer = cmdLineArgs.getOptionValue('z');
        boolean isLegacyChkptLocation = cmdLineArgs.hasOption('l');
        if (zkServer == null || zkServer.isEmpty()) {
            zkServer = "localhost:2181";
        }

        String partitionStr = cmdLineArgs.getOptionValue('p');
        String partition = partitionStr;
        if ((partition != null) && partition.equals("all")) {
            partition = "";
        }

        String[] fns = cmdLineArgs.getArgs();
        if (fns.length < 1) {
            usage();
            System.exit(1);
        }

        DatabusClusterUtilHelper clusterState = new DatabusClusterUtilHelper(zkServer, clusterName);

        String function = fns[0];
        String arg1 = (fns.length > 1) ? fns[1] : null;
        String arg2 = (fns.length > 2) ? fns[2] : null;

        boolean clusterExists = clusterState.existsCluster();
        if (function.equals("create")) {
            if (!clusterExists) {
                if (arg1 == null) {
                    throw new DatabusClusterUtilException("create: please provide the number of partitions");
                }
                int part = Integer.parseInt(arg1);
                clusterState.createCluster(part);
                return;
            } else {
                throw new DatabusClusterUtilException("Cluster " + clusterName + " already exists");
            }
        }
        if (!clusterExists) {
            throw new DatabusClusterUtilException("Cluster doesn't exist! ");
        }

        if (function.equals("delete")) {
            clusterState.removeCluster();
        } else if (function.equals("partitions")) {
            int numParts = clusterState.getNumPartitions();
            System.out.println(numParts);
        } else {
            // all these functions require the notion of partition;
            Set<Integer> partitions = getPartitions(partition, clusterState.getNumPartitions());
            if (function.equals("sources")) {
                DatabusClusterCkptManager ckptMgr = new DatabusClusterCkptManager(zkServer, clusterName, null,
                        partitions, isLegacyChkptLocation);
                Set<String> sources = ckptMgr.getSourcesFromCheckpoint();
                if (sources != null) {
                    for (String s : sources) {
                        System.out.println(s);
                    }
                } else {
                    throw new DatabusClusterUtilException(
                            "sources: Sources not found for cluster " + clusterName);
                }
            } else if (function.equals("clients")) {
                clusterState.getClusterInfo();
                for (Integer p : partitions) {
                    String client = clusterState.getInstanceForPartition(p);
                    System.out.println(p + "\t" + client);
                }
            } else if (function.equals("readSCN")) {
                List<String> sources = getSources(arg1);
                if ((sources != null) && !sources.isEmpty()) {
                    DatabusClusterCkptManager ckptMgr = new DatabusClusterCkptManager(zkServer, clusterName,
                            sources, partitions, isLegacyChkptLocation);
                    Map<Integer, Checkpoint> ckpts = ckptMgr.readCheckpoint();
                    char delim = '\t';
                    for (Map.Entry<Integer, Checkpoint> mkPair : ckpts.entrySet()) {
                        StringBuilder output = new StringBuilder(64);
                        output.append(mkPair.getKey());
                        output.append(delim);
                        Checkpoint cp = mkPair.getValue();
                        if (cp == null) {
                            output.append(-1);
                            output.append(delim);
                            output.append(-1);
                        } else {
                            if (cp.getConsumptionMode() == DbusClientMode.ONLINE_CONSUMPTION) {
                                output.append(cp.getWindowScn());
                                output.append(delim);
                                output.append(cp.getWindowOffset());
                            } else if (cp.getConsumptionMode() == DbusClientMode.BOOTSTRAP_CATCHUP) {
                                output.append(cp.getWindowScn());
                                output.append(delim);
                                output.append(cp.getWindowOffset());
                            } else if (cp.getConsumptionMode() == DbusClientMode.BOOTSTRAP_SNAPSHOT) {
                                output.append(cp.getBootstrapSinceScn());
                                output.append(delim);
                                output.append(-1);
                            }
                        }
                        System.out.println(output.toString());
                    }
                } else {
                    throw new DatabusClusterUtilException("readSCN: please specify non-empty sources");
                }
            } else if (function.equals("checkpoint")) {
                List<String> sources = getSources(arg1);
                if ((sources != null) && !sources.isEmpty()) {
                    DatabusClusterCkptManager ckptMgr = new DatabusClusterCkptManager(zkServer, clusterName,
                            sources, partitions, isLegacyChkptLocation);
                    Map<Integer, Checkpoint> ckpts = ckptMgr.readCheckpoint();
                    char delim = '\t';
                    for (Map.Entry<Integer, Checkpoint> mkPair : ckpts.entrySet()) {
                        StringBuilder output = new StringBuilder(64);
                        output.append(mkPair.getKey());
                        output.append(delim);
                        Checkpoint cp = mkPair.getValue();
                        if (cp == null) {
                            output.append("null");
                        } else {
                            output.append(cp.toString());
                        }
                        System.out.println(output.toString());
                    }
                } else {
                    throw new DatabusClusterUtilException("readSCN: please specify non-empty sources");
                }
            } else if (function.equals("writeSCN")) {
                String scnStr = arg1;
                Long scn = Long.parseLong(scnStr);
                if (partitionStr != null) {
                    List<String> sources = getSources(arg2);
                    if ((sources != null) && !sources.isEmpty()) {
                        DatabusClusterCkptManager ckptMgr = new DatabusClusterCkptManager(zkServer, clusterName,
                                sources, partitions, isLegacyChkptLocation);
                        ckptMgr.writeCheckpoint(scn);
                    } else {
                        throw new DatabusClusterUtilException("writeSCN: please specify non-empty sources");
                    }
                } else {
                    throw new DatabusClusterUtilException(
                            "writeSCN: to write the SCN to all partitions please use '-p all'");
                }
            } else if (function.equals("removeSCN")) {
                if (partitionStr != null) {

                    List<String> sources = getSources(arg1);
                    if ((sources != null) && !sources.isEmpty()) {
                        DatabusClusterCkptManager ckptMgr = new DatabusClusterCkptManager(zkServer, clusterName,
                                sources, partitions, isLegacyChkptLocation);
                        ckptMgr.remove();
                    } else {
                        throw new DatabusClusterUtilException("remove: please specify non-empty sources");
                    }
                } else {
                    throw new DatabusClusterUtilException(
                            "remove: to remove SCN from all partitions please use '-p all'");
                }
            } else {
                usage();
                System.exit(1);
            }
        }
    } catch (ParseException e) {
        usage();
        System.exit(1);
    } catch (DatabusClusterUtilException e) {
        System.err.println("Error! " + e.toString());
        System.exit(1);
    }

}

From source file:com.xruby.debug.DebugCommandLineOptions.java

/**
 * Constructor//from w  w  w.  j  a  v a  2s . c  o  m
 *
 * @param args Arguments
 */
public DebugCommandLineOptions(String[] args) {
    pathList = new ArrayList<String>();

    GnuParser parser = new GnuParser();

    Options options = new Options();
    options.addOption(SOURCE_PATH_S, SOURCE_PATH, true, "path for the source code, seperated by semicolon");
    options.addOption(CLASS_PATH_S, CLASS_PATH, true, "classpath for debugee");

    CommandLine line;
    try {
        line = parser.parse(options, args, true);
    } catch (ParseException e) {
        throw new Error(e.toString());
    }

    if (line.hasOption(SOURCE_PATH_S)) {
        String paths = line.getOptionValue(SOURCE_PATH_S);
        StringTokenizer st = new StringTokenizer(paths, SEPARATOR);

        while (st.hasMoreTokens()) {
            String path = st.nextToken();
            pathList.add(path);
        }
    }

    if (line.hasOption(CLASS_PATH_S)) {
        this.classPath = line.getOptionValue(CLASS_PATH_S);
    }

    String[] tmp = line.getArgs();
    entrance = new StringBuffer();
    for (String str : tmp) {
        entrance.append(str).append(" ");
    }
}

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

/**
 * Parse a array of arguments into a command.
 *
 * @param args array of arguments.//from   w ww.  java  2s.  c om
 * @return the parsed Command.
 * @throws ParseException thrown if the arguments could not be parsed.
 */
public Command parse(String[] args) throws ParseException {
    if (args.length == 0) {
        throw new ParseException("missing sub-command");
    } else {
        if (commands.containsKey(args[0])) {
            GnuParser parser = new GnuParser();
            String[] minusCommand = new String[args.length - 1];
            System.arraycopy(args, 1, minusCommand, 0, minusCommand.length);
            return new Command(args[0],
                    parser.parse(commands.get(args[0]), minusCommand, commandWithArgs.get(args[0])));
        } else {
            throw new ParseException(MessageFormat.format("invalid sub-command [{0}]", args[0]));
        }
    }
}

From source file:org.apache.oozie.cli.CLIParser.java

/**
 * Parse a array of arguments into a command.
 *
 * @param args array of arguments.//ww  w.j av a 2  s.c  om
 * @return the parsed Command.
 * @throws ParseException thrown if the arguments could not be parsed.
 */
public Command parse(String[] args) throws ParseException {
    if (args.length == 0) {
        throw new ParseException("missing sub-command");
    } else {
        if (commands.containsKey(args[0])) {
            GnuParser parser;
            String[] minusCommand = new String[args.length - 1];
            System.arraycopy(args, 1, minusCommand, 0, minusCommand.length);

            if (args[0].equals(OozieCLI.JOB_CMD)) {
                validdateArgs(args, minusCommand);
                parser = new OozieGnuParser(true);
            } else {
                parser = new OozieGnuParser(false);
            }

            return new Command(args[0],
                    parser.parse(commands.get(args[0]), minusCommand, commandWithArgs.get(args[0])));
        } else {
            throw new ParseException(MessageFormat.format("invalid sub-command [{0}]", args[0]));
        }
    }
}

From source file:org.apache.oozie.cli.CLIParser.java

public void validdateArgs(final String[] args, String[] minusCommand) throws ParseException {
    try {/*from   www.  j  a v a 2  s . c om*/
        GnuParser parser = new OozieGnuParser(false);
        parser.parse(commands.get(args[0]), minusCommand, commandWithArgs.get(args[0]));
    } catch (MissingOptionException e) {
        if (Arrays.toString(args).contains("-dryrun")) {
            // ignore this, else throw exception
            //Dryrun is also part of update sub-command. CLI parses dryrun as sub-command and throws
            //Missing Option Exception, if -dryrun is used as command. It's ok to skip exception only for dryrun.
        } else {
            throw e;
        }
    }
}

From source file:org.dspace.eperson.EPerson.java

/**
 * Tool for manipulating user accounts.//  w w w .j  a  v a  2s  . co  m
 */
public static void main(String argv[]) throws ParseException, SQLException {
    final OptionGroup VERBS = new OptionGroup();
    VERBS.addOption(VERB_ADD);
    VERBS.addOption(VERB_DELETE);
    VERBS.addOption(VERB_LIST);
    VERBS.addOption(VERB_MODIFY);

    final Options globalOptions = new Options();
    globalOptions.addOptionGroup(VERBS);
    globalOptions.addOption("h", "help", false, "explain options");

    GnuParser parser = new GnuParser();
    CommandLine command = parser.parse(globalOptions, argv, true);

    Context context = new Context();

    // Disable authorization since this only runs from the local commandline.
    context.turnOffAuthorisationSystem();

    int status = 0;
    if (command.hasOption(VERB_ADD.getOpt())) {
        status = cmdAdd(context, argv);
    } else if (command.hasOption(VERB_DELETE.getOpt())) {
        status = cmdDelete(context, argv);
    } else if (command.hasOption(VERB_MODIFY.getOpt())) {
        status = cmdModify(context, argv);
    } else if (command.hasOption(VERB_LIST.getOpt())) {
        status = cmdList(context, argv);
    } else if (command.hasOption('h')) {
        new HelpFormatter().printHelp("user [options]", globalOptions);
    } else {
        System.err.println("Unknown operation.");
        new HelpFormatter().printHelp("user [options]", globalOptions);
        context.abort();
        status = 1;
        throw new IllegalArgumentException();
    }

    if (context.isValid()) {
        try {
            context.complete();
        } catch (SQLException ex) {
            System.err.println(ex.getMessage());
        }
    }
}

From source file:org.dspace.eperson.EPersonCLITool.java

/**
 * Tool for manipulating user accounts.//from w  w w  . ja v a2 s  .  c o  m
 *
 * @param argv the command line arguments given
 * @throws ParseException
 *     Base for Exceptions thrown during parsing of a command-line.
 * @throws SQLException
 *     An exception that provides information on a database access error or other errors.
 * @throws AuthorizeException
 *     Exception indicating the current user of the context does not have permission
 *     to perform a particular action.
 */
public static void main(String argv[]) throws ParseException, SQLException, AuthorizeException {
    final OptionGroup VERBS = new OptionGroup();
    VERBS.addOption(VERB_ADD);
    VERBS.addOption(VERB_DELETE);
    VERBS.addOption(VERB_LIST);
    VERBS.addOption(VERB_MODIFY);

    final Options globalOptions = new Options();
    globalOptions.addOptionGroup(VERBS);
    globalOptions.addOption("h", "help", false, "explain options");

    GnuParser parser = new GnuParser();
    CommandLine command = parser.parse(globalOptions, argv, true);

    Context context = new Context();

    // Disable authorization since this only runs from the local commandline.
    context.turnOffAuthorisationSystem();

    int status = 0;
    if (command.hasOption(VERB_ADD.getOpt())) {
        status = cmdAdd(context, argv);
    } else if (command.hasOption(VERB_DELETE.getOpt())) {
        status = cmdDelete(context, argv);
    } else if (command.hasOption(VERB_MODIFY.getOpt())) {
        status = cmdModify(context, argv);
    } else if (command.hasOption(VERB_LIST.getOpt())) {
        status = cmdList(context, argv);
    } else if (command.hasOption('h')) {
        new HelpFormatter().printHelp("user [options]", globalOptions);
    } else {
        System.err.println("Unknown operation.");
        new HelpFormatter().printHelp("user [options]", globalOptions);
        context.abort();
        status = 1;
        throw new IllegalArgumentException();
    }

    if (context.isValid()) {
        try {
            context.complete();
        } catch (SQLException ex) {
            System.err.println(ex.getMessage());
        }
    }
}

From source file:org.eclipse.emf.search.examples.ecore.grep.EcoreGrep.java

private void runQuery(String[] args) {
    GnuParser p = new GnuParser();

    Options options = initOptions();/*from   ww  w .  j a  v  a 2  s . co  m*/

    try {
        CommandLine cl = p.parse(options, args, true);

        ModelSearchQueryTextualExpressionEnum pattern = computeQueryExpressionKind(
                cl.getOptionValue(PATTERN_OPT_ID));

        List<File> fLst = new ArrayList<File>();

        for (String fName : cl.getOptionValues(DIR_OPT_ID)) {
            fLst.add(new File(fName));
        }

        String expr = cl.getOptionValue(EXPR_OPT_ID) == null ? NORMAL_PATTERN_OPT
                : cl.getOptionValue(EXPR_OPT_ID);

        List<EClassifier> cLst = new ArrayList<EClassifier>();
        if (!cl.hasOption(PARTICIPANT_OPT_ID)) {
            cLst.addAll(EcorePackage.eINSTANCE.getEClassifiers());
        } else {
            for (String cName : cl.getOptionValues(PARTICIPANT_OPT_ID)) {
                cLst.add(EcorePackage.eINSTANCE.getEClassifier(cName));
            }
        }

        runTextualGlobalRegexModelSearchRuntimeQuery(expr, cLst, pattern, fLst);
    } catch (ParseException e) {
        new HelpFormatter().printHelp("EcoreGrep", options);
        return;
    }
}

From source file:org.esco.grouperui.services.dynamicgroup.BatchAddMember.java

/**
 * Default constructor.//from w  ww.  j  a  v  a 2  s  .  c o m
 * 
 * @param args
 *            arguments of the batch
 * @throws ParseException
 *             exception occurs parsing the command line
 */
public BatchAddMember(final String[] args) throws ParseException {

    GnuParser parser = new GnuParser();
    this.commandLine = parser.parse(BatchAddMember.OPTIONS, args, true);

    this.applicationContext = new ClassPathXmlApplicationContext(
            new String[] { "classpath:/properties/applicationContext.xml" });
}