Solved

javax.naming

Posted on 2001-08-30
6
204 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
Resolve Critical IT Incidents Fast

If your data, services or processes become compromised, your organization can suffer damage in just minutes and how fast you communicate during a major IT incident is everything. Learn how to immediately identify incidents & best practices to resolve them quickly and effectively.

 

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

How our DevOps Teams Maximize Uptime

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us. Read the use case whitepaper.

Question has a verified solution.

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

Suggested Solutions

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

685 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