Example usage for javax.naming.directory DirContext REMOVE_ATTRIBUTE

List of usage examples for javax.naming.directory DirContext REMOVE_ATTRIBUTE

Introduction

In this page you can find the example usage for javax.naming.directory DirContext REMOVE_ATTRIBUTE.

Prototype

int REMOVE_ATTRIBUTE

To view the source code for javax.naming.directory DirContext REMOVE_ATTRIBUTE.

Click Source Link

Document

This constant specifies to delete the specified attribute values from the attribute.

Usage

From source file:org.ligoj.app.plugin.id.ldap.dao.GroupLdapRepository.java

/**
 * Remove an "uniqueMember" from given group. Cache is not updated there.
 *
 * @param uniqueMember// ww w .  j  a v a 2 s  . co m
 *            DN of the member to remove.
 * @param group
 *            CN of the group to update. Must be normalized.
 * @return the {@link GroupOrg} where the member has just been removed from.
 */
private GroupOrg removeMember(final ResourceOrg uniqueMember, final String group) {
    final GroupOrg groupLdap = findById(group);
    if (groupLdap.getMembers().contains(uniqueMember.getId())
            || groupLdap.getSubGroups().contains(uniqueMember.getId())) {
        // Not useless LDAP operation, avoid LDAP duplicate deletion
        final ModificationItem[] mods = new ModificationItem[1];
        mods[0] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE,
                new BasicAttribute(UNIQUE_MEMBER, uniqueMember.getDn()));
        try {
            template.modifyAttributes(org.springframework.ldap.support.LdapUtils.newLdapName(groupLdap.getDn()),
                    mods);
        } catch (final org.springframework.ldap.AttributeInUseException aiue) {
            // Even if the membership update failed, the user does not exist anymore. A broken reference can remains
            // in LDAP, but this case is well managed.
            log.info("Unable to remove user {} from the group {} : {}", uniqueMember.getDn(), group, aiue);
        } catch (final org.springframework.ldap.SchemaViolationException sve) { // NOSONAR - Exception is logged
            // Occurs when there is a LDAP schema violation such as as last member removed
            log.warn("Unable to remove user {} from the group {}", uniqueMember.getDn(), group, sve);
            throw new ValidationJsonException("groups", "last-member-of-group", "user", uniqueMember.getId(),
                    "group", group);
        }
    }
    return groupLdap;
}

From source file:org.mule.module.ldap.api.jndi.LDAPJNDIConnection.java

/**
 * @param dn//  ww w.j  a v  a2 s . c o  m
 * @param attribute
 * @throws LDAPException
 * @see org.mule.module.ldap.api.LDAPConnection#deleteAttribute(java.lang.String,
 *      org.mule.module.ldap.api.LDAPEntryAttribute)
 */
public void deleteAttribute(String dn, LDAPEntryAttribute attribute) throws LDAPException {
    try {
        ModificationItem[] mods = new ModificationItem[1];
        mods[0] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, buildBasicAttribute(attribute));
        getConn().modifyAttributes(dn, mods);
    } catch (NamingException nex) {
        throw handleNamingException(nex, "Delete attribute failed.");
    }
}

From source file:org.nuxeo.ecm.directory.ldap.LDAPReference.java

/**
 * Store new links using the LDAP staticAttributeId strategy.
 *
 * @see org.nuxeo.ecm.directory.Reference#addLinks(String, List)
 *///from   w  w w  .j  av  a 2  s . c o m
