FelasDroid
FelasDroid

Reputation: 643

How can i get data from ldap with JNDI

sorry i'm noob in JNDI, i try to connect to my LDAPS with a simple auth with JNDI, but i don't know how i can after connection get data So my code is:

 public static void main(String[] args) {

// Set up environment for creating initial context
Hashtable<String, String> env = new Hashtable<String, String>(11);
env.put(Context.INITIAL_CONTEXT_FACTORY, 
    "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldaps://myadress:636");

// Authenticate as S. User and password "mysecret"
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "my BASE DN");
env.put(Context.SECURITY_CREDENTIALS, "mypass");


try {
    // Create initial context
    DirContext ctx = new InitialDirContext(env);
    // Close the context when we're done
    ctx.close();
} catch (NamingException e) {
    e.printStackTrace();
}
}

after

DirContext ctx = new InitialDirContext(env);`

i want get my tree and some data, but how?..for example my tree is:

-ou=people,dc=info,dc=uni,dc=com

---ou=students
-----uid=5tey37

how i can get data for the uid ?

sorry i'm a noob, and sorry for my english

Upvotes: 2

Views: 1063

Answers (1)

StoopidDonut
StoopidDonut

Reputation: 8617

You invoke a search on the context with specific parameters. In your example, you can do a context search based on the specific uid and get all the different attributes available corresponding to a directory object.

An example below, you might want to tweak the search and attributes specific to your directory

// Create initial context
DirContext ctx = new InitialDirContext(env);

String searchBase = "ou=people";
SearchControls searchCtls = new SearchControls();

// Specify the search scope
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

String uid = "5tey37";
String searchFilter = " (uid=" + uid + ") ";

NamingEnumeration<?> namingEnum = ctx.search(searchBase,searchFilter, searchCtls);
while (namingEnum.hasMore()) {
    SearchResult result = (SearchResult) namingEnum.next();
    // GET STUFF
    Attributes attrs = result.getAttributes();
    System.out.println(attrs.get("uid"));
...

}
namingEnum.close();
// Close the context when we're done
ctx.close();

Upvotes: 4

Related Questions