Example usage for java.lang Exception getMessage

List of usage examples for java.lang Exception getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:edu.msu.cme.rdp.graph.sandbox.KmerStartsFromKnown.java

public static void main(String[] args) throws Exception {
    final KmerStartsWriter out;
    final boolean translQuery;
    final int wordSize;
    final int translTable;

    try {//from   w w  w .ja  v a  2s  .c  om
        CommandLine cmdLine = new PosixParser().parse(options, args);
        args = cmdLine.getArgs();

        if (args.length < 2) {
            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("transl-table")) {
            translTable = Integer.valueOf(cmdLine.getOptionValue("transl-table"));
        } else {
            translTable = 11;
        }

        translQuery = cmdLine.hasOption("transl-kmer");
        wordSize = Integer.valueOf(args[0]);

    } catch (Exception e) {
        new HelpFormatter().printHelp("KmerStartsFromKnown <word_size> [name=]<ref_file> ...", options);
        System.err.println(e.getMessage());
        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();

    /*
     * if (args.length == 4) { maxThreads = Integer.valueOf(args[3]); } else
     * {
     */

    //}

    System.err.println("Starting kmer mapping at " + new Date());
    System.err.println("*  References:              " + Arrays.asList(args));
    System.err.println("*  Kmer length:             " + wordSize);

    for (int index = 1; 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 (SeqUtils.guessSequenceType(refFile) != SequenceType.Nucleotide) {
            throw new Exception("Reference file " + refFile + " contains " + SeqUtils.guessFileFormat(refFile)
                    + " sequences but expected nucleotide sequences");
        }

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

        while ((seq = seqReader.readNextSequence()) != null) {
            if (seq.getSeqName().startsWith("#")) {
                continue;
            }
            ModelPositionKmerGenerator kmers = new ModelPositionKmerGenerator(seq.getSeqString(), wordSize,
                    SequenceType.Nucleotide);

            for (char[] charmer : kmers) {
                int pos = kmers.getModelPosition() - 1;
                if (translQuery) {
                    if (pos % 3 != 0) {
                        continue;
                    } else {
                        pos /= 3;
                    }
                }

                String kmer = new String(charmer);

                out.write(new KmerStart(refName, seq.getSeqName(), seq.getSeqName(), kmer, 1, pos, translQuery,
                        (translQuery ? ProteinUtils.getInstance().translateToProtein(kmer, true, translTable)
                                : null)));

            }
        }
        seqReader.close();
    }
    out.close();
}

From source file:jfutbol.com.jfutbol.GcmSender.java

public static void main(String[] args) {
    log.info("GCM - Sender running");
    do {//w  w w.  j  av  a  2 s. co m

        Connection conn = null;
        Connection conn2 = null;
        Statement stmt = null;
        Statement stmt2 = null;

        try {
            // STEP 2: Register JDBC driver
            Class.forName(JDBC_DRIVER);
            // STEP 3: Open a connection
            // System.out.println("Connecting to database...");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
            conn2 = DriverManager.getConnection(DB_URL, USER, PASS);
            // STEP 4: Execute a query
            // System.out.println("Creating statement...");
            stmt = conn.createStatement();
            String sql;
            sql = "SELECT userId FROM notifications WHERE sentByGCM=0 GROUP BY userId";
            ResultSet rs = stmt.executeQuery(sql);
            // STEP 5: Extract data from result set
            while (rs.next()) {
                log.info("Notification found");
                int userId = rs.getInt("userId");

                stmt2 = conn2.createStatement();
                String sql2;
                sql2 = "SELECT COUNT(id) notificationCounter FROM notifications WHERE status=0 AND userId="
                        + userId;
                ResultSet rs2 = stmt2.executeQuery(sql2);
                int notificationCounter = rs2.getInt("notificationCounter");
                rs2.close();
                stmt2.close();
                // Retrieve by column name

                // Display values
                // System.out.print("userId: " + userId);
                // System.out.print(", notificationCounter: " +
                // notificationCounter);
                SendNotification(userId, notificationCounter);
            }
            // STEP 6: Clean-up environment
            rs.close();
            stmt.close();
            conn.close();
            conn2.close();
        } catch (SQLException se) {
            // Handle errors for JDBC
            log.error(se.getMessage());
            se.printStackTrace();
        } catch (Exception e) {
            // Handle errors for Class.forName
            log.error(e.getMessage());
            e.printStackTrace();
        } finally {
            // finally block used to close resources
            try {
                if (stmt != null)
                    stmt.close();
            } catch (SQLException se2) {
                log.error(se2.getMessage());
            } // nothing we can do
            try {
                if (conn != null)
                    conn.close();
            } catch (SQLException se) {
                log.error(se.getMessage());
                se.printStackTrace();
            } // end finally try
        } // end try
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
    } while (1 != 0);
}

From source file:chibi.gemmaanalysis.GeneExpressionWriterCLI.java

public static void main(String[] args) {
    GeneExpressionWriterCLI cli = new GeneExpressionWriterCLI();
    Exception e = cli.doWork(args);
    if (e != null)
        log.error(e.getMessage());
}

From source file:apps.classification.LearnSVMPerf.java

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

    Options options = new Options();

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

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

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

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

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

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

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

    SvmPerfLearnerCustomizer classificationLearnerCustomizer = null;

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

        remainingArgs = line.getArgs();

        classificationLearnerCustomizer = new SvmPerfLearnerCustomizer(remainingArgs[0]);

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

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

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

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

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

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

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

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

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

    String indexFile = remainingArgs[1];

    File file = new File(indexFile);

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

    // LEARNING
    SvmPerfLearner classificationLearner = new SvmPerfLearner();

    classificationLearner.setRuntimeCustomizer(classificationLearnerCustomizer);

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

    IClassifier classifier = classificationLearner.build(training);

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

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

From source file:com.aestel.chemistry.openEye.fp.apps.SDFFPNNFinder.java

public static void main(String... args) throws IOException {
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;//from w  ww  . j  a  v a 2 s.  co  m
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp();
    }

    args = cmd.getArgs();
    if (args.length > 0) {
        exitWithHelp("Unknown param: " + args[0]);
    }

    if (cmd.hasOption("d")) {
        System.err.println("Start debugger and press return:");
        new BufferedReader(new InputStreamReader(System.in)).readLine();
    }

    int nCpu = 1;
    int maxNeighbors = 1;
    double minSim = 0D;

    String fpTag = cmd.getOptionValue("fpTag");
    String idTag = cmd.getOptionValue("idTag");
    boolean doMaxTanimoto = cmd.hasOption("maxTanimoto");
    boolean printAll = cmd.hasOption("printAll");

    String d = cmd.getOptionValue("nCpu");
    if (d != null)
        nCpu = Integer.parseInt(d);

    d = cmd.getOptionValue("maxNeighbors");
    if (d != null)
        maxNeighbors = Integer.parseInt(d);

    d = cmd.getOptionValue("minSimilarity");
    if (d != null)
        minSim = Double.parseDouble(d);

    String countAboveSimilarityStr = cmd.getOptionValue("countSimilarAbove");

    String inFile = cmd.getOptionValue("in");
    String outFile = cmd.getOptionValue("out");
    String refFile = cmd.getOptionValue("ref");

    String tabOutput = cmd.getOptionValue("tabOutput");
    boolean outputDuplicates = cmd.hasOption("outputDuplicates");

    if (outputDuplicates && tabOutput != null)
        exitWithHelp("-outputDuplicates will not work with tabOutput");

    if (outputDuplicates && refFile == null)
        exitWithHelp("-outputDuplicates requires -ref ");

    if ("tab".equalsIgnoreCase(tabOutput) && refFile != null)
        exitWithHelp("-tabOutput tab: does not work with reference file");

    if ("tab".equalsIgnoreCase(tabOutput) && maxNeighbors == 1)
        exitWithHelp("-tabOutput tab: does not make sense with -maxNeighbors = 1");

    if (cmd.hasOption("countSimilarAbove") && tabOutput != null)
        exitWithHelp("-countSimilarAbove not supported for tab or vTab output");

    if (printAll && !(maxNeighbors > 1 || minSim > 0))
        exitWithHelp("printAll only supported if: maxNeighbors > 1 or minSim > 0");

    if (printAll && tabOutput != null)
        System.err.println("WARNING: printAll ignored tor tab output!\n");

    SimComparatorFactory<OEMolBase, FPComparator, FPComparator> compFact = new FPComparatorFact(doMaxTanimoto,
            fpTag);

    if (refFile == null) {
        perfromMatrixNNSearch(inFile, outFile, tabOutput, compFact, minSim, maxNeighbors, idTag, nCpu,
                countAboveSimilarityStr, printAll);

    } else {
        performReferenceSearch(inFile, refFile, outFile, tabOutput, compFact, minSim, maxNeighbors, idTag, nCpu,
                countAboveSimilarityStr, outputDuplicates, printAll);
    }

}

