Example usage for javax.naming.ldap LdapContext modifyAttributes

List of usage examples for javax.naming.ldap LdapContext modifyAttributes

Introduction

In this page you can find the example usage for javax.naming.ldap LdapContext modifyAttributes.

Prototype

public void modifyAttributes(Name name, ModificationItem[] mods) throws NamingException;

Source Link

Document

Modifies the attributes associated with a named object using an ordered list of modifications.

Usage

From source file:edu.vt.middleware.ldap.AbstractLdap.java

/**
 * This will modify the supplied dn using the supplied modifications. The
 * modifications are performed in the order specified. Each modification
 * specifies a modification operation code and an attribute on which to
 * operate. Where possible, the modifications are performed atomically. See
 * {@link javax.naming.DirContext#modifyAttributes(String,
 * ModificationItem[])}.//ww  w.ja  v a  2  s. c o m
 *
 * @param  dn  <code>String</code> named object in the LDAP
 * @param  mods  <code>ModificationItem[]</code> modifications
 *
 * @throws  NamingException  if the LDAP returns an error
 */
protected void modifyAttributes(final String dn, final ModificationItem[] mods) throws NamingException {
    if (this.logger.isDebugEnabled()) {
        this.logger.debug("Modify attributes with the following parameters:");
        this.logger.debug("  dn = " + dn);
        this.logger.debug("  mods = " + Arrays.toString(mods));
        if (this.logger.isTraceEnabled()) {
            this.logger.trace("  config = " + this.config.getEnvironment());
        }
    }

    LdapContext ctx = null;
    try {
        for (int i = 0; i <= this.config.getOperationRetry() || this.config.getOperationRetry() == -1; i++) {
            try {
                ctx = this.getContext();
                ctx.modifyAttributes(dn, mods);
                break;
            } catch (NamingException e) {
                this.operationRetry(ctx, e, i);
            }
        }
    } finally {
        if (ctx != null) {
            ctx.close();
        }
    }
}

From source file:com.liferay.portal.security.ldap.internal.exportimport.LDAPUserExporterImpl.java

@Override
public void exportUser(Contact contact, Map<String, Serializable> contactExpandoAttributes) throws Exception {

    long companyId = contact.getCompanyId();

    StopWatch stopWatch = new StopWatch();

    if (_log.isDebugEnabled()) {
        stopWatch.start();/*  w w w. j ava  2  s . c  o  m*/

        _log.debug("Exporting contact " + contact);
    }

    if (!_ldapSettings.isExportEnabled(companyId)) {
        return;
    }

    User user = _userLocalService.getUserByContactId(contact.getContactId());

    if (user.isDefaultUser() || (user.getStatus() != WorkflowConstants.STATUS_APPROVED)) {

        return;
    }

    long ldapServerId = _portalLDAP.getLdapServerId(companyId, user.getScreenName(), user.getEmailAddress());

    LdapContext ldapContext = _portalLDAP.getContext(ldapServerId, companyId);

    try {
        if (ldapContext == null) {
            return;
        }

        Properties contactMappings = _ldapSettings.getContactMappings(ldapServerId, companyId);
        Properties contactExpandoMappings = _ldapSettings.getContactExpandoMappings(ldapServerId, companyId);

        Binding binding = _portalLDAP.getUser(ldapServerId, contact.getCompanyId(), user.getScreenName(),
                user.getEmailAddress());

        if (binding == null) {
            Properties userMappings = _ldapSettings.getUserMappings(ldapServerId, companyId);

            binding = addUser(ldapServerId, ldapContext, user, userMappings);
        }

        Name name = new CompositeName();

        name.add(binding.getNameInNamespace());

        Modifications modifications = _portalToLDAPConverter.getLDAPContactModifications(contact,
                contactExpandoAttributes, contactMappings, contactExpandoMappings);

        if (modifications == null) {
            return;
        }

        ModificationItem[] modificationItems = modifications.getItems();

        ldapContext.modifyAttributes(name, modificationItems);
    } finally {
        if (ldapContext != null) {
            ldapContext.close();
        }

        if (_log.isDebugEnabled()) {
            _log.debug(StringBundler.concat("Finished exporting contact ", String.valueOf(contact), " in ",
                    String.valueOf(stopWatch.getTime()), "ms"));
        }
    }
}

