Example usage for java.io PrintStream PrintStream

List of usage examples for java.io PrintStream PrintStream

Introduction

In this page you can find the example usage for java.io PrintStream PrintStream.

Prototype

public PrintStream(File file) throws FileNotFoundException 

Source Link

Document

Creates a new print stream, without automatic line flushing, with the specified file.

Usage

From source file:com.denimgroup.threadfix.importer.cli.CommandLineMigration.java

public static void main(String[] args) {

    if (!check(args))
        return;/*from  ww w .j a v a 2s.c  o m*/

    try {
        String inputScript = args[0];
        String inputMySqlConfig = args[1];
        String outputScript = "import.sql";
        String outputMySqlConfigTemp = "jdbc_temp.properties";
        String errorLogFile = "error.log";
        String fixedSqlFile = "error_sql.sql";
        String errorLogAttemp1 = "error1.log";
        String infoLogFile = "info.log";
        String rollbackScript = "rollback.sql";

        deleteFile(outputScript);
        deleteFile(errorLogFile);
        deleteFile(errorLogFile);
        deleteFile(fixedSqlFile);
        deleteFile(errorLogAttemp1);
        deleteFile(infoLogFile);
        deleteFile(rollbackScript);

        PrintStream infoPrintStream = new PrintStream(new FileOutputStream(new File(infoLogFile)));
        System.setOut(infoPrintStream);

        long startTime = System.currentTimeMillis();

        copyFile(inputMySqlConfig, outputMySqlConfigTemp);

        LOGGER.info("Creating threadfix table in mySql database ...");
        ScriptRunner scriptRunner = SpringConfiguration.getContext().getBean(ScriptRunner.class);

        startTime = printTimeConsumed(startTime);
        convert(inputScript, outputScript);

        startTime = printTimeConsumed(startTime);

        PrintStream errPrintStream = new PrintStream(new FileOutputStream(new File(errorLogFile)));
        System.setErr(errPrintStream);

        LOGGER.info("Sending sql script to MySQL server ...");
        scriptRunner.run(outputScript, outputMySqlConfigTemp);

        long errorCount = scriptRunner.checkRunningAndFixStatements(errorLogFile, fixedSqlFile);
        long lastCount = errorCount + 1;
        int times = 1;
        int sameFixedSet = 0;

        // Repeat
        while (errorCount > 0) {
            //Flush error log screen to other file
            errPrintStream = new PrintStream(new FileOutputStream(new File(errorLogAttemp1)));
            System.setErr(errPrintStream);

            times += 1;

            if (errorCount == lastCount) {
                sameFixedSet++;
            } else {
                sameFixedSet = 0;
            }

            LOGGER.info("Found " + errorCount + " error statements. Sending fixed sql script to MySQL server "
                    + times + " times ...");
            scriptRunner.run(fixedSqlFile, outputMySqlConfigTemp);
            lastCount = errorCount;
            errorCount = scriptRunner.checkRunningAndFixStatements(errorLogAttemp1, fixedSqlFile);

            if (errorCount > lastCount || sameFixedSet > SAME_SET_TRY_LIMIT)
                break;
        }

        if (errorCount > 0) {
            LOGGER.error("After " + times + " of trying, still found errors in sql script. "
                    + "Please check error_sql.sql and error1.log for more details.");
            LOGGER.info("Do you want to keep data in MySQL, and then import manually error statements (y/n)? ");
            try (java.util.Scanner in = new java.util.Scanner(System.in)) {
                String answer = in.nextLine();
                if (!answer.equalsIgnoreCase("y")) {
                    rollbackData(scriptRunner, outputMySqlConfigTemp, rollbackScript);
                } else {
                    LOGGER.info(
                            "Data imported to MySQL, but still have some errors. Please check error_sql.sql and error1.log to import manually.");
                }

            }

        } else {
            printTimeConsumed(startTime);
            LOGGER.info("Migration successfully finished");
        }

        deleteFile(outputMySqlConfigTemp);

    } catch (Exception e) {
        LOGGER.error("Error: ", e);
    }
}

