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

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

Introduction

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

Prototype

CommandLine parse(Options options, String[] arguments) throws ParseException;

Source Link

Document

Parse the arguments according to the specified options.

Usage

From source file:com.example.dlp.Metadata.java

/** Retrieve infoTypes. */
public static void main(String[] args) throws Exception {
    Options options = new Options();
    Option languageCodeOption = new Option("language", null, true, "BCP-47 language code");
    languageCodeOption.setRequired(false);
    options.addOption(languageCodeOption);

    Option categoryOption = new Option("category", null, true, "Category of info types to list.");
    categoryOption.setRequired(false);/* w w  w  . j a v  a 2 s  .com*/
    options.addOption(categoryOption);

    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        formatter.printHelp(Metadata.class.getName(), options);
        System.exit(1);
        return;
    }
    String languageCode = cmd.getOptionValue(languageCodeOption.getOpt(), "en-US");
    if (cmd.hasOption(categoryOption.getOpt())) {
        String category = cmd.getOptionValue(categoryOption.getOpt());
        listInfoTypes(category, languageCode);
    } else {
        listRootCategories(languageCode);
    }
}

From source file:com.github.sdnwiselab.sdnwise.mote.standalone.Loader.java

/**
 * @param args the command line arguments
 *///from w  w  w  . j  a  v  a 2 s  .com
