Example usage for java.io Writer toString

List of usage examples for java.io Writer toString

Introduction

In this page you can find the example usage for java.io Writer toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:org.eurekaclinical.user.service.email.FreeMarkerEmailSender.java

/**
 * Send an email to the given email address with the given subject line,
 * using contents generated from the given template and parameters.
 *
 * @param templateName The name of the template used to generate the
 * contents of the email./*from w w w .  j  av a2 s.co m*/
 * @param subject The subject for the email being sent.
 * @param emailAddress Sends the email to this address.
 * @param params The template is merged with these parameters to generate
 * the content of the email.
 * @throws EmailException Thrown if there are any errors in generating
 * content from the template, composing the email, or sending the email.
 */
private void sendMessage(final String templateName, final String subject, final String emailAddress,
        final Map<String, Object> params) throws EmailException {
    Writer stringWriter = new StringWriter();
    try {
        Template template = this.configuration.getTemplate(templateName);
        template.process(params, stringWriter);
    } catch (TemplateException | IOException e) {
        throw new EmailException(e);
    }

    String content = stringWriter.toString();
    MimeMessage message = new MimeMessage(this.session);
    try {
        InternetAddress fromEmailAddress = null;
        String fromEmailAddressStr = this.userServiceProperties.getFromEmailAddress();
        if (fromEmailAddressStr != null) {
            fromEmailAddress = new InternetAddress(fromEmailAddressStr);
        }
        if (fromEmailAddress == null) {
            fromEmailAddress = InternetAddress.getLocalAddress(this.session);
        }
        if (fromEmailAddress == null) {
            try {
                fromEmailAddress = new InternetAddress(
                        "no-reply@" + InetAddress.getLocalHost().getCanonicalHostName());
            } catch (UnknownHostException ex) {
                fromEmailAddress = new InternetAddress("no-reply@localhost");
            }
        }
        message.setFrom(fromEmailAddress);
        message.setSubject(subject);
        message.setContent(content, "text/plain");
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailAddress));
        message.setSender(fromEmailAddress);
        Transport.send(message);
    } catch (MessagingException e) {
        LOGGER.error("Error sending the following email message:");
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            message.writeTo(out);
            out.close();
        } catch (IOException | MessagingException ex) {
            try {
                out.close();
            } catch (IOException ignore) {
            }
        }
        LOGGER.error(out.toString());
        throw new EmailException(e);
    }
}

From source file:com.centeractive.ws.builder.soap.XmlUtils.java

public static String serializePretty(Document document) {
    try {//from  w w  w . jav  a 2  s. co m
        Writer out = new StringWriter();
        serializePretty(document, out);
        return out.toString();
    } catch (IOException e) {
        log.error("Failed to serialize: " + e);
    }
    return null;
}

From source file:com.oneops.boo.BooConfigInterpolator.java

public String interpolate(String booYaml, Map<String, String> config) throws IOException {
    Map<String, Object> mustacheMap = Maps.newHashMap();
    for (Map.Entry<String, String> e : config.entrySet()) {
        String key = e.getKey();/* ww  w .  jav a  2s. c o m*/
        String value = e.getValue();
        Object mustacheValue;
        if (value.startsWith("\"") && value.endsWith("\"")) {
            mustacheValue = deliteral(value);
        } else if (value.contains(",")) {
            mustacheValue = splitter.split(value);
        } else {
            mustacheValue = value;
        }
        mustacheMap.put(key, mustacheValue);
    }
    Writer writer = new StringWriter();
    NoEncodingMustacheFactory mustacheFactory = new NoEncodingMustacheFactory();
    mustacheFactory.setObjectHandler(new BooReflectionObjectHandler());
    Mustache mustache = mustacheFactory.compile(new StringReader(booYaml), "boo");
    mustache.execute(writer, mustacheMap).flush();
    return writer.toString();
}

From source file:com.si.xe.trader.listener.OrderbookExternalListener.java

private String createJsonInString(TradeExecutedEvent event) throws IOException {
    Writer writer = new StringWriter();
    JsonGenerator g = jsonFactory.createJsonGenerator(writer);
    g.writeStartObject();/*from  w  ww .j a  va2 s  . c  om*/
    g.writeObjectFieldStart("tradeExecuted");
    g.writeStringField("orderbookId", event.getOrderBookIdentifier().toString());
    g.writeStringField("count", String.valueOf(event.getTradeCount()));
    g.writeStringField("price", String.valueOf(event.getTradePrice()));
    g.writeEndObject(); // for trade-executed
    g.close();
    return writer.toString();
}

From source file:org.springframework.data.couchbase.core.convert.translation.JacksonTranslationService.java

/**
 * Encode a {@link CouchbaseStorable} to a JSON string.
 *
 * @param source the source document to encode.
 *
 * @return the encoded JSON String.//from w w  w . j  a va  2  s  .c o m
 */
@Override
public final Object encode(final CouchbaseStorable source) {
    Writer writer = new StringWriter();

    try {
        JsonGenerator generator = factory.createGenerator(writer);
        encodeRecursive(source, generator);
        generator.close();
        writer.close();
    } catch (IOException ex) {
        throw new RuntimeException("Could not encode JSON", ex);
    }

    return writer.toString();
}

From source file:com.icoin.trading.tradeengine.infrastructure.listener.OrderbookExternalListener.java

