Java Code Examples for org.activiti.engine.impl.identity.Authentication#setAuthenticatedUserId()

The following examples show how to use org.activiti.engine.impl.identity.Authentication#setAuthenticatedUserId() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ExpressionManagerTest.java    From activiti6-boot2 with Apache License 2.0 7 votes vote down vote up
@Deployment
public void testAuthenticatedUserIdAvailable() {
  try {
    // Setup authentication
    Authentication.setAuthenticatedUserId("frederik");
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("testAuthenticatedUserIdAvailableProcess");
    
    // Check if the variable that has been set in service-task is the authenticated user
    String value = (String) runtimeService.getVariable(processInstance.getId(), "theUser");
    assertNotNull(value);
    assertEquals("frederik", value);
  } finally {
    // Cleanup
    Authentication.setAuthenticatedUserId(null);
  }
}
 
Example 2
Source File: ProcessServiceImpl.java    From open-cloud with MIT License 6 votes vote down vote up
/**
 * 执行任务
 *
 * @param taskOperate
 */
@Override
public void complete(TaskOperate taskOperate) {
    String taskId = taskOperate.getTaskId();
    String user = taskOperate.getUser();
    // 放入流程变量
    Map<String, Object> variables = Maps.newHashMap();
    // 设置任务变量_OPT
    variables.put(BpmConstants.TASK_OPERATE_KEY, taskOperate);
    // 使用任务id,获取任务对象,获取流程实例id
    Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
    if (task == null) {
        throw new OpenAlertException("任务不存在");
    }
    //利用任务对象,获取流程实例id
    String processInstancesId = task.getProcessInstanceId();
    //由于流程用户上下文对象是线程独立的,所以要在需要的位置设置,要保证设置和获取操作在同一个线程中
    //批注人的名称  一定要写,不然查看的时候不知道人物信息
    Authentication.setAuthenticatedUserId(user);
    taskService.addComment(taskId, processInstancesId, taskOperate.getOperateType().name(), taskOperate.getComment());
    //执行任务
    completeTask(taskOperate.getTaskId(), variables);
}
 
Example 3
Source File: ProcessInstanceIdentityLinksTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Deployment(resources = "org/activiti/engine/test/api/runtime/IdentityLinksProcess.bpmn20.xml")
public void testCustomLinkGroupLink() {
    Authentication.setAuthenticatedUserId(null);
    runtimeService.startProcessInstanceByKey("IdentityLinksProcess");

    String processInstanceId = runtimeService
            .createProcessInstanceQuery()
            .singleResult()
            .getId();

    runtimeService.addGroupIdentityLink(processInstanceId, "muppets", "playing");

    List<IdentityLink> identityLinks = runtimeService.getIdentityLinksForProcessInstance(processInstanceId);
    IdentityLink identityLink = identityLinks.get(0);

    assertEquals("muppets", identityLink.getGroupId());
    assertNull("kermit", identityLink.getUserId());
    assertEquals("playing", identityLink.getType());
    assertEquals(processInstanceId, identityLink.getProcessInstanceId());

    assertEquals(1, identityLinks.size());

    runtimeService.deleteGroupIdentityLink(processInstanceId, "muppets", "playing");

    assertEquals(0, runtimeService.getIdentityLinksForProcessInstance(processInstanceId).size());
}
 
Example 4
Source File: ProcessInstanceIdentityLinksTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Deployment(resources = "org/activiti/engine/test/api/runtime/IdentityLinksProcess.bpmn20.xml")
public void testCustomTypeUserLink() {
    Authentication.setAuthenticatedUserId(null);
    runtimeService.startProcessInstanceByKey("IdentityLinksProcess");

    String processInstanceId = runtimeService
            .createProcessInstanceQuery()
            .singleResult()
            .getId();

    runtimeService.addUserIdentityLink(processInstanceId, "kermit", "interestee");

    List<IdentityLink> identityLinks = runtimeService.getIdentityLinksForProcessInstance(processInstanceId);
    IdentityLink identityLink = identityLinks.get(0);

    assertNull(identityLink.getGroupId());
    assertEquals("kermit", identityLink.getUserId());
    assertEquals("interestee", identityLink.getType());
    assertEquals(processInstanceId, identityLink.getProcessInstanceId());

    assertEquals(1, identityLinks.size());

    runtimeService.deleteUserIdentityLink(processInstanceId, "kermit", "interestee");

    assertEquals(0, runtimeService.getIdentityLinksForProcessInstance(processInstanceId).size());
}
 