@Override
public void addLinks(String sourceId, List<String> targetIds) throws DirectoryException {

    if (targetIds.isEmpty()) {
        // optim: nothing to do, return silently without further creating
        // session instances
        return;
    }

    LDAPDirectory ldapTargetDirectory = (LDAPDirectory) getTargetDirectory();
    LDAPDirectory ldapSourceDirectory = (LDAPDirectory) getSourceDirectory();
    String attributeId = getStaticAttributeId();
    if (attributeId == null) {
        if (log.isTraceEnabled()) {
            log.trace(String.format("trying to edit a non-static reference from %s in directory %s: ignoring",
                    sourceId, ldapSourceDirectory.getName()));
        }
        return;
    }
    try (LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession();
            LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession()) {
        // fetch the entry to be able to run the security policy
        // implemented in an entry adaptor
        DocumentModel sourceEntry = sourceSession.getEntry(sourceId, false);
        if (sourceEntry == null) {
            throw new DirectoryException(String.format("could not add links from unexisting %s in directory %s",
                    sourceId, ldapSourceDirectory.getName()));
        }
        if (!BaseSession.isReadOnlyEntry(sourceEntry)) {
            SearchResult ldapEntry = sourceSession.getLdapEntry(sourceId);

            String sourceDn = ldapEntry.getNameInNamespace();
            Attribute storedAttr = ldapEntry.getAttributes().get(attributeId);
            String emptyRefMarker = ldapSourceDirectory.getDescriptor().getEmptyRefMarker();
            Attribute attrToAdd = new BasicAttribute(attributeId);
            for (String targetId : targetIds) {
                if (staticAttributeIdIsDn) {
                    // TODO optim: avoid LDAP search request when targetDn
                    // can be forged client side (rdnAttribute = idAttribute and scope is onelevel)
                    ldapEntry = targetSession.getLdapEntry(targetId);
                    if (ldapEntry == null) {
                        log.warn(String.format(
                                "entry '%s' in directory '%s' not found: could not add link from '%s' in directory '%s' for '%s'",
                                targetId, ldapTargetDirectory.getName(), sourceId,
                                ldapSourceDirectory.getName(), this));
                        continue;
                    }
                    String dn = ldapEntry.getNameInNamespace();
                    if (storedAttr == null || !storedAttr.contains(dn)) {
                        attrToAdd.add(dn);
                    }
                } else {
                    if (storedAttr == null || !storedAttr.contains(targetId)) {
                        attrToAdd.add(targetId);
                    }
                }
            }
            if (attrToAdd.size() > 0) {
                try {
                    // do the LDAP request to store missing dns
                    Attributes attrsToAdd = new BasicAttributes();
                    attrsToAdd.put(attrToAdd);

                    if (log.isDebugEnabled()) {
                        log.debug(String.format(
                                "LDAPReference.addLinks(%s, [%s]): LDAP modifyAttributes dn='%s' "
                                        + "mod_op='ADD_ATTRIBUTE' attrs='%s' [%s]",
                                sourceId, StringUtils.join(targetIds, ", "), sourceDn, attrsToAdd, this));
                    }
                    sourceSession.dirContext.modifyAttributes(sourceDn, DirContext.ADD_ATTRIBUTE, attrsToAdd);

                    // robustly clean any existing empty marker now that we are sure that the list in not empty
                    if (storedAttr.contains(emptyRefMarker)) {
                        Attributes cleanAttrs = new BasicAttributes(attributeId, emptyRefMarker);

                        if (log.isDebugEnabled()) {
                            log.debug(String.format(
                                    "LDAPReference.addLinks(%s, [%s]): LDAP modifyAttributes dn='%s'"
                                            + " mod_op='REMOVE_ATTRIBUTE' attrs='%s' [%s]",
                                    sourceId, StringUtils.join(targetIds, ", "), sourceDn, cleanAttrs, this));
                        }
                        sourceSession.dirContext.modifyAttributes(sourceDn, DirContext.REMOVE_ATTRIBUTE,
                                cleanAttrs);
                    }
                } catch (SchemaViolationException e) {
                    if (isDynamic()) {
                        // we are editing an entry that has no static part
                        log.warn(String.format("cannot update dynamic reference in field %s for source %s",
                                getFieldName(), sourceId));
                    } else {
                        // this is a real schema configuration problem,
                        // wrap up the exception
                        throw new DirectoryException(e);
                    }
                }
            }
        }
    } catch (NamingException e) {
        throw new DirectoryException("addLinks failed: " + e.getMessage(), e);
    }
}

From source file:org.nuxeo.ecm.directory.ldap.LDAPReference.java

/**
 * Store new links using the LDAP staticAttributeId strategy.
 *
 * @see org.nuxeo.ecm.directory.Reference#addLinks(List, String)
 *//*from   ww  w .  j a  v a 2  s .  c  o m*/
