You are on page 1of 18

 

Working with JBOSS Application Server


SkillSoft. (c) 2003. Copying Prohibited.

  

Reprinted for Ashutosh Patel, Accenture


ashutosh.patel@accenture.com

All rights reserved. Reproduction and/or distribution in whole or in part in electronic,paper or


other forms without written permission is prohibited.
Working with JBOSS Application Server

Chapter 3: Using Naming and Directory Services


The Java Naming and Directory Interface (JNDI) provides a standard way to access remote objects by name. Remote objects are stored in a
directory maintained by the naming services of a Web server and accessed by client applications using a JNDI name. JNDI provides classes
and interfaces to create and access the naming services. The classes and interfaces are categorized into client Application Programming
Interfaces (APIs) and Service Provider Interfaces (SPIs). Client APIs are used by applications to access a naming service whereas providers
implement a naming service, using SPIs. The client API enables applications to connect to different naming and directory services, such as
Lightweight Directory Access Protocol (LDAP), Directory, Remote Method Invocation (RMI) registry, or Domain Naming Service (DNS).

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:

Figure 3-1: JNDI Architecture

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.directory: Provides methods to access a naming service.

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.

The javax.naming Package


The javax.naming package contains classes and interfaces to access a naming service. Table 3-1 shows the classes and interfaces in this
package:
Table 3-1: The Naming Package

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.

The javax.naming.directory Package


The javax.naming.directory package extends the javax.naming package and provides classes and methods to access a naming service. This
package also enables client applications to contact a naming service and lookup a name. The classes in the directory package enable
applications to retrieve or update attributes of objects stored in the directory called named objects. In addition, these classes provide methods
to locate objects based on specific attributes.
Table 3-2 shows the classes and interfaces of the javax.naming.directory package:
Table 3-2: The javax.naming.directory Package

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.

The Context Interface


A context represents a set of name to object bindings and is associated with a specific naming convention. A context enables a JNDI client to
lookup a name and return the object associated with the name. In addition, a context provides methods to bind, unbind, or list names. You can
bind a name in one context to another context if both the objects have the same naming conventions.
A naming service encapsulates interconnected contexts that define the same naming convention and a common set of operations used with
these contexts. A set of names used in the naming service form a namespace.
A name can be a composite name that spans multiple namespaces or a compound name used within a single namespace. You can use the
javax.naming.CompositeName and javax.naming.CompoundName classes to create composite or compound names. To bind an object to a
naming service, invoke the bind() method of the Context class. You need to specify a name and an object as arguments to the bind() method.

The InitialContext Class


A naming service performs context-based operations on the javax.naming.InitialContext class. This class implements the Context interface.
The InitialContext class initiates an interaction with a naming service. When you create an InitialContext class, it is initialized with properties
such as the location of the naming service from the runtime environment. JNDI determines the values of these properties using arguments to
the InitialContext constructor and the jndi.properties file available in the client CLASSPATH environment variable. The jndi.properties file
includes JNDI provider specific information such as the name of an InitialContextFactory class or the provider URL. This information enables

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:

Figure 3-2: Accessing Various Naming Services 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.

J2EE and JNDI


The J2EE specifications use JNDI to isolate J2EE components, such as EJBs and servlets, from the environment in which these components
run. This runtime environment is called the Enterprise Naming Context (ENC) and you can customize this environment without modifying the
code in the components.

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.

The JBossNS MBean is defined by <mbean>:


<mbean code="org.jboss.naming.NamingService" name="jboss:service=Naming">
<attribute name="Port">1099</attribute>
</mbean>

Page 4 / 18
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server

JBossNS MBean includes the following attributes:

n Port: Specifies the port on which the JBossNS listens.

n RmiPort: Specifies the RMI port used by the JBossNS.


n BindAddress: Specifies the address at which the naming service is available.

n Backlog: Specifies the maximum number of connection requests that can be queued.

JBossNS Client Configuration


JBoss requires client side configuration to connect to JBossNS. This configuration helps create an InitialContext object that is provided to
clients for performing a lookup. In addition, JBoss requires JAR files to be installed in appropriate locations to support the naming service
operations. Clients connect to JBossNS to run naming operations require the jnp-client.jar, log4j.jar and jboss-common-client.jar files.
Properties associated with the InitialContext object are stored in the jndi.properties file in the /server/conf directory of JBoss. The
jndi.properties file includes the following code:
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.provider.url=jnp://localhost:1099
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces

Configurable properties in the jndi.properties file are:

