Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 2015 JBoss Inc
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * 
   *      http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
 */
 
 package org.kie.remote.services.cdi;
 
 import static org.kie.remote.services.cdi.DeploymentInfoBean.*;
 import static org.kie.services.client.serialization.jaxb.impl.JaxbRequestStatus.FAILURE;
 import static org.kie.services.client.serialization.jaxb.impl.JaxbRequestStatus.PERMISSIONS_CONFLICT;
 import static org.kie.services.shared.ServicesVersion.VERSION;
 
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
 import  javax.enterprise.context.ApplicationScoped;
 import  javax.inject.Inject;
 import  javax.persistence.EntityManagerFactory;
 import  javax.persistence.PersistenceUnit;
 
 import  org.drools.core.command.runtime.SetGlobalCommand;
 import  org.drools.core.command.runtime.process.CompleteWorkItemCommand;
 import  org.drools.core.command.runtime.process.SignalEventCommand;
 import  org.drools.core.command.runtime.process.StartCorrelatedProcessCommand;
 import  org.drools.core.command.runtime.process.StartProcessCommand;
 import  org.drools.core.command.runtime.rule.InsertObjectCommand;
 import  org.drools.core.command.runtime.rule.UpdateCommand;
 import  org.jbpm.process.audit.AuditLogService;
 import  org.jbpm.process.audit.JPAAuditLogService;
 import  org.jbpm.process.audit.command.AuditCommand;
 import  org.jbpm.services.api.ProcessInstanceNotFoundException;
 import  org.jbpm.services.api.ProcessService;
 import  org.jbpm.services.api.TaskNotFoundException;
 import  org.jbpm.services.api.UserTaskService;
 import  org.jbpm.services.task.commands.AddTaskCommand;
 import  org.jbpm.services.task.commands.CompleteTaskCommand;
 import  org.jbpm.services.task.commands.FailTaskCommand;
 import  org.jbpm.services.task.commands.GetContentCommand;
 import  org.jbpm.services.task.commands.GetTaskCommand;
 import  org.jbpm.services.task.commands.GetTaskContentCommand;
 import  org.jbpm.services.task.commands.SkipTaskCommand;
 import  org.jbpm.services.task.commands.TaskCommand;
 import  org.jbpm.services.task.exception.PermissionDeniedException;
 import  org.kie.api.command.Command;
 import  org.kie.api.runtime.KieSession;
 import  org.kie.api.runtime.manager.RuntimeManager;
 import  org.kie.api.task.TaskService;
 import  org.kie.api.task.model.Task;
 import  org.slf4j.Logger;
 import  org.slf4j.LoggerFactory;
