public String startProcess(
      String userId,
      String businessKey,
      String processDefinitionId,
      Map<String, Object> processParameters) {
    // 先设置登录用户
    IdentityService identityService = processEngine.getIdentityService();
    identityService.setAuthenticatedUserId(userId);

    ProcessInstance processInstance =
        processEngine
            .getRuntimeService()
            .startProcessInstanceById(processDefinitionId, businessKey, processParameters);

    // {流程标题:title}-{发起人:startUser}-{发起时间:startTime}
    String processDefinitionName =
        processEngine
            .getRepositoryService()
            .createProcessDefinitionQuery()
            .processDefinitionId(processDefinitionId)
            .singleResult()
            .getName();
    String processInstanceName =
        processDefinitionName
            + "-"
            + userConnector.findById(userId).getDisplayName()
            + "-"
            + new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date());
    processEngine
        .getRuntimeService()
        .setProcessInstanceName(processInstance.getId(), processInstanceName);

    return processInstance.getId();
  }
  @Deployment
  public void testSignalWithGlobalScope() {
    // Start the process that catches the signal
    ProcessInstance processInstanceCatch =
        runtimeService.startProcessInstanceByKey("processWithSignalCatch");
    assertEquals(
        "userTaskWithSignalCatch",
        taskService
            .createTaskQuery()
            .processInstanceId(processInstanceCatch.getId())
            .singleResult()
            .getName());

    // Then start the process that will throw thee signal
    runtimeService.startProcessInstanceByKey("processWithSignalThrow");

    // Since the signal is process instance scoped, the second process shouldn't have proceeded in
    // any way
    assertEquals(
        "userTaskAfterSignalCatch",
        taskService
            .createTaskQuery()
            .processInstanceId(processInstanceCatch.getId())
            .singleResult()
            .getName());
  }
  @Deployment(
      resources = {
        "org/activiti/examples/bpmn/event/timer/BoundaryTimerEventTest.testInterruptingTimerDuration.bpmn"
      })
  @Test
  public void testInterruptingTimerDuration() {

    // Start process instance
    RuntimeService runtimeService = activitiRule.getRuntimeService();
    ProcessInstance pi = runtimeService.startProcessInstanceByKey("escalationExample");

    // There should be one task, with a timer : first line support
    TaskService taskService = activitiRule.getTaskService();
    Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();
    assertEquals("First line support", task.getName());

    // Manually execute the job
    ManagementService managementService = activitiRule.getManagementService();
    Job timer = managementService.createJobQuery().singleResult();
    managementService.executeJob(timer.getId());

    // The timer has fired, and the second task (secondlinesupport) now exists
    task = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();
    assertEquals("Second line support", task.getName());
  }
  @Deployment(resources = {"org/activiti/engine/test/api/oneTaskProcess.bpmn20.xml"})
  public void testDeleteProcessInstance() {
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
    assertEquals(
        1,
        runtimeService.createProcessInstanceQuery().processDefinitionKey("oneTaskProcess").count());

    String deleteReason = "testing instance deletion";
    runtimeService.deleteProcessInstance(processInstance.getId(), deleteReason);
    assertEquals(
        0,
        runtimeService.createProcessInstanceQuery().processDefinitionKey("oneTaskProcess").count());

    // test that the delete reason of the process instance shows up as delete reason of the task in
    // history
    // ACT-848
    if (!ProcessEngineConfiguration.HISTORY_NONE.equals(processEngineConfiguration.getHistory())) {

      HistoricTaskInstance historicTaskInstance =
          historyService
              .createHistoricTaskInstanceQuery()
              .processInstanceId(processInstance.getId())
              .singleResult();

      assertEquals(deleteReason, historicTaskInstance.getDeleteReason());
    }
  }
  @Deployment
  public void testExpression() {
    // Set the clock fixed
    HashMap<String, Object> variables1 = new HashMap<String, Object>();
    variables1.put("dueDate", new Date());

    HashMap<String, Object> variables2 = new HashMap<String, Object>();
    variables2.put("dueDate", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(new Date()));

    // After process start, there should be timer created
    ProcessInstance pi1 =
        runtimeService.startProcessInstanceByKey("intermediateTimerEventExample", variables1);
    ProcessInstance pi2 =
        runtimeService.startProcessInstanceByKey("intermediateTimerEventExample", variables2);

    assertEquals(1, managementService.createJobQuery().processInstanceId(pi1.getId()).count());
    assertEquals(1, managementService.createJobQuery().processInstanceId(pi2.getId()).count());

    // After setting the clock to one second in the future the timers should fire
    List<Job> jobs = managementService.createJobQuery().executable().list();
    assertEquals(2, jobs.size());
    for (Job job : jobs) {
      managementService.executeJob(job.getId());
    }

    assertEquals(0, managementService.createJobQuery().processInstanceId(pi1.getId()).count());
    assertEquals(0, managementService.createJobQuery().processInstanceId(pi2.getId()).count());

    assertProcessEnded(pi1.getProcessInstanceId());
    assertProcessEnded(pi2.getProcessInstanceId());
  }
  public StreamResource buildStreamResource(
      ProcessInstance processInstance,
      RepositoryService repositoryService,
      RuntimeService runtimeService) {

    StreamResource imageResource = null;

    ProcessDefinitionEntity processDefinition =
        (ProcessDefinitionEntity)
            ((RepositoryServiceImpl) repositoryService)
                .getDeployedProcessDefinition(processInstance.getProcessDefinitionId());

    if (processDefinition != null && processDefinition.isGraphicalNotationDefined()) {
      InputStream definitionImageStream =
          ProcessDiagramGenerator.generateDiagram(
              processDefinition,
              "png",
              runtimeService.getActiveActivityIds(processInstance.getId()));

      StreamSource streamSource = new InputStreamStreamSource(definitionImageStream);

      // Create image name
      String imageExtension = extractImageExtension(processDefinition.getDiagramResourceName());
      String fileName = processInstance.getId() + UUID.randomUUID() + "." + imageExtension;

      imageResource = new StreamResource(streamSource, fileName, ExplorerApp.get());
    }
    return imageResource;
  }
