Search in sources :

Example 71 with RuntimeManager

use of org.kie.api.runtime.manager.RuntimeManager in project jbpm by kiegroup.

the class AsyncSignalEventCommand method execute.

@Override
public ExecutionResults execute(CommandContext ctx) throws Exception {
    String deploymentId = (String) ctx.getData("deploymentId");
    if (deploymentId == null) {
        deploymentId = (String) ctx.getData("DeploymentId");
    }
    Long processInstanceId = (Long) ctx.getData("processInstanceId");
    if (processInstanceId == null) {
        processInstanceId = (Long) ctx.getData("ProcessInstanceId");
    }
    String signal = (String) ctx.getData("Signal");
    Object event = ctx.getData("Event");
    if (deploymentId == null || signal == null) {
        throw new IllegalArgumentException("Deployment id and signal name is required");
    }
    RuntimeManager runtimeManager = RuntimeManagerRegistry.get().getManager(deploymentId);
    if (runtimeManager == null) {
        throw new IllegalArgumentException("No runtime manager found for deployment id " + deploymentId);
    }
    RuntimeEngine engine = runtimeManager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId));
    try {
        engine.getKieSession().signalEvent(signal, event, processInstanceId);
        return new ExecutionResults();
    } finally {
        runtimeManager.disposeRuntimeEngine(engine);
    }
}
Also used : RuntimeEngine(org.kie.api.runtime.manager.RuntimeEngine) ExecutionResults(org.kie.api.executor.ExecutionResults) RuntimeManager(org.kie.api.runtime.manager.RuntimeManager)

Example 72 with RuntimeManager

use of org.kie.api.runtime.manager.RuntimeManager in project jbpm by kiegroup.

the class ClassloaderKModuleDeploymentServiceTest method testDeploymentOfProcesses.

@Test
public void testDeploymentOfProcesses() throws Exception {
    assertNotNull(deploymentService);
    KModuleDeploymentUnit deploymentUnit = new KModuleDeploymentUnit(GROUP_ID, ARTIFACT_ID, VERSION, "defaultKieBase", "defaultKieSession");
    deploymentUnit.setStrategy(RuntimeStrategy.PER_REQUEST);
    deploymentService.deploy(deploymentUnit);
    units.add(deploymentUnit);
    DeployedUnit deployed = deploymentService.getDeployedUnit(deploymentUnit.getIdentifier());
    assertNotNull(deployed);
    assertNotNull(deployed.getDeploymentUnit());
    assertNotNull(deployed.getRuntimeManager());
    assertEquals("org.jbpm.test:jbpm-module:1.0:defaultKieBase:defaultKieSession", deployed.getDeploymentUnit().getIdentifier());
    assertNotNull(runtimeDataService);
    Collection<ProcessDefinition> processes = runtimeDataService.getProcesses(new QueryContext());
    assertNotNull(processes);
    assertEquals(1, processes.size());
    RuntimeManager manager = deploymentService.getRuntimeManager(deploymentUnit.getIdentifier());
    assertNotNull(manager);
    RuntimeEngine engine = manager.getRuntimeEngine(EmptyContext.get());
    assertNotNull(engine);
    Class<?> clazz = Class.forName("org.jbpm.test.Person", true, ((InternalRuntimeManager) manager).getEnvironment().getClassLoader());
    Object instance = clazz.newInstance();
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("person", instance);
    ProcessInstance processInstance = engine.getKieSession().startProcess("testkjar.src.main.resources.process", params);
    assertEquals(ProcessInstance.STATE_ACTIVE, processInstance.getState());
    List<TaskSummary> tasks = engine.getTaskService().getTasksOwned("salaboy", "en-UK");
    assertEquals(1, tasks.size());
    long taskId = tasks.get(0).getId();
    Map<String, Object> content = ((InternalTaskService) engine.getTaskService()).getTaskContent(taskId);
    assertTrue(content.containsKey("personIn"));
    Object person = content.get("personIn");
    assertEquals(clazz.getName(), person.getClass().getName());
    engine.getTaskService().start(taskId, "salaboy");
    Map<String, Object> data = new HashMap<String, Object>();
    data.put("personOut", instance);
    engine.getTaskService().complete(taskId, "salaboy", data);
    processInstance = engine.getKieSession().getProcessInstance(processInstance.getId());
    assertNull(processInstance);
}
Also used : RuntimeEngine(org.kie.api.runtime.manager.RuntimeEngine) InternalRuntimeManager(org.kie.internal.runtime.manager.InternalRuntimeManager) HashMap(java.util.HashMap) DeployedUnit(org.jbpm.services.api.model.DeployedUnit) RuntimeManager(org.kie.api.runtime.manager.RuntimeManager) InternalRuntimeManager(org.kie.internal.runtime.manager.InternalRuntimeManager) ProcessDefinition(org.jbpm.services.api.model.ProcessDefinition) InternalTaskService(org.kie.internal.task.api.InternalTaskService) QueryContext(org.kie.api.runtime.query.QueryContext) KModuleDeploymentUnit(org.jbpm.kie.services.impl.KModuleDeploymentUnit) TaskSummary(org.kie.api.task.model.TaskSummary) ProcessInstance(org.kie.api.runtime.process.ProcessInstance) AbstractKieServicesBaseTest(org.jbpm.kie.test.util.AbstractKieServicesBaseTest) Test(org.junit.Test)

