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:it.cnr.ilc.tokenizer.utils.InputToString.java

/**
 * Convert an inputstream into a string/*from w w  w  .  j a v a 2s  . co  m*/
 * @param is the inputstream
 * @return the string from the input
 */
public static String convertInputStreamToString(InputStream is) {
    StringWriter writer = new StringWriter();
    String encoding = "UTF-8";
    String message = "";
    String theString = "";
    try {
        IOUtils.copy(is, writer, encoding);
        theString = writer.toString();
    } catch (Exception e) {
        message = "IOException in coverting the stream into a string " + e.getMessage();
        Logger.getLogger(Utilities.class.getName()).log(Level.SEVERE, message);
    }

    //System.err.println("DDDD " + theString);
    IOUtils.closeQuietly(is);
    IOUtils.closeQuietly(writer);
    return theString;
}

From source file:Main.java

private static String nodeToString(Node node) throws Exception {
    StringWriter sw = new StringWriter();
    Transformer t = TransformerFactory.newInstance().newTransformer();
    t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    t.setOutputProperty(OutputKeys.INDENT, "yes");
    t.transform(new DOMSource(node), new StreamResult(sw));
    return sw.toString();
}

From source file:Main.java

/**
 * Converts an XML node (or document) to an XML String.
 *
 * @param node/*from w  w w . j a  va 2  s  . c o  m*/
 * @return
 * @throws TransformerException
 */
public static String toString(Node node) throws TransformerException {

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();

    // Node source
    DOMSource source = new DOMSource(node);

    // StringWriter result
    StringWriter stringWriter = new StringWriter();
    Result result = new StreamResult(stringWriter);

    transformer.transform(source, result);
    return stringWriter.toString();
}

From source file:com.websocket.server.commons.JsonPojoMapper.java

public static String toJson(Object pojo, boolean prettyPrint)
        throws JsonMappingException, JsonGenerationException, IOException {
    StringWriter sw = new StringWriter();
    JsonGenerator jsonGen = jsonFactory.createJsonGenerator(sw);
    if (prettyPrint) {
        jsonGen.useDefaultPrettyPrinter();
    }/*from  w  ww .  j  a  va2 s . c om*/
    mapper.writeValue(jsonGen, pojo);
    return sw.toString();
}

From source file:$.JaxbMapper.java

/**
     * Java Object->Xml with encoding.
     *///from  w ww. j a  v  a  2 s .c  om
    public static String toXml(Object root, Class clazz, String encoding) {
        try {
            StringWriter writer = new StringWriter();
            createMarshaller(clazz, encoding).marshal(root, writer);
            return writer.toString();
        } catch (JAXBException e) {
            throw Exceptions.unchecked(e);
        }
    }

From source file:com.osbcp.csssquasher.Squasher.java

/**
 * Performs the YUI Compressor on a String.
 * /* w ww.ja  va2 s. co m*/
 * @param log Log object.
 * @param css The CSS that should be compressed.
 * @return Compressed CSS.
 * @throws IOException If any error occurs.
 */

private static String compress(final StringBuilder log, final String css) throws IOException {

    StringReader reader = new StringReader(css);

    StringWriter writer = new StringWriter();

    CssCompressor compressor = new CssCompressor(reader);

    compressor.compress(writer, -1);

    String compressedCSS = writer.toString();

    log.append("Compressed the CSS from '" + css.length() + "' characters to '" + compressedCSS.length()
            + "' characters.\n");

    return compressedCSS;

}

From source file:com.partypoker.poker.engagement.utils.EngagementBundleToJSON.java

/**
 * Recursive function to write a value to JSON.
 * @param json the JSON serializer./*  w w w.ja v  a  2 s. c om*/
 * @param value the value to write in JSON.
 */
private static void convert(JSONStringer json, Object value) throws JSONException {
    /* Handle null */
    if (value == null)
        json.value(null);

    /* The function is recursive if it encounters a bundle */
    else if (value instanceof Bundle) {
        /* Cast bundle */
        Bundle bundle = (Bundle) value;

        /* Open object */
        json.object();

        /* Traverse bundle */
        for (String key : bundle.keySet()) {
            /* Write key */
            json.key(key);

            /* Recursive call to write the value */
            convert(json, bundle.get(key));
        }

        /* End object */
        json.endObject();
    }

    /* Handle array, write it as a JSON array */
    else if (value.getClass().isArray()) {
        /* Open array */
        json.array();

        /* Recursive call on each value */
        int length = Array.getLength(value);
        for (int i = 0; i < length; i++)
            convert(json, Array.get(value, i));

        /* Close array */
        json.endArray();
    }

    /* Handle ArrayList, write it as a JSON array */
    else if (value instanceof ArrayList<?>) {
        /* Open array */
        json.array();

        /* Recursive call on each value */
        ArrayList<?> arrayList = (ArrayList<?>) value;
        for (Object val : arrayList)
            convert(json, val);

        /* Close array */
        json.endArray();
    }

    /* Format throwable values with the stack trace */
    else if (value instanceof Throwable) {
        Throwable t = (Throwable) value;
        StringWriter text = new StringWriter();
        t.printStackTrace(new PrintWriter(text));
        json.value(text.toString());
    }

    /* Other values are handled directly by JSONStringer (numerical, boolean and String) */
    else
        json.value(value);
}

