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

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

Introduction

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

Prototype

GnuParser

Source Link

Usage

From source file:com.consol.citrus.CitrusCliTest.java

@Test
@SuppressWarnings("unchecked")
public void testMultipleTests() throws ParseException {
    reset(testngMock);//from w  w  w.  jav a 2  s  .co  m

    testngMock.setXmlSuites((List<XmlSuite>) anyObject());
    expectLastCall().andAnswer(new IAnswer<Object>() {
        public Object answer() throws Throwable {
            List<XmlSuite> suites = (List<XmlSuite>) getCurrentArguments()[0];
            Assert.assertEquals(suites.size(), 1);
            Assert.assertEquals(suites.get(0).getTests().size(), 2);
            Assert.assertEquals(suites.get(0).getName(), "citrus-test-suite");
            Assert.assertEquals(suites.get(0).getTests().get(0).getName(), "SampleTest");
            Assert.assertEquals(suites.get(0).getTests().get(1).getName(), "SampleTest");
            return null;
        }
    }).once();

    testngMock.run();
    expectLastCall().once();

    expect(testngMock.hasFailure()).andReturn(false).once();

    replay(testngMock);

    Citrus citrus = new Citrus(new GnuParser().parse(new CitrusCliOptions(),
            new String[] { "-test", "SampleTest", "SampleTest", "-testdir", "../src/citrus/tests" }));
    citrus.setTestNG(testngMock);
    citrus.run();

    verify(testngMock);
}

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  a  va  2s.  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>();
    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:com.twosigma.beaker.core.Main.java

private static CommandLine parseCommandLine(String[] args) throws ParseException {
    CommandLineParser parser = new GnuParser();
    Options opts = new Options();
    opts.addOption("h", "help", false, "print this message");
    opts.addOption(null, "disable-kerberos", false, "do not require kerberos authentication");
    opts.addOption(null, "open-browser", true, "open a web browser connected to the Beaker server");
    opts.addOption(null, "port-base", true, "main port number to use, other ports are allocated starting here");
    opts.addOption(null, "default-notebook", true, "file name to find default notebook");
    opts.addOption(null, "plugin-option", true, "pass option on to plugin");
    opts.addOption(null, "public-server", false, "allow connections from external computers");
    opts.addOption(null, "no-password", false,
            "do not require a password from external connections " + "(warning: for advanced users only!)");
    opts.addOption(null, "use-ssl-cert", true,
            "Enable SSL - requires path to cert file (both SSL options should be used)");
    opts.addOption(null, "use-ssl-key", true,
            "Enable SSL - requires path to key file (both SSL options should be used)");
    opts.addOption(null, "require-password", false, "Ask for password when connecting");
    opts.addOption(null, "password", true, "Password for public server");
    opts.addOption(null, "listen-interface", true, "Interface to listen on - requires ip address or '*'");
    opts.addOption(null, "portable", false,
            "Configuration and runtime files located in application instead of user home directory.");
    opts.addOption(null, "show-zombie-logging", false,
            "Show distracting logging by clients of previous server instances.");

    CommandLine line = parser.parse(opts, args);
    if (line.hasOption("help")) {
        new HelpFormatter().printHelp("beaker.command", opts);
        System.exit(0);/*from  w w w  .j  a  v  a2 s  .  c om*/
    }
    return line;
}

From source file:fr.ens.biologie.genomique.eoulsan.actions.CreateDesignAction.java

