Search in sources :

Example 31 with Attribute

use of org.forgerock.opendj.ldap.Attribute in project OpenAM by OpenRock.

the class DataLayer method getAttributes.

/**
     * Returns attributes for the given attribute names.
     * 
     * @param principal Authentication Principal.
     * @param guid Distinguished name.
     * @param attrNames Attribute names.
     * @return collection of Attr.
     *
     * @supported.api
     */
public Collection<Attr> getAttributes(Principal principal, Guid guid, Collection<String> attrNames) {
    String id = guid.getDn();
    SearchRequest request = LDAPRequests.newSearchRequest(id, SearchScope.BASE_OBJECT, "(objectclass=*)", attrNames.toArray(EMPTY_STRING_ARRAY));
    ConnectionEntryReader ldapEntry;
    try {
        ldapEntry = readLDAPEntry(principal, request);
        if (ldapEntry == null) {
            debug.warning("No attributes returned may not have permission to read");
            return Collections.emptySet();
        }
        Collection<Attr> attributes = new ArrayList<>();
        while (ldapEntry.hasNext()) {
            if (ldapEntry.isEntry()) {
                SearchResultEntry entry = ldapEntry.readEntry();
                for (Attribute attr : entry.getAllAttributes()) {
                    attributes.add(new Attr(attr));
                }
            }
        }
        return attributes;
    } catch (Exception e) {
        debug.warning("Exception in DataLayer.getAttributes for DN: {}", id, e);
        return null;
    }
}
Also used : SearchRequest(org.forgerock.opendj.ldap.requests.SearchRequest) ConnectionEntryReader(org.forgerock.opendj.ldif.ConnectionEntryReader) Attribute(org.forgerock.opendj.ldap.Attribute) ArrayList(java.util.ArrayList) ByteString(org.forgerock.opendj.ldap.ByteString) Attr(com.iplanet.services.ldap.Attr) LDAPServiceException(com.iplanet.services.ldap.LDAPServiceException) LdapException(org.forgerock.opendj.ldap.LdapException) IOException(java.io.IOException) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry)

Example 32 with Attribute

use of org.forgerock.opendj.ldap.Attribute in project OpenAM by OpenRock.

the class DataLayer method addEntry.

/**
     * Adds entry to the server.
     * 
     * @param principal Authenticated Principal.
     * @param guid Distinguished name.
     * @param attrSet attribute set containing name/value pairs.
     * @exception AccessRightsException if insufficient access>
     * @exception EntryAlreadyExistsException if the entry already exists.
     * @exception UMSException if fail to add entry.
     *
     * @supported.api
     */
public void addEntry(java.security.Principal principal, Guid guid, AttrSet attrSet) throws UMSException {
    String id = guid.getDn();
    ResultCode errorCode;
    try {
        AddRequest request = LDAPRequests.newAddRequest(id);
        for (Attribute attribute : attrSet.toLDAPAttributeSet()) {
            request.addAttribute(attribute);
        }
        int retry = 0;
        while (retry <= connNumRetry) {
            if (debug.messageEnabled()) {
                debug.message("DataLayer.addEntry retry: " + retry);
            }
            try (Connection conn = getConnection(principal)) {
                conn.add(request);
                return;
            } catch (LdapException e) {
                errorCode = e.getResult().getResultCode();
                if (!retryErrorCodes.contains(errorCode) || retry == connNumRetry) {
                    throw e;
                }
                retry++;
                try {
                    Thread.sleep(connRetryInterval);
                } catch (InterruptedException ex) {
                }
            }
        }
    } catch (LdapException e) {
        if (debug.warningEnabled()) {
            debug.warning("Exception in DataLayer.addEntry for DN: " + id, e);
        }
        errorCode = e.getResult().getResultCode();
        String[] args = { id };
        if (ResultCode.ENTRY_ALREADY_EXISTS.equals(errorCode)) {
            throw new EntryAlreadyExistsException(i18n.getString(IUMSConstants.ENTRY_ALREADY_EXISTS, args), e);
        } else if (ResultCode.INSUFFICIENT_ACCESS_RIGHTS.equals(errorCode)) {
            throw new AccessRightsException(i18n.getString(IUMSConstants.INSUFFICIENT_ACCESS_ADD, args), e);
        } else {
            throw new UMSException(i18n.getString(IUMSConstants.UNABLE_TO_ADD_ENTRY, args), e);
        }
    }
}
Also used : AddRequest(org.forgerock.opendj.ldap.requests.AddRequest) Attribute(org.forgerock.opendj.ldap.Attribute) Connection(org.forgerock.opendj.ldap.Connection) ByteString(org.forgerock.opendj.ldap.ByteString) LdapException(org.forgerock.opendj.ldap.LdapException) ResultCode(org.forgerock.opendj.ldap.ResultCode)

