Search in sources :

Example 1 with MatchingRule

use of com.unboundid.ldap.matchingrules.MatchingRule in project ldapsdk by pingidentity.

the class InMemoryRequestHandler method processModifyDNRequest.

/**
 * Attempts to process the provided modify DN request.  The attempt will fail
 * if any of the following conditions is true:
 * <UL>
 *   <LI>There is a problem with any of the request controls.</LI>
 *   <LI>The modify DN request contains a malformed target DN, new RDN, or
 *       new superior DN.</LI>
 *   <LI>The original or new DN is that of the root DSE.</LI>
 *   <LI>The original or new DN is that of the subschema subentry.</LI>
 *   <LI>The new DN of the entry would conflict with the DN of an existing
 *       entry.</LI>
 *   <LI>The new DN of the entry would exist outside the set of defined
 *       base DNs.</LI>
 *   <LI>The new DN of the entry is not a defined base DN and does not exist
 *       immediately below an existing entry.</LI>
 * </UL>
 *
 * @param  messageID  The message ID of the LDAP message containing the modify
 *                    DN request.
 * @param  request    The modify DN request that was included in the LDAP
 *                    message that was received.
 * @param  controls   The set of controls included in the LDAP message.  It
 *                    may be empty if there were no controls, but will not be
 *                    {@code null}.
 *
 * @return  The {@link LDAPMessage} containing the response to send to the
 *          client.  The protocol op in the {@code LDAPMessage} must be an
 *          {@code ModifyDNResponseProtocolOp}.
 */
