Example usage for javax.naming.directory DirContext modifyAttributes

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

Introduction

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

Prototype

public void modifyAttributes(String name, int mod_op, Attributes attrs) throws NamingException;

Source Link

Document

Modifies the attributes associated with a named object.

Usage

From source file:Modify1Example.java

public static void main(String args[]) {
    Hashtable env = new Hashtable(11);

    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://MyHost/o=JNDIExample");
    try {/*ww  w .j av  a  2  s .com*/
        DirContext dctx = new InitialDirContext(env);
        Attributes attrs = new BasicAttributes(true);
        attrs.put(new BasicAttribute("email", "name@site.com"));
        attrs.put(new BasicAttribute("website"));

        dctx.modifyAttributes("cn=Name, ou=People", DirContext.ADD_ATTRIBUTE, attrs);
    } catch (Exception e) {
        System.out.println(e);
    }
}

From source file:ldap.ActiveLoginImpl.java

/**
 * This updates the UserAccount./*w w w.j a  v  a 2s . c  om*/
 * It requires at a minimum a name;
 * and optionally any other attributes.
 *
 * Note that this will REPLACE any attributes passed, deleting any existing values
 * for the specified attribute (e.g. if the attribute is userPassword, the old userPassword will
 * be discarded, rather than there being two userPasswords in the entry).
 *
 * Modifying the naming attribute will probably result in an error (depending on the directory).
 *
 * @param account
 * @throws Exception
 */
public void updateAccount(UserAccount account, DirContext context, String userDN) throws Exception {

    //if (account.get(Config.USER_NAMING_ATT) == null)
    if (account.get(LdapConstants.ldapDnAttrType) == null)
        throw new NamingException("UpdateAccount(), UserAccount has no naming Attribute");

    // should not be used
    //logger.info("Updating: \n" + account.getUserDN() + "\n" + account.toString());
    logger.info("Updating: \n" + userDN + "\n" + account.toString());

    // remove the naming attribute from the account before adding

    Attributes atts = copyAttributes(account); // create a local copy

    //atts.remove(Config.USER_NAMING_ATT);  // we can't modify the naming attribute this way, so don't try...
    //atts.remove(LdapConstants.ldapAttrUid);  // we can't modify the naming attribute this way, so don't try...
    atts.remove(LdapConstants.ldapDnAttrType); // we can't modify the naming attribute this way, so don't try...
    atts = hashPasswordAttribute(atts);
    // context.modifyAttributes(account.getUserDN(), DirContext.REPLACE_ATTRIBUTE, atts);
    context.modifyAttributes(userDN, DirContext.REPLACE_ATTRIBUTE, atts);
}

From source file:nl.nn.adapterframework.ldap.LdapSender.java

