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

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

Introduction

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

Prototype

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

Source Link

Document

Parse the arguments according to the specified options.

Usage

From source file:eu.scape_project.tb.lsdr.hocrparser.HocrParser.java

/**
 * The main entry point.//from ww  w .j ava2  s . c  om
 */
public static void main(String[] args) throws ParseException {
    Configuration conf = new Configuration();

    //conf.setBoolean("mapreduce.client.genericoptionsparser.used", true);
    GenericOptionsParser gop = new GenericOptionsParser(conf, args);
    HocrParserCliConfig pc = new HocrParserCliConfig();
    CommandLineParser cmdParser = new PosixParser();
    CommandLine cmd = cmdParser.parse(HocrParserOptions.OPTIONS, gop.getRemainingArgs());
    if ((args.length == 0) || (cmd.hasOption(HocrParserOptions.HELP_OPT))) {
        HocrParserOptions.exit("Usage", 0);
    } else {
        HocrParserOptions.initOptions(cmd, pc);
    }
    String dir = pc.getDirStr();

    String name = pc.getHadoopJobName();
    if (name == null || name.equals("")) {
        name = "hocr_parser";
    }

    try {
        Job job = new Job(conf, name);
        job.setJarByClass(HocrParser.class);

        job.setMapperClass(HocrParserMapper.class);
        //job.setCombinerClass(HocrParserReducer.class);
        job.setReducerClass(HocrParserReducer.class);

        job.setInputFormatClass(SequenceFileInputFormat.class);

        job.setOutputFormatClass(TextOutputFormat.class);
        //SequenceFileOutputFormat.setOutputCompressionType(job, SequenceFile.CompressionType.NONE);

        //conf.setMapOutputKeyClass(Text.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(Text.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(LongWritable.class);

        SequenceFileInputFormat.addInputPath(job, new Path(dir));
        String outpath = "output/" + System.currentTimeMillis() + "hop";
        FileOutputFormat.setOutputPath(job, new Path(outpath));
        job.waitForCompletion(true);
        System.out.print(outpath);
        System.exit(0);
    } catch (Exception e) {
        logger.error("IOException occurred", e);
    }
}

From source file:is.merkor.core.cli.Main.java

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

    List<String> results = new ArrayList<String>();
    PrintStream out = new PrintStream(System.out, true, "UTF-8");

    CommandLineParser parser = new GnuParser();
    try {/*from w  ww. j  a  v a  2  s . c om*/

        MerkorCoreCommandLineOptions.createOptions();
        results = processCommandLine(parser.parse(MerkorCoreCommandLineOptions.options, args));
        out.print("\n");
        for (String str : results) {
            if (!str.equals("no message"))
                out.println(str);
        }
        out.print("\n");
        if (results.isEmpty()) {
            out.println("nothing found for parameters: ");
            for (int i = 0; i < args.length; i++)
                out.println("\t" + args[i]);
            out.println("for help type: -help or see README.markdown");
            out.print("\n");
        }
    } catch (ParseException e) {
        System.err.println("Parsing failed.  Reason: " + e.getMessage());
    }
}

From source file:cz.muni.fi.mir.mathmlcanonicalization.MathMLCanonicalizerCommandLineTool.java

/**
 * @param args the command line arguments
 *//*from ww w  .ja  va  2  s  .  c o  m*/
public static void main(String[] args) throws FileNotFoundException, XMLStreamException {
    final Options options = new Options();
    options.addOption("c", true, "load configuration file");
    options.addOption("dtd", false,
            "enforce injection of XHTML + MathML 1.1 DTD reference into input documents");
    options.addOption("w", false, "overwrite input files by canonical outputs");
    options.addOption("h", false, "print help");

    final CommandLineParser parser = new PosixParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, args);
    } catch (ParseException ex) {
        printHelp(options);
        System.exit(1);
    }

    File config = null;
    boolean overwrite = false;
    boolean dtdInjectionMode = false;
    if (line != null) {
        if (line.hasOption('c')) {
            config = new File(args[1]);
        }

        if (line.hasOption("dtd")) {
            dtdInjectionMode = true;
        }

        if (line.hasOption('w')) {
            overwrite = true;
        }

        if (line.hasOption('h')) {
            printHelp(options);
            System.exit(0);
        }

        final List<String> arguments = Arrays.asList(line.getArgs());
        if (arguments.size() > 0) {
            for (String arg : arguments) {
                try {
                    List<File> files = getFiles(new File(arg));
                    for (File file : files) {
                        canonicalize(file, config, dtdInjectionMode, overwrite);
                    }
                } catch (IOException ex) {
                    Logger.getLogger(MathMLCanonicalizerCommandLineTool.class.getName()).log(Level.SEVERE,
                            ex.getMessage(), ex);
                } catch (ConfigException ex) {
                    Logger.getLogger(MathMLCanonicalizerCommandLineTool.class.getName()).log(Level.SEVERE,
                            ex.getMessage(), ex);
                } catch (JDOMException ex) {
                    Logger.getLogger(MathMLCanonicalizerCommandLineTool.class.getName()).log(Level.SEVERE,
                            ex.getMessage(), ex);
                } catch (ModuleException ex) {
                    Logger.getLogger(MathMLCanonicalizerCommandLineTool.class.getName()).log(Level.SEVERE,
                            ex.getMessage(), ex);
                }
            }
        } else {
            printHelp(options);
            System.exit(0);
        }
    }
}

