Authorizable a = userManager.getAuthorizable(userId);
if (a == null || a.isGroup()) {
throw new RepositoryException(userId + " does not represent a valid user.");
}
Impersonation imp = checkNotNull(((User) a).getImpersonation());
// 1. collect principals to add and to remove.
Map<String, Principal> toRemove = new HashMap<String, Principal>();
for (PrincipalIterator pit = imp.getImpersonators(); pit.hasNext(); ) {
Principal princ = pit.nextPrincipal();
toRemove.put(princ.getName(), princ);
}
List<String> toAdd = new ArrayList<String>();
for (final String principalName : principalNames) {
if (toRemove.remove(principalName) == null) {
// add it to the list of new impersonators to be added.
toAdd.add(principalName);
} // else: no need to revoke impersonation for the given principal.
}
// 2. adjust set of impersonators
for (Principal princicpal : toRemove.values()) {
if (!imp.revokeImpersonation(princicpal)) {
String principalName = princicpal.getName();
handleFailure("Failed to revoke impersonation for " + principalName + " on " + a);
}
}
List<String> nonExisting = new ArrayList<String>();
for (String principalName : toAdd) {
Principal principal = (principals.containsKey(principalName)) ?
principals.get(principalName) :
new PrincipalImpl(principalName);
if (!imp.grantImpersonation(principal)) {
handleFailure("Failed to grant impersonation for " + principalName + " on " + a);
if (importBehavior == ImportBehavior.BESTEFFORT &&
getPrincipalManager().getPrincipal(principalName) == null) {
log.info("ImportBehavior.BESTEFFORT: Remember non-existing impersonator for special processing.");
nonExisting.add(principalName);