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

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

Introduction

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

Prototype

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

Source Link

Document

Parses the specified arguments based on the specifed Options .

Usage

From source file:com.betfair.cougar.test.socket.app.SocketCompatibilityTestingApp.java

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

    Parser parser = new PosixParser();
    Options options = new Options();
    options.addOption("r", "repo", true, "Repository type to search: local|central");
    options.addOption("c", "client-concurrency", true,
            "Max threads to allow each client tester to run tests, defaults to 10");
    options.addOption("t", "test-concurrency", true, "Max client testers to run concurrently, defaults to 5");
    options.addOption("m", "max-time", true,
            "Max time (in minutes) to allow tests to complete, defaults to 10");
    options.addOption("v", "version", false, "Print version and exit");
    options.addOption("h", "help", false, "This help text");
    CommandLine commandLine = parser.parse(options, args);
    if (commandLine.hasOption("h")) {
        System.out.println(options);
        System.exit(0);//from  w w  w .  j a  v a2 s  .  c  o  m
    }
    if (commandLine.hasOption("v")) {
        System.out.println("How the hell should I know?");
        System.exit(0);
    }
    // 1. Find all testers in given repos
    List<RepoSearcher> repoSearchers = new ArrayList<>();
    for (String repo : commandLine.getOptionValues("r")) {
        if ("local".equals(repo.toLowerCase())) {
            repoSearchers.add(new LocalRepoSearcher());
        } else if ("central".equals(repo.toLowerCase())) {
            repoSearchers.add(new CentralRepoSearcher());
        } else {
            System.err.println("Unrecognized repo: " + repo);
            System.err.println(options);
            System.exit(1);
        }
    }
    int clientConcurrency = 10;
    if (commandLine.hasOption("c")) {
        try {
            clientConcurrency = Integer.parseInt(commandLine.getOptionValue("c"));
        } catch (NumberFormatException nfe) {
            System.err.println(
                    "client-concurrency is not a valid integer: '" + commandLine.getOptionValue("c") + "'");
            System.exit(1);
        }
    }
    int testConcurrency = 5;
    if (commandLine.hasOption("t")) {
        try {
            testConcurrency = Integer.parseInt(commandLine.getOptionValue("t"));
        } catch (NumberFormatException nfe) {
            System.err.println(
                    "test-concurrency is not a valid integer: '" + commandLine.getOptionValue("t") + "'");
            System.exit(1);
        }
    }
    int maxMinutes = 10;
    if (commandLine.hasOption("m")) {
        try {
            maxMinutes = Integer.parseInt(commandLine.getOptionValue("m"));
        } catch (NumberFormatException nfe) {
            System.err.println("max-time is not a valid integer: '" + commandLine.getOptionValue("m") + "'");
            System.exit(1);
        }
    }

    Properties clientProps = new Properties();
    clientProps.setProperty("client.concurrency", String.valueOf(clientConcurrency));

    File baseRunDir = new File(System.getProperty("user.dir") + "/run");
    baseRunDir.mkdirs();

    File tmpDir = new File(baseRunDir, "jars");
    tmpDir.mkdirs();

    List<ServerRunner> serverRunners = new ArrayList<>();
    List<ClientRunner> clientRunners = new ArrayList<>();
    for (RepoSearcher searcher : repoSearchers) {
        List<File> jars = searcher.findAndCache(tmpDir);
        for (File f : jars) {
            ServerRunner serverRunner = new ServerRunner(f, baseRunDir);
            System.out.println("Found tester: " + serverRunner.getVersion());
            serverRunners.add(serverRunner);
            clientRunners.add(new ClientRunner(f, baseRunDir, clientProps));
        }
    }

    // 2. Start servers and collect ports
    System.out.println();
    System.out.println("Starting " + serverRunners.size() + " servers...");
    for (ServerRunner server : serverRunners) {
        server.startServer();
    }
    System.out.println();

    List<TestCombo> tests = new ArrayList<>(serverRunners.size() * clientRunners.size());
    for (ServerRunner server : serverRunners) {
        for (ClientRunner client : clientRunners) {
            tests.add(new TestCombo(server, client));
        }
    }

    System.out.println("Enqueued " + tests.size() + " test combos to run...");

    long startTime = System.currentTimeMillis();
    // 3. Run every client against every server, collecting results
    BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue(serverRunners.size() * clientRunners.size());
    ThreadPoolExecutor service = new ThreadPoolExecutor(testConcurrency, testConcurrency, 5000,
            TimeUnit.MILLISECONDS, workQueue);
    service.prestartAllCoreThreads();
    workQueue.addAll(tests);
    while (!workQueue.isEmpty()) {
        Thread.sleep(1000);
    }
    service.shutdown();
    service.awaitTermination(maxMinutes, TimeUnit.MINUTES);
    long endTime = System.currentTimeMillis();
    long totalTimeSecs = Math.round((endTime - startTime) / 1000.0);
    for (ServerRunner server : serverRunners) {
        server.shutdownServer();
    }

    System.out.println();
    System.out.println("=======");
    System.out.println("Results");
    System.out.println("-------");
    // print a summary
    int totalTests = 0;
    int totalSuccess = 0;
    for (TestCombo combo : tests) {
        String clientVer = combo.getClientVersion();
        String serverVer = combo.getServerVersion();
        String results = combo.getClientResults();
        ObjectMapper mapper = new ObjectMapper(new JsonFactory());
        JsonNode node = mapper.reader().readTree(results);
        JsonNode resultsArray = node.get("results");
        int numTests = resultsArray.size();
        int numSuccess = 0;
        for (int i = 0; i < numTests; i++) {
            if ("success".equals(resultsArray.get(i).get("result").asText())) {
                numSuccess++;
            }
        }
        totalSuccess += numSuccess;
        totalTests += numTests;
        System.out.println(clientVer + "/" + serverVer + ": " + numSuccess + "/" + numTests
                + " succeeded - took " + String.format("%2f", combo.getRunningTime()) + " seconds");
    }
    System.out.println("-------");
    System.out.println(
            "Overall: " + totalSuccess + "/" + totalTests + " succeeded - took " + totalTimeSecs + " seconds");

    FileWriter out = new FileWriter("results.json");
    PrintWriter pw = new PrintWriter(out);

    // 4. Output full results
    pw.println("{\n  \"results\": [");
    for (TestCombo combo : tests) {
        combo.emitResults(pw, "    ");
    }
    pw.println("  ],");
    pw.println("  \"servers\": [");
    for (ServerRunner server : serverRunners) {
        server.emitInfo(pw, "    ");
    }
    pw.println("  ],");
    pw.close();
}