public static void main(final String[] args) {
    Options options = new Options();
    options.addOption(Option.builder("n").argName("net").hasArg().required().desc("Network ID of the node")
            .numberOfArgs(1).build());
    options.addOption(Option.builder("a").argName("address").hasArg().required()
            .desc("Address of the node <0-65535>").numberOfArgs(1).build());
    options.addOption(Option.builder("p").argName("port").hasArg().required().desc("Listening UDP port")
            .numberOfArgs(1).build());
    options.addOption(Option.builder("t").argName("filename").hasArg().required()
            .desc("Use given file for neighbors discovery").numberOfArgs(1).build());
    options.addOption(Option.builder("c").argName("ip:port").hasArg()
            .desc("IP address and TCP port of the controller. (SINK ONLY)").numberOfArgs(1).build());
    options.addOption(Option.builder("sp").argName("port").hasArg()
            .desc("Port number of the switch. (SINK ONLY)").numberOfArgs(1).build());
    options.addOption(Option.builder("sm").argName("mac").hasArg()
            .desc("MAC address of the switch. Example: <00:00:00:00:00:00>." + " (SINK ONLY)").numberOfArgs(1)
            .build());
    options.addOption(Option.builder("sd").argName("dpid").hasArg().desc("DPID of the switch (SINK ONLY)")
            .numberOfArgs(1).build());
    options.addOption(Option.builder("l").argName("level").hasArg()
            .desc("Use given log level. Values: SEVERE, WARNING, INFO, " + "CONFIG, FINE, FINER, FINEST.")
            .numberOfArgs(1).optionalArg(true).build());

    // create the parser
    CommandLineParser parser = new DefaultParser();
    try {
        CommandLine line = parser.parse(options, args);
        Thread th;

        byte cmdNet = (byte) Integer.parseInt(line.getOptionValue("n"));
        NodeAddress cmdAddress = new NodeAddress(Integer.parseInt(line.getOptionValue("a")));
        int cmdPort = Integer.parseInt(line.getOptionValue("p"));
        String cmdTopo = line.getOptionValue("t");

        String cmdLevel;

        if (!line.hasOption("l")) {
            cmdLevel = "SEVERE";
        } else {
            cmdLevel = line.getOptionValue("l");
        }

        if (line.hasOption("c")) {

            if (!line.hasOption("sd")) {
                throw new ParseException("-sd option missing");
            }
            if (!line.hasOption("sp")) {
                throw new ParseException("-sp option missing");
            }
            if (!line.hasOption("sm")) {
                throw new ParseException("-sm option missing");
            }

            String cmdSDpid = line.getOptionValue("sd");
            String cmdSMac = line.getOptionValue("sm");
            long cmdSPort = Long.parseLong(line.getOptionValue("sp"));
            String[] ipport = line.getOptionValue("c").split(":");
            th = new Thread(new Sink(cmdNet, cmdAddress, cmdPort,
                    new InetSocketAddress(ipport[0], Integer.parseInt(ipport[1])), cmdTopo, cmdLevel, cmdSDpid,
                    cmdSMac, cmdSPort));
        } else {
            th = new Thread(new Mote(cmdNet, cmdAddress, cmdPort, cmdTopo, cmdLevel));
        }
        th.start();
        th.join();
    } catch (InterruptedException | ParseException ex) {
        System.out.println("Parsing failed.  Reason: " + ex.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("sdn-wise-data -n id -a address -p port"
                + " -t filename [-l level] [-sd dpid -sm mac -sp port]", options);
    }
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.CdoQueryClassDeclarationAttributes.java

public static void main(String[] args) {
    Options options = new Options();

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input CDO resource directory");
    inputOpt.setArgs(1);/*from ww  w .j  a v  a 2  s  .c o  m*/
    inputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    Option repoOpt = OptionBuilder.create(REPO_NAME);
    repoOpt.setArgName("REPO_NAME");
    repoOpt.setDescription("CDO Repository name");
    repoOpt.setArgs(1);
    repoOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(inClassOpt);
    options.addOption(repoOpt);

    CommandLineParser parser = new PosixParser();

    try {
        CommandLine commandLine = parser.parse(options, args);

        String repositoryDir = commandLine.getOptionValue(IN);
        String repositoryName = commandLine.getOptionValue(REPO_NAME);

        Class<?> inClazz = CdoQueryClassDeclarationAttributes.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        EmbeddedCDOServer server = new EmbeddedCDOServer(repositoryDir, repositoryName);
        try {
            server.run();
            CDOSession session = server.openSession();
            CDOTransaction transaction = session.openTransaction();
            Resource resource = transaction.getRootResource();

            {
                LOG.log(Level.INFO, "Start query");
                long begin = System.currentTimeMillis();
                HashMap<String, EList<NamedElement>> map = JavaQueries.getClassDeclarationAttributes(resource);
                long end = System.currentTimeMillis();
                LOG.log(Level.INFO, "End query");
                LOG.log(Level.INFO,
                        MessageFormat.format("Query result contains {0} elements", map.entrySet().size()));
                LOG.log(Level.INFO,
                        MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
            }

            transaction.close();
            session.close();
        } finally {
            server.stop();
        }
    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.CdoQueryThrownExceptionsPerPackage.java

public static void main(String[] args) {
    Options options = new Options();

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input CDO resource directory");
    inputOpt.setArgs(1);// w w  w .  j av a 2 s  . c  o  m
    inputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    Option repoOpt = OptionBuilder.create(REPO_NAME);
    repoOpt.setArgName("REPO_NAME");
    repoOpt.setDescription("CDO Repository name");
    repoOpt.setArgs(1);
    repoOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(inClassOpt);
    options.addOption(repoOpt);

    CommandLineParser parser = new PosixParser();

    try {
        CommandLine commandLine = parser.parse(options, args);

        String repositoryDir = commandLine.getOptionValue(IN);
        String repositoryName = commandLine.getOptionValue(REPO_NAME);

        Class<?> inClazz = CdoQueryThrownExceptionsPerPackage.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        EmbeddedCDOServer server = new EmbeddedCDOServer(repositoryDir, repositoryName);
        try {
            server.run();
            CDOSession session = server.openSession();
            CDOTransaction transaction = session.openTransaction();
            Resource resource = transaction.getRootResource();

            {
                LOG.log(Level.INFO, "Start query");
                long begin = System.currentTimeMillis();
                HashMap<String, EList<TypeAccess>> map = JavaQueries.getThrownExceptionsPerPackage(resource);
                long end = System.currentTimeMillis();
                LOG.log(Level.INFO, "End query");
                LOG.log(Level.INFO,
                        MessageFormat.format("Query result contains {0} elements", map.entrySet().size()));
                LOG.log(Level.INFO,
                        MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
            }

            transaction.close();
            session.close();
        } finally {
            server.stop();
        }
    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.MorsaTraverser.java

public static void main(String[] args) {
    Options options = new Options();

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input Kyanos resource directory");
    inputOpt.setArgs(1);/*from  ww  w .jav a 2s . c  o  m*/
    inputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(inClassOpt);

    CommandLineParser parser = new PosixParser();

    try {
        CommandLine commandLine = parser.parse(options, args);

        URI uri = URI.createURI("morsa://" + commandLine.getOptionValue(IN));

        Class<?> inClazz = MorsaTraverser.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put("morsa",
                new MorsaResourceFactoryImpl(new MongoDBMorsaBackendFactory()));

        Resource resource = resourceSet.createResource(uri);

        Map<String, Object> loadOpts = new HashMap<String, Object>();
        loadOpts.put(IMorsaResource.OPTION_SERVER_URI, "localhost");
        loadOpts.put(IMorsaResource.OPTION_MAX_SAVE_CACHE_SIZE, 30000);
        loadOpts.put(IMorsaResource.OPTION_DEMAND_LOAD, false);
        //         loadOpts.put(IMorsaResource.OPTION_CACHE_POLICY, FIFOEObjectCachePolicy.class.getName());
        //         loadOpts.put(IMorsaResource.OPTION_MAX_CACHE_SIZE, 30000);
        //         loadOpts.put(IMorsaResource.OPTION_CACHE_FLUSH_FACTOR, 0.3f);
        //         loadOpts.put(IMorsaResource.OPTION_DEMAND_LOAD_STRATEGY, IMorsaResource.OPTION_SINGLE_LOAD_STRATEGY);
        //         loadOpts.put(IMorsaResource.OPTION_DEMAND_LOAD, true);

        resource.load(loadOpts);

        LOG.log(Level.INFO, "Start counting");
        int count = 0;
        long begin = System.currentTimeMillis();
        for (Iterator<EObject> iterator = resource.getAllContents(); iterator.hasNext(); iterator
                .next(), count++)
            ;
        long end = System.currentTimeMillis();
        LOG.log(Level.INFO, "End counting");
        LOG.log(Level.INFO, MessageFormat.format("Resource {0} contains {1} elements", uri, count));
        LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));

    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:com.baystep.jukeberry.JukeBerry.java

/**
 * @param args the command line arguments
 *//*  w w  w.j  a  v  a2 s  .com*/
public static void main(String[] args) {
    System.out.println("Berry Music\n");

    JukeBerry bm = new JukeBerry();

    buildOptions();
    CommandLineParser cmdParser = new DefaultParser();
    try {
        CommandLine cmd = cmdParser.parse(cmdOptions, args);

        if (cmd.hasOption("h")) {
            cmdHelp.printHelp("BerryMusic", help_Header, cmdOptions, help_Footer, true);
            System.exit(0);
        }

        if (cmd.hasOption("pw"))
            bm.config.httpPort = Integer.parseInt(cmd.getOptionValue("pw"));

        if (cmd.hasOption("ps"))
            bm.config.websocketPort = Integer.parseInt(cmd.getOptionValue("ps"));

        if (cmd.hasOption("d")) {
            String dOpt = cmd.getOptionValue("d");
            bm.config.setDisableOption(dOpt);
        }

        if (cmd.hasOption("ss"))
            bm.config.mpStartService = cmd.getOptionValue("ss");

        if (cmd.hasOption("sc")) {
            BerryLogger.supressConsole();
        }

    } catch (ParseException pe) {
        System.err.println("Command line parsing failed, reason: " + pe.getMessage());
    }

    bm.init();
}

From source file:de.peregrinus.autocopyreport.AutoCopyReport.java

public static void main(String[] args) {
    SongInfo si;/*  ww w. j a  v  a 2  s  .  c om*/

    String openlpPath = "";
    String crPath = "";
    String crDataPath = "";
    String crPassword = "";

    System.out.println("AutoCopyReport v.1.00.00");
    System.out.println("(c) 2014 Volksmission Freudenstadt");
    System.out.println("Author: Christoph Fischer <christoph.fischer@volksmission.de>");
    //System.out.println("Available under the General Public License (GPL) v2");
    System.out.println();

    // get options
    Options options = new Options();
    options.addOption("h", "help", false, "display a list of available options");
    options.addOption(OptionBuilder.withLongOpt("openlp-path").withDescription("path to OpenLP data directory")
            .hasArg().withArgName("PATH").create());
    options.addOption(OptionBuilder.withLongOpt("copyreport-path")
            .withDescription("path to the CopyReport program directory").hasArg().withArgName("PATH").create());
    options.addOption(OptionBuilder.withLongOpt("copyreport-data-path")
            .withDescription("path to the CopyReport data directory").hasArg().withArgName("PATH").create());
    options.addOption(OptionBuilder.withLongOpt("password")
            .withDescription("internal password for the CopyReport database").hasArg().withArgName("PASSWORD")
            .create());

    // parse command line
    try {
        // parse the command line arguments
        CommandLineParser parser = new GnuParser();
        CommandLine line = parser.parse(options, args);

        // validate that block-size has been set
        if (line.hasOption("help")) {
            // automatically generate the help statement
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("AutoCopyReport", options);
            System.exit(0);
        } else {
            if (line.hasOption("openlp-path")) {
                openlpPath = line.getOptionValue("openlp-path") + "/songs/songs.sqlite";
                System.out.println("OpenLP data path: " + openlpPath);
            } else {
                System.out.println(
                        "ERROR: Please supply the path to your OpenLP data folder by using the --openlp-path parameter.");
                System.exit(0);
            }
            if (line.hasOption("copyreport-path")) {
                crPath = line.getOptionValue("copyreport-path");
                System.out.println("Copyreport application database: " + crPath + "/ccldata.h2.db");
            } else {
                System.out.println(
                        "ERROR: Please supply the path to your CopyReport program folder by using the --copyreport-path parameter.");
                System.exit(0);
            }
            if (line.hasOption("copyreport-data-path")) {
                crDataPath = line.getOptionValue("copyreport-data-path");
                System.out.println("Copyreport user database: " + crDataPath + "/userdata.h2.db");
            } else {
                System.out.println(
                        "ERROR: Please supply the path to your CopyReport data folder by using the --copyreport-data-path parameter.");
                System.exit(0);
            }
            if (line.hasOption("password")) {
                crPassword = line.getOptionValue("password");
            } else {
                System.out.println(
                        "ERROR: Please supply the internal password for the CopyReport database by using the --password parameter.");
                System.exit(0);
            }
        }
    } catch (ParseException exp) {
        System.out.println("Unexpected exception:" + exp.getMessage());
        System.exit(0);
    }

    SongDatabaseConnector sdb = new SongDatabaseConnector(openlpPath);
    SongRepository cdb = new SongRepository(crPath + "/ccldata", "sa", crPassword);

    CopyReport rpt = new CopyReport(crDataPath + "/userdata", "sa", crPassword);
    //rpt.createPeriod("2014");

    List<Song> songs = sdb.findLicensedSongs();
    for (Song song : songs) {
        System.out.println(song.title + ": " + song.ccliNumber);
        if (song.ccliNumber.matches("-?\\d+(\\.\\d+)?")) {
            si = cdb.findById(song.ccliNumber);
            if (si != null)
                rpt.reportSong(si);
        } else {
            System.out.println("Format error: '" + song.ccliNumber + "' is not numeric.");
        }
    }

    // wrap up: close the databases
    cdb.close();
    rpt.close();
    sdb.close();

}

From source file:com.act.biointerpretation.sarinference.ProductScorer.java

public static void main(String[] args) throws Exception {

    // Build command line parser.
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());/*www  .ja va2 s  .c  o  m*/
    }
    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        LOGGER.error("Argument parsing failed: %s", e.getMessage());
        HELP_FORMATTER.printHelp(L2FilteringDriver.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    File inputCorpusFile = new File(cl.getOptionValue(OPTION_PREDICTION_CORPUS));
    File lcmsFile = new File(cl.getOptionValue(OPTION_LCMS_RESULTS));
    File scoredSarsFile = new File(cl.getOptionValue(OPTION_SCORED_SARS));
    File outputFile = new File(cl.getOptionValue(OPTION_OUTPUT_PATH));

    JavaRunnable productScoreRunner = getProductScorer(inputCorpusFile, scoredSarsFile, lcmsFile, outputFile);

    LOGGER.info("Scoring products.");
    productScoreRunner.run();
    LOGGER.info("Complete!.");
}

From source file:com.genentech.chemistry.openEye.apps.SDFMCSSSphereExclusion.java

public static void main(String... args) throws IOException {
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;// w w w . jav  a 2s  . c o m
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp();
    }
    args = cmd.getArgs();

    if (cmd.hasOption("d")) {
        System.err.println("Start debugger and press return:");
        new BufferedReader(new InputStreamReader(System.in)).readLine();
    }

    // the only reason not to match centroids in reverse order id if
    // a non-centroid is to be assigned to multiple centroids
    boolean printSphereMatchCount = cmd.hasOption("printSphereMatchCount");
    boolean reverseMatch = !cmd.hasOption("checkSpheresInOrder") && !printSphereMatchCount;
    boolean printAll = cmd.hasOption("printAll") || printSphereMatchCount;
    double radius = Double.parseDouble(cmd.getOptionValue("radius"));
    String inFile = cmd.getOptionValue("in");
    String outFile = cmd.getOptionValue("out");
    String refFile = cmd.getOptionValue("ref");

    SimComparatorFactory<OEMolBase, OEMolBase, SimComparator<OEMolBase>> compFact;
    compFact = getComparatorFactory(cmd);

    SphereExclusion<OEMolBase, SimComparator<OEMolBase>> alg = new SphereExclusion<OEMolBase, SimComparator<OEMolBase>>(
            compFact, refFile, outFile, radius, reverseMatch, printSphereMatchCount, printAll);
    alg.run(inFile);
    alg.close();
}

From source file:eu.scape_project.pc.droid.cli.DroidCli.java

public static void main(String[] args) {
    // Static for command line option parsing
    DroidCli tc = new DroidCli();

    CommandLineParser cmdParser = new PosixParser();
    try {// ww  w.  j av a2 s . c o  m
        CommandLine cmd = cmdParser.parse(OPTIONS, args);
        if ((args.length == 0) || (cmd.hasOption(HELP_OPT))) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(Constants.USAGE, OPTIONS, true);
            System.exit(0);
        } else {
            if (cmd.hasOption(DIR_OPT) && cmd.getOptionValue(DIR_OPT) != null) {
                String dirStr = cmd.getOptionValue(DIR_OPT);
                logger.info("Directory: " + dirStr);

                // *** start timer
                long startClock = System.currentTimeMillis();
                try {
                    tc.processFiles(new File(dirStr));

                } catch (FileNotFoundException ex) {
                    logger.error("File not found", ex);
                } catch (IOException ex) {
                    logger.error("I/O Exception", ex);
                }

                // *** stop timer
                long elapsedTimeMillis = System.currentTimeMillis() - startClock;
                logger.info("Identification finished after " + elapsedTimeMillis + " milliseconds");

            } else {
                logger.error("No directory given.");
                HelpFormatter formatter = new HelpFormatter();
                formatter.printHelp(Constants.USAGE, OPTIONS, true);
                System.exit(1);
            }
        }
    } catch (ParseException ex) {
        logger.error("Problem parsing command line arguments.", ex);
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(Constants.USAGE, OPTIONS, true);
        System.exit(1);
    }
}