Example usage for javax.naming.directory DirContext REPLACE_ATTRIBUTE

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

Introduction

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

Prototype

int REPLACE_ATTRIBUTE

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

Click Source Link

Document

This constant specifies to replace an attribute with specified values.

Usage

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

/**
 * Lock an user :// ww w.j  av  a2  s .c om
 * <ul>
 * <li>Clear the password to prevent new authentication</li>
 * <li>Set the disabled flag.</li>
 * </ul>
 *
 * @param principal
 *            Principal user requesting the lock.
 * @param user
 *            The LDAP user to disable.
 * @param isolate
 *            When <code>true</code>, the user will be isolated in addition.
 */
private void lock(final String principal, final UserOrg user, final boolean isolate) {
    if (user.getLockedBy() == null) {
        // Not yet locked
        final ModificationItem[] mods = new ModificationItem[2];
        final long timeInMillis = DateUtils.newCalendar().getTimeInMillis();
        mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                new BasicAttribute(lockedAttribute, String.format("%s|%s|%s|%s|", lockedValue, timeInMillis,
                        principal, isolate ? user.getCompany() : "")));
        mods[1] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                new BasicAttribute(PASSWORD_ATTRIBUTE, null));
        template.modifyAttributes(org.springframework.ldap.support.LdapUtils.newLdapName(user.getDn()), mods);

        // Also update the disabled date
        user.setLocked(new Date(timeInMillis));
        user.setLockedBy(principal);
    }
}

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

@Override
public void setPassword(final UserOrg userLdap, final String password, final String newPassword) {
    log.info("Changing password for {} ...", userLdap.getId());
    final ModificationItem[] passwordChange = { new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
            new BasicAttribute(PASSWORD_ATTRIBUTE, digest(newPassword))) };

    // Unlock account when the user is locked by ppolicy
    set(userLdap, PWD_ACCOUNT_LOCKED_ATTRIBUTE, null);

    // Authenticate the user is needed before changing the password.
    template.executeReadWrite(new ContextExecutor<>() {
        @Override//from  ww w. j  a v  a2s. c om
        public Object executeWithContext(final DirContext dirCtx) throws NamingException {
            LdapContext ctx = (LdapContext) dirCtx;
            ctx.removeFromEnvironment(LDAP_CONNECT_POOL);
            ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userLdap.getDn());
            ctx.addToEnvironment(Context.SECURITY_CREDENTIALS,
                    password == null ? getTmpPassword(userLdap) : password);

            try {
                ctx.reconnect(null);
                ctx.modifyAttributes(userLdap.getDn(), passwordChange);
            } catch (final AuthenticationException e) {
                log.info("Authentication failed for {}: {}", userLdap.getId(), e.getMessage());
                throw new ValidationJsonException("password", "login");
            } catch (final InvalidAttributeValueException e) {
                log.info("Password change failed due to: {}", e.getMessage());
                throw new ValidationJsonException("password", "password-policy");
            }
            return null;
        }
    });
}

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

/**
 * @param entry//from w  ww .  j a  v a  2  s. co  m
 * @throws LDAPException
 * @see org.mule.module.ldap.api.LDAPConnection#updateEntry(org.mule.module.ldap.api.LDAPEntry)
 */
public void updateEntry(LDAPEntry entry) throws LDAPException {
    try {
        ModificationItem[] mods = new ModificationItem[entry.getAttributeCount()];
        Iterator<LDAPEntryAttribute> it = entry.attributes();
        for (int i = 0; it.hasNext() && i < mods.length; i++) {
            mods[i] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                    buildBasicAttribute(((LDAPEntryAttribute) it.next())));
        }
        getConn().modifyAttributes(entry.getDn(), mods);
    } catch (NamingException nex) {
        throw handleNamingException(nex, "Update entry failed.");
    }
}

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

/**
 * @param dn/* ww  w.j  a v  a 2 s  .  com*/
 * @param attribute
 * @throws LDAPException
 * @see org.mule.module.ldap.api.LDAPConnection#updateAttribute(java.lang.String,
 *      org.mule.module.ldap.api.LDAPEntryAttribute)
 */
