Friday, May 29, 2015

OIM 11G R2 PS2 (11.1.2.2.0) - usr_key is a System Attribute and cannot be set through OIM API

In this post , I will talk about an error which will happens if we try to use the OIM API method userManager.modify() to modify the user object. and how to fix it.

Below is the sample code with comments and fix
public User searchUserOnLogin(String userLoginValue)
            throws UserSearchException, AccessDeniedException {
        User user = null;

        //Get User Manager Object in Event Handler or Scheduled Job
        UserManager um = Platform.getService(UserManager.class);

        SearchCriteria sc = new SearchCriteria(
                UserManagerConstants.AttributeName.USER_LOGIN.getId(),
                userLoginValue, SearchCriteria.Operator.EQUAL);

        Set<String> retAttrs = new HashSet<String>();

        retAttrs.add(UserManagerConstants.AttributeName.USER_LOGIN.getId());

        List<User> users = um.search(sc, retAttrs, null);

        if (users.size() == 1) {
            user = users.get(0);
        }

        return user;
    }

    public void modifyUser(User user) throws ValidationFailedException,
            UserModifyException, NoSuchUserException,
            SearchKeyNotUniqueException, AccessDeniedException {

        user.setEmployeeNumber("11000696");

        // um.modify(user); // This will throw exception as usr_key is by
        // default present in user object
        // to work around this issue create a new null user object
      
        User user2 = new User(null);
        // Set the User Login Value first
        user2.setAttribute(
                UserManagerConstants.AttributeName.USER_LOGIN.getId(),
                user.getLogin());

        // Set the value to the attribute that you want modify

        user2.setEmployeeNumber("11000696");

        // Now modify
        UserManager um = Platform.getService(UserManager.class);
        um.modify(UserManagerConstants.AttributeName.USER_LOGIN.getId(),
                user.getLogin(), user2);

        // below will not work as usr_key is present in user which I fetched
        // from search

        // um.modify(user);

    }