List of usage examples for javax.naming NamingEnumeration close
public void close() throws NamingException;
From source file:org.eclipse.skalli.core.user.ldap.LDAPClient.java
private void closeQuietly(NamingEnumeration<?> result) { if (result != null) { try {/*from w w w . jav a 2s .c o m*/ result.close(); } catch (NamingException e) { LOG.error("Failed to close LDAP result set", e); } } }
From source file:org.geoserver.security.ldap.LDAPTestUtils.java
/** * Clear the directory sub-tree starting with the node represented by the * supplied distinguished name./* w ww . jav a 2s .c o m*/ * * @param ctx The DirContext to use for cleaning the tree. * @param name the distinguished name of the root node. * @throws NamingException if anything goes wrong removing the sub-tree. */ public static void clearSubContexts(DirContext ctx, Name name) throws NamingException { NamingEnumeration enumeration = null; try { enumeration = ctx.listBindings(name); while (enumeration.hasMore()) { Binding element = (Binding) enumeration.next(); DistinguishedName childName = new DistinguishedName(element.getName()); childName.prepend((DistinguishedName) name); try { ctx.destroySubcontext(childName); } catch (ContextNotEmptyException e) { clearSubContexts(ctx, childName); ctx.destroySubcontext(childName); } } } catch (NamingException e) { e.printStackTrace(); } finally { try { enumeration.close(); } catch (Exception e) { // Never mind this } } }
From source file:org.hyperic.hq.plugin.openldap.OpenLDAPMeasurementPlugin.java
private MetricValue getMetric(Metric metric, String tree, String attr) throws MetricNotFoundException, NamingException { NamingEnumeration enumer = null; try {/*from w ww .j a v a 2s .com*/ String[] a = { attr }; SearchControls cons = new SearchControls(); cons.setSearchScope(SearchControls.OBJECT_SCOPE); cons.setReturningAttributes(a); enumer = getDirContext(metric.getProperties()).search(tree, "(&(objectClass=*))", cons); while (enumer.hasMore()) { SearchResult searchresult = (SearchResult) enumer.next(); Attributes attrs = searchresult.getAttributes(); Attribute val; if (null != (val = attrs.get(attr))) { return new MetricValue(new Double(val.get().toString()), System.currentTimeMillis()); } } throw new MetricNotFoundException(""); } finally { if (enumer != null) { enumer.close(); } } }
From source file:org.hyperic.hq.plugin.openldap.OpenLDAPMeasurementPlugin.java
/** * @return true = monitoring is enabled * @return false = monitoring is not enabled * @exception NamingException no conection *//*from ww w .java 2s .c om*/ private boolean hasMonitoringEnabled(Metric metric) throws NamingException { NamingEnumeration enumer = null, enumerx = null, enumery = null; boolean res = false; try { String[] a = { "monitorContext" }; SearchControls cons = new SearchControls(); cons.setSearchScope(SearchControls.OBJECT_SCOPE); cons.setReturningAttributes(a); enumer = getDirContext(metric.getProperties()).search("", "(&(objectClass=*))", cons); while (enumer.hasMore() && !res) { SearchResult searchresult = (SearchResult) enumer.next(); Attributes attrs = searchresult.getAttributes(); enumerx = attrs.getIDs(); while (enumerx.hasMore()) { String id = (String) enumerx.next(); Attribute attr = attrs.get(id); res = true; } } } finally { if (enumer != null) { enumer.close(); } if (enumerx != null) { enumerx.close(); } if (enumery != null) { enumery.close(); } } log.debug("[hasMonitoringEnabled] res=" + res + " metric:" + metric); return res; }
From source file:org.jboss.additional.testsuite.jdkall.present.elytron.sasl.OtpSaslTestCase.java
/** * Check correct user attribute values in the LDAP when using OTP algorithm. *///from w ww . j a v a 2 s . c o m private void assertSequenceAndHash(Integer expectedSequence, byte[] expectedHash) throws NamingException { final Properties env = new Properties(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, LDAP_URL); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system"); env.put(Context.SECURITY_CREDENTIALS, "secret"); final LdapContext ctx = new InitialLdapContext(env, null); NamingEnumeration<?> namingEnum = ctx.search("dc=wildfly,dc=org", new BasicAttributes("cn", "jduke")); if (namingEnum.hasMore()) { SearchResult sr = (SearchResult) namingEnum.next(); Attributes attrs = sr.getAttributes(); assertEquals("Unexpected sequence number in LDAP attribute", expectedSequence, new Integer(attrs.get("telephoneNumber").get().toString())); assertEquals("Unexpected hash value in LDAP attribute", Base64.getEncoder().encodeToString(expectedHash), attrs.get("title").get().toString()); } else { fail("User not found in LDAP"); } namingEnum.close(); ctx.close(); }
From source file:org.nuxeo.ecm.directory.ldap.LDAPReference.java
/** * Fetch both statically and dynamically defined references and merge the results. * * @see org.nuxeo.ecm.directory.Reference#getSourceIdsForTarget(String) */// ww w. j a va 2s . c o m @Override public List<String> getSourceIdsForTarget(String targetId) throws DirectoryException { // container to hold merged references Set<String> sourceIds = new TreeSet<>(); SearchResult targetLdapEntry = null; String targetDn = null; // step #1: resolve static references String staticAttributeId = getStaticAttributeId(); if (staticAttributeId != null) { // step #1.1: fetch the dn of the targetId entry in the target // directory by the static dn valued strategy LDAPDirectory targetDir = getTargetLDAPDirectory(); if (staticAttributeIdIsDn) { try (LDAPSession targetSession = (LDAPSession) targetDir.getSession()) { targetLdapEntry = targetSession.getLdapEntry(targetId, false); if (targetLdapEntry == null) { String msg = String.format( "Failed to perform inverse lookup on LDAPReference" + " resolving field '%s' of '%s' to entries of '%s'" + " using the static content of attribute '%s':" + " entry '%s' cannot be found in '%s'", fieldName, sourceDirectory, targetDirectoryName, staticAttributeId, targetId, targetDirectoryName); throw new DirectoryEntryNotFoundException(msg); } targetDn = pseudoNormalizeDn(targetLdapEntry.getNameInNamespace()); } catch (NamingException e) { throw new DirectoryException( "error fetching " + targetId + " from " + targetDirectoryName + ": " + e.getMessage(), e); } } // step #1.2: search for entries that reference that dn in the // source directory and collect their ids LDAPDirectory ldapSourceDirectory = getSourceLDAPDirectory(); String filterExpr = String.format("(&(%s={0})%s)", staticAttributeId, ldapSourceDirectory.getBaseFilter()); String[] filterArgs = new String[1]; if (staticAttributeIdIsDn) { filterArgs[0] = targetDn; } else { filterArgs[0] = targetId; } String searchBaseDn = ldapSourceDirectory.getDescriptor().getSearchBaseDn(); SearchControls sctls = ldapSourceDirectory.getSearchControls(); try (LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession()) { if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.getSourceIdsForTarget(%s): LDAP search search base='%s'" + " filter='%s' args='%s' scope='%s' [%s]", targetId, searchBaseDn, filterExpr, StringUtils.join(filterArgs, ", "), sctls.getSearchScope(), this)); } NamingEnumeration<SearchResult> results = sourceSession.dirContext.search(searchBaseDn, filterExpr, filterArgs, sctls); try { while (results.hasMore()) { Attributes attributes = results.next().getAttributes(); // NXP-2461: check that id field is filled Attribute attr = attributes.get(sourceSession.idAttribute); if (attr != null) { Object value = attr.get(); if (value != null) { sourceIds.add(value.toString()); } } } } finally { results.close(); } } catch (NamingException e) { throw new DirectoryException("error during reference search for " + filterArgs[0], e); } } // step #2: resolve dynamic references String dynamicAttributeId = this.dynamicAttributeId; if (dynamicAttributeId != null) { LDAPDirectory ldapSourceDirectory = getSourceLDAPDirectory(); LDAPDirectory ldapTargetDirectory = getTargetLDAPDirectory(); String searchBaseDn = ldapSourceDirectory.getDescriptor().getSearchBaseDn(); try (LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession(); LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession()) { // step #2.1: fetch the target entry to apply the ldap url // filters of the candidate sources on it if (targetLdapEntry == null) { // only fetch the entry if not already fetched by the // static // attributes references resolution targetLdapEntry = targetSession.getLdapEntry(targetId, false); } if (targetLdapEntry == null) { String msg = String.format( "Failed to perform inverse lookup on LDAPReference" + " resolving field '%s' of '%s' to entries of '%s'" + " using the dynamic content of attribute '%s':" + " entry '%s' cannot be found in '%s'", fieldName, ldapSourceDirectory, targetDirectoryName, dynamicAttributeId, targetId, targetDirectoryName); throw new DirectoryException(msg); } targetDn = pseudoNormalizeDn(targetLdapEntry.getNameInNamespace()); Attributes targetAttributes = targetLdapEntry.getAttributes(); // step #2.2: find the list of entries that hold candidate // dynamic links in the source directory SearchControls sctls = ldapSourceDirectory.getSearchControls(); sctls.setReturningAttributes(new String[] { sourceSession.idAttribute, dynamicAttributeId }); String filterExpr = String.format("%s=*", dynamicAttributeId); if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.getSourceIdsForTarget(%s): LDAP search search base='%s'" + " filter='%s' scope='%s' [%s]", targetId, searchBaseDn, filterExpr, sctls.getSearchScope(), this)); } NamingEnumeration<SearchResult> results = sourceSession.dirContext.search(searchBaseDn, filterExpr, sctls); try { while (results.hasMore()) { // step #2.3: for each sourceId and each ldapUrl test // whether the current target entry matches the // collected // URL Attributes sourceAttributes = results.next().getAttributes(); NamingEnumeration<?> ldapUrls = sourceAttributes.get(dynamicAttributeId).getAll(); try { while (ldapUrls.hasMore()) { LdapURL ldapUrl = new LdapURL(ldapUrls.next().toString()); String candidateDN = pseudoNormalizeDn(ldapUrl.getDN()); // check base URL if (!targetDn.endsWith(candidateDN)) { continue; } // check onelevel scope constraints if ("onelevel".equals(ldapUrl.getScope())) { int targetDnSize = new LdapName(targetDn).size(); int urlDnSize = new LdapName(candidateDN).size(); if (targetDnSize - urlDnSize > 1) { // target is not a direct child of the // DN of the // LDAP URL continue; } } // check that the target entry matches the // filter if (getFilterMatcher().match(targetAttributes, ldapUrl.getFilter())) { // the target match the source url, add it // to the // collected ids sourceIds.add(sourceAttributes.get(sourceSession.idAttribute).get().toString()); } } } finally { ldapUrls.close(); } } } finally { results.close(); } } catch (NamingException e) { throw new DirectoryException("error during reference search for " + targetId, e); } } /* * This kind of reference is not supported because Active Directory use filter expression not yet supported by * LDAPFilterMatcher. See NXP-4562 */ if (dynamicReferences != null && dynamicReferences.length > 0) { log.error("This kind of reference is not supported."); } return new ArrayList<>(sourceIds); }
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.//from w ww . ja v a 2s .c o m * <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:org.nuxeo.ecm.directory.ldap.LDAPReference.java
/** * Retrieve the elements referenced by the filter/BaseDN/Scope request. * * @param attributes Attributes of the referencer element * @param directoryDn Dn of the Directory * @param linkDn Dn specified in the parent * @param filter Filter expression specified in the parent * @param scope scope for the search//from www . j a v a 2s. c o m * @return The list of the referenced elements. * @throws DirectoryException * @throws NamingException */ private Set<String> getReferencedElements(Attributes attributes, String directoryDn, String linkDn, String filter, int scope) throws DirectoryException, NamingException { Set<String> targetIds = new TreeSet<>(); LDAPDirectoryDescriptor targetDirconfig = getTargetDirectoryDescriptor(); LDAPDirectory ldapTargetDirectory = (LDAPDirectory) getTargetDirectory(); LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession(); // use the most specific scope between the one specified in the // Directory and the specified in the Parent String dn = directoryDn.endsWith(linkDn) && directoryDn.length() > linkDn.length() ? directoryDn : linkDn; // combine the ldapUrl search query with target // directory own constraints SearchControls scts = new SearchControls(); // use the most specific scope scts.setSearchScope(Math.min(scope, targetDirconfig.getSearchScope())); // only fetch the ids of the targets scts.setReturningAttributes(new String[] { targetSession.idAttribute }); // combine the filter of the target directory with the // provided filter if any String targetFilter = targetDirconfig.getSearchFilter(); if (filter == null || filter.length() == 0) { filter = targetFilter; } else if (targetFilter != null && targetFilter.length() > 0) { filter = String.format("(&(%s)(%s))", targetFilter, filter); } // perform the request and collect the ids if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.getLdapTargetIds(%s): LDAP search dn='%s' " + " filter='%s' scope='%s' [%s]", attributes, dn, dn, scts.getSearchScope(), this)); } Name name = new CompositeName().add(dn); NamingEnumeration<SearchResult> results = targetSession.dirContext.search(name, filter, scts); try { while (results.hasMore()) { // NXP-2461: check that id field is filled Attribute attr = results.next().getAttributes().get(targetSession.idAttribute); if (attr != null) { String collectedId = attr.get().toString(); if (collectedId != null) { targetIds.add(collectedId); } } } } finally { results.close(); } return targetIds; }
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) *//*from w w w. j a v 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); } }
From source file:org.nuxeo.ecm.directory.ldap.LDAPReference.java
/** * Remove existing statically defined links for the given target id (dynamic references remain unaltered) * * @see org.nuxeo.ecm.directory.Reference#removeLinksForTarget(String) */// w w w. j av a 2 s .c o m @Override public void removeLinksForTarget(String targetId) throws DirectoryException { if (!isStatic()) { // nothing to do: dynamic references cannot be updated return; } LDAPDirectory ldapTargetDirectory = (LDAPDirectory) getTargetDirectory(); LDAPDirectory ldapSourceDirectory = (LDAPDirectory) getSourceDirectory(); String attributeId = getStaticAttributeId(); try (LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession(); LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession()) { if (!sourceSession.isReadOnly()) { // get the dn of the target that matches targetId String targetAttributeValue; if (staticAttributeIdIsDn) { SearchResult targetLdapEntry = targetSession.getLdapEntry(targetId); if (targetLdapEntry == null) { String rdnAttribute = ldapTargetDirectory.getDescriptor().getRdnAttribute(); if (!rdnAttribute.equals(targetSession.idAttribute)) { log.warn(String.format( "cannot remove links to missing entry %s in directory %s for reference %s", targetId, ldapTargetDirectory.getName(), this)); return; } // the entry might have already been deleted, try to // re-forge it if possible (might not work if scope is // subtree) targetAttributeValue = String.format("%s=%s,%s", rdnAttribute, targetId, ldapTargetDirectory.getDescriptor().getSearchBaseDn()); } else { targetAttributeValue = pseudoNormalizeDn(targetLdapEntry.getNameInNamespace()); } } else { targetAttributeValue = targetId; } // build a LDAP query to find entries that point to the target String searchFilter = String.format("(%s=%s)", attributeId, targetAttributeValue); String sourceFilter = ldapSourceDirectory.getBaseFilter(); if (sourceFilter != null && !"".equals(sourceFilter)) { searchFilter = String.format("(&(%s)(%s))", searchFilter, sourceFilter); } SearchControls scts = new SearchControls(); scts.setSearchScope(ldapSourceDirectory.getDescriptor().getSearchScope()); scts.setReturningAttributes(new String[] { attributeId }); // find all source entries that point to the target key and // clean // those references if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.removeLinksForTarget(%s): LDAP search baseDn='%s' " + " filter='%s' scope='%s' [%s]", targetId, sourceSession.searchBaseDn, searchFilter, scts.getSearchScope(), this)); } NamingEnumeration<SearchResult> results = sourceSession.dirContext .search(sourceSession.searchBaseDn, searchFilter, scts); String emptyRefMarker = ldapSourceDirectory.getDescriptor().getEmptyRefMarker(); Attributes emptyAttribute = new BasicAttributes(attributeId, emptyRefMarker); try { while (results.hasMore()) { SearchResult result = results.next(); Attributes attrs = result.getAttributes(); Attribute attr = attrs.get(attributeId); try { if (attr.size() == 1) { // the attribute holds the last reference, put // the // empty ref. marker before removing the // attribute // since empty attribute are often not allowed // by // the server schema if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.removeLinksForTarget(%s): LDAP modifyAttributes key='%s' " + "mod_op='ADD_ATTRIBUTE' attrs='%s' [%s]", targetId, result.getNameInNamespace(), attrs, this)); } sourceSession.dirContext.modifyAttributes(result.getNameInNamespace(), DirContext.ADD_ATTRIBUTE, emptyAttribute); } // remove the reference to the target key attrs = new BasicAttributes(); attr = new BasicAttribute(attributeId); attr.add(targetAttributeValue); attrs.put(attr); if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.removeLinksForTarget(%s): LDAP modifyAttributes key='%s' " + "mod_op='REMOVE_ATTRIBUTE' attrs='%s' [%s]", targetId, result.getNameInNamespace(), attrs, this)); } sourceSession.dirContext.modifyAttributes(result.getNameInNamespace(), DirContext.REMOVE_ATTRIBUTE, attrs); } catch (SchemaViolationException e) { if (isDynamic()) { // we are editing an entry that has no static // part log.warn(String.format("cannot remove dynamic reference in field %s for target %s", getFieldName(), targetId)); } else { // this is a real schema configuration problem, // wrapup the exception throw new DirectoryException(e); } } } } finally { results.close(); } } } catch (NamingException e) { throw new DirectoryException("removeLinksForTarget failed: " + e.getMessage(), e); } }