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

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

Introduction

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

Prototype

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

Source Link

Usage

From source file:org.ihtsdo.otf.snomed.loader.GraphLoader.java

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

    DefaultParser p = new DefaultParser();

    CommandLine cli = null;// w  ww .ja v  a 2  s  . co  m
    try {

        cli = p.parse(DefaultParser.options, args);

    } catch (UnrecognizedOptionException e) {

        System.out.println(USAGE);
    }

    String dbConfig = cli.getOptionValue("config");

    validate(dbConfig, "Titan db configuration is required to initialize database");

    String type = cli.getOptionValue("type");
    validateType(type, "Data load type is required. Specify either SNAPSHOT or FULL or RDF or DELTA");

    //validate file format and type

    //validateFiles(cli, "No data file specified");

    TitanGraph g = null;
    try {

        g = openGraph(dbConfig);

        if (g == null) {

            throw new IllegalArgumentException("Could not get graph instance");
        }

        switch (LoadType.valueOf(type)) {

        case full:
            Rf2FullFeedLoader fLoader = new Rf2FullFeedLoader(g);
            if (!StringUtils.isBlank(cli.getOptionValue("bSize"))) {

                fLoader.setBufferSize(Integer.parseInt(cli.getOptionValue("bSize")));

            }

            FileType[] ffTypes = FileType.values();

            for (int i = 0; i < ffTypes.length; i++) {

                if (!ffTypes[i].equals(FileType.nt)) {

                    FileType fType = ffTypes[i];
                    LOGGER.info("Loading file type {}", fType.toString());
                    String file = cli.getOptionValue(fType.toString());
                    LOGGER.info("Loading file  {}", file);

                    if (!StringUtils.isBlank(file)) {

                        fLoader.load(file);

                    }

                }
            }

            break;

        case snapshot:
            Rf2SnapshotLoader loader = new Rf2SnapshotLoader(g);
            if (!StringUtils.isBlank(cli.getOptionValue("bSize"))) {

                loader.setBufferSize(Integer.parseInt(cli.getOptionValue("bSize")));

            }
            if (!StringUtils.isBlank(cli.getOptionValue("reload"))) {

                loader.setReload(Boolean.parseBoolean(cli.getOptionValue("reload")));

            }

            FileType[] fTypes = FileType.values();

            for (int i = 0; i < fTypes.length; i++) {

                if (!fTypes[i].equals(FileType.nt)) {

                    FileType fType = fTypes[i];
                    LOGGER.info("Loading file type {}", fType.toString());
                    String file = cli.getOptionValue(fType.toString());
                    LOGGER.info("Loading file  {}", file);

                    if (!StringUtils.isBlank(file)) {

                        loader.load(file);

                    }

                }
            }

            break;

        case audit:
            Rf2SnapshotAuditor auditor = new Rf2SnapshotAuditor(g);
            if (!StringUtils.isBlank(cli.getOptionValue("bSize"))) {

                auditor.setBufferSize(Integer.parseInt(cli.getOptionValue("bSize")));

            }

            if (!StringUtils.isBlank(cli.getOptionValue("reload"))) {

                auditor.setReload(Boolean.parseBoolean(cli.getOptionValue("reload")));

            }

            FileType[] afTypes = FileType.values();

            for (int i = 0; i < afTypes.length; i++) {

                if (!afTypes[i].equals(FileType.nt)) {

                    FileType fType = afTypes[i];
                    LOGGER.info("Auditing file type {}", fType.toString());
                    String file = cli.getOptionValue(fType.toString());
                    LOGGER.info("Auditing file  {}", file);

                    if (!StringUtils.isBlank(file)) {

                        auditor.setSubType(cli.getOptionValue("subType"));
                        auditor.audit(file);

                    }

                }
            }

            break;

        default:
            LOGGER.info("Nothing to load");
            break;
        }

        LOGGER.info("Finished loading");

    } catch (Exception e) {

        e.printStackTrace();

    } finally {

        if (g != null) {

            g.shutdown();

        }
    }

}

From source file:org.moe.cli.Main.java