@Override()
@NotNull()
public LDAPMessage processModifyDNRequest(final int messageID, @NotNull final ModifyDNRequestProtocolOp request, @NotNull final List<Control> controls) {
    synchronized (entryMap) {
        // Sleep before processing, if appropriate.
        sleepBeforeProcessing();
        // Process the provided request controls.
        final Map<String, Control> controlMap;
        try {
            controlMap = RequestControlPreProcessor.processControls(LDAPMessage.PROTOCOL_OP_TYPE_MODIFY_DN_REQUEST, controls);
        } catch (final LDAPException le) {
            Debug.debugException(le);
            return new LDAPMessage(messageID, new ModifyDNResponseProtocolOp(le.getResultCode().intValue(), null, le.getMessage(), null));
        }
        final ArrayList<Control> responseControls = new ArrayList<>(1);
        // If this operation type is not allowed, then reject it.
        final boolean isInternalOp = controlMap.containsKey(OID_INTERNAL_OPERATION_REQUEST_CONTROL);
        if ((!isInternalOp) && (!config.getAllowedOperationTypes().contains(OperationType.MODIFY_DN))) {
            return new LDAPMessage(messageID, new ModifyDNResponseProtocolOp(ResultCode.UNWILLING_TO_PERFORM_INT_VALUE, null, ERR_MEM_HANDLER_MODIFY_DN_NOT_ALLOWED.get(), null));
        }
        // client is authenticated.
        if ((authenticatedDN.isNullDN() && config.getAuthenticationRequiredOperationTypes().contains(OperationType.MODIFY_DN))) {
            return new LDAPMessage(messageID, new ModifyDNResponseProtocolOp(ResultCode.INSUFFICIENT_ACCESS_RIGHTS_INT_VALUE, null, ERR_MEM_HANDLER_MODIFY_DN_REQUIRES_AUTH.get(), null));
        }
        // without actually doing any further processing.
        try {
            final ASN1OctetString txnID = processTransactionRequest(messageID, request, controlMap);
            if (txnID != null) {
                return new LDAPMessage(messageID, new ModifyDNResponseProtocolOp(ResultCode.SUCCESS_INT_VALUE, null, INFO_MEM_HANDLER_OP_IN_TXN.get(txnID.stringValue()), null));
            }
        } catch (final LDAPException le) {
            Debug.debugException(le);
            return new LDAPMessage(messageID, new ModifyDNResponseProtocolOp(le.getResultCode().intValue(), le.getMatchedDN(), le.getDiagnosticMessage(), StaticUtils.toList(le.getReferralURLs())), le.getResponseControls());
        }
        // Get the parsed target DN, new RDN, and new superior DN values.
        final DN dn;
        final Schema schema = schemaRef.get();
        try {
            dn = new DN(request.getDN(), schema);
        } catch (final LDAPException le) {
            Debug.debugException(le);
            return new LDAPMessage(messageID, new ModifyDNResponseProtocolOp(ResultCode.INVALID_DN_SYNTAX_INT_VALUE, null, ERR_MEM_HANDLER_MOD_DN_MALFORMED_DN.get(request.getDN(), le.getMessage()), null));
        }
        final RDN newRDN;
        try {
            newRDN = new RDN(request.getNewRDN(), schema);
        } catch (final LDAPException le) {
            Debug.debugException(le);
            return new LDAPMessage(messageID, new ModifyDNResponseProtocolOp(ResultCode.INVALID_DN_SYNTAX_INT_VALUE, null, ERR_MEM_HANDLER_MOD_DN_MALFORMED_NEW_RDN.get(request.getDN(), request.getNewRDN(), le.getMessage()), null));
        }
        final DN newSuperiorDN;
        final String newSuperiorString = request.getNewSuperiorDN();
        if (newSuperiorString == null) {
            newSuperiorDN = null;
        } else {
            try {
                newSuperiorDN = new DN(newSuperiorString, schema);
            } catch (final LDAPException le) {
                Debug.debugException(le);
                return new LDAPMessage(messageID, new ModifyDNResponseProtocolOp(ResultCode.INVALID_DN_SYNTAX_INT_VALUE, null, ERR_MEM_HANDLER_MOD_DN_MALFORMED_NEW_SUPERIOR.get(request.getDN(), request.getNewSuperiorDN(), le.getMessage()), null));
            }
        }
        // See if the target entry or one of its superiors is a smart referral.
        if (!controlMap.containsKey(ManageDsaITRequestControl.MANAGE_DSA_IT_REQUEST_OID)) {
            final Entry referralEntry = findNearestReferral(dn);
            if (referralEntry != null) {
                return new LDAPMessage(messageID, new ModifyDNResponseProtocolOp(ResultCode.REFERRAL_INT_VALUE, referralEntry.getDN(), INFO_MEM_HANDLER_REFERRAL_ENCOUNTERED.get(), getReferralURLs(dn, referralEntry)));
            }
        }
        // changelog entry.
        if (dn.isNullDN()) {
            return new LDAPMessage(messageID, new ModifyDNResponseProtocolOp(ResultCode.UNWILLING_TO_PERFORM_INT_VALUE, null, ERR_MEM_HANDLER_MOD_DN_ROOT_DSE.get(), null));
        } else if (dn.equals(subschemaSubentryDN)) {
            return new LDAPMessage(messageID, new ModifyDNResponseProtocolOp(ResultCode.UNWILLING_TO_PERFORM_INT_VALUE, null, ERR_MEM_HANDLER_MOD_DN_SOURCE_IS_SCHEMA.get(), null));
        } else if (dn.isDescendantOf(changeLogBaseDN, true)) {
            return new LDAPMessage(messageID, new ModifyDNResponseProtocolOp(ResultCode.UNWILLING_TO_PERFORM_INT_VALUE, null, ERR_MEM_HANDLER_MOD_DN_SOURCE_IS_CHANGELOG.get(), null));
        }
        // Construct the new DN.
        final DN newDN;
        if (newSuperiorDN == null) {
            final DN originalParent = dn.getParent();
            if (originalParent == null) {
                newDN = new DN(newRDN);
            } else {
                newDN = new DN(newRDN, originalParent);
            }
        } else {
            newDN = new DN(newRDN, newSuperiorDN);
        }
        // If the new DN matches the old DN, then fail.
        if (newDN.equals(dn)) {
            return new LDAPMessage(messageID, new ModifyDNResponseProtocolOp(ResultCode.UNWILLING_TO_PERFORM_INT_VALUE, null, ERR_MEM_HANDLER_MOD_DN_NEW_DN_SAME_AS_OLD.get(request.getDN()), null));
        }
        // If the new DN is below a smart referral, then fail.
        if (!controlMap.containsKey(ManageDsaITRequestControl.MANAGE_DSA_IT_REQUEST_OID)) {
            final Entry referralEntry = findNearestReferral(newDN);
            if (referralEntry != null) {
                return new LDAPMessage(messageID, new ModifyDNResponseProtocolOp(ResultCode.UNWILLING_TO_PERFORM_INT_VALUE, referralEntry.getDN(), ERR_MEM_HANDLER_MOD_DN_NEW_DN_BELOW_REFERRAL.get(request.getDN(), referralEntry.getDN().toString(), newDN.toString()), null));
            }
        }
        // If the target entry doesn't exist, then fail.
        final Entry originalEntry = entryMap.get(dn);
        if (originalEntry == null) {
            return new LDAPMessage(messageID, new ModifyDNResponseProtocolOp(ResultCode.NO_SUCH_OBJECT_INT_VALUE, getMatchedDNString(dn), ERR_MEM_HANDLER_MOD_DN_NO_SUCH_ENTRY.get(request.getDN()), null));
        }
        // If the new DN matches the subschema subentry DN, then fail.
        if (newDN.equals(subschemaSubentryDN)) {
            return new LDAPMessage(messageID, new ModifyDNResponseProtocolOp(ResultCode.ENTRY_ALREADY_EXISTS_INT_VALUE, null, ERR_MEM_HANDLER_MOD_DN_TARGET_IS_SCHEMA.get(request.getDN(), newDN.toString()), null));
        }
        // If the new DN is at or below the changelog base DN, then fail.
        if (newDN.isDescendantOf(changeLogBaseDN, true)) {
            return new LDAPMessage(messageID, new ModifyDNResponseProtocolOp(ResultCode.UNWILLING_TO_PERFORM_INT_VALUE, null, ERR_MEM_HANDLER_MOD_DN_TARGET_IS_CHANGELOG.get(request.getDN(), newDN.toString()), null));
        }
        // If the new DN already exists, then fail.
        if (entryMap.containsKey(newDN)) {
            return new LDAPMessage(messageID, new ModifyDNResponseProtocolOp(ResultCode.ENTRY_ALREADY_EXISTS_INT_VALUE, null, ERR_MEM_HANDLER_MOD_DN_TARGET_ALREADY_EXISTS.get(request.getDN(), newDN.toString()), null));
        }
        // fail.
        if (baseDNs.contains(newDN)) {
        // The modify DN can be processed.
        } else {
            final DN newParent = newDN.getParent();
            if ((newParent != null) && entryMap.containsKey(newParent)) {
            // The modify DN can be processed.
            } else {
                return new LDAPMessage(messageID, new ModifyDNResponseProtocolOp(ResultCode.NO_SUCH_OBJECT_INT_VALUE, getMatchedDNString(newDN), ERR_MEM_HANDLER_MOD_DN_PARENT_DOESNT_EXIST.get(request.getDN(), newDN.toString()), null));
            }
        }
        // Create a copy of the entry and update it to reflect the new DN (with
        // attribute value changes).
        final RDN originalRDN = dn.getRDN();
        final Entry updatedEntry = originalEntry.duplicate();
        updatedEntry.setDN(newDN);
        if (request.deleteOldRDN()) {
            final String[] oldRDNNames = originalRDN.getAttributeNames();
            final byte[][] oldRDNValues = originalRDN.getByteArrayAttributeValues();
            for (int i = 0; i < oldRDNNames.length; i++) {
                updatedEntry.removeAttributeValue(oldRDNNames[i], oldRDNValues[i]);
            }
        }
        final String[] newRDNNames = newRDN.getAttributeNames();
        final byte[][] newRDNValues = newRDN.getByteArrayAttributeValues();
        for (int i = 0; i < newRDNNames.length; i++) {
            final MatchingRule matchingRule = MatchingRule.selectEqualityMatchingRule(newRDNNames[i], schema);
            updatedEntry.addAttribute(new Attribute(newRDNNames[i], matchingRule, newRDNValues[i]));
        }
        // If a schema was provided, then make sure the updated entry conforms to
        // the schema.  Also, reject the attempt if any of the new RDN attributes
        // is marked with NO-USER-MODIFICATION.
        final EntryValidator entryValidator = entryValidatorRef.get();
        if (entryValidator != null) {
            final ArrayList<String> invalidReasons = new ArrayList<>(1);
            if (!entryValidator.entryIsValid(updatedEntry, invalidReasons)) {
                return new LDAPMessage(messageID, new ModifyDNResponseProtocolOp(ResultCode.OBJECT_CLASS_VIOLATION_INT_VALUE, null, ERR_MEM_HANDLER_MOD_DN_VIOLATES_SCHEMA.get(request.getDN(), StaticUtils.concatenateStrings(invalidReasons)), null));
            }
            final String[] oldRDNNames = originalRDN.getAttributeNames();
            for (int i = 0; i < oldRDNNames.length; i++) {
                final String name = oldRDNNames[i];
                final AttributeTypeDefinition at = schema.getAttributeType(name);
                if ((!isInternalOp) && (at != null) && at.isNoUserModification()) {
                    final byte[] value = originalRDN.getByteArrayAttributeValues()[i];
                    if (!updatedEntry.hasAttributeValue(name, value)) {
                        return new LDAPMessage(messageID, new ModifyDNResponseProtocolOp(ResultCode.CONSTRAINT_VIOLATION_INT_VALUE, null, ERR_MEM_HANDLER_MOD_DN_NO_USER_MOD.get(request.getDN(), name), null));
                    }
                }
            }
            for (int i = 0; i < newRDNNames.length; i++) {
                final String name = newRDNNames[i];
                final AttributeTypeDefinition at = schema.getAttributeType(name);
                if ((!isInternalOp) && (at != null) && at.isNoUserModification()) {
                    final byte[] value = newRDN.getByteArrayAttributeValues()[i];
                    if (!originalEntry.hasAttributeValue(name, value)) {
                        return new LDAPMessage(messageID, new ModifyDNResponseProtocolOp(ResultCode.CONSTRAINT_VIOLATION_INT_VALUE, null, ERR_MEM_HANDLER_MOD_DN_NO_USER_MOD.get(request.getDN(), name), null));
                    }
                }
            }
        }
        // Perform the appropriate processing for the assertion and proxied
        // authorization controls
        final DN authzDN;
        try {
            handleAssertionRequestControl(controlMap, originalEntry);
            authzDN = handleProxiedAuthControl(controlMap);
        } catch (final LDAPException le) {
            Debug.debugException(le);
            return new LDAPMessage(messageID, new ModifyDNResponseProtocolOp(le.getResultCode().intValue(), null, le.getMessage(), null));
        }
        // attributes.
        if (generateOperationalAttributes) {
            updatedEntry.setAttribute(new Attribute("modifiersName", DistinguishedNameMatchingRule.getInstance(), authzDN.toString()));
            updatedEntry.setAttribute(new Attribute("modifyTimestamp", GeneralizedTimeMatchingRule.getInstance(), StaticUtils.encodeGeneralizedTime(new Date())));
            updatedEntry.setAttribute(new Attribute("entryDN", DistinguishedNameMatchingRule.getInstance(), newDN.toNormalizedString()));
        }
        // Perform the appropriate processing for the pre-read and post-read
        // controls.
        final PreReadResponseControl preReadResponse = handlePreReadControl(controlMap, originalEntry);
        if (preReadResponse != null) {
            responseControls.add(preReadResponse);
        }
        final PostReadResponseControl postReadResponse = handlePostReadControl(controlMap, updatedEntry);
        if (postReadResponse != null) {
            responseControls.add(postReadResponse);
        }
        // Remove the old entry and add the new one.
        entryMap.remove(dn);
        entryMap.put(newDN, new ReadOnlyEntry(updatedEntry));
        indexDelete(originalEntry);
        indexAdd(updatedEntry);
        // If the target entry had any subordinates, then rename them as well.
        final RDN[] oldDNComps = dn.getRDNs();
        final RDN[] newDNComps = newDN.getRDNs();
        final Set<DN> dnSet = new LinkedHashSet<>(entryMap.keySet());
        for (final DN mapEntryDN : dnSet) {
            if (mapEntryDN.isDescendantOf(dn, false)) {
                final Entry o = entryMap.remove(mapEntryDN);
                final Entry e = o.duplicate();
                final RDN[] oldMapEntryComps = mapEntryDN.getRDNs();
                final int compsToSave = oldMapEntryComps.length - oldDNComps.length;
                final RDN[] newMapEntryComps = new RDN[compsToSave + newDNComps.length];
                System.arraycopy(oldMapEntryComps, 0, newMapEntryComps, 0, compsToSave);
                System.arraycopy(newDNComps, 0, newMapEntryComps, compsToSave, newDNComps.length);
                final DN newMapEntryDN = new DN(newMapEntryComps);
                e.setDN(newMapEntryDN);
                if (generateOperationalAttributes) {
                    e.setAttribute(new Attribute("entryDN", DistinguishedNameMatchingRule.getInstance(), newMapEntryDN.toNormalizedString()));
                }
                entryMap.put(newMapEntryDN, new ReadOnlyEntry(e));
                indexDelete(o);
                indexAdd(e);
                handleReferentialIntegrityModifyDN(mapEntryDN, newMapEntryDN);
            }
        }
        addChangeLogEntry(request, authzDN);
        handleReferentialIntegrityModifyDN(dn, newDN);
        return new LDAPMessage(messageID, new ModifyDNResponseProtocolOp(ResultCode.SUCCESS_INT_VALUE, null, null, null), responseControls);
    }
}
Also used : ASN1OctetString(com.unboundid.asn1.ASN1OctetString) LinkedHashSet(java.util.LinkedHashSet) Attribute(com.unboundid.ldap.sdk.Attribute) Schema(com.unboundid.ldap.sdk.schema.Schema) ArrayList(java.util.ArrayList) ModifyDNResponseProtocolOp(com.unboundid.ldap.protocol.ModifyDNResponseProtocolOp) RDN(com.unboundid.ldap.sdk.RDN) DN(com.unboundid.ldap.sdk.DN) ASN1OctetString(com.unboundid.asn1.ASN1OctetString) EntryValidator(com.unboundid.ldap.sdk.schema.EntryValidator) AttributeTypeDefinition(com.unboundid.ldap.sdk.schema.AttributeTypeDefinition) VirtualListViewRequestControl(com.unboundid.ldap.sdk.controls.VirtualListViewRequestControl) SubtreeDeleteRequestControl(com.unboundid.ldap.sdk.controls.SubtreeDeleteRequestControl) RFC3672SubentriesRequestControl(com.unboundid.ldap.sdk.controls.RFC3672SubentriesRequestControl) SimplePagedResultsControl(com.unboundid.ldap.sdk.controls.SimplePagedResultsControl) VirtualListViewResponseControl(com.unboundid.ldap.sdk.controls.VirtualListViewResponseControl) TransactionSpecificationRequestControl(com.unboundid.ldap.sdk.controls.TransactionSpecificationRequestControl) DraftZeilengaLDAPNoOp12RequestControl(com.unboundid.ldap.sdk.experimental.DraftZeilengaLDAPNoOp12RequestControl) PostReadRequestControl(com.unboundid.ldap.sdk.controls.PostReadRequestControl) ProxiedAuthorizationV1RequestControl(com.unboundid.ldap.sdk.controls.ProxiedAuthorizationV1RequestControl) ServerSideSortResponseControl(com.unboundid.ldap.sdk.controls.ServerSideSortResponseControl) PreReadResponseControl(com.unboundid.ldap.sdk.controls.PreReadResponseControl) AuthorizationIdentityResponseControl(com.unboundid.ldap.sdk.controls.AuthorizationIdentityResponseControl) PermissiveModifyRequestControl(com.unboundid.ldap.sdk.controls.PermissiveModifyRequestControl) AuthorizationIdentityRequestControl(com.unboundid.ldap.sdk.controls.AuthorizationIdentityRequestControl) Control(com.unboundid.ldap.sdk.Control) IgnoreNoUserModificationRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.IgnoreNoUserModificationRequestControl) ProxiedAuthorizationV2RequestControl(com.unboundid.ldap.sdk.controls.ProxiedAuthorizationV2RequestControl) ServerSideSortRequestControl(com.unboundid.ldap.sdk.controls.ServerSideSortRequestControl) PostReadResponseControl(com.unboundid.ldap.sdk.controls.PostReadResponseControl) DontUseCopyRequestControl(com.unboundid.ldap.sdk.controls.DontUseCopyRequestControl) AssertionRequestControl(com.unboundid.ldap.sdk.controls.AssertionRequestControl) ManageDsaITRequestControl(com.unboundid.ldap.sdk.controls.ManageDsaITRequestControl) DraftLDUPSubentriesRequestControl(com.unboundid.ldap.sdk.controls.DraftLDUPSubentriesRequestControl) PreReadRequestControl(com.unboundid.ldap.sdk.controls.PreReadRequestControl) ChangeLogEntry(com.unboundid.ldap.sdk.ChangeLogEntry) SearchResultEntry(com.unboundid.ldap.sdk.SearchResultEntry) Entry(com.unboundid.ldap.sdk.Entry) ReadOnlyEntry(com.unboundid.ldap.sdk.ReadOnlyEntry) PostReadResponseControl(com.unboundid.ldap.sdk.controls.PostReadResponseControl) RDN(com.unboundid.ldap.sdk.RDN) LDAPMessage(com.unboundid.ldap.protocol.LDAPMessage) Date(java.util.Date) ReadOnlyEntry(com.unboundid.ldap.sdk.ReadOnlyEntry) LDAPException(com.unboundid.ldap.sdk.LDAPException) PreReadResponseControl(com.unboundid.ldap.sdk.controls.PreReadResponseControl) IntegerMatchingRule(com.unboundid.ldap.matchingrules.IntegerMatchingRule) DistinguishedNameMatchingRule(com.unboundid.ldap.matchingrules.DistinguishedNameMatchingRule) MatchingRule(com.unboundid.ldap.matchingrules.MatchingRule) GeneralizedTimeMatchingRule(com.unboundid.ldap.matchingrules.GeneralizedTimeMatchingRule) NotNull(com.unboundid.util.NotNull)

