Search in sources :

Example 51 with OrganizationalEntity

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

the class DefaultUserInfo method buildRegistry.

protected void buildRegistry(Properties registryProps) {
    if (registryProps != null) {
        Iterator<Object> propertyKeys = registryProps.keySet().iterator();
        while (propertyKeys.hasNext()) {
            String propertyKey = (String) propertyKeys.next();
            // following is the string for every organizational entity
            // email:locale:displayname:[member,member]
            // members are optional and should be given for group entities
            String propertyValue = registryProps.getProperty(propertyKey);
            String[] elems = propertyValue.split(":");
            Map<String, Object> entityInfo = new HashMap<String, Object>();
            entityInfo.put("email", elems[0]);
            entityInfo.put("locale", elems[1]);
            entityInfo.put("name", elems[2]);
            if (elems.length == 4 && elems[3] != null) {
                String memberList = elems[3];
                if (memberList.startsWith("[")) {
                    memberList = memberList.substring(1);
                }
                if (memberList.endsWith("]")) {
                    memberList = memberList.substring(0, memberList.length() - 1);
                }
                String[] members = memberList.split(",");
                List<OrganizationalEntity> membersList = new ArrayList<OrganizationalEntity>();
                for (String member : members) {
                    User user = TaskModelProvider.getFactory().newUser();
                    ((InternalOrganizationalEntity) user).setId(member);
                    membersList.add(user);
                }
                entityInfo.put("members", membersList);
            }
            registry.put(propertyKey, entityInfo);
        }
    }
}
Also used : User(org.kie.api.task.model.User) InternalOrganizationalEntity(org.kie.internal.task.api.model.InternalOrganizationalEntity) OrganizationalEntity(org.kie.api.task.model.OrganizationalEntity) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) InternalOrganizationalEntity(org.kie.internal.task.api.model.InternalOrganizationalEntity)

Example 52 with OrganizationalEntity

use of org.kie.api.task.model.OrganizationalEntity 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 53 with OrganizationalEntity

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

the class ExecuteDeadlinesCommand method execute.

@SuppressWarnings("unchecked")
@Override
public Void execute(Context context) {
    TaskContext ctx = (TaskContext) context;
    UserInfo userInfo = (UserInfo) context.get(EnvironmentName.TASK_USER_INFO);
    TaskPersistenceContext persistenceContext = ctx.getPersistenceContext();
    try {
        Task task = persistenceContext.findTask(taskId);
        Deadline deadline = persistenceContext.findDeadline(deadlineId);
        if (task == null || deadline == null) {
            return null;
        }
        TaskData taskData = task.getTaskData();
        if (taskData != null) {
            // check if task is still in valid status
            if (type.isValidStatus(taskData.getStatus())) {
                Map<String, Object> variables = null;
                Content content = persistenceContext.findContent(taskData.getDocumentContentId());
                if (content != null) {
                    ContentMarshallerContext mContext = ctx.getTaskContentService().getMarshallerContext(task);
                    Object objectFromBytes = ContentMarshallerHelper.unmarshall(content.getContent(), mContext.getEnvironment(), mContext.getClassloader());
                    if (objectFromBytes instanceof Map) {
                        variables = (Map<String, Object>) objectFromBytes;
                    } else {
                        variables = new HashMap<String, Object>();
                        variables.put("content", objectFromBytes);
                    }
                } else {
                    variables = Collections.emptyMap();
                }
                if (deadline == null || deadline.getEscalations() == null) {
                    return null;
                }
                TaskEventSupport taskEventSupport = ctx.getTaskEventSupport();
                for (Escalation escalation : deadline.getEscalations()) {
                    // run reassignment first to allow notification to be send to new potential owners
                    if (!escalation.getReassignments().isEmpty()) {
                        taskEventSupport.fireBeforeTaskReassigned(task, ctx);
                        // get first and ignore the rest.
                        Reassignment reassignment = escalation.getReassignments().get(0);
                        logger.debug("Reassigning to {}", reassignment.getPotentialOwners());
                        ((InternalTaskData) task.getTaskData()).setStatus(Status.Ready);
                        List<OrganizationalEntity> potentialOwners = new ArrayList<OrganizationalEntity>(reassignment.getPotentialOwners());
                        ((InternalPeopleAssignments) task.getPeopleAssignments()).setPotentialOwners(potentialOwners);
                        ((InternalTaskData) task.getTaskData()).setActualOwner(null);
                        // use assignment service to directly assign actual owner if enabled
                        AssignmentService assignmentService = AssignmentServiceProvider.get();
                        if (assignmentService.isEnabled()) {
                            assignmentService.assignTask(task, ctx);
                        }
                        taskEventSupport.fireAfterTaskReassigned(task, ctx);
                    }
                    for (Notification notification : escalation.getNotifications()) {
                        if (notification.getNotificationType() == NotificationType.Email) {
                            taskEventSupport.fireBeforeTaskNotified(task, ctx);
                            logger.debug("Sending an Email");
                            NotificationListenerManager.get().broadcast(new NotificationEvent(notification, task, variables), userInfo);
                            taskEventSupport.fireAfterTaskNotified(task, ctx);
                        }
                    }
                }
            }
        }
        deadline.setEscalated(true);
        persistenceContext.updateDeadline(deadline);
        persistenceContext.updateTask(task);
    } catch (Exception e) {
        logger.error("Error when executing deadlines", e);
    }
    return null;
}
Also used : Task(org.kie.api.task.model.Task) Escalation(org.kie.internal.task.api.model.Escalation) InternalTaskData(org.kie.internal.task.api.model.InternalTaskData) ArrayList(java.util.ArrayList) UserInfo(org.kie.internal.task.api.UserInfo) AssignmentService(org.jbpm.services.task.assignment.AssignmentService) Notification(org.kie.internal.task.api.model.Notification) InternalTaskData(org.kie.internal.task.api.model.InternalTaskData) TaskData(org.kie.api.task.model.TaskData) InternalPeopleAssignments(org.kie.internal.task.api.model.InternalPeopleAssignments) TaskEventSupport(org.jbpm.services.task.events.TaskEventSupport) ContentMarshallerContext(org.kie.internal.task.api.ContentMarshallerContext) OrganizationalEntity(org.kie.api.task.model.OrganizationalEntity) Deadline(org.kie.internal.task.api.model.Deadline) NotificationEvent(org.kie.internal.task.api.model.NotificationEvent) Reassignment(org.kie.internal.task.api.model.Reassignment) TaskPersistenceContext(org.kie.internal.task.api.TaskPersistenceContext) Content(org.kie.api.task.model.Content) HashMap(java.util.HashMap) Map(java.util.Map)

