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

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

Introduction

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

Prototype

Options

Source Link

Usage

From source file:com.rabbitmq.examples.FileConsumer.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption(new Option("h", "uri", true, "AMQP URI"));
    options.addOption(new Option("q", "queue", true, "queue name"));
    options.addOption(new Option("t", "type", true, "exchange type"));
    options.addOption(new Option("e", "exchange", true, "exchange name"));
    options.addOption(new Option("k", "routing-key", true, "routing key"));
    options.addOption(new Option("d", "directory", true, "output directory"));

    CommandLineParser parser = new GnuParser();

    try {//  w  ww. j  a v  a 2  s  .  co  m
        CommandLine cmd = parser.parse(options, args);

        String uri = strArg(cmd, 'h', "amqp://localhost");
        String requestedQueueName = strArg(cmd, 'q', "");
        String exchangeType = strArg(cmd, 't', "direct");
        String exchange = strArg(cmd, 'e', null);
        String routingKey = strArg(cmd, 'k', null);
        String outputDirName = strArg(cmd, 'd', ".");

        File outputDir = new File(outputDirName);
        if (!outputDir.exists() || !outputDir.isDirectory()) {
            System.err.println("Output directory must exist, and must be a directory.");
            System.exit(2);
        }

        ConnectionFactory connFactory = new ConnectionFactory();
        connFactory.setUri(uri);
        Connection conn = connFactory.newConnection();

        final Channel ch = conn.createChannel();

        String queueName = (requestedQueueName.equals("") ? ch.queueDeclare()
                : ch.queueDeclare(requestedQueueName, false, false, false, null)).getQueue();

        if (exchange != null || routingKey != null) {
            if (exchange == null) {
                System.err.println("Please supply exchange name to bind to (-e)");
                System.exit(2);
            }
            if (routingKey == null) {
                System.err.println("Please supply routing key pattern to bind to (-k)");
                System.exit(2);
            }
            ch.exchangeDeclare(exchange, exchangeType);
            ch.queueBind(queueName, exchange, routingKey);
        }

        QueueingConsumer consumer = new QueueingConsumer(ch);
        ch.basicConsume(queueName, consumer);
        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            Map<String, Object> headers = delivery.getProperties().getHeaders();
            byte[] body = delivery.getBody();
            Object headerFilenameO = headers.get("filename");
            String headerFilename = (headerFilenameO == null) ? UUID.randomUUID().toString()
                    : headerFilenameO.toString();
            File givenName = new File(headerFilename);
            if (givenName.getName().equals("")) {
                System.out.println("Skipping file with empty name: " + givenName);
            } else {
                File f = new File(outputDir, givenName.getName());
                System.out.print("Writing " + f + " ...");
                FileOutputStream o = new FileOutputStream(f);
                o.write(body);
                o.close();
                System.out.println(" done.");
            }
            ch.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        }
    } catch (Exception ex) {
        System.err.println("Main thread caught exception: " + ex);
        ex.printStackTrace();
        System.exit(1);
    }
}

From source file:eu.scape_project.sanselan_wrapper.SanselanCli.java

public static void main(String[] args) {
    try {/*from  w  w w .jav  a  2  s . c  o m*/
        Options options = new Options();
        options.addOption("i", "input-file", true, "input file");
        options.addOption("o", "output-file", true, "output file");

        CommandLineParser parser = new PosixParser();
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption("i") && cmd.hasOption("o")) {
            BufferedImage inImage = SanselanWrapper.load(cmd.getOptionValue("i"), null);
            SanselanWrapper.convert(inImage, cmd.getOptionValue("o"), null);
        } else {
            System.out.println("usage: (-i|--input-file=) INPUT_FILE (-o|--output-file=) OUTPUT_FILE");
            System.exit(1);
        }
    } catch (Exception e) {
        System.err.println(e);
        System.exit(1);
    }
    System.exit(0);
}

From source file:eu.scape_project.imageio_wrapper.ImageIOCli.java

public static void main(String[] args) {
    try {/*from  w  w w  .  j  a v a 2 s.c  om*/
        Options options = new Options();
        options.addOption("i", "input-file", true, "input file");
        options.addOption("o", "output-file", true, "output file");

        CommandLineParser parser = new PosixParser();
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption("i") && cmd.hasOption("o")) {
            BufferedImage inImage = ImageIOWrapper.load(cmd.getOptionValue("i"), null);
            if (inImage != null) {
                ImageIOWrapper.convert(inImage, cmd.getOptionValue("o"), null);
            } else {
                System.out.println("Unsuported input image file format!");
                System.exit(1);
            }
        } else {
            System.out.println("usage: (-i|--input-file=) INPUT_FILE (-o|--output-file=) OUTPUT_FILE");
            System.exit(1);
        }
    } catch (Exception e) {
        System.err.println(e);
        System.exit(1);
    }
    System.exit(0);
}