Example 2 with MatchingRule

use of com.unboundid.ldap.matchingrules.MatchingRule in project ldapsdk by pingidentity.

the class InMemoryRequestHandler method processAddRequest.

/**
 * Attempts to add an entry to the in-memory data set.  The attempt will fail
 * if any of the following conditions is true:
 * <UL>
 *   <LI>There is a problem with any of the request controls.</LI>
 *   <LI>The provided entry has a malformed DN.</LI>
 *   <LI>The provided entry has the null DN.</LI>
 *   <LI>The provided entry has a DN that is the same as or subordinate to the
 *       subschema subentry.</LI>
 *   <LI>The provided entry has a DN that is the same as or subordinate to the
 *       changelog base entry.</LI>
 *   <LI>An entry already exists with the same DN as the entry in the provided
 *       request.</LI>
 *   <LI>The entry is outside the set of base DNs for the server.</LI>
 *   <LI>The entry is below one of the defined base DNs but the immediate
 *       parent entry does not exist.</LI>
 *   <LI>If a schema was provided, and the entry is not valid according to the
 *       constraints of that schema.</LI>
 * </UL>
 *
 * @param  messageID  The message ID of the LDAP message containing the add
 *                    request.
 * @param  request    The add request that was included in the LDAP message
 *                    that was received.
 * @param  controls   The set of controls included in the LDAP message.  It
 *                    may be empty if there were no controls, but will not be
 *                    {@code null}.
 *
 * @return  The {@link LDAPMessage} containing the response to send to the
 *          client.  The protocol op in the {@code LDAPMessage} must be an
 *          {@code AddResponseProtocolOp}.
 */
