Example usage for org.apache.commons.cli CommandLine getOptionValue

List of usage examples for org.apache.commons.cli CommandLine getOptionValue

Introduction

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

Prototype

public String getOptionValue(char opt) 

Source Link

Document

Retrieve the argument, if any, of this option.

Usage

From source file:edu.umass.cs.gnsclient.client.testing.ReplicaLatencyTest.java

/**
 * The main routine run from the command line.
 *
 * @param args//from  w w  w. j a v  a 2s. c om
 * @throws Exception
 */
public static void main(String args[]) throws Exception {
    try {
        CommandLine parser = initializeOptions(args);
        if (parser.hasOption("help") || args.length == 0) {
            printUsage();
            System.exit(1);
        }
        String alias = parser.getOptionValue("alias");
        String host = parser.getOptionValue("host");
        String port = parser.getOptionValue("port");
        boolean debug = parser.hasOption("debug");
        String closeActiveReplica = parser.getOptionValue("closeAR");
        ReplicaLatencyTest test = new ReplicaLatencyTest(alias, host, port);
        // Need this on to read the which replica is responding
        //client.setEnableInstrumentation(true);
        test.findSlowGuid(closeActiveReplica);
        // send the reads and writes
        test.readsAndWrites(closeActiveReplica);
        //test.removeSubGuid();
        client.close();
        System.exit(0);
    } catch (HeadlessException e) {
        System.out
                .println("When running headless you'll need to specify the host and port on the command line");
        printUsage();
        System.exit(1);
    }
}

From source file:com.linkedin.helix.tools.ZKDumper.java

public static void main(String[] args) throws Exception {
    if (args == null || args.length == 0) {
        HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.printHelp("java " + ZKDumper.class.getName(), options);
        System.exit(1);/* ww w. j ava 2 s .  com*/
    }
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);
    cmd.hasOption("zkSvr");
    boolean download = cmd.hasOption("download");
    boolean upload = cmd.hasOption("upload");
    boolean del = cmd.hasOption("delete");
    String zkAddress = cmd.getOptionValue("zkSvr");
    String zkPath = cmd.getOptionValue("zkpath");
    String fsPath = cmd.getOptionValue("fspath");

    ZKDumper zkDump = new ZKDumper(zkAddress);
    if (download) {
        if (cmd.hasOption("addSuffix")) {
            zkDump.suffix = cmd.getOptionValue("addSuffix");
        }
        zkDump.download(zkPath, fsPath + zkPath);
    }
    if (upload) {
        if (cmd.hasOption("removeSuffix")) {
            zkDump.removeSuffix = true;
        }
        zkDump.upload(zkPath, fsPath);
    }
    if (del) {
        zkDump.delete(zkPath);
    }
}

From source file:de.htwg_konstanz.in.uce.hp.parallel.integration_test.SourceMock.java

public static void main(String[] args) {
    CommandLineParser parser = new PosixParser();

    // create the Options
    Options options = new Options();
    Option o = new Option("m", "mediatorIP", true, "mediator ip");
    o.setRequired(true);//from w w w.j  a  v  a2s .co  m
    options.addOption(o);
    o = new Option("p", "mediatorPort", true, "mediator port");
    o.setRequired(true);
    options.addOption(o);
    o = new Option("t", "targetId", true, "target ID");
    o.setRequired(true);
    options.addOption(o);
    o = new Option("d", "description", true, "scenario description");
    o.setRequired(true);
    options.addOption(o);
    o = new Option("sin", "numberOfsimultaneousConnections", true, "number of simultaneous " + "connections");
    o.setRequired(false);
    options.addOption(o);
    o = new Option("si", "simultaneousConnections", false, "simultaneous connections test");
    o.setRequired(false);
    options.addOption(o);
    o = new Option("su", "successiveConnections", false, "successive connections test");
    o.setRequired(false);
    options.addOption(o);
    o = new Option("r", "realisticConnections", false, "realistic connections test");
    o.setRequired(false);
    options.addOption(o);

    CommandLine cmd;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("SourceMock", options);
        return;
    }

    String mediatorIP = cmd.getOptionValue("mediatorIP");
    String mediatorPort = cmd.getOptionValue("mediatorPort");
    String description = cmd.getOptionValue("description");
    String targetId = cmd.getOptionValue("targetId");

    InetSocketAddress mediatorSocketAddress;

    try {
        int port = Integer.parseInt(mediatorPort);
        mediatorSocketAddress = new InetSocketAddress(mediatorIP, port);
    } catch (NumberFormatException e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("SourceMock", options);
        return;
    } catch (IllegalArgumentException e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("SourceMock", options);
        return;
    }

    if (cmd.hasOption("numberOfsimultaneousConnections")) {
        int simConnections = Integer.parseInt(cmd.getOptionValue("numberOfsimultaneousConnections"));
        new SourceMock(description, targetId, mediatorSocketAddress, simConnections).runTests(
                cmd.hasOption("simultaneousConnections"), cmd.hasOption("successiveConnections"),
                cmd.hasOption("realisticConnections"));
    } else {
        new SourceMock(description, targetId, mediatorSocketAddress).runTests(
                cmd.hasOption("simultaneousConnections"), cmd.hasOption("successiveConnections"),
                cmd.hasOption("realisticConnections"));
    }
}

