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:org.onebusaway.gtfs_realtime.visualizer.VisualizerMain.java

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

    if (args.length == 0 || CommandLineInterfaceLibrary.wantsHelp(args)) {
        printUsage();//from   ww w. j ava2 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>();
    VisualizerModule.addModuleAndDependencies(modules);

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

    VisualizerService service = injector.getInstance(VisualizerService.class);
    service.setVehiclePositionsUrl(new URL(cli.getOptionValue(ARG_VEHICLE_POSITIONS_URL)));
    injector.getInstance(VisualizerServer.class);

    LifecycleService lifecycleService = injector.getInstance(LifecycleService.class);
    lifecycleService.start();
}

From source file:org.onebusaway.phone.client.SimplePhoneClient.java

public static void main(String[] args) throws IOException, ParseException {

    Parser parser = new GnuParser();
    Options options = buildOptions();/*ww  w  . ja  va2  s. c o  m*/
    CommandLine cli = parser.parse(options, args);

    String host = cli.getOptionValue(ARG_HOSTNAME, "localhost");
    int port = Integer.parseInt(cli.getOptionValue(ARG_PORT, "8001"));
    String callerId = cli.getOptionValue(ARG_CALLER_ID, "2000");

    AgiClientScriptImpl script = new AgiClientScriptImpl();
    setupGui(script);

    DefaultAgiClient client = new DefaultAgiClient(host, port, script);
    client.setCallerId(callerId);
    client.setNetworkScript("index.agi");
    client.run();
}

From source file:org.onebusaway.phone.PhoneServerMain.java

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

    Options options = new Options();
    Daemonizer.buildOptions(options);/*  ww w. j  a  va 2 s.  c om*/
    options.addOption(ARG_RESOURCES, true, "resources");

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

    boolean isDaemon = Daemonizer.handleDaemonization(cli);

    List<String> resources = getResources(cli);
    ContainerLibrary.createContext(resources);

    if (isDaemon) {
        // We need a running non-daemon thread to avoid having the program
        // immediately exit
        new Thread(new Runnable() {
            @Override
            public synchronized void run() {
                try {
                    wait();
                } catch (InterruptedException e) {

                }
            }
        }).start();
    } else {
        StopButtonService button = new StopButtonService();
        button.start();
    }
}

From source file:org.onebusaway.quickstart.bootstrap.WebappBootstrapMain.java

public static void run(URL warUrl, boolean consoleMode, String[] args) throws Exception {

    if (args.length == 0 || isHelp(args)) {
        BootstrapCommon.printUsage(WebappBootstrapMain.class, "usage-webapp.txt");
        System.exit(-1);/* ww  w.  j a  va2s  . co m*/
    }

    Options options = createOptions();
    Parser parser = new GnuParser();

    CommandLine cli = parser.parse(options, args);
    args = cli.getArgs();

    if (args.length != 1) {
        BootstrapCommon.printUsage(WebappBootstrapMain.class, "usage-webapp.txt");
        System.exit(-1);
    }

    String bundlePath = args[0];
    System.setProperty("bundlePath", bundlePath);

    int port = 8080;
    if (cli.hasOption(ARG_PORT))
        port = Integer.parseInt(cli.getOptionValue(ARG_PORT));

    Server server = new Server();
    SocketConnector connector = new SocketConnector();

    // Set some timeout options to make debugging easier.
    connector.setMaxIdleTime(1000 * 60 * 60);
    connector.setSoLingerTime(-1);
    connector.setPort(port);
    server.setConnectors(new Connector[] { connector });

    WebAppContext context = new WebAppContext();
    context.setContextPath("/");
    // context.setWelcomeFiles(new String[] {"index.action"});
    context.setWar(warUrl.toExternalForm());
    // We store the command line object as a webapp context attribute so it can
    // be used by the context loader to inject additional beans as needed
    context.setAttribute(WebappCommon.COMMAND_LINE_CONTEXT_ATTRIBUTE, cli);

    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] { new WelcomeFileHandler(context), context });

    server.setHandler(handlers);

    /**
     * We specify a Jetty override descriptor to inject additional definitions
     * into our web.xml configuration. Specifically, we specify a
     * <context-param> to specify the "contextClass" that will be used to create
     * our Spring ApplicationContext. We create a custom version that will
     * inject additional beans based on command-line arguments.
     */
    context.addOverrideDescriptor("/WEB-INF/override-web.xml");

    if (cli.hasOption(WebappCommon.ARG_BUILD)) {
        System.setProperty("hibernate.hbm2ddl.auto", "update");
        System.setProperty("bundleCacheDir", bundlePath + "/cache");
        System.setProperty("gtfsPath", cli.getOptionValue(WebappCommon.ARG_GTFS_PATH));
        context.addOverrideDescriptor("/WEB-INF/builder-override-web.xml");
    }

    try {
        server.start();

        System.err.println("=============================================================");
        System.err.println("=");
        System.err.println("= Your OneBusAway instance has started.  Browse to:");
        System.err.println("=");
        System.err.println("= http://localhost:8080/");
        System.err.println("=");
        System.err.println("= to see your instance in action.");
        if (consoleMode) {
            System.err.println("=");
            System.err.println("= When you are finished, press return to exit gracefully...");
        }
        System.err.println("=============================================================");

        if (consoleMode) {
            System.in.read();
            server.stop();
            server.join();
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(100);
    }
}

