Template.java 6.84 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  javax.jcr.Binary
 *  javax.jcr.Item
 *  javax.jcr.Node
 *  javax.jcr.NodeIterator
 *  javax.jcr.Property
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  org.apache.commons.io.IOUtils
 *  org.apache.commons.lang.text.StrSubstitutor
 *  org.apache.commons.mail.Email
 *  org.apache.commons.mail.EmailException
 *  org.apache.commons.mail.SimpleEmail
 *  org.apache.jackrabbit.api.security.user.Authorizable
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.resource.ValueMap
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.workflow.impl.email;

import com.day.cq.workflow.impl.email.EMailBuilder;
import com.day.cq.workflow.impl.email.Notification;
import com.day.cq.workflow.impl.email.NotificationHelper;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.jcr.Binary;
import javax.jcr.Item;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.text.StrSubstitutor;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ValueMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Template
implements EMailBuilder {
    private static final Logger log = LoggerFactory.getLogger(Template.class);
    private Map<String, Properties> mailTemplates = new HashMap<String, Properties>();

    public Template(String path, Session session) {
        if (!this.loadDefaultsFromRepo(path, session)) {
            this.loadDefaults();
        }
    }

    @Override
    public Email build(Notification ntf, ResourceResolver resolver) throws EmailException {
        SimpleEmail email = new SimpleEmail();
        String from = ntf.getEmailFromAddress();
        if (from != null && from.length() > 0) {
            email.setFrom(ntf.getEmailFromAddress());
        }
        HashMap<String, String> headerMap = new HashMap<String, String>();
        headerMap.put("Content-Type", "text/plain; charset=utf-8");
        email.setHeaders(headerMap);
        email.setCharset("utf-8");
        try {
            email.addTo(NotificationHelper.getEmailAddress(ntf.getParticipant().getID(), resolver));
        }
        catch (RepositoryException e) {
            throw new EmailException("Unable to look up the participant's ID.", (Throwable)e);
        }
        StrSubstitutor repl = new StrSubstitutor((Map)ntf.getProperties());
        Properties mailTemplate = this.getMailTemplate(ntf);
        email.setSubject(repl.replace(mailTemplate.get("subject")));
        StringBuilder msg = new StringBuilder();
        msg.append(repl.replace(mailTemplate.get("header")));
        msg.append(repl.replace(mailTemplate.get("message")));
        msg.append(repl.replace(mailTemplate.get("footer")));
        email.setMsg(msg.toString());
        return email;
    }

    private void loadDefaults() {
        Properties props = new Properties();
        props.put("subject", "Workflow notification: ${event.EventType}");
        props.put("header", "-------------------------------------------------------------------------------------\nTime: ${event.TimeStamp}\nStep: ${item.node.title}\nUser: ${participant.name} (${participant.id})\nWorkflow: ${model.title}\n-------------------------------------------------------------------------------------\n\n");
        props.put("message", "Page: ${host.prefix}${payload.path}.html\n");
        props.put("footer", "\n-------------------------------------------------------------------------------------\nView the overview in your ${host.prefix}/libs/cq/workflow/content/console.html\n-------------------------------------------------------------------------------------\nThis is an automatically generated message. Please do not reply.");
        this.mailTemplates.put("en", props);
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private boolean loadDefaultsFromRepo(String path, Session session) {
        try {
            if (path != null && session.itemExists(path)) {
                Node defaultNode = (Node)session.getItem(path);
                NodeIterator templates = defaultNode.getNodes();
                while (templates.hasNext()) {
                    Node t = templates.nextNode();
                    if (!t.isNodeType("nt:file")) continue;
                    InputStream is = null;
                    try {
                        is = t.getProperty("jcr:content/jcr:data").getBinary().getStream();
                        Properties rawProps = new Properties();
                        rawProps.load(is);
                        Properties props = new Properties();
                        Enumeration e = rawProps.propertyNames();
                        while (e.hasMoreElements()) {
                            String key = (String)e.nextElement();
                            String rawValue = rawProps.getProperty(key);
                            String value = new String(rawValue.getBytes("ISO-8859-1"), "UTF-8");
                            props.put(key, value);
                        }
                        this.mailTemplates.put(this.getName(t.getName()), props);
                        log.debug("Loaded mail template for: " + t.getName());
                        continue;
                    }
                    catch (IOException ioe) {
                        log.debug("Error occured while reading mail template " + t.getPath(), (Throwable)ioe);
                        continue;
                    }
                    finally {
                        IOUtils.closeQuietly((InputStream)is);
                        continue;
                    }
                }
                return true;
            }
        }
        catch (RepositoryException re) {
            log.error("Error while loading email template.", (Throwable)re);
        }
        log.debug("Cannot load default mail templates from repository (" + path + ")");
        return false;
    }

    private Properties getMailTemplate(Notification ntf) {
        String lng;
        String string = lng = ntf.getProperties().containsKey((Object)"participant.language") ? (String)ntf.getProperties().get((Object)"participant.language") : "en";
        if (this.mailTemplates.containsKey(lng)) {
            return this.mailTemplates.get(lng);
        }
        return this.mailTemplates.get("en");
    }

    private String getName(String nodeName) {
        return nodeName.substring(0, nodeName.indexOf("."));
    }
}