n Context.INITIAL_CONTEXT_FACTORY: Contains the value, org.jnp, interfaces.NamingContextFactory.

n Context.PROVIDER_URL: Contains the value jnp://<servername>:1099, where jnp represent JNDI naming provider, the default protocol
used to connect to JbossNS.

n Context_URL_PKG_PREFIXES: Contains the value of org.jboss.naing:org.jnp.interfaces.


n jnp.socketFactory: Specifies an implementation of the javax.net.SocketFactory interface.

n jnp:timeout: Specifies the connection timeout in milliseconds.

n jnp:sotimeout: Specifies a read timeout for a socket.


To define the properties associated with the jndi properties file, you need to use the following code:
Properties prop=new Properties();
prop.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
prop.put(Context.PROVIDER_URL, "jnp://localhost:1099")

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.

JBoss Naming Contexts


The JBossNS creates the java:comp naming context that is accessed by application components as an ENC. When a JNDI client performs a
lookup on java:comp or any of its sub contexts, JBossNS returns the Context object to the client. If the object does not exist, a new instance is
created.

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 Environment entries declared with the <env-entry> elements

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

n Connection factories to the resources declared by the <resource-ref > elements

n Resource environment declared by the <resource-env-ref > elements


Each of the above elements is defined with JNDI naming conventions. These elements map the JNDI name to a JNDI context using which this
name is bound. This jboss.xml deployment descriptor enables JBoss to map elements in the application component descriptors to resources
in the runtime environment.

ENC Elements in Deployment Descriptors


Application components are packaged in JAR or WAR files. These JAR files contain component classes and a deployment descriptor. Web
components use a deployment descriptor defined in a file called web.xml. EJB components use a deployment descriptor called ejb-jar.xml.
The EJB deployment descriptor describes a collection of EJB components and their environment. This descriptor provides a logical view of
the ENC in which these EJBs must operate.

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:

Listing 3-1: The ejb-jar.xml File with the <env-entry> Element

<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>

The elements in Listing 3-1 are:


n ejb-name: Defines the name of the EJB.

n env-entry: Defines an environment variable for this EJB component.

Page 6 / 18
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server

n description: Provides a description for the environment variable.

n env-entry-name: Provides a name for the environment variable.

n env-entry-type: Defines the data type of the environment variable.

n env-entry-value: Specifies the value of the environment variables.

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:

Listing 3-2: Accessing the JNDI Name of the Environment Variable

InitialContext iniCtx=new InitialContext();


Context envCtx=(Context) iniCtx.lookup("java:comp/env");
Integer maxTransactions=(Integer) envCtx.lookup("maxTransactions");
Float AccountType=(Float) envCtx.lookup("AccountType");

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.

An <ejb-ref> element has child elements such as:


n description: Provides a description that defines the intent of the reference.

n ejb-ref-name: Specifies the name of the EJB reference relative to the java:/comp/env context.

n ejb-ref-type: Specifies the type of the EJB as entity or session.

n home: Specifies the fully qualified EJB home interface name.

n remote: Specifies the fully qualified remote interface name.

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:

Listing 3-3: Referencing an EJB in a Deployment Descriptor

<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:

n java:comp/env/jdbc: Represents a JDBC DataSource ConnectionFactory subcontext.

n java:comp/env/jms: Represents a JMS ConnectionFactory subcontext.

n java:comp/env/mail: Represents a JavaMail ConnectionFactory subcontext.

n java:comp/env/url: Represents a URL ConnectionFactory subcontext.

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 Description: Defines a description about the reference.

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:

Listing 3-4: Defining a Resource Environment Element

<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.

Naming Service MBeans


In addition to the NamingService MBean used to configure JBossNS, three MBeans are shipped with JBoss. These MBeans are
ExternalContext, NamingAlias, and JNDIView.

The ExternalContext MBean

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.

n Properties: Sets the jndi.properties information for the external InitialContext.


Listing 3-5 shows an entry in the jboss-service.xml file to define an ExternalContext MBean for an LDAP server:

Listing 3-5: Defining an ExternalContext MBean

<!-- Bind a remote LDAP server -->


<mbean code="org.jboss.naming.ExternalContext"
name=":service=ExternalContext,jndiName=external/ldap/dscape" >
<attribute name="JndiName">external/ldap/dscape</attribute>
<attribute name="Properties">dscape.ldap</attribute>
<attribute name="InitialContext">
javax.naming.ldap.InitialLdapContext
</attribute>
<attribute name="RemoteAccess">true
</attribute>
</mbean>

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:

Listing 3-6: 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

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>

The JNDIView 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.

