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:edu.msu.cme.rdp.readseq.utils.QualityTrimmer.java

public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("f", "fastq-out", false, "Write fastq instead of fasta file");
    options.addOption("l", "less-than", false, "Trim at <= instead of strictly =");
    options.addOption("i", "illumina", false, "Illumina trimming mode");

    FastqWriter fastqOut = null;/*  ww  w .  j av a 2 s .co m*/
    FastaWriter fastaOut = null;

    byte qualTrim = -1;

    boolean writeFasta = true;
    boolean trimle = false;
    boolean illumina = false;

    List<SeqReader> readers = new ArrayList();
    List<File> seqFiles = new ArrayList();

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

        if (line.hasOption("fastq-out")) {
            writeFasta = false;
        }

        if (line.hasOption("less-than")) {
            trimle = true;
        }
        if (line.hasOption("illumina")) {
            illumina = true;
        }

        args = line.getArgs();

        if (args.length < 2) {
            throw new Exception("Unexpected number of arguments");
        }

        if (args[0].length() != 1) {
            throw new Exception("Expected single character quality score");
        }

        qualTrim = FastqCore.Phred33QualFunction.translate(args[0].charAt(0));

        for (int index = 1; index < args.length; index++) {
            File seqFile = new File(args[index]);
            SeqReader reader;
            if (SeqUtils.guessFileFormat(seqFile) == SequenceFormat.FASTA) {
                if (index + 1 == args.length) {
                    throw new Exception("Fasta files must be immediately followed by their quality file");
                }

                File qualFile = new File(args[index + 1]);
                if (SeqUtils.guessFileFormat(qualFile) != SequenceFormat.FASTA) {
                    throw new Exception(seqFile + " was not followed by a fasta quality file");
                }

                reader = new QSeqReader(seqFile, qualFile);
                index++;
            } else {
                if (seqFile.getName().endsWith(".gz")) {
                    reader = new SequenceReader(new GZIPInputStream(new FileInputStream(seqFile)));
                } else {
                    reader = new SequenceReader(seqFile);
                }
            }

            readers.add(reader);
            seqFiles.add(seqFile);
        }
    } catch (Exception e) {
        new HelpFormatter().printHelp("USAGE: QualityTrimmer [options] <ascii_score> <seq_file> [qual_file]",
                options, true);
        System.err.println("Error: " + e.getMessage());
        System.exit(1);
    }

    for (int readerIndex = 0; readerIndex < readers.size(); readerIndex++) {
        File seqFile = seqFiles.get(readerIndex);
        String outStem = "trimmed_" + seqFile.getName().substring(0, seqFile.getName().lastIndexOf("."));
        if (writeFasta) {
            fastaOut = new FastaWriter(outStem + ".fasta");
        } else {
            fastqOut = new FastqWriter(outStem + ".fastq", FastqCore.Phred33QualFunction);
        }

        int[] lengthHisto = new int[200];

        SeqReader reader = readers.get(readerIndex);

        QSequence qseq;

        long totalLength = 0;
        int totalSeqs = 0;
        long trimmedLength = 0;
        int trimmedSeqs = 0;

        int zeroLengthAfterTrimming = 0;

        long startTime = System.currentTimeMillis();

        while ((qseq = (QSequence) reader.readNextSequence()) != null) {
            char[] bases = qseq.getSeqString().toCharArray();
            byte[] qual = qseq.getQuality();

            if (bases.length != qual.length) {
                System.err.println(qseq.getSeqName() + ": Quality length doesn't match seq length for seq");
                continue;
            }

            totalSeqs++;
            totalLength += bases.length;

            int trimIndex = -1;
            if (illumina && qual[bases.length - 1] == qualTrim) {
                trimIndex = bases.length - 1;
                while (trimIndex >= 0 && qual[trimIndex] == qualTrim) {
                    trimIndex--;
                }

                trimIndex++; //Technically we're positioned over the first good base, move back to the last bad base
            } else if (!illumina) {
                for (int index = 0; index < bases.length; index++) {
                    if (qual[index] == qualTrim || (trimle && qual[index] < qualTrim)) {
                        trimIndex = index;
                        break;
                    }
                }
            }

            String outSeq;
            byte[] outQual;
            if (trimIndex == -1) {
                outSeq = qseq.getSeqString();
                outQual = qseq.getQuality();
            } else {
                outSeq = new String(bases, 0, trimIndex);
                outQual = Arrays.copyOfRange(qual, 0, trimIndex);
                trimmedSeqs++;
            }
            int len = outSeq.length();
            trimmedLength += len;

            if (len >= lengthHisto.length) {
                lengthHisto = Arrays.copyOf(lengthHisto, len + 1);
            }
            lengthHisto[len]++;

            if (outSeq.length() == 0) {
                //System.err.println(qseq.getSeqName() + ": length 0 after trimming");
                zeroLengthAfterTrimming++;
                continue;
            }

            if (writeFasta) {
                fastaOut.writeSeq(qseq.getSeqName(), qseq.getDesc(), outSeq);
            } else {
                fastqOut.writeSeq(qseq.getSeqName(), qseq.getDesc(), outSeq, outQual);
            }
        }

        reader.close();

        if (writeFasta) {
            fastaOut.close();
        } else {
            fastqOut.close();
        }

        System.out.println(
                "Processed " + seqFile + " in " + (System.currentTimeMillis() - startTime) / 1000.0 + "s");
        System.out.println("Before trimming:");
        System.out.println("Total Sequences:           " + totalSeqs);
        System.out.println("Total Sequence Data:       " + totalLength);
        System.out.println("Average sequence length:   " + ((float) totalLength / totalSeqs));
        System.out.println();
        System.out.println("After trimming:");
        System.out.println("Total Sequences:           " + (totalSeqs - zeroLengthAfterTrimming));
        System.out.println("Sequences Trimmed:         " + trimmedSeqs);
        System.out.println("Total Sequence Data:       " + trimmedLength);
        System.out.println("Average sequence length:   "
                + ((float) trimmedLength / (totalSeqs - zeroLengthAfterTrimming)));
        System.out.println();

        System.out.println("Length\tCount");
        for (int index = 0; index < lengthHisto.length; index++) {
            if (lengthHisto[index] == 0) {
                continue;
            }

            System.out.println(index + "\t" + lengthHisto[index]);
        }

        System.out.println();
        System.out.println();
        System.out.println();
    }
}

