Search in sources :

Example 1 with EmailNotificationHeader

use of org.kie.internal.task.api.model.EmailNotificationHeader in project jbpm by kiegroup.

the class UserTaskAdminServiceImpl method buildEmailNotification.

@Override
public EmailNotification buildEmailNotification(String subjectStr, List<OrganizationalEntity> recipients, String bodyStr, String fromStr, String replyToStr) {
    EmailNotification emailNotification = TaskModelProvider.getFactory().newEmialNotification();
    Map<Language, EmailNotificationHeader> emailHeaders = new HashMap<Language, EmailNotificationHeader>();
    List<I18NText> subjects = new ArrayList<I18NText>();
    List<I18NText> names = new ArrayList<I18NText>();
    String locale = "en-UK";
    EmailNotificationHeader emailHeader = TaskModelProvider.getFactory().newEmailNotificationHeader();
    emailHeader.setBody(bodyStr);
    emailHeader.setFrom(fromStr);
    emailHeader.setReplyTo(replyToStr);
    emailHeader.setLanguage(locale);
    emailHeader.setSubject(subjectStr);
    Language lang = TaskModelProvider.getFactory().newLanguage();
    lang.setMapkey(locale);
    emailHeaders.put(lang, emailHeader);
    I18NText subject = TaskModelProvider.getFactory().newI18NText();
    ((InternalI18NText) subject).setLanguage(locale);
    ((InternalI18NText) subject).setText(emailHeader.getSubject());
    ;
    subjects.add(subject);
    names.add(subject);
    emailNotification.setEmailHeaders(emailHeaders);
    emailNotification.setNames(names);
    emailNotification.setRecipients(new ArrayList<>(recipients));
    emailNotification.setSubjects(subjects);
    return emailNotification;
}
Also used : I18NText(org.kie.api.task.model.I18NText) InternalI18NText(org.kie.internal.task.api.model.InternalI18NText) Language(org.kie.internal.task.api.model.Language) EmailNotificationHeader(org.kie.internal.task.api.model.EmailNotificationHeader) HashMap(java.util.HashMap) InternalI18NText(org.kie.internal.task.api.model.InternalI18NText) ArrayList(java.util.ArrayList) EmailNotification(org.kie.internal.task.api.model.EmailNotification)

Example 2 with EmailNotificationHeader

use of org.kie.internal.task.api.model.EmailNotificationHeader in project jbpm by kiegroup.

the class EmailNotificationListener method onNotification.

