Java Code Examples for javax.naming.directory.SearchControls#setReturningAttributes()

The following examples show how to use javax.naming.directory.SearchControls#setReturningAttributes() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ReadWriteLDAPUserStoreManager.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * Reused method to search groups with various filters.
 *
 * @param searchFilter
 * @param returningAttributes
 * @param searchScope
 * @return
 */
protected NamingEnumeration<SearchResult> searchInGroupBase(String searchFilter,
                                                            String[] returningAttributes,
                                                            int searchScope,
                                                            DirContext rootContext,
                                                            String searchBase)
        throws UserStoreException {
    SearchControls userSearchControl = new SearchControls();
    userSearchControl.setReturningAttributes(returningAttributes);
    userSearchControl.setSearchScope(searchScope);
    NamingEnumeration<SearchResult> groupSearchResults = null;
    try {
        groupSearchResults = rootContext.search(escapeDNForSearch(searchBase), searchFilter, userSearchControl);
    } catch (NamingException e) {
        String errorMessage = "Error occurred while searching in group base.";
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    }

    return groupSearchResults;
}
 
Example 2
Source File: OpenLdapUserManagerImpl.java    From cosmic with Apache License 2.0 6 votes vote down vote up
public LdapUser searchUser(final String basedn, final String searchString, final LdapContext context) throws NamingException, IOException {
    final SearchControls searchControls = new SearchControls();

    searchControls.setSearchScope(_ldapConfiguration.getScope());
    searchControls.setReturningAttributes(_ldapConfiguration.getReturnAttributes());

    final NamingEnumeration<SearchResult> results = context.search(basedn, searchString, searchControls);
    final List<LdapUser> users = new ArrayList<>();
    while (results.hasMoreElements()) {
        final SearchResult result = results.nextElement();
        users.add(createUser(result));
    }

    if (users.size() == 1) {
        return users.get(0);
    } else {
        throw new NamingException("No user found for basedn " + basedn + " and searchString " + searchString);
    }
}
 
Example 3
Source File: LdapManager.java    From fess with Apache License 2.0 6 votes vote down vote up
protected void search(final String baseDn, final String filter, final String[] returningAttrs,
        final Supplier<Hashtable<String, String>> envSupplier, final SearchConsumer consumer) {
    try (DirContextHolder holder = getDirContext(envSupplier)) {
        final SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        if (returningAttrs != null) {
            controls.setReturningAttributes(returningAttrs);
        }

        final long startTime = System.currentTimeMillis();
        final List<SearchResult> list = Collections.list(holder.get().search(baseDn, filter, controls));
        if (logger.isDebugEnabled()) {
            logger.debug("LDAP search[{}ms]: {} - {}", System.currentTimeMillis() - startTime, baseDn, filter);
        }
        consumer.accept(list);
    } catch (final NamingException e) {
        throw new LdapOperationException("Failed to search " + baseDn + " with " + filter, e);
    }
}
 
Example 4
Source File: JndiLdapAdditionalSignature.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void ldapInjectionSunApi(String input) throws NamingException {
    //Stub instances
    Properties props = new Properties();
    props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    props.put(Context.PROVIDER_URL, "ldap://ldap.example.com");
    props.put(Context.REFERRAL, "ignore");

    SearchControls ctrls = new SearchControls();
    ctrls.setReturningAttributes(new String[]{"givenName", "sn"});
    ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    //Two context instances mostly usable with sun specific API
    LdapCtx            context5 = null;
    EventDirContext    context6 = null; //LdapCtx is the only known class to implements to this interface

    NamingEnumeration<SearchResult> answers;
    answers = context5.search(new LdapName("dc=People,dc=example,dc=com"), "(uid=" + input + ")", ctrls);
    answers = context5.search(new LdapName("dc=People,dc=example,dc=com"), "(uid=" + input + ")", new Object[0], ctrls);
    answers = context5.search("dc=People,dc=example,dc=com", "(uid=" + input + ")", ctrls);
    answers = context5.search("dc=People,dc=example,dc=com", "(uid=" + input + ")", new Object[0], ctrls);

    answers = context6.search(new LdapName("dc=People,dc=example,dc=com"), "(uid=" + input + ")", ctrls);
    answers = context6.search(new LdapName("dc=People,dc=example,dc=com"), "(uid=" + input + ")", new Object[0], ctrls);
    answers = context6.search("dc=People,dc=example,dc=com", "(uid=" + input + ")", ctrls);
    answers = context6.search("dc=People,dc=example,dc=com", "(uid=" + input + ")", new Object[0], ctrls);
}
 
