EMailNotificationService.java 18.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.granite.security.user.UserPropertiesService
 *  com.day.cq.mailer.MailService
 *  com.day.cq.workflow.WorkflowException
 *  com.day.cq.workflow.WorkflowService
 *  com.day.cq.workflow.WorkflowSession
 *  com.day.cq.workflow.event.WorkflowEvent
 *  com.day.cq.workflow.exec.WorkItem
 *  com.day.cq.workflow.exec.Workflow
 *  com.day.cq.workflow.metadata.MetaDataMap
 *  com.day.cq.workflow.model.WorkflowNode
 *  javax.jcr.Session
 *  org.apache.commons.lang.StringUtils
 *  org.apache.commons.mail.Email
 *  org.apache.felix.scr.annotations.Component
 *  org.apache.felix.scr.annotations.Properties
 *  org.apache.felix.scr.annotations.Property
 *  org.apache.felix.scr.annotations.Reference
 *  org.apache.felix.scr.annotations.ReferenceCardinality
 *  org.apache.felix.scr.annotations.ReferencePolicy
 *  org.apache.felix.scr.annotations.Service
 *  org.apache.jackrabbit.api.security.user.Authorizable
 *  org.apache.jackrabbit.api.security.user.UserManager
 *  org.apache.sling.api.resource.LoginException
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.resource.ResourceResolverFactory
 *  org.apache.sling.i18n.ResourceBundleProvider
 *  org.apache.sling.jcr.api.SlingRepository
 *  org.osgi.service.component.ComponentContext
 *  org.osgi.service.event.Event
 *  org.osgi.service.event.EventHandler
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.workflow.impl.email;