From source file:cspro2sql.Main.java

public static void main(String[] args) {
    CsPro2SqlOptions opts = getCommandLineOptions(args);
    boolean error = false;
    List<Dictionary> dictionaries;
    try {/* w  w w .  j  a v a2s .  co  m*/
        dictionaries = DictionaryReader.parseDictionaries(opts.schema, opts.dictionary, opts.tablePrefix);
    } catch (Exception e) {
        opts.ps.close();
        opts.printHelp(e.getMessage());
        System.exit(1);
        return;
    }

    if (opts.schemaEngine) {
        error = !SchemaEngine.execute(dictionaries, opts.foreignKeys, opts.ps);
    } else if (opts.loaderEngine) {
        if (opts.delay == null) {
            error = !LoaderEngine.execute(dictionaries, opts.prop, opts.allRecords, opts.checkConstraints,
                    opts.checkOnly, opts.force, opts.recovery, opts.ps);
        } else {
            while (true) {
                try {
                    LoaderEngine.execute(dictionaries, opts.prop, opts.allRecords, opts.checkConstraints,
                            opts.checkOnly, opts.force, opts.recovery, opts.ps);
                } catch (Exception ex) {
                    System.err.println(ex.getMessage());
                }
                try {
                    Thread.sleep(opts.delay);
                } catch (Exception ex) {
                    System.err.println(ex.getMessage());
                }
            }
        }
    } else if (opts.monitorEngine) {
        error = !MonitorEngine.execute(dictionaries, opts.ps);
    } else if (opts.updateEngine) {
        error = !UpdateEngine.execute(opts.prop);
    } else if (opts.statusEngine) {
        error = !StatusEngine.execute(dictionaries, opts.prop);
    } else if (opts.loadAndUpdate) {
        while (true) {
            try {
                LoaderEngine.execute(dictionaries, opts.prop, opts.allRecords, opts.checkConstraints,
                        opts.checkOnly, opts.force, opts.recovery, opts.ps);
                UpdateEngine.execute(opts.prop);
            } catch (Exception ex) {
                System.err.println(ex.getMessage());
            }
            try {
                Thread.sleep(opts.delay);
            } catch (Exception ex) {
                System.err.println(ex.getMessage());
            }
        }
    }

    if (opts.ps != null) {
        opts.ps.close();
    }

    if (error) {
        System.exit(1);
    }
}

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;//  w  w w.  ja  va 2s.c  o  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:edu.msu.cme.rdp.multicompare.Reprocess.java

