List of usage examples for javax.naming NamingEnumeration next
public T next() throws NamingException;
From source file:org.apache.zeppelin.realm.LdapRealm.java
/** * Returns the LDAP User Distinguished Name (DN) to use when acquiring an * {@link javax.naming.ldap.LdapContext LdapContext} from the * {@link LdapContextFactory}./*from w ww. j a va 2 s . co m*/ * <p/> * If the the {@link #getUserDnTemplate() userDnTemplate} property has been * set, this implementation will construct the User DN by substituting the * specified {@code principal} into the configured template. If the * {@link #getUserDnTemplate() userDnTemplate} has not been set, the method * argument will be returned directly (indicating that the submitted * authentication token principal <em>is</em> the User DN). * * @param principal * the principal to substitute into the configured * {@link #getUserDnTemplate() userDnTemplate}. * @return the constructed User DN to use at runtime when acquiring an * {@link javax.naming.ldap.LdapContext}. * @throws IllegalArgumentException * if the method argument is null or empty * @throws IllegalStateException * if the {@link #getUserDnTemplate userDnTemplate} has not been * set. * @see LdapContextFactory#getLdapContext(Object, Object) */ @Override protected String getUserDn(final String principal) throws IllegalArgumentException, IllegalStateException { String userDn; String matchedPrincipal = matchPrincipal(principal); String userSearchBase = getUserSearchBase(); String userSearchAttributeName = getUserSearchAttributeName(); // If not searching use the userDnTemplate and return. if ((userSearchBase == null || userSearchBase.isEmpty()) || (userSearchAttributeName == null && userSearchFilter == null && !"object".equalsIgnoreCase(userSearchScope))) { userDn = expandTemplate(userDnTemplate, matchedPrincipal); if (log.isDebugEnabled()) { log.debug("LDAP UserDN and Principal: " + userDn + "," + principal); } return userDn; } // Create the searchBase and searchFilter from config. String searchBase = expandTemplate(getUserSearchBase(), matchedPrincipal); String searchFilter = null; if (userSearchFilter == null) { if (userSearchAttributeName == null) { searchFilter = String.format("(objectclass=%1$s)", getUserObjectClass()); } else { searchFilter = String.format("(&(objectclass=%1$s)(%2$s=%3$s))", getUserObjectClass(), userSearchAttributeName, expandTemplate(getUserSearchAttributeTemplate(), matchedPrincipal)); } } else { searchFilter = expandTemplate(userSearchFilter, matchedPrincipal); } SearchControls searchControls = getUserSearchControls(); // Search for userDn and return. LdapContext systemLdapCtx = null; NamingEnumeration<SearchResult> searchResultEnum = null; try { systemLdapCtx = getContextFactory().getSystemLdapContext(); if (log.isDebugEnabled()) { log.debug("SearchBase,SearchFilter,UserSearchScope: " + searchBase + "," + searchFilter + "," + userSearchScope); } searchResultEnum = systemLdapCtx.search(searchBase, searchFilter, searchControls); // SearchResults contains all the entries in search scope if (searchResultEnum.hasMore()) { SearchResult searchResult = searchResultEnum.next(); userDn = searchResult.getNameInNamespace(); if (log.isDebugEnabled()) { log.debug("UserDN Returned,Principal: " + userDn + "," + principal); } return userDn; } else { throw new IllegalArgumentException("Illegal principal name: " + principal); } } catch (AuthenticationException ne) { ne.printStackTrace(); throw new IllegalArgumentException("Illegal principal name: " + principal); } catch (NamingException ne) { throw new IllegalArgumentException("Hit NamingException: " + ne.getMessage()); } finally { try { if (searchResultEnum != null) { searchResultEnum.close(); } } catch (NamingException ne) { // Ignore exception on close. } finally { LdapUtils.closeContext(systemLdapCtx); } } }
From source file:org.springframework.ldap.core.DirContextAdapter.java
public String[] getNamesOfModifiedAttributes() { List tmpList = new ArrayList(); NamingEnumeration attributesEnumeration; if (isUpdateMode()) { attributesEnumeration = updatedAttrs.getAll(); } else {// w w w . j av a2s .c o m attributesEnumeration = originalAttrs.getAll(); } try { while (attributesEnumeration.hasMore()) { Attribute oneAttribute = (Attribute) attributesEnumeration.next(); tmpList.add(oneAttribute.getID()); } } catch (NamingException e) { throw LdapUtils.convertLdapException(e); } finally { closeNamingEnumeration(attributesEnumeration); } return (String[]) tmpList.toArray(new String[0]); }
From source file:org.jahia.services.usermanager.ldap.LDAPUserGroupProvider.java
private List<Member> loadMembers(NamingEnumeration<?> members) { List<Member> memberList = new ArrayList<Member>(); try {/*from w w w . j a v a2 s . co m*/ while (members != null && members.hasMore()) { final String memberNaming = (String) members.next(); // try to know if we deal with a group or a user Boolean isUser = userConfig.isCanGroupContainSubGroups() ? guessUserOrGroupFromDN(memberNaming) : true; // try to retrieve the object from the cache LDAPAbstractCacheEntry cacheEntry; if (isUser != null) { if (isUser) { cacheEntry = ldapCacheManager.getUserCacheEntryByDn(getKey(), memberNaming); } else { cacheEntry = ldapCacheManager.getGroupCacheEntryByDn(getKey(), memberNaming); } } else { // look in all cache cacheEntry = ldapCacheManager.getUserCacheEntryByDn(getKey(), memberNaming); if (cacheEntry == null) { cacheEntry = ldapCacheManager.getGroupCacheEntryByDn(getKey(), memberNaming); isUser = cacheEntry != null ? false : null; } else { isUser = true; } } if (cacheEntry != null) { if (isUser) { memberList.add(new Member(cacheEntry.getName(), Member.MemberType.USER)); } else { memberList.add(new Member(cacheEntry.getName(), Member.MemberType.GROUP)); } continue; } // try to retrieve if (isUser != null && userConfig.isSearchAttributeInDn()) { String name = getNameFromDn(memberNaming, isUser); if (StringUtils.isNotEmpty(name)) { memberList.add(isUser ? new Member(name, Member.MemberType.USER) : new Member(name, Member.MemberType.GROUP)); continue; } } // do queries // and cache the result Member member = null; LDAPUserCacheEntry userCacheEntry = getUserCacheEntryByDN(memberNaming, true); if (userCacheEntry == null) { // look in groups LDAPGroupCacheEntry groupCacheEntry = getGroupCacheEntryByDN(memberNaming, true, false); if (groupCacheEntry == null) { if (groupConfig.isDynamicEnabled()) { // look in dynamic groups groupCacheEntry = getGroupCacheEntryByDN(memberNaming, true, true); if (groupCacheEntry != null) { member = new Member(groupCacheEntry.getName(), Member.MemberType.GROUP); } } } else { member = new Member(groupCacheEntry.getName(), Member.MemberType.GROUP); } } else { member = new Member(userCacheEntry.getName(), Member.MemberType.USER); } if (member != null) { memberList.add(member); } } } catch (NamingException e) { logger.error("Error retrieving LDAP group members for group", e); } return memberList; }
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 w w . j a v a 2 s .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.atricore.idbus.idojos.ldapidentitystore.LDAPIdentityStore.java
/** * Obtains the roles for the given user. * * @param username the user name to fetch user data. * @return the list of roles to which the user is associated to. * @throws NamingException LDAP error obtaining roles fro the given user *//*from ww w . ja va 2 s. c o m*/ protected String[] selectRolesByUsername(String username) throws NamingException, NoSuchUserException { List userRoles = new ArrayList(); InitialLdapContext ctx = createLdapInitialContext(); String rolesCtxDN = getRolesCtxDN(); // Search for any roles associated with the user if (rolesCtxDN != null) { // The attribute where user DN is stored in roles : String uidAttributeID = getUidAttributeID(); if (uidAttributeID == null) uidAttributeID = "uniquemember"; // The attribute that identifies the role name String roleAttrName = getRoleAttributeID(); if (roleAttrName == null) roleAttrName = "roles"; String userDN; if ("UID".equals(getRoleMatchingMode())) { // Use User ID to match the role userDN = username; } else if ("PRINCIPAL".equals(getRoleMatchingMode())) { // Use User ID to match the role userDN = _principalUidAttributeID + "=" + username; } else { // Default behaviour: Match the role using the User DN, not just the username : userDN = selectUserDN(username); } if (logger.isDebugEnabled()) logger.debug( "Searching Roles for user '" + userDN + "' in Uid attribute name '" + uidAttributeID + "'"); if (userDN == null) throw new NoSuchUserException(username); try { if (userDN.contains("\\")) { logger.debug("Escaping '\\' character"); userDN = userDN.replace("\\", "\\\\\\"); } NamingEnumeration answer = ctx.search(rolesCtxDN, "(&(" + uidAttributeID + "=" + userDN + "))", getSearchControls()); if (logger.isDebugEnabled()) logger.debug("Search Name: " + rolesCtxDN); if (logger.isDebugEnabled()) logger.debug("Search Filter: (&(" + uidAttributeID + "=" + userDN + "))"); if (!answer.hasMore()) logger.info("No roles found for user " + username); while (answer.hasMore()) { SearchResult sr = (SearchResult) answer.next(); Attributes attrs = sr.getAttributes(); Attribute roles = attrs.get(roleAttrName); for (int r = 0; r < roles.size(); r++) { Object value = roles.get(r); String roleName = null; // The role attribute value is the role name roleName = value.toString(); if (roleName != null) { if (logger.isDebugEnabled()) logger.debug("Saving role '" + roleName + "' for user '" + username + "'"); userRoles.add(roleName); } } } } catch (NamingException e) { if (logger.isDebugEnabled()) logger.debug("Failed to locate roles", e); } } // Close the context to release the connection ctx.close(); return (String[]) userRoles.toArray(new String[userRoles.size()]); }
From source file:dk.magenta.ldap.LDAPMultiBaseUserRegistry.java
/** * Does a case-insensitive search for the given value in an attribute. * * @param attribute/*from w w w .j a v a2s .c om*/ * 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:org.josso.gateway.identity.service.store.ldap.LDAPIdentityStore.java
/** * Fetches the supplied user.//from w w w . ja v a2 s . c om * * @param attrValue the user id * @return the user id for the supplied uid * @throws NamingException LDAP error obtaining user information. * @throws IOException */ protected String selectUser(String attrId, String attrValue) throws NamingException, IOException { String uidValue = null; InitialLdapContext ctx = createLdapInitialContext(false); StartTlsResponse tls = null; if (getEnableStartTls()) { tls = startTls(ctx); } BasicAttributes matchAttrs = new BasicAttributes(true); String uidAttrName = this.getPrincipalUidAttributeID(); String usersCtxDN = this.getUsersCtxDN(); matchAttrs.put(attrId, attrValue); // String[] principalAttr = {attrId}; try { // NamingEnumeration answer = ctx.search(usersCtxDN, matchAttrs, principalAttr); // This gives more control over search behavior : NamingEnumeration answer = ctx.search(usersCtxDN, "(&(" + attrId + "=" + attrValue + "))", getSearchControls()); while (answer.hasMore()) { SearchResult sr = (SearchResult) answer.next(); Attributes attrs = sr.getAttributes(); Attribute uidAttr = attrs.get(uidAttrName); if (uidAttr == null) { logger.warn("Invalid user attrValue attribute '" + uidAttrName + "'"); continue; } uidValue = uidAttr.get().toString(); if (uidValue != null) { if (logger.isDebugEnabled()) logger.debug( "Found user '" + uidAttrName + "=" + uidValue + "' for user '" + attrValue + "'"); } else { if (logger.isDebugEnabled()) logger.debug("User not found for user '" + attrValue + "'"); } } } 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 uidValue; }
From source file:org.josso.gateway.identity.service.store.ldap.LDAPIdentityStore.java
/** * Fetches the supplied user DN./*from ww w .ja va2 s .c o m*/ * * @param uid the user id * @return the user DN for the supplied uid * @throws NamingException LDAP error obtaining user information. * @throws IOException */ protected String selectUserDN(String uid) throws NamingException, IOException { String dn = null; InitialLdapContext ctx = createLdapInitialContext(false); StartTlsResponse tls = null; if (getEnableStartTls()) { tls = startTls(ctx); } String principalUidAttrName = this.getPrincipalUidAttributeID(); String usersCtxDN = this.getUsersCtxDN(); try { // NamingEnumeration answer = ctx.search(usersCtxDN, matchAttrs, principalAttr); // This gives more control over search behavior : NamingEnumeration answer = ctx.search(usersCtxDN, "(&(" + principalUidAttrName + "=" + uid + "))", getSearchControls()); while (answer.hasMore()) { SearchResult sr = (SearchResult) answer.next(); Attributes attrs = sr.getAttributes(); Attribute uidAttr = attrs.get(principalUidAttrName); if (uidAttr == null) { logger.warn("Invalid user uid attribute '" + principalUidAttrName + "'"); continue; } String uidValue = uidAttr.get().toString(); if (uidValue != null) { dn = sr.getName() + "," + usersCtxDN; if (logger.isDebugEnabled()) logger.debug("Found user '" + principalUidAttrName + "=" + uidValue + "' for user '" + uid + "' DN=" + dn); } else { if (logger.isDebugEnabled()) logger.debug("User not found for user '" + uid + "'"); } } } 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 dn; }
From source file:nl.nn.adapterframework.ldap.LdapSender.java
private XmlBuilder searchResultsToXml(NamingEnumeration entries) throws NamingException { XmlBuilder entriesElem = new XmlBuilder("entries"); int row = 0;/*from w ww .java2 s . com*/ while ((getMaxEntriesReturned() == 0 || row < getMaxEntriesReturned()) && entries.hasMore()) { SearchResult searchResult = (SearchResult) entries.next(); XmlBuilder entryElem = new XmlBuilder("entry"); entryElem.addAttribute("name", searchResult.getName()); entryElem.addSubElement(attributesToXml(searchResult.getAttributes())); entriesElem.addSubElement(entryElem); row++; } return entriesElem; }
From source file:org.springframework.ldap.core.LdapTemplate.java
/** * Delete all subcontexts including the current one recursively. * //from w ww . j ava 2 s.c om * @param ctx The context to use for deleting. * @param name The starting point to delete recursively. * @throws NamingException if any error occurs */ protected void deleteRecursively(DirContext ctx, DistinguishedName name) { NamingEnumeration enumeration = null; try { enumeration = ctx.listBindings(name); while (enumeration.hasMore()) { Binding binding = (Binding) enumeration.next(); DistinguishedName childName = new DistinguishedName(binding.getName()); childName.prepend((DistinguishedName) name); deleteRecursively(ctx, childName); } ctx.unbind(name); if (log.isDebugEnabled()) { log.debug("Entry " + name + " deleted"); } } catch (javax.naming.NamingException e) { throw LdapUtils.convertLdapException(e); } finally { try { enumeration.close(); } catch (Exception e) { // Never mind this } } }