@Override
public void addLinks(List<String> sourceIds, String targetId) throws DirectoryException {
    String attributeId = getStaticAttributeId();
    if (attributeId == null && !sourceIds.isEmpty()) {
        log.warn("trying to edit a non-static reference: ignoring");
        return;
    }
    LDAPDirectory ldapTargetDirectory = (LDAPDirectory) getTargetDirectory();
    LDAPDirectory ldapSourceDirectory = (LDAPDirectory) getSourceDirectory();

    String emptyRefMarker = ldapSourceDirectory.getDescriptor().getEmptyRefMarker();
    try (LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession();
            LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession()) {
        if (!sourceSession.isReadOnly()) {
            // compute the target dn to add to all the matching source
            // entries
            SearchResult ldapEntry = targetSession.getLdapEntry(targetId);
            if (ldapEntry == null) {
                throw new DirectoryException(
                        String.format("could not add links to unexisting %s in directory %s", targetId,
                                ldapTargetDirectory.getName()));
            }
            String targetAttributeValue;
            if (staticAttributeIdIsDn) {
                targetAttributeValue = ldapEntry.getNameInNamespace();
            } else {
                targetAttributeValue = targetId;
            }

            for (String sourceId : sourceIds) {
                // fetch the entry to be able to run the security policy
                // implemented in an entry adaptor
                DocumentModel sourceEntry = sourceSession.getEntry(sourceId, false);
                if (sourceEntry == null) {
                    log.warn(String.format(
                            "entry %s in directory %s not found: could not add link to %s in directory %s",
                            sourceId, ldapSourceDirectory.getName(), targetId, ldapTargetDirectory.getName()));
                    continue;
                }
                if (BaseSession.isReadOnlyEntry(sourceEntry)) {
                    // skip this entry since it cannot be edited to add the
                    // reference to targetId
                    log.warn(String.format(
                            "entry %s in directory %s is readonly: could not add link to %s in directory %s",
                            sourceId, ldapSourceDirectory.getName(), targetId, ldapTargetDirectory.getName()));
                    continue;
                }
                ldapEntry = sourceSession.getLdapEntry(sourceId);
                String sourceDn = ldapEntry.getNameInNamespace();
                Attribute storedAttr = ldapEntry.getAttributes().get(attributeId);
                if (storedAttr.contains(targetAttributeValue)) {
                    // no need to readd
                    continue;
                }
                try {
                    // add the new dn
                    Attributes attrs = new BasicAttributes(attributeId, targetAttributeValue);

                    if (log.isDebugEnabled()) {
                        log.debug(String.format(
                                "LDAPReference.addLinks([%s], %s): LDAP modifyAttributes dn='%s'"
                                        + " mod_op='ADD_ATTRIBUTE' attrs='%s' [%s]",
                                StringUtils.join(sourceIds, ", "), targetId, sourceDn, attrs, this));
                    }
                    sourceSession.dirContext.modifyAttributes(sourceDn, DirContext.ADD_ATTRIBUTE, attrs);

                    // robustly clean any existing empty marker now that we
                    // are sure that the list in not empty
                    if (storedAttr.contains(emptyRefMarker)) {
                        Attributes cleanAttrs = new BasicAttributes(attributeId, emptyRefMarker);
                        if (log.isDebugEnabled()) {
                            log.debug(String.format(
                                    "LDAPReference.addLinks(%s, %s): LDAP modifyAttributes dn='%s'"
                                            + " mod_op='REMOVE_ATTRIBUTE' attrs='%s' [%s]",
                                    StringUtils.join(sourceIds, ", "), targetId, sourceDn,
                                    cleanAttrs.toString(), this));
                        }
                        sourceSession.dirContext.modifyAttributes(sourceDn, DirContext.REMOVE_ATTRIBUTE,
                                cleanAttrs);
                    }
                } catch (SchemaViolationException e) {
                    if (isDynamic()) {
                        // we are editing an entry that has no static part
                        log.warn(String.format("cannot add dynamic reference in field %s for target %s",
                                getFieldName(), targetId));
                    } else {
                        // this is a real schema configuration problem,
                        // wrap the exception
                        throw new DirectoryException(e);
                    }
                }
            }
        }
    } catch (NamingException e) {
        throw new DirectoryException("addLinks failed: " + e.getMessage(), e);
    }
}

From source file:org.nuxeo.ecm.directory.ldap.LDAPReference.java

/**
 * Remove existing statically defined links for the given source id (dynamic references remain unaltered)
 *
 * @see org.nuxeo.ecm.directory.Reference#removeLinksForSource(String)
 *//* w  ww  . j  a v a 2  s.  com*/
