List of usage examples for javax.naming.directory SearchControls setReturningAttributes
public void setReturningAttributes(String[] attrs)
From source file:com.wfp.utils.LDAPUtils.java
public static String getUserImageAsString(String uid) { String base64String = null; if (uid != null && uid != "") { // Specify the attributes to return String searchFilter = "(&" + FILTER_LDAP_USERS + "((uid=" + uid + ")))"; String searchBase = LDAP_FILTER_URL + "uid=" + uid + "," + LDAP_BASE; String returnedAtts[] = { "" + PROPERTY_IMAGE }; // Specify the search scope SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchCtls.setReturningAttributes(returnedAtts); // Search for objects using the filter try {/*from w w w. ja va 2 s . c o m*/ NamingEnumeration results = getSearchResults(getLDAPContext(), searchCtls, searchFilter, searchBase); while (results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); Attributes attributes = searchResult.getAttributes(); Attribute attr = attributes.get(PROPERTY_IMAGE); if (attr != null) base64String = new String( org.apache.commons.codec.binary.Base64.encodeBase64((byte[]) attr.get())); } } catch (NamingException e) { Logger.error(" Error occured while fetching user image 1334: getUserImageBytes(String uid):[" + e.getLocalizedMessage() + "]", LDAPUtils.class); } } return base64String; }
From source file:ldap.ActiveLoginImpl.java
/** * Returns whether this user is listed in the admin users role * * @param login/*from ww w. j av a 2 s .c o m*/ * @return * @throws Exception */ public boolean isAdmin(String login, DirContext context, String DN) throws Exception { NamingEnumeration result = null; String[] returnAttributes = new String[] { "uniqueMember" }; /* specify search constraints to search subtree */ SearchControls constraints = new SearchControls(); constraints.setSearchScope(SearchControls.OBJECT_SCOPE); constraints.setCountLimit(0); constraints.setTimeLimit(0); constraints.setReturningAttributes(returnAttributes); /* Entry user = null; try { user = searcher.getUser(LdapConstants.ldapAttrLogin, login, context); } catch (NamingException e) { throw new LdapException("getUser NamingException" + e.getMessage(), e); } String DN = null; if (user == null) { logger.info("USER DOES NOT EXIST"); return false; } else { DN = user.getName().toString(); if (DN != null) { logger.info("DN = " + DN); } } */ //result = context.search(LdapConstants.ldapAdminRoleDn, "(uniqueMember="+getUserDN(login)+")", constraints); result = context.search(LdapConstants.ldapAdminRoleDn, "(uniqueMember=" + DN + ")", constraints); if (result.hasMore()) { if (debug) { SearchResult sResult = (SearchResult) result.next(); logger.info("Read Admin Roles Object with members: " + sResult.getAttributes().toString()); } return true; } else if (debug) logger.info("Failed to find admin object with member " + DN); return false; }
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);/*from w w w.j ava2 s. com*/ if (attrIDS != null) { searchControls.setReturningAttributes(attrIDS); } return searchControls; }
From source file:org.apache.manifoldcf.authorities.authorities.sharepoint.SharePointADAuthority.java
/** Obtain the DistinguishedName for a given user logon name. *@param ctx is the ldap context to use./*from w ww . ja va2 s .c o m*/ *@param userName (Domain Logon Name) is the user name or identifier. *@param searchBase (Full Domain Name for the search ie: DC=qa-ad-76,DC=metacarta,DC=com) *@return DistinguishedName for given domain user logon name. * (Should throws an exception if user is not found.) */ protected String getDistinguishedName(LdapContext ctx, String userName, String searchBase, String userACLsUsername) throws ManifoldCFException { String returnedAtts[] = { "distinguishedName" }; String searchFilter = "(&(objectClass=user)(" + userACLsUsername + "=" + userName + "))"; SearchControls searchCtls = new SearchControls(); searchCtls.setReturningAttributes(returnedAtts); //Specify the search scope searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchCtls.setReturningAttributes(returnedAtts); try { NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls); while (answer.hasMoreElements()) { SearchResult sr = (SearchResult) answer.next(); Attributes attrs = sr.getAttributes(); if (attrs != null) { String dn = attrs.get("distinguishedName").get().toString(); return dn; } } return null; } catch (NamingException e) { throw new ManifoldCFException(e.getMessage(), e); } }
From source file:ldap.SearchUtility.java
/** * * @param searchBase// ww w. j a va 2 s. c o m * @param regexp * @param pageSize * @param pageNumber * @return a list of matching users. * @throws NamingException */ public List<Entry> getUsers(LdapName searchBase, String regexp, int pageSize, int pageNumber, ArrayList<String> attributes, DirContext context) throws NamingException { Pattern pattern = null; if (regexp != null) pattern = Pattern.compile(regexp); /* * Figure out an ldap search filter. Note that unless an ORDERING matching rule is defined on the server * for the attribute we are searching (and they usually aren't, since it requires extra indexing on the * server), we cannot use ldap greater than / less than search filters to find * a range of users, and have to do this search in code using a regular expression. */ //String filter = "(objectClass=" + Config.USER_OBJECTCLASS + ")"; String filter = ""; if (LdapConstants.ldapObjectClassEmployeeEnable) { filter = "(objectClass=" + LdapConstants.ldapObjectClassEmployee + ")"; } SearchControls controls = getSearchControls(); String[] attributesToReturn; if (attributes == null) { attributesToReturn = null; // a JNDI special value that means 'return everything' } else { //attributes.add(Config.USER_NAMING_ATT); attributes.add(LdapConstants.ldapAttrUid); attributesToReturn = attributes.toArray(new String[] {}); } if (controls != null) { controls.setReturningAttributes(attributesToReturn); } else { logger.info("controls is null"); } // do the directory search NamingEnumeration<SearchResult> userResults = context.search(searchBase, filter, controls); if (userResults == null) { logger.info("userResults is Null in getUsers()"); return null; } else { // parse the results, looking for entries that match our regexp ArrayList<Entry> users = new ArrayList<Entry>(); while (userResults.hasMore()) { SearchResult userResult = userResults.next(); Entry userEntry = new Entry(userResult); //String text = userEntry.getValue(Config.USER_NAMING_ATT).toUpperCase(); String text = userEntry.getValue(LdapConstants.ldapAttrUid).toUpperCase(); if (pattern == null) { users.add(userEntry); } else { Matcher matcher = pattern.matcher(text); if (matcher.find()) { users.add(userEntry); } } } // sort them alphabeticaly by user naming attribute Collections.sort(users); // trim the results to the page requested (if any) if (pageSize > 0) { ArrayList<Entry> userPage = new ArrayList<Entry>(pageSize); int startPos = pageSize * pageNumber; int size = users.size(); for (int i = startPos; i < (startPos + pageSize); i++) { if (i < size) { userPage.add(users.get(i)); } } users = userPage; } // add 'synthetic' attributes for for (Entry user : users) { fillInSyntheticAttributes(user); } // return the final user list return users; } // else }
From source file:com.adito.activedirectory.PagedResultTemplate.java
private void doPagedSearch(InitialLdapContext context, String filter, String[] attributes, PagedResultMapper mapper) throws NamingException { SearchControls constraints = new SearchControls(); constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); applyControls(context, pageSize);//w w w. j a v a2s. co m for (String searchBase : ouSearchBase) { if (logger.isDebugEnabled()) { logger.debug("Looking for items starting at " + searchBase + " (filter = " + filter + ")"); } try { int currentPage = 1; int startPosition = 0; int endPosition = pageSize - 1; byte[] cookie = null; do { String range = startPosition + "-" + endPosition; if (logger.isDebugEnabled()) { logger.debug("Starting search on page " + currentPage + " " + range); } constraints.setReturningAttributes(attributes); NamingEnumeration<SearchResult> results = context.search(searchBase, filter, constraints); try { mapResults(mapper, results); } catch (PartialResultException pre) { // We're paging so we dont care and don't log anymore } // Examine the paged results control response Control[] controls = context.getResponseControls(); if (controls != null) { for (int index = 0; index < controls.length; index++) { if (controls[index] instanceof PagedResultsResponseControl) { PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[index]; cookie = prrc.getCookie(); } } } applyControls(context, pageSize, cookie); startPosition = startPosition + pageSize; endPosition = endPosition + pageSize; currentPage++; } while ((cookie != null) && (cookie.length != 0)); } catch (NamingException e) { mapper.processException(e); logger.error("Possible configuration error! Did you enter your OUs correctly? [" + searchBase + "]", e); } } }
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 w ww. j a v a 2 s.c o m * 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:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java
@SuppressWarnings("unchecked") private List getUserRolesByDn(DirContext dirContext, String userDn, String username) throws LoginException, NamingException { List<String> roleList = new ArrayList<String>(); if (dirContext == null || _roleBaseDn == null || (_roleMemberAttribute == null && _roleUsernameMemberAttribute == null) || _roleObjectClass == null) { LOG.warn(//from www . j a v a 2 s .co m "JettyCachingLdapLoginModule: No user roles found: roleBaseDn, roleObjectClass and roleMemberAttribute or roleUsernameMemberAttribute must be specified."); addSupplementalRoles(roleList); return roleList; } String[] attrIDs = { _roleNameAttribute }; SearchControls ctls = new SearchControls(); ctls.setReturningAttributes(attrIDs); ctls.setDerefLinkFlag(true); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); String filter = OBJECT_CLASS_FILTER; final NamingEnumeration results; if (null != _roleUsernameMemberAttribute) { Object[] filterArguments = { _roleObjectClass, _roleUsernameMemberAttribute, username }; results = dirContext.search(_roleBaseDn, filter, filterArguments, ctls); } else { Object[] filterArguments = { _roleObjectClass, _roleMemberAttribute, userDn }; results = dirContext.search(_roleBaseDn, filter, filterArguments, ctls); } while (results.hasMoreElements()) { SearchResult result = (SearchResult) results.nextElement(); Attributes attributes = result.getAttributes(); if (attributes == null) { continue; } Attribute roleAttribute = attributes.get(_roleNameAttribute); if (roleAttribute == null) { continue; } NamingEnumeration roles = roleAttribute.getAll(); while (roles.hasMore()) { if (_rolePrefix != null && !"".equalsIgnoreCase(_rolePrefix)) { String role = (String) roles.next(); roleList.add(role.replace(_rolePrefix, "")); } else { roleList.add((String) roles.next()); } } } addSupplementalRoles(roleList); if (_nestedGroups) { roleList = getNestedRoles(dirContext, roleList); } if (roleList.size() < 1) { LOG.warn("JettyCachingLdapLoginModule: User '" + username + "' has no role membership; role query configuration may be incorrect"); } else { debug("JettyCachingLdapLoginModule: User '" + username + "' has roles: " + roleList); } return roleList; }
From source file:com.nridge.core.app.ldap.ADQuery.java
/** * Queries Active Directory for attributes defined within the bag. * The LDAP_ACCOUNT_NAME field must be populated prior to invoking * this method. Any site specific fields can be assigned to the * bag will be included in the attribute query. * * @param aUserBag Active Directory user fields. * * @throws NSException Thrown if an LDAP naming exception is occurs. *///from w w w . ja v a 2s . c om public void loadUserByAccountName(DataBag aUserBag) throws NSException { byte[] objectSid; Attribute responseAttribute; String fieldName, fieldValue; Attributes responseAttributes; Logger appLogger = mAppMgr.getLogger(this, "loadUserByAccountName"); appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER); if (mLdapContext == null) { String msgStr = "LDAP context has not been established."; appLogger.error(msgStr); throw new NSException(msgStr); } SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); int field = 0; String accountName = null; int attrCount = aUserBag.count(); String[] ldapAttrNames = new String[attrCount]; for (DataField dataField : aUserBag.getFields()) { fieldName = dataField.getName(); if (fieldName.equals(LDAP_ACCOUNT_NAME)) accountName = dataField.getValueAsString(); ldapAttrNames[field++] = fieldName; } searchControls.setReturningAttributes(ldapAttrNames); if (accountName == null) { String msgStr = String.format("LDAP account name '%s' is unassigned.", LDAP_ACCOUNT_NAME); appLogger.error(msgStr); throw new NSException(msgStr); } String userSearchBaseDN = getPropertyValue("user_searchbasedn", null); String userSearchFilter = String.format("(&(objectClass=user)(%s=%s))", LDAP_ACCOUNT_NAME, accountName); try { NamingEnumeration<?> searchResponse = mLdapContext.search(userSearchBaseDN, userSearchFilter, searchControls); if ((searchResponse != null) && (searchResponse.hasMore())) { responseAttributes = ((SearchResult) searchResponse.next()).getAttributes(); for (DataField complexField : aUserBag.getFields()) { fieldName = complexField.getName(); responseAttribute = responseAttributes.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); } } searchResponse.close(); } } catch (NamingException e) { String msgStr = String.format("LDAP Search Error (%s): %s", userSearchFilter, e.getMessage()); appLogger.error(msgStr, e); throw new NSException(msgStr); } appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART); }
From source file:com.nridge.core.app.ldap.ADQuery.java
/** * Queries Active Directory for attributes defined within the bag. * The LDAP_COMMON_NAME field must be populated prior to invoking * this method. Any site specific fields can be assigned to the * bag will be included in the attribute query. * * @param aUserBag Active Directory user fields. * * @throws NSException Thrown if an LDAP naming exception is occurs. *///from w w w . j av a 2 s .c o m public void loadUserByCommonName(DataBag aUserBag) throws NSException { byte[] objectSid; Attribute responseAttribute; String fieldName, fieldValue; Attributes responseAttributes; Logger appLogger = mAppMgr.getLogger(this, "loadUserByCommonName"); appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER); if (mLdapContext == null) { String msgStr = "LDAP context has not been established."; appLogger.error(msgStr); throw new NSException(msgStr); } SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); int field = 0; String commonName = null; int attrCount = aUserBag.count(); String[] ldapAttrNames = new String[attrCount]; for (DataField complexField : aUserBag.getFields()) { fieldName = complexField.getName(); if (fieldName.equals(LDAP_COMMON_NAME)) commonName = complexField.getValueAsString(); ldapAttrNames[field++] = fieldName; } searchControls.setReturningAttributes(ldapAttrNames); if (commonName == null) { String msgStr = String.format("LDAP common name '%s' is unassigned.", LDAP_COMMON_NAME); appLogger.error(msgStr); throw new NSException(msgStr); } String userSearchBaseDN = getPropertyValue("user_searchbasedn", null); String userSearchFilter = String.format("(&(objectClass=user)(%s=%s))", LDAP_COMMON_NAME, commonName); try { NamingEnumeration<?> searchResponse = mLdapContext.search(userSearchBaseDN, userSearchFilter, searchControls); if ((searchResponse != null) && (searchResponse.hasMore())) { responseAttributes = ((SearchResult) searchResponse.next()).getAttributes(); for (DataField complexField : aUserBag.getFields()) { fieldName = complexField.getName(); responseAttribute = responseAttributes.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); } } searchResponse.close(); } } catch (NamingException e) { String msgStr = String.format("LDAP Search Error (%s): %s", userSearchFilter, e.getMessage()); appLogger.error(msgStr, e); throw new NSException(msgStr); } appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART); }