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:de.shadowhunt.subversion.internal.AbstractPropfindOperation.java

@Override
protected HttpUriRequest createRequest() {
    final URI uri = URIUtils.createURI(repository, resource);
    final DavTemplateRequest request = new DavTemplateRequest("PROPFIND", uri);
    request.addHeader("Depth", depth.value);

    final Writer body = new StringBuilderWriter();
    try {//from  w w  w .j a va2  s. c  om
        final XMLStreamWriter writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(body);
        writer.writeStartDocument(XmlConstants.ENCODING, XmlConstants.VERSION_1_0);
        writer.writeStartElement("propfind");
        writer.writeDefaultNamespace(XmlConstants.DAV_NAMESPACE);
        if (requestedProperties == null) {
            writer.writeEmptyElement("prop");
        } else {
            if (requestedProperties.length == 0) {
                writer.writeEmptyElement("allprop");
            } else {
                writer.writeStartElement("prop");
                if (contains(XmlConstants.SUBVERSION_DAV_NAMESPACE)) {
                    writer.writeNamespace(XmlConstants.SUBVERSION_DAV_PREFIX,
                            XmlConstants.SUBVERSION_DAV_NAMESPACE);
                    writer.setPrefix(XmlConstants.SUBVERSION_DAV_PREFIX, XmlConstants.SUBVERSION_DAV_NAMESPACE);
                }
                if (contains(XmlConstants.SUBVERSION_SVN_NAMESPACE)) {
                    writer.writeNamespace(XmlConstants.SUBVERSION_SVN_PREFIX,
                            XmlConstants.SUBVERSION_SVN_NAMESPACE);
                    writer.setPrefix(XmlConstants.SUBVERSION_SVN_PREFIX, XmlConstants.SUBVERSION_SVN_NAMESPACE);
                }
                for (final ResourceProperty.Key requestedProperty : requestedProperties) {
                    writer.writeEmptyElement(requestedProperty.getType().getPrefix(),
                            requestedProperty.getName());
                }
                writer.writeEndElement(); // prop
            }
        }
        writer.writeEndElement(); // propfind
        writer.writeEndDocument();
        writer.close();
    } catch (final XMLStreamException e) {
        throw new SubversionException("could not create request body", e);
    }

    request.setEntity(new StringEntity(body.toString(), CONTENT_TYPE_XML));
    return request;
}

From source file:com.MainFiles.Functions.java

public static String StackTraceWriter(Exception exception) {
    Writer writer = new StringWriter();
    PrintWriter printWriter = new PrintWriter(writer);
    exception.printStackTrace(printWriter);
    String s = writer.toString();
    return s;/* w  ww .  ja  v a2  s . c o  m*/
}

From source file:org.apache.manifoldcf.crawler.connectors.meridio.meridiowrapper.MeridioWrapper.java

/** Given the castor object representing the Meridio DMDataSet XSD, this method generates
* the XML that must be passed over the wire to invoke the Meridio DM Web Service
*//*w  w  w  .  ja v  a  2 s  .c  o  m*/
protected MessageElement[] getSOAPMessage(DMDataSet dsDM) throws MeridioDataSetException {

    if (oLog != null)
        oLog.debug("Meridio: Entered getSOAPMessage method.");

    try {
        Writer writer = new StringWriter();
        dsDM.marshal(writer);
        writer.close();
        //oLog.debug("Meridio: Marshalled XML: " + writer.toString());

        StringReader stringReader = new StringReader(writer.toString());
        InputSource inputSource = new InputSource(stringReader);

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setValidating(false);
        Document document = documentBuilderFactory.newDocumentBuilder().parse(inputSource);
        Element element = document.getDocumentElement();
        MessageElement messageElement = new MessageElement(element);

        MessageElement[] messageElementArray = { messageElement };
        if (oLog != null)
            oLog.debug("Meridio: Exiting getSOAPMessage method.");
        return messageElementArray;

    } catch (MarshalException marshalException) {
        throw new MeridioDataSetException("Castor error in marshalling the XML from the Meridio Dataset",
                marshalException);
    } catch (ValidationException validationException) {
        throw new MeridioDataSetException("Castor error in validating the XML from the Meridio Dataset",
                validationException);
    } catch (IOException IoException) {
        throw new MeridioDataSetException("IO Error in marshalling the Meridio Dataset", IoException);
    } catch (SAXException SaxException) {
        throw new MeridioDataSetException("XML Error in marshalling the Meridio Dataset", SaxException);
    } catch (ParserConfigurationException parserConfigurationException) {
        throw new MeridioDataSetException("XML Error in parsing the Meridio Dataset",
                parserConfigurationException);
    }
}

