List of usage examples for javax.naming NamingEnumeration hasMore
public boolean hasMore() throws NamingException;
From source file:org.springframework.ldap.demo.dao.PersonDaoImpl.java
public List<Person> findAll() { DirContext ctx = createAnonymousContext(); LinkedList<Person> list = new LinkedList<Person>(); NamingEnumeration<?> results = null; try {//from ww w . j a v a2s . co 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:org.springframework.ldap.demo.dao.PersonDaoImpl.java
public List<String> getAllPersonNames() { DirContext ctx = createAnonymousContext(); LinkedList<String> list = new LinkedList<String>(); NamingEnumeration<?> results = null; try {/*from ww w . j av a 2 s.c om*/ SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); results = ctx.search("", "(objectclass=person)", controls); while (results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); Attributes attributes = searchResult.getAttributes(); Attribute attr = attributes.get("cn"); String cn = (String) attr.get(); list.add(cn); } } 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:com.aurel.track.util.LdapUtil.java
/** * Get all ldap groups/*from www .j a v a 2 s . c o 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:org.pegadi.server.user.LDAPUserServerImpl.java
/** * @param roleID the ID of a role// w ww. j a v a 2 s .c o m * @param userID the ID of a user * @return <code>true</code> if the user has that role. */ public boolean hasRole(Integer roleID, Long userID) { try { SearchControls sc = new SearchControls(); NamingEnumeration e = ctx.search("ou=people", "(&(employeeNumber=" + userID + ")(pegadiRole=" + roleID + ":*))", sc); if (e.hasMore()) return true; } catch (NamingException er) { log.error("Error checking for role: " + roleID + "for userID " + userID, er); } catch (Exception e) { log.error("Something else", e); } return false; }
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 v a2s.c o 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.apache.directory.studio.connection.core.io.jndi.LdifSearchLogger.java
/** * {@inheritDoc}/*from w w w . jav a 2s.c om*/ */ public void logSearchResultEntry(Connection connection, StudioSearchResult studioSearchResult, long requestNum, NamingException ex) { if (!isSearchResultEntryLogEnabled()) { return; } try { String formattedString; if (studioSearchResult != null) { String dn = studioSearchResult.getNameInNamespace(); Attributes attributes = studioSearchResult.getAttributes(); LdifContentRecord record = new LdifContentRecord(LdifDnLine.create(dn)); NamingEnumeration<? extends Attribute> attributeEnumeration = attributes.getAll(); while (attributeEnumeration.hasMore()) { Attribute attribute = attributeEnumeration.next(); String attributeName = attribute.getID(); NamingEnumeration<?> valueEnumeration = attribute.getAll(); while (valueEnumeration.hasMore()) { Object o = valueEnumeration.next(); if (o instanceof String) { record.addAttrVal(LdifAttrValLine.create(attributeName, (String) o)); } if (o instanceof byte[]) { record.addAttrVal(LdifAttrValLine.create(attributeName, (byte[]) o)); } } } record.finish(LdifSepLine.create()); formattedString = record.toFormattedString(LdifFormatParameters.DEFAULT); } else { formattedString = LdifFormatParameters.DEFAULT.getLineSeparator(); } log(formattedString, "SEARCH RESULT ENTRY (" + requestNum + ")", ex, connection); //$NON-NLS-1$ //$NON-NLS-2$ } catch (NamingException e) { } }
From source file:org.craftercms.studio.impl.v1.service.security.DbWithLdapExtensionSecurityProvider.java
@Override public String authenticate(String username, String password) throws BadCredentialsException, AuthenticationSystemException { // Mapper for user data if user is successfully authenticated AuthenticatedLdapEntryContextMapper<User> mapper = new AuthenticatedLdapEntryContextMapper<User>() { @Override// w w w . jav a 2s . co m public User mapWithContext(DirContext dirContext, LdapEntryIdentification ldapEntryIdentification) { try { // User entry - extract attributes DirContextOperations dirContextOperations = (DirContextOperations) dirContext .lookup(ldapEntryIdentification.getRelativeName()); Attributes attributes = dirContextOperations.getAttributes(); String emailAttribName = studioConfiguration.getProperty(SECURITY_LDAP_USER_ATTRIBUTE_EMAIL); String firstNameAttribName = studioConfiguration .getProperty(SECURITY_LDAP_USER_ATTRIBUTE_FIRST_NAME); String lastNameAttribName = studioConfiguration .getProperty(SECURITY_LDAP_USER_ATTRIBUTE_LAST_NAME); String siteIdAttribName = studioConfiguration.getProperty(SECURITY_LDAP_USER_ATTRIBUTE_SITE_ID); String groupNameAttribName = studioConfiguration .getProperty(SECURITY_LDAP_USER_ATTRIBUTE_GROUP_NAME); Attribute emailAttrib = attributes.get(emailAttribName); Attribute firstNameAttrib = attributes.get(firstNameAttribName); Attribute lastNameAttrib = attributes.get(lastNameAttribName); Attribute siteIdAttrib = attributes.get(siteIdAttribName); Attribute groupNameAttrib = attributes.get(groupNameAttribName); User user = new User(); user.setGroups(new ArrayList<>()); user.setActive(1); user.setUsername(username); if (emailAttrib != null && emailAttrib.get() != null) { user.setEmail(emailAttrib.get().toString()); } else { logger.error("No LDAP attribute " + emailAttribName + " found for username " + username + ". User will not be imported into DB."); return null; } if (firstNameAttrib != null && firstNameAttrib.get() != null) { user.setFirstname(firstNameAttrib.get().toString()); } else { logger.warn("No LDAP attribute " + firstNameAttribName + " found for username " + username); } if (lastNameAttrib != null && lastNameAttrib.get() != null) { user.setLastname(lastNameAttrib.get().toString()); } else { logger.warn("No LDAP attribute " + lastNameAttribName + " found for username " + username); } if (siteIdAttrib != null && siteIdAttrib.get() != null) { Map<String, Object> params = new HashMap<>(); NamingEnumeration siteIdValues = siteIdAttrib.getAll(); while (siteIdValues.hasMore()) { Object siteIdObj = siteIdValues.next(); if (siteIdObj != null) { String[] siteIdAndGroupName = extractSiteIdAndGroupNameFromAttributeValue( siteIdObj.toString()); if (siteIdAndGroupName.length > 0) { params.put("siteId", siteIdAndGroupName[0]); SiteFeed siteFeed = siteFeedMapper.getSite(params); if (siteFeed != null) { // Add groups, first the one that's specific to the site if (siteIdAndGroupName.length > 1) { addGroupToUser(user, siteIdAndGroupName[1], siteFeed); } extractGroupsFromAttribute(user, groupNameAttribName, groupNameAttrib, siteFeed); } else { logger.warn("Not site found for ID " + siteIdAndGroupName[0]); } } } } } else { String defaultSiteId = studioConfiguration.getProperty(SECURITY_LDAP_DEFAULT_SITE_ID); logger.debug("Assigning user " + username + " to default site " + defaultSiteId); Map<String, Object> params = new HashMap<>(); params.put("siteId", defaultSiteId); SiteFeed siteFeed = siteFeedMapper.getSite(params); if (siteFeed != null) { extractGroupsFromAttribute(user, groupNameAttribName, groupNameAttrib, siteFeed); } else { logger.warn("No site found for default site ID " + defaultSiteId); } } return user; } catch (NamingException e) { logger.error("Error getting details from LDAP for username " + username, e); return null; } } }; // Create ldap query to authenticate user LdapQuery ldapQuery = query().where(studioConfiguration.getProperty(SECURITY_LDAP_USER_ATTRIBUTE_USERNAME)) .is(username); User user; try { user = ldapTemplate.authenticate(ldapQuery, password, mapper); } catch (EmptyResultDataAccessException e) { logger.info("User " + username + " not found with external security provider. Trying to authenticate against studio database"); // When user not found try to authenticate against studio database return super.authenticate(username, password); } catch (CommunicationException e) { logger.info("Failed to connect with external security provider. " + "Trying to authenticate against studio database"); // When user not found try to authenticate against studio database return super.authenticate(username, password); } catch (AuthenticationException e) { logger.error("Authentication failed with the LDAP system", e); throw new BadCredentialsException(); } catch (Exception e) { logger.error("Authentication failed with the LDAP system", e); throw new AuthenticationSystemException("Authentication failed with the LDAP system", e); } if (user != null) { // When user authenticated against LDAP, upsert user data into studio database if (super.userExists(username)) { try { boolean success = updateUserInternal(user.getUsername(), user.getFirstname(), user.getLastname(), user.getEmail()); if (success) { ActivityService.ActivityType activityType = ActivityService.ActivityType.UPDATED; Map<String, String> extraInfo = new HashMap<>(); extraInfo.put(DmConstants.KEY_CONTENT_TYPE, StudioConstants.CONTENT_TYPE_USER); activityService.postActivity(getSystemSite(), user.getUsername(), user.getUsername(), activityType, ActivityService.ActivitySource.API, extraInfo); } } catch (UserNotFoundException e) { logger.error( "Error updating user " + username + " with data from external authentication provider", e); throw new AuthenticationSystemException( "Error updating user " + username + " with data from external authentication provider", e); } } else { try { boolean success = createUser(user.getUsername(), password, user.getFirstname(), user.getLastname(), user.getEmail(), true); if (success) { ActivityService.ActivityType activityType = ActivityService.ActivityType.CREATED; Map<String, String> extraInfo = new HashMap<>(); extraInfo.put(DmConstants.KEY_CONTENT_TYPE, StudioConstants.CONTENT_TYPE_USER); activityService.postActivity(getSystemSite(), user.getUsername(), user.getUsername(), activityType, ActivityService.ActivitySource.API, extraInfo); } } catch (UserAlreadyExistsException e) { logger.error("Error adding user " + username + " from external authentication provider", e); throw new AuthenticationSystemException( "Error adding user " + username + " from external authentication provider", e); } } for (Group group : user.getGroups()) { try { upsertUserGroup(group.getSite(), group.getName(), user.getUsername()); } catch (GroupAlreadyExistsException | SiteNotFoundException | UserNotFoundException | UserAlreadyExistsException | GroupNotFoundException e) { logger.error("Failed to upsert user groups data from LDAP", e); } } String token = createToken(user); storeSessionTicket(token); storeSessionUsername(username); return token; } else { logger.error("Failed to retrieve LDAP user details"); throw new AuthenticationSystemException("Failed to retrieve LDAP user details"); } }
From source file:org.orbeon.oxf.processor.LDAPProcessor.java
private List search(DirContext ctx, String rootDN, String scope, String filter, String[] attributes) { try {//from w ww . ja va 2s . c o m List listResults = new ArrayList(); SearchControls constraints = new SearchControls(); constraints.setSearchScope(convertSearchScope(scope)); constraints.setReturningAttributes(attributes); try { if (scope != null && scope.toUpperCase().equals("ALLLEVELS")) { String[] levels = rootDN.split(","); for (int i = 0; i < levels.length; i++) { String[] currentLevels = new String[levels.length - i]; System.arraycopy(levels, i, currentLevels, 0, levels.length - i); String levelRootDN = StringUtils.join(currentLevels, ","); if (logger.isDebugEnabled()) logger.debug("LDAP Search on level " + levelRootDN); NamingEnumeration results = ctx.search(levelRootDN, filter, constraints); for (; results.hasMore();) { SearchResult result = (SearchResult) results.next(); listResults.add(result); } } } else { NamingEnumeration results = ctx.search(rootDN, filter, constraints); for (; results.hasMore();) { SearchResult result = (SearchResult) results.next(); listResults.add(result); } } } catch (NameNotFoundException e) { // for example in case of ALLLEVELS scope, if the LDAP database suffix has more than one component, the last iteration would result in NameNotFoundException } return listResults; } catch (NamingException e) { throw new OXFException("LDAP Search Failed", e); } }
From source file:ru.runa.wfe.security.logic.LdapLogic.java
private void fillTargetActorsRecursively(DirContext dirContext, Set<Actor> recursiveActors, SearchResult searchResult, Map<String, SearchResult> groupResultsByDistinguishedName, Map<String, Actor> actorsByDistinguishedName) throws NamingException { NamingEnumeration<String> namingEnum = (NamingEnumeration<String>) searchResult.getAttributes() .get(ATTR_GROUP_MEMBER).getAll(); while (namingEnum.hasMore()) { String executorDistinguishedName = namingEnum.next(); SearchResult groupSearchResult = groupResultsByDistinguishedName.get(executorDistinguishedName); if (groupSearchResult != null) { fillTargetActorsRecursively(dirContext, recursiveActors, groupSearchResult, groupResultsByDistinguishedName, actorsByDistinguishedName); } else {/*from ww w .ja va 2s. co m*/ Actor actor = actorsByDistinguishedName.get(executorDistinguishedName); if (actor != null) { recursiveActors.add(actor); } else { Matcher m = getPatternForMissedPeople().matcher(executorDistinguishedName); String executorPath = m.replaceAll(""); Attribute samAttribute = dirContext.getAttributes(executorPath).get(ATTR_ACCOUNT_NAME); if (samAttribute != null) { String executorName = samAttribute.get().toString(); log.debug("Executor name " + executorDistinguishedName + " fetched by invocation: " + executorName); try { Executor executor = executorDao.getExecutor(executorName); if (executor instanceof Actor) { recursiveActors.add((Actor) executor); } } catch (ExecutorDoesNotExistException e) { log.warn(e.getMessage() + " for '" + executorDistinguishedName + "'"); } } else { log.warn("Not found '" + executorDistinguishedName + "' neither in group or actor maps or by invocation"); } } } } }
From source file:edu.internet2.middleware.subject.provider.JNDISourceAdapter.java
/** * /* w w w. j a v a2 s . co m*/ * @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; }