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

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

Introduction

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

Prototype

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

Source Link

Document

Parse the arguments according to the specified options.

Usage

From source file:edu.cmu.lti.oaqa.knn4qa.apps.CollectionSplitter.java

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

    options.addOption("i", null, true, "Input file");
    options.addOption("o", null, true, "Output file prefix");
    options.addOption("p", null, true, "Comma separated probabilities e.g., 0.1,0.2,0.7.");
    options.addOption("n", null, true, "Comma separated part names, e.g., dev,test,train");

    CommandLineParser parser = new org.apache.commons.cli.GnuParser();

    try {// w w  w  . j  av  a  2s  .com
        CommandLine cmd = parser.parse(options, args);

        InputStream input = null;

        if (cmd.hasOption("i")) {
            input = CompressUtils.createInputStream(cmd.getOptionValue("i"));
        } else {
            Usage("Specify Input file");
        }

        ArrayList<Double> probs = new ArrayList<Double>();
        String[] partNames = null;

        if (cmd.hasOption("p")) {
            String parts[] = cmd.getOptionValue("p").split(",");

            try {
                double sum = 0;
                for (String s : parts) {
                    double p = Double.parseDouble(s);
                    if (p <= 0 || p > 1)
                        Usage("All probabilities must be in the range (0,1)");
                    sum += p;
                    probs.add(p);
                }

                if (Math.abs(sum - 1.0) > Float.MIN_NORMAL) {
                    Usage("The sum of probabilities should be equal to 1, but it's: " + sum);
                }
            } catch (NumberFormatException e) {
                Usage("Can't convert some of the probabilities to a floating-point number.");
            }
        } else {
            Usage("Specify part probabilities.");
        }

        if (cmd.hasOption("n")) {
            partNames = cmd.getOptionValue("n").split(",");

            if (partNames.length != probs.size())
                Usage("The number of probabilities is not equal to the number of parts!");
        } else {
            Usage("Specify part names");
        }

        BufferedWriter[] outFiles = new BufferedWriter[partNames.length];

        if (cmd.hasOption("o")) {
            String outPrefix = cmd.getOptionValue("o");

            for (int partId = 0; partId < partNames.length; ++partId) {
                outFiles[partId] = new BufferedWriter(new OutputStreamWriter(
                        CompressUtils.createOutputStream(outPrefix + "_" + partNames[partId] + ".gz")));
            }
        } else {
            Usage("Specify Output file prefix");
        }

        System.out.println("Using probabilities:");
        for (int partId = 0; partId < partNames.length; ++partId)
            System.out.println(partNames[partId] + " : " + probs.get(partId));
        System.out.println("=================================================");

        XmlIterator inpIter = new XmlIterator(input, YahooAnswersReader.DOCUMENT_TAG);

        String oneRec = inpIter.readNext();
        int docNum = 1;
        for (; !oneRec.isEmpty(); ++docNum, oneRec = inpIter.readNext()) {
            double p = Math.random();

            if (docNum % 1000 == 0) {
                System.out.println(String.format("Processed %d documents", docNum));
            }

            BufferedWriter out = null;

            for (int partId = 0; partId < partNames.length; ++partId) {
                double pp = probs.get(partId);
                if (p <= pp || partId + 1 == partNames.length) {
                    out = outFiles[partId];
                    break;
                }
                p -= pp;
            }

            oneRec = oneRec.trim() + System.getProperty("line.separator");
            out.write(oneRec);
        }
        System.out.println(String.format("Processed %d documents", docNum - 1));
        // It's important to close all the streams here!
        for (BufferedWriter f : outFiles)
            f.close();
    } catch (ParseException e) {
        Usage("Cannot parse arguments");
    } catch (Exception e) {
        System.err.println("Terminating due to an exception: " + e);
        System.exit(1);
    }
}

From source file:com.arainfor.thermostat.daemon.HvacMonitor.java

