com.seajas.search.attender.service.template.TemplateService.java Source code

Java tutorial

Introduction

Here is the source code for com.seajas.search.attender.service.template.TemplateService.java

Source

/**
 * Copyright (C) 2013 Seajas, the Netherlands.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3, as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.seajas.search.attender.service.template;

import java.io.StringWriter;
import java.util.Date;
import java.util.List;

import javax.script.ScriptException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.seajas.search.attender.model.searchresult.SearchResult;
import com.seajas.search.attender.model.template.Template;
import com.seajas.search.attender.service.attender.AttenderService;
import com.seajas.search.attender.service.template.dao.TemplateDAO;
import com.seajas.search.utilities.logging.SearchLogger;
import com.seajas.search.utilities.scripting.TransformerCache;

/**
 * Template service implementation.
 * 
 * @author Jasper van Veghel <jasper@seajas.com>
 */
@Service
public class TemplateService {
    /**
     * The logger.
     */
    @Autowired
    private SearchLogger logger;

    /**
     * The template type.
     */
    public enum TemplateType {
        Confirmation, Results
    }

    /**
     * Transformer cache.
     */
    @Autowired
    private TransformerCache transformerCache;

    /**
     * Template DAO.
     */
    @Autowired
    private TemplateDAO templateDAO;

    /**
     * Attender service.
     */
    @Autowired
    private AttenderService attenderService;

    /**
     * Create a confirmation template result.
     * 
     * @param language
     * @param queryString
     * @param subscriberUUID
     * @param profileUUID
     */
    public TemplateResult createConfirmation(final String language, final String queryString,
            final String subscriberUUID, final String profileUUID) throws Exception {
        Template template = templateDAO.findTemplate(TemplateType.Confirmation, language);

        if (template == null) {
            logger.warn("Could not retrieve confirmation template for language " + language
                    + " - falling back to the default language " + attenderService.getDefaultApplicationLanguage());

            template = templateDAO.findTemplate(TemplateType.Confirmation,
                    attenderService.getDefaultApplicationLanguage());

            if (template == null) {
                logger.error("Could not retrieve fall-back confirmation template for language "
                        + attenderService.getDefaultApplicationLanguage() + " - not generating a template result");

                return null;
            }
        }

        try {
            // Plain text

            Transformer textTransformer = getTransformer(template, true);
            StringWriter textWriter = new StringWriter();

            textTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF8");
            textTransformer.setParameter("subscriberUUID", subscriberUUID);
            textTransformer.setParameter("profileUUID", profileUUID);
            textTransformer.setParameter("queryString", queryString);
            textTransformer.transform(new DOMSource(), new StreamResult(textWriter));

            // HTML

            Transformer htmlTransformer = getTransformer(template, false);
            StringWriter htmlWriter = new StringWriter();

            htmlTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF8");
            htmlTransformer.setParameter("subscriberUUID", subscriberUUID);
            htmlTransformer.setParameter("profileUUID", profileUUID);
            htmlTransformer.setParameter("queryString", queryString);
            htmlTransformer.transform(new DOMSource(), new StreamResult(htmlWriter));

            return new TemplateResult(textWriter.toString(), htmlWriter.toString());
        } catch (ScriptException e) {
            throw e;
        } catch (Exception e) {
            throw new Exception(e);
        }
    }

    /**
     * Create a results template result.
     * 
     * @param language
     * @param queryString
     * @param query
     * @param uuid
     * @param searchResults
     * @return TemplateResult
     */
    public TemplateResult createResults(final String language, final String queryString, final String query,
            final String subscriberUUID, final String profileUUID, final List<SearchResult> searchResults)
            throws ScriptException {
        Template template = templateDAO.findTemplate(TemplateType.Results, language);

        if (template == null) {
            logger.warn("Could not retrieve results template for language " + language
                    + " - falling back to default language " + attenderService.getDefaultApplicationLanguage());

            template = templateDAO.findTemplate(TemplateType.Confirmation,
                    attenderService.getDefaultApplicationLanguage());

            if (template == null) {
                logger.error("Could not retrieve fall-back results template for language "
                        + attenderService.getDefaultApplicationLanguage() + " - not generating a template result");

                return null;
            }
        }

        // Create an input document

        Document document;

        try {
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

            documentBuilderFactory.setCoalescing(true);
            documentBuilderFactory.setNamespaceAware(true);

            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

            document = documentBuilder.newDocument();

            Element results = document.createElement("results");

            results.setAttribute("templateLanguage", language);
            results.setAttribute("profileQuery", query);
            results.setAttribute("subscriberUUID", subscriberUUID);
            results.setAttribute("profileUUID", profileUUID);
            results.setAttribute("queryString", queryString);

            for (SearchResult searchResult : searchResults)
                results.appendChild(searchResult.toElement(document));

            document.appendChild(results);

            // Plain text

            Transformer textTransformer = getTransformer(template, true);
            StringWriter textWriter = new StringWriter();

            textTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF8");
            textTransformer.transform(new DOMSource(document), new StreamResult(textWriter));

            // HTML

            Transformer htmlTransformer = getTransformer(template, false);
            StringWriter htmlWriter = new StringWriter();

            htmlTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF8");
            htmlTransformer.transform(new DOMSource(document), new StreamResult(htmlWriter));

            return new TemplateResult(textWriter.toString(), htmlWriter.toString());
        } catch (ScriptException e) {
            throw e;
        } catch (Exception e) {
            throw new ScriptException(e);
        }
    }