From source file:com.xylocore.copybook.runtime.internal.AbstractCopybookGenerator.java

public static void main(String[] args) {
    try {// www  . jav a 2s. co m
        PrintStream myOutputStream = System.out;
        myOutputStream = new PrintStream(new FileOutputStream(
                "src/main/java/com/xylocore/commons/data/copybook/runtime/AbstractCopybook.java.new"));

        AbstractCopybookGenerator myGenerator = new AbstractCopybookGenerator();
        myGenerator.generate(myOutputStream);

        myOutputStream.close();
    } catch (Exception myException) {
        myException.printStackTrace();
    }
}

From source file:hadoopInstaller.Main.java

public static void main(String[] args) {
    // Disable VFS logging to console by default
    System.setProperty("org.apache.commons.logging.Log", //$NON-NLS-1$
            "org.apache.commons.logging.impl.NoOpLog"); //$NON-NLS-1$
    // Configure SimpleLog to show date and omit log name
    System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true"); //$NON-NLS-1$//$NON-NLS-2$
    System.setProperty("org.apache.commons.logging.simplelog.showlogname", "false"); //$NON-NLS-1$//$NON-NLS-2$
    System.setProperty("org.apache.commons.logging.simplelog.showShortLogname", "false"); //$NON-NLS-1$//$NON-NLS-2$
    try (PrintStream filePrintStream = new PrintStream(VFS.getManager()
            .resolveFile(MessageFormat.format("file://{0}/{1}", //$NON-NLS-1$
                    System.getProperty("user.dir"), Main.FILE_LOG_NAME)) //$NON-NLS-1$
            .getContent().getOutputStream(true))) {

        CompositeLog log = new CompositeLog();
        Integer logLevel = detectLogLevel(args);
        PrintStreamLog consoleLog = new PrintStreamLog(Installer.INSTALLER_NAME, System.out);
        consoleLog.setLevel(logLevel);//from w ww . j av  a 2  s .  c o m
        log.addLog(consoleLog);
        PrintStreamLog fileLog = new PrintStreamLog(Installer.INSTALLER_NAME, filePrintStream);
        fileLog.setLevel(logLevel);
        log.addLog(fileLog);
        boolean deploy = Arrays.asList(args).contains("-deploy"); //$NON-NLS-1$
        try {
            new Installer(log, deploy).run();
        } catch (InstallationFatalError e) {
            log.fatal(e.getLocalizedMessage());
            log.fatal(e.getCause().getLocalizedMessage());
            log.trace(e.getLocalizedMessage(), e);
        }
    } catch (FileSystemException e) {
        new PrintStreamLog(Installer.INSTALLER_NAME, System.err).fatal(e.getLocalizedMessage(), e);
        System.exit(1);
    }

    /*
     * TODO-- ssh-ask
     * 
     * Consider using a configuration that doesn't require password-less
     * authentication, but set's it up for the final cluster.
     */
}

From source file:it.cnr.isti.labse.glimpse.MainMonitoring.java

/**
 * Read the properties and init the connections to the enterprise service bus
 * //from  w  w w. jav a2  s .co  m
 * @param is the systemSettings file
 */
public static void main(String[] args) {
    try {
        FileOutputStream fos = new FileOutputStream("glimpseLog.log");
        PrintStream ps = new PrintStream(fos);
        System.setErr(ps);

        if (MainMonitoring.initProps(args[0]) && MainMonitoring.init()) {

            SplashScreen.Show();
            System.out.println("Please wait until setup is done...");
            //the buffer where the events are stored to be analyzed
            EventsBuffer<GlimpseBaseEvent<?>> buffer = new EventsBufferImpl<GlimpseBaseEvent<?>>();

            //The complex event engine that will be used (in this case drools)
            ComplexEventProcessor engine = new ComplexEventProcessorImpl(Manager.Read(MANAGERPARAMETERFILE),
                    buffer, connFact, initConn);
            engine.start();

            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            //the manager of all the architecture
            GlimpseManager manager = new GlimpseManager(Manager.Read(MANAGERPARAMETERFILE), connFact, initConn,
                    engine.getRuleManager());
            manager.start();
        }
    } catch (Exception e) {
        System.out.println("USAGE: java -jar MainMonitoring.jar \"systemSettings\"");
    }
}