import com.adobe.granite.security.user.UserPropertiesService;
import com.day.cq.mailer.MailService;
import com.day.cq.workflow.WorkflowException;
import com.day.cq.workflow.WorkflowService;
import com.day.cq.workflow.WorkflowSession;
import com.day.cq.workflow.event.WorkflowEvent;
import com.day.cq.workflow.exec.WorkItem;
import com.day.cq.workflow.exec.Workflow;
import com.day.cq.workflow.impl.ServiceLoginUtil;
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 com.day.cq.workflow.impl.email.NotificationImpl;
import com.day.cq.workflow.impl.email.Template;
import com.day.cq.workflow.metadata.MetaDataMap;
import com.day.cq.workflow.model.WorkflowNode;
import java.util.Collections;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import javax.jcr.Session;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.mail.Email;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.ReferencePolicy;
import org.apache.felix.scr.annotations.Service;
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.jackrabbit.api.security.user.UserManager;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.i18n.ResourceBundleProvider;
import org.apache.sling.jcr.api.SlingRepository;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(immediate=1, label="Day CQ Workflow Email Notification Service", metatype=1, description="Listenes to workflow events and triggers email notifications.")
@Service(value={EventHandler.class})
@Properties(value={@Property(name="event.topics", value={"com/day/cq/workflow/event", "com/adobe/granite/taskmanagement/event"}, propertyPrivate=1), @Property(name="event.filter", value={"(!(event.application=*))"}, propertyPrivate=1)})
public class EMailNotificationService
implements EventHandler {
    private static final Logger log = LoggerFactory.getLogger(EMailNotificationService.class);
    @Property(value={"noreply@day.com"}, label="From-Email-Address")
    private static final String EMAIL_FROM_ADDRESS = "from.address";
    @Property(value={"http://localhost:4502"}, label="Host URL Prefix", description="Used to prefix links to pages in the notification emails")
    private static final String NOTIFICATION_HOST_PREFIX = "host.prefix";
    @Property(boolValue={1}, label="Notify on Abort", description="Enables notification for workflow abort event")
    private static final String NOTIFYONABORT = "notify.onabort";
    @Property(boolValue={1}, label="Notify on Complete", description="Enables notification for workflow complete event")
    private static final String NOTIFYONCOMPLETE = "notify.oncomplete";
    @Property(boolValue={0}, label="Notify on Complete of Container Workflow", description="Enables notification for container workflow complete event")
    private static final String NOTIFY_ON_CONTAINER_COMPLETE = "notify.oncontainercomplete";
    public static final String JOB_SEND_NOTIFICATION_EMAIL = "WORKFLOW_SEND_NOTIFICATION_EMAIL";
    private static final String DO_NOTIFY = "DO_NOTIFY";
    private static final String TEMPLATE_ROOT_LOCATION = "/etc/workflow/notification/email/default";
    private static final String EMAIL_NOTIFICATION_STOP = "EMAIL_NOTIFICATION_STOP";
    @Reference
    protected SlingRepository repository = null;
    @Reference
    private ResourceResolverFactory resolverFactory = null;
    @Reference
    protected WorkflowService workflowService = null;
    @Reference(cardinality=ReferenceCardinality.MANDATORY_UNARY, policy=ReferencePolicy.STATIC)
    protected MailService mailService = null;
    @Reference
    protected ResourceBundleProvider resourceBundleProvider = null;
    @Reference
    private UserPropertiesService userPropertiesService = null;
    private String emailFromAddress;
    private String hostPrefix;
    private boolean notifyOnAbort;
    private boolean notifyOnComplete;
    private boolean notifyOnContainerComplete;
    private final Map<String, EMailBuilder> builders = new HashMap<String, EMailBuilder>();
    private final BlockingQueue<WorkflowEvent> queue = new LinkedBlockingQueue<WorkflowEvent>();
    private EventProcessor processor;

    public void handleEvent(Event event) {
        if ("com/day/cq/workflow/event".equals(event.getTopic()) && event.getProperty("WorkflowInstanceId") != null) {
            try {
                this.queue.put((WorkflowEvent)event);
                if (log.isDebugEnabled()) {
                    log.debug("handleEvent: put event [{}] in queue, size now [{}]", event.getProperty("EventType"), (Object)this.queue.size());
                }
            }
            catch (InterruptedException e) {}
        } else {
            log.debug("skipping non-workflow event: {}", (Object)event.toString());
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private void sendNotification(WorkflowEvent event) {
        WorkflowSession session = null;
        ResourceResolver userResolver = null;
        try {
            Workflow workflow;
            session = this.getWorkflowSession();
            if (session == null) {
                log.error("Unable to retrieve workflow session for event: {}.  Aborting", (Object)event);
                return;
            }
            String eventType = (String)event.getProperty("EventType");
            WorkItem item = (WorkItem)event.getProperty("Workitem");
            Workflow workflow2 = workflow = item == null ? null : item.getWorkflow();
            if (workflow == null) {
                try {
                    workflow = session.getWorkflow((String)event.getProperty("WorkflowInstanceId"));
                }
                catch (WorkflowException e) {
                    log.error("workflow does not exist: ", (Throwable)e);
                }
            }
            if (workflow == null) {
                log.error("unable to retrieve workflow for event: {}. aborting", (Object)event);
                return;
            }
            if (this.doNotifyParticipants(item == null ? null : item.getNode(), eventType)) {
                String userGroupId = this.getId(item, workflow, eventType);
                userResolver = ServiceLoginUtil.createWorkflowUserReaderResolver(this.resolverFactory);
                Set<Authorizable> users = NotificationHelper.getParticipants(userGroupId, userResolver);
                for (Authorizable user : users) {
                    NotificationImpl notification = new NotificationImpl(workflow, item, event, this.resolverFactory);
                    notification.load(this, user);
                    log.debug("Created and loaded notification for {}", (Object)event);
                    EMailBuilder builder = this.builders.get(eventType);
                    if (builder != null) {
                        try {
                            Email email = builder.build(notification, userResolver);
                            if (null != email) {
                                this.mailService.sendEmail(email);
                                continue;
                            }
                            log.error("could not send email, notificator did not deliver message: [{}]", (Object)notification);
                        }
                        catch (Throwable e) {
                            if (log.isDebugEnabled()) {
                                log.debug("error while sending email for " + (Object)item + ": ", e);
                                continue;
                            }
                            log.error("error while sending email for " + (Object)item + ": " + e.getMessage());
                        }
                        continue;
                    }
                    log.debug("could not find suitable workflow notifier for type [{}] - [{}]", (Object)eventType, (Object)item);
                }
            }
        }
        finally {
            if (session != null) {
                session.logout();
            }
            if (userResolver != null && userResolver.isLive()) {
                userResolver.close();
            }
        }
    }

    private String getId(WorkItem item, Workflow workflow, String eventType) {
        String id = null;
        if (eventType.equals("NodeTransition") && item != null) {
            id = (String)item.getNode().getMetaDataMap().get("PARTICIPANT", String.class);
        } else if (eventType.equals("WorkflowCompleted") || eventType.equals("WorkflowAborted")) {
            id = workflow.getInitiator();
        }
        if (id == null && item != null && item.getCurrentAssignee() != null) {
            id = item.getCurrentAssignee();
        }
        return id;
    }

    private boolean doNotifyParticipants(WorkflowNode node, String eventType) {
        if (node != null && eventType.equals("NodeTransition")) {
            MetaDataMap metadata = node.getMetaDataMap();
            return metadata != null && metadata.get("DO_NOTIFY", String.class) != null && (((String)metadata.get("DO_NOTIFY", String.class)).equals("on") || ((String)metadata.get("DO_NOTIFY", String.class)).equals("true"));
        }
        return true;
    }

    private boolean doNotifyOnEvent(WorkflowEvent event) {
        String eventType = (String)event.getProperty("EventType");
        if ("WorkflowAborted".equals(eventType)) {
            return this.notifyOnAbort;
        }
        if ("WorkflowCompleted".equals(eventType)) {
            String parentId = (String)event.getProperty("ParentWorkflowId");
            if (StringUtils.isNotEmpty((String)parentId) && StringUtils.startsWithIgnoreCase((String)parentId, (String)"/etc")) {
                log.debug("Is container workflow - notifyOnContainerComplete: {}", (Object)this.notifyOnContainerComplete);
                return this.notifyOnContainerComplete;
            }
            log.debug("Not a container workflow - notifyOnComplete: {}", (Object)this.notifyOnComplete);
            return this.notifyOnComplete;
        }
        return true;
    }

    public String getEmailFromAddress() {
        return this.emailFromAddress;
    }

    public String getHostPrefix() {
        return this.hostPrefix;
    }

    public String getUserLanguage(String userId) {
        return NotificationHelper.getUserLanguage(this.repository, this.resolverFactory, userId);
    }

    public ResourceBundle getUserResourceBundle(String language) {
        return this.resourceBundleProvider.getResourceBundle(new Locale(language));
    }

    private UserManager getUserManager(ResourceResolver userResolver) {
        UserManager um = null;
        if (userResolver != null) {
            um = (UserManager)userResolver.adaptTo(UserManager.class);
        }
        return um;
    }

    private ResourceResolver getResourceResolver(Session session) {
        ResourceResolver resolver = null;
        try {
            resolver = this.resolverFactory.getResourceResolver(Collections.singletonMap("user.jcr.session", session));
        }
        catch (LoginException e) {
            log.error("Unable to get resource resolver.", (Throwable)e);
        }
        return resolver;
    }

    private WorkflowSession getWorkflowSession() {
        Session session = ServiceLoginUtil.createWorkflowServiceSession(this.repository);
        return this.workflowService.getWorkflowSession(session);
    }

    protected void activate(ComponentContext context) {
        Dictionary properties = context.getProperties();
        this.emailFromAddress = (String)properties.get("from.address");
        this.hostPrefix = (String)properties.get("host.prefix");
        this.notifyOnAbort = (Boolean)properties.get("notify.onabort");
        this.notifyOnComplete = (Boolean)properties.get("notify.oncomplete");
        this.notifyOnContainerComplete = (Boolean)properties.get("notify.oncontainercomplete");
        Session session = ServiceLoginUtil.createWorkflowServiceSession(this.repository);
        if (session != null) {
            this.builders.put("NodeTransition", new Template("/etc/workflow/notification/email/default", session));
            this.builders.put("WorkflowAborted", new Template("/etc/workflow/notification/email/default", session));
            this.builders.put("WorkflowCompleted", new Template("/etc/workflow/notification/email/default", session));
        } else {
            log.error("Unable to load email templates.  Only default template will be used.");
        }
        if (session != null && session.isLive()) {
            session.logout();
        }
        this.processor = new EventProcessor();
        Thread thread = new Thread((Runnable)this.processor, this.getClass().getSimpleName() + "-Processor");
        thread.setDaemon(true);
        thread.start();
    }

    protected void deactivate(ComponentContext context) {
        this.processor.stop();
        Hashtable<String, Boolean> props = new Hashtable<String, Boolean>();
        props.put("EMAIL_NOTIFICATION_STOP", true);
        this.queue.offer(new WorkflowEvent(props));
    }

    protected void bindRepository(SlingRepository slingRepository) {
        this.repository = slingRepository;
    }

    protected void unbindRepository(SlingRepository slingRepository) {
        if (this.repository == slingRepository) {
            this.repository = null;
        }
    }

    protected void bindResolverFactory(ResourceResolverFactory resourceResolverFactory) {
        this.resolverFactory = resourceResolverFactory;
    }

    protected void unbindResolverFactory(ResourceResolverFactory resourceResolverFactory) {
        if (this.resolverFactory == resourceResolverFactory) {
            this.resolverFactory = null;
        }
    }

    protected void bindWorkflowService(WorkflowService workflowService) {
        this.workflowService = workflowService;
    }

    protected void unbindWorkflowService(WorkflowService workflowService) {
        if (this.workflowService == workflowService) {
            this.workflowService = null;
        }
    }

    protected void bindMailService(MailService mailService) {
        this.mailService = mailService;
    }

    protected void unbindMailService(MailService mailService) {
        if (this.mailService == mailService) {
            this.mailService = null;
        }
    }

    protected void bindResourceBundleProvider(ResourceBundleProvider resourceBundleProvider) {
        this.resourceBundleProvider = resourceBundleProvider;
    }

    protected void unbindResourceBundleProvider(ResourceBundleProvider resourceBundleProvider) {
        if (this.resourceBundleProvider == resourceBundleProvider) {
            this.resourceBundleProvider = null;
        }
    }

    protected void bindUserPropertiesService(UserPropertiesService userPropertiesService) {
        this.userPropertiesService = userPropertiesService;
    }

    protected void unbindUserPropertiesService(UserPropertiesService userPropertiesService) {
        if (this.userPropertiesService == userPropertiesService) {
            this.userPropertiesService = null;
        }
    }

    private class EventProcessor
    implements Runnable {
        private volatile boolean isRunning;

        private EventProcessor() {
            this.isRunning = true;
        }

        public void stop() {
            this.isRunning = false;
        }

        @Override
        public void run() {
            log.debug("Processor started");
            while (this.isRunning) {
                try {
                    WorkflowEvent event;
                    if (log.isDebugEnabled()) {
                        log.debug("taking next event from queue - [{}] remaining", (Object)EMailNotificationService.this.queue.size());
                    }
                    if ((event = (WorkflowEvent)EMailNotificationService.this.queue.take()).getProperty("EMAIL_NOTIFICATION_STOP") != null) {
                        log.debug("stop event, get out");
                        break;
                    }
                    if (EMailNotificationService.this.doNotifyOnEvent(event)) {
                        log.debug("sending notification for: {}", event.getProperty("EventType"));
                        EMailNotificationService.this.sendNotification(event);
                        continue;
                    }
                    log.debug("ignoring notification for: {}", event.getProperty("EventType"));
                }
                catch (InterruptedException e) {}
            }
            log.debug("Processor done");
        }
    }

}