Example usage for java.lang RuntimeException RuntimeException

List of usage examples for java.lang RuntimeException RuntimeException

Introduction

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

Prototype

public RuntimeException(Throwable cause) 

Source Link

Document

Constructs a new runtime exception with the specified cause and a detail message of (cause==null ?

Usage

From source file:com.cilogi.lid.util.TEA.java

public static void main(String[] args) {
    /* Create a cipher using the first 16 bytes of the passphrase */
    TEA tea = new TEA("And is there honey still for tea?".getBytes());

    byte[] original = quote.getBytes(Charsets.UTF_8);

    /* Run it through the cipher... and back */
    byte[] crypt = tea.encrypt(original);
    byte[] result = tea.decrypt(crypt);

    /* Ensure that all went well */
    String test = new String(result, Charsets.UTF_8);
    if (!test.equals(quote))
        throw new RuntimeException("Fail");
}

From source file:com.act.biointerpretation.BiointerpretationDriver.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());/*  w  ww  .  j a  va2 s. co  m*/
    }

    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        System.err.format("Argument parsing failed: %s\n", e.getMessage());
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        System.exit(1);
    }

    if (cl.hasOption("help")) {
        HELP_FORMATTER.printHelp(ReactionDesalter.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        return;
    }

    if (cl.hasOption(OPTION_CONFIGURATION_FILE)) {
        List<BiointerpretationStep> steps;
        File configFile = new File(cl.getOptionValue(OPTION_CONFIGURATION_FILE));
        if (!configFile.exists()) {
            String msg = String.format("Cannot find configuration file at %s", configFile.getAbsolutePath());
            LOGGER.error(msg);
            throw new RuntimeException(msg);
        }
        // Read the whole config file.
        try (InputStream is = new FileInputStream(configFile)) {
            steps = OBJECT_MAPPER.readValue(is, new TypeReference<List<BiointerpretationStep>>() {
            });
        } catch (IOException e) {
            LOGGER.error("Caught IO exception when attempting to read configuration file: %s", e.getMessage());
            throw e; // Crash after logging if the config file can't be read.
        }

        // Ask for explicit confirmation before dropping databases.
        LOGGER.info("Biointerpretation plan:");
        for (BiointerpretationStep step : steps) {
            crashIfInvalidDBName(step.getReadDBName());
            crashIfInvalidDBName(step.getWriteDBName());
            LOGGER.info("%s: %s -> %s", step.getOperation(), step.getReadDBName(), step.getWriteDBName());
        }
        LOGGER.warn("WARNING: each DB to be written will be dropped before the writing step commences");
        LOGGER.info("Proceed? [y/n]");
        String readLine;
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
            readLine = reader.readLine();
        }
        readLine.trim();
        if ("y".equalsIgnoreCase(readLine) || "yes".equalsIgnoreCase(readLine)) {
            LOGGER.info("Biointerpretation plan confirmed, commencing");
            for (BiointerpretationStep step : steps) {
                performOperation(step, true);
            }
            LOGGER.info("Biointerpretation plan completed");
        } else {
            LOGGER.info("Biointerpretation plan not confirmed, exiting");
        }
    } else if (cl.hasOption(OPTION_SINGLE_OPERATION)) {
        if (!cl.hasOption(OPTION_SINGLE_READ_DB) || !cl.hasOption(OPTION_SINGLE_WRITE_DB)) {
            String msg = "Must specify read and write DB names when performing a single operation";
            LOGGER.error(msg);
            throw new RuntimeException(msg);
        }
        BiointerpretationOperation operation;
        try {
            operation = BiointerpretationOperation.valueOf(cl.getOptionValue(OPTION_SINGLE_OPERATION));
        } catch (IllegalArgumentException e) {
            LOGGER.error("Caught IllegalArgumentException when trying to parse operation '%s': %s",
                    cl.getOptionValue(OPTION_SINGLE_OPERATION), e.getMessage());
            throw e; // Crash if we can't interpret the operation.
        }
        String readDB = crashIfInvalidDBName(cl.getOptionValue(OPTION_SINGLE_READ_DB));
        String writeDB = crashIfInvalidDBName(cl.getOptionValue(OPTION_SINGLE_WRITE_DB));

        performOperation(new BiointerpretationStep(operation, readDB, writeDB), false);
    } else {
        String msg = "Must specify either a config file or a single operation to perform.";
        LOGGER.error(msg);
        throw new RuntimeException(msg);
    }
}