Example 5
Source File: ProcessInstanceIdentityLinksTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Deployment(resources = "org/activiti/engine/test/api/runtime/IdentityLinksProcess.bpmn20.xml")
public void testParticipantUserLink() {
    Authentication.setAuthenticatedUserId(null);
    runtimeService.startProcessInstanceByKey("IdentityLinksProcess");

    String processInstanceId = runtimeService
            .createProcessInstanceQuery()
            .singleResult()
            .getId();

    runtimeService.addParticipantUser(processInstanceId, "kermit");

    List<IdentityLink> identityLinks = runtimeService.getIdentityLinksForProcessInstance(processInstanceId);
    IdentityLink identityLink = identityLinks.get(0);

    assertNull(identityLink.getGroupId());
    assertEquals("kermit", identityLink.getUserId());
    assertEquals(IdentityLinkType.PARTICIPANT, identityLink.getType());
    assertEquals(processInstanceId, identityLink.getProcessInstanceId());

    assertEquals(1, identityLinks.size());

    runtimeService.deleteParticipantUser(processInstanceId, "kermit");

    assertEquals(0, runtimeService.getIdentityLinksForProcessInstance(processInstanceId).size());
}
 
Example 6
Source File: ExpressionManagerTest.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
@Deployment
public void testAuthenticatedUserIdAvailable() {
  try {
    // Setup authentication
    Authentication.setAuthenticatedUserId("frederik");
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("testAuthenticatedUserIdAvailableProcess");

    // Check if the variable that has been set in service-task is the
    // authenticated user
    String value = (String) runtimeService.getVariable(processInstance.getId(), "theUser");
    assertNotNull(value);
    assertEquals("frederik", value);
  } finally {
    // Cleanup
    Authentication.setAuthenticatedUserId(null);
  }
}
 
Example 7
Source File: IdentityLinkEventsTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
/**
 * Check deletion of links on process instances.
 */
@Deployment(resources = { "org/activiti/engine/test/api/runtime/oneTaskProcess.bpmn20.xml" })
public void testProcessInstanceIdentityDeleteCandidateGroupEvents() throws Exception {
    Authentication.setAuthenticatedUserId(null);
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");

    org.flowable.task.api.Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
    assertNotNull(task);

    // Add identity link
    taskService.addCandidateUser(task.getId(), "kermit");
    taskService.addCandidateGroup(task.getId(), "sales");

    // Three events are received, since the user link on the task also creates an involvement in the process. See previous test
    assertEquals(6, listener.getEventsReceived().size());

    listener.clearEventsReceived();
    taskService.deleteCandidateUser(task.getId(), "kermit");
    assertEquals(1, listener.getEventsReceived().size());

    listener.clearEventsReceived();
    taskService.deleteCandidateGroup(task.getId(), "sales");
    assertEquals(1, listener.getEventsReceived().size());
}
 
Example 8
Source File: UserDetailsService.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
@Override
@Transactional
public UserDetails loadUserByUsername(final String login) {

  // This method is only called during the login.
  // All subsequent calls use the method with the long userId as parameter.
  // (Hence why the cache is NOT used here, but it is used in the loadByUserId)

  String actualLogin = login;
  User userFromDatabase = null;

  userFromDatabase = identityService.createUserQuery().userId(actualLogin).singleResult();

  // Verify user
  if (userFromDatabase == null) {
    throw new UsernameNotFoundException("User " + actualLogin + " was not found in the database");
  }

  // Add capabilities to user object
  Collection<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();

  // add default authority
  grantedAuthorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER));

  // check if user is in super user group
  String superUserGroupName = env.getRequiredProperty("admin.group");
  for (Group group : identityService.createGroupQuery().groupMember(userFromDatabase.getId()).list()) {
    if (StringUtils.equals(superUserGroupName, group.getName())) {
      grantedAuthorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ADMIN));
    }
  }
  
  // Adding it manually to cache
  userCache.putUser(userFromDatabase.getId(), new CachedUser(userFromDatabase, grantedAuthorities));

  // Set authentication globally for Activiti
  Authentication.setAuthenticatedUserId(String.valueOf(userFromDatabase.getId()));

  return new ActivitiAppUser(userFromDatabase, actualLogin, grantedAuthorities);
}
 
Example 9
Source File: FormLeaveController.java    From my_curd with Apache License 2.0 5 votes vote down vote up
/**
 * 新增 action
 */