From source file:com.hurence.logisland.runner.SparkJobLauncher.java

/**
 * main entry point//from  ww  w .j  a  v a 2  s  . c  o  m
 *
 * @param args
 */
public static void main(String[] args) {

    logger.info("starting StreamProcessingRunner");

    //////////////////////////////////////////
    // Commande lien management
    Parser parser = new GnuParser();
    Options options = new Options();

    String helpMsg = "Print this message.";
    Option help = new Option("help", helpMsg);
    options.addOption(help);

    OptionBuilder.withArgName(AGENT);
    OptionBuilder.withLongOpt("agent-quorum");
    OptionBuilder.isRequired();
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("logisland agent quorum like host1:8081,host2:8081");
    Option agent = OptionBuilder.create(AGENT);
    options.addOption(agent);

    OptionBuilder.withArgName(JOB);
    OptionBuilder.withLongOpt("job-name");
    OptionBuilder.isRequired();
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("logisland agent quorum like host1:8081,host2:8081");
    Option job = OptionBuilder.create(JOB);
    options.addOption(job);

    String logisland = "                      \n"
            + "     ????????   ?????     ??  ??\n"
            + "                    \n"
            + "             ????     ??  \n"
            + "??     ?\n"
            + "??????? ??????  ??????   ??????????????????  ????  ??????????   v0.10.0-SNAPSHOT\n\n\n";

    System.out.println(logisland);
    Optional<EngineContext> engineInstance = Optional.empty();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);
        String agentQuorum = line.getOptionValue(AGENT);
        String jobName = line.getOptionValue(JOB);

        // instanciate engine and all the processor from the config
        engineInstance = new RestComponentFactory(agentQuorum).getEngineContext(jobName);
        assert engineInstance.isPresent();
        assert engineInstance.get().isValid();

        logger.info("starting Logisland session version {}", engineInstance.get());
    } catch (Exception e) {
        logger.error("unable to launch runner : {}", e.toString());
    }

    try {
        // start the engine
        EngineContext engineContext = engineInstance.get();
        engineInstance.get().getEngine().start(engineContext);
    } catch (Exception e) {
        logger.error("something went bad while running the job : {}", e);
        System.exit(-1);
    }

}

