Search in sources :

Example 11 with Entry

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

the class DJLDAPv3Repo method create.

/**
     * Creates a new identity using the passed in attributes. The following steps will be performed with the passed in
     * data:
     * <ul>
     *  <li>The password will be encoded in case we are dealing with AD.</li>
     *  <li>If the attribute map contains the default status attribute, then it will be converted to the status values
     *      specified in the configuration.</li>
     *  <li>Performing creation attribute mapping, so certain attributes can have default values (coming from other
     *      attributes, or from the identity name if there is no mapping for the attribute).</li>
     *  <li>Removes all attributes that are not defined in the configuration.</li>
     * </ul>
     * If the default group member setting is being used and a new group identity is being created, the newly created
     * group will also have the default group member assigned.
     *
     * @param token Not used.
     * @param type The type of the identity.
     * @param name The name of the identity.
     * @param attrMap The attributes of the new identity, that needs to be stored.
     * @return The DN of the newly created identity
     * @throws IdRepoException If there is an error while creating the new identity, or if it's a group and there is a
     * problem while adding the default group member.
     */
@Override
public String create(SSOToken token, IdType type, String name, Map<String, Set<String>> attrMap) throws IdRepoException {
    if (DEBUG.messageEnabled()) {
        DEBUG.message("Create invoked on " + type + ": " + name + " attrMap = " + IdRepoUtils.getAttrMapWithoutPasswordAttrs(attrMap, null));
    }
    String dn = generateDN(type, name);
    Set<String> objectClasses = getObjectClasses(type);
    //First we should make sure that we wrap the attributes with a case insensitive hashmap.
    attrMap = new CaseInsensitiveHashMap(attrMap);
    byte[] encodedPwd = helper.encodePassword(type, attrMap.get(AD_UNICODE_PWD_ATTR));
    //Let's set the userstatus as it is configured in the datastore.
    mapUserStatus(type, attrMap);
    //In case some attributes are missing use the create attribute mapping to get those values.
    mapCreationAttributes(type, name, attrMap);
    //and lastly we should make sure that we get rid of the attributes that are not known by the datastore.
    attrMap = removeUndefinedAttributes(type, attrMap);
    Set<String> ocs = attrMap.get(OBJECT_CLASS_ATTR);
    if (ocs != null) {
        ocs.addAll(objectClasses);
    } else {
        attrMap.put(OBJECT_CLASS_ATTR, objectClasses);
    }
    attrMap.put(getSearchAttribute(type), asSet(name));
    Entry entry = new LinkedHashMapEntry(dn);
    Set<String> attributeValue;
    for (Map.Entry<String, Set<String>> attr : attrMap.entrySet()) {
        // Add only attributes whose values are not empty or null
        attributeValue = attr.getValue();
        if (attributeValue != null && !attributeValue.isEmpty()) {
            entry.addAttribute(attr.getKey(), attributeValue.toArray());
        }
    }
    if (type.equals(IdType.GROUP) && defaultGroupMember != null) {
        entry.addAttribute(uniqueMemberAttr, defaultGroupMember);
    }
    if (encodedPwd != null) {
        entry.replaceAttribute(AD_UNICODE_PWD_ATTR, encodedPwd);
    }
    Connection conn = null;
    try {
        conn = connectionFactory.getConnection();
        conn.add(LDAPRequests.newAddRequest(entry));
        if (type.equals(IdType.GROUP) && defaultGroupMember != null) {
            if (memberOfAttr != null) {
                ModifyRequest modifyRequest = LDAPRequests.newModifyRequest(defaultGroupMember);
                modifyRequest.addModification(ModificationType.ADD, memberOfAttr, dn);
                conn.modify(modifyRequest);
            }
        }
    } catch (LdapException ere) {
        DEBUG.error("Unable to add a new entry: " + name + " attrMap: " + IdRepoUtils.getAttrMapWithoutPasswordAttrs(attrMap, null), ere);
        if (ResultCode.ENTRY_ALREADY_EXISTS.equals(ere.getResult().getResultCode())) {
            throw IdRepoDuplicateObjectException.nameAlreadyExists(name);
        } else {
            handleErrorResult(ere);
        }
    } finally {
        IOUtils.closeIfNotNull(conn);
    }
    return dn;
}
Also used : SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry) LinkedHashMapEntry(org.forgerock.opendj.ldap.LinkedHashMapEntry) Entry(org.forgerock.opendj.ldap.Entry) Set(java.util.Set) CaseInsensitiveHashSet(com.sun.identity.common.CaseInsensitiveHashSet) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) CollectionUtils.asSet(org.forgerock.openam.utils.CollectionUtils.asSet) LinkedHashMapEntry(org.forgerock.opendj.ldap.LinkedHashMapEntry) Connection(org.forgerock.opendj.ldap.Connection) ByteString(org.forgerock.opendj.ldap.ByteString) ModifyRequest(org.forgerock.opendj.ldap.requests.ModifyRequest) Map(java.util.Map) HashMap(java.util.HashMap) CaseInsensitiveHashMap(com.sun.identity.common.CaseInsensitiveHashMap) LdapException(org.forgerock.opendj.ldap.LdapException) CaseInsensitiveHashMap(com.sun.identity.common.CaseInsensitiveHashMap)

