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 String getStringFromDocument(Document doc) throws TransformerException {
    DOMSource domSource = new DOMSource(doc);
    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.transform(domSource, result);
    return writer.toString();
}

From source file:eu.europeana.core.util.web.ExceptionResolver.java

private static String getStackTrace(Exception exception) {
    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter);
    exception.printStackTrace(printWriter);
    return stringWriter.toString();
}

From source file:com.opendoorlogistics.core.utils.XMLUtils.java

public static String toString(Node doc, OutputFormat format) {
    try {/*from w  w w  .  j  a  v a2  s  .com*/
        StringWriter stringOut = new StringWriter();
        XMLSerializer serial = new XMLSerializer(stringOut, format);
        serial.serialize(doc);
        return stringOut.toString();
    } catch (Throwable e) {
        throw new RuntimeException(e);
    }

}

From source file:Main.java

public static final String indenting(Node rootNode) throws XPathExpressionException, TransformerException {

    XPath xPath = XPathFactory.newInstance().newXPath();
    NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']", rootNode,
            XPathConstants.NODESET);

    for (int i = 0; i < nodeList.getLength(); ++i) {
        Node node = nodeList.item(i);
        node.getParentNode().removeChild(node);
    }// w  w  w.  ja  v a2 s  . c  o  m

    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

    StringWriter stringWriter = new StringWriter();
    StreamResult streamResult = new StreamResult(stringWriter);

    transformer.transform(new DOMSource(rootNode), streamResult);

    return stringWriter.toString();
}

From source file:com.opendoorlogistics.core.utils.XMLUtils.java

public static String toString(Node node) {
    try {/*from   w  ww  .jav  a 2 s  . c  om*/
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(node);
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        transformer.transform(source, result);
        return writer.toString();
    } catch (Throwable e) {
        throw new RuntimeException(e);
    }
}

From source file:com.redhat.rhn.common.util.FileUtils.java

/**
 * Read a file off disk into a String and return it.
 *
 * Expect weird stuff if the file is not textual.
 *
 * @param path of file to read in/* w ww .j a v a2  s . com*/
 * @return String containing file.
 */
public static String readStringFromFile(String path) {
    log.debug("readStringFromFile: " + path);

    File f = new File(path);
    BufferedReader input;
    try {
        input = new BufferedReader(new FileReader(f));
        StringWriter writer = new StringWriter();
        IOUtils.getInstance().copyWriter(input, writer);
        String contents = writer.toString();
        if (log.isDebugEnabled()) {
            log.debug("contents: " + contents);
        }
        return contents;
    } catch (FileNotFoundException e) {
        throw new RuntimeException("File not found: " + path);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:Main.java

public static String constructXMLString(Document dom) throws IOException {
    String retXMLStr = null;//from  w  ww .j av  a2  s .c  o  m
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer;
    try {
        transformer = factory.newTransformer();
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        DOMSource source = new DOMSource(dom);
        transformer.transform(source, result);
        writer.close();
        retXMLStr = writer.toString();
    } catch (TransformerConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TransformerException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    /*
    // Make a string out of the DOM object
    System.out.println(dom.toString());
    OutputFormat format = new OutputFormat(dom);
    format.setIndenting(true);
    ByteArrayOutputStream byteoutStream = new ByteArrayOutputStream();
    XMLSerializer serializer = new XMLSerializer(byteoutStream, format);
    serializer.serialize(dom);
    String retXMLStr = new String(byteoutStream.toByteArray());
    byteoutStream.close();
     */
    return retXMLStr;

}

From source file:Main.java

public static String toString(Collection<Integer> stack, String delimiterChars) {
    if (stack.isEmpty()) {
        return "";
    }//from w  w  w  .ja v  a 2s .c  om
    if (stack.size() == 1) {
        return Integer.toString(stack.iterator().next());
    }
    StringWriter writer = new StringWriter();
    String delimiter = "";
    for (Integer item : stack) {
        writer.append(delimiter);
        writer.append(Integer.toString(item));
        delimiter = delimiterChars;
    }
    return writer.toString();
}

From source file:com.lingxiang2014.util.FreemarkerUtils.java

public static String process(String template, Map<String, ?> model, Configuration configuration)
        throws IOException, TemplateException {
    if (template == null) {
        return null;
    }//from ww  w .j  a va2 s .c  om
    if (configuration == null) {
        configuration = new Configuration();
    }
    StringWriter out = new StringWriter();
    new Template("template", new StringReader(template), configuration).process(model, out);
    return out.toString();
}

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));
        }// w  w  w  .  j a v a 2s  . c om
        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);
    }
}