From source file:org.apache.manifoldcf.crawler.connectors.meridio.meridiowrapper.MeridioWrapper.java

/** Given the castor object representing the Meridio DMDataSet XSD, this method generates
* the XML that must be passed over the wire to invoke the Meridio DM Web Service
*//*from  w  w  w  .  j  a  v a2 s  .c  o  m*/

protected MessageElement[] getSOAPMessage(RMDataSet dsRM) throws MeridioDataSetException {

    if (oLog != null)
        oLog.debug("Meridio: Entered getSOAPMessage method.");

    try {
        Writer writer = new StringWriter();
        dsRM.marshal(writer);
        writer.close();
        //oLog.debug("Meridio: Marshalled XML: " + writer.toString());

        StringReader stringReader = new StringReader(writer.toString());
        InputSource inputSource = new InputSource(stringReader);

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setValidating(false);
        Document document = documentBuilderFactory.newDocumentBuilder().parse(inputSource);
        Element element = document.getDocumentElement();
        MessageElement messageElement = new MessageElement(element);

        MessageElement[] messageElementArray = { messageElement };
        if (oLog != null)
            oLog.debug("Meridio: Exiting getSOAPMessage method.");
        return messageElementArray;

    } catch (MarshalException marshalException) {
        throw new MeridioDataSetException("Castor error in marshalling the XML from the Meridio Dataset",
                marshalException);
    } catch (ValidationException validationException) {
        throw new MeridioDataSetException("Castor error in validating the XML from the Meridio Dataset",
                validationException);
    } catch (IOException IoException) {
        throw new MeridioDataSetException("IO Error in marshalling the Meridio Dataset", IoException);
    } catch (SAXException SaxException) {
        throw new MeridioDataSetException("XML Error in marshalling the Meridio Dataset", SaxException);
    } catch (ParserConfigurationException parserConfigurationException) {
        throw new MeridioDataSetException("XML Error in parsing the Meridio Dataset",
                parserConfigurationException);
    }
}

From source file:org.codice.ddf.spatial.ogc.csw.catalog.common.source.AbstractCswSource.java

private String getGetRecordsTypeAsXml(GetRecordsType getRecordsType) {
    Writer writer = new StringWriter();
    try {/* w w  w  . j  a v  a2  s . co  m*/
        Marshaller marshaller = JAXB_CONTEXT.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        JAXBElement<GetRecordsType> jaxbElement = new JAXBElement<GetRecordsType>(
                new QName(CswConstants.CSW_OUTPUT_SCHEMA, CswConstants.GET_RECORDS), GetRecordsType.class,
                getRecordsType);
        marshaller.marshal(jaxbElement, writer);
    } catch (JAXBException e) {
        LOGGER.error("{}: Unable to marshall {} to XML.", cswSourceConfiguration.getId(), GetRecordsType.class,
                e);
    }
    return writer.toString();
}

From source file:org.inquidia.kettle.plugins.tokenreplacement.TokenReplacement.java