From source file:com.artistech.tuio.dispatch.TuioPublish.java

public static void main(String[] args) throws InterruptedException {
    //read off the TUIO port from the command line
    int tuio_port = 3333;
    int zeromq_port = 5565;
    TuioSink.SerializeType serialize_method = TuioSink.SerializeType.PROTOBUF;

    Options options = new Options();
    options.addOption("t", "tuio-port", true, "TUIO Port to listen on. (Default = 3333)");
    options.addOption("z", "zeromq-port", true, "ZeroMQ Port to publish on. (Default = 5565)");
    options.addOption("s", "serialize-method", true,
            "Serialization Method (JSON, OBJECT, Default = PROTOBUF).");
    options.addOption("h", "help", false, "Show this message.");
    HelpFormatter formatter = new HelpFormatter();

    try {//ww w . j av  a2s. c om
        CommandLineParser parser = new org.apache.commons.cli.BasicParser();
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("help")) {
            formatter.printHelp("tuio-zeromq-publish", options);
            return;
        } else {
            if (cmd.hasOption("t") || cmd.hasOption("tuio-port")) {
                tuio_port = Integer.parseInt(cmd.getOptionValue("t"));
            }
            if (cmd.hasOption("z") || cmd.hasOption("zeromq-port")) {
                zeromq_port = Integer.parseInt(cmd.getOptionValue("z"));
            }
            if (cmd.hasOption("s") || cmd.hasOption("serialize-method")) {
                serialize_method = (TuioSink.SerializeType) Enum.valueOf(TuioSink.SerializeType.class,
                        cmd.getOptionValue("s"));
            }
        }
    } catch (ParseException | IllegalArgumentException ex) {
        System.err.println("Error Processing Command Options:");
        formatter.printHelp("tuio-zeromq-publish", options);
        return;
    }

    //start up the zmq publisher
    ZMQ.Context context = ZMQ.context(1);
    // We send updates via this socket
    try (ZMQ.Socket publisher = context.socket(ZMQ.PUB)) {
        // We send updates via this socket
        publisher.bind("tcp://*:" + Integer.toString(zeromq_port));

        //create a new TUIO sink connected at the specified port
        TuioSink sink = new TuioSink();
        sink.setSerializationType(serialize_method);
        TuioClient client = new TuioClient(tuio_port);

        System.out.println(
                MessageFormat.format("Listening to TUIO message at port: {0}", Integer.toString(tuio_port)));
        System.out.println(
                MessageFormat.format("Publishing to ZeroMQ at port: {0}", Integer.toString(zeromq_port)));
        System.out.println(MessageFormat.format("Serializing as: {0}", serialize_method));
        client.addTuioListener(sink);
        client.connect();

        //while not halted (infinite loop...)
        //read any available messages and publish
        while (!sink.mailbox.isHalted()) {
            ImmutablePair<String, byte[]> msg = sink.mailbox.getMessage();
            publisher.sendMore(msg.left + "." + serialize_method.toString());
            publisher.send(msg.right, 0);
        }

        //cleanup
    }
    context.term();
}

From source file:msuresh.raftdistdb.AtomixDB.java

/**
 * Main Method which runs a Apache CLI which takes 3 different options for the 3 operations <br>
 * @param args <br>//ww  w  .j a va 2  s  .  c  om
 * Options : <br>
 * -setup numberOfReplicas numberOfPartitions -- which sets the system given thenumber of partitions number of replicas per partition<br>
 * -set key Value -- adds a key value pair to the DB<br>
 * -get key -- returns a value for the key if it exists<br>
 * @throws InterruptedException 
 */