Example 73 with RuntimeManager

use of org.kie.api.runtime.manager.RuntimeManager in project jbpm by kiegroup.

the class GlobalQuartzDBTimerServiceTest method testAbortGlobalTestService.

/**
 * Test that illustrates that jobs are persisted and survives server restart
 * and as soon as GlobalTimerService is active jobs are fired and it loads and aborts the
 * process instance to illustrate jobs are properly removed when isntance is aborted
 * NOTE: this test is disabled by default as it requires real db (not in memory)
 * and test to be executed separately each with new jvm process
 */
@Test
@Ignore
public void testAbortGlobalTestService() throws Exception {
    RuntimeEnvironment environment = RuntimeEnvironmentBuilder.Factory.get().newDefaultBuilder().entityManagerFactory(emf).addAsset(ResourceFactory.newClassPathResource("org/jbpm/test/functional/timer/IntermediateCatchEventTimerCycle3.bpmn2"), ResourceType.BPMN2).addConfiguration("drools.timerService", "org.jbpm.process.core.timer.impl.RegisteredTimerServiceDelegate").get();
    RuntimeManager manger = RuntimeManagerFactory.Factory.get().newSingletonRuntimeManager(environment);
    // build GlobalTimerService instance
    TimerService globalTs = new GlobalTimerService(manger, globalScheduler);
    // and register it in the registry under 'default' key
    TimerServiceRegistry.getInstance().registerTimerService("default", globalTs);
    // prepare listener to assert results
    final List<Long> timerExporations = new ArrayList<Long>();
    ProcessEventListener listener = new DefaultProcessEventListener() {

        @Override
        public void afterNodeLeft(ProcessNodeLeftEvent event) {
            if (event.getNodeInstance().getNodeName().equals("timer")) {
                timerExporations.add(event.getProcessInstance().getId());
            }
        }
    };
    long id = -1;
    Thread.sleep(5000);
    RuntimeEngine runtime = manger.getRuntimeEngine(ProcessInstanceIdContext.get());
    KieSession ksession = runtime.getKieSession();
    ksession.addEventListener(listener);
    ksession.abortProcessInstance(id);
    ProcessInstance processInstance = ksession.getProcessInstance(id);
    assertNull(processInstance);
    // let's wait to ensure no more timers are expired and triggered
    Thread.sleep(3000);
    ksession.dispose();
}
Also used : RuntimeEngine(org.kie.api.runtime.manager.RuntimeEngine) RuntimeEnvironment(org.kie.api.runtime.manager.RuntimeEnvironment) ProcessEventListener(org.kie.api.event.process.ProcessEventListener) DefaultProcessEventListener(org.kie.api.event.process.DefaultProcessEventListener) NodeLeftCountDownProcessEventListener(org.jbpm.test.listener.NodeLeftCountDownProcessEventListener) RuntimeManager(org.kie.api.runtime.manager.RuntimeManager) AbstractRuntimeManager(org.jbpm.runtime.manager.impl.AbstractRuntimeManager) ArrayList(java.util.ArrayList) GlobalTimerService(org.jbpm.process.core.timer.impl.GlobalTimerService) TimerService(org.drools.core.time.TimerService) DefaultProcessEventListener(org.kie.api.event.process.DefaultProcessEventListener) KieSession(org.kie.api.runtime.KieSession) ProcessInstance(org.kie.api.runtime.process.ProcessInstance) ProcessNodeLeftEvent(org.kie.api.event.process.ProcessNodeLeftEvent) GlobalTimerService(org.jbpm.process.core.timer.impl.GlobalTimerService) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 74 with RuntimeManager