@Override
public void removeLinksForSource(String sourceId) throws DirectoryException {
    LDAPDirectory ldapTargetDirectory = (LDAPDirectory) getTargetDirectory();
    LDAPDirectory ldapSourceDirectory = (LDAPDirectory) getSourceDirectory();
    String attributeId = getStaticAttributeId();
    try (LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession();
            LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession()) {
        if (sourceSession.isReadOnly() || attributeId == null) {
            // do not try to do anything on a read only server or to a
            // purely dynamic reference
            return;
        }
        // get the dn of the entry that matches sourceId
        SearchResult sourceLdapEntry = sourceSession.getLdapEntry(sourceId);
        if (sourceLdapEntry == null) {
            throw new DirectoryException(
                    String.format("cannot edit the links hold by missing entry '%s' in directory '%s'",
                            sourceId, ldapSourceDirectory.getName()));
        }
        String sourceDn = pseudoNormalizeDn(sourceLdapEntry.getNameInNamespace());

        Attribute oldAttr = sourceLdapEntry.getAttributes().get(attributeId);
        if (oldAttr == null) {
            // consider it as an empty attribute to simplify the following
            // code
            oldAttr = new BasicAttribute(attributeId);
        }
        Attribute attrToRemove = new BasicAttribute(attributeId);

        NamingEnumeration<?> oldAttrs = oldAttr.getAll();
        String targetBaseDn = pseudoNormalizeDn(ldapTargetDirectory.getDescriptor().getSearchBaseDn());
        try {
            while (oldAttrs.hasMore()) {
                String targetKeyAttr = oldAttrs.next().toString();

                if (staticAttributeIdIsDn) {
                    String dn = pseudoNormalizeDn(targetKeyAttr);
                    if (forceDnConsistencyCheck) {
                        String id = getIdForDn(targetSession, dn);
                        if (id != null && targetSession.hasEntry(id)) {
                            // this is an entry managed by the current
                            // reference
                            attrToRemove.add(dn);
                        }
                    } else if (dn.endsWith(targetBaseDn)) {
                        // this is an entry managed by the current
                        // reference
                        attrToRemove.add(dn);
                    }
                } else {
                    attrToRemove.add(targetKeyAttr);
                }
            }
        } finally {
            oldAttrs.close();
        }
        try {
            if (attrToRemove.size() == oldAttr.size()) {
                // use the empty ref marker to avoid empty attr
                String emptyRefMarker = ldapSourceDirectory.getDescriptor().getEmptyRefMarker();
                Attributes emptyAttribute = new BasicAttributes(attributeId, emptyRefMarker);
                if (log.isDebugEnabled()) {
                    log.debug(String.format(
                            "LDAPReference.removeLinksForSource(%s): LDAP modifyAttributes key='%s' "
                                    + " mod_op='REPLACE_ATTRIBUTE' attrs='%s' [%s]",
                            sourceId, sourceDn, emptyAttribute, this));
                }
                sourceSession.dirContext.modifyAttributes(sourceDn, DirContext.REPLACE_ATTRIBUTE,
                        emptyAttribute);
            } else if (attrToRemove.size() > 0) {
                // remove the attribute managed by the current reference
                Attributes attrsToRemove = new BasicAttributes();
                attrsToRemove.put(attrToRemove);
                if (log.isDebugEnabled()) {
                    log.debug(String.format(
                            "LDAPReference.removeLinksForSource(%s): LDAP modifyAttributes dn='%s' "
                                    + " mod_op='REMOVE_ATTRIBUTE' attrs='%s' [%s]",
                            sourceId, sourceDn, attrsToRemove, this));
                }
                sourceSession.dirContext.modifyAttributes(sourceDn, DirContext.REMOVE_ATTRIBUTE, attrsToRemove);
            }
        } catch (SchemaViolationException e) {
            if (isDynamic()) {
                // we are editing an entry that has no static part
                log.warn(String.format("cannot remove dynamic reference in field %s for source %s",
                        getFieldName(), sourceId));
            } else {
                // this is a real schma configuration problem, wrapup the
                // exception
                throw new DirectoryException(e);
            }
        }
    } catch (NamingException e) {
        throw new DirectoryException("removeLinksForSource failed: " + e.getMessage(), e);
    }
}

From source file:org.nuxeo.ecm.directory.ldap.LDAPReference.java

/**
 * Remove existing statically defined links for the given target id (dynamic references remain unaltered)
 *
 * @see org.nuxeo.ecm.directory.Reference#removeLinksForTarget(String)
 */// ww  w  . j  a v a  2s.c o  m