public synchronized boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException {
    meta = (TokenReplacementMeta) smi;/*from  w ww.j  a v  a  2 s  .com*/
    data = (TokenReplacementData) sdi;

    boolean result = true;
    Object[] r = getRow(); // This also waits for a row to be finished.

    if (first && r != null) {
        first = false;

        data.inputRowMeta = getInputRowMeta();
        data.outputRowMeta = getInputRowMeta().clone();

        if (meta.getOutputType().equalsIgnoreCase("field")) {
            meta.getFields(data.outputRowMeta, getStepname(), null, null, this, repository, metaStore);

        }
        if (meta.getOutputType().equalsIgnoreCase("file") && !meta.isOutputFileNameInField()) {
            if (meta.getOutputFileName() != null) {
                String filename = meta.buildFilename(meta.getOutputFileName(), getTransMeta(), getCopy(),
                        getPartitionID(), data.splitnr);
                openNewOutputFile(filename);
            } else {
                throw new KettleException("Output file name cannot be null.");
            }
        }
    }

    if (r == null) {
        // no more input to be expected...
        closeAllOutputFiles();
        setOutputDone();
        return false;
    }

    if (meta.getOutputType().equalsIgnoreCase("file") && !meta.isOutputFileNameInField()
            && meta.getSplitEvery() > 0 && data.rowNumber % meta.getSplitEvery() == 0) {
        if (data.rowNumber > 0) {
            closeAllOutputFiles();
            data.splitnr++;
            String filename = meta.buildFilename(meta.getOutputFileName(), getTransMeta(), getCopy(),
                    getPartitionID(), data.splitnr);
            openNewOutputFile(filename);
        }
    }

    String outputFilename = "";
    if (meta.getOutputType().equalsIgnoreCase("file") && !meta.isOutputFileNameInField()) {
        outputFilename = meta.buildFilename(meta.getOutputFileName(), getTransMeta(), getCopy(),
                getPartitionID(), data.splitnr);
    } else if (meta.getOutputType().equalsIgnoreCase("file") && meta.isOutputFileNameInField()) {
        String filenameValue = data.inputRowMeta.getString(r,
                environmentSubstitute(meta.getOutputFileNameField()), "");
        if (!Const.isEmpty(filenameValue)) {
            outputFilename = filenameValue;
        } else {
            throw new KettleException("Filename cannot be empty.");
        }
    }

    //Create token resolver
    TokenResolver resolver = new TokenResolver();

    for (TokenReplacementField field : meta.getTokenReplacementFields()) {
        if (data.inputRowMeta.indexOfValue(field.getName()) >= 0) {
            String fieldValue = environmentSubstitute(data.inputRowMeta.getString(r, field.getName(), null));
            if (fieldValue == null && !BooleanUtils
                    .toBoolean(Const.getEnvironmentVariable("KETTLE_EMPTY_STRING_DIFFERS_FROM_NULL", "N"))) {
                fieldValue = Const.nullToEmpty(fieldValue);
            }
            resolver.addToken(field.getTokenName(), fieldValue);
        } else {
            throw new KettleValueException("Field " + field.getName() + " not found on input stream.");
        }
    }

    Reader reader;
    String inputFilename = "";

    if (meta.getInputType().equalsIgnoreCase("text")) {
        reader = new TokenReplacingReader(resolver, new StringReader(meta.getInputText()),
                environmentSubstitute(meta.getTokenStartString()),
                environmentSubstitute(meta.getTokenEndString()));

    } else if (meta.getInputType().equalsIgnoreCase("field")) {
        if (data.inputRowMeta.indexOfValue(meta.getInputFieldName()) >= 0) {
            String inputString = data.inputRowMeta.getString(r, meta.getInputFieldName(), "");
            reader = new TokenReplacingReader(resolver, new StringReader(inputString),
                    environmentSubstitute(meta.getTokenStartString()),
                    environmentSubstitute(meta.getTokenEndString()));

        } else {
            throw new KettleValueException(
                    "Input field " + meta.getInputFieldName() + " not found on input stream.");
        }
    } else if (meta.getInputType().equalsIgnoreCase("file")) {
        if (meta.isInputFileNameInField()) {
            if (data.inputRowMeta.indexOfValue(environmentSubstitute(meta.getInputFileNameField())) >= 0) {
                inputFilename = data.inputRowMeta.getString(r,
                        environmentSubstitute(meta.getInputFileNameField()), "");
            } else {
                throw new KettleValueException("Input filename field "
                        + environmentSubstitute(meta.getInputFileNameField()) + " not found on input stream.");
            }
        } else {
            inputFilename = environmentSubstitute(meta.getInputFileName());
        }

        if (Const.isEmpty(inputFilename)) {
            throw new KettleValueException("Input filename cannot be empty");
        }

        FileObject file = KettleVFS.getFileObject(inputFilename, getTransMeta());
        reader = new TokenReplacingReader(resolver,
                new InputStreamReader(KettleVFS.getInputStream(inputFilename, getTransMeta())),
                environmentSubstitute(meta.getTokenStartString()),
                environmentSubstitute(meta.getTokenEndString()));

        if (meta.isAddInputFileNameToResult()) {
            ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL,
                    KettleVFS.getFileObject(inputFilename, getTransMeta()), getTransMeta().getName(),
                    getStepname());
            resultFile.setComment(BaseMessages.getString(PKG, "TokenReplacement.AddInputResultFile"));
            addResultFile(resultFile);
        }
    } else {
        throw new KettleException("Unsupported input type " + meta.getInputType());
    }

    Writer stringWriter = null;
    OutputStream bufferedWriter = null;

    if (meta.getOutputType().equalsIgnoreCase("field")) {
        stringWriter = new StringBufferWriter(new StringBuffer(5000));
    } else if (meta.getOutputType().equalsIgnoreCase("file")) {

        if (inputFilename.equals(outputFilename)) {
            throw new KettleException("Input and output filenames must not be the same " + inputFilename);
        }

        int fileIndex = data.openFiles.indexOf(outputFilename);
        if (fileIndex < 0) {
            openNewOutputFile(outputFilename);
            fileIndex = data.openFiles.indexOf(outputFilename);
        }

        bufferedWriter = data.openBufferedWriters.get(fileIndex);

    } else {
        throw new KettleException("Unsupported output type " + meta.getOutputType());
    }

    String output = "";

    try {
        char[] cbuf = new char[5000];
        StringBuffer sb = new StringBuffer();
        int length = 0;
        while ((length = reader.read(cbuf)) > 0) {
            if (meta.getOutputType().equalsIgnoreCase("field")) {
                stringWriter.write(cbuf, 0, length);
            } else if (meta.getOutputType().equalsIgnoreCase("file")) {
                CharBuffer cBuffer = CharBuffer.wrap(cbuf, 0, length);
                ByteBuffer bBuffer = Charset.forName(meta.getOutputFileEncoding()).encode(cBuffer);
                byte[] bytes = new byte[bBuffer.limit()];
                bBuffer.get(bytes);
                bufferedWriter.write(bytes);

            } //No else.  Anything else will be thrown to a Kettle exception prior to getting here.
            cbuf = new char[5000];
        }

        if (meta.getOutputType().equalsIgnoreCase("field")) {
            output += stringWriter.toString();
        } else if (meta.getOutputType().equalsIgnoreCase("file")) {
            bufferedWriter.write(meta.getOutputFileFormatString().getBytes());
        }
    } catch (IOException ex) {
        throw new KettleException(ex.getMessage(), ex);
    } finally {
        try {
            reader.close();
            if (stringWriter != null) {
                stringWriter.close();
            }

            reader = null;
            stringWriter = null;

        } catch (IOException ex) {
            throw new KettleException(ex.getMessage(), ex);
        }

    }

    if (meta.getOutputType().equalsIgnoreCase("field")) {
        r = RowDataUtil.addValueData(r, data.outputRowMeta.size() - 1, output);
    } else if (meta.getOutputType().equalsIgnoreCase("file")) {
        incrementLinesWritten();
    }

    putRow(data.outputRowMeta, r); // in case we want it to go further...
    data.rowNumber++;
    if (checkFeedback(getLinesOutput())) {
        logBasic("linenr " + getLinesOutput());
    }

    return result;
}