From source file:com.genentech.retrival.tabExport.TABExporter.java

public static void main(String[] args) throws ParseException, JDOMException, IOException {
    long start = System.currentTimeMillis();
    int nStruct = 0;

    // create command line Options object
    Options options = new Options();
    Option opt = new Option("sqlFile", true, "sql-xml file");
    opt.setRequired(true);/*from  w w  w. j a v  a 2s. c  o  m*/
    options.addOption(opt);

    opt = new Option("sqlName", true, "name of SQL element in xml file");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option("o", true, "output file");
    opt.setRequired(false);
    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("noHeader", false, "Do not output header line");
    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);
    }
    args = cmd.getArgs();

    String outFile = cmd.getOptionValue("o");
    String sqlFile = cmd.getOptionValue("sqlFile");
    String sqlName = cmd.getOptionValue("sqlName");
    String newLineReplacement = cmd.getOptionValue("newLineReplacement");

    args = cmd.getArgs();

    try {
        PrintStream out = System.out;
        if (outFile != null)
            out = new PrintStream(outFile);

        SQLStatement stmt = SQLStatement.createFromFile(new File(sqlFile), sqlName);
        Object[] sqlArgs = args;
        if (stmt.getParamTypes().length != args.length) {
            System.err.printf(
                    "\nWarining sql statement needs %d parameters but got only %d. Filling up with NULLs.\n",
                    stmt.getParamTypes().length, args.length);
            sqlArgs = new Object[stmt.getParamTypes().length];
            System.arraycopy(args, 0, sqlArgs, 0, args.length);
        }

        Selecter sel = Selecter.factory(stmt);
        if (!sel.select(sqlArgs)) {
            System.err.println("No rows returned!");
            System.exit(0);
        }

        String[] fieldNames = sel.getFieldNames();
        if (fieldNames.length == 0) {
            System.err.println("Query did not return any columns");
            exitWithHelp(options);
        }

        if (!cmd.hasOption("noHeader")) {
            StringBuilder sb = new StringBuilder(200);
            for (String f : fieldNames)
                sb.append(f).append('\t');
            if (sb.length() > 1)
                sb.setLength(sb.length() - 1); // chop last \t
            String header = sb.toString();

            out.println(header);
        }

        StringBuilder sb = new StringBuilder(200);
        while (sel.hasNext()) {
            Record sqlRec = sel.next();
            sb.setLength(0);

            for (int i = 0; i < fieldNames.length; i++) {
                String fld = sqlRec.getStrg(i);
                if (newLineReplacement != null)
                    fld = NEWLinePattern.matcher(fld).replaceAll(newLineReplacement);

                sb.append(fld).append('\t');
            }

            if (sb.length() > 1)
                sb.setLength(sb.length() - 1); // chop last \t
            String row = sb.toString();

            out.println(row);

            nStruct++;
        }

    } catch (Exception e) {
        throw new Error(e);
    } finally {
        System.err.printf("TABExporter: Exported %d records in %dsec\n", nStruct,
                (System.currentTimeMillis() - start) / 1000);
    }
}

From source file:ca.uqac.dim.mapreduce.ltl.ParaLTLValidation.java

/**
 * Program entry point.//from w w  w  .  ja  va2s  . c  o  m
 * @param args Command-line arguments
 */
