Example usage for org.apache.commons.cli HelpFormatter setWidth

List of usage examples for org.apache.commons.cli HelpFormatter setWidth

Introduction

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

Prototype

public void setWidth(int width) 

Source Link

Document

Sets the 'width'.

Usage

From source file:com.asakusafw.compiler.bootstrap.OperatorCompilerDriver.java

/**
 * //from   w  w w .  ja  v  a 2s .  c o m
 * @param args 
 */
public static void main(String... args) {
    try {
        start(args);
    } catch (Exception e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(Integer.MAX_VALUE);
        formatter.printHelp(MessageFormat.format("java -classpath ... {0}", //$NON-NLS-1$
                OperatorCompilerDriver.class.getName()), OPTIONS, true);
        e.printStackTrace(System.out);
        System.exit(1);
    }
}

From source file:SequentialPersonalizedPageRank.java

@SuppressWarnings({ "static-access" })
public static void main(String[] args) throws IOException {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT));
    options.addOption(/*from   w  ww . j av  a  2s .c  o m*/
            OptionBuilder.withArgName("val").hasArg().withDescription("random jump factor").create(JUMP));
    options.addOption(OptionBuilder.withArgName("node").hasArg()
            .withDescription("source node (i.e., destination of the random jump)").create(SOURCE));

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();

    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(INPUT) || !cmdline.hasOption(SOURCE)) {
        System.out.println("args: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(120);
        formatter.printHelp(SequentialPersonalizedPageRank.class.getName(), options);
        ToolRunner.printGenericCommandUsage(System.out);
        System.exit(-1);
    }

    String infile = cmdline.getOptionValue(INPUT);
    final String source = cmdline.getOptionValue(SOURCE);
    float alpha = cmdline.hasOption(JUMP) ? Float.parseFloat(cmdline.getOptionValue(JUMP)) : 0.15f;

    int edgeCnt = 0;
    DirectedSparseGraph<String, Integer> graph = new DirectedSparseGraph<String, Integer>();

    BufferedReader data = new BufferedReader(new InputStreamReader(new FileInputStream(infile)));

    String line;
    while ((line = data.readLine()) != null) {
        line.trim();
        String[] arr = line.split("\\t");

        for (int i = 1; i < arr.length; i++) {
            graph.addEdge(new Integer(edgeCnt++), arr[0], arr[i]);
        }
    }

    data.close();

    if (!graph.containsVertex(source)) {
        System.err.println("Error: source node not found in the graph!");
        System.exit(-1);
    }

    WeakComponentClusterer<String, Integer> clusterer = new WeakComponentClusterer<String, Integer>();

    Set<Set<String>> components = clusterer.transform(graph);
    int numComponents = components.size();
    System.out.println("Number of components: " + numComponents);
    System.out.println("Number of edges: " + graph.getEdgeCount());
    System.out.println("Number of nodes: " + graph.getVertexCount());
    System.out.println("Random jump factor: " + alpha);

    // Compute personalized PageRank.
    PageRankWithPriors<String, Integer> ranker = new PageRankWithPriors<String, Integer>(graph,
            new Transformer<String, Double>() {
                @Override
                public Double transform(String vertex) {
                    return vertex.equals(source) ? 1.0 : 0;
                }
            }, alpha);

    ranker.evaluate();

    // Use priority queue to sort vertices by PageRank values.
    PriorityQueue<Ranking<String>> q = new PriorityQueue<Ranking<String>>();
    int i = 0;
    for (String pmid : graph.getVertices()) {
        q.add(new Ranking<String>(i++, ranker.getVertexScore(pmid), pmid));
    }

    // Print PageRank values.
    System.out.println("\nPageRank of nodes, in descending order:");
    Ranking<String> r = null;
    while ((r = q.poll()) != null) {
        System.out.println(r.rankScore + "\t" + r.getRanked());
    }
}

From source file:edu.umd.shrawanraina.SequentialPersonalizedPageRank.java