Example 5
Source File: LdapTemplateTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testSearch_String_ContextMapper_ReturningAttrs() throws Exception {
	expectGetReadOnlyContext();

	String[] attrs = new String[0];

	SearchControls controls = searchControlsOneLevel();
	controls.setReturningAttributes(attrs);

	Object expectedObject = new Object();
	SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes());

	singleSearchResultWithStringBase(controls, searchResult);

	Object expectedResult = expectedObject;
	when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult);

	List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", 1, attrs, contextMapperMock);

       verify(namingEnumerationMock).close();
       verify(dirContextMock).close();

       assertThat(list).isNotNull();
	assertThat(list).hasSize(1);
	assertThat(list.get(0)).isSameAs(expectedResult);
}
 
Example 6
Source File: TestLdap.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
public void testTBGalSearch() throws NamingException {
    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    searchControls.setReturningAttributes(new String[]{"mail", "cn"});
    NamingEnumeration<SearchResult> searchResults = ldapContext.search("ou=people",
            "(|(sn=mich*)(mail=mich*)(cn=mich*))", searchControls);
    searchResults.close();
}
 
Example 7
Source File: LdapManager.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Method that calls the actual search on the jndi context.
 *
 * @param searchbase       the domain name (relative to initial context in ldap) to search from.
 * @param filter           the non-null filter to use for the search
 * @param scope            the scope level of the search, one off "SearchControls.ONELEVEL_SCOPE
 * @param limit            the maximum number of results to return
 * @param timeout          the maximum time to wait before abandoning the search
 * @param returnAttributes an array of strings containing the names of attributes to search. (null = all, empty array = none)
 * @return
 * @throws NamingException
 */
public NamingEnumeration search(String searchbase, String filter,
		String[] returnAttributes, int scope, int limit, int timeout)
		throws NamingException {

	SearchControls constraints = new SearchControls();

	if (SearchControls.ONELEVEL_SCOPE == scope) {
		constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE);
	} else if (SearchControls.SUBTREE_SCOPE == scope) {
		constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
	} else if (SearchControls.OBJECT_SCOPE == scope) {
		constraints.setSearchScope(SearchControls.OBJECT_SCOPE);
	} else {
		throw new NamingException("Unknown search scope: " + scope);
	}

	if (returnAttributes != null && returnAttributes.length == 0)
		returnAttributes = new String[] { "objectClass" };

	constraints.setCountLimit(limit);
	constraints.setTimeLimit(timeout);

	constraints.setReturningAttributes(returnAttributes);

	Name n = new CompositeName().add(searchbase);
	NamingEnumeration results = ctx.search(n, filter, constraints);

	return results;

}
 
Example 8
Source File: LDAPLoginManagerImpl.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Find the user dn with its uid
 * 
 * @param uid
 * @param ctx
 * @return user's dn
 */
private String searchUserDN(final String uid, final DirContext ctx) {
    if (ctx == null) {
        return null;
    }

    final List<String> ldapBases = LDAPLoginModule.getLdapBases();
    final String objctClass = LDAPLoginModule.getLdapUserObjectClass();
    final String[] serachAttr = { "dn" };

    final String ldapUserIDAttribute = LDAPLoginModule.mapOlatPropertyToLdapAttribute(LDAPConstants.LDAP_USER_IDENTIFYER);
    final String filter = "(&(objectClass=" + objctClass + ")(" + ldapUserIDAttribute + "=" + uid + "))";
    final SearchControls ctls = new SearchControls();
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    ctls.setReturningAttributes(serachAttr);

    String userDN = null;
    for (final String ldapBase : ldapBases) {
        try {
            final NamingEnumeration<SearchResult> enm = ctx.search(ldapBase, filter, ctls);
            while (enm.hasMore()) {
                final SearchResult result = enm.next();
                userDN = result.getNameInNamespace();
            }
            if (userDN != null) {
                break;
            }
        } catch (final NamingException e) {
            log.error("NamingException when trying to bind user with username::" + uid + " on ldapBase::" + ldapBase, e);
        }
    }

    return userDN;
}
 
