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

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

Introduction

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

Prototype

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

Source Link

Document

Parses the specified arguments based on the specifed Options .

Usage

From source file:net.sf.mpaxs.spi.computeHost.StartUp.java

/**
 *
 * @param args// w ww  .j a  v a  2s  .c  o  m
 */
public static void main(String args[]) {
    FileHandler handler;
    try {
        handler = new FileHandler("computeHost.log");
        Logger logger = Logger.getLogger(StartUp.class.getName());
        logger.addHandler(handler);
    } catch (IOException ex) {
        Logger.getLogger(StartUp.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SecurityException ex) {
        Logger.getLogger(StartUp.class.getName()).log(Level.SEVERE, null, ex);
    }

    Options options = new Options();
    Option[] optionArray = new Option[] { OptionBuilder.withArgName("configuration").hasArg().isRequired()
            .withDescription("URL to configuration file for compute host").create("c") };
    for (Option opt : optionArray) {
        options.addOption(opt);
    }
    if (args.length == 0) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp(StartUp.class.getCanonicalName(), options, true);
        System.exit(1);
    }
    GnuParser gp = new GnuParser();
    try {
        CommandLine cl = gp.parse(options, args);
        try {
            URL configURL = new URL(cl.getOptionValue("c"));
            PropertiesConfiguration cfg = new PropertiesConfiguration(configURL);
            StartUp su = new StartUp(cfg);
        } catch (ConfigurationException ex) {
            Logger.getLogger(StartUp.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MalformedURLException ex) {
            Logger.getLogger(StartUp.class.getName()).log(Level.SEVERE, null, ex);
        }

    } catch (ParseException ex) {
        Logger.getLogger(StartUp.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:edu.cwru.jpdg.JPDG.java

public static void main(String[] argv) throws pDG_Builder.Error {
    final Option helpOpt = new Option("h", "help", false, "print this message");
    final Option outputOpt = new Option("o", "output", true, "output file location");
    final Option baseOpt = new Option("b", "base-dir", true, "base directory to analyze");
    final Option excludeOpt = new Option("e", "exclude", true, "exclude these directories");
    final Option classOpt = new Option("c", "classpath", true, "classpath for soot");
    final Option labelOpt = new Option("l", "label-type", true,
            "label type, valid choices are: expr-tree, inst");
    final org.apache.commons.cli.Options options = new org.apache.commons.cli.Options();

    options.addOption(helpOpt);/*from www  .  j  a  v a2 s .  co m*/
    options.addOption(outputOpt);
    options.addOption(baseOpt);
    options.addOption(classOpt);
    options.addOption(labelOpt);
    options.addOption(excludeOpt);

    String cp = null;
    String base_dir = null;
    String label_type = "expr-tree";
    String output_file = null;
    List<String> excluded = new ArrayList<String>();

    try {
        GnuParser parser = new GnuParser();
        CommandLine line = parser.parse(options, argv);

        if (line.hasOption(helpOpt.getLongOpt())) {
            Usage(options);
        }

        cp = line.getOptionValue(classOpt.getLongOpt());
        base_dir = line.getOptionValue(baseOpt.getLongOpt());
        label_type = line.getOptionValue(labelOpt.getLongOpt());
        output_file = line.getOptionValue(outputOpt.getLongOpt());
        String[] ex = line.getOptionValues(excludeOpt.getLongOpt());
        if (ex != null) {
            excluded = Arrays.asList(ex);
        }
    } catch (final MissingOptionException e) {
        System.err.println(e.getMessage());
        Usage(options);
    } catch (final UnrecognizedOptionException e) {
        System.err.println(e.getMessage());
        Usage(options);
    } catch (final ParseException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    }

    List<String> dirs = new ArrayList<String>();
    dirs.add(base_dir);

    soot.Scene S = runSoot(cp, dirs, excluded);
    writeGraph(build_PDG(S, excluded, label_type), output_file);
}

From source file:de.mpi_bremen.mgg.FastaValidatorUi.java

/**
 * @param args the command line arguments
 *//*from   w ww .jav a  2 s  . co m*/
public static void main(String[] args) {
    // create Options object
    Options options = new Options();
    // add verbose option
    options.addOption("v", "verbose", false, "verbose mode");
    // add inputfile option
    options.addOption("f", "file", true, "FASTA-formatted input file");
    // add help option
    options.addOption("h", "help", false, "print this help message");
    // add sequencetype option
    options.addOption("t", "seqtype", true, "sequence type (allowed values: all|dna|rna|protein)");
    // add gui-mode option
    options.addOption("nogui", false, "start in non-interactive mode");

    //create the cmdline-parser   
    GnuParser parser = new GnuParser();

    // parse the command line arguments
    try {
        //get cmdline arguments
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println(exp.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("FastaValidatorUi", options, true);
        System.exit(1); //indicate error to external environment
    }

    if (cmdline.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("FastaValidatorUi", options, true);
        System.exit(0); //indicate no errors to external environment
    }

    //which mode? (gui or cmdline)
    if (cmdline.hasOption("nogui")) { //cmdline-mode

        //create new cmdline-gui
        FvCmdline cmdlinegui = new FvCmdline();

        //set verbosity
        cmdlinegui.setVerbose(cmdline.hasOption("v"));

        //handle input file
        if (cmdline.hasOption("f")) {
            cmdlinegui.setInput(cmdline.getOptionValue("f"));
        }

        //set sequencetype
        if (cmdline.hasOption("t")) {
            cmdlinegui.setSequencetype(getSeqtype(cmdline.getOptionValue("t")));
        } else {
            cmdlinegui.setSequencetype(FastaValidator.Sequencetype.ALL);
        }

        //trigger validation and exit with exitcode
        int exitcode = cmdlinegui.validate().getValue();
        System.exit(exitcode);

    } else { //gui-mode
        //start gui in its own thread
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                FvGui w = new FvGui();
            }
        });
    }
}

From source file:ekb.elastic.ingest.TaxiQuery.java

public static void main(String... args) {

    Options options = new Options();
    HelpFormatter help = new HelpFormatter();

    try {//w w  w  . j  av a2s . c o m
        Option hostOpt = new Option("h", "host", true, "ElasticSearch URL");
        hostOpt.setArgs(1);
        hostOpt.setRequired(true);
        Option portOpt = new Option("p", "port", true, "ElasticSearch URL");
        portOpt.setArgs(1);
        portOpt.setRequired(true);
        Option clusterOpt = new Option("c", "cluster", true, "Cluster");
        clusterOpt.setArgs(1);
        clusterOpt.setRequired(true);
        Option indexOpt = new Option("i", "index", true, "The index");
        indexOpt.setArgs(1);
        indexOpt.setRequired(true);

        Option pickupTimeOpt = new Option("u", "pickup", true, "The pickup time");
        pickupTimeOpt.setArgs(1);
        pickupTimeOpt.setRequired(true);
        Option dropTimeOpt = new Option("d", "dropoff", true, "The dropoff time");
        dropTimeOpt.setArgs(1);
        dropTimeOpt.setRequired(true);

        options.addOption(hostOpt);
        options.addOption(portOpt);
        options.addOption(clusterOpt);
        options.addOption(indexOpt);
        options.addOption(pickupTimeOpt);
        options.addOption(dropTimeOpt);

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

        Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name", cmd.getOptionValue('c'))
                .build();
        Client client = new TransportClient(settings).addTransportAddress(new InetSocketTransportAddress(
                cmd.getOptionValue('h'), Integer.parseInt(cmd.getOptionValue('p'))));

        TaxiQuery tq = new TaxiQuery();

        TaxiStats stats = tq.getTaxiStats(client, cmd.getOptionValues("i"));

        log.info("Results:\n" + stats.toDateString());

        sdf.parse(cmd.getOptionValue("u"));
        sdf.parse(cmd.getOptionValue("d"));

        // 2013-01-01T10:10:00

        ArrayList<TaxiBucket> list = tq.getInterval(client, cmd.getOptionValues("index"),
                cmd.getOptionValue("u"), cmd.getOptionValue("d"), 60);

        log.info("List size is: " + list.size());

        client.close();

    } catch (ParseException pe) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);

        help.printUsage(pw, 80, TaxiQuery.class.getName(), options);

        log.error(sw.toString());

    } catch (TaxiQueryException e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        log.error(sw.toString());
    } catch (java.text.ParseException e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        log.error(sw.toString());
    }
}