/**
 * This class reprocesses the classification results (allrank output) and print out hierarchy output file, based on the confidence cutoff;
 * and print out only the detail classification results with assignment at certain rank with confidence above the cutoff or/and matching a given taxon.
 * @param args/*  ww w . j  a v  a 2 s. co  m*/
 * @throws Exception 
 */
public static void main(String[] args) throws Exception {

    PrintWriter assign_out = new PrintWriter(new NullWriter());
    float conf = 0.8f;
    PrintStream heir_out = null;
    String hier_out_filename = null;
    ClassificationResultFormatter.FORMAT format = ClassificationResultFormatter.FORMAT.allRank;
    String rank = null;
    String taxonFilterFile = null;
    String train_propfile = null;
    String gene = null;
    List<MCSample> samples = new ArrayList();

    try {
        CommandLine line = new PosixParser().parse(options, args);
        if (line.hasOption(CmdOptions.HIER_OUTFILE_SHORT_OPT)) {
            hier_out_filename = line.getOptionValue(CmdOptions.HIER_OUTFILE_SHORT_OPT);
            heir_out = new PrintStream(hier_out_filename);
        } else {
            throw new Exception(
                    "It make sense to provide output filename for " + CmdOptions.HIER_OUTFILE_LONG_OPT);
        }
        if (line.hasOption(CmdOptions.OUTFILE_SHORT_OPT)) {
            assign_out = new PrintWriter(line.getOptionValue(CmdOptions.OUTFILE_SHORT_OPT));
        }

        if (line.hasOption(CmdOptions.RANK_SHORT_OPT)) {
            rank = line.getOptionValue(CmdOptions.RANK_SHORT_OPT);
        }
        if (line.hasOption(CmdOptions.TAXON_SHORT_OPT)) {
            taxonFilterFile = line.getOptionValue(CmdOptions.TAXON_SHORT_OPT);
        }

        if (line.hasOption(CmdOptions.BOOTSTRAP_SHORT_OPT)) {
            conf = Float.parseFloat(line.getOptionValue(CmdOptions.BOOTSTRAP_SHORT_OPT));
            if (conf < 0 || conf > 1) {
                throw new IllegalArgumentException("Confidence must be in the range [0,1]");
            }
        }
        if (line.hasOption(CmdOptions.FORMAT_SHORT_OPT)) {
            String f = line.getOptionValue(CmdOptions.FORMAT_SHORT_OPT);
            if (f.equalsIgnoreCase("allrank")) {
                format = ClassificationResultFormatter.FORMAT.allRank;
            } else if (f.equalsIgnoreCase("fixrank")) {
                format = ClassificationResultFormatter.FORMAT.fixRank;
            } else if (f.equalsIgnoreCase("db")) {
                format = ClassificationResultFormatter.FORMAT.dbformat;
            } else if (f.equalsIgnoreCase("filterbyconf")) {
                format = ClassificationResultFormatter.FORMAT.filterbyconf;
            } else {
                throw new IllegalArgumentException(
                        "Not valid output format, only allrank, fixrank, filterbyconf and db allowed");
            }
        }
        if (line.hasOption(CmdOptions.TRAINPROPFILE_SHORT_OPT)) {
            if (gene != null) {
                throw new IllegalArgumentException(
                        "Already specified the gene from the default location. Can not specify train_propfile");
            } else {
                train_propfile = line.getOptionValue(CmdOptions.TRAINPROPFILE_SHORT_OPT);
            }
        }
        if (line.hasOption(CmdOptions.GENE_SHORT_OPT)) {
            if (train_propfile != null) {
                throw new IllegalArgumentException(
                        "Already specified train_propfile. Can not specify gene any more");
            }
            gene = line.getOptionValue(CmdOptions.GENE_SHORT_OPT).toLowerCase();

            if (!gene.equals(ClassifierFactory.RRNA_16S_GENE) && !gene.equals(ClassifierFactory.FUNGALLSU_GENE)
                    && !gene.equals(ClassifierFactory.FUNGALITS_warcup_GENE)
                    && !gene.equals(ClassifierFactory.FUNGALITS_unite_GENE)) {
                throw new IllegalArgumentException(gene + " is NOT valid, only allows "
                        + ClassifierFactory.RRNA_16S_GENE + ", " + ClassifierFactory.FUNGALLSU_GENE + ", "
                        + ClassifierFactory.FUNGALITS_warcup_GENE + " and "
                        + ClassifierFactory.FUNGALITS_unite_GENE);
            }
        }
        args = line.getArgs();
        if (args.length < 1) {
            throw new Exception("Incorrect number of command line arguments");
        }

        for (String arg : args) {
            String[] inFileNames = arg.split(",");
            String inputFile = inFileNames[0];
            File idmappingFile = null;

            if (inFileNames.length == 2) {
                idmappingFile = new File(inFileNames[1]);
                if (!idmappingFile.exists()) {
                    System.err.println("Failed to find input file \"" + inFileNames[1] + "\"");
                    return;
                }
            }

            MCSample nextSample = new MCSampleResult(inputFile, idmappingFile);
            samples.add(nextSample);

        }
    } catch (Exception e) {
        System.out.println("Command Error: " + e.getMessage());
        new HelpFormatter().printHelp(120,
                "Reprocess [options] <Classification_allrank_result>[,idmappingfile] ...", "", options, "");
        return;
    }

    if (train_propfile == null && gene == null) {
        gene = ClassifierFactory.RRNA_16S_GENE;
    }

    HashSet<String> taxonFilter = null;
    if (taxonFilterFile != null) {
        taxonFilter = readTaxonFilterFile(taxonFilterFile);
    }

    MultiClassifier multiClassifier = new MultiClassifier(train_propfile, gene);
    DefaultPrintVisitor printVisitor = new DefaultPrintVisitor(heir_out, samples);
    MultiClassifierResult result = multiClassifier.multiClassificationParser(samples, conf, assign_out, format,
            rank, taxonFilter);

    result.getRoot().topDownVisit(printVisitor);

    assign_out.close();
    heir_out.close();
    if (multiClassifier.hasCopyNumber()) {
        // print copy number corrected counts
        File cn_corrected_s = new File(new File(hier_out_filename).getParentFile(),
                "cncorrected_" + hier_out_filename);
        PrintStream cn_corrected_hier_out = new PrintStream(cn_corrected_s);
        printVisitor = new DefaultPrintVisitor(cn_corrected_hier_out, samples, true);
        result.getRoot().topDownVisit(printVisitor);
        cn_corrected_hier_out.close();
    }

}

