List of usage examples for javax.naming.directory SearchResult getAttributes
public Attributes getAttributes()
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 w w. j a va 2 s . com * * @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:gov.medicaid.dao.impl.LDAPIdentityProviderDAOBean.java
/** * Retrieves the roles for the from the identity provider. * * @param username the user to get the roles for * @return the list of roles for the user * @throws PortalServiceException for any errors encountered *///ww w. ja v a2 s . co m @SuppressWarnings("rawtypes") public List<String> findRoles(String username) throws PortalServiceException { DirContext ctx = null; try { ctx = new InitialDirContext(env); // Search for groups the user belongs to in order to get their names // Create the search controls SearchControls groupsSearchCtls = new SearchControls(); // Specify the search scope groupsSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Specify the attributes to return String groupsReturnedAtts[] = { "cn" }; groupsSearchCtls.setReturningAttributes(groupsReturnedAtts); String userDn = MessageFormat.format(userDNPattern, username); // Search for objects using the filter NamingEnumeration groupsAnswer = ctx.search(groupsSearchBase, MessageFormat.format(groupsFilterPattern, userDn), groupsSearchCtls); List<String> groups = new ArrayList<String>(); // Loop through the search results while (groupsAnswer.hasMoreElements()) { SearchResult sr = (SearchResult) groupsAnswer.next(); Attributes attrs = sr.getAttributes(); if (attrs != null) { groups.add((String) attrs.get("cn").get()); } if (sr.getObject() instanceof Context) { closeContext((Context) sr.getObject()); } } return groups; } catch (NamingException e) { throw new PortalServiceConfigurationException("Unable to get groups.", e); } finally { closeContext(ctx); } }
From source file:org.pegadi.server.user.LDAPUserServerImpl.java
/** * Find a user by ID. This id may be a compound ID, like the * LDAP database's DN structure. Otherwise it might be an empoyeeNumber * like this implementation use./*from www.j a va2 s. c o m*/ * <p/> * Tries first to get the user by pegadiID, which is the old method. * * @param id * @return the Userobject if found, or null if not. */ public Person getUserById(String id) { if (id == null || id.equals(0)) return null; Person user = null; String[] getThese = { "sn", "gn", "mail", "uid", "employeeNumber" }; try { //int nr = Integer.parseInt(id); //only needed if we can get the dn. SearchControls sc = new SearchControls(); sc.setReturningAttributes(getThese); NamingEnumeration e = ctx.search("ou=people", "employeeNumber=" + id, sc); if (e.hasMore()) { SearchResult sr = (SearchResult) e.next(); user = this.createUser(sr.getAttributes()); } } catch (NamingException e) { log.error("An error occured while trying to getUserById(" + id + ")", e); /*FIXME does not work. * try { Attributes attrs = ctx.getAttributes("dn=" + id,getThese); return createUser(attrs); } catch (NamingException e) { e.printStackTrace(); }*/ } return user; }
From source file:org.pegadi.server.user.LDAPUserServerImpl.java
/** * Returns an array of users.//from w w w.ja v a2 s . c o m * * @param inactive <code>true</code> if inactive users should be included. * @return an array of <code>User</code>s. */ public List<Person> getAllUsers(boolean inactive) { ArrayList<Person> users = new ArrayList<Person>(); try { SearchControls sc = new SearchControls(); String[] getThese = { "sn", "gn", "mail", "uid", "employeeNumber" }; sc.setReturningAttributes(getThese); if (inactive) { Attributes attrs = ctx.getAttributes("ou=people", getThese); users.add(this.createUser(attrs)); } else { NamingEnumeration e = ctx.search("ou=people", "(active=1)", 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("Could not get users", er); } catch (Exception e) { log.error("Something else", e); } return null; }
From source file:org.apache.directory.server.operations.bind.MiscBindIT.java
/** * Test to make sure that if anonymous binds are allowed a user may search * within a a partition./*w ww. ja v a 2 s. c om*/ * * @throws Exception if anything goes wrong */ @Test public void testAnonymousBindsEnabledBaseSearch() throws Exception { getLdapServer().getDirectoryService().setAllowAnonymousAccess(true); // Use the SUN JNDI provider to hit server port and bind as anonymous Hashtable<String, Object> env = new Hashtable<String, Object>(); env.put(Context.PROVIDER_URL, Network.ldapLoopbackUrl(getLdapServer().getPort())); env.put(Context.SECURITY_AUTHENTICATION, "none"); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); InitialDirContext ctx = new InitialDirContext(env); SearchControls cons = new SearchControls(); cons.setSearchScope(SearchControls.OBJECT_SCOPE); NamingEnumeration<SearchResult> list = ctx.search("dc=apache,dc=org", "(objectClass=*)", cons); SearchResult result = null; if (list.hasMore()) { result = list.next(); } assertFalse(list.hasMore()); list.close(); assertNotNull(result); assertNotNull(result.getAttributes().get("dc")); }
From source file:net.e2.bw.servicereg.ldap.ServiceInstanceLdapService.java
/** Converts a search result to a service instance entry */ private CachedServiceInstance toServiceInstance(SearchResult sr) { if (sr == null) { return null; }/*from w w w . j a v a2s . co m*/ Attributes attrs = sr.getAttributes(); String serviceInstanceId = getAttributeValue(attrs, "uid"); String name = getAttributeValue(attrs, "cn"); String summary = getAttributeValue(attrs, "description"); String organizationId = extractGroupId(getAttributeValue(attrs, "serviceOrganization")); String serviceSpecificationId = extractServiceSpecificationId( getAttributeValue(attrs, "serviceSpecification")); List<Area> coverage = decompressCoverage(getAttributeValue(attrs, "serviceCoverage")); List<ServiceEndpoint> endpoints = new ArrayList<>(); Attribute endpointAttr = attrs.get("serviceEndpoint"); for (int i = 0; endpointAttr != null && i < endpointAttr.size(); ++i) { try { endpoints.add(new ServiceEndpoint((String) endpointAttr.get(i))); } catch (Exception ignored) { } } Map<String, List<String>> roleUserMap = getRoleUsers(getServiceInstanceDN(serviceInstanceId)); return new CachedServiceInstance(serviceInstanceId, organizationId, serviceSpecificationId, name, summary, coverage, endpoints, roleUserMap); }
From source file:com.aurel.track.util.LdapUtil.java
/** * Gets a personBean from LDAP/*from w ww.j av a 2 s . com*/ * * @param searchResult * @param loginAttributeName * @param firstNameAttributeName * @param lastNameAttributName * @param emailAttributeName * @param phoneAttributName * @return */ public static TPersonBean getPersonBean(SearchResult searchResult, String loginAttributeName, String firstNameAttributeName, String lastNameAttributName, String emailAttributeName, String phoneAttributName) { Attributes attributes = searchResult.getAttributes(); if (attributes == null) { LOGGER.warn("No attributes found in LDAP search result " + searchResult.getName()); return null; } TPersonBean personBean = new TPersonBean(); try { Attribute loginAttribute = attributes.get(loginAttributeName); if (loginAttribute != null) { String loginName = (String) loginAttribute.get(); LOGGER.debug("Loginname: " + loginName); if (loginName == null || "".equals(loginName)) { LOGGER.info("No value for loginame attribute " + loginAttributeName); return null; } else { // loginname is mandatory for person personBean.setLoginName(loginName); } } else { LOGGER.info("No loginame attribute " + loginAttributeName); return null; } Attribute emailAttribute = attributes.get(emailAttributeName); if (emailAttribute != null) { String email = (String) emailAttribute.get(); LOGGER.debug("E-mail: " + email); if (email == null || "".equals(email)) { LOGGER.info("No value for e-mail attribute " + emailAttributeName); // e-mail is mandatory for person return null; } else { personBean.setEmail(email); } } else { LOGGER.info("No e-mail attribute " + emailAttributeName); return null; } Attribute firstNameAttribute = attributes.get(firstNameAttributeName); if (firstNameAttribute != null) { String firstName = (String) firstNameAttribute.get(); LOGGER.debug("Firstname: " + firstName); personBean.setFirstName(firstName); } Attribute lastNameAttribute = attributes.get(lastNameAttributName); if (lastNameAttribute != null) { String lastName = (String) lastNameAttribute.get(); LOGGER.debug("Lastname: " + lastName); if (lastName == null || "".equals(lastName)) { LOGGER.info("No value for lastname attribute " + lastNameAttributName); // lastname is mandatory for person return null; } else { personBean.setLastName(lastName); } } if (phoneAttributName != null) { Attribute phoneAttribute = attributes.get(phoneAttributName); if (phoneAttribute != null) { String phone = (String) phoneAttribute.get(); LOGGER.debug("Phone: " + phone); personBean.setPhone(phone); } } LOGGER.debug("LDAP entry cn: " + (String) attributes.get("cn").get()); LOGGER.debug("Processed " + personBean.getLoginName() + " (" + personBean.getFirstName() + " " + personBean.getLastName() + ")"); } 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"); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } return personBean; }
From source file:com.aurel.track.util.LdapUtil.java
/** * Get all ldap groups// w w w . j ava 2 s . co m * * @param siteBean * @param baseDnGroup * @param ldapFilterGroups * @param groupAttributeName * @param groupToMemberReferencesMap * @return * @throws Exception */ public static Map<String, TPersonBean> getLdapGroupsPaged(String baseURL, TSiteBean siteBean, String baseDnGroup, String ldapFilterGroups, String groupAttributeName, Map<String, List<String>> groupToMemberReferencesMap) throws Exception { if (ldapFilterGroups == null || "".equals(ldapFilterGroups) || "*".equals(ldapFilterGroups)) { ldapFilterGroups = "(" + groupAttributeName + "=*)"; } String bindDN = siteBean.getLdapBindDN(); String bindPassword = siteBean.getLdapBindPassword(); LdapContext context = getInitialContext(baseURL + baseDnGroup, bindDN, bindPassword); HashMap<String, TPersonBean> ldapGroupsMap = new HashMap<String, TPersonBean>(); if (context == null) { LOGGER.warn("Context is null"); return ldapGroupsMap; } int recordCount = 0; SearchControls ctls = null; String groupMemberAttributName = ldapMap.get(LDAP_CONFIG.GROUP_MEMBER); if (groupMemberAttributName == null) { groupMemberAttributName = DEFAULT_GROUP_MEMBER; } 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("", ldapFilterGroups, 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()); return null; } TPersonBean personBean = new TPersonBean(); try { Attribute groupNameAttribute = attributes.get(groupAttributeName); if (groupNameAttribute != null) { String groupName = (String) groupNameAttribute.get(); LOGGER.debug("Groupname: " + groupName); if (groupName == null || "".equals(groupName)) { LOGGER.info("No value for group name attribute " + groupAttributeName); return null; } else { 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); } 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 " + personBean.getLoginName() + " (" + personBean.getFirstName() + " " + personBean.getLastName() + ")"); } 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; }
From source file:edu.internet2.middleware.subject.provider.JNDISourceAdapter.java
/** * /*from w ww.ja v a 2s. c om*/ * @param search * @param searchValue * @param attributeNames * @return attributes * @throws SubjectNotFoundException * @throws SubjectNotUniqueException */ protected Attributes getLdapUnique(Search search, String searchValue, String[] attributeNames) throws SubjectNotFoundException, SubjectNotUniqueException { Attributes attributes1 = null; NamingEnumeration results = getLdapResults(search, searchValue, attributeNames); try { if (results == null || !results.hasMore()) { String errMsg = "No results: " + search.getSearchType() + " filter:" + search.getParam("filter") + " searchValue: " + searchValue; throw new SubjectNotFoundException(errMsg); } SearchResult si = (SearchResult) results.next(); attributes1 = si.getAttributes(); if (results.hasMore()) { si = (SearchResult) results.next(); String errMsg = "Search is not unique:" + si.getName() + "\n"; throw new SubjectNotUniqueException(errMsg); } } catch (NamingException ex) { log.error("Ldap NamingException: " + ex.getMessage(), ex); } return attributes1; }
From source file:org.apache.archiva.redback.users.ldap.ctl.DefaultLdapController.java
/** * @see org.apache.archiva.redback.users.ldap.ctl.LdapController#getUser(String, javax.naming.directory.DirContext) *///from w ww .j av a2s .c o m public LdapUser getUser(String username, DirContext context) throws LdapControllerException, MappingException { log.debug("Searching for user: {}", username); LdapUserQuery query = new LdapUserQuery(); query.setUsername(username); NamingEnumeration<SearchResult> result = null; try { result = searchUsers(context, null, query); if (result.hasMoreElements()) { SearchResult next = result.nextElement(); log.info("Found user: {}", username); return mapper.getUser(next.getAttributes()); } else { return null; } } catch (NamingException e) { String message = "Failed to retrieve information for user: " + username; throw new LdapControllerException(message, e); } finally { if (result != null) { try { result.close(); } catch (NamingException e) { log.warn("failed to close search results", e); } } } }