From source file:com.alibaba.rocketmq.example.benchmark.Consumer.java

public static void main(String[] args) throws MQClientException {
    Options options = ServerUtil.buildCommandlineOptions(new Options());
    CommandLine commandLine = ServerUtil.parseCmdLine("benchmarkConsumer", args,
            buildCommandlineOptions(options), new PosixParser());
    if (null == commandLine) {
        System.exit(-1);/*from   w  w  w.j a  va 2 s  .c om*/
    }

    final String topic = commandLine.hasOption('t') ? commandLine.getOptionValue('t').trim() : "BenchmarkTest";
    final String groupPrefix = commandLine.hasOption('g') ? commandLine.getOptionValue('g').trim()
            : "benchmark_consumer";
    final String isPrefixEnable = commandLine.hasOption('p') ? commandLine.getOptionValue('p').trim() : "true";
    String group = groupPrefix;
    if (Boolean.parseBoolean(isPrefixEnable)) {
        group = groupPrefix + "_" + Long.toString(System.currentTimeMillis() % 100);
    }

    System.out.printf("topic %s group %s prefix %s%n", topic, group, isPrefixEnable);

    final StatsBenchmarkConsumer statsBenchmarkConsumer = new StatsBenchmarkConsumer();

    final Timer timer = new Timer("BenchmarkTimerThread", true);

    final LinkedList<Long[]> snapshotList = new LinkedList<Long[]>();

    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            snapshotList.addLast(statsBenchmarkConsumer.createSnapshot());
            if (snapshotList.size() > 10) {
                snapshotList.removeFirst();
            }
        }
    }, 1000, 1000);

    timer.scheduleAtFixedRate(new TimerTask() {
        private void printStats() {
            if (snapshotList.size() >= 10) {
                Long[] begin = snapshotList.getFirst();
                Long[] end = snapshotList.getLast();

                final long consumeTps = (long) (((end[1] - begin[1]) / (double) (end[0] - begin[0])) * 1000L);
                final double averageB2CRT = (end[2] - begin[2]) / (double) (end[1] - begin[1]);
                final double averageS2CRT = (end[3] - begin[3]) / (double) (end[1] - begin[1]);

                System.out.printf(
                        "Consume TPS: %d Average(B2C) RT: %7.3f Average(S2C) RT: %7.3f MAX(B2C) RT: %d MAX(S2C) RT: %d%n",
                        consumeTps, averageB2CRT, averageS2CRT, end[4], end[5]);
            }
        }

        @Override
        public void run() {
            try {
                this.printStats();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }, 10000, 10000);

    DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(group);
    consumer.setInstanceName(Long.toString(System.currentTimeMillis()));

    consumer.subscribe(topic, "*");

    consumer.registerMessageListener(new MessageListenerConcurrently() {
        @Override
        public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
                ConsumeConcurrentlyContext context) {
            MessageExt msg = msgs.get(0);
            long now = System.currentTimeMillis();

            statsBenchmarkConsumer.getReceiveMessageTotalCount().incrementAndGet();

            long born2ConsumerRT = now - msg.getBornTimestamp();
            statsBenchmarkConsumer.getBorn2ConsumerTotalRT().addAndGet(born2ConsumerRT);

            long store2ConsumerRT = now - msg.getStoreTimestamp();
            statsBenchmarkConsumer.getStore2ConsumerTotalRT().addAndGet(store2ConsumerRT);

            compareAndSetMax(statsBenchmarkConsumer.getBorn2ConsumerMaxRT(), born2ConsumerRT);

            compareAndSetMax(statsBenchmarkConsumer.getStore2ConsumerMaxRT(), store2ConsumerRT);

            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        }
    });

    consumer.start();

    System.out.printf("Consumer Started.%n");
}