From source file:de.huberlin.wbi.cuneiform.cmdline.main.Main.java

public static void main(String[] args)
        throws IOException, ParseException, InterruptedException, NotDerivableException {

    CommandLine cmd;/*  w w  w  .j  ava2  s  . c  om*/
    Options opt;
    BaseRepl repl;
    BaseCreActor cre;
    Path sandbox;
    ExecutorService executor;
    TicketSrcActor ticketSrc;
    JsonSummary summary;
    Path summaryPath;
    Log statLog;
    int nthread;
    Path workDir;

    statLog = LogFactory.getLog("statLogger");

    executor = Executors.newCachedThreadPool();
    try {

        opt = getOptions();
        cmd = parse(args, opt);
        config(cmd);

        if (cmd.hasOption('h')) {

            System.out.println("CUNEIFORM - A Functional Workflow Language\nversion " + BaseRepl.LABEL_VERSION
                    + " build " + BaseRepl.LABEL_BUILD);
            new HelpFormatter().printHelp("java -jar cuneiform.jar [OPTION]*", opt);

            return;
        }

        if (cmd.hasOption('r'))
            Invocation.putLibPath(ForeignLambdaExpr.LANGID_R, cmd.getOptionValue('r'));

        if (cmd.hasOption('y'))
            Invocation.putLibPath(ForeignLambdaExpr.LANGID_PYTHON, cmd.getOptionValue('y'));

        if (cmd.hasOption('l'))
            sandbox = Paths.get(cmd.getOptionValue("l"));
        else
            sandbox = Paths.get(System.getProperty("user.home")).resolve(".cuneiform");

        sandbox = sandbox.toAbsolutePath();

        if (cmd.hasOption('c'))
            LocalThread.deleteIfExists(sandbox);

        if (cmd.hasOption('t'))
            nthread = Integer.valueOf(cmd.getOptionValue('t'));
        else
            nthread = Runtime.getRuntime().availableProcessors();

        if (cmd.hasOption('w'))
            workDir = Paths.get(cmd.getOptionValue('w'));
        else
            workDir = Paths.get(System.getProperty("user.dir"));

        workDir = workDir.toAbsolutePath();

        switch (platform) {

        case PLATFORM_LOCAL:

            if (!Files.exists(sandbox))
                Files.createDirectories(sandbox);

            cre = new LocalCreActor(sandbox, workDir, nthread);
            break;

        case PLATFORM_HTCONDOR:

            if (!Files.exists(sandbox))
                Files.createDirectories(sandbox);

            if (cmd.hasOption('m')) { // MAX_TRANSFER SIZE
                String maxTransferSize = cmd.getOptionValue('m');
                try {
                    cre = new CondorCreActor(sandbox, maxTransferSize);
                } catch (Exception e) {
                    System.out.println("INVALID '-m' option value: " + maxTransferSize
                            + "\n\nCUNEIFORM - A Functional Workflow Language\nversion "
                            + BaseRepl.LABEL_VERSION + " build " + BaseRepl.LABEL_BUILD);
                    new HelpFormatter().printHelp("java -jar cuneiform.jar [OPTION]*", opt);

                    return;
                }
            } else {
                cre = new CondorCreActor(sandbox);
            }

            break;

        default:
            throw new RuntimeException("Platform not recognized.");
        }

        executor.submit(cre);
        ticketSrc = new TicketSrcActor(cre);
        executor.submit(ticketSrc);
        executor.shutdown();

        switch (format) {

        case FORMAT_CF:

            if (cmd.hasOption("i"))
                repl = new InteractiveRepl(ticketSrc, statLog);
            else
                repl = new CmdlineRepl(ticketSrc, statLog);
            break;

        case FORMAT_DAX:
            repl = new DaxRepl(ticketSrc, statLog);
            break;

        default:
            throw new RuntimeException("Format not recognized.");
        }

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

            // run in interactive mode
            BaseRepl.run(repl);

            return;
        }

        // run in quiet mode

        if (inputFileVector.length > 0)

            for (Path f : inputFileVector)
                repl.interpret(readFile(f));

        else
            repl.interpret(readStdIn());

        Thread.sleep(3 * Actor.DELAY);
        while (repl.isBusy())
            Thread.sleep(Actor.DELAY);

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

            summary = new JsonSummary(ticketSrc.getRunId(), sandbox, repl.getAns());
            summaryPath = Paths.get(cmd.getOptionValue("s"));
            summaryPath = summaryPath.toAbsolutePath();
            try (BufferedWriter writer = Files.newBufferedWriter(summaryPath, Charset.forName("UTF-8"))) {

                writer.write(summary.toString());
            }

        }

    } finally {
        executor.shutdownNow();
    }

}