From source file:apps.classification.ClassifySVMPerf.java

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

    boolean dumpConfidences = false;

    String cmdLineSyntax = ClassifySVMPerf.class.getName()
            + " [OPTIONS] <path to svm_perf_classify> <testIndexDirectory> <modelDirectory>";

    Options options = new Options();

    OptionBuilder.withArgName("d");
    OptionBuilder.withDescription("Dump confidences file");
    OptionBuilder.withLongOpt("d");
    OptionBuilder.isRequired(false);/*from  w  w w  . j a v a 2s . com*/
    OptionBuilder.hasArg(false);
    options.addOption(OptionBuilder.create());

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

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

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

    SvmPerfClassifierCustomizer customizer = null;

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

        remainingArgs = line.getArgs();

        customizer = new SvmPerfClassifierCustomizer(remainingArgs[0]);

        if (line.hasOption("d"))
            dumpConfidences = true;

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

        if (line.hasOption("s")) {
            customizer.setDeleteTestFiles(false);
            customizer.setDeletePredictionsFiles(false);
        }

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

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

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

    String testFile = remainingArgs[1];

    File file = new File(testFile);

    String testName = file.getName();
    String testPath = file.getParent();

    String classifierFile = remainingArgs[2];

    file = new File(classifierFile);

    String classifierName = file.getName();
    String classifierPath = file.getParent();
    FileSystemStorageManager storageManager = new FileSystemStorageManager(testPath, false);
    storageManager.open();
    IIndex test = TroveReadWriteHelper.readIndex(storageManager, testName, TroveContentDBType.Full,
            TroveClassificationDBType.Full);
    storageManager.close();

    SvmPerfDataManager dataManager = new SvmPerfDataManager(customizer);
    storageManager = new FileSystemStorageManager(classifierPath, false);
    storageManager.open();
    SvmPerfClassifier classifier = (SvmPerfClassifier) dataManager.read(storageManager, classifierName);
    storageManager.close();

    classifier.setRuntimeCustomizer(customizer);

    // CLASSIFICATION
    String classificationName = testName + "_" + classifierName;

    Classifier classifierModule = new Classifier(test, classifier, dumpConfidences);
    classifierModule.setClassificationMode(ClassificationMode.PER_CATEGORY);
    classifierModule.exec();

    IClassificationDB testClassification = classifierModule.getClassificationDB();

    storageManager = new FileSystemStorageManager(testPath, false);
    storageManager.open();
    TroveReadWriteHelper.writeClassification(storageManager, testClassification, classificationName + ".cla",
            true);
    storageManager.close();

    if (dumpConfidences) {
        ClassificationScoreDB confidences = classifierModule.getConfidences();
        ClassificationScoreDB.write(testPath + Os.pathSeparator() + classificationName + ".confidences",
                confidences);
    }
}

