List of usage examples for javax.naming NamingEnumeration hasMore
public boolean hasMore() throws NamingException;
From source file:ldap.SearchUtility.java
public boolean checkPassword(String DN, String pwdAtt, String value, DirContext context) throws NamingException, UnsupportedEncodingException { SearchControls ctls = new SearchControls(); ctls.setReturningAttributes(new String[0]); // Return no attrs ctls.setSearchScope(SearchControls.OBJECT_SCOPE); // Search object only //byte[] pwdBytes = value.getBytes("UTF-8"); byte[] pwdBytes = value.getBytes(LdapConstants.UTF8); // Invoke search method that will use the LDAP "compare" operation NamingEnumeration answer = context.search(DN, "(" + pwdAtt + "={0})", new Object[] { pwdBytes }, ctls); return answer.hasMore(); }
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); }//ww w . j a v a 2s. c o 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; }
From source file:org.easy.ldap.AdminServiceImpl.java
@Override public List<LdapUser> findAllUsers(LdapUser example) { Preconditions.checkNotNull(example); Preconditions.checkNotNull(example.getTenantId()); List<LdapUser> out = new ArrayList<LdapUser>(0); try {//from www . j a v a 2 s.c o m LdapName rootDn = namingFactory.createUsersDn(example.getTenantId()); NamingEnumeration<SearchResult> result = ldapDao.findAll(rootDn, LdapDao.toAttributes(example)); while (result.hasMore()) { out.add(LdapDao.toModel(example.getTenantId(), result.next().getAttributes())); } } catch (NamingException e) { log.error(e); throw new java.lang.RuntimeException(e); } return out; }
From source file:org.rhq.enterprise.server.resource.group.LdapGroupManagerBean.java
public Map<String, String> findLdapUserDetails(String userName) { Properties systemConfig = systemManager.getSystemConfiguration(subjectManager.getOverlord()); HashMap<String, String> userDetails = new HashMap<String, String>(); // Load our LDAP specific properties Properties env = getProperties(systemConfig); // Load the BaseDN String baseDN = (String) systemConfig.get(RHQConstants.LDAPBaseDN); // Load the LoginProperty String loginProperty = (String) systemConfig.get(RHQConstants.LDAPLoginProperty); if (loginProperty == null) { // Use the default loginProperty = "cn"; }/*from w ww. ja va 2s . c om*/ // Load any information we may need to bind String bindDN = (String) systemConfig.get(RHQConstants.LDAPBindDN); String bindPW = (String) systemConfig.get(RHQConstants.LDAPBindPW); // Load any search filter String searchFilter = (String) systemConfig.get(RHQConstants.LDAPFilter); if (bindDN != null) { env.setProperty(Context.SECURITY_PRINCIPAL, bindDN); env.setProperty(Context.SECURITY_CREDENTIALS, bindPW); env.setProperty(Context.SECURITY_AUTHENTICATION, "simple"); } try { InitialLdapContext ctx = new InitialLdapContext(env, null); SearchControls searchControls = getSearchControls(); // Add the search filter if specified. This only allows for a single search filter.. i.e. foo=bar. String filter; if ((searchFilter != null) && (searchFilter.length() != 0)) { filter = "(&(" + loginProperty + "=" + userName + ")" + "(" + searchFilter + "))"; } else { filter = "(" + loginProperty + "=" + userName + ")"; } log.debug("Using LDAP filter [" + filter + "] to locate user details for " + userName); // Loop through each configured base DN. It may be useful // in the future to allow for a filter to be configured for // each BaseDN, but for now the filter will apply to all. String[] baseDNs = baseDN.split(BASEDN_DELIMITER); for (int x = 0; x < baseDNs.length; x++) { NamingEnumeration<SearchResult> answer = ctx.search(baseDNs[x], filter, searchControls); if (!answer.hasMoreElements()) { //BZ:582471- ldap api bug change log.debug("User " + userName + " not found for BaseDN " + baseDNs[x]); // Nothing found for this DN, move to the next one if we have one. continue; } // We use the first match SearchResult si = answer.next(); //generate the DN String userDN = null; try { userDN = si.getNameInNamespace(); } catch (UnsupportedOperationException use) { userDN = si.getName(); if (userDN.startsWith("\"")) { userDN = userDN.substring(1, userDN.length()); } if (userDN.endsWith("\"")) { userDN = userDN.substring(0, userDN.length() - 1); } userDN = userDN + "," + baseDNs[x]; } userDetails.put("dn", userDN); // Construct the UserDN NamingEnumeration<String> keys = si.getAttributes().getIDs(); while (keys.hasMore()) { String key = keys.next(); Attribute value = si.getAttributes().get(key); if ((value != null) && (value.get() != null)) { userDetails.put(key, value.get().toString()); } } return userDetails; } return userDetails; } catch (NamingException e) { throw new RuntimeException(e); } }
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 w ww.java 2 s. 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.wso2.carbon.user.core.ldap.LDAPConnectionContext.java
private void populateDCMap() throws UserStoreException { try {/*w w w . j a va 2 s . co m*/ //get the directory context for DNS DirContext dnsContext = new InitialDirContext(environmentForDNS); //compose the DNS service to be queried String DNSServiceName = LDAPConstants.ACTIVE_DIRECTORY_DOMAIN_CONTROLLER_SERVICE + DNSDomainName; //query the DNS Attributes attributes = dnsContext.getAttributes(DNSServiceName, new String[] { LDAPConstants.SRV_ATTRIBUTE_NAME }); Attribute srvRecords = attributes.get(LDAPConstants.SRV_ATTRIBUTE_NAME); //there can be multiple records with same domain name - get them all NamingEnumeration srvValues = srvRecords.getAll(); dcMap = new TreeMap<Integer, SRVRecord>(); //extract all SRV Records for _ldap._tcp service under the specified domain and populate dcMap //int forcedPriority = 0; while (srvValues.hasMore()) { String value = srvValues.next().toString(); SRVRecord srvRecord = new SRVRecord(); String valueItems[] = value.split(" "); String priority = valueItems[0]; if (priority != null) { int priorityInt = Integer.parseInt(priority); /*if ((priorityInt == forcedPriority) || (priorityInt < forcedPriority)) { forcedPriority++; priorityInt = forcedPriority; }*/ srvRecord.setPriority(priorityInt); } /* else { forcedPriority++; srvRecord.setPriority(forcedPriority); }*/ String weight = valueItems[1]; if (weight != null) { srvRecord.setWeight(Integer.parseInt(weight)); } String port = valueItems[2]; if (port != null) { srvRecord.setPort(Integer.parseInt(port)); } String host = valueItems[3]; if (host != null) { srvRecord.setHostName(host); } //we index dcMap on priority basis, therefore, priorities must be different dcMap.put(srvRecord.getPriority(), srvRecord); } //iterate over the SRVRecords for Active Directory Domain Controllers and figure out the //host records for that for (SRVRecord srvRecord : dcMap.values()) { Attributes hostAttributes = dnsContext.getAttributes(srvRecord.getHostName(), new String[] { LDAPConstants.A_RECORD_ATTRIBUTE_NAME }); Attribute hostRecord = hostAttributes.get(LDAPConstants.A_RECORD_ATTRIBUTE_NAME); //we know there is only one IP value for a given host. So we do just get, not getAll srvRecord.setHostIP((String) hostRecord.get()); } } catch (NamingException e) { log.error("Error obtaining information from DNS Server" + e.getMessage(), e); throw new UserStoreException("Error obtaining information from DNS Server " + e.getMessage(), e); } }
From source file:ru.runa.wfe.security.logic.LdapLogic.java
private int synchronizeGroups(DirContext dirContext, Map<String, Actor> actorsByDistinguishedName) throws NamingException { int changesCount = 0; List<Group> existingGroupsList = executorDao.getAllGroups(); Map<String, Group> existingGroupsByLdapNameMap = Maps.newHashMap(); for (Group group : existingGroupsList) { if (!Strings.isNullOrEmpty(group.getLdapGroupName())) { existingGroupsByLdapNameMap.put(group.getLdapGroupName(), group); }/* w w w . j av a 2 s. c o m*/ } Set<Group> ldapGroupsToDelete = Sets.newHashSet(); if (LdapProperties.isSynchronizationDeleteExecutors()) { Set<Executor> ldapExecutors = executorDao.getGroupChildren(importGroup); for (Executor executor : ldapExecutors) { if (executor instanceof Group) { ldapGroupsToDelete.add((Group) executor); } } } SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); Map<String, SearchResult> groupResultsByDistinguishedName = Maps.newHashMap(); for (String ou : LdapProperties.getSynchronizationOrganizationUnits()) { NamingEnumeration<SearchResult> list = dirContext.search(ou, OBJECT_CLASS_GROUP_FILTER, controls); while (list.hasMore()) { SearchResult searchResult = list.next(); if (searchResult.getAttributes().get(ATTR_GROUP_MEMBER) == null) { continue; } groupResultsByDistinguishedName.put(searchResult.getNameInNamespace(), searchResult); } } for (SearchResult searchResult : groupResultsByDistinguishedName.values()) { String name = getStringAttribute(searchResult, ATTR_ACCOUNT_NAME); String description = getStringAttribute(searchResult, LdapProperties.getSynchronizationGroupDescriptionAttribute()); ToStringHelper toStringHelper = MoreObjects.toStringHelper("group info"); toStringHelper.add("name", name).add("description", description).omitNullValues(); log.debug("Read " + toStringHelper.toString()); Group group = existingGroupsByLdapNameMap.get(name); if (group == null) { if (!LdapProperties.isSynchronizationCreateExecutors()) { continue; } group = new Group(name, description); group.setLdapGroupName(name); log.info("Creating " + group); executorDao.create(group); executorDao.addExecutorsToGroup(Lists.newArrayList(group), importGroup); permissionDao.setPermissions(importGroup, Lists.newArrayList(Permission.LIST), group); changesCount++; } else { ldapGroupsToDelete.remove(group); if (LdapProperties.isSynchronizationUpdateExecutors()) { List<IChange> changes = Lists.newArrayList(); if (isAttributeNeedsChange(description, group.getDescription())) { changes.add(new AttributeChange("description", group.getDescription(), description)); group.setDescription(description); executorDao.update(group); } if (executorDao.removeExecutorFromGroup(group, wasteGroup)) { changes.add(new Change("waste group removal")); } if (executorDao.addExecutorToGroup(group, importGroup)) { changes.add(new Change("import group addition")); } if (!changes.isEmpty()) { log.info("Updating " + group + ": " + changes); changesCount++; } } } Set<Actor> actorsToDelete = Sets.newHashSet(executorDao.getGroupActors(group)); Set<Actor> actorsToAdd = Sets.newHashSet(); Set<Actor> groupTargetActors = Sets.newHashSet(); fillTargetActorsRecursively(dirContext, groupTargetActors, searchResult, groupResultsByDistinguishedName, actorsByDistinguishedName); for (Actor targetActor : groupTargetActors) { if (!actorsToDelete.remove(targetActor)) { actorsToAdd.add(targetActor); } } if (actorsToAdd.size() > 0) { log.info("Adding to " + group + ": " + actorsToAdd); executorDao.addExecutorsToGroup(actorsToAdd, group); changesCount++; } if (actorsToDelete.size() > 0) { executorDao.removeExecutorsFromGroup(Lists.newArrayList(actorsToDelete), group); changesCount++; } } if (LdapProperties.isSynchronizationDeleteExecutors() && ldapGroupsToDelete.size() > 0) { executorDao.removeExecutorsFromGroup(ldapGroupsToDelete, importGroup); executorDao.addExecutorsToGroup(ldapGroupsToDelete, wasteGroup); log.info("Inactivating " + ldapGroupsToDelete); changesCount += ldapGroupsToDelete.size(); } return changesCount; }
From source file:org.eclipse.skalli.core.user.ldap.LDAPClient.java
private User searchUserById(LdapContext ldap, String userId) throws NamingException { SearchControls sc = getSearchControls(); NamingEnumeration<SearchResult> results = null; try {//from w w w .java 2 s.c om results = ldap.search(config.getBaseDN(), MessageFormat.format("(&(objectClass=user)(sAMAccountName={0}))", userId), sc); //$NON-NLS-1$ while (results != null && results.hasMore()) { SearchResult entry = results.next(); User user = processEntry(entry); if (user != null) { if (LOG.isDebugEnabled()) { LOG.debug(MessageFormat.format("Success reading from LDAP: {0}, {1} <{2}>", //$NON-NLS-1$ user.getUserId(), user.getDisplayName(), user.getEmail())); } return user; } } } finally { closeQuietly(results); } return new User(userId); }
From source file:org.apache.zeppelin.service.ShiroAuthenticationService.java
/** Function to extract users from Zeppelin LdapRealm. */ private List<String> getUserList(LdapRealm r, String searchText, int numUsersToFetch) { List<String> userList = new ArrayList<>(); LOGGER.debug("SearchText: " + searchText); String userAttribute = r.getUserSearchAttributeName(); String userSearchRealm = r.getUserSearchBase(); String userObjectClass = r.getUserObjectClass(); JndiLdapContextFactory cf = (JndiLdapContextFactory) r.getContextFactory(); try {/*www. j a va2 s .c o m*/ LdapContext ctx = cf.getSystemLdapContext(); SearchControls constraints = new SearchControls(); constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); constraints.setCountLimit(numUsersToFetch); String[] attrIDs = { userAttribute }; constraints.setReturningAttributes(attrIDs); NamingEnumeration result = ctx.search(userSearchRealm, "(&(objectclass=" + userObjectClass + ")(" + userAttribute + "=*" + searchText + "*))", constraints); while (result.hasMore()) { Attributes attrs = ((SearchResult) result.next()).getAttributes(); if (attrs.get(userAttribute) != null) { String currentUser; if (r.getUserLowerCase()) { LOGGER.debug("userLowerCase true"); currentUser = ((String) attrs.get(userAttribute).get()).toLowerCase(); } else { LOGGER.debug("userLowerCase false"); currentUser = (String) attrs.get(userAttribute).get(); } LOGGER.debug("CurrentUser: " + currentUser); userList.add(currentUser.trim()); } } } catch (Exception e) { LOGGER.error("Error retrieving User list from Ldap Realm", e); } return userList; }
From source file:com.aurel.track.util.LdapUtil.java
/** * Get all ldap groups// w w w . j av a2 s . c o m * * @param siteBean * @param baseDnGroup * @param ldapFilterGroups * @param groupAttributeName * @param groupToMemberReferencesMap * @return * @throws Exception */ public static Map<String, TPersonBean> getLdapGroupsByList(String baseURL, TSiteBean siteBean, String groupAttributeName, Map<String, List<String>> groupToMemberReferencesMap, Map<String, String> groups) throws Exception { HashMap<String, TPersonBean> ldapGroupsMap = new HashMap<String, TPersonBean>(); String bindDN = siteBean.getLdapBindDN(); String bindPassword = siteBean.getLdapBindPassword(); String groupMemberAttributName = ldapMap.get(LDAP_CONFIG.GROUP_MEMBER); if (groupMemberAttributName == null) { LOGGER.debug( "No groupMember attribute defined in quartz-jobs.xml. Fall back to " + DEFAULT_GROUP_MEMBER); groupMemberAttributName = DEFAULT_GROUP_MEMBER; } LdapContext baseContext = getInitialContext(baseURL, bindDN, bindPassword); if (baseContext == null) { LOGGER.warn("Context is null for baseURL " + baseURL); return ldapGroupsMap; } for (Map.Entry<String, String> groupEntry : groups.entrySet()) { String groupName = groupEntry.getKey(); String groupDN = groupEntry.getValue(); int index = groupDN.indexOf(","); if (index != -1) { String searchPart = groupDN.substring(0, index); String searchStr = "(" + searchPart + ")"; String parentDNPart = groupDN.substring(index + 1); LdapContext context = (LdapContext) baseContext.lookup(parentDNPart); if (context == null) { LOGGER.warn("Context is null after lookup for " + parentDNPart); continue; } int recordCount = 0; SearchControls ctls = null; try { // Activate paged results int pageSize = 5; byte[] cookie = null; context.setRequestControls( new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) }); int total; // Control the search ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); ctls.setCountLimit((ApplicationBean.getInstance().getMaxNumberOfFullUsers() + ApplicationBean.getInstance().getMaxNumberOfLimitedUsers()) * 3 + 10); // Don't ask for more than we can // handle anyways do { /* perform the search */ NamingEnumeration<SearchResult> results = context.search("", searchStr, ctls); /* * for each entry print out name + all attrs and values */ while (results != null && results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); // Attributes atrs = sr.getAttributes(); Attributes attributes = searchResult.getAttributes(); if (attributes == null) { LOGGER.warn("No attributes found in LDAP search result " + searchResult.getName()); continue; } TPersonBean personBean = new TPersonBean(); try { personBean.setLoginName(groupName); ldapGroupsMap.put(personBean.getLoginName(), personBean); Attribute memberAttribute = attributes.get(groupMemberAttributName); if (memberAttribute != null) { NamingEnumeration<?> members = memberAttribute.getAll(); while (members != null && members.hasMore()) { String memberSearchResult = (String) members.next(); List<String> memberDNList = groupToMemberReferencesMap.get(groupName); if (memberDNList == null) { memberDNList = new ArrayList<String>(); groupToMemberReferencesMap.put(groupName, memberDNList); } LOGGER.debug("Member found: " + memberSearchResult); memberDNList.add(memberSearchResult); } } else { LOGGER.info("Could not find value(s) for group member attribute " + groupMemberAttributName + " for group " + groupName); } LOGGER.debug("LDAP entry cn: " + (String) attributes.get("cn").get()); LOGGER.debug("Processed group " + groupName); } catch (Exception e) { LOGGER.warn("Problem setting attributes from LDAP: " + e.getMessage()); LOGGER.warn( "This is probably a configuration error in the LDAP mapping section of quartz-jobs.xml"); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Stack trace:", e); } } ++recordCount; } // Examine the paged results control response Control[] controls = context.getResponseControls(); if (controls != null) { for (int i = 0; i < controls.length; i++) { if (controls[i] instanceof PagedResultsResponseControl) { PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i]; total = prrc.getResultSize(); if (total != 0) { LOGGER.debug("***************** END-OF-PAGE " + "(total : " + total + ") *****************\n"); } else { LOGGER.debug("***************** END-OF-PAGE " + "(total: unknown) ***************\n"); } cookie = prrc.getCookie(); } } } else { LOGGER.debug("No controls were sent from the server"); } // Re-activate paged results context.setRequestControls( new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) }); } while (cookie != null); } catch (SizeLimitExceededException sle) { if (recordCount < ctls.getCountLimit()) { LOGGER.error("Searching LDAP asked for more entries than permitted by the LDAP server."); LOGGER.error("Size limit exceeded error occurred after record " + recordCount + " with " + sle.getMessage()); LOGGER.error( "You have to ask your LDAP server admin to increase the limit or specify a more suitable search base or filter."); } else { LOGGER.error("Searching LDAP asked for more entries than permitted by the Genji server (" + recordCount + ")."); LOGGER.error( "You have to get more user licenses for Genji or specify a more suitable search base or filter."); } LOGGER.error("The LDAP synchronization is most likely incomplete."); } catch (NamingException e) { LOGGER.error("PagedSearch failed."); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } catch (IOException ie) { LOGGER.error("PagedSearch failed."); LOGGER.debug(ExceptionUtils.getStackTrace(ie)); } finally { context.close(); } } } return ldapGroupsMap; }