From source file:edu.msu.cme.rdp.kmer.KmerSearch.java

public static void main(String[] args) throws IOException {
    KmerTrie kmerTrie = null;// ww  w  .  j  av  a2  s .  com
    SeqReader queryReader = null;
    SequenceType querySeqType = SequenceType.Unknown;
    FastaWriter out = null;
    boolean exhaustive = true;
    boolean translQuery = false;
    int wordSize = -1;
    int translTable = 11;

    try {
        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 FastaWriter(cmdLine.getOptionValue("out"));
        } else {
            out = new FastaWriter(System.out);
        }

        if (cmdLine.hasOption("correct")) {
            exhaustive = false;
        } else {
            exhaustive = true;
        }

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

        File trainingFile = new File(args[0]);
        wordSize = Integer.valueOf(args[1]);
        File queryFile = new File(args[2]);

        querySeqType = SeqUtils.guessSequenceType(queryFile);
        queryReader = new SequenceReader(new File(args[2]));

        kmerTrie = KmerTrie.buildTrie(new SequenceReader(trainingFile), wordSize);

        if (querySeqType == SequenceType.Protein && kmerTrie.getTreeSeqType() == SequenceType.Nucleotide) {
            throw new Exception("Trie is made of nucleotide sequences but the query sequences are protein");
        }

        if (querySeqType == SequenceType.Nucleotide && kmerTrie.getTreeSeqType() == SequenceType.Protein) {
            translQuery = true;
            System.err.println(
                    "Query sequences are nucleotide but trie is in protein space, query sequences will be translated");
        }

        if (querySeqType == SequenceType.Protein && exhaustive) {
            System.err.println("Cannot do an exaustive search with protein sequences, disabling");
            exhaustive = false;
        }

    } catch (Exception e) {
        new HelpFormatter().printHelp("KmerSearch <ref_file> <word_size> <query_file>", options);
        System.err.println(e.getMessage());
        System.exit(1);
    }

    long startTime = System.currentTimeMillis();
    long seqCount = 0, passedCount = 0;

    Sequence querySeq;

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

        List<Sequence> testSequences;

        if (!exhaustive) {
            if (translQuery) {
                testSequences = Arrays.asList(new Sequence(querySeq.getSeqName(), "", ProteinUtils.getInstance()
                        .translateToProtein(querySeq.getSeqString(), true, translTable)));
            } else {
                testSequences = Arrays.asList(querySeq);
            }
        } else {
            if (translQuery) {
                testSequences = ProteinUtils.getInstance().allTranslate(querySeq);
            } else {
                testSequences = Arrays.asList(querySeq, new Sequence(querySeq.getSeqName(), "",
                        IUBUtilities.reverseComplement(querySeq.getSeqString())));
            }
        }

        boolean passed = false;
        for (Sequence seq : testSequences) {
            for (char[] kmer : KmerGenerator.getKmers(seq.getSeqString(), wordSize)) {
                if (kmerTrie.contains(kmer) != null) {
                    passed = true;
                    break;
                }
            }

            if (passed) {
                out.writeSeq(seq);
                passedCount++;
                break;
            }
        }
    }
    System.err.println("Processed: " + seqCount);
    System.err.println("Passed: " + passedCount);
    System.err.println("Failed: " + (seqCount - passedCount));
    System.err.println("Time: " + (System.currentTimeMillis() - startTime) + " ms");
}

