Search in sources :

Example 11 with InternalOrganizationalEntity

use of org.kie.internal.task.api.model.InternalOrganizationalEntity 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 12 with InternalOrganizationalEntity

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

the class ConcurrentGlobalTimerServiceTest method testSessionPerProcessInstance.

@Test
public void testSessionPerProcessInstance() throws Exception {
    RuntimeEnvironment environment = RuntimeEnvironmentBuilder.Factory.get().newDefaultBuilder().entityManagerFactory(emf).userGroupCallback(userGroupCallback).addAsset(ResourceFactory.newClassPathResource("org/jbpm/test/functional/timer/IntermediateCatchEventTimerCycleWithHT.bpmn2"), ResourceType.BPMN2).schedulerService(globalScheduler).get();
    long startTimeStamp = System.currentTimeMillis();
    long maxEndTime = startTimeStamp + maxWaitTime;
    manager = RuntimeManagerFactory.Factory.get().newPerProcessInstanceRuntimeManager(environment);
    // prepare task service with users and groups
    RuntimeEngine engine = manager.getRuntimeEngine(EmptyContext.get());
    TaskService taskService = engine.getTaskService();
    Group grouphr = TaskModelProvider.getFactory().newGroup();
    ((InternalOrganizationalEntity) grouphr).setId("HR");
    User mary = TaskModelProvider.getFactory().newUser();
    ((InternalOrganizationalEntity) mary).setId("mary");
    User john = TaskModelProvider.getFactory().newUser();
    ((InternalOrganizationalEntity) john).setId("john");
    ((InternalTaskService) taskService).addGroup(grouphr);
    ((InternalTaskService) taskService).addUser(mary);
    ((InternalTaskService) taskService).addUser(john);
    manager.disposeRuntimeEngine(engine);
    completedStart = 0;
    for (int i = 0; i < nbThreadsProcess; i++) {
        new StartProcessPerProcessInstanceRunnable(manager, i).run();
    }
    completedTask = 0;
    for (int i = 0; i < nbThreadsTask; i++) {
        new Thread(new CompleteTaskPerProcessInstanceRunnable(manager, i)).start();
    }
    while (completedStart < nbThreadsProcess || completedTask < nbThreadsTask) {
        Thread.sleep(100);
        if (System.currentTimeMillis() > maxEndTime) {
            fail("Failure, did not finish in time most likely hanging");
        }
    }
    // make sure all process instance were completed
    engine = manager.getRuntimeEngine(EmptyContext.get());
    AuditService logService = engine.getAuditService();
    // active
    List<? extends ProcessInstanceLog> logs = logService.findActiveProcessInstances("IntermediateCatchEvent");
    assertNotNull(logs);
    for (ProcessInstanceLog log : logs) {
        logger.debug("Left over {}", log.getProcessInstanceId());
    }
    assertEquals(0, logs.size());
    // completed
    logs = logService.findProcessInstances("IntermediateCatchEvent");
    assertNotNull(logs);
    assertEquals(nbThreadsProcess, logs.size());
    manager.disposeRuntimeEngine(engine);
    logger.debug("Done");
}
Also used : Group(org.kie.api.task.model.Group) RuntimeEngine(org.kie.api.runtime.manager.RuntimeEngine) RuntimeEnvironment(org.kie.api.runtime.manager.RuntimeEnvironment) User(org.kie.api.task.model.User) InternalTaskService(org.kie.internal.task.api.InternalTaskService) TaskService(org.kie.api.task.TaskService) InternalTaskService(org.kie.internal.task.api.InternalTaskService) InternalOrganizationalEntity(org.kie.internal.task.api.model.InternalOrganizationalEntity) AuditService(org.kie.api.runtime.manager.audit.AuditService) ProcessInstanceLog(org.kie.api.runtime.manager.audit.ProcessInstanceLog) Test(org.junit.Test)

Example 13 with InternalOrganizationalEntity

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

the class GlobalTimerServiceVolumeTest method testRuntimeManagerStrategyWithTimerService.