From source file:com.liveramp.hank.util.CliUtils.java

public static CommandLine parseAndHelp(String appName, Options options, String[] args) {
    options.addOption(HELP_OPTION);/*  w ww  . j a  v  a 2 s  .co  m*/

    Parser parser = new GnuParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, args);
    } catch (MissingOptionException e) {
        new HelpFormatter().printHelp(appName, options, true);
        throw new IllegalArgumentException();
    } catch (MissingArgumentException e) {
        new HelpFormatter().printHelp(appName, options, true);
        throw new IllegalArgumentException();
    } catch (ParseException e) {
        System.err.println("Unexpected Exception: " + e);
        throw new IllegalArgumentException();
    }

    if (line.hasOption("help")) {
        new HelpFormatter().printHelp(appName, options, true);
        throw new IllegalArgumentException();
    }

    return line;
}

From source file:com.xtructure.xutil.opt.XOption.java

/**
 * Parses the given args array with the given parser, passing the arguments
 * to the given options//from www  .  ja  v a2s .co m
 * 
 * @param options
 * @param args
 * @param parser
 * @throws ParseException
 */
public static final void parseArgs(Options options, String[] args, Parser parser) throws ParseException {
    CommandLine cl = parser.parse(options, args);
    for (Object obj : options.getOptions()) {
        if (obj instanceof XOption<?>) {
            XOption<?> xOption = (XOption<?>) obj;
            xOption.setHasValue(cl.hasOption(xOption.getOpt()));
        }
    }
}

From source file:edu.wpi.checksims.ChecksimsCommandLine.java

/**
 * Parse a given set of CLI arguments into a Commons CLI CommandLine.
 *
 * @param args Arguments to parse//from   www .ja  v a2 s .  c om
 * @return CommandLine from parsed arguments
 * @throws ParseException Thrown on error parsing arguments
 */
static CommandLine parseOpts(String[] args) throws ParseException {
    checkNotNull(args);

    Parser parser = new GnuParser();

    // Parse the CLI args
    return parser.parse(getOpts(), args);
}

From source file:com.model.database.GtfsDatabaseLoaderMain.java

private CommandLine parseCommandLineOptions(String[] args) {
    try {/*from   www .  ja  v a2s .  co m*/
        Options options = new Options();
        buildOptions(options);
        Parser parser = new PosixParser();
        return parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        printUsage();
        System.exit(-1);
        return null;
    }
}

From source file:edu.usf.cutr.realtime.hart.HartToGtfsRealtimeMain.java