From source file:edu.uga.cs.fluxbuster.FluxbusterCLI.java

/**
 * The main method./*from w  ww  .  ja v  a2  s . co m*/
 *
 * @param args the command line arguments
 */
public static void main(String[] args) {
    GnuParser parser = new GnuParser();
    Options opts = FluxbusterCLI.initializeOptions();
    CommandLine cli;
    try {
        cli = parser.parse(opts, args);

        if (cli.hasOption('?')) {
            throw new ParseException(null);
        }

        if (validateDate(cli.getOptionValue('d')) && validateDate(cli.getOptionValue('e'))) {

            if (log.isInfoEnabled()) {
                StringBuffer arginfo = new StringBuffer("\n");
                arginfo.append("generate-clusters: " + cli.hasOption('g') + "\n");
                arginfo.append("calc-features: " + cli.hasOption('f') + "\n");
                arginfo.append("calc-similarity: " + cli.hasOption('s') + "\n");
                arginfo.append("classify-clusters: " + cli.hasOption('c') + "\n");
                arginfo.append("start-date: " + cli.getOptionValue('d') + "\n");
                arginfo.append("end-date: " + cli.getOptionValue('e') + "\n");
                log.info(arginfo.toString());
            }

            try {
                boolean clus = true, feat = true, simil = true, clas = true;
                if (cli.hasOption('g') || cli.hasOption('f') || cli.hasOption('s') || cli.hasOption('c')) {
                    if (!cli.hasOption('g')) {
                        clus = false;
                    }
                    if (!cli.hasOption('f')) {
                        feat = false;
                    }
                    if (!cli.hasOption('s')) {
                        simil = false;
                    }
                    if (!cli.hasOption('c')) {
                        clas = false;
                    }
                }

                DBInterfaceFactory.init();
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
                Date logdate = df.parse(cli.getOptionValue('d'));
                long startTime = logdate.getTime() / 1000;
                long endTime = df.parse(cli.getOptionValue('e')).getTime() / 1000;

                if (clus) {
                    ClusterGenerator cg = new ClusterGenerator();
                    List<DomainCluster> clusters = cg.generateClusters(startTime, endTime, true);
                    cg.storeClusters(clusters, logdate);
                }
                if (feat) {
                    FeatureCalculator calc = new FeatureCalculator();
                    calc.updateFeatures(logdate);
                }
                if (simil) {
                    ClusterSimilarityCalculator calc2 = new ClusterSimilarityCalculator();
                    calc2.updateClusterSimilarities(logdate);
                }
                if (clas) {
                    Classifier calc3 = new Classifier();
                    calc3.updateClusterClasses(logdate, 30);
                }
            } catch (Exception e) {
                if (log.isFatalEnabled()) {
                    log.fatal("", e);
                }
            } finally {
                DBInterfaceFactory.shutdown();
            }
        } else {
            throw new ParseException(null);
        }
    } catch (ParseException e1) {
        PrintWriter writer = new PrintWriter(System.out);
        HelpFormatter usageFormatter = new HelpFormatter();
        usageFormatter.printHelp(writer, 80, "fluxbuster", "If none of the options g, f, s, c are specified "
                + "then the program will execute as if all of them "
                + "have been specified.  Otherwise, the program will " + "only execute the options specified.",
                opts, 0, 2, "");
        writer.close();
    }
}

