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 StringBuffer transfer(Element element, StreamSource source) {
    try {/*from  ww  w .j a v  a  2  s .  com*/
        StringWriter sw = new StringWriter();
        Transformer trans = null;
        if (source != null)
            trans = TransformerFactory.newInstance().newTransformer(source);
        else
            trans = TransformerFactory.newInstance().newTransformer();
        trans.transform(new DOMSource(element), new StreamResult(sw));
        sw.close();
        return sw.getBuffer();
    } catch (TransformerConfigurationException e) {
        e.printStackTrace();
    } catch (TransformerFactoryConfigurationError e) {
        e.printStackTrace();
    } catch (TransformerException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:Main.java

public static <T> String toXml(T object) throws JAXBException {
    JAXBContext jaxbContext = JAXBContext.newInstance(object.getClass());
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    StringWriter writer = new StringWriter();
    marshaller.marshal(object, writer);/*from   www. j  a v a2  s  .  c  om*/
    return writer.toString();
}

From source file:Main.java

public static String xml2Str(Document document) {

    try {/*  www .ja v  a2 s .  c  o  m*/
        DOMSource source = new DOMSource(document);
        StringWriter writer = new StringWriter();
        Result result = new StreamResult(writer);
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.transform(source, result);
        return (writer.getBuffer().toString());

    } catch (Exception e) {
        e.printStackTrace();
    }

    return "";
}

From source file:Main.java

public static String xmlToString(Document doc) {
    try {/* w ww  .  j  a  v  a2  s.  c o m*/
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        StreamResult result = new StreamResult(new StringWriter());
        DOMSource source = new DOMSource(doc);
        transformer.transform(source, result);
        return result.getWriter().toString();
    } catch (TransformerException ex) {
        ex.printStackTrace();
    }
    return null;
}

From source file:Main.java

public static String format(Node node) throws TransformerException {
    final StringWriter writer = new StringWriter();
    format(new DOMSource(node), false, new StreamResult(writer));
    return writer.toString();
}

From source file:json_to_xml_1.java

public static void main(String args[]) {
    System.out.print("json_to_xml_1 workflow Copyright (C) 2016 Stephan Kreutzer\n"
            + "This program comes with ABSOLUTELY NO WARRANTY.\n"
            + "This is free software, and you are welcome to redistribute it\n"
            + "under certain conditions. See the GNU Affero General Public License 3\n"
            + "or any later version for details. Also, see the source code repository\n"
            + "https://github.com/publishing-systems/digital_publishing_workflow_tools/ and\n"
            + "the project website http://www.publishing-systems.org.\n\n");

    json_to_xml_1 converter = json_to_xml_1.getInstance();

    converter.getInfoMessages().clear();

    try {/* w  ww. j  a va  2s . c om*/
        converter.execute(args);
    } catch (ProgramTerminationException ex) {
        converter.handleTermination(ex);
    }

    if (converter.resultInfoFile != null) {
        try {
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(new FileOutputStream(converter.resultInfoFile), "UTF-8"));

            writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
            writer.write(
                    "<!-- This file was created by json_to_xml_1, which is free software licensed under the GNU Affero General Public License 3 or any later version (see https://github.com/publishing-systems/digital_publishing_workflow_tools/ and http://www.publishing-systems.org). -->\n");
            writer.write("<json-to-xml-1-result-information>\n");

            if (converter.getInfoMessages().size() <= 0) {
                writer.write("  <success/>\n");
            } else {
                writer.write("  <success>\n");
                writer.write("    <info-messages>\n");

                for (int i = 0, max = converter.getInfoMessages().size(); i < max; i++) {
                    InfoMessage infoMessage = converter.getInfoMessages().get(i);

                    writer.write("      <info-message number=\"" + i + "\">\n");
                    writer.write("        <timestamp>" + infoMessage.getTimestamp() + "</timestamp>\n");

                    String infoMessageText = infoMessage.getMessage();
                    String infoMessageId = infoMessage.getId();
                    String infoMessageBundle = infoMessage.getBundle();
                    Object[] infoMessageArguments = infoMessage.getArguments();

                    if (infoMessageBundle != null) {
                        // Ampersand needs to be the first, otherwise it would double-encode
                        // other entities.
                        infoMessageBundle = infoMessageBundle.replaceAll("&", "&amp;");
                        infoMessageBundle = infoMessageBundle.replaceAll("<", "&lt;");
                        infoMessageBundle = infoMessageBundle.replaceAll(">", "&gt;");

                        writer.write("        <id-bundle>" + infoMessageBundle + "</id-bundle>\n");
                    }

                    if (infoMessageId != null) {
                        // Ampersand needs to be the first, otherwise it would double-encode
                        // other entities.
                        infoMessageId = infoMessageId.replaceAll("&", "&amp;");
                        infoMessageId = infoMessageId.replaceAll("<", "&lt;");
                        infoMessageId = infoMessageId.replaceAll(">", "&gt;");

                        writer.write("        <id>" + infoMessageId + "</id>\n");
                    }

                    if (infoMessageText != null) {
                        // Ampersand needs to be the first, otherwise it would double-encode
                        // other entities.
                        infoMessageText = infoMessageText.replaceAll("&", "&amp;");
                        infoMessageText = infoMessageText.replaceAll("<", "&lt;");
                        infoMessageText = infoMessageText.replaceAll(">", "&gt;");

                        writer.write("        <message>" + infoMessageText + "</message>\n");
                    }

                    if (infoMessageArguments != null) {
                        writer.write("        <arguments>\n");

                        int argumentCount = infoMessageArguments.length;

                        for (int j = 0; j < argumentCount; j++) {
                            if (infoMessageArguments[j] == null) {
                                writer.write("          <argument number=\"" + j + "\">\n");
                                writer.write("            <class></class>\n");
                                writer.write("            <value>null</value>\n");
                                writer.write("          </argument>\n");

                                continue;
                            }

                            String className = infoMessageArguments[j].getClass().getName();

                            // Ampersand needs to be the first, otherwise it would double-encode
                            // other entities.
                            className = className.replaceAll("&", "&amp;");
                            className = className.replaceAll("<", "&lt;");
                            className = className.replaceAll(">", "&gt;");

                            String value = infoMessageArguments[j].toString();

                            // Ampersand needs to be the first, otherwise it would double-encode
                            // other entities.
                            value = value.replaceAll("&", "&amp;");
                            value = value.replaceAll("<", "&lt;");
                            value = value.replaceAll(">", "&gt;");

                            writer.write("          <argument number=\"" + j + "\">\n");
                            writer.write("            <class>" + className + "</class>\n");
                            writer.write("            <value>" + value + "</value>\n");
                            writer.write("          </argument>\n");
                        }

                        writer.write("        </arguments>\n");
                    }

                    Exception exception = infoMessage.getException();

                    if (exception != null) {
                        writer.write("        <exception>\n");

                        String className = exception.getClass().getName();

                        // Ampersand needs to be the first, otherwise it would double-encode
                        // other entities.
                        className = className.replaceAll("&", "&amp;");
                        className = className.replaceAll("<", "&lt;");
                        className = className.replaceAll(">", "&gt;");

                        writer.write("          <class>" + className + "</class>\n");

                        StringWriter stringWriter = new StringWriter();
                        PrintWriter printWriter = new PrintWriter(stringWriter);
                        exception.printStackTrace(printWriter);
                        String stackTrace = stringWriter.toString();

                        // Ampersand needs to be the first, otherwise it would double-encode
                        // other entities.
                        stackTrace = stackTrace.replaceAll("&", "&amp;");
                        stackTrace = stackTrace.replaceAll("<", "&lt;");
                        stackTrace = stackTrace.replaceAll(">", "&gt;");

                        writer.write("          <stack-trace>" + stackTrace + "</stack-trace>\n");
                        writer.write("        </exception>\n");
                    }

                    writer.write("      </info-message>\n");
                }

                writer.write("    </info-messages>\n");
                writer.write("  </success>\n");
            }

            writer.write("</json-to-xml-1-result-information>\n");
            writer.flush();
            writer.close();
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
            System.exit(-1);
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
            System.exit(-1);
        } catch (IOException ex) {
            ex.printStackTrace();
            System.exit(-1);
        }
    }

    converter.getInfoMessages().clear();
    converter.resultInfoFile = null;
}

From source file:Main.java

public static String xmlDocumentToString(final Document doc) {
    try {//from  ww w  .ja v  a  2 s  .  c o  m
        final DOMSource domSource = new DOMSource(doc);
        final StringWriter writer = new StringWriter();
        final StreamResult result = new StreamResult(writer);
        final TransformerFactory tf = TransformerFactory.newInstance();
        final Transformer transformer = tf.newTransformer();
        transformer.transform(domSource, result);
        return writer.toString();
    } catch (final TransformerException ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:Main.java

/**
 * Convert InputStream to String/*ww  w .  j  av  a 2  s  . c  o  m*/
 *
 * @param stream inputStream
 * @return string
 */
private static String streamToString(InputStream stream) {
    StringWriter writer = null;
    if (stream != null) {
        try {
            InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
            writer = new StringWriter();
            int n;
            char[] buffer = new char[1024 * 4];
            while (-1 != (n = reader.read(buffer))) {
                writer.write(buffer, 0, n);
            }
        } catch (IOException e) {
            // @todo better logging
            e.printStackTrace();
        }
    }
    return writer != null ? writer.toString() : "";
}

From source file:Main.java

public static String format(String input, int indent) {
    try {//w  w w . j  ava  2  s . c  om
        Source xmlInput = new StreamSource(new StringReader(input));
        StringWriter stringWriter = new StringWriter();
        StreamResult xmlOutput = new StreamResult(stringWriter);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", indent);
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(xmlInput, xmlOutput);
        return xmlOutput.getWriter().toString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:Main.java

/**
 * Transform xml Document to String//www  .j av  a2 s  .  com
 * @param doc Xml Document
 * @return String representation
 */
public static String getContent(Document doc) {
    try {
        StringWriter sw = 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(doc), new StreamResult(sw));
        return sw.toString();
    } catch (Exception ex) {
        throw new RuntimeException("Error converting to String", ex);
    }
}