Exemple #7
0
  /**
   * 启动流程
   *
   * @param entity
   */
  @Transactional(readOnly = false)
  public void save(Leave leave, Map<String, Object> variables) {

    // 保存业务数据
    if (StringUtils.isBlank(leave.getId())) {
      leave.preInsert();
      leaveDao.insert(leave);
    } else {
      leave.preUpdate();
      leaveDao.update(leave);
    }
    logger.debug("save entity: {}", leave);

    // 用来设置启动流程的人员ID,引擎会自动把用户ID保存到activiti:initiator中
    identityService.setAuthenticatedUserId(leave.getCurrentUser().getLoginName());

    // 启动流程
    String businessKey = leave.getId().toString();
    variables.put("type", "leave");
    variables.put("busId", businessKey);
    ProcessInstance processInstance =
        runtimeService.startProcessInstanceByKey(ActUtils.PD_LEAVE[0], businessKey, variables);
    leave.setProcessInstance(processInstance);

    // 更新流程实例ID
    leave.setProcessInstanceId(processInstance.getId());
    leaveDao.updateProcessInstanceId(leave);

    logger.debug(
        "start process of {key={}, bkey={}, pid={}, variables={}}",
        new Object[] {ActUtils.PD_LEAVE[0], businessKey, processInstance.getId(), variables});
  }
  @Test
  public void testAcknowledgement() {
    TaskService taskService = processEngine.getTaskService();
    FormService formService = processEngine.getFormService();

    List<Task> tasks =
        taskService
            .createTaskQuery()
            .taskAssignee("kermit")
            .processInstanceId(processInstance.getId())
            .list();
    assertEquals(1, tasks.size());
    assertEquals("get acknowledgement", tasks.get(0).getName());

    for (Task task : tasks) {
      Map<String, String> formData = new HashMap<String, String>();
      formService.submitTaskFormData(task.getId(), formData); // Stack trace starts here
    }

    tasks =
        taskService
            .createTaskQuery()
            .taskAssignee("kermit")
            .processInstanceId(processInstance.getId())
            .list();
    assertEquals(0, tasks.size());
  }
 /** @param args */
 public static void main(String[] args) {
   // 创建流程引擎
   ProcessEngine engine = ProcessEngines.getDefaultProcessEngine();
   // 得到流程存储服务组件
   RepositoryService repositoryService = engine.getRepositoryService();
   // 得到运行时服务组件
   RuntimeService runtimeService = engine.getRuntimeService();
   // 获取流程任务组件
   TaskService taskService = engine.getTaskService();
   // 部署流程文件
   repositoryService
       .createDeployment()
       .addClasspathResource("bpmn11.5/SignalBoundaryEvent.bpmn")
       .deploy();
   // 启动2个流程实例
   ProcessInstance pi1 = runtimeService.startProcessInstanceByKey("sbProcess");
   ProcessInstance pi2 = runtimeService.startProcessInstanceByKey("sbProcess");
   // 查找第一个流程实例中签订合同的任务
   Task pi1Task = taskService.createTaskQuery().processInstanceId(pi1.getId()).singleResult();
   taskService.complete(pi1Task.getId());
   // 查找第二个流程实例中签订合同的任务
   Task pi2Task = taskService.createTaskQuery().processInstanceId(pi2.getId()).singleResult();
   taskService.complete(pi2Task.getId());
   // 此时执行流到达确认合同任务,发送一次信号
   runtimeService.signalEventReceived("contactChangeSignal");
   // 查询全部的任务
   List<Task> tasks = taskService.createTaskQuery().list();
   // 输出结果
   for (Task task : tasks) {
     System.out.println(task.getProcessInstanceId() + "---" + task.getName());
   }
 }
 protected String getProcessDisplayName(
     ProcessDefinition processDefinition, ProcessInstance processInstance) {
   if (processDefinition.getName() != null) {
     return processDefinition.getName() + " (" + processInstance.getId() + ")";
   } else {
     return processDefinition.getKey() + " (" + processInstance.getId() + ")";
   }
 }
  @Test
  public void testCouponValidation() {
    TaskService taskService = processEngine.getTaskService();
    FormService formService = processEngine.getFormService();

    List<Task> tasks =
        taskService
            .createTaskQuery()
            .taskAssignee("kermit")
            .processInstanceId(processInstance.getId())
            .list();
    assertEquals(1, tasks.size());

    /** Invalid coupon hash */
    for (Task task : tasks) {
      assertNotNull(task);
      assertEquals("get coupon", task.getName());
      Map<String, String> formData = new HashMap<String, String>();
      formData.put("hash", "abc");
      formService.submitTaskFormData(task.getId(), formData);

      break;
    }

    tasks =
        taskService
            .createTaskQuery()
            .taskAssignee("kermit")
            .processInstanceId(processInstance.getId())
            .list();
    assertEquals(1, tasks.size());

    /** Valid coupon hash */
    for (Task task : tasks) {
      assertNotNull(task);
      assertEquals("get coupon", task.getName());
      Map<String, String> formData = new HashMap<String, String>();
      formData.put("hash", "abcd");
      formService.submitTaskFormData(task.getId(), formData);

      break;
    }

    // check if the price was reduced correctly
    Object price = runtimeService.getVariable(processInstance.getId(), "price");
    assertNotNull(price);
    assertEquals(new Double(130), price);

    // 'get bank transfer data' should be next on the list
    tasks =
        taskService
            .createTaskQuery()
            .taskAssignee("kermit")
            .processInstanceId(processInstance.getId())
            .list();
    assertEquals(1, tasks.size());
    assertEquals("get bank transfer data", tasks.get(0).getName());
  }
  @Test
  @Deployment(resources = "diagrams/chapter7/expression.bpmn")
  public void testExpression() {
    MyBean myBean = new MyBean();
    Map<String, Object> variables = new HashMap<String, Object>();
    variables.put("myBean", myBean);
    String name = "Henry Yan";
    variables.put("name", name);

    // 运行期表达式
    identityService.setAuthenticatedUserId("henryyan");
    String businessKey = "9999"; // 业务ID
    ProcessInstance processInstance =
        runtimeService.startProcessInstanceByKey("expression", businessKey, variables);
    assertEquals(
        "henryyan",
        runtimeService.getVariable(processInstance.getId(), "authenticatedUserIdForTest"));
    assertEquals(
        "Henry Yan, added by print(String name)",
        runtimeService.getVariable(processInstance.getId(), "returnValue"));
    assertEquals(businessKey, runtimeService.getVariable(processInstance.getId(), "businessKey"));

    // 显示数据库状态
    List<Map<String, Object>> rows =
        managementService
            .createTablePageQuery()
            .tableName("ACT_HI_DETAIL")
            .listPage(0, 100)
            .getRows();
    for (Map<String, Object> map : rows) {
      Set<Entry<String, Object>> entrySet = map.entrySet();
      for (Entry<String, Object> entry : entrySet) {
        System.out.println(entry.getKey() + " = " + entry.getValue());
      }
      System.out.println("-------------------------");
    }

    System.out.println("==============字节流数据==============");
    rows =
        managementService
            .createTablePageQuery()
            .tableName("ACT_GE_BYTEARRAY")
            .listPage(0, 100)
            .getRows();
    for (Map<String, Object> map : rows) {
      Set<Entry<String, Object>> entrySet = map.entrySet();
      for (Entry<String, Object> entry : entrySet) {
        System.out.println(entry.getKey() + " = " + entry.getValue());
      }
      System.out.println("-------------------------");
    }

    // DelegateTask 设置的变量
    Task task =
        taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
    String setByTask = (String) taskService.getVariable(task.getId(), "setByTask");
    assertEquals("I'm setted by DelegateTask, " + name, setByTask);
  }
  @Test
  public void testBankTransferValidation() {
    TaskService taskService = processEngine.getTaskService();
    FormService formService = processEngine.getFormService();

    List<Task> tasks =
        taskService
            .createTaskQuery()
            .taskAssignee("kermit")
            .processInstanceId(processInstance.getId())
            .list();
    assertEquals(1, tasks.size());

    // Invalid bank data
    for (Task task : tasks) {
      assertNotNull(task);
      assertEquals("get bank transfer data", task.getName());
      Map<String, String> formData = new HashMap<String, String>();
      formData.put("bankName", "Bank austria"); // invalid bank-name
      formData.put("bankCode", "12000");
      formData.put("accountNumber", "12345678901");
      formData.put("holdersName", "Max Muster");
      formService.submitTaskFormData(task.getId(), formData);
    }

    tasks =
        taskService
            .createTaskQuery()
            .taskAssignee("kermit")
            .processInstanceId(processInstance.getId())
            .list();
    assertEquals(1, tasks.size());
    // As of an error the form should be empty
    assertEquals(0, formService.getTaskFormData(tasks.get(0).getId()).getFormProperties().size());

    // Valid bank data
    for (Task task : tasks) {
      assertNotNull(task);
      assertEquals("get bank transfer data", task.getName());
      Map<String, String> formData = new HashMap<String, String>();
      formData.put("bankName", "Bank Austria");
      formData.put("bankCode", "12000");
      formData.put("accountNumber", "12345678901");
      formData.put("holdersName", "Max Muster");
      formService.submitTaskFormData(task.getId(), formData); // Stack trace starts here
    }

    tasks =
        taskService
            .createTaskQuery()
            .taskAssignee("kermit")
            .processInstanceId(processInstance.getId())
            .list();
    assertEquals(1, tasks.size());
    assertEquals("get acknowledgement", tasks.get(0).getName());
  }
  @Test
  @Ignore
  public void testHappyPath() {

    // Create test applicant
    Applicant applicant = new Applicant("John Doe", "*****@*****.**", "12344");
    applicantRepository.save(applicant);

    // Start process instance
    Map<String, Object> variables = new HashMap<String, Object>();
    variables.put("applicant", applicant);
    ProcessInstance processInstance =
        runtimeService.startProcessInstanceByKey("hireProcessWithJpa", variables);

    // First, the 'phone interview' should be active
    Task task =
        taskService
            .createTaskQuery()
            .processInstanceId(processInstance.getId())
            .taskCandidateGroup("dev-managers")
            .singleResult();
    Assert.assertEquals("Telephone interview", task.getName());

    // Completing the phone interview with success should trigger two new tasks
    Map<String, Object> taskVariables = new HashMap<String, Object>();
    taskVariables.put("telephoneInterviewOutcome", true);
    taskService.complete(task.getId(), taskVariables);

    List<Task> tasks =
        taskService
            .createTaskQuery()
            .processInstanceId(processInstance.getId())
            .orderByTaskName()
            .asc()
            .list();
    Assert.assertEquals(2, tasks.size());
    Assert.assertEquals("Financial negotiation", tasks.get(0).getName());
    Assert.assertEquals("Tech interview", tasks.get(1).getName());

    // Completing both should wrap up the subprocess, send out the 'welcome mail' and end the
    // process instance
    taskVariables = new HashMap<String, Object>();
    taskVariables.put("techOk", true);
    taskService.complete(tasks.get(0).getId(), taskVariables);

    taskVariables = new HashMap<String, Object>();
    taskVariables.put("financialOk", true);
    taskService.complete(tasks.get(1).getId(), taskVariables);

    // Verify email
    Assert.assertEquals(1, wiser.getMessages().size());

    // Verify process completed
    Assert.assertEquals(1, historyService.createHistoricProcessInstanceQuery().finished().count());
  }
