Example usage for javax.naming.directory BasicAttribute BasicAttribute

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

Introduction

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

Prototype

public BasicAttribute(String id) 

Source Link

Document

Constructs a new instance of an unordered attribute with no value.

Usage

From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java

protected void addLDAPRole(RoleContext context) throws UserStoreException {

    String roleName = context.getRoleName();
    String[] userList = context.getMembers();
    String groupEntryObjectClass = ((LDAPRoleContext) context).getGroupEntryObjectClass();
    String groupNameAttribute = ((LDAPRoleContext) context).getRoleNameProperty();
    String searchBase = ((LDAPRoleContext) context).getSearchBase();

    if ((userList == null || userList.length == 0) && !emptyRolesAllowed) {
        String errorMessage = "Can not create empty role. There should be at least " + "one user for the role.";
        throw new UserStoreException(errorMessage);
    } else if (userList == null && emptyRolesAllowed
            || userList != null && userList.length > 0 && !emptyRolesAllowed || emptyRolesAllowed) {

        // if (userList.length > 0) {
        DirContext mainDirContext = this.connectionSource.getContext();
        DirContext groupContext = null;
        NamingEnumeration<SearchResult> results = null;

        try {/*from  w ww  .  j a v a 2s.  co  m*/
            // create the attribute set for group entry
            Attributes groupAttributes = new BasicAttributes(true);

            // create group entry's object class attribute
            Attribute objectClassAttribute = new BasicAttribute(LDAPConstants.OBJECT_CLASS_NAME);
            objectClassAttribute.add(groupEntryObjectClass);
            groupAttributes.put(objectClassAttribute);

            // create cn attribute
            Attribute cnAttribute = new BasicAttribute(groupNameAttribute);
            cnAttribute.add(roleName);
            groupAttributes.put(cnAttribute);
            // following check is for if emptyRolesAllowed made this
            // code executed.
            if (userList != null && userList.length > 0) {

                String memberAttributeName = realmConfig
                        .getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE);
                Attribute memberAttribute = new BasicAttribute(memberAttributeName);
                for (String userName : userList) {

                    if (userName == null || userName.trim().length() == 0) {
                        continue;
                    }
                    // search the user in user search base
                    String searchFilter = realmConfig
                            .getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER);
                    searchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(userName));
                    results = searchInUserBase(searchFilter, new String[] {}, SearchControls.SUBTREE_SCOPE,
                            mainDirContext);
                    // we assume only one user with the given user
                    // name under user search base.
                    SearchResult userResult = null;
                    if (results.hasMore()) {
                        userResult = results.next();
                    } else {
                        String errorMsg = "There is no user with the user name: " + userName
                                + " to be added to this role.";
                        logger.error(errorMsg);
                        throw new UserStoreException(errorMsg);
                    }
                    // get his DN
                    String userEntryDN = userResult.getNameInNamespace();
                    // put it as member-attribute value
                    memberAttribute.add(userEntryDN);
                }
                groupAttributes.put(memberAttribute);
            }

            groupContext = (DirContext) mainDirContext.lookup(searchBase);
            NameParser ldapParser = groupContext.getNameParser("");
            /*
             * Name compoundGroupName = ldapParser.parse(groupNameAttributeName + "=" +
             * roleName);
             */
            Name compoundGroupName = ldapParser.parse("cn=" + roleName);
            groupContext.bind(compoundGroupName, null, groupAttributes);

        } catch (NamingException e) {
            String errorMsg = "Role: " + roleName + " could not be added.";
            if (log.isDebugEnabled()) {
                log.debug(errorMsg, e);
            }
            throw new UserStoreException(errorMsg, e);
        } catch (Exception e) {
            String errorMsg = "Role: " + roleName + " could not be added.";
            if (log.isDebugEnabled()) {
                log.debug(errorMsg, e);
            }
            throw new UserStoreException(errorMsg, e);
        } finally {
            JNDIUtil.closeNamingEnumeration(results);
            JNDIUtil.closeContext(groupContext);
            JNDIUtil.closeContext(mainDirContext);
        }

    }

}

From source file:org.nuxeo.ecm.directory.ldap.LDAPReference.java

/**
 * Remove existing statically defined links for the given target id (dynamic references remain unaltered)
 *
 * @see org.nuxeo.ecm.directory.Reference#removeLinksForTarget(String)
 *//*from  ww  w.ja  v  a2  s .  c o m*/
