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

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

Introduction

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

Prototype

Options

Source Link

Usage

From source file:apps.classification.LearnSVMPerf.java

public static void main(String[] args) throws IOException {
    String cmdLineSyntax = LearnSVMPerf.class.getName()
            + " [OPTIONS] <path to svm_perf> <trainingIndexDirectory>";

    Options options = new Options();

    OptionBuilder.withArgName("c");
    OptionBuilder.withDescription("The c value for svm_perf (default 0.01)");
    OptionBuilder.withLongOpt("c");
    OptionBuilder.isRequired(false);// w  w w .  j  a  va 2 s  . c o  m
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("t");
    OptionBuilder.withDescription("Path for temporary files");
    OptionBuilder.withLongOpt("t");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("l");
    OptionBuilder.withDescription("The loss function to optimize (default 2):\n"
            + "               0  Zero/one loss: 1 if vector of predictions contains error, 0 otherwise.\n"
            + "               1  F1: 100 minus the F1-score in percent.\n"
            + "               2  Errorrate: Percentage of errors in prediction vector.\n"
            + "               3  Prec/Rec Breakeven: 100 minus PRBEP in percent.\n"
            + "               4  Prec@p: 100 minus precision at p in percent.\n"
            + "               5  Rec@p: 100 minus recall at p in percent.\n"
            + "               10  ROCArea: Percentage of swapped pos/neg pairs (i.e. 100 - ROCArea).");
    OptionBuilder.withLongOpt("l");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("w");
    OptionBuilder.withDescription("Choice of structural learning algorithm (default 9):\n"
            + "               0: n-slack algorithm described in [2]\n"
            + "               1: n-slack algorithm with shrinking heuristic\n"
            + "               2: 1-slack algorithm (primal) described in [5]\n"
            + "               3: 1-slack algorithm (dual) described in [5]\n"
            + "               4: 1-slack algorithm (dual) with constraint cache [5]\n"
            + "               9: custom algorithm in svm_struct_learn_custom.c");
    OptionBuilder.withLongOpt("w");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("p");
    OptionBuilder.withDescription("The value of p used by the prec@p and rec@p loss functions (default 0)");
    OptionBuilder.withLongOpt("p");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("v");
    OptionBuilder.withDescription("Verbose output");
    OptionBuilder.withLongOpt("v");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg(false);
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("s");
    OptionBuilder.withDescription("Don't delete temporary training file in svm_perf format (default: delete)");
    OptionBuilder.withLongOpt("s");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg(false);
    options.addOption(OptionBuilder.create());

    SvmPerfLearnerCustomizer classificationLearnerCustomizer = null;

    GnuParser parser = new GnuParser();
    String[] remainingArgs = null;
    try {
        CommandLine line = parser.parse(options, args);

        remainingArgs = line.getArgs();

        classificationLearnerCustomizer = new SvmPerfLearnerCustomizer(remainingArgs[0]);

        if (line.hasOption("c"))
            classificationLearnerCustomizer.setC(Float.parseFloat(line.getOptionValue("c")));

        if (line.hasOption("w"))
            classificationLearnerCustomizer.setW(Integer.parseInt(line.getOptionValue("w")));

        if (line.hasOption("p"))
            classificationLearnerCustomizer.setP(Integer.parseInt(line.getOptionValue("p")));

        if (line.hasOption("l"))
            classificationLearnerCustomizer.setL(Integer.parseInt(line.getOptionValue("l")));

        if (line.hasOption("v"))
            classificationLearnerCustomizer.printSvmPerfOutput(true);

        if (line.hasOption("s"))
            classificationLearnerCustomizer.setDeleteTrainingFiles(false);

        if (line.hasOption("t"))
            classificationLearnerCustomizer.setTempPath(line.getOptionValue("t"));

    } catch (Exception exp) {
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(cmdLineSyntax, options);
        System.exit(-1);
    }

    if (remainingArgs.length != 2) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(cmdLineSyntax, options);
        System.exit(-1);
    }

    String indexFile = remainingArgs[1];

    File file = new File(indexFile);

    String indexName = file.getName();
    String indexPath = file.getParent();

    // LEARNING
    SvmPerfLearner classificationLearner = new SvmPerfLearner();

    classificationLearner.setRuntimeCustomizer(classificationLearnerCustomizer);

    FileSystemStorageManager storageManager = new FileSystemStorageManager(indexPath, false);
    storageManager.open();
    IIndex training = TroveReadWriteHelper.readIndex(storageManager, indexName, TroveContentDBType.Full,
            TroveClassificationDBType.Full);
    storageManager.close();

    IClassifier classifier = classificationLearner.build(training);

    File executableFile = new File(classificationLearnerCustomizer.getSvmPerfLearnPath());
    SvmPerfDataManager dataManager = new SvmPerfDataManager(new SvmPerfClassifierCustomizer(
            executableFile.getParentFile().getAbsolutePath() + Os.pathSeparator() + "svm_perf_classify"));
    String description = "_SVMPerf_C-" + classificationLearnerCustomizer.getC() + "_W-"
            + classificationLearnerCustomizer.getW() + "_L-" + classificationLearnerCustomizer.getL();
    if (classificationLearnerCustomizer.getL() == 4 || classificationLearnerCustomizer.getL() == 5)
        description += "_P-" + classificationLearnerCustomizer.getP();
    if (classificationLearnerCustomizer.getAdditionalParameters().length() > 0)
        description += "_" + classificationLearnerCustomizer.getAdditionalParameters();

    storageManager = new FileSystemStorageManager(indexPath, false);
    storageManager.open();
    dataManager.write(storageManager, indexName + description, classifier);
    storageManager.close();
}

