List of usage examples for javax.naming NamingEnumeration next
public T next() throws NamingException;
From source file:org.apache.archiva.redback.common.ldap.role.DefaultLdapRoleMapper.java
public List<String> getGroupsMember(String group, DirContext context) throws MappingException { NamingEnumeration<SearchResult> namingEnumeration = null; try {/*from w w w. j a v a2s . c o m*/ SearchControls searchControls = new SearchControls(); searchControls.setDerefLinkFlag(true); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); String filter = "objectClass=" + getLdapGroupClass(); namingEnumeration = context.search("cn=" + group + "," + getGroupsDn(), filter, searchControls); List<String> allMembers = new ArrayList<String>(); while (namingEnumeration.hasMore()) { SearchResult searchResult = namingEnumeration.next(); Attribute uniqueMemberAttr = searchResult.getAttributes().get(getLdapGroupMember()); 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, ","); log.debug("found userName for group {}: '{}", group, userName); allMembers.add(userName); } close(allMembersEnum); } } return allMembers; } catch (LdapException e) { throw new MappingException(e.getMessage(), e); } catch (NamingException e) { throw new MappingException(e.getMessage(), e); } finally { close(namingEnumeration); } }
From source file:org.atricore.idbus.idojos.ldapidentitystore.LDAPIdentityStore.java
/** * Fetch the Ldap user attributes to be used as credentials. * * @param uid the user id for whom credentials are required * @return the hash map containing user credentials as name/value pairs * @throws NamingException LDAP error obtaining user credentials. *//* w w w . j a v a 2s . com*/ protected HashMap selectCredentials(String uid) throws NamingException { HashMap credentialResultSet = new HashMap(); InitialLdapContext ctx = createLdapInitialContext(); String principalUidAttrName = this.getPrincipalUidAttributeID(); String usersCtxDN = this.getUsersCtxDN(); // BasicAttributes matchAttrs = new BasicAttributes(true); // matchAttrs.put(principalUidAttrName, uid); String credentialQueryString = getCredentialQueryString(); HashMap credentialQueryMap = parseQueryString(credentialQueryString); Iterator i = credentialQueryMap.keySet().iterator(); List credentialAttrList = new ArrayList(); while (i.hasNext()) { String o = (String) i.next(); credentialAttrList.add(o); } String[] credentialAttr = (String[]) credentialAttrList.toArray(new String[credentialAttrList.size()]); try { // NamingEnumeration answer = ctx.search(usersCtxDN, matchAttrs, credentialAttr); // 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 < credentialAttr.length; j++) { Object credentialObject = attrs.get(credentialAttr[j]).get(); String credentialName = (String) credentialQueryMap.get(credentialAttr[j]); String credentialValue = null; if (logger.isDebugEnabled()) logger.debug("Found user credential '" + credentialName + "' of type '" + credentialObject.getClass().getName() + "" + (credentialObject.getClass().isArray() ? "[" + Array.getLength(credentialObject) + "]" : "") + "'"); // if the attribute value is an array, cast it to byte[] and then convert to // String using proper encoding if (credentialObject.getClass().isArray()) { try { // Try to create a UTF-8 String, we use java.nio to handle errors in a better way. // If the byte[] cannot be converted to UTF-8, we're using the credentialObject as is. byte[] credentialData = (byte[]) credentialObject; ByteBuffer in = ByteBuffer.allocate(credentialData.length); in.put(credentialData); in.flip(); Charset charset = Charset.forName("UTF-8"); CharsetDecoder decoder = charset.newDecoder(); CharBuffer charBuffer = decoder.decode(in); credentialValue = charBuffer.toString(); } catch (CharacterCodingException e) { if (logger.isDebugEnabled()) logger.debug("Can't convert credential value to String using UTF-8"); } } else if (credentialObject instanceof String) { // The credential value must be a String ... credentialValue = (String) credentialObject; } // Check what do we have ... if (credentialValue != null) { // Remove any schema information from the credential value, like the {md5} prefix for passwords. credentialValue = getSchemeFreeValue(credentialValue); credentialResultSet.put(credentialName, credentialValue); } else { // We have a binary credential, leave it as it is ... probably binary value. credentialResultSet.put(credentialName, credentialObject); } if (logger.isDebugEnabled()) logger.debug("Found user credential '" + credentialName + "' with value '" + (credentialValue != null ? credentialValue : credentialObject) + "'"); } } } catch (NamingException e) { if (logger.isDebugEnabled()) logger.debug("Failed to locate user", e); } finally { // Close the context to release the connection ctx.close(); } return credentialResultSet; }
From source file:de.fiz.ddb.aas.utils.LDAPEngineUtilityOrganisation.java
public Set<OIDs> getAllSubOrgIds(boolean pLicensedOrgs, OIDs pOIDs, int pScopy, AasPrincipal pPerformer) throws ExecutionException { Set<OIDs> vSetOIDs = new HashSet<OIDs>(); NamingEnumeration<SearchResult> searchResults = null; try {/* ww w .j av a 2 s . com*/ searchResults = getAllSubOrgs(pLicensedOrgs, pOIDs, pScopy, new String[] { Constants.ldap_ddbOrg_Id, Constants.ldap_ddbOrg_PID, "+" }, pPerformer); SearchResult sr; Attribute attr; while (searchResults.hasMore()) { sr = searchResults.next(); if ((attr = sr.getAttributes().get(Constants.ldap_ddb_EntryDN)) != null) { vSetOIDs.add(new OIDs(String.valueOf(attr.get()), (attr = sr.getAttributes().get(Constants.ldap_ddbOrg_PID)) != null ? String.valueOf(attr.get()) : null)); } else { throw new ExecutionException("entryDN = null : OIDs = " + pOIDs, null); } } } catch (IllegalAccessException ex) { LOG.log(Level.SEVERE, "Connection-Error", ex); throw new ExecutionException(ex.getMessage(), ex.getCause()); } catch (NamingException ne) { LOG.log(Level.SEVERE, "NamingException", ne); throw new ExecutionException(ne.getMessage(), ne.getCause()); } finally { if (searchResults != null) { try { searchResults.close(); searchResults = null; } catch (NamingException ex) { } } } return vSetOIDs; }
From source file:org.infoscoop.account.ldap.LDAPAccountManager.java
public IAccount getUser(String uid) throws NamingException { SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration searchResultEnum; Map filters = new HashMap(); String uidAttrName = "uid"; if (this.propAttrMap.containsKey("user_id")) { try {// w ww . ja va2s .c om uidAttrName = (String) this.propAttrMap.get("user_id"); } catch (Exception ex) { //ignore } } if (uid != null && !"".equals(uid)) filters.put(uidAttrName, uid); DirContext context = null; try { context = this.initContext(); searchResultEnum = context.search(userBase, buildFilterByUid(filters), searchControls); //roop of retrieval result while (searchResultEnum.hasMore()) { SearchResult searchResult = (SearchResult) searchResultEnum.next(); String dn = searchResult.getName() + "," + userBase; LDAPAccount user = createLDAPUser(dn, searchResult.getAttributes()); setGroup(context, user); return user; } return null; } finally { if (context != null) context.close(); } }
From source file:org.nuxeo.ecm.directory.ldap.LDAPSession.java
@SuppressWarnings("unchecked") protected List<String> getMandatoryAttributes(Attribute objectClassesAttribute) throws DirectoryException { try {/*from w ww .j a v a 2 s. c o m*/ List<String> mandatoryAttributes = new ArrayList<String>(); DirContext schema = dirContext.getSchema(""); List<String> objectClasses = new ArrayList<String>(); if (objectClassesAttribute == null) { // use the creation classes as reference schema for this entry objectClasses.addAll(Arrays.asList(getDirectory().getDescriptor().getCreationClasses())); } else { // introspec the objectClass definitions to find the mandatory // attributes for this entry NamingEnumeration<Object> values = null; try { values = (NamingEnumeration<Object>) objectClassesAttribute.getAll(); while (values.hasMore()) { objectClasses.add(values.next().toString().trim()); } } catch (NamingException e) { throw new DirectoryException(e); } finally { if (values != null) { values.close(); } } } objectClasses.remove("top"); for (String creationClass : objectClasses) { Attributes attributes = schema.getAttributes("ClassDefinition/" + creationClass); Attribute attribute = attributes.get("MUST"); if (attribute != null) { NamingEnumeration<String> values = (NamingEnumeration<String>) attribute.getAll(); try { while (values.hasMore()) { String value = values.next(); mandatoryAttributes.add(value); } } finally { values.close(); } } } return mandatoryAttributes; } catch (NamingException e) { throw new DirectoryException("getMandatoryAttributes failed", e); } }
From source file:org.nuxeo.ecm.directory.ldap.LDAPSession.java
@SuppressWarnings("unchecked") protected Object getFieldValue(Attribute attribute, String fieldName, String entryId, boolean fetchReferences) throws DirectoryException { Field field = schemaFieldMap.get(fieldName); Type type = field.getType();/* www .j ava2 s. co m*/ Object defaultValue = field.getDefaultValue(); String typeName = type.getName(); if (attribute == null) { return defaultValue; } Object value; try { value = attribute.get(); } catch (NamingException e) { throw new DirectoryException("Could not fetch value for " + attribute, e); } if (value == null) { return defaultValue; } String trimmedValue = value.toString().trim(); if ("string".equals(typeName)) { return trimmedValue; } else if ("integer".equals(typeName) || "long".equals(typeName)) { if ("".equals(trimmedValue)) { return defaultValue; } try { return Long.valueOf(trimmedValue); } catch (NumberFormatException e) { log.error(String.format( "field %s of type %s has non-numeric value found on server: '%s' (ignoring and using default value instead)", fieldName, typeName, trimmedValue)); return defaultValue; } } else if (type.isListType()) { List<String> parsedItems = new LinkedList<String>(); NamingEnumeration<Object> values = null; try { values = (NamingEnumeration<Object>) attribute.getAll(); while (values.hasMore()) { parsedItems.add(values.next().toString().trim()); } return parsedItems; } catch (NamingException e) { log.error(String.format( "field %s of type %s has non list value found on server: '%s' (ignoring and using default value instead)", fieldName, typeName, values != null ? values.toString() : trimmedValue)); return defaultValue; } finally { if (values != null) { try { values.close(); } catch (NamingException e) { log.error(e, e); } } } } else if ("date".equals(typeName)) { if ("".equals(trimmedValue)) { return defaultValue; } try { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss'Z'"); dateFormat.setTimeZone(new SimpleTimeZone(0, "Z")); Date date = dateFormat.parse(trimmedValue); Calendar cal = Calendar.getInstance(); cal.setTime(date); return cal; } catch (ParseException e) { log.error(String.format( "field %s of type %s has invalid value found on server: '%s' (ignoring and using default value instead)", fieldName, typeName, trimmedValue)); return defaultValue; } } else if ("content".equals(typeName)) { return Blobs.createBlob((byte[]) value); } else { throw new DirectoryException("Field type not supported in directories: " + typeName); } }
From source file:org.nuxeo.ecm.directory.ldap.LDAPSession.java
protected DocumentModelList ldapResultsToDocumentModels(NamingEnumeration<SearchResult> results, boolean fetchReferences) throws DirectoryException, NamingException { DocumentModelListImpl list = new DocumentModelListImpl(); try {//w w w.j a v a2 s . c o m while (results.hasMore()) { SearchResult result = results.next(); DocumentModel entry = ldapResultToDocumentModel(result, null, fetchReferences); if (entry != null) { list.add(entry); } } } catch (SizeLimitExceededException e) { if (list.isEmpty()) { // the server did no send back the truncated results set, // re-throw the exception to that the user interface can display // the error message throw e; } // mark the collect results as a truncated result list log.debug("SizeLimitExceededException caught," + " return truncated results. Original message: " + e.getMessage() + " explanation: " + e.getExplanation()); list.setTotalSize(-2); } finally { results.close(); } log.debug("LDAP search returned " + list.size() + " results"); return list; }
From source file:com.wfp.utils.LDAPUtils.java
@SuppressWarnings("unchecked") public static Map<String, Map<String, String>> parseDataAsMap(NamingEnumeration searchResults, String optionalKey, String uniqueKey, String[] attrArray) { Logger.debug("Formatting the data as MAP", LDAPUtils.class); Map<String, Map<String, String>> resultMap = null; int totalResultLogger = 0; if (searchResults == null) { return null; }//from w ww . 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 (resultMap == null) { resultMap = new HashMap<String, Map<String, String>>(); } try { Map<String, String> resultAttrMap = new HashMap(); for (String attr : attrArray) { if (resultAttrMap.get(attr) == null) { attrs.get(attr); resultAttrMap.put(attr, ""); } } 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(); //if it is external id if (attr.getID().equals(EXTERNAL_ID)) { if (attrValue.contains(COMPASS_ID)) { resultAttrMap.put(attr.getID(), attrValue.replace(COMPASS_ID, "")); break; } else resultAttrMap.put(attr.getID(), "inValidFormat"); } resultAttrMap.put(attr.getID(), attrValue); } } if (optionalKey != null && !StringUtils.isNull(resultAttrMap.get(optionalKey))) { resultMap.put(resultAttrMap.get(optionalKey), resultAttrMap); } else { resultAttrMap.put("compasId", ""); resultMap.put(resultAttrMap.get(uniqueKey), resultAttrMap); } } 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 resultMap; }
From source file:de.fiz.ddb.aas.utils.LDAPEngineUtility.java
/** * get attribute values of given resource and attributes. * // ww w .ja v a 2 s.c o m * @param scope * scope * @param id * id of resource * @param attributeName * attribute-name to retrieve * * @return String attribute value * @throws NamingException * @throws IllegalAccessException */ public Map<String, String> getResourceAttributes(Scope scope, String id, String[] attributeNames) throws NamingException, IllegalAccessException { Map<String, String> returnMap = new HashMap<String, String>(); String baseDn = null; String filter = getIdFilter(scope, id); int levelScope = 0; InitialLdapContext ctx = null; NamingEnumeration<SearchResult> results = null; if (scope == Scope.ORGANIZATION) { baseDn = LDAPConnector.getSingletonInstance().getInstitutionBaseDN(); levelScope = SearchControls.SUBTREE_SCOPE; } else if (scope == Scope.PERSON) { baseDn = LDAPConnector.getSingletonInstance().getPersonBaseDN(); levelScope = SearchControls.ONELEVEL_SCOPE; } try { ctx = LDAPConnector.getSingletonInstance().takeCtx(); results = query(ctx, baseDn, filter, attributeNames, levelScope); if (results.hasMore()) { SearchResult searchResult = results.next(); if (results.hasMore()) { throw new IllegalAccessException("found more than one object with id=" + id); } Attributes attributes = searchResult.getAttributes(); for (int i = 0; i < attributeNames.length; i++) { Attribute attribute = attributes.get(attributeNames[i]); if (attribute == null) { returnMap.put(attributeNames[i], (String) null); } else { returnMap.put(attributeNames[i], (String) attribute.get()); } } return returnMap; } else { throw new NameNotFoundException("id not found"); } } finally { if (ctx != null) { try { LDAPConnector.getSingletonInstance().putCtx(ctx); } catch (IllegalAccessException ex) { LOG.log(Level.SEVERE, null, ex); } } if (results != null) { try { results.close(); } catch (NamingException e) { LOG.log(Level.WARNING, null, e); } } } }
From source file:org.wso2.carbon.user.core.ldap.ActiveDirectoryUserStoreManager.java
/** * This method overwrites the method in LDAPUserStoreManager. This implements the functionality * of updating user's profile information in LDAP user store. * * @param userName//from ww w .j ava2 s .com * @param claims * @param profileName * @throws org.wso2.carbon.user.core.UserStoreException */ @Override public void doSetUserClaimValues(String userName, Map<String, String> claims, 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); // if user name contains domain name, remove domain name String[] userNames = userName.split(CarbonConstants.DOMAIN_SEPARATOR); if (userNames.length > 1) { userName = userNames[1]; } userSearchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName)); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningAttributes(null); NamingEnumeration<SearchResult> returnedResultList = null; String returnedUserEntry = null; boolean cnModified = false; String cnValue = null; try { 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); } if (profileName == null) { profileName = UserCoreConstants.DEFAULT_PROFILE; } if (claims.get(UserCoreConstants.PROFILE_CONFIGURATION) == null) { claims.put(UserCoreConstants.PROFILE_CONFIGURATION, UserCoreConstants.DEFAULT_PROFILE_CONFIGURATION); } try { Attributes updatedAttributes = new BasicAttributes(true); String domainName = userName.indexOf(UserCoreConstants.DOMAIN_SEPARATOR) > -1 ? userName.split(UserCoreConstants.DOMAIN_SEPARATOR)[0] : realmConfig.getUserStoreProperty(UserStoreConfigConstants.DOMAIN_NAME); for (Map.Entry<String, String> claimEntry : claims.entrySet()) { String claimURI = claimEntry.getKey(); // if there is no attribute for profile configuration in LDAP, // skip updating it. if (claimURI.equals(UserCoreConstants.PROFILE_CONFIGURATION)) { continue; } // get the claimMapping related to this claimURI String attributeName = getClaimAtrribute(claimURI, userName, null); //remove user DN from cache if changing username attribute if (realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE).equals(attributeName)) { userCache.remove(userName); } // if mapped attribute is CN, then skip treating as a modified // attribute - // it should be an object rename if ("CN".toLowerCase().equals(attributeName.toLowerCase())) { cnModified = true; cnValue = claimEntry.getValue(); continue; } Attribute currentUpdatedAttribute = new BasicAttribute(attributeName); /* if updated attribute value is null, remove its values. */ if (EMPTY_ATTRIBUTE_STRING.equals(claimEntry.getValue())) { currentUpdatedAttribute.clear(); } else { if (claimEntry.getValue() != null) { String claimSeparator = realmConfig.getUserStoreProperty(MULTI_ATTRIBUTE_SEPARATOR); if (claimSeparator != null && !claimSeparator.trim().isEmpty()) { userAttributeSeparator = claimSeparator; } if (claimEntry.getValue().contains(userAttributeSeparator)) { StringTokenizer st = new StringTokenizer(claimEntry.getValue(), userAttributeSeparator); while (st.hasMoreElements()) { String newVal = st.nextElement().toString(); if (newVal != null && newVal.trim().length() > 0) { currentUpdatedAttribute.add(newVal.trim()); } } } else { currentUpdatedAttribute.add(claimEntry.getValue()); } } else { currentUpdatedAttribute.add(claimEntry.getValue()); } } 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); if (cnModified && cnValue != null) { subDirContext.rename(returnedUserEntry, "CN=" + escapeSpecialCharactersForDN(cnValue)); } } 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); } }