Example 12 with Entry

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

the class SMSLdapObject method read.

/**
     * Reads in the object from persistent store, assuming that the guid and the
     * SSOToken are valid
     */
public Map<String, Set<String>> read(SSOToken token, String dn) throws SMSException, SSOException {
    if (dn == null || dn.length() == 0) {
        // This must not be possible return an exception.
        debug.error("SMSLdapObject: read():Null or Empty DN=" + dn);
        throw new SMSException(LdapException.newLdapException(ResultCode.NO_SUCH_OBJECT, getBundleString(IUMSConstants.SMS_INVALID_DN, dn)), "sms-NO_SUCH_OBJECT");
    }
    if (!LDAPUtils.isDN(dn)) {
        debug.warning("SMSLdapObject: Invalid DN=" + dn);
        String[] args = { dn };
        throw new SMSException(IUMSConstants.UMS_BUNDLE_NAME, "sms-INVALID_DN", args);
    }
    // Check if entry does not exist
    if (SMSNotificationManager.isCacheEnabled() && entriesNotPresent.contains(dn)) {
        debug.message("SMSLdapObject:read Entry not present: {} (checked in cache)", dn);
        return null;
    }
    Entry ldapEntry = null;
    int retry = 0;
    while (retry <= connNumRetry) {
        debug.message("SMSLdapObject.read() retry: {}", retry);
        ResultCode errorCode = null;
        try (Connection conn = getConnection(token.getPrincipal())) {
            ldapEntry = conn.searchSingleEntry(LDAPRequests.newSingleEntrySearchRequest(DN.valueOf(dn), getAttributeNames()));
            break;
        } catch (LdapException e) {
            errorCode = e.getResult().getResultCode();
            if (!retryErrorCodes.contains(errorCode) || retry == connNumRetry) {
                if (errorCode.equals(ResultCode.NO_SUCH_OBJECT)) {
                    // Add to not present Set
                    objectChanged(dn, DELETE);
                    debug.message("SMSLdapObject.read: entry not present: {}", dn);
                    break;
                } else {
                    debug.warning("SMSLdapObject.read: Error in accessing entry DN: {}", dn, e);
                    throw new SMSException(e, "sms-entry-cannot-access");
                }
            }
            retry++;
            try {
                Thread.sleep(connRetryInterval);
            } catch (InterruptedException ex) {
            // ignored
            }
        }
    }
    if (ldapEntry != null) {
        if (debug.messageEnabled()) {
            debug.message("SMSLdapObject.read(): reading entry: " + dn);
        }
        return SMSUtils.convertEntryToAttributesMap(ldapEntry);
    } else {
        return null;
    }
}
Also used : SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry) SMSDataEntry(com.sun.identity.sm.SMSDataEntry) SMSEntry(com.sun.identity.sm.SMSEntry) LinkedHashMapEntry(org.forgerock.opendj.ldap.LinkedHashMapEntry) Entry(org.forgerock.opendj.ldap.Entry) SMSException(com.sun.identity.sm.SMSException) Connection(org.forgerock.opendj.ldap.Connection) LdapException(org.forgerock.opendj.ldap.LdapException) ResultCode(org.forgerock.opendj.ldap.ResultCode)