Example 33 with Attribute

use of org.forgerock.opendj.ldap.Attribute in project OpenAM by OpenRock.

the class DJLDAPv3Repo method getFilteredRoleMemberships.

/**
     * Returns the filtered and non-filtered role memberships for this given user. This will execute a read on the user
     * entry to retrieve the nsRole attribute. The values of the attribute will be returned along with the non-filtered
     * role memberships.
     *
     * @param dn The DN of the user identity.
     * @return The DNs of the filtered roles this user is member of.
     * @throws IdRepoException If there was an error while retrieving the filtered or non-filtered role membership
     * information.
     */
private Set<String> getFilteredRoleMemberships(String dn) throws IdRepoException {
    Set<String> results = new CaseInsensitiveHashSet();
    Connection conn = null;
    try {
        conn = connectionFactory.getConnection();
        SearchResultEntry entry = conn.searchSingleEntry(LDAPRequests.newSingleEntrySearchRequest(dn, roleAttr));
        Attribute attr = entry.getAttribute(roleAttr);
        if (attr != null) {
            results.addAll(LDAPUtils.getAttributeValuesAsStringSet(attr));
        }
    } catch (LdapException ere) {
        DEBUG.error("An error occurred while trying to retrieve filtered role memberships for " + dn + " using " + roleAttr + " attribute", ere);
        handleErrorResult(ere);
    } finally {
        IOUtils.closeIfNotNull(conn);
    }
    results.addAll(getRoleMemberships(dn));
    return results;
}
Also used : CaseInsensitiveHashSet(com.sun.identity.common.CaseInsensitiveHashSet) Attribute(org.forgerock.opendj.ldap.Attribute) LinkedAttribute(org.forgerock.opendj.ldap.LinkedAttribute) Connection(org.forgerock.opendj.ldap.Connection) ByteString(org.forgerock.opendj.ldap.ByteString) LdapException(org.forgerock.opendj.ldap.LdapException) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry)

Example 34 with Attribute

use of org.forgerock.opendj.ldap.Attribute in project OpenAM by OpenRock.

the class DJLDAPv3Repo method getGroupMembers.

/**
     * Returns the DNs of the members of this group. If the MemberURL attribute has been configured, then this
     * will also try to retrieve dynamic group members using the memberURL.
     *
     * @param dn The DN of the group to query.
     * @return The DNs of the members.
     * @throws IdRepoException If there is an error while trying to retrieve the members.
     */
private Set<String> getGroupMembers(String dn) throws IdRepoException {
    Set<String> results = new HashSet<String>();
    Connection conn = null;
    String[] attrs;
    if (memberURLAttr != null) {
        attrs = new String[] { uniqueMemberAttr, memberURLAttr };
    } else {
        attrs = new String[] { uniqueMemberAttr };
    }
    try {
        conn = connectionFactory.getConnection();
        SearchResultEntry entry = conn.searchSingleEntry(LDAPRequests.newSingleEntrySearchRequest(dn, attrs));
        Attribute attr = entry.getAttribute(uniqueMemberAttr);
        if (attr != null) {
            results.addAll(LDAPUtils.getAttributeValuesAsStringSet(attr));
        } else if (memberURLAttr != null) {
            attr = entry.getAttribute(memberURLAttr);
            if (attr != null) {
                for (ByteString byteString : attr) {
                    LDAPUrl url = LDAPUrl.valueOf(byteString.toString());
                    SearchRequest searchRequest = LDAPRequests.newSearchRequest(url.getName(), url.getScope(), url.getFilter(), DN_ATTR);
                    searchRequest.setTimeLimit(defaultTimeLimit);
                    searchRequest.setSizeLimit(defaultSizeLimit);
                    ConnectionEntryReader reader = conn.search(searchRequest);
                    while (reader.hasNext()) {
                        if (reader.isEntry()) {
                            results.add(reader.readEntry().getName().toString());
                        } else {
                            //ignore search result references
                            reader.readReference();
                        }
                    }
                }
            }
        }
    } catch (LdapException ere) {
        DEBUG.error("An error occurred while retrieving group members for " + dn, ere);
        handleErrorResult(ere);
    } catch (SearchResultReferenceIOException srrioe) {
        //should never ever happen...
        DEBUG.error("Got reference instead of entry", srrioe);
        throw newIdRepoException(IdRepoErrorCode.SEARCH_FAILED, CLASS_NAME);
    } finally {
        IOUtils.closeIfNotNull(conn);
    }
    return results;
}
Also used : SearchRequest(org.forgerock.opendj.ldap.requests.SearchRequest) Attribute(org.forgerock.opendj.ldap.Attribute) LinkedAttribute(org.forgerock.opendj.ldap.LinkedAttribute) ByteString(org.forgerock.opendj.ldap.ByteString) Connection(org.forgerock.opendj.ldap.Connection) ByteString(org.forgerock.opendj.ldap.ByteString) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) ConnectionEntryReader(org.forgerock.opendj.ldif.ConnectionEntryReader) LDAPUrl(org.forgerock.opendj.ldap.LDAPUrl) LdapException(org.forgerock.opendj.ldap.LdapException) CaseInsensitiveHashSet(com.sun.identity.common.CaseInsensitiveHashSet) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry)