@TxConfig(ActivitiConfig.DATASOURCE_NAME)
@Before(Tx.class)
public void addAction() {
    // 保存业务表
    FormLeave formLeave = getBean(FormLeave.class, "");
    formLeave.setId(IdUtils.id())
            .setCreater(WebUtils.getSessionUsername(this))
            .setCreateTime(new Date());
    formLeave.save();

    //发起流程
    String businessFormInfoId = getPara("businessFormInfoId");
    if (StringUtils.isEmpty(businessFormInfoId)) {
        renderFail("businessFormInfoId 参数为空");
        return;
    }
    BusinessFormInfo info = BusinessFormInfo.dao.findById(businessFormInfoId);
    if (info == null) {
        renderFail("businessFormInfoId 参数错误");
        return;
    }
    SysUser sysUser = WebUtils.getSysUser(this);
    String processInstanceName = info.getName() + "-( " + sysUser.getRealName()
            + new DateTime(formLeave.getCreateTime()).toString(" yyyy/MM/dd HH:mm )");
    Authentication.setAuthenticatedUserId(WebUtils.getSessionUsername(this));
    ProcessInstanceBuilder builder = ActivitiKit.getRuntimeService().createProcessInstanceBuilder()
            .processDefinitionKey(info.getProcessKey())
            .businessKey(formLeave.getId())
            .processInstanceName(processInstanceName)
            .addVariable("businessForm", info.getFormName());
    builder.start();

    renderSuccess(NEW_PROCESS_SUCCESS);
}
 
Example 10
Source File: HistoricProcessInstanceTest.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Deployment(resources = { "org/activiti/engine/test/history/oneTaskProcess.bpmn20.xml" })
public void testHistoricIdenityLinksOnProcessInstance() {
    Authentication.setAuthenticatedUserId(null);
    if (processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.AUDIT)) {
        ProcessInstance pi = runtimeService.startProcessInstanceByKey("oneTaskProcess");
        runtimeService.addUserIdentityLink(pi.getId(), "kermit", "myType");

        // Check historic links
        List<HistoricIdentityLink> historicLinks = historyService.getHistoricIdentityLinksForProcessInstance(pi.getId());
        assertEquals(1, historicLinks.size());

        assertEquals("myType", historicLinks.get(0).getType());
        assertEquals("kermit", historicLinks.get(0).getUserId());
        assertNull(historicLinks.get(0).getGroupId());
        assertEquals(pi.getId(), historicLinks.get(0).getProcessInstanceId());

        // When process is ended, link should remain
        taskService.complete(taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult().getId());
        assertNull(runtimeService.createProcessInstanceQuery().processInstanceId(pi.getId()).singleResult());

        assertEquals(1, historyService.getHistoricIdentityLinksForProcessInstance(pi.getId()).size());

        // When process is deleted, identitylinks shouldn't exist anymore
        historyService.deleteHistoricProcessInstance(pi.getId());
        assertEquals(0, historyService.getHistoricIdentityLinksForProcessInstance(pi.getId()).size());
    }
}
 
Example 11
Source File: ConcurrentEngineUsageTest.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
  Authentication.setAuthenticatedUserId(drivingUser);
  
  boolean finishTask = false;
  boolean tasksAvailable = false;
  
  while(numberOfProcesses > 0 || tasksAvailable)
  {
    if(numberOfProcesses > 0 && !finishTask) {
      // Start a new process
      retryStartProcess(drivingUser);
      finishTask = true;
      
      if(numberOfProcesses == 0) {
        // Make sure while-loop doesn't stop when processes are all started
        tasksAvailable = taskService.createTaskQuery().taskAssignee(drivingUser).count() > 0;
      }
      numberOfProcesses = numberOfProcesses - 1;
    } else {
      // Finish a task
      List<Task> taskToComplete = taskService.createTaskQuery().taskAssignee(drivingUser).listPage(0, 1);
      tasksAvailable = !taskToComplete.isEmpty();
      if(tasksAvailable) {
        retryFinishTask(taskToComplete.get(0).getId());
      }
      finishTask = false;
    }
  }
}
 