From source file:com.linkedin.restli.tools.snapshot.check.RestLiSnapshotCompatibilityChecker.java

public static void main(String[] args) {
    final Options options = new Options();
    options.addOption("h", "help", false, "Print help");
    options.addOption(OptionBuilder.withArgName("compatibility_level").withLongOpt("compat").hasArg()
            .withDescription("Compatibility level " + listCompatLevelOptions()).create('c'));
    options.addOption(OptionBuilder.withLongOpt("report").withDescription(
            "Prints a report at the end of the execution that can be parsed for reporting to other tools")
            .create("report"));
    final String cmdLineSyntax = RestLiSnapshotCompatibilityChecker.class.getCanonicalName()
            + " [pairs of <prevRestspecPath currRestspecPath>]";

    final CommandLineParser parser = new PosixParser();
    final CommandLine cmd;

    try {// w w w  .j  ava 2 s.co  m
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        new HelpFormatter().printHelp(cmdLineSyntax, options, true);
        System.exit(255);
        return; // to suppress IDE warning
    }

    final String[] targets = cmd.getArgs();
    if (cmd.hasOption('h') || targets.length < 2 || targets.length % 2 != 0) {
        new HelpFormatter().printHelp(cmdLineSyntax, options, true);
        System.exit(255);
    }

    final String compatValue;
    if (cmd.hasOption('c')) {
        compatValue = cmd.getOptionValue('c');
    } else {
        compatValue = CompatibilityLevel.DEFAULT.name();
    }

    final CompatibilityLevel compat;
    try {
        compat = CompatibilityLevel.valueOf(compatValue.toUpperCase());
    } catch (IllegalArgumentException e) {
        new HelpFormatter().printHelp(cmdLineSyntax, options, true);
        System.exit(255);
        return;
    }

    final String resolverPath = System.getProperty(AbstractGenerator.GENERATOR_RESOLVER_PATH);
    final RestLiSnapshotCompatibilityChecker checker = new RestLiSnapshotCompatibilityChecker();
    checker.setResolverPath(resolverPath);

    for (int i = 1; i < targets.length; i += 2) {
        String prevTarget = targets[i - 1];
        String currTarget = targets[i];
        checker.checkCompatibility(prevTarget, currTarget, compat, prevTarget.endsWith(".restspec.json"));
    }

    String summary = checker.getInfoMap().createSummary();

    if (compat != CompatibilityLevel.OFF && summary.length() > 0) {
        System.out.println(summary);
    }

    if (cmd.hasOption("report")) {
        System.out.println(new CompatibilityReport(checker.getInfoMap(), compat).createReport());
        System.exit(0);
    }

    System.exit(checker.getInfoMap().isCompatible(compat) ? 0 : 1);
}

From source file:com.linkedin.restli.tools.idlcheck.RestLiResourceModelCompatibilityChecker.java

