List of usage examples for java.io StringWriter flush
public void flush()
From source file:org.jetbrains.jet.grammar.GrammarGenerator.java
private static String generate(List<Token> tokens) throws IOException { StringWriter result = new StringWriter(); Set<String> declaredSymbols = new HashSet<String>(); Set<String> usedSymbols = new HashSet<String>(); Multimap<String, String> usages = Multimaps.newSetMultimap(Maps.<String, Collection<String>>newHashMap(), new Supplier<Set<String>>() { @Override/*from www . j a v a 2s. c o m*/ public Set<String> get() { return Sets.newHashSet(); } }); Declaration lastDeclaration = null; for (Token advance : tokens) { if (advance instanceof Declaration) { Declaration declaration = (Declaration) advance; lastDeclaration = declaration; declaredSymbols.add(declaration.getName()); } else if (advance instanceof Identifier) { Identifier identifier = (Identifier) advance; assert lastDeclaration != null; usages.put(identifier.getName(), lastDeclaration.getName()); usedSymbols.add(identifier.getName()); } } try { JAXBContext context = JAXBContext.newInstance(Annotation.class, Comment.class, Declaration.class, DocComment.class, Identifier.class, Other.class, StringToken.class, SymbolToken.class, Token.class, WhiteSpace.class, TokenList.class); Marshaller m = context.createMarshaller(); TokenList list = new TokenList(tokens); list.updateUsages(usedSymbols, usages); m.marshal(list, result); } catch (PropertyException e) { e.printStackTrace(); } catch (JAXBException e) { e.printStackTrace(); } result.flush(); result.close(); return result.toString(); }
From source file:com.tek42.perforce.parse.AbstractPerforceTemplate.java
protected StringBuilder getPerforceResponse(String origcmd[], ResponseFilter filter) throws PerforceException { // TODO: Create a way to wildcard portions of the error checking. Add method to check for these errors. boolean loop = false; boolean attemptLogin = true; List<String> lines = null; int totalLength = 0; do {//w w w. j a v a2s . co m int mesgIndex = -1, count = 0; Executor p4 = depot.getExecFactory().newExecutor(); String debugCmd = ""; // get entire cmd to execute String cmd[] = getExtraParams(origcmd); // setup information for logging... for (String cm : cmd) { debugCmd += cm + " "; } // Perform execution and IO p4.exec(cmd); BufferedReader reader = p4.getReader(); String line = null; totalLength = 0; lines = new ArrayList<String>(1024); TimedStreamCloser timedStreamCloser = null; try { PerforceSCM.PerforceSCMDescriptor scmDescr = PerforceSCM.getInstance(); p4.getWriter().close(); int timeout = -1; if (scmDescr.hasP4ReadlineTimeout()) { // Implementation with timeout timeout = scmDescr.getP4ReadLineTimeout(); } timedStreamCloser = new TimedStreamCloser(p4.getInputStream(), timeout); timedStreamCloser.start(); while ((line = reader.readLine()) != null) { timedStreamCloser.reset(); // only check for errors if we have not found one already if (mesgIndex == -1) mesgIndex = checkAuthnErrors(line); if (filter.reject(line)) continue; lines.add(line); totalLength += line.length(); count++; } if (timedStreamCloser.timedOut()) { throw new PerforceException("Perforce operation timed out after " + timeout + " seconds."); } } catch (IOException ioe) { //this is generally not anything to worry about. The underlying //perforce process terminated and that causes java to be angry StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw, true); ioe.printStackTrace(pw); pw.flush(); sw.flush(); getLogger().warn("Perforce process terminated suddenly"); getLogger().warn(sw.toString()); try { p4.getWriter().close(); } catch (IOException e) { getLogger().warn("Write pipe failed to close."); } try { p4.getReader().close(); } catch (IOException e) { getLogger().warn("Read pipe failed to close."); } p4.close(); // If the project was interrupted, p4 needs to be killed // or it will continue running. In the worst case it will // still synchronize gigabytes of data into the workspace p4.kill(); } finally { if (timedStreamCloser != null) timedStreamCloser.interrupt(); try { p4.getWriter().close(); } catch (IOException e) { getLogger().warn("Write pipe failed to close."); } try { p4.getReader().close(); } catch (IOException e) { getLogger().warn("Read pipe failed to close."); } p4.close(); } loop = false; // If we failed to execute because of an authentication issue, try a p4 login. if (attemptLogin && (mesgIndex == 1 || mesgIndex == 2 || mesgIndex == 6 || mesgIndex == 9)) { // password is unset means that perforce isn't using the environment var P4PASSWD // Instead it is using tickets. We must attempt to login via p4 login, then // retry this cmd. p4.close(); trustIfSSL(); login(); loop = true; attemptLogin = false; continue; } // We aren't using the exact message because we want to add the username for more info if (mesgIndex == 4) throw new PerforceException( "Access for user '" + depot.getUser() + "' has not been enabled by 'p4 protect'"); if (mesgIndex != -1) throw new PerforceException(p4errors[mesgIndex]); if (count == 0) throw new PerforceException("No output for: " + debugCmd); } while (loop); StringBuilder response = new StringBuilder(totalLength + lines.size()); for (String line : lines) { response.append(line); response.append("\n"); } return response; }
From source file:edu.cornell.med.icb.goby.modes.TestDiscoverSVMethylationRatesMode.java
@Test public void testMethylationFormatGenomicContext() throws IOException, JSAPException { final MethylationRateVCFOutputFormat outputFormat = new MethylationRateVCFOutputFormat(); DiscoverVariantIterateSortedAlignments iterator = new DiscoverVariantIterateSortedAlignments(outputFormat) { @Override//from w ww . j ava 2 s .co m public CharSequence getReferenceId(int targetIndex) { return Integer.toString(targetIndex); } }; DiscoverSequenceVariantsMode mode = new DiscoverSequenceVariantsMode() { @Override public String[] getSamples() { return new String[] { "methylated", "not-so" }; } @Override public String[] getGroups() { return new String[] { "methylated", "not-so" }; } @Override public int[] getReaderIndexToGroupIndex() { return new int[] { 0, 1 }; // sample index is group index; } @Override public ArrayList<GroupComparison> getGroupComparisons() { ArrayList<GroupComparison> list = new ArrayList<GroupComparison>(); list.add(new GroupComparison("methylated", "not-so", 0, 1, 0)); return list; } }; outputFormat.setGenome(genome); StringWriter writer = new StringWriter(); outputFormat.allocateStorage(2, 2); outputFormat.defineColumns(new PrintWriter(writer), mode); outputFormat.setMinimumEventThreshold(0); outputFormat.writeRecord(iterator, makeTwoSampleCounts(), 1, 6, list1(), 0, 1); writer.flush(); String stringB = writer.getBuffer().toString(); assertTrue(stringB, stringB.contains("Context=CpG")); writer = new StringWriter(); outputFormat.allocateStorage(2, 2); outputFormat.defineColumns(new PrintWriter(writer), mode); outputFormat.setMinimumEventThreshold(0); final int referenceIndex = 2; outputFormat.setGenomeReferenceIndex(referenceIndex); outputFormat.writeRecord(iterator, makeTwoSampleCounts(), referenceIndex, 1, list1(), 0, 1); writer.flush(); String stringC = writer.getBuffer().toString(); assertTrue(stringC, stringC.contains("Context=CpT")); writer = new StringWriter(); outputFormat.allocateStorage(2, 2); outputFormat.defineColumns(new PrintWriter(writer), mode); outputFormat.setMinimumEventThreshold(0); final int referenceIndex1 = 1; outputFormat.setGenomeReferenceIndex(referenceIndex1); outputFormat.writeRecord(iterator, makeTwoSampleCounts(), referenceIndex1, 2, list1(), 0, 1); stringB = writer.getBuffer().toString(); assertTrue(stringB, stringB.contains("CpT")); writer = new StringWriter(); outputFormat.allocateStorage(2, 2); outputFormat.defineColumns(new PrintWriter(writer), mode); outputFormat.setMinimumEventThreshold(0); final int referenceIndex4 = 4; outputFormat.setGenomeReferenceIndex(referenceIndex4); outputFormat.writeRecord(iterator, makeTwoSampleCounts(), referenceIndex4, 7, list1(), 0, 1); stringB = writer.getBuffer().toString(); assertTrue(stringB, stringB.contains("CpC")); }
From source file:fr.xebia.confluence.gist.GistMacro.java
private String fetchGistUrl(String gistUrl, String proxyHost, String proxyPort) throws MacroException { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); InputStream in = null;/* w w w . j a v a 2 s. co m*/ try { URL url = new URL(gistUrl); URLConnection c; if (proxyHost != null) { int port; if (proxyPort == null) { port = 80; } else { port = Integer.parseInt(proxyPort); } Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, port)); c = url.openConnection(proxy); } else { c = url.openConnection(); } in = c.getInputStream(); IOUtils.copy(in, pw, settingsManager.getGlobalSettings().getDefaultEncoding()); pw.flush(); sw.flush(); return sw.toString(); } catch (IOException e) { String message = ConfluenceActionSupport.getTextStatic(COULD_NOT_FETCH_URL_CONTENTS_ERROR_KEY, new String[] { gistUrl, e.getMessage() }); throw new MacroException(message, e); } finally { Closeables.closeQuietly(pw); Closeables.closeQuietly(sw); Closeables.closeQuietly(in); } }
From source file:org.apache.olingo.fit.utils.AbstractUtilities.java
public InputStream writeEntitySet(final Accept accept, final ResWrap<EntityCollection> container) throws ODataSerializerException, IOException { final StringWriter writer = new StringWriter(); if (accept == Accept.ATOM || accept == Accept.XML) { atomSerializer.write(writer, container); } else {/*from w ww. j a va 2 s.c om*/ jsonSerializer.write(writer, container); } writer.flush(); writer.close(); return IOUtils.toInputStream(writer.toString(), Constants.ENCODING); }
From source file:org.nuxeo.ecm.platform.ui.web.component.list.UIJavascriptList.java
/** * Renders an element using rowIndex -2 and client side marker {@link #TEMPLATE_INDEX_MARKER}. * <p>//from w w w .j a va 2 s. c o m * This element will be used on client side by js code to handle addition of a new element. */ protected void encodeTemplate(FacesContext context) throws IOException { int oldIndex = getRowIndex(); Object requestMapValue = saveRequestMapModelValue(); Map<String, Object> requestMap = getFacesContext().getExternalContext().getRequestMap(); boolean hasVar = false; if (requestMap.containsKey(IS_LIST_TEMPLATE_VAR)) { hasVar = true; } Object oldIsTemplateBoolean = requestMap.remove(IS_LIST_TEMPLATE_VAR); try { setRowIndex(-2); // expose a boolean that can be used on client side to hide this element without disturbing the DOM requestMap.put(IS_LIST_TEMPLATE_VAR, Boolean.TRUE); // render the template as escaped html ResponseWriter oldResponseWriter = context.getResponseWriter(); StringWriter cacheingWriter = new StringWriter(); ResponseWriter newResponseWriter = context.getResponseWriter().cloneWithWriter(cacheingWriter); context.setResponseWriter(newResponseWriter); if (getChildCount() > 0) { for (UIComponent kid : getChildren()) { if (!kid.isRendered()) { continue; } try { ComponentSupport.encodeRecursive(context, kid); } catch (IOException err) { log.error("Error while rendering component " + kid); } } } cacheingWriter.flush(); cacheingWriter.close(); context.setResponseWriter(oldResponseWriter); String html = Functions.htmlEscape(cacheingWriter.toString()); ResponseWriter writer = context.getResponseWriter(); writer.write("<script type=\"text/x-html-template\">"); writer.write(html); writer.write("</script>"); } finally { setRowIndex(oldIndex); // restore if (hasVar) { requestMap.put(IS_LIST_TEMPLATE_VAR, oldIsTemplateBoolean); } else { requestMap.remove(IS_LIST_TEMPLATE_VAR); } restoreRequestMapModelValue(requestMapValue); } }
From source file:edu.harvard.hul.ois.fits.tools.exiftool.Exiftool.java
private Document createXml(String execOut) throws FitsToolException { StringWriter out = new StringWriter(); out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); out.write("\n"); out.write("<exiftool>"); out.write("\n"); out.write("<rawOutput>\n" + StringEscapeUtils.escapeXml(execOut)); out.write("</rawOutput>"); out.write("\n"); String[] lines = execOut.split("\n"); for (String line : lines) { String[] parts = line.split("\t"); String field = parts[0].trim(); if (parts.length > 1) { String value = parts[1].trim(); out.write("<" + field + ">" + StringEscapeUtils.escapeXml(value) + "</" + field + ">"); out.write("\n"); }/*from w w w. j a v a2s. c o m*/ } out.write("</exiftool>"); out.write("\n"); out.flush(); try { out.close(); } catch (IOException e) { throw new FitsToolException("Error closing Exiftool XML output stream", e); } Document doc = null; try { doc = saxBuilder.build(new StringReader(out.toString())); } catch (Exception e) { throw new FitsToolException("Error parsing Exiftool XML Output", e); } return doc; }
From source file:edu.cornell.med.icb.goby.modes.TestDiscoverSVMethylationRatesMode.java
@Test public void testMethylationFormat() throws IOException, JSAPException { final MethylationRateVCFOutputFormat outputFormat = new MethylationRateVCFOutputFormat(); DiscoverVariantIterateSortedAlignments iterator = new DiscoverVariantIterateSortedAlignments(outputFormat) { @Override/*from w ww. ja va 2s .co m*/ public CharSequence getReferenceId(int targetIndex) { return "ref-id"; } }; DiscoverSequenceVariantsMode mode = new DiscoverSequenceVariantsMode() { @Override public String[] getSamples() { return new String[] { "methylated", "not-so" }; } @Override public String[] getGroups() { return new String[] { "methylated", "not-so" }; } @Override public int[] getReaderIndexToGroupIndex() { return new int[] { 0, 1 }; // sample index is group index; } @Override public ArrayList<GroupComparison> getGroupComparisons() { ArrayList<GroupComparison> list = new ArrayList<GroupComparison>(); list.add(new GroupComparison("methylated", "not-so", 0, 1, 0)); return list; } }; StringWriter writer = new StringWriter(); outputFormat.allocateStorage(2, 2); outputFormat.setGenome(genome); outputFormat.defineColumns(new PrintWriter(writer), mode); outputFormat.setMinimumEventThreshold(0); outputFormat.writeRecord(iterator, makeTwoSampleCounts(), 0, 0, list1(), 0, 1); writer.flush(); String stringB = writer.getBuffer().toString(); assertTrue(stringB, stringB.contains("#Cm_Group[methylated]=1;")); assertTrue(stringB, stringB.contains("#Cm_Group[not-so]=0;")); writer = new StringWriter(); outputFormat.allocateStorage(2, 2); outputFormat.defineColumns(new PrintWriter(writer), mode); final SampleCountInfo[] sampleCounts = makeTwoSampleCounts(); sampleCounts[0].referenceBase = 'G'; outputFormat.writeRecord(iterator, sampleCounts, 0, 0, list2(), 0, 1); writer.flush(); stringB = writer.getBuffer().toString(); assertTrue(stringB, stringB.contains("#Cm_Group[methylated]=1;")); assertTrue(stringB, stringB.contains("#Cm_Group[not-so]=0;")); assertTrue(stringB, stringB.contains("MR[methylated]=100.0;")); assertTrue(stringB, stringB.contains("MR[not-so]=NaN;")); writer = new StringWriter(); outputFormat.allocateStorage(2, 2); outputFormat.defineColumns(new PrintWriter(writer), mode); outputFormat.writeRecord(iterator, makeTwoSampleCounts(), 0, 0, list3(), 0, 1); stringB = writer.getBuffer().toString(); assertTrue(stringB, stringB.contains("#Cm_Group[methylated]=1;")); assertTrue(stringB, stringB.contains("#C_Group[methylated]=1;")); assertTrue(stringB, stringB.contains("#Cm_Group[not-so]=0;")); assertTrue(stringB, stringB.contains("#C_Group[not-so]=0;")); /* org.junit.Assert.assertEquals("content must match", header+ "ref-id\t1\t\tC\tA,T,N\t\t\tBIOMART_COORDS=ref-id:1:1;Strand=+;LOD[methylated/not-so]=NaN;LOD_SE[methylated/not-so]=NaN;LOD_Z[methylated/not-so]=NaN;FisherP[methylated/not-so]=NaN;#C Group[methylated]=0;#Cm Group[methylated]=1;#C Group[not-so]=0;#Cm Group[not-so]=0;DP=1\tMR:GT:BC:GB:FB\t100:0/1/2/3:A=5,T=1,C=9,G=0,N=1:16:0\t0:1/2/3:A=10,T=4,C=0,G=0,N=2:16:0", buffer.toString()); */ }
From source file:org.yamj.api.common.http.AbstractPoolingHttpClient.java
protected DigestedResponse readContent(final HttpResponse response, final Charset charset) throws IOException { StringWriter content = new StringWriter(SW_BUFFER_10K); InputStream is = response.getEntity().getContent(); InputStreamReader isr = null; BufferedReader br = null;//from w w w. j a v a 2 s .c o m final DigestedResponse digestedResponse = new DigestedResponse(); digestedResponse.setStatusCode(response.getStatusLine().getStatusCode()); try { if (charset == null) { isr = new InputStreamReader(is, Charset.defaultCharset()); } else { isr = new InputStreamReader(is, charset); } br = new BufferedReader(isr); String line = br.readLine(); while (line != null) { content.write(line); line = br.readLine(); } content.flush(); digestedResponse.setContent(content.toString()); return digestedResponse; } finally { if (br != null) { try { br.close(); } catch (IOException ex) { LOG.trace("Failed to close BufferedReader", ex); } } if (isr != null) { try { isr.close(); } catch (IOException ex) { LOG.trace("Failed to close InputStreamReader", ex); } } try { content.close(); } catch (IOException ex) { LOG.trace("Failed to close StringWriter", ex); } try { is.close(); } catch (IOException ex) { LOG.trace("Failed to close InputStream", ex); } } }
From source file:de.qucosa.webapi.v1.DocumentResource.java
private void debugDump(DigitalObjectDocument dod) { try {/*from ww w . j av a2s. c o m*/ StringWriter stringWriter = new StringWriter(); dod.save(stringWriter, new XmlOptions().setSavePrettyPrint()); stringWriter.flush(); log.debug(stringWriter.toString()); } catch (IOException e) { log.warn("Debug error: {}", e.getMessage()); } }