List of usage examples for javax.naming.directory SearchResult getNameInNamespace
public String getNameInNamespace()
From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java
/** * Check whether user is in the group by searching through its member attributes. * * @param userDN DN of the User whose existence in the group is searched. * @param groupEntry SearchResult representation of the Group. * @return true if the user exists in the role, false otherwise. * @throws UserStoreException If an error occurs while retrieving data. *///from ww w.j av a 2 s. c o m protected boolean isUserInRole(String userDN, SearchResult groupEntry) throws UserStoreException { boolean isUserInRole = false; try { Attributes groupAttributes = groupEntry.getAttributes(); if (groupAttributes != null) { // get group's returned attributes NamingEnumeration attributes = groupAttributes.getAll(); // loop through attributes while (attributes.hasMoreElements()) { Attribute memberAttribute = (Attribute) attributes.next(); String memberAttributeName = userStoreProperties.get(LDAPConstants.MEMBERSHIP_ATTRIBUTE); if (memberAttributeName.equalsIgnoreCase(memberAttribute.getID())) { // loop through attribute values for (int i = 0; i < memberAttribute.size(); i++) { if (userDN.equalsIgnoreCase((String) memberAttribute.get(i))) { return true; } } } } attributes.close(); } } catch (NamingException e) { String errorMessage = "Error occurred while looping through attributes set of group: " + groupEntry.getNameInNamespace(); if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } return isUserInRole; }
From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java
/** * Check whether this is the last/only user in this group. * * @param userDN/*from w ww .j a v a 2 s. c o m*/ * @param groupEntry * @return groupContext */ @SuppressWarnings("rawtypes") protected boolean isOnlyUserInRole(String userDN, SearchResult groupEntry) throws UserStoreException { boolean isOnlyUserInRole = false; try { Attributes groupAttributes = groupEntry.getAttributes(); if (groupAttributes != null) { NamingEnumeration attributes = groupAttributes.getAll(); while (attributes.hasMoreElements()) { Attribute memberAttribute = (Attribute) attributes.next(); String memberAttributeName = realmConfig .getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE); String attributeID = memberAttribute.getID(); if (memberAttributeName.equals(attributeID)) { if (memberAttribute.size() == 1 && userDN.equals(memberAttribute.get())) { return true; } } } attributes.close(); } } catch (NamingException e) { String errorMessage = "Error occurred while looping through attributes set of group: " + groupEntry.getNameInNamespace(); if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } return isOnlyUserInRole; }
From source file:dk.magenta.ldap.LDAPMultiBaseUserRegistry.java
public String resolveDistinguishedName(String userId, AuthenticationDiagnostic diagnostic) throws AuthenticationException { if (logger.isDebugEnabled()) { logger.debug("resolveDistinguishedName userId:" + userId); }/*ww w. j a v a2s. c o m*/ SearchControls userSearchCtls = new SearchControls(); userSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Although we don't actually need any attributes, we ask for the UID for compatibility with Sun Directory Server. See ALF-3868 userSearchCtls.setReturningAttributes(new String[] { this.userIdAttributeName }); InitialDirContext ctx = null; for (String userSearchBase : this.userSearchBases) { String query = userSearchBase + "(&" + this.personQuery + "(" + this.userIdAttributeName + "= userId))"; NamingEnumeration<SearchResult> searchResults = null; SearchResult result = null; try { ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(diagnostic); // Execute the user query with an additional condition that ensures only the user with the required ID is // returned. Force RFC 2254 escaping of the user ID in the filter to avoid any manipulation searchResults = ctx.search(userSearchBase, "(&" + this.personQuery + "(" + this.userIdAttributeName + "={0}))", new Object[] { userId }, userSearchCtls); if (searchResults.hasMore()) { result = searchResults.next(); Attributes attributes = result.getAttributes(); Attribute uidAttribute = attributes.get(this.userIdAttributeName); if (uidAttribute == null) { if (this.errorOnMissingUID) { throw new AlfrescoRuntimeException( "User returned by user search does not have mandatory user id attribute " + attributes); } else { LDAPMultiBaseUserRegistry.logger .warn("User returned by user search does not have mandatory user id attribute " + attributes); } } // MNT:2597 We don't trust the LDAP server's treatment of whitespace, accented characters etc. We will // only resolve this user if the user ID matches else if (userId.equalsIgnoreCase((String) uidAttribute.get(0))) { String name = result.getNameInNamespace(); // Close the contexts, see ALF-20682 Context context = (Context) result.getObject(); if (context != null) { context.close(); } result = null; return name; } // Close the contexts, see ALF-20682 Context context = (Context) result.getObject(); if (context != null) { context.close(); } result = null; } } catch (NamingException e) { // Connection is good here - AuthenticationException would be thrown by ldapInitialContextFactory Object[] args1 = { userId, query }; diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_SEARCH, false, args1); } if (result != null) { try { Context context = (Context) result.getObject(); if (context != null) { context.close(); } } catch (Exception e) { logger.debug("error when closing result block context", e); } } if (searchResults != null) { try { searchResults.close(); } catch (Exception e) { logger.debug("error when closing searchResults context", e); } } } if (ctx != null) { try { ctx.close(); } catch (NamingException e) { logger.debug("error when closing ldap context", e); } } // failed to search // Object[] args = {e.getLocalizedMessage()}; throw new AuthenticationException("authentication.err.connection.ldap.search", diagnostic); }
From source file:org.alfresco.repo.security.sync.ldap.LDAPUserRegistry.java
public String resolveDistinguishedName(String userId, AuthenticationDiagnostic diagnostic) throws AuthenticationException { if (logger.isDebugEnabled()) { logger.debug("resolveDistinguishedName userId:" + userId); }//from w w w .java 2s .com SearchControls userSearchCtls = new SearchControls(); userSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Although we don't actually need any attributes, we ask for the UID for compatibility with Sun Directory Server. See ALF-3868 userSearchCtls.setReturningAttributes(new String[] { this.userIdAttributeName }); String query = this.userSearchBase + "(&" + this.personQuery + "(" + this.userIdAttributeName + "= userId))"; NamingEnumeration<SearchResult> searchResults = null; SearchResult result = null; InitialDirContext ctx = null; try { ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(diagnostic); // Execute the user query with an additional condition that ensures only the user with the required ID is // returned. Force RFC 2254 escaping of the user ID in the filter to avoid any manipulation searchResults = ctx.search(this.userSearchBase, "(&" + this.personQuery + "(" + this.userIdAttributeName + "={0}))", new Object[] { userId }, userSearchCtls); if (searchResults.hasMore()) { result = searchResults.next(); Attributes attributes = result.getAttributes(); Attribute uidAttribute = attributes.get(this.userIdAttributeName); if (uidAttribute == null) { if (this.errorOnMissingUID) { throw new AlfrescoRuntimeException( "User returned by user search does not have mandatory user id attribute " + attributes); } else { LDAPUserRegistry.logger .warn("User returned by user search does not have mandatory user id attribute " + attributes); } } // MNT:2597 We don't trust the LDAP server's treatment of whitespace, accented characters etc. We will // only resolve this user if the user ID matches else if (userId.equalsIgnoreCase((String) uidAttribute.get(0))) { String name = result.getNameInNamespace(); // Close the contexts, see ALF-20682 Context context = (Context) result.getObject(); if (context != null) { context.close(); } result = null; return name; } // Close the contexts, see ALF-20682 Context context = (Context) result.getObject(); if (context != null) { context.close(); } result = null; } Object[] args = { userId, query }; diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_LOOKUP_USER, false, args); throw new AuthenticationException("authentication.err.connection.ldap.user.notfound", args, diagnostic); } catch (NamingException e) { // Connection is good here - AuthenticationException would be thrown by ldapInitialContextFactory Object[] args1 = { userId, query }; diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_SEARCH, false, args1); // failed to search Object[] args = { e.getLocalizedMessage() }; throw new AuthenticationException("authentication.err.connection.ldap.search", diagnostic, args, e); } finally { if (result != null) { try { Context context = (Context) result.getObject(); if (context != null) { context.close(); } } catch (Exception e) { logger.debug("error when closing result block context", e); } } if (searchResults != null) { try { searchResults.close(); } catch (Exception e) { logger.debug("error when closing searchResults context", e); } } if (ctx != null) { try { ctx.close(); } catch (NamingException e) { logger.debug("error when closing ldap context", e); } } } }
From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java
/** * Check whether user is in the group by searching through its member attributes. * * @param userDN/*from ww w. j av a2 s . com*/ * @param groupEntry * @return * @throws UserStoreException */ protected boolean isUserInRole(String userDN, SearchResult groupEntry) throws UserStoreException { boolean isUserInRole = false; try { Attributes groupAttributes = groupEntry.getAttributes(); if (groupAttributes != null) { // get group's returned attributes NamingEnumeration attributes = groupAttributes.getAll(); // loop through attributes while (attributes.hasMoreElements()) { Attribute memberAttribute = (Attribute) attributes.next(); String memberAttributeName = realmConfig .getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE); if (memberAttributeName.equalsIgnoreCase(memberAttribute.getID())) { // loop through attribute values for (int i = 0; i < memberAttribute.size(); i++) { if (userDN.equalsIgnoreCase((String) memberAttribute.get(i))) { return true; } } } } attributes.close(); } } catch (NamingException e) { String errorMessage = "Error occurred while looping through attributes set of group: " + groupEntry.getNameInNamespace(); if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } return isUserInRole; }
From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java
/** * {@inheritDoc}/*from w w w . jav a2s .c om*/ */ @Override public String[] doGetUserListOfRole(String roleName, int maxItemLimit) throws UserStoreException { boolean debug = log.isDebugEnabled(); List<String> userList = new ArrayList<String>(); String[] names = new String[0]; int givenMax = CommonConstants.MAX_USER_ROLE_LIST; int searchTime = CommonConstants.MAX_SEARCH_TIME; try { givenMax = Integer.parseInt(userStoreProperties.get(CommonConstants.PROPERTY_MAX_USER_LIST)); } catch (Exception e) { givenMax = CommonConstants.MAX_USER_ROLE_LIST; } try { searchTime = Integer.parseInt(userStoreProperties.get(CommonConstants.PROPERTY_MAX_SEARCH_TIME)); } catch (Exception e) { searchTime = CommonConstants.MAX_SEARCH_TIME; } if (maxItemLimit <= 0 || maxItemLimit > givenMax) { maxItemLimit = givenMax; } DirContext dirContext = null; NamingEnumeration<SearchResult> answer = null; try { SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchCtls.setTimeLimit(searchTime); searchCtls.setCountLimit(maxItemLimit); String searchFilter = userStoreProperties.get(LDAPConstants.GROUP_NAME_LIST_FILTER); String roleNameProperty = userStoreProperties.get(LDAPConstants.GROUP_NAME_ATTRIBUTE); searchFilter = "(&" + searchFilter + "(" + roleNameProperty + "=" + escapeSpecialCharactersForFilter(roleName) + "))"; String membershipProperty = userStoreProperties.get(LDAPConstants.MEMBERSHIP_ATTRIBUTE); String returnedAtts[] = { membershipProperty }; searchCtls.setReturningAttributes(returnedAtts); List<String> userDNList = new ArrayList<String>(); SearchResult sr = null; dirContext = connectionSource.getContext(); // handling multiple search bases String searchBases = userStoreProperties.get(LDAPConstants.GROUP_SEARCH_BASE); String[] roleSearchBaseArray = searchBases.split("#"); for (String searchBase : roleSearchBaseArray) { if (debug) { log.debug("Searching role: " + roleName + " SearchBase: " + searchBase + " SearchFilter: " + searchFilter); } try { // read the DN of users who are members of the group answer = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchCtls); int count = 0; if (answer.hasMore()) { // to check if there is a result while (answer.hasMore()) { // to check if there are more than one group if (count > 0) { throw new UserStoreException("More than one group exist with name"); } sr = answer.next(); count++; } break; } } catch (NamingException e) { // ignore if (log.isDebugEnabled()) { log.debug(e); } } } if (debug) { log.debug("Found role: " + sr.getNameInNamespace()); } // read the member attribute and get DNs of the users Attributes attributes = sr.getAttributes(); if (attributes != null) { NamingEnumeration attributeEntry = null; for (attributeEntry = attributes.getAll(); attributeEntry.hasMore();) { Attribute valAttribute = (Attribute) attributeEntry.next(); if (membershipProperty.equals(valAttribute.getID())) { NamingEnumeration values = null; for (values = valAttribute.getAll(); values.hasMore();) { String value = values.next().toString(); if (userDNList.size() >= maxItemLimit) { break; } userDNList.add(value); if (debug) { log.debug("Found attribute: " + membershipProperty + " value: " + value); } } } } } if (MEMBER_UID.equals(userStoreProperties.get(LDAPConstants.MEMBERSHIP_ATTRIBUTE))) { /* when the GroupEntryObjectClass is posixGroup, membership attribute is memberUid. We have to retrieve the DN using the memberUid. This procedure has to make an extra call to ldap. alternatively this can be done with a single ldap search using the memberUid and retrieving the display name and username. */ List<String> userDNListNew = new ArrayList<>(); for (String user : userDNList) { String userDN = getNameInSpaceForUserName(user); userDNListNew.add(userDN); } userDNList = userDNListNew; } // iterate over users' DN list and get userName and display name // attribute values String userNameProperty = userStoreProperties.get(LDAPConstants.USER_NAME_ATTRIBUTE); String displayNameAttribute = userStoreProperties.get(LDAPConstants.DISPLAY_NAME_ATTRIBUTE); String[] returnedAttributes = { userNameProperty, displayNameAttribute }; for (String user : userDNList) { if (debug) { log.debug("Getting name attributes of: " + user); } Attributes userAttributes; try { // '\' and '"' characters need another level of escaping before searching userAttributes = dirContext.getAttributes(escapeDNForSearch(user), returnedAttributes); String displayName = null; String userName = null; if (userAttributes != null) { Attribute userNameAttribute = userAttributes.get(userNameProperty); if (userNameAttribute != null) { userName = (String) userNameAttribute.get(); if (debug) { log.debug("UserName: " + userName); } } if (org.apache.commons.lang.StringUtils.isNotEmpty(displayNameAttribute)) { Attribute displayAttribute = userAttributes.get(displayNameAttribute); if (displayAttribute != null) { displayName = (String) displayAttribute.get(); } if (debug) { log.debug("DisplayName: " + displayName); } } } // Username will be null in the special case where the // username attribute has changed to another // and having different userNameProperty than the current // user-mgt.xml if (userName != null) { user = UserStoreUtils.getCombinedName(userName, displayName); userList.add(user); if (debug) { log.debug(user + " is added to the result list"); } } else { if (log.isDebugEnabled()) { log.debug( "User " + user + " doesn't have the user name property : " + userNameProperty); } } } catch (NamingException e) { if (log.isDebugEnabled()) { log.debug("Error in reading user information in the user store for the user " + user + e.getMessage(), e); } } } names = userList.toArray(new String[userList.size()]); } catch (PartialResultException e) { // can be due to referrals in AD. so just ignore error String errorMessage = "Error in reading user information in the user store"; if (isIgnorePartialResultException()) { if (log.isDebugEnabled()) { log.debug(errorMessage, e); } } else { throw new UserStoreException(errorMessage, e); } } catch (NamingException e) { String errorMessage = "Error in reading user information in the user store"; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeContext(dirContext); } return names; }
From source file:org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.java
/** * Returns the list of role names for the given search base and other * parameters//from www . j ava 2s .co m * * @param searchTime * @param filter * @param maxItemLimit * @param searchFilter * @param roleNameProperty * @param searchBase * @param appendTenantDomain * @return * @throws UserStoreException */ protected List<String> getLDAPRoleNames(int searchTime, String filter, int maxItemLimit, String searchFilter, String roleNameProperty, String searchBase, boolean appendTenantDomain) throws UserStoreException { boolean debug = log.isDebugEnabled(); List<String> roles = new ArrayList<String>(); SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchCtls.setCountLimit(maxItemLimit); searchCtls.setTimeLimit(searchTime); String returnedAtts[] = { roleNameProperty }; searchCtls.setReturningAttributes(returnedAtts); // / search filter TODO StringBuffer finalFilter = new StringBuffer(); finalFilter.append("(&").append(searchFilter).append("(").append(roleNameProperty).append("=") .append(escapeSpecialCharactersForFilterWithStarAsRegex(filter)).append("))"); if (debug) { log.debug("Listing roles. SearchBase: " + searchBase + " ConstructedFilter: " + finalFilter.toString()); } DirContext dirContext = null; NamingEnumeration<SearchResult> answer = null; try { dirContext = connectionSource.getContext(); answer = dirContext.search(escapeDNForSearch(searchBase), finalFilter.toString(), searchCtls); // append the domain if exist String domain = this.getRealmConfiguration() .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME); while (answer.hasMoreElements()) { SearchResult sr = (SearchResult) answer.next(); if (sr.getAttributes() != null) { Attribute attr = sr.getAttributes().get(roleNameProperty); if (attr != null) { String name = (String) attr.get(); name = UserCoreUtil.addDomainToName(name, domain); if (appendTenantDomain) { String dn = sr.getNameInNamespace(); name = UserCoreUtil.addTenantDomainToEntry(name, getTenantDomainFromRoleDN(dn, name)); } roles.add(name); } } } } catch (PartialResultException e) { // can be due to referrals in AD. so just ignore error String errorMessage = "Error occurred while getting LDAP role names. SearchBase: " + searchBase + " ConstructedFilter: " + finalFilter.toString(); if (isIgnorePartialResultException()) { if (log.isDebugEnabled()) { log.debug(errorMessage, e); } } else { throw new UserStoreException(errorMessage, e); } } catch (NamingException e) { String errorMessage = "Error occurred while getting LDAP role names. SearchBase: " + searchBase + " ConstructedFilter: " + finalFilter.toString(); if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeContext(dirContext); } if (debug) { Iterator<String> rolesIte = roles.iterator(); while (rolesIte.hasNext()) { log.debug("result: " + rolesIte.next()); } } return roles; }
From source file:org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.java
/** * @param userName/*from ww w . ja va2s . co m*/ * @param searchBase * @param searchFilter * @return * @throws UserStoreException */ protected String getNameInSpaceForUserName(String userName, String searchBase, String searchFilter) throws UserStoreException { boolean debug = log.isDebugEnabled(); String userDN = null; DirContext dirContext = this.connectionSource.getContext(); NamingEnumeration<SearchResult> answer = null; try { SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); if (log.isDebugEnabled()) { try { log.debug("Searching for user with SearchFilter: " + searchFilter + " in SearchBase: " + dirContext.getNameInNamespace()); } catch (NamingException e) { log.debug("Error while getting DN of search base", e); } } SearchResult userObj = null; String[] searchBases = searchBase.split("#"); for (String base : searchBases) { answer = dirContext.search(escapeDNForSearch(base), searchFilter, searchCtls); if (answer.hasMore()) { userObj = (SearchResult) answer.next(); if (userObj != null) { //no need to decode since , if decoded the whole string, can't be encoded again //eg CN=Hello\,Ok=test\,test, OU=Industry userDN = userObj.getNameInNamespace(); break; } } } if (userDN != null) { LdapName ldn = new LdapName(userDN); userCache.put(userName, ldn); } if (debug) { log.debug("Name in space for " + userName + " is " + userDN); } } catch (Exception e) { log.debug(e.getMessage(), e); } finally { JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeContext(dirContext); } return userDN; }
From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java
@Override public void doUpdateCredentialByAdmin(String userName, Object newCredential) throws UserStoreException { DirContext dirContext = this.connectionSource.getContext(); DirContext subDirContext = null; // first search the existing user entry. String searchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); String searchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER); searchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(userName)); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningAttributes(new String[] { "userPassword" }); NamingEnumeration<SearchResult> namingEnumeration = null; NamingEnumeration passwords = null; try {// w w w. ja va2 s . c om namingEnumeration = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchControls); // here we assume only one user // TODO: what to do if there are more than one user // there can be only only on user SearchResult searchResult = null; while (namingEnumeration.hasMore()) { searchResult = namingEnumeration.next(); String passwordHashMethod = realmConfig.getUserStoreProperty(PASSWORD_HASH_METHOD); if (!UserCoreConstants.RealmConfig.PASSWORD_HASH_METHOD_PLAIN_TEXT .equalsIgnoreCase(passwordHashMethod)) { Attributes attributes = searchResult.getAttributes(); Attribute userPassword = attributes.get("userPassword"); // When admin changes other user passwords he do not have to // provide the old password. Here it is only possible to have one password, if there // are more every one should match with the given old password passwords = userPassword.getAll(); if (passwords.hasMore()) { byte[] byteArray = (byte[]) passwords.next(); String password = new String(byteArray); if (password.startsWith("{")) { passwordHashMethod = password.substring(password.indexOf('{') + 1, password.indexOf('}')); } } } String dnName = searchResult.getName(); subDirContext = (DirContext) dirContext.lookup(searchBase); Attribute passwordAttribute = new BasicAttribute("userPassword"); passwordAttribute.add( UserCoreUtil.getPasswordToStore((String) newCredential, passwordHashMethod, kdcEnabled)); BasicAttributes basicAttributes = new BasicAttributes(true); basicAttributes.put(passwordAttribute); subDirContext.modifyAttributes(dnName, DirContext.REPLACE_ATTRIBUTE, basicAttributes); } // we check whether both carbon admin entry and ldap connection // entry are the same if (searchResult.getNameInNamespace() .equals(realmConfig.getUserStoreProperty(LDAPConstants.CONNECTION_NAME))) { this.connectionSource.updateCredential((String) newCredential); } } catch (NamingException e) { String errorMessage = "Can not access the directory service for user : " + userName; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeNamingEnumeration(passwords); JNDIUtil.closeNamingEnumeration(namingEnumeration); JNDIUtil.closeContext(subDirContext); JNDIUtil.closeContext(dirContext); } }
From source file:org.nuxeo.ecm.directory.ldap.LDAPSession.java
protected DocumentModel ldapResultToDocumentModel(SearchResult result, String entryId, boolean fetchReferences) throws DirectoryException, NamingException { Attributes attributes = result.getAttributes(); String passwordFieldId = getPasswordField(); Map<String, Object> fieldMap = new HashMap<String, Object>(); Attribute attribute = attributes.get(idAttribute); // NXP-2461: check that id field is filled + NXP-2730: make sure that // entry id is the one returned from LDAP if (attribute != null) { Object entry = attribute.get(); if (entry != null) { entryId = entry.toString();/* w ww. j a va2 s. com*/ } } // NXP-7136 handle id case entryId = changeEntryIdCase(entryId, idCase); if (entryId == null) { // don't bother return null; } for (String fieldName : schemaFieldMap.keySet()) { List<Reference> references = directory.getReferences(fieldName); if (references != null && references.size() > 0) { if (fetchReferences) { Map<String, List<String>> referencedIdsMap = new HashMap<>(); for (Reference reference : references) { // reference resolution List<String> referencedIds; if (reference instanceof LDAPReference) { // optim: use the current LDAPSession directly to // provide the LDAP reference with the needed backend entries LDAPReference ldapReference = (LDAPReference) reference; referencedIds = ldapReference.getLdapTargetIds(attributes); } else if (reference instanceof LDAPTreeReference) { // TODO: optimize using the current LDAPSession // directly to provide the LDAP reference with the // needed backend entries (needs to implement getLdapTargetIds) LDAPTreeReference ldapReference = (LDAPTreeReference) reference; referencedIds = ldapReference.getTargetIdsForSource(entryId); } else { referencedIds = reference.getTargetIdsForSource(entryId); } referencedIds = new ArrayList<>(referencedIds); Collections.sort(referencedIds); if (referencedIdsMap.containsKey(fieldName)) { referencedIdsMap.get(fieldName).addAll(referencedIds); } else { referencedIdsMap.put(fieldName, referencedIds); } } fieldMap.put(fieldName, referencedIdsMap.get(fieldName)); } } else { // manage directly stored fields String attributeId = getDirectory().getFieldMapper().getBackendField(fieldName); if (attributeId.equals(LDAPDirectory.DN_SPECIAL_ATTRIBUTE_KEY)) { // this is the special DN readonly attribute try { fieldMap.put(fieldName, result.getNameInNamespace()); } catch (UnsupportedOperationException e) { // ignore ApacheDS partial implementation when running // in embedded mode } } else { // this is a regular attribute attribute = attributes.get(attributeId); if (fieldName.equals(passwordFieldId)) { // do not try to fetch the password attribute continue; } else { fieldMap.put(fieldName, getFieldValue(attribute, fieldName, entryId, fetchReferences)); } } } } // check if the idAttribute was returned from the search. If not // set it anyway, maybe changing its case if it's a String instance String fieldId = getDirectory().getFieldMapper().getDirectoryField(idAttribute); Object obj = fieldMap.get(fieldId); if (obj == null) { fieldMap.put(fieldId, changeEntryIdCase(entryId, getDirectory().getDescriptor().getMissingIdFieldCase())); } else if (obj instanceof String) { fieldMap.put(fieldId, changeEntryIdCase((String) obj, idCase)); } return fieldMapToDocumentModel(fieldMap); }