public void run(String[] args) throws Exception {

    if (args.length == 0 || CommandLineInterfaceLibrary.wantsHelp(args)) {
        printUsage();//from   w w w  .j  av  a  2 s.c  o  m
        System.exit(-1);
    }

    Options options = new Options();
    buildOptions(options);
    Parser parser = new GnuParser();
    CommandLine cli = parser.parse(options, args);

    Set<Module> modules = new HashSet<Module>();
    HartToGtfsRealtimeModule.addModuleAndDependencies(modules);

    Injector injector = Guice.createInjector(modules);
    injector.injectMembers(this);

    if (cli.hasOption(ARG_TRIP_UPDATES_URL)) {
        URL url = new URL(cli.getOptionValue(ARG_TRIP_UPDATES_URL));
        TripUpdatesServlet servlet = injector.getInstance(TripUpdatesServlet.class);
        servlet.setUrl(url);
    }
    if (cli.hasOption(ARG_TRIP_UPDATES_PATH)) {
        File path = new File(cli.getOptionValue(ARG_TRIP_UPDATES_PATH));
        TripUpdatesFileWriter writer = injector.getInstance(TripUpdatesFileWriter.class);
        writer.setPath(path);
    }

    if (cli.hasOption(ARG_VEHICLE_POSITIONS_URL)) {
        URL url = new URL(cli.getOptionValue(ARG_VEHICLE_POSITIONS_URL));
        VehiclePositionsServlet servlet = injector.getInstance(VehiclePositionsServlet.class);
        servlet.setUrl(url);
    }
    if (cli.hasOption(ARG_VEHICLE_POSITIONS_PATH)) {
        File path = new File(cli.getOptionValue(ARG_VEHICLE_POSITIONS_PATH));
        VehiclePositionsFileWriter writer = injector.getInstance(VehiclePositionsFileWriter.class);
        writer.setPath(path);
    }

    if (cli.hasOption(ARG_REFRESH_INTERVAL)) {
        _provider.setRefreshInterval(Integer.parseInt(cli.getOptionValue(ARG_REFRESH_INTERVAL)));
    }

    _lifecycleService.start();
}

From source file:edu.usf.cutr.gtfs_realtime.bullrunner.GtfsRealtimeTripUpdatesProducerDemoMain.java

public void run(String[] args) throws Exception {

    if (args.length == 0 || CommandLineInterfaceLibrary.wantsHelp(args)) {
        printUsage();/*  ww w .j a v  a2 s  .  c o  m*/
        System.exit(-1);
    }

    Options options = new Options();
    buildOptions(options);
    Parser parser = new GnuParser();
    CommandLine cli = parser.parse(options, args);

    Set<Module> modules = new HashSet<Module>();
    GtfsRealtimeTripUpdatesProducerDemoModule.addModuleAndDependencies(modules);

    Injector injector = Guice.createInjector(modules);
    injector.injectMembers(this);

    _provider.setUrl(new URL(
            "http://api.syncromatics.com/feed/511/Prediction/?api_key=593e3f10de49d7fec7c8ace98f0ee6d1&format=json"));
    //only for test, creat a static json for 8:32pm, August 5th, 2014
    //_provider.setUrl(new URL( "http://myweb.usf.edu/~mona2/syncromticOffLine_8_32August5.json"));

    if (cli.hasOption(ARG_TRIP_UPDATES_URL)) {
        URL url = new URL(cli.getOptionValue(ARG_TRIP_UPDATES_URL));
        GtfsRealtimeServlet servlet = injector.getInstance(GtfsRealtimeServlet.class);
        servlet.setSource(_tripUpdates);
        servlet.setUrl(url);
    }
    if (cli.hasOption(ARG_TRIP_UPDATES_PATH)) {
        File path = new File(cli.getOptionValue(ARG_TRIP_UPDATES_PATH));

        GtfsRealtimeFileWriter writer = injector.getInstance(GtfsRealtimeFileWriter.class);
        writer.setSource(_tripUpdates);
        writer.setPath(path);
    }

    if (cli.hasOption(ARG_VEHICLE_POSITIONS_URL)) {
        URL url = new URL(cli.getOptionValue(ARG_VEHICLE_POSITIONS_URL));

        GtfsRealtimeServlet servlet = injector.getInstance(GtfsRealtimeServlet.class);
        servlet.setSource(_vehiclePositions);
        servlet.setUrl(url);
    }
    if (cli.hasOption(ARG_VEHICLE_POSITIONS_PATH)) {
        File path = new File(cli.getOptionValue(ARG_VEHICLE_POSITIONS_PATH));
        GtfsRealtimeFileWriter writer = injector.getInstance(GtfsRealtimeFileWriter.class);
        writer.setSource(_vehiclePositions);
        writer.setPath(path);
    }

    _lifecycleService.start();
}

