Search in sources :

Example 1 with ExecutorService

use of org.kie.api.executor.ExecutorService in project jbpm by kiegroup.

the class JPASignalManager method signalEvent.

public void signalEvent(String type, Object event) {
    String actualSignalType = type.replaceFirst(ASYNC_SIGNAL_PREFIX, "");
    ProcessPersistenceContextManager contextManager = (ProcessPersistenceContextManager) getKnowledgeRuntime().getEnvironment().get(EnvironmentName.PERSISTENCE_CONTEXT_MANAGER);
    ProcessPersistenceContext context = contextManager.getProcessPersistenceContext();
    List<Long> processInstancesToSignalList = context.getProcessInstancesWaitingForEvent(actualSignalType);
    // handle signal asynchronously
    if (type.startsWith(ASYNC_SIGNAL_PREFIX)) {
        RuntimeManager runtimeManager = ((RuntimeManager) getKnowledgeRuntime().getEnvironment().get("RuntimeManager"));
        ExecutorService executorService = (ExecutorService) getKnowledgeRuntime().getEnvironment().get("ExecutorService");
        if (runtimeManager != null && executorService != null) {
            for (Long processInstanceId : processInstancesToSignalList) {
                CommandContext ctx = new CommandContext();
                ctx.setData("deploymentId", runtimeManager.getIdentifier());
                ctx.setData("processInstanceId", processInstanceId);
                ctx.setData("Signal", actualSignalType);
                ctx.setData("Event", event);
                executorService.scheduleRequest(AsyncSignalEventCommand.class.getName(), ctx);
            }
            return;
        } else {
            logger.warn("Signal should be sent asynchronously but there is no executor service available, continuing sync...");
        }
    }
    for (long id : processInstancesToSignalList) {
        try {
            getKnowledgeRuntime().getProcessInstance(id);
        } catch (IllegalStateException e) {
        // IllegalStateException can be thrown when using RuntimeManager
        // and invalid ksession was used for given context
        } catch (RuntimeException e) {
            logger.warn("Exception when loading process instance for signal '{}', instance with id {} will not be signaled", e.getMessage(), id);
        }
    }
    super.signalEvent(actualSignalType, event);
}
Also used : CommandContext(org.kie.api.executor.CommandContext) RuntimeManager(org.kie.api.runtime.manager.RuntimeManager) ExecutorService(org.kie.api.executor.ExecutorService) ProcessPersistenceContextManager(org.jbpm.persistence.api.ProcessPersistenceContextManager) AsyncSignalEventCommand(org.jbpm.process.core.async.AsyncSignalEventCommand) ProcessPersistenceContext(org.jbpm.persistence.api.ProcessPersistenceContext)

Example 2 with ExecutorService

use of org.kie.api.executor.ExecutorService in project jbpm by kiegroup.

the class AsyncHandlerProducer method getWorkItemHandlers.

@Override
public Map<String, WorkItemHandler> getWorkItemHandlers(String identifier, Map<String, Object> params) {
    Map<String, WorkItemHandler> handlers = new HashMap<String, WorkItemHandler>();
    ExecutorService executorService = (ExecutorService) params.get("executorService");
    if (executorService != null) {
        handlers.put("async", new AsyncWorkItemHandler(executorService, PrintOutCommand.class.getName()));
    }
    return handlers;
}
Also used : AsyncWorkItemHandler(org.jbpm.executor.impl.wih.AsyncWorkItemHandler) WorkItemHandler(org.kie.api.runtime.process.WorkItemHandler) HashMap(java.util.HashMap) ExecutorService(org.kie.api.executor.ExecutorService) AsyncWorkItemHandler(org.jbpm.executor.impl.wih.AsyncWorkItemHandler)

Example 3 with ExecutorService

use of org.kie.api.executor.ExecutorService in project jbpm by kiegroup.

the class RequeueRunningJobsCommand method execute.