@SuppressWarnings({ "static-access" })
public static void main(String[] args) throws IOException {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT));
    options.addOption(/*from   w  ww  . ja  v  a  2s  .  c o m*/
            OptionBuilder.withArgName("val").hasArg().withDescription("random jump factor").create(JUMP));
    options.addOption(OptionBuilder.withArgName("node").hasArg()
            .withDescription("source node (i.e., destination of the random jump)").create(SOURCE));

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();

    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(INPUT) || !cmdline.hasOption(SOURCE)) {
        System.out.println("args: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(120);
        formatter.printHelp(SequentialPersonalizedPageRank.class.getName(), options);
        ToolRunner.printGenericCommandUsage(System.out);
        System.exit(-1);
    }

    String infile = cmdline.getOptionValue(INPUT);
    final String source = cmdline.getOptionValue(SOURCE);
    float alpha = cmdline.hasOption(JUMP) ? Float.parseFloat(cmdline.getOptionValue(JUMP)) : 0.15f;

    int edgeCnt = 0;
    DirectedSparseGraph<String, Integer> graph = new DirectedSparseGraph<String, Integer>();

    BufferedReader data = new BufferedReader(new InputStreamReader(new FileInputStream(infile)));

    String line;
    while ((line = data.readLine()) != null) {
        line.trim();
        String[] arr = line.split("\\t");

        for (int i = 1; i < arr.length; i++) {
            graph.addEdge(new Integer(edgeCnt++), arr[0], arr[i]);
        }
    }

    data.close();

    if (!graph.containsVertex(source)) {
        System.err.println("Error: source node not found in the graph!");
        System.exit(-1);
    }

    WeakComponentClusterer<String, Integer> clusterer = new WeakComponentClusterer<String, Integer>();

    Set<Set<String>> components = clusterer.transform(graph);
    int numComponents = components.size();
    System.out.println("Number of components: " + numComponents);
    System.out.println("Number of edges: " + graph.getEdgeCount());
    System.out.println("Number of nodes: " + graph.getVertexCount());
    System.out.println("Random jump factor: " + alpha);

    // Compute personalized PageRank.
    PageRankWithPriors<String, Integer> ranker = new PageRankWithPriors<String, Integer>(graph,
            new Transformer<String, Double>() {
                public Double transform(String vertex) {
                    return vertex.equals(source) ? 1.0 : 0;
                }
            }, alpha);

    ranker.evaluate();

    // Use priority queue to sort vertices by PageRank values.
    PriorityQueue<Ranking<String>> q = new PriorityQueue<Ranking<String>>();
    int i = 0;
    for (String pmid : graph.getVertices()) {
        q.add(new Ranking<String>(i++, ranker.getVertexScore(pmid), pmid));
    }

    // Print PageRank values.
    System.out.println("\nPageRank of nodes, in descending order:");
    Ranking<String> r = null;
    while ((r = q.poll()) != null) {
        System.out.println(r.rankScore + "\t" + r.getRanked());
    }
}

