List of usage examples for javax.naming NamingEnumeration next
public T next() throws NamingException;
From source file:org.atricore.idbus.idojos.ldapidentitystore.LDAPIdentityStore.java
/** * Fetches the supplied user.//from w w w.j av a 2 s .c o m * * @param attrValue the user id * @return the user id for the supplied uid * @throws NamingException LDAP error obtaining user information. */ protected String selectUser(String attrId, String attrValue) throws NamingException { String uidValue = null; InitialLdapContext ctx = createLdapInitialContext(); String uidAttrName = this.getPrincipalUidAttributeID(); String usersCtxDN = this.getUsersCtxDN(); try { // NamingEnumeration answer = ctx.search(usersCtxDN, matchAttrs, principalAttr); // This gives more control over search behavior : NamingEnumeration answer = ctx.search(usersCtxDN, "(&(" + attrId + "=" + attrValue + "))", getSearchControls()); while (answer.hasMore()) { SearchResult sr = (SearchResult) answer.next(); Attributes attrs = sr.getAttributes(); Attribute uidAttr = attrs.get(uidAttrName); if (uidAttr == null) { logger.warn("Invalid user attrValue attribute '" + uidAttrName + "'"); continue; } uidValue = uidAttr.get().toString(); if (uidValue != null) { if (logger.isDebugEnabled()) logger.debug( "Found user '" + uidAttrName + "=" + uidValue + "' for user '" + attrValue + "'"); } else { if (logger.isDebugEnabled()) logger.debug("User not found for user '" + attrValue + "'"); } } } catch (NamingException e) { if (logger.isDebugEnabled()) logger.debug("Failed to locate user", e); } finally { // Close the context to release the connection ctx.close(); } return uidValue; }
From source file:com.nridge.core.app.ldap.ADQuery.java
/** * This method will perform multiple queries into Active Directory * in order to resolve what groups a user is a member of. The * logic will identify nested groups and add them to the table. * <p>/*from ww w. j av a 2 s . c om*/ * The LDAP_ACCOUNT_NAME field must be populated in the user bag * prior to invoking this method. Any site specific fields can be * assigned to the user bag will be included in the attribute query. * </p> * <p> * Any site specific fields can be assigned to the group bag will * be included in the attribute query. * </p> * * @param aUserBag Active Directory user attributes. * @param aGroupBag Active Directory group attributes. * * @return Table of groups that the user is a member of. * * @throws NSException Thrown if an LDAP naming exception is occurs. */ @SuppressWarnings("StringConcatenationInsideStringBufferAppend") public DataTable loadUserGroupsByAccountName(DataBag aUserBag, DataBag aGroupBag) throws NSException { byte[] objectSid; DataBag groupBag; Attribute responseAttribute; String fieldName, fieldValue; Logger appLogger = mAppMgr.getLogger(this, "loadUserGroupsByAccountName"); appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER); if (mLdapContext == null) { String msgStr = "LDAP context has not been established."; appLogger.error(msgStr); throw new NSException(msgStr); } // First, we will populate our user bag so that we can obtain the distinguished name. loadUserByAccountName(aUserBag); // Now we will use the DN to find all of the groups the user is a member of. String distinguishedName = aUserBag.getValueAsString(LDAP_DISTINGUISHED_NAME); if (StringUtils.isEmpty(distinguishedName)) distinguishedName = getPropertyValue("user_searchbasedn", null); // Next, we will initialize our group membership table. DataTable memberTable = new DataTable(aUserBag); memberTable.setName(String.format("%s Group Membership", aUserBag.getValueAsString(LDAP_COMMON_NAME))); // The next logic section will query AD for all of the groups the user is a member // of. Because we are following tokenGroups, we will gain access to nested groups. String groupSearchBaseDN = getPropertyValue("group_searchbasedn", null); SearchControls userSearchControls = new SearchControls(); userSearchControls.setSearchScope(SearchControls.OBJECT_SCOPE); StringBuffer groupsSearchFilter = null; String ldapAttrNames[] = { "tokenGroups" }; userSearchControls.setReturningAttributes(ldapAttrNames); try { NamingEnumeration<?> userSearchResponse = mLdapContext.search(distinguishedName, "(objectClass=user)", userSearchControls); if ((userSearchResponse != null) && (userSearchResponse.hasMoreElements())) { groupsSearchFilter = new StringBuffer(); groupsSearchFilter.append("(|"); SearchResult userSearchResult = (SearchResult) userSearchResponse.next(); Attributes userResultAttributes = userSearchResult.getAttributes(); if (userResultAttributes != null) { try { for (NamingEnumeration<?> searchResultAttributesAll = userResultAttributes .getAll(); searchResultAttributesAll.hasMore();) { Attribute attr = (Attribute) searchResultAttributesAll.next(); for (NamingEnumeration<?> namingEnumeration = attr.getAll(); namingEnumeration .hasMore();) { objectSid = (byte[]) namingEnumeration.next(); groupsSearchFilter.append("(objectSid=" + objectSidToString2(objectSid) + ")"); } groupsSearchFilter.append(")"); } } catch (NamingException e) { String msgStr = String.format("LDAP Listing Member Exception: %s", e.getMessage()); appLogger.error(msgStr, e); throw new NSException(msgStr); } } userSearchResponse.close(); // Finally, we will query each group in the search filter and add it to the table. SearchControls groupSearchControls = new SearchControls(); groupSearchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); int field = 0; int attrCount = aGroupBag.count(); String[] groupsReturnedAtts = new String[attrCount]; for (DataField complexField : aGroupBag.getFields()) { fieldName = complexField.getName(); groupsReturnedAtts[field++] = fieldName; } groupSearchControls.setReturningAttributes(groupsReturnedAtts); NamingEnumeration<?> groupSearchResponse = mLdapContext.search(groupSearchBaseDN, groupsSearchFilter.toString(), groupSearchControls); while ((groupSearchResponse != null) && (groupSearchResponse.hasMoreElements())) { SearchResult groupSearchResult = (SearchResult) groupSearchResponse.next(); Attributes groupResultAttributes = groupSearchResult.getAttributes(); if (groupResultAttributes != null) { groupBag = new DataBag(aGroupBag); for (DataField complexField : groupBag.getFields()) { fieldName = complexField.getName(); responseAttribute = groupResultAttributes.get(fieldName); if (responseAttribute != null) { if (fieldName.equals(LDAP_OBJECT_SID)) { objectSid = (byte[]) responseAttribute.get(); fieldValue = objectSidToString2(objectSid); } else fieldValue = (String) responseAttribute.get(); if (StringUtils.isNotEmpty(fieldValue)) complexField.setValue(fieldValue); } } memberTable.addRow(groupBag); } } if (groupSearchResponse != null) groupSearchResponse.close(); } } catch (NamingException e) { String msgStr = String.format("LDAP Search Error (%s): %s", distinguishedName, e.getMessage()); appLogger.error(msgStr, e); throw new NSException(msgStr); } appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART); return memberTable; }
From source file:org.apache.archiva.redback.common.ldap.role.DefaultLdapRoleMapper.java
public boolean removeUserRole(String roleName, String username, DirContext context) throws MappingException { String groupName = findGroupName(roleName); if (groupName == null) { log.warn("no group found for role '{}", roleName); return false; }/*from ww w. j av a 2 s . c o m*/ NamingEnumeration<SearchResult> namingEnumeration = null; try { SearchControls searchControls = new SearchControls(); searchControls.setDerefLinkFlag(true); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); String filter = "objectClass=" + getLdapGroupClass(); namingEnumeration = context.search("cn=" + groupName + "," + getGroupsDn(), filter, searchControls); while (namingEnumeration.hasMore()) { SearchResult searchResult = namingEnumeration.next(); Attribute attribute = searchResult.getAttributes().get(getLdapGroupMember()); if (attribute != null) { BasicAttribute basicAttribute = new BasicAttribute(getLdapGroupMember()); basicAttribute.add(this.userIdAttribute + "=" + username + "," + getGroupsDn()); context.modifyAttributes("cn=" + groupName + "," + getGroupsDn(), new ModificationItem[] { new ModificationItem(DirContext.REMOVE_ATTRIBUTE, basicAttribute) }); } return true; } return false; } catch (LdapException e) { throw new MappingException(e.getMessage(), e); } catch (NamingException e) { throw new MappingException(e.getMessage(), e); } finally { if (namingEnumeration != null) { try { namingEnumeration.close(); } catch (NamingException e) { log.warn("failed to close search results", e); } } } }
From source file:org.atricore.idbus.idojos.ldapidentitystore.LDAPIdentityStore.java
/** * Fetches the supplied user DN.//from w w w .ja v a2 s . c o m * * @param uid the user id * @return the user DN for the supplied uid * @throws NamingException LDAP error obtaining user information. */ protected String selectUserDN(InitialLdapContext ctx, String uid) throws NamingException { String dn = null; String principalUidAttrName = this.getPrincipalUidAttributeID(); String usersCtxDN = this.getUsersCtxDN(); try { // NamingEnumeration answer = ctx.search(usersCtxDN, matchAttrs, principalAttr); // This gives more control over search behavior : NamingEnumeration answer = ctx.search(usersCtxDN, "(&(" + principalUidAttrName + "=" + uid + "))", getSearchControls()); while (answer.hasMore()) { SearchResult sr = (SearchResult) answer.next(); Attributes attrs = sr.getAttributes(); Attribute uidAttr = attrs.get(principalUidAttrName); if (uidAttr == null) { logger.warn("Invalid user uid attribute '" + principalUidAttrName + "'"); continue; } String uidValue = uidAttr.get().toString(); if (uidValue != null) { dn = sr.getName() + "," + usersCtxDN; if (logger.isDebugEnabled()) logger.debug("Found user '" + principalUidAttrName + "=" + uidValue + "' for user '" + uid + "' DN=" + dn); } else { if (logger.isDebugEnabled()) logger.debug("User not found for user '" + uid + "'"); } } } catch (NamingException e) { if (logger.isDebugEnabled()) logger.debug("Failed to locate user", e); } return dn; }
From source file:org.apache.archiva.redback.common.ldap.role.DefaultLdapRoleMapper.java
public boolean saveUserRole(String roleName, String username, DirContext context) throws MappingException { String groupName = findGroupName(roleName); if (groupName == null) { log.warn("no group found for role '{}", roleName); groupName = roleName;//from w ww . ja va 2s .com } NamingEnumeration<SearchResult> namingEnumeration = null; try { SearchControls searchControls = new SearchControls(); searchControls.setDerefLinkFlag(true); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); String filter = "objectClass=" + getLdapGroupClass(); namingEnumeration = context.search("cn=" + groupName + "," + getGroupsDn(), filter, searchControls); while (namingEnumeration.hasMore()) { SearchResult searchResult = namingEnumeration.next(); Attribute attribute = searchResult.getAttributes().get(getLdapGroupMember()); if (attribute == null) { BasicAttribute basicAttribute = new BasicAttribute(getLdapGroupMember()); basicAttribute.add(this.userIdAttribute + "=" + username + "," + getBaseDn()); context.modifyAttributes("cn=" + groupName + "," + getGroupsDn(), new ModificationItem[] { new ModificationItem(DirContext.ADD_ATTRIBUTE, basicAttribute) }); } else { attribute.add(this.userIdAttribute + "=" + username + "," + getBaseDn()); context.modifyAttributes("cn=" + groupName + "," + getGroupsDn(), new ModificationItem[] { new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attribute) }); } return true; } return false; } catch (LdapException e) { throw new MappingException(e.getMessage(), e); } catch (NamingException e) { throw new MappingException(e.getMessage(), e); } finally { if (namingEnumeration != null) { try { namingEnumeration.close(); } catch (NamingException e) { log.warn("failed to close search results", e); } } } }
From source file:org.wso2.carbon.user.core.ldap.ActiveDirectoryUserStoreManager.java
@Override public void doSetUserClaimValue(String userName, String claimURI, String value, String profileName) throws UserStoreException { // get the LDAP Directory context DirContext dirContext = this.connectionSource.getContext(); DirContext subDirContext = null; // search the relevant user entry by user name String userSearchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); String userSearchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER); userSearchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName)); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningAttributes(null); NamingEnumeration<SearchResult> returnedResultList = null; String returnedUserEntry = null; try {/* w ww . j a va2 s.c o m*/ returnedResultList = dirContext.search(escapeDNForSearch(userSearchBase), userSearchFilter, searchControls); // assume only one user is returned from the search // TODO:what if more than one user is returned returnedUserEntry = returnedResultList.next().getName(); } catch (NamingException e) { String errorMessage = "Results could not be retrieved from the directory context for user : " + userName; if (logger.isDebugEnabled()) { logger.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeNamingEnumeration(returnedResultList); } try { Attributes updatedAttributes = new BasicAttributes(true); // if there is no attribute for profile configuration in LDAP, skip // updating it. // get the claimMapping related to this claimURI String attributeName = getClaimAtrribute(claimURI, userName, null); if ("CN".equals(attributeName)) { subDirContext = (DirContext) dirContext.lookup(userSearchBase); subDirContext.rename(returnedUserEntry, "CN=" + value); return; } Attribute currentUpdatedAttribute = new BasicAttribute(attributeName); /* if updated attribute value is null, remove its values. */ if (EMPTY_ATTRIBUTE_STRING.equals(value)) { currentUpdatedAttribute.clear(); } else { String claimSeparator = realmConfig.getUserStoreProperty(MULTI_ATTRIBUTE_SEPARATOR); if (claimSeparator != null && !claimSeparator.trim().isEmpty()) { userAttributeSeparator = claimSeparator; } if (value.contains(userAttributeSeparator)) { StringTokenizer st = new StringTokenizer(value, userAttributeSeparator); while (st.hasMoreElements()) { String newVal = st.nextElement().toString(); if (newVal != null && newVal.trim().length() > 0) { currentUpdatedAttribute.add(newVal.trim()); } } } else { currentUpdatedAttribute.add(value); } } updatedAttributes.put(currentUpdatedAttribute); // update the attributes in the relevant entry of the directory // store subDirContext = (DirContext) dirContext.lookup(userSearchBase); subDirContext.modifyAttributes(returnedUserEntry, DirContext.REPLACE_ATTRIBUTE, updatedAttributes); } catch (org.wso2.carbon.user.api.UserStoreException e) { String errorMessage = "Error in obtaining claim mapping for user : " + userName; if (logger.isDebugEnabled()) { logger.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } catch (NamingException e) { handleException(e, userName); } finally { JNDIUtil.closeContext(subDirContext); JNDIUtil.closeContext(dirContext); } }
From source file:com.wfp.utils.LDAPUtils.java
public static Map<String, Object> parseDataAsMap(NamingEnumeration searchResults, String listValues) { //Logger.info("Formatting the data as MAP", LDAPUtils.class); Map<String, Object> resultAttrMap = null; int totalResultLogger = 0; if (searchResults == null) { return null; }/*from www . j av a 2 s . c om*/ // 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 null; } Attributes attrs = sr.getAttributes(); if (attrs != null) { if (resultAttrMap == null) { resultAttrMap = new HashMap<String, Object>(); } try { for (NamingEnumeration ae = attrs.getAll(); ae.hasMore();) { Attribute attr = (Attribute) ae.next(); for (NamingEnumeration e = attr.getAll(); e.hasMore(); totalResultLogger++) { String attrValue = (String) e.next(); List<String> attrValuesList = null; if (listValues.indexOf(attr.getID()) >= 0) { attrValuesList = resultAttrMap.get(attr.getID()) == null ? null : (List<String>) resultAttrMap.get(attr.getID()); if (attrValuesList == null) { attrValuesList = new ArrayList<String>(); } attrValuesList.add(attrValue); resultAttrMap.put(attr.getID(), attrValuesList); } else { resultAttrMap.put(attr.getID(), attrValue); } } } } catch (NamingException e) { Logger.error("Error ocuring while reading the attributes ", LDAPUtils.class, e); } } else { Logger.info("No attributes found on LDAP", LDAPUtils.class); } } return resultAttrMap; }
From source file:de.fiz.ddb.aas.utils.LDAPEngineUtilityOrganisation.java
protected Organisation convertLdapOrganizationToOrganisation( NamingEnumeration<SearchResult> pOrganizationResult, NamingEnumeration<SearchResult> pPrivilegesResult) throws ExecutionException, NameNotFoundException { Organisation vOrganisation = null;//from www . j a v a 2s . co m try { if ((pOrganizationResult != null) && pOrganizationResult.hasMore()) { SearchResult sr = pOrganizationResult.next(); vOrganisation = convertSearchResultToOrganization(sr); // -- Organization privileges: vOrganisation = this.convertLdapGroupsToOrganizationPrivileges(vOrganisation, pPrivilegesResult); } } catch (NameNotFoundException ex) { LOG.log(Level.SEVERE, null, ex); throw ex; } catch (NamingException ne) { LOG.log(Level.SEVERE, null, ne); throw new ExecutionException(ne.getMessage(), ne.getCause()); } finally { // -- releases this context's resources immediately, instead of waiting for the garbage collector if (pOrganizationResult != null) { try { pOrganizationResult.close(); } catch (NamingException ex) { } } } return vOrganisation; }
From source file:org.atricore.idbus.idojos.ldapidentitystore.LDAPIdentityStore.java
/** * Obtain the properties for the user associated with the given uid using the * configured user properties query string. * * @param uid the user id of the user for whom its user properties are required. * @return the hash map containing user properties as name/value pairs. * @throws NamingException LDAP error obtaining user properties. *//* w w w. j a v a 2 s . co m*/ protected HashMap selectUserProperties(String uid) throws NamingException { HashMap userPropertiesResultSet = new HashMap(); InitialLdapContext ctx = createLdapInitialContext(); BasicAttributes matchAttrs = new BasicAttributes(true); String principalUidAttrName = this.getPrincipalUidAttributeID(); String usersCtxDN = this.getUsersCtxDN(); matchAttrs.put(principalUidAttrName, uid); String userPropertiesQueryString = getUserPropertiesQueryString(); HashMap userPropertiesQueryMap = parseQueryString(userPropertiesQueryString); Iterator i = userPropertiesQueryMap.keySet().iterator(); List propertiesAttrList = new ArrayList(); while (i.hasNext()) { String o = (String) i.next(); propertiesAttrList.add(o); } String[] propertiesAttr = (String[]) propertiesAttrList.toArray(new String[propertiesAttrList.size()]); try { // This gives more control over search behavior : NamingEnumeration answer = ctx.search(usersCtxDN, "(&(" + principalUidAttrName + "=" + uid + "))", getSearchControls()); while (answer.hasMore()) { SearchResult sr = (SearchResult) answer.next(); Attributes attrs = sr.getAttributes(); for (int j = 0; j < propertiesAttr.length; j++) { Attribute attribute = attrs.get(propertiesAttr[j]); if (attribute == null) { logger.warn("Invalid user property attribute '" + propertiesAttr[j] + "'"); continue; } Object propertyObject = attrs.get(propertiesAttr[j]).get(); if (propertyObject == null) { logger.warn("Found a 'null' value for user property '" + propertiesAttr[j] + "'"); continue; } String propertyValue = propertyObject.toString(); String propertyName = (String) userPropertiesQueryMap.get(propertiesAttr[j]); userPropertiesResultSet.put(propertyName, propertyValue); if (logger.isDebugEnabled()) logger.debug( "Found user property '" + propertyName + "' with value '" + propertyValue + "'"); } } } catch (NamingException e) { if (logger.isDebugEnabled()) logger.debug("Failed to locate user", e); } finally { // Close the context to release the connection ctx.close(); } return userPropertiesResultSet; }
From source file:de.fiz.ddb.aas.utils.LDAPEngineUtilityOrganisation.java
protected Organisation convertLdapGroupsToOrganizationPrivileges(Organisation pOrg, NamingEnumeration<SearchResult> pPrivilegesResult) throws ExecutionException { try {/*www.j a v a 2 s. c o m*/ if (pPrivilegesResult != null) { PrivilegeEnum p; SearchResult sr; String vCnPrivileg; // construct privileges while (pPrivilegesResult.hasMore()) { sr = pPrivilegesResult.next(); vCnPrivileg = (String) sr.getAttributes().get(Constants.ldap_ddbPrivilege_Cn).get(); p = this.mapToPrivilege(sr.getAttributes(), Constants.ldap_ddbPrivilege_Cn); if (p != null) { pOrg.addPrivileges(p); } else { LOG.log(Level.WARNING, "Die Organisation ''{0}'' verfgt ber einen nicht existierende Privileg: ''{1}''!", new Object[] { pOrg.getId(), vCnPrivileg }); } } // -- releases this context's resources immediately, instead of waiting for the garbage collector pPrivilegesResult.close(); } } catch (NamingException ne) { LOG.log(Level.SEVERE, null, ne); throw new ExecutionException(ne.getMessage(), ne.getCause()); } finally { // -- releases this context's resources immediately, instead of waiting for the garbage collector if (pPrivilegesResult != null) { try { pPrivilegesResult.close(); } catch (NamingException ex) { } } } return pOrg; }