@Override
public void removeLinksForTarget(String targetId) throws DirectoryException {
    if (!isStatic()) {
        // nothing to do: dynamic references cannot be updated
        return;
    }
    LDAPDirectory ldapTargetDirectory = (LDAPDirectory) getTargetDirectory();
    LDAPDirectory ldapSourceDirectory = (LDAPDirectory) getSourceDirectory();
    String attributeId = getStaticAttributeId();
    try (LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession();
            LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession()) {
        if (!sourceSession.isReadOnly()) {
            // get the dn of the target that matches targetId
            String targetAttributeValue;

            if (staticAttributeIdIsDn) {
                SearchResult targetLdapEntry = targetSession.getLdapEntry(targetId);
                if (targetLdapEntry == null) {
                    String rdnAttribute = ldapTargetDirectory.getDescriptor().getRdnAttribute();
                    if (!rdnAttribute.equals(targetSession.idAttribute)) {
                        log.warn(String.format(
                                "cannot remove links to missing entry %s in directory %s for reference %s",
                                targetId, ldapTargetDirectory.getName(), this));
                        return;
                    }
                    // the entry might have already been deleted, try to
                    // re-forge it if possible (might not work if scope is
                    // subtree)
                    targetAttributeValue = String.format("%s=%s,%s", rdnAttribute, targetId,
                            ldapTargetDirectory.getDescriptor().getSearchBaseDn());
                } else {
                    targetAttributeValue = pseudoNormalizeDn(targetLdapEntry.getNameInNamespace());
                }
            } else {
                targetAttributeValue = targetId;
            }

            // build a LDAP query to find entries that point to the target
            String searchFilter = String.format("(%s=%s)", attributeId, targetAttributeValue);
            String sourceFilter = ldapSourceDirectory.getBaseFilter();

            if (sourceFilter != null && !"".equals(sourceFilter)) {
                searchFilter = String.format("(&(%s)(%s))", searchFilter, sourceFilter);
            }

            SearchControls scts = new SearchControls();
            scts.setSearchScope(ldapSourceDirectory.getDescriptor().getSearchScope());
            scts.setReturningAttributes(new String[] { attributeId });

            // find all source entries that point to the target key and
            // clean
            // those references
            if (log.isDebugEnabled()) {
                log.debug(String.format(
                        "LDAPReference.removeLinksForTarget(%s): LDAP search baseDn='%s' "
                                + " filter='%s' scope='%s' [%s]",
                        targetId, sourceSession.searchBaseDn, searchFilter, scts.getSearchScope(), this));
            }
            NamingEnumeration<SearchResult> results = sourceSession.dirContext
                    .search(sourceSession.searchBaseDn, searchFilter, scts);
            String emptyRefMarker = ldapSourceDirectory.getDescriptor().getEmptyRefMarker();
            Attributes emptyAttribute = new BasicAttributes(attributeId, emptyRefMarker);

            try {
                while (results.hasMore()) {
                    SearchResult result = results.next();
                    Attributes attrs = result.getAttributes();
                    Attribute attr = attrs.get(attributeId);
                    try {
                        if (attr.size() == 1) {
                            // the attribute holds the last reference, put
                            // the
                            // empty ref. marker before removing the
                            // attribute
                            // since empty attribute are often not allowed
                            // by
                            // the server schema
                            if (log.isDebugEnabled()) {
                                log.debug(String.format(
                                        "LDAPReference.removeLinksForTarget(%s): LDAP modifyAttributes key='%s' "
                                                + "mod_op='ADD_ATTRIBUTE' attrs='%s' [%s]",
                                        targetId, result.getNameInNamespace(), attrs, this));
                            }
                            sourceSession.dirContext.modifyAttributes(result.getNameInNamespace(),
                                    DirContext.ADD_ATTRIBUTE, emptyAttribute);
                        }
                        // remove the reference to the target key
                        attrs = new BasicAttributes();
                        attr = new BasicAttribute(attributeId);
                        attr.add(targetAttributeValue);
                        attrs.put(attr);
                        if (log.isDebugEnabled()) {
                            log.debug(String.format(
                                    "LDAPReference.removeLinksForTarget(%s): LDAP modifyAttributes key='%s' "
                                            + "mod_op='REMOVE_ATTRIBUTE' attrs='%s' [%s]",
                                    targetId, result.getNameInNamespace(), attrs, this));
                        }
                        sourceSession.dirContext.modifyAttributes(result.getNameInNamespace(),
                                DirContext.REMOVE_ATTRIBUTE, attrs);
                    } catch (SchemaViolationException e) {
                        if (isDynamic()) {
                            // we are editing an entry that has no static
                            // part
                            log.warn(String.format("cannot remove dynamic reference in field %s for target %s",
                                    getFieldName(), targetId));
                        } else {
                            // this is a real schema configuration problem,
                            // wrapup the exception
                            throw new DirectoryException(e);
                        }
                    }
                }
            } finally {
                results.close();
            }
        }
    } catch (NamingException e) {
        throw new DirectoryException("removeLinksForTarget failed: " + e.getMessage(), e);
    }
}