From source file:com.kurtraschke.amtkgtfsrealtime.AMTKRealtimeMain.java

public void run(String[] args) throws Exception {
    if (args.length == 0 || CommandLineInterfaceLibrary.wantsHelp(args)) {
        printUsage();/*from   w  w w.j  a  v a  2s. co  m*/
        System.exit(-1);
    }

    Options options = new Options();
    buildOptions(options);
    Daemonizer.buildOptions(options);
    Parser parser = new GnuParser();
    final CommandLine cli = parser.parse(options, args);
    Daemonizer.handleDaemonization(cli);

    Set<Module> modules = new HashSet<>();
    AMTKRealtimeModule.addModuleAndDependencies(modules);

    _injector = Guice.createInjector(new URLConverter(), new FileConverter(), new PropertiesConverter(),
            new ConfigurationModule() {
                @Override
                protected void bindConfigurations() {
                    bindEnvironmentVariables();
                    bindSystemProperties();

                    if (cli.hasOption(ARG_CONFIG_FILE)) {
                        bindProperties(new File(cli.getOptionValue(ARG_CONFIG_FILE)));
                    }
                }
            }, Rocoto.expandVariables(modules));

    _injector.injectMembers(this);

    _tripUpdatesUrl = getConfigurationValue(URL.class, "tripUpdates.url");
    if (_tripUpdatesUrl != null) {
        GtfsRealtimeServlet servlet = _injector.getInstance(GtfsRealtimeServlet.class);
        servlet.setUrl(_tripUpdatesUrl);
        servlet.setSource(_tripUpdatesExporter);

    }

    _tripUpdatesPath = getConfigurationValue(File.class, "tripUpdates.path");
    if (_tripUpdatesPath != null) {
        GtfsRealtimeFileWriter writer = _injector.getInstance(GtfsRealtimeFileWriter.class);
        writer.setPath(_tripUpdatesPath);
        writer.setSource(_tripUpdatesExporter);
    }

    _vehiclePositionsUrl = getConfigurationValue(URL.class, "vehiclePositions.url");
    if (_vehiclePositionsUrl != null) {
        GtfsRealtimeServlet servlet = _injector.getInstance(GtfsRealtimeServlet.class);
        servlet.setUrl(_vehiclePositionsUrl);
        servlet.setSource(_vehiclePositionsExporter);
    }

    _vehiclePositionsPath = getConfigurationValue(File.class, "vehiclePositions.path");
    if (_vehiclePositionsPath != null) {
        GtfsRealtimeFileWriter writer = _injector.getInstance(GtfsRealtimeFileWriter.class);
        writer.setPath(_vehiclePositionsPath);
        writer.setSource(_vehiclePositionsExporter);
    }

    _alertsUrl = getConfigurationValue(URL.class, "alerts.url");
    if (_alertsUrl != null) {
        GtfsRealtimeServlet servlet = _injector.getInstance(GtfsRealtimeServlet.class);
        servlet.setUrl(_alertsUrl);
        servlet.setSource(_alertsExporter);
    }

    _alertsPath = getConfigurationValue(File.class, "alerts.path");
    if (_alertsPath != null) {
        GtfsRealtimeFileWriter writer = _injector.getInstance(GtfsRealtimeFileWriter.class);
        writer.setPath(_alertsPath);
        writer.setSource(_alertsExporter);
    }

    _lifecycleService.start();
}

From source file:ExporterMain.java