public static void main(String[] argc) {
    try {/*from  www  . j  a  v a  2 s .co m*/
        System.out.println("wrapnatjgen running...");
        configureLogger();

        DefaultParser parser = new DefaultParser();
        CommandLine cmd = parser.parse(OptionsHandler.getAvalibleOptions(), argc);

        IExecutor executor = ExecutorManager.getExecutorByParams(cmd);

        if (executor != null) {
            executor.execute();
        }

        System.exit(0);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.exit(-1);
    }
}

From source file:org.moe.cli.ParameterParserTest.java

private CommandLine parseArgs(String[] args) throws ParseException {
    DefaultParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(OptionsHandler.getAvalibleOptions(), args);
    return cmd;//from   w w w  . j  a v  a2  s  .c  om
}

From source file:org.tallison.gramreaper.ingest.BuildIndex.java

public static void main(String[] args) throws Exception {
    DefaultParser parser = new DefaultParser();
    CommandLine commandLine = null;//from w  w  w.  ja va  2 s  . c o m
    try {
        commandLine = parser.parse(OPTIONS, args);
    } catch (ParseException e) {
        USAGE();
        return;
    }

    IndexSchema indexSchema = IndexSchema.load(Paths.get(commandLine.getOptionValue('s')));
    Indexer indexer = Indexer.build(Paths.get(commandLine.getOptionValue("idx")),
            indexSchema.getIndexAnalyzer(), indexSchema.getDefinedFields());

    Runner runner = null;
    if (commandLine.hasOption('i')) {
        Path inputFileOrDir = Paths.get(commandLine.getOptionValue('i'));
        if (Files.isDirectory(inputFileOrDir)) {
            runner = new DirectoryReaderRunner(inputFileOrDir);
        } else {
            runner = new FileReaderRunner(Paths.get(commandLine.getOptionValue('f')));
        }
    } else {
        runner = new SQLRunner(commandLine.getOptionValue("jdbc"), commandLine.getOptionValue("sql"));
    }
    runner.run(indexer);
    indexer.close();
}

From source file:org.terracotta.voter.TCVoterMain.java

public void processArgs(String[] args) throws ConfigurationSetupException, ParseException {
    DefaultParser parser = new DefaultParser();
    Options voterOptions = voterOptions();
    CommandLine commandLine = parser.parse(voterOptions, args);

    if (commandLine.getArgList().size() > 0) {
        throw new ConfigurationSetupException("Invalid arguments provided: " + commandLine.getArgList());
    }//from w w w  .  j  av a 2  s  . c om

    if (commandLine.hasOption(HELP)) {
        new HelpFormatter().printHelp("start-voter.sh[bat]", voterOptions);
        return;
    }

    if (commandLine.getOptions().length == 0) {
        throw new ConfigurationSetupException(
                "Neither the override option -o nor the regular options -s or -f provided");
    }

    if (commandLine.hasOption(SERVER) && commandLine.hasOption(CONFIG_FILE)) {
        throw new ConfigurationSetupException(
                "Both -s and -f options provided. Use either one and not both together.");
    }

    Optional<Properties> connectionProps = getConnectionProperties(commandLine);
    if (commandLine.hasOption(SERVER)) {
        processServerArg(connectionProps, commandLine.getOptionValues(SERVER));
    } else if (commandLine.hasOption(CONFIG_FILE)) {
        processConfigFileArg(connectionProps, commandLine.getOptionValues(CONFIG_FILE));
    } else if (commandLine.hasOption(OVERRIDE)) {
        String hostPort = commandLine.getOptionValue(OVERRIDE);
        validateHostPort(hostPort);
        getVoter(connectionProps).overrideVote(hostPort);
    } else {
        throw new AssertionError("This should not happen");
    }
}

From source file:ubic.gemma.core.util.AbstractCLI.java

/**
 * This must be called in your main method. It triggers parsing of the command line and processing of the options.
 * Check the error code to decide whether execution of your program should proceed.
 *
 * @param  args args/*from   w  w w  .  j  av  a2s. co  m*/
 * @return      Exception; null if nothing went wrong.
 */