/**
 * @param args The Program Arguments//from w w  w .j av a  2s  .  c o m
 */
public static void main(String[] args) throws IOException {

    Logger log = LoggerFactory.getLogger(HvacMonitor.class);

    //System.err.println(APPLICATION_NAME + " v" + APPLICATION_VERSION_MAJOR + "." + APPLICATION_VERSION_MINOR + "." + APPLICATION_VERSION_BUILD);
    Options options = new Options();
    options.addOption("help", false, "This message isn't very helpful");
    options.addOption("version", false, "Print the version number");
    options.addOption("monitor", false, "Start GUI Monitor");
    options.addOption("config", true, "The configuration file");

    CommandLineParser parser = new GnuParser();
    CommandLine cmd;

    try {
        cmd = parser.parse(options, args);
        if (cmd.hasOption("help")) {
            HelpFormatter hf = new HelpFormatter();
            hf.printHelp(APPLICATION_NAME, options);
            return;
        }
        if (cmd.hasOption("version")) {
            System.out.println("The " + APPLICATION_NAME + " v" + APPLICATION_VERSION_MAJOR + "."
                    + APPLICATION_VERSION_MINOR + "." + APPLICATION_VERSION_BUILD);
        }
    } catch (ParseException e) {
        e.printStackTrace();
        return;
    }

    String propFileName = "thermostat.properties";
    if (cmd.getOptionValue("config") != null)
        propFileName = cmd.getOptionValue("config");

    log.info("loading...{}", propFileName);

    try {
        Properties props = new PropertiesLoader(propFileName).getProps();

        // Append the system properties with our application properties
        props.putAll(System.getProperties());
        System.setProperties(props);
    } catch (FileNotFoundException fnfe) {
        log.warn("Cannot load file:", fnfe);
    }

    new HvacMonitor().start();

}

From source file:com.trovit.hdfstree.HdfsTree.java

public static void main(String... args) {
    Options options = new Options();
    options.addOption("l", false, "Use local filesystem.");
    options.addOption("p", true, "Path used as root for the tree.");
    options.addOption("s", false, "Display the size of the directory");
    options.addOption("d", true, "Maximum depth of the tree (when displaying)");

    CommandLineParser parser = new PosixParser();

    TreeBuilder treeBuilder;/*from  w w w  .  j a v a2  s.c o  m*/
    FSInspector fsInspector = null;
    String rootPath = null;

    Displayer displayer = new ConsoleDisplayer();

    try {
        CommandLine cmd = parser.parse(options, args);

        // local or hdfs.
        if (cmd.hasOption("l")) {
            fsInspector = new LocalFSInspector();
        } else {
            fsInspector = new HDFSInspector();
        }

        // check that it has the root path.
        if (cmd.hasOption("p")) {
            rootPath = cmd.getOptionValue("p");
        } else {
            throw new ParseException("Mandatory option (-p) is not specified.");
        }

        if (cmd.hasOption("d")) {
            displayer.setMaxDepth(Integer.parseInt(cmd.getOptionValue("d")));
        }

        if (cmd.hasOption("s")) {
            displayer.setDisplaySize();
        }
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("hdfstree", options);
        System.exit(1);
    }

    treeBuilder = new TreeBuilder(rootPath, fsInspector);
    TreeNode tree = treeBuilder.buildTree();
    displayer.display(tree);

}

From source file:de.binfalse.jatter.App.java

/**
 * Run jatter's main.// w w  w.  java2s  . c  om
 *
 * @param args
 *          the arguments
 * @throws Exception
 *           the exception
 */