private String performOperationUpdate(String entryName, ParameterResolutionContext prc, Map paramValueMap,
        Attributes attrs) throws SenderException, ParameterException {
    String entryNameAfter = entryName;
    if (paramValueMap != null) {
        String newEntryName = (String) paramValueMap.get("newEntryName");
        if (newEntryName != null && StringUtils.isNotEmpty(newEntryName)) {
            if (log.isDebugEnabled())
                log.debug("newEntryName=[" + newEntryName + "]");
            DirContext dirContext = null;
            try {
                dirContext = getDirContext(paramValueMap);
                dirContext.rename(entryName, newEntryName);
                entryNameAfter = newEntryName;
            } catch (NamingException e) {
                String msg;//from   w  ww.j  av a 2 s  .c  o  m
                // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
                //   32 LDAP_NO_SUCH_OBJECT Indicates the target object cannot be found. This code is not returned on following operations: Search operations that find the search base but cannot find any entries that match the search filter. Bind operations. 
                // Sun:
                //   [LDAP: error code 32 - No Such Object...
                if (e.getMessage().startsWith("[LDAP: error code 32 - ")) {
                    msg = "Operation [" + getOperation() + "] failed - wrong entryName [" + entryName + "]";
                } else {
                    msg = "Exception in operation [" + getOperation() + "] entryName [" + entryName + "]";
                }
                storeLdapException(e, prc);
                throw new SenderException(msg, e);
            } finally {
                closeDirContext(dirContext);
            }
        }
    }

    if (manipulationSubject.equals(MANIPULATION_ATTRIBUTE)) {
        NamingEnumeration na = attrs.getAll();
        while (na.hasMoreElements()) {
            Attribute a = (Attribute) na.nextElement();
            log.debug("Update attribute: " + a.getID());
            NamingEnumeration values;
            try {
                values = a.getAll();
            } catch (NamingException e1) {
                storeLdapException(e1, prc);
                throw new SenderException("cannot obtain values of Attribute [" + a.getID() + "]", e1);
            }
            while (values.hasMoreElements()) {
                Attributes partialAttrs = new BasicAttributes();
                Attribute singleValuedAttribute;
                String id = a.getID();
                Object value = values.nextElement();
                if (log.isDebugEnabled()) {
                    if (id.toLowerCase().contains("password") || id.toLowerCase().contains("pwd")) {
                        log.debug("Update value: ***");
                    } else {
                        log.debug("Update value: " + value);
                    }
                }
                if (unicodePwd && "unicodePwd".equalsIgnoreCase(id)) {
                    singleValuedAttribute = new BasicAttribute(id, encodeUnicodePwd(value));
                } else {
                    singleValuedAttribute = new BasicAttribute(id, value);
                }
                partialAttrs.put(singleValuedAttribute);
                DirContext dirContext = null;
                try {
                    dirContext = getDirContext(paramValueMap);
                    dirContext.modifyAttributes(entryNameAfter, DirContext.REPLACE_ATTRIBUTE, partialAttrs);
                } catch (NamingException e) {
                    String msg;
                    // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
                    //   32 LDAP_NO_SUCH_OBJECT Indicates the target object cannot be found. This code is not returned on following operations: Search operations that find the search base but cannot find any entries that match the search filter. Bind operations. 
                    // Sun:
                    //   [LDAP: error code 32 - No Such Object...
                    if (e.getMessage().startsWith("[LDAP: error code 32 - ")) {
                        msg = "Operation [" + getOperation() + "] failed - wrong entryName [" + entryNameAfter
                                + "]";
                    } else {
                        msg = "Exception in operation [" + getOperation() + "] entryName [" + entryNameAfter
                                + "]";
                    }
                    //result = DEFAULT_RESULT_UPDATE_NOK;
                    storeLdapException(e, prc);
                    throw new SenderException(msg, e);
                } finally {
                    closeDirContext(dirContext);
                }
            }
        }
        return DEFAULT_RESULT;
    } else {
        DirContext dirContext = null;
        try {
            dirContext = getDirContext(paramValueMap);
            //dirContext.rename(newEntryName, oldEntryName);
            //result = DEFAULT_RESULT;
            dirContext.rename(entryName, entryName);
            return "<LdapResult>Deze functionaliteit is nog niet beschikbaar - naam niet veranderd.</LdapResult>";
        } catch (NamingException e) {
            // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
            //   68 LDAP_ALREADY_EXISTS Indicates that the add operation attempted to add an entry that already exists, or that the modify operation attempted to rename an entry to the name of an entry that already exists.
            // Sun:
            //   [LDAP: error code 68 - Entry Already Exists]
            if (!e.getMessage().startsWith("[LDAP: error code 68 - ")) {
                storeLdapException(e, prc);
                throw new SenderException(e);
            }
            return DEFAULT_RESULT_CREATE_NOK;
        } finally {
            closeDirContext(dirContext);
        }
    }
}

From source file:nl.nn.adapterframework.ldap.LdapSender.java

