public void testUseSuperStateTransitionLogs() {
    ProcessDefinition processDefinition =
        ProcessDefinition.parseXmlString(
            "<process-definition>"
                + "  <start-state>"
                + "    <transition to='superstate/state' />"
                + "  </start-state>"
                + "  <super-state name='superstate'>"
                + "    <state name='state'/>"
                + "    <transition to='end' />"
                + "  </super-state>"
                + "  <end-state name='end' />"
                + "</process-definition>");

    // start a process instance
    ProcessInstance processInstance = new ProcessInstance(processDefinition);
    Token token = processInstance.getRootToken();
    processInstance.signal();
    processInstance.signal();

    // check the transition log (from the start state to the state)
    LoggingInstance loggingInstance = processInstance.getLoggingInstance();
    List transitionLogs = loggingInstance.getLogs(TransitionLog.class);
    assertEquals(2, transitionLogs.size());
    TransitionLog transitionLog = (TransitionLog) transitionLogs.get(1);
    assertSame(token, transitionLog.getToken());
    assertNotNull(transitionLog.getDate());
    assertSame(processDefinition.findNode("superstate/state"), transitionLog.getSourceNode());
    assertSame(processDefinition.getNode("end"), transitionLog.getDestinationNode());
  }
Пример #2
0
  /** Find Task Instances */
  @SuppressWarnings("rawtypes")
  public static List<TaskInstance> findTaskInstances(long processInstanceId)
      throws WorkflowException {
    log.debug("findTaskInstances({})", processInstanceId);
    JbpmContext jbpmContext = JBPMUtils.getConfig().createJbpmContext();
    ArrayList<TaskInstance> al = new ArrayList<TaskInstance>();

    try {
      GraphSession graphSession = jbpmContext.getGraphSession();
      org.jbpm.graph.exe.ProcessInstance pi = graphSession.getProcessInstance(processInstanceId);
      TaskMgmtInstance taskMgmtInstance = pi.getTaskMgmtInstance();

      if (taskMgmtInstance.getTaskInstances() != null) {
        for (Iterator it = taskMgmtInstance.getTaskInstances().iterator(); it.hasNext(); ) {
          org.jbpm.taskmgmt.exe.TaskInstance ti = (org.jbpm.taskmgmt.exe.TaskInstance) it.next();
          al.add(WorkflowUtils.copy(ti));
        }
      }

      // Sort
      Collections.sort(al);
    } catch (JbpmException e) {
      throw new WorkflowException(e.getMessage(), e);
    } finally {
      jbpmContext.close();
    }

    log.debug("findTaskInstances: {}", al);
    return al;
  }
 public void testNoRootTokenCreateLog() {
   // the root token logs are replaced by the process instance logs
   ProcessDefinition processDefinition = new ProcessDefinition();
   ProcessInstance processInstance = new ProcessInstance(processDefinition);
   LoggingInstance loggingInstance = processInstance.getLoggingInstance();
   assertEquals(0, loggingInstance.getLogs(TokenCreateLog.class).size());
 }
Пример #4
0
  /** Send Process Instance Signal */
  public static ProcessInstance sendProcessInstanceSignal(
      long processInstanceId, String transitionName) throws WorkflowException {
    log.debug(
        "sendProcessInstanceSignal({}, {})", new Object[] {processInstanceId, transitionName});
    JbpmContext jbpmContext = JBPMUtils.getConfig().createJbpmContext();
    ProcessInstance vo = new ProcessInstance();

    try {
      GraphSession graphSession = jbpmContext.getGraphSession();
      org.jbpm.graph.exe.ProcessInstance pi = graphSession.getProcessInstance(processInstanceId);
      org.jbpm.graph.exe.Token t = pi.getRootToken();

      if (transitionName != null && !transitionName.equals("")) {
        t.signal(transitionName);
      } else {
        t.signal();
      }

      jbpmContext.getSession().flush();
      vo = WorkflowUtils.copy(pi);
    } catch (JbpmException e) {
      throw new WorkflowException(e.getMessage(), e);
    } finally {
      jbpmContext.close();
    }

    log.debug("sendProcessInstanceSignal: {}", vo);
    return vo;
  }