From source file:edu.msu.cme.rdp.multicompare.Reprocess.java

/**
 * This class reprocesses the classification results (allrank output) and print out hierarchy output file, based on the confidence cutoff;
 * and print out only the detail classification results with assignment at certain rank with confidence above the cutoff or/and matching a given taxon.
 * @param args// w w  w  .java2  s.c o  m
 * @throws Exception 
 */
public static void main(String[] args) throws Exception {

    PrintWriter assign_out = new PrintWriter(new NullWriter());
    float conf = 0.8f;
    PrintStream heir_out = null;
    String hier_out_filename = null;
    ClassificationResultFormatter.FORMAT format = ClassificationResultFormatter.FORMAT.allRank;
    String rank = null;
    String taxonFilterFile = null;
    String train_propfile = null;
    String gene = null;
    List<MCSample> samples = new ArrayList();

    try {
        CommandLine line = new PosixParser().parse(options, args);
        if (line.hasOption(CmdOptions.HIER_OUTFILE_SHORT_OPT)) {
            hier_out_filename = line.getOptionValue(CmdOptions.HIER_OUTFILE_SHORT_OPT);
            heir_out = new PrintStream(hier_out_filename);
        } else {
            throw new Exception(
                    "It make sense to provide output filename for " + CmdOptions.HIER_OUTFILE_LONG_OPT);
        }
        if (line.hasOption(CmdOptions.OUTFILE_SHORT_OPT)) {
            assign_out = new PrintWriter(line.getOptionValue(CmdOptions.OUTFILE_SHORT_OPT));
        }

        if (line.hasOption(CmdOptions.RANK_SHORT_OPT)) {
            rank = line.getOptionValue(CmdOptions.RANK_SHORT_OPT);
        }
        if (line.hasOption(CmdOptions.TAXON_SHORT_OPT)) {
            taxonFilterFile = line.getOptionValue(CmdOptions.TAXON_SHORT_OPT);
        }

        if (line.hasOption(CmdOptions.BOOTSTRAP_SHORT_OPT)) {
            conf = Float.parseFloat(line.getOptionValue(CmdOptions.BOOTSTRAP_SHORT_OPT));
            if (conf < 0 || conf > 1) {
                throw new IllegalArgumentException("Confidence must be in the range [0,1]");
            }
        }
        if (line.hasOption(CmdOptions.FORMAT_SHORT_OPT)) {
            String f = line.getOptionValue(CmdOptions.FORMAT_SHORT_OPT);
            if (f.equalsIgnoreCase("allrank")) {
                format = ClassificationResultFormatter.FORMAT.allRank;
            } else if (f.equalsIgnoreCase("fixrank")) {
                format = ClassificationResultFormatter.FORMAT.fixRank;
            } else if (f.equalsIgnoreCase("db")) {
                format = ClassificationResultFormatter.FORMAT.dbformat;
            } else if (f.equalsIgnoreCase("filterbyconf")) {
                format = ClassificationResultFormatter.FORMAT.filterbyconf;
            } else {
                throw new IllegalArgumentException(
                        "Not valid output format, only allrank, fixrank, filterbyconf and db allowed");
            }
        }
        if (line.hasOption(CmdOptions.TRAINPROPFILE_SHORT_OPT)) {
            if (gene != null) {
                throw new IllegalArgumentException(
                        "Already specified the gene from the default location. Can not specify train_propfile");
            } else {
                train_propfile = line.getOptionValue(CmdOptions.TRAINPROPFILE_SHORT_OPT);
            }
        }
        if (line.hasOption(CmdOptions.GENE_SHORT_OPT)) {
            if (train_propfile != null) {
                throw new IllegalArgumentException(
                        "Already specified train_propfile. Can not specify gene any more");
            }
            gene = line.getOptionValue(CmdOptions.GENE_SHORT_OPT).toLowerCase();

            if (!gene.equals(ClassifierFactory.RRNA_16S_GENE) && !gene.equals(ClassifierFactory.FUNGALLSU_GENE)
                    && !gene.equals(ClassifierFactory.FUNGALITS_warcup_GENE)
                    && !gene.equals(ClassifierFactory.FUNGALITS_unite_GENE)) {
                throw new IllegalArgumentException(gene + " is NOT valid, only allows "
                        + ClassifierFactory.RRNA_16S_GENE + ", " + ClassifierFactory.FUNGALLSU_GENE + ", "
                        + ClassifierFactory.FUNGALITS_warcup_GENE + " and "
                        + ClassifierFactory.FUNGALITS_unite_GENE);
            }
        }
        args = line.getArgs();
        if (args.length < 1) {
            throw new Exception("Incorrect number of command line arguments");
        }

        for (String arg : args) {
            String[] inFileNames = arg.split(",");
            String inputFile = inFileNames[0];
            File idmappingFile = null;

            if (inFileNames.length == 2) {
                idmappingFile = new File(inFileNames[1]);
                if (!idmappingFile.exists()) {
                    System.err.println("Failed to find input file \"" + inFileNames[1] + "\"");
                    return;
                }
            }

            MCSample nextSample = new MCSampleResult(inputFile, idmappingFile);
            samples.add(nextSample);

        }
    } catch (Exception e) {
        System.out.println("Command Error: " + e.getMessage());
        new HelpFormatter().printHelp(120,
                "Reprocess [options] <Classification_allrank_result>[,idmappingfile] ...", "", options, "");
        return;
    }

    if (train_propfile == null && gene == null) {
        gene = ClassifierFactory.RRNA_16S_GENE;
    }

    HashSet<String> taxonFilter = null;
    if (taxonFilterFile != null) {
        taxonFilter = readTaxonFilterFile(taxonFilterFile);
    }

    MultiClassifier multiClassifier = new MultiClassifier(train_propfile, gene);
    DefaultPrintVisitor printVisitor = new DefaultPrintVisitor(heir_out, samples);
    MultiClassifierResult result = multiClassifier.multiClassificationParser(samples, conf, assign_out, format,
            rank, taxonFilter);

    result.getRoot().topDownVisit(printVisitor);

    assign_out.close();
    heir_out.close();
    if (multiClassifier.hasCopyNumber()) {
        // print copy number corrected counts
        File cn_corrected_s = new File(new File(hier_out_filename).getParentFile(),
                "cncorrected_" + hier_out_filename);
        PrintStream cn_corrected_hier_out = new PrintStream(cn_corrected_s);
        printVisitor = new DefaultPrintVisitor(cn_corrected_hier_out, samples, true);
        result.getRoot().topDownVisit(printVisitor);
        cn_corrected_hier_out.close();
    }

}