public static void main(String[] args) {
    final Options options = new Options();
    options.addOption("h", "help", false, "Print help");
    options.addOption(OptionBuilder.withArgName("compatibility_level").withLongOpt("compat").hasArg()
            .withDescription("Compatibility level " + listCompatLevelOptions()).create('c'));
    options.addOption(OptionBuilder.withLongOpt("report").withDescription(
            "Prints a report at the end of the execution that can be parsed for reporting to other tools")
            .create("report"));
    final String cmdLineSyntax = RestLiResourceModelCompatibilityChecker.class.getCanonicalName()
            + " [pairs of <prevRestspecPath currRestspecPath>]";

    final CommandLineParser parser = new PosixParser();
    final CommandLine cmd;

    try {/* w  w w  .j  av a 2s . co m*/
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        new HelpFormatter().printHelp(cmdLineSyntax, options, true);
        System.exit(255);
        return; // to suppress IDE warning
    }

    final String[] targets = cmd.getArgs();
    if (cmd.hasOption('h') || targets.length < 2 || targets.length % 2 != 0) {
        new HelpFormatter().printHelp(cmdLineSyntax, options, true);
        System.exit(255);
    }

    final String compatValue;
    if (cmd.hasOption('c')) {
        compatValue = cmd.getOptionValue('c');
    } else {
        compatValue = CompatibilityLevel.DEFAULT.name();
    }

    final CompatibilityLevel compat;
    try {
        compat = CompatibilityLevel.valueOf(compatValue.toUpperCase());
    } catch (IllegalArgumentException e) {
        new HelpFormatter().printHelp(cmdLineSyntax, options, true);
        System.exit(255);
        return;
    }

    final StringBuilder allSummaries = new StringBuilder();
    final RestLiResourceModelCompatibilityChecker checker = new RestLiResourceModelCompatibilityChecker();
    for (int i = 1; i < targets.length; i += 2) {
        checker.setResolverPath(System.getProperty(AbstractGenerator.GENERATOR_RESOLVER_PATH));

        String prevTarget = targets[i - 1];
        String currTarget = targets[i];
        checker.check(prevTarget, currTarget, compat);
    }

    allSummaries.append(checker.getInfoMap().createSummary());

    if (compat != CompatibilityLevel.OFF && allSummaries.length() > 0) {
        System.out.println(allSummaries);
    }

    if (cmd.hasOption("report")) {
        System.out.println(new CompatibilityReport(checker.getInfoMap(), compat).createReport());
        System.exit(0);
    }

    System.exit(checker.getInfoMap().isCompatible(compat) ? 0 : 1);
}

From source file:com.aerospike.examples.Main.java

/**
 * Main entry point.//from w w  w.j a v  a2s. c o  m
 */
public static void main(String[] args) {

    try {
        Options options = new Options();
        options.addOption("h", "host", true, "Server hostname (default: localhost)");
        options.addOption("p", "port", true, "Server port (default: 3000)");
        options.addOption("U", "user", true, "User name");
        options.addOption("P", "password", true, "Password");
        options.addOption("n", "namespace", true, "Namespace (default: test)");
        options.addOption("s", "set", true, "Set name. Use 'empty' for empty set (default: demoset)");
        options.addOption("g", "gui", false, "Invoke GUI to selectively run tests.");
        options.addOption("d", "debug", false, "Run in debug mode.");
        options.addOption("u", "usage", false, "Print usage.");

        CommandLineParser parser = new PosixParser();
        CommandLine cl = parser.parse(options, args, false);

        if (args.length == 0 || cl.hasOption("u")) {
            logUsage(options);
            return;
        }
        Parameters params = parseParameters(cl);
        String[] exampleNames = cl.getArgs();

        if ((exampleNames.length == 0) && (!cl.hasOption("g"))) {
            logUsage(options);
            return;
        }

        // Check for all.
        for (String exampleName : exampleNames) {
            if (exampleName.equalsIgnoreCase("all")) {
                exampleNames = ExampleNames;
                break;
            }
        }

        if (cl.hasOption("d")) {
            Log.setLevel(Level.DEBUG);
        }

        if (cl.hasOption("g")) {
            GuiDisplay.startGui(params);
        } else {
            Console console = new Console();
            runExamples(console, params, exampleNames);
        }
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
        ex.printStackTrace();
    }
}

From source file:com.datazuul.iiif.presentation.api.ManifestGenerator.java