Example 35 with Attribute

use of org.forgerock.opendj.ldap.Attribute in project OpenAM by OpenRock.

the class LDAPRoles method getUserRoles.

/**
     *  returns user's roles from userLDAPRoleCache if found, 
     *  else gets users roles from the directory
     *  @return <code>Set</code> of Role DNs.
     */
private Set getUserRoles(SSOToken token, SearchResultEntry userEntry) throws SSOException, PolicyException {
    if (token == null) {
        return null;
    }
    String tokenIDStr = token.getTokenID().toString();
    Map serverRoleMap = null;
    if ((serverRoleMap = (Map) userLDAPRoleCache.get(tokenIDStr)) != null) {
        Object[] element = (Object[]) serverRoleMap.get(ldapServer);
        if (element != null) {
            long timeToLive = (element[0] == null) ? 0 : ((Long) element[0]).longValue();
            long currentTime = System.currentTimeMillis();
            if (timeToLive > currentTime) {
                if (debug.messageEnabled()) {
                    debug.message("LDAPRoles.getUserRoles():" + " get the nsrole values from cache.\n");
                }
                return (Set) element[1];
            }
        }
    }
    // add or update the cache entry.
    // we come here either the token is not registered with the
    // cache or the cache element is out of date. 
    // get the user DN from the directory server.
    Set<String> roles = new HashSet<>();
    if (userEntry != null) {
        Attribute attribute = userEntry.getAttribute(LDAP_USER_ROLE_ATTR);
        if (attribute != null) {
            for (ByteString value : attribute) {
                roles.add(DN.valueOf(value.toString()).toString());
            }
        }
        // If the cache is enabled
        if (SubjectEvaluationCache.getSubjectEvalTTL() > 0) {
            Object[] elem = new Object[2];
            elem[0] = new Long(System.currentTimeMillis() + SubjectEvaluationCache.getSubjectEvalTTL());
            elem[1] = roles;
            serverRoleMap = null;
            if ((serverRoleMap = (Map) userLDAPRoleCache.get(tokenIDStr)) == null) {
                serverRoleMap = Collections.synchronizedMap(new HashMap());
                serverRoleMap.put(ldapServer, elem);
                userLDAPRoleCache.put(tokenIDStr, serverRoleMap);
            } else {
                serverRoleMap.put(ldapServer, elem);
            }
        }
    }
    return roles;
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) Attribute(org.forgerock.opendj.ldap.Attribute) HashMap(java.util.HashMap) ByteString(org.forgerock.opendj.ldap.ByteString) ByteString(org.forgerock.opendj.ldap.ByteString) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet)

Aggregations

Attribute (org.forgerock.opendj.ldap.Attribute)48 ByteString (org.forgerock.opendj.ldap.ByteString)35 LdapException (org.forgerock.opendj.ldap.LdapException)30 SearchResultEntry (org.forgerock.opendj.ldap.responses.SearchResultEntry)28 Connection (org.forgerock.opendj.ldap.Connection)25 ConnectionEntryReader (org.forgerock.opendj.ldif.ConnectionEntryReader)16 HashSet (java.util.HashSet)14 IOException (java.io.IOException)13 LinkedAttribute (org.forgerock.opendj.ldap.LinkedAttribute)11 SearchRequest (org.forgerock.opendj.ldap.requests.SearchRequest)10 SearchResultReferenceIOException (org.forgerock.opendj.ldap.SearchResultReferenceIOException)9 CaseInsensitiveHashSet (com.sun.identity.common.CaseInsensitiveHashSet)8 FileNotFoundException (java.io.FileNotFoundException)6 ArrayList (java.util.ArrayList)6 LinkedHashSet (java.util.LinkedHashSet)6 Set (java.util.Set)6 Modification (org.forgerock.opendj.ldap.Modification)6 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)5 HashMap (java.util.HashMap)5 ModifyRequest (org.forgerock.opendj.ldap.requests.ModifyRequest)5