Exemple #15
0
  @Deployment
  public void testSetScriptResultToProcessVariable() {
    Map<String, Object> variables = new HashMap<String, Object>();
    variables.put("echo", "hello");
    variables.put("existingProcessVariableName", "one");

    ProcessInstance pi =
        runtimeService.startProcessInstanceByKey("setScriptResultToProcessVariable", variables);

    assertEquals("hello", runtimeService.getVariable(pi.getId(), "existingProcessVariableName"));
    assertEquals(pi.getId(), runtimeService.getVariable(pi.getId(), "newProcessVariableName"));
  }
 @Test
 public void startProcessInstance() {
   Map<String, Object> variableMap = new HashMap<String, Object>();
   variableMap.put("price", 150);
   processInstance = runtimeService.startProcessInstanceByKey("OnlinePaymentProcess", variableMap);
   assertNotNull(processInstance.getId());
   logger.info(
       "Created new Activiti process instance: id "
           + processInstance.getId()
           + " "
           + processInstance.getProcessDefinitionId());
 }
  @Deployment(resources = {"org/activiti/engine/test/api/oneTaskProcess.bpmn20.xml"})
  public void testSetVariables() {
    Map<String, Object> vars = new HashMap<String, Object>();
    vars.put("variable1", "value1");
    vars.put("variable2", "value2");

    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
    runtimeService.setVariables(processInstance.getId(), vars);

    assertEquals("value1", runtimeService.getVariable(processInstance.getId(), "variable1"));
    assertEquals("value2", runtimeService.getVariable(processInstance.getId(), "variable2"));
  }