Example 54 with OrganizationalEntity

use of org.kie.api.task.model.OrganizationalEntity 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 55 with OrganizationalEntity

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

the class UserGroupCallbackTaskCommand method doCallbackOperationForPeopleAssignments.

protected void doCallbackOperationForPeopleAssignments(InternalPeopleAssignments assignments, TaskContext context) {
    List<OrganizationalEntity> nonExistingEntities = new ArrayList<OrganizationalEntity>();
    if (assignments != null) {
        List<? extends OrganizationalEntity> businessAdmins = assignments.getBusinessAdministrators();
        if (businessAdmins != null) {
            for (OrganizationalEntity admin : businessAdmins) {
                if (admin instanceof User) {
                    boolean userExists = doCallbackUserOperation(admin.getId(), context);
                    if (!userExists) {
                        nonExistingEntities.add(admin);
                    }
                }
                if (admin instanceof Group) {
                    boolean groupExists = doCallbackGroupOperation(admin.getId(), context);
                    if (!groupExists) {
                        nonExistingEntities.add(admin);
                    }
                }
            }
            if (!nonExistingEntities.isEmpty()) {
                businessAdmins.removeAll(nonExistingEntities);
                nonExistingEntities.clear();
            }
        }
        if (businessAdmins == null || businessAdmins.isEmpty()) {
            // throw an exception as it should not be allowed to create task without administrator
            throw new CannotAddTaskException("There are no known Business Administrators, task cannot be created according to WS-HT specification");
        }
        List<? extends OrganizationalEntity> potentialOwners = assignments.getPotentialOwners();
        if (potentialOwners != null) {
            for (OrganizationalEntity powner : potentialOwners) {
                if (powner instanceof User) {
                    boolean userExists = doCallbackUserOperation(powner.getId(), context);
                    if (!userExists) {
                        nonExistingEntities.add(powner);
                    }
                }
                if (powner instanceof Group) {
                    boolean groupExists = doCallbackGroupOperation(powner.getId(), context);
                    if (!groupExists) {
                        nonExistingEntities.add(powner);
                    }
                }
            }
            if (!nonExistingEntities.isEmpty()) {
                potentialOwners.removeAll(nonExistingEntities);
                nonExistingEntities.clear();
            }
        }
        if (assignments.getTaskInitiator() != null && assignments.getTaskInitiator().getId() != null) {
            doCallbackUserOperation(assignments.getTaskInitiator().getId(), context);
        }
        List<? extends OrganizationalEntity> excludedOwners = assignments.getExcludedOwners();
        if (excludedOwners != null) {
            for (OrganizationalEntity exowner : excludedOwners) {
                if (exowner instanceof User) {
                    boolean userExists = doCallbackUserOperation(exowner.getId(), context);
                    if (!userExists) {
                        nonExistingEntities.add(exowner);
                    }
                }
                if (exowner instanceof Group) {
                    boolean groupExists = doCallbackGroupOperation(exowner.getId(), context);
                    if (!groupExists) {
                        nonExistingEntities.add(exowner);
                    }
                }
            }
            if (!nonExistingEntities.isEmpty()) {
                excludedOwners.removeAll(nonExistingEntities);
                nonExistingEntities.clear();
            }
        }
        List<? extends OrganizationalEntity> recipients = assignments.getRecipients();
        if (recipients != null) {
            for (OrganizationalEntity recipient : recipients) {
                if (recipient instanceof User) {
                    boolean userExists = doCallbackUserOperation(recipient.getId(), context);
                    if (!userExists) {
                        nonExistingEntities.add(recipient);
                    }
                }
                if (recipient instanceof Group) {
                    boolean groupExists = doCallbackGroupOperation(recipient.getId(), context);
                    if (!groupExists) {
                        nonExistingEntities.add(recipient);
                    }
                }
            }
            if (!nonExistingEntities.isEmpty()) {
                recipients.removeAll(nonExistingEntities);
                nonExistingEntities.clear();
            }
        }
        List<? extends OrganizationalEntity> stakeholders = assignments.getTaskStakeholders();
        if (stakeholders != null) {
            for (OrganizationalEntity stakeholder : stakeholders) {
                if (stakeholder instanceof User) {
                    boolean userExists = doCallbackUserOperation(stakeholder.getId(), context);
                    if (!userExists) {
                        nonExistingEntities.add(stakeholder);
                    }
                }
                if (stakeholder instanceof Group) {
                    boolean groupExists = doCallbackGroupOperation(stakeholder.getId(), context);
                    if (!groupExists) {
                        nonExistingEntities.add(stakeholder);
                    }
                }
            }
            if (!nonExistingEntities.isEmpty()) {
                stakeholders.removeAll(nonExistingEntities);
                nonExistingEntities.clear();
            }
        }
    }
}
Also used : Group(org.kie.api.task.model.Group) CannotAddTaskException(org.jbpm.services.task.exception.CannotAddTaskException) User(org.kie.api.task.model.User) OrganizationalEntity(org.kie.api.task.model.OrganizationalEntity) InternalOrganizationalEntity(org.kie.internal.task.api.model.InternalOrganizationalEntity) ArrayList(java.util.ArrayList)

