Ошибка: Миграция из Activiti5 в flowable6, customSessionFactories

#activiti #flowable

Вопрос:

Я переношу свой код с Activiti 5 на Flowable 6, следуя руководству, оставленному создателями на их веб-сайте. https://flowable.com/open-source/docs/migration/

Этот проект отлично работал при использовании Activiti. Однако у меня возникает проблема, когда я хочу реализовать свои собственные SessionFactories в процессе настройки двигателя.

Мой контекст приложения:

 <!-- Flowable Database Access -->
<bean id="processEngine" class="org.flowable.spring.ProcessEngineFactoryBean"
      destroy-method="destroy">
    <property name="processEngineConfiguration" ref="processEngineConfiguration"/>
</bean>

<bean id="processEngineConfiguration" class="org.flowable.spring.SpringProcessEngineConfiguration">
    <property name="transactionManager" ref="flowableTransactionManager"/>
    <property name="dataSource" ref="flowableDataSource"/>
    <property name="asyncExecutorActivate" value="false" />
    <property name="databaseType" value="mysql"/>
    <!--<property name="jobExecutorActivate" value="false" />-->
    <property name="databaseSchemaUpdate" value="${hibernate.hbm2ddl.auto}"/>
    <!-- <property name="history" value="full" /> -->
    <property name="customSessionFactories">
        <list>
            <bean class="com.biit.activiti.users.FlowableUserManagerFactory"/>
            <bean class="com.biit.activiti.groups.FlowableGroupManagerFactory"/>
        </list>
    </property>
    <property name="deploymentResources" value="classpath*:/process/*.bpmn20.xml"/>
    <property name="flowable5CompatibilityEnabled" value="true" />
    <property name="flowable5CompatibilityHandlerFactory" ref="flowable5CompatibilityFactory" />
</bean>

<bean id="flowable5CompatibilityFactory" class="org.activiti.compatibility.spring.SpringFlowable5CompatibilityHandlerFactory" />

<bean id="flowableRule" class="org.flowable.engine.test.FlowableRule">
    <property name="processEngine" ref="processEngine"/>
</bean>
 

Моя новая сессияфАктория:

 @Service
public class FlowableUserManagerFactory implements SessionFactory {

@Autowired
private IAuthorizationService<Long, Long, Long> authorizationService;
@Autowired
private IAuthenticationService<Long, Long> authenticationService;
@Autowired
private IGroupToActivityRoleConverter groupToActivityConverter;

@Override
public Class<?> getSessionType() {
    return UserEntityManager.class;
}

@Override
public Session openSession(CommandContext commandContext) {
    return null;
}


public Session openSession() {
    return (Session) new FlowableUserManager(authorizationService, authenticationService, groupToActivityConverter);
}
 

}

Ошибка возникает, когда я использую procesEngine с вышеуказанной конфигурацией в следующем классе:

 @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:applicationContext.xml" })
@Test(groups = "activitiUsers")
public class FlowableUsersTest extends AbstractTransactionalTestNGSpringContextTests {
private final static String USER_ID = "20735";
private final static String USER_EMAIL = "sam@test.com";
private final static String USER_FIRST_NAME = "Sam";
private final static String USER_LAST_NAME = "Max";

@Autowired
private ProcessEngine processEngine;

@Test
public void getLiferayUserAsFlowable() {
    Assert.assertNotNull(processEngine);
    IdentityService identityService =  processEngine.getIdentityService();
    Assert.assertNotNull(identityService);

    User user = identityService.createUserQuery().userId(USER_ID).singleResult();
    Assert.assertNotNull(user);
    Assert.assertEquals(user.getFirstName(), USER_FIRST_NAME);
    Assert.assertEquals(user.getLastName(), USER_LAST_NAME);
}

@Test
public void getLiferayUserAsFlowableByEmail() {
    Assert.assertNotNull(processEngine);
    IdentityService identityService =  processEngine.getIdentityService();
    Assert.assertNotNull(identityService);


    User user = identityService.createUserQuery().userEmail(USER_EMAIL).singleResult();
    Assert.assertNotNull(user);
    Assert.assertEquals(user.getFirstName(), USER_FIRST_NAME);
    Assert.assertEquals(user.getLastName(), USER_LAST_NAME);
}
 

}