Example 9
Source File: TestLdap.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
public void testSearchNotFilter() throws NamingException {
    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    searchControls.setReturningAttributes(new String[]{"mail"});
    NamingEnumeration<SearchResult> searchResults = ldapContext.search("ou=people", "(!(objectclass=test))", searchControls);
     searchResults.close();
}
 
Example 10
Source File: LdapTemplate.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
private SearchControls getDefaultSearchControls(int searchScope, boolean returningObjFlag, String[] attrs) {
	SearchControls controls = new SearchControls();
	controls.setSearchScope(searchScope);
       controls.setTimeLimit(defaultTimeLimit);
       controls.setCountLimit(defaultCountLimit);
	controls.setReturningObjFlag(returningObjFlag);
	controls.setReturningAttributes(attrs);
	return controls;
}
 
Example 11
Source File: TestLdap.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
public void testSearchIPad() throws NamingException {
    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    searchControls.setReturningAttributes(new String[]{"postalcode", "labeleduri", "street", "givenname", "telephonenumber", "facsimiletelephonenumber", "title", "imhandle", "homepostaladdress", "st", "homephone", "applefloor", "jpegphoto", "pager", "mail", "sn", "buildingname", "ou", "destinationindicator", "c", "o", "l", "co", "postaladdress", "cn", "mobile"});
    NamingEnumeration<SearchResult> searchResults = ldapContext.search("ou=people", "(|(mail=Test*)(cn=Test*)(givenname=Test*)(sn=Test*))", searchControls);
    searchResults.close();
}
 
Example 12
Source File: JNDIProviderImpl.java    From ldapchai with GNU Lesser General Public License v2.1 5 votes vote down vote up
private SearchControls makeSearchControls()
{
    final SearchControls searchControls = new SearchControls();
    searchControls.setReturningObjFlag( false );
    searchControls.setReturningAttributes( new String[0] );
    searchControls.setSearchScope( searchHelper.getSearchScope().getJndiScopeInt() );
    final String[] returnAttributes = searchHelper.getAttributes() == null
            ? null
            : searchHelper.getAttributes().toArray( new String[searchHelper.getAttributes().size()] );

    searchControls.setReturningAttributes( returnAttributes );
    searchControls.setTimeLimit( searchHelper.getTimeLimit() );
    searchControls.setCountLimit( searchHelper.getMaxResults() );
    return searchControls;
}
 
Example 13
Source File: OpenLdapUserManagerImpl.java    From cosmic with Apache License 2.0 5 votes vote down vote up
@Override
public List<LdapUser> getUsersInGroup(final String groupName, final LdapContext context) throws NamingException {
    final String attributeName = _ldapConfiguration.getGroupUniqueMemeberAttribute();
    final SearchControls controls = new SearchControls();
    controls.setSearchScope(_ldapConfiguration.getScope());
    controls.setReturningAttributes(new String[]{attributeName});

    final NamingEnumeration<SearchResult> result = context.search(_ldapConfiguration.getBaseDn(), generateGroupSearchFilter(groupName), controls);

    final List<LdapUser> users = new ArrayList<>();
    //Expecting only one result which has all the users
    if (result.hasMoreElements()) {
        final Attribute attribute = result.nextElement().getAttributes().get(attributeName);
        final NamingEnumeration<?> values = attribute.getAll();

        while (values.hasMoreElements()) {
            final String userdn = String.valueOf(values.nextElement());
            try {
                users.add(getUserForDn(userdn, context));
            } catch (final NamingException e) {
                s_logger.info("Userdn: " + userdn + " Not Found:: Exception message: " + e.getMessage());
            }
        }
    }

    Collections.sort(users);

    return users;
}
 
