List of usage examples for java.io StringWriter close
public void close() throws IOException
From source file:org.mule.transport.sap.transformer.JcoFunctionToXmlTransformer.java
/** * Describe <code>transform</code> method here. * * @param obj an <code>Object</code> value * @return an <code>Object</code> value * @exception XMLStreamException if an error occurs *//*from ww w. jav a 2 s.co m*/ public Object transform(Object obj, String encoding) throws XMLStreamException { // getting JCoFunction object JCoFunction function = (JCoFunction) obj; factory = XMLOutputFactory.newInstance(); eventFactory = XMLEventFactory.newInstance(); StringWriter stringWriter = new StringWriter(); String result = null; try { // getting instance of writer writer = factory.createXMLEventWriter(stringWriter); // writing start document writeStartDocument(writer); // writing JCO start element writeCharacters(writer, "\n"); writeStartElement(writer, MessageConstants.JCO); // writing NAME writeAttribute(writer, MessageConstants.JCO_ATTR_NAME, function.getName()); // writing TIMESTAMP writeAttribute(writer, MessageConstants.JCO_ATTR_TIMESTAMP, String.valueOf(new Date().getTime())); // writing VERSION writeAttribute(writer, MessageConstants.JCO_ATTR_VERSION, MessageConstants.JCO_ATTR_VERSION_VALUE); // writing Import writeCharacters(writer, "\n"); writeImportElement(writer, function); // writing Export writeCharacters(writer, "\n "); writeExportElement(writer, function); // writing Tables writeCharacters(writer, "\n"); writeTablesElement(writer, function); // writing Errors writeCharacters(writer, "\n "); writeErrorElement(writer, function.getExceptionList()); // writing JCO end element writeEndElement(writer, MessageConstants.JCO); // close document writeEndDocument(writer); writer.flush(); result = stringWriter.toString(); } catch (XMLStreamException ex) { throw ex; } finally { // close if (writer != null) { try { writer.close(); } catch (XMLStreamException ex) { } } if (stringWriter != null) { try { stringWriter.close(); } catch (IOException ex) { } } } return result; }
From source file:org.apache.axis.message.MessageElement.java
/** * get the message element as a string./*www . j a v a 2 s . com*/ * This is not a cheap operation, as we have to serialise the * entire message element to the current context, then * convert it to a string. * Nor is it cached; repeated calls repeat the operation. * @return an XML fragment in a string. * @throws Exception if anything went wrong */ public String getAsString() throws Exception { SerializationContext serializeContext = null; StringWriter writer = new StringWriter(); MessageContext msgContext; if (context != null) { msgContext = context.getMessageContext(); } else { msgContext = MessageContext.getCurrentContext(); } serializeContext = new SerializationContext(writer, msgContext); serializeContext.setSendDecl(false); setDirty(false); output(serializeContext); writer.close(); return writer.getBuffer().toString(); }
From source file:org.wso2.carbon.ml.core.impl.MLModelHandler.java
/** * Append version attribute to pmml (temporary fix) * * @param pmmlString the pmml string to be appended * @return PMML with version as a String * @throws MLPmmlExportException// ww w . j a v a 2 s. c om */ private String appendVersionToPMML(String pmmlString) throws MLPmmlExportException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; StringWriter stringWriter = null; try { //convert the string to xml to append the version attribute builder = factory.newDocumentBuilder(); Document document = builder.parse(new InputSource(new StringReader(pmmlString))); Element root = document.getDocumentElement(); root.setAttribute("version", "4.2"); // convert it back to string stringWriter = new StringWriter(); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.transform(new DOMSource(document), new StreamResult(stringWriter)); return stringWriter.toString(); } catch (Exception e) { String msg = "Error while appending version attribute to pmml"; log.error(msg, e); throw new MLPmmlExportException(msg); } finally { try { if (stringWriter != null) { stringWriter.close(); } } catch (IOException e) { String msg = "Error while closing stringWriter stream resource"; log.error(msg, e); throw new MLPmmlExportException(msg); } } }
From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.latex2html.PandocLatexToHtmlConverter.java
@Override public Document convert(File tex, String title) { logger.debug("Start convert() with file " + tex.toPath().toAbsolutePath().toString() + ", title: " + title); CommandLine cmdLine;/*from w ww . j av a2 s . c o m*/ if (execPath != null) { // Run the configured pandoc executable logger.info("Pandoc will be run from: " + execPath.toString()); cmdLine = new CommandLine(execPath.toFile()); } else { // Run in system PATH environment logger.info("Pandoc will be run within the PATH variable."); cmdLine = new CommandLine("pandoc"); } cmdLine.addArgument("--from=latex"); cmdLine.addArgument("--to=html5"); cmdLine.addArgument("--asciimathml"); // With this option, pandoc does not render latex formulas cmdLine.addArgument("${file}"); HashMap<String, Path> map = new HashMap<String, Path>(); map.put("file", Paths.get(tex.toURI())); cmdLine.setSubstitutionMap(map); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000); // max execution time 1 minute Executor executor = new DefaultExecutor(); executor.setExitValue(1); executor.setWatchdog(watchdog); StringWriter writer = new StringWriter(); WriterOutputStream writerOutputStream = new WriterOutputStream(writer, Charset.forName("UTF-8")); ExecuteStreamHandler pandocStreamHandler = new PumpStreamHandler(writerOutputStream, System.err); executor.setStreamHandler(pandocStreamHandler); logger.debug("Launching pandoc:"); logger.debug(cmdLine.toString()); try { executor.execute(cmdLine, resultHandler); } catch (IOException e) { logger.error("Pandoc's execution failed, exiting..."); logger.error(e.getMessage(), e); System.exit(-1); } try { resultHandler.waitFor(); int exitValue = resultHandler.getExitValue(); logger.debug("Pandoc execution's exit value: " + exitValue); ExecuteException executeException = resultHandler.getException(); if (executeException != null && executeException.getCause() != null) { String exceptionKlass = executeException.getCause().getClass().getCanonicalName(); String exceptionMessage = executeException.getCause().getMessage(); if (exceptionKlass.endsWith("IOException") || exceptionMessage.contains("Cannot run program \"pandoc\"")) { logger.error("Pandoc could not be found! Exiting..."); logger.debug(executeException); System.exit(1); } logger.debug(exceptionKlass + ": " + exceptionMessage); } } catch (InterruptedException e) { logger.error("pandoc conversion thread got interrupted, exiting..."); logger.error(e.getMessage(), e); System.exit(1); } // add html document structure to output // pandoc returns no document markup (html, head, body) // therefore we have to use a template String htmlOutput = "<!DOCTYPE html>\n" + "<html>\n" + "<head>\n" + // set title "<title>" + title + "</title>\n" + // include css "<link rel=\"stylesheet\" type=\"text/css\" href=\"main.css\"></link>\n" + "</head>\n" + "<body>"; try { htmlOutput += writer.getBuffer().toString(); writer.close(); } catch (IOException e) { logger.error("Error reading html result from StringBuffer..."); logger.error(e.getMessage(), e); System.exit(1); } // Close tags in template htmlOutput += "</body>\n" + "</html>"; // output loading as JDOM Document SAXBuilder sax = new SAXBuilder(); Document document = null; try { document = sax.build(new StringReader(htmlOutput)); } catch (JDOMException e) { logger.error("JDOM Parsing error"); logger.error(e.getMessage(), e); System.exit(1); } catch (IOException e) { logger.error("Error reading from String..."); logger.error(e.getMessage(), e); System.exit(1); } return document; }
From source file:org.nuxeo.ecm.diff.content.adapter.HtmlContentDiffer.java
public List<Blob> getContentDiff(Blob leftBlob, Blob rightBlob, Locale locale) throws ContentDiffException { try {/*from w w w. j a va2 s . c o m*/ List<Blob> blobResults = new ArrayList<Blob>(); StringWriter sw = new StringWriter(); SAXTransformerFactory stf = (SAXTransformerFactory) TransformerFactory.newInstance(); TransformerHandler transformHandler = stf.newTransformerHandler(); transformHandler.setResult(new StreamResult(sw)); XslFilter htmlHeaderXslFilter = new XslFilter(); StringBuilder sb = new StringBuilder("xslfilter/htmldiffheader"); sb.append("_"); sb.append(locale.getLanguage()); sb.append(".xsl"); String htmlHeaderXslPath = sb.toString(); ContentHandler postProcess; try { postProcess = htmlHeaderXslFilter.xsl(transformHandler, htmlHeaderXslPath); } catch (IllegalStateException ise) { LOGGER.error(String.format( "Could not find the HTML diff header xsl file '%s', falling back on the default one.", htmlHeaderXslPath), ise); postProcess = htmlHeaderXslFilter.xsl(transformHandler, "xslfilter/htmldiffheader.xsl"); } String prefix = "diff"; HtmlCleaner cleaner = new HtmlCleaner(); InputSource leftIS = new InputSource(leftBlob.getStream()); InputSource rightIS = new InputSource(rightBlob.getStream()); DomTreeBuilder leftHandler = new DomTreeBuilder(); cleaner.cleanAndParse(leftIS, leftHandler); TextNodeComparator leftComparator = new TextNodeComparator(leftHandler, locale); DomTreeBuilder rightHandler = new DomTreeBuilder(); cleaner.cleanAndParse(rightIS, rightHandler); TextNodeComparator rightComparator = new TextNodeComparator(rightHandler, locale); postProcess.startDocument(); postProcess.startElement("", "diffreport", "diffreport", new AttributesImpl()); postProcess.startElement("", "diff", "diff", new AttributesImpl()); HtmlSaxDiffOutput output = new HtmlSaxDiffOutput(postProcess, prefix); HTMLDiffer differ = new HTMLDiffer(output); differ.diff(leftComparator, rightComparator); postProcess.endElement("", "diff", "diff"); postProcess.endElement("", "diffreport", "diffreport"); postProcess.endDocument(); String stringBlob = sw.toString().replaceAll(NUXEO_DEFAULT_CONTEXT_PATH, VirtualHostHelper.getContextPathProperty()); Blob mainBlob = Blobs.createBlob(stringBlob); sw.close(); mainBlob.setFilename("contentDiff.html"); mainBlob.setMimeType("text/html"); blobResults.add(mainBlob); return blobResults; } catch (Exception e) { throw new ContentDiffException(e); } }
From source file:com.moviejukebox.tools.WebBrowser.java
@SuppressWarnings("resource") public String request(URL url, Charset charset) throws IOException { LOG.debug("Requesting {}", url.toString()); // get the download limit for the host ThreadExecutor.enterIO(url);// www .ja v a2 s .c o m StringWriter content = new StringWriter(10 * 1024); try { URLConnection cnx = null; try { cnx = openProxiedConnection(url); sendHeader(cnx); readHeader(cnx); InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; try (InputStream inputStream = cnx.getInputStream()) { // If we fail to get the URL information we need to exit gracefully if (charset == null) { inputStreamReader = new InputStreamReader(inputStream, getCharset(cnx)); } else { inputStreamReader = new InputStreamReader(inputStream, charset); } bufferedReader = new BufferedReader(inputStreamReader); String line; while ((line = bufferedReader.readLine()) != null) { content.write(line); } // Attempt to force close connection // We have HTTP connections, so these are always valid content.flush(); } catch (FileNotFoundException ex) { LOG.error("URL not found: {}", url.toString()); } catch (IOException ex) { LOG.error("Error getting URL {}, {}", url.toString(), ex.getMessage()); } finally { // Close resources if (bufferedReader != null) { try { bufferedReader.close(); } catch (Exception ex) { /* ignore */ } } if (inputStreamReader != null) { try { inputStreamReader.close(); } catch (Exception ex) { /* ignore */ } } } } catch (SocketTimeoutException ex) { LOG.error("Timeout Error with {}", url.toString()); } finally { if (cnx != null) { if (cnx instanceof HttpURLConnection) { ((HttpURLConnection) cnx).disconnect(); } } } return content.toString(); } finally { content.close(); ThreadExecutor.leaveIO(); } }
From source file:org.energy_home.jemma.ah.internal.hac.lib.HacService.java
protected String doc2xmlString(Document doc) { final String XML_VERSION = "1.0"; final String XML_ENCODING = "UTF-8"; StringWriter strWriter = null; XMLSerializer probeMsgSerializer = null; OutputFormat outFormat = null;/*from w w w . j a v a 2s. c om*/ String xmlStr = null; try { probeMsgSerializer = new XMLSerializer(); strWriter = new StringWriter(); outFormat = new OutputFormat(); // Setup format settings outFormat.setEncoding(XML_ENCODING); outFormat.setVersion(XML_VERSION); outFormat.setIndenting(true); outFormat.setIndent(4); // Define a Writer probeMsgSerializer.setOutputCharStream(strWriter); // Apply the format settings probeMsgSerializer.setOutputFormat(outFormat); // Serialize XML Document probeMsgSerializer.serialize(doc); xmlStr = strWriter.toString(); strWriter.close(); } catch (IOException ioEx) { LOG.error("exception: " + ioEx); return null; } return xmlStr; }
From source file:org.kepler.objectmanager.ActorMetadata.java
/** * try to locate and parse a moml file as a class *//*from ww w . j a v a2 s. c o m*/ protected ComponentEntity parseMoMLFile(String className) throws Exception { if (isDebugging) log.debug("parseMoMLFile(" + className + ")"); JarFile jarFile = null; InputStream xmlStream = null; try { // first we need to find the file and read it File classFile = searchClasspath(className); StringWriter sw = new StringWriter(); if (classFile.getName().endsWith(".jar")) { jarFile = new JarFile(classFile); ZipEntry entry = jarFile.getEntry(className.replace('.', '/') + ".xml"); xmlStream = jarFile.getInputStream(entry); } else { xmlStream = new FileInputStream(classFile); } byte[] b = new byte[1024]; int numread = xmlStream.read(b, 0, 1024); while (numread != -1) { String s = new String(b, 0, numread); sw.write(s); numread = xmlStream.read(b, 0, 1024); } sw.flush(); // get the moml document String xmlDoc = sw.toString(); sw.close(); if (isDebugging) log.debug("**** MoMLParser ****"); // use the moml parser to parse the doc MoMLParser parser = new MoMLParser(); parser.reset(); // System.out.println("processing " + className); NamedObj obj = parser.parse(xmlDoc); return (ComponentEntity) obj; } finally { if (jarFile != null) { jarFile.close(); } if (xmlStream != null) { xmlStream.close(); } } }
From source file:com.amalto.workbench.utils.Util.java
public static String formatXsdSource(String xsdSource, boolean suppressDeclaration) { try {/* w w w. ja va2 s .c om*/ SAXReader reader = new SAXReader(); org.dom4j.Document document = reader.read(new StringReader(xsdSource)); StringWriter writer = new StringWriter(); OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("UTF-8");//$NON-NLS-1$ format.setSuppressDeclaration(suppressDeclaration); XMLWriter xmlwriter = new XMLWriter(writer, format); xmlwriter.write(document); String str = writer.toString(); writer.close(); xmlwriter.close(); return str; } catch (Exception e) { log.error(e.getMessage(), e); } return xsdSource; }
From source file:org.apache.axis.client.Call.java
/** * Invoke this Call with its established MessageContext * (perhaps because you called this.setRequestMessage()) * * Note: Not part of JAX-RPC specification. * * @exception AxisFault//from w ww . ja v a 2s .c o m */ public void invoke() throws AxisFault { if (log.isDebugEnabled()) { log.debug("Enter: Call::invoke()"); } isNeverInvoked = false; Message reqMsg = null; SOAPEnvelope reqEnv = null; msgContext.reset(); msgContext.setResponseMessage(null); msgContext.setProperty(MessageContext.CALL, this); msgContext.setProperty(WSDL_SERVICE, service); msgContext.setProperty(WSDL_PORT_NAME, getPortName()); if (isMsg) { msgContext.setProperty(MessageContext.IS_MSG, "true"); } if (username != null) { msgContext.setUsername(username); } if (password != null) { msgContext.setPassword(password); } msgContext.setMaintainSession(maintainSession); if (operation != null) { msgContext.setOperation(operation); operation.setStyle(getOperationStyle()); operation.setUse(getOperationUse()); } if (useSOAPAction) { msgContext.setUseSOAPAction(true); } if (SOAPActionURI != null) { msgContext.setSOAPActionURI(SOAPActionURI); } else { msgContext.setSOAPActionURI(null); } if (timeout != null) { msgContext.setTimeout(timeout.intValue()); } msgContext.setHighFidelity(!useStreaming); // Determine client target service if (myService != null) { // If we have a SOAPService kicking around, use that directly msgContext.setService(myService); } else { if (portName != null) { // No explicit service. If we have a target service name, // try that. msgContext.setTargetService(portName.getLocalPart()); } else { // No direct config, so try the namespace of the first body. reqMsg = msgContext.getRequestMessage(); boolean isStream = ((SOAPPart) reqMsg.getSOAPPart()).isBodyStream(); if (reqMsg != null && !isStream) { reqEnv = reqMsg.getSOAPEnvelope(); SOAPBodyElement body = reqEnv.getFirstBody(); if (body != null) { if (body.getNamespaceURI() == null) { throw new AxisFault("Call.invoke", Messages.getMessage("cantInvoke00", body.getName()), null, null); } else { msgContext.setTargetService(body.getNamespaceURI()); } } } } } if (log.isDebugEnabled()) { log.debug(Messages.getMessage("targetService", msgContext.getTargetService())); } Message requestMessage = msgContext.getRequestMessage(); if (requestMessage != null) { try { msgContext.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, requestMessage.getProperty(SOAPMessage.CHARACTER_SET_ENCODING)); } catch (SOAPException e) { } if (myHeaders != null) { reqEnv = requestMessage.getSOAPEnvelope(); // If we have headers to insert, do so now. for (int i = 0; myHeaders != null && i < myHeaders.size(); i++) { reqEnv.addHeader((SOAPHeaderElement) myHeaders.get(i)); } } } // set up transport if there is one if (transport != null) { transport.setupMessageContext(msgContext, this, service.getEngine()); } else { msgContext.setTransportName(transportName); } SOAPService svc = msgContext.getService(); if (svc != null) { svc.setPropertyParent(myProperties); } else { msgContext.setPropertyParent(myProperties); } // For debugging - print request message if (log.isDebugEnabled()) { StringWriter writer = new StringWriter(); try { SerializationContext ctx = new SerializationContext(writer, msgContext); requestMessage.getSOAPEnvelope().output(ctx); writer.close(); } catch (Exception e) { throw AxisFault.makeFault(e); } finally { log.debug(writer.getBuffer().toString()); } } if (!invokeOneWay) { invokeEngine(msgContext); } else { invokeEngineOneWay(msgContext); } if (log.isDebugEnabled()) { log.debug("Exit: Call::invoke()"); } }