    /**
     * Retrieve a transformer from the given template.
     * 
     * @param template
     * @param asText
     * @return Transformer
     */
    private Transformer getTransformer(final Template template, final Boolean asText) throws ScriptException {
        try {
            Transformer transformer = transformerCache.getTransformer(template.getId(),
                    "attender-" + template.getType() + (asText ? "-text" : "-html"),
                    template.getModificationDate());

            if (transformer == null)
                transformer = transformerCache.putContent(template.getId(),
                        "attender-" + template.getType() + (asText ? "-text" : "-html"),
                        template.getModificationDate(),
                        asText ? template.getTextContent() : template.getHtmlContent());

            return transformer;
        } catch (TransformerConfigurationException e) {
            logger.error("Unable to generate a (cached) transformer from the given content", e);

            throw new ScriptException("Unable to generate a (cached) transformer from the given content");
        } catch (TransformerFactoryConfigurationError e) {
            logger.error("Unable to generate a (cached) transformer from the given content", e);

            throw new ScriptException("Unable to generate a (cached) transformer from the given content");
        }
    }

    /**
     * Retrieve all templates.
     * 
     * @return List<Template>
     */
    public List<Template> getTemplates() {
        return templateDAO.findAllTemplates();
    }

    /**
     * Add a new template.
     * 
     * @param templateType
     * @param language
     * @param textContent
     * @param htmlContent
     * @return Integer
     */
    public Integer addTemplate(final TemplateType templateType, final String language, final String textContent,
            final String htmlContent) {
        return templateDAO.addTemplate(templateType, language, textContent, htmlContent, new Date());
    }

    /**
     * Delete a given template.
     * 
     * @param id
     * @return boolean
     */
    public boolean deleteTemplate(final Integer id) {
        return templateDAO.deleteTemplate(id);
    }

    /**
     * Modify a template.
     * 
     * @param id
     * @param templateType
     * @param language
     * @param textContent
     * @param htmlContent
     * @param modificationDate
     * @return boolean
     */
    public boolean modifyTemplate(final Integer id, final TemplateType templateType, final String language,
            final String textContent, final String htmlContent) {
        return templateDAO.modifyTemplate(id, templateType, language, textContent, htmlContent, new Date());
    }

    /**
     * Template result.
     * 
     * @author Jasper van Veghel <jasper@seajas.com>
     */
    public class TemplateResult {
        /**
         * The text result.
         */
        private String textResult;

        /**
         * The HTML result.
         */
        private String htmlResult;

        /**
         * Retrieve the textResult.
         * 
         * @return String
         */
        public String getTextResult() {
            return textResult;
        }

        /**
         * Default constructor.
         * 
         * @param textResult
         * @param htmlResult
         */
        public TemplateResult(final String textResult, final String htmlResult) {
            this.textResult = textResult;
            this.htmlResult = htmlResult;
        }

        /**
         * Set the textResult.
         * 
         * @param textResult
         */
        public void setTextResult(final String textResult) {
            this.textResult = textResult;
        }

        /**
         * Retrieve the htmlResult.
         * 
         * @return String
         */
        public String getHtmlResult() {
            return htmlResult;
        }

        /**
         * Set the htmlResult.
         * 
         * @param htmlResult
         */
        public void setHtmlResult(final String htmlResult) {
            this.htmlResult = htmlResult;
        }
    }
}