Example usage for java.io StringWriter getBuffer

List of usage examples for java.io StringWriter getBuffer

Introduction

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

Prototype

public StringBuffer getBuffer() 

Source Link

Document

Return the string buffer itself.

Usage

From source file:org.openmhealth.shim.healthvault.HealthvaultShim.java

/**
 * Utility method for getting XML fragments required
 * for parsing XML docs from microsoft.//from w  w  w.  j av a2  s  . c o  m
 *
 * @param doc - XML document fragment.
 * @return - Raw XML String.
 */
private static String convertDocumentToString(Document doc) {
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer;
    try {
        transformer = tf.newTransformer();
        StringWriter writer = new StringWriter();
        transformer.transform(new DOMSource(doc), new StreamResult(writer));
        return writer.getBuffer().toString();
    } catch (TransformerException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.apache.falcon.lifecycle.engine.oozie.utils.OozieBuilderUtils.java

private static Path marshal(Cluster cluster, JAXBElement<?> jaxbElement, JAXBContext jaxbContext, Path outPath)
        throws FalconException {
    try {/*from  w w  w.j  a va 2  s .com*/
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        if (LOG.isDebugEnabled()) {
            StringWriter writer = new StringWriter();
            marshaller.marshal(jaxbElement, writer);
            LOG.debug("Writing definition to {} on cluster {}", outPath, cluster.getName());
            LOG.debug(writer.getBuffer().toString());
        }

        FileSystem fs = HadoopClientFactory.get().createProxiedFileSystem(outPath.toUri(),
                ClusterHelper.getConfiguration(cluster));
        OutputStream out = fs.create(outPath);
        try {
            marshaller.marshal(jaxbElement, out);
        } finally {
            out.close();
        }

        LOG.info("Marshalled {} to {}", jaxbElement.getDeclaredType(), outPath);
        return outPath;
    } catch (Exception e) {
        throw new FalconException("Unable to marshall app object", e);
    }
}

From source file:org.andstatus.app.util.MyLog.java

/**
 * from org.apache.commons.lang3.exception.ExceptionUtils
 *///from   ww  w  . java 2 s  . c  o  m
public static String getStackTrace(Throwable throwable) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw, true);
    throwable.printStackTrace(pw); // NOSONAR
    return sw.getBuffer().toString();
}

From source file:it.tidalwave.northernwind.core.impl.filter.HtmlCleanupFilter.java

/*******************************************************************************************************************
 *
 ******************************************************************************************************************/
public static String formatHtml(final @Nonnull String text) throws IOException {
    final StringWriter sw = new StringWriter();
    final BufferedReader br = new BufferedReader(new StringReader(text));

    boolean inBody = false;

    for (;;) {//from   w ww  .  ja v a  2 s . c  o m
        final String s = br.readLine();

        if (s == null) {
            break;
        }

        if (s.contains("<!-- @nw.HtmlCleanupFilter.enabled=false")) {
            return text;
        }

        if ("</body>".equals(s.trim())) {
            break;
        }

        if (inBody) {
            sw.write(s + "\n");
        }

        if ("<body>".equals(s.trim())) {
            inBody = true;
        }
    }

    sw.close();
    br.close();

    return inBody ? sw.getBuffer().toString() : text;
}

From source file:com.github.jsonj.tools.JsonSerializer.java

/**
 * @param json//w ww. j  av a  2  s . c  o  m
 *            a {@link JsonElement}
 * @param pretty
 *            if true, a properly indented version of the json is returned
 * @return string representation of the json
 */
public static String serialize(final JsonElement json, final boolean pretty) {
    StringWriter sw = new StringWriter();
    if (pretty) {
        try {
            serialize(sw, json, pretty);
        } catch (IOException e) {
            throw new IllegalStateException("cannot serialize json to a string", e);
        } finally {
            try {
                sw.close();
            } catch (IOException e) {
                throw new IllegalStateException("cannot serialize json to a string", e);
            }
        }
        return sw.getBuffer().toString();
    } else {
        try {
            json.serialize(sw);
            return sw.getBuffer().toString();
        } catch (IOException e) {
            throw new IllegalStateException("cannot serialize json to a string", e);
        }
    }
}

From source file:com.vmware.qe.framework.datadriven.utils.XMLUtil.java

/**
 * Given a W3C Node, gives the XML string representation
 * /*  w  ww. j a v  a2  s  .c  o  m*/
 * @param node a W3C XML Node
 * @return node as string
 */