Пример #5
0
  public void testSuperStateLeavingTransition() {
    ProcessInstance processInstance = jbpmContext.newProcessInstance("jbpm2818");
    processInstance.signal();
    assertEquals("state1", processInstance.getRootToken().getNode().getName());

    processInstance = saveAndReload(processInstance);
    processInstance.signal();
    assertTrue("expected " + processInstance + " to have ended", processInstance.hasEnded());
  }
  public void testAprioriRuntimeKnowledgeScenario1() {
    scenario = 1;

    ProcessInstance processInstance = new ProcessInstance(processDefinition);
    Token token = processInstance.getRootToken();
    processInstance.signal();
    processInstance.signal();
    assertSame(c, token.getNode());
  }
 public void testProcessInstanceCreateLog() {
   ProcessDefinition processDefinition = new ProcessDefinition();
   ProcessInstance processInstance = new ProcessInstance(processDefinition);
   LoggingInstance loggingInstance = processInstance.getLoggingInstance();
   List processInstanceCreateLogs = loggingInstance.getLogs(ProcessInstanceCreateLog.class);
   assertEquals(1, processInstanceCreateLogs.size());
   ProcessInstanceCreateLog processInstanceCreateLog =
       (ProcessInstanceCreateLog) processInstanceCreateLogs.get(0);
   assertSame(processInstance.getRootToken(), processInstanceCreateLog.getToken());
 }
Пример #8
0
  /** Start Process Definition */
  public static ProcessInstance runProcessDefinition(
      String user, long processDefinitionId, String uuid, List<FormElement> variables)
      throws WorkflowException {
    log.debug(
        "runProcessDefinition({}, {}, {}, {})",
        new Object[] {user, processDefinitionId, uuid, variables});
    JbpmContext jbpmContext = JBPMUtils.getConfig().createJbpmContext();
    ProcessInstance vo = new ProcessInstance();

    if (Config.SYSTEM_READONLY) {
      throw new WorkflowException("System is in read-only mode");
    }

    try {
      jbpmContext.setActorId(user);
      GraphSession graphSession = jbpmContext.getGraphSession();
      Map<String, Object> hm = new HashMap<String, Object>();
      hm.put(Config.WORKFLOW_PROCESS_INSTANCE_VARIABLE_UUID, uuid);

      for (FormElement fe : variables) {
        hm.put(fe.getName(), fe);
      }

      org.jbpm.graph.def.ProcessDefinition pd =
          graphSession.getProcessDefinition(processDefinitionId);
      org.jbpm.graph.exe.ProcessInstance pi = pd.createProcessInstance(hm);

      if (pi != null) {
        org.jbpm.taskmgmt.exe.TaskMgmtInstance tmi = pi.getTaskMgmtInstance();

        // http://community.jboss.org/thread/115182
        if (tmi.getTaskMgmtDefinition().getStartTask() != null) {
          org.jbpm.taskmgmt.exe.TaskInstance ti = tmi.createStartTaskInstance();

          if (Config.WORKFLOW_START_TASK_AUTO_RUN) {
            ti.start();
            ti.end();
          }
        } else {
          pi.getRootToken().signal();
        }

        jbpmContext.save(pi);
        vo = WorkflowUtils.copy(pi);
      }
    } catch (JbpmException e) {
      throw new WorkflowException(e.getMessage(), e);
    } finally {
      jbpmContext.close();
    }

    log.debug("runProcessDefinition: {}", vo);
    return vo;
  }
  @Test
  public void testJpdl() {
    ProcessInstance pi = processDef.createProcessInstance();

    TrackingActionListener listener = new TrackingActionListener();
    DefaultActionHandler.setTrackingListener(listener);
    DefaultActionHandler.setSignalization(true);
    pi.signal();

    JpdlAssert.assertProcessStarted(pi);
    listener.wasCalledOnNode("node");
    JpdlAssert.assertProcessCompleted(pi);
  }