Figure 3-3 shows the Agent view:

Figure 3-3: Agent View

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

Figure 3-4: JNDIView MBean

Note You can select the listXML operation to view a list of names bound to the JBoss namespace.

Creating a JDBC Datasource Reference


You can create a JDBC datasource reference in JBossNS. Application components access this datasource by performing a lookup on a JNDI
service. The lookup returns a reference to the datasource object bound in the naming service.

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.

Creating the ViewServlet


The ViewServlet extends the HttpServlet class and contains code to generate a table that provides information about items in a stock table. To
create the servlet:
1. Import the servlet specific packages such as javax.servlet and javax.servlet.http.

2. Import the javax.sql and java.sql packages to enable database connectivity.


3. Import the javax.naming package to enable support for JNDI. Use the code:
import javax.servlet.*;
import javax.servlet.http.*;
import javax.naming.*;
import javax.sql.*;
import java.io.*;
import java.sql.*;
4. Define the ViewServlet class, which extends the HttpServlet.
5. Create a reference to ServletConfig and PrintWriter objects using the code:
public class ViewServlet extends HttpServlet
{
private PrintWriter out;
6. Define an init() method and initialize the ServletContext object, as shown below:
public void init(ServletConfig sc) throws ServletException
{
super.init(sc);

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:

Listing 3-7: Code to Format Table Information

out.println("<h2 align='center' style='background-color:olive'>Stock Report</h2>");


out.println("<table width='50%' align='center' border='1'>");
out.println("<tr>");
out.println("<td><b>Item Code</b></td>");
out.println("<td><b>Item Name</b></td>");
out.println("<td><b>Quantity</b></td>");
out.println("<td><b>Price</b></td>");

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:

Listing 3-8: Code for Placing Column Values

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");
}
}
}
}

Describing the stock Table


The ViewServlet class accesses the stock table stored in the MySQL database. Table 3-3 shows the structure of the stock table:
Table 3-3: Structure of the
stock Table

Fields Data Type Size


ITEM_CODE Varchar 5
ITEM_NAME Varchar 25
QTY Int default
PRICE Int default

To create the stock table, use the following code:


create table stock ( ITEM_CODE varchar(5), ITEM_NAME varchar(25), QTY int, PRICE int);

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);

Connecting to MySQL Database


By default, JBoss uses the Hypersonic database, that is provided with the JBoss download. To configure JBoss to access the MySQL
database, store the mysql-ds.xml file available in the /docs/examples/jca directory to the /server/deploy directory. The mysql-ds file contains
information about the database connection URL, username, and password. It also specifies information about the transaction type supported
by datasources for the MySQL database.
Note You need to edit the mysql-ds file to specify information about the database connection URL, username, and password to the
database.

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.

Defining the JNDI Name


You need to define the JNDI name for the JDBC datasource in a configuration file called standardjaws.xml. This file contains database specific
information needed to map Java datatypes to database column datatypes.
You need to add elements in the standardjaws.xml file to define the JNDI name for the datasource, as shown below:
<datasource>java:/MySqlDS</datasource>
<type-mapping>mySQL</type-mapping>
<debug>false</debug>

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.

Creating the web.xml File


The web.xml file contains the resource-ref element to specify the JNDI name of the datasource. It also provides elements such as the servlet
name, class, and a URL pattern to invoke the ViewServlet.
Listing 3-9 shows the web.xml file:

Listing 3-9: The web.xml File

<?xml version="1.0" encoding="ISO-8859-1"?>


<!DOCTYPE web-app
PUBLIC '-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN'
'http://java.sun.com/j2ee/dtds/web-app_2.2.dtd'>
<web-app>
<display-name>View Servlet</display-name>
<description>View Servlet</description>
<servlet>
<servlet-name>ViewServlet</servlet-name>
<servlet-class>ViewServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ViewServlet</servlet-name>
<url-pattern>/ViewServlet</url-pattern>
</servlet-mapping>
<resource-ref>
<description>The MySql DS</description>
<res-ref-name>jdbc/MySqlDS</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>

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.

Creating the jboss-web.xml File


The jboss-web.xml file is the JBoss specific deployment descriptor for the Web component. This deployment descriptor enables JBoss to map
the JNDI name specified in the web.xml to a naming context in the JBossNS. Listing 3-10 shows the jboss-web.xml file:

Listing 3-10: The jboss-web.xml File

<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:

Figure 3-5: Mapping Between web.xml and jboss-web.xml

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.

Deploying the Application