Example 13 with Entry

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

the class LdapQueryBuilder method getEntries.

private Collection<Entry> getEntries(Connection connection) throws CoreTokenException {
    // Prepare the search
    Filter ldapFilter = getLDAPFilter();
    SearchRequest searchRequest = LDAPRequests.newSearchRequest(dataLayerConfiguration.getTokenStoreRootSuffix(), SearchScope.WHOLE_SUBTREE, ldapFilter, requestedAttributes);
    searchRequest.setSizeLimit(sizeLimit);
    if (isPagingResults()) {
        searchRequest = searchRequest.addControl(SimplePagedResultsControl.newControl(true, pageSize, pagingCookie));
    }
    // Perform the search
    Collection<Entry> entries = createResultsList();
    final Result result = handler.performSearch(connection, searchRequest, entries);
    if (isPagingResults()) {
        try {
            SimplePagedResultsControl control = result.getControl(SimplePagedResultsControl.DECODER, new DecodeOptions());
            if (control == null) {
                if (debug.warningEnabled()) {
                    debug.warning("There was no paged result control in the search response, it is recommended to " + "set the CTS user's size-limit at least to " + (pageSize + 1));
                }
                pagingCookie = getEmptyPagingCookie();
            } else {
                pagingCookie = control.getCookie();
            }
        } catch (DecodeException e) {
            throw new CoreTokenException("Failed to decode Paging Cookie", e);
        }
    }
    if (debug.messageEnabled()) {
        debug.message(MessageFormat.format(CoreTokenConstants.DEBUG_HEADER + "Query: matched {0} results\n" + "Search Request: {1}\n" + "Filter: {2}\n" + "Result: {3}", entries.size(), searchRequest, ldapFilter.toString(), result));
    }
    return entries;
}
Also used : SearchRequest(org.forgerock.opendj.ldap.requests.SearchRequest) Entry(org.forgerock.opendj.ldap.Entry) Filter(org.forgerock.opendj.ldap.Filter) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) SimplePagedResultsControl(org.forgerock.opendj.ldap.controls.SimplePagedResultsControl) DecodeException(org.forgerock.opendj.ldap.DecodeException) DecodeOptions(org.forgerock.opendj.ldap.DecodeOptions) Result(org.forgerock.opendj.ldap.responses.Result)

Example 14 with Entry

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

the class LdapTokenAttributeConversion method getEntry.

/**
     * Generate an Entry based on the given Token.
     *
     * @param token Non null Token to base the Entry on.
     *
     * @return An Entry suitable for LDAP operations. Includes the Object Class.
     */
public Entry getEntry(Token token) {
    Entry entry = new LinkedHashMapEntry(generateTokenDN(token));
    addObjectClass(entry);
    for (CoreTokenField field : token.getAttributeNames()) {
        String key = field.toString();
        // Token Type special case is an Enum
        if (CoreTokenField.TOKEN_TYPE.equals(field)) {
            TokenType type = token.getValue(field);
            entry.addAttribute(key, type.name());
            continue;
        }
        if (CoreTokenFieldTypes.isCalendar(field)) {
            Calendar calendar = token.getValue(field);
            String dateString = conversion.toLDAPDate(calendar);
            entry.addAttribute(key, dateString);
        } else if (CoreTokenFieldTypes.isByteArray(field)) {
            byte[] array = token.getValue(field);
            entry.addAttribute(key, array);
        } else if (CoreTokenFieldTypes.isInteger(field)) {
            Integer value = token.getValue(field);
            entry.addAttribute(key, value);
        } else if (CoreTokenFieldTypes.isString(field)) {
            String value = token.getValue(field);
            if (!value.isEmpty()) {
                entry.addAttribute(key, value);
            }
        } else {
            throw new IllegalStateException();
        }
    }
    return entry;
}
Also used : LinkedHashMapEntry(org.forgerock.opendj.ldap.LinkedHashMapEntry) Entry(org.forgerock.opendj.ldap.Entry) TokenType(org.forgerock.openam.tokens.TokenType) LinkedHashMapEntry(org.forgerock.opendj.ldap.LinkedHashMapEntry) Calendar(java.util.Calendar) CoreTokenField(org.forgerock.openam.tokens.CoreTokenField)