Пример #10
0
  /** Resume Process Instance */
  public static void resumeProcessInstance(long processInstanceId) throws WorkflowException {
    log.debug("resumeProcessInstance({})", processInstanceId);
    JbpmContext jbpmContext = JBPMUtils.getConfig().createJbpmContext();

    try {
      org.jbpm.graph.exe.ProcessInstance pi = jbpmContext.getProcessInstance(processInstanceId);
      pi.resume();
      jbpmContext.getSession().flush();
    } catch (JbpmException e) {
      throw new WorkflowException(e.getMessage(), e);
    } finally {
      jbpmContext.close();
    }
  }
  public void testStringVariableQuery() {
    ProcessDefinition processDefinition =
        ProcessDefinition.parseXmlString(
            "<process-definition name='variables'>"
                + "  <start-state name='start'/>"
                + "</process-definition>");
    deployProcessDefinition(processDefinition);

    ProcessInstance one = jbpmContext.newProcessInstanceForUpdate("variables");
    one.getContextInstance().setVariable("category", "overpaid");
    one.getContextInstance().setVariable("duedate", "tomorrow");

    ProcessInstance two = jbpmContext.newProcessInstanceForUpdate("variables");
    two.getContextInstance().setVariable("category", "overpaid");
    two.getContextInstance().setVariable("duedate", "yesterday");

    ProcessInstance three = jbpmContext.newProcessInstanceForUpdate("variables");
    three.getContextInstance().setVariable("category", "underpaid");
    three.getContextInstance().setVariable("duedate", "today");

    newTransaction();

    Set expectedPids = new HashSet();
    expectedPids.add(new Long(one.getId()));
    expectedPids.add(new Long(two.getId()));

    Query query =
        session.createQuery(
            "select pi.id "
                + "from org.jbpm.context.exe.variableinstance.StringInstance si "
                + "join si.processInstance pi "
                + "where si.name = 'category'"
                + "  and si.value like 'overpaid'");
    Set retrievedPids = new HashSet(query.list());

    assertEquals(expectedPids, retrievedPids);

    newTransaction();

    expectedPids.clear();
    expectedPids.add(new Long(three.getId()));

    query =
        session.createQuery(
            "select pi.id "
                + "from org.jbpm.context.exe.variableinstance.StringInstance si "
                + "join si.processInstance pi "
                + "where si.name = 'category'"
                + "  and si.value like 'underpaid'");
    retrievedPids.clear();
    retrievedPids.addAll(query.list());

    assertEquals(expectedPids, retrievedPids);
  }
Пример #12
0
  /** Delete Process Instance */
  public static void deleteProcessInstanceVariable(long processInstanceId, String name)
      throws WorkflowException {
    log.debug("deleteProcessInstanceVariable({}, {})", new Object[] {processInstanceId, name});
    JbpmContext jbpmContext = JBPMUtils.getConfig().createJbpmContext();

    try {
      org.jbpm.graph.exe.ProcessInstance pi = jbpmContext.getProcessInstance(processInstanceId);
      pi.getContextInstance().deleteVariable(name);
      jbpmContext.getSession().flush();
    } catch (JbpmException e) {
      throw new WorkflowException(e.getMessage(), e);
    } finally {
      jbpmContext.close();
    }
  }
