Example usage for javax.naming.directory ModificationItem ModificationItem

List of usage examples for javax.naming.directory ModificationItem ModificationItem

Introduction

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

Prototype

public ModificationItem(int mod_op, Attribute attr) 

Source Link

Document

Creates a new instance of ModificationItem.

Usage

From source file:ca.tnt.ldaputils.impl.LdapEntry.java

/**
 * Please note, the preferred method is to call setXXXX() where XXXX is the
 * attribute name, followed by save()./* w  ww . java2  s . co m*/
 * <p/>
 * This sets a batch attribute.  This means that it will be added to a queue
 * for changing LDAP.  You can modify the same attribute multiple times,
 * assuming LDAP supports multivalued attributes for that attribute. You are
 * then required to call modifyBatchAttributes(), which will actually do the
 * operations requested.
 * <p/>
 * You should call this one or more times per attribute, followed by
 * modifyBatchAttributes().
 * <p/>
 * Each time you call this method, for the same attribute, you should
 * specify the same operation, otherwise you will get an
 * IllegalArgumentException, with an appropriate error message.
 *
 * @param operation one of ADD_ATTRIBUTE, REPLACE_ATTRIBUTE,
 *                  REMOVE_ATTRIBUTE
 * @param attribute the name of the attribute
 * @param value     the value of the attribute
 *
 * @see #ADD_ATTRIBUTE ADD_ATTRIBUTE
 * @see #REPLACE_ATTRIBUTE REPLACE_ATTRIBUTE
 * @see #REMOVE_ATTRIBUTE REMOVE_ATTRIBUTE
 */
public void modifyBatchAttribute(final int operation, final String attribute, final Object value) {
    final Attribute newAttribute;
    ModificationItem modItem;
    final int mod_op;

    switch (operation) {
    case ADD_ATTRIBUTE:
        mod_op = DirContext.ADD_ATTRIBUTE;
        break;
    case REPLACE_ATTRIBUTE:
        mod_op = DirContext.REPLACE_ATTRIBUTE;
        break;
    case REMOVE_ATTRIBUTE:
        mod_op = DirContext.REMOVE_ATTRIBUTE;
        break;
    default:
        mod_op = DirContext.ADD_ATTRIBUTE;
    }

    modItem = (ModificationItem) modificationItems.get(attribute);
    if (modItem == null) { // first time we are doing something with this attribute
        newAttribute = new BasicAttribute(attribute, value);
        modItem = new ModificationItem(mod_op, newAttribute);
    } else { // we will add it to the attribute values for this attribute
        if (modItem.getModificationOp() != mod_op) { // make sure they aren't changing their mind on which op
            throw new IllegalArgumentException(
                    "error, operation does not match previous batch items for this attribute");
        }

        modItem.getAttribute().add(value);
    }
    modified = true;
    modificationItems.put(attribute, modItem);
}

From source file:edu.kit.scc.ldap.LdapPosixGroupDao.java

/**
 * Removes a POSIX user from the specified POSIX group.
 * /*from   www.  j a  v  a 2  s .c om*/
 * @param group the POSIX group
 * @param memberUid the POSIX user's uid
 * @return true on success
 */
public boolean removeMember(PosixGroup group, String memberUid) {
    ModificationItem[] modificationItems = new ModificationItem[] {
            new ModificationItem(DirContext.REMOVE_ATTRIBUTE, new BasicAttribute("memberUid", memberUid)) };
    LdapName groupDn = LdapUtils.emptyLdapName();
    try {
        groupDn = new LdapName(groupBase);
        groupDn.add("cn=" + group.getCommonName());
        log.debug("Remove member {} from {}", memberUid, groupDn.toString());
        ldapTemplate.modifyAttributes(groupDn, modificationItems);
        return true;
    } catch (AttributeInUseException ex) {
        log.error("ERROR {}", ex.toString());
    } catch (InvalidNameException ex) {
        log.error("ERROR {}", ex.toString());
    }
    return false;
}

From source file:com.globalsight.everest.usermgr.UserLdapHelper.java

/**
 * Generate an ModificationItem object for delete user operation. This
 * actually just sets the user status to 'DELETED' instead of deleting the
 * LDAP entry.//www.  j a  v  a2 s  . c  o m
 */
static ModificationItem getLDAPModificationForDeleteUser() {
    BasicAttribute attr = new BasicAttribute(LDAP_ATTR_STATUS, LDAP_DELETED_STATUS);
    ModificationItem mod = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attr);

    return mod;
}