@Override
public void onNotification(NotificationEvent event, UserInfo userInfo) {
    if (userInfo == null || mailSession == null) {
        logger.info("Missing mail session or userinfo - skipping email notification listener processing");
        return;
    }
    if (event.getNotification() instanceof EmailNotification) {
        EmailNotification notification = (EmailNotification) event.getNotification();
        Task task = event.getTask();
        // group users into languages
        Map<String, List<User>> users = new HashMap<String, List<User>>();
        for (OrganizationalEntity entity : notification.getBusinessAdministrators()) {
            if (entity instanceof Group) {
                buildMapByLanguage(users, (Group) entity, userInfo);
            } else {
                buildMapByLanguage(users, (User) entity, userInfo);
            }
        }
        for (OrganizationalEntity entity : notification.getRecipients()) {
            if (entity instanceof Group) {
                buildMapByLanguage(users, (Group) entity, userInfo);
            } else {
                buildMapByLanguage(users, (User) entity, userInfo);
            }
        }
        Map<String, Object> variables = event.getContent();
        Map<? extends Language, ? extends EmailNotificationHeader> headers = notification.getEmailHeaders();
        for (Iterator<Map.Entry<String, List<User>>> it = users.entrySet().iterator(); it.hasNext(); ) {
            try {
                Map.Entry<String, List<User>> entry = it.next();
                Language lang = TaskModelProvider.getFactory().newLanguage();
                lang.setMapkey(entry.getKey());
                EmailNotificationHeader header = headers.get(lang);
                Message msg = new MimeMessage(mailSession);
                Set<String> toAddresses = new HashSet<String>();
                for (User user : entry.getValue()) {
                    String emailAddress = userInfo.getEmailForEntity(user);
                    if (emailAddress != null && !toAddresses.contains(emailAddress)) {
                        msg.addRecipients(Message.RecipientType.TO, InternetAddress.parse(emailAddress, false));
                        toAddresses.add(emailAddress);
                    } else {
                        logger.warn("Email address not found for user {}", user.getId());
                    }
                }
                if (header.getFrom() != null && header.getFrom().trim().length() > 0) {
                    User user = TaskModelProvider.getFactory().newUser();
                    ((InternalOrganizationalEntity) user).setId(header.getFrom());
                    msg.setFrom(new InternetAddress(userInfo.getEmailForEntity(user)));
                } else {
                    msg.setFrom(new InternetAddress(mailSession.getProperty("mail.from")));
                }
                if (header.getReplyTo() != null && header.getReplyTo().trim().length() > 0) {
                    User user = TaskModelProvider.getFactory().newUser();
                    ((InternalOrganizationalEntity) user).setId(header.getReplyTo());
                    msg.setReplyTo(new InternetAddress[] { new InternetAddress(userInfo.getEmailForEntity(user)) });
                } else if (mailSession.getProperty("mail.replyto") != null) {
                    msg.setReplyTo(new InternetAddress[] { new InternetAddress(mailSession.getProperty("mail.replyto")) });
                }
                Map<String, Object> vars = new HashMap<String, Object>();
                vars.put("doc", variables);
                // add internal items to be able to reference them in templates
                vars.put("processInstanceId", task.getTaskData().getProcessInstanceId());
                vars.put("processSessionId", task.getTaskData().getProcessSessionId());
                vars.put("workItemId", task.getTaskData().getWorkItemId());
                vars.put("expirationTime", task.getTaskData().getExpirationTime());
                vars.put("taskId", task.getId());
                if (task.getPeopleAssignments() != null) {
                    vars.put("owners", task.getPeopleAssignments().getPotentialOwners());
                }
                String subject = (String) TemplateRuntime.eval(header.getSubject(), vars);
                String body = (String) TemplateRuntime.eval(header.getBody(), vars);
                if (variables.containsKey("attachments")) {
                    Multipart multipart = new MimeMultipart();
                    // prepare body as first mime body part
                    MimeBodyPart messageBodyPart = new MimeBodyPart();
                    messageBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(body, "text/html")));
                    multipart.addBodyPart(messageBodyPart);
                    List<String> attachments = getAttachements(variables.get("attachments"));
                    for (String attachment : attachments) {
                        MimeBodyPart attachementBodyPart = new MimeBodyPart();
                        URL attachmentUrl = getAttachemntURL(attachment);
                        String contentType = MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(attachmentUrl.getFile());
                        attachementBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(attachmentUrl.openStream(), contentType)));
                        String fileName = new File(attachmentUrl.getFile()).getName();
                        attachementBodyPart.setFileName(fileName);
                        attachementBodyPart.setContentID("<" + fileName + ">");
                        multipart.addBodyPart(attachementBodyPart);
                    }
                    // Put parts in message
                    msg.setContent(multipart);
                } else {
                    msg.setDataHandler(new DataHandler(new ByteArrayDataSource(body, "text/html")));
                }
                msg.setSubject(subject);
                msg.setHeader("X-Mailer", "jbpm human task service");
                msg.setSentDate(new Date());
                Transport.send(msg);
            } catch (Exception e) {
                logger.error("Unable to send email notification due to {}", e.getMessage());
                logger.debug("Stacktrace:", e);
            }
        }
    }
}
Also used : Group(org.kie.api.task.model.Group) Task(org.kie.api.task.model.Task) InternetAddress(javax.mail.internet.InternetAddress) Multipart(javax.mail.Multipart) MimeMultipart(javax.mail.internet.MimeMultipart) User(org.kie.api.task.model.User) EmailNotificationHeader(org.kie.internal.task.api.model.EmailNotificationHeader) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) HashMap(java.util.HashMap) DataHandler(javax.activation.DataHandler) EmailNotification(org.kie.internal.task.api.model.EmailNotification) InternalOrganizationalEntity(org.kie.internal.task.api.model.InternalOrganizationalEntity) URL(java.net.URL) Language(org.kie.internal.task.api.model.Language) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) ArrayList(java.util.ArrayList) List(java.util.List) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) HashSet(java.util.HashSet) OrganizationalEntity(org.kie.api.task.model.OrganizationalEntity) InternalOrganizationalEntity(org.kie.internal.task.api.model.InternalOrganizationalEntity) Date(java.util.Date) MalformedURLException(java.net.MalformedURLException) MimeBodyPart(javax.mail.internet.MimeBodyPart) HashMap(java.util.HashMap) MimetypesFileTypeMap(javax.activation.MimetypesFileTypeMap) Map(java.util.Map) File(java.io.File)