This test checks that users created in Liferay can be brought into Flowable, using the following class:

 public class FlowableUserManager implements UserEntityManager{
private IAuthorizationService<Long, Long, Long> authorizationService;
private IAuthenticationService<Long, Long> authenticationService;
private IGroupToActivityRoleConverter groupToActivityConverter;


public FlowableUserManager(IAuthorizationService<Long, Long, Long> authorizationService, IAuthenticationService<Long, Long> authenticationService,
        IGroupToActivityRoleConverter groupToActivityConverter) {
    this.authorizationService = authorizationService;
    this.authenticationService = authenticationService;
    this.groupToActivityConverter = groupToActivityConverter;
}


public static UserEntity getActivitiUser(IUser<Long> liferayUser) {
    if (liferayUser instanceof User) {
        return getActivitiUser((User) liferayUser);
    }
    return null;
}

public static UserEntity getActivitiUser(User liferayUser) {
    if (liferayUser == null) {
        return null;
    }
    UserEntityImpl activitiUser = new UserEntityImpl();
    activitiUser.setEmail(liferayUser.getEmailAddress());
    activitiUser.setFirstName(liferayUser.getFirstName());
    activitiUser.setId(liferayUser.getUniqueId()   "");
    activitiUser.setLastName(liferayUser.getLastName());
    activitiUser.setPassword(liferayUser.getPassword());
    activitiUser.setPicture(new Picture(null, null));
    activitiUser.setRevision(0);

    return activitiUser;
}


public UserEntity findUserById(String userId) {
    try {
        IUser<Long> liferayUser = authenticationService.getUserById(Long.parseLong(userId));
        return getActivitiUser(liferayUser);
    } catch (NumberFormatException | UserManagementException e) {
        e.printStackTrace();
        FlowableUsersLogger.errorMessage(this.getClass().getName(), e);
    }
    return null;
}

private UserEntity findUserByEmail(String userEmail) {
    try {
        IUser<Long> liferayUser = authenticationService.getUserByEmail(userEmail);
        return getActivitiUser(liferayUser);
    } catch (NumberFormatException | UserManagementException | UserDoesNotExistException e) {
        FlowableUsersLogger.errorMessage(this.getClass().getName(), e);
    }
    return null;
}

@Override
public boolean isNewUser(org.flowable.idm.api.User user) {
    return false;
}

@Override
public Picture getUserPicture(org.flowable.idm.api.User user) {
    return null;
}

@Override
public void setUserPicture(org.flowable.idm.api.User user, Picture picture) {

}

@Override
public void deletePicture(org.flowable.idm.api.User user) {

}

@Override
public List<org.flowable.idm.api.User> findUsersByPrivilegeId(String s) {
    return null;
}


public List<org.flowable.idm.api.Group> findGroupsByUser(String userId) {
    List<org.flowable.idm.api.Group> activitiGroups = new ArrayList<>();

    IUser<Long> liferayUser;
    try {
        liferayUser = authenticationService.getUserById(Long.parseLong(userId));
        Set<IRole<Long>> liferayRoles = authorizationService.getUserRoles(liferayUser);
        for (IRole<Long> liferayRole : liferayRoles) {
            activitiGroups.add(FlowableGroupManager.getActivitiGroup(liferayRole, groupToActivityConverter));
        }
    } catch (NumberFormatException | UserManagementException e) {
        FlowableUsersLogger.errorMessage(this.getClass().getName(), e);
    }
    return activitiGroups;
}


public Boolean checkPassword(String userId, String password) {
    IUser<Long> liferayUser;
    try {
        liferayUser = authenticationService.getUserById(Long.parseLong(userId));
        return authenticationService.authenticate(liferayUser.getEmailAddress(), password) != null;
    } catch (NumberFormatException | InvalidCredentialsException | UserManagementException | AuthenticationRequired | UserDoesNotExistException e) {
        FlowableUsersLogger.errorMessage(this.getClass().getName(), e);
    }
    return false;
}


public void insertUser(org.flowable.idm.api.User user) {
    throw new UnsupportedOperationException();
}

@Override
public void updateUser(org.flowable.idm.api.User updatedUser) {
    throw new UnsupportedOperationException();
}

@Override
public List<org.flowable.idm.api.User> findUserByQueryCriteria(UserQueryImpl userQuery) {
    return null;
}

@Override
public UserEntity createNewUser(String userId) {
    throw new UnsupportedOperationException();
}


public void deleteUser(String userId) {
    throw new UnsupportedOperationException();
}


public IdentityInfoEntity findUserInfoByUserIdAndKey(String userId, String key) {
    throw new UnsupportedOperationException();
}


public List<String> findUserInfoKeysByUserIdAndType(String userId, String type) {
    throw new UnsupportedOperationException();
}


public List<org.flowable.idm.api.User> findUserByQueryCriteria(UserQueryImpl query, Page page) {
    List<org.flowable.idm.api.User> userList = new ArrayList<org.flowable.idm.api.User>();
    UserQueryImpl userQuery = (UserQueryImpl) query;
    if (!StringUtils.isEmpty(userQuery.getId())) {
        userList.add(findUserById(userQuery.getId()));
        return userList;
    } else if (!StringUtils.isEmpty(userQuery.getEmail())) {
        userList.add(findUserByEmail(userQuery.getEmail()));
        return userList;
    } else {
        Set<IUser<Long>> liferayUsers;
        try {
            liferayUsers = authorizationService.getAllUsers();
            for (IUser<Long> liferayUser : liferayUsers) {
                userList.add(getActivitiUser(liferayUser));
            }
            return userList;
        } catch (UserManagementException e) {
            FlowableUsersLogger.errorMessage(this.getClass().getName(), e);
        }
    }
    return null;
}

@Override
public long findUserCountByQueryCriteria(UserQueryImpl query) {
    return findUserByQueryCriteria(query, null).size();
}

@Override
public UserQuery createNewUserQuery() {
    return null;
}

@Override
public Boolean checkPassword(String s, String s1, PasswordEncoder passwordEncoder, PasswordSalt passwordSalt) {
    return null;
}

@Override
public List<org.flowable.idm.api.User> findUsersByNativeQuery(Map<String, Object> map) {
    return null;
}


public List<org.flowable.idm.api.User> findPotentialStarterUsers(String proceDefId) {
    throw new UnsupportedOperationException();
}


public List<org.flowable.idm.api.User> findUsersByNativeQuery(Map<String, Object> parameterMap, int firstResult, int maxResults) {
    throw new UnsupportedOperationException();
}

@Override
public long findUserCountByNativeQuery(Map<String, Object> parameterMap) {
    throw new UnsupportedOperationException();
}


public Picture getUserPicture(String userId) {
    return null;

}

public void setUserPicture(String userId, Picture picture) {
    throw new UnsupportedOperationException();
}

public IAuthorizationService<Long, Long, Long> getAuthorizationService() {
    return authorizationService;
}

public void setAuthorizationService(IAuthorizationService<Long, Long, Long> authorizationService) {
    this.authorizationService = authorizationService;
}


@Override
public UserEntity create() {
    return null;
}

@Override
public UserEntity findById(String s) {
    return null;
}

@Override
public void insert(UserEntity entity) {

}

@Override
public void insert(UserEntity entity, boolean b) {

}

@Override
public UserEntity update(UserEntity entity) {
    return null;
}

@Override
public UserEntity update(UserEntity entity, boolean b) {
    return null;
}

@Override
public void delete(String s) {

}

@Override
public void delete(UserEntity entity) {

}

@Override
public void delete(UserEntity entity, boolean b) {

}
 

}

Ошибка:

 FlowableUsersTest>AbstractTestNGSpringContextTests.run:184->getLiferayUserAsFlowable:38 null
 FlowableUsersTest>AbstractTestNGSpringContextTests.run:184->getLiferayUserAsFlowableByEmail:51 null
 

Пользователи имеют значение null, когда они должны быть созданы. После отладки я обнаружил, что новый sessionfactory никогда не вызывает правильные методы. Когда я запускаю пошаговые тесты, мой пользовательский sessionfactory никогда не вызывается.

Похоже, что при добавлении свойства customSessionFactories оно неправильно настроено в контексте приложения, поскольку методы внутри классов никогда не используются.

Однако я не уверен, что ошибка есть, она может быть вызвана другим фактором. Я был бы признателен за любую возможную помощь.

Как я могу решить свою проблему?

Проблема вызвана свойством:customSessionFactories?

Спасибо!

Комментарии:

1. Это может быть простой вопрос, но вы убедились, что ваши новые фабрики сеансов включены в сканирование компонентов?