List of usage examples for javax.naming.directory SearchControls setSearchScope
public void setSearchScope(int scope)
From source file:org.nuxeo.ecm.directory.ldap.LDAPDirectoryTestCase.java
protected void destroyRecursively(String dn, DirContext ctx, int limit) throws NamingException { if (limit == 0) { log.warn("Reach recursion limit, stopping deletion at" + dn); return;/* w w w .j a v a2s .c o m*/ } SearchControls scts = new SearchControls(); scts.setSearchScope(SearchControls.ONELEVEL_SCOPE); String providerUrl = (String) ctx.getEnvironment().get(Context.PROVIDER_URL); NamingEnumeration<SearchResult> children = ctx.search(dn, "(objectClass=*)", scts); try { while (children.hasMore()) { SearchResult child = children.next(); String subDn = child.getName(); if (!USE_EXTERNAL_TEST_LDAP_SERVER && subDn.endsWith(providerUrl)) { subDn = subDn.substring(0, subDn.length() - providerUrl.length() - 1); } else { subDn = subDn + ',' + dn; } destroyRecursively(subDn, ctx, limit); } } catch (SizeLimitExceededException e) { log.warn("SizeLimitExceededException: trying again on partial results " + dn); if (limit == -1) { limit = 100; } destroyRecursively(dn, ctx, limit - 1); } ctx.destroySubcontext(dn); }
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 w w . j a va 2 s. co 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 target id (dynamic references remain unaltered) * * @see org.nuxeo.ecm.directory.Reference#removeLinksForTarget(String) *//* w w w. j av a2 s . co 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); } }
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) */// w w w .j a va2s . c o 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); }
From source file:org.nuxeo.ecm.directory.ldap.LDAPTreeReference.java
/** * Fetches children, onelevel or subtree given the reference configuration. * <p>/*from ww w .ja v a 2 s . co m*/ * Removes entries with same id than parent to only get real children. * * @see org.nuxeo.ecm.directory.Reference#getTargetIdsForSource(String) */ // TODO: optimize reusing the same ldap session (see LdapReference optim // method) @Override public List<String> getTargetIdsForSource(String sourceId) throws DirectoryException { Set<String> targetIds = new TreeSet<>(); String sourceDn = null; // step #1: fetch the dn of the sourceId entry in the source // directory by the static dn valued strategy LDAPDirectory sourceDir = getSourceLDAPDirectory(); try (LDAPSession sourceSession = (LDAPSession) sourceDir.getSession()) { SearchResult sourceLdapEntry = sourceSession.getLdapEntry(sourceId, true); if (sourceLdapEntry == null) { throw new DirectoryException(sourceId + " does not exist in " + sourceDirectoryName); } sourceDn = pseudoNormalizeDn(sourceLdapEntry.getNameInNamespace()); } catch (NamingException e) { throw new DirectoryException("error fetching " + sourceId, e); } // step #2: search for entries with sourceDn as base dn and collect // their ids LDAPDirectory ldapTargetDirectory = getTargetLDAPDirectory(); String filterExpr = String.format("(&%s)", ldapTargetDirectory.getBaseFilter()); String[] filterArgs = {}; // get a copy of original search controls SearchControls sctls = ldapTargetDirectory.getSearchControls(true); sctls.setSearchScope(getScope()); try (LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession()) { if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.getTargetIdsForSource(%s): LDAP search search base='%s'" + " filter='%s' args='%s' scope='%s' [%s]", sourceId, sourceDn, filterExpr, StringUtils.join(filterArgs, ", "), sctls.getSearchScope(), this)); } NamingEnumeration<SearchResult> results = targetSession.dirContext.search(sourceDn, filterExpr, filterArgs, sctls); try { while (results.hasMore()) { Attributes attributes = results.next().getAttributes(); // NXP-2461: check that id field is filled Attribute attr = attributes.get(targetSession.idAttribute); if (attr != null) { Object value = attr.get(); if (value != null) { // always remove self as child String targetId = value.toString(); if (!sourceId.equals(targetId)) { targetIds.add(targetId); } } } } } finally { results.close(); } } catch (NamingException e) { throw new DirectoryException("error during reference search for " + sourceDn, e); } return new ArrayList<>(targetIds); }
From source file:org.nuxeo.wizard.RouterServlet.java
public void handleUserPOST(Page currentPage, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Context ctx = Context.instance(req); ParamCollector collector = ctx.getCollector(); String refreshParam = req.getParameter("refresh"); String directoryType = collector.getConfigurationParam("nuxeo.directory.type"); if ("true".equals(refreshParam)) { currentPage.dispatchToJSP(req, resp); return;//from w ww.j a v a 2 s. c o m } if ("checkNetwork".equals(refreshParam) || "checkAuth".equals(refreshParam) || "checkUserLdapParam".equals(refreshParam) || "checkGroupLdapParam".equals(refreshParam)) { try { if ("checkNetwork".equals(refreshParam)) { bindLdapConnection(collector, false); ctx.trackInfo("nuxeo.ldap.url", "info.host.found"); } else if ("checkAuth".equals(refreshParam)) { bindLdapConnection(collector, true); ctx.trackInfo("nuxeo.ldap.auth", "info.auth.success"); } else { DirContext dirContext = new InitialDirContext(getContextEnv(collector, true)); String searchScope; String searchBaseDn; String searchClass; String searchFilter; if ("checkUserLdapParam".equals(refreshParam)) { searchBaseDn = collector.getConfigurationParam("nuxeo.ldap.user.searchBaseDn"); searchScope = collector.getConfigurationParam("nuxeo.ldap.user.searchScope"); searchClass = collector.getConfigurationParam("nuxeo.ldap.user.searchClass"); searchFilter = collector.getConfigurationParam("nuxeo.ldap.user.searchFilter"); } else { searchBaseDn = collector.getConfigurationParam("nuxeo.ldap.group.searchBaseDn"); searchScope = collector.getConfigurationParam("nuxeo.ldap.group.searchScope"); searchFilter = collector.getConfigurationParam("nuxeo.ldap.group.searchFilter"); searchClass = ""; } SearchControls scts = new SearchControls(); if ("onelevel".equals(searchScope)) { scts.setSearchScope(SearchControls.ONELEVEL_SCOPE); } else { scts.setSearchScope(SearchControls.SUBTREE_SCOPE); } String filter = String.format("(&(%s)(objectClass=%s))", searchFilter.isEmpty() ? "objectClass=*" : searchFilter, searchClass.isEmpty() ? "*" : searchClass); NamingEnumeration<SearchResult> results; try { results = dirContext.search(searchBaseDn, filter, scts); if (!results.hasMore()) { ctx.trackError("nuxeo.ldap.search", "error.ldap.noresult"); } else { SearchResult result = results.next(); if (searchBaseDn.equalsIgnoreCase(result.getNameInNamespace()) && results.hasMore()) { // try not to display the root of the search // base DN result = results.next(); } ctx.trackInfo("dn", result.getNameInNamespace()); Attributes attributes = result.getAttributes(); NamingEnumeration<String> ids = attributes.getIDs(); String id; StringBuilder sb; while (ids.hasMore()) { id = ids.next(); NamingEnumeration<?> values = attributes.get(id).getAll(); sb = new StringBuilder(); while (values.hasMore()) { sb.append(values.next()).append(" , "); } ctx.trackInfo(id, sb.substring(0, sb.length() - 3)); } } } catch (NameNotFoundException e) { ctx.trackError("nuxeo.ldap.search", "error.ldap.searchBaseDn"); log.warn(e); } dirContext.close(); } } catch (AuthenticationException e) { ctx.trackError("nuxeo.ldap.auth", "error.auth.failed"); log.warn(e); } catch (NamingException e) { ctx.trackError("nuxeo.ldap.url", "error.host.not.found"); log.warn(e); } } // Form submit if (!"default".equals(directoryType) && refreshParam.isEmpty()) { // first check bind to LDAP server try { bindLdapConnection(collector, true); } catch (NamingException e) { ctx.trackError("nuxeo.ldap.auth", "error.ldap.bind.failed"); log.warn(e); } // then check mandatory fields if (collector.getConfigurationParam("nuxeo.ldap.user.searchBaseDn").isEmpty()) { ctx.trackError("nuxeo.ldap.user.searchBaseDn", "error.user.searchBaseDn.required"); } if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.rdn").isEmpty()) { ctx.trackError("nuxeo.ldap.user.mapping.rdn", "error.user.rdn.required"); } if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.username").isEmpty()) { ctx.trackError("nuxeo.ldap.user.mapping.username", "error.user.username.required"); } if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.password").isEmpty()) { ctx.trackError("nuxeo.ldap.user.mapping.password", "error.user.password.required"); } if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.firstname").isEmpty()) { ctx.trackError("nuxeo.ldap.user.mapping.firstname", "error.user.firstname.required"); } if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.lastname").isEmpty()) { ctx.trackError("nuxeo.ldap.user.mapping.lastname", "error.user.lastname.required"); } String userGroupStorage = collector.getConfigurationParam("nuxeo.user.group.storage"); if (!"userLdapOnly".equals(userGroupStorage) && !"multiUserSqlGroup".equals(userGroupStorage)) { if (collector.getConfigurationParam("nuxeo.ldap.group.searchBaseDn").isEmpty()) { ctx.trackError("nuxeo.ldap.group.searchBaseDn", "error.group.searchBaseDn.required"); } if (collector.getConfigurationParam("nuxeo.ldap.group.mapping.rdn").isEmpty()) { ctx.trackError("nuxeo.ldap.group.mapping.rdn", "error.group.rdn.required"); } if (collector.getConfigurationParam("nuxeo.ldap.group.mapping.name").isEmpty()) { ctx.trackError("nuxeo.ldap.group.mapping.name", "error.group.name.required"); } } if ("true".equals(collector.getConfigurationParam("nuxeo.user.emergency.enable"))) { if (collector.getConfigurationParam("nuxeo.user.emergency.username").isEmpty()) { ctx.trackError("nuxeo.user.emergency.username", "error.emergency.username.required"); } if (collector.getConfigurationParam("nuxeo.user.emergency.password").isEmpty()) { ctx.trackError("nuxeo.user.emergency.password", "error.emergency.password.required"); } } } if (ctx.hasErrors() || ctx.hasInfos()) { currentPage.dispatchToJSP(req, resp); } else { currentPage.next().dispatchToJSP(req, resp, true); } }
From source file:org.olat.ldap.LDAPLoginManagerImpl.java
/** * Find the user dn with its uid//from w w w. j av a2s . c o m * * @param uid * @param ctx * @return user's dn */ private String searchUserDN(final String uid, final DirContext ctx) { if (ctx == null) { return null; } final List<String> ldapBases = LDAPLoginModule.getLdapBases(); final String objctClass = LDAPLoginModule.getLdapUserObjectClass(); final String[] serachAttr = { "dn" }; final String ldapUserIDAttribute = LDAPLoginModule .mapOlatPropertyToLdapAttribute(LDAPConstants.LDAP_USER_IDENTIFYER); final String filter = "(&(objectClass=" + objctClass + ")(" + ldapUserIDAttribute + "=" + uid + "))"; final SearchControls ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); ctls.setReturningAttributes(serachAttr); String userDN = null; for (final String ldapBase : ldapBases) { try { final NamingEnumeration<SearchResult> enm = ctx.search(ldapBase, filter, ctls); while (enm.hasMore()) { final SearchResult result = enm.next(); userDN = result.getNameInNamespace(); } if (userDN != null) { break; } } catch (final NamingException e) { logError("NamingException when trying to bind user with username::" + uid + " on ldapBase::" + ldapBase, e); } } return userDN; }
From source file:org.olat.ldap.LDAPLoginManagerImpl.java
private void searchInLdap(final LdapVisitor visitor, final String filter, final String[] returningAttrs, final LdapContext ctx) { final SearchControls ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); ctls.setReturningAttributes(returningAttrs); ctls.setCountLimit(0); // set no limits final boolean paging = isPagedResultControlSupported(ctx); for (final String ldapBase : LDAPLoginModule.getLdapBases()) { int counter = 0; try {//from w w w . ja va 2 s .c o m if (paging) { byte[] cookie = null; ctx.setRequestControls( new Control[] { new PagedResultsControl(PAGE_SIZE, Control.NONCRITICAL) }); do { final NamingEnumeration<SearchResult> enm = ctx.search(ldapBase, filter, ctls); while (enm.hasMore()) { visitor.visit(enm.next()); } cookie = getCookie(ctx); } while (cookie != null); } else { final NamingEnumeration<SearchResult> enm = ctx.search(ldapBase, filter, ctls); while (enm.hasMore()) { visitor.visit(enm.next()); } counter++; } } catch (final SizeLimitExceededException e) { logError("SizeLimitExceededException after " + counter + " records when getting all users from LDAP, reconfigure your LDAP server, hints: http://www.ldapbrowser.com/forum/viewtopic.php?t=14", null); } catch (final NamingException e) { logError("NamingException when trying to fetch deleted users from LDAP using ldapBase::" + ldapBase + " on row::" + counter, e); } catch (final Exception e) { logError("Exception when trying to fetch deleted users from LDAP using ldapBase::" + ldapBase + " on row::" + counter, e); } } }
From source file:org.olat.ldap.LDAPLoginManagerImpl.java
private boolean isPagedResultControlSupported(final LdapContext ctx) { try {/*www. j a va 2 s.c o m*/ final SearchControls ctl = new SearchControls(); ctl.setReturningAttributes(new String[] { "supportedControl" }); ctl.setSearchScope(SearchControls.OBJECT_SCOPE); /* search for the rootDSE object */ final NamingEnumeration<SearchResult> results = ctx.search("", "(objectClass=*)", ctl); while (results.hasMore()) { final SearchResult entry = results.next(); final NamingEnumeration<? extends Attribute> attrs = entry.getAttributes().getAll(); while (attrs.hasMore()) { final Attribute attr = attrs.next(); final NamingEnumeration<?> vals = attr.getAll(); while (vals.hasMore()) { final String value = (String) vals.next(); if (value.equals(PAGED_RESULT_CONTROL_OID)) { return true; } } } } return false; } catch (final Exception e) { logError("Exception when trying to know if the server support paged results.", e); return false; } }
From source file:org.openiam.spml2.spi.example.ShellConnectorImpl.java
private NamingEnumeration search(ManagedSystemObjectMatch matchObj, LdapContext ctx, String searchValue, String[] attrAry) throws NamingException { SearchControls searchCtls = new SearchControls(); searchCtls.setReturningAttributes(attrAry); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); String searchFilter = matchObj.getSearchFilter(); // replace the place holder in the search filter searchFilter = searchFilter.replace("?", searchValue); System.out.println("Search Filter=" + searchFilter); System.out.println("BaseDN=" + matchObj.getBaseDn()); return ctx.search(matchObj.getSearchBaseDn(), searchFilter, searchCtls); }