Пример #13
0
  protected List<TaskInstance> getTasksInstancesBySubmittingUser(
      long companyId,
      long userId,
      Boolean completed,
      int start,
      int end,
      OrderByComparator orderByComparator) {

    List<TaskInstance> taskInstances = new ArrayList<TaskInstance>();

    try {
      Criteria criteria = _session.createCriteria(TaskInstance.class);

      criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

      if (completed != null) {
        if (completed.booleanValue()) {
          criteria.add(Restrictions.isNotNull("end"));
        } else {
          criteria.add(Restrictions.isNull("end"));
        }
      }

      addOrder(criteria, orderByComparator);

      for (TaskInstance taskInstance : (List<TaskInstance>) criteria.list()) {

        ProcessInstance processInstance = taskInstance.getProcessInstance();

        ContextInstance contextInstance = processInstance.getContextInstance();

        long taskInstanceUserId =
            GetterUtil.getLong((String) contextInstance.getVariable("userId"));

        if (userId == taskInstanceUserId) {
          taskInstances.add(taskInstance);
        }
      }
    } catch (Exception e) {
      throw new JbpmException(e);
    }

    if ((end != QueryUtil.ALL_POS) && (taskInstances.size() > end)) {
      taskInstances = ListUtil.subList(taskInstances, start, end);
    }

    return taskInstances;
  }
 public void setUp() throws Exception {
   super.setUp();
   // create process instance
   ProcessInstance pi = process.createProcessInstance();
   // commit changes
   jbpmContext.save(pi);
   newTransaction();
   // reassociate the process instance with the new session
   jbpmContext.getSession().lock(pi, LockMode.READ);
   token = pi.getRootToken();
   token.setNode((Node) receiver.getInboundMessageActivity());
   // initiate correlation set
   CorrelationSetInstance csi =
       receiver.getCorrelations().getCorrelation("csId").getSet().getInstance(token);
   csi.initialize(Collections.singletonMap(ID_PROP, ID_VALUE));
 }
  public void testEnactReportWorkflow() {
    long processId = 5;
    StudyParticipantAssignment assignment = Fixtures.createAssignment();
    ExpeditedAdverseEventReport aeReport = Fixtures.createSavableExpeditedReport();
    Report report = Fixtures.createReport("testReport");
    aeReport.setId(55);
    AdverseEventReportingPeriod reportingPeriod = Fixtures.createReportingPeriod();
    WorkflowConfig workflowConfig = Fixtures.createWorkflowConfig("test");
    StudySite site = assignment.getStudySite();
    StudySiteWorkflowConfig ssWfCfg = new StudySiteWorkflowConfig("report", site, workflowConfig);
    site.addStudySiteWorkflowConfig(ssWfCfg);
    reportingPeriod.addAeReport(aeReport);
    aeReport.setAssignment(assignment);
    aeReport.addReport(report);

    Map<String, Object> variables = new HashMap<String, Object>();
    variables.put(WorkflowService.VAR_STUDY_ID, site.getStudy().getId());
    variables.put(WorkflowService.VAR_WF_TYPE, Report.class.getName());
    variables.put(WorkflowService.VAR_REPORT_ID, report.getId());
    variables.put(WorkflowService.VAR_EXPEDITED_REPORT_ID, aeReport.getId());
    variables.put(WorkflowService.VAR_WF_STUDY_NAME, reportingPeriod.getStudy().getDisplayName());
    variables.put(
        WorkflowService.VAR_WF_SUBJECT_NAME, reportingPeriod.getParticipant().getFullName());
    variables.put(WorkflowService.VAR_WF_COURSE_NAME, reportingPeriod.getName());

    EasyMock.expect(wfService.createProcessInstance("test", variables)).andReturn(processInstance);
    EasyMock.expect(processInstance.getId()).andReturn(processId).anyTimes();
    reportDao.save(report);
    replayMocks();
    impl.enactReportWorkflow(report);
    verifyMocks();
  }
 public void testFirstTermVariableUser() {
   expressionAssignmentHandler.expression = "variable(uservariable)";
   User john = identitySession.getUserByName("john");
   processInstance.getContextInstance().setVariable("uservariable", john);
   expressionAssignmentHandler.assign(assignable, executionContext);
   assertEquals("john", assignable.getActorId());
 }
  public void testEnactReportingPeriodWorkflow() {
    long processId = 5;
    StudyParticipantAssignment assignment = Fixtures.createAssignment();
    AdverseEventReportingPeriod reportingPeriod = Fixtures.createReportingPeriod();
    reportingPeriod.setId(44);
    WorkflowConfig workflowConfig = Fixtures.createWorkflowConfig("test");
    StudySite site = assignment.getStudySite();
    StudySiteWorkflowConfig ssWfCfg =
        new StudySiteWorkflowConfig("reportingPeriod", site, workflowConfig);
    site.addStudySiteWorkflowConfig(ssWfCfg);
    reportingPeriod.setAssignment(assignment);

    Map<String, Object> variables = new HashMap<String, Object>();
    variables.put(WorkflowService.VAR_STUDY_ID, site.getStudy().getId());
    variables.put(WorkflowService.VAR_WF_TYPE, AdverseEventReportingPeriod.class.getName());
    variables.put(WorkflowService.VAR_WF_STUDY_NAME, reportingPeriod.getStudy().getDisplayName());
    variables.put(
        WorkflowService.VAR_WF_SUBJECT_NAME, reportingPeriod.getParticipant().getFullName());
    variables.put(WorkflowService.VAR_WF_COURSE_NAME, reportingPeriod.getName());
    variables.put(WorkflowService.VAR_REPORTING_PERIOD_ID, reportingPeriod.getId());

    EasyMock.expect(wfService.createProcessInstance("test", variables)).andReturn(processInstance);
    EasyMock.expect(processInstance.getId()).andReturn(processId).anyTimes();
    rpDao.modifyOrSaveReviewStatusAndComments(reportingPeriod);
    replayMocks();
    impl.enactReportingPeriodWorkflow(reportingPeriod);
    verifyMocks();
  }