public static void main(String[] args) throws InterruptedException, ExecutionException, FileNotFoundException {
    Options options = new Options();
    Option opt = new Option("setup", true, "Sets up the replica that run the Raft Consensus Algorithm.");
    opt.setArgs(3);
    options.addOption(opt);
    opt = new Option("set", true, " Add a key-value pair into the Distributed Database.");
    opt.setArgs(3);
    options.addOption(opt);
    opt = new Option("get", true, "Given a key gets the value from the DB");
    opt.setArgs(2);
    options.addOption(opt);
    opt = new Option("clean", false, "Cleans the state information.");
    options.addOption(opt);
    opt = new Option("test", true, "Cleans the state information.");
    opt.setArgs(2);
    options.addOption(opt);
    try {
        CommandLineParser parser = new BasicParser();
        CommandLine line = null;
        line = parser.parse(options, args);
        if (line.hasOption("setup")) {
            String[] vals = line.getOptionValues("setup");
            System.out.println(vals[0]);
            RaftCluster.createCluster(vals[0], Integer.parseInt(vals[1]), Integer.parseInt(vals[2]));
        } else if (line.hasOption("set")) {
            String[] vals = line.getOptionValues("set");
            addKey(vals[0], vals[1], vals[2]);
        } else if (line.hasOption("get")) {
            String[] vals = line.getOptionValues("get");
            getKey(vals[0], vals[1]);
        } else if (line.hasOption("clean")) {
            cleanState();
        } else if (line.hasOption("test")) {
            String[] vals = line.getOptionValues("test");
            TestAtomix.createCluster(vals[0], Integer.parseInt(vals[1]));
        }
    } catch (ParseException exp) {
        System.out.println("Unexpected exception:" + exp.getMessage());
    }
}

From source file:com.genentech.chemistry.tool.align.SDFAlign.java

public static void main(String... args) {
    Options options = new Options();
    Option opt = new Option("in", true, "input sd file");
    opt.setRequired(true);//  ww  w . java 2  s  .c o m
    options.addOption(opt);

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

    opt = new Option("method", true, "fss|sss|MCS|clique (default mcs).");
    options.addOption(opt);

    opt = new Option("ref", true,
            "reference molecule if not given first in file is used. If multiple ref molecules are read the min RMSD is reported");
    options.addOption(opt);

    opt = new Option("mirror", false, "If given and the molecule is not chiral, return best mirror image.");
    options.addOption(opt);

    opt = new Option("rmsdTag", true, "Tagname for output of rmsd, default: no output.");
    options.addOption(opt);

    opt = new Option("atomMatch", true,
            "Sequence of none|default|hcount|noAromatic specifing how atoms are matched cf. oe document.\n"
                    + "noAromatic can be used to make terminal atoms match aliphatic and aromatic atoms.\n"
                    + "Queryfeatures are considered only if default is used.");
    options.addOption(opt);

    opt = new Option("bondMatch", true,
            "Sequence of none|default specifing how bonds are matched cf. oe document.");
    options.addOption(opt);

    opt = new Option("keepCoreHydrogens", false,
            "If not specified the hydrigen atoms are removed from the core.");
    options.addOption(opt);

    opt = new Option("outputMol", true, "aligned|original (def: aligned) use original to just compute rmsd.");
    options.addOption(opt);

    opt = new Option("doNotOptimize", false,
            "If specified the RMSD is computed without moving optimizing the overlay.");
    options.addOption(opt);

    opt = new Option("quiet", false, "Reduced warining messages");
    options.addOption(opt);

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        exitWithHelp(e.getMessage(), options);
    }

    if (cmd.getArgs().length > 0)
        exitWithHelp("To many arguments", options);

    // do not check aromaticity on atoms so that a terminal atom matches aromatic and non aromatic atoms
    int atomExpr = OEExprOpts.DefaultAtoms;
    int bondExpr = OEExprOpts.DefaultBonds;

    String atomMatch = cmd.getOptionValue("atomMatch");
    if (atomMatch == null)
        atomMatch = "";
    atomMatch = '|' + atomMatch.toLowerCase() + '|';

    String bondMatch = cmd.getOptionValue("bondMatch");
    if (bondMatch == null)
        bondMatch = "";
    bondMatch = '|' + bondMatch.toLowerCase() + '|';

    String inFile = cmd.getOptionValue("in");
    String outFile = cmd.getOptionValue("out");
    String refFile = cmd.getOptionValue("ref");
    String method = cmd.getOptionValue("method");
    String rmsdTag = cmd.getOptionValue("rmsdTag");
    String oMol = cmd.getOptionValue("outputMol");
    boolean doMirror = cmd.hasOption("mirror");
    boolean doOptimize = !cmd.hasOption("doNotOptimize");
    boolean quiet = cmd.hasOption("quiet");

    OUTType outputMol = oMol == null ? OUTType.ALIGNED : OUTType.valueOf(oMol.toUpperCase());

    if (atomMatch.startsWith("|none"))
        atomExpr = 0;
    if (atomMatch.contains("|hcount|"))
        atomExpr |= OEExprOpts.HCount;
    if (atomMatch.contains("|noAromatic|"))
        atomExpr &= (~OEExprOpts.Aromaticity);

    if (bondMatch.startsWith("|none"))
        bondExpr = 0;

    ArrayList<OEMol> refmols = new ArrayList<OEMol>();
    if (refFile != null) {
        oemolistream reffs = new oemolistream(refFile);
        if (!is3DFormat(reffs.GetFormat()))
            oechem.OEThrow.Fatal("Invalid input format: need 3D coordinates");
        reffs.SetFormat(OEFormat.MDL);

        int aromodel = OEIFlavor.Generic.OEAroModelOpenEye;
        int qflavor = reffs.GetFlavor(reffs.GetFormat());
        reffs.SetFlavor(reffs.GetFormat(), (qflavor | aromodel));

        OEMol rmol = new OEMol();
        while (oechem.OEReadMDLQueryFile(reffs, rmol)) {
            if (!cmd.hasOption("keepCoreHydrogens"))
                oechem.OESuppressHydrogens(rmol);
            refmols.add(rmol);
            rmol = new OEMol();
        }
        rmol.delete();

        if (refmols.size() == 0)
            throw new Error("reference file had no entries");

        reffs.close();
    }

    oemolistream fitfs = new oemolistream(inFile);
    if (!is3DFormat(fitfs.GetFormat()))
        oechem.OEThrow.Fatal("Invalid input format: need 3D coordinates");

    oemolostream ofs = new oemolostream(outFile);
    if (!is3DFormat(ofs.GetFormat()))
        oechem.OEThrow.Fatal("Invalid output format: need 3D coordinates");

    AlignInterface aligner = null;
    OEGraphMol fitmol = new OEGraphMol();

    if (oechem.OEReadMolecule(fitfs, fitmol)) {
        if (refmols.size() == 0) {
            OEMol rmol = new OEMol(fitmol);
            if (!cmd.hasOption("keepCoreHydrogens"))
                oechem.OESuppressHydrogens(rmol);

            refmols.add(rmol);
        }

        if ("sss".equalsIgnoreCase(method)) {
            aligner = new SSSAlign(refmols, outputMol, rmsdTag, doOptimize, doMirror, atomExpr, bondExpr,
                    quiet);

        } else if ("clique".equalsIgnoreCase(method)) {
            aligner = new CliqueAlign(refmols, outputMol, rmsdTag, doOptimize, doMirror, atomExpr, bondExpr,
                    quiet);

        } else if ("fss".equalsIgnoreCase(method)) {
            if (cmd.hasOption("atomMatch") || cmd.hasOption("bondMatch"))
                exitWithHelp("method fss does not support '-atomMatch' or '-bondMatch'", options);
            aligner = new FSSAlign(refmols, outputMol, rmsdTag, doOptimize, doMirror);

        } else {
            aligner = new McsAlign(refmols, outputMol, rmsdTag, doOptimize, doMirror, atomExpr, bondExpr,
                    quiet);
        }

        do {
            aligner.align(fitmol);
            oechem.OEWriteMolecule(ofs, fitmol);
        } while (oechem.OEReadMolecule(fitfs, fitmol));

    }

    fitmol.delete();
    if (aligner != null)
        aligner.close();
    for (OEMolBase mol : refmols)
        mol.delete();
    fitfs.close();
    ofs.close();
}