From source file:com.liferay.portal.security.ldap.internal.exportimport.LDAPUserExporterImpl.java

@Override
public void exportUser(long userId, long userGroupId, UserOperation userOperation) throws Exception {

    User user = _userLocalService.getUser(userId);

    long companyId = user.getCompanyId();

    StopWatch stopWatch = new StopWatch();

    if (_log.isDebugEnabled()) {
        stopWatch.start();//from  ww w  .  j  a  v a 2s  .  c o  m

        _log.debug(StringBundler.concat("Exporting user ", String.valueOf(user), " in user group ",
                String.valueOf(userGroupId)));
    }

    if (!_ldapSettings.isExportEnabled(companyId) || !_ldapSettings.isExportGroupEnabled(companyId)) {

        return;
    }

    long ldapServerId = _portalLDAP.getLdapServerId(companyId, user.getScreenName(), user.getEmailAddress());

    LdapContext ldapContext = _portalLDAP.getContext(ldapServerId, companyId);

    if (ldapContext == null) {
        return;
    }

    UserGroup userGroup = _userGroupLocalService.getUserGroup(userGroupId);

    Properties groupMappings = _ldapSettings.getGroupMappings(ldapServerId, companyId);
    Properties userMappings = _ldapSettings.getUserMappings(ldapServerId, companyId);

    Binding binding = _portalLDAP.getGroup(ldapServerId, companyId, userGroup.getName());

    if (binding == null) {
        if (userOperation == UserOperation.ADD) {
            addGroup(ldapServerId, ldapContext, userGroup, user, groupMappings, userMappings);
        } else {
            if (_log.isWarnEnabled()) {
                _log.warn("Unable to get or add LDAP bindings for user group " + userGroup.getName());
            }
        }

        return;
    }

    try {
        Name name = new CompositeName();

        name.add(binding.getNameInNamespace());

        Modifications modifications = _portalToLDAPConverter.getLDAPGroupModifications(ldapServerId, userGroup,
                user, groupMappings, userMappings, userOperation);

        ModificationItem[] modificationItems = modifications.getItems();

        ldapContext.modifyAttributes(name, modificationItems);
    } catch (SchemaViolationException sve) {
        if (_log.isInfoEnabled()) {
            _log.info("Unable to update LDAP bindings for user group " + userGroup.getName(), sve);
        }

        String fullGroupDN = binding.getNameInNamespace();

        Attributes attributes = _portalLDAP.getGroupAttributes(ldapServerId, companyId, ldapContext,
                fullGroupDN, true);

        Attribute groupMembers = attributes.get(groupMappings.getProperty(GroupConverterKeys.USER));

        if ((groupMembers != null) && (groupMembers.size() == 1)) {
            ldapContext.unbind(fullGroupDN);
        }
    } finally {
        if (ldapContext != null) {
            ldapContext.close();
        }

        if (_log.isDebugEnabled()) {
            _log.debug(StringBundler.concat("Finished exporting user ", String.valueOf(user), " in user group ",
                    String.valueOf(userGroupId), " in ", String.valueOf(stopWatch.getTime()), "ms"));
        }
    }
}

From source file:com.liferay.portal.security.ldap.internal.exportimport.LDAPUserExporterImpl.java