private String performOperationCreate(String entryName, ParameterResolutionContext prc, Map paramValueMap,
        Attributes attrs) throws SenderException, ParameterException {
    if (manipulationSubject.equals(MANIPULATION_ATTRIBUTE)) {
        String result = null;/*from w w w .ja  va 2s.c  o m*/
        NamingEnumeration na = attrs.getAll();
        while (na.hasMoreElements()) {
            Attribute a = (Attribute) na.nextElement();
            log.debug("Create attribute: " + a.getID());
            NamingEnumeration values;
            try {
                values = a.getAll();
            } catch (NamingException e1) {
                storeLdapException(e1, prc);
                throw new SenderException("cannot obtain values of Attribute [" + a.getID() + "]", e1);
            }
            while (values.hasMoreElements()) {
                Attributes partialAttrs = new BasicAttributes();
                Attribute singleValuedAttribute;
                String id = a.getID();
                Object value = values.nextElement();
                if (log.isDebugEnabled()) {
                    if (id.toLowerCase().contains("password") || id.toLowerCase().contains("pwd")) {
                        log.debug("Create value: ***");
                    } else {
                        log.debug("Create value: " + value);
                    }
                }
                if (unicodePwd && "unicodePwd".equalsIgnoreCase(id)) {
                    singleValuedAttribute = new BasicAttribute(id, encodeUnicodePwd(value));
                } else {
                    singleValuedAttribute = new BasicAttribute(id, value);
                }
                partialAttrs.put(singleValuedAttribute);
                DirContext dirContext = null;
                try {
                    dirContext = getDirContext(paramValueMap);
                    dirContext.modifyAttributes(entryName, DirContext.ADD_ATTRIBUTE, partialAttrs);
                } catch (NamingException e) {
                    // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
                    //   20 LDAP_TYPE_OR_VALUE_EXISTS Indicates that the attribute value specified in a modify or add operation already exists as a value for that attribute.
                    // Sun:
                    //   [LDAP: error code 20 - Attribute Or Value Exists]
                    if (e.getMessage().startsWith("[LDAP: error code 20 - ")) {
                        if (log.isDebugEnabled())
                            log.debug("Operation [" + getOperation() + "] successful: " + e.getMessage());
                        result = DEFAULT_RESULT_CREATE_OK;
                    } else {
                        storeLdapException(e, prc);
                        throw new SenderException(
                                "Exception in operation [" + getOperation() + "] entryName [" + entryName + "]",
                                e);
                    }
                } finally {
                    closeDirContext(dirContext);
                }
            }
        }
        if (result != null) {
            return result;
        }
        return DEFAULT_RESULT;
    } else {
        DirContext dirContext = null;
        try {
            if (unicodePwd) {
                Enumeration enumeration = attrs.getIDs();
                while (enumeration.hasMoreElements()) {
                    String id = (String) enumeration.nextElement();
                    if ("unicodePwd".equalsIgnoreCase(id)) {
                        Attribute attr = attrs.get(id);
                        for (int i = 0; i < attr.size(); i++) {
                            attr.set(i, encodeUnicodePwd(attr.get(i)));
                        }
                    }
                }
            }
            dirContext = getDirContext(paramValueMap);
            dirContext.bind(entryName, null, attrs);
            return DEFAULT_RESULT;
        } catch (NamingException e) {
            // if (log.isDebugEnabled()) log.debug("Exception in operation [" + getOperation()+ "] entryName ["+entryName+"]", e);
            if (log.isDebugEnabled())
                log.debug("Exception in operation [" + getOperation() + "] entryName [" + entryName + "]: "
                        + e.getMessage());
            // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
            //   68 LDAP_ALREADY_EXISTS Indicates that the add operation attempted to add an entry that already exists, or that the modify operation attempted to rename an entry to the name of an entry that already exists.
            // Sun:
            //   [LDAP: error code 68 - Entry Already Exists]
            if (e.getMessage().startsWith("[LDAP: error code 68 - ")) {
                return DEFAULT_RESULT_CREATE_OK;
            } else {
                storeLdapException(e, prc);
                throw new SenderException(e);
            }
        } finally {
            closeDirContext(dirContext);
        }
    }

}

From source file:nl.nn.adapterframework.ldap.LdapSender.java