From source file:com.globalsight.everest.usermgr.UserLdapHelper.java

/**
 * Generates an ModificationItem object for deactivating a user.
 *///from   www .ja v  a  2  s  .c om
static ModificationItem getLDAPModificationForDeactiveUser() {

    BasicAttribute attr = new BasicAttribute(LDAP_ATTR_STATUS, LDAP_DEACTIVE_STATUS);
    ModificationItem mod = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attr);

    return mod;
}

From source file:com.globalsight.everest.usermgr.UserLdapHelper.java

/**
 * Generate an ModificationItem object for activating a user. This actually
 * just sets the user status to 'ACTIVE' in the LDAP entry.
 */// w  w w .  j  a  va2  s  .c  o m
static ModificationItem getLDAPModificationForActivateUser() {

    BasicAttribute attr = new BasicAttribute(LDAP_ATTR_STATUS, LDAP_ACTIVE_STATUS);
    ModificationItem mod = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attr);

    return mod;
}

From source file:com.globalsight.everest.usermgr.UserLdapHelper.java

/**
 * Convert an User object to ModificationItem[] object for updating that
 * User info in LDAP.// w  w w  .j  av a  2 s  .  c o m
 */
static ModificationItem[] convertUserToModificationSet(User p_user) {

    ArrayList attrSet = new ArrayList();
    attrSet.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
            generateLDAPAttribute(LDAP_ATTR_USERID, p_user.getUserId())));

    if (isStringValid(p_user.getTitle())) {
        attrSet.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                generateLDAPAttribute(LDAP_ATTR_TITLE, p_user.getTitle())));
    } else {
        attrSet.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                generateLDAPAttribute(LDAP_ATTR_TITLE, "null")));
    }

    if (p_user.getPassword() != null && p_user.isPasswordSet()) {
        /* If the user doesn't set the password, use the original one */
        String password = encyptMD5Password(p_user.getPassword());

        attrSet.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                generateLDAPAttribute(LDAP_ATTR_PASSWORD, password)));
    }

    attrSet.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
            generateLDAPAttribute(LDAP_ATTR_USER_NAME, p_user.getUserName())));
    attrSet.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
            generateLDAPAttribute(LDAP_ATTR_LAST_NAME, p_user.getLastName())));
    attrSet.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
            generateLDAPAttribute(LDAP_ATTR_FIRST_NAME, p_user.getFirstName())));

    String status = getStateAsString(p_user.getState());
    attrSet.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
            generateLDAPAttribute(LDAP_ATTR_STATUS, status)));

    if (isStringValid(p_user.getEmail())) {
        attrSet.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                generateLDAPAttribute(LDAP_ATTR_EMAIL, p_user.getEmail())));
    }
    if (isStringValid(p_user.getCCEmail())) {
        attrSet.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                generateLDAPAttribute(LDAP_ATTR_CC_EMAIL, p_user.getCCEmail())));
    } else {
        attrSet.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                generateLDAPAttribute(LDAP_ATTR_CC_EMAIL, "null")));
    }
    if (isStringValid(p_user.getBCCEmail())) {
        attrSet.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                generateLDAPAttribute(LDAP_ATTR_BCC_EMAIL, p_user.getBCCEmail())));
    } else {
        attrSet.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                generateLDAPAttribute(LDAP_ATTR_BCC_EMAIL, "null")));
    }
    if (isStringValid(p_user.getHomePhoneNumber())) {
        attrSet.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                generateLDAPAttribute(LDAP_ATTR_HOME_PHONE, p_user.getHomePhoneNumber())));
    } else {
        attrSet.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                generateLDAPAttribute(LDAP_ATTR_HOME_PHONE, "null")));
    }
    if (isStringValid(p_user.getOfficePhoneNumber())) {
        attrSet.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                generateLDAPAttribute(LDAP_ATTR_OFFICE_PHONE, p_user.getOfficePhoneNumber())));
    } else {
        attrSet.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                generateLDAPAttribute(LDAP_ATTR_OFFICE_PHONE, "null")));
    }
    if (isStringValid(p_user.getCellPhoneNumber())) {
        attrSet.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                generateLDAPAttribute(LDAP_ATTR_CELL_NUMBER, p_user.getCellPhoneNumber())));
    } else {
        attrSet.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                generateLDAPAttribute(LDAP_ATTR_CELL_NUMBER, "null")));
    }
    if (isStringValid(p_user.getFaxPhoneNumber())) {
        attrSet.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                generateLDAPAttribute(LDAP_ATTR_FAX_NUMBER, p_user.getFaxPhoneNumber())));
    } else {
        attrSet.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                generateLDAPAttribute(LDAP_ATTR_FAX_NUMBER, "null")));
    }
    if (isStringValid(p_user.getDefaultUILocale())) {
        attrSet.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                generateLDAPAttribute(LDAP_ATTR_DEFAULT_UI_LOCALE, p_user.getDefaultUILocale())));
    }
    if (isStringValid(p_user.getAddress())) {
        attrSet.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                generateLDAPAttribute(LDAP_ATTR_ADDRESS, p_user.getAddress())));
    } else {
        attrSet.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                generateLDAPAttribute(LDAP_ATTR_ADDRESS, "null")));
    }
    if (isStringValid(p_user.getCompanyName())) {
        attrSet.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                generateLDAPAttribute(LDAP_ATTR_COMPANY, p_user.getCompanyName())));
    }
    attrSet.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
            generateLDAPAttribute(LDAP_ATTR_INALLPROJECTS, p_user.isInAllProjects())));
    // a user can't be changed from anonymous to GlobalSight and back
    // so just leave the type field alone for now
    // LDAP_ATTR_TYPE, LDAP_ANONYMOUS_USER_TYPE
    return (ModificationItem[]) attrSet.toArray(new ModificationItem[] {});
}