@Override()
@NotNull()
public LDAPMessage processAddRequest(final int messageID, @NotNull final AddRequestProtocolOp request, @NotNull final List<Control> controls) {
    synchronized (entryMap) {
        // Sleep before processing, if appropriate.
        sleepBeforeProcessing();
        // Process the provided request controls.
        final Map<String, Control> controlMap;
        try {
            controlMap = RequestControlPreProcessor.processControls(LDAPMessage.PROTOCOL_OP_TYPE_ADD_REQUEST, controls);
        } catch (final LDAPException le) {
            Debug.debugException(le);
            return new LDAPMessage(messageID, new AddResponseProtocolOp(le.getResultCode().intValue(), null, le.getMessage(), null));
        }
        final ArrayList<Control> responseControls = new ArrayList<>(1);
        // If this operation type is not allowed, then reject it.
        final boolean isInternalOp = controlMap.containsKey(OID_INTERNAL_OPERATION_REQUEST_CONTROL);
        if ((!isInternalOp) && (!config.getAllowedOperationTypes().contains(OperationType.ADD))) {
            return new LDAPMessage(messageID, new AddResponseProtocolOp(ResultCode.UNWILLING_TO_PERFORM_INT_VALUE, null, ERR_MEM_HANDLER_ADD_NOT_ALLOWED.get(), null));
        }
        // client is authenticated.
        if ((authenticatedDN.isNullDN() && config.getAuthenticationRequiredOperationTypes().contains(OperationType.ADD))) {
            return new LDAPMessage(messageID, new AddResponseProtocolOp(ResultCode.INSUFFICIENT_ACCESS_RIGHTS_INT_VALUE, null, ERR_MEM_HANDLER_ADD_REQUIRES_AUTH.get(), null));
        }
        // actually doing any further processing.
        try {
            final ASN1OctetString txnID = processTransactionRequest(messageID, request, controlMap);
            if (txnID != null) {
                return new LDAPMessage(messageID, new AddResponseProtocolOp(ResultCode.SUCCESS_INT_VALUE, null, INFO_MEM_HANDLER_OP_IN_TXN.get(txnID.stringValue()), null));
            }
        } catch (final LDAPException le) {
            Debug.debugException(le);
            return new LDAPMessage(messageID, new AddResponseProtocolOp(le.getResultCode().intValue(), le.getMatchedDN(), le.getDiagnosticMessage(), StaticUtils.toList(le.getReferralURLs())), le.getResponseControls());
        }
        // Get the entry to be added.  If a schema was provided, then make sure
        // the attributes are created with the appropriate matching rules.
        final Entry entry;
        final Schema schema = schemaRef.get();
        if (schema == null) {
            entry = new Entry(request.getDN(), request.getAttributes());
        } else {
            final List<Attribute> providedAttrs = request.getAttributes();
            final List<Attribute> newAttrs = new ArrayList<>(providedAttrs.size());
            for (final Attribute a : providedAttrs) {
                final String baseName = a.getBaseName();
                final MatchingRule matchingRule = MatchingRule.selectEqualityMatchingRule(baseName, schema);
                newAttrs.add(new Attribute(a.getName(), matchingRule, a.getRawValues()));
            }
            entry = new Entry(request.getDN(), schema, newAttrs);
        }
        // Make sure that the DN is valid.
        final DN dn;
        try {
            dn = entry.getParsedDN();
        } catch (final LDAPException le) {
            Debug.debugException(le);
            return new LDAPMessage(messageID, new AddResponseProtocolOp(ResultCode.INVALID_DN_SYNTAX_INT_VALUE, null, ERR_MEM_HANDLER_ADD_MALFORMED_DN.get(request.getDN(), le.getMessage()), null));
        }
        // entry.
        if (dn.isNullDN()) {
            return new LDAPMessage(messageID, new AddResponseProtocolOp(ResultCode.ENTRY_ALREADY_EXISTS_INT_VALUE, null, ERR_MEM_HANDLER_ADD_ROOT_DSE.get(), null));
        } else if (dn.isDescendantOf(subschemaSubentryDN, true)) {
            return new LDAPMessage(messageID, new AddResponseProtocolOp(ResultCode.ENTRY_ALREADY_EXISTS_INT_VALUE, null, ERR_MEM_HANDLER_ADD_SCHEMA.get(subschemaSubentryDN.toString()), null));
        } else if (dn.isDescendantOf(changeLogBaseDN, true)) {
            return new LDAPMessage(messageID, new AddResponseProtocolOp(ResultCode.UNWILLING_TO_PERFORM_INT_VALUE, null, ERR_MEM_HANDLER_ADD_CHANGELOG.get(changeLogBaseDN.toString()), null));
        }
        // See if there is a referral at or above the target entry.
        if (!controlMap.containsKey(ManageDsaITRequestControl.MANAGE_DSA_IT_REQUEST_OID)) {
            final Entry referralEntry = findNearestReferral(dn);
            if (referralEntry != null) {
                return new LDAPMessage(messageID, new AddResponseProtocolOp(ResultCode.REFERRAL_INT_VALUE, referralEntry.getDN(), INFO_MEM_HANDLER_REFERRAL_ENCOUNTERED.get(), getReferralURLs(dn, referralEntry)));
            }
        }
        // See if another entry exists with the same DN.
        if (entryMap.containsKey(dn)) {
            return new LDAPMessage(messageID, new AddResponseProtocolOp(ResultCode.ENTRY_ALREADY_EXISTS_INT_VALUE, null, ERR_MEM_HANDLER_ADD_ALREADY_EXISTS.get(request.getDN()), null));
        }
        // Make sure that all RDN attribute values are present in the entry.
        final RDN rdn = dn.getRDN();
        final String[] rdnAttrNames = rdn.getAttributeNames();
        final byte[][] rdnAttrValues = rdn.getByteArrayAttributeValues();
        for (int i = 0; i < rdnAttrNames.length; i++) {
            final MatchingRule matchingRule = MatchingRule.selectEqualityMatchingRule(rdnAttrNames[i], schema);
            entry.addAttribute(new Attribute(rdnAttrNames[i], matchingRule, rdnAttrValues[i]));
        }
        // Make sure that all superior object classes are present in the entry.
        if (schema != null) {
            final String[] objectClasses = entry.getObjectClassValues();
            if (objectClasses != null) {
                final LinkedHashMap<String, String> ocMap = new LinkedHashMap<>(StaticUtils.computeMapCapacity(objectClasses.length));
                for (final String ocName : objectClasses) {
                    final ObjectClassDefinition oc = schema.getObjectClass(ocName);
                    if (oc == null) {
                        ocMap.put(StaticUtils.toLowerCase(ocName), ocName);
                    } else {
                        ocMap.put(StaticUtils.toLowerCase(oc.getNameOrOID()), ocName);
                        for (final ObjectClassDefinition supClass : oc.getSuperiorClasses(schema, true)) {
                            ocMap.put(StaticUtils.toLowerCase(supClass.getNameOrOID()), supClass.getNameOrOID());
                        }
                    }
                }
                final String[] newObjectClasses = new String[ocMap.size()];
                ocMap.values().toArray(newObjectClasses);
                entry.setAttribute("objectClass", newObjectClasses);
            }
        }
        // If a schema was provided, then make sure the entry complies with it.
        // Also make sure that there are no attributes marked with
        // NO-USER-MODIFICATION.
        final EntryValidator entryValidator = entryValidatorRef.get();
        if (entryValidator != null) {
            final ArrayList<String> invalidReasons = new ArrayList<>(1);
            if (!entryValidator.entryIsValid(entry, invalidReasons)) {
                return new LDAPMessage(messageID, new AddResponseProtocolOp(ResultCode.OBJECT_CLASS_VIOLATION_INT_VALUE, null, ERR_MEM_HANDLER_ADD_VIOLATES_SCHEMA.get(request.getDN(), StaticUtils.concatenateStrings(invalidReasons)), null));
            }
            if ((!isInternalOp) && (schema != null) && (!controlMap.containsKey(IgnoreNoUserModificationRequestControl.IGNORE_NO_USER_MODIFICATION_REQUEST_OID))) {
                for (final Attribute a : entry.getAttributes()) {
                    final AttributeTypeDefinition at = schema.getAttributeType(a.getBaseName());
                    if ((at != null) && at.isNoUserModification()) {
                        return new LDAPMessage(messageID, new AddResponseProtocolOp(ResultCode.CONSTRAINT_VIOLATION_INT_VALUE, null, ERR_MEM_HANDLER_ADD_CONTAINS_NO_USER_MOD.get(request.getDN(), a.getName()), null));
                    }
                }
            }
        }
        // If the entry contains a proxied authorization control, then process it.
        final DN authzDN;
        try {
            authzDN = handleProxiedAuthControl(controlMap);
        } catch (final LDAPException le) {
            Debug.debugException(le);
            return new LDAPMessage(messageID, new AddResponseProtocolOp(le.getResultCode().intValue(), null, le.getMessage(), null));
        }
        // Add a number of operational attributes to the entry.
        if (generateOperationalAttributes) {
            final Date d = new Date();
            if (!entry.hasAttribute("entryDN")) {
                entry.addAttribute(new Attribute("entryDN", DistinguishedNameMatchingRule.getInstance(), dn.toNormalizedString()));
            }
            if (!entry.hasAttribute("entryUUID")) {
                entry.addAttribute(new Attribute("entryUUID", CryptoHelper.getRandomUUID().toString()));
            }
            if (!entry.hasAttribute("subschemaSubentry")) {
                entry.addAttribute(new Attribute("subschemaSubentry", DistinguishedNameMatchingRule.getInstance(), subschemaSubentryDN.toString()));
            }
            if (!entry.hasAttribute("creatorsName")) {
                entry.addAttribute(new Attribute("creatorsName", DistinguishedNameMatchingRule.getInstance(), authzDN.toString()));
            }
            if (!entry.hasAttribute("createTimestamp")) {
                entry.addAttribute(new Attribute("createTimestamp", GeneralizedTimeMatchingRule.getInstance(), StaticUtils.encodeGeneralizedTime(d)));
            }
            if (!entry.hasAttribute("modifiersName")) {
                entry.addAttribute(new Attribute("modifiersName", DistinguishedNameMatchingRule.getInstance(), authzDN.toString()));
            }
            if (!entry.hasAttribute("modifyTimestamp")) {
                entry.addAttribute(new Attribute("modifyTimestamp", GeneralizedTimeMatchingRule.getInstance(), StaticUtils.encodeGeneralizedTime(d)));
            }
        }
        // now.
        try {
            handleAssertionRequestControl(controlMap, entry);
        } catch (final LDAPException le) {
            Debug.debugException(le);
            return new LDAPMessage(messageID, new AddResponseProtocolOp(le.getResultCode().intValue(), null, le.getMessage(), null));
        }
        // values are properly encoded.
        if ((!passwordEncoders.isEmpty()) && (!configuredPasswordAttributes.isEmpty())) {
            final ReadOnlyEntry readOnlyEntry = new ReadOnlyEntry(entry.duplicate());
            for (final String passwordAttribute : configuredPasswordAttributes) {
                for (final Attribute attr : readOnlyEntry.getAttributesWithOptions(passwordAttribute, null)) {
                    final ArrayList<byte[]> newValues = new ArrayList<>(attr.size());
                    for (final ASN1OctetString value : attr.getRawValues()) {
                        try {
                            newValues.add(encodeAddPassword(value, readOnlyEntry, Collections.<Modification>emptyList()).getValue());
                        } catch (final LDAPException le) {
                            Debug.debugException(le);
                            return new LDAPMessage(messageID, new AddResponseProtocolOp(ResultCode.UNWILLING_TO_PERFORM_INT_VALUE, le.getMatchedDN(), le.getMessage(), null));
                        }
                    }
                    final byte[][] newValuesArray = new byte[newValues.size()][];
                    newValues.toArray(newValuesArray);
                    entry.setAttribute(new Attribute(attr.getName(), schema, newValuesArray));
                }
            }
        }
        // If the request includes the post-read request control, then create the
        // appropriate response control.
        final PostReadResponseControl postReadResponse = handlePostReadControl(controlMap, entry);
        if (postReadResponse != null) {
            responseControls.add(postReadResponse);
        }
        // add the entry.
        if (baseDNs.contains(dn)) {
            entryMap.put(dn, new ReadOnlyEntry(entry));
            indexAdd(entry);
            addChangeLogEntry(request, authzDN);
            return new LDAPMessage(messageID, new AddResponseProtocolOp(ResultCode.SUCCESS_INT_VALUE, null, null, null), responseControls);
        }
        // See if the parent entry exists.  If so, then we can add the entry.
        final DN parentDN = dn.getParent();
        if ((parentDN != null) && entryMap.containsKey(parentDN)) {
            entryMap.put(dn, new ReadOnlyEntry(entry));
            indexAdd(entry);
            addChangeLogEntry(request, authzDN);
            return new LDAPMessage(messageID, new AddResponseProtocolOp(ResultCode.SUCCESS_INT_VALUE, null, null, null), responseControls);
        }
        // within any of the configured base DNs.
        for (final DN baseDN : baseDNs) {
            if (dn.isDescendantOf(baseDN, true)) {
                return new LDAPMessage(messageID, new AddResponseProtocolOp(ResultCode.NO_SUCH_OBJECT_INT_VALUE, getMatchedDNString(dn), ERR_MEM_HANDLER_ADD_MISSING_PARENT.get(request.getDN(), dn.getParentString()), null));
            }
        }
        return new LDAPMessage(messageID, new AddResponseProtocolOp(ResultCode.NO_SUCH_OBJECT_INT_VALUE, null, ERR_MEM_HANDLER_ADD_NOT_BELOW_BASE_DN.get(request.getDN()), null));
    }
}
Also used : ASN1OctetString(com.unboundid.asn1.ASN1OctetString) Attribute(com.unboundid.ldap.sdk.Attribute) Schema(com.unboundid.ldap.sdk.schema.Schema) ArrayList(java.util.ArrayList) AddResponseProtocolOp(com.unboundid.ldap.protocol.AddResponseProtocolOp) RDN(com.unboundid.ldap.sdk.RDN) DN(com.unboundid.ldap.sdk.DN) ASN1OctetString(com.unboundid.asn1.ASN1OctetString) EntryValidator(com.unboundid.ldap.sdk.schema.EntryValidator) LinkedHashMap(java.util.LinkedHashMap) AttributeTypeDefinition(com.unboundid.ldap.sdk.schema.AttributeTypeDefinition) VirtualListViewRequestControl(com.unboundid.ldap.sdk.controls.VirtualListViewRequestControl) SubtreeDeleteRequestControl(com.unboundid.ldap.sdk.controls.SubtreeDeleteRequestControl) RFC3672SubentriesRequestControl(com.unboundid.ldap.sdk.controls.RFC3672SubentriesRequestControl) SimplePagedResultsControl(com.unboundid.ldap.sdk.controls.SimplePagedResultsControl) VirtualListViewResponseControl(com.unboundid.ldap.sdk.controls.VirtualListViewResponseControl) TransactionSpecificationRequestControl(com.unboundid.ldap.sdk.controls.TransactionSpecificationRequestControl) DraftZeilengaLDAPNoOp12RequestControl(com.unboundid.ldap.sdk.experimental.DraftZeilengaLDAPNoOp12RequestControl) PostReadRequestControl(com.unboundid.ldap.sdk.controls.PostReadRequestControl) ProxiedAuthorizationV1RequestControl(com.unboundid.ldap.sdk.controls.ProxiedAuthorizationV1RequestControl) ServerSideSortResponseControl(com.unboundid.ldap.sdk.controls.ServerSideSortResponseControl) PreReadResponseControl(com.unboundid.ldap.sdk.controls.PreReadResponseControl) AuthorizationIdentityResponseControl(com.unboundid.ldap.sdk.controls.AuthorizationIdentityResponseControl) PermissiveModifyRequestControl(com.unboundid.ldap.sdk.controls.PermissiveModifyRequestControl) AuthorizationIdentityRequestControl(com.unboundid.ldap.sdk.controls.AuthorizationIdentityRequestControl) Control(com.unboundid.ldap.sdk.Control) IgnoreNoUserModificationRequestControl(com.unboundid.ldap.sdk.unboundidds.controls.IgnoreNoUserModificationRequestControl) ProxiedAuthorizationV2RequestControl(com.unboundid.ldap.sdk.controls.ProxiedAuthorizationV2RequestControl) ServerSideSortRequestControl(com.unboundid.ldap.sdk.controls.ServerSideSortRequestControl) PostReadResponseControl(com.unboundid.ldap.sdk.controls.PostReadResponseControl) DontUseCopyRequestControl(com.unboundid.ldap.sdk.controls.DontUseCopyRequestControl) AssertionRequestControl(com.unboundid.ldap.sdk.controls.AssertionRequestControl) ManageDsaITRequestControl(com.unboundid.ldap.sdk.controls.ManageDsaITRequestControl) DraftLDUPSubentriesRequestControl(com.unboundid.ldap.sdk.controls.DraftLDUPSubentriesRequestControl) PreReadRequestControl(com.unboundid.ldap.sdk.controls.PreReadRequestControl) ChangeLogEntry(com.unboundid.ldap.sdk.ChangeLogEntry) SearchResultEntry(com.unboundid.ldap.sdk.SearchResultEntry) Entry(com.unboundid.ldap.sdk.Entry) ReadOnlyEntry(com.unboundid.ldap.sdk.ReadOnlyEntry) PostReadResponseControl(com.unboundid.ldap.sdk.controls.PostReadResponseControl) RDN(com.unboundid.ldap.sdk.RDN) ObjectClassDefinition(com.unboundid.ldap.sdk.schema.ObjectClassDefinition) LDAPMessage(com.unboundid.ldap.protocol.LDAPMessage) Date(java.util.Date) ReadOnlyEntry(com.unboundid.ldap.sdk.ReadOnlyEntry) LDAPException(com.unboundid.ldap.sdk.LDAPException) IntegerMatchingRule(com.unboundid.ldap.matchingrules.IntegerMatchingRule) DistinguishedNameMatchingRule(com.unboundid.ldap.matchingrules.DistinguishedNameMatchingRule) MatchingRule(com.unboundid.ldap.matchingrules.MatchingRule) GeneralizedTimeMatchingRule(com.unboundid.ldap.matchingrules.GeneralizedTimeMatchingRule) NotNull(com.unboundid.util.NotNull)