From source file:com.genentech.retrival.SDFExport.SDFSDFExporter.java

public static void main(String[] args) throws ParseException, JDOMException, IOException { // create command line Options object
    Options options = new Options();
    Option opt = new Option("sqlFile", true, "sql-xml file");
    opt.setRequired(false);//from w  w  w.  ja v a 2 s.co m
    options.addOption(opt);

    opt = new Option("sqlName", true, "name of SQL element in xml file, Default sql.xml in 'sdfExport' config");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("selectStatement", true, "select statement to execute");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("paramTypes", true,
            "'|' separated list of parameter types to pass tostatment int,float,string,date");
    opt.setRequired(false);
    options.addOption(opt);

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

    opt = new Option("i", "in", true,
            "input file, oe or .tab each record executes the query once. Use '.tab' to read from stdin");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("queryTags", true, "'|' separetaed list of tags whose values is passt to the sql.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option("newLineReplacement", true,
            "If given newlines in fields will be replaced by this string.");
    options.addOption(opt);

    opt = new Option("filterIfNoRecords", false,
            "If no rows are returned by the query that record is filtered out.");
    options.addOption(opt);

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

    String outFile = cmd.getOptionValue("o");
    String inFile = cmd.getOptionValue("i");
    String sqlFile = cmd.getOptionValue("sqlFile");
    String sqlName = cmd.getOptionValue("sqlName");
    String selStr = cmd.getOptionValue("selectStatement");
    String pTypes = cmd.getOptionValue("paramTypes");
    String newLineReplacement = cmd.getOptionValue("newLineReplacement");
    boolean printIfNoRecord = !cmd.hasOption("filterIfNoRecords");
    String[] tagStr = cmd.getOptionValue("queryTags").trim().split("\\|");

    try {
        SDFSDFExporter exporter = null;
        if ((sqlFile != null && sqlFile.length() > 0) || (sqlName != null && sqlName.length() > 0)) {
            if ((selStr != null && selStr.length() > 0) || (pTypes != null && pTypes.length() > 0)) {
                System.err.println("sqlFile and sqlName may not be used with selectStatement and paramTypes");
                exitWithHelp(options);
            }

            exporter = createFromFile(sqlFile, sqlName, inFile, outFile, tagStr, printIfNoRecord,
                    newLineReplacement);

        } else if (selStr == null || selStr.length() == 0 || pTypes == null || pTypes.length() == 0) {
            System.err.println("sqlFile and sqlName or selectStatement and paramTypes must be given");
            exitWithHelp(options);

        } else {
            exporter = createFromStatementStr(selStr, pTypes, inFile, outFile, tagStr, printIfNoRecord,
                    newLineReplacement);
        }

        exporter.export();
        exporter.close();
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println();
        exitWithHelp(options);
    }

}