From source file:hisqisnoten.HisqisNoten.java

public static void main(String[] args) {
    options = new Options();
    options.addOption("h", "help", false, "this help");
    options.addOption("u", "user", true, "username for hisqis");
    options.addOption("p", "pass", true, "password for hisqis");
    options.addOption("c", "console", false, "console mode instead of gui mode");

    CommandLineParser parser = new PosixParser();

    try {// ww  w .j  av  a2  s . c om
        CommandLine cmdline = parser.parse(options, args);

        if (cmdline.hasOption("help")) {
            printHelp();
            System.exit(0);
        }

        if (cmdline.getArgList().size() != 0) {
            System.err.println("Please use the new commandline options.");
            System.out.println();

            printHelp();
            System.exit(1);
        }

        HisqisSettings settings = null;
        HisqisSettings.genConfigPath();

        for (File configpath : HisqisSettings.configpath) {
            if (configpath.exists() && configpath.canRead()) {
                settings = HisqisSettingsReader.loadDocument(configpath);

                if (settings != null) {
                    break;
                }
            }
        }

        if (settings == null) {
            settings = new HisqisSettings();
        }

        String user = cmdline.getOptionValue("user", null);
        String pass = cmdline.getOptionValue("pass", null);

        if (user != null) {
            settings.username = user;
        }
        if (pass != null) {
            settings.password = pass;
        }

        if (cmdline.hasOption("console")) {
            new HisqisConsole(settings);
        } else {
            new HisqisGUI(settings);
        }
    } catch (ParseException e) {
        printHelp();
    }
}