private String performOperationDelete(String entryName, ParameterResolutionContext prc, Map paramValueMap,
        Attributes attrs) throws SenderException, ParameterException {
    if (manipulationSubject.equals(MANIPULATION_ATTRIBUTE)) {
        String result = null;//from w ww  .j a v  a2  s  . c  o m
        NamingEnumeration na = attrs.getAll();
        while (na.hasMoreElements()) {
            Attribute a = (Attribute) na.nextElement();
            log.debug("Delete attribute: " + a.getID());
            NamingEnumeration values;
            try {
                values = a.getAll();
            } catch (NamingException e1) {
                storeLdapException(e1, prc);
                throw new SenderException("cannot obtain values of Attribute [" + a.getID() + "]", e1);
            }
            while (values.hasMoreElements()) {
                Attributes partialAttrs = new BasicAttributes();
                Attribute singleValuedAttribute;
                String id = a.getID();
                Object value = values.nextElement();
                if (log.isDebugEnabled()) {
                    if (id.toLowerCase().contains("password") || id.toLowerCase().contains("pwd")) {
                        log.debug("Delete value: ***");
                    } else {
                        log.debug("Delete value: " + value);
                    }
                }
                if (unicodePwd && "unicodePwd".equalsIgnoreCase(id)) {
                    singleValuedAttribute = new BasicAttribute(id, encodeUnicodePwd(value));
                } else {
                    singleValuedAttribute = new BasicAttribute(id, value);
                }
                partialAttrs.put(singleValuedAttribute);
                DirContext dirContext = null;
                try {
                    dirContext = getDirContext(paramValueMap);
                    dirContext.modifyAttributes(entryName, DirContext.REMOVE_ATTRIBUTE, partialAttrs);
                } catch (NamingException e) {
                    // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
                    //   16 LDAP_NO_SUCH_ATTRIBUTE Indicates that the attribute specified in the modify or compare operation does not exist in the entry.
                    //   32 LDAP_NO_SUCH_OBJECT Indicates the target object cannot be found. This code is not returned on following operations: Search operations that find the search base but cannot find any entries that match the search filter. Bind operations. 
                    // Sun:
                    //   [LDAP: error code 16 - No Such Attribute...
                    //   [LDAP: error code 32 - No Such Object...
                    // AD:
                    //   [LDAP: error code 16 - 00002085: AtrErr: DSID-03151F03, #1...
                    if (e.getMessage().startsWith("[LDAP: error code 16 - ")
                            || e.getMessage().startsWith("[LDAP: error code 32 - ")) {
                        if (log.isDebugEnabled())
                            log.debug("Operation [" + getOperation() + "] successful: " + e.getMessage());
                        result = DEFAULT_RESULT_DELETE;
                    } else {
                        storeLdapException(e, prc);
                        throw new SenderException(
                                "Exception in operation [" + getOperation() + "] entryName [" + entryName + "]",
                                e);
                    }
                } finally {
                    closeDirContext(dirContext);
                }
            }
        }
        if (result != null) {
            return result;
        }
        return DEFAULT_RESULT;
    } else {
        DirContext dirContext = null;
        try {
            dirContext = getDirContext(paramValueMap);
            dirContext.unbind(entryName);
            return DEFAULT_RESULT;
        } catch (NamingException e) {
            // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
            //   32 LDAP_NO_SUCH_OBJECT Indicates the target object cannot be found. This code is not returned on following operations: Search operations that find the search base but cannot find any entries that match the search filter. Bind operations. 
            // Sun:
            //   [LDAP: error code 32 - No Such Object...
            if (e.getMessage().startsWith("[LDAP: error code 32 - ")) {
                if (log.isDebugEnabled())
                    log.debug("Operation [" + getOperation() + "] successful: " + e.getMessage());
                return DEFAULT_RESULT_DELETE;
            } else {
                storeLdapException(e, prc);
                throw new SenderException(
                        "Exception in operation [" + getOperation() + "] entryName [" + entryName + "]", e);
            }
        } finally {
            closeDirContext(dirContext);
        }
    }
}

From source file:org.exoplatform.services.organization.DummyLDAPServiceImpl.java

private void addNewSchema() throws NamingException {
    DirContext ctx = getLdapContext();
    try {//from  w w  w .j av  a 2  s .c  om
        Attributes atAttrs = new BasicAttributes(true);
        atAttrs.put("attributeTypes",
                "( 1.2.840.113556.1.4.8 NAME 'userAccountControl' DESC 'Flags that control the behavior of the user account' EQUALITY integerMatch SYNTAX '1.3.6.1.4.1.1466.115.121.1.27' SINGLE-VALUE )");
        ctx.modifyAttributes("cn=schema", DirContext.ADD_ATTRIBUTE, atAttrs);
        Attributes ocAttrs = new BasicAttributes(true);
        ocAttrs.put("objectClasses",
                "( 1.2.840.113556.1.5.9 NAME 'user' SUP inetOrgPerson STRUCTURAL MAY (userAccountControl) )");
        ctx.modifyAttributes("cn=schema", DirContext.ADD_ATTRIBUTE, ocAttrs);
    } finally {
        ctx.close();
    }
}