@Override
public void action(final List<String> arguments) {

    final Options options = makeOptions();
    final CommandLineParser parser = new GnuParser();
    String filename = "design.txt";
    int argsOptions = 0;
    boolean pairedEndMode = false;
    final List<String> sampleSheetPaths = new ArrayList<>();
    String samplesProjectName = null;
    boolean symlinks = false;
    int formatVersion = DEFAULT_DESIGN_FORMAT;

    try {/* w w  w  .j  a va2s.c  o  m*/

        // parse the command line arguments
        final CommandLine line = parser.parse(options, arguments.toArray(new String[arguments.size()]), true);

        // Pair-end option
        if (line.hasOption("paired-end")) {
            pairedEndMode = true;
            argsOptions += 1;
        }

        // Help option
        if (line.hasOption("help")) {
            help(options);
        }

        // Output option
        if (line.hasOption("o")) {

            filename = line.getOptionValue("o");
            argsOptions += 2;
        }

        // Casava design option
        if (line.hasOption("s")) {

            String[] sampleSheets = line.getOptionValues("s");
            sampleSheetPaths.addAll(Arrays.asList(sampleSheets));
            argsOptions += sampleSheets.length * 2;
        }

        // Casava project option
        if (line.hasOption("n")) {

            samplesProjectName = line.getOptionValue("n");
            argsOptions += 2;
        }

        // Symbolic links option
        if (line.hasOption("symlinks")) {

            symlinks = true;
            argsOptions++;
        }

        // Eoulsan design format version option
        if (line.hasOption("f")) {

            try {
                formatVersion = Integer.parseInt(line.getOptionValue("f").trim());
            } catch (NumberFormatException e) {
                Common.errorExit(e, "Invalid Eoulsan design format version: " + e.getMessage());
            }
            argsOptions += 2;
        }

    } catch (ParseException e) {
        Common.errorExit(e, "Error while parsing command line arguments: " + e.getMessage());
    }

    // Write log entries
    Main.getInstance().flushLog();

    Design design = null;
    final DataFile designFile = new DataFile(filename);

    try {

        final List<String> newArgs = arguments.subList(argsOptions, arguments.size());

        final DesignBuilder db = new DesignBuilder();

        // Add all the files of a Casava design if Casava design path is defined
        for (String sampleSheetPath : sampleSheetPaths) {
            db.addBcl2FastqSamplesheetProject(new File(sampleSheetPath), samplesProjectName);
        }

        // Add files in the command line
        db.addFiles(newArgs);

        design = db.getDesign(pairedEndMode);

        if (symlinks) {
            DesignUtils.replaceLocalPathBySymlinks(design, designFile.getParent());
        }

    } catch (EoulsanException | IOException e) {
        Common.errorExit(e, "Error: " + e.getMessage());
    }

    if (design.getSamples().isEmpty()) {
        Common.showErrorMessageAndExit(
                "Error: Nothing to create, no file found.\n" + "  Use the -h option to get more information.\n"
                        + "usage: " + Globals.APP_NAME_LOWER_CASE + " createdesign files");

    }

    try {

        if (designFile.exists()) {
            throw new IOException("Output design file " + designFile + " already exists");
        }

        final DesignWriter dw;

        switch (formatVersion) {

        case 1:
            dw = new Eoulsan1DesignWriter(designFile.create());
            break;

        case 2:
            dw = new Eoulsan2DesignWriter(designFile.create());
            break;

        default:
            Common.showErrorMessageAndExit("Unknown Eoulsan design format version: " + formatVersion);
            return;
        }

        dw.write(design);

    } catch (IOException e) {
        Common.errorExit(e, "File not found: " + e.getMessage());
    }

}

From source file:fr.ens.biologie.genomique.eoulsan.actions.UploadS3Action.java

@Override
public void action(final List<String> arguments) {

    System.err.println(/*  w  w w . j ava2s.  c o m*/
            "WARNING: the action \"" + getName() + "\" is currently under development for the next version of "
                    + Globals.APP_NAME + " and may actually not work.");

    final Options options = makeOptions();
    final CommandLineParser parser = new GnuParser();

    int argsOptions = 0;

    try {

        // parse the command line arguments
        final CommandLine line = parser.parse(options, arguments.toArray(new String[arguments.size()]), true);

        // Help option
        if (line.hasOption("help")) {
            help(options);
        }

    } catch (ParseException e) {
        Common.errorExit(e, "Error while parsing command line arguments: " + e.getMessage());
    }

    if (arguments.size() != argsOptions + 3) {
        help(options);
    }

    final File paramFile = new File(arguments.get(argsOptions));
    final File designFile = new File(arguments.get(argsOptions + 1));
    final DataFile s3Path = new DataFile(
            StringUtils.replacePrefix(arguments.get(argsOptions + 2), "s3:/", "s3n:/"));
    final String jobDescription = "Upload data to " + s3Path;

    // Upload data
    run(paramFile, designFile, s3Path, jobDescription);
}