From source file:io.anserini.index.IndexGov2.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(/*  ww w .  j  a v a 2s . c o  m*/
            OptionBuilder.withArgName("path").hasArg().withDescription("input data path").create(INPUT_OPTION));
    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("output index path")
            .create(INDEX_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of indexer threads")
            .create(THREADS_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg()
            .withDescription("max number of documents to index (-1 to index everything)")
            .create(DOCLIMIT_OPTION));

    options.addOption(POSITIONS_OPTION, false, "index positions");
    options.addOption(OPTIMIZE_OPTION, false, "merge all index segments");

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();
    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(INPUT_OPTION) || !cmdline.hasOption(INDEX_OPTION)
            || !cmdline.hasOption(THREADS_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(100);
        formatter.printHelp(IndexGov2.class.getCanonicalName(), options);
        System.exit(-1);
    }

    final String dirPath = cmdline.getOptionValue(INDEX_OPTION);
    final String dataDir = cmdline.getOptionValue(INPUT_OPTION);
    final int docCountLimit = cmdline.hasOption(DOCLIMIT_OPTION)
            ? Integer.parseInt(cmdline.getOptionValue(DOCLIMIT_OPTION))
            : -1;
    final int numThreads = Integer.parseInt(cmdline.getOptionValue(THREADS_OPTION));

    final boolean doUpdate = cmdline.hasOption(UPDATE_OPTION);
    final boolean positions = cmdline.hasOption(POSITIONS_OPTION);
    final boolean optimize = cmdline.hasOption(OPTIMIZE_OPTION);

    final Analyzer a = new EnglishAnalyzer();
    final TrecContentSource trecSource = createGov2Source(dataDir);
    final Directory dir = FSDirectory.open(Paths.get(dirPath));

    LOG.info("Index path: " + dirPath);
    LOG.info("Doc limit: " + (docCountLimit == -1 ? "all docs" : "" + docCountLimit));
    LOG.info("Threads: " + numThreads);
    LOG.info("Positions: " + positions);
    LOG.info("Optimize (merge segments): " + optimize);

    final IndexWriterConfig config = new IndexWriterConfig(a);

    if (doUpdate) {
        config.setOpenMode(IndexWriterConfig.OpenMode.APPEND);
    } else {
        config.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
    }

    final IndexWriter writer = new IndexWriter(dir, config);
    Gov2IndexThreads threads = new Gov2IndexThreads(writer, positions, trecSource, numThreads, docCountLimit);
    LOG.info("Indexer: start");

    final long t0 = System.currentTimeMillis();

    threads.start();

    while (!threads.done()) {
        Thread.sleep(100);
    }
    threads.stop();

    final long t1 = System.currentTimeMillis();
    LOG.info("Indexer: indexing done (" + (t1 - t0) / 1000.0 + " sec); total " + writer.maxDoc() + " docs");
    if (!doUpdate && docCountLimit != -1 && writer.maxDoc() != docCountLimit) {
        throw new RuntimeException("w.maxDoc()=" + writer.maxDoc() + " but expected " + docCountLimit);
    }
    if (threads.failed.get()) {
        throw new RuntimeException("exceptions during indexing");
    }

    final long t2;
    t2 = System.currentTimeMillis();

    final Map<String, String> commitData = new HashMap<String, String>();
    commitData.put("userData", "multi");
    writer.setCommitData(commitData);
    writer.commit();
    final long t3 = System.currentTimeMillis();
    LOG.info("Indexer: commit multi (took " + (t3 - t2) / 1000.0 + " sec)");

    if (optimize) {
        LOG.info("Indexer: merging all segments");
        writer.forceMerge(1);
        final long t4 = System.currentTimeMillis();
        LOG.info("Indexer: segments merged (took " + (t4 - t3) / 1000.0 + " sec)");
    }

    LOG.info("Indexer: at close: " + writer.segString());
    final long tCloseStart = System.currentTimeMillis();
    writer.close();
    LOG.info("Indexer: close took " + (System.currentTimeMillis() - tCloseStart) / 1000.0 + " sec");
    dir.close();
    final long tFinal = System.currentTimeMillis();
    LOG.info("Indexer: finished (" + (tFinal - t0) / 1000.0 + " sec)");
    LOG.info("Indexer: net bytes indexed " + threads.getBytesIndexed());
    LOG.info("Indexer: " + (threads.getBytesIndexed() / 1024. / 1024. / 1024. / ((tFinal - t0) / 3600000.))
            + " GB/hour plain text");
}

From source file:eu.freme.bpt.Main.java

