Solved

javax.naming

Posted on 2001-08-30
6
203 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
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 

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

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

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…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

813 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

13 Experts available now in Live!

Get 1:1 Help Now