Пример #18
0
  public void deleteProcessInstance(
      ProcessInstance processInstance, boolean includeTasks, boolean includeJobs) {
    if (processInstance == null) {
      throw new IllegalArgumentException("processInstance cannot be null");
    }

    try {
      // delete outstanding jobs
      if (includeJobs) deleteJobs(processInstance);

      // delete logs
      deleteLogs(processInstance);

      // detach from superprocess token
      Token superProcessToken = processInstance.getSuperProcessToken();
      if (superProcessToken != null) detachFromSuperProcess(processInstance, superProcessToken);

      // delete subprocess instances
      deleteSubProcesses(processInstance);

      // delete tasks; since TaskLogs reference tasks, logs are deleted first
      if (includeTasks) deleteTasks(processInstance);

      // delete the process instance
      session.delete(processInstance);
    } catch (HibernateException e) {
      handle(e);
      throw new JbpmPersistenceException("could not delete " + processInstance, e);
    }
  }
 public void testFirstTermSwimlane() {
   expressionAssignmentHandler.expression = "swimlane(boss)";
   SwimlaneInstance swimlaneInstance = new SwimlaneInstance(new Swimlane("boss"));
   swimlaneInstance.setActorId("john");
   processInstance.getTaskMgmtInstance().addSwimlaneInstance(swimlaneInstance);
   expressionAssignmentHandler.assign(assignable, executionContext);
   assertEquals("john", assignable.getActorId());
 }
Пример #20
0
  public ActionForward insertPayment(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws AppException {
    String forwardPage = "";
    Inform inf = new Inform();

    Workflow workflow = (Workflow) form;

    JbpmContext jbpmContext = JbpmUtil.getJbpmContext();
    try {
      String issueperson = "user1";
      // 设置当前用户为user1
      jbpmContext.setActorId(issueperson);

      ProcessDefinition pd = jbpmContext.getGraphSession().findLatestProcessDefinition("payment");

      ProcessInstance processInstance = pd.createProcessInstance();
      ContextInstance contextInstance = processInstance.getContextInstance();

      //
      contextInstance.setVariable("issueperson", issueperson);

      // 创建开始节点的TaskInstance
      TaskInstance taskInstance = processInstance.getTaskMgmtInstance().createStartTaskInstance();

      // 向任务实例当中写入相关变量
      taskInstance.setVariable("title", workflow.getTitle());
      taskInstance.setVariable("moneyCount", workflow.getMoneyCount());
      taskInstance.setVariable("remark", workflow.getRemark());

      // 结束任务实例,token进入部门经理审批
      taskInstance.end();

      inf.setMessage("报销申请提交成功");
    } catch (Exception e) {
      e.printStackTrace();
      inf.setMessage("异常信息:" + e.getMessage());
    } finally {
      jbpmContext.close();
    }
    return forwardInformPage(inf, mapping, request);
  }
 public void testFirstTermVariableGroup() {
   expressionAssignmentHandler.expression = "variable(groupvariable)";
   Group hellsangels = identitySession.getGroupByName("hellsangels");
   processInstance.getContextInstance().setVariable("groupvariable", hellsangels);
   expressionAssignmentHandler.assign(assignable, executionContext);
   Set pooledActors = assignable.getPooledActors();
   PooledActor pooledActor = (PooledActor) pooledActors.iterator().next();
   assertEquals("hellsangels", pooledActor.getActorId());
 }
Пример #22
0
  public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof ModuleInstance)) return false;

    ModuleInstance other = (ModuleInstance) o;
    if (id != 0 && id == other.getId()) return true;

    return getClass().getName().equals(other.getClass().getName())
        && processInstance.equals(other.getProcessInstance());
  }
Пример #23
0
  public void testFindByActorIds() {
    ProcessDefinition processDefinition =
        ProcessDefinition.parseXmlString(
            "<?xml version='1.0'?>"
                + "<process-definition name='jbpm1921'>"
                + "  <start-state name='start'>"
                + "    <transition to='team work'/>"
                + "  </start-state>"
                + "  <task-node name='team work'>"
                + "    <task>"
                + "      <assignment pooled-actors='ernie,bert,groover' />"
                + "    </task>"
                + "  </task-node>"
                + "</process-definition>");
    deployProcessDefinition(processDefinition);

    ProcessInstance processInstance = jbpmContext.newProcessInstance(processDefinition.getName());
    processInstance.signal();
    List pooledTasks = jbpmContext.getGroupTaskList(Arrays.asList(new String[] {"ernie", "bert"}));
    assertEquals(1, pooledTasks.size());
  }