Exemple #18
0
  @Deployment(
      resources = {
        "org/activiti/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml"
      })
  public void testTaskDueDate() throws Exception {
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
    Task task =
        taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();

    // Set due-date on task
    Date dueDate = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss").parse("01/02/2003 01:12:13");
    task.setDueDate(dueDate);
    taskService.saveTask(task);

    assertEquals(
        1,
        taskService
            .createTaskQuery()
            .processInstanceId(processInstance.getId())
            .dueDate(dueDate)
            .count());

    Calendar otherDate = Calendar.getInstance();
    otherDate.add(Calendar.YEAR, 1);
    assertEquals(
        0,
        taskService
            .createTaskQuery()
            .processInstanceId(processInstance.getId())
            .dueDate(otherDate.getTime())
            .count());

    Calendar priorDate = Calendar.getInstance();
    priorDate.setTime(dueDate);
    priorDate.roll(Calendar.YEAR, -1);

    assertEquals(
        1,
        taskService
            .createTaskQuery()
            .processInstanceId(processInstance.getId())
            .dueAfter(priorDate.getTime())
            .count());

    assertEquals(
        1,
        taskService
            .createTaskQuery()
            .processInstanceId(processInstance.getId())
            .dueBefore(otherDate.getTime())
            .count());
  }
  @Deployment
  public void testSignalWithProcessVariables() {

    ProcessInstance processInstance =
        runtimeService.startProcessInstanceByKey("testSignalWithProcessVariables");
    Map<String, Object> processVariables = new HashMap<String, Object>();
    processVariables.put("variable", "value");

    // signal the execution while passing in the variables
    runtimeService.signal(processInstance.getId(), processVariables);

    Map<String, Object> variables = runtimeService.getVariables(processInstance.getId());
    assertEquals(variables, processVariables);
  }
  /**
   * easyui 运行中流程列表数据
   *
   * @param request
   * @param response
   * @param dataGrid
   */
  @RequestMapping(params = "runningProcessDataGrid")
  public void runningProcessDataGrid(
      HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {

    /*
     * List<HistoricProcessInstance> historicProcessInstances =
     * historyService .createHistoricProcessInstanceQuery()
     * .unfinished().list();
     */
    ProcessInstanceQuery processInstanceQuery = runtimeService.createProcessInstanceQuery();
    List<ProcessInstance> list = processInstanceQuery.list();

    StringBuffer rows = new StringBuffer();
    for (ProcessInstance hi : list) {
      rows.append(
          "{'id':"
              + hi.getId()
              + ",'processDefinitionId':'"
              + hi.getProcessDefinitionId()
              + "','processInstanceId':'"
              + hi.getProcessInstanceId()
              + "','activityId':'"
              + hi.getActivityId()
              + "'},");
    }

    String rowStr = StringUtils.substringBeforeLast(rows.toString(), ",");

    JSONObject jObject =
        JSONObject.fromObject("{'total':" + list.size() + ",'rows':[" + rowStr + "]}");
    responseDatagrid(response, jObject);
  }
  @Test
  @Rollback(value = false)
  public void testDeploy() throws Exception {
    String path = ProcessDefManagerTest.class.getClassLoader().getResource("bpmnsub.xml").getPath();
    String value = FileUtils.readFileToString(new File(path));

    Deployment deployment =
        repositoryService
            .createDeployment()
            .addString("sub-model.bpmn", value)
            .name("子流程")
            .category("行政")
            .enableDuplicateFiltering()
            .deploy();
    //
    //        // 4. Start a process instance
    Map<String, Object> map = new HashMap<String, Object>();
    //        map.put("signAssignee", Arrays.asList("hr", "dep", "user"));
    identityService.setAuthenticatedUserId("dynamic");
    ProcessDefinition definition =
        repositoryService
            .createProcessDefinitionQuery()
            .deploymentId(deployment.getId())
            .singleResult();

    ProcessInstance processInstance =
        runtimeService.startProcessInstanceById(definition.getId(), map);
    int i = 0;
    System.out.println(processInstance.getId());
  }
 @Deployment(resources = {"org/activiti/engine/test/api/oneTaskProcess.bpmn20.xml"})
 public void testGetVariableUnexistingVariableName() {
   ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
   Object variableValue =
       runtimeService.getVariable(processInstance.getId(), "unexistingVariable");
   assertNull(variableValue);
 }
  @Deployment
  public void testAsyncTriggeredSignalEvent() {
    ProcessInstance processInstance =
        runtimeService.startProcessInstanceByKey("processWithSignalCatch");

    assertNotNull(processInstance);
    Execution execution =
        runtimeService
            .createExecutionQuery()
            .processInstanceId(processInstance.getId())
            .signalEventSubscriptionName("The Signal")
            .singleResult();
    assertNotNull(execution);
    assertEquals(1, createEventSubscriptionQuery().count());
    assertEquals(2, runtimeService.createExecutionQuery().count());

    runtimeService.signalEventReceivedAsync("The Signal", execution.getId());

    assertEquals(1, managementService.createJobQuery().messages().count());

    waitForJobExecutorToProcessAllJobs(8000L, 200L);
    assertEquals(0, createEventSubscriptionQuery().count());
    assertEquals(0, runtimeService.createProcessInstanceQuery().count());
    assertEquals(0, managementService.createJobQuery().count());
  }
  @Override
  public void costWorkFlowStart(CostApprovalEntity costApproval, HttpServletRequest request) {
    // 由session取到登录用户id
    String applyUserId = ResourceUtil.getSessionUserName().getId();
    this.save(costApproval);
    String processKey = request.getParameter("processKey");
    if (!StringUtil.isNotEmpty(processKey)) {
      WorkFlowSetEntity workFlowSet =
          this.findUniqueByProperty(
              WorkFlowSetEntity.class, "entityName", costApproval.getClass().getSimpleName());
      processKey = workFlowSet.getProcessKey();
    }
    String businessKey = costApproval.getId().toString();
    ProcessInstance processInstance = null;
    // 用来设置启动流程的人员ID,引擎会自动把用户ID保存到activiti:initiator中
    identityService.setAuthenticatedUserId(applyUserId);

    Map<String, Object> variables = new HashMap<String, Object>();
    variables.put(ProcessConstantsUtil.getApplyUserId(), applyUserId);
    processInstance = runtimeService.startProcessInstanceByKey(processKey, businessKey, variables);
    String processInstanceId = processInstance.getId();
    costApproval.setProcessinstanceId(processInstanceId);

    // 获取并执行当前流程实例的下一步任务
    Task task = null;
    TaskQuery query =
        taskService.createTaskQuery().processInstanceBusinessKey(businessKey).active();
    task = query.singleResult();
    variables.put(
        ProcessConstantsUtil.getDeptLeaderId(),
        ResourceUtil.getSessionUserName().getCurrentDepart().getDepartManager().getId());
    taskService.complete(task.getId(), variables);
  }
  @Deployment(
      resources = {
        "org/activiti/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml"
      })
  public void testWithoutDueDateQuery() throws Exception {
    if (processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.AUDIT)) {
      ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
      HistoricTaskInstance historicTask =
          historyService
              .createHistoricTaskInstanceQuery()
              .processInstanceId(processInstance.getId())
              .withoutTaskDueDate()
              .singleResult();
      assertNotNull(historicTask);
      assertNull(historicTask.getDueDate());

      // Set due-date on task
      Task task =
          taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
      Date dueDate = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss").parse("01/02/2003 01:12:13");
      task.setDueDate(dueDate);
      taskService.saveTask(task);

      assertEquals(
          0,
          historyService
              .createHistoricTaskInstanceQuery()
              .processInstanceId(processInstance.getId())
              .withoutTaskDueDate()
              .count());

      task =
          taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();

      // Clear due-date on task
      task.setDueDate(null);
      taskService.saveTask(task);

      assertEquals(
          1,
          historyService
              .createHistoricTaskInstanceQuery()
              .processInstanceId(processInstance.getId())
              .withoutTaskDueDate()
              .count());
    }
  }
  @Deployment
  public void testCandidate() {
    if (processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.ACTIVITY)) {
      ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
      List<HistoricTaskInstance> tasks =
          historyService.createHistoricTaskInstanceQuery().taskCandidateUser("kermit").list();
      assertEquals(3, tasks.size());

      tasks = historyService.createHistoricTaskInstanceQuery().taskCandidateUser("gonzo").list();
      assertEquals(0, tasks.size());

      tasks = historyService.createHistoricTaskInstanceQuery().taskCandidateUser("fozzie").list();
      assertEquals(1, tasks.size());

      tasks =
          historyService.createHistoricTaskInstanceQuery().taskCandidateGroup("management").list();
      assertEquals(1, tasks.size());
      List<String> groups = new ArrayList<String>();
      groups.add("management");
      groups.add("accountancy");
      tasks = historyService.createHistoricTaskInstanceQuery().taskCandidateGroupIn(groups).list();
      assertEquals(1, tasks.size());

      Task task =
          taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
      taskService.complete(task.getId());

      assertEquals(
          0, taskService.createTaskQuery().processInstanceId(processInstance.getId()).count());

      tasks = historyService.createHistoricTaskInstanceQuery().taskCandidateUser("kermit").list();
      assertEquals(3, tasks.size());

      tasks = historyService.createHistoricTaskInstanceQuery().taskCandidateUser("gonzo").list();
      assertEquals(0, tasks.size());

      tasks = historyService.createHistoricTaskInstanceQuery().taskCandidateUser("fozzie").list();
      assertEquals(1, tasks.size());

      tasks =
          historyService.createHistoricTaskInstanceQuery().taskCandidateGroup("management").list();
      assertEquals(1, tasks.size());

      tasks = historyService.createHistoricTaskInstanceQuery().taskCandidateGroupIn(groups).list();
      assertEquals(1, tasks.size());
    }
  }
  @Deployment(resources = {"org/activiti/engine/test/api/oneTaskProcess.bpmn20.xml"})
  public void testFindActiveActivityIds() {
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");

    List<String> activities = runtimeService.getActiveActivityIds(processInstance.getId());
    assertNotNull(activities);
    assertEquals(1, activities.size());
  }