From source file:io.anserini.index.IndexGov2.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(/*from   w  ww  .  ja v  a2s .c  o  m*/
            OptionBuilder.withArgName("path").hasArg().withDescription("input data path").create(INPUT_OPTION));
    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("output index path")
            .create(INDEX_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of indexer threads")
            .create(THREADS_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg()
            .withDescription("max number of documents to index (-1 to index everything)")
            .create(DOCLIMIT_OPTION));

    options.addOption(POSITIONS_OPTION, false, "index positions");
    options.addOption(OPTIMIZE_OPTION, false, "merge all index segments");

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();
    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(INPUT_OPTION) || !cmdline.hasOption(INDEX_OPTION)
            || !cmdline.hasOption(THREADS_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(100);
        formatter.printHelp(IndexGov2.class.getCanonicalName(), options);
        System.exit(-1);
    }

    final String dirPath = cmdline.getOptionValue(INDEX_OPTION);
    final String dataDir = cmdline.getOptionValue(INPUT_OPTION);
    final int docCountLimit = cmdline.hasOption(DOCLIMIT_OPTION)
            ? Integer.parseInt(cmdline.getOptionValue(DOCLIMIT_OPTION))
            : -1;
    final int numThreads = Integer.parseInt(cmdline.getOptionValue(THREADS_OPTION));

    final boolean doUpdate = cmdline.hasOption(UPDATE_OPTION);
    final boolean positions = cmdline.hasOption(POSITIONS_OPTION);
    final boolean optimize = cmdline.hasOption(OPTIMIZE_OPTION);

    final Analyzer a = new EnglishAnalyzer();
    final TrecContentSource trecSource = createGov2Source(dataDir);
    final Directory dir = FSDirectory.open(Paths.get(dirPath));

    LOG.info("Index path: " + dirPath);
    LOG.info("Doc limit: " + (docCountLimit == -1 ? "all docs" : "" + docCountLimit));
    LOG.info("Threads: " + numThreads);
    LOG.info("Positions: " + positions);
    LOG.info("Optimize (merge segments): " + optimize);

    final IndexWriterConfig config = new IndexWriterConfig(a);

    if (doUpdate) {
        config.setOpenMode(IndexWriterConfig.OpenMode.APPEND);
    } else {
        config.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
    }

    final IndexWriter writer = new IndexWriter(dir, config);
    Gov2IndexThreads threads = new Gov2IndexThreads(writer, positions, trecSource, numThreads, docCountLimit);
    LOG.info("Indexer: start");

    final long t0 = System.currentTimeMillis();

    threads.start();

    while (!threads.done()) {
        Thread.sleep(100);
    }
    threads.stop();

    final long t1 = System.currentTimeMillis();
    LOG.info("Indexer: indexing done (" + (t1 - t0) / 1000.0 + " sec); total " + writer.maxDoc() + " docs");
    if (!doUpdate && docCountLimit != -1 && writer.maxDoc() != docCountLimit) {
        throw new RuntimeException("w.maxDoc()=" + writer.maxDoc() + " but expected " + docCountLimit);
    }
    if (threads.failed.get()) {
        throw new RuntimeException("exceptions during indexing");
    }

    final long t2;
    t2 = System.currentTimeMillis();

    final Map<String, String> commitData = new HashMap<String, String>();
    commitData.put("userData", "multi");
    writer.setCommitData(commitData);
    writer.commit();
    final long t3 = System.currentTimeMillis();
    LOG.info("Indexer: commit multi (took " + (t3 - t2) / 1000.0 + " sec)");

    if (optimize) {
        LOG.info("Indexer: merging all segments");
        writer.forceMerge(1);
        final long t4 = System.currentTimeMillis();
        LOG.info("Indexer: segments merged (took " + (t4 - t3) / 1000.0 + " sec)");
    }

    LOG.info("Indexer: at close: " + writer.segString());
    final long tCloseStart = System.currentTimeMillis();
    writer.close();
    LOG.info("Indexer: close took " + (System.currentTimeMillis() - tCloseStart) / 1000.0 + " sec");
    dir.close();
    final long tFinal = System.currentTimeMillis();
    LOG.info("Indexer: finished (" + (tFinal - t0) / 1000.0 + " sec)");
    LOG.info("Indexer: net bytes indexed " + threads.getBytesIndexed());
    LOG.info("Indexer: " + (threads.getBytesIndexed() / 1024. / 1024. / 1024. / ((tFinal - t0) / 3600000.))
            + " GB/hour plain text");
}