Example 3 with MatchingRule

use of com.unboundid.ldap.matchingrules.MatchingRule in project ldapsdk by pingidentity.

the class SplitLDIFAttributeHashTranslator method translate.

/**
 * {@inheritDoc}
 */
@Override()
@NotNull()
public SplitLDIFEntry translate(@NotNull final Entry original, final long firstLineNumber) throws LDIFException {
    // Get the parsed DN for the entry.  If we can't, that's an error and we
    // should only include it in the error set.
    final DN dn;
    try {
        dn = original.getParsedDN();
    } catch (final LDAPException le) {
        Debug.debugException(le);
        return createEntry(original, ERR_SPLIT_LDIF_ATTR_HASH_TRANSLATOR_CANNOT_PARSE_DN.get(le.getMessage()), getErrorSetNames());
    }
    // appropriate sets for that.
    if (!dn.isDescendantOf(getSplitBaseDN(), true)) {
        return createEntry(original, outsideSplitBaseSetNames);
    }
    // all of the split sets.
    if (dn.equals(getSplitBaseDN())) {
        return createEntry(original, splitBaseEntrySetNames);
    }
    // Determine which RDN component is immediately below the split base DN and
    // get its normalized string representation.
    final RDN[] rdns = dn.getRDNs();
    final int targetRDNIndex = rdns.length - getSplitBaseRDNs().length - 1;
    final String normalizedRDNString = rdns[targetRDNIndex].toNormalizedString();
    // we'll use the cache to send this entry to the same set as its parent.
    if (targetRDNIndex > 0) {
        // the --assumeFlatDIT argument was provided), then this is an error.
        if (rdnCache == null) {
            return createEntry(original, ERR_SPLIT_LDIF_ATTR_HASH_TRANSLATOR_NON_FLAT_DIT.get(getSplitBaseDN().toString()), getErrorSetNames());
        }
        // the caller will consider that an error and handle it appropriately.
        return createEntry(original, rdnCache.get(normalizedRDNString));
    }
    // At this point, we know that the entry is exactly one level below the
    // split base DN, and we're going to need to generate an MD5 digest of
    // something (preferably one or more values for the target attribute, but
    // if not then the normalized RDN).  Get an MD5 digest generator.
    final MessageDigest md5Digest;
    try {
        md5Digest = getMD5();
        md5Digest.reset();
    } catch (final Exception e) {
        // This should never happen.
        Debug.debugException(e);
        return createEntry(original, ERR_SPLIT_LDIF_TRANSLATOR_CANNOT_GET_MD5.get(StaticUtils.getExceptionMessage(e)), getErrorSetNames());
    }
    // Try to compute the digest based on the target attribute.  If we can't
    // do that for some reason, then fall back to computing it based on the
    // normalized RDN.
    byte[] md5Bytes = null;
    final Attribute a = original.getAttribute(attributeName);
    if (a != null) {
        // We want to use the normalized representation of the attribute values,
        // so get the appropriate matching rule.
        MatchingRule mr = a.getMatchingRule();
        if (mr == null) {
            mr = CaseIgnoreStringMatchingRule.getInstance();
        }
        // in the entry won't affect the checksum.
        if (useAllValues && (a.size() > 1)) {
            try {
                final TreeSet<String> sortedValues = new TreeSet<>();
                for (final ASN1OctetString value : a.getRawValues()) {
                    sortedValues.add(mr.normalize(value).stringValue());
                }
                for (final String value : sortedValues) {
                    md5Digest.update(StaticUtils.getBytes(value));
                }
                md5Bytes = md5Digest.digest();
            } catch (final Exception e) {
                Debug.debugException(e);
            }
        } else if (a.size() != 0) {
            try {
                md5Bytes = md5Digest.digest(mr.normalize(a.getRawValues()[0]).getValue());
            } catch (final Exception e) {
                Debug.debugException(e);
            }
        }
    }
    if (md5Bytes == null) {
        md5Bytes = md5Digest.digest(StaticUtils.getBytes(normalizedRDNString));
    }
    // Use the first four bytes of the MD5 digest to compute an integer checksum
    // (but don't use the most significant bit of the first byte to avoid the
    // possibility of a negative number).  Then use a modulus operation to
    // convert that checksum into a value that we can use to get the
    // corresponding set names.
    final int checksum = ((md5Bytes[0] & 0x7F) << 24) | ((md5Bytes[1] & 0xFF) << 16) | ((md5Bytes[2] & 0xFF) << 8) | (md5Bytes[3] & 0xFF);
    final int setNumber = checksum % setNames.size();
    // Get the appropriate set, update the RDN cache if appropriate, and return
    // the transformed entry.
    final Set<String> sets = setNames.get(setNumber);
    if (rdnCache != null) {
        rdnCache.put(normalizedRDNString, sets);
    }
    return createEntry(original, sets);
}
Also used : ASN1OctetString(com.unboundid.asn1.ASN1OctetString) Attribute(com.unboundid.ldap.sdk.Attribute) RDN(com.unboundid.ldap.sdk.RDN) DN(com.unboundid.ldap.sdk.DN) ASN1OctetString(com.unboundid.asn1.ASN1OctetString) LDIFException(com.unboundid.ldif.LDIFException) LDAPException(com.unboundid.ldap.sdk.LDAPException) LDAPException(com.unboundid.ldap.sdk.LDAPException) TreeSet(java.util.TreeSet) MessageDigest(java.security.MessageDigest) RDN(com.unboundid.ldap.sdk.RDN) MatchingRule(com.unboundid.ldap.matchingrules.MatchingRule) CaseIgnoreStringMatchingRule(com.unboundid.ldap.matchingrules.CaseIgnoreStringMatchingRule) NotNull(com.unboundid.util.NotNull)

