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 getXML(NodeList childNodes) {
    try {// w  w  w .j  a v  a  2s .  com
        StringBuilder builder = new StringBuilder();
        Transformer t = TransformerFactory.newInstance().newTransformer();
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        for (int i = 0; i < childNodes.getLength(); i++) {
            StringWriter sw = new StringWriter();
            t.transform(new DOMSource(childNodes.item(i)), new StreamResult(sw));
            builder.append(sw.toString());
        }
        return builder.toString();
    } catch (Exception ex) {
        return "";
    }
}

From source file:Main.java

/**
 * Formats an unformatted xml and returns a pretty format.
 * //from  w w  w  .  j  av  a2  s.co m
 * @param unformattedXml
 *            the unformatted xml string
 * @return the xml in a pretty format
 * @throws TransformerException
 */
public static String formatXml(String unformattedXml) throws TransformerException {
    Document doc = parseXml(unformattedXml);

    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    // initialize StreamResult with File object to save to file
    StreamResult result = new StreamResult(new StringWriter());
    DOMSource source = new DOMSource(doc);
    transformer.transform(source, result);
    String xmlString = result.getWriter().toString();
    return xmlString;
}

From source file:Main.java

/**
 * @param doc/*from w w  w .  j  av  a2  s  . c  o  m*/
 * @return
 * @throws RuntimeException
 */
public static String prettyPrint(Document doc) throws RuntimeException {
    TransformerFactory tfactory = TransformerFactory.newInstance();
    Transformer serializer;
    StringWriter writer = new StringWriter();
    try {
        serializer = tfactory.newTransformer();

        // Setup indenting to "pretty print"
        serializer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
        serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); //$NON-NLS-1$ //$NON-NLS-2$

        serializer.transform(new DOMSource(doc), new StreamResult(writer));
        return writer.toString();
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    }
}

From source file:Main.java

/**
 * Object to XML// ww w . java  2s. c om
 * 
 * @param object
 * @return
 */