From source file:org.archone.ad.domain.LdapActions.java

@RPCAction(name = "user.mod", required = { "userId" })
@RequiresAuthentication/*from w w w .  jav a 2  s  . c  o  m*/
@SecuredMethod(constraints = "administrator.by_domain")
public HashMap<String, Object> modifyUser(OperationContext opContext) throws NamingException {

    String userId = (String) opContext.getParams().get("userId");

    UserDn userDn = nameHelper.newUserDnFromId(userId);
    DomainDn domainDn = nameHelper.newDomainDnFromDomain(userDn.getDomain());
    DirContextAdapter userDirContext = (DirContextAdapter) SecurityUtils.getSubject().getPrincipal();

    HashMap<String, Object> response = new HashMap<String, Object>();

    DirContextAdapter dca = (DirContextAdapter) userDirContext.lookup(userDn);

    HashMap<String, Object> modValues = displayAttributeHelper
            .apiToLdapAttrNames((HashMap<String, Object>) opContext.getParams().get("mod"));
    HashMap<String, Object> addValues = displayAttributeHelper
            .apiToLdapAttrNames((HashMap<String, Object>) opContext.getParams().get("add"));
    HashMap<String, Object> removeValues = displayAttributeHelper
            .apiToLdapAttrNames((HashMap<String, Object>) opContext.getParams().get("remove"));
    List<String> removeAttrs = (List<String>) opContext.getParams().get("removeAttr");

    IntegrityCheckUtil integrityCheckUtil = new IntegrityCheckUtil(userDirContext);
    HashMap<String, String> busyValues = new HashMap<String, String>();

    LinkedList<ModificationItem> removeAttrList = new LinkedList<ModificationItem>();
    if (removeAttrs != null) {
        for (String apiName : removeAttrs) {
            BasicAttribute attr = new BasicAttribute(displayAttributeHelper.getLdapName(apiName));
            ModificationItem mi = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, attr);
            removeAttrList.add(mi);
        }
    }

    for (Entry<String, Object> entry : modValues.entrySet()) {

        if (displayAttributeHelper.byLdapName(entry.getKey()).isDomainUnique()) {
            if (!integrityCheckUtil.isUnique(domainDn, entry.getKey(), entry.getValue().toString())) {
                busyValues.put(entry.getKey(), entry.getValue().toString());
            }
        }

        dca.setAttributeValue(entry.getKey(), entry.getValue().toString());
    }

    for (Entry<String, Object> entry : removeValues.entrySet()) {
        if (entry.getValue() instanceof List) {
            for (Object value : (List) entry.getValue()) {
                dca.removeAttributeValue(entry.getKey(), value);
            }
        } else {
            dca.removeAttributeValue(entry.getKey(), entry.getValue());
        }
    }

    for (Entry<String, Object> entry : addValues.entrySet()) {
        if (entry.getValue() instanceof List) {

            for (Object value : (List) entry.getValue()) {

                if (displayAttributeHelper.byLdapName(entry.getKey()).isDomainUnique()) {
                    if (!integrityCheckUtil.isUnique(domainDn, entry.getKey(), (String) value)) {
                        busyValues.put(entry.getKey(), (String) value);
                    }
                }

                dca.addAttributeValue(entry.getKey(), value);
            }
        } else {

            if (displayAttributeHelper.byLdapName(entry.getKey()).isDomainUnique()) {
                if (!integrityCheckUtil.isUnique(domainDn, entry.getKey(), (String) entry.getValue())) {
                    busyValues.put(entry.getKey(), (String) entry.getValue());
                }
            }

            dca.addAttributeValue(entry.getKey(), entry.getValue());
        }
    }

    if (busyValues.size() > 0) {
        response.put("success", false);
        response.put("busyValues", busyValues);
    } else {
        userDirContext.modifyAttributes(userDn, removeAttrList.toArray(new ModificationItem[0]));
        userDirContext.modifyAttributes(userDn, dca.getModificationItems());
        response.put("success", true);
    }

    return response;
}