Example 4 with MatchingRule

use of com.unboundid.ldap.matchingrules.MatchingRule in project ldapsdk by pingidentity.

the class LDIFReader method parseAttributes.

/**
 * Parses the data available through the provided iterator as a collection of
 * attributes suitable for use in an entry or an add change record.
 *
 * @param  dn                      The DN of the record being read.
 * @param  duplicateValueBehavior  The behavior that should be exhibited if
 *                                 the LDIF reader encounters an entry with
 *                                 duplicate values.
 * @param  trailingSpaceBehavior   The behavior that should be exhibited when
 *                                 encountering attribute values which are not
 *                                 base64-encoded but contain trailing spaces.
 * @param  schema                  The schema to use when parsing the
 *                                 attributes, or {@code null} if none is
 *                                 needed.
 * @param  ldifLines               The lines that comprise the LDIF
 *                                 representation of the full record being
 *                                 parsed.
 * @param  iterator                The iterator to use to access the attribute
 *                                 lines.
 * @param  relativeBasePath        The base path that will be prepended to
 *                                 relative paths in order to obtain an
 *                                 absolute path.
 * @param  firstLineNumber         The line number for the start of the
 *                                 record.
 *
 * @return  The collection of attributes that were read.
 *
 * @throws  LDIFException  If the provided LDIF data cannot be decoded as a
 *                         set of attributes.
 */
