naming
Parsing a JNDI compound name example
In this example we are going to see how to perform Parsing on JNDI compound name. This example parses a compound name using a parser from an LDAP service in which components are arranged from right to left, delimited by the comma character (,). The LDAP service is running on localhost and on default port (389)
Parsing a JNDI compound name requires that you:
- Create a new
Hashtable
and name itenv
. - Use
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory")
. - Use
env.put(Context.PROVIDER_URL,"ldap://localhost/o=JNDIExample")
- Create new
Context
usingInitialContext(env)
. - Use
ctx.getNameParser
to get aNameParser
. - And get a
Name
withparser.parse("cn=byron, ou=People, o=JNDIExample")
.
Here is the code:
package com.javacodegeeks.snippets.enterprise; import java.util.Hashtable; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.Name; import javax.naming.NameParser; import javax.naming.NamingException; public class ParseJNDICompoundName { public static void main(String[] args) { try { /* * This example parses a compound name using a parser from an LDAP service in which * components are arranged from right to left, delimited by the comma character (,). * The LDAP service is running on localhost and on default port (389) */ Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://localhost/o=JNDIExample"); Context ctx = new InitialContext(env); System.out.println("Initial Context created successfully"); NameParser parser = ctx.getNameParser(""); Name dn = parser.parse("cn=byron, ou=People, o=JNDIExample"); System.out.println("Compound name : " + dn); System.out.println("Second component : " + dn.remove(1)); dn.add(0, "c=gr"); System.out.println("After adding component 'c=gr' at the end : " + dn); dn.add("cn=ilias"); System.out.println("After adding component 'cn=ilias' at the beginning : " + dn); } catch (NamingException e) { System.out.println("Exception occurred while parsing Compound name : " + e.getMessage()); } } }
Output:
Initial Context created successfully
Compound name : cn=byron, ou=People, o=JNDIExample
Second component : ou=People
After adding component 'c=gr' at the end : cn=byron,o=JNDIExample,c=gr
After adding component 'cn=ilias' at the beginning : cn=ilias,cn=byron,o=JNDIExample,c=gr
This was an example on how to parse a JNDI compound name.