Example usage for java.lang Integer valueOf

List of usage examples for java.lang Integer valueOf

Introduction

In this page you can find the example usage for java.lang Integer valueOf.

Prototype

@HotSpotIntrinsicCandidate
public static Integer valueOf(int i) 

Source Link

Document

Returns an Integer instance representing the specified int value.

Usage

From source file:com.esri.geoevent.test.tools.RunTcpInBdsOutTest.java

public static void main(String args[]) {

    // Example Command line args
    //-n 10000 -g w12ags104a.jennings.home -i 5565 -m https://w12ags104a.jennings.home/arcgis/rest/services/Hosted/FAA-Stream/MapServer/0 -f D:\github\performance-test-harness-for-geoevent\app\simulations\faa-stream.csv -r 1000,3000,1000

    int numberEvents = 10000; // Number of Events    
    String gisServer = "w12ags104a.jennings.home"; // GIS Server
    int inputTcpPort = 5565; // TCP Input Port       

    String msLayerUrl = "http://w12ags104a.jennings.home/arcgis/rest/services/Hosted/FAA-Stream/MapServer/0";

    String EventsInputFile = "D:\\github\\performance-test-harness-for-geoevent\\app\\simulations\\faa-stream.csv"; // Events input File        

    int start_rate = 5000;
    int end_rate = 5005;
    int rate_step = 1;

    Options opts = new Options();
    opts.addOption("n", true, "Number of Events");
    opts.addOption("g", true, "GIS Server");
    opts.addOption("i", true, "Input TCP Port");
    opts.addOption("m", true, "Map Service Layer URL");
    opts.addOption("f", true, "File with GeoEvents to Send");
    opts.addOption("r", true, "Rates to test Start,End,Step");
    opts.addOption("h", false, "Help");

    try {/*from   ww  w  .  ja v a 2 s  .c o m*/

        CommandLineParser parser = new BasicParser();
        CommandLine cmd = null;

        try {
            cmd = parser.parse(opts, args, false);
        } catch (org.apache.commons.cli.ParseException ignore) {
            System.err.println(ignore.getMessage());
        }

        String cmdInputErrorMsg = "";

        if (cmd.getOptions().length == 0 || cmd.hasOption("h")) {
            throw new org.apache.commons.cli.ParseException("Show Help");
        }

        if (cmd.hasOption("n")) {
            String val = cmd.getOptionValue("n");
            try {
                numberEvents = Integer.valueOf(val);
            } catch (NumberFormatException e) {
                cmdInputErrorMsg += "Invalid value for n. Must be integer.\n";
            }
        }

        if (cmd.hasOption("g")) {
            gisServer = cmd.getOptionValue("g");
        }

        if (cmd.hasOption("i")) {
            String val = cmd.getOptionValue("i");
            try {
                inputTcpPort = Integer.valueOf(val);
            } catch (NumberFormatException e) {
                cmdInputErrorMsg += "Invalid value for i. Must be integer.\n";
            }
        }

        if (cmd.hasOption("m")) {
            msLayerUrl = cmd.getOptionValue("m");
        }

        if (cmd.hasOption("f")) {
            EventsInputFile = cmd.getOptionValue("f");
        }

        if (cmd.hasOption("r")) {
            String val = cmd.getOptionValue("r");
            try {
                String parts[] = val.split(",");
                if (parts.length == 3) {
                    start_rate = Integer.parseInt(parts[0]);
                    end_rate = Integer.parseInt(parts[1]);
                    rate_step = Integer.parseInt(parts[2]);
                } else if (parts.length == 1) {
                    // Run single rate
                    start_rate = Integer.parseInt(parts[0]);
                    end_rate = start_rate;
                    rate_step = start_rate;
                } else {
                    throw new org.apache.commons.cli.ParseException(
                            "Rate must be three comma seperated values or a single value");
                }

            } catch (org.apache.commons.cli.ParseException e) {
                cmdInputErrorMsg += e.getMessage();
            } catch (NumberFormatException e) {
                cmdInputErrorMsg += "Invalid value for r. Must be integers.\n";
            }
        }

        if (!cmdInputErrorMsg.equalsIgnoreCase("")) {
            throw new org.apache.commons.cli.ParseException(cmdInputErrorMsg);
        }

        // Assuming the ES port is 9220 
        RunTcpInBdsOutTest t = new RunTcpInBdsOutTest();
        DecimalFormat df = new DecimalFormat("##0");

        if (start_rate == end_rate) {
            // Single Rate Test
            System.out.println("*********************************");
            System.out.println("Incremental testing at requested rate: " + start_rate);
            System.out.println("Count,Incremental Rate");

            t.runTest(numberEvents, start_rate, gisServer, inputTcpPort, EventsInputFile, msLayerUrl, true);
            if (t.send_rate < 0 || t.rcv_rate < 0) {
                throw new Exception("Test Run Failed!");
            }
            System.out.println("Overall Average Send Rate, Received Rate");
            System.out.println(df.format(t.send_rate) + "," + df.format(t.rcv_rate));

        } else {
            System.out.println("*********************************");
            System.out.println("rateRqstd,avgSendRate,avgRcvdRate");

            for (int rate = start_rate; rate <= end_rate; rate += rate_step) {

                t.runTest(numberEvents, rate, gisServer, inputTcpPort, EventsInputFile, msLayerUrl, false);
                if (t.send_rate < 0 || t.rcv_rate < 0) {
                    throw new Exception("Test Run Failed!");
                }
                System.out.println(
                        Integer.toString(rate) + "," + df.format(t.send_rate) + "," + df.format(t.rcv_rate));
                Thread.sleep(3 * 1000);
            }

        }

    } catch (ParseException e) {
        System.out.println("Invalid Command Options: ");
        System.out.println(e.getMessage());
        System.out.println(
                "Command line options: -n NumberOfEvents -g GISServer -i InputTCPPort -m MapServerLayerURL -f FileWithEvents -r StartRate,EndRate,Step");

    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

}

From source file:net.bobah.mail.Dupes.java

public static void main(String[] args) throws Exception {
    installDefaultUncaughtExceptionHandler(log);

    final CommandLineParser parser = new PosixParser();
    final Options options = new Options()
            .addOption("j", "threads", true, "number of parallel threads to use for analyzing")
            .addOption("hash", true,
                    "hash function to use, possible values: " + Arrays.toString(Hashes.values()))
            .addOption("dir", true, "add directory to search");
    final CommandLine cmdline = parser.parse(options, args);

    final int threads = Integer.valueOf(
            cmdline.getOptionValue("threads", String.valueOf(Runtime.getRuntime().availableProcessors())));
    final HashFunction hash = Hashes.valueOf(cmdline.getOptionValue("hash", "adler32")).hashfunc;
    final File[] dirs = Collections2
            .transform(Arrays.asList(cmdline.getOptionValues("dir")), new Function<String, File>() {
                @Override/*from   www  . j a v a 2s.co m*/
                public File apply(String from) {
                    return new File(from);
                }
            }).toArray(new File[] {});

    log.info("hash: {}, threads: {}, dirs: {} in total", hash, threads, dirs.length);
    try {
        new Dupes(threads, hash, dirs).run();
    } finally {
        Utils.shutdownLogger();
    }
}

From source file:ColumnStorage.TestColumnStorage.java

public static void main(String[] argv) throws Exception {

    try {// www  .  ja  v  a 2 s .  co m
        if (argv.length < 1) {
            System.out.println("TestColumnStorage cmd[write | read ]");
            return;
        }

        String cmd = argv[0];
        if (cmd.equals("write")) {
            writeFile1();
            writeFile2();
            writeFile3();
        } else {
            if (argv.length < 2) {
                System.out.println("TestColumnStorage read line");
                return;
            }

            fieldMap.addField(new Field(ConstVar.FieldType_Byte, ConstVar.Sizeof_Byte, (short) 0));
            fieldMap.addField(new Field(ConstVar.FieldType_Short, ConstVar.Sizeof_Short, (short) 1));
            fieldMap.addField(new Field(ConstVar.FieldType_Int, ConstVar.Sizeof_Int, (short) 2));
            fieldMap.addField(new Field(ConstVar.FieldType_Long, ConstVar.Sizeof_Long, (short) 3));
            fieldMap.addField(new Field(ConstVar.FieldType_Float, ConstVar.Sizeof_Float, (short) 4));
            fieldMap.addField(new Field(ConstVar.FieldType_Byte, ConstVar.Sizeof_Byte, (short) 5));
            fieldMap.addField(new Field(ConstVar.FieldType_Short, ConstVar.Sizeof_Short, (short) 6));
            fieldMap.addField(new Field(ConstVar.FieldType_Int, ConstVar.Sizeof_Int, (short) 7));
            fieldMap.addField(new Field(ConstVar.FieldType_Long, ConstVar.Sizeof_Long, (short) 8));
            fieldMap.addField(new Field(ConstVar.FieldType_Double, ConstVar.Sizeof_Double, (short) 9));
            fieldMap.addField(new Field(ConstVar.FieldType_String, 0, (short) 10));

            int line = Integer.valueOf(argv[1]);
            getRecordByLine1(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
        System.out.println("get IOException:" + e.getMessage());
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("get exception:" + e.getMessage());
    }
}

From source file:edu.msu.cme.rdp.kmer.cli.FastKmerFilter.java

public static void main(String[] args) throws Exception {
    final KmerSet<Set<RefKmer>> kmerSet;
    final SeqReader queryReader;
    final SequenceType querySeqType;
    final File queryFile;
    final KmerStartsWriter out;
    final boolean translQuery;
    final int wordSize;
    final int translTable;
    final boolean alignedSeqs;
    final List<String> refLabels = new ArrayList();
    final int maxThreads;
    final int trieWordSize;

    try {//from  ww w .  j  a  va  2s.com
        CommandLine cmdLine = new PosixParser().parse(options, args);
        args = cmdLine.getArgs();

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

        if (cmdLine.hasOption("out")) {
            out = new KmerStartsWriter(cmdLine.getOptionValue("out"));
        } else {
            out = new KmerStartsWriter(System.out);
        }

        if (cmdLine.hasOption("aligned")) {
            alignedSeqs = true;
        } else {
            alignedSeqs = false;
        }

        if (cmdLine.hasOption("transl-table")) {
            translTable = Integer.valueOf(cmdLine.getOptionValue("transl-table"));
        } else {
            translTable = 11;
        }

        if (cmdLine.hasOption("threads")) {
            maxThreads = Integer.valueOf(cmdLine.getOptionValue("threads"));
        } else {
            maxThreads = Runtime.getRuntime().availableProcessors();
        }

        queryFile = new File(args[1]);
        wordSize = Integer.valueOf(args[0]);
        SequenceType refSeqType = null;

        querySeqType = SeqUtils.guessSequenceType(queryFile);
        queryReader = new SequenceReader(queryFile);

        if (querySeqType == SequenceType.Protein) {
            throw new Exception("Expected nucl query sequences");
        }

        refSeqType = SeqUtils
                .guessSequenceType(new File(args[2].contains("=") ? args[2].split("=")[1] : args[2]));

        translQuery = refSeqType == SequenceType.Protein;

        if (translQuery && wordSize % 3 != 0) {
            throw new Exception("Word size must be a multiple of 3 for nucl ref seqs");
        }

        if (translQuery) {
            trieWordSize = wordSize / 3;
        } else {
            trieWordSize = wordSize;
        }
        kmerSet = new KmerSet<Set<RefKmer>>();//new KmerTrie(trieWordSize, translQuery);

        for (int index = 2; index < args.length; index++) {
            String refName;
            String refFileName = args[index];
            if (refFileName.contains("=")) {
                String[] lexemes = refFileName.split("=");
                refName = lexemes[0];
                refFileName = lexemes[1];
            } else {
                String tmpName = new File(refFileName).getName();
                if (tmpName.contains(".")) {
                    refName = tmpName.substring(0, tmpName.lastIndexOf("."));
                } else {
                    refName = tmpName;
                }
            }

            File refFile = new File(refFileName);

            if (refSeqType != SeqUtils.guessSequenceType(refFile)) {
                throw new Exception(
                        "Reference file " + refFile + " contains " + SeqUtils.guessFileFormat(refFile)
                                + " sequences but expected " + refSeqType + " sequences");
            }

            SequenceReader seqReader = new SequenceReader(refFile);
            Sequence seq;

            while ((seq = seqReader.readNextSequence()) != null) {
                if (seq.getSeqName().startsWith("#")) {
                    continue;
                }

                KmerGenerator kmers;
                try {
                    if (translQuery) { //protein ref
                        kmers = new ProtKmerGenerator(seq.getSeqString(), trieWordSize, alignedSeqs);
                    } else {
                        kmers = new NuclKmerGenerator(seq.getSeqString(), trieWordSize, alignedSeqs);
                    }
                    while (kmers.hasNext()) {
                        Kmer temp = kmers.next();
                        long[] next = temp.getLongKmers();
                        Set<RefKmer> refKmers = kmerSet.get(next);
                        if (refKmers == null) {
                            refKmers = new HashSet();
                            kmerSet.add(next, refKmers);
                        }

                        RefKmer kmerRef = new RefKmer();
                        kmerRef.modelPos = kmers.getPosition();
                        kmerRef.refFileIndex = refLabels.size();
                        kmerRef.refSeqid = seq.getSeqName();
                        refKmers.add(kmerRef);
                    }
                } catch (IllegalArgumentException ex) {
                    //System.err.println(seq.getSeqName()+ " " + ex.getMessage());
                }
            }
            seqReader.close();

            refLabels.add(refName);
        }

    } catch (Exception e) {
        new HelpFormatter().printHelp(
                "KmerSearch <kmerSize> <query_file> [name=]<ref_file> ...\nkmerSize should be multiple of 3, (recommend 45, minimum 30, maximum 63) ",
                options);
        e.printStackTrace();
        System.exit(1);
        throw new RuntimeException("Stupid jvm"); //While this will never get thrown it is required to make sure javac doesn't get confused about uninitialized variables
    }

    long startTime = System.currentTimeMillis();
    long seqCount = 0;
    final int maxTasks = 25000;

    System.err.println("Starting kmer mapping at " + new Date());
    System.err.println("*  Number of threads:       " + maxThreads);
    System.err.println("*  References:              " + refLabels);
    System.err.println("*  Reads file:              " + queryFile);
    System.err.println("*  Kmer length:             " + trieWordSize);
    System.err.println("*  Kmer Refset Size:        " + kmerSet.size());

    final AtomicInteger processed = new AtomicInteger();
    final AtomicInteger outstandingTasks = new AtomicInteger();

    ExecutorService service = Executors.newFixedThreadPool(maxThreads);

    Sequence querySeq;

    while ((querySeq = queryReader.readNextSequence()) != null) {
        seqCount++;

        String seqString = querySeq.getSeqString();

        if ((!translQuery && seqString.length() < wordSize)
                || (translQuery && seqString.length() < wordSize + 2)) {
            //System.err.println(querySeq.getSeqName() + "\t" + seqString.length());
            continue;
        }

        final Sequence threadSeq = querySeq;

        Runnable r = new Runnable() {

            public void run() {
                try {
                    processSeq(threadSeq, refLabels, kmerSet, out, wordSize, translQuery, translTable, false);
                    processSeq(threadSeq, refLabels, kmerSet, out, wordSize, translQuery, translTable, true);

                    processed.incrementAndGet();
                    outstandingTasks.decrementAndGet();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        outstandingTasks.incrementAndGet();
        service.submit(r);

        while (outstandingTasks.get() >= maxTasks)
            ;

        if ((processed.get() + 1) % 1000000 == 0) {
            System.err.println("Processed " + processed + " sequences in "
                    + (System.currentTimeMillis() - startTime) + " ms");
        }
    }

    service.shutdown();
    service.awaitTermination(1, TimeUnit.DAYS);

    System.err.println("Finished Processed " + processed + " sequences in "
            + (System.currentTimeMillis() - startTime) + " ms");

    out.close();
}

From source file:edu.msu.cme.rdp.graph.utils.ContigMerger.java

public static void main(String[] args) throws IOException {
    final BufferedReader hmmgsResultReader;
    final IndexedSeqReader nuclContigReader;
    final double minBits;
    final int minProtLength;
    final Options options = new Options();
    final PrintStream out;
    final ProfileHMM hmm;
    final FastaWriter protSeqOut;
    final FastaWriter nuclSeqOut;
    final boolean prot;
    final boolean all;
    final String shortSampleName;

    options.addOption("a", "all", false,
            "Generate all combinations for multiple paths, instead of just the best");
    options.addOption("b", "min-bits", true, "Minimum bits score");
    options.addOption("l", "min-length", true, "Minimum length");
    options.addOption("s", "short_samplename", true,
            "short sample name, to be used as part of contig identifiers. This allow analyzing contigs together from different samples in downstream analysis ");
    options.addOption("o", "out", true, "Write output to file instead of stdout");

    try {/* w  ww.j  av  a  2  s .  c  om*/
        CommandLine line = new PosixParser().parse(options, args);

        if (line.hasOption("min-bits")) {
            minBits = Double.valueOf(line.getOptionValue("min-bits"));
        } else {
            minBits = Double.NEGATIVE_INFINITY;
        }

        if (line.hasOption("min-length")) {
            minProtLength = Integer.valueOf(line.getOptionValue("min-length"));
        } else {
            minProtLength = 0;
        }

        if (line.hasOption("short_samplename")) {
            shortSampleName = line.getOptionValue("short_samplename") + "_";
        } else {
            shortSampleName = "";
        }

        if (line.hasOption("out")) {
            out = new PrintStream(line.getOptionValue("out"));
        } else {
            out = System.err;
        }

        all = line.hasOption("all");

        args = line.getArgs();

        if (args.length != 3) {
            throw new Exception("Unexpected number of arguments");
        }

        hmmgsResultReader = new BufferedReader(new FileReader(new File(args[1])));
        nuclContigReader = new IndexedSeqReader(new File(args[2]));
        hmm = HMMER3bParser.readModel(new File(args[0]));

        prot = (hmm.getAlphabet() == SequenceType.Protein);

        if (prot) {
            protSeqOut = new FastaWriter(new File("prot_merged.fasta"));
        } else {
            protSeqOut = null;
        }
        nuclSeqOut = new FastaWriter(new File("nucl_merged.fasta"));

    } catch (Exception e) {
        new HelpFormatter().printHelp("USAGE: ContigMerger [options] <hmm> <hmmgs_file> <nucl_contig>",
                options);
        System.err.println("Error: " + e.getMessage());
        System.exit(1);
        throw new RuntimeException("I hate you javac");
    }

    String line;
    SearchDirection lastDir = SearchDirection.left; //So this has an assumption built in
    //It depends on hmmgs always outputting left fragments, then right
    //We can't just use the kmer to figure out if we've switched to another starting point
    //because we allow multiple starting model pos, so two different starting
    //positions can have the same starting kmer

    Map<String, Sequence> leftContigs = new HashMap();
    Map<String, Sequence> rightContigs = new HashMap();

    int contigsMerged = 0;
    int writtenMerges = 0;
    long startTime = System.currentTimeMillis();
    String kmer = null;
    String geneName = null;

    while ((line = hmmgsResultReader.readLine()) != null) {
        if (line.startsWith("#")) {
            continue;
        }

        String[] lexemes = line.trim().split("\t");
        if (lexemes.length != 12 || lexemes[0].equals("-")) {
            System.err.println("Skipping line: " + line);
            continue;
        }
        //contig_53493   nirk   1500:6:35:16409:3561/1   ADV15048   tcggcgctctacacgttcctgcagcccggg   40   210   70   left   -44.692   184   0
        int index = 0;

        String seqid = lexemes[0];
        geneName = lexemes[1];
        String readid = lexemes[2];
        String refid = lexemes[3];
        kmer = lexemes[4];
        int modelStart = Integer.valueOf(lexemes[5]);

        int nuclLength = Integer.valueOf(lexemes[6]);
        int protLength = Integer.valueOf(lexemes[7]);

        SearchDirection dir = SearchDirection.valueOf(lexemes[8]);
        if (dir != lastDir) {
            if (dir == SearchDirection.left) {
                List<MergedContig> mergedContigs = all
                        ? mergeAllContigs(leftContigs, rightContigs, kmer, geneName, hmm)
                        : mergeContigs(leftContigs, rightContigs, kmer, geneName, hmm);

                contigsMerged++;

                for (MergedContig mc : mergedContigs) {
                    String mergedId = shortSampleName + geneName + "_" + mc.leftContig + "_" + mc.rightContig;
                    out.println(mergedId + "\t" + mc.length + "\t" + mc.score);

                    if (mc.score > minBits && mc.length > minProtLength) {
                        if (prot) {
                            protSeqOut.writeSeq(mergedId, mc.protSeq);
                        }
                        nuclSeqOut.writeSeq(mergedId, mc.nuclSeq);

                        writtenMerges++;
                    }
                }
                leftContigs.clear();
                rightContigs.clear();
            }

            lastDir = dir;
        }

        Sequence seq = nuclContigReader.readSeq(seqid);

        if (dir == SearchDirection.left) {
            leftContigs.put(seqid, seq);
        } else if (dir == SearchDirection.right) {
            rightContigs.put(seqid, seq);
        } else {
            throw new IOException("Cannot handle search direction " + dir);
        }
    }

    if (!leftContigs.isEmpty() || !rightContigs.isEmpty()) {
        List<MergedContig> mergedContigs = all ? mergeAllContigs(leftContigs, rightContigs, kmer, geneName, hmm)
                : mergeContigs(leftContigs, rightContigs, kmer, geneName, hmm);

        for (MergedContig mc : mergedContigs) {
            String mergedId = shortSampleName + mc.gene + "_" + mc.leftContig + "_" + mc.rightContig;
            out.println(mergedId + "\t" + mc.length + "\t" + mc.score);
            contigsMerged++;

            if (mc.score > minBits && mc.length > minProtLength) {
                if (prot) {
                    protSeqOut.writeSeq(mergedId, mc.protSeq);
                }
                nuclSeqOut.writeSeq(mergedId, mc.nuclSeq);
                writtenMerges++;
            }
        }
    }

    out.close();
    if (prot) {
        protSeqOut.close();
    }
    nuclSeqOut.close();

    System.err.println("Read in " + contigsMerged + " contigs, wrote out " + writtenMerges
            + " merged contigs in " + ((double) (System.currentTimeMillis() - startTime) / 1000) + "s");
}

From source file:org.apache.commons.vfs2.util.NHttpServer.java

public static void main(final String[] args) throws Exception {
    new NHttpServer().run(Integer.valueOf(args[0]), new File(args[1]), 0);
}

From source file:com.abiquo.vsm.migration.Migrator.java

public static void main(String[] args) throws UnknownHostException, IOException {
    String host = getProperty("abiquo.redis.host", "localhost");
    int port = Integer.valueOf(getProperty("abiquo.redis.port", "6379"));

    CommandLine command = null;//from   w w w .  j  av  a 2 s  .co  m
    String filename = null;

    try {
        // Parse the command line arguments
        command = new PosixParser().parse(buildOptions(), args);

        if (command.hasOption("help")) {
            printUsage();
            System.exit(0);
        }

        if (command.hasOption("f")) {
            filename = command.getOptionValue("f");
        }

        if (command.hasOption("h")) {
            host = command.getOptionValue("h");
        }

        if (command.hasOption("p")) {
            port = Integer.parseInt(command.getOptionValue("p"));
        }
    } catch (Exception e) {
        logger.error("Error while parsing arguments. " + e.getMessage());
        printUsage();
        System.exit(-1);
    }

    // Start migration
    Migrator migrator = new Migrator(host, port, 0);
    logger.info("Migrating from 1.6.8 to 1.7 data model on redis located at {}:{}", host, port);

    if (filename == null) {
        migrator.migrateNonPersistedModelFromRedis();
    } else {
        File file = new File(filename);
        migrator.migrateNonPersistedModelFromFile(file);
    }

    migrator.migratePersistedModel();

    logger.info("Number of migrated physical machines: {}", migrator.getMachinesCount());
    logger.info("Number of migrated subscriptions: {}", migrator.getSubscriptionsCount());

    System.exit(0);
}

From source file:com.seanmadden.fast.ldap.main.Main.java

/**
 * The Main Event./*from   w w  w.  j  av a  2 s.  c  om*/
 * 
 * @param args
 */
@SuppressWarnings("static-access")
public static void main(String[] args) {
    BasicConfigurator.configure();
    log.debug("System initializing");
    try {
        Logger.getRootLogger().addAppender(
                new FileAppender(new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN), "log.log"));
    } catch (IOException e1) {
        log.error("Unable to open the log file..?");
    }

    /*
     * Initialize the configuration engine.
     */
    XMLConfiguration config = new XMLConfiguration();
    config.setListDelimiter('|');

    /*
     * Initialize the Command-Line parsing engine.
     */
    CommandLineParser parser = new PosixParser();
    Options opts = new Options();
    opts.addOption(OptionBuilder.withLongOpt("config-file").hasArg()
            .withDescription("The configuration file to load").withArgName("config.xml").create("c"));

    opts.addOption(OptionBuilder.withLongOpt("profile").hasArg().withDescription("The profile to use")
            .withArgName("Default").create("p"));

    opts.addOption(OptionBuilder.withLongOpt("password").hasArg().withDescription("Password to connect with")
            .withArgName("password").create("P"));

    opts.addOption(OptionBuilder.withLongOpt("debug").hasArg(false).create('d'));

    opts.addOption(OptionBuilder.withLongOpt("verbose").hasArg(false).create('v'));

    File configurationFile = new File("config.xml");

    try {
        // Parse the command-line options
        CommandLine cmds = parser.parse(opts, args);

        if (!cmds.hasOption('p')) {
            Logger.getRootLogger().addAppender(new GuiErrorAlerter(Level.ERROR));
        }

        Logger.getRootLogger().setLevel(Level.ERROR);
        if (cmds.hasOption('v')) {
            Logger.getRootLogger().setLevel(Level.INFO);
        }
        if (cmds.hasOption('d')) {
            Logger.getRootLogger().setLevel(Level.DEBUG);
        }

        log.debug("Enabling configuration file parsing");
        // The user has given us a file to parse.
        if (cmds.hasOption("c")) {
            configurationFile = new File(cmds.getOptionValue("c"));
        }
        log.debug("Config file: " + configurationFile);

        // Load the configuration file
        if (configurationFile.exists()) {
            config.load(configurationFile);
        } else {
            log.error("Cannot find config file");
        }

        /*
         * Convert the profiles into memory
         */
        Vector<ConnectionProfile> profs = new Vector<ConnectionProfile>();
        List<?> profList = config.configurationAt("Profiles").configurationsAt("Profile");
        for (Object p : profList) {
            SubnodeConfiguration profile = (SubnodeConfiguration) p;
            String name = profile.getString("[@name]");
            String auth = profile.getString("LdapAuthString");
            String server = profile.getString("LdapServerString");
            String group = profile.getString("LdapGroupsLocation");
            ConnectionProfile prof = new ConnectionProfile(name, server, auth, group);
            profs.add(prof);
        }
        ConnectionProfile prof = null;
        if (!cmds.hasOption('p')) {
            /*
             * Deploy the profile selector, to select a profile
             */
            ProfileSelector profSel = new ProfileSelector(profs);
            prof = profSel.getSelection();
            if (prof == null) {
                return;
            }
            /*
             * Empty the profiles and load a clean copy - then save it back
             * to the file
             */
            config.clearTree("Profiles");
            for (ConnectionProfile p : profSel.getProfiles()) {
                config.addProperty("Profiles.Profile(-1)[@name]", p.getName());
                config.addProperty("Profiles.Profile.LdapAuthString", p.getLdapAuthString());
                config.addProperty("Profiles.Profile.LdapServerString", p.getLdapServerString());
                config.addProperty("Profiles.Profile.LdapGroupsLocation", p.getLdapGroupsString());
            }
            config.save(configurationFile);
        } else {
            for (ConnectionProfile p : profs) {
                if (p.getName().equals(cmds.getOptionValue('p'))) {
                    prof = p;
                    break;
                }
            }
        }

        log.info("User selected " + prof);

        String password = "";
        if (cmds.hasOption('P')) {
            password = cmds.getOptionValue('P');
        } else {
            password = PasswordPrompter.promptForPassword("Password?");
        }

        if (password.equals("")) {
            return;
        }

        LdapInterface ldap = new LdapInterface(prof.getLdapServerString(), prof.getLdapAuthString(),
                prof.getLdapGroupsString(), password);

        /*
         * Gather options information from the configuration engine for the
         * specified report.
         */
        Hashtable<String, Hashtable<String, ReportOption>> reportDataStructure = new Hashtable<String, Hashtable<String, ReportOption>>();
        List<?> repConfig = config.configurationAt("Reports").configurationsAt("Report");
        for (Object p : repConfig) {
            SubnodeConfiguration repNode = (SubnodeConfiguration) p;

            // TODO Do something with the report profile.
            // Allowing the user to deploy "profiles" is a nice feature
            // String profile = repNode.getString("[@profile]");

            String reportName = repNode.getString("[@report]");
            Hashtable<String, ReportOption> reportOptions = new Hashtable<String, ReportOption>();
            reportDataStructure.put(reportName, reportOptions);
            // Loop through the options and add each to the table.
            for (Object o : repNode.configurationsAt("option")) {
                SubnodeConfiguration option = (SubnodeConfiguration) o;
                String name = option.getString("[@name]");
                String type = option.getString("[@type]");
                String value = option.getString("[@value]");

                ReportOption ro = new ReportOption();
                ro.setName(name);

                if (type.toLowerCase().equals("boolean")) {
                    ro.setBoolValue(Boolean.parseBoolean(value));
                } else if (type.toLowerCase().equals("integer")) {
                    ro.setIntValue(Integer.valueOf(value));
                } else {
                    // Assume a string type here then.
                    ro.setStrValue(value);
                }
                reportOptions.put(name, ro);
                log.debug(ro);
            }
        }
        System.out.println(reportDataStructure);

        /*
         * At this point, we now need to deploy the reports window to have
         * the user pick a report and select some happy options to allow
         * that report to work. Let's go.
         */
        /*
         * Deploy the Reports selector, to select a report
         */
        Reports.getInstance().setLdapConnection(ldap);
        ReportsWindow reports = new ReportsWindow(Reports.getInstance().getAllReports(), reportDataStructure);
        Report report = reports.getSelection();
        if (report == null) {
            return;
        }
        /*
         * Empty the profiles and load a clean copy - then save it back to
         * the file
         */
        config.clearTree("Reports");
        for (Report r : Reports.getInstance().getAllReports()) {
            config.addProperty("Reports.Report(-1)[@report]", r.getClass().getCanonicalName());
            config.addProperty("Reports.Report[@name]", "Standard");
            for (ReportOption ro : r.getOptions().values()) {
                config.addProperty("Reports.Report.option(-1)[@name]", ro.getName());
                config.addProperty("Reports.Report.option[@type]", ro.getType());
                config.addProperty("Reports.Report.option[@value]", ro.getStrValue());
            }
        }
        config.save(configurationFile);
        ProgressBar bar = new ProgressBar();
        bar.start();
        report.execute();
        ASCIIFormatter format = new ASCIIFormatter();
        ReportResult res = report.getResult();
        format.format(res, new File(res.getForName() + "_" + res.getReportName() + ".txt"));
        bar.stop();

        JOptionPane.showMessageDialog(null,
                "The report is at " + res.getForName() + "_" + res.getReportName() + ".txt", "Success",
                JOptionPane.INFORMATION_MESSAGE);

    } catch (ParseException e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("FAST Ldap Searcher", opts);
    } catch (ConfigurationException e) {
        e.printStackTrace();
        log.fatal("OH EM GEES!  Configuration errors.");
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.ning.hfind.Find.java

public static void main(String[] origArgs) throws ParseException, IOException {
    PrinterConfig printerConfig = new PrinterConfig();

    CommandLineParser parser = new PosixParser();
    CommandLine line = parser.parse(options, origArgs);
    String[] args = line.getArgs();

    if (args.length > 1) {
        // find(1) seems to complain about the first argument only, let's do the same
        System.out.println(String.format("hfind: %s: unknown option", args[1]));
        System.exit(COMMAND_LINE_ERROR);
    }//from  w w  w .  j a va  2  s .c  om
    if (line.hasOption("help") || args.length == 0) {
        usage();
        return;
    }

    String path = args[0];
    // Optimization: check the depth on a top-level basis, not on a per-file basis
    // This avoids crawling files on Hadoop we don't care about
    int maxDepth = Integer.MAX_VALUE;
    if (line.hasOption("maxdepth")) {
        String maxDepthOptionValue = line.getOptionValue("maxdepth");
        maxDepth = Integer.valueOf(maxDepthOptionValue);
    }
    if (line.hasOption("delete")) {
        // -delete implies -d
        printerConfig.setDepthMode(true);
        printerConfig.setDeleteMode(true);
    }
    if (line.hasOption("d")) {
        printerConfig.setDepthMode(true);
    }
    if (line.hasOption("print0")) {
        printerConfig.setEndLineWithNull(true);
    }
    if (line.hasOption("verbose")) {
        printerConfig.setVerbose(true);
    }

    // Ignore certain primaries
    Iterator<Option> optionsIterator = ExpressionFactory.sanitizeCommandLine(line.getOptions());

    Expression expression = null;
    try {
        expression = ExpressionFactory
                .buildExpressionFromCommandLine(new PushbackIterator<Option>(optionsIterator));
        //System.out.println(String.format("find %s: %s", StringUtils.join(origArgs, " "), expression));
    } catch (IllegalArgumentException e) {
        System.err.println(e);
        System.exit(COMMAND_LINE_ERROR);
    }

    try {
        expression.run(path, maxDepth, printerConfig);
        System.exit(0);
    } catch (IOException e) {
        System.err.println(String.format("Error crawling HDFS: %s", e.getLocalizedMessage()));
        System.exit(HADOOP_ERROR);
    }
}

From source file:com.bitsofproof.example.Simple.java

public static void main(String[] args) {
    Security.addProvider(new BouncyCastleProvider());

    final CommandLineParser parser = new GnuParser();
    final Options gnuOptions = new Options();
    gnuOptions.addOption("h", "help", false, "I can't help you yet");
    gnuOptions.addOption("s", "server", true, "Server URL");
    gnuOptions.addOption("u", "user", true, "User");
    gnuOptions.addOption("p", "password", true, "Password");

    System.out.println("BOP Bitcoin Server Simple Client 3.5.0 (c) 2013-2014 bits of proof zrt.");
    CommandLine cl = null;//www .  j a  va 2  s  .  co m
    String url = null;
    String user = null;
    String password = null;
    try {
        cl = parser.parse(gnuOptions, args);
        url = cl.getOptionValue('s');
        user = cl.getOptionValue('u');
        password = cl.getOptionValue('p');
    } catch (org.apache.commons.cli.ParseException e) {
        e.printStackTrace();
        System.exit(1);
    }
    if (url == null || user == null || password == null) {
        System.err.println("Need -s server -u user -p password");
        System.exit(1);
    }

    BCSAPI api = getServer(url, user, password);
    try {
        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        long start = System.currentTimeMillis();
        api.ping(start);
        System.out.println("Server round trip " + (System.currentTimeMillis() - start) + "ms");
        api.addAlertListener(new AlertListener() {
            @Override
            public void alert(String s, int severity) {
                System.err.println("ALERT: " + s);
            }
        });
        System.out.println("Talking to " + (api.isProduction() ? "PRODUCTION" : "test") + " server");
        ConfirmationManager confirmationManager = new ConfirmationManager();
        confirmationManager.init(api, 144);
        System.out.printf("Please enter wallet name: ");
        String wallet = input.readLine();
        SimpleFileWallet w = new SimpleFileWallet(wallet + ".wallet");
        TransactionFactory am = null;
        if (!w.exists()) {
            System.out.printf("Enter passphrase: ");
            String passphrase = input.readLine();
            System.out.printf("Enter master (empty for new): ");
            String master = input.readLine();
            if (master.equals("")) {
                w.init(passphrase);
                w.unlock(passphrase);
                System.out.printf("First account: ");
                String account = input.readLine();
                am = w.createAccountManager(account);
                w.lock();
                w.persist();
            } else {
                StringTokenizer tokenizer = new StringTokenizer(master, "@");
                String key = tokenizer.nextToken();
                long since = 0;
                if (tokenizer.hasMoreElements()) {
                    since = Long.parseLong(tokenizer.nextToken()) * 1000;
                }
                w.init(passphrase, ExtendedKey.parse(key), true, since);
                w.unlock(passphrase);
                System.out.printf("First account: ");
                String account = input.readLine();
                am = w.createAccountManager(account);
                w.lock();
                w.persist();
                w.sync(api);
            }
        } else {
            w = SimpleFileWallet.read(wallet + ".wallet");
            w.sync(api);
            List<String> names = w.getAccountNames();
            System.out.println("Accounts:");
            System.out.println("---------");
            String first = null;
            for (String name : names) {
                System.out.println(name);
                if (first == null) {
                    first = name;
                }
            }
            System.out.println("---------");
            am = w.getAccountManager(first);
            System.out.println("Using account " + first);
        }
        confirmationManager.addAccount(am);
        api.registerTransactionListener(am);

        while (true) {
            printMenu();
            String answer = input.readLine();
            System.out.printf("\n");
            if (answer.equals("1")) {
                System.out.printf("The balance is: " + printBit(am.getBalance()) + "\n");
                System.out.printf("     confirmed: " + printBit(am.getConfirmed()) + "\n");
                System.out.printf("    receiveing: " + printBit(am.getReceiving()) + "\n");
                System.out.printf("        change: " + printBit(am.getChange()) + "\n");
                System.out.printf("(      sending: " + printBit(am.getSending()) + ")\n");
            } else if (answer.equals("2")) {
                for (Address a : am.getAddresses()) {
                    System.out.printf(a + "\n");
                }
            } else if (answer.equals("3")) {
                ExtendedKeyAccountManager im = (ExtendedKeyAccountManager) am;
                System.out.printf(
                        im.getMaster().serialize(api.isProduction()) + "@" + im.getCreated() / 1000 + "\n");
            } else if (answer.equals("4")) {
                System.out.printf("Enter passphrase: ");
                String passphrase = input.readLine();
                w.unlock(passphrase);
                ExtendedKeyAccountManager im = (ExtendedKeyAccountManager) am;
                System.out.printf(
                        im.getMaster().serialize(api.isProduction()) + "@" + im.getCreated() / 1000 + "\n");
                w.lock();
            } else if (answer.equals("5")) {
                System.out.printf("Enter passphrase: ");
                String passphrase = input.readLine();
                w.unlock(passphrase);
                System.out.printf("Number of recipients");
                Integer nr = Integer.valueOf(input.readLine());
                Transaction spend;
                if (nr.intValue() == 1) {
                    System.out.printf("Receiver address: ");
                    String address = input.readLine();
                    System.out.printf("amount (Bit): ");
                    long amount = parseBit(input.readLine());
                    spend = am.pay(Address.fromSatoshiStyle(address), amount);
                    System.out.println("About to send " + printBit(amount) + " to " + address);
                } else {
                    List<Address> addresses = new ArrayList<>();
                    List<Long> amounts = new ArrayList<>();
                    long total = 0;
                    for (int i = 0; i < nr; ++i) {
                        System.out.printf("Receiver address: ");
                        String address = input.readLine();
                        addresses.add(Address.fromSatoshiStyle(address));
                        System.out.printf("amount (Bit): ");
                        long amount = parseBit(input.readLine());
                        amounts.add(amount);
                        total += amount;
                    }
                    spend = am.pay(addresses, amounts);
                    System.out.println("About to send " + printBit(total));
                }
                System.out.println("inputs");
                for (TransactionInput in : spend.getInputs()) {
                    System.out.println(in.getSourceHash() + " " + in.getIx());
                }
                System.out.println("outputs");
                for (TransactionOutput out : spend.getOutputs()) {
                    System.out.println(out.getOutputAddress() + " " + printBit(out.getValue()));
                }
                w.lock();
                System.out.printf("Type yes to go: ");
                if (input.readLine().equals("yes")) {
                    api.sendTransaction(spend);
                    System.out.printf("Sent transaction: " + spend.getHash());
                } else {
                    System.out.printf("Nothing happened.");
                }
            } else if (answer.equals("6")) {
                System.out.printf("Address: ");
                Set<Address> match = new HashSet<Address>();
                match.add(Address.fromSatoshiStyle(input.readLine()));
                api.scanTransactionsForAddresses(match, 0, new TransactionListener() {
                    @Override
                    public boolean process(Transaction t) {
                        System.out.printf("Found transaction: " + t.getHash() + "\n");
                        return true;
                    }
                });
            } else if (answer.equals("7")) {
                System.out.printf("Public key: ");
                ExtendedKey ek = ExtendedKey.parse(input.readLine());
                api.scanTransactions(ek, 0, 10, 0, new TransactionListener() {
                    @Override
                    public boolean process(Transaction t) {
                        System.out.printf("Found transaction: " + t.getHash() + "\n");
                        return true;
                    }
                });
            } else if (answer.equals("a")) {
                System.out.printf("Enter account name: ");
                String account = input.readLine();
                am = w.getAccountManager(account);
                api.registerTransactionListener(am);
                confirmationManager.addAccount(am);
            } else if (answer.equals("c")) {
                System.out.printf("Enter account name: ");
                String account = input.readLine();
                System.out.printf("Enter passphrase: ");
                String passphrase = input.readLine();
                w.unlock(passphrase);
                am = w.createAccountManager(account);
                System.out.println("using account: " + account);
                w.lock();
                w.persist();
                api.registerTransactionListener(am);
                confirmationManager.addAccount(am);
            } else if (answer.equals("m")) {
                System.out.printf("Enter passphrase: ");
                String passphrase = input.readLine();
                w.unlock(passphrase);
                System.out.println(w.getMaster().serialize(api.isProduction()));
                System.out.println(w.getMaster().getReadOnly().serialize(true));
                w.lock();
            } else if (answer.equals("s")) {
                System.out.printf("Enter private key: ");
                String key = input.readLine();
                ECKeyPair k = ECKeyPair.parseWIF(key);
                KeyListAccountManager alm = new KeyListAccountManager();
                alm.addKey(k);
                alm.syncHistory(api);
                Address a = am.getNextReceiverAddress();
                Transaction t = alm.pay(a, alm.getBalance(), PaymentOptions.receiverPaysFee);
                System.out.println("About to sweep " + printBit(alm.getBalance()) + " to " + a);
                System.out.println("inputs");
                for (TransactionInput in : t.getInputs()) {
                    System.out.println(in.getSourceHash() + " " + in.getIx());
                }
                System.out.println("outputs");
                for (TransactionOutput out : t.getOutputs()) {
                    System.out.println(out.getOutputAddress() + " " + printBit(out.getValue()));
                }
                System.out.printf("Type yes to go: ");
                if (input.readLine().equals("yes")) {
                    api.sendTransaction(t);
                    System.out.printf("Sent transaction: " + t.getHash());
                } else {
                    System.out.printf("Nothing happened.");
                }
            } else {
                System.exit(0);
            }
        }
    } catch (Exception e) {
        System.err.println("Something went wrong");
        e.printStackTrace();
        System.exit(1);
    }
}