JNDI Naming and directory operations

Source: Internet
Author: User
Tags ldap java se

Naming and Directory Operations
Original address: https://docs.oracle.com/javase/tutorial/jndi/TOC.html
You can use Jndi for naming operations, including read and update operation namespaces. The following actions are described in this article: Find objects List contents of context Add, overwrite, remove bindings rename objects Create and destroy Subcontext configuration

Before naming or directory services for any operation, you need to get the inital context, which starts at the start point of the namespace. This is because all naming and directory service methods are performed in some context. To get the inital context, you must follow these steps. Select the service provider for the appropriate service you want to access specify the configuration that the inital context requires. Call the InitialContext constructor first step: Select the service provider for the inital context

You can create a inital context for a service provider by specifying a set of environment properties (hashtable types), or add the name of a service provider class to the inital context
This link provides a detailed tutorial on the use of environment properties. https://docs.oracle.com/javase/jndi/tutorial/beyond/env/index.html
If you are using an LDAP Service provider that is included with JDK, your code looks like this:

hashtable<string, object> env = new hashtable<string, object> ();
Env.put (Context.initial_context_factory, "com.sun.jndi.ldap.LdapCtxFactory");

To specify the file system service provider in the JDK, your code looks like this:

hashtable<string, object> env = new hashtable>string, object> ();
Env.put (Context.initial_context_factory, "com.sun.jndi.fscontext.RefFSContextFactory");

You can also use System properties to specify that the service is provided to the program using:
Https://docs.oracle.com/javase/jndi/tutorial/beyond/index.html Step Two: Provide the information needed for the inital context

Clients of different directories may need different information to contact the directory. For example, you might want to indicate which server is running and what information is required to identify the user to that directory. Such information is passed to the service provider through environment properties. JNDI specifies some common environment properties to be used by service providers. Your service provider documentation provides detailed information about these properties.
The LDAP provider requires that the program specify the location of the LDAP server, as well as user identity information. To provide this information, you can write the following code:

Env.put (Context.provider_url, "ldap://ldap.wiz.com:389");
Env.put (Context.security_principal, "joeuser");
Env.put (Context.security_credentials, "Joepassword");

The following example uses the LDAP service provider in the JDK. This example assumes that the server has started and used the port 389 on the local machine and the user name "O=jnditutorial". This is an update directory that does not require authentication. They include the following code to create an environment

Env.put (Context.provider_url, "ldap://localhost:389/o=jnditutorial");

If you are using a different set of directories, you will need to set these environment properties accordingly. You will need to replace the machine name "localhost", and you can run these samples on any Non-public directory server or on your own server. You will need to replace the machine name "localhost" and username o=jnditutorial. Step Three: Create the inital context

You are now ready to create the inital context. To do this, you provide the environment properties that you created earlier to the InitialContext constructor:

Context ctx = new InitialContext (env);

Now that you have a reference to a context object, you can begin to access the naming service.
To perform directory operations, you need to use a initialdircontext. To do this, you need to use its constructor:

DirContext CTX = new InitialDirContext (env);

This statement returns a DirContext reference object that performs a directory operation. Naming Exceptions

Many methods in the Jndi package throw namingexception when the required request operation cannot be performed. Typically, you'll see a try/catch code block, or throw a namingexception:

Try {context
    CTX = new InitialContext ();
    Object obj = ctx.lookup ("somename");
} catch (Namingexception e) {
    //Handle the error
    System.err.println (e);
}
hierarchy of Exception classes

Jndi has a rich exception hierarchy, and all exceptions have a common base class: Namingexception.
The following is an example of using subclass Authenticationexception:

Try {context
    CTX = new InitialContext ();
    Object obj = ctx.lookup ("somename");
} catch (Authenticationexception e) {
    //attempt to reacquire the authentication information
    ...
} catch (Na Mingexception e) {
    //Handle the error
    System.err.println (e);
}
Enumeration

For example, Context.list () and Dircontext.search () will return a namingenumeration. In this case, if an error occurs and no results are returned, then namingexception or its corresponding subclass will be thrown.
If an error occurs, some results are returned and a namingenumeration is returned so that you can get the results. When all the results are exhausted, invoking Namingenumeration.hasmore () causes namingexception (or one of its subclasses) to be thrown. At this point, the enumeration is invalid and no other method can be invoked.
For example, if you execute a search () and specify a number (N) to limit how many result sets to return, search () returns a result set containing the most N results. If the number of results is more than N, and then Namingenumeration.hasmore () is called N + 1 times, a sizelimitexceededexception is thrown.
All the exception descriptions can be found here:
https://docs.oracle.com/javase/8/docs/api/javax/naming/package-summary.html Find Objects

Use Context.lookup () to find objects in the named service, using the name of the object you want to retrieve. Suppose you have a name in the object naming service: Cn=rosanna lee,ou=people. To retrieve the object, you will write

Object obj = ctx.lookup ("Cn=rosanna lee,ou=people");

