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:gov.nih.nci.cabig.caaers.service.FreeMarkerService.java

/**
 * applyRuntimeReplacementsForReport/*  w w w.j  a  va2  s.  c  o  m*/
 * @param rawText
 * @param replacements
 * @return
 */
public String applyRuntimeReplacementsForReport(final String rawText, final Map<Object, Object> replacements) {
    if (rawText == null)
        return "";

    //clean null values in Map
    final Map<Object, Object> variableMap = new HashMap<Object, Object>();
    if (replacements != null) {
        for (Map.Entry<Object, Object> entry : replacements.entrySet()) {
            if (entry.getValue() != null) {
                variableMap.put(entry.getKey(), entry.getValue());
            } else {
                log.warn("Entry value is null, ignoring key : " + entry.getKey());
            }
        }
    }

    Configuration cfg = new Configuration();
    cfg.setTemplateExceptionHandler(new TemplateExceptionHandler() {
        public void handleTemplateException(TemplateException e, Environment environment, Writer writer)
                throws TemplateException {
            log.warn("Error while replacing variables", e);
            if (log.isDebugEnabled()) {
                log.debug("rawText :" + rawText);
                log.debug("variableMap :" + String.valueOf(variableMap));
            }
            try {
                writer.write("_");
            } catch (IOException ignore) {
            }
        }
    });
    try {
        Template t = new Template("message", new StringReader(rawText), cfg);

        StringWriter writer = new StringWriter();
        t.process(variableMap, writer);
        return writer.toString();
    } catch (TemplateException e) {
        throw new CaaersSystemException("Error while applying freemarker template", e);
    } catch (IOException e) {
        throw new CaaersSystemException("Error while applying freemarker template", e);
    }
}

From source file:de.kp.ames.web.core.service.ServiceImpl.java

/**
 * Send Bad Request response/*ww w. ja  v a 2 s  .  com*/
 * 
 * @param ctx
 * @param e
 */
protected void sendBadRequest(RequestContext ctx, Throwable e) {

    // TODO: xxx pa debug stacktrace
    Writer result = new StringWriter();
    PrintWriter printWriter = new PrintWriter(result);
    e.printStackTrace(printWriter);

    String errorMessage = "[" + this.getClass().getName() + "] " + result.toString();
    //      String errorMessage = "[" + this.getClass().getName() + "] " + e.getMessage();
    int errorStatus = HttpServletResponse.SC_BAD_REQUEST;

    System.out.println("====> sendBadRequest: " + errorMessage);

    try {
        sendErrorResponse(errorMessage, errorStatus, ctx.getResponse());

    } catch (IOException e1) {
        // do nothing
    }

}

From source file:org.jumpmind.metl.core.runtime.component.DelimitedFormatter.java

@Override
public void handle(Message inputMessage, ISendMessageCallback callback, boolean unitOfWorkBoundaryReached) {
    if (inputMessage instanceof EntityDataMessage) {
        if (attributes.size() == 0) {
            log(LogLevel.INFO,/*from w w  w .  j  a v a2  s  .c  o m*/
                    "There are no format attributes configured.  Writing all entity fields to the output");
        }

        ArrayList<EntityData> inputRows = ((EntityDataMessage) inputMessage).getPayload();

        ArrayList<String> outputPayload = new ArrayList<String>();

        if (useHeader) {
            Writer writer = new StringWriter();
            CsvWriter csvWriter = getCsvWriter(writer);
            try {
                for (AttributeFormat attr : attributes) {
                    if (attr.getAttribute() != null) {
                        csvWriter.write(attr.getAttribute().getName());
                    }
                }
            } catch (IOException e) {
                throw new IoException("Error writing to stream for formatted output. " + e.getMessage());
            }
            outputPayload.add(writer.toString());
        }

        String outputRec;
        for (EntityData inputRow : inputRows) {
            outputRec = processInputRow(inputMessage, inputRow);
            outputPayload.add(outputRec);
        }

        callback.sendTextMessage(null, outputPayload);
    }
}

From source file:net.ausgstecktis.DAL.RestClient.java

/**
 * Converts a Inputstream to String//from w w  w  .j  a  v a2s .c  o  m
 * 
 * @author naikon
 * @param is the inputstream which is to convert
 * @throws IOException if an input or output exception occurred
 * @return the converted string
 */
public String convertStreamToString(final InputStream is) throws IOException {
    if (is != null) {
        final Writer writer = new StringWriter();
        final char[] buffer = new char[1024];
        try {
            final Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1)
                writer.write(buffer, 0, n);
        } catch (final UnsupportedEncodingException e) {
            e.printStackTrace();
        } finally {
            is.close();
        }
        return writer.toString();
    }
    return "";
}

