List of usage examples for org.apache.commons.io.output NullWriter nullWriter
public static Writer nullWriter()
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/*w ww.j a v a2 s . com*/ * @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.multicompare.Main.java
public static void main(String[] args) throws Exception { PrintStream hier_out = null;//from w w w.j a v a 2s . c o m PrintWriter assign_out = new PrintWriter(new NullWriter()); PrintStream bootstrap_out = null; File hier_out_filename = null; String propFile = null; File biomFile = null; File metadataFile = null; PrintWriter shortseq_out = null; List<MCSample> samples = new ArrayList(); ClassificationResultFormatter.FORMAT format = ClassificationResultFormatter.FORMAT.allRank; float conf = CmdOptions.DEFAULT_CONF; String gene = null; int min_bootstrap_words = Classifier.MIN_BOOTSTRSP_WORDS; try { CommandLine line = new PosixParser().parse(options, args); if (line.hasOption(CmdOptions.OUTFILE_SHORT_OPT)) { assign_out = new PrintWriter(line.getOptionValue(CmdOptions.OUTFILE_SHORT_OPT)); } else { throw new IllegalArgumentException("Require the output file for classification assignment"); } if (line.hasOption(CmdOptions.HIER_OUTFILE_SHORT_OPT)) { hier_out_filename = new File(line.getOptionValue(CmdOptions.HIER_OUTFILE_SHORT_OPT)); hier_out = new PrintStream(hier_out_filename); } if (line.hasOption(CmdOptions.BIOMFILE_SHORT_OPT)) { biomFile = new File(line.getOptionValue(CmdOptions.BIOMFILE_SHORT_OPT)); } if (line.hasOption(CmdOptions.METADATA_SHORT_OPT)) { metadataFile = new File(line.getOptionValue(CmdOptions.METADATA_SHORT_OPT)); } 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 { propFile = line.getOptionValue(CmdOptions.TRAINPROPFILE_SHORT_OPT); } } 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("filterbyconf")) { format = ClassificationResultFormatter.FORMAT.filterbyconf; } else if (f.equalsIgnoreCase("db")) { format = ClassificationResultFormatter.FORMAT.dbformat; } else if (f.equalsIgnoreCase("biom")) { format = ClassificationResultFormatter.FORMAT.biom; } else { throw new IllegalArgumentException( "Not an valid output format, only allrank, fixrank, biom, filterbyconf and db allowed"); } } if (line.hasOption(CmdOptions.GENE_SHORT_OPT)) { if (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 + " not found, choose from" + ClassifierFactory.RRNA_16S_GENE + ", " + ClassifierFactory.FUNGALLSU_GENE + ", " + ClassifierFactory.FUNGALITS_warcup_GENE + ", " + ClassifierFactory.FUNGALITS_unite_GENE); } } if (line.hasOption(CmdOptions.MIN_BOOTSTRAP_WORDS_SHORT_OPT)) { min_bootstrap_words = Integer .parseInt(line.getOptionValue(CmdOptions.MIN_BOOTSTRAP_WORDS_SHORT_OPT)); if (min_bootstrap_words < Classifier.MIN_BOOTSTRSP_WORDS) { throw new IllegalArgumentException(CmdOptions.MIN_BOOTSTRAP_WORDS_LONG_OPT + " must be at least " + Classifier.MIN_BOOTSTRSP_WORDS); } } if (line.hasOption(CmdOptions.BOOTSTRAP_SHORT_OPT)) { String confString = line.getOptionValue(CmdOptions.BOOTSTRAP_SHORT_OPT); try { conf = Float.valueOf(confString); } catch (NumberFormatException e) { throw new IllegalArgumentException("Confidence must be a decimal number"); } if (conf < 0 || conf > 1) { throw new IllegalArgumentException("Confidence must be in the range [0,1]"); } } if (line.hasOption(CmdOptions.SHORTSEQ_OUTFILE_SHORT_OPT)) { shortseq_out = new PrintWriter(line.getOptionValue(CmdOptions.SHORTSEQ_OUTFILE_SHORT_OPT)); } if (line.hasOption(CmdOptions.BOOTSTRAP_OUTFILE_SHORT_OPT)) { bootstrap_out = new PrintStream(line.getOptionValue(CmdOptions.BOOTSTRAP_OUTFILE_SHORT_OPT)); } if (format.equals(ClassificationResultFormatter.FORMAT.biom) && biomFile == null) { throw new IllegalArgumentException("biom format requires an input biom file"); } if (biomFile != null) { // if input biom file provided, use biom format format = ClassificationResultFormatter.FORMAT.biom; } args = line.getArgs(); for (String arg : args) { String[] inFileNames = arg.split(","); File inputFile = new File(inFileNames[0]); File idmappingFile = null; if (!inputFile.exists()) { throw new IllegalArgumentException("Failed to find input file \"" + inFileNames[0] + "\""); } if (inFileNames.length == 2) { idmappingFile = new File(inFileNames[1]); if (!idmappingFile.exists()) { throw new IllegalArgumentException("Failed to find input file \"" + inFileNames[1] + "\""); } } MCSample nextSample = new MCSample(inputFile, idmappingFile); samples.add(nextSample); } if (propFile == null && gene == null) { gene = CmdOptions.DEFAULT_GENE; } if (samples.size() < 1) { throw new IllegalArgumentException("Require at least one sample files"); } } catch (Exception e) { System.out.println("Command Error: " + e.getMessage()); new HelpFormatter().printHelp(80, " [options] <samplefile>[,idmappingfile] ...", "", options, ""); return; } MultiClassifier multiClassifier = new MultiClassifier(propFile, gene, biomFile, metadataFile); MultiClassifierResult result = multiClassifier.multiCompare(samples, conf, assign_out, format, min_bootstrap_words); assign_out.close(); if (hier_out != null) { DefaultPrintVisitor printVisitor = new DefaultPrintVisitor(hier_out, samples); result.getRoot().topDownVisit(printVisitor); hier_out.close(); if (multiClassifier.hasCopyNumber()) { // print copy number corrected counts File cn_corrected_s = new File(hier_out_filename.getParentFile(), "cnadjusted_" + hier_out_filename.getName()); 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(); } } if (bootstrap_out != null) { for (MCSample sample : samples) { MCSamplePrintUtil.printBootstrapCountTable(bootstrap_out, sample); } bootstrap_out.close(); } if (shortseq_out != null) { for (String id : result.getBadSequences()) { shortseq_out.write(id + "\n"); } shortseq_out.close(); } }
From source file:edu.msu.cme.rdp.readseq.utils.SequenceTrimmer.java
public static void main(String[] args) throws IOException { Options options = new Options(); options.addOption("r", "ref-seq", true, "Trim points are given as positions in a reference sequence from this file"); options.addOption("i", "inclusive", false, "Trim points are inclusive"); options.addOption("l", "length", true, "Minimum length of sequence after trimming"); options.addOption("f", "filled-ratio", true, "Minimum ratio of filled model positions of sequence after trimming"); options.addOption("o", "out", true, "Write sequences to directory (default=cwd)"); options.addOption("s", "stats", true, "Write stats to file"); PrintWriter statsOut = new PrintWriter(new NullWriter()); boolean inclusive = false; int minLength = 0; int minTrimmedLength = 0; int maxNs = 0; int maxTrimNs = 0; int trimStart = 0; int trimStop = 0; Sequence refSeq = null;/*from ww w.j a va 2 s . c o m*/ float minFilledRatio = 0; int expectedModelPos = -1; String[] inputFiles = null; File outdir = new File("."); try { CommandLine line = new PosixParser().parse(options, args); if (line.hasOption("ref-seq")) { refSeq = readRefSeq(new File(line.getOptionValue("ref-seq"))); } if (line.hasOption("inclusive")) { inclusive = true; } if (line.hasOption("length")) { minLength = Integer.valueOf(line.getOptionValue("length")); } if (line.hasOption("filled-ratio")) { minFilledRatio = Float.valueOf(line.getOptionValue("filled-ratio")); } if (line.hasOption("out")) { outdir = new File(line.getOptionValue("out")); if (!outdir.isDirectory()) { outdir = outdir.getParentFile(); System.err.println("Output option is not a directory, using " + outdir + " instead"); } } if (line.hasOption("stats")) { statsOut = new PrintWriter(line.getOptionValue("stats")); } args = line.getArgs(); if (args.length < 3) { throw new Exception("Unexpected number of arguments"); } trimStart = Integer.parseInt(args[0]); trimStop = Integer.parseInt(args[1]); inputFiles = Arrays.copyOfRange(args, 2, args.length); if (refSeq != null) { expectedModelPos = SeqUtils.getMaskedBySeqString(refSeq.getSeqString()).length(); trimStart = translateCoord(trimStart, refSeq, CoordType.seq, CoordType.model); trimStop = translateCoord(trimStop, refSeq, CoordType.seq, CoordType.model); } } catch (Exception e) { new HelpFormatter().printHelp("SequenceTrimmer <trim start> <trim stop> <aligned file> ...", options); System.err.println("Error: " + e.getMessage()); } System.err.println("Starting sequence trimmer"); System.err.println("* Input files: " + Arrays.asList(inputFiles)); System.err.println("* Minimum Length: " + minLength); System.err.println("* Trim point inclusive?: " + inclusive); System.err.println("* Trim points: " + trimStart + "-" + trimStop); System.err.println("* Min filled ratio: " + minFilledRatio); System.err.println("* refSeq: " + ((refSeq == null) ? "model" : refSeq.getSeqName() + " " + refSeq.getDesc())); Sequence seq; SeqReader reader; TrimStats stats; writeStatsHeader(statsOut); FastaWriter seqWriter; File in; for (String infile : inputFiles) { in = new File(infile); reader = new SequenceReader(in); seqWriter = new FastaWriter(new File(outdir, "trimmed_" + in.getName())); while ((seq = reader.readNextSequence()) != null) { if (seq.getSeqName().startsWith("#")) { seqWriter.writeSeq(seq.getSeqName(), "", trimMetaSeq(seq.getSeqString(), trimStart, trimStop)); continue; } stats = getStats(seq, trimStart, trimStop); boolean passed = didSeqPass(stats, minLength, minTrimmedLength, maxNs, maxTrimNs, minFilledRatio); writeStats(statsOut, seq.getSeqName(), stats, passed); if (passed) { seqWriter.writeSeq(seq.getSeqName(), seq.getDesc(), new String(stats.trimmedBases)); } } reader.close(); seqWriter.close(); } statsOut.close(); }
From source file:net.krotscheck.dfr.text.AbstractTextEncoderTest.java
/** * Assert that we can change the destination. * * @throws Exception Should not be thrown. *//*from w ww. j a va2s . c om*/ @Test public void testGetSetDestination() throws Exception { ITextEncoder encoder = new TestTextEncoder(); Assert.assertNull(encoder.getWriter()); // Test input stream Writer writer = new NullWriter(); encoder.setWriter(writer); Assert.assertEquals(writer, encoder.getWriter()); }
From source file:edu.cornell.med.icb.goby.stats.DummyObservationWriter.java
public DummyObservationWriter() { super(new NullWriter()); }
From source file:net.krotscheck.dfr.text.AbstractTextEncoderTest.java
/** * Assert that we can call close with an output stream. * * @throws Exception Should not be thrown. *//*w w w . ja va 2s. c om*/ @Test public void testCloseWithStream() throws Exception { ITextEncoder encoder = new TestTextEncoder(); Assert.assertNull(encoder.getWriter()); Writer writer = new NullWriter(); encoder.setWriter(writer); Assert.assertEquals(writer, encoder.getWriter()); encoder.close(); Assert.assertNull(encoder.getWriter()); }
From source file:edu.umn.msi.tropix.grid.xml.SerializationUtilsTest.java
@Test(groups = "unit", expectedExceptions = XMLException.class) public void serializationProblem() { final ResearchCenter inputCenter = new ResearchCenter(); inputCenter.setDisplayName("Moo"); UTILS.serialize(new NullWriter(), ResearchCenter.class, ResearchCenter.getTypeDesc().getXmlType()); }
From source file:ar.com.zauber.commons.web.transformation.processors.impl.TidyScrapper.java
/** @see */ public final void scrap(final Reader content, final Writer writer, final Map<String, Object> map) { Validate.notNull(writer);/*from w w w . ja v a 2 s .c om*/ Validate.notNull(map); Validate.notNull(content); try { final Document doc; if (tidy != null) { doc = tidy.parseDOM(content, new NullWriter()); } else { doc = documentProvider.parse(new InputSource(content)); } scraper.scrap(doc, map, writer); } finally { IOUtils.closeQuietly(content); } }
From source file:com.github.rwitzel.streamflyer.core.ModifiableWriterUnitTest.java
/** * Asserts that the content of the character buffer is never bigger than the newNumberOfChars plus the look-behind. * Additionally asserts that the capacity of the character buffer does not exceed twice the size of * newNumberOfChars./* ww w.ja va2 s . co m*/ * * @param minimumLengthOfLookBehind * @param newNumberOfChars * @param numberOfCharactersToSkip * @param sizeOfInput * @param bufferSize * @throws Exception */ private void assertCharacterBufferDoesNotExceedRequestedLength(int minimumLengthOfLookBehind, int newNumberOfChars, int numberOfCharactersToSkip, int sizeOfInput, int bufferSize) throws Exception { // setup: create modifier and reader IdleModifier modifier = new IdleModifier(minimumLengthOfLookBehind, newNumberOfChars, numberOfCharactersToSkip); ModifyingWriter writer = new ModifyingWriter(new NullWriter(), modifier); Writer bufferedWriter = new BufferedWriter(writer, bufferSize); // read the stream into an output stream for (int index = 0; index < sizeOfInput; index++) { bufferedWriter.append('a'); } writer.flush(); writer.close(); assertTrue( "max requested length of character buffer " + modifier.getFactory().getMaxRequestedNewNumberOfChars() + " should be smaller than " + newNumberOfChars + " but was not", modifier.getFactory().getMaxRequestedNewNumberOfChars() <= newNumberOfChars); assertTrue("max size of character buffer " + modifier.getMaxSizeOfCharacterBuffer() + " should be smaller than " + (minimumLengthOfLookBehind + newNumberOfChars) + " but was not", modifier.getMaxSizeOfCharacterBuffer() <= minimumLengthOfLookBehind + newNumberOfChars); // as we know that StringBuilder.ensureCapacity(int) doubles the input // size if appropriate, we test for (look-behind + numChars) * 2 assertTrue("max capacity of character buffer " + modifier.getMaxCapacityOfCharacterBuffer() + " should be smaller than " + (minimumLengthOfLookBehind + newNumberOfChars) * 2 + " but was not", modifier.getMaxCapacityOfCharacterBuffer() <= (minimumLengthOfLookBehind + newNumberOfChars) * 2); }
From source file:com.linkedin.restli.tools.idlgen.DocletDocsProvider.java
@Override public void registerSourceFiles(Collection<String> sourceFileNames) { log.info("Executing Javadoc tool..."); final String flatClasspath; if (_classpath == null) { flatClasspath = System.getProperty("java.class.path"); } else {/*from w ww. j ava 2 s. c o m*/ flatClasspath = StringUtils.join(_classpath, ":"); } final PrintWriter sysoutWriter = new PrintWriter(System.out, true); final PrintWriter nullWriter = new PrintWriter(new NullWriter()); final List<String> javadocArgs = new ArrayList<String>( Arrays.asList("-classpath", flatClasspath, "-sourcepath", StringUtils.join(_sourcePaths, ":"))); if (_resourcePackages != null) { javadocArgs.add("-subpackages"); javadocArgs.add(StringUtils.join(_resourcePackages, ":")); } else { javadocArgs.addAll(sourceFileNames); } _doclet = RestLiDoclet.generateDoclet(_apiName, sysoutWriter, nullWriter, nullWriter, javadocArgs.toArray(new String[0])); }