Example usage for java.io StringWriter write

List of usage examples for java.io StringWriter write

Introduction

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

Prototype

public void write(String str) 

Source Link

Document

Write a string.

Usage

From source file:com.ibm.sbt.test.lib.MockSerializer.java

private String serialize(Header[] o) {
    StringWriter w = new StringWriter();
    for (Header h : o) {
        w.write("\n    <header>\n        <name><![CDATA[");
        w.write(h.getName());/*  w  ww . j  a  va2 s .c o  m*/
        w.write("]]></name>\n        <value><![CDATA[");
        w.write(h.getValue());
        w.write("]]></value>\n    </header>");

    }

    return w.toString();
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.individual.ExternalIndividualController.java

JSONObject getExternalInfoFromService(String serviceURL, JSONArray propertiesJSON) {
    JSONObject jsonObject = null;/*from   w w w  . java  2 s. c o m*/
    String results = null;

    try {

        StringWriter sw = new StringWriter();
        URL rss = new URL(serviceURL);

        BufferedReader in = new BufferedReader(new InputStreamReader(rss.openStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            sw.write(inputLine);
        }
        in.close();

        results = sw.toString();
        log.debug("Results string is " + results);
        // System.out.println("results before processing: "+results);

        jsonObject = extractInfoAsJSON(results, propertiesJSON);

    } catch (Exception ex) {
        log.error("Exception occurred in retrieving results", ex);
        //ex.printStackTrace();
    }
    return jsonObject;
}

From source file:org.cloudbyexample.dc.agent.command.ImageClientImpl.java

private String convertInputStreamToString(InputStream response) {
    StringWriter logwriter = new StringWriter();

    try {// ww w. j a va 2s . c  om
        LineIterator itr = IOUtils.lineIterator(response, "UTF-8");

        while (itr.hasNext()) {
            String line = itr.next();
            logwriter.write(line + (itr.hasNext() ? "\n" : ""));

            logger.info(line);
        }

        return logwriter.toString();
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        IOUtils.closeQuietly(response);
    }
}

From source file:javancss.NcssTest.java

public void testNcssAndMore() throws IOException {
    final int ncss1 = 318;
    checkNcss(1, ncss1);//from   w  w  w .  j a v  a  2s .com

    final int ncss6 = 565;
    checkNcssAndLoc(6, ncss6, 1254);

    // Nr. 10
    Javancss javancss = measureTestFile(9);
    assertFalse("LOC: " + javancss.getLOC(), ncss1 != javancss.getLOC());

    checkNcssAndLoc(10, ncss6);
    checkNcssAndLoc(11);

    javancss = checkNcssAndLoc(12);
    List<FunctionMetric> vFunctions = javancss.getFunctionMetrics();
    String sFirstFunction = vFunctions.get(0).name;
    assertNotNull(sFirstFunction);
    /* System.out.println( sFirstFunction ); */
    assertFalse(sFirstFunction, !sFirstFunction.equals("Test12.readFile(URL)"));

    // Nr. 22
    javancss = measureTestFile(19);
    vFunctions = javancss.getFunctionMetrics();
    sFirstFunction = vFunctions.get(0).name;
    assertFalse(sFirstFunction, !sFirstFunction.equals("test.Test19.foo(String[],Controller)"));
    sFirstFunction = vFunctions.get(3).name;
    assertFalse(!sFirstFunction.equals("test.Test19.main(String[])"));

    javancss = checkNcss(23, 10);
    vFunctions = javancss.getFunctionMetrics();
    assertFalse(vFunctions.size() != 7);
    assertFalse(measureTestFile(24).getFunctionMetrics().size() != vFunctions.size());

    // Nr. 30
    javancss = checkNcss(25, 12);
    assertFalse(javancss.getFunctionMetrics().size() != 9);

    javancss = measureTestFile(56);
    StringWriter sw = new StringWriter();
    javancss.printPackageNcss(sw);
    sw.write("\n");
    javancss.printObjectNcss(sw);
    sw.write("\n");
    javancss.printFunctionNcss(sw);

    String sOutput56 = sw.toString().replaceAll("\r\n", "\n");
    String sCompare56 = FileUtils.readFileToString(getTestFile("Output56.txt"), "ISO-8859-1");
    assertEquals("File test/Output56.txt and javancss output differs", sOutput56, sCompare56);

    // check that javadocs are counted correctly
    // after patches for additional comment counting
    javancss = measureTestFile(32);
    sw = new StringWriter();
    javancss.printPackageNcss(sw);
    sw.write("\n");
    javancss.printObjectNcss(sw);
    sw.write("\n");
    javancss.printFunctionNcss(sw);

    String sOutput32 = sw.toString().replaceAll("\r\n", "\n");
    String sCompare32 = FileUtils.readFileToString(getTestFile("Output32.txt"), "ISO-8859-1");
    assertEquals("File test/Output32.txt and javancss output differs", sOutput32, sCompare32);
}

From source file:org.easyrec.plugin.slopeone.store.dao.impl.LogEntryDAOMysqlImpl.java

public int insertLogEntry(LogEntry logEntry) {
    StringWriter configWriter = new StringWriter();
    StringWriter statsWriter = new StringWriter();

    try {/*ww  w  . j a  va2s . c o  m*/
        JAX_MARSHALLER.marshal(logEntry.getConfiguration(), configWriter);
    } catch (JAXBException ex) {
        configWriter.write("[marshalling error]");

        logger.error("failed to marshal configuration", ex);
    }

    try {
        JAX_MARSHALLER.marshal(logEntry.getStatistics(), statsWriter);
    } catch (JAXBException ex) {
        configWriter.write("[marshalling error]");

        logger.error("failed to marshal statistics", ex);
    }

    Object[] args = new Object[] { logEntry.getTenantId(), logEntry.getExecution(), configWriter.toString(),
            statsWriter.toString() };

    return getJdbcTemplate().update(QUERY_INSERT, args, ARGT_INSERT);
}

From source file:eu.fusepool.p3.transformer.client.TransformerClientImpl.java

@Override
public Entity transform(Entity entity, MimeType... acceptedFormats) {
    HttpURLConnection connection = null;
    try {/*  w w w  .  jav  a2  s.co  m*/
        final URL transfromerUrl = uri.toURL();
        connection = (HttpURLConnection) transfromerUrl.openConnection();
        connection.setRequestMethod("POST");
        String acceptHeaderValue = null;
        if (acceptedFormats.length > 0) {
            final StringWriter acceptString = new StringWriter();
            double q = 1;
            for (MimeType mimeType : acceptedFormats) {
                acceptString.write(mimeType.toString());
                acceptString.write("; q=");
                acceptString.write(Double.toString(q));
                q = q * 0.9;
                acceptString.write(", ");
            }
            acceptHeaderValue = acceptString.toString();
            connection.setRequestProperty("Accept", acceptHeaderValue);
        }

        connection.setRequestProperty("Content-Type", entity.getType().toString());
        if (entity.getContentLocation() != null) {
            connection.setRequestProperty("Content-Location", entity.getContentLocation().toString());
        }

        connection.setDoOutput(true);
        connection.setUseCaches(false);
        try (OutputStream out = connection.getOutputStream()) {
            entity.writeData(out);
        }
        final int responseCode = connection.getResponseCode();
        if (responseCode == 200) {
            return getResponseEntity(connection);
        }
        if ((responseCode == 202) || (responseCode == 201)) {
            final String location = connection.getHeaderField("Location");
            if (location == null) {
                throw new RuntimeException("No location header in first 202 response");
            }
            return getAsyncResponseEntity(new URL(transfromerUrl, location), acceptHeaderValue);
        }
        throw new UnexpectedResponseException(responseCode, getResponseEntity(connection));

    } catch (IOException e) {
        throw new RuntimeException("Cannot establish connection to " + uri.toString() + " !", e);
    } catch (MimeTypeParseException ex) {
        throw new RuntimeException("Error parsing MediaType returned from Server. ", ex);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:org.jboss.test.classloader.leak.test.ClassloaderLeakTestBase.java

private void makeWebRequest(String url, String responseContent) {
    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(url);
    int responseCode = 0;
    try {/*w w  w .j a v a 2s .  c o  m*/
        responseCode = client.executeMethod(method);

        assertTrue("Get OK with url: " + url + " responseCode: " + responseCode,
                responseCode == HttpURLConnection.HTTP_OK);

        InputStream rs = method.getResponseBodyAsStream();
        InputStreamReader reader = new InputStreamReader(rs);
        StringWriter writer = new StringWriter();
        int c;
        while ((c = reader.read()) != -1)
            writer.write(c);

        String rsp = writer.toString();

        assertTrue("Response contains " + responseContent, rsp.indexOf(responseContent) >= 0);
    } catch (IOException e) {
        e.printStackTrace();
        fail("HttpClient executeMethod fails." + e.toString());
    } finally {
        method.releaseConnection();
    }
}

From source file:com.norconex.importer.ImporterConfig.java

private void writeObject(Writer out, String tagName, Object object, boolean ignore) throws IOException {
    if (object == null) {
        if (ignore) {
            out.write("<" + tagName + " ignore=\"" + ignore + "\" />");
        }/*from  w  ww.  j a v a  2 s .c om*/
        return;
    }
    StringWriter w = new StringWriter();
    if (object instanceof IXMLConfigurable) {
        ((IXMLConfigurable) object).saveToXML(w);
    } else {
        w.write("<" + tagName + " class=\"" + object.getClass().getCanonicalName() + "\" />");
    }
    String xml = w.toString();
    if (ignore) {
        xml = xml.replace("<" + tagName + " class=\"", "<" + tagName + " ignore=\"true\" class=\"");
    }
    out.write(xml);
    out.flush();
}

From source file:nl.armatiek.xslweb.web.servlet.XSLWebServlet.java

private Destination getDestination(WebApp webApp, Destination destination, PipelineStep step) {
    if (webApp.getDevelopmentMode() && step.getLog()) {
        StringWriter sw = new StringWriter();
        sw.write("----------\n");
        sw.write("OUTPUT OF STEP: \"" + step.getName() + "\":\n");
        Serializer debugSerializer = webApp.getProcessor().newSerializer(new ProxyWriter(sw) {
            @Override/*from   www  . j  a  v a2 s.  c  o m*/
            public void flush() throws IOException {
                logger.debug(out.toString());
            }
        });
        debugSerializer.setOutputProperty(Serializer.Property.METHOD, "xml");
        debugSerializer.setOutputProperty(Serializer.Property.INDENT, "yes");
        if (destination instanceof XdmDestination) {
            destination = new TeeSourceDestination((XdmDestination) destination, debugSerializer);
        } else {
            destination = new TeeDestination(destination, debugSerializer);
        }
    }
    return destination;
}

From source file:edu.cornell.mannlib.semservices.service.impl.UMLSService.java

public List<Concept> processResults(String term) throws Exception {
    String results = null;/*from w ww.j  av  a2s  . c  o  m*/
    String dataUrl = submissionUrl + "textToProcess=" + URLEncoder.encode(term, "UTF-8") + "&format=json";

    try {

        StringWriter sw = new StringWriter();
        URL rss = new URL(dataUrl);

        BufferedReader in = new BufferedReader(new InputStreamReader(rss.openStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            sw.write(inputLine);
        }
        in.close();

        results = sw.toString();
        //System.out.println("results before processing: "+results);
        List<Concept> conceptList = processOutput(results);
        return conceptList;

    } catch (Exception ex) {
        logger.error("error occurred in servlet", ex);
        return null;
    }

}