Example 3 with EmailNotificationHeader

use of org.kie.internal.task.api.model.EmailNotificationHeader in project jbpm by kiegroup.

the class ExecuteReminderCommand method buildDefaultNotification.

private Notification buildDefaultNotification(TaskData taskData, Task task) {
    EmailNotification emailNotificationImpl = TaskModelProvider.getFactory().newEmialNotification();
    Map<Language, EmailNotificationHeader> map = new HashMap<Language, EmailNotificationHeader>();
    EmailNotificationHeader emailNotificationHeaderImpl = TaskModelProvider.getFactory().newEmailNotificationHeader();
    emailNotificationHeaderImpl.setBody(buildDefafultEmailBody(taskData, task));
    emailNotificationHeaderImpl.setFrom(fromUser);
    emailNotificationHeaderImpl.setReplyTo(fromUser);
    emailNotificationHeaderImpl.setLanguage("en-UK");
    emailNotificationHeaderImpl.setSubject(buildDefafultEmailSubject(taskData, task));
    Language language = TaskModelProvider.getFactory().newLanguage();
    language.setMapkey("en-UK");
    map.put(language, emailNotificationHeaderImpl);
    emailNotificationImpl.setEmailHeaders(map);
    List<OrganizationalEntity> recipients = new ArrayList<OrganizationalEntity>();
    recipients.add(taskData.getActualOwner());
    emailNotificationImpl.setRecipients(recipients);
    return emailNotificationImpl;
}
Also used : Language(org.kie.internal.task.api.model.Language) EmailNotificationHeader(org.kie.internal.task.api.model.EmailNotificationHeader) OrganizationalEntity(org.kie.api.task.model.OrganizationalEntity) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) EmailNotification(org.kie.internal.task.api.model.EmailNotification)

Example 4 with EmailNotificationHeader

use of org.kie.internal.task.api.model.EmailNotificationHeader in project jbpm by kiegroup.

the class ListTaskNotificationsCommand method execute.