public void run(String[] args) throws Exception {

    if (CommandLineInterfaceLibrary.wantsHelp(args)) {
        printUsage();//from w  w w.java2 s .  c  om
        System.exit(-1);
    }

    Options options = new Options();
    buildOptions(options);
    Parser parser = new GnuParser();
    CommandLine cli = parser.parse(options, args);

    Set<Module> modules = new HashSet<Module>();
    ExporterModule.addModuleAndDependencies(modules);

    Injector injector = Guice.createInjector(modules);
    injector.injectMembers(this);

    provider.setTrip_update_path(DEFAULT_TRIP_UPDATES_PATH_READ);
    provider.setVehicle_positions_path(DEFAULT_VEHICLE_POSITIONS_PATH_READ);
    provider.setAlerts_path(DEFAULT_ALERTS_PATH_READ);

    URL urlTripUpdates = new URL(DEFAULT_TRIP_UPDATES_URL);
    URL urlVehiclePositions = new URL(DEFAULT_VEHICLE_POSITIONS_URL);
    URL urlAlerts = new URL(DEFAULT_ALERTS_URL);

    if (cli.hasOption(ARG_TRIP_UPDATES_URL)) {
        urlTripUpdates = new URL(cli.getOptionValue(ARG_TRIP_UPDATES_URL));
    }
    if (cli.hasOption(ARG_TRIP_UPDATES_PATH)) {
        File path = new File(cli.getOptionValue(ARG_TRIP_UPDATES_PATH));
        TripUpdatesFileWriter writer = injector.getInstance(TripUpdatesFileWriter.class);
        writer.setPath(path);
    }
    if (cli.hasOption(ARG_TRIP_UPDATES_PATH_READ)) {
        provider.setTrip_update_path(cli.getOptionValue(ARG_TRIP_UPDATES_PATH_READ));
    }

    if (cli.hasOption(ARG_VEHICLE_POSITIONS_URL)) {
        urlVehiclePositions = new URL(cli.getOptionValue(ARG_VEHICLE_POSITIONS_URL));
    }
    if (cli.hasOption(ARG_VEHICLE_POSITIONS_PATH)) {
        File path = new File(cli.getOptionValue(ARG_VEHICLE_POSITIONS_PATH));
        VehiclePositionsFileWriter writer = injector.getInstance(VehiclePositionsFileWriter.class);
        writer.setPath(path);
    }
    if (cli.hasOption(ARG_VEHICLE_POSITIONS_PATH_READ)) {
        provider.setVehicle_positions_path(cli.getOptionValue(ARG_VEHICLE_POSITIONS_PATH_READ));
    }

    if (cli.hasOption(ARG_ALERTS_URL)) {
        urlAlerts = new URL(cli.getOptionValue(ARG_ALERTS_URL));
    }
    if (cli.hasOption(ARG_ALERTS_PATH)) {
        File path = new File(cli.getOptionValue(ARG_ALERTS_PATH));
        AlertsFileWriter writer = injector.getInstance(AlertsFileWriter.class);
        writer.setPath(path);
    }
    if (cli.hasOption(ARG_ALERTS_PATH_READ)) {
        provider.setAlerts_path(cli.getOptionValue(ARG_ALERTS_PATH_READ));
    }

    if (cli.hasOption(ARG_REFRESH_INTERVAL)) {
        provider.setRefreshInterval(Integer.parseInt(cli.getOptionValue(ARG_REFRESH_INTERVAL)));
    }

    if (cli.hasOption(ARG_CONFIG_FILE)) {
        ReadConfig.CONFIG_FILE = cli.getOptionValue(ARG_CONFIG_FILE);
    }

    TripUpdatesServlet tripUpdatesServlet = injector.getInstance(TripUpdatesServlet.class);
    tripUpdatesServlet.setUrl(urlTripUpdates);

    VehiclePositionsServlet vehiclePositionsServlet = injector.getInstance(VehiclePositionsServlet.class);
    vehiclePositionsServlet.setUrl(urlVehiclePositions);

    AlertsServlet alertsServlet = injector.getInstance(AlertsServlet.class);
    alertsServlet.setUrl(urlAlerts);

    lifecycleService.start();
}