Example 12
Source File: ConcurrentEngineUsageTest.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
  Authentication.setAuthenticatedUserId(drivingUser);

  boolean finishTask = false;
  boolean tasksAvailable = false;

  while (numberOfProcesses > 0 || tasksAvailable) {
    if (numberOfProcesses > 0 && !finishTask) {
      // Start a new process
      retryStartProcess(drivingUser);
      finishTask = true;

      if (numberOfProcesses == 0) {
        // Make sure while-loop doesn't stop when processes are
        // all started
        tasksAvailable = taskService.createTaskQuery().taskAssignee(drivingUser).count() > 0;
      }
      numberOfProcesses = numberOfProcesses - 1;
    } else {
      // Finish a task
      List<Task> taskToComplete = taskService.createTaskQuery().taskAssignee(drivingUser).listPage(0, 1);
      tasksAvailable = !taskToComplete.isEmpty();
      if (tasksAvailable) {
        retryFinishTask(taskToComplete.get(0).getId());
      }
      finishTask = false;
    }
  }
}
 
Example 13
Source File: BoundaryErrorEventTest.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
  super.setUp();

  // Normally the UI will do this automatically for us
  Authentication.setAuthenticatedUserId("kermit");
}
 
Example 14
Source File: UserDetailsService.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
@Transactional
public UserDetails loadByUserId(final String userId) {

  CachedUser cachedUser = userCache.getUser(userId, true, true, false); // Do not check for validity. This would lead to A LOT of db requests! For login, there is a validity period (see below)
  if (cachedUser == null) {
    throw new UsernameNotFoundException("User " + userId + " was not found in the database");
  }

  long lastDatabaseCheck = cachedUser.getLastDatabaseCheck();
  long currentTime = System.currentTimeMillis(); // No need to create a Date object. The Date constructor simply calls this method too!

  if (userValidityPeriod <= 0L || (currentTime - lastDatabaseCheck >= userValidityPeriod)) {

    userCache.invalidate(userId);
    cachedUser = userCache.getUser(userId, true, true, false); // Fetching it again will refresh data

    cachedUser.setLastDatabaseCheck(currentTime);
  }

  // The Spring security docs clearly state a new instance must be returned on every invocation
  User user = cachedUser.getUser();
  String actualUserId = user.getEmail();

  // Set authentication globally for Activiti
  Authentication.setAuthenticatedUserId(String.valueOf(user.getId()));

  return new ActivitiAppUser(cachedUser.getUser(), actualUserId, cachedUser.getGrantedAuthorities());
}
 
Example 15
Source File: BoundaryErrorEventTest.java    From activiti6-boot2 with Apache License 2.0 4 votes vote down vote up
@Override
protected void tearDown() throws Exception {
  Authentication.setAuthenticatedUserId(null);
  super.tearDown();
}
 
Example 16
Source File: IdentityLinkEventsTest.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
/**
 * Check identity links on process instances.
 */
@Deployment(resources = { "org/activiti/engine/test/api/runtime/oneTaskProcess.bpmn20.xml" })
public void testTaskIdentityLinks() throws Exception {
    Authentication.setAuthenticatedUserId(null);
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");

    org.flowable.task.api.Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
    assertNotNull(task);

    // Add identity link
    taskService.addCandidateUser(task.getId(), "kermit");
    taskService.addCandidateGroup(task.getId(), "sales");

    // Three events are received, since the user link on the task also creates an involvement in the process
    assertEquals(6, listener.getEventsReceived().size());

    FlowableEngineEntityEvent event = (FlowableEngineEntityEvent) listener.getEventsReceived().get(0);
    assertEquals(FlowableEngineEventType.ENTITY_CREATED, event.getType());
    assertTrue(event.getEntity() instanceof IdentityLink);
    IdentityLink link = (IdentityLink) event.getEntity();
    assertEquals("kermit", link.getUserId());
    assertEquals("candidate", link.getType());
    assertEquals(task.getId(), link.getTaskId());
    assertEquals(task.getExecutionId(), event.getExecutionId());
    assertEquals(task.getProcessDefinitionId(), event.getProcessDefinitionId());
    assertEquals(task.getProcessInstanceId(), event.getProcessInstanceId());

    event = (FlowableEngineEntityEvent) listener.getEventsReceived().get(1);
    assertEquals(FlowableEngineEventType.ENTITY_INITIALIZED, event.getType());
    assertEquals("kermit", link.getUserId());
    assertEquals("candidate", link.getType());

    event = (FlowableEngineEntityEvent) listener.getEventsReceived().get(4);
    assertEquals(FlowableEngineEventType.ENTITY_CREATED, event.getType());
    assertTrue(event.getEntity() instanceof IdentityLink);
    link = (IdentityLink) event.getEntity();
    assertEquals("sales", link.getGroupId());
    assertEquals("candidate", link.getType());
    assertEquals(task.getId(), link.getTaskId());
    assertEquals(task.getExecutionId(), event.getExecutionId());
    assertEquals(task.getProcessDefinitionId(), event.getProcessDefinitionId());
    assertEquals(task.getProcessInstanceId(), event.getProcessInstanceId());
    event = (FlowableEngineEntityEvent) listener.getEventsReceived().get(5);
    assertEquals(FlowableEngineEventType.ENTITY_INITIALIZED, event.getType());
    assertEquals("sales", link.getGroupId());
    assertEquals("candidate", link.getType());

    listener.clearEventsReceived();

    // Deleting process should delete identity link
    runtimeService.deleteProcessInstance(processInstance.getId(), "test");
    assertEquals(3, listener.getEventsReceived().size());

    event = (FlowableEngineEntityEvent) listener.getEventsReceived().get(0);
    assertEquals(FlowableEngineEventType.ENTITY_DELETED, event.getType());
    event = (FlowableEngineEntityEvent) listener.getEventsReceived().get(1);
    assertEquals(FlowableEngineEventType.ENTITY_DELETED, event.getType());
    event = (FlowableEngineEntityEvent) listener.getEventsReceived().get(2);
    assertEquals(FlowableEngineEventType.ENTITY_DELETED, event.getType());
}
 