From source file:edu.cmu.lti.oaqa.annographix.apps.SolrSimpleIndexApp.java

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

    options.addOption("i", null, true, "Input File");
    options.addOption("u", null, true, "Solr URI");
    options.addOption("n", null, true, "Batch size");

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

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

        if (cmd.hasOption("i")) {
            inputFile = cmd.getOptionValue("i");
        } else {
            Usage("Specify Input File");
        }

        if (cmd.hasOption("u")) {
            solrURI = cmd.getOptionValue("u");
        } else {
            Usage("Specify Solr URI");
        }

        if (cmd.hasOption("n")) {
            batchQty = Integer.parseInt(cmd.getOptionValue("n"));
        }

        SolrServerWrapper solrServer = new SolrServerWrapper(solrURI);

        BufferedReader inpText = new BufferedReader(
                new InputStreamReader(CompressUtils.createInputStream(inputFile)));

        XmlHelper xmlHlp = new XmlHelper();

        String docText = XmlHelper.readNextXMLIndexEntry(inpText);

        for (int docNum = 1; docText != null; ++docNum, docText = XmlHelper.readNextXMLIndexEntry(inpText)) {

            // 1. Read document text
            Map<String, String> docFields = null;
            HashMap<String, Object> objDocFields = new HashMap<String, Object>();

            try {
                docFields = xmlHlp.parseXMLIndexEntry(docText);
            } catch (SAXException e) {
                System.err.println("Parsing error, offending DOC:" + NL + docText);
                throw new Exception("Parsing error.");
            }

            for (Map.Entry<String, String> e : docFields.entrySet()) {
                //System.out.println(e.getKey() + " " + e.getValue());
                objDocFields.put(e.getKey(), e.getValue());
            }

            solrServer.indexDocument(objDocFields);
            if ((docNum - 1) % batchQty == 0)
                solrServer.indexCommit();
        }
        solrServer.indexCommit();

    } 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.aerospike.client.rest.AerospikeRESTfulService.java

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

    Options options = new Options();
    options.addOption("h", "host", true, "Server hostname (default: localhost)");
    options.addOption("p", "port", true, "Server port (default: 3000)");

    // parse the command line args
    CommandLineParser parser = new PosixParser();
    CommandLine cl = parser.parse(options, args, false);

    // set properties
    Properties as = System.getProperties();
    String host = cl.getOptionValue("h", "localhost");
    as.put("seedHost", host);
    String portString = cl.getOptionValue("p", "3000");
    as.put("port", portString);

    // start app/*from w  ww  .j a  va 2s.c  o  m*/
    SpringApplication.run(AerospikeRESTfulService.class, args);

}

From source file:com.akana.demo.freemarker.templatetester.App.java