public static String getNodeAsString(Node node) {
    try {
        Source source = new DOMSource(node);
        StringWriter stringWriter = new StringWriter();
        Result result = new StreamResult(stringWriter);
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(source, result);
        return stringWriter.getBuffer().toString();
    } catch (TransformerConfigurationException e) {
        log.error("Caught Exception ", e);
    } catch (TransformerException e) {
        log.error("Caught Exception ", e);
    }
    return null;
}

From source file:com.dien.upload.server.UploadServlet.java

/**
 * Simple method to get a string from the exception stack.
 * //from w  w w  . ja v  a  2s.  com
 * @param e
 * @return string
 */
protected static String stackTraceToString(Exception e) {
    StringWriter writer = new StringWriter();
    e.printStackTrace(new PrintWriter(writer));
    return writer.getBuffer().toString();
}

From source file:controllers.SensorCategoryController.java

private static String toCsv(List<SensorCategory> categories) {
    StringWriter sw = new StringWriter();
    CellProcessor[] processors = new CellProcessor[] { new Optional(), new Optional() };
    ICsvBeanWriter writer = new CsvBeanWriter(sw, CsvPreference.STANDARD_PREFERENCE);

    try {/*from w w w.ja  v  a2  s.  com*/
        final String[] header = new String[] { "sensorCategoryName", "purpose" };
        writer.writeHeader(header);
        for (SensorCategory category : categories) {
            writer.write(category, header, processors);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sw.getBuffer().toString();
}

From source file:Main.java

/**
 * Use the transform specified by xslSrc and transform the document specified by docSrc, and return the resulting
 * document./*ww w .  j  av  a2  s.  co m*/
 * 
 * @param xslSrc
 *          StreamSrc containing the xsl transform
 * @param docSrc
 *          StreamSrc containing the document to be transformed
 * @param params
 *          Map of properties to set on the transform
 * @param resolver
 *          URIResolver instance to resolve URI's in the output document.
 * 
 * @return StringBuffer containing the XML results of the transform
 * @throws TransformerConfigurationException
 *           if the TransformerFactory fails to create a Transformer.
 * @throws TransformerException
 *           if actual transform fails.
 */
protected static final StringBuffer transformXml(final StreamSource xslSrc, final StreamSource docSrc,
        final Map params, final URIResolver resolver)
        throws TransformerConfigurationException, TransformerException {

    StringBuffer sb = null;
    StringWriter writer = new StringWriter();

    TransformerFactory tf = TransformerFactory.newInstance();
    if (null != resolver) {
        tf.setURIResolver(resolver);
    }
    // TODO need to look into compiling the XSLs...
    Transformer t = tf.newTransformer(xslSrc); // can throw
    // TransformerConfigurationException
    // Start the transformation
    if (params != null) {
        Set<?> keys = params.keySet();
        Iterator<?> it = keys.iterator();
        String key, val;
        while (it.hasNext()) {
            key = (String) it.next();
            val = (String) params.get(key);
            if (val != null) {
                t.setParameter(key, val);
            }
        }
    }
    t.transform(docSrc, new StreamResult(writer)); // can throw
    // TransformerException
    sb = writer.getBuffer();

    return sb;
}

From source file:org.apache.axis.utils.Admin.java

/** Get an XML document representing this engine's configuration.
 *
 * This document is suitable for saving and reloading into the
 * engine.//  www  .j a v  a2s  .c o  m
 *
 * @param engine the AxisEngine to work with
 * @return an XML document holding the engine config
 * @exception AxisFault
 */
public static Document listConfig(AxisEngine engine) throws AxisFault {
    StringWriter writer = new StringWriter();
    SerializationContext context = new SerializationContext(writer);
    context.setPretty(true);
    try {
        EngineConfiguration config = engine.getConfig();

        if (config instanceof WSDDEngineConfiguration) {
            WSDDDeployment deployment = ((WSDDEngineConfiguration) config).getDeployment();
            deployment.writeToContext(context);
        }
    } catch (Exception e) {
        // If the engine config isn't a FileProvider, or we have no
        // engine config for some odd reason, we'll end up here.

        throw new AxisFault(Messages.getMessage("noEngineWSDD"));
    }

    try {
        writer.close();
        return XMLUtils.newDocument(new InputSource(new StringReader(writer.getBuffer().toString())));
    } catch (Exception e) {
        log.error("exception00", e);
        return null;
    }
}