@Override
public List<TaskNotification> execute(Context cntxt) {
    TaskContext context = (TaskContext) cntxt;
    Language lang = factory.newLanguage();
    lang.setMapkey("en-UK");
    Task task = context.getTaskQueryService().getTaskInstanceById(taskId);
    if (!isBusinessAdmin(userId, task.getPeopleAssignments().getBusinessAdministrators(), context)) {
        throw new PermissionDeniedException("User " + userId + " is not business admin of task " + taskId);
    }
    Deadlines deadlines = ((InternalTask) task).getDeadlines();
    List<TaskNotification> notificationsNotStarted = deadlines.getStartDeadlines().stream().filter(d -> !d.getEscalations().isEmpty() && !d.getEscalations().get(0).getNotifications().isEmpty()).map(d -> {
        Notification n = d.getEscalations().get(0).getNotifications().get(0);
        EmailNotificationHeader email = ((EmailNotification) n).getEmailHeaders().get(lang);
        return new TaskNotificationImpl(d.getId(), get(n.getNames()), email.getSubject(), email.getBody(), d.getDate(), n.getRecipients(), n.getBusinessAdministrators(), !d.isEscalated());
    }).collect(Collectors.toList());
    List<TaskNotification> notificationsNotCompleted = deadlines.getEndDeadlines().stream().filter(d -> !d.getEscalations().isEmpty() && !d.getEscalations().get(0).getNotifications().isEmpty()).map(d -> {
        Notification n = d.getEscalations().get(0).getNotifications().get(0);
        EmailNotificationHeader email = ((EmailNotification) n).getEmailHeaders().get(lang);
        return new TaskNotificationImpl(d.getId(), get(n.getNames()), email.getSubject(), email.getBody(), d.getDate(), n.getRecipients(), n.getBusinessAdministrators(), !d.isEscalated());
    }).collect(Collectors.toList());
    List<TaskNotification> result = new ArrayList<>();
    result.addAll(notificationsNotStarted);
    result.addAll(notificationsNotCompleted);
    if (activeOnly) {
        logger.debug("Removing already completed deadlines from the result");
        result = result.stream().filter(t -> t.isActive()).collect(Collectors.toList());
    }
    return result;
}
Also used : Logger(org.slf4j.Logger) Task(org.kie.api.task.model.Task) EmailNotificationHeader(org.kie.internal.task.api.model.EmailNotificationHeader) LoggerFactory(org.slf4j.LoggerFactory) I18NText(org.kie.api.task.model.I18NText) TaskModelProvider(org.kie.internal.task.api.TaskModelProvider) TaskNotification(org.jbpm.services.api.admin.TaskNotification) EmailNotification(org.kie.internal.task.api.model.EmailNotification) Collectors(java.util.stream.Collectors) Language(org.kie.internal.task.api.model.Language) ArrayList(java.util.ArrayList) TaskNotificationImpl(org.jbpm.kie.services.impl.admin.TaskNotificationImpl) UserGroupCallbackTaskCommand(org.jbpm.services.task.commands.UserGroupCallbackTaskCommand) List(java.util.List) Context(org.kie.api.runtime.Context) PermissionDeniedException(org.jbpm.services.task.exception.PermissionDeniedException) TaskModelFactory(org.kie.internal.task.api.TaskModelFactory) InternalTask(org.kie.internal.task.api.model.InternalTask) TaskContext(org.jbpm.services.task.commands.TaskContext) Deadlines(org.kie.internal.task.api.model.Deadlines) Notification(org.kie.internal.task.api.model.Notification) Task(org.kie.api.task.model.Task) InternalTask(org.kie.internal.task.api.model.InternalTask) TaskContext(org.jbpm.services.task.commands.TaskContext) EmailNotificationHeader(org.kie.internal.task.api.model.EmailNotificationHeader) InternalTask(org.kie.internal.task.api.model.InternalTask) ArrayList(java.util.ArrayList) EmailNotification(org.kie.internal.task.api.model.EmailNotification) TaskNotification(org.jbpm.services.api.admin.TaskNotification) EmailNotification(org.kie.internal.task.api.model.EmailNotification) Notification(org.kie.internal.task.api.model.Notification) TaskNotificationImpl(org.jbpm.kie.services.impl.admin.TaskNotificationImpl) Deadlines(org.kie.internal.task.api.model.Deadlines) Language(org.kie.internal.task.api.model.Language) PermissionDeniedException(org.jbpm.services.task.exception.PermissionDeniedException) TaskNotification(org.jbpm.services.api.admin.TaskNotification)

Example 5 with EmailNotificationHeader

use of org.kie.internal.task.api.model.EmailNotificationHeader in project jbpm by kiegroup.

the class HumanTaskHandlerHelperTest method testNotStartedNotifyMinimalMultipleExpirations.