From source file:org.openmrs.module.idcards.web.servlet.PrintEmptyIdcardsServlet.java

/**
 * Write the pdf to the given response/*from   w  ww. j  a va2s  . com*/
 */
@SuppressWarnings("unchecked")
public static void generateOutputForIdentifiers(IdcardsTemplate card, String baseURL,
        HttpServletResponse response, List<String> identifiers, String password)
        throws ServletException, IOException {

    Properties props = new Properties();
    props.setProperty(RuntimeConstants.RESOURCE_LOADER, "class");
    props.setProperty("class.resource.loader.description", "VelocityClasspathResourceLoader");
    props.setProperty("class.resource.loader.class",
            "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
    props.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS,
            "org.apache.velocity.runtime.log.NullLogSystem");

    // do the velocity magic
    Writer writer = new StringWriter();
    try {
        // Allow images to be served from Unix servers.
        try {
            java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment();
        } catch (Throwable t) {
            log.warn(
                    "Unable to get graphics environment.  "
                            + "Make sure that -Djava.awt.headless=true is defined as a JAVA OPT during startup",
                    t);
        }
        Velocity.init(props);
        VelocityContext velocityContext = new VelocityContext();
        velocityContext.put("locale", Context.getLocale());
        velocityContext.put("identifiers", identifiers);
        velocityContext.put("baseURL", baseURL);
        Velocity.evaluate(velocityContext, writer, PrintEmptyIdcardsServlet.class.getName(), card.getXml());
    } catch (ParseErrorException e) {
        throw new ServletException("Error parsing template: ", e);
    } catch (MethodInvocationException e) {
        throw new ServletException("Error parsing template: ", e);
    } catch (ResourceNotFoundException e) {
        throw new ServletException("Error parsing template: ", e);
    } catch (Exception e) {
        throw new ServletException("Error initializing Velocity engine", e);
    } finally {
        System.gc();
    }

    try {
        //Setup a buffer to obtain the content length
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        FopFactory fopFactory = FopFactory.newInstance();

        //fopFactory supports customization with a config file
        //Load the config file before creating the user agent.
        String userConfigFile = Context.getAdministrationService()
                .getGlobalProperty("idcards.fopConfigFilePath");
        if (userConfigFile != null) {
            try {
                fopFactory.setUserConfig(new java.io.File(userConfigFile));
                log.debug("Successfully loaded config file |" + userConfigFile + "|");
            } catch (Exception e) {
                log.error("Could not initialize fopFactory user config with file at " + userConfigFile
                        + ". Error message:" + e.getMessage());
            }
        }

        FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
        foUserAgent.getRendererOptions().put("encryption-params",
                new PDFEncryptionParams(password, null, true, false, false, false));

        //Setup FOP
        Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);

        //Setup Transformer
        Source xsltSrc = new StreamSource(new StringReader(card.getXslt()));
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer(xsltSrc);

        //Make sure the XSL transformation's result is piped through to FOP
        Result res = new SAXResult(fop.getDefaultHandler());

        //Setup input
        String xml = writer.toString();
        Source src = new StreamSource(new StringReader(xml));

        //Start the transformation and rendering process
        transformer.transform(src, res);

        //Prepare response
        String time = new SimpleDateFormat("yyyy-MM-dd_Hms").format(new Date());
        String filename = card.getName().replace(" ", "_") + "-" + time + ".pdf";
        response.setHeader("Content-Disposition", "attachment; filename=" + filename);
        response.setContentType("application/pdf");
        response.setContentLength(out.size());

        //Send content to Browser
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(out.toByteArray());
        outputStream.flush();
    } catch (FOPException e) {
        throw new ServletException("Error generating report", e);
    } catch (TransformerConfigurationException e) {
        throw new ServletException("Error generating report", e);
    } catch (TransformerException e) {
        throw new ServletException("Error generating report", e);
    }
}

