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:br.org.indt.ndg.server.client.TemporaryOpenRosaBussinessDelegate.java

/********** Uploading OpenRosa Surveys and Results **********/

public boolean parseAndPersistSurvey(InputStreamReader inputStreamReader, String contentType)
        throws IOException {
    String surveyString = parseMultipartEncodedFile(inputStreamReader, contentType, "filename");
    String surveyId = null;/* w  w w .  ja  v  a 2 s  . c  o  m*/
    String surveyIdOriginal = null;

    Document surveyDomDocument = null;
    ByteArrayInputStream streamToParse = new ByteArrayInputStream(surveyString.getBytes("UTF-8"));
    try {
        surveyDomDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(streamToParse);
    } catch (SAXException e) {
        e.printStackTrace();
        return false;
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
        return false;
    } finally {
        streamToParse.close();
    }

    NodeList dataNodeList = surveyDomDocument.getElementsByTagName("data");
    if (dataNodeList.getLength() != 1) {
        return false; // there MUST be exactly 1 <data> node
    } else {
        Element dataElement = (Element) dataNodeList.item(0);
        Random rand = new Random(System.currentTimeMillis());
        int newId = rand.nextInt(Integer.MAX_VALUE);
        surveyId = String.valueOf(newId);
        surveyIdOriginal = dataElement.getAttribute("id");
        dataElement.setAttribute("id", String.valueOf(newId));
        StringWriter stringWriter = null;
        try {
            Source source = new DOMSource(surveyDomDocument);
            stringWriter = new StringWriter();
            Result result = new StreamResult(stringWriter);
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "no");
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            transformer.setOutputProperty(OutputKeys.METHOD, "xml");
            transformer.transform(source, result);
            surveyString = stringWriter.getBuffer().toString();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            stringWriter.close();
        }
        log.info("========================");
        log.info("Original Survey Id: " + surveyIdOriginal);
        log.info("New Survey Id: " + surveyId);
        log.info("========================");
    }
    return persistSurvey(surveyString, surveyId, surveyIdOriginal);
}

From source file:nl.nn.adapterframework.extensions.svn.ScanTibcoSolutionPipe.java

public PipeRunResult doPipe(Object input, IPipeLineSession session) throws PipeRunException {
    StringWriter stringWriter = new StringWriter();
    XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
    XMLStreamWriter xmlStreamWriter;
    try {//from w w  w  .j  av  a2 s. c o m
        xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(stringWriter);
        xmlStreamWriter.writeStartDocument();
        xmlStreamWriter.writeStartElement("root");
        xmlStreamWriter.writeAttribute("url", getUrl());
        // xmlStreamWriter.writeAttribute("level",
        // String.valueOf(getLevel()));
        process(xmlStreamWriter, getUrl(), getLevel());
        xmlStreamWriter.writeEndDocument();
        xmlStreamWriter.flush();
        xmlStreamWriter.close();
    } catch (XMLStreamException e) {
        throw new PipeRunException(this, "XMLStreamException", e);
    } catch (DomBuilderException e) {
        throw new PipeRunException(this, "DomBuilderException", e);
    } catch (XPathExpressionException e) {
        throw new PipeRunException(this, "XPathExpressionException", e);
    }

    return new PipeRunResult(getForward(), stringWriter.getBuffer().toString());
}

From source file:org.metaservice.core.AbstractDispatcher.java

protected void sendDataByLoad(URI metadata, Collection<Statement> generatedStatements,
        Set<Statement> loadedStatements) throws MetaserviceException {
    StringWriter stringWriter = new StringWriter();
    try {/*from  w  w w . j av  a2s.  c  om*/
        NTriplesWriter nTriplesWriter = new NTriplesWriter(stringWriter);
        Repository inferenceRepository = createTempRepository(true);
        RepositoryConnection inferenceRepositoryConnection = inferenceRepository.getConnection();
        LOGGER.debug("Start inference...");
        inferenceRepositoryConnection.add(loadedStatements);
        inferenceRepositoryConnection.add(generatedStatements);
        LOGGER.debug("Finished inference");
        List<Statement> filteredStatements = getGeneratedStatements(inferenceRepositoryConnection,
                loadedStatements);
        nTriplesWriter.startRDF();
        for (Statement statement : filteredStatements) {
            nTriplesWriter.handleStatement(statement);
        }
        nTriplesWriter.endRDF();
        inferenceRepositoryConnection.close();
        inferenceRepository.shutDown();

        Executor executor = Executor.newInstance(HttpClientBuilder.create()
                .setConnectionManager(new BasicHttpClientConnectionManager()).build());

        executor.execute(Request.Post(config.getSparqlEndpoint() + "?context-uri=" + metadata.toString())
                .bodyStream(new ByteArrayInputStream(stringWriter.getBuffer().toString().getBytes("UTF-8")),
                        ContentType.create("text/plain", Charset.forName("UTF-8"))));
    } catch (RDFHandlerException | IOException | RepositoryException e) {
        throw new MetaserviceException(e);
    }
}