@NotNull()
private static ArrayList<Attribute> parseAttributes(@NotNull final String dn, @NotNull final DuplicateValueBehavior duplicateValueBehavior, @NotNull final TrailingSpaceBehavior trailingSpaceBehavior, @Nullable final Schema schema, @NotNull final ArrayList<StringBuilder> ldifLines, @NotNull final Iterator<StringBuilder> iterator, @NotNull final String relativeBasePath, final long firstLineNumber) throws LDIFException {
    final LinkedHashMap<String, Object> attributes = new LinkedHashMap<>(StaticUtils.computeMapCapacity(ldifLines.size()));
    while (iterator.hasNext()) {
        final StringBuilder line = iterator.next();
        handleTrailingSpaces(line, dn, firstLineNumber, trailingSpaceBehavior);
        final int colonPos = line.indexOf(":");
        if (colonPos <= 0) {
            throw new LDIFException(ERR_READ_NO_ATTR_COLON.get(firstLineNumber), firstLineNumber, true, ldifLines, null);
        }
        final String attributeName = line.substring(0, colonPos);
        final String lowerName = StaticUtils.toLowerCase(attributeName);
        final MatchingRule matchingRule;
        if (schema == null) {
            matchingRule = CaseIgnoreStringMatchingRule.getInstance();
        } else {
            matchingRule = MatchingRule.selectEqualityMatchingRule(attributeName, schema);
        }
        Attribute attr;
        final LDIFAttribute ldifAttr;
        final Object attrObject = attributes.get(lowerName);
        if (attrObject == null) {
            attr = null;
            ldifAttr = null;
        } else {
            if (attrObject instanceof Attribute) {
                attr = (Attribute) attrObject;
                ldifAttr = new LDIFAttribute(attr.getName(), matchingRule, attr.getRawValues()[0]);
                attributes.put(lowerName, ldifAttr);
            } else {
                attr = null;
                ldifAttr = (LDIFAttribute) attrObject;
            }
        }
        final int length = line.length();
        if (length == (colonPos + 1)) {
            // acceptable.
            if (attrObject == null) {
                attr = new Attribute(attributeName, matchingRule, "");
                attributes.put(lowerName, attr);
            } else {
                try {
                    if (!ldifAttr.addValue(new ASN1OctetString(), duplicateValueBehavior)) {
                        if (duplicateValueBehavior != DuplicateValueBehavior.STRIP) {
                            throw new LDIFException(ERR_READ_DUPLICATE_VALUE.get(dn, firstLineNumber, attributeName), firstLineNumber, true, ldifLines, null);
                        }
                    }
                } catch (final LDAPException le) {
                    throw new LDIFException(ERR_READ_VALUE_SYNTAX_VIOLATION.get(dn, firstLineNumber, attributeName, StaticUtils.getExceptionMessage(le)), firstLineNumber, true, ldifLines, le);
                }
            }
        } else if (line.charAt(colonPos + 1) == ':') {
            // Skip over any spaces leading up to the value, and then the rest of
            // the string is the base64-encoded attribute value.
            int pos = colonPos + 2;
            while ((pos < length) && (line.charAt(pos) == ' ')) {
                pos++;
            }
            try {
                final byte[] valueBytes = Base64.decode(line.substring(pos));
                if (attrObject == null) {
                    attr = new Attribute(attributeName, matchingRule, valueBytes);
                    attributes.put(lowerName, attr);
                } else {
                    try {
                        if (!ldifAttr.addValue(new ASN1OctetString(valueBytes), duplicateValueBehavior)) {
                            if (duplicateValueBehavior != DuplicateValueBehavior.STRIP) {
                                throw new LDIFException(ERR_READ_DUPLICATE_VALUE.get(dn, firstLineNumber, attributeName), firstLineNumber, true, ldifLines, null);
                            }
                        }
                    } catch (final LDAPException le) {
                        throw new LDIFException(ERR_READ_VALUE_SYNTAX_VIOLATION.get(dn, firstLineNumber, attributeName, StaticUtils.getExceptionMessage(le)), firstLineNumber, true, ldifLines, le);
                    }
                }
            } catch (final ParseException pe) {
                Debug.debugException(pe);
                throw new LDIFException(ERR_READ_CANNOT_BASE64_DECODE_ATTR.get(attributeName, firstLineNumber, pe.getMessage()), firstLineNumber, true, ldifLines, pe);
            }
        } else if (line.charAt(colonPos + 1) == '<') {
            // Skip over any spaces leading up to the value, and then the rest of
            // the string is a URL that indicates where to get the real content.
            // At the present time, we'll only support the file URLs.
            int pos = colonPos + 2;
            while ((pos < length) && (line.charAt(pos) == ' ')) {
                pos++;
            }
            final byte[] urlBytes;
            final String urlString = line.substring(pos);
            try {
                urlBytes = retrieveURLBytes(urlString, relativeBasePath, firstLineNumber);
            } catch (final Exception e) {
                Debug.debugException(e);
                throw new LDIFException(ERR_READ_URL_EXCEPTION.get(attributeName, urlString, firstLineNumber, e), firstLineNumber, true, ldifLines, e);
            }
            if (attrObject == null) {
                attr = new Attribute(attributeName, matchingRule, urlBytes);
                attributes.put(lowerName, attr);
            } else {
                try {
                    if (!ldifAttr.addValue(new ASN1OctetString(urlBytes), duplicateValueBehavior)) {
                        if (duplicateValueBehavior != DuplicateValueBehavior.STRIP) {
                            throw new LDIFException(ERR_READ_DUPLICATE_VALUE.get(dn, firstLineNumber, attributeName), firstLineNumber, true, ldifLines, null);
                        }
                    }
                } catch (final LDIFException le) {
                    Debug.debugException(le);
                    throw le;
                } catch (final Exception e) {
                    Debug.debugException(e);
                    throw new LDIFException(ERR_READ_URL_EXCEPTION.get(attributeName, urlString, firstLineNumber, e), firstLineNumber, true, ldifLines, e);
                }
            }
        } else {
            // Skip over any spaces leading up to the value, and then the rest of
            // the string is the value.
            int pos = colonPos + 1;
            while ((pos < length) && (line.charAt(pos) == ' ')) {
                pos++;
            }
            final String valueString = line.substring(pos);
            if (attrObject == null) {
                attr = new Attribute(attributeName, matchingRule, valueString);
                attributes.put(lowerName, attr);
            } else {
                try {
                    if (!ldifAttr.addValue(new ASN1OctetString(valueString), duplicateValueBehavior)) {
                        if (duplicateValueBehavior != DuplicateValueBehavior.STRIP) {
                            throw new LDIFException(ERR_READ_DUPLICATE_VALUE.get(dn, firstLineNumber, attributeName), firstLineNumber, true, ldifLines, null);
                        }
                    }
                } catch (final LDAPException le) {
                    throw new LDIFException(ERR_READ_VALUE_SYNTAX_VIOLATION.get(dn, firstLineNumber, attributeName, StaticUtils.getExceptionMessage(le)), firstLineNumber, true, ldifLines, le);
                }
            }
        }
    }
    final ArrayList<Attribute> attrList = new ArrayList<>(attributes.size());
    for (final Object o : attributes.values()) {
        if (o instanceof Attribute) {
            attrList.add((Attribute) o);
        } else {
            attrList.add(((LDIFAttribute) o).toAttribute());
        }
    }
    return attrList;
}
Also used : ASN1OctetString(com.unboundid.asn1.ASN1OctetString) Attribute(com.unboundid.ldap.sdk.Attribute) ArrayList(java.util.ArrayList) ASN1OctetString(com.unboundid.asn1.ASN1OctetString) ParseException(java.text.ParseException) LDAPException(com.unboundid.ldap.sdk.LDAPException) IOException(java.io.IOException) LinkedHashMap(java.util.LinkedHashMap) LDAPException(com.unboundid.ldap.sdk.LDAPException) ParseException(java.text.ParseException) MatchingRule(com.unboundid.ldap.matchingrules.MatchingRule) CaseIgnoreStringMatchingRule(com.unboundid.ldap.matchingrules.CaseIgnoreStringMatchingRule) NotNull(com.unboundid.util.NotNull)