From source file:com.consol.citrus.admin.executor.ClasspathTestExecutor.java

/**
 * {@inheritDoc}/*from w  ww  . j  a  v  a 2  s . c o m*/
 */
public void execute(String testName) throws ParseException {
    Citrus citrus = new Citrus(new GnuParser().parse(new CitrusCliOptions(), new String[] { "-test", testName,
            "-testdir", new File(configService.getProjectHome()).getAbsolutePath() }));
    citrus.run();

    Map<String, TestReporter> reporters = appContextHolder.getApplicationContext()
            .getBeansOfType(TestReporter.class);
    for (TestReporter reporter : reporters.values()) {
        reporter.clearTestResults();
    }
}

From source file:com.kijes.ela.cli.CommandLineOptions.java

public void parse(String[] args) throws ParseException {
    commandLine = new GnuParser().parse(getProgramOptions(), args);
}

From source file:gov.nasa.jpl.mudrod.main.MudrodEngine.java

/**
 * Main program invocation. Accepts one argument denoting location (on disk)
 * to a log file which is to be ingested. Help will be provided if invoked
 * with incorrect parameters./*from   w w  w. jav a  2 s  . c  o m*/
 *
 * @param args
 *          {@link java.lang.String} array contaning correct parameters.
 */
public static void main(String[] args) {
    // boolean options
    Option helpOpt = new Option("h", "help", false, "show this help message");

    // log ingest (preprocessing + processing)
    Option logIngestOpt = new Option("l", LOG_INGEST, false, "begin log ingest");
    // metadata ingest (preprocessing + processing)
    Option metaIngestOpt = new Option("m", META_INGEST, false, "begin metadata ingest");
    // ingest both log and metadata
    Option fullIngestOpt = new Option("f", FULL_INGEST, false, "begin full ingest Mudrod workflow");
    // processing only, assuming that preprocessing results is in dataDir
    Option processingOpt = new Option("p", PROCESSING, false, "begin processing with preprocessing results");

    // argument options
    Option dataDirOpt = OptionBuilder.hasArg(true).withArgName("/path/to/data/directory").hasArgs(1)
            .withDescription("the data directory to be processed by Mudrod").withLongOpt("dataDirectory")
            .isRequired().create(DATA_DIR);

    Option esHostOpt = OptionBuilder.hasArg(true).withArgName("host_name").hasArgs(1)
            .withDescription("elasticsearch cluster unicast host").withLongOpt("elasticSearchHost")
            .isRequired(false).create(ES_HOST);

    Option esTCPPortOpt = OptionBuilder.hasArg(true).withArgName("port_num").hasArgs(1)
            .withDescription("elasticsearch transport TCP port").withLongOpt("elasticSearchTransportTCPPort")
            .isRequired(false).create(ES_TCP_PORT);

    Option esPortOpt = OptionBuilder.hasArg(true).withArgName("port_num").hasArgs(1)
            .withDescription("elasticsearch HTTP/REST port").withLongOpt("elasticSearchHTTPPort")
            .isRequired(false).create(ES_HTTP_PORT);

    // create the options
    Options options = new Options();
    options.addOption(helpOpt);
    options.addOption(logIngestOpt);
    options.addOption(metaIngestOpt);
    options.addOption(fullIngestOpt);
    options.addOption(processingOpt);
    options.addOption(dataDirOpt);
    options.addOption(esHostOpt);
    options.addOption(esTCPPortOpt);
    options.addOption(esPortOpt);

    CommandLineParser parser = new GnuParser();
    try {
        CommandLine line = parser.parse(options, args);
        String processingType = null;

        if (line.hasOption(LOG_INGEST)) {
            processingType = LOG_INGEST;
        } else if (line.hasOption(PROCESSING)) {
            processingType = PROCESSING;
        } else if (line.hasOption(META_INGEST)) {
            processingType = META_INGEST;
        } else if (line.hasOption(FULL_INGEST)) {
            processingType = FULL_INGEST;
        }

        String dataDir = line.getOptionValue(DATA_DIR).replace("\\", "/");
        if (!dataDir.endsWith("/")) {
            dataDir += "/";
        }

        MudrodEngine me = new MudrodEngine();
        me.loadConfig();
        me.props.put(DATA_DIR, dataDir);

        if (line.hasOption(ES_HOST)) {
            String esHost = line.getOptionValue(ES_HOST);
            me.props.put(MudrodConstants.ES_UNICAST_HOSTS, esHost);
        }

        if (line.hasOption(ES_TCP_PORT)) {
            String esTcpPort = line.getOptionValue(ES_TCP_PORT);
            me.props.put(MudrodConstants.ES_TRANSPORT_TCP_PORT, esTcpPort);
        }

        if (line.hasOption(ES_HTTP_PORT)) {
            String esHttpPort = line.getOptionValue(ES_HTTP_PORT);
            me.props.put(MudrodConstants.ES_HTTP_PORT, esHttpPort);
        }

        me.es = new ESDriver(me.getConfig());
        me.spark = new SparkDriver(me.getConfig());
        loadFullConfig(me, dataDir);
        if (processingType != null) {
            switch (processingType) {
            case PROCESSING:
                me.startProcessing();
                break;
            case LOG_INGEST:
                me.startLogIngest();
                break;
            case META_INGEST:
                me.startMetaIngest();
                break;
            case FULL_INGEST:
                me.startFullIngest();
                break;
            default:
                break;
            }
        }
        me.end();
    } catch (Exception e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(
                "MudrodEngine: 'dataDir' argument is mandatory. " + "User must also provide an ingest method.",
                options, true);
        LOG.error("Error whilst parsing command line.", e);
    }
}