The target type returned by lookup () depends on the underlying naming system and the data associated with the object itself. A named system can contain many different types of objects, and looking up objects in different parts of the system may produce different types of objects. In the example above, "Cn=rosanna lee,ou=people" happens to be the object bound to the context (Javax.naming.ldap.LdapContext). You can use lookup () to find the target class:

For example, the following code finds the object "Cn=rosanna lee,ou=people" and converts it to ldapcontext.

Import Javax.naming.ldap.LdapContext;
...
Ldapcontext CTX = (ldapcontext) ctx.lookup ("Cn=rosanna lee,ou=people");

The complete sample file is in Lookup.java:
Https://docs.oracle.com/javase/tutorial/jndi/ops/examples/Lookup.java

Here are 2 new static methods to find a name in Java SE 6:
Initialcontext.dolookup (name name)
Initialcontext.dolookup (String name)
These methods provide a shortcut to find initialcontext that does not need to be instantiated to list the contents of the context

If you do not use Context.lookup () to get a single object at a time, you can list the contents of the context by using a single action. There are two ways to list the context: One is the method that returns the binding, and one returns the Name-to-object class. Context.list ()
Returns a Nameclasspair enumeration in which each Nameclasspair contains the object name and class name, and the following code fragment lists the contents of the "Ou=people" directory (that is, the appropriate files and directories found in the "Ou=people" directory).

Namingenumeration list = ctx.list ("Ou=people");

