user2093952
user2093952

Reputation: 21

LDAP JNDI subtree searching

I have a problem of searching LDAP. If I use the following code, I can get level 2 using the following code. But I want to get Level 4 object. Thanks for any kind help.

The current search base: ou=HQ2-BR, filter: "(ou=*)";

Regards, Man Pak Hong, Dave [email protected] [email protected]

LDAP structure

The code:

public void loopLDAP() {
    String adminName = "uid=writer,ou=People,o=com,dc=rabbitforever";
    String adminPassword = "password";

    Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY,
            "com.sun.jndi.ldap.LdapCtxFactory");
    //env.put(Context.PROVIDER_URL,
    //        "ldap://192.168.1.127:389/dc=rabbitforever,dc=com");
    env.put(Context.PROVIDER_URL,
            "ldap://10.10.176.156:389/o=com,dc=rabbitforever");
    //env.put(Context.SECURITY_AUTHENTICATION, "none");

    env.put(Context.SECURITY_PRINCIPAL, adminName);
    env.put(Context.SECURITY_CREDENTIALS, adminPassword);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.REFERRAL, "follow");

    try {
        LdapContext ctx = new InitialLdapContext(env, null);
        ctx.setRequestControls(null);

        String filter = "(ou=*)";

        NamingEnumeration<?> namingEnum = ctx.search("ou=HQ2-BR", filter,
                getSimpleSearchControls());
        while (namingEnum.hasMore()) {
            SearchResult result = (SearchResult) namingEnum.next();
            Attributes attrs = result.getAttributes();

            String cn = "";
            String sn = "";
            String description = "";
            String uid = "";
            if (null != attrs.get(cn)) {
                cn = attrs.get("cn").toString();
            }
            if (null != attrs.get("sn")) {
                sn = attrs.get("sn").toString();
            }
            if (null != attrs.get("description")) {
                description = attrs.get("description").toString();
            }
            if (null != attrs.get("uid")) {
                uid = attrs.get("uid").toString();
            }
            System.out.println(cn + " | " + sn + " | " + description
                    + " | " + uid);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
} // end loopLDAP()

Upvotes: 2

Views: 4046

Answers (1)

Alex
Alex

Reputation: 377

You probably need to construct SearchControls object with SearchControls.SUBTREE_SCOPE, and pass it to ctx.search method. See example from another answer.

Upvotes: 2

Related Questions