@Test
public void testNotStartedNotifyMinimalMultipleExpirations() {
    WorkItem workItem = new WorkItemImpl();
    workItem.setParameter("NotStartedNotify", "[tousers:john|subject:Test of notification|body:And here is the body]@[4h,6h]");
    @SuppressWarnings("unchecked") Deadlines deadlines = HumanTaskHandlerHelper.setDeadlines(workItem, Collections.EMPTY_LIST, null);
    assertNotNull(deadlines);
    assertEquals(2, deadlines.getStartDeadlines().size());
    assertEquals(0, deadlines.getEndDeadlines().size());
    assertEquals(1, deadlines.getStartDeadlines().get(0).getEscalations().size());
    assertEquals(1, deadlines.getStartDeadlines().get(0).getEscalations().get(0).getNotifications().size());
    assertEquals(0, deadlines.getStartDeadlines().get(0).getEscalations().get(0).getReassignments().size());
    // verify notification
    Notification notification = deadlines.getStartDeadlines().get(0).getEscalations().get(0).getNotifications().get(0);
    assertNotNull(notification);
    assertEquals(1, notification.getRecipients().size());
    assertEquals("john", notification.getRecipients().get(0).getId());
    assertEquals(1, notification.getSubjects().size());
    assertEquals("Test of notification", notification.getSubjects().get(0).getText());
    EmailNotification emailNotification = (EmailNotification) notification;
    assertEquals(1, emailNotification.getEmailHeaders().size());
    Language lang = TaskModelProvider.getFactory().newLanguage();
    lang.setMapkey("en-UK");
    EmailNotificationHeader header = emailNotification.getEmailHeaders().get(lang);
    assertNotNull(header);
    assertEquals("Test of notification", header.getSubject());
    assertEquals("And here is the body", header.getBody());
    // check deadline expiration time
    assertNotNull(deadlines.getStartDeadlines().get(0).getDate());
    long expirationTime = deadlines.getStartDeadlines().get(0).getDate().getTime() - System.currentTimeMillis();
    assertEquals(4, roundExpirationTime(expirationTime));
    // verify notification
    notification = deadlines.getStartDeadlines().get(1).getEscalations().get(0).getNotifications().get(0);
    assertNotNull(notification);
    assertEquals(1, notification.getRecipients().size());
    assertEquals("john", notification.getRecipients().get(0).getId());
    assertEquals(1, notification.getSubjects().size());
    assertEquals("Test of notification", notification.getSubjects().get(0).getText());
    emailNotification = (EmailNotification) notification;
    assertEquals(1, emailNotification.getEmailHeaders().size());
    lang = TaskModelProvider.getFactory().newLanguage();
    lang.setMapkey("en-UK");
    header = emailNotification.getEmailHeaders().get(lang);
    assertNotNull(header);
    assertEquals("Test of notification", header.getSubject());
    assertEquals("And here is the body", header.getBody());
    // check deadline expiration time
    assertNotNull(deadlines.getStartDeadlines().get(1).getDate());
    expirationTime = deadlines.getStartDeadlines().get(1).getDate().getTime() - System.currentTimeMillis();
    assertEquals(6, roundExpirationTime(expirationTime));
}
Also used : Deadlines(org.kie.internal.task.api.model.Deadlines) Language(org.kie.internal.task.api.model.Language) EmailNotificationHeader(org.kie.internal.task.api.model.EmailNotificationHeader) WorkItemImpl(org.drools.core.process.instance.impl.WorkItemImpl) EmailNotification(org.kie.internal.task.api.model.EmailNotification) WorkItem(org.drools.core.process.instance.WorkItem) EmailNotification(org.kie.internal.task.api.model.EmailNotification) Notification(org.kie.internal.task.api.model.Notification) Test(org.junit.Test) AbstractBaseTest(org.jbpm.test.util.AbstractBaseTest)

Aggregations

EmailNotification (org.kie.internal.task.api.model.EmailNotification)9 EmailNotificationHeader (org.kie.internal.task.api.model.EmailNotificationHeader)9 Language (org.kie.internal.task.api.model.Language)9 Notification (org.kie.internal.task.api.model.Notification)6 ArrayList (java.util.ArrayList)5 Deadlines (org.kie.internal.task.api.model.Deadlines)5 HashMap (java.util.HashMap)4 WorkItem (org.drools.core.process.instance.WorkItem)4 WorkItemImpl (org.drools.core.process.instance.impl.WorkItemImpl)4 AbstractBaseTest (org.jbpm.test.util.AbstractBaseTest)4 Test (org.junit.Test)4 I18NText (org.kie.api.task.model.I18NText)3 OrganizationalEntity (org.kie.api.task.model.OrganizationalEntity)3 List (java.util.List)2 Group (org.kie.api.task.model.Group)2 Task (org.kie.api.task.model.Task)2 User (org.kie.api.task.model.User)2 File (java.io.File)1 MalformedURLException (java.net.MalformedURLException)1 URL (java.net.URL)1