From source file:com.act.lcms.db.io.LoadTSVIntoDB.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    opts.addOption(Option.builder("t").argName("type")
            .desc("The type of TSV data to read, options are: " + StringUtils.join(TSV_TYPE.values(), ", "))
            .hasArg().required().longOpt("table-type").build());
    opts.addOption(Option.builder("i").argName("path").desc("The TSV file to read").hasArg().required()
            .longOpt("input-file").build());

    // DB connection options.
    opts.addOption(Option.builder().argName("database url")
            .desc("The url to use when connecting to the LCMS db").hasArg().longOpt("db-url").build());
    opts.addOption(Option.builder("u").argName("database user").desc("The LCMS DB user").hasArg()
            .longOpt("db-user").build());
    opts.addOption(Option.builder("p").argName("database password").desc("The LCMS DB password").hasArg()
            .longOpt("db-pass").build());
    opts.addOption(Option.builder("H").argName("database host")
            .desc(String.format("The LCMS DB host (default = %s)", DB.DEFAULT_HOST)).hasArg().longOpt("db-host")
            .build());//from www .java2  s . c om
    opts.addOption(Option.builder("P").argName("database port")
            .desc(String.format("The LCMS DB port (default = %d)", DB.DEFAULT_PORT)).hasArg().longOpt("db-port")
            .build());
    opts.addOption(Option.builder("N").argName("database name")
            .desc(String.format("The LCMS DB name (default = %s)", DB.DEFAULT_DB_NAME)).hasArg()
            .longOpt("db-name").build());

    // Everybody needs a little help from their friends.
    opts.addOption(
            Option.builder("h").argName("help").desc("Prints this help message").longOpt("help").build());

    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        System.err.format("Argument parsing failed: %s\n", e.getMessage());
        HelpFormatter fmt = new HelpFormatter();
        fmt.printHelp(LoadTSVIntoDB.class.getCanonicalName(), opts, true);
        System.exit(1);
    }

    if (cl.hasOption("help")) {
        new HelpFormatter().printHelp(LoadTSVIntoDB.class.getCanonicalName(), opts, true);
        return;
    }

    File inputFile = new File(cl.getOptionValue("input-file"));
    if (!inputFile.exists()) {
        System.err.format("Unable to find input file at %s\n", cl.getOptionValue("input-file"));
        new HelpFormatter().printHelp(LoadTSVIntoDB.class.getCanonicalName(), opts, true);
        System.exit(1);
    }

    TSV_TYPE contentType = null;
    try {
        contentType = TSV_TYPE.valueOf(cl.getOptionValue("table-type"));
    } catch (IllegalArgumentException e) {
        System.err.format("Unrecognized TSV type '%s'\n", cl.getOptionValue("table-type"));
        new HelpFormatter().printHelp(LoadTSVIntoDB.class.getCanonicalName(), opts, true);
        System.exit(1);
    }

    DB db;

    if (cl.hasOption("db-url")) {
        db = new DB().connectToDB(cl.getOptionValue("db-url"));
    } else {
        Integer port = null;
        if (cl.getOptionValue("P") != null) {
            port = Integer.parseInt(cl.getOptionValue("P"));
        }
        db = new DB().connectToDB(cl.getOptionValue("H"), port, cl.getOptionValue("N"), cl.getOptionValue("u"),
                cl.getOptionValue("p"));
    }

    try {
        db.getConn().setAutoCommit(false);

        TSVParser parser = new TSVParser();
        parser.parse(inputFile);

        List<Pair<Integer, DB.OPERATION_PERFORMED>> results = null;
        switch (contentType) {
        case CURATED_CHEMICAL:
            results = CuratedChemical.insertOrUpdateCuratedChemicalsFromTSV(db, parser);
            break;
        case CONSTRUCT:
            results = ConstructEntry.insertOrUpdateCompositionMapEntriesFromTSV(db, parser);
            break;
        case CHEMICAL_OF_INTEREST:
            results = ChemicalOfInterest.insertOrUpdateChemicalOfInterestsFromTSV(db, parser);
            break;
        default:
            throw new RuntimeException(String.format("Unsupported TSV type: %s", contentType));
        }
        if (results != null) {
            for (Pair<Integer, DB.OPERATION_PERFORMED> r : results) {
                System.out.format("%d: %s\n", r.getLeft(), r.getRight());
            }
        }
        // If we didn't encounter an exception, commit the transaction.
        db.getConn().commit();
    } catch (Exception e) {
        System.err.format("Caught exception when trying to load plate composition, rolling back. %s\n",
                e.getMessage());
        db.getConn().rollback();
        throw (e);
    } finally {
        db.getConn().close();
    }
}

