Search code examples
javaspring-ldapldap-query

how to stop ldap search when result is found


I am trying to get loggedin user's group name from distinguishedName parameter. I can find the group name but search is countine, even if i find the person in ldap search and in the and gets

PartialResultException: Unprocessed Continuation Reference(s);

Here is My code

I want to stop ldapTemplate.search process when I got a successful result do you guys have any idea ?

public List<String> getUserGroup(String username) throws Exception {
        try {
            LdapQuery query;
            LdapTemplate ldapTemplate = ldapConf.ldapTemplate();
            if (ldapConf.getSearchBase().isEmpty()) {
                System.out.println("searchbase empty");
                query = query().where(env.getProperty("retouch.ldap.searchKeyword")).isPresent();
            } else
                query = query().base(ldapConf.getSearchBase()).where(env.getProperty("retouch.ldap.searchKeyword")).isPresent();
            List<String> result = ldapTemplate.search(query, new AttributesMapper<String>() {
                public String mapFromAttributes(Attributes attrs) throws NamingException, javax.naming.NamingException {

                    for (Enumeration vals = attrs.get("distinguishedName").getAll(); vals.hasMoreElements();) {
                        String userName = (String) vals.nextElement();
                        if (userName.contains(username)) {
                            return (String) attrs.get("distinguishedName").get();
                        }
                    }

                    return null;
                }
            });
            logger.debug("ldap groups" + result);
            while (result.remove(null)) {
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e, e);
            throw e;
        }
    } 

Solution

  • I totally misunderstood ldap search mechanism. My ldap query was also wrong

    query = query().where(env.getProperty("ldap.searchKeyword")).isPresent();

    instead of isPresent() I should have used is(username) so I can directly get the user that I want. Also I was trying to get user DN in my code. Instead of new AttributesMapper<String>() , new ContextMapper<String>() provide the DN