Example usage for java.io StringWriter StringWriter

List of usage examples for java.io StringWriter StringWriter

Introduction

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

Prototype

public StringWriter() 

Source Link

Document

Create a new string writer using the default initial string-buffer size.

Usage

From source file:Main.java

public static String sourceToXMLString(Source result) {

    String xmlResult = null;//  w  w w  .  j a  va2 s . c  om
    try {
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();
        //transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        StringWriter out = new StringWriter();
        StreamResult streamResult = new StreamResult(out);
        transformer.transform(result, streamResult);
        xmlResult = streamResult.getWriter().toString();
    } catch (TransformerException e) {
        e.printStackTrace();
    }

    return xmlResult;
}

From source file:Main.java

public static String getXMLString(Element elm, boolean htmlMode) throws TransformerException {
    /* TODO: Certain HTML entities, like "⇒", currently seem impossible to represent, as the
         HTML mode will output them in a named form unsupported by the Swing HTML parser
         (e.g. "⇐"). *//*  w  w  w . java2 s  . c  o m*/
    Transformer t;
    t = TransformerFactory.newInstance().newTransformer();
    t.setOutputProperty(OutputKeys.METHOD, htmlMode ? "html" : "xml");
    t.setOutputProperty(OutputKeys.INDENT, "no");
    t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, htmlMode ? "yes" : "no");
    StringWriter ret = new StringWriter();
    t.transform(new DOMSource(elm), new StreamResult(ret));
    return ret.toString();
}

From source file:Main.java

/**
 * Makes a tag string readable when rendered in HTML. The method
 * escapes all the angle brackets and inserts spaces before and
 * after tags so a browser will wrap the text correctly.
 * This method is used in many places to return an XML string to the
 * user in the event of an error./*from w  w  w.ja  va2  s  .c  o m*/
 * @param tagString the string containing XML tags.
 * @return the readable tag string, or "null" if tagString is null.
 */
public static String makeReadableTagString(String tagString) {
    if (tagString == null)
        return "null";
    StringWriter sw = new StringWriter();
    char c;
    for (int i = 0; i < tagString.length(); i++) {
        c = tagString.charAt(i);
        if (c == '<')
            sw.write(" &#60;"); //note the leading space
        else if (c == '>')
            sw.write("&#62; "); //note the trailing space
        else if (c == '&')
            sw.write("&#38;");
        else if (c == '\"')
            sw.write("&#34;");
        else
            sw.write(c);
    }
    return sw.toString();
}

From source file:Main.java

public static String setAttribute(String xmlStr, String tagName, String attrName, String newValue) {
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(false); // never forget this!
    int i, j;//from w  w w . ja v a 2  s  .  co m
    Document doc = null;
    DocumentBuilder builder = null;

    StringWriter stringOut = new StringWriter();
    try {
        builder = domFactory.newDocumentBuilder();
        doc = builder.parse(new ByteArrayInputStream(xmlStr.getBytes()));
        // Get the root element
        Node rootNode = doc.getFirstChild();
        NodeList nodeList = doc.getElementsByTagName(tagName);
        if ((nodeList.getLength() == 0) || (nodeList.item(0).getAttributes().getNamedItem(attrName) == null)) {
            logger.error("Either node " + tagName + " or attribute " + attrName + " not found.");
        } else {
            logger.debug("value of " + tagName + " attribute: " + attrName + " = "
                    + nodeList.item(0).getAttributes().getNamedItem(attrName).getNodeValue());
            nodeList.item(0).getAttributes().getNamedItem(attrName).setNodeValue(newValue);

            // write the content into xml file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(stringOut);
            // StreamResult result = new StreamResult(new File(filepath));
            transformer.transform(source, result);
            logger.debug("Updated XML: \n" + stringOut.toString());
        }
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }

    return stringOut.toString();
}

From source file:Main.java

protected static Result internalTransform(InputStream doc, Templates templates, Result r, boolean trace) {
    StringWriter sw = new StringWriter();

    try {//from www  .  j  a v a 2  s  .com
        Transformer transformer = templates.newTransformer();

        transformer.transform(new StreamSource(doc), r);

        sw.close();
        return r;
    } catch (Throwable th) {
        th.printStackTrace();
        return r;
    }

}

From source file:Main.java

/**
 * Uses a TransformerFactory with an identity transformation to convert a
 * Document into a String representation of the XML.
 *
 * @param document Document.//from w  w w.  j  ava  2  s.c  o  m
 * @return An XML String.
 * @throws IOException if an error occurs during transformation.
 */
public static String documentToString(Document document) throws IOException {
    String xml = null;

    try {
        DOMSource dom = new DOMSource(document);
        StringWriter writer = new StringWriter();
        StreamResult output = new StreamResult(writer);

        // Use Transformer to serialize a DOM
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();

        // No need for pretty printing
        transformer.setOutputProperty(OutputKeys.INDENT, INDENT_XML);

        // XML Declarations unexpected whitespace for legacy AS XMLDocument type,
        // so we always omit it. We can't tell whether one was present when
        // constructing the Document in the first place anyway...
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, OMIT_XML_DECLARATION);

        transformer.transform(dom, output);

        xml = writer.toString();
    } catch (TransformerException te) {
        throw new IOException("Error serializing Document as String: " + te.getMessageAndLocation());
    }
    return xml;
}

From source file:Main.java

public static String nodeToString(Node n, boolean isOmitXmlDeclaration, boolean isIndent)
        throws TransformerException {
    StringWriter sw = new StringWriter();
    Transformer transformer = generateTransformer(isOmitXmlDeclaration, isIndent);
    transformer.transform(new DOMSource(n), new StreamResult(sw));
    return sw.toString();
}

From source file:Main.java

public static String serialize(Document document, boolean prettyPrint) {
    DOMImplementationLS impl = getDOMImpl();
    LSSerializer serializer = impl.createLSSerializer();
    // document.normalizeDocument();
    DOMConfiguration config = serializer.getDomConfig();
    if (prettyPrint && config.canSetParameter("format-pretty-print", Boolean.TRUE)) {
        config.setParameter("format-pretty-print", true);
    }/*  w  w  w  .  j a  va2 s  .c  om*/
    config.setParameter("xml-declaration", true);
    LSOutput output = impl.createLSOutput();
    output.setEncoding("UTF-8");
    Writer writer = new StringWriter();
    output.setCharacterStream(writer);
    serializer.write(document, output);
    return writer.toString();
}

From source file:Main.java

public static String toString(Throwable e) {
    StringWriter w = new StringWriter();
    PrintWriter p = new PrintWriter(w);
    p.print(e.getClass().getName() + ": ");
    if (e.getMessage() != null) {
        p.print(e.getMessage() + "\n");
    }/*from w  w w.  j ava  2s . c om*/
    p.println();
    try {
        e.printStackTrace(p);
        return w.toString();
    } finally {
        p.close();
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.web.directives.BaseTemplateDirectiveModel.java

public static String processTemplateToString(String templateName, Map<String, Object> map, Environment env) {
    Template template = getTemplate(templateName, env);
    StringWriter sw = new StringWriter();
    try {//from   w w  w  . j  ava 2s .  co  m
        template.process(map, sw);
    } catch (TemplateException e) {
        log.error("Template Exception creating processing environment", e);
    } catch (IOException e) {
        log.error("IOException creating processing environment", e);
    }
    return sw.toString();
}