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:com.cloudera.flume.reporter.ReportEvent.java

/**
 * Return event as JSON string//  w w  w. j a va 2  s  .c o m
 * 
 * Use ReportUtil.toJSONObject instead of this method
 */
@Deprecated
public String toJson() {
    StringWriter sw = new StringWriter();
    try {
        toJson(sw);
    } catch (IOException e) {
        LOG.error("String writer should never throw IOException", e);
        return null;
    }
    return sw.getBuffer().toString();
}

From source file:org.cleverbus.core.reqres.ResponseReceiveEventNotifier.java

/**
 * Transforms {@link Exception} to string representation.
 *
 * @param exception the exception that occurred
 * @return string of XML that represents exception of calling external system
 *///from  ww w .  j  a  v  a2 s  . c  om
private @Nullable String transformException(Exception exception) {
    Assert.notNull(exception, "the exception must not be null");

    String exceptionString = null;

    if (exception instanceof SoapFaultClientException) {
        // exception from Spring WS = Soap Fault
        SoapFaultClientException ex = (SoapFaultClientException) exception;

        StringWriter writer = new StringWriter();

        try {
            // An identity transformer
            if (ex.getSoapFault() != null && ex.getSoapFault().getSource() != null) {
                Transformer transformer = TransformerFactory.newInstance().newTransformer();
                StreamResult result = new StreamResult(writer);
                transformer.transform(ex.getSoapFault().getSource(), result);
                StringBuffer sb = writer.getBuffer();
                exceptionString = sb.toString();
            }
        } catch (TransformerException e) {
            Log.warn("Error occurs during transformation SOAP Fault to XML representation", e);
        }
    }

    return exceptionString;
}

From source file:com.vmware.gemfire.tools.pulse.tests.junit.ClusterSelectedRegionServiceTest.java

/**
 * Tests that service returns json object
 *
 *///  ww  w.  j  av a  2  s.c o  m
@Test
public void testResponseNotNull() {
    System.out.println(
            "ClusterSelectedRegionServiceTest ::  ------TESTCASE BEGIN : NULL RESPONSE CHECK FOR CLUSTER REGIONS------");
    if (httpclient != null) {
        try {
            HttpUriRequest pulseupdate = RequestBuilder.post().setUri(new URI(PULSE_UPDATE_URL))
                    .addParameter(PULSE_UPDATE_PARAM, PULSE_UPDATE_1_VALUE).build();
            CloseableHttpResponse response = httpclient.execute(pulseupdate);
            try {
                HttpEntity entity = response.getEntity();

                System.out.println("ClusterSelectedRegionServiceTest :: HTTP request status : "
                        + response.getStatusLine());
                BufferedReader respReader = new BufferedReader(new InputStreamReader(entity.getContent()));
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                String sz = null;
                while ((sz = respReader.readLine()) != null) {
                    pw.print(sz);
                }
                String jsonResp = sw.getBuffer().toString();
                System.out.println("ClusterSelectedRegionServiceTest :: JSON response returned : " + jsonResp);
                EntityUtils.consume(entity);

                JSONObject jsonObj = new JSONObject(jsonResp);
                Assert.assertNotNull(
                        "ClusterSelectedRegionServiceTest :: Server returned null response for ClusterSelectedRegion",
                        jsonObj.getJSONObject("ClusterSelectedRegion"));
            } finally {
                response.close();
            }
        } catch (Exception failed) {
            logException(failed);
            Assert.fail("Exception ! ");
        }
    } else {
        Assert.fail("ClusterSelectedRegionServiceTest :: No Http connection was established.");
    }
    System.out.println(
            "ClusterSelectedRegionServiceTest ::  ------TESTCASE END : NULL RESPONSE CHECK FOR CLUSTER REGIONS------\n");
}

From source file:de.elbe5.base.data.XmlData.java