public static void main(String[] args) throws Exception {
    Options options = new Options();

    Option conf = new Option("c", "config", true, "config file path");
    conf.setRequired(false);
    options.addOption(conf);

    Option t = new Option("t", "template", false, "show a config template");
    t.setRequired(false);
    options.addOption(t);

    Option v = new Option("v", "verbose", false, "print information messages");
    v.setRequired(false);
    options.addOption(v);

    Option d = new Option("d", "debug", false, "print debugging messages incl stack traces");
    d.setRequired(false);
    options.addOption(d);

    Option h = new Option("h", "help", false, "show help");
    h.setRequired(false);
    options.addOption(h);

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd;

    try {
        cmd = parser.parse(options, args);
        if (cmd.hasOption("h"))
            throw new RuntimeException("showing the help page");
    } catch (Exception e) {
        help(options, e.getMessage());
        return;
    }

    if (cmd.hasOption("t")) {
        System.out.println();
        BufferedReader br = new BufferedReader(new InputStreamReader(
                App.class.getClassLoader().getResourceAsStream("config.properties.template")));
        while (br.ready())
            System.out.println(br.readLine());
        br.close();
        System.exit(0);
    }

    if (cmd.hasOption("v"))
        LOGGER.setMinLevel(LOGGER.INFO);

    if (cmd.hasOption("d")) {
        LOGGER.setMinLevel(LOGGER.DEBUG);
        LOGGER.setLogStackTrace(true);
    }

    if (!cmd.hasOption("c"))
        help(options, "a config file is required for running jatter");

    startJatter(cmd.getOptionValue("c"));
}

From source file:edu.msu.cme.rdp.unifrac.Unifrac.java

public static void main(String[] args) throws Exception {
    CommandLineParser parser = new PosixParser();
    CommandLine line = null;//from  www .  ja v  a2 s. c  o m
    try {
        line = parser.parse(options, args);
    } catch (UnrecognizedOptionException e) {
        System.err.println(e.getMessage());
        printUsage();
        return;
    }
    UnifracTree unifracTree = null;
    PrintStream out = System.out;

    if (line.hasOption("tree") && line.hasOption("sequence-files")) {
        printUsage();
    } else if (!(line.hasOption("weighted") || line.hasOption("unweighted")
            || line.hasOption("significance"))) {
        System.err.println("Must specify at least one calculation option");
        printUsage();
    } else if (line.hasOption("sample-mapping")) {
        Map<String, UnifracSample> sampleMap = readSampleMap(line.getOptionValue("sample-mapping"));

        if (line.hasOption("tree")) {
            unifracTree = parseNewickTree(line.getOptionValue("tree"), sampleMap);
        }
    } else {
        if (!line.hasOption("sample-mapping")) {
            System.err.println("A sample mapping file must be provided");
        }
        printUsage();
    }

    if (line.hasOption("outfile")) {
        out = new PrintStream(line.getOptionValue("outfile"));
    }

    if (unifracTree != null) {
        if (line.hasOption("unweighted")) {
            printResults(out, unifracTree.computeUnifrac(), "Unweighted Unifrac");
            if (line.hasOption("significance")) {
                printResults(out, unifracTree.computeUnifracSig(1000, false),
                        "Unweighted Unifrac Significance");
            }
        }

        if (line.hasOption("weighted")) {
            printResults(out, unifracTree.computeWeightedUnifrac(), "Weighted Unifrac");
            if (line.hasOption("significance")) {
                printResults(out, unifracTree.computeUnifracSig(1000, true), "Weighted Unifrac Significance");
            }
        }
    }
}

From source file:lee.util.jtap.JTapCli.java

/**
 * @param args//ww  w .  j  a va2 s .  c o  m
 */