From source file:org.nuxeo.ecm.directory.ldap.LDAPSession.java

@Override
@SuppressWarnings("unchecked")
public void updateEntry(DocumentModel docModel) {
    checkPermission(SecurityConstants.WRITE);
    List<String> updateList = new ArrayList<String>();
    List<String> referenceFieldList = new LinkedList<String>();

    try {//from  w  w w .ja  v a2s  . c o  m
        for (String fieldName : schemaFieldMap.keySet()) {
            if (!docModel.getPropertyObject(schemaName, fieldName).isDirty()) {
                continue;
            }
            if (getDirectory().isReference(fieldName)) {
                referenceFieldList.add(fieldName);
            } else {
                updateList.add(fieldName);
            }
        }

        if (!isReadOnlyEntry(docModel) && !updateList.isEmpty()) {
            Attributes attrs = new BasicAttributes();
            SearchResult ldapEntry = getLdapEntry(docModel.getId());
            if (ldapEntry == null) {
                throw new DirectoryException(docModel.getId() + " not found");
            }
            Attributes oldattrs = ldapEntry.getAttributes();
            String dn = ldapEntry.getNameInNamespace();
            Attributes attrsToDel = new BasicAttributes();
            for (String f : updateList) {
                Object value = docModel.getProperty(schemaName, f);
                String backendField = getDirectory().getFieldMapper().getBackendField(f);
                if (LDAPDirectory.DN_SPECIAL_ATTRIBUTE_KEY.equals(backendField)) {
                    // skip special LDAP DN field that is readonly
                    log.warn(String.format("field %s is mapped to read only DN field: ignored", f));
                    continue;
                }
                if (value == null || value.equals("")) {
                    Attribute objectClasses = oldattrs.get("objectClass");
                    Attribute attr;
                    if (getMandatoryAttributes(objectClasses).contains(backendField)) {
                        attr = new BasicAttribute(backendField);
                        // XXX: this might fail if the mandatory attribute
                        // is typed integer for instance
                        attr.add(" ");
                        attrs.put(attr);
                    } else if (oldattrs.get(backendField) != null) {
                        attr = new BasicAttribute(backendField);
                        attr.add(oldattrs.get(backendField).get());
                        attrsToDel.put(attr);
                    }
                } else if (f.equals(getPasswordField())) {
                    // The password has been updated, it has to be encrypted
                    Attribute attr = new BasicAttribute(backendField);
                    attr.add(PasswordHelper.hashPassword((String) value, passwordHashAlgorithm));
                    attrs.put(attr);
                } else {
                    attrs.put(getAttributeValue(f, value));
                }
            }

            if (log.isDebugEnabled()) {
                log.debug(String.format("LDAPSession.updateEntry(%s): LDAP modifyAttributes dn='%s' "
                        + "mod_op='REMOVE_ATTRIBUTE' attr='%s' [%s]", docModel, dn, attrsToDel, this));
            }
            dirContext.modifyAttributes(dn, DirContext.REMOVE_ATTRIBUTE, attrsToDel);

            if (log.isDebugEnabled()) {
                log.debug(String.format("LDAPSession.updateEntry(%s): LDAP modifyAttributes dn='%s' "
                        + "mod_op='REPLACE_ATTRIBUTE' attr='%s' [%s]", docModel, dn, attrs, this));
            }
            dirContext.modifyAttributes(dn, DirContext.REPLACE_ATTRIBUTE, attrs);
        }

        // update reference fields
        for (String referenceFieldName : referenceFieldList) {
            List<Reference> references = directory.getReferences(referenceFieldName);
            if (references.size() > 1) {
                // not supported
            } else {
                Reference reference = references.get(0);
                List<String> targetIds = (List<String>) docModel.getProperty(schemaName, referenceFieldName);
                reference.setTargetIdsForSource(docModel.getId(), targetIds);
            }
        }
    } catch (NamingException e) {
        handleException(e, "updateEntry failed:");
    }
    getDirectory().invalidateCaches();
}