Пример #24
0
  public void testFindByActorId() {
    ProcessDefinition processDefinition =
        ProcessDefinition.parseXmlString(
            "<?xml version='1.0'?>"
                + "<process-definition name='jbpm1921'>"
                + "  <start-state name='start'>"
                + "    <transition to='team work'/>"
                + "  </start-state>"
                + "  <task-node name='team work'>"
                + "    <task>"
                + "      <assignment pooled-actors='ernie,bert,ernie' />"
                + "    </task>"
                + "  </task-node>"
                + "</process-definition>");
    deployProcessDefinition(processDefinition);

    ProcessInstance processInstance = jbpmContext.newProcessInstance(processDefinition.getName());
    processInstance.signal();
    List pooledTasks = taskMgmtSession.findPooledTaskInstances("ernie");
    assertEquals(1, pooledTasks.size());
  }
Пример #25
0
  public void testTimerWithSuperState() {
    ProcessDefinition processDefinition =
        ProcessDefinition.parseXmlString(
            "<process-definition name='jbpm2812'>"
                + "  <start-state name='start'>"
                + "    <transition to='super-state/state1'/>"
                + "  </start-state>"
                + "  <super-state name='super-state'>"
                + "    <state name='state1'>"
                + "      <timer duedate='1 second' name='timeout-timer' transition='timeout'/>"
                + "      <transition to='state2' name='go'/>"
                + "    </state>"
                + "    <state name='state2'>"
                + "  	 <transition to='end' name='go'/>"
                + "    </state>"
                + "    <transition to='timed-out-end' name='timeout'/>"
                + "  </super-state>"
                + "  <end-state name='timed-out-end'/>"
                + "  <end-state name='end'/>"
                + "</process-definition>");
    deployProcessDefinition(processDefinition);

    ProcessInstance processInstance = new ProcessInstance(processDefinition);
    processInstance.signal();
    assertEquals("state1", processInstance.getRootToken().getNode().getName());

    processJobs();
    processInstance = jbpmContext.loadProcessInstance(processInstance.getId());
    assertTrue("expected " + processInstance + " to have ended", processInstance.hasEnded());
    assertEquals("timed-out-end", processInstance.getRootToken().getNode().getName());
  }
 public Token startScenario() {
   ProcessDefinition pd = milestoneProcessDefinition;
   ProcessInstance pi = new ProcessInstance(pd);
   pi.signal();
   return pi.getRootToken();
 }
 public void testFindProcessInstance() {
   ProcessInstance pi = jbpmService.getProcessInstance(5L);
   System.out.println(pi.getId());
   assertEquals(5L, pi.getId());
 }