public static void main(String[] args) {
    Options options = constructOptions();

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println("Cmd Parsing Error:   " + e.getMessage());
        JTapCli.printHelp(options);
    }
    String resultMessage = "Done.";
    if (cmd.hasOption("dumpkeys")) {
        resultMessage = JTapCli.dumpKeys();
    } else if (cmd.hasOption("dumpall")) {
        resultMessage = JTapCli.dumpAll();
    } else if (cmd.hasOption("s") || cmd.hasOption("session")) {
        HashMap<String, String> argsMap = getMappedArgs(cmd, "host", "bucket", "password", "port");
        resultMessage = ">> " + JTapCli.setSession(argsMap);
    } else if (cmd.hasOption("dk") || cmd.hasOption("deletekey")) {
        resultMessage = JTapCli.deleteKey(cmd.getOptionValues("dk"));
    } else if (cmd.hasOption("gk") || cmd.hasOption("getkey")) {
        resultMessage = JTapCli.dumpKey(cmd.getOptionValues("gk"));
    } else if (cmd.hasOption("cs") || cmd.hasOption("clearsession")) {
        boolean removed = JTapCli.session.delete();
        if (removed) {
            System.out
                    .println("Saved session data has been cleared. To set the values again call with -session");
        }
    } else {
        JTapCli.printHelp(options);
        resultMessage = "";
    }
    System.out.println(resultMessage);
    return;
}

From source file:de.tudarmstadt.ukp.teaching.uima.nounDecompounding.evaluation.CouchDbExport.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    Options options = new Options();
    options.addOption(OptionBuilder.withLongOpt("host")
            .withDescription("(optional) The couchdb host. default: 127.0.0.1").hasArg().create());
    options.addOption(OptionBuilder.withLongOpt("port")
            .withDescription("(optional) The couchdb port. default: 5984").hasArg().create());
    options.addOption(OptionBuilder.withLongOpt("username")
            .withDescription("(optional) The couchdb username. default: <empty>").hasArg().create());
    options.addOption(OptionBuilder.withLongOpt("password")
            .withDescription("(optional) The couchdb password. default: <empty>").hasArg().create());
    options.addOption(OptionBuilder.withLongOpt("dbname")
            .withDescription("(optional) The couchdb database name. default: noun_decompounding").hasArg()
            .create());/* w  w w .  j a  v  a2 s.  co  m*/
    options.addOption(OptionBuilder.withLongOpt("limit")
            .withDescription("(optional) The amount of documents you want to export. default: all").hasArg()
            .create());

    CommandLineParser parser = new PosixParser();
    CommandLine cmd;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println("Error: " + e.getMessage());

        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("countTotalFreq", options);
        return;
    }
    String host = (cmd.hasOption("host")) ? cmd.getOptionValue("host") : "127.0.0.1";
    int port = Integer.parseInt((cmd.hasOption("port")) ? cmd.getOptionValue("port") : "5984");
    String username = (cmd.hasOption("username")) ? cmd.getOptionValue("username") : "";
    String password = (cmd.hasOption("password")) ? cmd.getOptionValue("password") : "";
    String dbName = (cmd.hasOption("dbname")) ? cmd.getOptionValue("dbname") : "";
    int limit = (cmd.hasOption("limit")) ? Integer.parseInt(cmd.getOptionValue("limit")) : Integer.MAX_VALUE;

    IDictionary dict = new IGerman98Dictionary(new File("src/main/resources/de_DE.dic"),
            new File("src/main/resources/de_DE.aff"));
    LinkingMorphemes morphemes = new LinkingMorphemes(new File("src/main/resources/linkingMorphemes.txt"));
    LeftToRightSplitAlgorithm algo = new LeftToRightSplitAlgorithm(dict, morphemes);

    HttpClient httpClient = new StdHttpClient.Builder().host(host).port(port).username(username)
            .password(password).build();
    CouchDbInstance dbInstance = new StdCouchDbInstance(httpClient);
    CouchDbConnector db = new StdCouchDbConnector(dbName, dbInstance);

    try {
        CouchDbExport exporter = new CouchDbExport(
                new CcorpusReader(new File("src/main/resources/evaluation/ccorpus.txt")), db);
        exporter.export(algo, limit);
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
}

From source file:eu.scape_project.cdx_creator.CDXCreator.java

/**
 * Main entry point./*from   www . j a v  a 2 s.  c om*/
 *
 * @param args
 * @throws java.io.IOException
 * @throws org.apache.commons.cli.ParseException
 */