From source file:apps.classification.LearnSVMPerf.java

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

    Options options = new Options();

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

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

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

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

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

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

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

    SvmPerfLearnerCustomizer classificationLearnerCustomizer = null;

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

        remainingArgs = line.getArgs();

        classificationLearnerCustomizer = new SvmPerfLearnerCustomizer(remainingArgs[0]);

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

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

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

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

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

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

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

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

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

    String indexFile = remainingArgs[1];

    File file = new File(indexFile);

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

    // LEARNING
    SvmPerfLearner classificationLearner = new SvmPerfLearner();

    classificationLearner.setRuntimeCustomizer(classificationLearnerCustomizer);

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

    IClassifier classifier = classificationLearner.build(training);

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

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

From source file:com.eucalyptus.upgrade.TestHarness.java

public static void main(String[] args) {
    boolean anyFail = false;
    try {//from  www  .  jav  a  2  s . c o m
        System.out.println(Arrays.asList(args));
        final Options opts = getCliOptions();
        final GnuParser cliParser = new GnuParser();
        final CommandLine cmd = cliParser.parse(opts, args);

        try {
            anyFail = Iterables.any(Lists.newArrayList(Opts.values()), new Predicate<Opts>() {
                public boolean apply(Opts o) {
                    return !o.run(cmd, opts);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.exit(0); //This is necessary now; some shutdown process is hanging
    //return (anyFail) ? 1 : 0;
}

From source file:net.sf.mpaxs.test.ImpaxsExecution.java

/**
 *
 * @param args//from w w w  .  j a v  a 2  s  . c o  m
 */
public static void main(String[] args) {
    Options options = new Options();
    Option[] optionArray = new Option[] {
            OptionBuilder.withArgName("nhosts").hasArg()
                    .withDescription("Number of hosts for parallel processing").create("n"),
            OptionBuilder.withArgName("mjobs").hasArg().withDescription("Number of jobs to run in parallel")
                    .create("m"),
            OptionBuilder.withArgName("runmode").hasArg()
                    .withDescription("The mode in which to operate: one of <ALL,LOCAL,DISTRIBUTED>")
                    .create("r"), //            OptionBuilder.withArgName("gui").
            //            withDescription("Create gui for distributed execution").create("g")
    };
    for (Option opt : optionArray) {
        options.addOption(opt);
    }
    if (args.length == 0) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp(StartUp.class.getCanonicalName(), options, true);
        System.exit(1);
    }
    GnuParser gp = new GnuParser();
    int nhosts = 1;
    int mjobs = 10;
    boolean gui = false;
    Mode mode = Mode.ALL;
    try {
        CommandLine cl = gp.parse(options, args);
        if (cl.hasOption("n")) {
            nhosts = Integer.parseInt(cl.getOptionValue("n"));
        }
        if (cl.hasOption("m")) {
            mjobs = Integer.parseInt(cl.getOptionValue("m"));
        }
        if (cl.hasOption("r")) {
            mode = Mode.valueOf(cl.getOptionValue("r"));
        }
        //            if (cl.hasOption("g")) {
        //                gui = true;
        //            }
    } catch (Exception ex) {
        Logger.getLogger(StartUp.class.getName()).log(Level.SEVERE, null, ex);
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp(StartUp.class.getCanonicalName(), options, true);
        System.exit(1);
    }

    String version;
    try {
        version = net.sf.mpaxs.api.Version.getVersion();
        System.out.println("Running mpaxs " + version);
        File computeHostJarLocation = new File(System.getProperty("user.dir"), "mpaxs.jar");
        if (!computeHostJarLocation.exists() || !computeHostJarLocation.isFile()) {
            throw new IOException("Could not locate mpaxs.jar in " + System.getProperty("user.dir"));
        }
        final PropertiesConfiguration cfg = new PropertiesConfiguration();
        //set default execution type
        cfg.setProperty(ConfigurationKeys.KEY_EXECUTION_MODE, ExecutionType.DRMAA);
        //set location of compute host jar
        cfg.setProperty(ConfigurationKeys.KEY_PATH_TO_COMPUTEHOST_JAR, computeHostJarLocation);
        //do not exit to console when master server shuts down
        cfg.setProperty(ConfigurationKeys.KEY_MASTER_SERVER_EXIT_ON_SHUTDOWN, false);
        //limit the number of used compute hosts
        cfg.setProperty(ConfigurationKeys.KEY_MAX_NUMBER_OF_CHOSTS, nhosts);
        cfg.setProperty(ConfigurationKeys.KEY_NATIVE_SPEC, "");
        cfg.setProperty(ConfigurationKeys.KEY_GUI_MODE, gui);
        cfg.setProperty(ConfigurationKeys.KEY_SILENT_MODE, true);
        cfg.setProperty(ConfigurationKeys.KEY_SCHEDULE_WAIT_TIME, "500");
        final int maxJobs = mjobs;
        final int maxThreads = nhosts;
        final Mode runMode = mode;
        printMessage("Run mode: " + runMode);
        Executors.newSingleThreadExecutor().submit(new Runnable() {
            @Override
            public void run() {
                if (runMode == Mode.ALL || runMode == Mode.LOCAL) {
                    printMessage("Running Within VM Execution");
                    /*
                     * LOCAL within VM execution
                     */
                    WithinVmExecution lhe = new WithinVmExecution(maxJobs, maxThreads);
                    try {
                        Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.INFO,
                                "Sum is: " + lhe.call());
                    } catch (Exception ex) {
                        Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

                if (runMode == Mode.ALL || runMode == Mode.DISTRIBUTED) {
                    printMessage("Running Distributed Host RMI Execution");
                    /*
                     * Grid Engine (DRMAA API) or local host distributed RMI execution
                     */
                    DistributedRmiExecution de = new DistributedRmiExecution(cfg, maxJobs);
                    try {
                        Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.INFO,
                                "Sum is: " + de.call());
                    } catch (Exception ex) {
                        Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                System.exit(0);
            }
        });
    } catch (IOException ex) {
        Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:ch.psi.zmq.receiver.FileReceiver.java

public static void main(String[] args) {

    int port = 8888;
    String source = "localhost";
    Options options = new Options();
    options.addOption("h", false, "Help");

    @SuppressWarnings("static-access")
    Option optionP = OptionBuilder.withArgName("port").hasArg()
            .withDescription("Source port (default: " + port + ")").create("p");
    options.addOption(optionP);//from  w w w.jav  a 2  s  .c  o  m

    @SuppressWarnings("static-access")
    Option optionS = OptionBuilder.withArgName("source").hasArg().isRequired().withDescription(
            "Source address of the ZMQ stream (default port " + port + " : use -p to set the port if needed)")
            .create("s");
    options.addOption(optionS);

    @SuppressWarnings("static-access")
    Option optionD = OptionBuilder.withArgName("path").hasArg().isRequired()
            .withDescription("tpath for storing files with relative destination paths").create("d");
    options.addOption(optionD);

    GnuParser parser = new GnuParser();
    CommandLine line;
    String path = ".";
    try {
        line = parser.parse(options, args);
        if (line.hasOption(optionP.getOpt())) {
            port = Integer.parseInt(line.getOptionValue(optionP.getOpt()));
        }
        if (line.hasOption("h")) {
            HelpFormatter f = new HelpFormatter();
            f.printHelp("receiver", options);
            return;
        }

        source = line.getOptionValue(optionS.getOpt());
        path = line.getOptionValue(optionD.getOpt());

    } catch (ParseException e) {
        System.err.println(e.getMessage());
        HelpFormatter f = new HelpFormatter();
        f.printHelp("receiver", options);
        System.exit(-1);
    }

    final FileReceiver r = new FileReceiver(source, port, path);
    r.receive();

    // Control+C
    Signal.handle(new Signal("INT"), new SignalHandler() {
        int count = 0;

        public void handle(Signal sig) {
            if (count < 1) {
                count++;
                r.terminate();
            } else {
                System.exit(-1);
            }

        }
    });
}