From source file:edu.cornell.med.icb.goby.stats.TestAnnotationAveragingWriter.java

@Test
public void testCase4() {
    String[] samples = new String[] { "sample1", "sample2", "sample3" };
    int[] positions = new int[] { 6, 8, 14, 16 };
    int[][] C = { { 5, 3, 9, 8 }, { 4, 6, 3, 2 }, { 8, 3, 8, 9 } };
    int[][] Cm = { { 9, 7, 1, 5 }, { 9, 7, 9, 3 }, { 2, 3, 2, 8 } };
    testSupport = new MethylCountProviderTestSupport(samples, positions, "Case2", C, Cm);
    final StringWriter stringWriter = new StringWriter();
    AnnotationAveragingWriter testWriter = new AnnotationAveragingWriter(stringWriter, genome, testSupport);
    testWriter.setWriteNumSites(false);//from   w  w  w. j  a  v a  2  s.co  m
    testWriter.setContexts(DEFAULT_TEST_CONTEXTS);
    testWriter.setAnnotationFilename("test-data/vcf-averaging/annotations-1.tsv");
    testWriter.writeRecord();
    testWriter.writeRecord();
    testWriter.writeRecord();
    testWriter.writeRecord();
    testWriter.close();
    assertEquals("Test Case 4 result: ",
            "Chromosome\tStart\tEnd\tFeature\tMR[sample1][CpG]\tMR[sample2][CpG]\tMR[sample3][CpG]\tMR[sample1][CpA]\tMR[sample2][CpA]\tMR[sample3][CpA]\tMR[sample1][CpC]\tMR[sample2][CpC]\tMR[sample3][CpC]\tMR[sample1][CpT]\tMR[sample2][CpT]\tMR[sample3][CpT]\tMR[sample1][CpN]\tMR[sample2][CpN]\tMR[sample3][CpN]\n"
                    + "Case2\t5\t9\tannotation1\t66.67\t61.54\t31.25\t\t\t\t\t\t\t\t\t\t\t\t\n"
                    + "Case2\t13\t17\tannotation2\t26.09\t70.59\t37.04\t\t\t\t\t\t\t\t\t\t\t\t\n",
            stringWriter.getBuffer().toString());
}

From source file:edu.cornell.med.icb.goby.stats.TestAnnotationAveragingWriter.java

@Test
// test writing counts and sites
public void testCase10() {
    String[] samples = new String[] { "sample1" };
    int[] positions = new int[] { 5, 7 };
    int[][] C = { { 5, 3 } };
    int[][] Cm = { { 9, 8 } };
    testSupport = new MethylCountProviderTestSupport(samples, positions, "Case1", C, Cm);
    final StringWriter stringWriter = new StringWriter();
    AnnotationAveragingWriter testWriter = new AnnotationAveragingWriter(stringWriter, genome, testSupport);
    testWriter.setWriteNumSites(true);//from w  ww .ja  v  a 2s .c  om
    testWriter.setWriteCounts(true);
    testWriter.setContexts(DEFAULT_TEST_CONTEXTS);
    testWriter.setAnnotationFilename("test-data/vcf-averaging/annotations-1.tsv");
    testWriter.writeRecord();
    testWriter.writeRecord();
    testWriter.close();
    assertEquals("Test Case 1 result: ",
            "Chromosome\tStart\tEnd\tFeature\t#C[sample1][CpG]\t#C[sample1][CpA]\t#C[sample1][CpC]\t#C[sample1][CpT]\t#C[sample1][CpN]\t#Cm[sample1][CpG]\t#Cm[sample1][CpA]\t#Cm[sample1][CpC]\t#Cm[sample1][CpT]\t#Cm[sample1][CpN]\tMR[sample1][CpG]\tMR[sample1][CpA]\tMR[sample1][CpC]\tMR[sample1][CpT]\tMR[sample1][CpN]\t#Sites[sample1][CpG]\t#Sites[sample1][CpA]\t#Sites[sample1][CpC]\t#Sites[sample1][CpT]\t#Sites[sample1][CpN]\n"
                    + "Case1\t4\t8\tannotation0\t8\t0\t0\t0\t0\t17\t0\t0\t0\t0\t68.00\t\t\t\t\t2\t0\t0\t0\t0\n",
            stringWriter.getBuffer().toString());
}