@Test(timeout = 30000)
public void testRuntimeManagerStrategyWithTimerService() throws Exception {
    // prepare task service with users and groups
    RuntimeEngine engine = manager.getRuntimeEngine(EmptyContext.get());
    TaskService taskService = engine.getTaskService();
    Group grouphr = TaskModelProvider.getFactory().newGroup();
    ((InternalOrganizationalEntity) grouphr).setId("HR");
    Group groupadmins = TaskModelProvider.getFactory().newGroup();
    ((InternalOrganizationalEntity) groupadmins).setId("Administrators");
    User mary = TaskModelProvider.getFactory().newUser();
    ((InternalOrganizationalEntity) mary).setId("mary");
    User john = TaskModelProvider.getFactory().newUser();
    ((InternalOrganizationalEntity) john).setId("john");
    User admin = TaskModelProvider.getFactory().newUser();
    ((InternalOrganizationalEntity) admin).setId("Administrator");
    ((InternalTaskService) taskService).addGroup(grouphr);
    ((InternalTaskService) taskService).addGroup(groupadmins);
    ((InternalTaskService) taskService).addUser(mary);
    ((InternalTaskService) taskService).addUser(john);
    ((InternalTaskService) taskService).addUser(admin);
    manager.disposeRuntimeEngine(engine);
    int counter = numberOfProcesses;
    // start processes until oom
    while (counter > 0) {
        new GlobalTimerServiceVolumeTest.StartProcessPerProcessInstanceRunnable(manager).run();
        counter--;
    }
    Collection<TimerJobInstance> timers = null;
    Map<Long, List<GlobalJobHandle>> jobs = null;
    TimerService timerService = TimerServiceRegistry.getInstance().get(manager.getIdentifier() + TimerServiceRegistry.TIMER_SERVICE_SUFFIX);
    if (timerService != null) {
        if (timerService instanceof GlobalTimerService) {
            jobs = ((GlobalTimerService) timerService).getTimerJobsPerSession();
            timers = ((GlobalTimerService) timerService).getTimerJobFactoryManager().getTimerJobInstances();
        }
    }
    assertNotNull("Jobs should not be null as number of timers have been created", jobs);
    assertEquals("There should be no jobs in the global timer service", 0, jobs.size());
    assertNotNull("Timer instances should not be null as number of timers have been created", timers);
    assertEquals("There should be no timer instances in the global timer service manager", 0, timers.size());
    RuntimeEngine empty = manager.getRuntimeEngine(EmptyContext.get());
    AuditService logService = empty.getAuditService();
    List<? extends ProcessInstanceLog> logs = logService.findActiveProcessInstances("IntermediateCatchEvent");
    assertEquals("Active process instances should be " + numberOfProcesses, numberOfProcesses, logs.size());
    countDownListener.waitTillCompleted();
    List<TaskSummary> tasks = empty.getTaskService().getTasksAssignedAsPotentialOwner("john", "en-UK");
    assertEquals("Number of John's tasks should be " + numberOfProcesses, numberOfProcesses, tasks.size());
    for (TaskSummary task : tasks) {
        RuntimeEngine piEngine = manager.getRuntimeEngine(ProcessInstanceIdContext.get(task.getProcessInstanceId()));
        piEngine.getTaskService().start(task.getId(), "john");
        piEngine.getTaskService().complete(task.getId(), "john", null);
        manager.disposeRuntimeEngine(piEngine);
    }
    logs = logService.findActiveProcessInstances("IntermediateCatchEvent");
    assertEquals("Active process instances should be 0", 0, logs.size());
    logService.dispose();
    manager.disposeRuntimeEngine(empty);
}
Also used : Group(org.kie.api.task.model.Group) RuntimeEngine(org.kie.api.runtime.manager.RuntimeEngine) User(org.kie.api.task.model.User) TimerJobInstance(org.drools.core.time.impl.TimerJobInstance) InternalTaskService(org.kie.internal.task.api.InternalTaskService) TaskService(org.kie.api.task.TaskService) InternalTaskService(org.kie.internal.task.api.InternalTaskService) InternalOrganizationalEntity(org.kie.internal.task.api.model.InternalOrganizationalEntity) GlobalTimerService(org.jbpm.process.core.timer.impl.GlobalTimerService) TimerService(org.drools.core.time.TimerService) TaskSummary(org.kie.api.task.model.TaskSummary) List(java.util.List) ArrayList(java.util.ArrayList) AuditService(org.kie.api.runtime.manager.audit.AuditService) GlobalTimerService(org.jbpm.process.core.timer.impl.GlobalTimerService) Test(org.junit.Test)

Example 14 with InternalOrganizationalEntity

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

the class PeopleAssignmentHelper method assignBusinessAdministrators.

@SuppressWarnings("unchecked")
protected void assignBusinessAdministrators(WorkItem workItem, PeopleAssignments peopleAssignments) {
    List<OrganizationalEntity> businessAdministrators = peopleAssignments.getBusinessAdministrators();
    Object businessAdminGroupIds = adjustParam(workItem.getParameter(BUSINESSADMINISTRATOR_GROUP_ID), groupFilter);
    Object businessAdministratorIds = adjustParam(workItem.getParameter(BUSINESSADMINISTRATOR_ID), userFilter);
    if (!hasAdminAssigned(businessAdministrators)) {
        User administrator = TaskModelProvider.getFactory().newUser();
        ((InternalOrganizationalEntity) administrator).setId(administratorUser);
        businessAdministrators.add(administrator);
        Group adminGroup = TaskModelProvider.getFactory().newGroup();
        ((InternalOrganizationalEntity) adminGroup).setId(administratorGroup);
        businessAdministrators.add(adminGroup);
    }
    if (businessAdministratorIds instanceof Collection) {
        processPeopleAssignments((Collection<OrganizationalEntity>) businessAdministratorIds, businessAdministrators);
    } else {
        processPeopleAssignments((String) businessAdministratorIds, businessAdministrators, true);
    }
    if (businessAdminGroupIds instanceof Collection) {
        processPeopleAssignments((Collection<OrganizationalEntity>) businessAdminGroupIds, businessAdministrators);
    } else {
        processPeopleAssignments((String) businessAdminGroupIds, businessAdministrators, false);
    }
}
Also used : Group(org.kie.api.task.model.Group) User(org.kie.api.task.model.User) InternalOrganizationalEntity(org.kie.internal.task.api.model.InternalOrganizationalEntity) OrganizationalEntity(org.kie.api.task.model.OrganizationalEntity) Collection(java.util.Collection) InternalOrganizationalEntity(org.kie.internal.task.api.model.InternalOrganizationalEntity)