From source file:org.gbif.portal.registration.LDAPUtils.java

/**
 * Creates a user. String array contains:
 * 1) first name/* w  ww. j a  v a  2 s.  c o  m*/
 * 2) surname
 * 3) email
 * 4) username
 * 5) password
 * 
 * @param userDetails
 * @return
 * @throws NamingException
 */
public boolean createNewUser(UserLogin userLogin) throws NamingException {
    DirContext ctx = getUserContext();
    Attributes attributes = new BasicAttributes();
    attributes.put(new BasicAttribute("sn", userLogin.getSurname()));
    attributes.put(new BasicAttribute("givenName", userLogin.getFirstName()));
    attributes.put(new BasicAttribute("cn", userLogin.getFirstName() + " " + userLogin.getSurname()));
    attributes.put(new BasicAttribute("mail", userLogin.getEmail()));
    if (userLogin.getTelephone() != null) {
        attributes.put(new BasicAttribute("telephoneNumber", userLogin.getTelephone()));
    }
    attributes.put(new BasicAttribute("userPassword", userLogin.getPassword()));
    attributes.put(new BasicAttribute("objectClass", "top"));
    attributes.put(new BasicAttribute("objectClass", "person"));
    attributes.put(new BasicAttribute("objectClass", "organizationalPerson"));
    attributes.put(new BasicAttribute("objectClass", "inetorgperson"));
    String contextName = "uid=" + userLogin.getUsername();
    String fullContextName = contextName + "," + ctx.getNameInNamespace();

    //add the user to ldap
    ctx.createSubcontext(contextName, attributes);

    //need to add user to group
    for (int i = 0; i < userGroups.length; i++) {
        DirContext groupContext = getGroupContext();
        Attributes groupAttributes = groupContext.getAttributes(userGroups[i]);
        groupAttributes.get("uniqueMember").add(fullContextName);
        groupContext.modifyAttributes(userGroups[i], DirContext.REPLACE_ATTRIBUTE, groupAttributes);
    }
    return true;
}

From source file:org.gbif.portal.registration.LDAPUtils.java

/**
 * Update the details of the supplied user in LDAP.
 * @param userLogin//from  ww w  .j ava  2s  .  c o  m
 * @return
 * @throws NamingException
 */
public boolean updateUser(UserLogin userLogin) throws NamingException {
    DirContext ctx = getUserContext();
    Attributes attributes = new BasicAttributes();
    attributes.put(new BasicAttribute("sn", userLogin.getSurname()));
    attributes.put(new BasicAttribute("givenName", userLogin.getFirstName()));
    attributes.put(new BasicAttribute("cn", userLogin.getFirstName() + " " + userLogin.getSurname()));
    attributes.put(new BasicAttribute("mail", userLogin.getEmail()));
    if (userLogin.getTelephone() != null) {
        attributes.put(new BasicAttribute("telephoneNumber", userLogin.getTelephone()));
    }
    attributes.put(new BasicAttribute("userPassword", userLogin.getPassword()));
    ctx.modifyAttributes("uid=" + userLogin.getUsername(), DirContext.REPLACE_ATTRIBUTE, attributes);
    return true;
}

From source file:org.gbif.portal.registration.LDAPUtils.java

/**
 * Update the password for the supplied user.
 * @param username// www  . j ava  2 s  .  c o m
 * @param newPassword
 * @throws NamingException
 */
public void updatePassword(String username, String newPassword) throws NamingException {
    DirContext ctx = getUserContext();
    Attributes attributes = new BasicAttributes();
    attributes.put(new BasicAttribute("userPassword", newPassword));
    ctx.modifyAttributes("uid=" + username, DirContext.REPLACE_ATTRIBUTE, attributes);
}

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

private void update(DirContext ctx, Update update) {
    try {/*  w w w . ja  v a2 s . c o  m*/
        ctx.modifyAttributes(update.getName(), DirContext.REPLACE_ATTRIBUTE, update.getAttributes());
    } catch (NamingException e) {
        throw new OXFException("LDAP Update Failed", e);
    }
}