Example 14
Source File: LDAPLoginManagerImpl.java    From olat with Apache License 2.0 5 votes vote down vote up
private boolean isPagedResultControlSupported(final LdapContext ctx) {
    try {
        final SearchControls ctl = new SearchControls();
        ctl.setReturningAttributes(new String[] { "supportedControl" });
        ctl.setSearchScope(SearchControls.OBJECT_SCOPE);

        /* search for the rootDSE object */
        final NamingEnumeration<SearchResult> results = ctx.search("", "(objectClass=*)", ctl);

        while (results.hasMore()) {
            final SearchResult entry = results.next();
            final NamingEnumeration<? extends Attribute> attrs = entry.getAttributes().getAll();
            while (attrs.hasMore()) {
                final Attribute attr = attrs.next();
                final NamingEnumeration<?> vals = attr.getAll();
                while (vals.hasMore()) {
                    final String value = (String) vals.next();
                    if (value.equals(PAGED_RESULT_CONTROL_OID)) {
                        return true;
                    }
                }
            }
        }
        return false;
    } catch (final Exception e) {
        log.error("Exception when trying to know if the server support paged results.", e);
        return false;
    }
}
 
Example 15
Source File: TestLdap.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
public void testSearchMail() throws NamingException {
    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    searchControls.setReturningAttributes(new String[]{"mail"});
    NamingEnumeration<SearchResult> searchResults = ldapContext.search("ou=people", "(objectclass=*)", searchControls);
    searchResults.close();
}
 
Example 16
Source File: ReadOnlyLDAPUsersDAO.java    From james-project with Apache License 2.0 5 votes vote down vote up
/**
 * For a given name, this method makes ldap search in userBase with filter {@link LdapRepositoryConfiguration#userIdAttribute}=name
 * and objectClass={@link LdapRepositoryConfiguration#userObjectClass} and builds {@link User} based on search result.
 *
 * @param name
 *            The userId which should be value of the field {@link LdapRepositoryConfiguration#userIdAttribute}
 * @return A {@link ReadOnlyLDAPUser} instance which is initialized with the
 *         userId of this user and ldap connection information with which
 *         the user was searched. Return null if such a user was not found.
 * @throws NamingException
 *             Propagated by the underlying LDAP communication layer.
 */
private ReadOnlyLDAPUser searchAndBuildUser(Username name) throws NamingException {
    SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    sc.setReturningAttributes(new String[] { ldapConfiguration.getUserIdAttribute() });
    sc.setCountLimit(1);

    String filterTemplate = "(&({0}={1})(objectClass={2})" +
        StringUtils.defaultString(ldapConfiguration.getFilter(), "") +
        ")";

    String sanitizedFilter = FilterEncoder.format(
        filterTemplate,
        ldapConfiguration.getUserIdAttribute(),
        name.asString(),
        ldapConfiguration.getUserObjectClass());

    NamingEnumeration<SearchResult> sr = ldapContext.search(ldapConfiguration.getUserBase(), sanitizedFilter, sc);

    if (!sr.hasMore()) {
        return null;
    }

    SearchResult r = sr.next();
    Attribute userName = r.getAttributes().get(ldapConfiguration.getUserIdAttribute());

    if (!ldapConfiguration.getRestriction().isActivated()
        || userInGroupsMembershipList(r.getNameInNamespace(), ldapConfiguration.getRestriction().getGroupMembershipLists(ldapContext))) {
        return new ReadOnlyLDAPUser(Username.of(userName.get().toString()), r.getNameInNamespace(), ldapContext);
    }

    return null;
}
 
Example 17
Source File: LdapUserService.java    From pmq with Apache License 2.0 5 votes vote down vote up
private void doInitUser(Map<String, UserInfo> userInfos, Map<String, Organization> orgMap, String serverPath)
		throws NamingException {
	Properties env = new Properties();
	env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
	env.put(Context.SECURITY_AUTHENTICATION, "simple");
	env.put(Context.SECURITY_PRINCIPAL, "corp\\" + soaConfig.getMqLdapUser());
	env.put(Context.SECURITY_CREDENTIALS, soaConfig.getMqLdapPass());
	env.put(Context.PROVIDER_URL, adServer.get());

	LdapContext ctx = new InitialLdapContext(env, null);
	SearchControls searchCtls = new SearchControls();
	searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

	String searchFilter = String
			.format("(&(objectClass=top)(objectClass=user)(objectClass=person)(objectClass=organizationalPerson))");

	String returnedAtts[] = { "memberOf", "sAMAccountName", "cn", "distinguishedName", "mail" };
	searchCtls.setReturningAttributes(returnedAtts);
	NamingEnumeration<SearchResult> answer = ctx.search(serverPath, searchFilter, searchCtls);
	while (answer.hasMoreElements()) {
		SearchResult sr = (SearchResult) answer.next();
		Attributes at = sr.getAttributes();
		UserInfo userInfo = new UserInfo();
		userInfo.setDepartment(getDValue(at.get("distinguishedName")));
		userInfo.setEmail(getValue(at.get("mail")));
		userInfo.setUserId(getValue(at.get("sAMAccountName")));
		userInfo.setName(getValue(at.get("cn")));
		userInfo.setAdmin(roleService.isAdmin(userInfo.getUserId()));
		userInfos.put(userInfo.getUserId(), userInfo);
		if (!StringUtils.isEmpty(userInfo.getDepartment())) {
			Organization organization = new Organization();
			organization.setOrgId(userInfo.getDepartment());
			orgMap.put(userInfo.getDepartment(), organization);
		}
	}
	ctx.close();
}
 