public static void main(String[] args) throws IOException, ParseException {
    Configuration conf = new Configuration();
    // Command line interface
    config = new CDXCreatorConfig();
    CommandLineParser cmdParser = new PosixParser();
    GenericOptionsParser gop = new GenericOptionsParser(conf, args);
    CDXCreatorOptions cdxCreatorOpts = new CDXCreatorOptions();
    CommandLine cmd = cmdParser.parse(cdxCreatorOpts.options, gop.getRemainingArgs());
    if ((args.length == 0) || (cmd.hasOption(cdxCreatorOpts.HELP_OPT))) {
        cdxCreatorOpts.exit("Help", 0);
    } else {
        cdxCreatorOpts.initOptions(cmd, config);
    }

    // configuration properties
    if (config.getPropertiesFilePath() != null) {
        pu = new PropertyUtil(config.getPropertiesFilePath(), true);
    } else {
        pu = new PropertyUtil("/eu/scape_project/cdx_creator/config.properties", false);
    }

    config.setCdxfileCsColumns(pu.getProp("cdxfile.cscolumns"));
    config.setCdxfileCsHeader(pu.getProp("cdxfile.csheader"));

    CDXCreator cdxCreator = new CDXCreator();

    File input = new File(config.getInputStr());

    if (input.isDirectory()) {
        config.setDirectoryInput(true);
        cdxCreator.traverseDir(input);
    } else {
        CDXCreationTask cdxCreationTask = new CDXCreationTask(config, input, input.getName());
        cdxCreationTask.createIndex();
    }

    System.exit(0);
}

From source file:com.ibm.soatf.SOATestingFramework.java

/**
 * SOA Testing Framework main static method.
 *
 * @param args Main input parameters.//from   w  w  w . ja v a2 s .co  m
 */
public static void main(String[] args) {
    Options options = new Options();
    options.addOption(new Option("gui", "Display a GUI"));

    options.addOption(OptionBuilder.withArgName("environment").hasArg()
            .withDescription("Environment to run the tests on").create("env")); // has a value
    options.addOption(OptionBuilder.withArgName("project").hasArg()
            .withDescription("Project to run the tests on").create("p")); // has a value
    options.addOption(OptionBuilder.withArgName("interface").hasArg()
            .withDescription("Interface to run the tests on").create("i")); // has a value
    CommandLineParser parser = new BasicParser();
    try {
        CommandLine cmd = parser.parse(options, args);
        validate(cmd);

        if (cmd.hasOption("gui")) {

            /* Set the Nimbus look and feel */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
             * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
             */
            try {
                if (false) { //disabled the OS Look'n'Feel
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } else {
                    for (UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                        if ("Nimbus".equals(info.getName())) {
                            javax.swing.UIManager.setLookAndFeel(info.getClassName());
                            break;
                        }
                    }
                    UIManager.getLookAndFeelDefaults().put("nimbusOrange", (new Color(0, 128, 255)));
                }
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
                    | javax.swing.UnsupportedLookAndFeelException ex) {
                logger.error("Cannot set look and feel", ex);
            }
            //</editor-fold>

            final SOATestingFrameworkGUI soatfgui = new SOATestingFrameworkGUI();
            java.awt.EventQueue.invokeLater(new Runnable() {

                @Override
                public void run() {
                    soatfgui.setVisible(true);
                }
            });
        } else {
            //<editor-fold defaultstate="collapsed" desc="Command line mode">
            try {
                // Initialization of configuration manager.
                ConfigurationManager.getInstance().init();

                String env = cmd.getOptionValue("env", null);
                String ifaceName;
                boolean inboundOnly = false;
                if (cmd.hasOption("p")) {
                    String projectName = cmd.getOptionValue("p");
                    MasterConfiguration masterConfig = ConfigurationManager.getInstance().getMasterConfig();
                    List<SOATestingFrameworkMasterConfiguration.Interfaces.Interface> interfaces = masterConfig
                            .getInterfaces();
                    all: for (Interface iface : interfaces) {
                        List<Project> projects = iface.getProjects().getProject();
                        for (Project project : projects) {
                            if (project.getName().equals(projectName)) {
                                inboundOnly = "INBOUND".equalsIgnoreCase(project.getDirection());
                                ifaceName = iface.getName();
                                break all;
                            }
                        }
                    }
                    throw new FrameworkExecutionException(
                            "No such project found in master configuration: " + projectName);
                } else {
                    ifaceName = cmd.getOptionValue("i");
                    inboundOnly = false;
                }
                DirectoryStructureManager.checkFrameworkDirectoryStructure(ifaceName);
                FlowExecutor flowExecutor = new FlowExecutor(inboundOnly, env, ifaceName);
                flowExecutor.execute();
            } catch (FrameworkConfigurationException ex) {
                logger.fatal("Configuration corrupted. See the exception stack trace for details.", ex);
            } catch (FrameworkException ex) {
                logger.fatal(ex);
            }
            //</editor-fold>
        }
    } catch (ParseException ex) {
        logger.fatal("Could not parse the command line arguments. Reason: " + ex);
        printUsage();
    } catch (Throwable ex) {
        logger.fatal("Unexpected error occured: ", ex);
        printUsage();
        System.exit(-1);
    }
}