From source file:com.streamreduce.util.JSONUtils.java

/**
 * Reads in a JSON file from the classpath.
 *
 * @param resource the resource to read in as a string
 *
 * @return the contents of the resource as string
 *
 * @throws Exception if anything goes wrong
 *//*  w w  w . j a  v  a2s . com*/
public static String readJSONFromClasspath(String resource) throws Exception {
    InputStream inputStream = JSONUtils.class.getResourceAsStream(resource);
    StringWriter writer = new StringWriter();

    IOUtils.copy(inputStream, writer, "UTF-8");

    return writer.toString();
}

From source file:Main.java

public static String toPrettyString(String xml) {
    int indent = 4;
    try {/*from  w ww  .j a v a 2  s. c om*/
        // Turn xml string into a document
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8"))));

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

        for (int i = 0; i < nodeList.getLength(); ++i) {
            Node node = nodeList.item(i);
            node.getParentNode().removeChild(node);
        }

        // Setup pretty print options
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", indent);
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");

        // Return pretty print xml string
        StringWriter stringWriter = new StringWriter();
        transformer.transform(new DOMSource(document), new StreamResult(stringWriter));
        return stringWriter.toString();
    } catch (Exception e) {
        System.out.println(xml);
        throw new RuntimeException(
                "Problems prettyfing xml content [" + Splitter.fixedLength(100).split(xml) + "]", e);
    }
}

From source file:com.googlecode.osde.internal.shindig.ShindigLauncher.java

private static void createConfigFileForHibernate(OsdeConfig config) {
    FileOutputStream fos = null;//from  w w  w .  j  a  v  a 2 s . c o  m
    try {
        InputStreamReader in = new InputStreamReader(
                ShindigLauncher.class.getResourceAsStream("/shindig/osde_hibernate.cfg.xml.tmpl"), "UTF-8");
        StringWriter out = new StringWriter();
        IOUtils.copy(in, out);
        String code = out.toString();
        if (config.isUseInternalDatabase()) {
            code = code.replace("$driver_class$", "org.h2.Driver");
            code = code.replace("$url$", "jdbc:h2:tcp://localhost:9092/shindig");
            code = code.replace("$username$", "sa");
            code = code.replace("$password$", "");
            code = code.replace("$dialect$", "H2");
            String databaseDir = config.getDatabaseDir();
            File dbFile = new File(databaseDir, "shindig.data.db");
            code = code.replace("$hbm2ddl$", dbFile.isFile() ? "update" : "create");
        } else {
            if (config.getExternalDatabaseType().equals("MySQL")) {
                code = code.replace("$driver_class$", "com.mysql.jdbc.Driver");
                String url = "jdbc:mysql://";
                url += config.getExternalDatabaseHost();
                String port = config.getExternalDatabasePort();
                if (StringUtils.isNotEmpty(port)) {
                    url += ":" + port;
                }
                url += "/" + config.getExternalDatabaseName();
                code = code.replace("$url$", url);
                code = code.replace("$username$", config.getExternalDatabaseUsername());
                code = code.replace("$password$", config.getExternalDatabasePassword());
                code = code.replace("$dialect$", "MySQL");
            } else if (config.getExternalDatabaseType().equals("Oracle")) {
                code = code.replace("$driver_class$", "oracle.jdbc.driver.OracleDriver");
                String url = "jdbc:oracle:thin:@";
                url += config.getExternalDatabaseHost();
                String port = config.getExternalDatabasePort();
                if (StringUtils.isNotEmpty(port)) {
                    url += ":" + port;
                }
                url += ":" + config.getExternalDatabaseName();
                code = code.replace("$url$", url);
                code = code.replace("$username$", config.getExternalDatabaseUsername());
                code = code.replace("$password$", config.getExternalDatabasePassword());
                code = code.replace("$dialect$", "Oracle");
            }
        }
        File file = new File(HibernateUtils.configFileDir, HibernateUtils.configFileName);
        fos = new FileOutputStream(file);
        ByteArrayInputStream bytes = new ByteArrayInputStream(code.getBytes("UTF-8"));
        IOUtils.copy(bytes, fos);
    } catch (IOException e) {
        logger.error("Creating the configuration file for H2Database failed.", e);
        throw new IllegalStateException(e);
    } finally {
        IOUtils.closeQuietly(fos);
    }
}