List of usage examples for javax.naming NamingEnumeration next
public T next() throws NamingException;
From source file:org.wso2.carbon.directory.server.manager.internal.LDAPServerStoreManager.java
public void updateServicePrinciplePassword(String serverName, Object oldCredential, Object newCredentials) throws DirectoryServerManagerException { DirContext dirContext;//from www .j a v a 2 s . c o m try { dirContext = this.connectionSource.getContext(); } catch (UserStoreException e) { throw new DirectoryServerManagerException("Unable to retrieve directory connection.", e); } //first search the existing user entry. String searchBase = this.realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); String searchFilter = getServicePrincipleFilter(serverName); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningAttributes(new String[] { LDAPServerManagerConstants.LDAP_PASSWORD }); try { NamingEnumeration<SearchResult> namingEnumeration = dirContext.search(searchBase, searchFilter, searchControls); // here we assume only one user while (namingEnumeration.hasMore()) { BasicAttributes basicAttributes = new BasicAttributes(true); SearchResult searchResult = namingEnumeration.next(); Attributes attributes = searchResult.getAttributes(); Attribute userPassword = attributes.get(LDAPServerManagerConstants.LDAP_PASSWORD); Attribute newPasswordAttribute = getChangePasswordAttribute(userPassword, oldCredential, newCredentials); basicAttributes.put(newPasswordAttribute); String dnName = searchResult.getName(); dirContext = (DirContext) dirContext.lookup(searchBase); dirContext.modifyAttributes(dnName, DirContext.REPLACE_ATTRIBUTE, basicAttributes); } } catch (NamingException e) { log.error("Unable to update server principle password details. Server name - " + serverName); throw new DirectoryServerManagerException("Can not access the directory service", e); } finally { try { JNDIUtil.closeContext(dirContext); } catch (UserStoreException e) { log.error("Unable to close directory context.", e); } } }
From source file:com.wfp.utils.LDAPUtils.java
@SuppressWarnings("unchecked") public static void parseData(NamingEnumeration searchResults) { int totalResultLogger = 0; if (searchResults == null) { return;//from w ww . j a va 2 s . co m } // Loop through the search results while (searchResults.hasMoreElements()) { SearchResult sr = null; try { sr = (SearchResult) searchResults.next(); } catch (NamingException e1) { Logger.error("No Search results on LDAP ", LDAPUtils.class); } if (sr == null) { Logger.error("No Search results on LDAP ", LDAPUtils.class); return; } Attributes attrs = sr.getAttributes(); if (attrs != null) { try { for (NamingEnumeration ae = attrs.getAll(); ae.hasMore();) { Attribute attr = (Attribute) ae.next(); for (NamingEnumeration e = attr.getAll(); e.hasMore(); totalResultLogger++) { } } } catch (NamingException e) { Logger.error("Error ocuring while reading the attributes ", LDAPUtils.class, e); } } else { Logger.info("No attributes found on LDAP", LDAPUtils.class); } } }
From source file:org.apache.syncope.fit.core.reference.RoleITCase.java
@Test public void issueSYNCOPE632() { RoleTO roleTO = null;//from ww w . j a va 2s.c o m try { // 1. create new LDAP resource having account id mapped to a derived attribute ResourceTO newLDAP = resourceService.read(RESOURCE_NAME_LDAP); newLDAP.setKey("new-ldap"); newLDAP.setPropagationPrimary(true); MappingItemTO accountId = newLDAP.getRmapping().getAccountIdItem(); accountId.setIntMappingType(IntMappingType.RoleDerivedSchema); accountId.setIntAttrName("displayProperty"); newLDAP.getRmapping().setAccountIdItem(accountId); newLDAP.getRmapping().setAccountLink("'cn=' + displayProperty + ',ou=groups,o=isp'"); MappingItemTO description = new MappingItemTO(); description.setIntMappingType(IntMappingType.RoleId); description.setExtAttrName("description"); description.setPurpose(MappingPurpose.BOTH); newLDAP.getRmapping().addItem(description); newLDAP = createResource(newLDAP); assertNotNull(newLDAP); // 2. create a role and give the resource created above roleTO = buildRoleTO("lastRole"); roleTO.getRPlainAttrTemplates().add("icon"); roleTO.getPlainAttrs().add(attrTO("icon", "anIcon")); roleTO.getRPlainAttrTemplates().add("show"); roleTO.getPlainAttrs().add(attrTO("show", "true")); roleTO.getRDerAttrTemplates().add("displayProperty"); roleTO.getDerAttrs().add(attrTO("displayProperty", null)); roleTO.getResources().clear(); roleTO.getResources().add("new-ldap"); roleTO = createRole(roleTO); assertNotNull(roleTO); // 3. update the role RoleMod roleMod = new RoleMod(); roleMod.setKey(roleTO.getKey()); roleMod.getPlainAttrsToRemove().add("icon"); roleMod.getPlainAttrsToUpdate().add(attrMod("icon", "anotherIcon")); roleTO = updateRole(roleMod); assertNotNull(roleTO); // 4. check that a single group exists in LDAP for the role created and updated above int entries = 0; DirContext ctx = null; try { ctx = getLdapResourceDirContext(null, null); SearchControls ctls = new SearchControls(); ctls.setReturningAttributes(new String[] { "*", "+" }); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<SearchResult> result = ctx.search("ou=groups,o=isp", "(description=" + roleTO.getKey() + ")", ctls); while (result.hasMore()) { result.next(); entries++; } } catch (Exception e) { // ignore } finally { if (ctx != null) { try { ctx.close(); } catch (NamingException e) { // ignore } } } assertEquals(1, entries); } finally { if (roleTO != null) { roleService.delete(roleTO.getKey()); } resourceService.delete("new-ldap"); } }
From source file:org.projectforge.business.ldap.LdapUserDao.java
public LdapUser findByUsername(final Object username, final String... organizationalUnits) { return (LdapUser) new LdapTemplate(ldapConnector) { @Override/* ww w. j a v a2 s. c o m*/ protected Object call() throws NameNotFoundException, Exception { NamingEnumeration<?> results = null; final SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); final String searchBase = getSearchBase(organizationalUnits); results = ctx.search(searchBase, "(&(objectClass=" + getObjectClass() + ")(uid=" + username + "))", controls); if (results.hasMore() == false) { return null; } final SearchResult searchResult = (SearchResult) results.next(); final String dn = searchResult.getName(); final Attributes attributes = searchResult.getAttributes(); if (results.hasMore() == true) { log.error("Oups, found entries with multiple id's: " + getObjectClass() + "." + username); } return mapToObject(dn, searchBase, attributes); } }.excecute(); }
From source file:org.apache.manifoldcf.authorities.authorities.sharepoint.SharePointADAuthority.java
/** Obtain the DistinguishedName for a given user logon name. *@param ctx is the ldap context to use.// w w w . j a v a2 s . c o m *@param userName (Domain Logon Name) is the user name or identifier. *@param searchBase (Full Domain Name for the search ie: DC=qa-ad-76,DC=metacarta,DC=com) *@return DistinguishedName for given domain user logon name. * (Should throws an exception if user is not found.) */ protected String getDistinguishedName(LdapContext ctx, String userName, String searchBase, String userACLsUsername) throws ManifoldCFException { String returnedAtts[] = { "distinguishedName" }; String searchFilter = "(&(objectClass=user)(" + userACLsUsername + "=" + userName + "))"; SearchControls searchCtls = new SearchControls(); searchCtls.setReturningAttributes(returnedAtts); //Specify the search scope searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchCtls.setReturningAttributes(returnedAtts); try { NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls); while (answer.hasMoreElements()) { SearchResult sr = (SearchResult) answer.next(); Attributes attrs = sr.getAttributes(); if (attrs != null) { String dn = attrs.get("distinguishedName").get().toString(); return dn; } } return null; } catch (NamingException e) { throw new ManifoldCFException(e.getMessage(), e); } }
From source file:org.swordess.ldap.odm.core.SessionImpl.java
public List<String> lookup(String context, String filter) { if (null == filter) { return null; }//from www.j av a 2s. co m LogUtils.debug(LOG, String.format("search DNs with context=%s, filter=%s", context, filter)); SearchControls ctrl = new SearchControls(); ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE); ctrl.setReturningAttributes(new String[] {}); try { List<String> retVal = new ArrayList<String>(); NamingEnumeration<SearchResult> results = ctx.search(context, filter, ctrl); while (results.hasMore()) { retVal.add(results.next().getNameInNamespace()); } return retVal; } catch (NamingException e) { throw new SessionException(e.getMessage(), e); } }
From source file:org.olat.ldap.LDAPLoginManagerImpl.java
/** * Creates list of all OLAT Users which have been deleted out of the LDAP directory but still exits in OLAT Configuration: Required Attributes = olatextconfig.xml * (property=reqAttrs) LDAP Base = olatextconfig.xml (property=ldapBase) * /* w ww . j a v a 2 s. c om*/ * @param syncTime The time to search in LDAP for changes since this time. SyncTime has to formatted: JJJJMMddHHmm * @param ctx The LDAP system connection, if NULL or closed NamingExecpiton is thrown * @return Returns list of Identity from the user which have been deleted in LDAP * @throws NamingException */ public List<Identity> getIdentitysDeletedInLdap(final LdapContext ctx) { if (ctx == null) { return null; } // Find all LDAP Users final String userID = LDAPLoginModule.mapOlatPropertyToLdapAttribute(LDAPConstants.LDAP_USER_IDENTIFYER); final String objctClass = LDAPLoginModule.getLdapUserObjectClass(); final List<String> ldapList = new ArrayList<String>(); searchInLdap(new LdapVisitor() { public void visit(final SearchResult result) throws NamingException { final Attributes attrs = result.getAttributes(); final NamingEnumeration<? extends Attribute> aEnum = attrs.getAll(); while (aEnum.hasMore()) { final Attribute attr = aEnum.next(); // use lowercase username ldapList.add(attr.get().toString().toLowerCase()); } } }, "(objectClass=" + objctClass + ")", new String[] { userID }, ctx); if (ldapList.isEmpty()) { logWarn("No users in LDAP found, can't create deletionList!!", null); return null; } // Find all User in OLAT, members of LDAPSecurityGroup final SecurityGroup ldapGroup = securityManager.findSecurityGroupByName(LDAPConstants.SECURITY_GROUP_LDAP); if (ldapGroup == null) { logError("Error getting users from OLAT security group '" + LDAPConstants.SECURITY_GROUP_LDAP + "' : group does not exist", null); return null; } final List<Identity> identityListToDelete = new ArrayList<Identity>(); final List<Identity> olatListIdentity = securityManager.getIdentitiesOfSecurityGroup(ldapGroup); for (final Identity ida : olatListIdentity) { // compare usernames with lowercase if (!ldapList.contains(ida.getName().toLowerCase())) { identityListToDelete.add(ida); } } return identityListToDelete; }
From source file:org.olat.ldap.LDAPLoginManagerImpl.java
private boolean isPagedResultControlSupported(final LdapContext ctx) { try {/*w w w . j a va 2 s .com*/ final SearchControls ctl = new SearchControls(); ctl.setReturningAttributes(new String[] { "supportedControl" }); ctl.setSearchScope(SearchControls.OBJECT_SCOPE); /* search for the rootDSE object */ final NamingEnumeration<SearchResult> results = ctx.search("", "(objectClass=*)", ctl); while (results.hasMore()) { final SearchResult entry = results.next(); final NamingEnumeration<? extends Attribute> attrs = entry.getAttributes().getAll(); while (attrs.hasMore()) { final Attribute attr = attrs.next(); final NamingEnumeration<?> vals = attr.getAll(); while (vals.hasMore()) { final String value = (String) vals.next(); if (value.equals(PAGED_RESULT_CONTROL_OID)) { return true; } } } } return false; } catch (final Exception e) { logError("Exception when trying to know if the server support paged results.", e); return false; } }
From source file:org.apereo.portal.groups.ldap.LDAPGroupStore.java
protected void processLdapResults(NamingEnumeration results, ArrayList keys) { //long time1 = System.currentTimeMillis(); //long casting=0; //long getting=0; //long setting=0; //long looping=0; //long loop1=System.currentTimeMillis(); try {//from ww w . j a va 2 s . c o m while (results.hasMore()) { //long loop2 = System.currentTimeMillis(); //long cast1=System.currentTimeMillis(); //looping=looping+loop2-loop1; SearchResult result = (SearchResult) results.next(); //long cast2 = System.currentTimeMillis(); //long get1 = System.currentTimeMillis(); Attributes ldapattribs = result.getAttributes(); //long get2 = System.currentTimeMillis(); //long set1 = System.currentTimeMillis(); Attribute attrib = ldapattribs.get(keyfield); if (attrib != null) { keys.add(String.valueOf(attrib.get()).toLowerCase()); } //long set2 = System.currentTimeMillis(); //loop1=System.currentTimeMillis(); //casting=casting+cast2-cast1; //setting=setting+set2-set1; //getting=getting+get2-get1; } } catch (NamingException nex) { log.error("LDAPGroupStore: error processing results", nex); } finally { try { results.close(); } catch (Exception e) { } } //long time5 = System.currentTimeMillis(); //System.out.println("Result processing took "+(time5-time1)+": "+getting+" for getting, " // +setting+" for setting, "+casting+" for casting, "+looping+" for looping," // +(time5-loop1)+" for closing"); }
From source file:org.olat.ldap.LDAPLoginManagerImpl.java
/** * Find the user dn with its uid/*w w w . j a v a2 s . c om*/ * * @param uid * @param ctx * @return user's dn */ private String searchUserDN(final String uid, final DirContext ctx) { if (ctx == null) { return null; } final List<String> ldapBases = LDAPLoginModule.getLdapBases(); final String objctClass = LDAPLoginModule.getLdapUserObjectClass(); final String[] serachAttr = { "dn" }; final String ldapUserIDAttribute = LDAPLoginModule .mapOlatPropertyToLdapAttribute(LDAPConstants.LDAP_USER_IDENTIFYER); final String filter = "(&(objectClass=" + objctClass + ")(" + ldapUserIDAttribute + "=" + uid + "))"; final SearchControls ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); ctls.setReturningAttributes(serachAttr); String userDN = null; for (final String ldapBase : ldapBases) { try { final NamingEnumeration<SearchResult> enm = ctx.search(ldapBase, filter, ctls); while (enm.hasMore()) { final SearchResult result = enm.next(); userDN = result.getNameInNamespace(); } if (userDN != null) { break; } } catch (final NamingException e) { logError("NamingException when trying to bind user with username::" + uid + " on ldapBase::" + ldapBase, e); } } return userDN; }