+ @Override
+ protected void prepare(WorkingCopy wc) {
+ try {
+ getLdapContext().reconnect(getLdapContext().getConnectControls());
+ // delete
+ for (LdapName dn : wc.getDeletedUsers().keySet()) {
+ if (!entryExists(dn))
+ throw new UserDirectoryException("User to delete no found "
+ + dn);
+ }
+ // add
+ for (LdapName dn : wc.getNewUsers().keySet()) {
+ if (!entryExists(dn))
+ throw new UserDirectoryException("User to create found "
+ + dn);
+ }
+ // modify
+ for (LdapName dn : wc.getModifiedUsers().keySet()) {
+ if (!entryExists(dn))
+ throw new UserDirectoryException("User to modify no found "
+ + dn);
+ }
+ } catch (NamingException e) {
+ throw new UserDirectoryException("Cannot prepare LDAP", e);
+ }
+ }
+
+ private boolean entryExists(LdapName dn) throws NamingException {
+ return getLdapContext().getAttributes(dn).size() != 0;
+ }
+
+ @Override
+ protected void commit(WorkingCopy wc) {
+ try {
+ // delete
+ for (LdapName dn : wc.getDeletedUsers().keySet()) {
+ getLdapContext().destroySubcontext(dn);
+ }
+ // add
+ for (LdapName dn : wc.getNewUsers().keySet()) {
+ DirectoryUser user = wc.getNewUsers().get(dn);
+ getLdapContext().createSubcontext(dn, user.getAttributes());
+ }
+ // modify
+ for (LdapName dn : wc.getModifiedUsers().keySet()) {
+ Attributes modifiedAttrs = wc.getModifiedUsers().get(dn);
+ getLdapContext().modifyAttributes(dn,
+ DirContext.REPLACE_ATTRIBUTE, modifiedAttrs);
+ }
+ } catch (NamingException e) {
+ throw new UserDirectoryException("Cannot commit LDAP", e);
+ }