Example 15 with InternalOrganizationalEntity

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

the class TestPersistenceContext method createSomeTask.

public void createSomeTask() {
    testIsInitialized();
    TaskImpl task = new TaskImpl();
    InternalI18NText name = (InternalI18NText) TaskModelProvider.getFactory().newI18NText();
    name.setText("Some Task");
    List<I18NText> names = new ArrayList<I18NText>();
    names.add(name);
    task.setNames(names);
    InternalTaskData taskData = (InternalTaskData) TaskModelProvider.getFactory().newTaskData();
    taskData.setWorkItemId(12);
    taskData.setProcessInstanceId(1);
    taskData.setProcessId("someprocess");
    taskData.setDeploymentId("org.jbpm.test:someprocess:1.0");
    taskData.setProcessSessionId(1);
    task.setTaskData(taskData);
    InternalPeopleAssignments peopleAssignments = (InternalPeopleAssignments) TaskModelProvider.getFactory().newPeopleAssignments();
    peopleAssignments.setPotentialOwners(new ArrayList<OrganizationalEntity>());
    peopleAssignments.setBusinessAdministrators(new ArrayList<OrganizationalEntity>());
    peopleAssignments.setExcludedOwners(new ArrayList<OrganizationalEntity>());
    peopleAssignments.setRecipients(new ArrayList<OrganizationalEntity>());
    peopleAssignments.setTaskStakeholders(new ArrayList<OrganizationalEntity>());
    InternalOrganizationalEntity jdoe = (InternalOrganizationalEntity) TaskModelProvider.getFactory().newUser();
    jdoe.setId("jdoe");
    peopleAssignments.getPotentialOwners().add(jdoe);
    peopleAssignments.getBusinessAdministrators().add(jdoe);
    task.setPeopleAssignments(peopleAssignments);
    final boolean txOwner = transactionManager.begin();
    try {
        EntityManager em = entityManagerFactory.createEntityManager();
        em.persist(jdoe);
        em.persist(task);
        transactionManager.commit(txOwner);
    } catch (Exception ex) {
        ex.printStackTrace();
        transactionManager.rollback(txOwner);
        throw new RuntimeException(ex.getMessage(), ex);
    }
}
Also used : I18NText(org.kie.api.task.model.I18NText) InternalI18NText(org.kie.internal.task.api.model.InternalI18NText) OrganizationalEntity(org.kie.api.task.model.OrganizationalEntity) InternalOrganizationalEntity(org.kie.internal.task.api.model.InternalOrganizationalEntity) InternalI18NText(org.kie.internal.task.api.model.InternalI18NText) TaskImpl(org.jbpm.persistence.scripts.oldentities.TaskImpl) ArrayList(java.util.ArrayList) InternalTaskData(org.kie.internal.task.api.model.InternalTaskData) InternalOrganizationalEntity(org.kie.internal.task.api.model.InternalOrganizationalEntity) SQLException(java.sql.SQLException) ParseException(java.text.ParseException) IOException(java.io.IOException) InternalPeopleAssignments(org.kie.internal.task.api.model.InternalPeopleAssignments) EntityManager(javax.persistence.EntityManager)

Aggregations

InternalOrganizationalEntity (org.kie.internal.task.api.model.InternalOrganizationalEntity)31 User (org.kie.api.task.model.User)25 OrganizationalEntity (org.kie.api.task.model.OrganizationalEntity)21 Test (org.junit.Test)16 ArrayList (java.util.ArrayList)14 InternalTask (org.kie.internal.task.api.model.InternalTask)14 InternalTaskData (org.kie.internal.task.api.model.InternalTaskData)14 InternalPeopleAssignments (org.kie.internal.task.api.model.InternalPeopleAssignments)12 InputStreamReader (java.io.InputStreamReader)11 Reader (java.io.Reader)11 Group (org.kie.api.task.model.Group)11 ContentData (org.kie.internal.task.api.model.ContentData)11 HashMap (java.util.HashMap)10 CountDownTaskEventListener (org.jbpm.services.task.util.CountDownTaskEventListener)10 InternalContent (org.kie.internal.task.api.model.InternalContent)10 Date (java.util.Date)9 Task (org.kie.api.task.model.Task)5 I18NText (org.kie.api.task.model.I18NText)4 InternalI18NText (org.kie.internal.task.api.model.InternalI18NText)4 StringReader (java.io.StringReader)3