Example 18
Source File: LdapAuthenticator.java    From onedev with MIT License 4 votes vote down vote up
private Collection<String> retrieveGroupsByFilter(DirContext ctx, DirContext referralCtx, String userDN) {
	Collection<String> groupNames = new HashSet<>();
	try {
    	SearchGroupsUsingFilter groupRetrieval = (SearchGroupsUsingFilter) getGroupRetrieval();
    	String groupNameAttribute = groupRetrieval.getGroupNameAttribute();
        Name groupSearchBase = new CompositeName().add(groupRetrieval.getGroupSearchBase());
        String groupSearchFilter = StringUtils.replace(groupRetrieval.getGroupSearchFilter(), "{0}", userDN);
        groupSearchFilter = StringUtils.replace(groupSearchFilter, "\\", "\\\\");

        logger.debug("Evaluated group search filter: " + groupSearchFilter);
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        searchControls.setReturningAttributes(new String[]{groupNameAttribute});
        searchControls.setReturningObjFlag(true);

    	NamingEnumeration<SearchResult> results;
        if (referralCtx != null)
            results = referralCtx.search(groupSearchBase, groupSearchFilter, searchControls);
        else
            results = ctx.search(groupSearchBase, groupSearchFilter, searchControls);
        if (results != null) {
            while (results.hasMore()) {
            	SearchResult searchResult = (SearchResult) results.next();
                Attributes searchResultAttributes = searchResult.getAttributes();
                if (searchResultAttributes == null 
                		|| searchResultAttributes.get(groupNameAttribute) == null
                        || searchResultAttributes.get(groupNameAttribute).get() == null) {
                    throw new RuntimeException("Can not find attribute '" 
                    		+ groupNameAttribute + "' in the returned group object.");
                }
                groupNames.add((String) searchResultAttributes.get(groupNameAttribute).get());
            }
        }
       } catch (PartialResultException pre) {
           logger.warn("Partial exception detected. You may try to set property " +
           		"'follow referrals' to true to avoid this exception.", pre);
	} catch (NamingException e) {
		logger.error("Error retrieving groups by filter", e);
	}
	return groupNames;
}
 