public static void main(String[] args) {

    final Options options = new Options();

    @SuppressWarnings("static-access")
    Option optionContentType = OptionBuilder.withArgName("content-type").hasArg()
            .withDescription("content type of model").create("content");
    @SuppressWarnings("static-access")
    Option optionUrlPath = OptionBuilder.withArgName("httpRequestLine").hasArg()
            .withDescription("url path and parameters in HTTP Request Line format").create("url");
    @SuppressWarnings("static-access")
    Option optionRootMessageName = OptionBuilder.withArgName("messageName").hasArg()
            .withDescription("root data object name, defaults to 'message'").create("root");
    @SuppressWarnings("static-access")
    Option optionAdditionalMessages = OptionBuilder.withArgName("dataModelPaths")
            .hasArgs(Option.UNLIMITED_VALUES).withDescription("additional message object data sources")
            .create("messages");
    @SuppressWarnings("static-access")
    Option optionDebugMessages = OptionBuilder.hasArg(false)
            .withDescription("Shows debug information about template processing").create("debug");

    Option optionHelp = new Option("help", "print this message");

    options.addOption(optionHelp);/*from   www. j av  a  2 s .c o m*/
    options.addOption(optionContentType);
    options.addOption(optionUrlPath);
    options.addOption(optionRootMessageName);
    options.addOption(optionAdditionalMessages);
    options.addOption(optionDebugMessages);

    CommandLineParser parser = new DefaultParser();

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

        // Check for help flag
        if (cmd.hasOption("help")) {
            showHelp(options);
            return;
        }

        String[] remainingArguments = cmd.getArgs();
        if (remainingArguments.length < 2) {
            showHelp(options);
            return;
        }
        String ftlPath, dataPath = "none";

        ftlPath = remainingArguments[0];
        dataPath = remainingArguments[1];

        String contentType = "text/xml";
        // Discover content type from file extension
        String ext = FilenameUtils.getExtension(dataPath);
        if (ext.equals("json")) {
            contentType = "json";
        } else if (ext.equals("txt")) {
            contentType = "txt";
        }
        // Override discovered content type
        if (cmd.hasOption("content")) {
            contentType = cmd.getOptionValue("content");
        }
        // Root data model name
        String rootMessageName = "message";
        if (cmd.hasOption("root")) {
            rootMessageName = cmd.getOptionValue("root");
        }
        // Additional data models
        String[] additionalModels = new String[0];
        if (cmd.hasOption("messages")) {
            additionalModels = cmd.getOptionValues("messages");
        }
        // Debug Info
        if (cmd.hasOption("debug")) {
            System.out.println(" Processing ftl   : " + ftlPath);
            System.out.println("   with data model: " + dataPath);
            System.out.println(" with content-type: " + contentType);
            System.out.println(" data model object: " + rootMessageName);
            if (cmd.hasOption("messages")) {
                System.out.println("additional models: " + additionalModels.length);
            }
        }

        Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
        cfg.setDirectoryForTemplateLoading(new File("."));
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

        /* Create the primary data-model */
        Map<String, Object> message = new HashMap<String, Object>();
        if (contentType.contains("json") || contentType.contains("txt")) {
            message.put("contentAsString",
                    FileUtils.readFileToString(new File(dataPath), StandardCharsets.UTF_8));
        } else {
            message.put("contentAsXml", freemarker.ext.dom.NodeModel.parse(new File(dataPath)));
        }

        if (cmd.hasOption("url")) {
            message.put("getProperty", new AkanaGetProperty(cmd.getOptionValue("url")));
        }

        Map<String, Object> root = new HashMap<String, Object>();
        root.put(rootMessageName, message);
        if (additionalModels.length > 0) {
            for (int i = 0; i < additionalModels.length; i++) {
                Map<String, Object> m = createMessageFromFile(additionalModels[i], contentType);
                root.put("message" + i, m);
            }
        }

        /* Get the template (uses cache internally) */
        Template temp = cfg.getTemplate(ftlPath);

        /* Merge data-model with template */
        Writer out = new OutputStreamWriter(System.out);
        temp.process(root, out);

    } catch (ParseException e) {
        showHelp(options);
        System.exit(1);
    } catch (IOException e) {
        System.out.println("Unable to parse ftl.");
        e.printStackTrace();
    } catch (SAXException e) {
        System.out.println("XML parsing issue.");
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        System.out.println("Unable to configure parser.");
        e.printStackTrace();
    } catch (TemplateException e) {
        System.out.println("Unable to parse template.");
        e.printStackTrace();
    }

}

From source file:com.guye.baffle.obfuscate.Main.java