@Override
public void removeLinksForTarget(String targetId) throws DirectoryException {
    if (!isStatic()) {
        // nothing to do: dynamic references cannot be updated
        return;
    }
    LDAPDirectory ldapTargetDirectory = (LDAPDirectory) getTargetDirectory();
    LDAPDirectory ldapSourceDirectory = (LDAPDirectory) getSourceDirectory();
    String attributeId = getStaticAttributeId();
    try (LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession();
            LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession()) {
        if (!sourceSession.isReadOnly()) {
            // get the dn of the target that matches targetId
            String targetAttributeValue;

            if (staticAttributeIdIsDn) {
                SearchResult targetLdapEntry = targetSession.getLdapEntry(targetId);
                if (targetLdapEntry == null) {
                    String rdnAttribute = ldapTargetDirectory.getDescriptor().getRdnAttribute();
                    if (!rdnAttribute.equals(targetSession.idAttribute)) {
                        log.warn(String.format(
                                "cannot remove links to missing entry %s in directory %s for reference %s",
                                targetId, ldapTargetDirectory.getName(), this));
                        return;
                    }
                    // the entry might have already been deleted, try to
                    // re-forge it if possible (might not work if scope is
                    // subtree)
                    targetAttributeValue = String.format("%s=%s,%s", rdnAttribute, targetId,
                            ldapTargetDirectory.getDescriptor().getSearchBaseDn());
                } else {
                    targetAttributeValue = pseudoNormalizeDn(targetLdapEntry.getNameInNamespace());
                }
            } else {
                targetAttributeValue = targetId;
            }

            // build a LDAP query to find entries that point to the target
            String searchFilter = String.format("(%s=%s)", attributeId, targetAttributeValue);
            String sourceFilter = ldapSourceDirectory.getBaseFilter();

            if (sourceFilter != null && !"".equals(sourceFilter)) {
                searchFilter = String.format("(&(%s)(%s))", searchFilter, sourceFilter);
            }

            SearchControls scts = new SearchControls();
            scts.setSearchScope(ldapSourceDirectory.getDescriptor().getSearchScope());
            scts.setReturningAttributes(new String[] { attributeId });

            // find all source entries that point to the target key and
            // clean
            // those references
            if (log.isDebugEnabled()) {
                log.debug(String.format(
                        "LDAPReference.removeLinksForTarget(%s): LDAP search baseDn='%s' "
                                + " filter='%s' scope='%s' [%s]",
                        targetId, sourceSession.searchBaseDn, searchFilter, scts.getSearchScope(), this));
            }
            NamingEnumeration<SearchResult> results = sourceSession.dirContext
                    .search(sourceSession.searchBaseDn, searchFilter, scts);
            String emptyRefMarker = ldapSourceDirectory.getDescriptor().getEmptyRefMarker();
            Attributes emptyAttribute = new BasicAttributes(attributeId, emptyRefMarker);

            try {
                while (results.hasMore()) {
                    SearchResult result = results.next();
                    Attributes attrs = result.getAttributes();
                    Attribute attr = attrs.get(attributeId);
                    try {
                        if (attr.size() == 1) {
                            // the attribute holds the last reference, put
                            // the
                            // empty ref. marker before removing the
                            // attribute
                            // since empty attribute are often not allowed
                            // by
                            // the server schema
                            if (log.isDebugEnabled()) {
                                log.debug(String.format(
                                        "LDAPReference.removeLinksForTarget(%s): LDAP modifyAttributes key='%s' "
                                                + "mod_op='ADD_ATTRIBUTE' attrs='%s' [%s]",
                                        targetId, result.getNameInNamespace(), attrs, this));
                            }
                            sourceSession.dirContext.modifyAttributes(result.getNameInNamespace(),
                                    DirContext.ADD_ATTRIBUTE, emptyAttribute);
                        }
                        // remove the reference to the target key
                        attrs = new BasicAttributes();
                        attr = new BasicAttribute(attributeId);
                        attr.add(targetAttributeValue);
                        attrs.put(attr);
                        if (log.isDebugEnabled()) {
                            log.debug(String.format(
                                    "LDAPReference.removeLinksForTarget(%s): LDAP modifyAttributes key='%s' "
                                            + "mod_op='REMOVE_ATTRIBUTE' attrs='%s' [%s]",
                                    targetId, result.getNameInNamespace(), attrs, this));
                        }
                        sourceSession.dirContext.modifyAttributes(result.getNameInNamespace(),
                                DirContext.REMOVE_ATTRIBUTE, attrs);
                    } 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 target %s",
                                    getFieldName(), targetId));
                        } else {
                            // this is a real schema configuration problem,
                            // wrapup the exception
                            throw new DirectoryException(e);
                        }
                    }
                }
            } finally {
                results.close();
            }
        }
    } catch (NamingException e) {
        throw new DirectoryException("removeLinksForTarget failed: " + e.getMessage(), e);
    }
}

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