public static void main(String[] args) {
    final List<String> services = new ArrayList<>();
    for (EService eService : EService.values()) {
        services.add(eService.getName());
    }/*w w  w .  ja v  a  2s. c o m*/

    Pair<EService, String[]> serviceAndArgs = extractService(args, services);

    EService service = serviceAndArgs.getName();

    // create options that will be parsed from the args
    /////// General BPT options ///////
    Option helpOption = new Option("h", "help", false, "Prints this message");
    Option inputOption = Option.builder("if").longOpt("input-file").argName("input file").desc(
            "The input file or directory to process. In case of a directory, each file in that directory is processed. "
                    + "If not given, standard in is used.")
            .hasArg().build();
    Option outputOption = Option.builder("od").longOpt("output-dir").argName("output dir")
            .desc("The output directory. If not given, output is written to standard out.").hasArg().build();
    Option propertiesOption = Option.builder("prop").longOpt("properties").argName("properties file")
            .desc("The properties file that contains configuration of the tool.").hasArg().build();

    Options options = new Options().addOption(helpOption).addOption(inputOption).addOption(outputOption)
            .addOption(propertiesOption);

    /////// Common service options ///////
    Option informatOption = Option.builder("f").longOpt("informat").argName("FORMAT")
            .desc("The format of the input document(s). Defaults to 'turtle'").hasArg().build();
    Option outformatOption = Option.builder("o").longOpt("outformat").argName("FORMAT")
            .desc("The desired output format of the service. Defaults to 'turtle'").hasArg().build();
    options.addOption(informatOption).addOption(outformatOption);

    /////// Service specific options ///////
    if (service != null) {
        switch (service) {
        case E_TRANSLATION:
            ETranslation.addOptions(options);
            break;
        case E_ENTITY:
            EEntity.addOptions(options);
            break;
        case E_LINK:
            ELink.addOptions(options);
            break;
        case E_TERMINOLOGY:
            ETerminology.addOptions(options);
            break;
        case PIPELINING:
            Pipelining.addOptions(options);
            break;
        case E_PUBLISHING:
            // TODO !
        default:
            logger.warn("Unknown service {}. Skipping!", service);
            break;
        }
    } else {
        ETranslation.addOptions(options);
        EEntity.addOptions(options);
        ELink.addOptions(options);
        ETerminology.addOptions(options);
        Pipelining.addOptions(options);
    }

    CommandLine commandLine = null;
    int exitValue;
    try {
        CommandLineParser parser = new DefaultParser();
        commandLine = parser.parse(options, serviceAndArgs.getValue());
        exitValue = 0;
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        exitValue = 1;
    }
    if ((exitValue != 0) || commandLine.hasOption("h") || service == null) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(132);
        formatter.printHelp("java -jar <this jar file> <e-service> ", options, true);
        System.exit(exitValue);
    }

    logger.debug("Commandline successfully parsed!");

    try {
        BPT batchProcessingTool = new BPT();
        if (commandLine.hasOption("prop")) {
            batchProcessingTool.loadProperties(commandLine.getOptionValue("prop"));
        }
        if (commandLine.hasOption("if")) {
            batchProcessingTool.setInput(commandLine.getOptionValue("if"));
        }
        if (commandLine.hasOption("od")) {
            batchProcessingTool.setOutput(commandLine.getOptionValue("od"));
        }
        if (commandLine.hasOption('f')) {
            batchProcessingTool.setInFormat(Format.valueOf(commandLine.getOptionValue('f').replace('-', '_')));
        }
        if (commandLine.hasOption('o')) {
            batchProcessingTool.setOutFormat(Format.valueOf(commandLine.getOptionValue('o').replace('-', '_')));
        }

        switch (service) {
        case E_TRANSLATION:
            batchProcessingTool.eTranslation(commandLine.getOptionValue("source-lang"),
                    commandLine.getOptionValue("target-lang"), commandLine.getOptionValue("system"),
                    commandLine.getOptionValue("domain"), commandLine.getOptionValue("key"));
            break;
        case E_ENTITY:
            batchProcessingTool.eEntity(commandLine.getOptionValue("language"),
                    commandLine.getOptionValue("dataset"), commandLine.getOptionValue("mode"));
            break;
        case E_LINK:
            batchProcessingTool.eLink(commandLine.getOptionValue("templateid"));
            break;
        case E_TERMINOLOGY:
            batchProcessingTool.eTerminology(commandLine.getOptionValue("source-lang"),
                    commandLine.getOptionValue("target-lang"), commandLine.getOptionValue("collection"),
                    commandLine.getOptionValue("domain"), commandLine.getOptionValue("key"),
                    commandLine.getOptionValue("mode"));
            break;
        case PIPELINING:
            batchProcessingTool.pipelining(commandLine.getOptionValue("templateid"));
            break;
        case E_PUBLISHING:
        default:
            logger.error("Unknown service {}. Aborting!", service);
            System.exit(3);
        }
    } catch (Exception e) {
        logger.error("Cannot handle input or output. Reason: ", e);
        System.exit(2);
    }
}

From source file:com.asakusafw.compiler.bootstrap.AllBatchCompilerDriver.java

/**
 * The program entry.//  w  w w . j a  v a2 s.c  om
 * @param args command line arguments
 */
public static void main(String... args) {
    try {
        if (start(args) == false) {
            System.exit(1);
        }
    } catch (Exception e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(Integer.MAX_VALUE);
        formatter.printHelp(MessageFormat.format("java -classpath ... {0}", //$NON-NLS-1$
                AllBatchCompilerDriver.class.getName()), OPTIONS, true);
        e.printStackTrace(System.out);
        System.exit(1);
    }
}