From source file:executables.Align.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws IOException {
    Options options = new Options()
            .addOption(OptionBuilder.withArgName("f1").withDescription("Fasta file 1").hasArg().create("f1"))
            .addOption(OptionBuilder.withArgName("f2").withDescription("Fasta file 2").hasArg().create("f2"))
            .addOption(OptionBuilder.withArgName("s1").withDescription("sequence 1").hasArg().create("s1"))
            .addOption(OptionBuilder.withArgName("s2").withDescription("sequence 2").hasArg().create("s2"))
            .addOption(OptionBuilder.withArgName("gap-linear").withDescription("Linear gap cost").hasArg()
                    .create("gl"))
            .addOption(OptionBuilder.withArgName("gap-open").withDescription("Affine gap open cost").hasArg()
                    .create("go"))
            .addOption(OptionBuilder.withArgName("gap-extend").withDescription("Affine gap extend cost")
                    .hasArg().create("ge"))
            .addOption(OptionBuilder.withArgName("gap-function").withDescription("Gap function file").hasArg()
                    .create("gf"))
            .addOption(/* ww  w  .  ja v a 2  s. c  o  m*/
                    OptionBuilder.withArgName("gapless").withDescription("Gapless alignment").create("gapless"))
            .addOption(OptionBuilder.withArgName("mode")
                    .withDescription("Alignment mode: global,local,freeshift (Default: freeshift)").hasArg()
                    .create('m'))
            .addOption(OptionBuilder.withArgName("match").withDescription("Match score").hasArg().create("ma"))
            .addOption(OptionBuilder.withArgName("mismatch").withDescription("Mismatch score").hasArg()
                    .create("mi"))
            .addOption(OptionBuilder.withDescription("Do not append unaligned flanking sequences")
                    .create("noflank"))
            .addOption(OptionBuilder.withArgName("check").withDescription("Calculate checkscore").create('c'))
            .addOption(OptionBuilder.withArgName("format").withDescription(
                    "Output format, see String.format, parameters are: id1,id2,score,alignment (alignment only, if -f is specified); (default: '%s %s %.4f' w/o -f and '%s %s %.4f\n%s' w/ -f)")
                    .hasArg().create("format"))
            .addOption(OptionBuilder.withArgName("matrix")
                    .withDescription("Output dynamic programming matrix as well").create("matrix"))
            .addOption(OptionBuilder.withArgName("quasar-format")
                    .withDescription("Scoring matrix in quasar format").hasArg().create('q'))
            .addOption(
                    OptionBuilder.withArgName("pairs").withDescription("Pairs file").hasArg().create("pairs"))
            .addOption(OptionBuilder.withArgName("output").withDescription("Output").hasArg().create('o'))
            .addOption(OptionBuilder.withArgName("seqlib").withDescription("Seqlib file").hasArg()
                    .create("seqlib"))
            .addOption(OptionBuilder.withArgName("full").withDescription("Full output").create('f'));

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

        LongScoring<CharSequence> scoring = createScoring(cmd);
        AlignmentMode mode = createMode(cmd);
        if (mode == null)
            throw new ParseException("Mode unknown: " + cmd.getOptionValue('m'));

        Iterator<MutablePair<String, String>> idIterator = createSequences(scoring, cmd);

        GapCostFunction gap = createGapFunction(cmd);
        String format = getFormat(cmd);

        LongAligner<CharSequence> aligner;
        if (gap instanceof AffineGapCostFunction)
            aligner = new LongAligner<CharSequence>(scoring, ((AffineGapCostFunction) gap).getGapOpen(),
                    ((AffineGapCostFunction) gap).getGapExtend(), mode);
        else if (gap instanceof LinearGapCostFunction)
            aligner = new LongAligner<CharSequence>(scoring, ((LinearGapCostFunction) gap).getGap(), mode);
        else if (gap instanceof InfiniteGapCostFunction)
            aligner = new LongAligner<CharSequence>(scoring, mode);
        else
            throw new RuntimeException("Gap cost function " + gap.toString() + " currently not supported!");

        SimpleAlignmentFormatter formatter = cmd.hasOption('f')
                ? new SimpleAlignmentFormatter().setAppendUnaligned(!cmd.hasOption("noflank"))
                : null;

        CheckScore checkscore = cmd.hasOption('c') ? new CheckScore() : null;
        Alignment alignment = checkscore != null || formatter != null ? new Alignment() : null;

        float score;
        String ali;
        LineOrientedFile out = new LineOrientedFile(
                cmd.hasOption('o') ? cmd.getOptionValue('o') : LineOrientedFile.STDOUT);
        Writer wr = out.startWriting();

        while (idIterator.hasNext()) {
            MutablePair<String, String> ids = idIterator.next();

            score = alignment == null ? aligner.alignCache(ids.Item1, ids.Item2)
                    : aligner.alignCache(ids.Item1, ids.Item2, alignment);
            ali = formatter != null ? formatter.format(alignment, scoring, gap, mode,
                    scoring.getCachedSubject(ids.Item1), scoring.getCachedSubject(ids.Item2)) : "";
            out.writeLine(String.format(Locale.US, format, ids.Item1, ids.Item2, score, ali));

            if (cmd.hasOption("matrix")) {
                aligner.writeMatrix(wr,
                        aligner.getScoring().getCachedSubject(ids.Item1).toString().toCharArray(),
                        aligner.getScoring().getCachedSubject(ids.Item2).toString().toCharArray());
            }

            if (checkscore != null)
                checkscore.checkScore(aligner, scoring.getCachedSubject(ids.Item1).length(),
                        scoring.getCachedSubject(ids.Item2).length(), alignment, score);

        }

        out.finishWriting();

    } catch (ParseException e) {
        e.printStackTrace();
        HelpFormatter f = new HelpFormatter();
        f.printHelp("Align", options);
    }
}