From source file:org.onebusaway.siri.repeater.SiriRepeaterCommandLineConfiguration.java

public Injector configure(String[] args) throws Exception {

    if (needsHelp(args)) {
        printUsage();//from w w w  .  jav  a2 s  . c om
        System.exit(0);
    }

    Options options = new Options();
    buildOptions(options);

    Daemonizer.buildOptions(options);

    Parser parser = new PosixParser();
    CommandLine cli = parser.parse(options, args);

    Daemonizer.handleDaemonization(cli);

    args = cli.getArgs();

    if (args.length == 0 && !cli.hasOption(ARG_NO_SUBSCRIPTIONS)) {
        printUsage();
        System.exit(-1);
    }

    Set<Module> modules = new HashSet<Module>();
    SiriCoreModule.addModuleAndDependencies(modules);
    SiriJettyModule.addModuleAndDependencies(modules);
    Injector injector = Guice.createInjector(modules);

    handleCommandLineOptions(cli, injector);

    return injector;
}

From source file:org.onebusaway.transit_data_federation.bundle.FederatedTransitDataBundleCreatorMain.java

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

    try {//from w  ww . ja  va2s  .  com
        Parser parser = new GnuParser();

        Options options = new Options();
        buildOptions(options);

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

        String[] remainingArgs = commandLine.getArgs();

        if (remainingArgs.length < 2) {
            printUsage();
            System.exit(-1);
        }

        FederatedTransitDataBundleCreator creator = new FederatedTransitDataBundleCreator();

        Map<String, BeanDefinition> beans = new HashMap<String, BeanDefinition>();
        creator.setContextBeans(beans);

        List<GtfsBundle> gtfsBundles = new ArrayList<GtfsBundle>();
        List<String> contextPaths = new ArrayList<String>();

        for (int i = 0; i < remainingArgs.length - 1; i++) {
            File path = new File(remainingArgs[i]);
            if (path.isDirectory() || path.getName().endsWith(".zip")) {
                GtfsBundle gtfsBundle = new GtfsBundle();
                gtfsBundle.setPath(path);
                gtfsBundles.add(gtfsBundle);
            } else {
                contextPaths.add("file:" + path);
            }
        }

        if (!gtfsBundles.isEmpty()) {
            BeanDefinitionBuilder bean = BeanDefinitionBuilder.genericBeanDefinition(GtfsBundles.class);
            bean.addPropertyValue("bundles", gtfsBundles);
            beans.put("gtfs-bundles", bean.getBeanDefinition());
        }

        if (commandLine.hasOption(ARG_USE_DATABASE_FOR_GTFS)) {
            contextPaths.add("classpath:org/onebusaway/gtfs/application-context.xml");
        } else {
            BeanDefinitionBuilder bean = BeanDefinitionBuilder
                    .genericBeanDefinition(GtfsRelationalDaoImpl.class);
            beans.put("gtfsRelationalDaoImpl", bean.getBeanDefinition());
        }

        if (commandLine.hasOption(ARG_DATASOURCE_URL)) {
            String dataSourceUrl = commandLine.getOptionValue(ARG_DATASOURCE_URL);
            BeanDefinitionBuilder bean = BeanDefinitionBuilder
                    .genericBeanDefinition(DriverManagerDataSource.class);
            bean.addPropertyValue("url", dataSourceUrl);
            if (commandLine.hasOption(ARG_DATASOURCE_DRIVER_CLASS_NAME))
                bean.addPropertyValue("driverClassName",
                        commandLine.getOptionValue(ARG_DATASOURCE_DRIVER_CLASS_NAME));
            if (commandLine.hasOption(ARG_DATASOURCE_USERNAME))
                bean.addPropertyValue("username", commandLine.getOptionValue(ARG_DATASOURCE_USERNAME));
            if (commandLine.hasOption(ARG_DATASOURCE_PASSWORD))
                bean.addPropertyValue("password", commandLine.getOptionValue(ARG_DATASOURCE_PASSWORD));
            beans.put("dataSource", bean.getBeanDefinition());
        }

        if (commandLine.hasOption(ARG_OSM)) {
            File osmPath = new File(commandLine.getOptionValue(ARG_OSM));
            BeanDefinitionBuilder bean = BeanDefinitionBuilder
                    .genericBeanDefinition(FileBasedOpenStreetMapProviderImpl.class);
            bean.addPropertyValue("path", osmPath);
            beans.put("osmProvider", bean.getBeanDefinition());
        }

        File outputPath = new File(remainingArgs[remainingArgs.length - 1]);

        if (commandLine.hasOption(ARG_ONLY_IF_DNE) && outputPath.exists()) {
            System.err.println("Bundle path already exists.  Exiting...");
            System.exit(0);
        }

        if (commandLine.hasOption(ARG_RANDOMIZE_CACHE_DIR))
            creator.setRandomizeCacheDir(true);

        if (commandLine.hasOption(ARG_BUNDLE_KEY)) {
            String key = commandLine.getOptionValue(ARG_BUNDLE_KEY);
            creator.setBundleKey(key);
        }

        /**
         * Optionally override any system properties (ok this duplicates existing
         * functionality, yes, but it allows for -D arguments after the main
         * class)
         */
        if (commandLine.hasOption("D")) {
            Properties props = commandLine.getOptionProperties("D");
            for (Object key : props.keySet()) {
                String propName = (String) key;
                String propValue = props.getProperty(propName);
                System.setProperty(propName, propValue);
            }
        }

        /**
         * Optionally override any system properties (ok this duplicates existing
         * functionality, yes, but it allows for -D arguments after the main
         * class)
         */
        if (commandLine.hasOption("P")) {
            Properties props = commandLine.getOptionProperties("P");
            creator.setAdditionalBeanPropertyOverrides(props);
        }

        setStagesToSkip(commandLine, creator);

        creator.setOutputPath(outputPath);
        creator.setContextPaths(contextPaths);

        try {

            if (commandLine.hasOption(ARG_ADDITIONAL_RESOURCES_DIRECTORY)) {
                File additionalResourceDirectory = new File(
                        commandLine.getOptionValue(ARG_ADDITIONAL_RESOURCES_DIRECTORY));
                copyFiles(additionalResourceDirectory, outputPath);
            }

            creator.run();
        } catch (Exception ex) {
            _log.error("error building transit data bundle", ex);
            System.exit(-1);
        }
    } catch (ParseException ex) {
        System.err.println(ex.getLocalizedMessage());
        printUsage();
        System.exit(-1);
    }

    System.exit(0);
}