From source file:com.asakusafw.dmdl.thundergate.Main.java

/**
 * ???//from w  w w .j av  a 2  s. c  o  m
 * @param args ???????????
 */
public static void main(String... args) {
    GenerateTask task;
    try {
        Configuration conf = loadConfigurationFromArguments(args);
        task = new GenerateTask(conf);
    } catch (Exception e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(Integer.MAX_VALUE);
        formatter.printHelp(MessageFormat.format("java -classpath ... {0}", Main.class.getName()), OPTIONS,
                true);
        e.printStackTrace(System.out);
        System.exit(1);
        return;
    }
    try {
        task.call();
    } catch (Exception e) {
        e.printStackTrace(System.out);
        System.exit(1);
        return;
    }
}

From source file:com.jgaap.backend.CLI.java

/**
 * Parses the arguments passed to jgaap from the command line. Will either
 * display the help or run jgaap on an experiment.
 * /*  w  ww  .  java2 s .  c  om*/
 * @param args
 *            command line arguments
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    CommandLineParser parser = new GnuParser();
    CommandLine cmd = parser.parse(options, args);
    if (cmd.hasOption('h')) {
        String command = cmd.getOptionValue('h');
        if (command == null) {
            HelpFormatter helpFormatter = new HelpFormatter();
            helpFormatter.setLeftPadding(5);
            helpFormatter.setWidth(100);
            helpFormatter.printHelp(
                    "jgaap -c [canon canon ...] -es [event] -ec [culler culler ...] -a [analysis] <-d [distance]> -l [file] <-s [file]>",
                    "Welcome to JGAAP the Java Graphical Authorship Attribution Program.\nMore information can be found at http://jgaap.com",
                    options, "Copyright 2013 Evaluating Variation in Language Lab, Duquesne University");
        } else {
            List<Displayable> list = new ArrayList<Displayable>();
            if (command.equalsIgnoreCase("c")) {
                list.addAll(Canonicizers.getCanonicizers());
            } else if (command.equalsIgnoreCase("es")) {
                list.addAll(EventDrivers.getEventDrivers());
            } else if (command.equalsIgnoreCase("ec")) {
                list.addAll(EventCullers.getEventCullers());
            } else if (command.equalsIgnoreCase("a")) {
                list.addAll(AnalysisDrivers.getAnalysisDrivers());
            } else if (command.equalsIgnoreCase("d")) {
                list.addAll(DistanceFunctions.getDistanceFunctions());
            } else if (command.equalsIgnoreCase("lang")) {
                list.addAll(Languages.getLanguages());
            }
            for (Displayable display : list) {
                if (display.showInGUI())
                    System.out.println(display.displayName() + " - " + display.tooltipText());
            }
            if (list.isEmpty()) {
                System.out.println("Option " + command + " was not found.");
                System.out.println("Please use c, es, d, a, or lang");
            }
        }
    } else if (cmd.hasOption('v')) {
        System.out.println("Java Graphical Authorship Attribution Program version 5.2.0");
    } else if (cmd.hasOption("ee")) {
        String eeFile = cmd.getOptionValue("ee");
        String lang = cmd.getOptionValue("lang");
        ExperimentEngine.runExperiment(eeFile, lang);
        System.exit(0);
    } else {
        JGAAP.commandline = true;
        API api = API.getPrivateInstance();
        String documentsFilePath = cmd.getOptionValue('l');
        if (documentsFilePath == null) {
            throw new Exception("No Documents CSV specified");
        }
        List<Document> documents;
        if (documentsFilePath.startsWith(JGAAPConstants.JGAAP_RESOURCE_PACKAGE)) {
            documents = Utils.getDocumentsFromCSV(
                    CSVIO.readCSV(com.jgaap.JGAAP.class.getResourceAsStream(documentsFilePath)));
        } else {
            documents = Utils.getDocumentsFromCSV(CSVIO.readCSV(documentsFilePath));
        }
        for (Document document : documents) {
            api.addDocument(document);
        }
        String language = cmd.getOptionValue("lang", "english");
        api.setLanguage(language);
        String[] canonicizers = cmd.getOptionValues('c');
        if (canonicizers != null) {
            for (String canonicizer : canonicizers) {
                api.addCanonicizer(canonicizer);
            }
        }
        String[] events = cmd.getOptionValues("es");
        if (events == null) {
            throw new Exception("No EventDriver specified");
        }
        for (String event : events) {
            api.addEventDriver(event);
        }
        String[] eventCullers = cmd.getOptionValues("ec");
        if (eventCullers != null) {
            for (String eventCuller : eventCullers) {
                api.addEventCuller(eventCuller);
            }
        }
        String analysis = cmd.getOptionValue('a');
        if (analysis == null) {
            throw new Exception("No AnalysisDriver specified");
        }
        AnalysisDriver analysisDriver = api.addAnalysisDriver(analysis);
        String distanceFunction = cmd.getOptionValue('d');
        if (distanceFunction != null) {
            api.addDistanceFunction(distanceFunction, analysisDriver);
        }
        api.execute();
        List<Document> unknowns = api.getUnknownDocuments();
        OutputStreamWriter outputStreamWriter;
        String saveFile = cmd.getOptionValue('s');
        if (saveFile == null) {
            outputStreamWriter = new OutputStreamWriter(System.out);
        } else {
            outputStreamWriter = new OutputStreamWriter(new FileOutputStream(saveFile));
        }
        Writer writer = new BufferedWriter(outputStreamWriter);
        for (Document unknown : unknowns) {
            writer.append(unknown.getFormattedResult(analysisDriver));
        }
        writer.append('\n');
    }
}