Example 19
Source File: UserSync.java    From ranger with Apache License 2.0 4 votes vote down vote up
private void findAdvGroupProperties(LdapContext ldapContext) throws Throwable {
    int noOfGroups = 0;
    NamingEnumeration<SearchResult> groupSearchResultEnum = null;
    SearchControls groupSearchControls = new SearchControls();
    groupSearchControls.setSearchScope(config.getGroupSearchScope());
    Set<String> groupSearchAttributes = new HashSet<>();
    groupSearchAttributes.add(groupNameAttrName);
    groupSearchAttributes.add(groupMemberName);
    groupSearchAttributes.add("distinguishedName");
    groupSearchControls.setReturningAttributes(groupSearchAttributes.toArray(
            new String[groupSearchAttributes.size()]));
    String extendedGroupSearchFilter = "(objectclass=" + groupObjClassName + ")";

    try {
        HashMap<String, Integer> ouOccurences = new HashMap<>();
        if (groupSearchBase == null || groupSearchBase.isEmpty()) {
        	groupSearchResultEnum = ldapContext.search(searchBase, extendedGroupSearchFilter,
                groupSearchControls);
        } else {
        	groupSearchResultEnum = ldapContext.search(groupSearchBase, extendedGroupSearchFilter,
                    groupSearchControls);
        }

        while (groupSearchResultEnum.hasMore()) {
            if (noOfGroups >= 20) {
                break;
            }

            final SearchResult groupEntry = groupSearchResultEnum.next();
            if (groupEntry == null) {
                continue;
            }
            Attributes groupAttributes = groupEntry.getAttributes();
            if (groupAttributes == null) {
                logFile.println("WARN: Attributes missing for entry " + groupEntry.getNameInNamespace());
                continue;
            }

            String dnValue;

            Attribute dnAttr = groupAttributes.get("distinguishedName");
            if (dnAttr != null) {
                dnValue = dnAttr.get().toString();
                String ouStr = "OU=";
                int indexOfOU = dnValue.indexOf(ouStr);
                if (indexOfOU > 0) {
                    dnValue = dnValue.substring(indexOfOU);

                } else {
                    dnValue = dnValue.substring(dnValue.indexOf(",") + 1);
                }

            } else {
                // If distinguishedName is not found,
                // strip off the userName from the long name for OU or sub domain
                dnValue = groupEntry.getNameInNamespace();
                dnValue = dnValue.substring(dnValue.indexOf(",") + 1);
            }
            //System.out.println("OU from dn = " + dnValue);
            Integer ouOccrs = ouOccurences.get(dnValue);
            if (ouOccrs == null) {
                //System.out.println("value = 0");
                ouOccrs = Integer.valueOf(0);
            }
            int val = ouOccrs.intValue();
            ouOccrs = Integer.valueOf(++val);
            ouOccurences.put(dnValue, ouOccrs);

            noOfGroups++;
        }

        if (!ouOccurences.isEmpty()) {
            Set<String> keys = ouOccurences.keySet();
            int maxOUOccr = 0;
            for (String key : keys) {
                int ouOccurVal = ouOccurences.get(key).intValue();
                logFile.println("INFO: No. of groups from " + key + " = " + ouOccurVal);
                if (ouOccurVal > maxOUOccr) {
                    maxOUOccr = ouOccurVal;
                    groupSearchBase = key;
                }
            }
        }

        if (groupSearchFilter == null || groupSearchFilter.isEmpty()) {
        	groupSearchFilter = groupNameAttrName + "=*";
        }

        installProps.println("SYNC_GROUP_SEARCH_BASE=" + groupSearchBase);
        installProps.println("SYNC_LDAP_GROUP_SEARCH_FILTER=" + groupSearchFilter);

        ambariProps.println("ranger.usersync.group.searchbase=" + groupSearchBase);
        ambariProps.println("ranger.usersync.group.searchfilter=" + groupSearchFilter);

    } finally {

        if (groupSearchResultEnum != null) {
            groupSearchResultEnum.close();
        }
    }
}
 
Example 20
Source File: SimpleLDAPAuthenticationManagerImpl.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
private String getNameFromId(final String id, final Subject gssapiIdentity)
        throws NamingException
{
    if (!isBindWithoutSearch())
    {
        InitialDirContext ctx = createSearchInitialDirContext(gssapiIdentity);

        try
        {
            SearchControls searchControls = new SearchControls();
            searchControls.setReturningAttributes(new String[]{});
            searchControls.setCountLimit(1L);
            searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

            LOGGER.debug("Searching for '{}'", id);
            NamingEnumeration<?> namingEnum = invokeContextOperationAs(gssapiIdentity,
                                                  (PrivilegedExceptionAction<NamingEnumeration<?>>) () -> ctx.search(
                                                          _searchContext,
                                                          _searchFilter,
                                                          new String[]{id},
                                                          searchControls));

            if (namingEnum.hasMore())
            {
                SearchResult result = (SearchResult) namingEnum.next();
                String name = result.getNameInNamespace();
                LOGGER.debug("Found '{}' DN '{}'", id, name);
                return name;
            }
            else
            {
                LOGGER.debug("Not found '{}'", id);
                return null;
            }
        }
        finally
        {
            closeSafely(ctx);
        }
    }
    else
    {
        return id;
    }
}