Aggregations

OrganizationalEntity (org.kie.api.task.model.OrganizationalEntity)147 Test (org.junit.Test)94 HashMap (java.util.HashMap)69 CaseFileInstance (org.jbpm.casemgmt.api.model.instance.CaseFileInstance)55 ArrayList (java.util.ArrayList)54 User (org.kie.api.task.model.User)52 UserImpl (org.jbpm.services.task.impl.model.UserImpl)51 AbstractCaseServicesBaseTest (org.jbpm.casemgmt.impl.util.AbstractCaseServicesBaseTest)48 CaseInstance (org.jbpm.casemgmt.api.model.instance.CaseInstance)41 InternalPeopleAssignments (org.kie.internal.task.api.model.InternalPeopleAssignments)36 InternalTask (org.kie.internal.task.api.model.InternalTask)35 InternalOrganizationalEntity (org.kie.internal.task.api.model.InternalOrganizationalEntity)34 Task (org.kie.api.task.model.Task)33 QueryContext (org.kie.api.runtime.query.QueryContext)32 Group (org.kie.api.task.model.Group)29 CaseNotFoundException (org.jbpm.casemgmt.api.CaseNotFoundException)26 TaskSummary (org.kie.api.task.model.TaskSummary)25 AdHocFragmentNotFoundException (org.jbpm.casemgmt.api.AdHocFragmentNotFoundException)24 CaseActiveException (org.jbpm.casemgmt.api.CaseActiveException)24 CaseCommentNotFoundException (org.jbpm.casemgmt.api.CaseCommentNotFoundException)24