From source file:AmazonKinesisGet.java

public static void main(String[] args) throws Exception {
    init();//  ww w .  j ava2 s  .c  o m

    final String myStreamName = "philsteststream";
    final Integer myStreamSize = 1;

    // list all of my streams
    ListStreamsRequest listStreamsRequest = new ListStreamsRequest();
    listStreamsRequest.setLimit(10);
    ListStreamsResult listStreamsResult = kinesisClient.listStreams(listStreamsRequest);
    List<String> streamNames = listStreamsResult.getStreamNames();
    while (listStreamsResult.isHasMoreStreams()) {
        if (streamNames.size() > 0) {
            listStreamsRequest.setExclusiveStartStreamName(streamNames.get(streamNames.size() - 1));
        }

        listStreamsResult = kinesisClient.listStreams(listStreamsRequest);

        streamNames.addAll(listStreamsResult.getStreamNames());

    }
    LOG.info("Printing my list of streams : ");

    // print all of my streams.
    if (!streamNames.isEmpty()) {
        System.out.println("List of my streams: ");
    }
    for (int i = 0; i < streamNames.size(); i++) {
        System.out.println(streamNames.get(i));
    }

    //System.out.println(streamNames.get(0));
    String myownstream = streamNames.get(0);

    // Retrieve the Shards from a Stream
    DescribeStreamRequest describeStreamRequest = new DescribeStreamRequest();
    describeStreamRequest.setStreamName(myownstream);
    DescribeStreamResult describeStreamResult;
    List<Shard> shards = new ArrayList<>();
    String lastShardId = null;

    do {
        describeStreamRequest.setExclusiveStartShardId(lastShardId);
        describeStreamResult = kinesisClient.describeStream(describeStreamRequest);
        shards.addAll(describeStreamResult.getStreamDescription().getShards());
        if (shards.size() > 0) {
            lastShardId = shards.get(shards.size() - 1).getShardId();
        }
    } while (describeStreamResult.getStreamDescription().getHasMoreShards());

    // Get Data from the Shards in a Stream
    // Hard-coded to use only 1 shard
    String shardIterator;
    GetShardIteratorRequest getShardIteratorRequest = new GetShardIteratorRequest();
    getShardIteratorRequest.setStreamName(myownstream);
    //get(0) shows hardcoded to 1 stream
    getShardIteratorRequest.setShardId(shards.get(0).getShardId());
    // using TRIM_HORIZON but could use alternatives
    getShardIteratorRequest.setShardIteratorType("TRIM_HORIZON");

    GetShardIteratorResult getShardIteratorResult = kinesisClient.getShardIterator(getShardIteratorRequest);
    shardIterator = getShardIteratorResult.getShardIterator();

    // Continuously read data records from shard.
    List<Record> records;

    while (true) {
        // Create new GetRecordsRequest with existing shardIterator.
        // Set maximum records to return to 1000.

        GetRecordsRequest getRecordsRequest = new GetRecordsRequest();
        getRecordsRequest.setShardIterator(shardIterator);
        getRecordsRequest.setLimit(1000);

        GetRecordsResult result = kinesisClient.getRecords(getRecordsRequest);

        // Put result into record list. Result may be empty.
        records = result.getRecords();

        // Print records
        for (Record record : records) {
            ByteBuffer byteBuffer = record.getData();
            System.out.println(String.format("Seq No: %s - %s", record.getSequenceNumber(),
                    new String(byteBuffer.array())));
        }

        try {
            Thread.sleep(1000);
        } catch (InterruptedException exception) {
            throw new RuntimeException(exception);
        }

        shardIterator = result.getNextShardIterator();
    }

}