public ExecutionResults execute(CommandContext ctx) {
    Long olderThan = (Long) ctx.getData("MaxRunningTime");
    Long requestId = (Long) ctx.getData("RequestId");
    try {
        ExecutorService executorService = ExecutorServiceFactory.newExecutorService(null);
        if (executorService instanceof RequeueAware) {
            if (requestId != null) {
                logger.info("Requeue jobs by id {}", requestId);
                ((RequeueAware) executorService).requeueById(requestId);
            } else {
                logger.info("Requeue jobs older than {}", olderThan);
                ((RequeueAware) executorService).requeue(olderThan);
            }
        } else {
            logger.info("Executor Service is not capable of jobs requeue");
        }
    } catch (Exception e) {
        logger.error("Error while creating CDI bean from jbpm executor", e);
    }
    logger.info("Command executed on executor with data {}", ctx.getData());
    ExecutionResults executionResults = new ExecutionResults();
    return executionResults;
}
Also used : ExecutionResults(org.kie.api.executor.ExecutionResults) RequeueAware(org.jbpm.executor.RequeueAware) ExecutorService(org.kie.api.executor.ExecutorService)

Example 4 with ExecutorService

use of org.kie.api.executor.ExecutorService in project jbpm by kiegroup.

the class AsyncEventNodeInstance method internalTrigger.

public void internalTrigger(final NodeInstance from, String type) {
    super.internalTrigger(from, type);
    ExecutorService executorService = (ExecutorService) getProcessInstance().getKnowledgeRuntime().getEnvironment().get("ExecutorService");
    if (executorService != null) {
        RuntimeManager runtimeManager = ((RuntimeManager) getProcessInstance().getKnowledgeRuntime().getEnvironment().get("RuntimeManager"));
        CommandContext ctx = new CommandContext();
        ctx.setData("deploymentId", runtimeManager.getIdentifier());
        ctx.setData("processInstanceId", getProcessInstance().getId());
        ctx.setData("Signal", getEventType());
        ctx.setData("Event", null);
        executorService.scheduleRequest(AsyncSignalEventCommand.class.getName(), ctx);
        Node node = getNode();
        if (node != null) {
            String uniqueId = (String) node.getMetaData().get("UniqueId");
            if (uniqueId == null) {
                uniqueId = ((NodeImpl) node).getUniqueId();
            }
            ((WorkflowProcessInstanceImpl) getProcessInstance()).getIterationLevels().remove(getNode().getMetaData().get("UniqueId"));
        }
    } else {
        logger.warn("No async executor service found continuing as sync operation...");
        // if there is no executor service available move as sync node
        triggerCompleted();
    }
}
Also used : CommandContext(org.kie.api.executor.CommandContext) AsyncEventNode(org.jbpm.workflow.core.node.AsyncEventNode) Node(org.kie.api.definition.process.Node) ExecutorService(org.kie.api.executor.ExecutorService) RuntimeManager(org.kie.api.runtime.manager.RuntimeManager) AsyncSignalEventCommand(org.jbpm.process.core.async.AsyncSignalEventCommand)

Example 5 with ExecutorService

use of org.kie.api.executor.ExecutorService in project jbpm by kiegroup.

the class ParallelAsyncJobsTest method testRunBasicAsync.

/**
 * The tests verifies that async. jobs will be executed in parallel.
 *
 * JobExecutor configuration:
 * - Thread pool size = 4
 * - Pending task scan interval = 1 second
 *
 * The process in this test will create 4 long running tasks (8 seconds) one after another. Then
 * the test will sleep for 4 seconds giving the JobExecutor time to pick up at least 2 tasks.
 *
 * The JobExecutor should be able to pick up all the tasks because one task takes 8 seconds to
 * complete and the scan interval is 1 second. On the other hand a task should not complete in
 * the 4 seconds so pending task count should not be lower than 3 if parallelism does not work.
 */