From source file:co.turnus.analysis.buffers.BoundedBufferSchedulingCliLauncher.java

public static void main(String[] args) {
    try {//from   www .j a  v a2  s  .  c  o m
        CommandLineParser parser = new GnuParser();
        CommandLine cmd = parser.parse(cliOptions, args);
        Configuration config = parseCommandLine(cmd);

        // init models
        AnalysisActivator.init();

        // set logger verbosity
        if (config.getBoolean(VERBOSE, false)) {
            TurnusLogger.setLevel(TurnusLevel.ALL);
        }

        File tDir = new File(config.getString(TRACE_PROJECT));
        TraceProject project = TraceProject.load(tDir);

        BoundedBufferScheduling bbs = new BoundedBufferScheduling(project);
        bbs.setConfiguration(config);

        BufferMinimizationData data = bbs.run();

        TurnusLogger.info("Storing results...");
        File outPath = new File(config.getString(OUTPUT_PATH));

        // store the analysis report
        String uuid = UUID.randomUUID().toString();
        File rFile = new File(outPath, uuid + "." + TurnusExtension.REPORT);
        Report report = DataFactory.eINSTANCE.createReport();
        report.setDate(new Date());
        report.setComment("Report with only Bounded Buffer Scheduling results analysis");
        report.getDataSet().add(data);
        EcoreHelper.storeEObject(report, new ResourceSetImpl(), rFile);
        TurnusLogger.info("TURNUS report stored in " + rFile);

        // store formatted reports
        String xlsName = config.getString(XLS, "");
        if (!xlsName.isEmpty()) {
            File xlsFile = new File(outPath, xlsName + ".xls");
            new XlsBufferMinimizationDataWriter().write(data, xlsFile);
            TurnusLogger.info("XLS report stored in " + xlsFile);
        }

        String bxdfName = config.getString(BXDF, "");
        if (!bxdfName.isEmpty()) {
            File bxdfFile = new File(outPath, bxdfName + ".bxdf");
            new XmlBufferMinimizationDataWriter().write(data, bxdfFile);
            TurnusLogger.info("BXDF files (one for each configuration) " + "stored in " + outPath);
        }

        TurnusLogger.info("Analysis Done!");

    } catch (ParseException e) {
        TurnusLogger.error(e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(BoundedBufferSchedulingCliLauncher.class.getSimpleName(), cliOptions);
    } catch (Exception e) {
        TurnusLogger.error(e.getCause().toString());
    }
}