Search in sources :

Example 1 with ExecutionResults

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

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

the class AsyncCloseCaseCommand method execute.

@Override
public ExecutionResults execute(CommandContext ctx) throws Exception {
    String caseId = (String) ((WorkItem) ctx.getData("workItem")).getParameter("CaseId");
    CaseService caseService = (CaseService) ServiceRegistry.get().service(ServiceRegistry.CASE_SERVICE);
    caseService.closeCase(caseId, "Closing case from async command");
    return new ExecutionResults();
}
Also used : ExecutionResults(org.kie.api.executor.ExecutionResults) CaseService(org.jbpm.casemgmt.api.CaseService)

Example 3 with ExecutionResults

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

the class WebServiceCommand method execute.

@Override
public ExecutionResults execute(CommandContext ctx) throws Exception {
    // since JaxWsDynamicClientFactory will change the TCCL we need to restore it after creating client
    ClassLoader origClassloader = Thread.currentThread().getContextClassLoader();
    try {
        Object[] parameters = null;
        WorkItem workItem = (WorkItem) ctx.getData("workItem");
        String interfaceRef = (String) workItem.getParameter("Interface");
        String operationRef = (String) workItem.getParameter("Operation");
        String endpointAddress = (String) workItem.getParameter("Endpoint");
        String username = (String) workItem.getParameter("Username");
        String password = (String) workItem.getParameter("Password");
        if (workItem.getParameter("Parameter") instanceof Object[]) {
            parameters = (Object[]) workItem.getParameter("Parameter");
        } else if (workItem.getParameter("Parameter") != null && workItem.getParameter("Parameter").getClass().isArray()) {
            int length = Array.getLength(workItem.getParameter("Parameter"));
            parameters = new Object[length];
            for (int i = 0; i < length; i++) {
                parameters[i] = Array.get(workItem.getParameter("Parameter"), i);
            }
        } else {
            parameters = new Object[] { workItem.getParameter("Parameter") };
        }
        Client client = getWSClient(workItem, interfaceRef, ctx);
        // Override endpoint address if configured.
        if (endpointAddress != null && !"".equals(endpointAddress)) {
            client.getRequestContext().put(Message.ENDPOINT_ADDRESS, endpointAddress);
        }
        // apply authorization if needed
        applyAuthorization(username, password, client);
        Object[] result = client.invoke(operationRef, parameters);
        ExecutionResults results = new ExecutionResults();
        if (result == null || result.length == 0) {
            results.setData("Result", null);
        } else {
            results.setData("Result", result[0]);
        }
        logger.debug("Received sync response {}", result);
        return results;
    } finally {
        Thread.currentThread().setContextClassLoader(origClassloader);
    }
}
Also used : ExecutionResults(org.kie.api.executor.ExecutionResults) Client(org.apache.cxf.endpoint.Client) WorkItem(org.kie.api.runtime.process.WorkItem)

Example 4 with ExecutionResults

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

the class WebServiceCommandTest method testExecuteCommand.

@Test
public void testExecuteCommand() throws Exception {
    Object[] clientObject = Arrays.asList("testResults").toArray();
    when(clients.containsKey(anyObject())).thenReturn(true);
    when(clients.get(anyObject())).thenReturn(client);
    when(client.invoke(anyString(), any(Object[].class))).thenReturn(clientObject);
    WorkItemImpl workItem = new WorkItemImpl();
    workItem.setParameter("Interface", "someInterface");
    workItem.setParameter("Operation", "someOperation");
    when(commandContext.getData(anyString())).thenReturn(workItem);
    WebServiceCommand command = new WebServiceCommand();
    command.setClients(clients);
    ExecutionResults results = command.execute(commandContext);
    assertNotNull(results);
    assertEquals("testResults", results.getData("Result"));
}
Also used : ExecutionResults(org.kie.api.executor.ExecutionResults) WorkItemImpl(org.drools.core.process.instance.impl.WorkItemImpl) Test(org.junit.Test)

Example 5 with ExecutionResults

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

the class CDIPrintOutCommand method execute.

public ExecutionResults execute(CommandContext ctx) {
    BeanManager manager = CDIUtils.lookUpBeanManager(ctx);
    String clazz = (String) getParameter(ctx, "CDIBeanClassName");
    if (StringUtils.isEmpty(clazz)) {
        clazz = ExecutorService.class.getName();
    }
    try {
        Object cdiBean = CDIUtils.createBean(Class.forName(clazz), manager);
        logger.info("CDI bean created {}", cdiBean);
    } 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) ExecutorService(org.kie.api.executor.ExecutorService) BeanManager(javax.enterprise.inject.spi.BeanManager)

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