Example 5 with MatchingRule

use of com.unboundid.ldap.matchingrules.MatchingRule in project ldapsdk by pingidentity.

the class DefaultObjectEncoder method encodeCollection.

/**
 * Encodes the contents of the provided collection.
 *
 * @param  genericType    The generic type of the collection.
 * @param  collection     The collection to process.
 * @param  attributeName  The name to use for the attribute to create.
 *
 * @return  The attribute containing the encoded collection contents.
 *
 * @throws  LDAPPersistException  If a problem occurs while trying to create
 *                                the attribute.
 */
@NotNull()
private static Attribute encodeCollection(@NotNull final Class<?> genericType, @NotNull final Collection<?> collection, @NotNull final String attributeName) throws LDAPPersistException {
    final ASN1OctetString[] values = new ASN1OctetString[collection.size()];
    final AtomicReference<MatchingRule> matchingRule = new AtomicReference<>();
    int i = 0;
    for (final Object o : collection) {
        if (genericType.equals(AtomicInteger.class) || genericType.equals(AtomicLong.class) || genericType.equals(BigDecimal.class) || genericType.equals(BigInteger.class) || genericType.equals(Double.class) || genericType.equals(Double.TYPE) || genericType.equals(Float.class) || genericType.equals(Float.TYPE) || genericType.equals(Integer.class) || genericType.equals(Integer.TYPE) || genericType.equals(Long.class) || genericType.equals(Long.TYPE) || genericType.equals(Short.class) || genericType.equals(Short.TYPE) || genericType.equals(String.class) || genericType.equals(StringBuffer.class) || genericType.equals(StringBuilder.class) || genericType.equals(UUID.class) || genericType.equals(DN.class) || genericType.equals(Filter.class) || genericType.equals(LDAPURL.class) || genericType.equals(RDN.class)) {
            if (matchingRule.get() == null) {
                final String syntaxOID = getSyntaxOID(genericType);
                matchingRule.set(MatchingRule.selectMatchingRuleForSyntax(syntaxOID));
            }
            values[i] = new ASN1OctetString(String.valueOf(o));
        } else if (genericType.equals(URI.class)) {
            final URI uri = (URI) o;
            values[i] = new ASN1OctetString(uri.toASCIIString());
        } else if (genericType.equals(URL.class)) {
            final URL url = (URL) o;
            values[i] = new ASN1OctetString(url.toExternalForm());
        } else if (o instanceof byte[]) {
            matchingRule.compareAndSet(null, OctetStringMatchingRule.getInstance());
            values[i] = new ASN1OctetString((byte[]) o);
        } else if (o instanceof char[]) {
            values[i] = new ASN1OctetString(new String((char[]) o));
        } else if (genericType.equals(Boolean.class) || genericType.equals(Boolean.TYPE)) {
            matchingRule.compareAndSet(null, BooleanMatchingRule.getInstance());
            final Boolean b = (Boolean) o;
            if (b) {
                values[i] = new ASN1OctetString("TRUE");
            } else {
                values[i] = new ASN1OctetString("FALSE");
            }
        } else if (genericType.equals(Date.class)) {
            matchingRule.compareAndSet(null, GeneralizedTimeMatchingRule.getInstance());
            final Date d = (Date) o;
            values[i] = new ASN1OctetString(StaticUtils.encodeGeneralizedTime(d));
        } else if (genericType.isEnum()) {
            final Enum<?> e = (Enum<?>) o;
            values[i] = new ASN1OctetString(e.name());
        } else if (Serializable.class.isAssignableFrom(genericType)) {
            matchingRule.compareAndSet(null, OctetStringMatchingRule.getInstance());
            try {
                final ByteArrayOutputStream baos = new ByteArrayOutputStream();
                final ObjectOutputStream oos = new ObjectOutputStream(baos);
                oos.writeObject(o);
                oos.close();
                values[i] = new ASN1OctetString(baos.toByteArray());
            } catch (final Exception e) {
                Debug.debugException(e);
                throw new LDAPPersistException(ERR_DEFAULT_ENCODER_CANNOT_SERIALIZE.get(attributeName, StaticUtils.getExceptionMessage(e)), e);
            }
        } else {
            throw new LDAPPersistException(ERR_DEFAULT_ENCODER_UNSUPPORTED_TYPE.get(genericType.getName()));
        }
        i++;
    }
    matchingRule.compareAndSet(null, CaseIgnoreStringMatchingRule.getInstance());
    return new Attribute(attributeName, matchingRule.get(), values);
}
Also used : ASN1OctetString(com.unboundid.asn1.ASN1OctetString) Attribute(com.unboundid.ldap.sdk.Attribute) ASN1OctetString(com.unboundid.asn1.ASN1OctetString) ObjectOutputStream(java.io.ObjectOutputStream) URI(java.net.URI) URL(java.net.URL) LDAPURL(com.unboundid.ldap.sdk.LDAPURL) UUID(java.util.UUID) RDN(com.unboundid.ldap.sdk.RDN) AtomicReference(java.util.concurrent.atomic.AtomicReference) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Date(java.util.Date) InvocationTargetException(java.lang.reflect.InvocationTargetException) LDAPException(com.unboundid.ldap.sdk.LDAPException) AtomicLong(java.util.concurrent.atomic.AtomicLong) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Filter(com.unboundid.ldap.sdk.Filter) BigInteger(java.math.BigInteger) MatchingRule(com.unboundid.ldap.matchingrules.MatchingRule) GeneralizedTimeMatchingRule(com.unboundid.ldap.matchingrules.GeneralizedTimeMatchingRule) OctetStringMatchingRule(com.unboundid.ldap.matchingrules.OctetStringMatchingRule) BooleanMatchingRule(com.unboundid.ldap.matchingrules.BooleanMatchingRule) CaseIgnoreStringMatchingRule(com.unboundid.ldap.matchingrules.CaseIgnoreStringMatchingRule) NotNull(com.unboundid.util.NotNull)

Aggregations

MatchingRule (com.unboundid.ldap.matchingrules.MatchingRule)19 ASN1OctetString (com.unboundid.asn1.ASN1OctetString)18 NotNull (com.unboundid.util.NotNull)12 CaseIgnoreStringMatchingRule (com.unboundid.ldap.matchingrules.CaseIgnoreStringMatchingRule)11 Attribute (com.unboundid.ldap.sdk.Attribute)8 LDAPException (com.unboundid.ldap.sdk.LDAPException)8 GeneralizedTimeMatchingRule (com.unboundid.ldap.matchingrules.GeneralizedTimeMatchingRule)7 RDN (com.unboundid.ldap.sdk.RDN)7 ArrayList (java.util.ArrayList)5 Date (java.util.Date)5 BooleanMatchingRule (com.unboundid.ldap.matchingrules.BooleanMatchingRule)4 OctetStringMatchingRule (com.unboundid.ldap.matchingrules.OctetStringMatchingRule)4 DN (com.unboundid.ldap.sdk.DN)4 DistinguishedNameMatchingRule (com.unboundid.ldap.matchingrules.DistinguishedNameMatchingRule)3 IntegerMatchingRule (com.unboundid.ldap.matchingrules.IntegerMatchingRule)3 ASN1Exception (com.unboundid.asn1.ASN1Exception)2 LDAPMessage (com.unboundid.ldap.protocol.LDAPMessage)2 ChangeLogEntry (com.unboundid.ldap.sdk.ChangeLogEntry)2 Control (com.unboundid.ldap.sdk.Control)2 Entry (com.unboundid.ldap.sdk.Entry)2