public String getContent(Element element) {
    try {/* w w w  . j  a v a2  s  .  c  o m*/
        Source source = new DOMSource(element);
        StringWriter stringWriter = new StringWriter();
        Result result = new StreamResult(stringWriter);
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();
        transformer.transform(source, result);
        return stringWriter.getBuffer().toString();
    } catch (TransformerException e) {
        Log.error("xml error", e);
    }
    return "";
}

From source file:de.elbe5.base.data.XmlData.java

public String toString() {
    try {/*from  www .  j  a  va2s  .  com*/
        Source source = new DOMSource(doc);
        StringWriter stringWriter = new StringWriter();
        Result result = new StreamResult(stringWriter);
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();
        transformer.transform(source, result);
        return stringWriter.getBuffer().toString();
    } catch (TransformerException e) {
        Log.error("xml error", e);
    }
    return "";
}

From source file:org.terasoluna.gfw.web.token.transaction.TransactionTokenTagTest.java

/**
 * TransactionToken is null//from   w w  w. j  av a  2 s  .  c om
 */
@Test
public void testWriteTagContentTagWriter01() {

    // setup arguments
    TransactionTokenTag tag = new TransactionTokenTag();
    PageContext pageContext = mock(PageContext.class);
    tag.setPageContext(pageContext);
    HttpServletRequest request = mock(HttpServletRequest.class);
    StringWriter sw = new StringWriter();
    TagWriter tagWriter = new TagWriter(sw);

    // mock behavior
    when((HttpServletRequest) pageContext.getRequest()).thenReturn(request);
    when((TransactionToken) request.getAttribute(TransactionTokenInterceptor.NEXT_TOKEN_REQUEST_ATTRIBUTE_NAME))
            .thenReturn(null);

    // run
    int result = 1;
    try {
        result = tag.writeTagContent(tagWriter);
    } catch (JspException e) {
        fail();
    }

    // assert
    assertThat(sw.getBuffer().toString(), is(""));
    assertThat(result, is(0));
}

From source file:com.vmware.gemfire.tools.pulse.tests.junit.ClusterSelectedRegionServiceTest.java

/**
*
* Tests that response is for same logged in user
*
*///  w  ww  .j a va  2 s.  c om
@Test
public void testResponseUsername() {
    System.out.println(
            "ClusterSelectedRegionServiceTest ::  ------TESTCASE BEGIN : NULL USERNAME IN RESPONSE CHECK FOR CLUSTER REGIONS------");
    if (httpclient != null) {
        try {
            HttpUriRequest pulseupdate = RequestBuilder.post().setUri(new URI(PULSE_UPDATE_URL))
                    .addParameter(PULSE_UPDATE_PARAM, PULSE_UPDATE_1_VALUE).build();
            CloseableHttpResponse response = httpclient.execute(pulseupdate);
            try {
                HttpEntity entity = response.getEntity();

                System.out.println("ClusterSelectedRegionServiceTest :: HTTP request status : "
                        + response.getStatusLine());

                BufferedReader respReader = new BufferedReader(new InputStreamReader(entity.getContent()));
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                String sz = null;
                while ((sz = respReader.readLine()) != null) {
                    pw.print(sz);
                }
                String jsonResp = sw.getBuffer().toString();
                System.out.println("ClusterSelectedRegionServiceTest :: JSON response returned : " + jsonResp);
                EntityUtils.consume(entity);

                JSONObject jsonObj = new JSONObject(jsonResp);
                JSONObject clusterSelectedRegionObj = jsonObj.getJSONObject("ClusterSelectedRegion");
                Assert.assertNotNull(
                        "ClusterSelectedRegionServiceTest :: Server returned null response for ClusterSelectedRegion",
                        clusterSelectedRegionObj);
                String szUser = clusterSelectedRegionObj.getString("userName");
                Assert.assertEquals(
                        "ClusterSelectedRegionServiceTest :: Server returned wrong user name. Expected was admin. Server returned = "
                                + szUser,
                        szUser, "admin");
            } finally {
                response.close();
            }
        } catch (Exception failed) {
            logException(failed);
            Assert.fail("Exception ! ");
        }
    } else {
        Assert.fail("ClusterSelectedRegionServiceTest :: No Http connection was established.");
    }
    System.out.println(
            "ClusterSelectedRegionServiceTest ::  ------TESTCASE END : NULL USERNAME IN RESPONSE CHECK FOR CLUSTER REGIONS------\n");
}

From source file:edu.toronto.cs.cidb.ncbieutils.NCBIEUtilsAccessService.java

protected String getSummariesXML(List<String> idList) {
    // response example at
    // http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=omim&id=190685,605298,604829,602917,601088,602523,602259
    // response type: XML
    // return it//from   w  w  w  . j  a  v  a 2  s .  c  o  m
    String queryList = getSerializedList(idList);
    String url = composeURL(TERM_SUMMARY_QUERY_SCRIPT, TERM_SUMMARY_PARAM_NAME, queryList);
    try {
        Document response = readXML(url);
        NodeList nodes = response.getElementsByTagName("Item");
        // OMIM titles are all UPPERCASE, try to fix this
        for (int i = 0; i < nodes.getLength(); ++i) {
            Node n = nodes.item(i);
            if (n.getNodeType() == Node.ELEMENT_NODE) {
                if (n.getFirstChild() != null) {
                    n.replaceChild(response.createTextNode(fixCase(n.getTextContent())), n.getFirstChild());
                }
            }
        }
        Source source = new DOMSource(response);
        StringWriter stringWriter = new StringWriter();
        Result result = new StreamResult(stringWriter);
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();
        transformer.transform(source, result);
        return stringWriter.getBuffer().toString();
    } catch (Exception ex) {
        this.logger.error("Error while trying to retrieve summaries for ids " + idList + " "
                + ex.getClass().getName() + " " + ex.getMessage(), ex);
    }
    return "";
}

From source file:com.jskaleel.xml.JSONObject.java

/**
 * Produce a string in double quotes with backslash sequences in all the
 * right places. A backslash will be inserted within </, producing <\/,
 * allowing JSON text to be delivered in HTML. In JSON text, a string cannot
 * contain a control character or an unescaped quote or backslash.
 *
 * @param string//from w  ww.  j a  v  a  2  s.c om
 *            A String
 * @return A String correctly formatted for insertion in a JSON text.
 */
public static String quote(String string) {
    StringWriter sw = new StringWriter();
    synchronized (sw.getBuffer()) {
        try {
            return quote(string, sw).toString();
        } catch (IOException ignored) {
            // will never happen - we are writing to a string writer
            return "";
        }
    }
}

From source file:io.cos.cas.authentication.handler.support.OpenScienceFrameworkPrincipalFromRequestRemoteUserNonInteractiveCredentialsAction.java

/**
 * Normalize the Remote Principal credential.
 *
 * @param credential the credential object bearing the username, password, etc...
 * @return the json object to serialize for authorization with the OSF API
 * @throws ParserConfigurationException a parser configuration exception
 * @throws TransformerException a transformer exception
 *//*from  w  w  w . ja  v a2 s . co  m*/
private JSONObject normalizeRemotePrincipal(final OpenScienceFrameworkCredential credential)
        throws ParserConfigurationException, TransformerException {
    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    final DocumentBuilder builder = factory.newDocumentBuilder();

    final Document document = builder.newDocument();
    final Element rootElement = document.createElement("auth");
    document.appendChild(rootElement);

    for (final String key : credential.getAuthenticationHeaders().keySet()) {
        final Element attribute = document.createElement("attribute");
        attribute.setAttribute("name", key);
        attribute.setAttribute("value", credential.getAuthenticationHeaders().get(key));
        rootElement.appendChild(attribute);
    }

    // run the auth document through the transformer
    final DOMSource source = new DOMSource(document);
    final StringWriter writer = new StringWriter();
    final StreamResult result = new StreamResult(writer);

    this.institutionsAuthTransformer.transform(source, result);

    // convert transformed xml to json
    return XML.toJSONObject(writer.getBuffer().toString());
}