Search in sources :

Example 6 with CommandContext

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

the class AbstractAvailableJobsExecutor method executeGivenJob.

public void executeGivenJob(RequestInfo request) {
    Throwable exception = null;
    try {
        AsyncExecutionMarker.markAsync();
        eventSupport.fireBeforeJobExecuted(request, null);
        if (request != null) {
            boolean processReoccurring = false;
            Command cmd = null;
            CommandContext ctx = null;
            ExecutionResults results = null;
            List<CommandCallback> callbacks = null;
            ClassLoader cl = getClassLoader(request.getDeploymentId());
            try {
                logger.debug("Processing Request Id: {}, status {} command {}", request.getId(), request.getStatus(), request.getCommandName());
                byte[] reqData = request.getRequestData();
                if (reqData != null) {
                    ObjectInputStream in = null;
                    try {
                        in = new ClassLoaderObjectInputStream(cl, new ByteArrayInputStream(reqData));
                        ctx = (CommandContext) in.readObject();
                    } catch (IOException e) {
                        logger.warn("Exception while serializing context data", e);
                        return;
                    } finally {
                        if (in != null) {
                            in.close();
                        }
                    }
                }
                if (request.getResponseData() == null) {
                    for (Map.Entry<String, Object> entry : contextData.entrySet()) {
                        ctx.setData(entry.getKey(), entry.getValue());
                    }
                    // add class loader so internally classes can be created with valid (kjar) deployment
                    ctx.setData("ClassLoader", cl);
                    cmd = classCacheManager.findCommand(request.getCommandName(), cl);
                    // increment execution counter directly to cover both success and failure paths
                    request.setExecutions(request.getExecutions() + 1);
                    results = cmd.execute(ctx);
                    if (results == null) {
                        results = new ExecutionResults();
                    }
                    try {
                        ByteArrayOutputStream bout = new ByteArrayOutputStream();
                        ObjectOutputStream out = new ObjectOutputStream(bout);
                        out.writeObject(results);
                        byte[] respData = bout.toByteArray();
                        request.setResponseData(respData);
                    } catch (IOException e) {
                        request.setResponseData(null);
                    }
                    results.setData("CompletedAt", new Date());
                    request.setStatus(STATUS.DONE);
                    executorStoreService.updateRequest(request, null);
                    processReoccurring = true;
                } else {
                    logger.debug("Job was already successfully executed, retrying callbacks only...");
                    byte[] resData = request.getResponseData();
                    if (resData != null) {
                        ObjectInputStream in = null;
                        try {
                            in = new ClassLoaderObjectInputStream(cl, new ByteArrayInputStream(resData));
                            results = (ExecutionResults) in.readObject();
                        } catch (IOException e) {
                            logger.warn("Exception while serializing response data", e);
                            return;
                        } finally {
                            if (in != null) {
                                in.close();
                            }
                        }
                    }
                    request.setStatus(STATUS.DONE);
                    executorStoreService.updateRequest(request, null);
                    processReoccurring = true;
                }
                // callback handling after job execution
                callbacks = classCacheManager.buildCommandCallback(ctx, cl);
                for (CommandCallback handler : callbacks) {
                    handler.onCommandDone(ctx, results);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } catch (Throwable e) {
                exception = e;
                if (callbacks == null) {
                    callbacks = classCacheManager.buildCommandCallback(ctx, cl);
                }
                processReoccurring = handleException(request, e, ctx, callbacks);
            } finally {
                ((ExecutorImpl) executor).clearExecution(request.getId());
                AsyncExecutionMarker.reset();
                handleCompletion(processReoccurring, cmd, ctx);
                eventSupport.fireAfterJobExecuted(request, exception);
            }
        }
    } catch (Exception e) {
        logger.warn("Unexpected error while processin executor's job {}", e.getMessage(), e);
    }
}
Also used : CommandContext(org.kie.api.executor.CommandContext) ExecutionResults(org.kie.api.executor.ExecutionResults) ClassLoaderObjectInputStream(org.apache.commons.io.input.ClassLoaderObjectInputStream) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ObjectOutputStream(java.io.ObjectOutputStream) Date(java.util.Date) IOException(java.io.IOException) AsyncJobException(org.jbpm.executor.AsyncJobException) Command(org.kie.api.executor.Command) ByteArrayInputStream(java.io.ByteArrayInputStream) CommandCallback(org.kie.api.executor.CommandCallback) HashMap(java.util.HashMap) Map(java.util.Map) ObjectInputStream(java.io.ObjectInputStream) ClassLoaderObjectInputStream(org.apache.commons.io.input.ClassLoaderObjectInputStream)

Example 7 with CommandContext

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

the class BasicExecutorBaseTest method cancelRequestWithSearchByCommandTest.

@Test(timeout = 10000)
public void cancelRequestWithSearchByCommandTest() throws InterruptedException {
    CommandContext ctxCMD = new CommandContext();
    String businessKey = UUID.randomUUID().toString();
    ctxCMD.setData("businessKey", businessKey);
    Date futureDate = new Date(System.currentTimeMillis() + EXTRA_TIME);
    Long requestId = executorService.scheduleRequest("org.jbpm.executor.test.CustomCommand", futureDate, ctxCMD);
    List<RequestInfo> requests = executorService.getRequestsByCommand("org.jbpm.executor.test.CustomCommand", new QueryContext());
    assertNotNull(requests);
    assertEquals(1, requests.size());
    assertEquals(requestId, requests.get(0).getId());
    // cancel the task immediately
    executorService.cancelRequest(requestId);
    List<RequestInfo> cancelledRequests = executorService.getCancelledRequests(new QueryContext());
    assertEquals(1, cancelledRequests.size());
}
Also used : CommandContext(org.kie.api.executor.CommandContext) AtomicLong(java.util.concurrent.atomic.AtomicLong) QueryContext(org.kie.api.runtime.query.QueryContext) RequestInfo(org.kie.api.executor.RequestInfo) Date(java.util.Date) Test(org.junit.Test)

Example 8 with CommandContext

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

the class BasicExecutorBaseTest method defaultRequestRetryTest.

@Test(timeout = 10000)
public void defaultRequestRetryTest() throws InterruptedException {
    CountDownAsyncJobListener countDownListener = configureListener(4);
    CommandContext ctxCMD = new CommandContext();
    ctxCMD.setData("businessKey", UUID.randomUUID().toString());
    executorService.scheduleRequest("org.jbpm.executor.ThrowExceptionCommand", ctxCMD);
    countDownListener.waitTillCompleted();
    List<RequestInfo> inErrorRequests = executorService.getInErrorRequests(new QueryContext());
    assertEquals(1, inErrorRequests.size());
    RequestInfo failedJob = inErrorRequests.get(0);
    assertEquals(4, failedJob.getExecutions());
    List<ErrorInfo> errors = executorService.getAllErrors(new QueryContext());
    logger.info("Errors: {}", errors);
    // Three retries means 4 executions in total 1(regular) + 3(retries)
    assertEquals(4, errors.size());
}
Also used : CountDownAsyncJobListener(org.jbpm.executor.test.CountDownAsyncJobListener) CommandContext(org.kie.api.executor.CommandContext) ErrorInfo(org.kie.api.executor.ErrorInfo) QueryContext(org.kie.api.runtime.query.QueryContext) RequestInfo(org.kie.api.executor.RequestInfo) Test(org.junit.Test)

Example 9 with CommandContext

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

the class BasicExecutorBaseTest method cleanupLogExecutionTest.

@Test(timeout = 10000)
public void cleanupLogExecutionTest() throws InterruptedException {
    CountDownAsyncJobListener countDownListener = configureListener(3);
    CommandContext ctxCMD = new CommandContext();
    ctxCMD.setData("businessKey", UUID.randomUUID().toString());
    Long requestId = executorService.scheduleRequest("org.jbpm.executor.commands.ReoccurringPrintOutCommand", ctxCMD);
    countDownListener.waitTillCompleted();
    List<RequestInfo> inErrorRequests = executorService.getInErrorRequests(new QueryContext());
    assertEquals(0, inErrorRequests.size());
    List<RequestInfo> queuedRequests = executorService.getQueuedRequests(new QueryContext());
    assertEquals(1, queuedRequests.size());
    List<RequestInfo> executedRequests = executorService.getCompletedRequests(new QueryContext());
    assertEquals(3, executedRequests.size());
    executorService.cancelRequest(requestId + 3);
    List<RequestInfo> canceled = executorService.getCancelledRequests(new QueryContext());
    ExecutorJPAAuditService auditService = new ExecutorJPAAuditService(emf);
    int resultCount = auditService.requestInfoLogDeleteBuilder().date(canceled.get(0).getTime()).status(STATUS.ERROR).build().execute();
    assertEquals(0, resultCount);
    resultCount = auditService.errorInfoLogDeleteBuilder().date(canceled.get(0).getTime()).build().execute();
    assertEquals(0, resultCount);
    ctxCMD = new CommandContext();
    ctxCMD.setData("businessKey", UUID.randomUUID().toString());
    ctxCMD.setData("SingleRun", "true");
    ctxCMD.setData("EmfName", "org.jbpm.executor");
    ctxCMD.setData("SkipProcessLog", "true");
    ctxCMD.setData("SkipTaskLog", "true");
    executorService.scheduleRequest("org.jbpm.executor.commands.LogCleanupCommand", ctxCMD);
    countDownListener.reset(1);
    countDownListener.waitTillCompleted();
    inErrorRequests = executorService.getInErrorRequests(new QueryContext());
    assertEquals(0, inErrorRequests.size());
    queuedRequests = executorService.getQueuedRequests(new QueryContext());
    assertEquals(0, queuedRequests.size());
    executedRequests = executorService.getCompletedRequests(new QueryContext());
    assertEquals(1, executedRequests.size());
}
Also used : CountDownAsyncJobListener(org.jbpm.executor.test.CountDownAsyncJobListener) CommandContext(org.kie.api.executor.CommandContext) AtomicLong(java.util.concurrent.atomic.AtomicLong) QueryContext(org.kie.api.runtime.query.QueryContext) ExecutorJPAAuditService(org.jbpm.executor.impl.jpa.ExecutorJPAAuditService) RequestInfo(org.kie.api.executor.RequestInfo) Test(org.junit.Test)

Example 10 with CommandContext

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

the class BasicExecutorBaseTest method clearAllRequestsTest.

@Test(timeout = 10000)
public void clearAllRequestsTest() throws InterruptedException {
    CommandContext ctxCMD = new CommandContext();
    String businessKey = UUID.randomUUID().toString();
    ctxCMD.setData("businessKey", businessKey);
    Date futureDate = new Date(System.currentTimeMillis() + EXTRA_TIME);
    // Testing clearing of active request.
    Long requestId = executorService.scheduleRequest("org.jbpm.executor.test.CustomCommand", futureDate, ctxCMD);
    List<RequestInfo> allRequests = executorService.getAllRequests(new QueryContext());
    assertEquals(1, allRequests.size());
    executorService.clearAllRequests();
    allRequests = executorService.getAllRequests(new QueryContext());
    assertEquals(0, allRequests.size());
    // Testing clearing of cancelled request.
    requestId = executorService.scheduleRequest("org.jbpm.executor.test.CustomCommand", futureDate, ctxCMD);
    allRequests = executorService.getAllRequests(new QueryContext());
    assertEquals(1, allRequests.size());
    executorService.cancelRequest(requestId);
    executorService.clearAllRequests();
    allRequests = executorService.getAllRequests(new QueryContext());
    assertEquals(0, allRequests.size());
}
Also used : CommandContext(org.kie.api.executor.CommandContext) AtomicLong(java.util.concurrent.atomic.AtomicLong) QueryContext(org.kie.api.runtime.query.QueryContext) RequestInfo(org.kie.api.executor.RequestInfo) Date(java.util.Date) Test(org.junit.Test)

Aggregations

CommandContext (org.kie.api.executor.CommandContext)52 Test (org.junit.Test)43 RequestInfo (org.kie.api.executor.RequestInfo)39 QueryContext (org.kie.api.runtime.query.QueryContext)39 CountDownAsyncJobListener (org.jbpm.executor.test.CountDownAsyncJobListener)25 AtomicLong (java.util.concurrent.atomic.AtomicLong)22 Date (java.util.Date)10 ErrorInfo (org.kie.api.executor.ErrorInfo)9 KieSession (org.kie.api.runtime.KieSession)6 HashMap (java.util.HashMap)5 RuntimeManager (org.kie.api.runtime.manager.RuntimeManager)5 ProcessInstance (org.kie.api.runtime.process.ProcessInstance)5 ByteArrayInputStream (java.io.ByteArrayInputStream)4 IOException (java.io.IOException)4 ObjectInputStream (java.io.ObjectInputStream)4 ExecutorServiceImpl (org.jbpm.executor.impl.ExecutorServiceImpl)4 AsyncSignalEventCommand (org.jbpm.process.core.async.AsyncSignalEventCommand)4 AbstractRuntimeManager (org.jbpm.runtime.manager.impl.AbstractRuntimeManager)4 RuntimeEngine (org.kie.api.runtime.manager.RuntimeEngine)4 UserTransaction (javax.transaction.UserTransaction)3