Solved

javax.naming

Posted on 2001-08-30
6
201 Views
Last Modified: 2013-11-24
The code below outputs the result based the Organisational Unit("ou=People", matchAttrs). I need code-example on how to get all users based on the groupname(group in LDAP).


// Specify the attributes to match
// Ask for objects that has a surname ("sn") attribute with
// the value "Geisel" and the "mail" attribute
Attributes matchAttrs = new BasicAttributes(true); // ignore attribute name case
matchAttrs.put(new BasicAttribute("sn", "Geisel"));
matchAttrs.put(new BasicAttribute("mail"));

// Search for objects that have those matching attributes
NamingEnumeration answer = ctx.search("ou=People", matchAttrs);

You can then print the results as follows.
while (answer.hasMore()) {
    SearchResult sr = (SearchResult)answer.next();
    System.out.println(">>>" + sr.getName());
    printAttrs(sr.getAttributes());
}

0
Comment
Question by:jaatun
  • 3
  • 2
6 Comments
 
LVL 1

Expert Comment

by:RichardA
ID: 6440094
I have code for searching using a little different approach
I Import..

import javax.naming.Context;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.DirContext;
import javax.naming.directory.Attributes;
import javax.naming.NamingException;
import javax.naming.directory.*;
import javax.naming.*;
import java.util.*;

My search code is...
Note where I set the Search filter and you need to provide LDAP URL.  Your filter may be a little different depending on whether you have an LDAP attribute of  group.  This one gets all in group.  You could specify a name also.



        String sn = "";
        String mail = "";

        // set the filter for the search
        String filter = ("group=*");
       
        // Set up environment for creating initial context
        Hashtable env = new Hashtable(5);
        env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, "LDAP URL GOES HERE");
       
        try {
            // Create initial context
            DirContext ctx = new InitialDirContext(env);
           
            // do something useful with ctx
            String[] attrIDs = {"sn","mail"};
            SearchControls ctls = new SearchControls();
            ctls.setReturningAttributes(attrIDs);
            ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
           
            // Search subtree for objects using filter
            NamingEnumeration ne = ctx.search("", filter, ctls);
           
            try {
                while (ne.hasMore()) {
                    SearchResult sr = (SearchResult)ne.next();
                    // System.out.println(sr.getName());
                    Attributes ats = sr.getAttributes();
                    int i;
                   
                    Attribute atsn = ats.get("sn");
                    if (atsn != null)  sn += (String)atsn.get();
                   
                    Attribute atmail = ats.get("mail");
                    if (atmail != null)  mail += (String)atmail.get();
                   
                }// end while
               
            } catch (javax.naming.NamingException e) {
                System.out.println("ERROR: " + e);
            }
           
            ctx.close();
        } catch (NamingException e) {
            e.printStackTrace();
        }
0
 
LVL 1

Expert Comment

by:chauhanvinit
ID: 6452753
Hi,

This code will solve your problem:-
Punch line is use "objectclass=*" to get all attribute and
then look for what u want.
U cannot get complete user list from the Ldap server
because server have limitations on sending results.
So it might be that after 500 entries u may get
a size limit exception.

Remeber to substitute baseDN with actual Distinguished
Name on which search is to be made.



public static void main(String[] args) {

    String ldapServer = "ldap://server";
    String baseDN = "baseDN";
    Hashtable env = new Hashtable(5, 0.75f);
     env.put(Context.INITIAL_CONTEXT_FACTORY,
         "com.sun.jndi.ldap.LdapCtxFactory");
     env.put(Context.PROVIDER_URL, ldapServer);
    env.put(Context.SECURITY_AUTHENTICATION, "none");



    try {
        DirContext ctx = new InitialDirContext(env);
        String[] attrIDs = {"cn", "mail"};
        SearchControls constraints = new SearchControls();
        constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        constraints.setReturningAttributes(attrIDs);
        System.out.println("time: " + constraints.getTimeLimit());

        NamingEnumeration results
            = ctx.search(baseDN, "(objectclass=*)", constraints);

        int i = 0;
        System.out.println("no of entries " + i);
        while (results != null && results.hasMore()) {
            SearchResult si = (SearchResult)results.next();
            i++;
            /* print its name */
            System.out.println("name: " + si.getName());

            Attributes attrs = si.getAttributes();
            if (attrs == null) {
                System.out.println("No attributes");
            } else {
                //System.out.println("not null");
                /* print each attribute */

                for (NamingEnumeration ae = attrs.getAll();
                     ae.hasMoreElements();) {
                    Attribute attr = (Attribute)ae.next();
                    String attrId = attr.getID();

                    /* print each value */
                    for (Enumeration vals = attr.getAll();
                         vals.hasMoreElements();
                         System.out.println(attrId + " = " + vals.nextElement()))
                            ;
                }
            }
            System.out.println();
        }
        ctx.close();
    } catch (NamingException e) {
        System.out.println(e.getClass().getName());
        System.err.println("Search example failed.");
        e.printStackTrace();
    }
}
0
 

Author Comment

by:jaatun
ID: 6460597
1) This code works fine if you want a list of all users and groups under baseDN, but what if you just want to list the users in one of the groups?

2) I list the users based on organisation units. How do I list the users based on the groupname?

3) Why are there limitations on sending results from a ldap-server and how do you set the limitations? Can you still list all users in one group or will the limitations stop when you reach the limit?
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:jaatun
ID: 6463457
To RichardA,

String filter = ("group=*");
When using this filter my server will not return anything. When I use ("objectclass=*") it will list everything under baseDN. Do you know why?

0
 
LVL 1

Expert Comment

by:chauhanvinit
ID: 6463475
Hi,
There must be no object such as group under the base DN.
But objectclass=* will give u everything under that DN
and u can pick up from there what u want.


0
 
LVL 1

Accepted Solution

by:
chauhanvinit earned 200 total points
ID: 6463489
Answers to your question:-
1) This code works fine if you want a list of all users and groups under baseDN, but what if you just
want to list the users in one of the groups?

Then the base DN for begining the search should be
something like(depends upon yur ldap server):-
"ou=groupname o=organisation c=country"
so under the ou=groupname there would be entries for users.


2) I list the users based on organisation units. How do I list the users based on the groupname?
I think the above comment will help you out.

3) Why are there limitations on sending results from a ldap-server and how do you set the limitations?
Can you still list all users in one group or will the limitations stop when you reach the limit?

This limitation is set by the Ldap server
you dont have any control over it.
As soon as it is reached u will get a size limit
exception, thats all. So u cannot get the full list of
users if that limit is less than users.


0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now