List of usage examples for javax.naming NamingEnumeration next
public T next() throws NamingException;
From source file:org.orbeon.oxf.processor.LDAPProcessor.java
private void serialize(List results, Config config, ContentHandler ch) { try {/*from www. j a v a2 s. c o m*/ ch.startDocument(); ch.startElement("", "results", "results", SAXUtils.EMPTY_ATTRIBUTES); for (Iterator i = results.iterator(); i.hasNext();) { SearchResult sr = (SearchResult) i.next(); ch.startElement("", "result", "result", SAXUtils.EMPTY_ATTRIBUTES); addElement(ch, "name", sr.getName()); try { addElement(ch, "fullname", sr.getNameInNamespace()); } catch (UnsupportedOperationException e) { // This seems to be the only way to know if sr contains a name! } Attributes attr = sr.getAttributes(); NamingEnumeration attrEn = attr.getAll(); while (attrEn.hasMoreElements()) { Attribute a = (Attribute) attrEn.next(); if (config.getAttributes().isEmpty() || config.getAttributes().contains(a.getID())) { ch.startElement("", "attribute", "attribute", SAXUtils.EMPTY_ATTRIBUTES); addElement(ch, "name", a.getID()); NamingEnumeration aEn = a.getAll(); while (aEn.hasMoreElements()) { Object o = aEn.next(); addElement(ch, "value", o.toString()); } ch.endElement("", "attribute", "attribute"); } } ch.endElement("", "result", "result"); } ch.endElement("", "results", "results"); ch.endDocument(); } catch (Exception e) { throw new OXFException(e); } }
From source file:org.ballerinalang.auth.ldap.nativeimpl.GetLdapScopesOfUser.java
private List<String> getListOfNames(List<String> searchBases, String searchFilter, SearchControls searchCtls, String property, boolean appendDn) throws NamingException { if (LOG.isDebugEnabled()) { LOG.debug("Result for searchBase: " + searchBases + " searchFilter: " + searchFilter + " property:" + property + " appendDN: " + appendDn); }/* w w w. j a va2 s . com*/ List<String> names = new ArrayList<String>(); NamingEnumeration<SearchResult> answer = null; try { // handle multiple search bases for (String searchBase : searchBases) { answer = ldapConnectionContext.search(LdapUtils.escapeDNForSearch(searchBase), searchFilter, searchCtls); while (answer.hasMoreElements()) { SearchResult searchResult = answer.next(); if (searchResult.getAttributes() == null) { continue; } Attribute attr = searchResult.getAttributes().get(property); if (attr == null) { continue; } for (Enumeration vals = attr.getAll(); vals.hasMoreElements();) { String name = (String) vals.nextElement(); if (LOG.isDebugEnabled()) { LOG.debug("Found user: " + name); } names.add(name); } } if (LOG.isDebugEnabled()) { for (String name : names) { LOG.debug("Result : " + name); } } } } finally { LdapUtils.closeNamingEnumeration(answer); } return names; }
From source file:org.wso2.carbon.appfactory.userstore.AppFactoryTenantManager.java
protected String[] getTenantDomains(String userDN) throws UserStoreException { DirContext dirContext;/* w w w. j ava 2 s.com*/ String groupNameSearchFilter = realmConfig.getUserStoreProperty("GroupNameListFilter"); String groupNameProperty = realmConfig.getUserStoreProperty("MembershipAttribute"); String searchFilter = getSearchFilter(groupNameSearchFilter, groupNameProperty, userDN); Set<String> list = new HashSet<String>(); if (log.isDebugEnabled()) { log.debug((new StringBuilder()).append("Searching for ").append(searchFilter).toString()); } dirContext = ldapConnectionSource.getContext(); NamingEnumeration answer = null; String domainsStrs[]; try { String dn; String domain; answer = searchForObject(searchFilter, null, dirContext, tenantMgtConfig.getTenantStoreProperties().get("RootPartition")); while (answer.hasMoreElements()) { SearchResult sr = (SearchResult) answer.next(); dn = sr.getNameInNamespace(); domain = getOrganizationalContextName(dn); if (domain != null) { list.add(domain); } } domainsStrs = list.toArray(new String[list.size()]); } catch (Exception e) { log.error(e.getMessage(), e); throw new UserStoreException(e.getMessage(), e); } finally { JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeContext(dirContext); } return domainsStrs; }
From source file:org.apache.zeppelin.service.ShiroAuthenticationService.java
/** Function to extract users from LDAP. */ private List<String> getUserList(JndiLdapRealm r, String searchText, int numUsersToFetch) { List<String> userList = new ArrayList<>(); String userDnTemplate = r.getUserDnTemplate(); String userDn[] = userDnTemplate.split(",", 2); String userDnPrefix = userDn[0].split("=")[0]; String userDnSuffix = userDn[1]; JndiLdapContextFactory cf = (JndiLdapContextFactory) r.getContextFactory(); try {/*from w w w .j a va2 s . co m*/ LdapContext ctx = cf.getSystemLdapContext(); SearchControls constraints = new SearchControls(); constraints.setCountLimit(numUsersToFetch); constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); String[] attrIDs = { userDnPrefix }; constraints.setReturningAttributes(attrIDs); NamingEnumeration result = ctx.search(userDnSuffix, "(" + userDnPrefix + "=*" + searchText + "*)", constraints); while (result.hasMore()) { Attributes attrs = ((SearchResult) result.next()).getAttributes(); if (attrs.get(userDnPrefix) != null) { String currentUser = attrs.get(userDnPrefix).toString(); userList.add(currentUser.split(":")[1].trim()); } } } catch (Exception e) { LOGGER.error("Error retrieving User list from Ldap Realm", e); } LOGGER.info("UserList: " + userList); return userList; }
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 .j av a2 s . 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); }
From source file:com.predic8.membrane.core.interceptor.authentication.session.LDAPUserDataProvider.java
private String searchUser(String login, HashMap<String, String> userAttrs, DirContext ctx) throws NamingException { String uid;//from www . j a va 2 s . co m SearchControls ctls = new SearchControls(); ctls.setReturningObjFlag(true); ctls.setSearchScope(searchScope); String search = searchPattern.replaceAll(Pattern.quote("%LOGIN%"), escapeLDAPSearchFilter(login)); log.debug("Searching LDAP for " + search); NamingEnumeration<SearchResult> answer = ctx.search(base, search, ctls); try { if (!answer.hasMore()) throw new NoSuchElementException(); log.debug("LDAP returned >=1 record."); SearchResult result = answer.next(); uid = result.getName(); for (Map.Entry<String, String> e : attributeMap.entrySet()) { log.debug("found LDAP attribute: " + e.getKey()); Attribute a = result.getAttributes().get(e.getKey()); if (a != null) userAttrs.put(e.getValue(), a.get().toString()); } } finally { answer.close(); } return uid; }
From source file:org.nuxeo.ecm.directory.ldap.LDAPTreeReference.java
/** * Fetches children, onelevel or subtree given the reference configuration. * <p>//from ww w . j a va 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.pegadi.server.user.LDAPUserServerImpl.java
/** * Returns an array of users having a given role. Either active or * inactive users are returned./* w ww .j a va 2 s. co m*/ * * @param roleID the role of the users. * @param active specifying whether we want the active or inactive users. * @return an array of <code>User</code>s. */ public List<Person> getUsersByRole(int roleID, int active) { if (roleID <= 0) return null; ArrayList<Person> users = new ArrayList<Person>(); try { SearchControls sc = new SearchControls(); String[] getThese = { "sn", "gn", "mail", "uid", "employeeNumber" }; sc.setReturningAttributes(getThese); NamingEnumeration e = ctx.search("ou=people", "(&(active=" + active + ")(pegadiRole=" + roleID + "*))", sc); while (e.hasMore()) { SearchResult sr = (SearchResult) e.next(); users.add(this.createUser(sr.getAttributes())); } Collections.sort(users); return users; } catch (NamingException er) { log.error("Error, getUsersByRole(" + roleID + "," + active + ")", er); } return null; }
From source file:org.springframework.ldap.samples.article.dao.TraditionalPersonDaoImpl.java
public List findAll() { DirContext ctx = createAnonymousContext(); LinkedList list = new LinkedList(); NamingEnumeration results = null; try {// ww w. j av a 2 s .c o m SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); results = ctx.search("", "(objectclass=person)", controls); while (results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); String dn = searchResult.getName(); Attributes attributes = searchResult.getAttributes(); list.add(mapToPerson(dn, attributes)); } } catch (NamingException e) { throw new RuntimeException(e); } finally { if (results != null) { try { results.close(); } catch (Exception e) { // Never mind this. } } if (ctx != null) { try { ctx.close(); } catch (Exception e) { // Never mind this. } } } return list; }
From source file:edu.internet2.middleware.subject.provider.LdapSourceAdapter.java
protected Attributes getLdapUnique(Search search, String searchValue, String[] attributeNames) throws SubjectNotFoundException, SubjectNotUniqueException { Attributes attributes = null; Iterator<SearchResult> results = getLdapResults(search, searchValue, attributeNames); if (results == null || !results.hasNext()) { String errMsg = "No results: " + search.getSearchType() + " filter:" + search.getParam("filter") + " searchValue: " + searchValue; throw new SubjectNotFoundException(errMsg); }/* w w w.j a va 2 s.co m*/ SearchResult si = (SearchResult) results.next(); attributes = si.getAttributes(); if (results.hasNext()) { si = (SearchResult) results.next(); if (!multipleResults) { String errMsg = "Search is not unique:" + si.getName() + "\n"; throw new SubjectNotUniqueException(errMsg); } Attributes attr = si.getAttributes(); NamingEnumeration<? extends Attribute> n = attr.getAll(); try { while (n.hasMore()) { Attribute a = n.next(); log.debug("checking attribute " + a.getID()); if (attributes.get(a.getID()) == null) { log.debug("adding " + a.getID()); attributes.put(a); } } } catch (NamingException e) { log.error("ldap excp: " + e); } } return attributes; }