Search in sources :

Example 11 with ExecutionResults

use of org.kie.api.executor.ExecutionResults 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 12 with ExecutionResults

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

the class BasicExecutorIntegrationTest method multipleCallbackTest.

@Test
public void multipleCallbackTest() throws InterruptedException {
    CommandContext commandContext = new CommandContext();
    commandContext.setData("businessKey", UUID.randomUUID().toString());
    cachedEntities.put((String) commandContext.getData("businessKey"), new AtomicLong(1));
    commandContext.setData("callbacks", "org.jbpm.executor.ejb.impl.test.SimpleIncrementCallback, org.jbpm.executor.ejb.impl.test.CustomCallback");
    executorService.scheduleRequest("org.jbpm.executor.commands.PrintOutCommand", commandContext);
    Thread.sleep(10000);
    List<RequestInfo> inErrorRequests = executorService.getInErrorRequests(new QueryContext());
    assertEquals(0, inErrorRequests.size());
    List<RequestInfo> queuedRequests = executorService.getQueuedRequests(new QueryContext());
    assertEquals(0, queuedRequests.size());
    List<RequestInfo> executedRequests = executorService.getCompletedRequests(new QueryContext());
    assertEquals(1, executedRequests.size());
    assertEquals(2, ((AtomicLong) cachedEntities.get((String) commandContext.getData("businessKey"))).longValue());
    ExecutionResults results = null;
    byte[] responseData = executedRequests.get(0).getResponseData();
    ObjectInputStream in = null;
    try {
        in = new ObjectInputStream(new ByteArrayInputStream(responseData));
        results = (ExecutionResults) in.readObject();
    } catch (Exception e) {
        logger.warn("Exception while serializing context data", e);
        return;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    String result = (String) results.getData("custom");
    assertNotNull(result);
    assertEquals("custom callback invoked", result);
}
Also used : AtomicLong(java.util.concurrent.atomic.AtomicLong) CommandContext(org.kie.api.executor.CommandContext) ByteArrayInputStream(java.io.ByteArrayInputStream) ExecutionResults(org.kie.api.executor.ExecutionResults) QueryContext(org.kie.api.runtime.query.QueryContext) IOException(java.io.IOException) RequestInfo(org.kie.api.executor.RequestInfo) IOException(java.io.IOException) ObjectInputStream(java.io.ObjectInputStream) Test(org.junit.Test)

Example 13 with ExecutionResults

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

the class UserCommand method execute.

public ExecutionResults execute(CommandContext ctx) {
    System.out.println("[INFO] Command executed on executor with " + ctx.getData());
    WorkItem workItem = (WorkItem) ctx.getData("workItem");
    User user = (User) workItem.getParameter("UserIn");
    user.setName(user.getName() + " after command execution");
    ExecutionResults executionResults = new ExecutionResults();
    executionResults.setData("UserOut", user);
    double item = 0;
    for (int i = 0; i < 99; i++) {
        System.out.println("[INFO] User item:" + item);
        item++;
    }
    return executionResults;
}
Also used : ExecutionResults(org.kie.api.executor.ExecutionResults) WorkItem(org.kie.api.runtime.process.WorkItem)

Example 14 with ExecutionResults

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

the class AsyncStartProcessCommand method execute.

@SuppressWarnings("unchecked")
@Override
public ExecutionResults execute(CommandContext ctx) throws Exception {
    String deploymentId = getDeploymentId(ctx);
    String processId = (String) getData("ProcessId", ctx);
    String correlationKey = (String) getData("CorrelationKey", ctx);
    Map<String, Object> variables = (Map<String, Object>) getData("Variables", ctx);
    if (deploymentId == null || processId == null) {
        throw new IllegalArgumentException("Deployment id and process id 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());
    try {
        if (correlationKey == null || correlationKey.isEmpty()) {
            engine.getKieSession().startProcess(processId, variables);
        } else {
            String[] correlationKeyProperties = correlationKey.split(",");
            CorrelationKey ck = correlationKeyFactory.newCorrelationKey(Arrays.asList(correlationKeyProperties));
            ((CorrelationAwareProcessRuntime) engine.getKieSession()).startProcess(processId, ck, variables);
        }
        return new ExecutionResults();
    } finally {
        runtimeManager.disposeRuntimeEngine(engine);
    }
}
Also used : RuntimeEngine(org.kie.api.runtime.manager.RuntimeEngine) CorrelationAwareProcessRuntime(org.kie.internal.process.CorrelationAwareProcessRuntime) CorrelationKey(org.kie.internal.process.CorrelationKey) ExecutionResults(org.kie.api.executor.ExecutionResults) RuntimeManager(org.kie.api.runtime.manager.RuntimeManager) Map(java.util.Map)

Example 15 with ExecutionResults

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

the class SLATrackingCommand method execute.

@Override
public ExecutionResults execute(CommandContext ctx) throws Exception {
    ExecutionResults executionResults = new ExecutionResults();
    String emfName = (String) ctx.getData("EmfName");
    if (emfName == null) {
        emfName = "org.jbpm.domain";
    }
    String singleRun = (String) ctx.getData("SingleRun");
    if ("true".equalsIgnoreCase(singleRun)) {
        // disable rescheduling
        this.nextScheduleTimeAdd = -1;
    }
    String nextRun = (String) ctx.getData("NextRun");
    if (nextRun != null) {
        nextScheduleTimeAdd = DateTimeUtils.parseDateAsDuration(nextRun);
    }
    // get hold of persistence and create instance of audit service
    EntityManagerFactory emf = EntityManagerFactoryManager.get().getOrCreate(emfName);
    // collect parameters
    String forDeployment = (String) ctx.getData("ForDeployment");
    // SLA Violations on nodes
    Map<String, Object> parameters = new HashMap<>();
    parameters.put("now", new Date());
    StringBuilder lookupQuery = new StringBuilder();
    lookupQuery.append("select log from NodeInstanceLog log where ");
    lookupQuery.append("log.nodeInstanceId in ( select nil.nodeInstanceId from NodeInstanceLog nil where nil.slaDueDate < :now and nil.slaCompliance = 1 ");
    lookupQuery.append("GROUP BY nil.nodeInstanceId ");
    lookupQuery.append("HAVING sum(nil.type) = 0) ");
    lookupQuery.append("and log.type = 0 ");
    if (forDeployment != null && !forDeployment.isEmpty()) {
        lookupQuery.append(" and log.externalId = :forDeployment");
        parameters.put("forDeployment", forDeployment);
    }
    TransactionalCommandService commandService = new TransactionalCommandService(emf);
    List<NodeInstanceLog> nodeInstancesViolations = commandService.execute(new QueryStringCommand<List<NodeInstanceLog>>(lookupQuery.toString(), parameters));
    logger.debug("Number of node instances with violated SLA {}", nodeInstancesViolations.size());
    if (!nodeInstancesViolations.isEmpty()) {
        logger.debug("Signaling process instances that have SLA violations on nodes");
        int nodeSignals = 0;
        for (NodeInstanceLog niLog : nodeInstancesViolations) {
            RuntimeManager runtimeManager = RuntimeManagerRegistry.get().getManager(niLog.getExternalId());
            if (runtimeManager == null) {
                logger.debug("No runtime manager found for {}, not able to send SLA violation signal", niLog.getExternalId());
                continue;
            }
            RuntimeEngine engine = runtimeManager.getRuntimeEngine(ProcessInstanceIdContext.get(niLog.getProcessInstanceId()));
            try {
                engine.getKieSession().signalEvent("slaViolation:" + niLog.getNodeInstanceId(), null, niLog.getProcessInstanceId());
                nodeSignals++;
            } catch (Exception e) {
                logger.warn("Unexpected error when signalig process instance {} about SLA violation {}", niLog.getProcessInstanceId(), e.getMessage(), e);
            } finally {
                runtimeManager.disposeRuntimeEngine(engine);
            }
        }
        logger.info("SLA Violations JOB :: Number of nodes successfully signaled is {}", nodeSignals);
        executionResults.setData("NodeSLASignals", nodeSignals);
    }
    // SLA Violations on process instances
    parameters = new HashMap<>();
    parameters.put("now", new Date());
    lookupQuery = new StringBuilder();
    lookupQuery.append("select log from ProcessInstanceLog log where log.slaDueDate < :now and log.slaCompliance = 1 ");
    if (forDeployment != null && !forDeployment.isEmpty()) {
        lookupQuery.append(" and log.externalId = :forDeployment");
        parameters.put("forDeployment", forDeployment);
    }
    List<ProcessInstanceLog> processInstancesViolations = commandService.execute(new QueryStringCommand<List<ProcessInstanceLog>>(lookupQuery.toString(), parameters));
    logger.debug("Number of node instances with violated SLA {}", nodeInstancesViolations.size());
    if (!processInstancesViolations.isEmpty()) {
        logger.debug("Signaling process instances that have SLA violations");
        int processSignals = 0;
        for (ProcessInstanceLog piLog : processInstancesViolations) {
            RuntimeManager runtimeManager = RuntimeManagerRegistry.get().getManager(piLog.getExternalId());
            if (runtimeManager == null) {
                logger.debug("No runtime manager found for {}, not able to send SLA violation signal", piLog.getExternalId());
                continue;
            }
            RuntimeEngine engine = runtimeManager.getRuntimeEngine(ProcessInstanceIdContext.get(piLog.getProcessInstanceId()));
            try {
                engine.getKieSession().signalEvent("slaViolation", null, piLog.getProcessInstanceId());
                processSignals++;
            } catch (Exception e) {
                logger.warn("Unexpected error when signalig process instance {} about SLA violation {}", piLog.getProcessInstanceId(), e.getMessage(), e);
            } finally {
                runtimeManager.disposeRuntimeEngine(engine);
            }
        }
        logger.info("SLA Violations JOB :: Number of process instances successfully signaled is {}", processSignals);
        executionResults.setData("ProcessSLASignals", processSignals);
    }
    return executionResults;
}
Also used : RuntimeEngine(org.kie.api.runtime.manager.RuntimeEngine) NodeInstanceLog(org.jbpm.process.audit.NodeInstanceLog) HashMap(java.util.HashMap) ExecutionResults(org.kie.api.executor.ExecutionResults) RuntimeManager(org.kie.api.runtime.manager.RuntimeManager) Date(java.util.Date) EntityManagerFactory(javax.persistence.EntityManagerFactory) TransactionalCommandService(org.jbpm.shared.services.impl.TransactionalCommandService) List(java.util.List) ProcessInstanceLog(org.jbpm.process.audit.ProcessInstanceLog)

Aggregations

ExecutionResults (org.kie.api.executor.ExecutionResults)23 Date (java.util.Date)5 EntityManagerFactory (javax.persistence.EntityManagerFactory)4 Test (org.junit.Test)4 WorkItem (org.kie.api.runtime.process.WorkItem)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 IOException (java.io.IOException)3 ObjectInputStream (java.io.ObjectInputStream)3 HashMap (java.util.HashMap)3 CommandContext (org.kie.api.executor.CommandContext)3 RuntimeEngine (org.kie.api.runtime.manager.RuntimeEngine)3 RuntimeManager (org.kie.api.runtime.manager.RuntimeManager)3 QueryContext (org.kie.api.runtime.query.QueryContext)3 SimpleDateFormat (java.text.SimpleDateFormat)2 Map (java.util.Map)2 AtomicLong (java.util.concurrent.atomic.AtomicLong)2 BeanManager (javax.enterprise.inject.spi.BeanManager)2 WorkItemImpl (org.drools.core.process.instance.impl.WorkItemImpl)2 TransactionalCommandService (org.jbpm.shared.services.impl.TransactionalCommandService)2 ExecutorService (org.kie.api.executor.ExecutorService)2