From source file:com.stratio.qa.specs.CommonG.java

/**
 * Returns the information contained in file passed as parameter
 *
 * @param baseData path to file to be read
 * @param type     type of information, it can be: json|string
 * @return String/* w ww  .j  a  v a 2  s.  c om*/
 */
public String retrieveData(String baseData, String type) {
    String result;

    InputStream stream = getClass().getClassLoader().getResourceAsStream(baseData);

    Writer writer = new StringWriter();
    char[] buffer = new char[1024];
    Reader reader;

    if (stream == null) {
        this.getLogger().error("File does not exist: {}", baseData);
        return "ERR! File not found: " + baseData;
    }

    try {
        reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
        int n;
        while ((n = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, n);
        }
    } catch (Exception readerexception) {
        this.getLogger().error(readerexception.getMessage());
    } finally {
        try {
            stream.close();
        } catch (Exception closeException) {
            this.getLogger().error(closeException.getMessage());
        }
    }
    String text = writer.toString();

    String std = text.replace("\r", "").replace("\n", ""); // make sure we have unix style text regardless of the input

    if ("json".equals(type)) {
        result = JsonValue.readHjson(std).asObject().toString();
    } else {
        result = std;
    }
    return result;
}

From source file:de.shadowhunt.subversion.internal.MergeOperation.java