To deploy the application, you need to set environment variables, create an ANT build file, and use ANT to package the application as a WAR
component. ANT also places the WAR component in the deploy directory of your JBoss installation.

Setting Environment Variables


You need to configure the JBoss runtime environment setting the path and classpath environment variables. You need to specify information
about the ANT installation folder to enable ANT to build the application. To set environment variables:
1. Set the JBOSS_HOME environment variable to the JBoss installation directory using the command:
JBOSS_HOME=/usr/java/jboss-3.2.1
2. Export the JBOSS_HOME environment variable using the following command:
export JBOSS HOME
3. Set JAVA_HOME environment variable to the J2SDK installation directory using the following command:
JAVA_HOME=/usr/java/j2sdk1.4.1_01
4. Export the JAVA_HOME environment variable using the following command:
export JAVA_HOME
5. Set the ANT_HOME environment variable to the ANT installation directory using the following command:
ANT_HOME=/usr/java/ant1.5.3.1
6. Export ANT_HOME using the following command:
export ANT_HOME
7. Set the PATH environment variable using the following command:
PATH=$JBOSS/bin:$JAVA_HOME/bin:$ANT_HOME/bin:
8. Export the PATH environment variable using the command:
export PATH

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

Creating an ANT Build File


ANT uses an XML file called build.xml, which specifies the tasks to build an application. You need to create the build.xml file to perform tasks,
such as compilation, creation of deployment directories, and packaging of the Web application as a WAR file. You need to create a directory
called source in the working directory and save all the java files in the source directory. Save the web.xml, jboss-web.xml, in the working
directory. The build.xml file references files in the source and working directory.
Listing 3-11 shows the build.xml file:

Listing 3-11: The build.xml File

<project name="View Servlet" default="build-all" basedir=".">


<property name="jboss.dir" value="/usr/java/jboss-3.2.1"/>
<property name="jboss.deploy.dir" value="${jboss.dir}/server/default/deploy"/>
<property name="source.dir" value="${basedir}/source"/>
<property name="build.dir" value="${basedir}/build"/>
<property name="build.classes.dir" value="${build.dir}/classes"/>
<property name="warfile" value="ViewServlet.war"/>
<!-- the build path that contains the classpath required to compile the source files -->
<path id="classpath">
<pathelement location="${build.classes.dir}"/>
<pathelement location="${jboss.dir}/server/default/lib/javax.servlet.jar"/>
<pathelement location="${jboss.dir}/client/jboss-j2ee.jar"/>
</path>
<!-- compile source files -->
<target name="compile">
<echo message="Compiling source files ...." />
<mkdir dir="${build.classes.dir}"/>
<javac srcdir="${source.dir}"
destdir="${build.classes.dir}"
deprecation="on"
classpathref="classpath"
includes="*"/>
</target>
<!-- war file -->
<target name="war" depends="compile">
<echo message="Creating war file ...." />
<war warfile="${warfile}" webxml="web.xml">
<webinf dir="${basedir}" >
<include name="jboss-web.xml"/>
</webinf>
<classes dir="${build.classes.dir}">
<include name="ViewServlet.class" />
</classes>
</war>
</target>
<!-- copy war file to the deploy directory under jboss installation-->
<target name="build-all" depends="war">
<echo message="Copying war file to the deploy directory...." />
<copy file="${warfile}" todir="${jboss.deploy.dir}"/>
</target>
</project>

The build.xml file performs the following tasks:


1. Creates a build directory.
2. Creates a directory called classes to store compiled source files.
3. Compiles the source files and places these classes in the classes directory.
4. Packages the contents of the build directory in a WAR file. This file is stored in the /server/default/deploy directory of the JBoss
installation.

Performing the ANT Build


To perform the ANT build, you need to change to the working directory where you have saved the build.xml file. The ANT tool references the
build.xml in this directory to obtain instructions need to build the application. To perform the build:

Page 16 / 18
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server

1. Start JBoss using the following command:


sh run.sh
2. Invoke the ANT tool using the following command:
ant

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

Using the JNDIView


To view the JNDI name of the datasource bound to JBossNS, open a browser and type the URL: http://localhost:8080/jmx-console. To use the
JNDIView:
1. Select the service=JNDIView link to view the JNDIView MBean. Figure 3-6 shows the output in the browser:

Figure 3-6: MBean Operations

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

Figure 3-7: Listing JNDI Names

Running the Application


To run the application in JBoss, open a browser and type the URL: http://localhost:8080/ViewServlet/ViewServlet. Figure 3-8 shows the output
of the ViewServlet in the browser:

Figure 3-8: Displaying a Report

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

You might also like