Example 17
Source File: AbstractProcessEngineTest.java    From openwebflow with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * 测试加签功能的持久化
 */
@Test
public void testInsertTasksWithPersistence() throws Exception
{
	ProcessInstance instance = _processEngine.getRuntimeService().startProcessInstanceByKey("test2");
	String processInstanceId = instance.getId();
	TaskService taskService = _processEngine.getTaskService();
	TaskFlowControlService tfcs = _taskFlowControlServiceFactory.create(instance.getId());
	//到了step2
	//在前面加两个节点
	Authentication.setAuthenticatedUserId("kermit");
	ActivityImpl[] as = tfcs.insertTasksAfter("step2", "bluejoe", "alex");
	//应该执行到了第一个节点
	//完成该节点
	taskService.complete(taskService.createTaskQuery().singleResult().getId());
	//应该到了下一个节点
	Assert.assertEquals("bluejoe", taskService.createTaskQuery().singleResult().getAssignee());

	//此时模拟服务器重启
	ProcessEngine oldProcessEngine = _processEngine;
	rebuildApplicationContext();
	Assert.assertNotSame(oldProcessEngine, _processEngine);

	//重新构造以上对象
	instance = _processEngine.getRuntimeService().createProcessInstanceQuery().processInstanceId(processInstanceId)
			.singleResult();
	taskService = _processEngine.getTaskService();
	tfcs = _taskFlowControlServiceFactory.create(instance.getId());

	//应该到了下一个节点
	Assert.assertEquals("bluejoe", taskService.createTaskQuery().singleResult().getAssignee());
	//完成该节点
	taskService.complete(taskService.createTaskQuery().singleResult().getId());
	//应该到了下一个节点
	Assert.assertEquals(as[2].getId(), taskService.createTaskQuery().singleResult().getTaskDefinitionKey());
	Assert.assertEquals("alex", taskService.createTaskQuery().singleResult().getAssignee());
	//完成该节点
	taskService.complete(taskService.createTaskQuery().singleResult().getId());
	//应该到了下一个节点
	Assert.assertEquals("step3", taskService.createTaskQuery().singleResult().getTaskDefinitionKey());

	//确认历史轨迹里已保存
	//step1,step2,step2,step2-1,step2-2,step3
	List<HistoricActivityInstance> activities = _processEngine.getHistoryService()
			.createHistoricActivityInstanceQuery().processInstanceId(instance.getId()).list();
	Assert.assertEquals(6, activities.size());

	//删掉流程
	_processEngine.getRuntimeService().deleteProcessInstance(instance.getId(), "test");
}
 
Example 18
Source File: IdentityServiceImpl.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@Override
public void setAuthenticatedUserId(String authenticatedUserId) {
    Authentication.setAuthenticatedUserId(authenticatedUserId);
}
 
Example 19
Source File: BoundaryErrorEventTest.java    From activiti6-boot2 with Apache License 2.0 4 votes vote down vote up
@Override
protected void tearDown() throws Exception {
  Authentication.setAuthenticatedUserId(null);
  super.tearDown();
}
 
Example 20
Source File: IdentityServiceImpl.java    From activiti6-boot2 with Apache License 2.0 4 votes vote down vote up
public void setAuthenticatedUserId(String authenticatedUserId) {
  Authentication.setAuthenticatedUserId(authenticatedUserId);
}