Example usage for java.io StringWriter close

List of usage examples for java.io StringWriter close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closing a StringWriter has no effect.

Usage

From source file:com.intuit.tank.transform.scriptGenerator.ConverterUtil.java

public static String getWorkloadXML(HDWorkload hdWorkload) {
    StringWriter sw;
    try {/*from   w  w w  . java2 s. co m*/
        JAXBContext context = JAXBContext.newInstance(HDWorkload.class.getPackage().getName());
        Marshaller createMarshaller = context.createMarshaller();
        createMarshaller.setProperty("jaxb.formatted.output", Boolean.TRUE);
        sw = new StringWriter();
        createMarshaller.marshal(hdWorkload, sw);
        sw.flush();
        sw.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
    return sw.toString();

}

From source file:nl.ellipsis.webdav.server.util.XMLHelper.java

public static String format(Document document) {
    String retval = null;/*from  w w  w  . ja  v a2  s .  c om*/
    if (document != null) {
        TransformerFactory transfac = TransformerFactory.newInstance();
        StringWriter sw = null;
        try {
            Transformer transformer = transfac.newTransformer();

            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");

            //create string from xml tree
            sw = new StringWriter();
            StreamResult result = new StreamResult(sw);

            DOMSource source = new DOMSource(document);

            transformer.transform(source, result);

            retval = sw.toString();
        } catch (TransformerException e) {
            e.printStackTrace();
        } finally {
            try {
                sw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return retval;
}

From source file:com.amalto.workbench.utils.XmlUtil.java

public static String format(Document document, OutputFormat format, String encoding) {

    StringWriter writer = new StringWriter();

    format.setEncoding(encoding);// w ww  . ja  va  2  s .  c  o  m

    format.setNewLineAfterDeclaration(false);
    // format.setSuppressDeclaration(suppressDeclaration);

    XMLWriter xmlwriter = new XMLWriter(writer, format);

    String result = ""; //$NON-NLS-1$

    try {

        xmlwriter.write(document);
        result = writer.toString().replaceAll("<\\?xml.*?\\?>", "").trim();//$NON-NLS-1$//$NON-NLS-2$
    } catch (Exception e) {
        log.error(e.getMessage(), e);

    } finally {
        try {
            if (xmlwriter != null)
                xmlwriter.close();

            if (writer != null)
                writer.close();
        } catch (IOException e) {

        }
    }

    return result;
}

From source file:Main.java

/**
 * Convert XML DOM document to a XML string representation
 *
 * @param doc/*from w ww  . j a  v  a2  s .  c o m*/
 *            XML DOM document
 * @return XML string
 * @throws Exception
 *             in error case
 */
public static String xmlDOMDocumentToString(Document doc) throws Exception {
    if (doc == null) {
        throw new RuntimeException("No XML DOM document (null)!");
    }
    StringWriter stringWriter = new StringWriter();
    String strDoc = null;

    try {
        StreamResult streamResult = new StreamResult(stringWriter);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        // transformerFactory.setAttribute("nIndent-number", new Integer(4));
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.transform(new DOMSource(doc.getDocumentElement()), streamResult);
        stringWriter.flush();
        strDoc = stringWriter.toString();
    } catch (Exception e) {
        //            Logger.XMLEval.logState("Parsing of XML DOM document failed: " + e.getMessage(), LogLevel.Error);
        throw e;
    } finally {
        if (stringWriter != null) {
            stringWriter.close();
            stringWriter = null;
        }
    }

    return strDoc;
}

From source file:org.firstopen.singularity.util.XMLUtil.java

public static String generateXMLFromDoc(Document doc) {

    String XML_VERSION = "1.0";
    String XML_ENCODING = "UTF-8";
    String xml = null;//  w w  w.  j av a  2  s.c o  m
    StringWriter strWriter = null;
    XMLSerializer probeMsgSerializer = null;
    OutputFormat outFormat = null;

    try {
        probeMsgSerializer = new XMLSerializer();
        probeMsgSerializer.setNamespaces(true);
        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);
        xml = strWriter.toString();
        strWriter.close();

    } catch (IOException ioEx) {
        log.error("Error ", ioEx);
    }

    return xml;
}

From source file:org.sipfoundry.sipxconfig.admin.dialplan.config.XmlFile.java

/**
 * Retrieves configuration file content as string depending on the location
 *
 * Use only for preview, use write function to dump it to the file.
 *
 *///from w  w w .ja va 2 s .co  m
public String getFileContent(Location location) {
    try {
        StringWriter writer = new StringWriter();
        write(writer, location);
        writer.close();
        return writer.toString();
    } catch (IOException e) {
        // ignore when writing to string
        LogFactory.getLog(XmlFile.class).error("Ignoring exception", e);
        return "";
    }
}

From source file:org.teavm.html4j.JavaScriptResourceInterceptor.java

@Override
public void begin(RenderingManager manager, BuildTarget buildTarget) throws IOException {
    boolean hasOneResource = false;
    for (String className : manager.getClassSource().getClassNames()) {
        ClassReader cls = manager.getClassSource().get(className);
        AnnotationReader annot = cls.getAnnotations().get(JavaScriptResource.class.getName());
        if (annot == null) {
            continue;
        }/*from   w  ww  .  j  av  a 2s  . com*/
        String path = annot.getValue("value").getString();
        String packageName = className.substring(0, className.lastIndexOf('.'));
        String resourceName = packageName.replace('.', '/') + "/" + path;
        try (InputStream input = manager.getClassLoader().getResourceAsStream(resourceName)) {
            if (input == null) {
                throw new RenderingException("Error processing JavaScriptResource annotation on class "
                        + className + ". Resource not found: " + resourceName);
            }
            StringWriter writer = new StringWriter();
            IOUtils.copy(input, writer);
            writer.close();
            manager.getWriter().append("// Resource " + path + " included by " + className).newLine();
            manager.getWriter().append(writer.toString()).newLine().newLine();
        }
        hasOneResource = true;
    }
    if (hasOneResource) {
        manager.getWriter().append("// TeaVM generated classes").newLine();
    }
}

From source file:org.globus.gsi.bc.BouncyCastleOpenSSLKeyTest.java

private String toString(OpenSSLKey key) throws Exception {
    StringWriter writer = new StringWriter();
    key.writeTo(writer);//from   w  w  w. j  ava  2s.co m
    writer.close();
    String s = writer.toString();
    logger.debug(s);
    return s;
}

From source file:org.apiwatch.util.IO.java

public static void putAPIData(APIScope scope, String format, String encoding, String location, String username,
        String password) throws SerializationError, IOException, HttpException {
    if (URL_RX.matcher(location).matches()) {
        DefaultHttpClient client = new DefaultHttpClient();
        if (username != null && password != null) {
            client.getCredentialsProvider().setCredentials(new AuthScope(null, -1),
                    new UsernamePasswordCredentials(username, password));
        }/*  www . j a v a 2  s  . com*/
        HttpPost req = new HttpPost(location);
        StringWriter writer = new StringWriter();
        Serializers.dumpAPIScope(scope, writer, format);
        HttpEntity entity = new StringEntity(writer.toString(), encoding);
        req.setEntity(entity);
        req.setHeader("content-type", format);
        req.setHeader("content-encoding", encoding);
        HttpResponse response = client.execute(req);
        client.getConnectionManager().shutdown();
        if (response.getStatusLine().getStatusCode() >= 400) {
            throw new HttpException(response.getStatusLine().getReasonPhrase());
        }
        LOGGER.info("Sent results to URL: " + location);
    } else {
        File dir = new File(location);
        dir.mkdirs();
        File file = new File(dir, "api." + format);
        OutputStream out = new FileOutputStream(file);
        Writer writer = new OutputStreamWriter(out, encoding);
        Serializers.dumpAPIScope(scope, writer, format);
        writer.flush();
        writer.close();
        out.close();
        LOGGER.info("Wrote results to file: " + file);
    }
}

From source file:org.calrissian.mango.json.deser.NodeDeserializerTest.java

@Test
public void testEqDeserialize() throws Exception {
    String json = "{\"eq\":{\"key\":\"k1\",\"type\":\"string\",\"value\":\"v1\"}}";
    Node node = objectMapper.readValue(json, Node.class);
    StringWriter writer = new StringWriter();
    node.accept(new PrintNodeVisitor(writer));
    writer.flush();//from  w ww.jav  a  2s  .  c o m
    writer.close();
    String eq = writer.toString();
    assertEquals("Equals[k1,v1],", eq);
}