Example usage for javax.naming.directory DirContext ADD_ATTRIBUTE

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

Introduction

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

Prototype

int ADD_ATTRIBUTE

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

Click Source Link

Document

This constant specifies to add an attribute with the specified values.

Usage

From source file:org.apache.archiva.redback.common.ldap.role.DefaultLdapRoleMapper.java

public boolean saveUserRole(String roleName, String username, DirContext context) throws MappingException {

    String groupName = findGroupName(roleName);

    if (groupName == null) {
        log.warn("no group found for role '{}", roleName);
        groupName = roleName;/*from  w  ww .j a  va 2 s.  co m*/
    }

    NamingEnumeration<SearchResult> namingEnumeration = null;
    try {
        SearchControls searchControls = new SearchControls();

        searchControls.setDerefLinkFlag(true);
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        String filter = "objectClass=" + getLdapGroupClass();

        namingEnumeration = context.search("cn=" + groupName + "," + getGroupsDn(), filter, searchControls);

        while (namingEnumeration.hasMore()) {
            SearchResult searchResult = namingEnumeration.next();
            Attribute attribute = searchResult.getAttributes().get(getLdapGroupMember());
            if (attribute == null) {
                BasicAttribute basicAttribute = new BasicAttribute(getLdapGroupMember());
                basicAttribute.add(this.userIdAttribute + "=" + username + "," + getBaseDn());
                context.modifyAttributes("cn=" + groupName + "," + getGroupsDn(), new ModificationItem[] {
                        new ModificationItem(DirContext.ADD_ATTRIBUTE, basicAttribute) });
            } else {
                attribute.add(this.userIdAttribute + "=" + username + "," + getBaseDn());
                context.modifyAttributes("cn=" + groupName + "," + getGroupsDn(), new ModificationItem[] {
                        new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attribute) });
            }
            return true;
        }

        return false;
    } catch (LdapException e) {
        throw new MappingException(e.getMessage(), e);
    } catch (NamingException e) {
        throw new MappingException(e.getMessage(), e);
    }

    finally {
        if (namingEnumeration != null) {
            try {
                namingEnumeration.close();
            } catch (NamingException e) {
                log.warn("failed to close search results", e);
            }
        }
    }
}

From source file:it.infn.ct.security.utilities.LDAPUtils.java

public static boolean registerUser(LDAPUser lus, UserRequest userReq, String OrgDN, String OrgUDN) {
    boolean registration = false;
    DirContext ctx = null;//from w w  w. j  ava2  s  .  c o  m
    try {
        ctx = getAuthContext(lus.getUsername(), lus.getPassword());

        Attributes attrsBag = new BasicAttributes();

        Attribute oc = new BasicAttribute("objectClass");
        oc.add("inetOrgPerson");
        oc.add("organizationalPerson");
        oc.add("person");
        oc.add("top");
        attrsBag.put(oc);

        Attribute sn = new BasicAttribute("sn", userReq.getSurname());
        attrsBag.put(sn);

        Attribute cn = new BasicAttribute("cn", userReq.getUsername());
        attrsBag.put(cn);

        Attribute dispName = new BasicAttribute("displayName", userReq.getUsername());
        attrsBag.put(dispName);

        Attribute uPass = new BasicAttribute("userPassword", userReq.getPassword());
        attrsBag.put(uPass);

        Attribute regAdd = new BasicAttribute("registeredAddress", userReq.getPreferredMail());
        attrsBag.put(regAdd);

        if (userReq.getTitle() != null && !userReq.getTitle().isEmpty()) {
            Attribute title = new BasicAttribute("title", userReq.getTitle());
            attrsBag.put(title);
        }

        Attribute gName = new BasicAttribute("givenName", userReq.getGivenname());
        attrsBag.put(gName);

        Attribute inits = new BasicAttribute("initials", userReq.getGivenname().substring(0, 1).toUpperCase()
                + userReq.getSurname().substring(0, 1).toUpperCase());
        attrsBag.put(inits);

        Attribute mails = new BasicAttribute("mail");
        mails.add(userReq.getPreferredMail());
        for (String adMail : userReq.getAdditionalMails().split("[,\\s;]"))
            if (!adMail.isEmpty())
                mails.add(adMail.trim());
        attrsBag.put(mails);

        Attribute org = new BasicAttribute("o", OrgDN);
        attrsBag.put(org);

        if (OrgUDN != null && !OrgUDN.isEmpty()) {
            Attribute orgU = new BasicAttribute("ou", OrgUDN);
            attrsBag.put(orgU);
        }

        ResourceBundle rb = ResourceBundle.getBundle("ldap");
        ctx.createSubcontext("cn=" + userReq.getUsername() + "," + rb.getString("peopleRoot"), attrsBag);

        ModificationItem[] modItems = new ModificationItem[1];
        modItems[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute("uniqueMember",
                "cn=" + userReq.getUsername() + "," + rb.getString("peopleRoot")));

        ctx.modifyAttributes(rb.getString("usersGroup"), modItems);

        registration = true;
    } catch (NameNotFoundException ex) {
        _log.error(ex);
    } catch (NamingException e) {
        _log.error(e);
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
    }

    return registration;
}

