Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

javax.naming

Posted on 2001-08-30
6
Medium Priority
?
208 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
Build and deliver software with DevOps

A digital transformation requires faster time to market, shorter software development lifecycles, and the ability to adapt rapidly to changing customer demands. DevOps provides the solution.

 

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 400 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

Basic Security of Your VPC

So, you’ve got this shiny new VPC and a fancy new application configured on your EC2 servers ready to go. This application is only accessible from your computer, which is great for security, but you need your users to be able to access it! So, what’s the easiest way to do this?

Question has a verified solution.

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

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
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 third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
Suggested Courses

722 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