List of usage examples for javax.naming.directory Attribute getAll
NamingEnumeration<?> getAll() throws NamingException;
From source file:org.apache.jmeter.protocol.ldap.sampler.LDAPExtSampler.java
private void writeSearchResult(final SearchResult sr, final XMLBuffer xmlb) throws NamingException { final Attributes attrs = sr.getAttributes(); final int size = attrs.size(); final ArrayList<Attribute> sortedAttrs = new ArrayList<>(size); xmlb.openTag("searchresult"); // $NON-NLS-1$ xmlb.tag("dn", sr.getName()); // $NON-NLS-1$ xmlb.tag("returnedattr", Integer.toString(size)); // $NON-NLS-1$ xmlb.openTag("attributes"); // $NON-NLS-1$ try {//from w w w.j a v a 2 s .c o m for (NamingEnumeration<? extends Attribute> en = attrs.getAll(); en.hasMore();) { final Attribute attr = en.next(); sortedAttrs.add(attr); } sortAttributes(sortedAttrs); for (final Attribute attr : sortedAttrs) { StringBuilder sb = new StringBuilder(); if (attr.size() == 1) { sb.append(getWriteValue(attr.get())); } else { final ArrayList<String> sortedVals = new ArrayList<>(attr.size()); boolean first = true; for (NamingEnumeration<?> ven = attr.getAll(); ven.hasMore();) { final Object value = getWriteValue(ven.next()); sortedVals.add(value.toString()); } Collections.sort(sortedVals); for (final String value : sortedVals) { if (first) { first = false; } else { sb.append(", "); // $NON-NLS-1$ } sb.append(value); } } xmlb.tag(attr.getID(), sb); } } finally { xmlb.closeTag("attributes"); // $NON-NLS-1$ xmlb.closeTag("searchresult"); // $NON-NLS-1$ } }
From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.EnhancedLDAPUserRegistry.java
protected Collection<Object> mapAttribute(final Attribute attribute) throws NamingException { Collection<Object> values; if (attribute.isOrdered()) { values = new ArrayList<>(); } else {// w ww. j a v a2 s. co m values = new HashSet<>(); } final NamingEnumeration<?> allAttributeValues = attribute.getAll(); while (allAttributeValues.hasMore()) { final Object next = allAttributeValues.next(); final Object mappedValue = this.mapAttributeValue(attribute.getID(), next); values.add(mappedValue); } LOGGER.debug("Mapped value of {} to {}", attribute, values); return values; }
From source file:org.liveSense.auth.ldap.LdapAuthenticationHandler.java
/** * Copy LDAP user properties to JCR User properties * @param ldapUser//w ww. j a v a 2s. c om */ private void updateUserAttributes(Session session, LdapUser ldapUser, Authorizable user) { // Collecting attribute names try { for (Iterator e = user.getPropertyNames(); e.hasNext();) { user.removeProperty((String) e.next()); } for (NamingEnumeration<? extends Attribute> ae = ldapUser.getAttributes().getAll(); ae.hasMore();) { Attribute attr = ae.next(); log.info("Attribute: " + attr.getID()); // multi value attribute if (attr.size() > 1) { Value[] props = new Value[attr.size()]; int i = 0; for (NamingEnumeration e = attr.getAll(); e.hasMore();) { Object o = e.next(); if (o instanceof String) props[i] = session.getValueFactory().createValue((String) o); i++; } user.setProperty(attr.getID(), props); } else { if (attr.get(0) instanceof String) user.setProperty(attr.getID(), session.getValueFactory().createValue((String) attr.get(0))); } } } catch (Exception e) { log.error("Could not update user attributes", e); } }
From source file:org.josso.gateway.identity.service.store.ldap.LDAPIdentityStore.java
/** * Fetch the Ldap user attributes to be used as credentials. * * @param uid the user id (or lookup value) for whom credentials are required * @return the hash map containing user credentials as name/value pairs * @throws NamingException LDAP error obtaining user credentials. * @throws IOException //from ww w .j a v a 2 s . co m */ protected HashMap selectCredentials(String uid, CredentialProvider cp) throws NamingException, IOException { HashMap credentialResultSet = new HashMap(); InitialLdapContext ctx = createLdapInitialContext(false); StartTlsResponse tls = null; if (getEnableStartTls()) { tls = startTls(ctx); } String schemeName = null; if (cp instanceof AuthenticationScheme) { schemeName = ((AuthenticationScheme) cp).getName(); } String principalLookupAttrName = this.getPrincipalLookupAttributeID(); if (principalLookupAttrName == null || principalLookupAttrName.trim().equals("") || !"strong-authentication".equals(schemeName)) { principalLookupAttrName = this.getPrincipalUidAttributeID(); } String usersCtxDN = this.getUsersCtxDN(); // BasicAttributes matchAttrs = new BasicAttributes(true); // matchAttrs.put(principalUidAttrName, uid); String credentialQueryString = getCredentialQueryString(); HashMap credentialQueryMap = parseQueryString(credentialQueryString); Iterator i = credentialQueryMap.keySet().iterator(); List credentialAttrList = new ArrayList(); while (i.hasNext()) { String o = (String) i.next(); credentialAttrList.add(o); } String[] credentialAttr = (String[]) credentialAttrList.toArray(new String[credentialAttrList.size()]); try { // NamingEnumeration answer = ctx.search(usersCtxDN, matchAttrs, credentialAttr); // This gives more control over search behavior : NamingEnumeration answer = ctx.search(usersCtxDN, "(&(" + principalLookupAttrName + "=" + uid + "))", getSearchControls()); while (answer.hasMore()) { SearchResult sr = (SearchResult) answer.next(); Attributes attrs = sr.getAttributes(); String userDN = sr.getNameInNamespace(); if (logger.isDebugEnabled()) logger.debug("Processing results for entry '" + userDN + "'"); for (int j = 0; j < credentialAttr.length; j++) { if (attrs.get(credentialAttr[j]) == null) continue; //Object credentialObject = attrs.get(credentialAttr[j]).get(); String credentialName = (String) credentialQueryMap.get(credentialAttr[j]); String credentialValue = null; Attribute attr = attrs.get(credentialAttr[j]); NamingEnumeration attrEnum = attr.getAll(); while (attrEnum.hasMore()) { Object credentialObject = attrEnum.next(); if (credentialObject == null) continue; if (logger.isDebugEnabled()) logger.debug("Found user credential '" + credentialName + "' of type '" + credentialObject.getClass().getName() + "" + (credentialObject.getClass().isArray() ? "[" + Array.getLength(credentialObject) + "]" : "") + "'"); // if the attribute value is an array, cast it to byte[] and then convert to // String using proper encoding if (credentialObject.getClass().isArray()) { try { // Try to create a UTF-8 String, we use java.nio to handle errors in a better way. // If the byte[] cannot be converted to UTF-8, we're using the credentialObject as is. byte[] credentialData = (byte[]) credentialObject; ByteBuffer in = ByteBuffer.allocate(credentialData.length); in.put(credentialData); in.flip(); Charset charset = Charset.forName("UTF-8"); CharsetDecoder decoder = charset.newDecoder(); CharBuffer charBuffer = decoder.decode(in); credentialValue = charBuffer.toString(); } catch (CharacterCodingException e) { if (logger.isDebugEnabled()) logger.debug("Can't convert credential value to String using UTF-8"); } } else if (credentialObject instanceof String) { // The credential value must be a String ... credentialValue = (String) credentialObject; } // Check what do we have ... List credentials = (List) credentialResultSet.get(credentialName); if (credentials == null) { credentials = new ArrayList(); } if (credentialValue != null) { // Remove any schema information from the credential value, like the {md5} prefix for passwords. credentialValue = getSchemeFreeValue(credentialValue); credentials.add(credentialValue); } else { // We have a binary credential, leave it as it is ... probably binary value. credentials.add(credentialObject); } credentialResultSet.put(credentialName, credentials); if (logger.isDebugEnabled()) logger.debug("Found user credential '" + credentialName + "' with value '" + (credentialValue != null ? credentialValue : credentialObject) + "'"); } } } } catch (NamingException e) { if (logger.isDebugEnabled()) logger.debug("Failed to locate user", e); } finally { // Close the context to release the connection if (tls != null) { tls.close(); } ctx.close(); } return credentialResultSet; }
From source file:dk.magenta.ldap.LDAPMultiBaseUserRegistry.java
/** * Does a case-insensitive search for the given value in an attribute. * * @param attribute/* w ww .j a va2 s .co m*/ * the attribute * @param value * the value to search for * @return <code>true</code>, if the value was found * @throws javax.naming.NamingException * if there is a problem accessing the attribute values */ private boolean hasAttributeValue(Attribute attribute, String value) throws NamingException { if (attribute != null) { NamingEnumeration<?> values = attribute.getAll(); while (values.hasMore()) { try { if (value.equalsIgnoreCase((String) values.next())) { return true; } } catch (ClassCastException e) { // Not a string value. ignore and continue } } } return false; }
From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.EnhancedLDAPUserRegistry.java
protected <T> Collection<T> mapAttribute(final Attribute attribute, final Class<T> expectedValueClass) throws NamingException { Collection<T> values;//from w ww . ja va2s . c o m if (attribute.isOrdered()) { values = new ArrayList<>(); } else { values = new HashSet<>(); } final NamingEnumeration<?> allAttributeValues = attribute.getAll(); while (allAttributeValues.hasMore()) { final Object next = allAttributeValues.next(); final Object mappedValue = this.mapAttributeValue(attribute.getID(), next); final T value = DefaultTypeConverter.INSTANCE.convert(expectedValueClass, mappedValue); values.add(value); } LOGGER.debug("Mapped value of {} to {}", attribute, values); return values; }
From source file:nl.nn.adapterframework.ldap.LdapSender.java
private String performOperationDelete(String entryName, ParameterResolutionContext prc, Map paramValueMap, Attributes attrs) throws SenderException, ParameterException { if (manipulationSubject.equals(MANIPULATION_ATTRIBUTE)) { String result = null;/*from w ww . j a v a 2s . c om*/ NamingEnumeration na = attrs.getAll(); while (na.hasMoreElements()) { Attribute a = (Attribute) na.nextElement(); log.debug("Delete attribute: " + a.getID()); NamingEnumeration values; try { values = a.getAll(); } catch (NamingException e1) { storeLdapException(e1, prc); throw new SenderException("cannot obtain values of Attribute [" + a.getID() + "]", e1); } while (values.hasMoreElements()) { Attributes partialAttrs = new BasicAttributes(); Attribute singleValuedAttribute; String id = a.getID(); Object value = values.nextElement(); if (log.isDebugEnabled()) { if (id.toLowerCase().contains("password") || id.toLowerCase().contains("pwd")) { log.debug("Delete value: ***"); } else { log.debug("Delete value: " + value); } } if (unicodePwd && "unicodePwd".equalsIgnoreCase(id)) { singleValuedAttribute = new BasicAttribute(id, encodeUnicodePwd(value)); } else { singleValuedAttribute = new BasicAttribute(id, value); } partialAttrs.put(singleValuedAttribute); DirContext dirContext = null; try { dirContext = getDirContext(paramValueMap); dirContext.modifyAttributes(entryName, DirContext.REMOVE_ATTRIBUTE, partialAttrs); } catch (NamingException e) { // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes: // 16 LDAP_NO_SUCH_ATTRIBUTE Indicates that the attribute specified in the modify or compare operation does not exist in the entry. // 32 LDAP_NO_SUCH_OBJECT Indicates the target object cannot be found. This code is not returned on following operations: Search operations that find the search base but cannot find any entries that match the search filter. Bind operations. // Sun: // [LDAP: error code 16 - No Such Attribute... // [LDAP: error code 32 - No Such Object... // AD: // [LDAP: error code 16 - 00002085: AtrErr: DSID-03151F03, #1... if (e.getMessage().startsWith("[LDAP: error code 16 - ") || e.getMessage().startsWith("[LDAP: error code 32 - ")) { if (log.isDebugEnabled()) log.debug("Operation [" + getOperation() + "] successful: " + e.getMessage()); result = DEFAULT_RESULT_DELETE; } else { storeLdapException(e, prc); throw new SenderException( "Exception in operation [" + getOperation() + "] entryName [" + entryName + "]", e); } } finally { closeDirContext(dirContext); } } } if (result != null) { return result; } return DEFAULT_RESULT; } else { DirContext dirContext = null; try { dirContext = getDirContext(paramValueMap); dirContext.unbind(entryName); return DEFAULT_RESULT; } catch (NamingException e) { // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes: // 32 LDAP_NO_SUCH_OBJECT Indicates the target object cannot be found. This code is not returned on following operations: Search operations that find the search base but cannot find any entries that match the search filter. Bind operations. // Sun: // [LDAP: error code 32 - No Such Object... if (e.getMessage().startsWith("[LDAP: error code 32 - ")) { if (log.isDebugEnabled()) log.debug("Operation [" + getOperation() + "] successful: " + e.getMessage()); return DEFAULT_RESULT_DELETE; } else { storeLdapException(e, prc); throw new SenderException( "Exception in operation [" + getOperation() + "] entryName [" + entryName + "]", e); } } finally { closeDirContext(dirContext); } } }
From source file:org.nuxeo.ecm.directory.ldap.LDAPReference.java
/** * Optimized method to spare a LDAP request when the caller is a LDAPSession object that has already fetched the * LDAP Attribute instances./* w w w .j a va 2 s . c om*/ * <p> * This method should return the same results as the sister method: org.nuxeo * .ecm.directory.Reference#getTargetIdsForSource(java.lang.String) * * @return target reference ids * @throws DirectoryException */ public List<String> getLdapTargetIds(Attributes attributes) throws DirectoryException { Set<String> targetIds = new TreeSet<>(); LDAPDirectory ldapTargetDirectory = (LDAPDirectory) getTargetDirectory(); LDAPDirectoryDescriptor targetDirconfig = getTargetDirectoryDescriptor(); String emptyRefMarker = ldapTargetDirectory.getDescriptor().getEmptyRefMarker(); try (LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession()) { String baseDn = pseudoNormalizeDn(targetDirconfig.getSearchBaseDn()); // step #1: fetch ids referenced by static attributes String staticAttributeId = getStaticAttributeId(); Attribute staticAttribute = null; if (staticAttributeId != null) { staticAttribute = attributes.get(staticAttributeId); } if (staticAttribute != null && !staticAttributeIdIsDn) { NamingEnumeration<?> staticContent = staticAttribute.getAll(); try { while (staticContent.hasMore()) { String value = staticContent.next().toString(); if (!emptyRefMarker.equals(value)) { targetIds.add(value); } } } finally { staticContent.close(); } } if (staticAttribute != null && staticAttributeIdIsDn) { NamingEnumeration<?> targetDns = staticAttribute.getAll(); try { while (targetDns.hasMore()) { String targetDn = targetDns.next().toString(); if (!pseudoNormalizeDn(targetDn).endsWith(baseDn)) { // optim: avoid network connections when obvious if (log.isTraceEnabled()) { log.trace(String.format("ignoring: dn='%s' (does not match '%s') for '%s'", targetDn, baseDn, this)); } continue; } // find the id of the referenced entry String id = null; if (targetSession.rdnMatchesIdField()) { // optim: do not fetch the entry to get its true id // but // guess it by reading the targetDn LdapName name = new LdapName(targetDn); String rdn = name.get(name.size() - 1); int pos = rdn.indexOf("="); id = rdn.substring(pos + 1); } else { id = getIdForDn(targetSession, targetDn); if (id == null) { log.warn(String.format( "ignoring target '%s' (missing attribute '%s') while resolving reference '%s'", targetDn, targetSession.idAttribute, this)); continue; } } if (forceDnConsistencyCheck) { // check that the referenced entry is actually part // of // the target directory (takes care of the filters // and // the scope) // this check can be very expensive on large groups // and thus not enabled by default if (!targetSession.hasEntry(id)) { if (log.isTraceEnabled()) { log.trace(String.format( "ignoring target '%s' when resolving '%s' (not part of target" + " directory by forced DN consistency check)", targetDn, this)); } continue; } } // NXP-2461: check that id field is filled if (id != null) { targetIds.add(id); } } } finally { targetDns.close(); } } // step #2: fetched dynamically referenced ids String dynamicAttributeId = this.dynamicAttributeId; Attribute dynamicAttribute = null; if (dynamicAttributeId != null) { dynamicAttribute = attributes.get(dynamicAttributeId); } if (dynamicAttribute != null) { NamingEnumeration<?> rawldapUrls = dynamicAttribute.getAll(); try { while (rawldapUrls.hasMore()) { LdapURL ldapUrl = new LdapURL(rawldapUrls.next().toString()); String linkDn = pseudoNormalizeDn(ldapUrl.getDN()); String directoryDn = pseudoNormalizeDn(targetDirconfig.getSearchBaseDn()); int scope = SearchControls.ONELEVEL_SCOPE; String scopePart = ldapUrl.getScope(); if (scopePart != null && scopePart.toLowerCase().startsWith("sub")) { scope = SearchControls.SUBTREE_SCOPE; } if (!linkDn.endsWith(directoryDn) && !directoryDn.endsWith(linkDn)) { // optim #1: if the dns do not match, abort continue; } else if (directoryDn.endsWith(linkDn) && linkDn.length() < directoryDn.length() && scope == SearchControls.ONELEVEL_SCOPE) { // optim #2: the link dn is pointing to elements // that at // upperlevel than directory elements continue; } else { // Search for references elements targetIds.addAll(getReferencedElements(attributes, directoryDn, linkDn, ldapUrl.getFilter(), scope)); } } } finally { rawldapUrls.close(); } } if (dynamicReferences != null && dynamicReferences.length > 0) { // Only the first Dynamic Reference is used LDAPDynamicReferenceDescriptor dynAtt = dynamicReferences[0]; Attribute baseDnsAttribute = attributes.get(dynAtt.baseDN); Attribute filterAttribute = attributes.get(dynAtt.filter); if (baseDnsAttribute != null && filterAttribute != null) { NamingEnumeration<?> baseDns = null; NamingEnumeration<?> filters = null; try { // Get the BaseDN value from the descriptor baseDns = baseDnsAttribute.getAll(); String linkDnValue = baseDns.next().toString(); baseDns.close(); linkDnValue = pseudoNormalizeDn(linkDnValue); // Get the filter value from the descriptor filters = filterAttribute.getAll(); String filterValue = filters.next().toString(); filters.close(); // Get the scope value from the descriptor int scope = "subtree".equalsIgnoreCase(dynAtt.type) ? SearchControls.SUBTREE_SCOPE : SearchControls.ONELEVEL_SCOPE; String directoryDn = pseudoNormalizeDn(targetDirconfig.getSearchBaseDn()); // if the dns match, and if the link dn is pointing to // elements that at upperlevel than directory elements if ((linkDnValue.endsWith(directoryDn) || directoryDn.endsWith(linkDnValue)) && !(directoryDn.endsWith(linkDnValue) && linkDnValue.length() < directoryDn.length() && scope == SearchControls.ONELEVEL_SCOPE)) { // Correct the filter expression filterValue = FilterExpressionCorrector.correctFilter(filterValue, FilterJobs.CORRECT_NOT); // Search for references elements targetIds.addAll(getReferencedElements(attributes, directoryDn, linkDnValue, filterValue, scope)); } } finally { if (baseDns != null) { baseDns.close(); } if (filters != null) { filters.close(); } } } } // return merged attributes return new ArrayList<String>(targetIds); } catch (NamingException e) { throw new DirectoryException("error computing LDAP references", e); } }
From source file:nl.nn.adapterframework.ldap.LdapSender.java
private String performOperationCreate(String entryName, ParameterResolutionContext prc, Map paramValueMap, Attributes attrs) throws SenderException, ParameterException { if (manipulationSubject.equals(MANIPULATION_ATTRIBUTE)) { String result = null;/*ww w . j a v a 2 s . c o m*/ NamingEnumeration na = attrs.getAll(); while (na.hasMoreElements()) { Attribute a = (Attribute) na.nextElement(); log.debug("Create attribute: " + a.getID()); NamingEnumeration values; try { values = a.getAll(); } catch (NamingException e1) { storeLdapException(e1, prc); throw new SenderException("cannot obtain values of Attribute [" + a.getID() + "]", e1); } while (values.hasMoreElements()) { Attributes partialAttrs = new BasicAttributes(); Attribute singleValuedAttribute; String id = a.getID(); Object value = values.nextElement(); if (log.isDebugEnabled()) { if (id.toLowerCase().contains("password") || id.toLowerCase().contains("pwd")) { log.debug("Create value: ***"); } else { log.debug("Create value: " + value); } } if (unicodePwd && "unicodePwd".equalsIgnoreCase(id)) { singleValuedAttribute = new BasicAttribute(id, encodeUnicodePwd(value)); } else { singleValuedAttribute = new BasicAttribute(id, value); } partialAttrs.put(singleValuedAttribute); DirContext dirContext = null; try { dirContext = getDirContext(paramValueMap); dirContext.modifyAttributes(entryName, DirContext.ADD_ATTRIBUTE, partialAttrs); } catch (NamingException e) { // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes: // 20 LDAP_TYPE_OR_VALUE_EXISTS Indicates that the attribute value specified in a modify or add operation already exists as a value for that attribute. // Sun: // [LDAP: error code 20 - Attribute Or Value Exists] if (e.getMessage().startsWith("[LDAP: error code 20 - ")) { if (log.isDebugEnabled()) log.debug("Operation [" + getOperation() + "] successful: " + e.getMessage()); result = DEFAULT_RESULT_CREATE_OK; } else { storeLdapException(e, prc); throw new SenderException( "Exception in operation [" + getOperation() + "] entryName [" + entryName + "]", e); } } finally { closeDirContext(dirContext); } } } if (result != null) { return result; } return DEFAULT_RESULT; } else { DirContext dirContext = null; try { if (unicodePwd) { Enumeration enumeration = attrs.getIDs(); while (enumeration.hasMoreElements()) { String id = (String) enumeration.nextElement(); if ("unicodePwd".equalsIgnoreCase(id)) { Attribute attr = attrs.get(id); for (int i = 0; i < attr.size(); i++) { attr.set(i, encodeUnicodePwd(attr.get(i))); } } } } dirContext = getDirContext(paramValueMap); dirContext.bind(entryName, null, attrs); return DEFAULT_RESULT; } catch (NamingException e) { // if (log.isDebugEnabled()) log.debug("Exception in operation [" + getOperation()+ "] entryName ["+entryName+"]", e); if (log.isDebugEnabled()) log.debug("Exception in operation [" + getOperation() + "] entryName [" + entryName + "]: " + e.getMessage()); // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes: // 68 LDAP_ALREADY_EXISTS Indicates that the add operation attempted to add an entry that already exists, or that the modify operation attempted to rename an entry to the name of an entry that already exists. // Sun: // [LDAP: error code 68 - Entry Already Exists] if (e.getMessage().startsWith("[LDAP: error code 68 - ")) { return DEFAULT_RESULT_CREATE_OK; } else { storeLdapException(e, prc); throw new SenderException(e); } } finally { closeDirContext(dirContext); } } }
From source file:org.nuxeo.ecm.directory.ldap.LDAPReference.java
/** * Remove existing statically defined links for the given source id (dynamic references remain unaltered) * * @see org.nuxeo.ecm.directory.Reference#removeLinksForSource(String) *///w ww . j av a 2 s. c om @Override public void removeLinksForSource(String sourceId) throws DirectoryException { LDAPDirectory ldapTargetDirectory = (LDAPDirectory) getTargetDirectory(); LDAPDirectory ldapSourceDirectory = (LDAPDirectory) getSourceDirectory(); String attributeId = getStaticAttributeId(); try (LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession(); LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession()) { if (sourceSession.isReadOnly() || attributeId == null) { // do not try to do anything on a read only server or to a // purely dynamic reference return; } // get the dn of the entry that matches sourceId SearchResult sourceLdapEntry = sourceSession.getLdapEntry(sourceId); if (sourceLdapEntry == null) { throw new DirectoryException( String.format("cannot edit the links hold by missing entry '%s' in directory '%s'", sourceId, ldapSourceDirectory.getName())); } String sourceDn = pseudoNormalizeDn(sourceLdapEntry.getNameInNamespace()); Attribute oldAttr = sourceLdapEntry.getAttributes().get(attributeId); if (oldAttr == null) { // consider it as an empty attribute to simplify the following // code oldAttr = new BasicAttribute(attributeId); } Attribute attrToRemove = new BasicAttribute(attributeId); NamingEnumeration<?> oldAttrs = oldAttr.getAll(); String targetBaseDn = pseudoNormalizeDn(ldapTargetDirectory.getDescriptor().getSearchBaseDn()); try { while (oldAttrs.hasMore()) { String targetKeyAttr = oldAttrs.next().toString(); if (staticAttributeIdIsDn) { String dn = pseudoNormalizeDn(targetKeyAttr); if (forceDnConsistencyCheck) { String id = getIdForDn(targetSession, dn); if (id != null && targetSession.hasEntry(id)) { // this is an entry managed by the current // reference attrToRemove.add(dn); } } else if (dn.endsWith(targetBaseDn)) { // this is an entry managed by the current // reference attrToRemove.add(dn); } } else { attrToRemove.add(targetKeyAttr); } } } finally { oldAttrs.close(); } try { if (attrToRemove.size() == oldAttr.size()) { // use the empty ref marker to avoid empty attr String emptyRefMarker = ldapSourceDirectory.getDescriptor().getEmptyRefMarker(); Attributes emptyAttribute = new BasicAttributes(attributeId, emptyRefMarker); if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.removeLinksForSource(%s): LDAP modifyAttributes key='%s' " + " mod_op='REPLACE_ATTRIBUTE' attrs='%s' [%s]", sourceId, sourceDn, emptyAttribute, this)); } sourceSession.dirContext.modifyAttributes(sourceDn, DirContext.REPLACE_ATTRIBUTE, emptyAttribute); } else if (attrToRemove.size() > 0) { // remove the attribute managed by the current reference Attributes attrsToRemove = new BasicAttributes(); attrsToRemove.put(attrToRemove); if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.removeLinksForSource(%s): LDAP modifyAttributes dn='%s' " + " mod_op='REMOVE_ATTRIBUTE' attrs='%s' [%s]", sourceId, sourceDn, attrsToRemove, this)); } sourceSession.dirContext.modifyAttributes(sourceDn, DirContext.REMOVE_ATTRIBUTE, attrsToRemove); } } catch (SchemaViolationException e) { if (isDynamic()) { // we are editing an entry that has no static part log.warn(String.format("cannot remove dynamic reference in field %s for source %s", getFieldName(), sourceId)); } else { // this is a real schma configuration problem, wrapup the // exception throw new DirectoryException(e); } } } catch (NamingException e) { throw new DirectoryException("removeLinksForSource failed: " + e.getMessage(), e); } }