Example 15 with Entry

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

the class LdapQueryBuilderTest method shouldReturnTokensFromSearch.

@Test
public void shouldReturnTokensFromSearch() throws CoreTokenException {
    // Given
    final Collection<Entry> entries = new LinkedList<Entry>();
    entries.add(new LinkedHashMapEntry());
    entries.add(new LinkedHashMapEntry());
    // Slightly more fiddly mocking to provide behaviour when the mock is called.
    given(searchHandler.performSearch(any(Connection.class), any(SearchRequest.class), any(Collection.class))).will(new Answer() {

        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            Collection<Entry> list = (Collection<Entry>) invocationOnMock.getArguments()[2];
            list.addAll(entries);
            return null;
        }
    });
    // Ensure that the Token Conversion returns a Token
    given(tokenEntryConverter.convert(any(Entry.class), any(String[].class))).willReturn(new Token(Long.toString(System.currentTimeMillis()), TokenType.SESSION));
    // When
    Iterator<Collection<Token>> results = builder.execute(mockConnection);
    // Then
    verifyZeroInteractions(tokenEntryConverter);
    assertThat(results.next().size()).isEqualTo(entries.size());
    verify(tokenEntryConverter, times(2)).convert(any(Entry.class), any(String[].class));
}
Also used : SearchRequest(org.forgerock.opendj.ldap.requests.SearchRequest) Connection(org.forgerock.opendj.ldap.Connection) PartialToken(org.forgerock.openam.sm.datalayer.api.query.PartialToken) Token(org.forgerock.openam.cts.api.tokens.Token) LinkedList(java.util.LinkedList) Answer(org.mockito.stubbing.Answer) LinkedHashMapEntry(org.forgerock.opendj.ldap.LinkedHashMapEntry) Entry(org.forgerock.opendj.ldap.Entry) LinkedHashMapEntry(org.forgerock.opendj.ldap.LinkedHashMapEntry) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Collection(java.util.Collection) Test(org.testng.annotations.Test)

Aggregations

Entry (org.forgerock.opendj.ldap.Entry)15 LinkedHashMapEntry (org.forgerock.opendj.ldap.LinkedHashMapEntry)12 Test (org.testng.annotations.Test)8 Token (org.forgerock.openam.cts.api.tokens.Token)4 Attribute (org.forgerock.opendj.ldap.Attribute)4 Connection (org.forgerock.opendj.ldap.Connection)4 LdapException (org.forgerock.opendj.ldap.LdapException)4 SearchResultEntry (org.forgerock.opendj.ldap.responses.SearchResultEntry)4 SearchRequest (org.forgerock.opendj.ldap.requests.SearchRequest)3 SMSDataEntry (com.sun.identity.sm.SMSDataEntry)2 SMSEntry (com.sun.identity.sm.SMSEntry)2 SMSException (com.sun.identity.sm.SMSException)2 Calendar (java.util.Calendar)2 LinkedList (java.util.LinkedList)2 ByteString (org.forgerock.opendj.ldap.ByteString)2 ResultCode (org.forgerock.opendj.ldap.ResultCode)2 ModifyRequest (org.forgerock.opendj.ldap.requests.ModifyRequest)2 CaseInsensitiveHashMap (com.sun.identity.common.CaseInsensitiveHashMap)1 CaseInsensitiveHashSet (com.sun.identity.common.CaseInsensitiveHashSet)1 FileInputStream (java.io.FileInputStream)1