From source file:com.trackplus.tools.DBConnectionTester.java

private void parseCommandLineArguments(String[] args) {
    Option option = new Option("h", "Print this help message.");
    option.setLongOpt("help");
    options.addOption(option);//  www . j a va 2 s  .  c o  m

    option = new Option("v", "Turn on verbose output.");
    option.setLongOpt("verbose");
    options.addOption(option);

    options.addOption(newOption("u", "Database user name.", "user", "database user"));
    options.addOption(newOption("c", "JDBC connector class.", "jdbc", "class name"));
    options.addOption(newOption("url", "Use this user name for login.", "url", "JDBC URL"));

    options.addOption(newOption("p", "Database user password.", "password", "password"));
    option.setOptionalArg(true);
    options.addOption(option);

    CommandLineParser parser = new GnuParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println("Error: Parsing failed. Reason: " + e.getMessage());
        System.exit(1);
    }

    if (line != null) {
        if (line.hasOption("h")) {
            printUsage();
            System.exit(0);
        }

        if (line.hasOption("v")) {
            verbose = true;
        }

        if (line.hasOption("u")) {
            user = line.getOptionValue("u", "");
        }

        if (line.hasOption("c")) {
            jdbc = line.getOptionValue("c", "");
        }

        if (line.hasOption("url")) {
            url = line.getOptionValue("url", "");
        }

        if (line.hasOption("p")) {
            password = line.getOptionValue("p");
            if (password == null) {
                try {
                    System.out.print("Password: ");
                    System.out.flush();
                    password = new BufferedReader(new InputStreamReader(System.in)).readLine();
                } catch (IOException e) {
                    System.out.println();
                    System.exit(1);
                }
            }
        }
    }
    return;
}

From source file:com.laex.cg2d.render.MyGdxGameDesktop.java

/**
 * Parses the./* w ww.  j  a v a2  s . c o m*/
 * 
 * @param options
 *          the options
 * @param args
 *          the args
 * @return the map
 * @throws ParseException
 *           the parse exception
 */
private static Map<String, Object> parse(Options options, String args[]) throws ParseException {
    Map<String, Object> prefs = new HashMap<String, Object>();

    CommandLineParser parse = new GnuParser();
    CommandLine cmd = parse.parse(options, args);

    // CG2D File
    if (cmd.hasOption("screenFile")) {
        prefs.put(PreferenceConstants.SCREEN_FILE, cmd.getOptionValue("screenFile"));
    }

    // screen controller file
    if (cmd.hasOption("screenController")) {
        prefs.put(PreferenceConstants.SCREEN_CONTROLLER, cmd.getOptionValue("screenController"));
    }

    return prefs;
}