List of usage examples for javax.naming NamingEnumeration hasMore
public boolean hasMore() throws NamingException;
From source file:org.archone.ad.domain.LdapActions.java
@RPCAction(name = "group.list", required = { "domain" }) @SecuredMethod(constraints = "administrator.by_domain") public HashMap<String, Object> listGroups(OperationContext opContext) throws NamingException { String domain = (String) opContext.getParams().get("domain"); DirContextAdapter userDirContext = (DirContextAdapter) SecurityUtils.getSubject().getPrincipal(); DomainDn domainDn = nameHelper.newDomainDnFromDomain(domain); SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<SearchResult> searchResults = userDirContext.search(nameHelper.getGroupsBaseDn(domainDn), "(cn=*)", controls); List<HashMap<String, Object>> groups = new LinkedList<HashMap<String, Object>>(); while (searchResults.hasMore()) { SearchResult sr = searchResults.next(); if (nameHelper.isGroupDn(sr.getNameInNamespace().toLowerCase())) { HashMap<String, Object> group = new HashMap<String, Object>(); group.put("groupId", nameHelper.newGroupDn(sr.getNameInNamespace().toLowerCase()).getAsGroupId()); groups.add(group);//from www. j a v a2 s . co m } } HashMap<String, Object> response = new HashMap<String, Object>(); response.put("groups", groups); return response; }
From source file:net.officefloor.plugin.web.http.security.store.JndiLdapCredentialStoreTest.java
/** * Ensure correct roles.//from w ww . j av a 2 s.c om */ @SuppressWarnings("unchecked") public void testRoles() throws Exception { // Mocks final NamingEnumeration<SearchResult> searchResults = this.createMock(NamingEnumeration.class); final Attributes attributes = this.createMock(Attributes.class); final Attribute attribute = this.createMock(Attribute.class); // Objects final SearchResult searchResult = new SearchResult("uid=daniel", null, attributes); searchResult.setNameInNamespace("uid=daniel,ou=People,dc=officefloor,dc=net"); // Record obtaining the Credential Entry this.recordReturn(this.context, this.context.search("ou=People,dc=officefloor,dc=net", "(&(objectClass=inetOrgPerson)(uid=daniel))", null), searchResults); this.recordReturn(searchResults, searchResults.hasMore(), true); this.recordReturn(searchResults, searchResults.next(), searchResult); // Record obtaining the Groups this.recordReturn(this.context, this.context.search("ou=Groups,dc=officefloor,dc=net", "(&(objectClass=groupOfNames)" + "(member=uid=daniel,ou=People,dc=officefloor,dc=net))", null), searchResults); this.recordReturn(searchResults, searchResults.hasMore(), true); this.recordReturn(searchResults, searchResults.next(), new SearchResult("cn=developers", null, attributes)); this.recordReturn(attributes, attributes.get("ou"), attribute); this.recordReturn(attribute, attribute.get(), "developer"); this.recordReturn(searchResults, searchResults.hasMore(), true); this.recordReturn(searchResults, searchResults.next(), new SearchResult("cn=founders", null, attributes)); this.recordReturn(attributes, attributes.get("ou"), attribute); this.recordReturn(attribute, attribute.get(), "founder"); this.recordReturn(searchResults, searchResults.hasMore(), false); // Test this.replayMockObjects(); CredentialEntry entry = this.store.retrieveCredentialEntry("daniel", "REALM"); Set<String> roles = entry.retrieveRoles(); this.verifyMockObjects(); // Ensure correct roles assertEquals("Incorrect number of roles", 2, roles.size()); assertTrue("Must have developer role", roles.contains("developer")); assertTrue("Must have founder role", roles.contains("founder")); }
From source file:org.infoscoop.account.ldap.LDAPAccountManager.java
private List searchFromUsers(DirContext context, Map filters) throws NamingException { SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration searchResultEnum; String filter = buildFilter(filters); if (log.isInfoEnabled()) log.info("Search User from " + userBase + " by " + filter); searchResultEnum = context.search(userBase, filter, searchControls); //roop of retrieval result List users = new ArrayList(); while (searchResultEnum.hasMore()) { SearchResult searchResult = (SearchResult) searchResultEnum.next(); String dn = searchResult.getName() + "," + userBase; LDAPAccount user = createLDAPUser(dn, searchResult.getAttributes()); users.add(user);//from w w w . j a v a 2 s . c o m } return users; }
From source file:org.archone.ad.domain.LdapActions.java
@RPCAction(name = "user.remove", required = { "userId" }) @SecuredMethod(constraints = "administrator.by_domain") public HashMap<String, Object> removeUser(OperationContext opContext) throws NamingException { String userId = (String) opContext.getParams().get("userId"); DirContextAdapter userDirContext = (DirContextAdapter) SecurityUtils.getSubject().getPrincipal(); UserDn userDn = nameHelper.newUserDnFromId(userId); DomainDn domainDn = nameHelper.newDomainDnFromDomain(userDn.getDomain()); SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<SearchResult> searchResults = userDirContext.search( nameHelper.getGroupsBaseDn(nameHelper.newDomainDnFromDomain(userDn.getDomain())), "(uniqueMember=" + userDn.toString() + ")", controls); while (searchResults.hasMore()) { SearchResult sr = searchResults.next(); DirContextAdapter dca = (DirContextAdapter) userDirContext.lookup(sr.getNameInNamespace()); dca.removeAttributeValue("uniqueMember", userDn.toString()); userDirContext.modifyAttributes(sr.getNameInNamespace(), dca.getModificationItems()); }//from w ww . j ava 2s.c o m userDirContext.unbind(userDn); HashMap<String, Object> response = new HashMap<String, Object>(); response.put("success", true); return response; }
From source file:hudson.plugins.active_directory.ActiveDirectoryUnixAuthenticationProvider.java
private void parseMembers(String userDN, Set<GrantedAuthority> groups, NamingEnumeration<SearchResult> renum) throws NamingException { try {/* w w w . j ava2s . co m*/ while (renum.hasMore()) { Attributes a = renum.next().getAttributes(); Attribute cn = a.get("cn"); if (LOGGER.isLoggable(Level.FINE)) LOGGER.fine(userDN + " is a member of " + cn); groups.add(new GrantedAuthorityImpl(cn.get().toString())); } } catch (PartialResultException e) { // See JENKINS-42687. Just log the exception. Sometimes all the groups are correctly // retrieved but this Exception is launched as a last element of the NamingEnumeration // Even if it is really a PartialResultException, I don't see why this should be a blocker // I think a better approach is to log the Exception and continue LOGGER.log(Level.WARNING, String.format("JENKINS-42687 Might be more members for user %s", userDN), e); } }
From source file:org.easy.ldap.LdapDao.java
/** * @param rootDn/*w w w . j av a 2s.c o m*/ * @param type * @return */ public List<String> findRdnValue(LdapName rootDn, RdnType type) { NamingEnumeration<SearchResult> result = null; List<String> out = new ArrayList<String>(0); DirContext ctx = null; try { ctx = contextFactory.createContext(rootDn.toString()); Attributes attributes = new BasicAttributes(); attributes.put(new BasicAttribute(type.toString())); result = ctx.search("", attributes); while (result.hasMore()) { attributes = result.next().getAttributes(); out.add(attributes.get(type.toString()).get().toString()); } } catch (NamingException e) { throw new RuntimeException(type.toString() + "," + rootDn.toString(), e); } finally { if (contextFactory != null) contextFactory.closeContext(ctx); } return out; }
From source file:org.apache.archiva.redback.users.ldap.ctl.DefaultLdapController.java
public Map<String, Collection<String>> findUsersWithRoles(DirContext dirContext) throws LdapControllerException { Map<String, Collection<String>> usersWithRoles = new HashMap<String, Collection<String>>(); NamingEnumeration<SearchResult> namingEnumeration = null; try {//w w w . ja v a 2 s . com SearchControls searchControls = new SearchControls(); searchControls.setDerefLinkFlag(true); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); String filter = "objectClass=" + getLdapGroupClass(); namingEnumeration = dirContext.search(getGroupsDn(), filter, searchControls); while (namingEnumeration.hasMore()) { SearchResult searchResult = namingEnumeration.next(); String groupName = searchResult.getName(); // cn=blabla we only want bla bla groupName = StringUtils.substringAfter(groupName, "="); Attribute uniqueMemberAttr = searchResult.getAttributes().get("uniquemember"); if (uniqueMemberAttr != null) { NamingEnumeration<String> allMembersEnum = (NamingEnumeration<String>) uniqueMemberAttr .getAll(); while (allMembersEnum.hasMore()) { String userName = allMembersEnum.next(); // uid=blabla we only want bla bla userName = StringUtils.substringAfter(userName, "="); userName = StringUtils.substringBefore(userName, ","); Collection<String> roles = usersWithRoles.get(userName); if (roles == null) { roles = new HashSet<String>(); } roles.add(groupName); usersWithRoles.put(userName, roles); } } log.debug("found groupName: '{}' with users: {}", groupName); } return usersWithRoles; } catch (NamingException e) { throw new LdapControllerException(e.getMessage(), e); } finally { if (namingEnumeration != null) { try { namingEnumeration.close(); } catch (NamingException e) { log.warn("failed to close search results", e); } } } }
From source file:de.fiz.ddb.aas.utils.LDAPEngineUtility.java
protected Privilege convertLdapGroupToOrganizationPrivilegeWithUsers( NamingEnumeration<SearchResult> pPrivilegesSearchResults) throws NamingException, IllegalAccessException { Privilege vOrgPrivilege = null;/* w w w .j a v a 2 s. c o m*/ try { if ((pPrivilegesSearchResults != null) && (pPrivilegesSearchResults.hasMore())) { vOrgPrivilege = this.convertLdapGroupToOrgPriv(pPrivilegesSearchResults.next()); } } finally { // -- releases this context's resources immediately, instead of // waiting for the garbage collector if (pPrivilegesSearchResults != null) { try { pPrivilegesSearchResults.close(); pPrivilegesSearchResults = null; } catch (NamingException ex) { } } } return vOrgPrivilege; }
From source file:org.tolven.ldapmgr.LDAPMgrPlugin.java
protected void updateUser(String user, String encryptedPassword, DirContext dirContext, SearchControls controls) { NamingEnumeration<SearchResult> namingEnum = null; try {// w w w. j a v a 2 s . c o m String ldapPeople = getLDAPPeople(); String ldapSuffix = getLDAPSuffix(); boolean schemaExists = false; try { namingEnum = dirContext.search(ldapPeople + "," + ldapSuffix, "uid=" + user, controls); schemaExists = namingEnum.hasMore(); } catch (NamingException ex) { throw new RuntimeException("Could find schema for: " + user, ex); } if (schemaExists) { logger.info("LDAP schema for user " + user + " already exists"); } else { String dn = "uid=" + user + "," + ldapPeople + "," + ldapSuffix; Attributes attributes = new BasicAttributes(); Attribute objclass = new BasicAttribute("objectclass"); objclass.add("inetOrgPerson"); attributes.put(objclass); attributes.put("uid", user); attributes.put("sn", user); attributes.put("cn", user); attributes.put("userPassword", encryptedPassword); try { dirContext.createSubcontext(dn, attributes); } catch (NamingException ex) { throw new RuntimeException("Could not create schema for: " + user, ex); } logger.info("Created LDAP schema for " + user); } } finally { if (namingEnum != null) { try { namingEnum.close(); } catch (NamingException ex) { throw new RuntimeException( "Could not close the naming enumeration for the ldap schema: " + user, ex); } } } }
From source file:com.funambol.LDAP.security.LDAPUserProvisioningOfficer.java
/** * return the user dn of an ldap entry/*from w w w .j a v a2 s. c o m*/ * * search: base, filter, attrs, user, pass * @return */ protected SearchResult ldapSearch(String bindUser, String bindPass, String base, String filter, String[] attributes) { SearchResult ret = null; Hashtable<String, Object> bindEnv = new Hashtable<String, Object>(11); bindEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); bindEnv.put(Context.PROVIDER_URL, getLdapUrl()); // remove null attributes List<String> goodAttributes = new ArrayList<String>(); for (String s : attributes) { if (s != null) { goodAttributes.add(s); } } // get the DN DirContext authenticationContext; try { SearchControls ctls = new SearchControls(); ctls.setCountLimit(1); ctls.setReturningObjFlag(true); ctls.setReturningAttributes(goodAttributes.toArray(new String[0])); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Authenticate as User and password if (bindUser != null && bindPass != null) { log.debug("NBinding with credential as user: " + bindUser); bindEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); bindEnv.put(Context.SECURITY_PRINCIPAL, bindUser); bindEnv.put(Context.SECURITY_CREDENTIALS, bindPass); } authenticationContext = new InitialDirContext(bindEnv); // %u, %d in baseDN are still expanded NamingEnumeration<SearchResult> answer; try { answer = authenticationContext.search(base, filter, ctls); if (answer.hasMore()) { ret = (SearchResult) answer.next(); } } catch (NamingException e) { log.warn("Error while searching user with filter [" + filter + "]: " + e.getMessage()); } authenticationContext.close(); return ret; } catch (NamingException e) { log.error("Error while creating context: " + e.getMessage()); if (e.getCause() != null) { log.error("Error is: " + e.getCause().getMessage()); } return null; } }