This class is used by both the RuntimeResourceImpl and TaskResourceImpl to do the core operations on the Deployment/Runtime's KieSession and TaskService. It contains the necessary logic to do the following:
  • Retrieve the KieSession or TaskService
  • Execute the submitted command
 
 @ApplicationScoped
 public class ProcessRequestBean {
 
     private static final Logger logger = LoggerFactory.getLogger(ProcessRequestBean.class);
     
     /* KIE processing */
 
     @Inject
     private ProcessService processService;
 
     @Inject
     private UserTaskService userTaskService;

    
AuditLogService
 
     private static final String PERSISTENCE_UNIT_NAME = "org.jbpm.domain";
    
    @PersistenceUnit(unitName = )
    private EntityManagerFactory emf;
   
    private AuditLogService auditLogService;
  
    // Injection methods for tests
    public void setProcessService(ProcessService processService) {
        this. = processService;
    }
    public void setUserTaskService(UserTaskService userTaskService) {
        this. = userTaskService;
    }
    public void setAuditLogService(AuditLogService auditLogService) {
        this. = auditLogService;
    }
    // Audit Log Service logic 
    
    public void initAuditLogService() { 
         = new JPAAuditLogService();
        if == null ) { 
            ((JPAAuditLogService) ).setPersistenceUnitName();
        }
    }
    
    public AuditLogService getAuditLogService() { 
        return ;
    }
    
    // Methods used
    
    public void processCommand(Command cmdJaxbCommandsRequest requestint iJaxbCommandsResponse jaxbResponse) { 
        String version = request.getVersion();
        ifversion == null ) { 
            version = "pre-6.0.3";
        }
        if( ! version.equals(VERSION) ) { 
            .warn( "Request received from client version [{}] while server is version [{}]! THIS MAY CAUSE PROBLEMS!"version, VERSION);
        }
        jaxbResponse.setVersion(VERSION);
        
        String cmdName = cmd.getClass().getSimpleName();
        .debug("Processing command " + cmdName);
        String errMsg = "Unable to execute " + cmdName + "/" + i;
        
        Object cmdResult = null;
        try {
            // check that all parameters have been correctly deserialized/unmarshalled
            preprocessCommand(cmd);
            
            ifcmd instanceof TaskCommand<?> ) { 
                TaskCommand<?> taskCmd = (TaskCommand<?>) cmd;
                cmdResult = doTaskOperation(
                        taskCmd.getTaskId(), 
                        request.getDeploymentId(), 
                        request.getProcessInstanceId(), 
                        null
                        taskCmd);
            } else ifcmd instanceof AuditCommand<?>) { 
                AuditCommand<?> auditCmd = ((AuditCommand<?>) cmd);
                auditCmd.setAuditLogService(getAuditLogService());
                cmdResult = auditCmd.execute(null);
            } else {
                cmdResult = doKieSessionOperation(
                        cmd
                        request.getDeploymentId(), 
                        request.getProcessInstanceId());
            }
        } catch (PermissionDeniedException pde) {
            .warn(errMsgpde);
            jaxbResponse.addException(pdeicmd, PERMISSIONS_CONFLICT);
        } catch (Exception e) {
            .warn(errMsge);
            jaxbResponse.addException(eicmd, FAILURE);
        } 
        if (cmdResult != null) {
            try {
                // addResult could possibly throw an exception, which is why it's here and not above
                jaxbResponse.addResult(cmdResulticmd);
            } catch (Exception e) {
                errMsg = "Unable to add result from " + cmdName + "/" + i;
                .error(errMsge);
                jaxbResponse.addException(eicmd, FAILURE);
            }
        }
    }
   
    void preprocessCommand(Command cmd) { 
       if..contains(cmd.getClass()) ) { 
           ifcmd instanceof CompleteWorkItemCommand ) {
               checkThatUserDefinedClassesWereUnmarshalled(((CompleteWorkItemCommand) cmd).getResults());
           } else ifcmd instanceof SignalEventCommand ) {
               checkThatUserDefinedClassesWereUnmarshalled(((SignalEventCommand) cmd).getEvent());
           } else ifcmd instanceof StartCorrelatedProcessCommand ) {
               checkThatUserDefinedClassesWereUnmarshalled(((StartCorrelatedProcessCommand) cmd).getData());
               checkThatUserDefinedClassesWereUnmarshalled(((StartCorrelatedProcessCommand) cmd).getParameters());
           } else ifcmd instanceof StartProcessCommand ) {
               checkThatUserDefinedClassesWereUnmarshalled(((StartProcessCommand) cmd).getData());
               checkThatUserDefinedClassesWereUnmarshalled(((StartProcessCommand) cmd).getParameters());
           } else ifcmd instanceof SetGlobalCommand ) {
               checkThatUserDefinedClassesWereUnmarshalled(((SetGlobalCommand) cmd).getObject());
           } else ifcmd instanceof InsertObjectCommand ) {
               checkThatUserDefinedClassesWereUnmarshalled(((InsertObjectCommand) cmd).getObject());
           } else ifcmd instanceof UpdateCommand ) {
               checkThatUserDefinedClassesWereUnmarshalled(((UpdateCommand) cmd).getObject());
           } else ifcmd instanceof AddTaskCommand ) {
               checkThatUserDefinedClassesWereUnmarshalled(((AddTaskCommand) cmd).getParams());
           } else ifcmd instanceof CompleteTaskCommand ) {
               checkThatUserDefinedClassesWereUnmarshalled(((CompleteTaskCommand) cmd).getData());
           } else ifcmd instanceof FailTaskCommand ) {
               checkThatUserDefinedClassesWereUnmarshalled(((FailTaskCommand) cmd).getData());
           }  
       }
    }
    
       ifobj != null ) { 
          ifobj instanceof List ) { 
             forObject listElem : (Listobj ) { 
                 verifyObjectHasBeenUnmarshalled(listElem);
             }
          } else ifobj instanceof Map ) { 
              forObject mapVal : ((Mapobj).values() ) { 
                 verifyObjectHasBeenUnmarshalled(mapVal);
              }
          } else { 
              verifyObjectHasBeenUnmarshalled(obj);
          }
       }
    }
   
    private void verifyObjectHasBeenUnmarshalled(Object obj) { 
        ifElement.class.isAssignableFrom(obj.getClass()) ) { 
            String typeName = ((Elementobj).getAttribute("xsi:type");
            throw new KieRemoteServicesDeploymentException("Could not unmarshall user-defined class instance parameter of type '" + typeName + "'");
        }
    }
    
    
Executes a command on the KieSession from the proper RuntimeManager. This method ends up synchronizing around the retrieved KieSession in order to avoid race-conditions.