From source file:org.onebusaway.transit_data_federation.bundle.tasks.transfer_pattern.utilities.TransferPatternCounterMain.java

public void run(String[] args) throws ParseException, IOException {
    Options options = createOptions();/*from  w w w  .  java  2  s.c o  m*/
    Parser parser = new GnuParser();
    CommandLine cli = parser.parse(options, args);
    args = cli.getArgs();

    if (args.length == 0) {
        usage();
        System.exit(-1);
    }

    Map<String, Integer> depths = new HashMap<String, Integer>();
    Counter<String> counts = new Counter<String>();

    List<String> paths = new ArrayList<String>();
    for (String arg : args) {
        File f = new File(arg);
        if (f.isDirectory()) {
            FederatedTransitDataBundle bundle = new FederatedTransitDataBundle(f);
            for (File path : bundle.getAllTransferPatternsPaths())
                paths.add(path.getAbsolutePath());
        } else {
            paths.add(arg);
        }
    }

    for (String path : paths) {

        System.err.println("# " + path);

        BufferedReader reader = new BufferedReader(IOLibrary.getPathAsReader(path));
        String line = null;

        while ((line = reader.readLine()) != null) {

            if (line.length() == 0)
                continue;

            List<String> tokens = CSVLibrary.parse(line);
            String index = tokens.get(0);
            String stopId = tokens.get(1);
            String parentIndex = null;
            if (tokens.size() > 3)
                parentIndex = tokens.get(3);

            int depth = 0;

            if (parentIndex == null) {
                depths.clear();
                depths.put(index, 0);
            }

            if (parentIndex != null) {
                depth = depths.get(parentIndex) + 1;
                depths.put(index, depth);
            }

            if (depth > 0 && depth % 2 == 0)
                counts.increment(stopId);
        }

        reader.close();
    }

    List<String> keys = counts.getSortedKeys();
    for (String key : keys)
        System.out.println(counts.getCount(key) + "\t" + key);
}