@SuppressWarnings("static-access")
public static void main(String[] args) {
    // Define and process command line arguments
    Options options = new Options();
    HelpFormatter help_formatter = new HelpFormatter();
    Option opt;
    options.addOption("h", "help", false, "Show help");
    opt = OptionBuilder.withArgName("property").hasArg()
            .withDescription("Property to verify, enclosed in double quotes").create("p");
    options.addOption(opt);
    opt = OptionBuilder.withArgName("filename").hasArg().withDescription("Input filename").create("i");
    options.addOption(opt);
    opt = OptionBuilder.withArgName("x").hasArg()
            .withDescription("Set verbosity level to x (default: 0 = quiet)").create("v");
    options.addOption(opt);
    opt = OptionBuilder.withArgName("ParserType").hasArg().withDescription("Parser type (Dom or Sax)")
            .create("t");
    options.addOption(opt);
    opt = OptionBuilder.withLongOpt("redirection").withArgName("x").hasArg()
            .withDescription("Set the redirection file for the System.out").create("r");
    options.addOption(opt);
    opt = OptionBuilder.withLongOpt("mapper").withArgName("x").hasArg()
            .withDescription("Set the number of mapper").create("m");
    options.addOption(opt);
    opt = OptionBuilder.withLongOpt("reducer").withArgName("x").hasArg()
            .withDescription("Set the number of reducer").create("n");
    options.addOption(opt);
    CommandLine c_line = parseCommandLine(options, args);

    String redirectionFile = "";

    //Contains a redirection file for the output
    if (c_line.hasOption("redirection")) {
        try {
            redirectionFile = c_line.getOptionValue("redirection");
            PrintStream ps;
            ps = new PrintStream(redirectionFile);
            System.setOut(ps);
        } catch (FileNotFoundException e) {
            System.out.println("Redirection error !!!");
            e.printStackTrace();
        }
    }

    if (!c_line.hasOption("p") || !c_line.hasOption("i") | c_line.hasOption("h")) {
        help_formatter.printHelp(app_name, options);
        System.exit(1);
    }
    assert c_line.hasOption("p");
    assert c_line.hasOption("i");
    String trace_filename = c_line.getOptionValue("i");
    String trace_format = getExtension(trace_filename);
    String property_str = c_line.getOptionValue("p");
    String ParserType = "";
    int MapperNum = 0;
    int ReducerNum = 0;

    //Contains a parser type
    if (c_line.hasOption("t")) {
        ParserType = c_line.getOptionValue("t");
    } else {
        System.err.println("No Parser Type in Arguments");
        System.exit(ERR_ARGUMENTS);
    }

    //Contains a mapper number
    if (c_line.hasOption("m")) {
        MapperNum = Integer.parseInt(c_line.getOptionValue("m"));
    } else {
        System.err.println("No Mapper Number in Arguments");
        System.exit(ERR_ARGUMENTS);
    }

    //Contains a reducer number
    if (c_line.hasOption("n")) {
        ReducerNum = Integer.parseInt(c_line.getOptionValue("n"));
    } else {
        System.err.println("No Reducer Number in Arguments");
        System.exit(ERR_ARGUMENTS);
    }

    if (c_line.hasOption("v"))
        m_verbosity = Integer.parseInt(c_line.getOptionValue("v"));

    // Obtain the property to verify and break into subformulas
    Operator property = null;
    try {
        int preset = Integer.parseInt(property_str);
        property = new Edoc2012Presets().property(preset);
    } catch (NumberFormatException e) {
        try {
            property = Operator.parseFromString(property_str);
        } catch (Operator.ParseException pe) {
            System.err.println("ERROR: parsing");
            System.exit(1);
        }
    }
    Set<Operator> subformulas = property.getSubformulas();

    // Initialize first collector depending on input file format
    int max_loops = property.getDepth();
    int max_tuples_total = 0, total_tuples_total = 0;
    long time_begin = System.nanoTime();
    TraceCollector initial_collector = null;
    {
        File in_file = new File(trace_filename);
        if (trace_format.compareToIgnoreCase(".txt") == 0) {
            initial_collector = new CharacterTraceCollector(in_file, subformulas);
        } else if (trace_format.compareToIgnoreCase(".xml") == 0) {
            if (ParserType.equals("Dom")) {
                initial_collector = new XmlDomTraceCollector(in_file, subformulas);
            } else if (ParserType.equals("Sax")) {
                initial_collector = new XmlSaxTraceCollector(in_file, subformulas);
            } else {
                initial_collector = new XmlSaxTraceCollector(in_file, subformulas);
            }
        }
    }
    if (initial_collector == null) {
        System.err.println("ERROR: unrecognized input format");
        System.exit(1);
    }

    // Start workflow
    int trace_len = initial_collector.getTraceLength();
    InCollector<Operator, LTLTupleValue> loop_collector = initial_collector;
    print(System.out, property.toString(), 2);
    print(System.out, loop_collector.toString(), 3);
    for (int i = 0; i < max_loops; i++) {
        print(System.out, "Loop " + i, 2);
        LTLParallelWorkflow w = new LTLParallelWorkflow(new LTLMapper(subformulas),
                new LTLReducer(subformulas, trace_len), loop_collector,
                new ResourceManager<Operator, LTLTupleValue>(MapperNum),
                new ResourceManager<Operator, LTLTupleValue>(ReducerNum));
        loop_collector = w.run();
        max_tuples_total += w.getMaxTuples();
        total_tuples_total += w.getTotalTuples();

        if (m_verbosity >= 3) {
            print(System.out, loop_collector.toString(), 3);
        }
    }
    boolean result = getVerdict(loop_collector, property);
    long time_end = System.nanoTime();
    if (result)
        print(System.out, "Formula is true", 1);
    else
        print(System.out, "Formula is false", 1);

    long time_total = (time_end - time_begin) / 1000000;
    System.out.println(trace_len + "," + max_tuples_total + "," + total_tuples_total + "," + time_total);
}