From source file:edu.umd.ujjwalgoel.AnalyzePMI.java

@SuppressWarnings({ "static-access" })
public static void main(String[] args) {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT));

    CommandLine cmdline = null;// w  ww  .ja  v  a  2  s  .  c om
    CommandLineParser parser = new GnuParser();

    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(INPUT)) {
        System.out.println("args: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(120);
        formatter.printHelp(AnalyzePMI.class.getName(), options);
        ToolRunner.printGenericCommandUsage(System.out);
        System.exit(-1);
    }

    String inputPath = cmdline.getOptionValue(INPUT);
    System.out.println("input path: " + inputPath);

    BufferedReader br = null;
    int countPairs = 0;

    List<PairOfWritables<PairOfStrings, FloatWritable>> pmis = new ArrayList<PairOfWritables<PairOfStrings, FloatWritable>>();
    List<PairOfWritables<PairOfStrings, FloatWritable>> cloudPmis = new ArrayList<PairOfWritables<PairOfStrings, FloatWritable>>();
    List<PairOfWritables<PairOfStrings, FloatWritable>> lovePmis = new ArrayList<PairOfWritables<PairOfStrings, FloatWritable>>();

    PairOfWritables<PairOfStrings, FloatWritable> highestPMI = null;
    PairOfWritables<PairOfStrings, FloatWritable> highestCloudPMI = null;
    PairOfWritables<PairOfStrings, FloatWritable> highestCloudPMI2 = null;
    PairOfWritables<PairOfStrings, FloatWritable> highestCloudPMI3 = null;

    PairOfWritables<PairOfStrings, FloatWritable> highestLovePMI = null;
    PairOfWritables<PairOfStrings, FloatWritable> highestLovePMI2 = null;
    PairOfWritables<PairOfStrings, FloatWritable> highestLovePMI3 = null;

    try {
        FileSystem fs = FileSystem.get(new Configuration());
        FileStatus[] status = fs.listStatus(new Path(inputPath));
        //PairOfStrings pair = new PairOfStrings();
        for (int i = 0; i < status.length; i++) {
            br = new BufferedReader(new InputStreamReader(fs.open(status[i].getPath())));
            String line = br.readLine();
            while (line != null) {
                String[] words = line.split("\\t");
                float value = Float.parseFloat(words[1].trim());
                String[] wordPair = words[0].replaceAll("\\(", "").replaceAll("\\)", "").split(",");
                PairOfStrings pair = new PairOfStrings();
                pair.set(wordPair[0].trim(), wordPair[1].trim());
                if (wordPair[0].trim().equals("cloud")) {
                    PairOfWritables<PairOfStrings, FloatWritable> cloudPmi = new PairOfWritables<PairOfStrings, FloatWritable>();
                    cloudPmi.set(pair, new FloatWritable(value));
                    cloudPmis.add(cloudPmi);
                    if ((highestCloudPMI == null)
                            || (highestCloudPMI.getRightElement().compareTo(cloudPmi.getRightElement()) < 0)) {
                        highestCloudPMI = cloudPmi;
                    } else if ((highestCloudPMI2 == null)
                            || (highestCloudPMI2.getRightElement().compareTo(cloudPmi.getRightElement()) < 0)) {
                        highestCloudPMI2 = cloudPmi;
                    } else if ((highestCloudPMI3 == null)
                            || (highestCloudPMI3.getRightElement().compareTo(cloudPmi.getRightElement()) < 0)) {
                        highestCloudPMI3 = cloudPmi;
                    }
                }
                if (wordPair[0].trim().equals("love")) {
                    PairOfWritables<PairOfStrings, FloatWritable> lovePmi = new PairOfWritables<PairOfStrings, FloatWritable>();
                    lovePmi.set(pair, new FloatWritable(value));
                    lovePmis.add(lovePmi);
                    if ((highestLovePMI == null)
                            || (highestLovePMI.getRightElement().compareTo(lovePmi.getRightElement()) < 0)) {
                        highestLovePMI = lovePmi;
                    } else if ((highestLovePMI2 == null)
                            || (highestLovePMI2.getRightElement().compareTo(lovePmi.getRightElement()) < 0)) {
                        highestLovePMI2 = lovePmi;
                    } else if ((highestLovePMI3 == null)
                            || (highestLovePMI3.getRightElement().compareTo(lovePmi.getRightElement()) < 0)) {
                        highestLovePMI3 = lovePmi;
                    }
                }
                PairOfWritables<PairOfStrings, FloatWritable> pmi = new PairOfWritables<PairOfStrings, FloatWritable>();
                pmi.set(pair, new FloatWritable(value));
                pmis.add(pmi);
                if (highestPMI == null) {
                    highestPMI = pmi;
                } else if (highestPMI.getRightElement().compareTo(pmi.getRightElement()) < 0) {
                    highestPMI = pmi;
                }
                countPairs++;
                line = br.readLine();
            }
        }
    } catch (Exception ex) {
        System.out.println("ERROR" + ex.getMessage());
    }

    /*Collections.sort(pmis, new Comparator<PairOfWritables<PairOfStrings, FloatWritable>>() {
      public int compare(PairOfWritables<PairOfStrings, FloatWritable> e1,
          PairOfWritables<PairOfStrings, FloatWritable> e2) {
        /*if (e2.getRightElement().compareTo(e1.getRightElement()) == 0) {
          return e1.getLeftElement().getLeftElement().compareTo(e2.getLeftElement().getLeftElement());
        }
            
        return e2.getRightElement().compareTo(e1.getRightElement());
      }
    });
            
            
    Collections.sort(cloudPmis, new Comparator<PairOfWritables<PairOfStrings, FloatWritable>>() {
      public int compare(PairOfWritables<PairOfStrings, FloatWritable> e1,
          PairOfWritables<PairOfStrings, FloatWritable> e2) {
        if (e2.getRightElement().compareTo(e1.getRightElement()) == 0) {
    return e1.getLeftElement().getLeftElement().compareTo(e2.getLeftElement().getLeftElement());
            }
            
        return e2.getRightElement().compareTo(e1.getRightElement());
      }
    });
            
            
    Collections.sort(lovePmis, new Comparator<PairOfWritables<PairOfStrings, FloatWritable>>() {
      public int compare(PairOfWritables<PairOfStrings, FloatWritable> e1,
          PairOfWritables<PairOfStrings, FloatWritable> e2) {
        if (e2.getRightElement().compareTo(e1.getRightElement()) == 0) {
    return e1.getLeftElement().getLeftElement().compareTo(e2.getLeftElement().getLeftElement());
           }
            
        return e2.getRightElement().compareTo(e1.getRightElement());
      }
    });
            
     PairOfWritables<PairOfStrings, FloatWritable> highestPMI = pmis.get(0);
     PairOfWritables<PairOfStrings, FloatWritable> highestCloudPMI = cloudPmis.get(0);      PairOfWritables<PairOfStrings, FloatWritable> highestCloudPMI2 = cloudPmis.get(1);
     PairOfWritables<PairOfStrings, FloatWritable> highestCloudPMI3 = cloudPmis.get(2);
             
     PairOfWritables<PairOfStrings, FloatWritable> highestLovePMI = lovePmis.get(0);       PairOfWritables<PairOfStrings, FloatWritable> highestLovePMI2 = lovePmis.get(1);
     PairOfWritables<PairOfStrings, FloatWritable> highestLovePMI3 = lovePmis.get(2);*/

    System.out.println("Total Distinct Pairs : " + countPairs);
    System.out.println("Pair with highest PMI : (" + highestPMI.getLeftElement().getLeftElement() + ", "
            + highestPMI.getLeftElement().getRightElement());

    System.out
            .println("Word with highest PMI with Cloud : " + highestCloudPMI.getLeftElement().getRightElement()
                    + " with value : " + highestCloudPMI.getRightElement().get());
    System.out.println(
            "Word with second highest PMI with Cloud : " + highestCloudPMI2.getLeftElement().getRightElement()
                    + " with value : " + highestCloudPMI2.getRightElement().get());
    System.out.println(
            "Word with third highest PMI with Cloud : " + highestCloudPMI3.getLeftElement().getRightElement()
                    + " with value : " + highestCloudPMI3.getRightElement().get());

    System.out.println("Word with highest PMI with Love : " + highestLovePMI.getLeftElement().getRightElement()
            + " with value : " + highestLovePMI.getRightElement().get());
    System.out.println(
            "Word with second highest PMI with Love : " + highestLovePMI2.getLeftElement().getRightElement()
                    + " with value : " + highestLovePMI2.getRightElement().get());
    System.out.println(
            "Word with third highest PMI with Love : " + highestLovePMI3.getLeftElement().getRightElement()
                    + " with value : " + highestLovePMI3.getRightElement().get());

}

