{
user = getUserModule().findUserById(user.getId());
}
catch(NoSuchUserException e)
{
throw new IdentityException("Illegal state - cached user doesn't exist in identity store: ", e);
}
}
LDAPUserImpl ldapUser = (LDAPUserImpl)user;
userDNsToAdd.add(ldapUser.getDn());
}
catch(ClassCastException e)
{
throw new IdentityException("Can add only LDAPUserImpl objects", e);
}
}
String memberOfName=null;
//Find all the users that currently contain role as member (need to remove role from some of them)
if (isUidAttributeIsDN())
{
memberOfName = ldapRole.getDn();
}
else
{
memberOfName = ldapRole.getName();
}
LdapContext ldapContext = getConnectionContext().createInitialContext();
try
{
String filter = getMemberAttributeID().concat("=").concat(memberOfName);
log.debug("Search filter: " + filter);
List sr = getUserModule().searchUsers(filter, null);
//iterate over users that contain a role
for (Iterator iterator = sr.iterator(); iterator.hasNext();)
{
SearchResult res = (SearchResult)iterator.next();
DirContext ctx = (DirContext)res.getObject();
String userDN = ctx.getNameInNamespace();
ctx.close();
//if user is one which we want to add
if (userDNsToAdd.contains(userDN))
{
//we do nothing but mark this user as added
userDNsToAdd.remove(userDN);
continue;
}
//if it's not on the list we need to remove role from it
else
{
//obtain Role entry attributes from directory
Attributes attrs = ldapContext.getAttributes(userDN, new String[] {getMemberAttributeID()});
//log.debug("Role attributes: " + attrs);
if (attrs == null)
{
throw new IdentityException("Cannot find User with DN: " + userDN);
}
Attribute attr = attrs.get(getMemberAttributeID());
attr.remove(memberOfName);
//and replace attributes
Attributes newAttrs = new BasicAttributes(true);
//newAttrs.put(getMemberAttributeID(), attr);
newAttrs.put(attr);
ldapContext.modifyAttributes(userDN, DirContext.REPLACE_ATTRIBUTE, newAttrs);
//and mark this role as done
userDNsToAdd.remove(userDN);
}
}
//now iterate over roles that left to process
for (Iterator iterator = userDNsToAdd.iterator(); iterator.hasNext();)
{
String userDN = (String)iterator.next();
//changes to make
ModificationItem[] mods = new ModificationItem[1];
mods[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE,
new BasicAttribute(getMemberAttributeID(), memberOfName));
// Perform the requested modifications on the named object
ldapContext.modifyAttributes(userDN, mods);
}
fireMembershipChangedEvent(role, users);
//and that should be all...
}
catch (NamingException e)
{
throw new IdentityException("Failed to assign users", e);
}
finally
{
try
{
ldapContext.close();
}
catch (NamingException e)
{
throw new IdentityException("Failed to close LDAP connection", e);
}
}
}