From source file:it.infn.ct.security.utilities.LDAPUtils.java

public static boolean addMail(LDAPUser user, String newMail) {
    DirContext ctx = null;/*from  w  w  w  . j a  v a2  s  .c  om*/
    try {
        ctx = getAuthContext(user.getUsername(), user.getPassword());

        ModificationItem[] modItems = new ModificationItem[1];
        modItems[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute("mail", newMail));

        ResourceBundle rb = ResourceBundle.getBundle("ldap");

        ctx.modifyAttributes("cn=" + user.getUsername() + "," + rb.getString("peopleRoot"), modItems);
    } catch (NamingException ex) {
        _log.error(ex);
        return false;
    }

    return true;
}

From source file:edu.internet2.middleware.psp.ldap.LdapSpmlTarget.java

/**
 * Converts spml modifications to jndi modifications.
 * /*from w ww  .ja  v  a 2  s . c  o m*/
 * @param modification the spml modification
 * @return the jndi modifications
 * @throws PspException if a psp error occurs
 */
protected List<ModificationItem> getDsmlMods(Modification modification) throws PspException {
    List<ModificationItem> mods = new ArrayList<ModificationItem>();

    for (Object object : modification.getOpenContentElements(DSMLModification.class)) {
        DSMLModification dsmlModification = (DSMLModification) object;

        Attribute attribute = new BasicAttribute(dsmlModification.getName());

        DSMLValue[] dsmlValues = dsmlModification.getValues();
        for (DSMLValue dsmlValue : dsmlValues) {
            // for example, when <dsmlValue><dsmlValue/> and op is a replace
            if (!DatatypeHelper.isEmpty(dsmlValue.getValue())) {
                attribute.add(dsmlValue.getValue());
            }
        }

        int op = -1;
        if (dsmlModification.getOperation().equals(ModificationMode.ADD)) {
            op = DirContext.ADD_ATTRIBUTE;
        } else if (dsmlModification.getOperation().equals(ModificationMode.DELETE)) {
            op = DirContext.REMOVE_ATTRIBUTE;
        } else if (dsmlModification.getOperation().equals(ModificationMode.REPLACE)) {
            op = DirContext.REPLACE_ATTRIBUTE;
        } else {
            throw new PspException("Unknown dsml modification operation : " + dsmlModification.getOperation());
        }

        mods.add(new ModificationItem(op, attribute));
    }

    return mods;
}

From source file:CreateJavaSchema.java

/**
 * Writes schema modifications to the Active Directory schema immediately.
 */// w  w w  .  ja v a  2  s  . c  om
protected void flushADSchemaMods(DirContext rootCtx) throws NamingException {

    rootCtx.modifyAttributes("", new ModificationItem[] {
            new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute("schemaUpdateNow", "1")) });
}

From source file:edu.internet2.middleware.psp.ldap.LdapSpmlTarget.java

/**
 * Converts spml modifications to jndi modifications.
 * //from w w  w  .ja va 2  s . com
 * @param modification the spml modification
 * @return the jndi modifications
 * @throws PspException if a psp error occurs
 */