From source file:org.kuali.ole.repository.CheckoutManager.java

public String getData(Node nodeByUUID) throws OleException, RepositoryException, FileNotFoundException {
    StringBuffer stringBuffer = new StringBuffer();
    if (null != nodeByUUID) {
        Node jcrContent = nodeByUUID.getNode("jcr:content");
        Binary binary = jcrContent.getProperty("jcr:data").getBinary();
        InputStream content = binary.getStream();

        Writer writer;
        try {/*from   w w w .ja  v  a2s . com*/
            writer = new StringWriter();
            char[] buffer = new char[1024];
            try {
                Reader reader = new BufferedReader(new InputStreamReader(content, "UTF-8"));
                int n;
                while ((n = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, n);
                }
            } finally {
                stringBuffer.append(writer.toString());
                content.close();
            }

        } catch (IOException e) {
            getDocStoreLogger().log("failure during checkOut of ", e);
        }

    }

    return stringBuffer.toString();
}

From source file:org.kuali.ole.docstore.repository.CustomNodeManager.java

public String getData(Node nodeByUUID) throws OleDocStoreException, RepositoryException, FileNotFoundException {
    StringBuffer stringBuffer = new StringBuffer();
    if (null != nodeByUUID) {
        Node jcrContent = nodeByUUID.getNode("jcr:content");
        Binary binary = jcrContent.getProperty("jcr:data").getBinary();
        InputStream content = binary.getStream();

        Writer writer;
        try {/* www.ja v  a2 s  .com*/
            writer = new StringWriter();
            char[] buffer = new char[1024];
            try {
                Reader reader = new BufferedReader(new InputStreamReader(content, "UTF-8"));
                int n;
                while ((n = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, n);
                }
            } finally {
                stringBuffer.append(writer.toString());
                content.close();
            }

        } catch (IOException e) {
            logger.info("failure during checkOut of ", e);
        }

    }

    return stringBuffer.toString();
}

From source file:gtu.youtube.JavaYoutubeDownloader.java

private String getStringFromInputStream(String encoding, InputStream instream)
        throws UnsupportedEncodingException, IOException {
    Writer writer = new StringWriter();

    char[] buffer = new char[1024];
    try {/*w  ww  .j  ava  2s  . c o m*/
        Reader reader = new BufferedReader(new InputStreamReader(instream, encoding));
        int n;
        while ((n = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, n);
        }
    } finally {
        instream.close();
    }
    String result = writer.toString();
    return result;
}

From source file:com.googlecode.esms.provider.Vodafone.java

/**
 * Convert any stream to a string. /*from   ww  w .j  a v  a2s  . co m*/
 * @param input Stream to be read.
 * @return String representation of the stream.
 */
private String convertStreamToString(InputStream input) throws IOException {
    if (input != null) {
        Writer writer = new StringWriter();
        char[] buffer = new char[1024];
        Reader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
        int n;
        while ((n = reader.read(buffer)) != -1)
            writer.write(buffer, 0, n);
        input.close();
        return writer.toString();
    } else {
        return "";
    }
}

From source file:org.apereo.portal.portlet.container.EventProviderImpl.java

@Override
public Event createEvent(QName qname, Serializable value) throws IllegalArgumentException {
    if (this.isDeclaredAsPublishingEvent(qname)) {
        if (value != null && !this.isValueInstanceOfDefinedClass(qname, value)) {
            throw new IllegalArgumentException("Payload class (" + value.getClass().getCanonicalName()
                    + ") does not have the right class, check your defined event types in portlet.xml.");
        }/*from   w  w w .  ja  va 2  s  .  co m*/

        if (value == null) {
            return new EventImpl(qname);
        }

        try {
            final Thread currentThread = Thread.currentThread();
            final ClassLoader cl = currentThread.getContextClassLoader();
            final Writer out = new StringWriter();
            final Class clazz = value.getClass();
            try {
                currentThread.setContextClassLoader(this.portletClassLoader);
                final JAXBContext jc = JAXBContext.newInstance(clazz);
                final Marshaller marshaller = jc.createMarshaller();
                final JAXBElement<Serializable> element = new JAXBElement<Serializable>(qname, clazz, value);
                marshaller.marshal(element, out);
            } finally {
                currentThread.setContextClassLoader(cl);
            }
            return new EventImpl(qname, out.toString());
        } catch (JAXBException e) {
            // maybe there is no valid jaxb binding
            // TODO throw exception?
            logger.error("Event handling failed", e);
        } catch (FactoryConfigurationError e) {
            // TODO throw exception?
            logger.warn(e.getMessage(), e);
        }
    }
    return null;
}