private String createJsonInString(TradeExecutedEvent event) throws IOException {
    Writer writer = new StringWriter();
    JsonGenerator g = jsonFactory.createJsonGenerator(writer);
    g.writeStartObject();//  ww  w .j av a  2 s  . co  m
    g.writeObjectFieldStart("tradeExecuted");
    g.writeStringField("orderbookId", event.getOrderBookIdentifier().toString());
    g.writeStringField("amount", String.valueOf(event.getTradeAmount()));
    g.writeStringField("price", String.valueOf(event.getTradedPrice()));
    g.writeEndObject(); // for trade-executed
    g.close();
    return writer.toString();
}

From source file:org.ncbo.stanford.service.xml.impl.XMLSerializationServiceImpl.java

/**
 * Generate an XML representation of a successfully processed request with
 * XSL Transformation./* ww  w .j  ava 2s .co m*/
 * 
 * @param request
 * @param data
 * @param xsltFile
 * @return String
 * @throws TransformerException
 */
private String applyXSL(Request request, Object data, String xsltFile) throws TransformerException {
    SuccessBean sb = getSuccessBean(request, data);
    // create source
    TraxSource traxSource = new TraxSource(sb, xmlSerializer);
    // create buffer for XML output
    Writer buffer = new StringWriter();
    getTransformerInstance(xsltFile).transform(traxSource, new StreamResult(buffer));

    return buffer.toString();
}

From source file:edina.eframework.gefcdemo.controllers.ProcessErosionController.java

/**
 * Brokers the WPS request and response. Supports two different WPS requests,
 * the landcover preview and the process soil erosion model requests.
 * //from  w  w w .  ja v  a 2  s .  c  om
 * @param params parameters used when calculating the soil erosion model
 * @param wpsResponse results from the WPS process are written to this object
 * @param template the VM template to use to generate the WPS request
 * @param wpsOutputFile the filename to write the TIFF result file
 * @throws IOException
 * @throws JAXBException
 */
private void generateWpsRequest(SoilErosionWps params, WpsResponse wpsResponse, String template,
        String wpsOutputFile) throws IOException, JAXBException {

    Writer wpsRequest = new StringWriter();
    Map<String, Object> velocityMap = new HashMap<String, Object>();

    velocityMap.put("params", params);

    VelocityEngineUtils.mergeTemplate(velocityEngine, template, velocityMap, wpsRequest);
    wpsRequest.close();

    log.debug(wpsRequest.toString());
    log.debug("Submitting to " + wpsServer);

    RequestEntity entity = null;
    try {
        entity = new StringRequestEntity(wpsRequest.toString(), "text/xml", "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new MalformedURLException("Apparantly 'UTF-8' is an unsupported encoding type.");
    }

    PostMethod post = new PostMethod(wpsServer.toString());
    post.setRequestEntity(entity);

    HttpClient client = new HttpClient(new SimpleHttpConnectionManager());

    client.getHttpConnectionManager().getParams().setSoTimeout(0);
    client.getHttpConnectionManager().getParams().setConnectionTimeout(0);

    client.executeMethod(post);

    JAXBContext jaxbContext = JAXBContext.newInstance("edina.eframework.gefcdemo.generated.wps");
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

    ExecuteResponse executeResponse = null;
    // First save post data into a String so we can log any potential errors.
    // Response isn't very large from the WPS so this shouldn't be a problem.
    // Trying to access post data if a direct InputStream is passed to unmarshal
    // doesn't work.
    String postData = post.getResponseBodyAsString();
    try {
        executeResponse = (ExecuteResponse) unmarshaller
                .unmarshal(new ByteArrayInputStream(postData.getBytes()));
    } catch (ClassCastException e) {
        log.error("Error from WPS:\n" + postData);
        throw e;
    }

    //executeResponse.getStatus().getProcessAccepted(); // TODO check for failed
    String resultUrl = executeResponse.getProcessOutputs().getOutput().get(0).getReference().getHref();

    log.debug("Output " + resultUrl);
    wpsResponse.setOutputUrl(new URL(resultUrl));
    wpsResponse.setOutputId(resultUrl.substring(resultUrl.lastIndexOf("id=") + 3, resultUrl.length()));
    wpsResponse.setStatus(200);

    // Save the WPS output data to a file mapserver can use
    File resultOutputFile = new File(wpsOutputFile);
    resultOutputFile.getParentFile().mkdirs();
    FileOutputStream resultFileStream = new FileOutputStream(resultOutputFile);
    InputStream resultInputFile = null;
    try {
        resultInputFile = wpsResponse.getOutputUrl().openStream();
        byte[] buffer = new byte[4096];
        int i;
        while ((i = resultInputFile.read(buffer)) != -1) {
            resultFileStream.write(buffer, 0, i);
        }
        resultFileStream.flush();
    } finally {
        try {
            resultInputFile.close();
        } catch (Exception e) {
        }
        try {
            resultFileStream.close();
        } catch (Exception e) {
        }
    }

    log.debug("Result saved to " + resultOutputFile);
}

From source file:org.lockss.util.TestStreamUtil.java

public void testCopyNullReader() throws IOException {
    Writer writer = new CharArrayWriter(11);
    assertEquals(0, StreamUtil.copy(null, writer));
    String resultStr = writer.toString();
    writer.close();/*from  w  ww . j  a  va  2s .c o  m*/
    assertEquals("", writer.toString());
}

From source file:com.blackducksoftware.tools.commonframework.standard.email.CFEmailNotifier.java

private String getStackTraceAsString(Throwable aThrowable) {
    final Writer result = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(result);
    aThrowable.printStackTrace(printWriter);
    return result.toString();
}