From source file:edu.msu.cme.rdp.readseq.ToFasta.java

public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("m", "mask", true, "Mask sequence name indicating columns to drop");
    String maskSeqid = null;//ww  w .ja  va  2 s .  com

    try {
        CommandLine line = new PosixParser().parse(options, args);

        if (line.hasOption("mask")) {
            maskSeqid = line.getOptionValue("mask");
        }

        args = line.getArgs();
        if (args.length == 0) {
            throw new Exception("");
        }

    } catch (Exception e) {
        new HelpFormatter().printHelp("USAGE: to-fasta <input-file>", options);
        System.err.println("ERROR: " + e.getMessage());
        System.exit(1);
        return;
    }

    SeqReader reader = null;

    FastaWriter out = new FastaWriter(System.out);
    Sequence seq;
    int totalSeqs = 0;
    long totalTime = System.currentTimeMillis();

    for (String fname : args) {
        if (fname.equals("-")) {
            reader = new SequenceReader(System.in);
        } else {
            File seqFile = new File(fname);

            if (maskSeqid == null) {
                reader = new SequenceReader(seqFile);
            } else {
                reader = new IndexedSeqReader(seqFile, maskSeqid);
            }
        }

        long startTime = System.currentTimeMillis();
        int thisFileTotalSeqs = 0;
        while ((seq = reader.readNextSequence()) != null) {
            out.writeSeq(seq.getSeqName().replace(" ", "_"), seq.getDesc(), seq.getSeqString());
            thisFileTotalSeqs++;
        }
        totalSeqs += thisFileTotalSeqs;
        System.err.println("Converted " + thisFileTotalSeqs + " (total sequences: " + totalSeqs
                + ") sequences from " + fname + " (" + reader.getFormat() + ") to fasta in "
                + (System.currentTimeMillis() - startTime) / 1000 + " s");
    }
    System.err.println("Converted " + totalSeqs + " to fasta in "
            + (System.currentTimeMillis() - totalTime) / 1000 + " s");

    out.close();
}

From source file:au.id.hazelwood.xmltvguidebuilder.runner.Main.java

public static void main(String[] args) throws Exception {
    SLF4JBridgeHandler.install();//w  w  w  . j  ava 2s  .  c om

    Options options = new Options();
    options.addOption(createOptionWithArg("config", true, "file", File.class, "Config file location"));
    options.addOption(createOptionWithArg("out", true, "file", File.class, "Output file name"));

    try {
        CommandLineParser parser = new GnuParser();
        CommandLine line = parser.parse(options, args);
        App app = new App();
        app.run((File) line.getParsedOptionValue("config"), (File) line.getParsedOptionValue("out"));
    } catch (ParseException exp) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Main", options, true);
    }
}

From source file:edu.upc.eetac.dsa.exercices.java.lang.exceptions.App.java

public static void main(String[] args) throws FileNotFoundException {
    String filename = null;//  ww w  . j ava 2s . c  o  m
    String maxInteger = null;

    Options options = new Options();
    Option optionFile = OptionBuilder.withArgName("file").hasArg().withDescription("file with integers")
            .withLongOpt("file").create("f");
    options.addOption(optionFile);
    Option optionMax = OptionBuilder.withArgName("max").hasArg()
            .withDescription("maximum integer allowed in the file").withLongOpt("max").create("M");
    options.addOption(optionFile);
    options.addOption(optionMax);

    options.addOption("h", "help", false, "prints this message");

    CommandLineParser parser = new GnuParser();
    CommandLine line = null;
    try {
        // parse the command line arguments
        line = parser.parse(options, args);
        if (line.hasOption("h")) { // No hace falta preguntar por el parmetro "help". Ambos son sinnimos
            new HelpFormatter().printHelp(App.class.getCanonicalName(), options);
            return;
        }
        filename = line.getOptionValue("f");
        if (filename == null) {
            throw new org.apache.commons.cli.ParseException(
                    "You must provide the path to the file with numbers.");
        }
        maxInteger = line.getOptionValue("M");
    } catch (ParseException exp) {
        System.err.println(exp.getMessage());
        new HelpFormatter().printHelp(App.class.getCanonicalName(), options);
        return;
    }

    try {
        int[] numbers = (maxInteger != null) ? FileNumberReader.readFile(filename, Integer.parseInt(maxInteger))
                : FileNumberReader.readFile(filename);
        for (int i = 0; i < numbers.length; i++) {
            System.out.println("Integer read: " + numbers[i]);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (BigNumberException e) {
        e.printStackTrace();
    }
}