@Override
public void exportUser(User user, Map<String, Serializable> userExpandoAttributes) throws Exception {

    if (user.isDefaultUser() || (user.getStatus() != WorkflowConstants.STATUS_APPROVED)) {

        return;/*from w  ww. java  2 s. c o  m*/
    }

    long companyId = user.getCompanyId();

    if (!_ldapSettings.isExportEnabled(companyId)) {
        return;
    }

    long ldapServerId = _portalLDAP.getLdapServerId(companyId, user.getScreenName(), user.getEmailAddress());

    LdapContext ldapContext = _portalLDAP.getContext(ldapServerId, companyId);

    try {
        if (ldapContext == null) {
            return;
        }

        Properties userMappings = _ldapSettings.getUserMappings(ldapServerId, companyId);
        Properties userExpandoMappings = _ldapSettings.getUserExpandoMappings(ldapServerId, companyId);

        Binding binding = _portalLDAP.getUser(ldapServerId, user.getCompanyId(), user.getScreenName(),
                user.getEmailAddress(), true);

        if (binding == null) {
            binding = addUser(ldapServerId, ldapContext, user, userMappings);
        } else {
            Attributes attributes = _portalLDAP.getUserAttributes(ldapServerId, companyId, ldapContext,
                    binding.getNameInNamespace());

            String modifyTimestamp = LDAPUtil.getAttributeString(attributes, "modifyTimestamp");

            if (Validator.isNotNull(modifyTimestamp)) {
                Date modifiedDate = LDAPUtil.parseDate(modifyTimestamp);

                if (modifiedDate.equals(user.getModifiedDate())) {
                    if (_log.isDebugEnabled()) {
                        _log.debug("Skipping user " + user.getEmailAddress()
                                + " because he is already synchronized");
                    }

                    return;
                }
            }
        }

        Name name = new CompositeName();

        name.add(binding.getNameInNamespace());

        Modifications modifications = _portalToLDAPConverter.getLDAPUserModifications(user,
                userExpandoAttributes, userMappings, userExpandoMappings);

        if (modifications == null) {
            return;
        }

        ModificationItem[] modificationItems = modifications.getItems();

        ldapContext.modifyAttributes(name, modificationItems);

        if (!_ldapSettings.isExportGroupEnabled(companyId)) {
            return;
        }

        List<UserGroup> userGroups = _userGroupLocalService.getUserUserGroups(user.getUserId());

        for (UserGroup userGroup : userGroups) {
            exportUser(user.getUserId(), userGroup.getUserGroupId(), UserOperation.ADD);
        }

        Modifications groupModifications = _portalToLDAPConverter.getLDAPUserGroupModifications(ldapServerId,
                userGroups, user, userMappings);

        ModificationItem[] groupModificationItems = groupModifications.getItems();

        if (groupModificationItems.length > 0) {
            ldapContext.modifyAttributes(name, groupModificationItems);
        }
    } catch (NameNotFoundException nnfe) {
        LDAPAuthConfiguration ldapAuthConfiguration = _ldapAuthConfigurationProvider
                .getConfiguration(companyId);

        if (ldapAuthConfiguration.required()) {
            throw nnfe;
        }

        _log.error(nnfe, nnfe);
    } finally {
        if (ldapContext != null) {
            ldapContext.close();
        }
    }
}

From source file:org.apache.directory.studio.connection.core.io.jndi.JNDIConnectionWrapper.java

/**
 * Modifies attributes of an entry.//  w  w  w .  j  av a  2  s.  c om
 * 
 * @param dn the Dn
 * @param modificationItems the modification items
 * @param controls the controls
 * @param monitor the progress monitor
 * @param referralsInfo the referrals info
 */
public void modifyEntry(final String dn, final ModificationItem[] modificationItems, final Control[] controls,
        final StudioProgressMonitor monitor, final ReferralsInfo referralsInfo) {
    if (connection.isReadOnly()) {
        monitor.reportError(
                new Exception(NLS.bind(Messages.error__connection_is_readonly, connection.getName())));
        return;
    }

    InnerRunnable runnable = new InnerRunnable() {
        public void run() {
            try {
                // create modify context
                LdapContext modCtx = context.newInstance(controls);

                // use "throw" as we handle referrals manually
                modCtx.addToEnvironment(Context.REFERRAL, REFERRAL_THROW);

                // perform modification
                modCtx.modifyAttributes(getSaveJndiName(dn), modificationItems);
            } catch (ReferralException re) {
                try {
                    ReferralsInfo newReferralsInfo = handleReferralException(re, referralsInfo);
                    Referral referral = newReferralsInfo.getNextReferral();

                    if (referral != null) {
                        Connection referralConnection = ConnectionWrapperUtils.getReferralConnection(referral,
                                monitor, this);
                        if (referralConnection != null) {
                            List<String> urls = new ArrayList<>(referral.getLdapUrls());

                            String referralDn = new LdapUrl(urls.get(0)).getDn().getName();
                            referralConnection.getConnectionWrapper().modifyEntry(referralDn, modificationItems,
                                    controls, monitor, newReferralsInfo);
                        } else {
                            canceled = true;
                        }
                    }

                    return;
                } catch (NamingException ne) {
                    namingException = ne;
                } catch (LdapURLEncodingException e) {
                    namingException = new NamingException(e.getMessage());
                }
            } catch (NamingException ne) {
                namingException = ne;
            }

            for (IJndiLogger logger : getJndiLoggers()) {
                logger.logChangetypeModify(connection, dn, modificationItems, controls, namingException);
            }
        }
    };

    try {
        checkConnectionAndRunAndMonitor(runnable, monitor);
    } catch (NamingException ne) {
        monitor.reportError(ne);
    }

    if (runnable.isCanceled()) {
        monitor.setCanceled(true);
    }
    if (runnable.getException() != null) {
        monitor.reportError(runnable.getException());
    }
}