From source file:com.act.lcms.v2.fullindex.Builder.java

public static void main(String[] args) throws Exception {
    CLIUtil cliUtil = new CLIUtil(Builder.class, HELP_MESSAGE, OPTION_BUILDERS);
    CommandLine cl = cliUtil.parseCommandLine(args);

    File inputFile = new File(cl.getOptionValue(OPTION_SCAN_FILE));
    if (!inputFile.exists()) {
        cliUtil.failWithMessage("Cannot find input scan file at %s", inputFile.getAbsolutePath());
    }//ww  w .ja v  a 2s  . c  o  m

    File indexDir = new File(cl.getOptionValue(OPTION_INDEX_PATH));
    if (indexDir.exists()) {
        cliUtil.failWithMessage("Index file at %s already exists--remove and retry",
                indexDir.getAbsolutePath());
    }

    Builder indexBuilder = Factory.makeBuilder(indexDir);
    try {
        indexBuilder.processScan(indexBuilder.makeTargetMasses(), inputFile);
    } finally {
        if (indexBuilder != null) {
            indexBuilder.close();
        }
    }

    LOGGER.info("Done");
}

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();// w  w  w .  j  a va 2  s.com

    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:cd.what.DutchBot.Main.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws IOException, IrcException, InterruptedException,
        ConfigurationException, InstantiationException, IllegalAccessException {
    String configfile = "irc.properties";
    DutchBot bot = null;/*from www  .  j  av a 2  s .  com*/

    Options options = new Options();
    options.addOption(OptionBuilder.withLongOpt("config").withArgName("configfile").hasArg()
            .withDescription("Load configuration from configfile, or use the default irc.cfg").create("c"));
    options.addOption(OptionBuilder.withLongOpt("server").withArgName("<url>").hasArg()
            .withDescription("Connect to this server").create("s"));
    options.addOption(OptionBuilder.withLongOpt("port").hasArg().withArgName("port")
            .withDescription("Connect to the server with this port").create("p"));
    options.addOption(OptionBuilder.withLongOpt("password").hasArg().withArgName("password")
            .withDescription("Connect to the server with this password").create("pw"));
    options.addOption(OptionBuilder.withLongOpt("nick").hasArg().withArgName("nickname")
            .withDescription("Connect to the server with this nickname").create("n"));
    options.addOption(OptionBuilder.withLongOpt("nspass").hasArg().withArgName("password")
            .withDescription("Sets the password for NickServ").create("ns"));
    options.addOption("h", "help", false, "Displays this menu");

    try {
        CommandLineParser parser = new GnuParser();
        CommandLine cli = parser.parse(options, args);
        if (cli.hasOption("h")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("DutchBot", options);
            return;
        }
        // check for override config file
        if (cli.hasOption("c"))
            configfile = cli.getOptionValue("c");

        bot = new DutchBot(configfile);

        // Read the cli parameters
        if (cli.hasOption("pw"))
            bot.setServerPassword(cli.getOptionValue("pw"));
        if (cli.hasOption("s"))
            bot.setServerAddress(cli.getOptionValue("s"));
        if (cli.hasOption("p"))
            bot.setIrcPort(Integer.parseInt(cli.getOptionValue("p")));
        if (cli.hasOption("n"))
            bot.setBotName(cli.getOptionValue("n"));
        if (cli.hasOption("ns"))
            bot.setNickservPassword(cli.getOptionValue("ns"));

    } catch (ParseException e) {
        System.err.println("Error parsing command line vars " + e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("DutchBot", options);
        System.exit(1);
    }

    boolean result = bot.tryConnect();

    if (result)
        bot.logMessage("Connected");
    else {
        System.out.println(" Connecting failed :O");
        System.exit(1);
    }
}

From source file:com.act.lcms.v2.MZCollisionCounter.java

public static void main(String[] args) throws Exception {
    CLIUtil cliUtil = new CLIUtil(MassChargeCalculator.class, HELP_MESSAGE, OPTION_BUILDERS);
    CommandLine cl = cliUtil.parseCommandLine(args);

    File inputFile = new File(cl.getOptionValue(OPTION_INPUT_INCHI_LIST));
    if (!inputFile.exists()) {
        cliUtil.failWithMessage("Input file at does not exist at %s", inputFile.getAbsolutePath());
    }/*from  w  w  w.j  a  va  2 s  .com*/

    List<MassChargeCalculator.MZSource> sources = new ArrayList<>();
    try (BufferedReader reader = new BufferedReader(new FileReader(inputFile))) {
        String line;
        while ((line = reader.readLine()) != null) {
            line = line.trim();
            sources.add(new MassChargeCalculator.MZSource(line));
            if (sources.size() % 1000 == 0) {
                LOGGER.info("Loaded %d sources from input file", sources.size());
            }
        }
    }

    Set<String> considerIons = Collections.emptySet();
    if (cl.hasOption(OPTION_ONLY_CONSIDER_IONS)) {
        List<String> ions = Arrays.asList(cl.getOptionValues(OPTION_ONLY_CONSIDER_IONS));
        LOGGER.info("Only considering ions for m/z calculation: %s", StringUtils.join(ions, ", "));
        considerIons = new HashSet<>(ions);
    }

    TSVWriter<String, Long> tsvWriter = new TSVWriter<>(Arrays.asList("collisions", "count"));
    tsvWriter.open(new File(cl.getOptionValue(OPTION_OUTPUT_FILE)));

    try {
        LOGGER.info("Loaded %d sources in total from input file", sources.size());

        MassChargeCalculator.MassChargeMap mzMap = MassChargeCalculator.makeMassChargeMap(sources,
                considerIons);

        if (!cl.hasOption(OPTION_COUNT_WINDOW_INTERSECTIONS)) {
            // Do an exact analysis of the m/z collisions if windowing is not specified.

            LOGGER.info("Computing precise collision histogram.");
            Iterable<Double> mzs = mzMap.ionMZIter();
            Map<Integer, Long> collisionHistogram = histogram(
                    StreamSupport.stream(mzs.spliterator(), false).map(mz -> { // See comment about Iterable below.
                        try {
                            return mzMap.ionMZToMZSources(mz).size();
                        } catch (NoSuchElementException e) {
                            LOGGER.error("Caught no such element exception for mz %f: %s", mz, e.getMessage());
                            throw e;
                        }
                    }));
            List<Integer> sortedCollisions = new ArrayList<>(collisionHistogram.keySet());
            Collections.sort(sortedCollisions);
            for (Integer collision : sortedCollisions) {
                tsvWriter.append(new HashMap<String, Long>() {
                    {
                        put("collisions", collision.longValue());
                        put("count", collisionHistogram.get(collision));
                    }
                });
            }
        } else {
            /* After some deliberation (thanks Gil!), the windowed variant of this calculation counts the number of
             * structures whose 0.01 Da m/z windows (for some set of ions) overlap with each other.
             *
             * For example, let's assume we have five total input structures, and are only searching for one ion.  Let's
             * also assume that three of those structures have m/z A and the remaining two have m/z B.  The windows might
             * look like this in the m/z domain:
             * |----A----|
             *        |----B----|
             * Because A represents three structures and overlaps with B, which represents two, we assign A a count of 5--
             * this is the number of structures we believe could fall into the range of A given our current peak calling
             * approach.  Similarly, B is assigned a count of 5, as the possibility for collision/confusion is symmetric.
             *
             * Note that this is an over-approximation of collisions, as we could more precisely only consider intersections
             * when the exact m/z of B falls within the window around A and vice versa.  However, because we have observed
             * cases where the MS sensor doesn't report structures at exactly the m/z we predict, we employ this weaker
             * definition of intersection to give a slightly pessimistic view of what confusions might be possible. */
            // Compute windows for every m/z.  We don't care about the original mz values since we just want the count.
            List<Double> mzs = mzMap.ionMZsSorted();

            final Double windowHalfWidth;
            if (cl.hasOption(OPTION_WINDOW_HALFWIDTH)) {
                // Don't use get with default for this option, as we want the exact FP value of the default tolerance.
                windowHalfWidth = Double.valueOf(cl.getOptionValue(OPTION_WINDOW_HALFWIDTH));
            } else {
                windowHalfWidth = DEFAULT_WINDOW_TOLERANCE;
            }

            /* Window = (lower bound, upper bound), counter of represented m/z's that collide with this window, and number
             * of representative structures (which will be used in counting collisions). */
            LinkedList<CollisionWindow> allWindows = new LinkedList<CollisionWindow>() {
                {
                    for (Double mz : mzs) {
                        // CPU for memory trade-off: don't re-compute the window bounds over and over and over and over and over.
                        try {
                            add(new CollisionWindow(mz, windowHalfWidth, mzMap.ionMZToMZSources(mz).size()));
                        } catch (NoSuchElementException e) {
                            LOGGER.error("Caught no such element exception for mz %f: %s", mz, e.getMessage());
                            throw e;
                        }
                    }
                }
            };

            // Sweep line time!  The window ranges are the interesting points.  We just accumulate overlap counts as we go.
            LinkedList<CollisionWindow> workingSet = new LinkedList<>();
            List<CollisionWindow> finished = new LinkedList<>();

            while (allWindows.size() > 0) {
                CollisionWindow thisWindow = allWindows.pop();
                // Remove any windows from the working set that don't overlap with the next window.
                while (workingSet.size() > 0 && workingSet.peekFirst().getMaxMZ() < thisWindow.getMinMZ()) {
                    finished.add(workingSet.pop());
                }

                for (CollisionWindow w : workingSet) {
                    /* Add the size of the new overlapping window's structure count to each of the windows in the working set,
                     * which represents the number of possible confused structures that fall within the overlapping region.
                     * We exclude the window itself as it should already have counted the colliding structures it represents. */
                    w.getAccumulator().add(thisWindow.getStructureCount());

                    /* Reciprocally, add the structure counts of all windows with which the current window overlaps to it. */
                    thisWindow.getAccumulator().add(w.getStructureCount());
                }

                // Now that accumulation is complete, we can safely add the current window.
                workingSet.add(thisWindow);
            }

            // All the interesting events are done, so drop the remaining windows into the finished set.
            finished.addAll(workingSet);

            Map<Long, Long> collisionHistogram = histogram(
                    finished.stream().map(w -> w.getAccumulator().longValue()));
            List<Long> sortedCollisions = new ArrayList<>(collisionHistogram.keySet());
            Collections.sort(sortedCollisions);
            for (Long collision : sortedCollisions) {
                tsvWriter.append(new HashMap<String, Long>() {
                    {
                        put("collisions", collision);
                        put("count", collisionHistogram.get(collision));
                    }
                });
            }
        }
    } finally {
        if (tsvWriter != null) {
            tsvWriter.close();
        }
    }
}

From source file:io.github.dustalov.maxmax.Application.java

public static void main(String[] args) throws IOException {
    final CommandLineParser parser = new DefaultParser();

    final Options options = new Options();
    options.addOption(Option.builder("in").argName("in").desc("input graph in the ABC format").hasArg()
            .required().build());/*from ww w . j av a 2  s. co  m*/
    options.addOption(Option.builder("out").argName("out").desc("name of cluster output file").hasArg()
            .required().build());

    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (final ParseException ex) {
        System.err.println(ex.getMessage());
        final HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar this.jar", options, true);
        System.exit(1);
    }

    final UndirectedGraph<String, DefaultWeightedEdge> graph = parse(cmd.getOptionValue("in"),
            ABCParser::parse);
    final MaxMax<String> maxmax = new MaxMax<>(graph);
    maxmax.run();
    write(cmd.getOptionValue("out"), maxmax);
}

From source file:jena.RuleMap.java

/**
 * General command line utility to process one RDF file into another
 * by application of a set of forward chaining rules. 
 * <pre>/*w  w w . j  av a2 s  . c  om*/
 * Usage:  RuleMap [-il inlang] [-ol outlang] -d infile rulefile
 * </pre>
 */
public static void main(String[] args) {
    try {

        // Parse the command line
        String usage = "Usage:  RuleMap [-il inlang] [-ol outlang] [-d] rulefile infile (- for stdin)";
        final CommandLineParser parser = new DefaultParser();
        Options options = new Options().addOption("il", "inputLang", true, "input language")
                .addOption("ol", "outputLang", true, "output language").addOption("d", "Deductions only?");
        CommandLine cl = parser.parse(options, args);
        final List<String> filenameArgs = cl.getArgList();
        if (filenameArgs.size() != 2) {
            System.err.println(usage);
            System.exit(1);
        }

        String inLang = cl.getOptionValue("inputLang");
        String fname = filenameArgs.get(1);
        Model inModel = null;
        if (fname.equals("-")) {
            inModel = ModelFactory.createDefaultModel();
            inModel.read(System.in, null, inLang);
        } else {
            inModel = FileManager.get().loadModel(fname, inLang);
        }

        String outLang = cl.hasOption("outputLang") ? cl.getOptionValue("outputLang") : "N3";

        boolean deductionsOnly = cl.hasOption('d');

        // Fetch the rule set and create the reasoner
        BuiltinRegistry.theRegistry.register(new Deduce());
        Map<String, String> prefixes = new HashMap<>();
        List<Rule> rules = loadRules(filenameArgs.get(0), prefixes);
        Reasoner reasoner = new GenericRuleReasoner(rules);

        // Process
        InfModel infModel = ModelFactory.createInfModel(reasoner, inModel);
        infModel.prepare();
        infModel.setNsPrefixes(prefixes);

        // Output
        try (PrintWriter writer = new PrintWriter(System.out)) {
            if (deductionsOnly) {
                Model deductions = infModel.getDeductionsModel();
                deductions.setNsPrefixes(prefixes);
                deductions.setNsPrefixes(inModel);
                deductions.write(writer, outLang);
            } else {
                infModel.write(writer, outLang);
            }
        }
    } catch (Throwable t) {
        System.err.println("An error occured: \n" + t);
        t.printStackTrace();
    }
}