From source file:org.onebusaway.transit_data_federation.bundle.tasks.transfer_pattern.utilities.TransferPatternUtilityMain.java

public void run(String[] args) throws ParseException, IOException {
    Options options = createOptions();//from   w  w  w.  j  ava 2 s.c om
    Parser parser = new GnuParser();
    CommandLine cli = parser.parse(options, args);
    args = cli.getArgs();

    if (args.length == 0) {
        usage();
        System.exit(-1);
    }

    boolean pruneDirectTransfers = cli.hasOption(ARG_PRUNE_DIRECT_TRANSFERS);

    Map<String, Integer> hubStops = loadHubStops(cli);
    Set<String> originStopsWeHaveSeen = new HashSet<String>();

    Set<String> pruneFromParent = new HashSet<String>();
    Map<String, Integer> depths = new HashMap<String, Integer>();

    Map<String, String> directTransfers = new HashMap<String, String>();

    for (String arg : args) {

        System.err.println("# " + arg);

        BufferedReader reader = new BufferedReader(IOLibrary.getPathAsReader(arg));
        String line = null;

        int originHubDepth = Integer.MAX_VALUE;
        String originIndex = null;
        boolean skipTree = false;

        while ((line = reader.readLine()) != null) {

            if (line.length() == 0)
                continue;

            List<String> tokens = CSVLibrary.parse(line);
            String index = tokens.get(0);
            String stopId = tokens.get(1);
            String type = tokens.get(2);
            String parentIndex = null;
            if (tokens.size() > 3)
                parentIndex = tokens.get(3);

            int depth = 0;
            boolean isOrigin = false;

            if (parentIndex == null) {

                isOrigin = true;
                originHubDepth = hubDepth(hubStops, stopId);

                _idMapping.clear();
                pruneFromParent.clear();
                depths.clear();

                directTransfers.clear();

                depths.put(index, 0);

                skipTree = false;

                if (originStopsWeHaveSeen.add(stopId)) {
                    System.err.println("#   Origin Stop: " + stopId);
                } else {
                    System.err.println("#   Skipping duplicate origin stop: " + stopId);
                    skipTree = true;
                }
            }

            if (skipTree)
                continue;

            if (parentIndex != null) {
                if (pruneFromParent.contains(parentIndex)) {
                    pruneFromParent.add(index);
                    continue;
                }

                /**
                 * If we had an uncommited parent, commit it
                 */
                String parentStopId = directTransfers.remove(parentIndex);
                if (parentStopId != null)
                    commitLine(parentIndex, parentStopId, "0", originIndex);

                depth = depths.get(parentIndex) + 1;
                depths.put(index, depth);

                String newParentIndex = _idMapping.get(parentIndex);
                tokens.set(3, newParentIndex);
                parentIndex = newParentIndex;
            }

            int hubDepth = hubDepth(hubStops, stopId);
            if ((depth % 2) == 0 && hubDepth < originHubDepth) {
                pruneFromParent.add(index);
                type = "2";
            }

            if (pruneDirectTransfers && depth == 1) {
                directTransfers.put(index, stopId);
            } else {
                String newIndex = commitLine(index, stopId, type, parentIndex);

                if (isOrigin)
                    originIndex = newIndex;
            }
        }

        reader.close();
    }

}