Exemple #28
0
 /** 启动流程实例 使用key启动默认是按照最新版本的流程定义启动 */
 @Test
 public void startProcessInstance() {
   ProcessInstance p1 =
       processEngine
           .getRuntimeService() // 与正在执行的流程实例和执行对象相关的service
           .startProcessInstanceByKey("hellowrold"); // 使用流程定义的key
   // key=bpmn文件中ID值
   System.out.println("流程实例ID " + p1.getId()); // 流程实例ID
   System.out.println("流程定义ID" + p1.getProcessDefinitionId()); // 流程定义ID
 }
  @Test
  public void startProcess() throws Exception {
    RepositoryService repositoryService = activitiRule.getRepositoryService();
    TaskService taskService = activitiRule.getTaskService();
    repositoryService
        .createDeployment()
        .addInputStream("process1.bpmn20.xml", new FileInputStream(filename))
        .deploy();
    RuntimeService runtimeService = activitiRule.getRuntimeService();
    Map<String, Object> variableMap = new HashMap<String, Object>();
    variableMap.put("name", "Activiti");
    ProcessInstance processInstance =
        runtimeService.startProcessInstanceByKey("MyProcess", variableMap);
    assertNotNull(processInstance.getId());
    System.out.println(
        "id " + processInstance.getId() + " " + processInstance.getProcessDefinitionId());

    assertNotNull(taskService.createTaskQuery().taskAssignee("fg").singleResult());
  }
 @Deployment(resources = {"org/activiti/engine/test/api/oneTaskProcess.bpmn20.xml"})
 public void testSetVariableNullVariableName() {
   try {
     ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
     runtimeService.setVariable(processInstance.getId(), null, "variableValue");
     fail("ActivitiException expected");
   } catch (ActivitiException ae) {
     assertTextPresent("variableName is null", ae.getMessage());
   }
 }