From source file:co.cask.cdap.data2.util.hbase.HBaseVersion.java

/**
 * Prints out the HBase {@link Version} enum value for the current version of HBase on the classpath.
 *///from ww  w. jav a 2s. c o  m
public static void main(String[] args) {
    // Suppress any output to stdout
    PrintStream stdout = System.out;
    System.setOut(new PrintStream(new NullOutputStream()));
    Version version = HBaseVersion.get();

    // Restore stdout
    System.setOut(stdout);
    System.out.println(version.getMajorVersion());

    if (args.length == 1 && "-v".equals(args[0])) {
        // Print versionString if verbose
        System.out.println("versionString=" + getVersionString());
    }
}

From source file:at.tuwien.ifs.somtoolbox.doc.RunnablesReferenceCreator.java

public static void main(String[] args) {
    ArrayList<Class<? extends SOMToolboxApp>> runnables = SubClassFinder.findSubclassesOf(SOMToolboxApp.class,
            true);/* w  ww  . j  a  va2  s  .c o m*/
    Collections.sort(runnables, SOMToolboxApp.TYPE_GROUPED_COMPARATOR);

    StringBuilder sbIndex = new StringBuilder(runnables.size() * 50);
    StringBuilder sbDetails = new StringBuilder(runnables.size() * 200);

    sbIndex.append("\n<table border=\"0\">\n");

    Type lastType = null;

    for (Class<? extends SOMToolboxApp> c : runnables) {
        try {
            // Ignore abstract classes and interfaces
            if (Modifier.isAbstract(c.getModifiers()) || Modifier.isInterface(c.getModifiers())) {
                continue;
            }

            Type type = Type.getType(c);
            if (type != lastType) {
                sbIndex.append("  <tr> <td colspan=\"2\"> <h5> " + type + " Applications </h5> </td> </tr>\n");
                sbDetails.append("<h2> " + type + " Applications </h2>\n");
                lastType = type;
            }
            String descr = "N/A";
            try {
                descr = (String) c.getDeclaredField("DESCRIPTION").get(null);
            } catch (Exception e) {
            }
            String longDescr = "descr";
            try {
                longDescr = (String) c.getDeclaredField("LONG_DESCRIPTION").get(null);
            } catch (Exception e) {
            }

            sbIndex.append("  <tr>\n");
            sbIndex.append("    <td> <a href=\"#").append(c.getSimpleName()).append("\">")
                    .append(c.getSimpleName()).append("</a> </td>\n");
            sbIndex.append("    <td> ").append(descr).append(" </td>\n");
            sbIndex.append("  </tr>\n");

            sbDetails.append("<h3 id=\"").append(c.getSimpleName()).append("\">").append(c.getSimpleName())
                    .append("</h3>\n");
            sbDetails.append("<p>").append(longDescr).append("</p>\n");

            try {
                Parameter[] options = (Parameter[]) c.getField("OPTIONS").get(null);
                JSAP jsap = AbstractOptionFactory.registerOptions(options);
                final ByteArrayOutputStream os = new ByteArrayOutputStream();
                PrintStream ps = new PrintStream(os);
                AbstractOptionFactory.printHelp(jsap, c.getName(), ps);
                sbDetails.append("<pre>").append(StringEscapeUtils.escapeHtml(os.toString())).append("</pre>");
            } catch (Exception e1) { // we didn't find the options => let the class be invoked ...
            }

        } catch (SecurityException e) {
            // Should not happen - no Security
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
    }
    sbIndex.append("</table>\n\n");
    System.out.println(sbIndex);
    System.out.println(sbDetails);
}

From source file:edu.msu.cme.rdp.taxatree.TreeBuilder.java

public static void main(String[] args) throws IOException {
    if (args.length != 3) {
        System.err.println("USAGE: TreeBuilder <idmapping> <merges.bin> <newick_out>");
        return;/*from  w w  w  . j a v  a2 s.co m*/
    }

    IdMapping<Integer> idMapping = IdMapping.fromFile(new File(args[0]));
    DataInputStream mergeStream = new DataInputStream(new BufferedInputStream(new FileInputStream(args[1])));
    TaxonHolder lastMerged = null;
    int taxid = 0;
    final Map<Integer, Double> distMap = new HashMap();
    Map<Integer, TaxonHolder> taxonMap = new HashMap();

    try {
        while (true) {
            if (mergeStream.readBoolean()) { // Singleton
                int cid = mergeStream.readInt();
                int intId = mergeStream.readInt();
                TaxonHolder<Taxon> holder;

                List<String> seqids = idMapping.getIds(intId);
                if (seqids.size() == 1) {
                    holder = new TaxonHolder(new Taxon(taxid++, seqids.get(0), ""));
                } else {
                    holder = new TaxonHolder(new Taxon(taxid++, "", ""));
                    for (String seqid : seqids) {
                        int id = taxid++;
                        distMap.put(id, 0.0);
                        TaxonHolder th = new TaxonHolder(new Taxon(id, seqid, ""));
                        th.setParent(holder);
                        holder.addChild(th);
                    }
                }

                lastMerged = holder;
                taxonMap.put(cid, holder);
            } else {
                int ci = mergeStream.readInt();
                int cj = mergeStream.readInt();
                int ck = mergeStream.readInt();
                double dist = (double) mergeStream.readInt() / DistanceCalculator.MULTIPLIER;

                TaxonHolder holder = new TaxonHolder(new Taxon(taxid++, "", ""));

                taxonMap.put(ck, holder);
                holder.addChild(taxonMap.get(ci));
                taxonMap.get(ci).setParent(holder);
                distMap.put(ci, dist);
                holder.addChild(taxonMap.get(cj));
                taxonMap.get(cj).setParent(holder);
                distMap.put(cj, dist);

                lastMerged = holder;
            }
        }
    } catch (EOFException e) {

    }

    if (lastMerged == null) {
        throw new IOException("No merges in file");
    }

    PrintStream newickTreeOut = new PrintStream(new File(args[2]));
    NewickPrintVisitor visitor = new NewickPrintVisitor(newickTreeOut, false, new NewickDistanceFactory() {

        public float getDistance(int i) {
            return distMap.get(i).floatValue();
        }

    });

    lastMerged.biDirectionDepthFirst(visitor);
    newickTreeOut.close();
}

From source file:edu.msu.cme.rdp.seqmatch.cli.SeqMatchMain.java

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

    if (args.length == 0) {
        System.err.println("USAGE: SeqMatchMain [train|seqmatch] <args>");
        return;/*from ww  w.  j av a2 s . c  o m*/
    }

    String cmd = args[0];
    args = Arrays.copyOfRange(args, 1, args.length);

    if (cmd.equals("train")) {
        if (args.length != 2) {
            System.err.println("USAGE: train <reference sequences> <trainee_out_file_prefix>"
                    + "\nMultiple trainee output files might be created, each containing maximum "
                    + Trainee.MAX_NUM_SEQ + " sequences");
            return;
        }

        File refSeqs = new File(args[0]);
        File traineeFileOut = new File(args[1]);

        //maybe more than 1 trainee files need to be created, depending on the number of seqs
        CreateMultiMatchFromFile.getMultiTrainee(refSeqs, traineeFileOut);
    } else if (cmd.equals("seqmatch")) {
        File refFile = null;
        File queryFile = null;
        HashMap<String, String> descMap = new HashMap<String, String>();
        PrintStream out = new PrintStream(System.out);
        int knn = 20;
        float minSab = .5f;

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

            if (line.hasOption("knn")) {
                knn = Integer.parseInt(line.getOptionValue("knn"));
            }

            if (line.hasOption("sab")) {
                minSab = Float.parseFloat(line.getOptionValue("sab"));
            }
            if (line.hasOption("desc")) {
                descMap = readDesc(new File(line.getOptionValue("desc")));
            }
            if (line.hasOption("outFile")) {
                out = new PrintStream(new File(line.getOptionValue("outFile")));
            }

            args = line.getArgs();

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

            refFile = new File(args[0]);
            queryFile = new File(args[1]);

        } catch (Exception e) {
            new HelpFormatter().printHelp("seqmatch <refseqs | trainee_file_or_dir> <query_file>\n"
                    + " trainee_file_or_dir is a single trainee file or a directory containing multiple trainee files",
                    options);
            System.err.println("Error: " + e.getMessage());
            return;
        }

        SeqMatch seqmatch = null;
        if (refFile.isDirectory()) { // a directory of trainee files
            List<SeqMatch> engineList = new ArrayList<SeqMatch>();
            for (File f : refFile.listFiles()) {
                if (!f.isHidden()) {
                    TwowaySeqMatch match = new TwowaySeqMatch(new SeqMatchEngine(new StorageTrainee(f)));
                    engineList.add(match);
                }
            }
            seqmatch = new MultiTraineeSeqMatch(engineList);
        } else { // a single fasta file or trainee file
            if (SeqUtils.guessFileFormat(refFile) == SequenceFormat.UNKNOWN) {
                seqmatch = CLISeqMatchFactory.trainTwowaySeqMatch(new StorageTrainee(refFile));
            } else {
                seqmatch = CreateMultiMatchFromFile.getMultiMatch(refFile);
            }
        }

        out.println("query name\tmatch seq\torientation\tS_ab score\tunique oligomers\tdescription");

        SeqReader reader = new SequenceReader(queryFile);
        Sequence seq;

        while ((seq = reader.readNextSequence()) != null) {
            SeqMatchResultSet resultSet = seqmatch.match(seq, knn);
            for (SeqMatchResult result : resultSet) {
                char r = '+';
                if (result.isReverse()) {
                    r = '-';
                }

                if (result.getScore() > minSab) {
                    out.println(seq.getSeqName() + "\t" + result.getSeqName() + "\t" + r + "\t"
                            + result.getScore() + "\t" + resultSet.getQueryWordCount() + "\t"
                            + descMap.get(result.getSeqName()));
                }
            }
        }

        out.close();
    } else {
        throw new IllegalArgumentException("USAGE: SeqMatchMain [train|seqmatch] <args>");
    }
}