From source file:jeplus.Main.java

/**
 * @param args the command line arguments
 *///from www  .  j  a v  a2 s  .com
public static void main(String[] args) {
    //        if (REDIRECT_ERR) {
    //            try {
    //                // Redirect err
    //                System.setErr(new PrintStream(new FileOutputStream("jeplus.err")));
    //            } catch (FileNotFoundException ex) {
    //                //Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    //                ex.printStackTrace();
    //            }
    //        }

    try {
        // Set cross-platform Java L&F (also called "Metal")
        //            UIManager.setLookAndFeel(
        //                UIManager.getCrossPlatformLookAndFeelClassName());
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        //            for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
        //                if ("Nimbus".equals(info.getName())) {
        //                    UIManager.setLookAndFeel(info.getClassName());
        //                    break;
        //                }
        //            }
    } catch (UnsupportedLookAndFeelException e) {
        System.err.println("Unsupported Look-And-Feel Option. Reverting to the default UI.");
    } catch (ClassNotFoundException e) {
        System.err.println("Specified Look-And-Feel class cannot be found. Reverting to the default UI.");
    } catch (InstantiationException e) {
        System.err.println("Fialed to instantiate the specified Look-And-Feel. Reverting to the default UI.");
    } catch (IllegalAccessException e) {
        System.err.println("Cannot access the specified Look-And-Feel. Reverting to the default UI.");
    }

    // Set locale to UK
    Locale.setDefault(Locale.UK);
    // Set line end to DOS style
    System.setProperty("line.separator", "\r\n");
    // System.setProperty("file.separator", "/");  // seemed to have no effect

    // create the parser
    CommandLineParser parser = new GnuParser();
    Options options = new Main().getCommandLineOptions(null);
    CommandLine commandline = null;
    HelpFormatter formatter = new HelpFormatter();
    formatter.setWidth(80);
    try {
        // parse the command line arguments
        commandline = parser.parse(options, args);
        if (commandline.hasOption("help")) {
            // automatically generate the help statement
            formatter.printHelp("java -Xmx1000m -jar jEPlus.jar [OPTIONS]", options);
            System.exit(-1);
        }
        // Set log4j configuration
        if (commandline.hasOption("log")) {
            PropertyConfigurator.configure(commandline.getOptionValue("log"));
        } else {
            PropertyConfigurator.configure("log4j.cfg");
        }
    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        // automatically generate the help statement
        formatter.printHelp("java -Xmx1000m -jar jEPlus.jar [OPTIONS]", options);
        System.exit(-1);
    }

    // Call main fuction with commandline
    new Main().mainFunction(commandline);
}