List of usage examples for javax.naming.directory SearchControls getSearchScope
public int getSearchScope()
From source file:org.apache.directory.studio.connection.core.io.api.DirectoryApiConnectionWrapper.java
/** * Converts the search scope./*from www. java 2 s . c om*/ * * @param searchControls * the search controls * @return * the associated search scope */ private SearchScope convertSearchScope(SearchControls searchControls) { int scope = searchControls.getSearchScope(); if (scope == SearchControls.OBJECT_SCOPE) { return SearchScope.OBJECT; } else if (scope == SearchControls.ONELEVEL_SCOPE) { return SearchScope.ONELEVEL; } else if (scope == SearchControls.SUBTREE_SCOPE) { return SearchScope.SUBTREE; } else { return SearchScope.SUBTREE; } }
From source file:org.apache.directory.studio.connection.core.io.jndi.LdifSearchLogger.java
/** * {@inheritDoc}// w w w .jav a 2s . c o m */ public void logSearchRequest(Connection connection, String searchBase, String filter, SearchControls searchControls, AliasDereferencingMethod aliasesDereferencingMethod, Control[] controls, long requestNum, NamingException ex) { if (!isSearchRequestLogEnabled()) { return; } String scopeAsString = searchControls.getSearchScope() == SearchControls.SUBTREE_SCOPE ? "wholeSubtree (2)" //$NON-NLS-1$ : searchControls.getSearchScope() == SearchControls.ONELEVEL_SCOPE ? "singleLevel (1)" //$NON-NLS-1$ : "baseObject (0)"; //$NON-NLS-1$ String attributesAsString = searchControls.getReturningAttributes() == null ? "*" //$NON-NLS-1$ : searchControls.getReturningAttributes().length == 0 ? "1.1" //$NON-NLS-1$ : StringUtils.join(searchControls.getReturningAttributes(), " "); String aliasAsString = aliasesDereferencingMethod == AliasDereferencingMethod.ALWAYS ? "derefAlways (3)" //$NON-NLS-1$ : aliasesDereferencingMethod == AliasDereferencingMethod.FINDING ? "derefFindingBaseObj (2)" //$NON-NLS-1$ : aliasesDereferencingMethod == AliasDereferencingMethod.SEARCH ? "derefInSearching (1)" //$NON-NLS-1$ : "neverDerefAliases (0)"; //$NON-NLS-1$ // build LDAP URL LdapUrl url = Utils.getLdapURL(connection, searchBase, searchControls.getSearchScope(), filter, searchControls.getReturningAttributes()); // build command line String cmdLine = Utils.getLdapSearchCommandLine(connection, searchBase, searchControls.getSearchScope(), aliasesDereferencingMethod, searchControls.getCountLimit(), searchControls.getTimeLimit(), filter, searchControls.getReturningAttributes()); // build Collection<LdifLineBase> lines = new ArrayList<LdifLineBase>(); lines.add(LdifCommentLine.create("# LDAP URL : " + url.toString())); //$NON-NLS-1$ lines.add(LdifCommentLine.create("# command line : " + cmdLine.toString())); //$NON-NLS-1$ lines.add(LdifCommentLine.create("# baseObject : " + searchBase)); //$NON-NLS-1$ lines.add(LdifCommentLine.create("# scope : " + scopeAsString)); //$NON-NLS-1$ lines.add(LdifCommentLine.create("# derefAliases : " + aliasAsString)); //$NON-NLS-1$ lines.add(LdifCommentLine.create("# sizeLimit : " + searchControls.getCountLimit())); //$NON-NLS-1$ lines.add(LdifCommentLine.create("# timeLimit : " + searchControls.getTimeLimit())); //$NON-NLS-1$ lines.add(LdifCommentLine.create("# typesOnly : " + "False")); //$NON-NLS-1$ //$NON-NLS-2$ lines.add(LdifCommentLine.create("# filter : " + filter)); //$NON-NLS-1$ lines.add(LdifCommentLine.create("# attributes : " + attributesAsString)); //$NON-NLS-1$ if (controls != null) { for (Control control : controls) { lines.add(LdifCommentLine.create("# control : " + control.getID())); //$NON-NLS-1$ } } lines.add(LdifSepLine.create()); String formattedString = ""; //$NON-NLS-1$ for (LdifLineBase line : lines) { formattedString += line.toFormattedString(LdifFormatParameters.DEFAULT); } log(formattedString, "SEARCH REQUEST (" + requestNum + ")", ex, connection); //$NON-NLS-1$ //$NON-NLS-2$ }
From source file:org.cloudfoundry.identity.uaa.ldap.extension.SpringSecurityLdapTemplate.java
/** * We need to make sure the search controls has the return object flag set to true, in order for * the search to return DirContextAdapter instances. * @param originalControls//from w w w .j a v a 2s. c o m * @return */ private static SearchControls buildControls(SearchControls originalControls) { return new SearchControls(originalControls.getSearchScope(), originalControls.getCountLimit(), originalControls.getTimeLimit(), originalControls.getReturningAttributes(), RETURN_OBJECT, originalControls.getDerefLinkFlag()); }
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) */// w ww.j av a 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
/** * 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 w ww. j a v a 2s . com*/ * @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 target id (dynamic references remain unaltered) * * @see org.nuxeo.ecm.directory.Reference#removeLinksForTarget(String) *//*from w ww. j a va 2 s .c om*/ @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); } }
From source file:org.nuxeo.ecm.directory.ldap.LDAPSession.java
protected SearchResult getLdapEntry(String id, boolean fetchAllAttributes) throws NamingException { if (StringUtils.isEmpty(id)) { log.warn(/*from ww w . j ava 2 s .c o m*/ "The application should not " + "query for entries with an empty id " + "=> return no results"); return null; } String filterExpr; String baseFilter = getDirectory().getBaseFilter(); if (baseFilter.startsWith("(")) { filterExpr = String.format("(&(%s={0})%s)", idAttribute, baseFilter); } else { filterExpr = String.format("(&(%s={0})(%s))", idAttribute, baseFilter); } String[] filterArgs = { id }; SearchControls scts = getDirectory().getSearchControls(fetchAllAttributes); if (log.isDebugEnabled()) { log.debug(String.format( "LDAPSession.getLdapEntry(%s, %s): LDAP search base='%s' filter='%s' " + " args='%s' scope='%s' [%s]", id, fetchAllAttributes, searchBaseDn, filterExpr, id, scts.getSearchScope(), this)); } NamingEnumeration<SearchResult> results; try { results = dirContext.search(searchBaseDn, filterExpr, filterArgs, scts); } catch (NameNotFoundException nnfe) { // sometimes ActiveDirectory have some query fail with: LDAP: // error code 32 - 0000208D: NameErr: DSID-031522C9, problem // 2001 (NO_OBJECT). // To keep the application usable return no results instead of // crashing but log the error so that the AD admin // can fix the issue. log.error("Unexpected response from server while performing query: " + nnfe.getMessage(), nnfe); return null; } if (!results.hasMore()) { log.debug("Entry not found: " + id); return null; } SearchResult result = results.next(); try { String dn = result.getNameInNamespace(); if (results.hasMore()) { result = results.next(); String dn2 = result.getNameInNamespace(); String msg = String.format("Unable to fetch entry for '%s': found more than one match," + " for instance: '%s' and '%s'", id, dn, dn2); log.error(msg); // ignore entries that are ambiguous while giving enough info // in the logs to let the LDAP admin be able to fix the issue return null; } if (log.isDebugEnabled()) { log.debug(String.format( "LDAPSession.getLdapEntry(%s, %s): LDAP search base='%s' filter='%s' " + " args='%s' scope='%s' => found: %s [%s]", id, fetchAllAttributes, searchBaseDn, filterExpr, id, scts.getSearchScope(), dn, this)); } } catch (UnsupportedOperationException e) { // ignore unsupported operation thrown by the Apache DS server in // the tests in embedded mode } return result; }
From source file:org.nuxeo.ecm.directory.ldap.LDAPSession.java
@Override public DocumentModelList getEntries() throws DirectoryException { if (!hasPermission(SecurityConstants.READ)) { return new DocumentModelListImpl(); }//from www. java2s .co m try { SearchControls scts = getDirectory().getSearchControls(true); if (log.isDebugEnabled()) { log.debug(String.format( "LDAPSession.getEntries(): LDAP search base='%s' filter='%s' " + " args=* scope=%s [%s]", searchBaseDn, getDirectory().getBaseFilter(), scts.getSearchScope(), this)); } NamingEnumeration<SearchResult> results = dirContext.search(searchBaseDn, getDirectory().getBaseFilter(), scts); // skip reference fetching return ldapResultsToDocumentModels(results, false); } catch (SizeLimitExceededException e) { throw new org.nuxeo.ecm.directory.SizeLimitExceededException(e); } catch (NamingException e) { throw new DirectoryException("getEntries failed", e); } }
From source file:org.nuxeo.ecm.directory.ldap.LDAPSession.java
public DocumentModelList query(Map<String, Serializable> filter, Set<String> fulltext, boolean fetchReferences, Map<String, String> orderBy) throws DirectoryException { if (!hasPermission(SecurityConstants.READ)) { return new DocumentModelListImpl(); }/*w w w .j a v a 2 s. c om*/ try { // building the query using filterExpr / filterArgs to // escape special characters and to fulltext search only on // the explicitly specified fields String[] filters = new String[filter.size()]; String[] filterArgs = new String[filter.size()]; if (fulltext == null) { fulltext = Collections.emptySet(); } int index = 0; for (String fieldName : filter.keySet()) { if (getDirectory().isReference(fieldName)) { log.warn(fieldName + " is a reference and will be ignored as a query criterion"); continue; } String backendFieldName = getDirectory().getFieldMapper().getBackendField(fieldName); Object fieldValue = filter.get(fieldName); StringBuilder currentFilter = new StringBuilder(); currentFilter.append("("); if (fieldValue == null) { currentFilter.append("!(" + backendFieldName + "=*)"); } else if ("".equals(fieldValue)) { if (fulltext.contains(fieldName)) { currentFilter.append(backendFieldName + "=*"); } else { currentFilter.append("!(" + backendFieldName + "=*)"); } } else { currentFilter.append(backendFieldName + "="); if (fulltext.contains(fieldName)) { switch (substringMatchType) { case subinitial: currentFilter.append("{" + index + "}*"); break; case subfinal: currentFilter.append("*{" + index + "}"); break; case subany: currentFilter.append("*{" + index + "}*"); break; } } else { currentFilter.append("{" + index + "}"); } } currentFilter.append(")"); filters[index] = currentFilter.toString(); if (fieldValue != null && !"".equals(fieldValue)) { if (fieldValue instanceof Blob) { // filter arg could be a sequence of \xx where xx is the // hexadecimal value of the byte log.warn("Binary search is not supported"); } else { // XXX: what kind of Objects can we get here? Is // toString() enough? filterArgs[index] = fieldValue.toString(); } } index++; } String filterExpr = "(&" + getDirectory().getBaseFilter() + StringUtils.join(filters) + ')'; SearchControls scts = getDirectory().getSearchControls(true); if (log.isDebugEnabled()) { log.debug(String.format( "LDAPSession.query(...): LDAP search base='%s' filter='%s' args='%s' scope='%s' [%s]", searchBaseDn, filterExpr, StringUtils.join(filterArgs, ","), scts.getSearchScope(), this)); } try { NamingEnumeration<SearchResult> results = dirContext.search(searchBaseDn, filterExpr, filterArgs, scts); DocumentModelList entries = ldapResultsToDocumentModels(results, fetchReferences); if (orderBy != null && !orderBy.isEmpty()) { getDirectory().orderEntries(entries, orderBy); } return entries; } catch (NameNotFoundException nnfe) { // sometimes ActiveDirectory have some query fail with: LDAP: // error code 32 - 0000208D: NameErr: DSID-031522C9, problem // 2001 (NO_OBJECT). // To keep the application usable return no results instead of // crashing but log the error so that the AD admin // can fix the issue. log.error("Unexpected response from server while performing query: " + nnfe.getMessage(), nnfe); return new DocumentModelListImpl(); } } catch (LimitExceededException e) { throw new org.nuxeo.ecm.directory.SizeLimitExceededException(e); } catch (NamingException e) { throw new DirectoryException("executeQuery failed", e); } }
From source file:org.nuxeo.ecm.directory.ldap.LDAPTreeReference.java
/** * Fetches single parent, cutting the dn and trying to get the given entry. * * @see org.nuxeo.ecm.directory.Reference#getSourceIdsForTarget(String) *///from w w w . ja v a 2s .co m @Override public List<String> getSourceIdsForTarget(String targetId) throws DirectoryException { Set<String> sourceIds = new TreeSet<>(); String targetDn = null; // step #1: fetch the dn of the targetId entry in the target // directory by the static dn valued strategy LDAPDirectory targetDir = getTargetLDAPDirectory(); try (LDAPSession targetSession = (LDAPSession) targetDir.getSession()) { SearchResult targetLdapEntry = targetSession.getLdapEntry(targetId, true); if (targetLdapEntry == null) { // no parent accessible => return empty list return EMPTY_STRING_LIST; } targetDn = pseudoNormalizeDn(targetLdapEntry.getNameInNamespace()); } catch (NamingException e) { throw new DirectoryException("error fetching " + targetId, e); } // step #2: search for entries that reference parent dn in the // source directory and collect its id LDAPDirectory ldapSourceDirectory = getSourceLDAPDirectory(); String parentDn = getParentDn(targetDn); String filterExpr = String.format("(&%s)", ldapSourceDirectory.getBaseFilter()); String[] filterArgs = {}; // get a copy of original search controls SearchControls sctls = ldapSourceDirectory.getSearchControls(true); sctls.setSearchScope(SearchControls.OBJECT_SCOPE); 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, parentDn, filterExpr, StringUtils.join(filterArgs, ", "), sctls.getSearchScope(), this)); } NamingEnumeration<SearchResult> results = sourceSession.dirContext.search(parentDn, 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()); // only supposed to get one result anyway break; } } } } finally { results.close(); } } catch (NamingException e) { throw new DirectoryException("error during reference search for " + targetDn, e); } return new ArrayList<>(sourceIds); }