From source file:org.fao.geonet.kernel.security.ldap.LdapUserDetailsManager.java

/**
 * Changes the password for the current user. The username is obtained from the security
 * context. <p> If the old password is supplied, the update will be made by rebinding as the
 * user, thus modifying the password using the user's permissions. If <code>oldPassword</code>
 * is null, the update will be attempted using a standard read/write context supplied by the
 * context source. </p>/*  w  w  w . j a va  2s  .  c o  m*/
 *
 * @param oldPassword the old password
 * @param newPassword the new value of the password.
 */
public void changePassword(final String oldPassword, final String newPassword) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    Assert.notNull(authentication,
            "No authentication object found in security context. Can't change current user's password!");

    String username = authentication.getName();

    logger.debug("Changing password for user '" + username);

    final DistinguishedName dn = usernameMapper.buildDn(username);
    final ModificationItem[] passwordChange = new ModificationItem[] { new ModificationItem(
            DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(passwordAttributeName, newPassword)) };

    if (oldPassword == null) {
        template.modifyAttributes(dn, passwordChange);
        return;
    }

    template.executeReadWrite(new ContextExecutor() {

        public Object executeWithContext(DirContext dirCtx) throws NamingException {
            LdapContext ctx = (LdapContext) dirCtx;
            ctx.removeFromEnvironment("com.sun.jndi.ldap.connect.pool");
            ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, LdapUtils.getFullDn(dn, ctx).toString());
            ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, oldPassword);
            // TODO: reconnect doesn't appear to actually change the
            // credentials
            try {
                ctx.reconnect(null);
            } catch (javax.naming.AuthenticationException e) {
                throw new BadCredentialsException("Authentication for password change failed.");
            }

            ctx.modifyAttributes(dn, passwordChange);

            return null;
        }
    });
}

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   w w  w .  j  a v  a  2s  .  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.openiam.spml2.spi.ldap.LdapConnectorImpl.java

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

    ConnectionMgr conMgr = null;/* ww  w.j a  v  a 2 s.  c  om*/

    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.springframework.security.ldap.userdetails.LdapUserDetailsManager.java

private void changePasswordUsingAttributeModification(DistinguishedName userDn, String oldPassword,
        String newPassword) {// www  . jav  a 2s. com

    final ModificationItem[] passwordChange = new ModificationItem[] { new ModificationItem(
            DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(passwordAttributeName, newPassword)) };

    if (oldPassword == null) {
        template.modifyAttributes(userDn, passwordChange);
        return;
    }

    template.executeReadWrite(dirCtx -> {
        LdapContext ctx = (LdapContext) dirCtx;
        ctx.removeFromEnvironment("com.sun.jndi.ldap.connect.pool");
        ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, LdapUtils.getFullDn(userDn, ctx).toString());
        ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, oldPassword);
        // TODO: reconnect doesn't appear to actually change the credentials
        try {
            ctx.reconnect(null);
        } catch (javax.naming.AuthenticationException e) {
            throw new BadCredentialsException("Authentication for password change failed.");
        }

        ctx.modifyAttributes(userDn, passwordChange);

        return null;
    });

}