protected final Exception processCommandLine(String[] args) {
    /* COMMAND LINE PARSER STAGE */
    DefaultParser parser = new DefaultParser();
    String appVersion = Settings.getAppVersion();
    if (appVersion == null)
        appVersion = "?";
    System.err.println("Gemma version " + appVersion);

    if (args == null) {
        this.printHelp();
        return new Exception("No arguments");
    }

    try {
        commandLine = parser.parse(options, args);
    } catch (ParseException e) {
        if (e instanceof MissingOptionException) {
            System.err.println("Required option(s) were not supplied: " + e.getMessage());
        } else if (e instanceof AlreadySelectedException) {
            System.err.println("The option(s) " + e.getMessage() + " were already selected");
        } else if (e instanceof MissingArgumentException) {
            System.err.println("Missing argument: " + e.getMessage());
        } else if (e instanceof UnrecognizedOptionException) {
            System.err.println("Unrecognized option: " + e.getMessage());
        } else {
            e.printStackTrace();
        }

        this.printHelp();

        if (AbstractCLI.log.isDebugEnabled()) {
            AbstractCLI.log.debug(e);
        }

        return e;
    }

    /* INTERROGATION STAGE */
    if (commandLine.hasOption('h')) {
        this.printHelp();
        return new Exception("Help selected");
    }

    this.processStandardOptions();
    this.processOptions();

    return null;

}

From source file:uk.ac.wlv.rgcl.openbooksigntagger.SimpleSyntaxApp.java

public static CommandLine createCommandLineParser(String[] args) {
    Options options = new Options();

    Option help = new Option("help", "displays this message");

    Option displayFormat = Option.builder("of").longOpt("output-format").argName("format").hasArg()
            .desc("specifies the format of the output. Valid values for "
                    + "<format> are txt, xml and html. The XML format is " + "the default one.")
            .build();//from  ww  w .java 2 s  . co m

    options.addOption(help);
    options.addOption(displayFormat);

    DefaultParser parser = new DefaultParser();
    CommandLine cmd = null;

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException ex) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java <classpath> " + "uk.ac.wlv.rgcl.openbooksigntagger.SimpleSyntaxApp "
                + " [options] <input file>", options);
    }

    return cmd;
}

From source file:xeviousvs.server.XeviousVS_Server.java

public static void main(String args[]) {
    Options opts = new Options();
    opts.addOption("i", "serverAddress", true, "IP address of the server");
    opts.addOption("p", "serverPort", true, "Listening TCP port used to initiate handshakes");
    opts.addOption("d", "databaseAddress", true, "IP address of the matchmaking database");
    opts.addOption("f", "databasePort", true, "Listening port of the matchmaking database");
    opts.addOption("t", "tickrate", true, "Number of transmission session to execute per second");
    opts.addOption("c", "connectionTimeout", true, "Timeout for UDP connections");

    DefaultParser parser = new DefaultParser();
    CommandLine commandLine = null;/*from  ww  w .  j  a v  a2 s.  c om*/
    try {
        commandLine = parser.parse(opts, args);
    } catch (ParseException ex) {
        ex.printStackTrace();
        System.exit(1);
    }

    String databaseAddress = commandLine.getOptionValue("databaseAddress");
    int databasePort = Integer.parseInt(commandLine.getOptionValue("databasePort"));
    OperazioniDatabaseServer.impostaIndirizzoDatabase(databaseAddress, databasePort);

    String serverAddress = commandLine.getOptionValue("serverAddress");
    int serverPort = Integer.parseInt(commandLine.getOptionValue("serverPort"));
    int tickrate = Integer.parseInt(commandLine.getOptionValue("tickrate"));
    int connectionTimeout = Integer.parseInt(commandLine.getOptionValue("connectionTimeout"));

    LOG.debug("Server started, command line parsed");

    XeviousVSLockstepServer lockstepServer = new XeviousVSLockstepServer(serverAddress, serverPort, tickrate,
            connectionTimeout);
    lockstepServer.setName("Main-server-thread");
    lockstepServer.start();

    try {
        lockstepServer.join();
    } catch (InterruptedException ex) {
        LOG.error("Server interrupted while joining");
    }
}