public static void main(String[] args)
        throws ParseException, JsonProcessingException, IOException, URISyntaxException {
    Options options = new Options();
    options.addOption("d", true, "Absolute file path to the directory containing the image files.");

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

    if (cmd.hasOption("d")) {
        String imageDirectoryPath = cmd.getOptionValue("d");
        Path imageDirectory = Paths.get(imageDirectoryPath);
        final List<Path> files = new ArrayList<>();
        try {//w w w .j a  va 2 s  . co  m
            Files.walkFileTree(imageDirectory, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    if (!attrs.isDirectory()) {
                        // TODO there must be a more elegant solution for filtering jpeg files...
                        if (file.getFileName().toString().endsWith("jpg")) {
                            files.add(file);
                        }
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
        Collections.sort(files, new Comparator() {
            @Override
            public int compare(Object fileOne, Object fileTwo) {
                String filename1 = ((Path) fileOne).getFileName().toString();
                String filename2 = ((Path) fileTwo).getFileName().toString();

                try {
                    // numerical sorting
                    Integer number1 = Integer.parseInt(filename1.substring(0, filename1.lastIndexOf(".")));
                    Integer number2 = Integer.parseInt(filename2.substring(0, filename2.lastIndexOf(".")));
                    return number1.compareTo(number2);
                } catch (NumberFormatException nfe) {
                    // alpha-numerical sorting
                    return filename1.compareToIgnoreCase(filename2);
                }
            }
        });

        generateManifest(imageDirectory.getFileName().toString(), files);
    } else {
        // automatically generate the help statement
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("ManifestGenerator", options);
    }
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.KyanosMapQueryRenameAllMethods.java

public static void main(String[] args) {
    Options options = new Options();

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input Kyanos resource directory");
    inputOpt.setArgs(1);// w w  w  .j a va 2 s.  c  o m
    inputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(inClassOpt);

    CommandLineParser parser = new PosixParser();

    try {
        PersistenceBackendFactoryRegistry.getFactories().put(NeoMapURI.NEO_MAP_SCHEME,
                new MapPersistenceBackendFactory());

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

        URI uri = NeoMapURI.createNeoMapURI(new File(commandLine.getOptionValue(IN)));

        Class<?> inClazz = KyanosMapQueryRenameAllMethods.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put(NeoMapURI.NEO_MAP_SCHEME,
                PersistentResourceFactory.eINSTANCE);

        Resource resource = resourceSet.createResource(uri);

        Map<String, Object> loadOpts = new HashMap<String, Object>();
        resource.load(loadOpts);
        String name = UUID.randomUUID().toString();
        {
            LOG.log(Level.INFO, "Start query");
            long begin = System.currentTimeMillis();
            JavaQueries.renameAllMethods(resource, name);
            long end = System.currentTimeMillis();
            resource.save(Collections.emptyMap());
            LOG.log(Level.INFO, "End query");
            LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
        }

        if (resource instanceof PersistentResourceImpl) {
            PersistentResourceImpl.shutdownWithoutUnload((PersistentResourceImpl) resource);
        } else {
            resource.unload();
        }

    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:com.ctriposs.rest4j.tools.snapshot.check.Rest4JSnapshotCompatibilityChecker.java

public static void main(String[] args) {
    final Options options = new Options();
    options.addOption("h", "help", false, "Print help");
    options.addOption(OptionBuilder.withArgName("compatibility_level").withLongOpt("compat").hasArg()
            .withDescription("Compatibility level " + listCompatLevelOptions()).create('c'));
    final String cmdLineSyntax = Rest4JSnapshotCompatibilityChecker.class.getCanonicalName()
            + " [pairs of <prevRestspecPath currRestspecPath>]";

    final CommandLineParser parser = new PosixParser();
    final CommandLine cmd;

    try {/*from  w w w.  j  a  va2s .c om*/
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        new HelpFormatter().printHelp(cmdLineSyntax, options, true);
        System.exit(1);
        return; // to suppress IDE warning
    }

    final String[] targets = cmd.getArgs();
    if (cmd.hasOption('h') || targets.length < 2 || targets.length % 2 != 0) {
        new HelpFormatter().printHelp(cmdLineSyntax, options, true);
        System.exit(1);
    }

    final String compatValue;
    if (cmd.hasOption('c')) {
        compatValue = cmd.getOptionValue('c');
    } else {
        compatValue = CompatibilityLevel.DEFAULT.name();
    }

    final CompatibilityLevel compat;
    try {
        compat = CompatibilityLevel.valueOf(compatValue.toUpperCase());
    } catch (IllegalArgumentException e) {
        new HelpFormatter().printHelp(cmdLineSyntax, options, true);
        System.exit(1);
        return;
    }

    final StringBuilder allSummaries = new StringBuilder();
    boolean result = true;
    final String resolverPath = System.getProperty(AbstractGenerator.GENERATOR_RESOLVER_PATH);
    final Rest4JSnapshotCompatibilityChecker checker = new Rest4JSnapshotCompatibilityChecker();
    checker.setResolverPath(resolverPath);

    for (int i = 1; i < targets.length; i += 2) {
        String prevTarget = targets[i - 1];
        String currTarget = targets[i];
        CompatibilityInfoMap infoMap = checker.check(prevTarget, currTarget, compat);
        result &= infoMap.isCompatible(compat);
        allSummaries.append(infoMap.createSummary(prevTarget, currTarget));

    }

    if (compat != CompatibilityLevel.OFF && allSummaries.length() > 0) {
        System.out.println(allSummaries);
    }

    System.exit(result ? 0 : 1);
}

From source file:com.ingby.socbox.bischeck.configuration.DocManager.java

/**
 * @param args//from   w  ww.j a  v a 2s. c  om
 */
public static void main(String[] args) {
    CommandLineParser parser = new GnuParser();
    CommandLine line = null;
    // create the Options
    Options options = new Options();
    options.addOption("u", "usage", false, "show usage.");
    options.addOption("d", "directory", true, "output directory");
    options.addOption("t", "type", true, "type of out put - html or csv");

    try {
        // parse the command line arguments
        line = parser.parse(options, args);

    } catch (org.apache.commons.cli.ParseException e) {
        System.out.println("Command parse error:" + e.getMessage());
        Util.ShellExit(FAILED);
    }

    if (line.hasOption("usage")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("DocManager", options);
        Util.ShellExit(OKAY);
    }

    DocManager dmgmt = null;

    if (line.hasOption("directory")) {
        String dirname = line.getOptionValue("directory");
        try {
            dmgmt = new DocManager(dirname);
        } catch (IOException ioe) {
            System.out.println(ioe.getMessage());
            Util.ShellExit(FAILED);
        }
    } else {
        try {
            dmgmt = new DocManager();
        } catch (IOException ioe) {
            System.out.println(ioe.getMessage());
            Util.ShellExit(FAILED);
        }
    }

    try {
        if (line.hasOption("type")) {
            String type = line.getOptionValue("type");
            if ("html".equalsIgnoreCase(type)) {
                dmgmt.genHtml();
            } else if ("text".equalsIgnoreCase(type)) {
                dmgmt.genText();
            }
        } else {
            dmgmt.genHtml();
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
        Util.ShellExit(FAILED);
    }
}

From source file:de.tudarmstadt.lt.lm.app.GenerateNgrams.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    Options opts = new Options();
    opts.addOption(OptionBuilder.withLongOpt("help").withDescription("Display help message.").create("?"));
    opts.addOption(OptionBuilder.withLongOpt("ptype").withArgName("class").hasArg().withDescription(
            "specify the instance of the language model provider that you want to use: {LtSegProvider, BreakIteratorStringProvider, UimaStringProvider, PreTokenizedStringProvider} (default: LtSegProvider)")
            .create("p"));
    opts.addOption(OptionBuilder.withLongOpt("cardinality").withArgName("ngram-order").hasArg().withDescription(
            "Specify the cardinality of the ngrams (min. 1). Specify a range using 'from-to'. (Examples: 5 = extract 5grams; 1-5 = extract 1grams, 2grams, ..., 5grams; default: 1-5).")
            .create("n"));
    opts.addOption(OptionBuilder.withLongOpt("dir").withArgName("directory").isRequired().hasArg()
            .withDescription(//from   w  w  w .j av a2  s .c  om
                    "specify the directory that contains '.txt' files that are used as source for generating ngrams.")
            .create("d"));
    opts.addOption(OptionBuilder.withLongOpt("overwrite").withDescription("Overwrite existing ngram file.")
            .create("w"));

    CommandLine cli = null;
    try {
        cli = new GnuParser().parse(opts, args);
    } catch (Exception e) {
        print_usage(opts, e.getMessage());
    }
    if (cli.hasOption("?"))
        print_usage(opts, null);

    AbstractStringProvider prvdr = null;
    try {
        prvdr = StartLM
                .getStringProviderInstance(cli.getOptionValue("ptype", LtSegProvider.class.getSimpleName()));
    } catch (Exception e) {
        print_usage(opts, String.format("Could not instantiate LmProvider '%s': %s",
                cli.getOptionValue("ptype", LtSegProvider.class.getSimpleName()), e.getMessage()));
    }

    String n_ = cli.getOptionValue("cardinality", "1-5");
    int dash_index = n_.indexOf('-');
    int n_e = Integer.parseInt(n_.substring(dash_index + 1, n_.length()).trim());
    int n_b = n_e;
    if (dash_index == 0)
        n_b = 1;
    if (dash_index > 0)
        n_b = Math.max(1, Integer.parseInt(n_.substring(0, dash_index).trim()));

    final File src_dir = new File(cli.getOptionValue("dir"));
    boolean overwrite = Boolean.parseBoolean(cli.getOptionValue("overwrite", "false"));

    generateNgrams(src_dir, prvdr, n_b, n_e, overwrite);

}

From source file:com.genentech.retrival.tabExport.TABExporter.java

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

    // create command line Options object
    Options options = new Options();
    Option opt = new Option("sqlFile", true, "sql-xml file");
    opt.setRequired(true);// ww w . ja va2  s .c  o m
    options.addOption(opt);

    opt = new Option("sqlName", true, "name of SQL element in xml file");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option("o", true, "output file");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("newLineReplacement", true,
            "If given newlines in fields will be replaced by this string.");
    options.addOption(opt);

    opt = new Option("noHeader", false, "Do not output header line");
    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 outFile = cmd.getOptionValue("o");
    String sqlFile = cmd.getOptionValue("sqlFile");
    String sqlName = cmd.getOptionValue("sqlName");
    String newLineReplacement = cmd.getOptionValue("newLineReplacement");

    args = cmd.getArgs();

    try {
        PrintStream out = System.out;
        if (outFile != null)
            out = new PrintStream(outFile);

        SQLStatement stmt = SQLStatement.createFromFile(new File(sqlFile), sqlName);
        Object[] sqlArgs = args;
        if (stmt.getParamTypes().length != args.length) {
            System.err.printf(
                    "\nWarining sql statement needs %d parameters but got only %d. Filling up with NULLs.\n",
                    stmt.getParamTypes().length, args.length);
            sqlArgs = new Object[stmt.getParamTypes().length];
            System.arraycopy(args, 0, sqlArgs, 0, args.length);
        }

        Selecter sel = Selecter.factory(stmt);
        if (!sel.select(sqlArgs)) {
            System.err.println("No rows returned!");
            System.exit(0);
        }

        String[] fieldNames = sel.getFieldNames();
        if (fieldNames.length == 0) {
            System.err.println("Query did not return any columns");
            exitWithHelp(options);
        }

        if (!cmd.hasOption("noHeader")) {
            StringBuilder sb = new StringBuilder(200);
            for (String f : fieldNames)
                sb.append(f).append('\t');
            if (sb.length() > 1)
                sb.setLength(sb.length() - 1); // chop last \t
            String header = sb.toString();

            out.println(header);
        }

        StringBuilder sb = new StringBuilder(200);
        while (sel.hasNext()) {
            Record sqlRec = sel.next();
            sb.setLength(0);

            for (int i = 0; i < fieldNames.length; i++) {
                String fld = sqlRec.getStrg(i);
                if (newLineReplacement != null)
                    fld = NEWLinePattern.matcher(fld).replaceAll(newLineReplacement);

                sb.append(fld).append('\t');
            }

            if (sb.length() > 1)
                sb.setLength(sb.length() - 1); // chop last \t
            String row = sb.toString();

            out.println(row);

            nStruct++;
        }

    } catch (Exception e) {
        throw new Error(e);
    } finally {
        System.err.printf("TABExporter: Exported %d records in %dsec\n", nStruct,
                (System.currentTimeMillis() - start) / 1000);
    }
}