naming

Create an Initial Context to a Directory

In this example we are going to see how to create an Initial Context to a Directory. This example uses the JNDI/LDAP service provider to connect to an LDAP server on the local machine.

In order to do that you should :

  • Create a new Hashtable.
  • Use put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory")
  • Use put(Context.PROVIDER_URL, "ldap://localhost/o=JNDIExample").
  • For simple authentication we can use :
    • env.put(Context.SECURITY_AUTHENTICATION, "simple")
    • env.put(Context.SECURITY_PRINCIPAL, "userDN")
    • env.put(Context.SECURITY_CREDENTIALS, "secret")
  • Create a new DirContext using InitialDirContext method .

Let’s see the code:

package com.javacodegeeks.snippets.enterprise;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

public class CreateInitialDirContext {

  public static void main(String[] args) {

// This example uses the JNDI/LDAP service provider to connect to an LDAP server on the local machine

Hashtable env = new Hashtable();

env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

env.put(Context.PROVIDER_URL, "ldap://localhost/o=JNDIExample");

/*

 * For simple authentication we can use :

 *

 * env.put(Context.SECURITY_AUTHENTICATION, "simple");

 * env.put(Context.SECURITY_PRINCIPAL, "userDN");

 * env.put(Context.SECURITY_CREDENTIALS, "secret");

 */

try {

    DirContext ctx = new InitialDirContext(env);

    System.out.println("Initial Directory Context created successfully");

} catch (NamingException e) {

    System.out.println("Could not create directory context : " + e.getMessage());

}

  }
}

Example Output:

Initial Directory Context created successfully

 
This was an example on how to create an Initial Context to a Directory.

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions

 

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button