Пример #28
0
 public int hashCode() {
   int result = 1849786963 + getClass().getName().hashCode();
   result = 1566965963 * result + processInstance.hashCode();
   return result;
 }
  /**
   * extract the list of information from the process variables and make them available locally.
   * Note that if no task instance variables are specified, the full process variables scope will be
   * visible (that means that the user did not specify a special task instance scope).
   */
  public void initializeVariables(TaskInstance taskInstance) {
    ClassLoader surroundingClassLoader = Thread.currentThread().getContextClassLoader();
    try {
      // set context class loader correctly for delegation class
      // (https://jira.jboss.org/jira/browse/JBPM-1448)
      Thread.currentThread()
          .setContextClassLoader(
              JbpmConfiguration.getProcessClassLoader(
                  taskInstance.getTask().getProcessDefinition()));

      if (taskControllerDelegation != null) {
        TaskControllerHandler taskControllerHandler =
            (TaskControllerHandler) taskControllerDelegation.instantiate();
        ProcessInstance processInstance = taskInstance.getTaskMgmtInstance().getProcessInstance();
        ContextInstance contextInstance =
            (processInstance != null ? processInstance.getContextInstance() : null);
        Token token = taskInstance.getToken();

        if (UserCodeInterceptorConfig.userCodeInterceptor != null) {
          UserCodeInterceptorConfig.userCodeInterceptor.executeTaskControllerInitialization(
              taskControllerHandler, taskInstance, contextInstance, token);
        } else {
          taskControllerHandler.initializeTaskVariables(taskInstance, contextInstance, token);
        }

      } else {
        Token token = taskInstance.getToken();
        ProcessInstance processInstance = token.getProcessInstance();
        ContextInstance contextInstance = processInstance.getContextInstance();

        if (variableAccesses != null) {
          Iterator iter = variableAccesses.iterator();
          while (iter.hasNext()) {
            VariableAccess variableAccess = (VariableAccess) iter.next();
            String mappedName = variableAccess.getMappedName();
            if (variableAccess.isReadable()) {
              String variableName = variableAccess.getVariableName();
              Object value = contextInstance.getVariable(variableName, token);
              log.debug(
                  "creating task instance variable '"
                      + mappedName
                      + "' from process variable '"
                      + variableName
                      + "', value '"
                      + value
                      + "'");
              taskInstance.setVariableLocally(mappedName, value);
            } else {
              log.debug(
                  "creating task instance local variable '"
                      + mappedName
                      + "'. initializing with null value.");
              taskInstance.setVariableLocally(mappedName, null);
            }
          }
        }
      }
    } finally {
      Thread.currentThread().setContextClassLoader(surroundingClassLoader);
    }
  }
  /** update the process variables from the the task-instance variables. */
  public void submitParameters(TaskInstance taskInstance) {
    ClassLoader surroundingClassLoader = Thread.currentThread().getContextClassLoader();
    try {
      // set context class loader correctly for delegation class
      // (https://jira.jboss.org/jira/browse/JBPM-1448)
      Thread.currentThread()
          .setContextClassLoader(
              JbpmConfiguration.getProcessClassLoader(
                  taskInstance.getTask().getProcessDefinition()));

      if (taskControllerDelegation != null) {
        TaskControllerHandler taskControllerHandler =
            (TaskControllerHandler) taskControllerDelegation.instantiate();
        ProcessInstance processInstance = taskInstance.getTaskMgmtInstance().getProcessInstance();
        ContextInstance contextInstance =
            (processInstance != null ? processInstance.getContextInstance() : null);
        Token token = taskInstance.getToken();

        if (UserCodeInterceptorConfig.userCodeInterceptor != null) {
          UserCodeInterceptorConfig.userCodeInterceptor.executeTaskControllerSubmission(
              taskControllerHandler, taskInstance, contextInstance, token);
        } else {
          taskControllerHandler.submitTaskVariables(taskInstance, contextInstance, token);
        }

      } else {

        Token token = taskInstance.getToken();
        ProcessInstance processInstance = token.getProcessInstance();
        ContextInstance contextInstance = processInstance.getContextInstance();

        if (variableAccesses != null) {
          String missingTaskVariables = null;
          Iterator iter = variableAccesses.iterator();
          while (iter.hasNext()) {
            VariableAccess variableAccess = (VariableAccess) iter.next();
            String mappedName = variableAccess.getMappedName();
            // first check if the required variableInstances are present
            if ((variableAccess.isRequired()) && (!taskInstance.hasVariableLocally(mappedName))) {
              if (missingTaskVariables == null) {
                missingTaskVariables = mappedName;
              } else {
                missingTaskVariables += ", " + mappedName;
              }
            }
          }

          // if there are missing, required parameters, throw an
          // IllegalArgumentException
          if (missingTaskVariables != null) {
            throw new IllegalArgumentException("missing task variables: " + missingTaskVariables);
          }

          iter = variableAccesses.iterator();
          while (iter.hasNext()) {
            VariableAccess variableAccess = (VariableAccess) iter.next();
            String mappedName = variableAccess.getMappedName();
            String variableName = variableAccess.getVariableName();
            if (variableAccess.isWritable()) {
              Object value = taskInstance.getVariable(mappedName);
              if (value != null) {
                log.debug(
                    "submitting task variable '"
                        + mappedName
                        + "' to process variable '"
                        + variableName
                        + "', value '"
                        + value
                        + "'");
                contextInstance.setVariable(variableName, value, token);
              }
            }
          }
        }
      }
    } finally {
      Thread.currentThread().setContextClassLoader(surroundingClassLoader);
    }
  }