Solved

javax.naming

Posted on 2001-08-30
6
206 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

 

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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
A solution for Fortify Path Manipulation.
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
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.
Suggested Courses

635 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