@Test(timeout = 30000)
@BZ("1146829")
public void testRunBasicAsync() throws Exception {
    ExecutorService executorService = getExecutorService();
    final Set<String> threadExeuctingJobs = new HashSet<>();
    CountDownAsyncJobListener countDownListener = new CountDownAsyncJobListener(4) {

        @Override
        public void afterJobExecuted(AsynchronousJobEvent event) {
            super.afterJobExecuted(event);
            threadExeuctingJobs.add(Thread.currentThread().getName());
        }
    };
    ((ExecutorServiceImpl) executorService).addAsyncJobListener(countDownListener);
    KieSession ks = createKSession(PARENT, SUBPROCESS);
    ks.getWorkItemManager().registerWorkItemHandler("async", new AsyncWorkItemHandler(executorService, "org.jbpm.test.command.LongRunningCommand"));
    List<String> exceptions = new ArrayList<String>();
    exceptions.add("ADRESS_EXCEPTION");
    exceptions.add("ID_EXCEPTION");
    exceptions.add("PHONE_EXCEPTION");
    Map<String, Object> pm = new HashMap<String, Object>();
    pm.put("exceptions", exceptions);
    ProcessInstance pi = ks.startProcess(PARENT_ID, pm);
    // assert that the main process was completed as tasks are executed asynchronously
    assertProcessInstanceCompleted(pi.getId());
    countDownListener.waitTillCompleted();
    // assert that all jobs have where completed.
    Assertions.assertThat(executorService.getCompletedRequests(new QueryContext())).as("All async jobs should have been executed").hasSize(4);
    Assertions.assertThat(threadExeuctingJobs).as("There should be 4 distinct threads as jobs where executed in parallel").hasSize(4);
}
Also used : ExecutorServiceImpl(org.jbpm.executor.impl.ExecutorServiceImpl) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) QueryContext(org.kie.api.runtime.query.QueryContext) AsynchronousJobEvent(org.jbpm.executor.AsynchronousJobEvent) CountDownAsyncJobListener(org.jbpm.executor.test.CountDownAsyncJobListener) ExecutorService(org.kie.api.executor.ExecutorService) AsyncWorkItemHandler(org.jbpm.executor.impl.wih.AsyncWorkItemHandler) KieSession(org.kie.api.runtime.KieSession) ProcessInstance(org.kie.api.runtime.process.ProcessInstance) HashSet(java.util.HashSet) Test(org.junit.Test) BZ(qa.tools.ikeeper.annotation.BZ)

Aggregations

ExecutorService (org.kie.api.executor.ExecutorService)6 HashMap (java.util.HashMap)2 ExecutorServiceImpl (org.jbpm.executor.impl.ExecutorServiceImpl)2 AsyncWorkItemHandler (org.jbpm.executor.impl.wih.AsyncWorkItemHandler)2 AsyncSignalEventCommand (org.jbpm.process.core.async.AsyncSignalEventCommand)2 CommandContext (org.kie.api.executor.CommandContext)2 RuntimeManager (org.kie.api.runtime.manager.RuntimeManager)2 ArrayList (java.util.ArrayList)1 HashSet (java.util.HashSet)1 AsynchronousJobEvent (org.jbpm.executor.AsynchronousJobEvent)1 RequeueAware (org.jbpm.executor.RequeueAware)1 AvailableJobsExecutor (org.jbpm.executor.impl.AvailableJobsExecutor)1 ClassCacheManager (org.jbpm.executor.impl.ClassCacheManager)1 ExecutorImpl (org.jbpm.executor.impl.ExecutorImpl)1 ExecutorQueryServiceImpl (org.jbpm.executor.impl.jpa.ExecutorQueryServiceImpl)1 ExecutorRequestAdminServiceImpl (org.jbpm.executor.impl.jpa.ExecutorRequestAdminServiceImpl)1 JPAExecutorStoreService (org.jbpm.executor.impl.jpa.JPAExecutorStoreService)1 CountDownAsyncJobListener (org.jbpm.executor.test.CountDownAsyncJobListener)1 ProcessPersistenceContext (org.jbpm.persistence.api.ProcessPersistenceContext)1 ProcessPersistenceContextManager (org.jbpm.persistence.api.ProcessPersistenceContextManager)1