Find BASE DN from LDAP directory context object

2019-08-17 03:00发布


I have directory context for LDAP but i need to find out the BASE DN from that directory context object. I have following code to get Directory context object,

// Configure our directory context environment.
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://test.mycomp.com:389");
env.put(Context.SECURITY_AUTHENTICATION, "Simple");
env.put(Context.SECURITY_PRINCIPAL,"uid=test.gen,OU=Generics,O=test.mycomp.com");
env.put(Context.SECURITY_CREDENTIALS, "test123");
DirContext dirContext = new InitialDirContext(env);
System.out.println("loaded dirContext");

I have following code to get the Base DN, I has been returning base DN name but i want to make my filter optimised rather than putting 2 loops to get base DN,

    SearchControls constraints = new SearchControls();
    constraints.setSearchScope(SearchControls.OBJECT_SCOPE);
    NamingEnumeration results = dirContext.search("",
            "(&(objectClass=organization)(objectClass=top))", constraints);

        // Fail if no entries found
    if (results == null || !results.hasMore()) {
        System.out.println("No result found");
        return;
    }

    while(results.hasMoreElements()){
        Object res = results.next();
        SearchResult serResult = (SearchResult) res;
        Attributes atts = serResult.getAttributes();
        System.out.println(atts.toString());
        Attribute baseAttr = atts.get("namingContexts");
        NamingEnumeration  ids = baseAttr.getAll();
        while(ids.hasMoreElements()){
            Object obj = ids.next();
            System.out.println(obj.toString());
        }
    }

Please help me out to optimize my filter.

2条回答
乱世女痞
2楼-- · 2019-08-17 03:24

LDAP-compliant directory servers should provide information about the namingContexts when the root DSE is queried. For more information about the root DSE, see "LDAP: The root DSE". The UnboundID LDAP SDK provides a class to encapsulate the root DSE and a convenience method to retrieve it.

查看更多
何必那么认真
3楼-- · 2019-08-17 03:39

You don't need the search. Just get the namingContexts attribute from the InitialContext.

Attributes atttrs = context.getAttributes("", new String[]{"namingContexts"});
查看更多
登录 后发表回答