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.kurtraschke.septa.gtfsrealtime.SeptaRealtimeMain.java

public void run(String[] args) throws Exception {
    if (args.length == 0 || CommandLineInterfaceLibrary.wantsHelp(args)) {
        printUsage();//from  www. ja  va  2 s.  c  o  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<>();
    SeptaRealtimeModule.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:com.kurtraschke.ctatt.gtfsrealtime.TrainTrackerRealtimeMain.java

public void run(String[] args) throws Exception {
    if (args.length == 0 || CommandLineInterfaceLibrary.wantsHelp(args)) {
        printUsage();/*from ww  w.j  ava2s.  c  o 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<>();
    TrainTrackerRealtimeModule.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:br.usp.poli.lta.cereda.macro.util.CLIParser.java

/**
 * Realiza a anlise dos argumentos de linha de comando e retorna um par
 * contendo o texto a ser expandido e o arquivo de sada.
 * @return Um par contendo o texto a ser expandido e o arquivo de sada.
 * @throws IOException Um dos arquivos de entrada no existe.
 *///from  ww w . j a  va  2s .c o  m
public Pair<String, File> parse() throws IOException {

    // opo de entrada
    Option input = OptionBuilder.withLongOpt("input").hasArgs().withArgName("lista de arquivos")
            .withDescription("arquivos de entrada").create("i");

    // opo de sada
    Option output = OptionBuilder.withLongOpt("output").hasArg().withArgName("arquivo")
            .withDescription("arquivo de sada").create("o");

    // opo do editor embutido
    Option ui = OptionBuilder.withLongOpt("editor").withDescription("editor grfico").create("e");

    Options options = new Options();
    options.addOption(input);
    options.addOption(output);
    options.addOption(ui);

    try {

        // parsing dos argumentos
        Parser parser = new BasicParser();
        CommandLine line = parser.parse(options, arguments);

        // verifica se  uma chamada ao editor e retorna em caso positivo
        if (line.hasOption("e")) {
            editor = true;
            return null;
        }

        // se no  uma chamada ao editor de macros,  necessrio verificar
        // se existe um arquivo de entrada
        if (!line.hasOption("i")) {
            throw new ParseException("");
        }

        // existem argumentos restantes, o que representa situao de erro
        if (!line.getArgList().isEmpty()) {
            throw new ParseException("");
        }

        String text = "";
        File out = line.hasOption("output") ? new File(line.getOptionValue("output")) : null;

        if (out == null) {
            logger.info("A sada ser gerada no terminal.");
        } else {
            logger.info("A sada ser gerada no arquivo '{}'.", out.getName());
        }

        // faz a leitura de todos os arquivos e concatena seu contedo em
        // uma varivel
        logger.info("Iniciando a leitura dos arquivos de entrada.");
        String[] files = line.getOptionValues("input");
        for (String file : files) {
            logger.info("Lendo arquivo '{}'.", file);
            text = text.concat(FileUtils.readFileToString(new File(file), Charset.forName("UTF-8")));
        }

        // retorna o par da varivel contendo o texto de todos os arquivos
        // e a referncia ao arquivo de sada (podendo este ser nulo)
        return new Pair<>(text, out);

    } catch (ParseException exception) {

        // imprime a ajuda
        HelpFormatter help = new HelpFormatter();
        help.printHelp("expander ( --editor | --input <lista de arquivos>" + " [ --output <arquivo> ] )",
                options);
    }

    // retorna um valor invlido indicando para no prosseguir com o
    // processo de expanso
    return null;

}

From source file:com.kurtraschke.wmata.gtfsrealtime.WMATARealtimeMain.java

public void run(String[] args) throws Exception {
    if (args.length == 0 || CommandLineInterfaceLibrary.wantsHelp(args)) {
        printUsage();/*from  ww  w  .j a  va2  s . 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<>();
    WMATARealtimeModule.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:com.github.mrstampy.poisonivy.PoisonIvy.java

protected boolean executeImpl() throws Exception {
    String[] poisonArgs = getArgs();
    logArgs(poisonArgs);/*from  w  w w .  ja  v a2s .  com*/

    Parser parser = new BasicParser();
    CommandLine cli = parser.parse(getOptions(), poisonArgs);

    if (cli.hasOption(HELP_PARM)) {
        printHelpMessage();
        return true;
    }

    if (executeLibraryRetrieval(cli)) {
        if (cli.hasOption(MAIN_JAR_PARM) || cli.hasOption(MAIN_CLASS_PARM))
            executeMain(cli);
        return true;
    }

    log.error("Could not retrieve libraries via ivy");

    return false;
}

From source file:it.crs4.pydoop.mapreduce.pipes.CommandLineParser.java

CommandLine parse(Configuration conf, String[] args) throws IOException, ParseException {
    Parser parser = new BasicParser();
    conf.setBoolean("mapreduce.client.genericoptionsparser.used", true);
    GenericOptionsParser genericParser = new GenericOptionsParser(conf, args);
    return parser.parse(options, genericParser.getRemainingArgs());
}

From source file:it.crs4.pydoop.pipes.Submitter.java

@Override
public int run(String[] args) throws Exception {
    CommandLineParser cli = new CommandLineParser();
    if (args.length == 0) {
        cli.printUsage();//from ww w.  ja v  a 2s.c o m
        return 1;
    }
    cli.addOption("input", false, "input path to the maps", "path");
    cli.addOption("output", false, "output path from the reduces", "path");

    cli.addOption("jar", false, "job jar file", "path");
    cli.addOption("inputformat", false, "java classname of InputFormat", "class");
    //cli.addArgument("javareader", false, "is the RecordReader in Java");
    cli.addOption("map", false, "java classname of Mapper", "class");
    cli.addOption("partitioner", false, "java classname of Partitioner", "class");
    cli.addOption("reduce", false, "java classname of Reducer", "class");
    cli.addOption("writer", false, "java classname of OutputFormat", "class");
    cli.addOption("program", false, "URI to application executable", "class");
    cli.addOption("reduces", false, "number of reduces", "num");
    cli.addOption("jobconf", false,
            "\"n1=v1,n2=v2,..\" (Deprecated) Optional. Add or override a JobConf property.", "key=val");
    cli.addOption("lazyOutput", false, "Optional. Create output lazily", "boolean");
    Parser parser = cli.createParser();
    try {

        GenericOptionsParser genericParser = new GenericOptionsParser(getConf(), args);
        CommandLine results = parser.parse(cli.options, genericParser.getRemainingArgs());

        JobConf job = new JobConf(getConf());

        if (results.hasOption("input")) {
            FileInputFormat.setInputPaths(job, results.getOptionValue("input"));
        }
        if (results.hasOption("output")) {
            FileOutputFormat.setOutputPath(job, new Path(results.getOptionValue("output")));
        }
        if (results.hasOption("jar")) {
            job.setJar(results.getOptionValue("jar"));
        }
        if (results.hasOption("inputformat")) {
            setIsJavaRecordReader(job, true);
            job.setInputFormat(getClass(results, "inputformat", job, InputFormat.class));
        }
        if (results.hasOption("javareader")) {
            setIsJavaRecordReader(job, true);
        }
        if (results.hasOption("map")) {
            setIsJavaMapper(job, true);
            job.setMapperClass(getClass(results, "map", job, Mapper.class));
        }
        if (results.hasOption("partitioner")) {
            job.setPartitionerClass(getClass(results, "partitioner", job, Partitioner.class));
        }
        if (results.hasOption("reduce")) {
            setIsJavaReducer(job, true);
            job.setReducerClass(getClass(results, "reduce", job, Reducer.class));
        }
        if (results.hasOption("reduces")) {
            job.setNumReduceTasks(Integer.parseInt(results.getOptionValue("reduces")));
        }
        if (results.hasOption("writer")) {
            setIsJavaRecordWriter(job, true);
            job.setOutputFormat(getClass(results, "writer", job, OutputFormat.class));
        }

        if (results.hasOption("lazyOutput")) {
            if (Boolean.parseBoolean(results.getOptionValue("lazyOutput"))) {
                LazyOutputFormat.setOutputFormatClass(job, job.getOutputFormat().getClass());
            }
        }

        if (results.hasOption("program")) {
            setExecutable(job, results.getOptionValue("program"));
        }
        if (results.hasOption("jobconf")) {
            LOG.warn("-jobconf option is deprecated, please use -D instead.");
            String options = results.getOptionValue("jobconf");
            StringTokenizer tokenizer = new StringTokenizer(options, ",");
            while (tokenizer.hasMoreTokens()) {
                String keyVal = tokenizer.nextToken().trim();
                String[] keyValSplit = keyVal.split("=");
                job.set(keyValSplit[0], keyValSplit[1]);
            }
        }
        // if they gave us a jar file, include it into the class path
        String jarFile = job.getJar();
        if (jarFile != null) {
            final URL[] urls = new URL[] { FileSystem.getLocal(job).pathToFile(new Path(jarFile)).toURL() };
            //FindBugs complains that creating a URLClassLoader should be
            //in a doPrivileged() block. 
            ClassLoader loader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
                public ClassLoader run() {
                    return new URLClassLoader(urls);
                }
            });
            job.setClassLoader(loader);
        }

        runJob(job);
        return 0;
    } catch (ParseException pe) {
        LOG.info("Error : " + pe);
        cli.printUsage();
        return 1;
    }

}

From source file:de.bmw.yamaica.common.console.CommandExecuter.java

public int executeCommand(String[] arguments) {
    Assert.isNotNull(arguments);/*from w  w  w.  j av a2 s . c  om*/

    final List<ConsoleConfiguration> configurations = getParsedExtensionPointConfigurations();

    // Print message if there are no registered console commands.
    if (configurations.size() == 0) {
        println(HELP_NO_COMMANDS_TEXT_MESSAGE);

        return DEFAULT_RETURN_VALUE;
    }

    // Print help text if no option is available.
    if (arguments.length == 0) {
        printHelp(configurations);

        return DEFAULT_RETURN_VALUE;
    }

    // Find a suitable console configuration.
    final List<ConsoleConfiguration> perfectMatchingConfigurations = new ArrayList<ConsoleConfiguration>();
    final List<ConsoleConfiguration> partialMatchingConfigurations = new ArrayList<ConsoleConfiguration>();
    final List<ConsoleConfiguration> notMatchingConfigurations = new ArrayList<ConsoleConfiguration>();

    Parser parser = new PosixParser();

    for (ConsoleConfiguration configuration : configurations) {
        try {
            CommandLine commandLine = parser.parse(configuration.options, arguments);

            // Add ID option and ID information to configuration. Thus if there are several
            // perfect matches the printHelp method can print this information.
            configuration.options.addOption(ID_OPTION);
            configuration.message = String.format(HELP_ID_TEXT_MESSAGE, SHORT_ID_OPTION, configuration.id);
            configuration.commandLine = commandLine;
            perfectMatchingConfigurations.add(configuration);
        } catch (MissingOptionException | MissingArgumentException | AlreadySelectedException exception) {
            configuration.message = exception.getMessage();
            partialMatchingConfigurations.add(configuration);
        } catch (UnrecognizedOptionException exception) {
            // Check if the unrecognized option is the ID option.
            String unrecognizedOption = exception.getOption();

            if (unrecognizedOption.equals("-" + SHORT_ID_OPTION)
                    || unrecognizedOption.equals("--" + LONG_ID_OPTION)) {
                try {
                    // Add ID option to options object an parse arguments again.
                    CommandLine commandLine = parser.parse(configuration.options.addOption(ID_OPTION),
                            arguments);
                    String idValue = commandLine.getOptionValue(SHORT_ID_OPTION);

                    // The correct console configuration is found if parsing did not throw an
                    // exception and the ID option equals extension point ID.
                    if (configuration.id.equals(idValue)) {
                        configuration.commandLine = commandLine;
                        perfectMatchingConfigurations.add(configuration);
                    } else {
                        configuration.message = String.format(HELP_WRONG_ID_MESSAGE, SHORT_ID_OPTION,
                                configuration.id, idValue);
                        partialMatchingConfigurations.add(configuration);
                    }
                } catch (ParseException e) {
                    configuration.message = e.getMessage();
                    notMatchingConfigurations.add(configuration);
                }
            } else {
                configuration.message = exception.getMessage();
                notMatchingConfigurations.add(configuration);
            }
        } catch (ParseException exception) {
            configuration.message = exception.getMessage();
            notMatchingConfigurations.add(configuration);
        }
    }

    // Execute compatible command or print help text
    if (perfectMatchingConfigurations.size() == 1) {
        SafeRunner.run(new ISafeRunnable() {
            @Override
            public void run() throws Exception {
                ConsoleConfiguration configuration = perfectMatchingConfigurations.get(0);

                if (configurations.size() > 1) {
                    println(EXECUTE_COMMAND_MESSAGE, configuration.name, SHORT_ID_OPTION, configuration.id);
                }

                Object executable = configuration.commandConfiguration
                        .createExecutableExtension(COMMAND_HANDLER_ATTRIBUTE_NAME);
                ICommandLineHandler handler = (ICommandLineHandler) executable;

                returnValue = handler.excute(configuration.commandLine);
            }

            @Override
            public void handleException(Throwable throwable) {
                log(throwable);
            }
        });
    } else if (perfectMatchingConfigurations.size() > 1) {
        println(HELP_SEVERAL_COMMANDS_MESSAGE);
        printHelp(perfectMatchingConfigurations);
    } else if (partialMatchingConfigurations.size() > 0) {
        printHelp(partialMatchingConfigurations);
    } else {
        printHelp(notMatchingConfigurations);
    }

    return returnValue;
}

From source file:edu.umn.msi.gx.ontology_lookup_client.OntologyLookUp.java

private void parseOtions(String[] args) {
    Parser parser = new BasicParser();
    String ontologyOpt = "ontology";
    String termOpt = "term";
    String nameOpt = "name";
    String filterOpt = "filter";
    String outputOpt = "output";

    Options options = new Options();
    options.addOption("O", ontologyOpt, true, "Ontology e.g. BTO");
    options.addOption("t", termOpt, true, "TermID e.g. BTO:0000759");
    options.addOption("n", nameOpt, true, "Entry names must include this");
    options.addOption("f", filterOpt, true, "include: ALL,MATCH,LEAF");
    options.addOption("o", outputOpt, true, "output file");

    try {/*from   w w w  . j a v  a 2s  .  co m*/
        // parse the command line arguments
        CommandLine cli = parser.parse(options, args);
        if (cli.hasOption(ontologyOpt)) {
            ontology = cli.getOptionValue(ontologyOpt);

        } else {
            System.err.printf("Failed: ontology option required. Available onologies: %s\n", ontologyList);
            System.exit(1);
        }
        if (cli.hasOption(termOpt)) {
            String terms = cli.getOptionValue(termOpt);
            termIDs = Arrays.asList(terms.split(",\\s*"));
        }
        if (cli.hasOption(nameOpt)) {
            String terms = cli.getOptionValue(nameOpt);
            names = Arrays.asList(terms.split(",\\s*"));
        }

        if (cli.hasOption(filterOpt)) {
            String filt = cli.getOptionValue(filterOpt);
            switch (filt) {
            case "LEAF":
                filter = Filter.LEAF;
                break;
            case "ALL":
                filter = Filter.ALL;
                break;
            case "MATCH":
                filter = Filter.MATCH;
                break;
            }
        }
        if (cli.hasOption(outputOpt)) {
            String outputFile = cli.getOptionValue(outputOpt);
            out = new PrintStream(outputFile);
        }
    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
    } catch (FileNotFoundException ex) {
        Logger.getLogger(OntologyLookUp.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:edu.umn.msi.gx.mztosqlite.MzToSQLite.java

public final void parseOptions(String[] args) {
    Integer MAX_INPUTS = 100;/*from ww w  .  j  a va  2 s  . co m*/
    Parser parser = new BasicParser();
    String dbOpt = "sqlite";
    String inputFileOpt = "input";
    String inputNameOpt = "name";
    String inputIdOpt = "encoded_id";
    String verboseOpt = "verbose";
    String helpOpt = "help";
    Options options = new Options();
    options.addOption("s", dbOpt, true, "SQLite output file");
    options.addOption("v", verboseOpt, false, "verbose");
    options.addOption("h", helpOpt, false, "help");
    options.addOption("i", inputFileOpt, verbose, "input file");
    options.addOption("n", inputNameOpt, verbose, "name for input file");
    options.addOption("e", inputIdOpt, verbose, "encoded id for input file");
    options.addOption("f", inputIdOpt, verbose, "FASTA Search Database files");
    options.getOption(inputFileOpt).setArgs(MAX_INPUTS);
    options.getOption(inputNameOpt).setArgs(MAX_INPUTS);
    options.getOption(inputIdOpt).setArgs(MAX_INPUTS);
    // create the parser
    try {
        // parse the command line arguments
        CommandLine cli = parser.parse(options, args);
        if (cli.hasOption(helpOpt)) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("java -jar MzToSQLite.jar [options] [proteomics_data_file ...]", options);
            exit(0);
        }
        if (cli.hasOption(verboseOpt)) {
            verbose = true;
        }
        if (cli.hasOption(dbOpt)) {
            dbPath = cli.getOptionValue(dbOpt);
            mzSQLiteDB = new MzSQLiteDB(dbPath);
            try {
                mzSQLiteDB.createTables();
            } catch (SqlJetException ex) {
                Logger.getLogger(MzToSQLite.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        List<String> argList = cli.getArgList();
        if (argList != null) {
            for (String filePath : argList) {
                File inputFile = new File(filePath);
                if (inputFile.canRead()) {
                    try {
                        ProteomicsFormat format = ProteomicsFormat.getFormat(inputFile);
                        switch (format) {
                        case MZID:
                            identFiles.put(filePath, format);
                            break;
                        case MZML:
                        case MGF:
                        case DTA:
                        case MS2:
                        case PKL:
                        case MZXML:
                        case XML_FILE:
                        case MZDATA:
                        case PRIDEXML:
                            scanFiles.put(filePath, format);
                            break;
                        case FASTA:
                            seqDbFiles.put(filePath, format);
                            break;
                        case PEPXML:
                        case UNSUPPORTED:
                        default:
                            Logger.getLogger(MzToSQLite.class.getName()).log(Level.WARNING,
                                    "Unknown or unsupported format: {0}", filePath);
                            break;
                        }
                    } catch (IOException ex) {
                        Logger.getLogger(MzToSQLite.class.getName()).log(Level.SEVERE, null, ex);
                    }
                } else {
                    Logger.getLogger(MzToSQLite.class.getName()).log(Level.WARNING, "Unable to read {0}",
                            filePath);
                }
            }
        }
    } catch (ParseException exp) {
        Logger.getLogger(MzToSQLite.class.getName()).log(Level.SEVERE, null, exp);
    }

}