From source file:gov.medicaid.dao.impl.LDAPIdentityProviderDAOBean.java

/**
 * Synchronizes the roles between the application and the identity provider.
 *
 * @param username the user to synchronize the role for
 * @param role the role that should be set on the identity provider
 * @throws PortalServiceException for any errors encountered
 *///from  w  w w .  j  a  va 2 s.com
private void synchRoles(String username, Role role) throws PortalServiceException {
    List<String> roles = findRoles(username);

    DirContext ctx = null;
    try {
        ctx = new InitialDirContext(env);

        // remove all roles, we expect only one
        for (String existingRole : roles) {
            if (!existingRole.equals(role.getDescription())) {
                removeRoleAssignment(ctx, username, existingRole);
            }
        }

        // add the new role if needed
        if (!roles.contains(role.getDescription())) {
            ModificationItem[] mods = new ModificationItem[1];
            BasicAttribute m = new BasicAttribute(groupMemberAttr,
                    MessageFormat.format(userDNPattern, username));
            mods[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, m);
            ctx.modifyAttributes(MessageFormat.format(groupDNPattern, role.getDescription()), mods);
        }
    } catch (NamingException e) {
        throw new PortalServiceConfigurationException("Unable to reset password.", e);
    } finally {
        closeContext(ctx);
    }

}

From source file:gov.medicaid.dao.impl.LDAPIdentityProviderDAOBean.java

/**
 * Removes the given user from the given role.
 *
 * @param ctx the directory context//from  w  w w .j  a  v a 2s .com
 * @param username the user to be removed
 * @param existingRole the role to be removed from
 * @throws NamingException for any errors encountered
 */
private void removeRoleAssignment(DirContext ctx, String username, String existingRole) throws NamingException {
    ModificationItem[] mods = new ModificationItem[1];
    BasicAttribute m = new BasicAttribute(groupMemberAttr, MessageFormat.format(userDNPattern, username));
    mods[0] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, m);
    ctx.modifyAttributes(MessageFormat.format(groupDNPattern, existingRole), mods);
}

From source file:com.adito.ldap.LdapUserDatabase.java

/**
 * (non-Javadoc)//from  w  ww. j  a  v a2s . c om
 *
 * @see com.adito.security.DefaultUserDatabase#setPassword(java.lang.String, java.lang.String, boolean, com.adito.security.User, java.lang.String)
 */
public void setPassword(String username, String password, boolean forcePasswordChangeAtLogon, User adminUser,
        String adminPassword) throws UserDatabaseException, InvalidLoginCredentialsException {
    if (!supportsPasswordChange()) {
        throw new InvalidLoginCredentialsException("Database doesn't support password change.");
    }

    LdapUser user;

    try {
        user = getAccount(username);
    } catch (Exception e) {
        throw new UserDatabaseException(e.toString());
    }

    if (forcePasswordChangeAtLogon)
        user.setLastPasswordChange(null);
    else
        user.setLastPasswordChange(new Date());

    LdapTemplate ldapTemplate = new LdapTemplate();
    ldapTemplate.setContextSource(ldapContextSource);
    Attribute attr = new BasicAttribute(PASSWORD_ATTRIBUTE, password);
    ModificationItem item = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attr);
    try {
        String dn = getAccount(username).getDn();
        int ind = dn.indexOf(baseDn);
        String rdn = dn.substring(0, ind - 1);
        ldapTemplate.modifyAttributes(rdn, new ModificationItem[] { item });
    } catch (Exception e) {
        throw new UserDatabaseException("Error in LDAP server");
    }

}