protected List<ModificationItem> getReferenceMods(Modification modification) throws PspException {
    List<ModificationItem> mods = new ArrayList<ModificationItem>();

    Map<String, List<Reference>> references = PSPUtil.getReferences(modification.getCapabilityData());

    if (references.isEmpty()) {
        return mods;
    }

    for (String typeOfReference : references.keySet()) {

        List<String> ids = new ArrayList<String>();
        for (Reference reference : references.get(typeOfReference)) {
            if (reference.getToPsoID().getTargetID().equals(getId())) {
                String id = reference.getToPsoID().getID();
                // fake empty string since the spml toolkit ignores an empty string psoID
                // if (id.equals(PSOReferencesDefinition.EMPTY_STRING)) {
                // id = "";
                // }
                if (id == null) {
                    id = "";
                }
                ids.add(id);
            }
        }

        Attribute attribute = new BasicAttribute(typeOfReference);
        for (String id : ids) {
            attribute.add(id);
        }

        int op = -1;
        if (modification.getModificationMode().equals(ModificationMode.ADD)) {
            op = DirContext.ADD_ATTRIBUTE;
        } else if (modification.getModificationMode().equals(ModificationMode.DELETE)) {
            op = DirContext.REMOVE_ATTRIBUTE;
        } else if (modification.getModificationMode().equals(ModificationMode.REPLACE)) {
            op = DirContext.REPLACE_ATTRIBUTE;
        } else {
            throw new PspException("Unknown modification operation : " + modification.getModificationMode());
        }

        mods.add(new ModificationItem(op, attribute));
    }

    return mods;
}

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;//  ww  w.  ja  v  a2  s  .co 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 performOperationChangeUnicodePwd(String entryName, ParameterResolutionContext prc,
        Map paramValueMap) throws SenderException, ParameterException {
    ModificationItem[] modificationItems = new ModificationItem[2];
    modificationItems[0] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE,
            new BasicAttribute("unicodePwd", encodeUnicodePwd((String) paramValueMap.get("oldPassword"))));
    modificationItems[1] = new ModificationItem(DirContext.ADD_ATTRIBUTE,
            new BasicAttribute("unicodePwd", encodeUnicodePwd((String) paramValueMap.get("newPassword"))));
    DirContext dirContext = null;
    try {/*www  . j a  va2 s  . com*/
        dirContext = getDirContext(paramValueMap);
        dirContext.modifyAttributes(entryName, modificationItems);
        return DEFAULT_RESULT_CHANGE_UNICODE_PWD_OK;
    } catch (NamingException e) {
        // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
        //   19 LDAP_CONSTRAINT_VIOLATION Indicates that the attribute value specified in a modify, add, or modify DN operation violates constraints placed on the attribute. The constraint can be one of size or content (string only, no binary).
        // AD:
        //   [LDAP: error code 19 - 0000052D: AtrErr: DSID-03191041, #1...
        if (e.getMessage().startsWith("[LDAP: error code 19 - ")) {
            if (log.isDebugEnabled())
                log.debug("Operation [" + getOperation()
                        + "] old password doesn't match or new password doesn't comply with policy for: "
                        + entryName);
            return DEFAULT_RESULT_CHANGE_UNICODE_PWD_NOK;
        } else {
            storeLdapException(e, prc);
            throw new SenderException(
                    "Exception in operation [" + getOperation() + "] entryName [" + entryName + "]", e);
        }
    } finally {
        closeDirContext(dirContext);
    }
}

From source file:org.apache.directory.studio.connection.core.io.api.DirectoryApiConnectionWrapper.java

/**
 * Converts a modification operation./*from   www.j a  v  a2s. c  o  m*/
 *
 * @param modificationOp
 *      a modification operation
 * @return
 *      the converted modification operation
 */
private ModificationOperation convertModificationOperation(int modificationOp) {
    if (modificationOp == DirContext.ADD_ATTRIBUTE) {
        return ModificationOperation.ADD_ATTRIBUTE;
    } else if (modificationOp == DirContext.REPLACE_ATTRIBUTE) {
        return ModificationOperation.REPLACE_ATTRIBUTE;
    } else if (modificationOp == DirContext.REMOVE_ATTRIBUTE) {
        return ModificationOperation.REMOVE_ATTRIBUTE;
    }

    return null;
}

From source file:org.apache.directory.studio.ldapbrowser.core.jobs.ImportDsmlRunnable.java

/**
 * Converts the modification operation from Shared LDAP to JNDI
 *
 * @param operation/*w w  w. j  av a  2s .c  o m*/
 *      the Shared LDAP modification operation
 * @return
 *      the equivalent modification operation in JNDI
 */
private int convertModificationOperation(ModificationOperation operation) {
    switch (operation) {
    case ADD_ATTRIBUTE:
        return DirContext.ADD_ATTRIBUTE;
    case REMOVE_ATTRIBUTE:
        return DirContext.REMOVE_ATTRIBUTE;
    case REPLACE_ATTRIBUTE:
        return DirContext.REPLACE_ATTRIBUTE;
    default:
        return 0;
    }
}