Professional Documents
Culture Documents
This chapter introduces JNDI and describes how JBoss implements JNDI in the JBoss Naming Service (JBossNS). The chapter describes
how to view directory content using the JBoss JNDIView, and how to configure the JNDI service in JBoss. It also describes a sample Web
application that accesses the JBossNS to obtain a reference to a ConnectionFactory object.
An Overview of JNDI
JNDI is included with the Java Development Kit (JDK), version 1.3 and later. JNDI provides a common interface to enable applications access
existing naming services such as RMI or LDAP. In addition, JNDI provides the SPI, which is implemented by service providers called JNDI
providers, as core JNDI classes. The core classes expose the naming service to JNDI client interfaces. Figure 3-1 shows how Java
applications use the JNDI client API to interface with a JNDI naming manager available in any naming service:
The JNDI client and SPI APIs consist of the following five packages:
n javax.naming: Consists of a key class called InitialContext and Context and Name interfaces. This package is the main JNDI package.
n javax.naming.event: Contains classes and interfaces to support event notification in naming services.
n javax.naming.ldap: Contains classes and interfaces to support LDAP specific naming service features such as referrals and
chaining.
n javax.naming.spi: Provides classes to dynamically plug-in any JNDI provider such as JBoss or J2EE application server.
The Context interface defines methods to lookup a directory service and registers or unregisters a remote object in a directory. When a
remote object is registered, it binds itself to the directory. When unregistered, the object unbinds itself from the directory. The Name interface
encapsulates a name bound to a naming service. Each name consists of an ordered sequence of components that together constitute a
directory entry.
The javax.naming and javax.naming.directory packages contain the client side APIs. Application components such as Enterprise Java Beans
and Web components that interact with a naming service use these packages. JNDI providers implement the event, ldap, and spi sub
packages in the javax.naming package to define a naming service and its operations.
Name Description
Context Is an interface that specifies a set of names to object bindings.
Binding Is a class that encapsulates a name to object binding.
CompositeName Is a class that represents a name consisting of multiple components.
CompoundName Is a class that represents a name from a hierarchical namespace created by a naming service.
InitialContext Is a class that implements the Context interface and enable applications to send requests on a naming service.
Page 2 / 18
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server
LinkRef Is a class that represents a Reference. The content in the Reference is a link name that is bound to an object name in the context.
NameClassPair Is a class that represents an object and a class name pair associated with a remote object.
InitialContext Is a class that implements the Context interface.
Reference Is a class that represents a reference to an object residing outside the naming service.
Name Is an interface that denotes a name in the naming service.
NameParser Is an interface that parses the components of a name.
Name Description
Attribute interface Represents an attribute of a named object.
Attributes interface Represents a collection of attributes.
DirContext interface Provides methods to search or update the attributes of a named object.
BasicAttribute class Implements the Attribute interface.
BasicAttributes class Implements the Attributes interface.
InitialDirContext class Implements the DirContext interface and represents a context to perform the directory operations such as search or bind operations.
ModificationItem class Represents an attribute modified by a client application.
SearchControls class Encapsulates factors to define the scope of a search on a named object.
SearchResults class Contains an enumeration returned by directory search operations.
JNDI Names
A name is a fundamental element of the naming service and enables the naming service to locate remote objects. A name is represented as a
string that is parsed into components by the naming service. A name consists of a sequence of components numbered from 0 to N. A naming
service uses the component at index 0 to search for names. This component is called the significant component. The syntax for a name
depends on the JNDI provider and applications need to specify provider specific JNDI names.
A naming service comprises unique names, which clients reference to locate a remote object associated with the name. A remote object is
bound to the naming service, and each binding is represented as an instance of the javax.naming.Binding class. A binding object consists of
the name and class of the object and the object itself.
Each naming service adopts a different mechanism to store objects in a binding. Some naming services store Java objects in a serialized
form and others store a reference to the object. JNDI provides the javax.naming.Reference class to represent a reference to a remote object.
The SPI constructs a copy of the remote object using the information in the Reference object when JNDI clients request for a remote object.
Page 3 / 18
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server
you to write generic code that can be reused with a different naming service provider. For example, you can use an EJB created with the J2EE
application server for a JBoss enterprise application. Figure 3-2 shows different naming services accessed using an InitialContext reference:
The InitialContext class is specified by the environment property java.naming.factory.initial in the jndi.properties file. This property is used to
specify the fully qualified class name of the InitialContext class defined by the JNDI provider.
The EJB or Web container provides the ENC for J2EE components in the form of a JNDI context. The container enables J2EE components to
access information in the ENC using the entries of the deployment descriptor. These entries define the resources and information needed by
the component at runtime.
A container provides tools to help you map ENC references made by the component to the deployment environment and make the component
ready for deployment.
An application component locates the ENC using JNDI. To locate the ENC, the component creates an InitialContext object using a non-
argumented constructor and performs a lookup for an ENC using the name java:comp/env.
For example, an application component contains the following code to locate the ENC:
Context iniCtx=new InitialContext();
Context compEnv=(Context) iniCtx.lookup("java:comp/env");
The ENC obtained through a lookup is accessible only by the component and cannot be accessed or shared by other components. The ENC
provides an isolated read-only namespace for a component, and each component defines its own ENC. Applications can use the same JNDI
name to refer to different remote objects.
Configuring JBossNS
JBossNS is an RMI based implementation of JNDI. Application components use RMI to connect to the naming service and perform
operations. JBoss manages and monitors JBossNS using a management component called MBean.
Note JBoss uses Java Management Extensions (JMX) MBeans to provide a Java wrapper that encapsulates properties and operations in
a service.
The jboss-service.xml root configuration file in the /server/conf directory of your JBoss installation contains <mbean> entries to specify services
that are loaded by default at JBoss startup. These <mbean> elements also include properties of these services specified as the <mbean>
element attributes.
Page 4 / 18
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server
n Backlog: Specifies the maximum number of connection requests that can be queued.
n Context.PROVIDER_URL: Contains the value jnp://<servername>:1099, where jnp represent JNDI naming provider, the default protocol
used to connect to JbossNS.
You can create an InitialContext that uses the Properties object defined above. You need to use the following code:
InitialContext jbossInitialContext=new InitialContext(prop);
When a client creates an InitialContext with JBossNS properties, the org.jnp.interfaces.NamingContextFactory object creates the Context
instance used in the subsequent operations. The NamingContextFactory class is the JBossNS implementation of the
javax.naming.spi.InitialContextFactory interface. When the NamingContextFactory class creates a Context object, an
org.jnp.interfaces.NamingContext instance with the InitialContext environment is also created.
In addition, the class creates the name of the context in the global JNDI namespace. It is the NamingContext instance that actually performs the
task of connecting to the JBossNS server and implements the Context interface. The Context.PROVIDER_URL property stored as an
environment variable specifies the server that runs the JBossNS service.
JBossNS provides three levels of naming contexts: java:comp, java:, or any user-defined name such as external/ldap to reference an LDAP
directory. The java:comp context and its subcontexts are available to applications associated with the java:comp context. Subcontexts under
the java: context are accessible only within the Java Virtual Machine in the JBoss server.
Application components such as EJBs or Web components reference a JNDI name stored within a naming context. A reference to resources
required by application components is specified in the ejb-jar.xml file for EJBs and web.xml file for Web components. The naming service is
provided by the container or Application server and uses vendor-specific deployment descriptors to obtain the JNDI name for the resource.
The JNDI name is specified in these vendor specific deployment descriptors such as jboss.xml and jboss-web.xml.
The ejb-jar.xml and web.xml descriptors use the following elements to reference a JNDI name:
Page 5 / 18
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server
n EJBs referenced by an application and declared with the <ejb-ref> and <ejb-local-ref> elements
n Connections to resources, such as datasources declared with the <resource-ref> elements
You need to provide a logical name in the deployment descriptor to describe the environment where the EJB will be deployed. The application
server maps the logical names in the deployment descriptor to the resources available in the local environment. The mapping enables
application components to access these resources. JBoss uses a server specific deployment descriptor called jboss.xml to link logical names
in an EJB deployment descriptor to the local environment.
The web.xml file describes a collection of Web components and their environment. The ENC for these components is declared globally and is
used by all servlets and JSP pages in the Web application. JBoss uses a server-specific Web component descriptor called jboss-Web.xml to
map logical names specified in the web.xml file to resources in the local environment.
Environment Entries
An ENC defines environment variables, such as global variables or initialization values to these variables, for application components using
environment entries. These entries are stored as name value bindings in a naming service. Applications refer to these values using the JNDI
name.
Every application component that is packaged with the jboss.xml file contains environment entries within <env-entry>elements. These
elementsprovide a link to the ENC defined in the component. The <env-entry> element contains child elements, such as a <description>, <env-
entry-name>, <env-entry-type>, and <env-entry-value> elements.
The <description> element provides a description of the entry, and the <env-entry-name>element defines the JNDI name of the entry relative to
the java:comp/env name. The <env-entry-type> element specifies the Java data type of the entry and the <env-entry-value> specifies the entry
value as a string.
Listing 3-1 shows the code for a sample <env-entry> element in the deployment descriptor of an EJB:
<session>
<ejb-name>A SessionBean</ejb-name>
<env-entry>
<description>The maximum number of transactions performed on an account </description>
<env-entry-name>maxTransactions</env-entry-name>
<env-entry-type>java.lang.Integer</env-entry-type>
<env-entry-value>5</env-entry-value>
</env-entry>
<env-entry>
<description>Account Type
</description>
<env-entry-name>AccountType</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>Current</env-entry-value>
</env-entry>
</session>
Page 6 / 18
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server
Applications access the <env-entry> element in the ejb-jar.xml file using an InitialContext to perform a lookup on the naming service. The
naming service returns the value of the <env-entry> element.
Listing 3-2 contains the code to access the <env-entry> element:
EJB References
EJBs and Web components in applications interact with other EJBs. You can declare an EJB reference that defines a link in a naming service.
The link points to the referenced EJB’s home interface.
Note An EJB home interface is an interface that defines lifecycle methods such as the create() method of an EJB.
The name used by the referencing EJB is a logical link that abstracts the actual name of the referenced EJB’s home interface. EJB references
are organized in the java:comp/env/ejb context of the JBossNS.
The ejb-jar.xml deployment descriptor defines an <ejb-ref> element to declare an EJB reference. Each <ejb-ref> element describes the
interfaces provided by the referencing EJB to the referenced EJB.
n ejb-ref-name: Specifies the name of the EJB reference relative to the java:/comp/env context.
n ejb-link: Links the reference to another EJB used by the same application.
Listing 3-3 shows the sample code in an ejb-jar.xml file for the ejb-ref element:
<session>
<ejb-name>PurchaseBean</ejb-name>
</session>
<session>
<ejb-name>CustomerBean</ejb-name>
<ejb-ref>
<description>This is a reference to the customer entity
</description>
<ejb-ref-name>ejb/CustomerHome</ejb-ref-name>
<ejb-ref-type>Entity</ejb-ref-type>
<home>sample.CustomerHome</home>
<remote> sample.Customer</remote>
</ejb-ref>
</session>
<session>
<ejb-ref>
<ejb-name>PurchaseBean</ejb-name>
<ejb-ref-name>ejb/PurchaseHome</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<home>store.PurchaseHome</home>
Page 7 / 18
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server
<remote> store.Purchase</remote>
<ejb-link>PurchaseBean</ejb-link>
</ejb-ref>
</session>
The above code defines a JNDI reference to an EJB bean called CustomerBean referenced by a bean called PurchaseBean.
To access the <ejb-ref element> element, an application component obtains an InitialContext and performs a lookup for the name using the
following code:
InitialContext iniCtx=new InitialContext();
Context ejbCtx=(Context) iniCtx.lookup("java:comp/env/ejb");
PurchaseHome home=(PurchaseHome) ejbCtx.lookup("PurchaseHome");
ConnectionFactory References
Application components can refer to resource factories such as the ConnectionFactory class using logical names bound to JBossNS. These
logical names are referenced by the application using <resource-ref> element in the ejb-jar.xml or web.xml deployment descriptors.
ConnectionFactory references need to be added to different JNDI subcontext for each resource type. The subcontexts used are:
When application components are deployed the resource manager ConnectionFactory references are mapped to ConnectionFactories
available in the local environment using the jboss.xml and jboss-web.xml files.
A resource-ref element describes a ConnectionFactory and contains the following child elements:
n res-ref-name: Specifies the name of the reference relative to the java:comp/env context.
n res-type: Specifies the fully qualified classname of the resource manager connection factory.
n res-auth: Specifies whether the component can access the resource or the EJB or Web container provides authentication information
required to access the resource.
The jboss.xml and jboss-web.xml deployment descriptors provide a link between the logical names defined in the resource-ref-name element
to the JNDI name of the JBoss-specific ConnectionFactory.
Each resource ConnectionFactory reference associated with JBoss needs to be organized in different subcontexts of the application
components ENC. For example, a JDBC DataSource reference should be declared in the java:/comp/env/jdbc subcontext. You need to define
URL ConnectionFactories in the java:/cop/env/url subcontext.
Resource Environment References
A resource environment reference element specifies logical names for resource specific administered objects. An object that is created and
configured by a system administrator is called an administered object, such as a queue used in a mail service. The resource environment
reference is defined with a <resource-env-ref> element in the application component deployment descriptors. The JBoss runtime environment
binds these logical names to administered objects using the jboss specific deployment descriptors.
The<resource-env-ref> element describes the requirements of an application component with respect to the administered object and includes
child elements, such as a <description>, and a <resource-env-ref-name> to specify a name relative to the java:comp/env context.
Listing 3-4 shows the <resource-env-ref> element in an EJB deployment descriptor:
<resource-env-ref>
<description>This is a reference to a JMS queue
</description>
<resource-env-ref-name>jms/ItemInfo</resource-env-ref-name>
<resource-env-ref-type>javax.jms.Queue</resource-env-ref-type>
</resource-env-ref>
</session>
Page 8 / 18
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server
The <resource-env-ref> element in the jboss.xml file maps the logical names in the EJB deployment descriptor to the JNDI name of the
administered object deployed in JBoss.
The ExternalContext MBean merges external JNDI contexts in the JBoss JNDI namespace. You can integrate LDAP servers, file systems,
DNS servers with JBoss. To access a naming service other than the default JBossNS, you need to add an ExternalContext MBean to the
jboss-service.xml file. This MBean defines configurable attributes, such as:
n JndiName: Specifies the JNDI name of the external context.
n RemoteAccess: Contains a boolean value to indicate whether the external InitialContext is bound to the naming service using a
serializable instance.
n CacheContext: Contains a boolean value to indicate that the external context is created and stored in memory when the NamingService is
started.
n InitialContext: Specifies the fully qualified class name of the InitialContext implementation. This class name needs to be either the
javax.naming.InitialContext, the javax.naming.directory.InitialDirContext, or javax.naming.ldap.InitialLdapContext classes.
The above code shows how to bind an LDAP context in the JBoss JNDI namespace with the external/ldap/dscape name.
You need to add a dscape.ldap properties file to specify the properties associated with the LDAP context. Listing 3-6 shows the dscape.ldap
properties file:
java.naming.factory.initial=com.sun.jndi.ldap.LdapCtxFactory
java.naming.provider.url=ldap://ldaphost.externscape.com:389/o=externscape.com
java.naming.security.principal=cn=Directory Manager
java.naming.security.authentication=simple
java.naming.security.credentials=ldapuser
You can access the external LDAP context using the URL ldap://ldaphost.externscape.com:389/o=externscape.com from JBoss using the
following code:
InitialContext iniCtx=new InitialContext();
LdapContext ldapCtx=iniCtx.lookup("external/ldap/dscape");
The NamingAlias MBean allows you to create an alias for a JNDI name as a JNDI javax.naming.LinkRef object. To create a JNDI name alias,
you need to add an <mbean> entry for the NamingAlias MBean in the jboss-service.xml file. The NamingAlias MBean contains attributes such
as a FromName that specifies the context where the LinkRef is bound under JNDI and a ToName that specifies the alias name. The alias
name is the target name to which the LinkRef object refers.
The NamingAlias MBean is specified in the jboss-service.xml file using the <mbean> element shown in the following code:
Page 9 / 18
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server
<mbean code="org.jboss.naming.NamingAlias"
name="DefaultDomain:service=NamingAlias,fromName=MyDataSource">
<attribute name="ToName">TestDataSource</attribute>
<attribute name="FromName">MyDataSource</attribute>
</mbean>
JBoss provides a user interface called the JNDIView to view a list of objects bound in the JBossNS directory. The JNDIView service is
managed by the JNDIView MBean. To access the JNDIView, type the URL: http://localhost:8080/jmx-console. This URL displays the JBoss
Agent view.
Note The Agent view is a JMX MBean in JBoss that provides a graphical user interface to administer JBoss services such as the Web or
naming service.
To access the JNDIView, select the service=JNDIView link. Figure 3-4 shows the JNDIView MBean in the browser:
Page 10 / 18
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server
Note You can select the listXML operation to view a list of names bound to the JBoss namespace.
A servlet, VeiwServlet, accesses information using a database table. This servlet uses the information in the database to create a stock
report. The Web component uses a ConnectionFactory to create Connection objects that establish physical connections to the database.
You can define a JDBC datasource as a ConnectionFactory for the servlet. The WAR component into which the servlet is packaged accesses
the JNDI name of the datasource using the web.xml deployment descriptor file packaged with it.
Page 11 / 18
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server
;
}
7. Define a service() method in the ViewServlet class.
8. Specify the content type and obtain a reference to a PrinterWriter object.
9. Invoke a user defined method called printReport using the following code:
public void service(HttpServletRequest req,HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
out=res.getWriter();
printReport();
}
10. Define a userdefined method called getConnection() in the ViewServlet.
11. Define a Connection object in the getConnection() method using the code:
private Connection getConnection()
{
Connection con=null;
12. Create a Context object.
13. Perform a JNDI lookup to locate the JDBC datasource using the JNDI name of the datasource, java:/MySqlDS.
14. Use the datasource object to get a Connection object and return this Connection object from the getConnection() method using the
following code:
try
{
Context ctx=new InitialContext();
DataSource ds=(DataSource) ctx.lookup("java:/MySqlDS");
con=ds.getConnection();
}
catch(Exception e)
{
System.out.println("Exception in Connecting to DataSource ... ");
e.printStackTrace();
}
return con;
}
15. Define the printReport() method.
16. Invoke the getConnection() method using the following code:
public void printReport()
{
try
{
Connection con=this.getConnection();
17. Define an SQL query to fetch information from the stock table.
18. Create a PreparedStatement object and assign the SQL query as parameter to this object using the code:
String query="select * from stock ";
PreparedStatement ps=con.prepareStatement(query);
Use the PreparedStatement object to execute the query and obtain a ResultSet object
ResultSet rs=ps.executeQuery();
19. Define table formatting information such as table width and border to display query results in a table using the code shown in Listing 3-7:
Page 12 / 18
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server
20. Iterate through the ResultSet object and retrieve column values.
21. Place these column values in table cells using the code shown in Listing 3-8:
while(rs.next())
{
out.println("<tr>");
out.println("<td>"+rs.getString("ITEM_CODE")+"</td>");
out.println("<td>"+rs.getString("ITEM_NAME")+"</td>");
out.println("<td>"+rs.getInt("QTY")+"</td>");
out.println("<td>"+rs.getInt("PRICE")+"</td>");
out.println("</tr>");
}
out.println("</table>");
}
catch(Exception e)
{
System.out.println("Exception in displaying the results .... ");
}
finally
{
try
{
if(con!=null) con.close();
}
catch(Exception e)
{
System.out.println("Exception occurred in closing the connection");
}
}
}
}
You can add records in the stock table using the code:
insert into stock values ('H1001','Haversack ',20,25);
insert into stock values ('W1052','Wallet ',70,15);
insert into stock values ('S4021','Suitcase ',20,50);
Page 13 / 18
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server
You need to delete the hqldb-ds.xml file in the deploy directory because JBoss uses this file to connect to Hypersonic database. You also need
to copy the mysql driver to the /server/default/lib directory to enable JBoss to connect to the MySQL database.
The above code defines the JNDI name java:/MySqlDS for the JDBC datasource and specifies the <type-mapping> element to identify the
MySQL database for this datasource.
The above code shows the web.xml file that contains the <resource-ref> element. This element provides a description of the JDBC
datasource, and defines the <res-ref-name> element. This element is a logical name that maps to the JNDI name of the datasource as
specified in the standardjaws.xml file. The <res-type> element specifies the ConnectionFactory reference as javax.sql.DataSource object.
<jboss-web>
<resource-ref>
<res-ref-name>jdbc/MySqlDS</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<jndi-name>jdbc:/MySqlDS</jndi-name>
</resource-ref>
</jboss-web>
Page 14 / 18
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server
Figure 3-5 shows the mapping between the web.xml and the jboss-web.xml for the <resource-ref> element:
In Figure 3-5, the <res-type> element in web.xml maps to the <res-type> element in jboss-web.xml. In addition, the name in the <resource-ref-
name> element in web.xml matches the <jndi-name> element value:jdbc:/MySqlDS in jboss-web.xml.
The JBoss runtime uses the environment variables created in the above code to access Java executables, use ANT and use JBoss-specific
JAR files.
Page 15 / 18
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server
Page 16 / 18
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server
ANT compiles the ViewServlet, packages the deployment descriptors, and servlet classinto a WAR file. ANT also copies the WAR file to
the /server/default/deploy directory in JBoss
2. Click Invoke to invoke the method listXML. Figure 3-7 shows the output of the listXML method in the browser:
Page 17 / 18
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server
The ViewServlet servlet performs a JNDI lookup to retrieve a reference to the datasource. The ViewServlet servlet establishes a connection to
the MySQL database using this reference and fetches information needed to generate the stock report.
Page 18 / 18
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited