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.apache.falcon.workflow.OozieWorkflowBuilder.java

protected void marshal(Cluster cluster, JAXBElement<?> jaxbElement, JAXBContext jaxbContext, Path outPath)
        throws FalconException {
    try {/*from  www  .java  2s .  c  o  m*/
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        FileSystem fs = HadoopClientFactory.get().createFileSystem(outPath.toUri(),
                ClusterHelper.getConfiguration(cluster));
        OutputStream out = fs.create(outPath);
        try {
            marshaller.marshal(jaxbElement, out);
        } finally {
            out.close();
        }
        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());
        }

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

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

/**
*
* Tests that response is for same region
*
* Test method for {@link com.vmware.gemfire.tools.pulse.internal.service.MemberGatewayHubService#execute(javax.servlet.http.HttpServletRequest)}.
*
*//*from  w  w w. j av  a2  s . c  o m*/
@Test
public void testResponseGatewaySenderProperties() {
    System.out.println(
            "MemberGatewayHubServiceTest ::  ------TESTCASE BEGIN : GATEWAY SENDER PROPERTIES IN RESPONSE CHECK FOR MEMBER GATEWAY HUB SERVICE------");
    if (httpclient != null) {
        try {
            HttpUriRequest pulseupdate = RequestBuilder.post().setUri(new URI(PULSE_UPDATE_URL))
                    .addParameter(PULSE_UPDATE_PARAM, PULSE_UPDATE_5_VALUE).build();
            CloseableHttpResponse response = httpclient.execute(pulseupdate);
            try {
                HttpEntity entity = response.getEntity();

                System.out.println(
                        "MemberGatewayHubServiceTest :: 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("MemberGatewayHubServiceTest :: JSON response returned : " + jsonResp);
                EntityUtils.consume(entity);

                JSONObject jsonObj = new JSONObject(jsonResp);
                JSONObject memberGatewayHubObj = jsonObj.getJSONObject("MemberGatewayHub");
                Assert.assertNotNull(
                        "MemberGatewayHubServiceTest :: Server returned null response for MemberGatewayHub",
                        memberGatewayHubObj);
                Assert.assertTrue(
                        "MemberGatewayHubServiceTest :: Server did not return 'isGatewaySender' for member",
                        memberGatewayHubObj.has("isGatewaySender"));
                Boolean boolIsGatewaySender = memberGatewayHubObj.getBoolean("isGatewaySender");

                Assert.assertTrue(
                        "MemberGatewayHubServiceTest :: Server did not return 'gatewaySenders' for member",
                        memberGatewayHubObj.has("gatewaySenders"));
                JSONArray arrGatewaySender = memberGatewayHubObj.getJSONArray("gatewaySenders");
                Assert.assertNotNull(
                        "MemberGatewayHubServiceTest :: Server returned null response for 'gatewaySenders'",
                        arrGatewaySender);
                Assert.assertTrue(
                        "MemberGatewayHubServiceTest :: Server returned mis-matched values for 'isGatewaySender' and gateway senders array count",
                        ((boolIsGatewaySender && (arrGatewaySender.length() > 0))
                                || ((!boolIsGatewaySender) && (arrGatewaySender.length() == 0))));

                Assert.assertTrue(
                        "MemberGatewayHubServiceTest :: Server did not return 'remoteDSId' for member",
                        ((JSONObject) arrGatewaySender.get(0)).has("remoteDSId"));
                Assert.assertTrue(
                        "MemberGatewayHubServiceTest :: Server did not return 'eventsExceedingAlertThreshold' for member",
                        ((JSONObject) arrGatewaySender.get(0)).has("eventsExceedingAlertThreshold"));
            } finally {
                response.close();
            }
        } catch (Exception failed) {
            logException(failed);
            Assert.fail("Exception ! ");
        }
    } else {
        Assert.fail("MemberGatewayHubServiceTest :: No Http connection was established.");
    }
    System.out.println(
            "MemberGatewayHubServiceTest ::  ------TESTCASE END : GATEWAY SENDER PROPERTIES IN RESPONSE CHECK FOR MEMBER GATEWAY HUB SERVICE ------\n");
}

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

/**
*
* Tests that response is for same region
*
* Test method for {@link com.vmware.gemfire.tools.pulse.internal.service.MemberGatewayHubService#execute(javax.servlet.http.HttpServletRequest)}.
*
*///from  ww  w . ja  v  a 2  s  .c  om
@Test
public void testResponseAsyncEventQueueProperties() {
    System.out.println(
            "MemberGatewayHubServiceTest ::  ------TESTCASE BEGIN : ASYNC EVENT QUEUE PROPERTIES IN RESPONSE CHECK FOR MEMBER GATEWAY HUB SERVICE------");
    if (httpclient != null) {
        try {
            HttpUriRequest pulseupdate = RequestBuilder.post().setUri(new URI(PULSE_UPDATE_URL))
                    .addParameter(PULSE_UPDATE_PARAM, PULSE_UPDATE_5_VALUE).build();
            CloseableHttpResponse response = httpclient.execute(pulseupdate);
            try {
                HttpEntity entity = response.getEntity();

                System.out.println(
                        "MemberGatewayHubServiceTest :: 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("MemberGatewayHubServiceTest :: JSON response returned : " + jsonResp);
                EntityUtils.consume(entity);

                JSONObject jsonObj = new JSONObject(jsonResp);
                JSONObject memberGatewayHubObj = jsonObj.getJSONObject("MemberGatewayHub");
                Assert.assertNotNull(
                        "MemberGatewayHubServiceTest :: Server returned null response for MemberGatewayHub",
                        memberGatewayHubObj);

                Assert.assertTrue(
                        "MemberGatewayHubServiceTest :: Server did not return 'asyncEventQueues' for member",
                        memberGatewayHubObj.has("asyncEventQueues"));
                JSONArray arrAsyncEventQueues = memberGatewayHubObj.getJSONArray("asyncEventQueues");
                Assert.assertNotNull(
                        "MemberGatewayHubServiceTest :: Server returned null response for 'asyncEventQueues'",
                        arrAsyncEventQueues);

                Assert.assertTrue("MemberGatewayHubServiceTest :: Server did not return 'id' for member",
                        ((JSONObject) arrAsyncEventQueues.get(0)).has("id"));
                Assert.assertTrue("MemberGatewayHubServiceTest :: Server did not return 'primary' for member",
                        ((JSONObject) arrAsyncEventQueues.get(0)).has("primary"));
                Assert.assertTrue(
                        "MemberGatewayHubServiceTest :: Server did not return 'senderType' for member",
                        ((JSONObject) arrAsyncEventQueues.get(0)).has("senderType"));
                Assert.assertTrue("MemberGatewayHubServiceTest :: Server did not return 'batchSize' for member",
                        ((JSONObject) arrAsyncEventQueues.get(0)).has("batchSize"));
                Assert.assertTrue(
                        "MemberGatewayHubServiceTest :: Server did not return 'batchTimeInterval' for member",
                        ((JSONObject) arrAsyncEventQueues.get(0)).has("batchTimeInterval"));
                Assert.assertTrue(
                        "MemberGatewayHubServiceTest :: Server did not return 'batchConflationEnabled' for member",
                        ((JSONObject) arrAsyncEventQueues.get(0)).has("batchConflationEnabled"));
                Assert.assertTrue(
                        "MemberGatewayHubServiceTest :: Server did not return 'asyncEventListener' for member",
                        ((JSONObject) arrAsyncEventQueues.get(0)).has("asyncEventListener"));
                Assert.assertTrue("MemberGatewayHubServiceTest :: Server did not return 'queueSize' for member",
                        ((JSONObject) arrAsyncEventQueues.get(0)).has("queueSize"));
            } finally {
                response.close();
            }
        } catch (Exception failed) {
            logException(failed);
            Assert.fail("Exception ! ");
        }
    } else {
        Assert.fail("MemberGatewayHubServiceTest :: No Http connection was established.");
    }
    System.out.println(
            "MemberGatewayHubServiceTest ::  ------TESTCASE END : ASYNC EVENT QUEUE PROPERTIES IN RESPONSE CHECK FOR MEMBER GATEWAY HUB SERVICE ------\n");
}

From source file:org.apache.archiva.redback.integration.mail.VelocityMailGenerator.java

public String generateMail(String templateName, AuthenticationKey authkey, String baseUrl) {
    VelocityContext context = createVelocityContext(authkey, baseUrl);

    String packageName = getClass().getPackage().getName().replace('.', '/');
    String templateFile = packageName + "/template/" + templateName + ".vm";

    StringWriter writer = new StringWriter();

    try {/*  w  w  w  .  j av a  2  s.  co  m*/
        velocityEngine.mergeTemplate(templateFile, context, writer);
    } catch (ResourceNotFoundException e) {
        log.error("No such template: '{}'.", templateFile);
    } catch (ParseErrorException e) {
        log.error("Unable to generate email for template '{}': {}", templateFile, e.getMessage(), e);
    } catch (MethodInvocationException e) {
        log.error("Unable to generate email for template '{}': {}", templateFile, e.getMessage(), e);
    } catch (Exception e) {
        log.error("Unable to generate email for template '{}': {}", templateFile, e.getMessage(), e);
    }

    return writer.getBuffer().toString();
}

From source file:be.fedict.eid.applet.service.signer.ooxml.RelationshipTransformService.java

private String toString(Node dom) throws TransformerException {
    Source source = new DOMSource(dom);
    StringWriter stringWriter = new StringWriter();
    Result result = new StreamResult(stringWriter);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    /*//from w  w  w . j  a  va  2 s . com
     * We have to omit the ?xml declaration if we want to embed the
     * document.
     */
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.transform(source, result);
    return stringWriter.getBuffer().toString();
}

From source file:eu.europa.ec.fisheries.uvms.reporting.rest.resources.ReportingResource.java

private ObjectNode mapToGeoJson(ExecutionResultDTO dto) throws IOException {

    ObjectNode rootNode;//from   w w w . j a  va 2  s.com

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
    rootNode = mapper.createObjectNode();
    StringWriter stringWriter = new StringWriter();

    GeometryMapper.INSTANCE.featureCollectionToGeoJson(dto.getMovements(), stringWriter);

    rootNode.set("movements", mapper.readTree(stringWriter.toString()));

    stringWriter.getBuffer().setLength(0);
    GeometryMapper.INSTANCE.featureCollectionToGeoJson(dto.getSegments(), stringWriter);
    rootNode.set("segments", mapper.readTree(stringWriter.toString()));

    rootNode.putPOJO("tracks", dto.getTracks());
    rootNode.putPOJO("trips", dto.getTrips());

    ObjectNode activityNode = new FeatureToGeoJsonJacksonMapper().convert(dto.getActivities());
    rootNode.putPOJO("activities", activityNode);

    rootNode.putPOJO("criteria", dto.getFaCatchSummaryDTO());

    return rootNode;
}

From source file:alba.components.FilteredShowFileRequestHandler.java

private void showFromZooKeeper(SolrQueryRequest req, SolrQueryResponse rsp, CoreContainer coreContainer)
        throws KeeperException, InterruptedException, UnsupportedEncodingException {

    SolrZkClient zkClient = coreContainer.getZkController().getZkClient();

    String adminFile = getAdminFileFromZooKeeper(req, rsp, zkClient, hiddenFiles);

    if (adminFile == null) {
        return;//from  w w w.j a  va 2s.  co m
    }

    // Show a directory listing
    List<String> children = zkClient.getChildren(adminFile, null, true);
    if (children.size() > 0) {

        NamedList<SimpleOrderedMap<Object>> files = new SimpleOrderedMap<>();
        for (String f : children) {
            if (isHiddenFile(req, rsp, f, false, hiddenFiles)) {
                continue;
            }

            SimpleOrderedMap<Object> fileInfo = new SimpleOrderedMap<>();
            files.add(f, fileInfo);
            List<String> fchildren = zkClient.getChildren(adminFile + "/" + f, null, true);
            if (fchildren.size() > 0) {
                fileInfo.add("directory", true);
            } else {
                // TODO? content type
                fileInfo.add("size", f.length());
            }
            // TODO: ?
            // fileInfo.add( "modified", new Date( f.lastModified() ) );
        }
        rsp.add("files", files);
    } else {
        // Include the file contents
        // The file logic depends on RawResponseWriter, so force its use.
        ModifiableSolrParams params = new ModifiableSolrParams(req.getParams());
        params.set(CommonParams.WT, "raw");
        req.setParams(params);

        ContentStreamBase content = new ContentStreamBase.ByteArrayStream(
                zkClient.getData(adminFile, null, null, true), adminFile);
        content.setContentType(req.getParams().get(USE_CONTENT_TYPE));

        // Velocity parsing here!

        // http://velocity.apache.org/engine/devel/developer-guide.html#The_Context
        Velocity.init();

        VelocityContext context = new VelocityContext();

        //add some vars??
        //context.put( "context", new String("Velocity") );

        for (int i = 0; i < rsp.getValues().size(); i++) {
            context.put(rsp.getValues().getName(i), rsp.getValues().getVal(i));
        }

        Template template = null;

        String fname = req.getParams().get("file", null);

        try {
            //TODO what if fname is null?
            template = Velocity.getTemplate(fname);
        } catch (ResourceNotFoundException rnfe) {
            // couldn't find the template, try to load it

            // TODO it should be fired only for SOME mimetypes (..through an annotation??)
            StringBuilder sb = this.getTemplate(content);

            RuntimeServices runtimeServices = RuntimeSingleton.getRuntimeServices();
            StringReader reader = new StringReader(sb.toString());
            SimpleNode node = null;
            try {
                node = runtimeServices.parse(reader, fname);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                logger.error("error while parsing new template", e);
            }

            template = new Template();

            template.setRuntimeServices(runtimeServices);

            if (node != null) {
                template.setData(node);
            } else {
                logger.error("node null, can't set on template");
            }

            template.initDocument();

        } catch (ParseErrorException pee) {
            // syntax error: problem parsing the template
            logger.error("error while parsing template: ", pee);

        } catch (MethodInvocationException mie) {
            // something invoked in the template
            // threw an exception
            logger.error("error while parsing temaplate: ", mie);
        } catch (Exception e) {
            logger.error("error while parsing temaplate: ", e);
        }

        StringWriter sw = new StringWriter();

        template.merge(context, sw);

        // http://stackoverflow.com/questions/18571223/how-to-convert-java-string-into-byte
        content = new ContentStreamBase.ByteArrayStream(
                sw.getBuffer().toString().getBytes(Charset.forName("UTF-8")), adminFile);
        content.setContentType(req.getParams().get(USE_CONTENT_TYPE));

        rsp.add(RawResponseWriter.CONTENT, content);
    }
    rsp.setHttpCaching(false);
}

From source file:de.mogwai.common.web.component.renderkit.html.common.TableRenderer.java

protected void renderChildAndCheckEmptyness(FacesContext aContext, UIComponent aComponent) throws IOException {

    ResponseWriter theWriter = aContext.getResponseWriter();

    StringWriter theStringWriter = new StringWriter();
    ResponseWriter theBufferedWriter = theWriter.cloneWithWriter(theStringWriter);
    aContext.setResponseWriter(theBufferedWriter);

    if (aComponent != null) {
        RendererUtils.renderChild(aContext, aComponent);
    }/*from  w w w. jav  a 2s .  c o  m*/

    aContext.setResponseWriter(theWriter);

    theStringWriter.flush();
    StringBuffer theContent = stripCommentsFromString(theStringWriter.getBuffer());
    if (theContent.length() > 0) {
        theWriter.write(theContent.toString());
    } else {
        theWriter.write("<div style=\"width:1px; height:1px;\"></div>");
    }

}

From source file:org.ajax4jsf.context.AjaxContextImpl.java

public void saveViewState(FacesContext context) throws IOException {
    ResponseWriter writer = context.getResponseWriter();
    StateManager stateManager = context.getApplication().getStateManager();
    Object serializedView = stateManager.saveView(context);
    if (null != serializedView && null != writer) {
        StringWriter bufWriter = new StringWriter();
        ResponseWriter tempWriter;/*from w  w w .jav  a2  s.  c  o  m*/
        tempWriter = writer.cloneWithWriter(bufWriter);
        context.setResponseWriter(tempWriter);
        stateManager.writeState(context, serializedView);
        tempWriter.flush();
        if (bufWriter.getBuffer().length() > 0) {
            context.getExternalContext().getRequestMap().put(AjaxViewHandler.SERIALIZED_STATE_KEY,
                    bufWriter.toString());
        }
        context.setResponseWriter(writer);
    }
}

From source file:com.redhat.rhn.frontend.taglibs.ListDisplayTagBase.java

protected void renderPanelHeading(JspWriter out) throws IOException {

    StringWriter headFilterContent = new StringWriter();
    StringWriter titleContent = new StringWriter();
    StringWriter headAddons = new StringWriter();

    renderTitle(titleContent);/*from www.  j a  va2 s  . co m*/
    if (getPageList().hasFilter()) {
        headFilterContent.append("<div class=\"spacewalk-list-filter\">");
        renderFilterBox(headFilterContent);
        headFilterContent.append("</div>");
    }
    renderHeadExtraAddons(headAddons);

    int headContentLength = headFilterContent.getBuffer().length() + titleContent.getBuffer().length()
            + headAddons.getBuffer().length();

    if (headContentLength > 0) {
        out.println("<div class=\"panel-heading\">");
        out.println(titleContent.toString());
        out.println("<div class=\"spacewalk-list-head-addons\">");
        out.println(headFilterContent.toString());
        out.println("<div class=\"spacewalk-list-head-addons-extra\">");
        out.println(headAddons.toString());
        out.println("</div>");
        out.println("</div>");
        out.println("</div>");
    }
}