Example usage for java.io StringWriter toString

List of usage examples for java.io StringWriter toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Return the buffer's current value as a string.

Usage

From source file:Main.java

public static void printNode(Node node) {
    try {/*from w w w. ja va 2s.  c  o m*/
        // Set up the output transformer
        TransformerFactory transfac = TransformerFactory.newInstance();
        Transformer trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        trans.setOutputProperty(OutputKeys.INDENT, "yes");

        // Print the DOM node

        StringWriter sw = new StringWriter();
        StreamResult result = new StreamResult(sw);
        DOMSource source = new DOMSource(node);
        trans.transform(source, result);
        String xmlString = sw.toString();

        System.out.println(xmlString);
    } catch (TransformerException e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static String XMLDocumentToString(Document _doc) {
    TransformerFactory transfac = TransformerFactory.newInstance();
    Transformer trans;/*w  w w  .  jav a 2  s  . co  m*/
    String xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
    try {
        trans = transfac.newTransformer();

        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        trans.setOutputProperty(OutputKeys.INDENT, "yes");
        StringWriter sw = new StringWriter();
        StreamResult result = new StreamResult(sw);
        DOMSource source = new DOMSource(_doc);
        trans.transform(source, result);
        xmlString += sw.toString();
    } catch (TransformerConfigurationException e) {
        System.out.println("C:" + e.getClass() + "\nM:" + e.getMessage());
        return null;
    } catch (TransformerException e) {
        System.out.println("C:" + e.getClass() + "\nM:" + e.getMessage());
        return null;
    }
    return xmlString;
}

From source file:Main.java

public static String prettyPrint(Document document) {
    // Pretty-prints a DOM document to XML using DOM Load and Save's
    // LSSerializer.
    // Note that the "format-pretty-print" DOM configuration parameter can
    // only be set in JDK 1.6+.

    DOMImplementationRegistry domImplementationRegistry;
    try {//from  w w  w  .  j  a va 2  s  . c  o m
        domImplementationRegistry = DOMImplementationRegistry.newInstance();
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | ClassCastException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        throw new RuntimeException(e);
    }
    DOMImplementation domImplementation = document.getImplementation();
    if (domImplementation.hasFeature("LS", "3.0") && domImplementation.hasFeature("Core", "2.0")) {
        /*DOMImplementationLS domImplementationLS = (DOMImplementationLS) domImplementation
          .getFeature("LS", "3.0");*/
        DOMImplementationLS domImplementationLS = (DOMImplementationLS) domImplementationRegistry
                .getDOMImplementation("LS");

        LSSerializer lsSerializer = domImplementationLS.createLSSerializer();
        DOMConfiguration domConfiguration = lsSerializer.getDomConfig();
        if (domConfiguration.canSetParameter("format-pretty-print", Boolean.TRUE)) {
            lsSerializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
            LSOutput lsOutput = domImplementationLS.createLSOutput();
            lsOutput.setEncoding("UTF-8");
            StringWriter stringWriter = new StringWriter();
            lsOutput.setCharacterStream(stringWriter);
            lsSerializer.write(document, lsOutput);
            return stringWriter.toString();
        } else {
            throw new RuntimeException("DOMConfiguration 'format-pretty-print' parameter isn't settable.");
        }
    } else {
        throw new RuntimeException("DOM 3.0 LS and/or DOM 2.0 Core not supported.");
    }
}

From source file:com.microsoft.rest.serializer.JacksonHelper.java

/**
 * Serializes an object into a JSON string using the current {@link ObjectMapper}.
 *
 * @param object the object to serialize.
 * @return the serialized string. Null if the object to serialize is null.
 *///www  .j  a  v  a  2s .  com
public static String serialize(Object object) {
    if (object == null)
        return null;
    try {
        StringWriter writer = new StringWriter();
        getObjectMapper().writeValue(writer, object);
        return writer.toString();
    } catch (Exception e) {
        return null;
    }
}

From source file:Main.java

/**
 * Returns String representation of the the XML node (document or element).
 * @param node the node/*w  w w .  ja v a2 s . c o m*/
 * @return string representation of the input
 * @throws Exception if an error occurs
 */
public static String toXml(Node node) throws Exception {
    Source source = new DOMSource(node);
    StringWriter writer = new StringWriter();
    Result result = new StreamResult(writer);
    Transformer t = TransformerFactory.newInstance().newTransformer();
    t.transform(source, result);
    return writer.toString();
}

From source file:Main.java

public static String xmlToString(Document xml) {
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = null;

    try {/*from   w w  w.  ja  v a  2 s  . c om*/
        transformer = tFactory.newTransformer();
    } catch (TransformerConfigurationException e) {
        e.printStackTrace();
    }
    DOMSource source = new DOMSource(xml);
    StringWriter writer = new StringWriter();
    try {
        transformer.transform(source, new StreamResult(writer));
    } catch (TransformerException e) {
        e.printStackTrace();
    }
    return writer.toString();

}

From source file:com.evolveum.midpoint.cli.common.ToolsUtils.java

public static String serializeObject(Object object) throws JAXBException {
    if (object == null) {
        return null;
    }/*from   w w  w .  j  av a2s  .  co m*/

    Marshaller marshaller = JAXB_CONTEXT.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_ENCODING, StandardCharsets.UTF_8.name());
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    StringWriter sw = new StringWriter();
    marshaller.marshal(object, sw);
    return sw.toString();
}

From source file:Hex.java

/**
 * Encodar binrt till hex/*from w w  w . j  ava 2 s .com*/
 *
 *@param dataStr bin-representation av data
 *@return Hex-representation av data
 **/
public static String encode(byte[] dataStr) {
    StringWriter w = new StringWriter();
    for (int i = 0; i < dataStr.length; i++) {
        int b = dataStr[i];
        w.write(hex[((b >> 4) & 0xF)]);
        w.write(hex[((b >> 0) & 0xF)]);
    }
    return w.toString();
}

From source file:org.kordamp.javatrove.example01.TestHelper.java

public static String repositoriesAsJSON(Collection<Repository> repositories, ObjectMapper objectMapper) {
    StringWriter writer = new StringWriter();
    try {/*from w  ww .j  a va 2  s  .c  om*/
        objectMapper.writeValue(writer, repositories);
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
    return writer.toString();
}

From source file:email.mandrill.SendMail.java

public static MessageResponses sendMail(Message message) {
    try {//from  w w  w  . j a va2 s.  co m
        logger.log(Level.INFO, "Message:" + message.toJSONString());

        HttpClient httpclient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost("https://mandrillapp.com/api/1.0/messages/send.json");

        String request = message.toJSONString();
        HttpEntity entity = new ByteArrayEntity(request.getBytes("UTF-8"));
        httppost.setEntity(entity);
        //Execute and get the response.
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity responseEntity = response.getEntity();

        if (responseEntity != null) {
            InputStream instream = responseEntity.getContent();
            try {
                StringWriter writer = new StringWriter();
                IOUtils.copy(instream, writer, "UTF-8");
                String theString = writer.toString();

                MessageResponses messageResponses = new MessageResponses(theString);
                //Do whateveer is needed with the response.
                logger.log(Level.INFO, theString);
                return messageResponses;
            } finally {
                instream.close();
            }
        }
    } catch (Exception e) {
        logger.log(Level.SEVERE, util.Utility.logMessage(e, "Exception while updating org name:", null));
    }
    return null;
}