From source file:com.act.biointerpretation.sars.SarGenerationDriver.java

public static void main(String[] args) throws Exception {
    // Build command line parser.
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());//w  ww  .  j  ava  2  s .c  o m
    }

    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        LOGGER.error("Argument parsing failed: %s", e.getMessage());
        HELP_FORMATTER.printHelp(SarGenerationDriver.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    // Print help.
    if (cl.hasOption(OPTION_HELP)) {
        HELP_FORMATTER.printHelp(SarGenerationDriver.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        return;
    }

    // Create DB and DbAPI
    MongoDB mongoDB = new MongoDB(LOCAL_HOST, MONGO_PORT, cl.getOptionValue(OPTION_DB));
    DbAPI dbApi = new DbAPI(mongoDB);

    // Handle output file
    File outputFile = new File(cl.getOptionValue(OPTION_OUTPUT_PATH));
    if (outputFile.isDirectory() || outputFile.exists()) {
        LOGGER.error("Supplied output file is a directory or already exists.");
        HELP_FORMATTER.printHelp(SarGenerationDriver.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }
    outputFile.createNewFile();

    // Check that there is exactly one reaction group input option
    if (cl.hasOption(OPTION_REACTION_LIST) && cl.hasOption(OPTION_REACTIONS_FILE)) {
        LOGGER.error("Cannot process both a reaction list and a reactions file as input.");
        HELP_FORMATTER.printHelp(SarGenerationDriver.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }
    if (!cl.hasOption(OPTION_REACTION_LIST) && !cl.hasOption(OPTION_REACTIONS_FILE)) {
        LOGGER.error("Must supply either a reaction list or a reactions file as input.");
        HELP_FORMATTER.printHelp(SarGenerationDriver.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    // Build input reaction group corpus.
    Iterable<ReactionGroup> groups = null;
    if (cl.hasOption(OPTION_REACTION_LIST)) {
        LOGGER.info("Using specific input reactions.");
        ReactionGroup group = new ReactionGroup("ONLY_GROUP", "NO_DB");
        for (String idString : cl.getOptionValues(OPTION_REACTION_LIST)) {
            group.addReactionId(Long.parseLong(idString));
        }
        groups = Arrays.asList(group);
    }
    if (cl.hasOption(OPTION_REACTIONS_FILE)) {
        LOGGER.info("Using reactions file.");
        File inputFile = new File(cl.getOptionValue(OPTION_REACTIONS_FILE));
        try {
            groups = ReactionGroupCorpus.loadFromJsonFile(inputFile);
            LOGGER.info("Successfully parsed input as json file.");
        } catch (IOException e) {
            LOGGER.info("Input file not json file. Trying txt format.");
            try {
                groups = ReactionGroupCorpus.loadFromTextFile(inputFile);
                LOGGER.info("Successfully parsed input as text file.");
            } catch (IOException f) {
                LOGGER.error("Reactions input file not parseable. %s", f.getMessage());
                throw f;
            }
        }
    }

    // Build all pieces of SAR generator
    ReactionProjector projector = new ReactionProjector();
    ExpandedReactionSearcher generalizer = new ExpandedReactionSearcher(projector);

    McsCalculator reactionMcsCalculator = new McsCalculator(McsCalculator.REACTION_BUILDING_OPTIONS);
    McsCalculator sarMcsCalculator = new McsCalculator(McsCalculator.SAR_OPTIONS);

    FullReactionBuilder reactionBuilder = new FullReactionBuilder(reactionMcsCalculator, generalizer,
            projector);

    SarFactory substructureSarFactory = new OneSubstrateSubstructureSar.Factory(sarMcsCalculator);
    SarFactory carbonCountSarFactory = new OneSubstrateCarbonCountSar.Factory();
    List<SarFactory> sarFactories = Arrays.asList(carbonCountSarFactory, substructureSarFactory);

    ErosCorpus roCorpus = new ErosCorpus();
    roCorpus.loadValidationCorpus();

    ReactionGroupCharacterizer reactionGroupCharacterizer = new OneSubstrateOneRoCharacterizer(dbApi,
            sarFactories, reactionBuilder, roCorpus);
    SarCorpusBuilder corpusBuilder = new SarCorpusBuilder(groups, reactionGroupCharacterizer);
    LOGGER.info("Parsed arguments and constructed SAR corpus builder. Building corpus.");

    SarCorpus sarCorpus = corpusBuilder.build();
    LOGGER.info("Built sar corpus. Printing to file in json format.");

    sarCorpus.printToJsonFile(outputFile);
    LOGGER.info("Complete!");
}

From source file:com.hurence.logisland.utils.avro.eventgenerator.DataGenerator.java

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

    // load and verify the options
    CommandLineParser parser = new PosixParser();
    Options opts = loadOptions();/*from  ww  w  .java  2 s.  c  o m*/

    CommandLine cmd = null;
    try {
        cmd = parser.parse(opts, args);
    } catch (org.apache.commons.cli.ParseException parseEx) {
        LOG.error("Invalid option");
        printHelp(opts);
        return;
    }

    // check for necessary options
    String fileLoc = cmd.getOptionValue("schemaLocation");
    if (fileLoc == null) {
        LOG.error("schemaLocation not specified");
        printHelp(opts);
    }

    //get string length and check if min is greater than 0

    // Generate the record
    File schemaFile = new File(fileLoc);
    DataGenerator dataGenerator = new DataGenerator(schemaFile);
    GenericRecord record = dataGenerator.generateRandomRecord();
    if (cmd.hasOption(PRINT_AVRO_JSON_OPTNAME)) {
        String outname = cmd.getOptionValue(PRINT_AVRO_JSON_OPTNAME);
        OutputStream outs = System.out;
        if (!outname.equals("-")) {
            outs = new FileOutputStream(outname);
        }
        printAvroJson(record, outs);
        if (!outname.equals("-")) {
            outs.close();
        }
    } else {
        DataGenerator.prettyPrint(record);
    }

}

From source file:com.genentech.chemistry.tool.SDF2HtmlTab.java

public static void main(String[] args) throws ParseException, JDOMException, IOException {
    long start = System.currentTimeMillis();

    // create command line Options object
    Options options = new Options();
    Option opt = new Option("in", true, "input sd file");
    opt.setRequired(true);//ww  w .ja v a2s.co  m
    options.addOption(opt);

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp(options);
    }
    args = cmd.getArgs();

    String inFile = cmd.getOptionValue("in");

    args = cmd.getArgs();
    if (args.length > 0) {
        exitWithHelp(options);
    }

    oemolistream ifs;
    Set<String> tagSet = getTagSet(inFile);

    System.out.println(
            "<html xmlns:v='urn:schemas-microsoft-com:vml' xmlns:o='urn:schemas-microsoft-com:office:office'>");
    System.out.println("<head>");
    System.out.println("<BASE href='" + BASEUrl + "'/>");
    System.out.println(
            "<link href='/" + Settings.SERVLET_CONTEXT + "/css/Aestel.css' rel='stylesheet' type='text/css'/>");

    System.out.println("<style type='text/css'>");
    System.out.println("td.stru { width: " + (IMGWidth + 2) + "px; height: " + (IMGHeigth + 4)
            + "px; vertical-align: top; }");
    System.out.println("table.grid tr.first { border-top: 3px solid black; }");
    // for tables in tables
    System.out.println("table.grid table td { border: 0px; text-align: right;}");
    System.out.println("table.grid table td:first-child { text-align: left;}");
    System.out.println("th.head { border-left: 1px solid black; border-bottom: 2px solid black;\n"
            + "          empty-cells: show; background-color: #6297ff; color: #000000;\n"
            + "          padding: 0em .3em 0em .3em; vertical-align: middle; }");
    System.out.println("</style>");

    System.out.println("</head>");
    System.out.println("<body>");

    System.out.println("<table class='grid'><tr>");
    System.out.println("<th class='head'>Structure</th>");

    for (String tag : tagSet)
        System.out.println("<th class='head'>" + tag + "</th>");
    System.out.println("</tr>");

    OEGraphMol mol = new OEGraphMol();
    ifs = new oemolistream(inFile);
    int iCounter = 0;
    while (oechem.OEReadMolecule(ifs, mol)) {
        iCounter++;
        System.out.println("<tr>");
        String smi = OETools.molToCanSmi(mol, true);
        String img = DepictHelper.DEFAULT.getExcelSmilesImageElement(BASEUrl, 120, 120, ImageType.PNG, smi,
                null);

        System.out.print(" <td class='stru'>");
        System.out.print(img);
        System.out.println("</td>");

        for (String tag : tagSet) {
            String val = oechem.OEGetSDData(mol, tag);

            System.out.print(" <td>");
            System.out.print(val);
            System.out.println("</td>");
        }

        System.out.println("</tr>");
    }

    System.out.println("</table></body></html>");

    System.err.printf("SDF2HtmlTab: Exported %d structures in %dsec\n", iCounter,
            (System.currentTimeMillis() - start) / 1000);
}

From source file:edu.isi.mtandao.twitter.StreamCrawler.java

public static void main(String[] args)
        throws ParseException, InstantiationException, IllegalAccessException, ClassNotFoundException {
    // extract command line arguments
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(CLI_OPTIONS, args);

    // get crawler class
    String crawlerClass = cmd.getOptionValue("crawlerClass");
    if (crawlerClass == null) {
        printUsage(CLI_OPTIONS);// ww  w  . j  av  a  2s.  com
    }

    // instantiate and initialize the crawler
    StreamCrawler crawler = (StreamCrawler) Class.forName(crawlerClass).newInstance();

    try {
        crawler.initialize(cmd);
    } catch (Exception e) {
        printUsage(CLI_OPTIONS);
    }

    // start crawling
    crawler.crawl();
}

From source file:glacierpipe.GlacierPipeMain.java

public static void main(String[] args) throws IOException, ParseException {
    CommandLineParser parser = new GnuParser();

    CommandLine cmd = parser.parse(OPTIONS, args);

    if (cmd.hasOption("help")) {
        try (PrintWriter writer = new PrintWriter(System.err)) {
            printHelp(writer);//from   w  w w . j a va  2 s.  c  o  m
        }

        System.exit(0);
    } else if (cmd.hasOption("upload")) {

        // Turn the CommandLine into Properties
        Properties cliProperties = new Properties();
        for (Iterator<?> i = cmd.iterator(); i.hasNext();) {
            Option o = (Option) i.next();

            String opt = o.getLongOpt();
            opt = opt != null ? opt : o.getOpt();

            String value = o.getValue();
            value = value != null ? value : "";

            cliProperties.setProperty(opt, value);
        }

        // Build up a configuration
        ConfigBuilder configBuilder = new ConfigBuilder();

        // Archive name
        List<?> archiveList = cmd.getArgList();
        if (archiveList.size() > 1) {
            throw new ParseException("Too many arguments");
        } else if (archiveList.isEmpty()) {
            throw new ParseException("No archive name provided");
        }

        configBuilder.setArchive(archiveList.get(0).toString());

        // All other arguments on the command line
        configBuilder.setFromProperties(cliProperties);

        // Load any config from the properties file
        Properties fileProperties = new Properties();
        try (InputStream in = new FileInputStream(configBuilder.propertiesFile)) {
            fileProperties.load(in);
        } catch (IOException e) {
            System.err.printf("Warning: unable to read properties file %s; %s%n", configBuilder.propertiesFile,
                    e);
        }

        configBuilder.setFromProperties(fileProperties);

        // ...
        Config config = new Config(configBuilder);

        IOBuffer buffer = new MemoryIOBuffer(config.partSize);

        AmazonGlacierClient client = new AmazonGlacierClient(
                new BasicAWSCredentials(config.accessKey, config.secretKey));
        client.setEndpoint(config.endpoint);

        // Actual upload
        try (InputStream in = new BufferedInputStream(System.in, 4096);
                PrintWriter writer = new PrintWriter(System.err);
                ObservableProperties configMonitor = config.reloadProperties
                        ? new ObservableProperties(config.propertiesFile)
                        : null;
                ProxyingThrottlingStrategy throttlingStrategy = new ProxyingThrottlingStrategy(config);) {
            TerminalGlacierPipeObserver observer = new TerminalGlacierPipeObserver(writer);

            if (configMonitor != null) {
                configMonitor.registerObserver(throttlingStrategy);
            }

            GlacierPipe pipe = new GlacierPipe(buffer, observer, config.maxRetries, throttlingStrategy);
            pipe.pipe(client, config.vault, config.archive, in);
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }

        System.exit(0);
    } else {
        try (PrintWriter writer = new PrintWriter(System.err)) {
            writer.println("No action specified.");
            printHelp(writer);
        }

        System.exit(-1);
    }
}

From source file:net.sourceforge.dita4publishers.tools.ditadxpunpacker.DitaDxpUnpacker.java

/**
 * @param args/*from w ww. j  av  a2s . co  m*/
 */
public static void main(String[] args) {

    Options cmdlineOptions = configureOptions();

    CommandLineParser parser = new PosixParser();

    CommandLine cmdline = null;
    try {
        // parse the command line arguments
        cmdline = parser.parse(cmdlineOptions, args);
    } catch (ParseException exp) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(DitaDxpUnpacker.class.getSimpleName(), cmdlineOptions);
        System.exit(-1);
    }

    if (!cmdline.hasOption(INPUT_OPTION_ONE_CHAR)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(DitaDxpUnpacker.class.getSimpleName(), cmdlineOptions);
        System.exit(-1);
    }

    DitaDxpUnpacker app = new DitaDxpUnpacker(cmdline);
    try {
        app.run();
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }

}

From source file:gobblin.runtime.util.JobStateToJsonConverter.java

@SuppressWarnings("all")
public static void main(String[] args) throws Exception {
    Option sysConfigOption = Option.builder("sc").argName("system configuration file")
            .desc("Gobblin system configuration file").longOpt("sysconfig").hasArgs().build();
    Option storeUrlOption = Option.builder("u").argName("gobblin state store URL")
            .desc("Gobblin state store root path URL").longOpt("storeurl").hasArgs().required().build();
    Option jobNameOption = Option.builder("n").argName("gobblin job name").desc("Gobblin job name")
            .longOpt("name").hasArgs().required().build();
    Option jobIdOption = Option.builder("i").argName("gobblin job id").desc("Gobblin job id").longOpt("id")
            .hasArgs().build();/* ww w .  j av a 2s  . c  om*/
    Option convertAllOption = Option.builder("a")
            .desc("Whether to convert all past job states of the given job").longOpt("all").build();
    Option keepConfigOption = Option.builder("kc").desc("Whether to keep all configuration properties")
            .longOpt("keepConfig").build();
    Option outputToFile = Option.builder("t").argName("output file name").desc("Output file name")
            .longOpt("toFile").hasArgs().build();

    Options options = new Options();
    options.addOption(sysConfigOption);
    options.addOption(storeUrlOption);
    options.addOption(jobNameOption);
    options.addOption(jobIdOption);
    options.addOption(convertAllOption);
    options.addOption(keepConfigOption);
    options.addOption(outputToFile);

    CommandLine cmd = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cmd = parser.parse(options, args);
    } catch (ParseException pe) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("JobStateToJsonConverter", options);
        System.exit(1);
    }

    Properties sysConfig = new Properties();
    if (cmd.hasOption(sysConfigOption.getLongOpt())) {
        sysConfig = JobConfigurationUtils.fileToProperties(cmd.getOptionValue(sysConfigOption.getLongOpt()));
    }

    JobStateToJsonConverter converter = new JobStateToJsonConverter(sysConfig, cmd.getOptionValue('u'),
            cmd.hasOption("kc"));
    StringWriter stringWriter = new StringWriter();
    if (cmd.hasOption('i')) {
        converter.convert(cmd.getOptionValue('n'), cmd.getOptionValue('i'), stringWriter);
    } else {
        if (cmd.hasOption('a')) {
            converter.convertAll(cmd.getOptionValue('n'), stringWriter);
        } else {
            converter.convert(cmd.getOptionValue('n'), stringWriter);
        }
    }

    if (cmd.hasOption('t')) {
        Closer closer = Closer.create();
        try {
            FileOutputStream fileOutputStream = closer.register(new FileOutputStream(cmd.getOptionValue('t')));
            OutputStreamWriter outputStreamWriter = closer.register(
                    new OutputStreamWriter(fileOutputStream, ConfigurationKeys.DEFAULT_CHARSET_ENCODING));
            BufferedWriter bufferedWriter = closer.register(new BufferedWriter(outputStreamWriter));
            bufferedWriter.write(stringWriter.toString());
        } catch (Throwable t) {
            throw closer.rethrow(t);
        } finally {
            closer.close();
        }
    } else {
        System.out.println(stringWriter.toString());
    }
}