From source file:org.projectforge.business.ldap.LdapUserDao.java

public void changePassword(final LdapUser user, final String oldPassword, final String newPassword) {
    log.info("Change password for " + getObjectClass() + ": " + buildDn(null, user));
    final List<ModificationItem> modificationItems = new ArrayList<ModificationItem>();
    if (oldPassword != null) {
        modificationItems.add(new ModificationItem(DirContext.REMOVE_ATTRIBUTE,
                new BasicAttribute("userPassword", oldPassword)));
        modificationItems.add(new ModificationItem(DirContext.ADD_ATTRIBUTE,
                new BasicAttribute("userPassword", newPassword)));
    } else {//from w ww. ja  v a 2 s .com
        modificationItems.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                new BasicAttribute("userPassword", newPassword)));
    }
    if (isSambaAccountsConfigured() == true && user.getSambaSIDNumber() != null) {
        final String sambaNTPassword = SmbEncrypt.NTUNICODEHash(newPassword);
        modificationItems.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                new BasicAttribute("sambaNTPassword", sambaNTPassword)));
    }
    // Perform the update
    modify(user, modificationItems);
}

From source file:org.sonar.plugins.activedirectory.server.ApacheDS.java

@SuppressWarnings("unused")
private ApacheDS startKerberos() throws Exception {
    Preconditions.checkState(ldapServer.isStarted());

    kdcServer.setDirectoryService(directoryService);
    // FIXME hard-coded ports
    kdcServer.setTransports(new TcpTransport(6088), new UdpTransport(6088));
    kdcServer.setEnabled(true);/*from  w  ww.  j a  v a  2  s.co  m*/
    kdcServer.setPrimaryRealm(realm);
    kdcServer.setSearchBaseDn(baseDn);
    kdcServer.setKdcPrincipal("krbtgt/" + realm + "@" + baseDn);
    kdcServer.start();

    // -------------------------------------------------------------------
    // Enable the krb5kdc schema
    // -------------------------------------------------------------------

    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(DirectoryService.JNDI_KEY, directoryService);
    env.put(Context.INITIAL_CONTEXT_FACTORY, CoreContextFactory.class.getName());
    env.put(Context.PROVIDER_URL, ServerDNConstants.OU_SCHEMA_DN);
    InitialLdapContext schemaRoot = new InitialLdapContext(env, null);

    // check if krb5kdc is disabled
    Attributes krb5kdcAttrs = schemaRoot.getAttributes("cn=Krb5kdc");
    boolean isKrb5KdcDisabled = false;
    if (krb5kdcAttrs.get("m-disabled") != null) {
        isKrb5KdcDisabled = ((String) krb5kdcAttrs.get("m-disabled").get()).equalsIgnoreCase("TRUE");
    }

    // if krb5kdc is disabled then enable it
    if (isKrb5KdcDisabled) {
        Attribute disabled = new BasicAttribute("m-disabled");
        ModificationItem[] mods = new ModificationItem[] {
                new ModificationItem(DirContext.REMOVE_ATTRIBUTE, disabled) };
        schemaRoot.modifyAttributes("cn=Krb5kdc", mods);
    }
    return this;
}

From source file:org.sonar.plugins.activedirectory.server.ApacheDS.java

/**
 * This seems to be required for objectClass posixGroup.
 *//*from w w  w. j a  va2  s  .co  m*/
private ApacheDS activateNis() throws Exception {
    Preconditions.checkState(ldapServer.isStarted());

    Attribute disabled = new BasicAttribute("m-disabled", "TRUE");
    Attribute disabled2 = new BasicAttribute("m-disabled", "FALSE");
    ModificationItem[] mods = new ModificationItem[] {
            new ModificationItem(DirContext.REMOVE_ATTRIBUTE, disabled),
            new ModificationItem(DirContext.ADD_ATTRIBUTE, disabled2) };

    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, getUrl());

    DirContext ctx = new InitialDirContext(env);
    ctx.modifyAttributes("cn=nis,ou=schema", mods);

    return this;
}