while (List.hasmore ()) {
    Nameclasspair NC = (nameclasspair) list.next ();
    SYSTEM.OUT.PRINTLN (NC);

Run this example to produce the following output:

# java List cn=jon Ruiz:javax.naming.directory.DirContext Cn=scott Seligman:javax.naming.directory.DirContext cn= Samuel Clemens:javax.naming.directory.DirContext Cn=rosanna Lee:javax.naming.directory.DirContext cn=maxine erlund: Javax.naming.directory.DirContext cn=niels Bohr:javax.naming.directory.DirContext Cn=uri Geller: Javax.naming.directory.DirContext cn=colleen Sullivan:javax.naming.directory.DirContext Cn=vinnie Ryan: Javax.naming.directory.DirContext Cn=rod Serling:javax.naming.directory.DirContext Cn=jonathan Wood: Javax.naming.directory.DirContext Cn=aravindan Ranganathan:javax.naming.directory.DirContext Cn=ian Anderson: Javax.naming.directory.DirContext Cn=lao Tzu:javax.naming.directory.DirContext Cn=don Knuth: Javax.naming.directory.DirContext Cn=roger Waters:javax.naming.directory.DirContext Cn=ben Dubin: Javax.naming.directory.DirContext cn=spuds Mackenzie:javax.naming.directory.DirContext Cn=john Fowler: Javax.naming.directory.DirContext Cn=londo Mollari:jaVax.naming.directory.DirContext cn=ted Geisel:javax.naming.directory.DirContext 
Context.listbindings ()
Returns a binding enumeration, binding is a Nameclasspair subclass. Binding contains the name of the object and the class name, but it also contains the object itself. The following code enumerates the context of "ou=people" and prints out the name and object of each binding.
Namingenumeration bindings = ctx.listbindings ("Ou=people");

while (Bindings.hasmore ()) {
    Binding bd = (Binding) bindings.next ();
    System.out.println (Bd.getname () + ":" + bd.getobject ());
}

Run this example to produce the following output:

# java listbindings cn=jon ruiz:com.sun.jndi.ldap.ldapctx@1d4c61c Cn=scott seligman:com.sun.jndi.ldap.ldapctx@1a626f Cn=samuel CLEMENS:COM.SUN.JNDI.LDAP.LDAPCTX@34A1FC Cn=rosanna lee:com.sun.jndi.ldap.ldapctx@176c74b cn=Maxine ERLUND:COM.SUN.JNDI.LDAP.LDAPCTX@11B9FB1 cn=niels bohr:com.sun.jndi.ldap.ldapctx@913fe2 Cn=Uri Geller: Com.sun.jndi.ldap.ldapctx@12558d6 cn=colleen sullivan:com.sun.jndi.ldap.ldapctx@eb7859 Cn=Vinnie Ryan: Com.sun.jndi.ldap.ldapctx@12a54f9 Cn=rod serling:com.sun.jndi.ldap.ldapctx@30e280 Cn=Jonathan Wood: COM.SUN.JNDI.LDAP.LDAPCTX@16672D6 Cn=aravindan ranganathan:com.sun.jndi.ldap.ldapctx@fd54d6 Cn=Ian Anderson: Com.sun.jndi.ldap.ldapctx@1415de6 Cn=lao tzu:com.sun.jndi.ldap.ldapctx@7bd9f2 cn=Don Knuth: Com.sun.jndi.ldap.ldapctx@121cc40 Cn=roger waters:com.sun.jndi.ldap.ldapctx@443226 cn=Ben Dubin: com.sun.jndi.ldap.ldapctx@1386000 cn=spuds mackenzie:com.sun.jndi.ldap.ldapctx@26d4f1 Cn=John Fowler: Com.sun.jndi.ldap.ldapctx@1662dc8 Cn=londo mollari:com. SUN.JNDI.LDAP.LDAPCTX@147C5FC cn=ted Geisel:com.sun.jndi.ldap.ldapctx@3eca90 
Terminate a namingenumeration

A namingenumeration can have three ways: natural termination, clarity, or accident. When Namingenumeration.hasmore () returns false, the enumeration is a complete and valid termination. You can explicitly terminate the enumeration by calling Namingenumeration.close (). This provides a hint to the underlying implementation to release any resources associated with the enumeration. If Hasmore () or Next () throws a namingexception, then the enumeration is terminated effectively. why there are two different list methods.

List () is an application that browses mode, and only wants to display the name of the object in a context. For example, a browser lists the names in the context first, waits for the user to select one or several, and then displays the name of the further action. Such an application usually does not need to access all the objects in the context.
Listbindings () is used for applications that need to perform operations on all objects in the context. For example, a backup application might need to perform a "file statistics" operation on all objects in the file directory. or the printer management program may want to restart all printers for one project. To do so, these applications need to get all the objects in the context. Therefore, it is more advantageous to return the object as part of the enumeration.
Applications can use the list () or more expensive listbindings (), depending on the type of information needed. Add, replace, or delete bindings

The context interface contains methods for adding, replacing, and deleting bindings for the context add bindings
Context.bind () is used to add a binding to the context that accepts the bound object name and object as parameters.

Create objects that need to be bound
Fruit Fruit = new Fruit ("Orange");

Perform binding
ctx.bind ("Cn=favorite Fruit", Fruit);

This example creates an object of a fruit class and binds it to the "Cn=favorite Fruit" into the context named CTX. If you subsequently use CTX's lookup name: "Cn=favorite Fruit", then you will get Fruit object.
If you run this example two times, then the exception will be thrown: namealreadyboundexception. This is because the name "Cn=favorite Fruit" has been bound. For a second successful attempt, you will have to use rebind ().

To add or replace a binding:
Rebind () is used to add or replace bindings. It accepts the same parameters as bind (), but the semantics is this, and if it is already bound, it binds the new object.

Create the object to be bound
Fruit Fruit = new Fruit ("Lemon");

Perform the bind
ctx.rebind ("Cn=favorite Fruit", Fruit);

When you run this example, it will replace the object created by the bind () example
Removing bindings

Remove bindings using unbind ().

Remove The binding
ctx.unbind ("Cn=favorite Fruit");

Here are three complete examples:
Https://docs.oracle.com/javase/tutorial/jndi/ops/examples/Rebind.java
Https://docs.oracle.com/javase/tutorial/jndi/ops/examples/Bind.java
Https://docs.oracle.com/javase/tutorial/jndi/ops/examples/Unbind.java Renaming

You can rename an object in the context by Context.rename ()

Rename to Scott S
ctx.rename ("Cn=scott Seligman", "Cn=scott S");

This example renames the object to be bound to "Cn=scott Seligman" to "Cn=scott S" as follows:

Rename back to Scott Seligman
ctx.rename ("Cn=scott S", "Cn=scott Seligman");
Create and Destroy Subcontext

The context interface contains methods for creating and destroying subcontext, and a context is necessarily the same type as another context.
The example presented here uses an object with attributes and creates subcontext into the directory. You can use DirContext to associate the zodiac to the object, while adding binding and subcontext to the namespace. For example, you can create an object, bind it to a namespace, and associate the object's properties at the same time. This name equivalence has no attributes.
Createsubcontext () Creates a new object, Dircontext.createsubcontext () creates a child object, and needs to specify the properties and context to create a context

Create a context that you provide to the name of the Createsubcontext () context. Createsubcontext () Name of the case you want to create and its properties.

Create attributes to is associated with the new context
attributes Attrs = new Basicattributes (true);//Case-ignor E
Attribute objclass = new BasicAttribute ("objectclass");
Objclass.add ("top");
Objclass.add ("organizationalunit");
Attrs.put (objclass);

Create the context result
= Ctx.createsubcontext ("NewOU", attrs);

This example creates a new context in which the "Ou=newou" has a property "objectclass" with two values, "Top" and "organizationalunit", in ctx contexts.

# java Create
ou=groups:javax.naming.directory.dircontext
ou=people:javax.naming.directory.dircontext
Ou=newou:javax.naming.directory.dircontext

This example creates a new background, called "NewOU," which is a CTX context.
Destroy context

Destroying the context, you provide the name of the Destroysubcontext () context to destroy.

Destroy the context
ctx.destroysubcontext ("NewOU");

This is the complete code for destroying the context:
Https://docs.oracle.com/javase/tutorial/jndi/ops/examples/Destroy.java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.