use of org.kie.api.runtime.manager.RuntimeManager in project jbpm by kiegroup.

the class ServiceTaskHandler method executeWorkItem.

public void executeWorkItem(WorkItem workItem, final WorkItemManager manager) {
    String implementation = (String) workItem.getParameter("implementation");
    if ("##WebService".equalsIgnoreCase(implementation)) {
        // since JaxWsDynamicClientFactory will change the TCCL we need to restore it after creating client
        ClassLoader origClassloader = Thread.currentThread().getContextClassLoader();
        String interfaceRef = (String) workItem.getParameter("interfaceImplementationRef");
        String operationRef = (String) workItem.getParameter("operationImplementationRef");
        Object parameter = workItem.getParameter("Parameter");
        WSMode mode = WSMode.valueOf(workItem.getParameter("mode") == null ? "SYNC" : ((String) workItem.getParameter("mode")).toUpperCase());
        try {
            Client client = getWSClient(workItem, interfaceRef);
            if (client == null) {
                throw new IllegalStateException("Unable to create client for web service " + interfaceRef + " - " + operationRef);
            }
            switch(mode) {
                case SYNC:
                    Object[] result = client.invoke(operationRef, parameter);
                    Map<String, Object> output = new HashMap<String, Object>();
                    if (result == null || result.length == 0) {
                        output.put("Result", null);
                    } else {
                        output.put("Result", result[0]);
                    }
                    manager.completeWorkItem(workItem.getId(), output);
                    break;
                case ASYNC:
                    final ClientCallback callback = new ClientCallback();
                    final long workItemId = workItem.getId();
                    final String deploymentId = nonNull(((WorkItemImpl) workItem).getDeploymentId());
                    final long processInstanceId = workItem.getProcessInstanceId();
                    client.invoke(callback, operationRef, parameter);
                    new Thread(new Runnable() {

                        public void run() {
                            try {
                                Object[] result = callback.get(asyncTimeout, TimeUnit.SECONDS);
                                Map<String, Object> output = new HashMap<String, Object>();
                                if (callback.isDone()) {
                                    if (result == null) {
                                        output.put("Result", null);
                                    } else {
                                        output.put("Result", result[0]);
                                    }
                                }
                                RuntimeManager manager = RuntimeManagerRegistry.get().getManager(deploymentId);
                                if (manager != null) {
                                    RuntimeEngine engine = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId));
                                    engine.getKieSession().getWorkItemManager().completeWorkItem(workItemId, output);
                                    manager.disposeRuntimeEngine(engine);
                                } else {
                                    // in case there is no RuntimeManager available use available ksession,
                                    // as it might be used without runtime manager at all
                                    ksession.getWorkItemManager().completeWorkItem(workItemId, output);
                                }
                            } catch (Exception e) {
                                logger.error("Error encountered while invoking ws operation asynchronously ", e);
                            }
                        }
                    }).start();
                    break;
                case ONEWAY:
                    ClientCallback callbackFF = new ClientCallback();
                    client.invoke(callbackFF, operationRef, parameter);
                    manager.completeWorkItem(workItem.getId(), new HashMap<String, Object>());
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            handleException(e, interfaceRef, "", operationRef, parameter.getClass().getName(), parameter);
        } finally {
            Thread.currentThread().setContextClassLoader(origClassloader);
        }
    } else {
        executeJavaWorkItem(workItem, manager);
    }
}
Also used : ClientCallback(org.apache.cxf.endpoint.ClientCallback) RuntimeEngine(org.kie.api.runtime.manager.RuntimeEngine) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) RuntimeManager(org.kie.api.runtime.manager.RuntimeManager) InvocationTargetException(java.lang.reflect.InvocationTargetException) Client(org.apache.cxf.endpoint.Client)