public static String convertToXML(Object object) {
    try {
        System.out.println(mMap.containsKey(object.getClass()) + "---mmap-----");
        if (!mMap.containsKey(object.getClass())) {
            JAXBContext jaxbContext = JAXBContext.newInstance(object.getClass());
            Marshaller marshaller = jaxbContext.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            // marshaller.setProperty(CharacterEscapeHandler.class.getName(),
            // new CharacterEscapeHandler() {
            // public void escape(char[] ac, int i, int j, boolean
            // flag,Writer writer) throws IOException {
            // writer.write( ac, i, j ); }
            // });
            mMap.put(object.getClass(), marshaller);
        }
        System.out.println("----mmap--" + mMap.toString());
        StringWriter stringWriter = new StringWriter();
        mMap.get(object.getClass()).marshal(object, stringWriter);
        return stringWriter.getBuffer().toString();
    } catch (JAXBException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:Main.java

/**
 * Converts a DOM Tree to a String./*from  www. j  ava 2  s  .c om*/
 *
 * @param xml The DOM document to convert.
 *
 * @return A string containing the XML if successful, null otherwise.
 */
public static String xmlToString(Document xml) {
    try {
        TransformerFactory f = TransformerFactory.newInstance();
        StringWriter writer = new StringWriter();
        Transformer t = f.newTransformer();
        DOMSource src = new DOMSource(xml);
        StreamResult result = new StreamResult(writer);
        t.transform(src, result);
        return writer.toString();
    } catch (TransformerException e) {
        return null;
    }
}

From source file:net.fizzl.redditengine.data.UserListing.java

public static UserListing fromInputStream(InputStream in) throws IOException {
    StringWriter writer = new StringWriter();
    IOUtils.copy(in, writer, "UTF-8");
    return fromInputStream(writer.toString());
}

From source file:org.mstc.zmq.json.Encoder.java

public static String encode(Object o) throws IOException {
    StringWriter writer = new StringWriter();
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
    JsonFactory factory = mapper.getFactory();
    try (JsonGenerator g = factory.createGenerator(writer)) {
        g.writeStartObject();/* w  w w.j  a  va2s  .  co  m*/
        for (Field f : o.getClass().getDeclaredFields()) {
            try {
                f.setAccessible(true);
                Object value = f.get(o);
                if (value != null) {
                    if (f.getType().isAssignableFrom(List.class)) {
                        String items = mapper.writeValueAsString(value);
                        g.writeStringField(f.getName(), items);
                    } else if (f.getType().isArray()) {
                        if (f.getType().getComponentType().isAssignableFrom(byte.class)) {
                            g.writeBinaryField(f.getName(), (byte[]) value);
                        } else {
                            int length = Array.getLength(value);
                            g.writeFieldName(f.getName());
                            g.writeStartArray();
                            for (int i = 0; i < length; i++) {
                                Object av = Array.get(value, i);
                                if (av instanceof Double) {
                                    g.writeNumber(new BigDecimal((Double) av).toPlainString());
                                } else if (av instanceof Float) {
                                    g.writeNumber(new BigDecimal((Float) av).toPlainString());
                                } else if (av instanceof Integer) {
                                    g.writeNumber(new BigDecimal((Integer) av).toPlainString());
                                } else {
                                    g.writeObject(av);
                                }
                                /*if (av instanceof Double)
                                g.writeNumber(new BigDecimal((Double) av));
                                else if (av instanceof Float)
                                g.writeNumber(new BigDecimal((Float) av));
                                else if (av instanceof Integer)
                                g.writeNumber((Integer) av);*/
                            }
                            g.writeEndArray();
                        }
                    } else {
                        g.writeObjectField(f.getName(), value);
                    }
                }

            } catch (IllegalAccessException e) {
                logger.warn("Could not get field: {}", f.getName(), e);
            }
        }
        g.writeEndObject();
    }
    if (logger.isDebugEnabled())
        logger.debug(writer.toString());
    return writer.toString();
}

From source file:Main.java

/**
 * Pretty print an XML. Use with caution as this drains the source if it is
 * a StreamSource.//from w ww  . j a v  a  2 s.  c om
 * @param source the XML source
 * @return a String with readable XML
 */
public static String prettyPrint(final Source source) {
    try {
        Transformer serializer = TransformerFactory.newInstance().newTransformer();
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        StringWriter writer = new StringWriter();
        serializer.transform(source, new StreamResult(writer));
        return writer.toString();
    } catch (TransformerException e) {
        return e.getMessage();
    }
}

From source file:com.netflix.hystrix.serial.SerialHystrixRequestEvents.java

public static String toJsonString(HystrixRequestEvents requestEvents) {
    StringWriter jsonString = new StringWriter();

    try {//from   ww  w  .  j  a va  2 s  . c o  m
        JsonGenerator json = jsonFactory.createGenerator(jsonString);

        serializeRequestEvents(requestEvents, json);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return jsonString.getBuffer().toString();
}

From source file:Main.java

private static String getXmlString(Document document, String tagName)
        throws ParserConfigurationException, SAXException, IOException, TransformerException {
    NodeList nodeList = document.getElementsByTagName(tagName);
    if (nodeList.getLength() < 1) {
        throw new IllegalArgumentException("no " + tagName + " found");
    }/*from  w ww.  j  av a 2  s  . co  m*/
    Node sub = nodeList.item(0);
    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document subdoc = db.newDocument();
    subdoc.appendChild(sub.cloneNode(true));

    TransformerFactory transFactory = TransformerFactory.newInstance();
    Transformer transformer = transFactory.newTransformer();
    DOMSource domSource = new DOMSource(subdoc);
    StringWriter sw = new StringWriter();
    StreamResult xmlResult = new StreamResult(sw);
    transformer.transform(domSource, xmlResult);
    sw.flush();
    return sw.toString();
}