@Override
protected HttpUriRequest createRequest() {
    final DavTemplateRequest request = new DavTemplateRequest("MERGE", repository);
    request.addHeader("X-SVN-Options", "release-locks");

    final Writer body = new StringBuilderWriter();
    try {//from   w  w w  . j a  v  a2 s .  c o m
        final XMLStreamWriter writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(body);
        writer.writeStartDocument(XmlConstants.ENCODING, XmlConstants.VERSION_1_0);
        writer.writeStartElement("merge");
        writer.writeDefaultNamespace(XmlConstants.DAV_NAMESPACE);
        writer.writeStartElement("source");
        writer.writeStartElement("href");
        writer.writeCData(repository.getPath() + resource.getValue());
        writer.writeEndElement(); // href
        writer.writeEndElement(); // source
        writer.writeEmptyElement("no-auto-merge");
        writer.writeEmptyElement("no-checkout");
        writer.writeStartElement("prop");
        writer.writeEmptyElement("checked-in");
        writer.writeEmptyElement("version-name");
        writer.writeEmptyElement("resourcetype");
        writer.writeEmptyElement("creationdate");
        writer.writeEmptyElement("creator-displayname");
        writer.writeEndElement(); // prop
        if (!infoSet.isEmpty()) {
            writer.setPrefix(XmlConstants.SVN_PREFIX, XmlConstants.SVN_NAMESPACE);
            writer.writeStartElement(XmlConstants.SVN_NAMESPACE, "lock-token-list");
            writer.writeNamespace(XmlConstants.SVN_PREFIX, XmlConstants.SVN_NAMESPACE);
            for (final Info info : infoSet) {
                final String lockToken = info.getLockToken();
                assert (lockToken != null) : "must not be null";
                final Resource infoResource = info.getResource();

                writer.writeStartElement(XmlConstants.SVN_NAMESPACE, "lock");
                writer.writeStartElement(XmlConstants.SVN_NAMESPACE, "lock-path");
                writer.writeCData(infoResource.getValueWithoutLeadingSeparator());
                writer.writeEndElement(); // lock-path
                writer.writeStartElement(XmlConstants.SVN_NAMESPACE, "lock-token");
                writer.writeCharacters(lockToken);
                writer.writeEndElement(); // lock-token
                writer.writeEndElement(); // lock
            }
            writer.writeEndElement(); // lock-token-list
        }
        writer.writeEndElement(); // merge
        writer.writeEndDocument();
        writer.close();
    } catch (final XMLStreamException e) {
        throw new SubversionException("could not create request body", e);
    }

    request.setEntity(new StringEntity(body.toString(), CONTENT_TYPE_XML));
    return request;
}

From source file:org.apache.ambari.server.state.services.AlertNoticeDispatchService.java

/**
 * Generates the content for the {@link Notification} using the
 * {@link #m_alertTemplates} and the single alert passed in. If there is a
 * problem with the templates, this will fallback to non-formatted content.
 *
 * @param notification//from   ww  w .  ja v a  2 s.  c  o  m
 *          the notification (not {@code null}).
 * @param history
 *          the alert to generate the content from (not {@code null}.
 * @param target
 *          the target of the {@link Notification}.
 */
private void renderNotificationContent(Notification notification, AlertHistoryEntity history,
        AlertTargetEntity target) throws IOException {
    String targetType = target.getNotificationType();

    // build the velocity objects for template rendering
    AmbariInfo ambari = new AmbariInfo(m_metaInfo.get());
    AlertInfo alert = new AlertInfo(history);
    DispatchInfo dispatch = new DispatchInfo(target);

    // get the template for this target type
    final Writer subjectWriter = new StringWriter();
    final Writer bodyWriter = new StringWriter();
    final AlertTemplate template = m_alertTemplates.getTemplate(targetType);

    if (null != template) {
        // create the velocity context for template rendering
        VelocityContext velocityContext = new VelocityContext();
        velocityContext.put(VELOCITY_AMBARI_KEY, ambari);
        velocityContext.put(VELOCITY_ALERT_KEY, alert);
        velocityContext.put(VELOCITY_DISPATCH_KEY, dispatch);

        // render the template and assign the content to the notification
        String subjectTemplate = template.getSubject();
        String bodyTemplate = template.getBody();

        // render the subject
        Velocity.evaluate(velocityContext, subjectWriter, VELOCITY_LOG_TAG, subjectTemplate);

        // render the body
        Velocity.evaluate(velocityContext, bodyWriter, VELOCITY_LOG_TAG, bodyTemplate);
    } else {
        // a null template is possible from parsing incorrectly or not
        // having the correct type defined for the target
        subjectWriter.write(alert.getAlertState().name());
        subjectWriter.write(" ");
        subjectWriter.write(alert.getAlertName());

        bodyWriter.write(alert.getAlertState().name());
        bodyWriter.write(" ");
        bodyWriter.write(alert.getAlertName());
        bodyWriter.write(" ");
        bodyWriter.write(alert.getAlertText());
        bodyWriter.write("\n");
    }

    notification.Subject = subjectWriter.toString();
    notification.Body = bodyWriter.toString();
}