List of usage examples for javax.naming.directory SearchControls SearchControls
public SearchControls()
From source file:com.aurel.track.util.LdapUtil.java
/** * Gets the LDAP users/*from ww w .j a v a 2 s . co m*/ * * @param ctx * @param loginAttributeName * @param searchStrs * @return */ static List<TPersonBean> getLdapUsers(LdapContext ctx, String loginAttributeName, List<String> searchStrs) { List<TPersonBean> personBeans = new LinkedList<TPersonBean>(); if (ldapMap == null || ldapMap.isEmpty()) { LOGGER.error("There is no LDAP mapping in quartz-jobs.xml. Please provide!"); return personBeans; } String firstNameAttributeName = ldapMap.get(LdapUtil.LDAP_CONFIG.FIRST_NAME); String lastNameAttributName = ldapMap.get(LdapUtil.LDAP_CONFIG.LAST_NAME); String emailAttributeName = ldapMap.get(LdapUtil.LDAP_CONFIG.EMAIL); String phoneAttributName = ldapMap.get(LdapUtil.LDAP_CONFIG.PHONE); for (String searchStr : searchStrs) { LOGGER.debug("Searching by filter " + searchStr); SearchControls ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); try { NamingEnumeration<SearchResult> results = ctx.search("", searchStr, ctls); while (results != null && results.hasMore()) { SearchResult sr = (SearchResult) results.next(); TPersonBean personBean = getPersonBean(sr, loginAttributeName, firstNameAttributeName, lastNameAttributName, emailAttributeName, phoneAttributName); if (personBean != null) { LOGGER.debug("Search successful " + searchStr); personBeans.add(personBean); } } } catch (NamingException e) { LOGGER.warn("Search failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } } return personBeans; }
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 . jav a 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.nuxeo.ecm.directory.ldap.LDAPReference.java
/** * Remove existing statically defined links for the given target id (dynamic references remain unaltered) * * @see org.nuxeo.ecm.directory.Reference#removeLinksForTarget(String) *///from www. j a v a 2s. com @Override public void removeLinksForTarget(String targetId) throws DirectoryException { if (!isStatic()) { // nothing to do: dynamic references cannot be updated return; } LDAPDirectory ldapTargetDirectory = (LDAPDirectory) getTargetDirectory(); LDAPDirectory ldapSourceDirectory = (LDAPDirectory) getSourceDirectory(); String attributeId = getStaticAttributeId(); try (LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession(); LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession()) { if (!sourceSession.isReadOnly()) { // get the dn of the target that matches targetId String targetAttributeValue; if (staticAttributeIdIsDn) { SearchResult targetLdapEntry = targetSession.getLdapEntry(targetId); if (targetLdapEntry == null) { String rdnAttribute = ldapTargetDirectory.getDescriptor().getRdnAttribute(); if (!rdnAttribute.equals(targetSession.idAttribute)) { log.warn(String.format( "cannot remove links to missing entry %s in directory %s for reference %s", targetId, ldapTargetDirectory.getName(), this)); return; } // the entry might have already been deleted, try to // re-forge it if possible (might not work if scope is // subtree) targetAttributeValue = String.format("%s=%s,%s", rdnAttribute, targetId, ldapTargetDirectory.getDescriptor().getSearchBaseDn()); } else { targetAttributeValue = pseudoNormalizeDn(targetLdapEntry.getNameInNamespace()); } } else { targetAttributeValue = targetId; } // build a LDAP query to find entries that point to the target String searchFilter = String.format("(%s=%s)", attributeId, targetAttributeValue); String sourceFilter = ldapSourceDirectory.getBaseFilter(); if (sourceFilter != null && !"".equals(sourceFilter)) { searchFilter = String.format("(&(%s)(%s))", searchFilter, sourceFilter); } SearchControls scts = new SearchControls(); scts.setSearchScope(ldapSourceDirectory.getDescriptor().getSearchScope()); scts.setReturningAttributes(new String[] { attributeId }); // find all source entries that point to the target key and // clean // those references if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.removeLinksForTarget(%s): LDAP search baseDn='%s' " + " filter='%s' scope='%s' [%s]", targetId, sourceSession.searchBaseDn, searchFilter, scts.getSearchScope(), this)); } NamingEnumeration<SearchResult> results = sourceSession.dirContext .search(sourceSession.searchBaseDn, searchFilter, scts); String emptyRefMarker = ldapSourceDirectory.getDescriptor().getEmptyRefMarker(); Attributes emptyAttribute = new BasicAttributes(attributeId, emptyRefMarker); try { while (results.hasMore()) { SearchResult result = results.next(); Attributes attrs = result.getAttributes(); Attribute attr = attrs.get(attributeId); try { if (attr.size() == 1) { // the attribute holds the last reference, put // the // empty ref. marker before removing the // attribute // since empty attribute are often not allowed // by // the server schema if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.removeLinksForTarget(%s): LDAP modifyAttributes key='%s' " + "mod_op='ADD_ATTRIBUTE' attrs='%s' [%s]", targetId, result.getNameInNamespace(), attrs, this)); } sourceSession.dirContext.modifyAttributes(result.getNameInNamespace(), DirContext.ADD_ATTRIBUTE, emptyAttribute); } // remove the reference to the target key attrs = new BasicAttributes(); attr = new BasicAttribute(attributeId); attr.add(targetAttributeValue); attrs.put(attr); if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.removeLinksForTarget(%s): LDAP modifyAttributes key='%s' " + "mod_op='REMOVE_ATTRIBUTE' attrs='%s' [%s]", targetId, result.getNameInNamespace(), attrs, this)); } sourceSession.dirContext.modifyAttributes(result.getNameInNamespace(), DirContext.REMOVE_ATTRIBUTE, attrs); } catch (SchemaViolationException e) { if (isDynamic()) { // we are editing an entry that has no static // part log.warn(String.format("cannot remove dynamic reference in field %s for target %s", getFieldName(), targetId)); } else { // this is a real schema configuration problem, // wrapup the exception throw new DirectoryException(e); } } } } finally { results.close(); } } } catch (NamingException e) { throw new DirectoryException("removeLinksForTarget failed: " + e.getMessage(), e); } }
From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java
/** * @param searchFilter Username search filter. * @param returnedAtts Required attribute list of the user * @param dirContext LDAP connection context. * @return Search results for the given user. * @throws UserStoreException If an error occurs while searching. *//*from w w w .j a v a 2 s . c om*/ private NamingEnumeration<SearchResult> searchForUser(String searchFilter, String[] returnedAtts, DirContext dirContext) throws UserStoreException { SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); String searchBases = userStoreProperties.get(LDAPConstants.USER_SEARCH_BASE); if (returnedAtts[0].equals(CommonConstants.WILD_CARD_FILTER)) { returnedAtts = null; } searchCtls.setReturningAttributes(returnedAtts); 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); } if (returnedAtts == null) { log.debug("No attributes requested"); } else { for (String attribute : returnedAtts) { log.debug("Requesting attribute :" + attribute); } } } String[] searchBaseAraay = searchBases.split(CommonConstants.XML_PATTERN_SEPERATOR); NamingEnumeration<SearchResult> answer = null; try { for (String searchBase : searchBaseAraay) { answer = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchCtls); if (answer.hasMore()) { return answer; } } } catch (PartialResultException e) { // can be due to referrals in AD. so just ignore error String errorMessage = "Error occurred while search user for filter : " + searchFilter; if (isIgnorePartialResultException()) { if (log.isDebugEnabled()) { log.debug(errorMessage, e); } } else { throw new UserStoreException(errorMessage, e); } } catch (NamingException e) { String errorMessage = "Error occurred while search user for filter : " + searchFilter; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } return answer; }
From source file:com.aurel.track.util.LdapUtil.java
/** * Gets all persons for a group/*from w ww.j ava 2 s. c o m*/ * * @param groups * @param siteBean * @param filter * @return * @throws Exception */ static List<TPersonBean> getAllLdapUsersDescendants(String providerUrl, String bindDN, String bindPassword, String loginAttributeName, String filter) throws Exception { List<TPersonBean> personBeans = new ArrayList<TPersonBean>(); if (filter == null || "".equals(filter) || "*".equals(filter)) { filter = loginAttributeName + "=*"; } int recordCount = 0; SearchControls ctls = null; LdapContext ctx = null; try { ctx = getInitialContext(providerUrl, bindDN, bindPassword); if (ctx == null) { return personBeans; } // Activate paged results int pageSize = 5; // TODO replace for GROOVY ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) }); int total; String searchStr = "(" + filter + ")"; // Control the search ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); ctls.setCountLimit((ApplicationBean.getInstance().getMaxNumberOfFullUsers() + ApplicationBean.getInstance().getMaxNumberOfLimitedUsers()) * 3 + 10); // Don't ask for more than we can handle // anyways if (ldapMap == null || ldapMap.isEmpty()) { LOGGER.error("There is no LDAP mapping in quartz-jobs.xml. Please provide!"); return personBeans; } String firstNameAttributeName = ldapMap.get("firstName"); String lastNameAttributName = ldapMap.get("lastName"); String emailAttributeName = ldapMap.get("email"); String phoneAttributName = ldapMap.get("phone"); byte[] cookie = null; // TODO replace for GROOVY cookie = new byte[] {}; // cookie = [] as byte[]; while (cookie != null) { NamingEnumeration<SearchResult> results = ctx.search("", searchStr, ctls); while (results != null && results.hasMore()) { SearchResult sr = (SearchResult) results.next(); TPersonBean personBean = getPersonBean(sr, loginAttributeName, firstNameAttributeName, lastNameAttributName, emailAttributeName, phoneAttributName); if (personBean != null) { personBeans.add(personBean); ++recordCount; } } // Examine the paged results control response Control[] controls = ctx.getResponseControls(); if (controls != null) { for (int i = 0; i < controls.length; i++) { if (controls[i] instanceof PagedResultsResponseControl) { PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i]; total = prrc.getResultSize(); if (total != 0) { LOGGER.debug("***************** END-OF-PAGE " + "(total : " + total + ") *****************\n"); } else { LOGGER.debug( "***************** END-OF-PAGE " + "(total: unknown) ***************\n"); } cookie = prrc.getCookie(); } } } else { LOGGER.debug("No controls were sent from the server"); } // Re-activate paged results // TODO replace for GROOVY ctx.setRequestControls( new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) }); } } catch (SizeLimitExceededException sle) { if (recordCount < ctls.getCountLimit()) { LOGGER.error("Searching LDAP asked for more entries than permitted by the LDAP server."); LOGGER.error("Size limit exceeded error occurred after record " + recordCount + " with " + sle.getMessage()); LOGGER.error( "You have to ask your LDAP server admin to increase the limit or specify a more suitable search base or filter."); } else { LOGGER.error("Searching LDAP asked for more entries than permitted by the Genji server (" + recordCount + ")."); LOGGER.error( "You have to get more user licenses for Genji or specify a more suitable search base or filter."); } LOGGER.error("The LDAP synchronization is most likely incomplete."); } catch (NamingException e) { LOGGER.error("PagedSearch failed."); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } catch (IOException ie) { LOGGER.error("PagedSearch failed."); LOGGER.debug(ExceptionUtils.getStackTrace(ie)); } finally { if (ctx != null) { ctx.close(); } } return personBeans; }
From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java
/** * @param userName Username of the user. * @param searchBase Searchbase which the user should be searched for. * @param searchFilter Search filter of the username. * @return DN of the user whose usename is given. * @throws UserStoreException If an error occurs while connecting to the LDAP userstore. *//*from w w w . j av a 2s. c o m*/ private 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; String[] searchBases = searchBase.split(CommonConstants.XML_PATTERN_SEPERATOR); for (String base : searchBases) { answer = dirContext.search(escapeDNForSearch(base), searchFilter, searchCtls); if (answer.hasMore()) { userObj = 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 (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:com.wfp.utils.LDAPUtils.java
public static SearchControls getSimpleSearchControls(String[] attrIDS) { SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setTimeLimit(30000);/* w w w. j a v a2 s . co m*/ if (attrIDS != null) { searchControls.setReturningAttributes(attrIDS); } return searchControls; }
From source file:com.wfp.utils.LDAPUtils.java
public static SearchControls getSimpleSearchControls() { SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setTimeLimit(30000);/*from w w w . ja v a2 s . c o m*/ return searchControls; }
From source file:org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.java
/** * *//*from ww w . jav a 2 s . co m*/ public String[] getUserListOfLDAPRole(RoleContext context, String filter) throws UserStoreException { boolean debug = log.isDebugEnabled(); if (debug) { log.debug("Getting user list of role: " + context.getRoleName() + " with filter: " + filter); } List<String> userList = new ArrayList<String>(); String[] names = new String[0]; int givenMax = UserCoreConstants.MAX_USER_ROLE_LIST; int searchTime = UserCoreConstants.MAX_SEARCH_TIME; try { givenMax = Integer.parseInt( realmConfig.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_MAX_USER_LIST)); } catch (Exception e) { givenMax = UserCoreConstants.MAX_USER_ROLE_LIST; } try { searchTime = Integer.parseInt( realmConfig.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_MAX_SEARCH_TIME)); } catch (Exception e) { searchTime = UserCoreConstants.MAX_SEARCH_TIME; } DirContext dirContext = null; NamingEnumeration<SearchResult> answer = null; try { SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchCtls.setTimeLimit(searchTime); searchCtls.setCountLimit(givenMax); String searchFilter = ((LDAPRoleContext) context).getListFilter(); String roleNameProperty = ((LDAPRoleContext) context).getRoleNameProperty(); searchFilter = "(&" + searchFilter + "(" + roleNameProperty + "=" + escapeSpecialCharactersForFilter(context.getRoleName()) + "))"; String membershipProperty = realmConfig.getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE); String returnedAtts[] = { membershipProperty }; searchCtls.setReturningAttributes(returnedAtts); List<String> userDNList = new ArrayList<String>(); SearchResult sr = null; dirContext = connectionSource.getContext(); // with DN patterns if (((LDAPRoleContext) context).getRoleDNPatterns().size() > 0) { for (String pattern : ((LDAPRoleContext) context).getRoleDNPatterns()) { if (debug) { log.debug("Using pattern: " + pattern); } pattern = MessageFormat.format(pattern.trim(), escapeSpecialCharactersForDN(context.getRoleName())); try { answer = dirContext.search(escapeDNForSearch(pattern), searchFilter, searchCtls); if (answer.hasMore()) { sr = (SearchResult) answer.next(); break; } } catch (NamingException e) { // ignore if (log.isDebugEnabled()) { log.debug(e); } } } } if (sr == null) { // handling multiple search bases String searchBases = ((LDAPRoleContext) context).getSearchBase(); String[] roleSearchBaseArray = searchBases.split("#"); for (String searchBase : roleSearchBaseArray) { if (debug) { log.debug("Searching role: " + context.getRoleName() + " 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 = (SearchResult) 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 == null || membershipProperty.equals(valAttribute.getID())) { NamingEnumeration values = null; for (values = valAttribute.getAll(); values.hasMore();) { String value = values.next().toString(); userDNList.add(value); if (debug) { log.debug("Found attribute: " + membershipProperty + " value: " + value); } } } } } if (MEMBER_UID.equals(realmConfig.getUserStoreProperty(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 = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE); String displayNameAttribute = realmConfig.getUserStoreProperty(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( user.replace("\\\\", "\\\\\\").replace("\\\"", "\\\\\""), 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 (displayNameAttribute != null) { Attribute displayAttribute = userAttributes.get(displayNameAttribute); if (displayAttribute != null) { displayName = (String) displayAttribute.get(); } if (debug) { log.debug("DisplayName: " + displayName); } } } String domainName = realmConfig .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME); // 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 = UserCoreUtil.getCombinedName(domainName, userName, displayName); userList.add(user); if (debug) { log.debug(user + " is added to the result list"); } } // Skip listing users which are not applicable to current // user-mgt.xml 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 for filter : " + filter; 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 for filter : " + filter; 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.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java
/** * @param userName Username of the user. * @param searchBase Search base group search base. * @return List of roles of the given user. * @throws UserStoreException If an error occurs while retrieving data from LDAP userstore. *//*from w w w . j a v a 2 s .com*/ private String[] getLDAPRoleListOfUser(String userName, String searchBase) throws UserStoreException { boolean debug = log.isDebugEnabled(); List<String> list; SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Load normal roles with the user String searchFilter; String roleNameProperty; searchFilter = userStoreProperties.get(LDAPConstants.GROUP_NAME_LIST_FILTER); roleNameProperty = userStoreProperties.get(LDAPConstants.GROUP_NAME_ATTRIBUTE); String membershipProperty = userStoreProperties.get(LDAPConstants.MEMBERSHIP_ATTRIBUTE); String userDNPattern = userStoreProperties.get(LDAPConstants.USER_DN_PATTERN); String nameInSpace; if (userDNPattern != null && userDNPattern.trim().length() > 0 && !userDNPattern.contains(CommonConstants.XML_PATTERN_SEPERATOR)) { nameInSpace = MessageFormat.format(userDNPattern, escapeSpecialCharactersForDN(userName)); } else { nameInSpace = this.getNameInSpaceForUserName(userName); } String membershipValue; if (nameInSpace != null) { try { LdapName ldn = new LdapName(nameInSpace); if (MEMBER_UID.equals(userStoreProperties.get(LDAPConstants.MEMBERSHIP_ATTRIBUTE))) { // membership value of posixGroup is not DN of the user List rdns = ldn.getRdns(); membershipValue = ((Rdn) rdns.get(rdns.size() - 1)).getValue().toString(); } else { membershipValue = escapeLdapNameForFilter(ldn); } } catch (InvalidNameException e) { log.error("Error while creating LDAP name from: " + nameInSpace); throw new UserStoreException("Invalid naming exception for : " + nameInSpace, e); } } else { return new String[0]; } searchFilter = "(&" + searchFilter + "(" + membershipProperty + "=" + membershipValue + "))"; String returnedAtts[] = { roleNameProperty }; searchCtls.setReturningAttributes(returnedAtts); if (debug) { log.debug("Reading roles with the membershipProperty Property: " + membershipProperty); } list = this.getListOfNames(searchBase, searchFilter, searchCtls, roleNameProperty); String[] result = list.toArray(new String[list.size()]); for (String rolename : result) { log.debug("Found role: " + rolename); } return result; }