Example 75 with RuntimeManager

use of org.kie.api.runtime.manager.RuntimeManager in project jbpm by kiegroup.

the class JBPMHelper method loadStatefulKnowledgeSession.

@Deprecated
public static StatefulKnowledgeSession loadStatefulKnowledgeSession(KieBase kbase, int sessionId) {
    Properties properties = getProperties();
    String persistenceEnabled = properties.getProperty("persistence.enabled", "false");
    RuntimeEnvironmentBuilder builder = null;
    if ("true".equals(persistenceEnabled)) {
        String dialect = properties.getProperty("persistence.persistenceunit.dialect", "org.hibernate.dialect.H2Dialect");
        Map<String, String> map = new HashMap<String, String>();
        map.put("hibernate.dialect", dialect);
        EntityManagerFactory emf = Persistence.createEntityManagerFactory(properties.getProperty("persistence.persistenceunit.name", "org.jbpm.persistence.jpa"), map);
        builder = RuntimeEnvironmentBuilder.Factory.get().newDefaultBuilder().entityManagerFactory(emf).addEnvironmentEntry(EnvironmentName.TRANSACTION_MANAGER, com.arjuna.ats.jta.TransactionManager.transactionManager());
    } else {
        builder = RuntimeEnvironmentBuilder.Factory.get().newDefaultInMemoryBuilder();
    }
    builder.knowledgeBase(kbase);
    RuntimeManager manager = RuntimeManagerFactory.Factory.get().newSingletonRuntimeManager(builder.get());
    return (StatefulKnowledgeSession) manager.getRuntimeEngine(EmptyContext.get()).getKieSession();
}
Also used : HashMap(java.util.HashMap) EntityManagerFactory(javax.persistence.EntityManagerFactory) StatefulKnowledgeSession(org.kie.internal.runtime.StatefulKnowledgeSession) RuntimeManager(org.kie.api.runtime.manager.RuntimeManager) Properties(java.util.Properties) RuntimeEnvironmentBuilder(org.kie.api.runtime.manager.RuntimeEnvironmentBuilder)

Aggregations

RuntimeManager (org.kie.api.runtime.manager.RuntimeManager)150 RuntimeEngine (org.kie.api.runtime.manager.RuntimeEngine)116 InternalRuntimeManager (org.kie.internal.runtime.manager.InternalRuntimeManager)79 KieSession (org.kie.api.runtime.KieSession)55 TaskService (org.kie.api.task.TaskService)53 Test (org.junit.Test)51 HashMap (java.util.HashMap)49 ProcessInstance (org.kie.api.runtime.process.ProcessInstance)46 InternalTaskService (org.kie.internal.task.api.InternalTaskService)44 DeployedUnit (org.jbpm.services.api.model.DeployedUnit)38 UserTaskService (org.jbpm.services.api.UserTaskService)36 UserTaskInstanceDesc (org.jbpm.services.api.model.UserTaskInstanceDesc)35 AbstractKieServicesBaseTest (org.jbpm.kie.test.util.AbstractKieServicesBaseTest)23 TaskSummary (org.kie.api.task.model.TaskSummary)21 ArrayList (java.util.ArrayList)19 KModuleDeploymentUnit (org.jbpm.kie.services.impl.KModuleDeploymentUnit)19 DeploymentNotFoundException (org.jbpm.services.api.DeploymentNotFoundException)18 TaskNotFoundException (org.jbpm.services.api.TaskNotFoundException)15 DeploymentUnit (org.jbpm.services.api.model.DeploymentUnit)15 PermissionDeniedException (org.jbpm.services.task.exception.PermissionDeniedException)15