Overview of naming and directory interface Jndi in Java Basic operation methods _java

Source: Internet
Author: User
Tags ldap list of attributes object object jboss tomcat

The overall understanding of Jndi:

Jndi (Java naming and directory Interface) it provides a set of interfaces that use naming and directory services. It allows users to use naming and directory services. Just like JDBC. Jndi includes both the naming service and the directory service, where the directory service contains directory object directory objects, which contains several property objects. Provides a number of actions on a property.
Naming and Directory services:

Naming and Directory services we have been using, such as the operating system file system, which gives us the ability to file operations, queries, add deletions, and more. The DNS service binds URLs together with IP addresses. The most important function of naming and directory systems is to bind name and object. On top of it, there are more features such as Lookup,search. and stored objects have a certain level of structure. With such a service we can manage and manipulate objects more efficiently.
The naming service maps a name to an object. Both the RMI registry and the CORBA naming service are named services.
The directory service also holds objects, but the directory service recognizes the related properties of those objects. You can use Project properties to search for a directory.
In the early the 1990s, Lightweight Directory Access Protocol (LIGHTWEIGHTDIRETORYACCESSPROTOCOL,LDAP) was developed as a standard directory protocol, and Jndi was able to access LDAP.
J2SE provides 5 expansion packs for Jndi:

    • Javax.naming the API provided for accessing the naming service
    • Javax.naming.directory; Provides a basic interface for accessing directory services
    • Javax.naming.event support for event notifications in naming and directory services
    • JAVAX.NAMING.LDAP support for LDAP packages,
    • JAVAX.NAMING.SPI provides a way for different naming and directory services to hook up their implementations.

Context:context is a set of Name-to-object bindings (bindings) that can be understood as hierarchies or directories, and it can also include the next layer of subcontext. Obtaining the initial context when using naming and directory services is the entry point for the entire namespace operation. In the directory service is DirContext.
JNDI (Java naming and directory Interface) is an application-designed API that provides developers with a common, unified interface for locating and accessing various naming and directory services, similar to JDBC, built on an abstraction layer.
The existing directories and services that JNDI can access are:
DNS, Xnam, Novell Directory Service, LDAP (Lightweight Directory Access Protocol Lightweight Directory accessing protocol), CORBA object Service, file system, Windows xp/2000/nt/me/ 9x registry, RMI, DSML v1&v2, NIS.
Jndi Benefits:
includes a large number of naming and directory services, using a common interface to access different kinds of services, connecting to multiple naming or directory services at the same time, and establishing logical associations that allow names to be associated with Java objects or resources without having to guide the physical IDs of objects or resources.

Jndi Package:

    • Javax.naming: Naming operations;
    • Javax.naming.directory: directory operation;
    • Javax.naming.event: Request event notification in a named directory server;
    • JAVAX.NAMING.LDAP: Provide LDAP support;
    • JAVAX.NAMING.SPI: Allows dynamic insertion of different implementations.
    • Use Jndi's naming and service capabilities to meet enterprise-class APIs for naming and service access, such as EJBs, JMS, JDBC 2.0, and RMI on IIOP using CORBA's naming service via Jndi.

Jndi and JDBC:
Jndi provides a unified way to find and access services on the network. By specifying a resource name that corresponds to a record in the database or naming service, it returns the information necessary to establish the database connection.
code example:

try{context
Cntxt = new InitialContext ();
DataSource ds = (DataSource) cntxt.lookup ("JDBC/DPT");
}
catch (Namingexception ne) {
...
}

Jndi and JMS:
message communication is a method used by software components or applications to communicate. JMS is a Java technology that allows applications to create, send, receive, and read messages.
code example:

try{
Properties env = new properties ();
InitialContext inictxt = new InitialContext (env);
Topicconnectionfactory connfactory = (topicconnectionfactory) inictxt.lookup ("Ttopicconnectionfactory");
...
}
catch (Namingexception ne) {
...
}

Access to a specific directory: for example, a person is an object, he has several attributes, such as the person's name, phone number, e-mail address, postal code and other attributes. Through the GetAttributes () method

Attribute attr = directory.getattributes (personname). Get ("email");
string email = (string) attr.get ();

Use Jndi to let customers use the name or properties of an object to find an object:

Foxes = Directory.search ("O=wiz,c=us", "Sn=fox", controls);

Find examples of printers by using Jndi to find objects such as printers and databases:

Printer Printer = (Printer) namespace.lookup (printername);
Printer.print (document);

Browsing namespaces:

Namingenumeration list = Namespace.list ("O=widget, C=us");
while (List.hasmore ()) {
Nameclasspair entry = (Nameclasspair) list.next ();
Display (Entry.getname (), Entry.getclassname ());

    • Common Jndi Operations:
    • void bind (String sname,object object);-binding: The process of associating names with objects
    • void Rebind (String sname,object object);--rebind: Used to rebind an object with an already existing name
    • void Unbind (String sname);-Release: Used to release objects from the directory
    • void Lookup (String sname,object object);-Lookup: Returns an object of the total catalog
    • void rename (String soldname,string snewname);--Renaming: The name used to modify the binding of an object name
    • Namingenumeration listbinding (String sname);-Checklist: Returns a list of the objects bound to a specific context
    • Namingenumeration list (String sname);

code example: the name, class name, and bound object are again obtained.

Namingenumeration namenumlist = ctxt.listbinding ("Cntxtname");
...
while (Namenumlist.hasmore ()) {
Binding BND = (Binding) namenumlist.next ();
String sobjname = Bnd.getname ();
String sclassname = Bnd.getclassname ();
Someobject objlocal = (someobject) bnd.getobject ();
}

Learn about the concepts of name services and directory services to help you better use Jndi. Naming Service Name Services define how to associate a name with an object and how to find an object by name. Typical examples are: DNS associates domain names with IP, and file systems associate file names with files. In the name service, the main concept:
-Name (Names), in the name system of the actual object code, such as file name, domain name, etc., it will be used to find the associated object. There are different naming conventions in different systems, such as the file system uses "\" to represent the hierarchy, while DNS uses ".".
-Binding (bindings), the name and the actual object's association.
-References and addresses (References and Addresses), when an object cannot be stored directly in the name system, you must use a reference to find the actual object by reference. In the system, the contents of the saved reference are called addresses. There is another useful reference: in the name System, there is a lack of concepts like the foreign keys of relational databases. By using references, you can act as a substitute for foreign keys.
-context, which is a name-object collection that provides the primary operations for interacting with the name system, such as finding, binding, and binding. A child context (subcontext) is related to its relationship to a directory and subdirectory in a file system, which is contained in a context and is associated with a child context by a name in the parent context.
-The name System and the namespace (naming Systems and namespaces), the name System is a set of the same type of context, which provides the name service; the name space, which is the name set in the name system, such as file system file name and directory.
The directory service is an extension of the name service, which, in addition to associating names and objects, allows an object to contain attributes. A directory system usually organizes data in a hierarchical structure. Key concepts in the directory service:
-Attribute (Attributes), which belongs to the directory object, it is (first name, value) pair, the attribute can have more than one value.
-Directory and directory service (directories and directory services), the directory is a collection of directory objects, directory services provide directory-related services, create, delete, and modify the properties of objects stored in the directory.
-Find and find filters (searches and search Filters) to get the directory object's action is to find it; filters are objects that resemble the lookup criteria.
Basic use

² Registering JNDI Providers
Before using Jndi, you need to get the provider of the Jndi and register it with the system. Jndi-related system attributes are defined in Javax.naming.Context, commonly used properties:
-Java.naming.factory.initial, the class name used by the service provider to create the InitialContext.
-Java.naming.provider.url, used to configure the initial URL of the InitialContext
-Java.naming.factory.object, a class used to create Name-to-object mappings for Nameclasspair and references.
-Java.naming.factory.state, the class used to create the Jndi state
For directory services, because of the general need for security settings, it is also common to use:
-Java.naming.security.authentication, security type, three values: None,simple or strong.
-Java.naming.security.principal, authentication information.
-Java.naming.security.credentials, certificate information.
-Java.naming.security.protocol, security protocol name.
Using System.setproperty registration, if the program does not display instructions, then Java will find jdni.properties files within Classpath to complete the registration. jdni.properties Example:
Java.naming.factory.initial=com.codeline.db.mockinitialcontextfactory

Connection Services
After registering, you can implement a service connection. For the first name service starts with InitialContext, the directory service uses InitialDirContext. They implement both context and dircontext, which correspond to the interface of the name Service and directory service respectively, and are the two most important interfaces in Jndi.
Connection Name Service:

System.setproperty (Context.initial_context_factory, " 
com.sun.jndi.fscontext.FSContextFactory"); 
InitialContext CTX = new InitialContext ();

To connect to the directory service:

 Hashtable env = new Hashtable (); 
 Env.put (Context.initial_context_factory, "com.sun.jndi.ldap.LdapCtxFactory"); 
 Env.put (Context.provider_url, "ldap://myserver.com/");
 Env.put (Context.security_authentication, "simple"); 
 Login to LDAP server requires user name 
 env.put (Context.security_principal, "Ldapuser"); 
 Login LDAP server required password 
 env.put (context.security_credentials, "MyPassword"); 
InitialDirContext CTX = new InitialDirContext (env);


Multi-service provider: If the application contains more than one service provider, the connection is slightly different. Take the name service as an example

Hashtable env = new Hashtable (); 
 Env.put (Context.initial_context_factory, 
"com.sun.jndi.rmi.registry.RegistryContextFactory"); 
 Env.put (Context.provider_url, "rmi://myserver.com:1099"); 
 Using different constructors 
initialcontext ctx = new InitialContext (env); 


Finding objects
both the name service and the directory service use lookup to find objects. In addition to using string as a parameter, lookup can use the name interface as an argument.

Greeter Greeter = (Greeter) ctx.lookup ("SayHello"); 

If you want to get all the object names in the context, use LIS to return the Nameclasspair list. Nameclasspair contains the object name and object class name. If you want to get a real list of object instances, use Listbindings, which returns a list of binding. Binding is a subclass of Nameclasspair that contains an instance of an object.
-List

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

-Listbindings

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


Object Bindings
-use bind to add bindings

Fruit Fruit = new Fruit ("Orange");
Ctx.bind ("favorite", fruit);

-use rebind to modify bindings

Fruit Fruit = new Fruit ("Lemon");
Ctx.rebind ("favorite", fruit);

-Use Unbind to remove bindings.

Ctx.unbind ("favorite"); 


Object Renaming
use Rename to rename an object in the context

Ctx.rename ("Report.txt", "old_report.txt");

-Get Properties
Attributes and attributes are the associated interfaces, which are in the Javax.naming.directory package. By DirContext The GetAttributes method, we can get the attribute collection of the object, and then use the attributes get method to obtain the corresponding property, and finally, we can get the attribute value by means of the Getting method.

String DN = "Uid=me, Dc=mycompany, dc=com, Ou=customer, O=exampleapp"; 
Context user = (context) ctx.lookup (DN); 
Get all properties 
Attributes attrs = User.getattributes (""); 
Attribute test= attrs. Get ("test"); 
Object testvalue= test.get (); 

In the example above, all of the properties of user are obtained, and in actual use, you can set the list of properties to get by considering the impact of network bandwidth:

String reqd_attrs = new string[] {"Surname", "initials", "title", "Rfc822mailalias"}; 
Attributes attrs = User.getattributes ("", reqd_attrs); 


Find and Filter
done using the search method.

 public dircontext[] Finduser (String initials,string surname,string country,string 
  e) {//Construction condition Basicattributes search_attrs = new Basicattributes (); 
  Search_attrs.put ("initials", initials); 
  Search_attrs.put ("Sn", surname); 
  Search_attrs.put ("C", country); 
  if (phone!= null) search_attrs.put ("PhoneNumber", phone); 
  Namingenumeration results = Initial_ctx.search ("Ou=customer,o=exampleapp", search_attrs); 
  LinkedList found = new LinkedList (); 
   while (Results.hasmore ()) {searchresults sr = (searchresults) results.next (); 
   String name = Sr.getname (); 
   Object CTX = Sr.getobject (); if ((CTX = null) | |! ( 
   CTX instanceof DirContext)) Found.add (Initial_ctx.lookup (name)); 
  else Found.add (CTX); 
  } dircontext[] Ret_val = new dircontext[found.size ()]; 
  Found.toarray (Ret_val); 
 return ret_val; } 


DirContext Interface Main filtration mode:

1. Use filter string

String reqd_attrs = new string[] {"cn", "UID", "Rfc822mailalias"}; 
Namingenumeration results = Initial_ctx.search ("Ou=customer, O=exampleapp", search_attrs,reqd_attrs); 


2. Use Searchcontrols to gain more control

Searchcontrols ctrls = new Searchcontrols (); 
Ctrls.setcountlimit (a); 
Ctrls.settimelimit (5000); 
Ctrls.setsearchscope (searchcontrols.subtree_scope); 
Namingenumeration results = Initial_ctx.search ("cat=books,ou=products, 
O=exampleapp", "title=*java*", ctrls); 

modifying properties
done using the Modifyattributes method of DirContext and InitialDirContext. The so-called modification process, in fact, is to construct the list of attributes to be modified, and then submit using the above method. When a property contains more than one value, you need to include the value of the property's unmodified values, or the server will consider those values removed if they are no longer needed.

 public void Updateaddress (string dn,string address, string country, String phone) { 
  basicattributes mod_attrs = new Ba Sicattributes (); 
  if (address!= null) 
   mod_attrs.put (' address ', address); 
   if (country!= null) 
    mod_attrs.put ("C", country); 
  if (phone!= null) 
    mod_attrs.put ("PhoneNumber", phone); 
   if (mod_attrs.size ()!= 0) 
   initial_ctx.modifyattributes (DN, Dircontext.replace_attribute, mod_attrs); 
 

With Modificationitem, you can also make several different modifications at once:

modificationitem[] Mod_items = new modificationitems[2]; 
Attribute email = new BasicAttribute ("Rfc822mailalias", new_email); 
Modificationitem email_mod = new Modificationitem (dircontext.add_attribute, email); 
Attribute addr = new BasicAttribute ("Address", address); 
Modificationitem addr_mod = new Modificationitem (dircontext.replace_attribute, addr); 
Mod_items[0] = Email_mod; 
MOD_ITEMS[1] = Addr_mod; 
Initial_ctx.modifyattributes (DN, mod_items);

Create context
done using the Createsubcontext method.

 Basicattributes attrs = new Basicattributes (); 
Attrs.put ("initials", initials); 
 Attrs.put ("Sn", surname); 
 Attrs.put ("Rfc822mailalias", email); 
 if (address!= null) 
  attrs.put (' address ', address); 
 if (country!= null) 
  attrs.put ("C", country); 
 if (phone!= null) 
 attrs.put ("PhoneNumber", phone); 
Initial_ctx.createsubcontext (DN, attrs); 


Delete Context
done using the Destroysubcontext method.

Initial_ctx.destroysubcontext (DN); 

Instance
here's another example.

Configured in Tomcat's Conf/server.xml:

<context path= "/jndi" > 
 
 <resource name= "bean/mybeanfactory" auth= "Container" 
   Com.huawei.jndi.bean.MyBean " 
   factory=" org.apache.naming.factory.BeanFactory " 
   bar="/> 
 
</ Context> 

It declares a component in Tomcat, and then you can get this component in your code:

Try 
{context 
 Initcontext = new InitialContext (); 
 Context Envctx = (context) initcontext.lookup ("java:comp/env"); 
 Mybean bean = (mybean) envctx.lookup ("Bean/mybeanfactory"); 
 System.out.println (Bean.getbar ()); 
} 
catch (Exception e) 
{ 
 e.printstacktrace (); 
} 

Summary: Configure the Jndi component in Tomcat, and then get the configured component in your code.

The Jndi implementation classes for each Web container are different, for example, in JBoss, the Jndi provider class is org.jnp.interfaces.NamingContextFactory and is different from Tomcat.

In this way, the role of Jndi is similar to spring's dependency injection. But through Jndi, you can get components across applications and even across domains. Components configured on Server A, on another server B, can be obtained through JNDI.

Spring also provides a encapsulation of jndi, which is more convenient to use, and here's an example.

<!--jndi template--> 
<bean id= "jnditemplate" class= "Org.springframework.jndi.JndiTemplate" > 
 < Property name= "Environment" > 
  <props> 
   <prop key= "Java.naming.factory.initial" > org.jnp.interfaces.namingcontextfactory</prop> 
   <prop key= "Java.naming.provider.url" > 10.137.96.212:18199</prop> 
   <prop key= "java.naming.factory.url.pkgs" >org.jnp.interfaces:o rg.jboss.naming</prop> 
  </props> 
 </property> 
</bean> 
 
<!--Create a connection factory-- > 
<bean id= "jmsconnectionfactory" class= "Org.springframework.jndi.JndiObjectFactoryBean" > 
 <property name= "Jnditemplate" ref= "jnditemplate"/> <property name= "Jndiname" 
 Topicconnectionfactory "/> 
</bean> 

Declare the Jnditemplate, configure the destination address, and the Jndi service provider class. Then by Jndiobjectfactorybean, you can easily get the Jndi components and type conversions.

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.