JBoss Community

Re: New process instance created but no task insert in db

created by Sandra Renaud in jBPM - View the full discussion

Hello Demian,


Thank you for your answer. Sur I will give my code. I use the localTaskService.


This is the producer for knowledgeSession :



public class KnowledgeSessionProducer implements Serializable{
          private static final long serialVersionUID = -4494168896880405667L;
          private Logger log = LoggerFactory.getLogger(KnowledgeSessionProducer.class);
          private KnowledgeRuntimeLogger logger;
          private StatefulKnowledgeSession ksession;
    @PersistenceUnit(unitName = "org.jbpm.task")
    private EntityManagerFactory emf;
    private @Inject RecoveryDao recoveryDao;
    public @PostConstruct void init(){
              log.debug("init of KnowledgeSessionProducer ...");
              // By Setting the jbpm.usergroup.callback property with the call
        // back class full name, task service will use this to validate the
        // user/group exists and its permissions are ok.
              InputStream usergroupsin = KnowledgeSessionProducer.class.getResourceAsStream(  "/jbpm.usergroup.callback.properties" );
              if(usergroupsin != null) {
                        Properties callbackproperties = new Properties();
                        try {
                                  log.debug("Task service registered usergroup callback ...");
                        } catch (Exception e) {
                                  log.debug("Task service unable to register usergroup callback ...");
                        System.out.println("userGroupCallBack exists ! :)");
                        System.out.println("userGroupCallBack don't exist ! :(");
              TaskService taskService = new TaskService(emf, SystemEventListenerFactory.getSystemEventListener());
              taskService.setUserinfo(new AMSUserInfoImpl());
        TaskServiceSession taskSession = taskService.createSession();
        // Add users
                    Map vars = new HashMap();
        InputStream usersin = KnowledgeSessionProducer.class.getResourceAsStream( "/LoadUsers.mvel" );
        if(usersin != null) {
                  Reader reader = new InputStreamReader( usersin );   
                  Map<String, User> users = ( Map<String, User> ) TaskService.eval( reader, vars );   
                  log.debug("Users to load in db : ...");
                  for ( User user : users.values() ) {
                            taskSession.addUser( user );
                            log.debug(" - "+user);
        InputStream groupsin = KnowledgeSessionProducer.class.getResourceAsStream( "/LoadGroups.mvel" );
        if(groupsin != null) {
                  Reader reader = new InputStreamReader( groupsin );   
                  Map<String, Group> groups = ( Map<String, Group> ) TaskService.eval( reader, vars );     
                  log.debug("Groups to load in db : ...");
                  for ( Group group : groups.values() ) {
                            taskSession.addGroup( group );
                            log.debug(" - "+group);
        log.debug("Task service started correctly!");
        log.debug("Task service running ...");
          public StatefulKnowledgeSession produceKnowledgeSession(){
                    log.debug("produce the KnowledgeSession ...");
                    //Create the knowledgeBase
                    /*This factory is used to build the knowledge base resources that are held collectively in KnowledgePackages.*/
                    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
                    //Add all processes to the knowledgeBuilder
                    List<Resource> resources = getProcessDefinitionList();
                    for (Resource resource : resources) {
                              kbuilder.add(resource, ResourceType.BPMN2);
                    /*Create a new KnowledgeBase from the knowledge packages that have been added to this builder. 
                     * An exception is thrown if there are any errors.*/
//                    assertFalse( kbuilder.hasErrors() );
                    if ( kbuilder.hasErrors() ) {
                         log.error( kbuilder.getErrors().toString() );
                    KnowledgeBase kbase = kbuilder.newKnowledgeBase();
                    Environment env = KnowledgeBaseFactory.newEnvironment();
                    env.set( EnvironmentName.ENTITY_MANAGER_FACTORY, emf );
                    if(kbase != null){
                              System.out.println("knowledge base NOT null");
                              for(org.drools.definition.process.Process p :kbase.getProcesses()){
                                        System.out.println(" - process "+p.getName()+" ["+p.getId()+"]");
                     * recover a persistent knowledge session or instanciate a new one
                    int sessionId = recoveryDao.getPersistentKnowledgeSession();
                    if(sessionId < 0){
                              ksession = JPAKnowledgeService.newStatefulKnowledgeSession(kbase, null, env);
                              KnowledgeSessionRecovery kSessionRecovery = new KnowledgeSessionRecovery(ksession.getId());
                              ksession = JPAKnowledgeService.loadStatefulKnowledgeSession(sessionId, kbase, null, env);
                    /*Create a new StatefulKnowledgeSession using the default session configuration. 
                     * Don't forget to dispose() session when you are done.
                     * Long term out of the box persistence of runtime state with JPA is possible with Drools & jBPM.
                     * StatefulKnowledgeSession is the most common way to interact with the engine. 
                     * A StatefulKnowledgeSession allows the application to establish an iterative conversation with the engine, 
                     * where the state of the session is kept across invocations.*/
//                    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
                    System.out.println(" !!!! DEBUG SESSION PERSISTENCE : new session with id : "+ksession.getId()+" !!!!");
        logger = KnowledgeRuntimeLoggerFactory.newThreadedFileLogger(ksession, "loggerFile", 1000);
        /*A work item manager is responsible for finding the right work item handler when a work item should be executed 
         * and should be notified when this work item has been completed (or aborted).
         * Register the given handler for all work items of the given type of work 
         * This part is done in the LocalHumanTaskService*/
        WorkItemHandler wihHT = new HumanTaskHandler();
        ksession.getWorkItemManager().registerWorkItemHandler("Human Task", wihHT );
//        ksession.getEnvironment().set(EnvironmentName.ENTITY_MANAGER_FACTORY, emf);
         * Register WorkItem Handler for Email
//        EmailWorkItemHandler emailHandler =  new EmailWorkItemHandler();
//        ksession.getWorkItemManager().registerWorkItemHandler("Email", emailHandler);
        return ksession;
          public KnowledgeRuntimeLogger getLogger(){
                    return this.logger;
          public void end(){
                    log.debug("ksession disposed");
          private List<Resource> getProcessDefinitionList(){
                    List<Resource> resourceList = new ArrayList<>();
                     * TODO 
                     * add all other process here
                    return resourceList;


and here the method in a class where I put all functions to interact with the engine :


           * Start a new processInstance of an existing Process
           * and set the variables of this instance
           * @param processId, map of variables
           * @return ProcessInstance created
          public ProcessInstance startProcess(String processId, Map<String, Object> parameters){
                    ProcessInstance p = kSession.startProcess(processId,parameters);
                    return p;
           * Return the WorkflowProcessInstance associated to a Task
           * This instance allow to access the map of variables
           * @return WorkflowProcessInstance managed
          public WorkflowProcessInstance getWorkflowProcessInstance(long processInstanceId){
                    return (WorkflowProcessInstance)kSession.getProcessInstance(processInstanceId);
           * This method allow to access object store in
           * process instance variables
           * @return an object link to the processInstance
          public Object getProcessVariable(final Long processInstanceId, Long taskId, String key){
                    Object retObj = null;
                    WorkflowProcessInstance wpi = (WorkflowProcessInstance)kSession.getProcessInstance(processInstanceId);
                    if((wpi == null) || (wpi.getVariable(key) == null)){
                              System.out.println("workflow process instance is null :-(");
                              Map<String, Object> variables = kSession.execute(new GenericCommand<Map<String, Object>>() {
                                  public Map<String, Object> execute(Context context) {
                                      StatefulKnowledgeSession ksession = ((KnowledgeCommandContext) context).getStatefulKnowledgesession();
                                      org.jbpm.process.instance.ProcessInstance processInstance = (org.jbpm.process.instance.ProcessInstance) ksession.getProcessInstance(processInstanceId);
                                      VariableScopeInstance variableScope = (VariableScopeInstance) processInstance.getContextInstance(VariableScope.VARIABLE_SCOPE);
                                      Map<String, Object> variables = variableScope.getVariables();
                                      return variables;
                              System.out.println("variables size : "+variables.size());
                              for(String str : variables.keySet()){
                                        System.out.println(" - "+str);
                              retObj = variables.get(key);
                              System.out.println("workflow process instance is NOT null :-)");
                              retObj = wpi.getVariable(key);
                    if(retObj == null){
                              System.out.println(" get variable return null ::-(");
                              System.out.println(" get variable return "+retObj.toString()+"  |-)");
                    return retObj;


Thanks again.

Reply to this message by going to Community

Start a new discussion in jBPM at Community