List of usage examples for javax.naming.directory SearchResult getAttributes
public Attributes getAttributes()
From source file:org.apache.lens.server.user.LDAPBackedDatabaseUserConfigLoader.java
/** * Gets the attributes.//from w w w . j a v a2 s . co m * * @param user the user * @return the attributes * @throws NamingException the naming exception */ public String[] getAttributes(String user) throws NamingException { String[] attributes = new String[ldapFields.length]; SearchResult sr = findAccountByAccountName(user); for (int i = 0; i < attributes.length; i++) { Attribute attr = sr.getAttributes().get(ldapFields[i]); attributes[i] = (attr == null ? null : attr.get().toString()); } return attributes; }
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); }/*from w ww. ja v a 2s . 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:py.una.pol.karaku.security.KarakuUserService.java
private List<KarakuPermission> loadAuthoritiesByDn(String uid) { List<KarakuPermission> listaRoles = new ArrayList<KarakuPermission>(); try {/*from w ww . j av a 2 s . com*/ DirContext ctx = getInitialDirContext(propertiesUtil.get(LDAP_ADMIN_KEY), propertiesUtil.get(LDAP_ADMIN_PASS_KEY)); Attributes matchAttrs = new BasicAttributes(true); matchAttrs.put(new BasicAttribute("member", getRealUsername(uid))); NamingEnumeration<SearchResult> answer = ctx.search("ou=permissions", matchAttrs); while (answer.hasMore()) { SearchResult searchResult = answer.next(); Attributes attributes = searchResult.getAttributes(); Attribute attr = attributes.get("cn"); String rol = (String) attr.get(); KarakuPermission grantedAuthority = new KarakuPermission(rol); listaRoles.add(grantedAuthority); } return listaRoles; } catch (NamingException e) { LOG.warn("Can't create Ldap Context", e); return Collections.emptyList(); } }
From source file:org.apache.ftpserver.usermanager.LdapUserManager.java
/** * Get all user names.//from www. j a v a 2s. c o m */ public synchronized Collection getAllUserNames() throws FtpException { try { // search ldap Attributes matchAttrs = new BasicAttributes(true); matchAttrs.put(m_objClassAttr); matchAttrs.put(new BasicAttribute(CLASS_NAME, BaseUser.class.getName())); NamingEnumeration answers = m_adminContext.search(m_userBaseDn, matchAttrs, CN_ATTRS); m_log.info("Getting all users under " + m_userBaseDn); // populate list ArrayList allUsers = new ArrayList(); while (answers.hasMore()) { SearchResult sr = (SearchResult) answers.next(); String cn = sr.getAttributes().get(CN).get().toString(); allUsers.add(cn); } Collections.sort(allUsers); return allUsers; } catch (NamingException ex) { m_log.error("LdapUserManager.getAllUserNames()", ex); throw new FtpException("LdapUserManager.getAllUserNames()", ex); } }
From source file:org.wso2.carbon.appfactory.userstore.OTAppFactoryUserStore.java
@Override public String[] doListUsers(String filter, int maxItemLimit) throws UserStoreException { String[] userNames = new String[0]; if (maxItemLimit == 0) { return userNames; }//from www .j av a 2s . c om int givenMax = Integer .parseInt(realmConfig.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_MAX_USER_LIST)); if (maxItemLimit < 0 || maxItemLimit > givenMax) { maxItemLimit = givenMax; } SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchCtls.setCountLimit(maxItemLimit); if (filter.contains("?") || filter.contains("**")) { throw new UserStoreException( "Invalid character sequence entered for user serch. Please enter valid sequence."); } StringBuffer searchFilter = null; searchFilter = new StringBuffer(realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_LIST_FILTER)); String searchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); String userNameProperty = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE); StringBuffer buff = new StringBuffer(); buff.append("(&").append(searchFilter).append("(").append(userNameProperty).append("=").append(filter) .append("))"); String serviceNameAttribute = "sn"; String mailAttribute = "mail"; String returnedAtts[] = { userNameProperty, serviceNameAttribute, mailAttribute }; searchCtls.setReturningAttributes(returnedAtts); DirContext dirContext = null; NamingEnumeration<SearchResult> answer = null; String[] allUserNames = null; try { dirContext = connectionSource.getContext(); answer = dirContext.search(searchBase, buff.toString(), searchCtls); List<String> list = new ArrayList<String>(); int i = 0; while (answer.hasMoreElements() && i < maxItemLimit) { SearchResult sr = (SearchResult) answer.next(); if (sr.getAttributes() != null) { Attribute attr = sr.getAttributes().get(mailAttribute); /* * If this is a service principle, just ignore and iterate rest of the array. * The entity is a service if value of surname is Service */ Attribute attrSurname = sr.getAttributes().get(serviceNameAttribute); if (attrSurname != null) { String serviceName = (String) attrSurname.get(); if (serviceName != null && serviceName.equals(LDAPConstants.SERVER_PRINCIPAL_ATTRIBUTE_VALUE)) { continue; } } if (attr != null) { String name = (String) attr.get(); //append the domain if exist String domain = userRealm.getRealmConfiguration() .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME); if (domain != null) { domain = domain + "/"; name = domain + name; } list.add(name); i++; } } } userNames = list.toArray(new String[list.size()]); //get secondary user lists UserStoreManager secUserManager = this.getSecondaryUserStoreManager(); if (secUserManager != null) { String[] secUserNames = secUserManager.listUsers(filter, maxItemLimit); allUserNames = UserCoreUtil.combineArrays(userNames, secUserNames); } else { allUserNames = userNames; } Arrays.sort(allUserNames); } catch (NamingException e) { log.error(e.getMessage(), e); throw new UserStoreException(e.getMessage(), e); } finally { JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeContext(dirContext); } return allUserNames; }
From source file:edu.internet2.middleware.subject.provider.ESCOJNDISourceAdapter.java
/** * {@inheritDoc}//from w w w . j a v a 2s . c o m */ @Override public Set<Subject> search(final String searchString) { final Set<Subject> result = new HashSet<Subject>(); Search search = this.getSearch("search"); String searchExpression; // If an scope value is found in the search string // the string is decomposed and a decorated Search instance is used. final int index = searchString.indexOf(ESCOJNDISourceAdapter.SCOPE_DELIM); if (index >= 0) { final String searchTerm = searchString.substring(0, index).trim(); final String scopeTerm = searchString.substring(index + ESCOJNDISourceAdapter.SCOPE_DELIM.length()) .trim(); final String[] scopes = scopeTerm.split(ESCOJNDISourceAdapter.SCOPE_SEP); search = new ESCOSearchWithScopeDecorator(scopes, search); searchExpression = searchTerm; } else { searchExpression = searchString; } if (search == null) { LOGGER.error("searchType: \"search\" not defined."); return result; } final String[] attributeNames = { this.nameAttributeName, this.subjectIDAttributeName, this.descriptionAttributeName, }; @SuppressWarnings("rawtypes") NamingEnumeration ldapResults = this.getLdapResults(search, searchExpression, attributeNames); if (ldapResults == null) { return result; } try { while (ldapResults.hasMore()) { SearchResult si = (SearchResult) ldapResults.next(); Attributes attributes1 = si.getAttributes(); Subject subject = this.createSubject(attributes1); result.add(subject); } } catch (NamingException ex) { LOGGER.error("LDAP Naming Except: " + ex.getMessage(), ex); } return result; }
From source file:org.jboss.additional.testsuite.jdkall.present.elytron.sasl.OtpSaslTestCase.java
/** * Check correct user attribute values in the LDAP when using OTP algorithm. *//*from ww w .j a v a 2 s .c o m*/ private void assertSequenceAndHash(Integer expectedSequence, byte[] expectedHash) throws NamingException { final Properties env = new Properties(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, LDAP_URL); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system"); env.put(Context.SECURITY_CREDENTIALS, "secret"); final LdapContext ctx = new InitialLdapContext(env, null); NamingEnumeration<?> namingEnum = ctx.search("dc=wildfly,dc=org", new BasicAttributes("cn", "jduke")); if (namingEnum.hasMore()) { SearchResult sr = (SearchResult) namingEnum.next(); Attributes attrs = sr.getAttributes(); assertEquals("Unexpected sequence number in LDAP attribute", expectedSequence, new Integer(attrs.get("telephoneNumber").get().toString())); assertEquals("Unexpected hash value in LDAP attribute", Base64.getEncoder().encodeToString(expectedHash), attrs.get("title").get().toString()); } else { fail("User not found in LDAP"); } namingEnum.close(); ctx.close(); }
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 a v a 2 s .c o 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:org.apache.archiva.redback.users.ldap.LdapUserManagerTest.java
private void assertExist(DirContext context, String dn, String attribute, String value) throws NamingException { SearchControls ctls = new SearchControls(); ctls.setDerefLinkFlag(true);//from www . jav a2 s . com 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); // NamingEnumeration<SearchResult> results = context.search( suffix, "(" + attribute + "=" + value + ")", ctls // ); assertTrue(results.hasMoreElements()); SearchResult result = results.nextElement(); Attributes attrs = result.getAttributes(); Attribute testAttr = attrs.get(attribute); assertEquals(value, testAttr.get()); }
From source file:org.sipfoundry.sipxconfig.bulk.ldap.UserMapper.java
/** * @return UserPreview// w w w . ja va 2 s . c o m */ public Object mapFromNameClassPair(NameClassPair nameClass) throws NamingException { SearchResult searchResult = (SearchResult) nameClass; Attributes attrs = searchResult.getAttributes(); User user = new User(); List<String> groupNames = new ArrayList<String>(getGroupNames(searchResult)); setUserProperties(user, attrs); setAliasesSet(getAliasesSet(attrs), user); UserPreview preview = new UserPreview(user, groupNames); return preview; }