/**
 *Strips all the values from the attributes in <code>input</code>. This is performed to be able to delete 
 *the attributes without having to match the values. If values exist they must be exactly matched too in
 *order to delete the attribute./*from  w w w.  j  a v a  2 s .  c  om*/
 */
protected Attributes removeValuesFromAttributes(Attributes input) {
    Attributes result = new BasicAttributes(true);
    // ignore attribute name case
    NamingEnumeration enumeration = input.getIDs();
    while (enumeration.hasMoreElements()) {
        String attrId = (String) enumeration.nextElement();
        result.put(new BasicAttribute(attrId));
    }
    return result;
}

From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java

/**
 * Either delete or add user from/to group.
 *
 * @param userNameDN : distinguish name of user entry.
 * @param groupRDN   : relative distinguish name of group entry
 * @param modifyType : modify attribute type in DirCOntext.
 * @throws UserStoreException// w  w  w  .  j ava 2s. com
 */
protected void modifyUserInRole(String userNameDN, String groupRDN, int modifyType, String searchBase)
        throws UserStoreException {

    if (log.isDebugEnabled()) {
        logger.debug("Modifying role: " + groupRDN + " with type: " + modifyType + " user: " + userNameDN
                + " in search base: " + searchBase);
    }

    DirContext mainDirContext = null;
    DirContext groupContext = null;
    try {
        mainDirContext = this.connectionSource.getContext();
        groupContext = (DirContext) mainDirContext.lookup(searchBase);
        String memberAttributeName = realmConfig.getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE);
        Attributes modifyingAttributes = new BasicAttributes(true);
        Attribute memberAttribute = new BasicAttribute(memberAttributeName);
        memberAttribute.add(userNameDN);
        modifyingAttributes.put(memberAttribute);

        groupContext.modifyAttributes(groupRDN, modifyType, modifyingAttributes);
        if (log.isDebugEnabled()) {
            logger.debug("User: " + userNameDN + " was successfully " + "modified in LDAP group: " + groupRDN);
        }
    } catch (NamingException e) {
        String errorMessage = "Error occurred while modifying user entry: " + userNameDN + " in LDAP role: "
                + groupRDN;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage);
    } finally {
        JNDIUtil.closeContext(groupContext);
        JNDIUtil.closeContext(mainDirContext);
    }
}

From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java

/**
 * Either delete or add user from/to group.
 *
 * @param userNameDN : distinguish name of user entry.
 * @param groupRDN   : relative distinguish name of group entry
 * @param modifyType : modify attribute type in DirCOntext.
 * @throws UserStoreException If an error occurs while updating.
 *//*from  w w w .j a va2  s . com*/
protected void modifyUserInRole(String userNameDN, String groupRDN, int modifyType, String searchBase)
        throws UserStoreException {

    if (log.isDebugEnabled()) {
        log.debug("Modifying role: " + groupRDN + " with type: " + modifyType + " user: " + userNameDN
                + " in search base: " + searchBase);
    }

    DirContext mainDirContext = null;
    DirContext groupContext = null;
    try {
        mainDirContext = this.connectionSource.getContext();
        groupContext = (DirContext) mainDirContext.lookup(searchBase);
        String memberAttributeName = userStoreProperties.get(LDAPConstants.MEMBERSHIP_ATTRIBUTE);
        Attributes modifyingAttributes = new BasicAttributes(true);
        Attribute memberAttribute = new BasicAttribute(memberAttributeName);
        memberAttribute.add(userNameDN);
        modifyingAttributes.put(memberAttribute);

        groupContext.modifyAttributes(groupRDN, modifyType, modifyingAttributes);
        if (log.isDebugEnabled()) {
            log.debug("User: " + userNameDN + " was successfully " + "modified in LDAP group: " + groupRDN);
        }
    } catch (NamingException e) {
        String errorMessage = "Error occurred while modifying user entry: " + userNameDN + " in LDAP role: "
                + groupRDN;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage);
    } finally {
        JNDIUtil.closeContext(groupContext);
        JNDIUtil.closeContext(mainDirContext);
    }
}