From source file:raymond.mockftpserver.S3CachedFtpServer.java

public static void main(String[] args) throws Exception {
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

    String identityPath = (String) ctx.getBean("identityPath");
    String charset = (String) ctx.getBean("charset");
    String keyBase = (String) ctx.getBean("keyBase");
    // String host = (String) ctx.getBean("s3Host");
    String bucket = (String) ctx.getBean("s3Bucket");
    String chave = (String) ctx.getBean("chave");
    Region region = (Region) ctx.getBean("s3Region");

    ctx.close();// www  .  j  a va 2  s .  c o  m

    // check if user wants to create credentials
    File _accessFile = new File(identityPath);

    S3CachedFtpServer s3FtpServer = new S3CachedFtpServer();
    s3FtpServer.init(_accessFile, chave, charset, keyBase, bucket, region);

    if (!_accessFile.exists() && args.length != 2) {
        throw new RuntimeException("sem credenciais");
    } else if (!_accessFile.exists()) {
        s3FtpServer.writeKeyFile(args[0], args[1].toCharArray());
    }

    s3FtpServer.go();
}

From source file:eu.itesla_project.offline.mpi.Master.java

public static void main(String[] args) throws Exception {
    try {/* w  w  w  .ja  va 2s .  c o  m*/
        CommandLineParser parser = new GnuParser();
        CommandLine line = parser.parse(OPTIONS, args);

        Mode mode = Mode.valueOf(line.getOptionValue("mode"));
        String simulationDbName = line.hasOption("simulation-db-name")
                ? line.getOptionValue("simulation-db-name")
                : OfflineConfig.DEFAULT_SIMULATION_DB_NAME;
        String rulesDbName = line.hasOption("rules-db-name") ? line.getOptionValue("rules-db-name")
                : OfflineConfig.DEFAULT_RULES_DB_NAME;
        String metricsDbName = line.hasOption("metrics-db-name") ? line.getOptionValue("metrics-db-name")
                : OfflineConfig.DEFAULT_METRICS_DB_NAME;
        Path tmpDir = Paths.get(line.getOptionValue("tmp-dir"));
        Class<?> statisticsFactoryClass = Class.forName(line.getOptionValue("statistics-factory-class"));
        Path statisticsDbDir = Paths.get(line.getOptionValue("statistics-db-dir"));
        String statisticsDbName = line.getOptionValue("statistics-db-name");
        int coresPerRank = Integer.parseInt(line.getOptionValue("cores"));
        Path stdOutArchive = line.hasOption("stdout-archive") ? Paths.get(line.getOptionValue("stdout-archive"))
                : null;
        String workflowId = line.hasOption("workflow") ? line.getOptionValue("workflow") : null;

        MpiExecutorContext mpiExecutorContext = new MultiStateNetworkAwareMpiExecutorContext();
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
        ExecutorService offlineExecutorService = MultiStateNetworkAwareExecutors
                .newSizeLimitedThreadPool("OFFLINE_POOL", 100);
        try {
            MpiStatisticsFactory statisticsFactory = statisticsFactoryClass
                    .asSubclass(MpiStatisticsFactory.class).newInstance();
            try (MpiStatistics statistics = statisticsFactory.create(statisticsDbDir, statisticsDbName)) {
                try (ComputationManager computationManager = new MpiComputationManager(tmpDir, statistics,
                        mpiExecutorContext, coresPerRank, false, stdOutArchive)) {
                    OfflineConfig config = OfflineConfig.load();
                    try (LocalOfflineApplication application = new LocalOfflineApplication(config,
                            computationManager, simulationDbName, rulesDbName, metricsDbName,
                            scheduledExecutorService, offlineExecutorService)) {
                        switch (mode) {
                        case ui:
                            application.await();
                            break;

                        case simulations: {
                            if (workflowId == null) {
                                workflowId = application.createWorkflow(null,
                                        OfflineWorkflowCreationParameters.load());
                            }
                            application.startWorkflowAndWait(workflowId, OfflineWorkflowStartParameters.load());
                        }
                            break;

                        case rules: {
                            if (workflowId == null) {
                                throw new RuntimeException("Workflow '" + workflowId + "' not found");
                            }
                            application.computeSecurityRulesAndWait(workflowId);
                        }
                            break;

                        default:
                            throw new IllegalArgumentException("Invalid mode " + mode);
                        }
                    }
                }
            }
        } finally {
            mpiExecutorContext.shutdown();
            offlineExecutorService.shutdown();
            scheduledExecutorService.shutdown();
            offlineExecutorService.awaitTermination(15, TimeUnit.MINUTES);
            scheduledExecutorService.awaitTermination(15, TimeUnit.MINUTES);
        }
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("master", OPTIONS, true);
        System.exit(-1);
    } catch (Throwable t) {
        LOGGER.error(t.toString(), t);
        System.exit(-1);
    }
}

From source file:de.forsthaus.backend.util.IpLocator.java

/**
 * For unit testing purposes only/*w ww . j  a  va2s  .  co  m*/
 * 
 * @param args
 */
public static void main(String args[]) {
    System.err.println("Start");
    try {

        final IpLocator ipl = IpLocator.locate("12.215.42.19");
        // System.out.println("City=" + ipl.getCity());
        // System.out.println("Country=" + ipl.getCountry());
        // System.out.println("CountryCode=" + ipl.getCountryCode());
        // System.out.println("Latitude=" + ipl.getLatitude());
        // System.out.println("Longitude=" + ipl.getLongitude());
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}