From source file:org.onebusaway.transit_data_federation.bundle.utilities.GtfsComputePolylineBoundaryForStopsMain.java

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

    try {//ww  w. java2s.c  o m
        Parser parser = new GnuParser();

        Options options = new Options();
        buildOptions(options);

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

        String[] remainingArgs = commandLine.getArgs();

        if (remainingArgs.length < 2) {
            printUsage();
            System.exit(-1);
        }

        List<GtfsBundle> bundles = getGtfsBundlesFromCommandLine(remainingArgs);
        EFormat format = getFormat(commandLine);

        StopToPolygonEntityHandler handler = new StopToPolygonEntityHandler(2500);

        for (GtfsBundle bundle : bundles) {
            System.err.println(bundle.getPath());
            GtfsReader reader = new GtfsReader();
            reader.addEntityHandler(handler);
            reader.setInputLocation(bundle.getPath());
            if (bundle.getDefaultAgencyId() != null)
                reader.setDefaultAgencyId(bundle.getDefaultAgencyId());
            reader.readEntities(Stop.class);
        }

        PrintWriter out = getOutputAsPrinter(remainingArgs[remainingArgs.length - 1]);

        switch (format) {
        case OSM:
            handleOutputAsOSMPolygon(out, handler);
            break;
        case TEXT:
            handleOutputAsText(out, handler);
            break;
        }

        out.close();

    } catch (ParseException ex) {
        System.err.println(ex.getLocalizedMessage());
        printUsage();
        System.exit(-1);
    }

    System.exit(0);
}

From source file:org.onebusaway.transit_data_federation.bundle.utilities.GtfsStopsForMergingMain.java

public static void main(String[] args) throws IOException, ParseException {

    Options options = new Options();
    options.addOption(ARG_DISTANCE, true, "");
    options.addOption(ARG_CONSOLIDATED, true, "");

    Parser parser = new GnuParser();
    CommandLine cli = parser.parse(options, args);
    args = cli.getArgs();//from  ww w.  jav a2  s.  c om

    if (args.length < 5) {
        usage();
        System.exit(-1);
    }

    double distanceThreshold = 20;
    if (cli.hasOption(ARG_DISTANCE))
        distanceThreshold = Double.parseDouble(cli.getOptionValue(ARG_DISTANCE));

    TreeUnionFind<AgencyAndId> existingConsolidatedStops = new TreeUnionFind<AgencyAndId>();
    if (cli.hasOption(ARG_CONSOLIDATED))
        existingConsolidatedStops = loadExistingConsolidatedStops(cli.getOptionValue(ARG_CONSOLIDATED));

    PrintWriter writer = getOutputAsWriter(args[args.length - 1]);

    TreeUnionFind<AgencyAndId> union = new TreeUnionFind<AgencyAndId>();
    List<Collection<Stop>> allStops = new ArrayList<Collection<Stop>>();

    for (int i = 0; i < args.length - 1; i += 2) {
        String path = args[i];
        String agencyId = args[i + 1];
        Collection<Stop> stops = readStopsFromGtfsPath(path, agencyId);

        for (Collection<Stop> previousStops : allStops) {
            for (Stop stopA : previousStops) {
                for (Stop stopB : stops) {
                    double d = SphericalGeometryLibrary.distance(stopA.getLat(), stopA.getLon(), stopB.getLat(),
                            stopB.getLon());
                    if (d < distanceThreshold
                            && !existingConsolidatedStops.isSameSet(stopA.getId(), stopB.getId())) {
                        union.union(stopA.getId(), stopB.getId());
                    }
                }
            }
        }

        allStops.add(stops);
    }

    for (Set<AgencyAndId> set : union.getSetMembers()) {
        Set<Sentry> existing = new HashSet<Sentry>();
        boolean first = true;
        for (AgencyAndId stopId : set) {
            if (first)
                first = false;
            else
                writer.print(' ');
            if (existingConsolidatedStops.contains(stopId))
                existing.add(existingConsolidatedStops.find(stopId));
            writer.print(AgencyAndIdLibrary.convertToString(stopId));
        }
        writer.println();
        for (Sentry sentry : existing)
            writer.println("  => " + existingConsolidatedStops.members(sentry));
        writer.flush();
    }
}