List of usage examples for java.io StringWriter close
public void close() throws IOException
From source file:org.acmsl.commons.utils.ThrowableUtils.java
/** * Retrieves given throwable's stack trace. * @param throwable the error to output. * @return its stack trace./* w w w . jav a2 s .c om*/ */ @SuppressWarnings("unused") @NotNull public String getStackTrace(@NotNull final Throwable throwable) { @NotNull final String result; @NotNull final StringWriter t_swResult = new StringWriter(); @NotNull final PrintWriter t_PrintWriter = new PrintWriter(t_swResult); throwable.printStackTrace(t_PrintWriter); result = t_swResult.toString(); t_PrintWriter.close(); try { t_swResult.close(); } catch (final IOException ioException) { LogFactory.getLog(ThrowableUtils.class).fatal("Strange and exceptional error", ioException); } return result; }
From source file:org.tequila.template.directive.freemarker.FileSection.java
@Override public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) { log.debug("Executing <@" + getDirectiveName() + " .../>"); // Check if params were given if (params.isEmpty()) { throw new DirectiveException( "<@" + getDirectiveName() + " .../> 'path, name' are required parameters."); }/* w w w .java2 s.co m*/ if (loopVars.length != 0) { throw new DirectiveException("<@" + getDirectiveName() + " .../> doesn't allow loop variables."); } // If there is non-empty nested content: if (body != null) { try { // Executes the nested body. Same as <#nested> in FTL, except // that we use our own writer instead of the current output writer. String path = null; String name = null; String appendBeforeLast = null; Set<Entry<String, SimpleScalar>> entrySet = params.entrySet(); for (Entry<String, SimpleScalar> entry : entrySet) { String key = entry.getKey(); SimpleScalar value = entry.getValue(); if (key.equals(PATH)) { path = value.getAsString(); } else if (key.equals(NAME)) { name = value.getAsString(); } else if (key.equals(APPEND_BEFORE_LAST)) { appendBeforeLast = value.getAsString(); } else { throw new DirectiveException( "<@" + getDirectiveName() + " .../> doesn't allow " + key + " parameter"); } } // write the file StringWriter sw = new StringWriter(); BufferedWriter bw = new BufferedWriter(sw); body.render(bw); env.getOut().flush(); bw.flush(); sw.flush(); bw.close(); sw.close(); TemplateProcessed tp = new TemplateProcessed(); tp.setTemplateResult(sw.toString()); tp.setOutputFolder(path); tp.setOutputFileName(name); // notificar a los observadores super.setChanged(); super.notifyObservers(tp); } catch (TemplateException ex) { throw new DirectiveException("Error al ejecutar la directiva '" + getDirectiveName() + "'", ex); } catch (IOException ex) { throw new DirectiveException("Error al ejecutar la directiva '" + getDirectiveName() + "'", ex); } } else { throw new DirectiveException("missing body"); } }
From source file:org.pepstock.jem.ant.validator.transformer.TransformerValidator.java
/** * Do the xsl transformation. During the transformation, the transformer * object is locked, so the file listner is inhibited to do a refresh of * transformer object// w w w. j a v a 2s. co m * * @param inXmlContent the in xml content * @throws ValidationException the validation exception */ private synchronized void transform(String inXmlContent) throws ValidationException { // sync is necessary to avoid concurrent access to transformer by file // listner synchronized (this) { StreamSource source = null; StreamResult result = null; try { // traverse the transformation, if some errors are found will be // generated some exceptions, otherwise do nothing InputStream is = new ByteArrayInputStream(inXmlContent.getBytes(CharSet.DEFAULT)); source = new StreamSource(is); // Use the Transformer to transform an XML Source and send the // output to a Result object. StringWriter sw = new StringWriter(); result = new StreamResult(sw); transformer.transform(source, result); sw.close(); } catch (TransformerConfigurationException e) { throw new ValidationException(e); } catch (TransformerException e) { throw new ValidationException(e.getMessageAndLocation(), e); } catch (Exception e) { throw new ValidationException(e); } } }
From source file:org.camunda.spin.impl.json.jackson.query.JsonPathJacksonProvider.java
public String toJson(Object obj) { StringWriter writer = new StringWriter(); try {/*ww w . ja v a2 s . c o m*/ JsonGenerator jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(writer); objectMapper.writeValue(jsonGenerator, obj); writer.close(); return writer.getBuffer().toString(); } catch (IOException e) { throw new InvalidJsonException(); } }
From source file:com.gmail.tracebachi.DeltaSkins.Shared.MojangApi.java
public JsonArray getUuids() throws IOException, RateLimitedException { synchronized (uuidRequestLock) { // If requests are empty, do not make a request if (uuidRequests.size() <= 0) { return new JsonArray(); }//from w w w. j a va 2s . com } String stringPayload = convertUuidRequestsToStringPayload(); HttpURLConnection httpConn = openNameToIdConnection(); httpConn.setRequestMethod("POST"); httpConn.setRequestProperty("Content-Type", "application/json"); OutputStream outputStream = httpConn.getOutputStream(); byte[] payload = stringPayload.getBytes(StandardCharsets.UTF_8); outputStream.write(payload); outputStream.flush(); outputStream.close(); plugin.debugApi("[Payload] " + stringPayload); if (httpConn.getResponseCode() == 429) { throw new RateLimitedException(); } StringWriter writer = new StringWriter(); InputStream inputStream = httpConn.getInputStream(); IOUtils.copy(inputStream, writer, StandardCharsets.UTF_8); inputStream.close(); String response = writer.toString(); writer.close(); plugin.debugApi("[Response] " + response); synchronized (parserLock) { return parser.parse(response).getAsJsonArray(); } }
From source file:Main.java
/** * Convert xml to string./* w w w. j av a2 s .c o m*/ * * @param pDocument * the p document * @param encoding * the encoding * @return the string * @throws Exception * the exception */ public static String convertXML2String(Document pDocument, String encoding) throws Exception { TransformerFactory transformerFactory = null; Transformer transformer = null; DOMSource domSource = null; StringWriter writer = new java.io.StringWriter(); StreamResult result = null; try { transformerFactory = TransformerFactory.newInstance(); if (transformerFactory == null) { throw new Exception("TransformerFactory error"); } transformer = transformerFactory.newTransformer(); if (transformer == null) { throw new Exception("Transformer error"); } if (encoding != null) { transformer.setOutputProperty(OutputKeys.ENCODING, encoding); } else { transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); } domSource = new DOMSource(pDocument); result = new StreamResult(writer); transformer.transform(domSource, result); return writer.toString(); } catch (TransformerFactoryConfigurationError e) { throw new Exception("TransformerFactoryConfigurationError", e); } catch (TransformerConfigurationException e) { throw new Exception("TransformerConfigurationException", e); } catch (TransformerException e) { throw new Exception("TransformerException", e); } finally { try { if (writer != null) { writer.close(); } } catch (IOException ex) { throw new Exception("IO error", ex); } } }
From source file:gdv.xport.satz.SatzTest.java
/** * Ein Export mit einem Teildatensatz sollte aus genau 256 Bytes bestehen, * da in der SetUp-Methode das EOD-Zeichen auf "" gesetzt wurde. * * @throws IOException//from w w w. j a v a 2s . c om * sollte nicht auftreten, da wir mit StringWriter arbeiten */ @Test public void testExport() throws IOException { StringWriter swriter = new StringWriter(256); satz.export(swriter, ""); swriter.close(); String content = swriter.toString(); assertEquals(256, content.length()); assertEquals(satz.getSatzartFeld().getInhalt(), content.substring(0, 4)); }
From source file:plugins.GerritTriggerTest.java
private String stringFrom(Process curl) throws InterruptedException, IOException { assertThat(curl.waitFor(), is(equalTo(0))); StringWriter writer = new StringWriter(); IOUtils.copy(curl.getInputStream(), writer); String string = writer.toString().replaceAll(System.getProperty("line.separator"), "").replaceAll(" ", ""); writer.close(); return string; }
From source file:org.broadleafcommerce.openadmin.web.resource.MessagesResourceResolver.java
protected String getResourceContents(Resource resource) throws IOException { StringWriter writer = null; String contents;/*from ww w. j a v a 2s . c om*/ try { writer = new StringWriter(); IOUtils.copy(resource.getInputStream(), writer, "UTF-8"); contents = writer.toString(); } finally { if (writer != null) { writer.flush(); writer.close(); } } return contents; }
From source file:org.broadleafcommerce.common.web.resource.AbstractGeneratedResourceHandler.java
/** * @param resource//from ww w . j a v a 2 s . c o m * @return the UTF-8 String represetation of the contents of the resource */ protected String getResourceContents(Resource resource) throws IOException { StringWriter writer = null; try { writer = new StringWriter(); IOUtils.copy(resource.getInputStream(), writer, "UTF-8"); return writer.toString(); } finally { if (writer != null) { writer.flush(); writer.close(); } } }