List of usage examples for javax.naming NamingEnumeration nextElement
E nextElement();
From source file:org.sipfoundry.sipxconfig.bulk.ldap.UserMapper.java
/** * Returns all string values for an attribute with a given name, ignores the values that are * not string values/*from ww w . ja va 2 s . c o m*/ * * @param attrs collection of attributes * @param attr attribute name */ private Set<String> getValues(Attributes attrs, String attrName) throws NamingException { Attribute attribute = attrs.get(attrName); if (attribute == null) { return null; } Set<String> values = new TreeSet<String>(); NamingEnumeration<?> allValues = attribute.getAll(); while (allValues.hasMore()) { Object object = allValues.nextElement(); if (object instanceof String) { values.add((String) object); } } return values; }
From source file:com.healthcit.cacure.businessdelegates.LdapUserManager.java
public Set<UserCredentials> loadUsersByRole(RoleCode roleCode) { Role role = roleDao.getByRoleCode(roleCode); String groupFilter = createGroupFilter(roleCode); Set<UserCredentials> userCredentials = new HashSet<UserCredentials>(); try {/*w w w .ja v a 2 s . c om*/ Attributes attrs = contextSource.getReadOnlyContext().getAttributes(groupFilter); Attribute memAttr = attrs.get(Constants.LDAP_GROUP_UNIQUE_MEMBER); NamingEnumeration<?> elements = memAttr.getAll(); while (elements.hasMoreElements()) { DistinguishedName dn = new DistinguishedName((String) elements.nextElement()); String userName = dn.getValue(Constants.LDAP_UID); DirContextOperations dir = searchForUser(userName); String email = dir.getStringAttribute("mail"); UserCredentials user = getUserFromDatabase(userName); user.setEmail(email); userCredentials.add(user); } } catch (NamingException e) { log.error(e.getMessage()); } return userCredentials; }
From source file:org.apache.cloudstack.ldap.LdapUserManager.java
private LdapUser getUserForDn(String userdn, LdapContext context) throws NamingException { final SearchControls controls = new SearchControls(); controls.setSearchScope(_ldapConfiguration.getScope()); controls.setReturningAttributes(_ldapConfiguration.getReturnAttributes()); NamingEnumeration<SearchResult> result = context.search(userdn, "(objectClass=" + _ldapConfiguration.getUserObject() + ")", controls); if (result.hasMoreElements()) { return createUser(result.nextElement()); } else {//from ww w .j a v a 2 s . c o m throw new NamingException("No user found for dn " + userdn); } }
From source file:com.globalsight.everest.usermgr.UserLdapHelper.java
/** * Get the company names from a NamingEnumeration *///from ww w .j a v a 2 s .c o m static String[] getCompanyNamesFromSearchResults(NamingEnumeration p_searchResults) throws NamingException { // use a set so duplicates are not saved Set companyNames = new TreeSet(); while (p_searchResults.hasMoreElements()) { String cName = null; Object searchResultObj = p_searchResults.nextElement(); if (searchResultObj instanceof SearchResult) { SearchResult tempSearchResult = (SearchResult) searchResultObj; Attributes entry = tempSearchResult.getAttributes(); cName = getSingleAttributeValue(entry.get(LDAP_ATTR_COMPANY)); } if (cName != null && cName.trim().length() > 0) { // adds it to the set // if it already exists just returns (NOP) companyNames.add(cName); } } p_searchResults.close(); String[] cns = new String[companyNames.size()]; return (String[]) companyNames.toArray(cns); }
From source file:org.apache.cloudstack.ldap.LdapUserManager.java
public List<LdapUser> searchUsers(final String username, final LdapContext context) throws NamingException, IOException { final SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(_ldapConfiguration.getScope()); searchControls.setReturningAttributes(_ldapConfiguration.getReturnAttributes()); String basedn = _ldapConfiguration.getBaseDn(); if (StringUtils.isBlank(basedn)) { throw new IllegalArgumentException("ldap basedn is not configured"); }/* ww w . ja v a2 s . c o m*/ byte[] cookie = null; int pageSize = _ldapConfiguration.getLdapPageSize(); context.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) }); final List<LdapUser> users = new ArrayList<LdapUser>(); NamingEnumeration<SearchResult> results; do { results = context.search(basedn, generateSearchFilter(username), searchControls); while (results.hasMoreElements()) { final SearchResult result = results.nextElement(); users.add(createUser(result)); } Control[] contextControls = context.getResponseControls(); if (contextControls != null) { for (Control control : contextControls) { if (control instanceof PagedResultsResponseControl) { PagedResultsResponseControl prrc = (PagedResultsResponseControl) control; cookie = prrc.getCookie(); } } } else { s_logger.info("No controls were sent from the ldap server"); } context.setRequestControls( new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) }); } while (cookie != null); return users; }
From source file:org.apache.lens.server.user.LDAPBackedDatabaseUserConfigLoader.java
/** * Find account by account name./*www .j ava2s .c om*/ * * @param accountName the account name * @return the search result * @throws NamingException the naming exception */ protected SearchResult findAccountByAccountName(String accountName) throws NamingException { String searchFilter = String.format(searchFilterPattern, accountName); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); InitialLdapContext ctx = new InitialLdapContext(env, null); try { NamingEnumeration<SearchResult> results = ctx.search(searchBase, searchFilter, searchControls); if (!results.hasMoreElements()) { throw new UserConfigLoaderException("LDAP Search returned no accounts"); } SearchResult searchResult = results.nextElement(); if (results.hasMoreElements()) { throw new UserConfigLoaderException("More than one account found in ldap search"); } return searchResult; } finally { ctx.close(); } }
From source file:org.apache.archiva.redback.common.ldap.role.TestLdapRoleMapper.java
private void assertExist(DirContext context, String dn, String attribute, String value) throws NamingException { SearchControls ctls = new SearchControls(); ctls.setDerefLinkFlag(true);//from w w w . j a va 2 s . c o m ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE); ctls.setReturningAttributes(new String[] { "*" }); BasicAttributes matchingAttributes = new BasicAttributes(); matchingAttributes.put(attribute, value); BasicAttribute objectClass = new BasicAttribute("objectClass"); objectClass.add("inetOrgPerson"); matchingAttributes.put(objectClass); NamingEnumeration<SearchResult> results = context.search(suffix, matchingAttributes); assertTrue(results.hasMoreElements()); SearchResult result = results.nextElement(); Attributes attrs = result.getAttributes(); Attribute testAttr = attrs.get(attribute); assertEquals(value, testAttr.get()); }
From source file:org.wso2.carbon.identity.account.suspension.notification.task.ldap.LDAPNotificationReceiversRetrieval.java
@Override public List<NotificationReceiver> getNotificationReceivers(long lookupMin, long lookupMax, long delayForSuspension, String tenantDomain) throws AccountSuspensionNotificationException { List<NotificationReceiver> users = new ArrayList<NotificationReceiver>(); if (realmConfiguration != null) { String ldapSearchBase = realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); RealmService realmService = NotificationTaskDataHolder.getInstance().getRealmService(); try {//from w w w . j av a 2 s . co m ClaimManager claimManager = (ClaimManager) realmService .getTenantUserRealm(IdentityTenantUtil.getTenantId(tenantDomain)).getClaimManager(); String userStoreDomain = realmConfiguration .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME); if (StringUtils.isBlank(userStoreDomain)) { userStoreDomain = IdentityUtil.getPrimaryDomainName(); } String usernameMapAttribute = claimManager.getAttributeName(userStoreDomain, NotificationConstants.USERNAME_CLAIM); String firstNameMapAttribute = claimManager.getAttributeName(userStoreDomain, NotificationConstants.FIRST_NAME_CLAIM); String emailMapAttribute = claimManager.getAttributeName(userStoreDomain, NotificationConstants.EMAIL_CLAIM); String lastLoginTimeAttribute = claimManager.getAttributeName(userStoreDomain, NotificationConstants.LAST_LOGIN_TIME); if (log.isDebugEnabled()) { log.debug( "Retrieving ldap user list for lookupMin: " + lookupMin + " - lookupMax: " + lookupMax); } LDAPConnectionContext ldapConnectionContext = new LDAPConnectionContext(realmConfiguration); DirContext ctx = ldapConnectionContext.getContext(); //carLicense is the mapped LDAP attribute for LastLoginTime claim String searchFilter = "(&(" + lastLoginTimeAttribute + ">=" + lookupMin + ")(" + lastLoginTimeAttribute + "<=" + lookupMax + "))"; SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<SearchResult> results = ctx.search(ldapSearchBase, searchFilter, searchControls); if (log.isDebugEnabled()) { log.debug("LDAP user list retrieved."); } while (results.hasMoreElements()) { SearchResult result = results.nextElement(); NotificationReceiver receiver = new NotificationReceiver(); receiver.setEmail((String) result.getAttributes().get(emailMapAttribute).get()); receiver.setUsername((String) result.getAttributes().get(usernameMapAttribute).get()); receiver.setFirstName((String) result.getAttributes().get(firstNameMapAttribute).get()); receiver.setUserStoreDomain(userStoreDomain); long lastLoginTime = Long .parseLong(result.getAttributes().get(lastLoginTimeAttribute).get().toString()); long expireDate = lastLoginTime + TimeUnit.DAYS.toMillis(delayForSuspension); receiver.setExpireDate(new SimpleDateFormat("dd-MM-yyyy").format(new Date(expireDate))); if (log.isDebugEnabled()) { log.debug("Expire date was set to: " + receiver.getExpireDate()); } users.add(receiver); } } catch (NamingException e) { throw new AccountSuspensionNotificationException("Failed to filter users from LDAP user store.", e); } catch (UserStoreException e) { throw new AccountSuspensionNotificationException("Failed to load LDAP connection context.", e); } catch (org.wso2.carbon.user.api.UserStoreException e) { throw new AccountSuspensionNotificationException( "Error occurred while getting tenant user realm for " + "tenant:" + tenantDomain, e); } } return users; }
From source file:com.healthcit.cacure.businessdelegates.LdapUserManager.java
public List<UserCredentials> getAllUsers() { List<UserCredentials> userCredentials = new ArrayList<UserCredentials>(); try {//from w ww. j a v a 2 s .co m SearchControls searchCtls = new SearchControls(); String returnedAtts[] = { "uid" }; searchCtls.setReturningAttributes(returnedAtts); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); String searchFilter = "(&(objectClass=person))"; NamingEnumeration<SearchResult> elements = contextSource.getReadOnlyContext().search("", searchFilter, searchCtls); while (elements.hasMoreElements()) { DistinguishedName dn = new DistinguishedName(elements.nextElement().getName()); String userName = dn.getValue("uid"); userCredentials.add(getUserFromDatabase(userName)); } } catch (org.springframework.ldap.NamingException e) { e.printStackTrace(); return null; } catch (NamingException e) { e.printStackTrace(); return null; } return userCredentials; }
From source file:de.tuttas.util.LDAPUtil.java
/** * Benutzer aus der LDAP Abfragen//from ww w. java 2s .co m * * @param username Benutzername * @param password Kennwort * @return der Benutzer * @throws Exception Wenn etwas schief ging */ public LDAPUser authenticateJndi(String username, String password) throws Exception { // Anbindung ans LDAP Properties props = new Properties(); props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); props.put(Context.PROVIDER_URL, Config.getInstance().ldaphost); props.put(Context.SECURITY_PRINCIPAL, Config.getInstance().bindUser);//adminuser - User with special priviledge, dn user props.put(Context.SECURITY_CREDENTIALS, Config.getInstance().bindPassword);//dn user password try { context = new InitialDirContext(props); ctrls = new SearchControls(); ctrls.setReturningAttributes(new String[] { "description", "mail", "sn", "initials", "givenName", "memberOf", "userPrincipalName", "distinguishedName" }); ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE); } catch (NamingException ex) { Logger.getLogger(LDAPUtil.class.getName()).log(Level.SEVERE, null, ex); } NamingEnumeration<javax.naming.directory.SearchResult> answers = context .search(Config.getInstance().userContext, "(cn=" + username + ")", ctrls); Log.d("answers=" + answers); Log.d("answers=" + answers.hasMore()); if (!answers.hasMore()) { return null; } javax.naming.directory.SearchResult result = answers.nextElement(); try { for (NamingEnumeration ae = result.getAttributes().getAll(); ae.hasMore();) { Attribute attr = (Attribute) ae.next(); Log.d("attribute: " + attr.getID()); /* print each value */ for (NamingEnumeration e = attr.getAll(); e.hasMore(); System.out.println("value: " + e.next())) ; } } catch (NamingException e) { e.printStackTrace(); } String inititials = ""; if (result.getAttributes().get("initials") != null) { inititials = result.getAttributes().get("initials").getAll().next().toString(); } LDAPUser u; if (result.getAttributes().get("mail") == null) { u = new LDAPUser(result.getAttributes().get("sn").getAll().next().toString(), result.getAttributes().get("givenName").getAll().next().toString(), "", inititials); } else { u = new LDAPUser(result.getAttributes().get("sn").getAll().next().toString(), result.getAttributes().get("givenName").getAll().next().toString(), result.getAttributes().get("mail").getAll().next().toString(), inititials); } String dName = result.getAttributes().get("distinguishedName").getAll().next().toString(); Log.d("dName=" + dName); if (dName.contains("OU=Lehrer")) { Log.d("Ich bin ein Lehrer"); u.setRole(Roles.toString(Roles.LEHRER)); } else { Log.d("Ich bin ein Schler"); u.setRole(Roles.toString(Roles.SCHUELER)); if (result.getAttributes().get("memberOf") != null) { String memberOf = result.getAttributes().get("memberOf").getAll().next().toString(); String courseName = memberOf.split(",")[0]; courseName = courseName.substring(courseName.indexOf("=") + 1); Log.d("Name der Klasse ist " + courseName); u.setCourse(courseName); } } String user = result.getNameInNamespace(); try { props = new Properties(); props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); props.put(Context.PROVIDER_URL, Config.getInstance().ldaphost); props.put(Context.SECURITY_PRINCIPAL, user); props.put(Context.SECURITY_CREDENTIALS, password); context = new InitialDirContext(props); } catch (Exception e) { return null; } return u; }