public static void main(String[] args) throws IOException, BaffleException {
    Options opt = new Options();

    opt.addOption("c", "config", true, "config file path,keep or mapping");

    opt.addOption("o", "output", true, "output mapping writer file");

    opt.addOption("v", "verbose", false, "explain what is being done.");

    opt.addOption("h", "help", false, "print help for the command.");

    opt.getOption("c").setArgName("file list");

    opt.getOption("o").setArgName("file path");

    String formatstr = "baffle [-c/--config filepaths list ][-o/--output filepath][-h/--help] ApkFile TargetApkFile";

    HelpFormatter formatter = new HelpFormatter();
    CommandLineParser parser = new PosixParser();
    CommandLine cl = null;/*from w  w w  .  j av a2s .com*/
    try {
        // ?Options?
        cl = parser.parse(opt, args);

    } catch (ParseException e) {
        formatter.printHelp(formatstr, opt); // ???
        return;
    }

    if (cl == null || cl.getArgs() == null || cl.getArgs().length == 0) {
        formatter.printHelp(formatstr, opt);
        return;
    }

    // ?-h--help??
    if (cl.hasOption("h")) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp(formatstr, "", opt, "");
        return;
    }

    // ???DirectoryName
    String[] str = cl.getArgs();
    if (str == null || str.length != 2) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("not specify apk file or taget apk file", opt);
        return;
    }

    if (str[1].equals(str[0])) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("apk file can not rewrite , please specify new target file", opt);
        return;
    }
    File apkFile = new File(str[0]);
    if (!apkFile.exists()) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("apk file not exists", opt);
        return;
    }

    File[] configs = null;
    if (cl.hasOption("c")) {
        String cfg = cl.getOptionValue("c");
        String[] fs = cfg.split(",");
        int len = fs.length;
        configs = new File[fs.length];
        for (int i = 0; i < len; i++) {
            configs[i] = new File(fs[i]);
            if (!configs[i].exists()) {
                HelpFormatter hf = new HelpFormatter();
                hf.printHelp("config file " + fs[i] + " not exists", opt);
                return;
            }
        }
    }

    File mappingfile = null;
    if (cl.hasOption("o")) {
        String mfile = cl.getOptionValue("o");
        mappingfile = new File(mfile);

        if (mappingfile.getParentFile() != null) {
            mappingfile.getParentFile().mkdirs();
        }

    }

    if (cl.hasOption('v')) {
        Logger.getLogger(Obfuscater.LOG_NAME).setLevel(Level.CONFIG);
    } else {
        Logger.getLogger(Obfuscater.LOG_NAME).setLevel(Level.OFF);
    }

    Logger.getLogger(Obfuscater.LOG_NAME).addHandler(new ConsoleHandler());

    Obfuscater obfuscater = new Obfuscater(configs, mappingfile, apkFile, str[1]);

    obfuscater.obfuscate();
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.CdoQueryRenameAllMethods.java

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

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input CDO resource directory");
    inputOpt.setArgs(1);//  www.  j  a  va 2 s .  c o m
    inputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    Option repoOpt = OptionBuilder.create(REPO_NAME);
    repoOpt.setArgName("REPO_NAME");
    repoOpt.setDescription("CDO Repository name");
    repoOpt.setArgs(1);
    repoOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(inClassOpt);
    options.addOption(repoOpt);

    CommandLineParser parser = new PosixParser();

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

        String repositoryDir = commandLine.getOptionValue(IN);
        String repositoryName = commandLine.getOptionValue(REPO_NAME);

        Class<?> inClazz = CdoQueryRenameAllMethods.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        EmbeddedCDOServer server = new EmbeddedCDOServer(repositoryDir, repositoryName);
        try {
            server.run();
            CDOSession session = server.openSession();
            ((CDONet4jSession) session).options().setCommitTimeout(50 * 1000);
            CDOTransaction transaction = session.openTransaction();
            Resource resource = transaction.getRootResource();

            String name = UUID.randomUUID().toString();
            {
                LOG.log(Level.INFO, "Start query");
                long begin = System.currentTimeMillis();
                JavaQueries.renameAllMethods(resource, name);
                long end = System.currentTimeMillis();
                transaction.commit();
                LOG.log(Level.INFO, "End query");
                LOG.log(Level.INFO,
                        MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
            }

            //            {
            //               transaction.close();
            //               session.close();
            //               
            //               session = server.openSession();
            //               transaction = session.openTransaction();
            //               resource = transaction.getRootResource();
            //               
            //               EList<? extends EObject> methodList = JavaQueries.getAllInstances(resource, JavaPackage.eINSTANCE.getMethodDeclaration());
            //               int i = 0;
            //               for (EObject eObject: methodList) {
            //                  MethodDeclaration method = (MethodDeclaration) eObject;
            //                  if (name.equals(method.getName())) {
            //                     i++;
            //                  }
            //               }
            //               LOG.log(Level.INFO, MessageFormat.format("Renamed {0} methods", i));
            //            }

            transaction.close();
            session.close();
        } finally {
            server.stop();
        }
    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:com.redhat.poc.jdg.bankofchina.function.TestCase413RemoteMultiThreads.java

public static void main(String[] args) throws Exception {
    CommandLine commandLine;//from   www . j  a  v  a  2  s.co m
    Options options = new Options();
    options.addOption("s", true, "The start csv file number option");
    options.addOption("e", true, "The end csv file number option");
    BasicParser parser = new BasicParser();
    parser.parse(options, args);
    commandLine = parser.parse(options, args);
    if (commandLine.getOptions().length > 0) {
        if (commandLine.hasOption("s")) {
            String start = commandLine.getOptionValue("s");
            if (start != null && start.length() > 0) {
                csvFileStart = Integer.parseInt(start);
            }
        }
        if (commandLine.hasOption("e")) {
            String end = commandLine.getOptionValue("e");
            if (end != null && end.length() > 0) {
                csvFileEnd = Integer.parseInt(end);
            }
        }
    }

    System.out.println(
            "%%%%%%%%%  csv ?, ?, ?(ms),"
                    + new Date().getTime());
    for (int i = csvFileStart; i <= csvFileEnd; i++) {
        new TestCase413RemoteMultiThreads(i).start();
    }
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.CdoQueryInvisibleMethodDeclarations.java

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

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input CDO resource directory");
    inputOpt.setArgs(1);/*from  w ww  .  ja  va  2s.c o  m*/
    inputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    Option repoOpt = OptionBuilder.create(REPO_NAME);
    repoOpt.setArgName("REPO_NAME");
    repoOpt.setDescription("CDO Repository name");
    repoOpt.setArgs(1);
    repoOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(inClassOpt);
    options.addOption(repoOpt);

    CommandLineParser parser = new PosixParser();

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

        String repositoryDir = commandLine.getOptionValue(IN);
        String repositoryName = commandLine.getOptionValue(REPO_NAME);

        Class<?> inClazz = CdoQueryInvisibleMethodDeclarations.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        EmbeddedCDOServer server = new EmbeddedCDOServer(repositoryDir, repositoryName);
        try {
            server.run();
            CDOSession session = server.openSession();
            CDOTransaction transaction = session.openTransaction();
            Resource resource = transaction.getRootResource();

            {
                LOG.log(Level.INFO, "Start query");
                long begin = System.currentTimeMillis();
                EList<MethodDeclaration> list = JavaQueries.getInvisibleMethodDeclarations(resource);
                long end = System.currentTimeMillis();
                LOG.log(Level.INFO, "End query");
                LOG.log(Level.INFO, MessageFormat.format("Query result contains {0} elements", list.size()));
                LOG.log(Level.INFO,
                        MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
            }

            transaction.close();
            session.close();
        } finally {
            server.stop();
        }
    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:com.redhat.poc.jdg.bankofchina.function.TestCase412RemoteMultiThreads.java

public static void main(String[] args) throws Exception {
    CommandLine commandLine;/*from  w ww.  j  a  va  2 s  . co  m*/
    Options options = new Options();
    options.addOption("s", true, "The start csv file number option");
    options.addOption("e", true, "The end csv file number option");
    BasicParser parser = new BasicParser();
    parser.parse(options, args);
    commandLine = parser.parse(options, args);
    if (commandLine.getOptions().length > 0) {
        if (commandLine.hasOption("s")) {
            String start = commandLine.getOptionValue("s");
            if (start != null && start.length() > 0) {
                csvFileStart = Integer.parseInt(start);
            }
        }
        if (commandLine.hasOption("e")) {
            String end = commandLine.getOptionValue("e");
            if (end != null && end.length() > 0) {
                csvFileEnd = Integer.parseInt(end);
            }
        }
    }

    System.out.println(
            "%%%%%%%%%  csv ?, ?, ?(ms),"
                    + new Date().getTime());
    for (int i = csvFileStart; i <= csvFileEnd; i++) {
        new TestCase412RemoteMultiThreads(i).start();
    }
}