001/** 002 * Copyright 2005-2017 The Kuali Foundation 003 * 004 * Licensed under the Educational Community License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.opensource.org/licenses/ecl2.php 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.kuali.rice.kew.mail; 017 018import org.kuali.rice.core.api.mail.EmailContent; 019import org.kuali.rice.core.api.util.xml.XmlJotter; 020import org.kuali.rice.kew.api.WorkflowRuntimeException; 021import org.w3c.dom.Document; 022import org.w3c.dom.Node; 023 024import javax.xml.transform.Templates; 025import javax.xml.transform.TransformerException; 026import javax.xml.transform.dom.DOMResult; 027import javax.xml.transform.dom.DOMSource; 028import javax.xml.xpath.XPath; 029import javax.xml.xpath.XPathConstants; 030import javax.xml.xpath.XPathExpressionException; 031import javax.xml.xpath.XPathFactory; 032 033 034/** 035 * A class which has some convenience methods for handling Emails and stylesheets. 036 * 037 * @author Kuali Rice Team (rice.collab@kuali.org) 038 * 039 */ 040public class EmailStyleHelper { 041 042 private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(EmailStyleHelper.class); 043 044 public EmailContent generateEmailContent(Templates style, Document document) { 045 DOMResult result = new DOMResult(); 046 if (LOG.isDebugEnabled()) { 047 LOG.debug("Input document: " + XmlJotter.jotNode(document.getDocumentElement(), true)); 048 } 049 try { 050 style.newTransformer().transform(new DOMSource(document), result); 051 } catch (TransformerException te) { 052 String message = "Error transforming immediate reminder DOM"; 053 LOG.error(message, te); 054 throw new WorkflowRuntimeException(message, te); 055 } 056 057 Node node = result.getNode(); 058 059 if (LOG.isDebugEnabled()) { 060 LOG.debug("Email to be sent: " + XmlJotter.jotNode(node)); 061 } 062 XPathFactory xpf = XPathFactory.newInstance(); 063 XPath xpath = xpf.newXPath(); 064 try { 065 String subject = (String) xpath.evaluate("/email/subject", node, XPathConstants.STRING); 066 String body = (String) xpath.evaluate("/email/body", node, XPathConstants.STRING); 067 // simple heuristic to determine whether content is HTML 068 return new EmailContent(subject, body, body.matches("(?msi).*<(\\w+:)?html.*")); 069 } catch (XPathExpressionException xpee) { 070 throw new WorkflowRuntimeException("Error evaluating generated email content", xpee); 071 } 072 } 073 074}