From source file:at.ac.tuwien.dsg.comot.orchestrator.interraction.rsybl.rSYBLInterraction.java

public void sendUpdatedConfigToRSYBL(CloudService serviceTemplate,
        CompositionRulesConfiguration compositionRulesConfiguration, String effectsJSON) {

    HttpHost endpoint = new HttpHost(rSYBL_BASE_IP, rSYBL_BASE_PORT);

    {/* w  w w .j  a  va2s  . c om*/
        DefaultHttpClient httpClient = new DefaultHttpClient();

        try {

            JAXBContext jAXBContext = JAXBContext.newInstance(CompositionRulesConfiguration.class);

            Marshaller marshaller = jAXBContext.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

            StringWriter sw = new StringWriter();
            log.info("Sending  updated composition rules");
            marshaller.marshal(compositionRulesConfiguration, sw);
            log.info(sw.toString());

            URI putDeploymentStructureURL = UriBuilder
                    .fromPath(rSYBL_BASE_URL + "/" + serviceTemplate.getId() + "/compositionRules").build();
            HttpPost putDeployment = new HttpPost(putDeploymentStructureURL);

            StringEntity entity = new StringEntity(sw.getBuffer().toString());

            entity.setContentType("application/xml");
            entity.setChunked(true);

            putDeployment.setEntity(entity);

            log.info("Executing request " + putDeployment.getRequestLine());
            HttpResponse response = httpClient.execute(endpoint, putDeployment);
            HttpEntity resEntity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (response.getStatusLine().getStatusCode() == 200) {

            }
            if (resEntity != null) {
                System.out.println("Response content length: " + resEntity.getContentLength());
                System.out.println("Chunked?: " + resEntity.isChunked());
            }

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

    }

    {
        DefaultHttpClient httpClient = new DefaultHttpClient();

        try {

            URI putDeploymentStructureURL = UriBuilder
                    .fromPath(rSYBL_BASE_URL + "/" + serviceTemplate.getId() + "/elasticityCapabilitiesEffects")
                    .build();
            HttpPost putDeployment = new HttpPost(putDeploymentStructureURL);

            StringEntity entity = new StringEntity(effectsJSON);

            entity.setContentType("application/json");
            entity.setChunked(true);

            putDeployment.setEntity(entity);

            log.info("Send updated Effects");
            log.info(effectsJSON);

            HttpResponse response = httpClient.execute(endpoint, putDeployment);

            HttpEntity resEntity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (response.getStatusLine().getStatusCode() == 200) {

            }
            if (resEntity != null) {
                System.out.println("Response content length: " + resEntity.getContentLength());
                System.out.println("Chunked?: " + resEntity.isChunked());
            }

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

    }

    {
        DefaultHttpClient httpClient = new DefaultHttpClient();

        try {

            JAXBContext jAXBContext = JAXBContext.newInstance(CloudServiceXML.class);
            CloudServiceXML cloudServiceXML = toRSYBLRepresentation(serviceTemplate);
            Marshaller marshaller = jAXBContext.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            StringWriter sw = new StringWriter();
            log.info("Sending updated service description to rSYBL");
            marshaller.marshal(cloudServiceXML, sw);
            log.info(sw.toString());

            URI putDeploymentStructureURL = UriBuilder
                    .fromPath(rSYBL_BASE_URL + "/" + serviceTemplate.getId() + "/elasticityRequirements")
                    .build();
            HttpPost putDeployment = new HttpPost(putDeploymentStructureURL);

            StringEntity entity = new StringEntity(sw.getBuffer().toString());

            entity.setContentType("application/xml");
            entity.setChunked(true);

            putDeployment.setEntity(entity);

            log.info("Executing request " + putDeployment.getRequestLine());
            HttpResponse response = httpClient.execute(endpoint, putDeployment);
            HttpEntity resEntity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (response.getStatusLine().getStatusCode() == 200) {

            }
            if (resEntity != null) {
                System.out.println("Response content length: " + resEntity.getContentLength());
                System.out.println("Chunked?: " + resEntity.isChunked());
            }

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

    }

}

From source file:org.apache.axis.SOAPPart.java

/**
 * Get the contents of this Part (not the headers!), as a String.
 * This will force buffering of the message.
 *
 * @return a <code>String</code> containing the content of this message
 * @throws AxisFault  if there is an error serializing this part
 *//*from w  ww  .  j  a va  2 s. com*/
public String getAsString() throws AxisFault {
    log.debug("Enter: SOAPPart::getAsString");
    if (currentForm == FORM_STRING) {
        if (log.isDebugEnabled()) {
            log.debug("Exit: SOAPPart::getAsString(): " + currentMessage);
        }
        return (String) currentMessage;
    }

    if (currentForm == FORM_INPUTSTREAM || currentForm == FORM_BODYINSTREAM) {
        getAsBytes();
        // Fall thru to "Bytes"
    }

    if (currentForm == FORM_OPTIMIZED) {
        try {
            currentMessageAsBytes = ((ByteArray) currentMessage).toByteArray();
        } catch (IOException e) {
            throw AxisFault.makeFault(e);
        }

        try {
            setCurrentForm(new String((byte[]) currentMessageAsBytes, currentEncoding), FORM_STRING);
        } catch (UnsupportedEncodingException ue) {
            setCurrentForm(new String((byte[]) currentMessageAsBytes), FORM_STRING);
        }
        if (log.isDebugEnabled()) {
            log.debug("Exit: SOAPPart::getAsString(): " + currentMessage);
        }
        return (String) currentMessage;
    }

    if (currentForm == FORM_BYTES) {
        // If the current message was already converted from
        // a String to byte[], return the String representation
        // (this is done to avoid unnecessary conversions)
        if (currentMessage == currentMessageAsBytes && currentMessageAsString != null) {
            if (log.isDebugEnabled()) {
                log.debug("Exit: SOAPPart::getAsString(): " + currentMessageAsString);
            }
            return currentMessageAsString;
        }

        // Save this message in case it is requested later in getAsBytes
        currentMessageAsBytes = (byte[]) currentMessage;
        try {
            setCurrentForm(new String((byte[]) currentMessage, currentEncoding), FORM_STRING);
        } catch (UnsupportedEncodingException ue) {
            setCurrentForm(new String((byte[]) currentMessage), FORM_STRING);
        }
        currentMessageAsString = (String) currentMessage;
        if (log.isDebugEnabled()) {
            log.debug("Exit: SOAPPart::getAsString(): " + currentMessage);
        }
        return (String) currentMessage;
    }

    if (currentForm == FORM_FAULT) {
        StringWriter writer = new StringWriter();
        try {
            this.writeTo(writer);
        } catch (Exception e) {
            log.error(Messages.getMessage("exception00"), e);
            return null;
        }
        setCurrentForm(writer.getBuffer().toString(), FORM_STRING);
        if (log.isDebugEnabled()) {
            log.debug("Exit: SOAPPart::getAsString(): " + currentMessage);
        }
        return (String) currentMessage;
    }

    if (currentForm == FORM_SOAPENVELOPE) {
        StringWriter writer = new StringWriter();
        try {
            this.writeTo(writer);
        } catch (Exception e) {
            throw AxisFault.makeFault(e);
        }
        setCurrentForm(writer.getBuffer().toString(), FORM_STRING);
        if (log.isDebugEnabled()) {
            log.debug("Exit: SOAPPart::getAsString(): " + currentMessage);
        }
        return (String) currentMessage;
    }

    log.error(Messages.getMessage("cantConvert01", "" + currentForm));

    log.debug("Exit: SOAPPart::getAsString()");
    return null;
}

From source file:gov.va.ds4p.ds4pmobileportal.ui.eHealthExchange.java

private String converXmlDocToString(Document xmlDocument) {

    String xmlString = "";

    try {//from w  ww  . j  av  a 2 s.  c  om
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

        StringWriter writer = new StringWriter();
        transformer.transform(new DOMSource(xmlDocument), new StreamResult(writer));
        xmlString = writer.getBuffer().toString(); //.replaceAll("\n|\r", "");
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return xmlString;
}

From source file:edu.cornell.med.icb.goby.stats.TestAnnotationAveragingWriter.java

@Test
public void testCase3() {
    String[] samples = new String[] { "sample1" };
    int[] positions = new int[] { 5, 7, 12, 14, 19, 24, 26, 29 };
    int[][] C = { { 5, 3, 9, 8, 9, 9, 8, 6 } };
    int[][] Cm = { { 9, 7, 1, 5, 3, 7, 8, 3 } };
    testSupport = new MethylCountProviderTestSupport(samples, positions, "Case3", C, Cm);
    final StringWriter stringWriter = new StringWriter();
    AnnotationAveragingWriter testWriter = new AnnotationAveragingWriter(stringWriter, genome, testSupport);
    testWriter.setWriteNumSites(false);/*from w ww  .j a v a 2 s .  co  m*/
    testWriter.setContexts(DEFAULT_TEST_CONTEXTS);
    testWriter.setAnnotationFilename("test-data/vcf-averaging/annotations-1.tsv");
    testWriter.writeRecord();
    testWriter.writeRecord();
    testWriter.writeRecord();
    testWriter.writeRecord();
    testWriter.writeRecord();
    testWriter.writeRecord();
    testWriter.writeRecord();
    testWriter.writeRecord();
    testWriter.close();
    assertEquals("Test Case 3 result: ",
            "Chromosome\tStart\tEnd\tFeature\tMR[sample1][CpG]\tMR[sample1][CpA]\tMR[sample1][CpC]\tMR[sample1][CpT]\tMR[sample1][CpN]\n"
                    + "Case3\t4\t21\tannotation4\t52.78\t\t\t\t\n"
                    + "Case3\t11\t26\tannotation6\t35.82\t\t\t\t\n"
                    + "Case3\t4\t30\tannotation3\t43.00\t\t\t\t\n"
                    + "Case3\t11\t30\tannotation5\t28.13\t\t\t\t\n",
            stringWriter.getBuffer().toString());
}

From source file:net.bull.javamelody.TestMonitoringFilter.java

private void monitoring(Map<HttpParameter, String> parameters, boolean checkResultContent)
        throws IOException, ServletException {
    final HttpServletRequest request = createNiceMock(HttpServletRequest.class);
    expect(request.getRequestURI()).andReturn("/test/monitoring").anyTimes();
    expect(request.getRequestURL()).andReturn(new StringBuffer("/test/monitoring")).anyTimes();
    expect(request.getContextPath()).andReturn(CONTEXT_PATH).anyTimes();
    expect(request.getRemoteAddr()).andReturn("here").anyTimes();
    final Random random = new Random();
    if (random.nextBoolean()) {
        expect(request.getHeaders("Accept-Encoding"))
                .andReturn(Collections.enumeration(Arrays.asList("application/gzip"))).anyTimes();
    } else {/*from   w ww  .j  ava 2  s  . c  o  m*/
        expect(request.getHeaders("Accept-Encoding"))
                .andReturn(Collections.enumeration(Arrays.asList("text/html"))).anyTimes();
    }
    for (final Map.Entry<HttpParameter, String> entry : parameters.entrySet()) {
        if (HttpParameter.REQUEST == entry.getKey()) {
            expect(request.getHeader(entry.getKey().getName())).andReturn(entry.getValue()).anyTimes();
        } else {
            expect(entry.getKey().getParameterFrom(request)).andReturn(entry.getValue()).anyTimes();
        }
    }
    final Range range = Period.JOUR.getRange();
    final List<JavaInformations> javaInformationsList = Collections
            .singletonList(new JavaInformations(null, false));
    // getAttribute("range") et getAttribute("javaInformationsList") pour PdfController
    expect(request.getAttribute("range")).andReturn(range).anyTimes();
    expect(request.getAttribute("javaInformationsList")).andReturn(javaInformationsList).anyTimes();
    if (parameters.isEmpty() || HttpPart.JNLP.getName().equals(parameters.get(HttpParameter.PART))) {
        // dans au moins un cas on met un cookie
        final Cookie[] cookies = { new Cookie("dummy", "dummy"),
                new Cookie(PERIOD_COOKIE_NAME, Period.SEMAINE.getCode()), };
        expect(request.getCookies()).andReturn(cookies).anyTimes();
    }
    final HttpServletResponse response = createNiceMock(HttpServletResponse.class);
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    expect(response.getOutputStream()).andReturn(new FilterServletOutputStream(output)).anyTimes();
    final StringWriter stringWriter = new StringWriter();
    expect(response.getWriter()).andReturn(new PrintWriter(stringWriter)).anyTimes();
    final FilterChain chain = createNiceMock(FilterChain.class);

    replay(request);
    replay(response);
    replay(chain);
    monitoringFilter.doFilter(request, response, chain);
    verify(request);
    verify(response);
    verify(chain);

    if (checkResultContent) {
        assertTrue("result", output.size() != 0 || stringWriter.getBuffer().length() != 0);
    }
}