Parameters:
cmd The command to be executed.
deploymentId The id of the runtime.
processInstanceId The process instance id, if available.
Returns:
The result of the Command.
    public <T> T doKieSessionOperation(Command<T> cmdString deploymentIdLong processInstanceId) {
        ifemptyDeploymentId(deploymentId) ) {
            throw new DeploymentNotFoundException("No deployment id supplied! Could not retrieve runtime to execute " + cmd.getClass().getSimpleName());
        }
        try {
            T result = .execute(deploymentIdcmd);
            return result;
        } catch (ProcessInstanceNotFoundException e) {
            throw KieRemoteRestOperationException.notFound("Process instance " + processInstanceId + " could not be found!");
        } catch (org.jbpm.services.api.DeploymentNotFoundException e) {
            throw KieRemoteRestOperationException.notFound(e.getMessage());
        }  catch (RuntimeException re) {
            throw KieRemoteRestOperationException.internalServerError(re.getMessage(), re);
        }
    }

   
    
Returns the actual variable instance from the runtime (as opposed to retrieving the string value of the variable via the history/audit operations.

Parameters:
deploymentId The id of the runtime
processInstanceId The process instance id (required)
varName The name of the variable
Returns:
The variable object instance.
    public Object getVariableObjectInstanceFromRuntime(String deploymentIdlong processInstanceIdString varName) { 
        try {
            Object procVar = .getProcessInstanceVariable(processInstanceIdvarName);
            return procVar;
        } catch (ProcessInstanceNotFoundException e) {
            throw KieRemoteRestOperationException.notFound("Process instance " + processInstanceId + " could not be found!");
        } catch (org.jbpm.services.api.DeploymentNotFoundException e) {
            throw KieRemoteRestOperationException.notFound(e.getMessage());
        }  catch (RuntimeException re) {
            throw KieRemoteRestOperationException.internalServerError(re.getMessage(), re);
        }
    }
    // task operations ------------------------------------------------------------------------------------------------------------
    private static Set<Class<? extends TaskCommand>> taskDeploymentIdCommands = new HashSet<Class<? extends TaskCommand>>();
    static {
        .add(CompleteTaskCommand.class);
        .add(FailTaskCommand.class);
        .add(SkipTaskCommand.class);
    }
    
    
There are 3 possibilities here:
  1. This is an operation that should be done on a deployment if possible, but it's an independent task.
  2. This is an operation that should be done on a deployment, and a deployment/runtime is available.
  3. This is an operation that does not modify the KieSession and should be done via the injected TaskService.

Parameters:
taskId
deploymentId
processInstanceId
cmd
onDeployment
errorMsg
Returns:
    private <T> T doTaskOperation(Long taskIdString deploymentIdLong processInstanceId, Task task, TaskCommand<T> cmd) { 
        // take care of serialization
        ifcmd instanceof GetTaskCommand 
                || cmd instanceof GetContentCommand 
                || cmd instanceof GetTaskContentCommand ) { 
           cmd = new ExecuteAndSerializeCommand(cmd); 
        }
        ifemptyDeploymentId(deploymentId) && .contains(cmd.getClass()) ) {
            deploymentId = getDeploymentId(task,taskIdcmd);
        }
        try {
            return .execute(deploymentIdcmd);
        } catch (TaskNotFoundException e) {
            throw KieRemoteRestOperationException.notFound("Task " + taskId + " could not be found!");
        } catch (ProcessInstanceNotFoundException e) {
            throw KieRemoteRestOperationException.notFound("Process instance " + processInstanceId + " could not be found!");
        } catch (org.jbpm.services.api.DeploymentNotFoundException e) {
            throw KieRemoteRestOperationException.notFound(e.getMessage());
        }  catch (RuntimeException re) {
            throw KieRemoteRestOperationException.internalServerError(re.getMessage(), re);
        }
    }
    public <T> T doRestTaskOperation(Long taskIdString deploymentIdLong processInstanceId, Task task, TaskCommand<T> cmd) {
        try { 
            return doTaskOperation(taskIddeploymentIdprocessInstanceIdtaskcmd);
        } catch (PermissionDeniedException pde) {
            throw KieRemoteRestOperationException.conflict(pde.getMessage(), pde);
        } 
    }
    private String getDeploymentId(Task taskLong taskId, TaskCommand cmd) {
        iftask == null ) {
            iftaskId == null ) {
                taskId = cmd.getTaskId();
            }
            task = .getTask(taskId);
        }
        String deploymentId = null;
        iftask != null && task.getTaskData() != null ) { 
            deploymentId = task.getTaskData().getDeploymentId();
        }
        return deploymentId;
    }
New to GrepCode? Check out our FAQ X