public void updateAttribute(String dn, LDAPEntryAttribute attribute) throws LDAPException {

    try {
        ModificationItem[] mods = new ModificationItem[1];
        mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, buildBasicAttribute(attribute));
        getConn().modifyAttributes(dn, mods);
    } catch (NamingException nex) {
        throw handleNamingException(nex, "Update attribute failed.");
    }
}

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)
 *///  ww w . j  a  va 2 s.  c  o  m
@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.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 {//  w  ww  .j  a  v a2s .co 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.olat.ldap.LDAPLoginManagerImpl.java

/**
 * Change the password on the LDAP server.
 * /*from  w  ww  .ja  v  a2 s .com*/
 * @see org.olat.ldap.LDAPLoginManager#changePassword(org.olat.core.id.Identity, java.lang.String, org.olat.ldap.LDAPError)
 */
@Override
public void changePassword(final Identity identity, final String pwd, final LDAPError errors) {
    final String uid = identity.getName();
    final String ldapUserPasswordAttribute = LDAPLoginModule.getLdapUserPasswordAttribute();
    try {
        final DirContext ctx = bindSystem();
        final String dn = searchUserDN(uid, ctx);

        final ModificationItem[] modificationItems = new ModificationItem[1];

        Attribute userPasswordAttribute;
        if (LDAPLoginModule.isActiveDirectory()) {
            // active directory need the password enquoted and unicoded (but little-endian)
            final String quotedPassword = "\"" + pwd + "\"";
            final char unicodePwd[] = quotedPassword.toCharArray();
            final byte pwdArray[] = new byte[unicodePwd.length * 2];
            for (int i = 0; i < unicodePwd.length; i++) {
                pwdArray[i * 2 + 1] = (byte) (unicodePwd[i] >>> 8);
                pwdArray[i * 2 + 0] = (byte) (unicodePwd[i] & 0xff);
            }
            userPasswordAttribute = new BasicAttribute(ldapUserPasswordAttribute, pwdArray);
        } else {
            userPasswordAttribute = new BasicAttribute(ldapUserPasswordAttribute, pwd);
        }

        modificationItems[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, userPasswordAttribute);
        ctx.modifyAttributes(dn, modificationItems);
        ctx.close();
    } catch (final NamingException e) {
        logError("NamingException when trying to change password with username::" + uid, e);
        errors.insert("Cannot change the password");
    }
}

From source file:org.olat.ldap.manager.LDAPLoginManagerImpl.java

/**
 * Change the password on the LDAP server.
 * @see org.olat.ldap.LDAPLoginManager#changePassword(org.olat.core.id.Identity, java.lang.String, org.olat.ldap.LDAPError)
 *///from ww  w .j  a  v a 2s  . c o  m
@Override
public boolean changePassword(Identity identity, String pwd, LDAPError errors) {
    String uid = identity.getName();
    String ldapUserPasswordAttribute = syncConfiguration.getLdapUserPasswordAttribute();
    try {
        DirContext ctx = bindSystem();
        String dn = ldapDao.searchUserDN(uid, ctx);

        ModificationItem[] modificationItems = new ModificationItem[1];

        Attribute userPasswordAttribute;
        if (ldapLoginModule.isActiveDirectory()) {
            //active directory need the password enquoted and unicoded (but little-endian)
            String quotedPassword = "\"" + pwd + "\"";
            char unicodePwd[] = quotedPassword.toCharArray();
            byte pwdArray[] = new byte[unicodePwd.length * 2];
            for (int i = 0; i < unicodePwd.length; i++) {
                pwdArray[i * 2 + 1] = (byte) (unicodePwd[i] >>> 8);
                pwdArray[i * 2 + 0] = (byte) (unicodePwd[i] & 0xff);
            }
            userPasswordAttribute = new BasicAttribute(ldapUserPasswordAttribute, pwdArray);
        } else {
            userPasswordAttribute = new BasicAttribute(ldapUserPasswordAttribute, pwd);
        }

        modificationItems[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, userPasswordAttribute);
        ctx.modifyAttributes(dn, modificationItems);
        ctx.close();
        return true;
    } catch (NamingException e) {
        log.error("NamingException when trying to change password with username::" + uid, e);
        errors.insert("Cannot change the password");
        return false;
    } catch (Exception e) {
        log.error("Unexpected exception when trying to change password with username::" + uid, e);
        errors.insert("Cannot change the password");
        return false;
    }
}

From source file:org.openiam.spml2.spi.ldap.LdapConnectorImpl.java

public ResponseType setPassword(SetPasswordRequestType reqType) {
    log.debug("setPassword request called..");

    ConnectionMgr conMgr = null;/*from  w ww.j  av a2  s .co  m*/

    String requestID = reqType.getRequestID();
    /* PSO - Provisioning Service Object -
       *     -  ID must uniquely specify an object on the target or in the target's namespace
       *     -  Try to make the PSO ID immutable so that there is consistency across changes. */
    PSOIdentifierType psoID = reqType.getPsoID();
    /* targetID -  */
    String targetID = psoID.getTargetID();
    /* ContainerID - May specify the container in which this object should be created
       *      ie. ou=Development, org=Example */
    PSOIdentifierType containerID = psoID.getContainerID();

    /* A) Use the targetID to look up the connection information under managed systems */
    ManagedSys managedSys = managedSysService.getManagedSys(targetID);

    try {
        log.debug("managedSys found for targetID=" + targetID + " " + " Name=" + managedSys.getName());
        conMgr = ConnectionFactory.create(ConnectionManagerConstant.LDAP_CONNECTION);
        LdapContext ldapctx = conMgr.connect(managedSys);

        log.debug("Ldapcontext = " + ldapctx);

        String ldapName = psoID.getID();

        ModificationItem[] mods = new ModificationItem[1];
        mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                new BasicAttribute("userPassword", reqType.getPassword()));
        ldapctx.modifyAttributes(ldapName, mods);

        // check if the request contains additional attributes
        List<ExtensibleObject> extObjList = reqType.getAny();
        if (extObjList != null && extObjList.size() > 0) {
            ExtensibleObject obj = extObjList.get(0);
            if (obj != null) {
                List<ExtensibleAttribute> attrList = obj.getAttributes();
                if (attrList != null && attrList.size() > 0) {
                    mods = new ModificationItem[attrList.size()];
                    for (ExtensibleAttribute a : attrList) {
                        mods[0] = new ModificationItem(a.getOperation(),
                                new BasicAttribute(a.getName(), a.getValue()));
                    }
                    ldapctx.modifyAttributes(ldapName, mods);
                }
            }
        }

    } catch (NamingException ne) {
        log.error(ne.getMessage(), ne);

        ResponseType resp = new ResponseType();
        resp.setStatus(StatusCodeType.FAILURE);
        resp.setError(ErrorCode.NO_SUCH_IDENTIFIER);
        return resp;
    } catch (Exception ne) {
        log.error(ne.getMessage(), ne);

        ResponseType resp = new ResponseType();
        resp.setStatus(StatusCodeType.FAILURE);
        resp.setError(ErrorCode.OTHER_ERROR);
        resp.addErrorMessage(ne.toString());
        return resp;

    } finally {
        /* close the connection to the directory */
        try {
            if (conMgr != null) {
                conMgr.close();
            }

        } catch (NamingException n) {
            log.error(n);
        }

    }

    ResponseType respType = new ResponseType();
    respType.setStatus(StatusCodeType.SUCCESS);
    return respType;

}

From source file:org.orbeon.oxf.processor.LDAPProcessor.java

private void update(DirContext ctx, Update update) {
    try {/*from w  ww. j a v a 2  s . c om*/
        ctx.modifyAttributes(update.getName(), DirContext.REPLACE_ATTRIBUTE, update.getAttributes());
    } catch (NamingException e) {
        throw new OXFException("LDAP Update Failed", e);
    }
}