站内搜索: 请输入搜索关键词
当前页面: 在线文档首页 > JBoss Application Server 4.0.1 release2 Guide 英文版指南文档

Chapter 3. Naming on JBoss - JBoss Application Server 4.0.1 release2 Guide 英文版指南文档

Chapter 3. Naming on JBoss

The JNDI Naming Service

This chapter discusses the JBoss JNDI based naming service and the role of JNDI in JBoss and J2EE. An introduction to the basic JNDI API and common usage conventions will also be discussed. The JBoss specific configuration of J2EE component naming environments defined by the standard deployment descriptors will also be addressed. The final topic is the configuration and architecture of the JBoss naming service.

The JBoss naming service is an plays a key role in J2EE because it provides a naming service that allows a user to map a name onto an object. This is a fundamental need in any programming environment because developers and administrators want to be able to refer to objects and services by recognizable names. A good example of a pervasive naming service is the Internet Domain Name System (DNS). The DNS service allows you to refer to hosts using logical names, rather than their numeric Internet addresses. JNDI serves a similar role in J2EE by enabling developers and administrators to create name-to-object bindings for use in J2EE components.

3.1. An Overview of JNDI

JNDI is a standard Java API that is bundled with JDK1.3 and higher. JNDI provides a common interface to a variety of existing naming services: DNS, LDAP, Active Directory, RMI registry, COS registry, NIS, and file systems. The JNDI API is divided logically into a client API that is used to access naming services, and a service provider interface (SPI) that allows the user to create JNDI implementations for naming services.

The SPI layer is an abstraction that naming service providers must implement to enable the core JNDI classes to expose the naming service using the common JNDI client interface. An implementation of JNDI for a naming service is referred to as a JNDI provider. JBoss naming is an example JNDI implementation, based on the SPI classes. Note that the JNDI SPI is not needed by J2EE component developers.

For a thorough introduction and tutorial on JNDI, which covers both the client and service provider APIs, see the Sun tutorial at http://java.sun.com/products/jndi/tutorial/.

3.1.1. The JNDI API

The main JNDI API package is the javax.naming package. It contains five interfaces, 10 classes, and several exceptions. There is one key class, InitialContext, and two key interfaces, Context and Name

3.1.1.1. Names

The notion of a name is of fundamental importance in JNDI. The naming system determines the syntax that the name must follow. The syntax of the naming system allows the user to parse string representations of names into its components. A name is used with a naming system to locate objects. In the simplest sense, a naming system is just a collection of objects with unique names. To locate an object in a naming system you provide a name to the naming system, and the naming system returns the object store under the name.

As an example, consider the Unix file system's naming convention. Each file is named from its path relative to the root of the file system, with each component in the path separated by the forward slash character ("/"). The file's path is ordered from left to right. The pathname/usr/jboss/readme.txt, for example, names a file readme.txt in the directory jboss, under the directory usr, located in the root of the file system. JBoss naming uses a UNIX-style namespace as its naming convention.

The javax.naming.Name interface represents a generic name as an ordered sequence of components. It can be a composite name (one that spans multiple namespaces), or a compound name (one that is used within a single hierarchical naming system). The components of a name are numbered. The indexes of a name with N components range from 0 up to, but not including, N. The most significant component is at index 0. An empty name has no components.

A composite name is a sequence of component names that span multiple namespaces. An example of a composite name would be the hostname and file combination commonly used with UNIX commands like scp. For example, the following command copies localfile.txt to the file remotefile.txt in the tmp directory on host ahost.someorg.org:

scp localfile.txt ahost.someorg.org:/tmp/remotefile.txt

A compound name is derived from a hierarchical namespace. Each component in a compound name is an atomic name, meaning a string that cannot be parsed into smaller components. A file pathname in the UNIX file system is an example of a compound name. ahost.someorg.org:/tmp/remotefile.txt is a composite name that spans the DNS and UNIX file system namespaces. The components of the composite name are ahost.someorg.org and /tmp/remotefile.txt. A component is a string name from the namespace of a naming system. If the component comes from a hierarchical namespace, that component can be further parsed into its atomic parts by using the javax.naming.CompoundName class. The JNDI API provides the javax.naming.CompositeName class as the implementation of the Name interface for composite names.

3.1.1.2. Contexts

The javax.naming.Context interface is the primary interface for interacting with a naming service. The Context interface represents a set of name-to-object bindings. Every context has an associated naming convention that determines how the context parses string names into javax.naming.Name instances. To create a name to object binding you invoke the bind method of a Context and specify a name and an object as arguments. The object can later be retrieved using its name using the Context lookup method. A Context will typically provide operations for binding a name to an object, unbinding a name, and obtaining a listing of all name-to-object bindings. The object you bind into a Context can itself be of type Context . The Context object that is bound is referred to as a subcontext of the Context on which the bind method was invoked.

As an example, consider a file directory with a pathname /usr, which is a context in the UNIX file system. A file directory named relative to another file directory is a subcontext (commonly referred to as a subdirectory). A file directory with a pathname /usr/jboss names a jboss context that is a subcontext of usr. In another example, a DNS domain, such as org, is a context. A DNS domain named relative to another DNS domain is another example of a subcontext. In the DNS domain jboss.org, the DNS domain jboss is a subcontext of org because DNS names are parsed right to left.

3.1.1.2.1. Obtaining a Context using InitialContext

All naming service operations are performed on some implementation of the Context interface. Therefore, you need a way to obtain a Context for the naming service you are interested in using. The javax.naming.IntialContext class implements the Context interface, and provides the starting point for interacting with a naming service.

When you create an InitialContext, it is initialized with properties from the environment. JNDI determines each property's value by merging the values from the following two sources, in order.

  • The first occurrence of the property from the constructor's environment parameter and (for appropriate properties) the applet parameters and system properties.

  • All jndi.properties resource files found on the classpath.

For each property found in both of these two sources, the property's value is determined as follows. If the property is one of the standard JNDI properties that specify a list of JNDI factories, all of the values are concatenated into a single colon-separated list. For other properties, only the first value found is used. The preferred method of specifying the JNDI environment properties is through a jndi.properties file, which allows your code to externalize the JNDI provider specific information so that changing JNDI providers will not require changes to your code or recompilation.

The Context implementation used internally by the InitialContext class is determined at runtime. The default policy uses the environment property java.naming.factory.initial, which contains the class name of the javax.naming.spi.InitialContextFactory implementation. You obtain the name of the InitialContextFactory class from the naming service provider you are using.

Example 3.1, “A sample jndi.properties file” gives a sample jndi.properties file a client application would use to connect to a JBossNS service running on the local host at port 1099. The client application would need to have the jndi.properties file available on the application classpath. These are the properties that the JBossNS JNDI implementation requires. Other JNDI providers will have different properties and values.

Example 3.1. A sample jndi.properties file

### JBossNS properties
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

3.1.2. J2EE and JNDI - The Application Component Environment

JNDI is a fundamental aspect of the J2EE specifications. One key usage is the isolation of J2EE component code from the environment in which the code is deployed. Use of the application component's environment allows the application component to be customized without the need to access or change the application component's source code. The application component environment is referred to as the ENC, the enterprise naming context. It is the responsibility of the application component container to make an ENC available to the container components in the form of JNDI Context. The ENC is utilized by the participants involved in the life cycle of a J2EE component in the following ways.

  • Application component business logic should be coded to access information from its ENC. The component provider uses the standard deployment descriptor for the component to specify the required ENC entries. The entries are declarations of the information and resources the component requires at runtime.

  • The container provides tools that allow a deployer of a component to map the ENC references made by the component developer to the deployment environment entity that satisfies the reference.

  • The component deployer utilizes the container tools to ready a component for final deployment.

  • The component container uses the deployment package information to build the complete component ENC at runtime

The complete specification regarding the use of JNDI in the J2EE platform can be found in section 5 of the J2EE 1.4 specification. The J2EE specification is available at http://java.sun.com/j2ee/download.html.

An application component instance locates the ENC using the JNDI API. An application component instance creates a javax.naming.InitialContext object by using the no argument constructor and then looks up the naming environment under the name java:comp/env. The application component's environment entries are stored directly in the ENC, or in its subcontexts. Example 3.2, “ENC access sample code” illustrates the prototypical lines of code a component uses to access its ENC.

Example 3.2. ENC access sample code

// Obtain the application component's ENC
Context iniCtx = new InitialContext();
Context compEnv = (Context) iniCtx.lookup("java:comp/env");

An application component environment is a local environment that is accessible only by the component when the application server container thread of control is interacting with the application component. This means that an EJB Bean1 cannot access the ENC elements of EJB Bean2, and vice versa. Similarly, Web application Web1 cannot access the ENC elements of Web application Web2 or Bean1 or Bean2 for that matter. Also, arbitrary client code, whether it is executing inside of the application server VM or externally cannot access a component's java:comp JNDI context. The purpose of the ENC is to provide an isolated, read-only namespace that the application component can rely on regardless of the type of environment in which the component is deployed. The ENC must be isolated from other components because each component defines its own ENC content. Components A and B, for example, may define the same name to refer to different objects. For example, EJB Bean1 may define an environment entry java:comp/env/red to refer to the hexadecimal value for the RGB color for red, while Web application Web1 may bind the same name to the deployment environment language locale representation of red.

There are three commonly used levels of naming scope in JBoss: names under java:comp, names under java:, and any other name. As discussed, the java:comp context and its subcontexts are only available to the application component associated with that particular context. Subcontexts and object bindings directly under java: are only visible within the JBoss server virtual machine and not to remote clients. Any other context or object binding is available to remote clients, provided the context or object supports serialization. You'll see how the isolation of these naming scopes is achieved in the Section 3.2, “The JBossNS Architecture”.

An example of where the restricting a binding to the java: context is useful would be a javax.sql.DataSource connection factory that can only be used inside of the JBoss server where the associated database pool resides. On the other hand, an EJB home interface would be boung to a globally visible name that should accessible by remote client.

3.1.2.1. ENC Usage Conventions

JNDI is used as the API for externalizing a great deal of information from an application component. The JNDI name that the application component uses to access the information is declared in the standard ejb-jar.xml deployment descriptor for EJB components, and the standard web.xml deployment descriptor for Web components. Several different types of information may be stored in and retrieved from JNDI including:

  • Environment entries as declared by the env-entry elements

  • EJB references as declared by ejb-ref and ejb-local-ref elements.

  • Resource manager connection factory references as declared by the resource-ref elements

  • Resource environment references as declared by the resource-env-ref elements

Each type of deployment descriptor element has a JNDI usage convention with regard to the name of the JNDI context under which the information is bound. Also, in addition to the standard deploymentdescriptor element, there is a JBoss server specific deployment descriptor element that maps the JNDI name as used by the application component to the deployment environment JNDI name.

3.1.2.1.1. Environment Entries

Environment entries are the simplest form of information stored in a component ENC, and are similar to operating system environment variables like those found on UNIX or Windows. Environment entries are a name-to-value binding that allows a component to externalize a value and refer to the value using a name.

An environment entry is declared using an env-entry element in the standard deployment descriptors. The env-entry element contains the following child elements:

  • An optional description element that provides a description of the entry

  • An env-entry-name element giving the name of the entry relative to java:comp/env

  • An env-entry-type element giving the Java type of the entry value that must be one of:

    • java.lang.Byte

    • java.lang.Boolean

    • java.lang.Character

    • java.lang.Double

    • java.lang.Float

    • java.lang.Integer

    • java.lang.Long

    • java.lang.Short

    • java.lang.String

  • An env-entry-value element giving the value of entry as a string

An example of an env-entry fragment from an ejb-jar.xml deployment descriptor is given in Example 3.3, “An example ejb-jar.xml env-entry fragment”. There is no JBoss specific deployment descriptor element because an env-entry is a complete name and value specification. Example 3.4, “ ENC env-entry access code fragment” shows a sample code fragment for accessing the maxExemptions and taxRate env-entry values declared in the deployment descriptor.

Example 3.3. An example ejb-jar.xml env-entry fragment

<!-- ... -->
<session>
    <ejb-name>ASessionBean</ejb-name>
    <!-- ... -->
    <env-entry>
        <description>The maximum number of tax exemptions allowed </description>
        <env-entry-name>maxExemptions</env-entry-name>
        <env-entry-type>java.lang.Integer</env-entry-type>
        <env-entry-value>15</env-entry-value>
    </env-entry>
    <env-entry>
        <description>The tax rate </description>
        <env-entry-name>taxRate</env-entry-name>
        <env-entry-type>java.lang.Float</env-entry-type>
        <env-entry-value>0.23</env-entry-value>
    </env-entry>
</session>
<!-- ... -->    

Example 3.4.  ENC env-entry access code fragment

InitialContext iniCtx = new InitialContext();
Context envCtx = (Context) iniCtx.lookup("java:comp/env");
Integer maxExemptions = (Integer) envCtx.lookup("maxExemptions");
Float taxRate = (Float) envCtx.lookup("taxRate");
3.1.2.1.2. EJB References

It is common for EJBs and Web components to interact with other EJBs. Because the JNDI name under which an EJB home interface is bound is a deployment time decision, there needs to be a way for a component developer to declare a reference to an EJB that will be linked by the deployer. EJB references satisfy this requirement.

An EJB reference is a link in an application component naming environment that points to a deployed EJB home interface. The name used by the application component is a logical link that isolates the component from the actual name of the EJB home in the deployment environment. The J2EE specification recommends that all references to enterprise beans be organized in the java:comp/env/ejb context of the application component's environment.

An EJB reference is declared using an ejb-ref element in the deployment descriptor. Each ejb-ref element describes the interface requirements that the referencing application component has for the referenced enterprise bean. The ejb-ref element contains the following child elements:

  • An optional description element that provides the purpose of the reference.

  • An ejb-ref-name element that specifies the name of the reference relative to the java:comp/env context. To place the reference under the recommended java:comp/env/ejb context, use an ejb/link-name form for the ejb-ref-name value.

  • An ejb-ref-type element that specifies the type of the EJB. This must be either Entity or Session.

  • A home element that gives the fully qualified class name of the EJB home interface.

  • A remote element that gives the fully qualified class name of the EJB remote interface.

  • An optional ejb-link element that links the reference to another enterprise bean in the same EJB JAR or in the same J2EE application unit. The ejb-link value is the ejb-name of the referenced bean. If there are multiple enterprise beans with the same ejb-name, the value uses the path name specifying the location of the ejb-jar file that contains the referenced component. The path name is relative to the referencing ejb-jar file. The Application Assembler appends the ejb-name of the referenced bean to the path name separated by #. This allows multiple beans with the same name to be uniquely identified.

An EJB reference is scoped to the application component whose declaration contains the ejb-ref element. This means that the EJB reference is not accessible from other application components at runtime, and that other application components may define ejb-ref elements with the same ejb-ref-name without causing a name conflict. Example 3.5, “An example ejb-jar.xml ejb-ref descriptor fragment” provides an ejb-jar.xml fragment that illustrates the use of the ejb-ref element. A code sample that illustrates accessing the ShoppingCartHome reference declared in Example 3.5, “An example ejb-jar.xml ejb-ref descriptor fragment” is given in Example 3.6, “ ENC ejb-ref access code fragment”.

Example 3.5. An example ejb-jar.xml ejb-ref descriptor fragment

<!-- ... -->
<session>
    <ejb-name>ShoppingCartBean</ejb-name>
    <!-- ...-->
</session>

<session>
    <ejb-name>ProductBeanUser</ejb-name>
    <!--...-->
    <ejb-ref>
        <description>This is a reference to the store products entity </description>
        <ejb-ref-name>ejb/ProductHome</ejb-ref-name>
        <ejb-ref-type>Entity</ejb-ref-type>
        <home>org.jboss.store.ejb.ProductHome</home>
    </ejb-ref>
    <remote> org.jboss.store.ejb.Product</remote>
</session>

<session>
    <ejb-ref>
        <ejb-name>ShoppingCartUser</ejb-name>
        <!--...-->
        <ejb-ref-name>ejb/ShoppingCartHome</ejb-ref-name>
        <ejb-ref-type>Session</ejb-ref-type>
        <home>org.jboss.store.ejb.ShoppingCartHome</home>
        <remote> org.jboss.store.ejb.ShoppingCart</remote>
        <ejb-link>ShoppingCartBean</ejb-link>
    </ejb-ref>
</session>

<entity>
    <description>The Product entity bean </description>
    <ejb-name>ProductBean</ejb-name>
    <!--...-->
</entity>

<!--...--> 

Example 3.6.  ENC ejb-ref access code fragment

InitialContext iniCtx = new InitialContext();
Context ejbCtx = (Context) iniCtx.lookup("java:comp/env/ejb");
ShoppingCartHome home = (ShoppingCartHome) ejbCtx.lookup("ShoppingCartHome"); 
3.1.2.1.3. EJB References with jboss.xml and jboss-web.xml

The JBoss specific jboss.xml EJB deployment descriptor affects EJB references in two ways. First, the jndi-name child element of the session and entity elements allows the user to specify the deployment JNDI name for the EJB home interface. In the absence of a jboss.xml specification of the jndi-name for an EJB, the home interface is bound under the ejb-jar.xml ejb-name value. For example, the session EJB with the ejb-name of ShoppingCartBean in Example 3.5, “An example ejb-jar.xml ejb-ref descriptor fragment” would have its home interface bound under the JNDI name ShoppingCartBean in the absence of a jboss.xml jndi-name specification.

The second use of the jboss.xml descriptor with respect to ejb-refs is the setting of the destination to which a component's ENC ejb-ref refers. The ejb-link element cannot be used to refer to EJBs in another enterprise application. If your ejb-ref needs to access an external EJB, you can specify the JNDI name of the deployed EJB home using the jboss.xml ejb-ref/jndi-name element.

The jboss-web.xml descriptor is used only to set the destination to which a Web application ENC ejb-ref refers. The content model for the JBoss ejb-ref is as follows:

  • An ejb-ref-name element that corresponds to the ejb-ref-name element in the ejb-jar.xml or web.xml standard descriptor

  • A jndi-name element that specifies the JNDI name of the EJB home interface in the deployment environment

Example 3.7, “ An example jboss.xml ejb-ref fragment” provides an example jboss.xml descriptor fragment that illustrates the following usage points:

  • The ProductBeanUser ejb-ref link destination is set to the deployment name of jboss/store/ProductHome

  • The deployment JNDI name of the ProductBean is set to jboss/store/ProductHome

Example 3.7.  An example jboss.xml ejb-ref fragment

<!-- ... -->
<session>
    <ejb-name>ProductBeanUser</ejb-name>
    <ejb-ref>
        <ejb-ref-name>ejb/ProductHome</ejb-ref-name>
        <jndi-name>jboss/store/ProductHome</jndi-name>
    </ejb-ref>
</session>
                        
<entity>
    <ejb-name>ProductBean</ejb-name>
    <jndi-name>jboss/store/ProductHome</jndi-name>
     <!-- ... -->
</entity>
<!-- ... -->
3.1.2.1.4. EJB Local References

EJB 2.0 added local interfaces that do not use RMI call by value semantics. These interfaces use a call by reference semantic and therefore do not incur any RMI serialization overhead. An EJB local reference is a link in an application component naming environment that points to a deployed EJB local home interface. The name used by the application component is a logical link that isolates the component from the actual name of the EJB local home in the deployment environment. The J2EE specification recommends that all references to enterprise beans be organized in the java:comp/env/ejb context of the application component's environment.

An EJB local reference is declared using an ejb-local-ref element in the deployment descriptor. Each ejb-local-ref element describes the interface requirements that the referencing application component has for the referenced enterprise bean. The ejb-local-ref element contains the following child elements:

  • An optional description element that provides the purpose of the reference.

  • An ejb-ref-name element that specifies the name of the reference relative to the java:comp/env context. To place the reference under the recommended java:comp/env/ejb context, use an ejb/link-name form for the ejb-ref-name value.

  • An ejb-ref-type element that specifies the type of the EJB. This must be either Entity or Session.

  • A local-home element that gives the fully qualified class name of the EJB local home interface.

  • A local element that gives the fully qualified class name of the EJB local interface.

  • An ejb-link element that links the reference to another enterprise bean in the ejb-jar file or in the same J2EE application unit. The ejb-link value is the ejb-name of the referenced bean. If there are multiple enterprise beans with the same ejb-name, the value uses the path name specifying the location of the ejb-jar file that contains the referenced component. The path name is relative to the referencing ejb-jar file. The Application Assembler appends the ejb-name of the referenced bean to the path name separated by #. This allows multiple beans with the same name to be uniquely identified. An ejb-link element must be specified in JBoss to match the local reference to the corresponding EJB.

An EJB local reference is scoped to the application component whose declaration contains the ejb-local-ref element. This means that the EJB local reference is not accessible from other application components at runtime, and that other application components may define ejb-local-ref elements with the same ejb-ref-name without causing a name conflict. Example 3.8, “ An example ejb-jar.xml ejb-local-ref descriptor fragment” provides an ejb-jar.xml fragment that illustrates the use of the ejb-local-ref element. A code sample that illustrates accessing the ProbeLocalHome reference declared in Example 3.8, “ An example ejb-jar.xml ejb-local-ref descriptor fragment” is given in Example 3.9, “ENC ejb-local-ref access code fragment”.

Example 3.8.  An example ejb-jar.xml ejb-local-ref descriptor fragment

    <!-- ... -->
    <session>
        <ejb-name>Probe</ejb-name>
        <home>org.jboss.test.perf.interfaces.ProbeHome</home>
        <remote>org.jboss.test.perf.interfaces.Probe</remote>
        <local-home>org.jboss.test.perf.interfaces.ProbeLocalHome</local-home>
        <local>org.jboss.test.perf.interfaces.ProbeLocal</local>
        <ejb-class>org.jboss.test.perf.ejb.ProbeBean</ejb-class>
        <session-type>Stateless</session-type>
        <transaction-type>Bean</transaction-type>
    </session>
    <session>
        <ejb-name>PerfTestSession</ejb-name>
        <home>org.jboss.test.perf.interfaces.PerfTestSessionHome</home>
        <remote>org.jboss.test.perf.interfaces.PerfTestSession</remote>
        <ejb-class>org.jboss.test.perf.ejb.PerfTestSessionBean</ejb-class>
        <session-type>Stateless</session-type>
        <transaction-type>Container</transaction-type>
        <ejb-ref>
            <ejb-ref-name>ejb/ProbeHome</ejb-ref-name>
            <ejb-ref-type>Session</ejb-ref-type>
            <home>org.jboss.test.perf.interfaces.SessionHome</home>
            <remote>org.jboss.test.perf.interfaces.Session</remote>
            <ejb-link>Probe</ejb-link>
        </ejb-ref>
        <ejb-local-ref>
            <ejb-ref-name>ejb/ProbeLocalHome</ejb-ref-name>
            <ejb-ref-type>Session</ejb-ref-type>
            <local-home>org.jboss.test.perf.interfaces.ProbeLocalHome</local-home>
            <local>org.jboss.test.perf.interfaces.ProbeLocal</local>
            <ejb-link>Probe</ejb-link>
        </ejb-local-ref>
    </session>
    <!-- ... -->

Example 3.9. ENC ejb-local-ref access code fragment

InitialContext iniCtx = new InitialContext();
Context ejbCtx = (Context) iniCtx.lookup("java:comp/env/ejb");
ProbeLocalHome home = (ProbeLocalHome) ejbCtx.lookup("ProbeLocalHome");
3.1.2.1.5. Resource Manager Connection Factory References

Resource manager connection factory references allow application component code to refer to resource factories using logical names called resource manager connection factory references. Resource manager connection factory references are defined by the resource-ref elements in the standard deployment descriptors. The Deployer binds the resource manager connection factory references to the actual resource manager connection factories that exist in the target operational environment using the jboss.xml and jboss-web.xml descriptors.

Each resource-ref element describes a single resource manager connection factory reference. The resource-ref element consists of the following child elements:

  • An optional description element that provides the purpose of the reference.

  • A res-ref-name element that specifies the name of the reference relative to the java:comp/env context. The resource type based naming convention for which subcontext to place the res-ref-name into is discussed in the next paragraph.

  • A res-type element that specifies the fully qualified class name of the resource manager connection factory.

  • A res-auth element that indicates whether the application component code performs resource signon programmatically, or whether the container signs on to the resource based on the principal mapping information supplied by the Deployer. It must be one of Application or Container.

  • An optional res-sharing-scope element. This currently is not supported by JBoss.

The J2EE specification recommends that all resource manager connection factory references be organized in the subcontexts of the application component's environment, using a different subcontext for each resource manager type. The recommended resource manager type to subcontext name is as follows:

  • JDBC DataSource references should be declared in the java:comp/env/jdbc subcontext.

  • JMS connection factories should be declared in the java:comp/env/jms subcontext.

  • JavaMail connection factories should be declared in the java:comp/env/mail subcontext.

  • URL connection factories should be declared in the java:comp/env/url subcontext.

Example 3.10, “ A web.xml resource-ref descriptor fragment” shows an example web.xml descriptor fragment that illustrates the resource-ref element usage. Example 3.11, “ENC resource-ref access sample code fragment” provides a code fragment that an application component would use to access the DefaultMail resource declared by the resource-ref.

Example 3.10.  A web.xml resource-ref descriptor fragment

<web>
    <!-- ... -->
    <servlet>
        <servlet-name>AServlet</servlet-name>
        <!-- ... -->
    </servlet>
    <!-- ... -->
    <!-- JDBC DataSources (java:comp/env/jdbc) -->
    <resource-ref>
        <description>The default DS</description>
        <res-ref-name>jdbc/DefaultDS</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
    </resource-ref>
    <!-- JavaMail Connection Factories (java:comp/env/mail) -->
    <resource-ref>
        <description>Default Mail</description>
        <res-ref-name>mail/DefaultMail</res-ref-name>
        <res-type>javax.mail.Session</res-type>
        <res-auth>Container</res-auth>
    </resource-ref>
    <!-- JMS Connection Factories (java:comp/env/jms) -->
    <resource-ref>
        <description>Default QueueFactory</description>
        <res-ref-name>jms/QueueFactory</res-ref-name>
        <res-type>javax.jms.QueueConnectionFactory</res-type>
        <res-auth>Container</res-auth>
    </resource-re>      

Example 3.11. ENC resource-ref access sample code fragment

Context initCtx = new InitialContext();
javax.mail.Session s = (javax.mail.Session)
initCtx.lookup("java:comp/env/mail/DefaultMail");
3.1.2.1.6. Resource Manager Connection Factory References with jboss.xml and jboss-web.xml

The purpose of the JBoss jboss.xml EJB deployment descriptor and jboss-web.xml Web application deployment descriptor is to provide the link from the logical name defined by the res-ref-name element to the JNDI name of the resource factory as deployed in JBoss. This is accomplished by providing a resource-ref element in the jboss.xml or jboss-web.xml descriptor. The JBoss resource-ref element consists of the following child elements:

  • A res-ref-name element that must match the res-ref-name of a corresponding resource-ref element from the ejb-jar.xml or web.xml standard descriptors

  • An optional res-type element that specifies the fully qualified class name of the resource manager connection factory

  • A jndi-name element that specifies the JNDI name of the resource factory as deployed in JBoss

  • A res-url element that specifies the URL string in the case of a resource-ref of type java.net.URL

Example 3.12, “A sample jboss-web.xml resource-ref descriptor fragment” provides a sample jboss-web.xml descriptor fragment that shows sample mappings of the resource-ref elements given in Example 3.10, “ A web.xml resource-ref descriptor fragment”.

Example 3.12. A sample jboss-web.xml resource-ref descriptor fragment

<jboss-web>
    <!-- ... -->
    <resource-ref>
        <res-ref-name>jdbc/DefaultDS</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <jndi-name>java:/DefaultDS</jndi-name>
    </resource-ref>
    <resource-ref>
        <res-ref-name>mail/DefaultMail</res-ref-name>
        <res-type>javax.mail.Session</res-type>
        <jndi-name>java:/Mail</jndi-name>
    </resource-ref>
    <resource-ref>
        <res-ref-name>jms/QueueFactory</res-ref-name>
        <res-type>javax.jms.QueueConnectionFactory</res-type>
        <jndi-name>QueueConnectionFactory</jndi-name>
    </resource-ref>
    <!-- ... -->
</jboss-web>
3.1.2.1.7. Resource Environment References

Resource environment references are elements that refer to administered objects that are associated with a resource (for example, JMS destinations) using logical names. Resource environment references are defined by the resource-env-ref elements in the standard deployment descriptors. The Deployer binds the resource environment references to the actual administered objects location in the target operational environment using the jboss.xml and jboss-web.xml descriptors.

Each resource-env-ref element describes the requirements that the referencing application component has for the referenced administered object. The resource-env-ref element consists of the following child elements:

  • An optional description element that provides the purpose of the reference.

  • A resource-env-ref-name element that specifies the name of the reference relative to the java:comp/env context. Convention places the name in a subcontext that corresponds to the associated resource factory type. For example, a JMS queue reference named MyQueue should have a resource-env-ref-name of jms/MyQueue.

  • A resource-env-ref-type element that specifies the fully qualified class name of the referenced object. For example, in the case of a JMS queue, the value would be javax.jms.Queue.

Example 3.13, “An example ejb-jar.xml resource-env-ref fragment” provides an example resource-ref-env element declaration by a session bean. Example 3.14, “ ENC resource-env-ref access code fragment” gives a code fragment that illustrates how to look up the StockInfo queue declared by the resource-env-ref.

Example 3.13. An example ejb-jar.xml resource-env-ref fragment

<session>
    <ejb-name>MyBean</ejb-name>
    
    <resource-env-ref>
        <description>This is a reference to a JMS queue used in the
            processing of Stock info
        </description>
        <resource-env-ref-name>jms/StockInfo</resource-env-ref-name>
        <resource-env-ref-type>javax.jms.Queue</resource-env-ref-type>
    </resource-env-ref>
    <!-- ... -->
</session>

Example 3.14.  ENC resource-env-ref access code fragment

InitialContext iniCtx = new InitialContext();
javax.jms.Queue q = (javax.jms.Queue)
envCtx.lookup("java:comp/env/jms/StockInfo");
3.1.2.1.8. Resource Environment References and jboss.xml, jboss-web.xml

The purpose of the JBoss jboss.xml EJB deployment descriptor and jboss-web.xml Web application deployment descriptor is to provide the link from the logical name defined by the resource-env-ref-name element to the JNDI name of the administered object deployed in JBoss. This is accomplished by providing a resource-env-ref element in the jboss.xml or jboss-web.xml descriptor. The JBoss resource-env-ref element consists of the following child elements:

  • A resource-env-ref-name element that must match the resource-env-ref-name of a corresponding resource-env-ref element from the ejb-jar.xml or web.xml standard descriptors

  • A jndi-name element that specifies the JNDI name of the resource as deployed in JBoss

Example 3.15, “A sample jboss.xml resource-env-ref descriptor fragment” provides a sample jboss.xml descriptor fragment that shows a sample mapping for the StockInfo resource-env-ref.

Example 3.15. A sample jboss.xml resource-env-ref descriptor fragment

<session>
    <ejb-name>MyBean</ejb-name>
        
        <resource-env-ref>
        <resource-env-ref-name>jms/StockInfo</resource-env-ref-name>
        <jndi-name>queue/StockInfoQueue</jndi-name>
    </resource-env-ref>
    <!-- ... -->
</session>  

3.2. The JBossNS Architecture

The JBossNS architecture is a Java socket/RMI based implementation of the javax.naming.Context interface. It is a client/server implementation that can be accessed remotely. The implementation is optimized so that access from within the same VM in which the JBossNS server is running does not involve sockets. Same VM access occurs through an object reference available as a global singleton. Figure 3.1, “Key components in the JBossNS architecture.” illustrates some of the key classes in the JBossNS implementation and their relationships.

Key components in the JBossNS architecture.

Figure 3.1. Key components in the JBossNS architecture.

We will start with the NamingService MBean. The NamingService MBean provides the JNDI naming service. This is a key service used pervasively by the J2EE technology components. The configurable attributes for the NamingService are as follows.

  • Port: The jnp protocol listening port for the NamingService. If not specified default is 1099, the same as the RMI registry default port.

  • RmiPort: The RMI port on which the RMI Naming implementation will be exported. If not specified the default is 0 which means use any available port.

  • BindAddress: The specific address the NamingService listens on. This can be used on a multi-homed host for a java.net.ServerSocket that will only accept connect requests on one of its addresses.

  • RmiBindAddress: The specific address the RMI server portion of the NamingService listens on. This can be used on a multi-homed host for a java.net.ServerSocket that will only accept connect requests on one of its addresses. If this is not specified and the BindAddress is, the RmiBindAddress defaults to the BindAddress value.

  • Backlog: The maximum queue length for incoming connection indications (a request to connect) is set to the backlog parameter. If a connection indication arrives when the queue is full, the connection is refused.

  • ClientSocketFactory: An optional custom java.rmi.server.RMIClientSocketFactory implementation class name. If not specified the default RMIClientSocketFactory is used.

  • ServerSocketFactory: An optional custom java.rmi.server.RMIServerSocketFactory implementation class name. If not specified the default RMIServerSocketFactory is used.

  • JNPServerSocketFactory: An optional custom javax.net.ServerSocketFactory implementation class name. This is the factory for the ServerSocket used to bootstrap the download of the JBossNS Naming interface. If not specified the javax.net.ServerSocketFactory.getDefault() method value is used.

The NamingService also creates the java:comp context such that access to this context is isolated based on the context class loader of the thread that accesses the java:comp context. This provides the application component private ENC that is required by the J2EE specs. This segregation is accomplished by binding a javax.naming.Reference to a context that uses the org.jboss.naming.ENCFactory as its javax.naming.ObjectFactory. When a client performs a lookup of java:comp, or any subcontext, the ENCFactory checks the thread context ClassLoader, and performs a lookup into a map using the ClassLoader as the key.

If a context instance does not exist for the class loader instance, one is created and associated with that class loader in the ENCFactory map. Thus, correct isolation of an application component's ENC relies on each component receiving a unique ClassLoader that is associated with the component threads of execution.

The NamingService delegates its functionality to an org.jnp.server.Main MBean. The reason for the duplicate MBeans is because JBossNS started out as a stand-alone JNDI implementation, and can still be run as such. The NamingService MBean embeds the Main instance into the JBoss server so that usage of JNDI with the same VM as the JBoss server does not incur any socket overhead. The configurable attributes of the NamingService are really the configurable attributes of the JBossNS Main MBean. The setting of any attributes on the NamingService MBean simply set the corresponding attributes on the Main MBean the NamingService contains. When the NamingService is started, it starts the contained Main MBean to activate the JNDI naming service.

In addition, the NamingService exposes the Naming interface operations through a JMX detyped invoke operation. This allows the naming service to be accessed via JMX adaptors for arbitrary protocols. We will look at an example of how HTTP can be used to access the naming service using the invoke operation later in this chapter.

The details of threads and the thread context class loader won't be explored here, but the JNDI tutorial provides a concise discussion that is applicable. See http://java.sun.com/products/jndi/tutorial/beyond/misc/classloader.html for the details.

When the Main MBean is started, it performs the following tasks:

  • Instantiates an org.jnp.naming.NamingService instance and sets this as the local VM server instance. This is used by any org.jnp.interfaces.NamingContext instances that are created within the JBoss server VM to avoid RMI calls over TCP/IP.

  • Exports the NamingServer instance's org.jnp.naming.interfaces.Naming RMI interface using the configured RmiPort, ClientSocketFactory, ServerSocketFactoryattributes.

  • Creates a socket that listens on the interface given by the BindAddress and Port attributes.

  • Spawns a thread to accept connections on the socket.

3.2.1. The Naming InitialContext Factories

The JBoss JNDI provider currently supports three different InitialContext factory implementations. The most commonly used factory is the org.jnp.interfaces.NamingContextFactory implementation. Its properties include:

  • java.naming.factory.initial: The name of the environment property for specifying the initial context factory to use. The value of the property should be the fully qualified class name of the factory class that will create an initial context. If it is not specified, a javax.naming.NoInitialContextException will be thrown when an InitialContext object is created.

  • java.naming.provider.url: The name of the environment property for specifying the location of the JBoss JNDI service provider the client will use. The NamingContextFactory class uses this information to know which JBossNS server to connect to. The value of the property should be a URL string. For JBossNS the URL format is jnp://host:port/[jndi_path]. The jnp: portion of the URL is the protocol and refers to the socket/RMI based protocol used by JBoss. The jndi_path portion of the URL is an option JNDI name relative to the root context, for example, apps or apps/tmp. Everything but the host component is optional. The following examples are equivalent because the default port value is 1099.

    • jnp://www.jboss.org:1099/

    • www.jboss.org:1099

    • www.jboss.org

  • java.naming.factory.url.pkgs: The name of the environment property for specifying the list of package prefixes to use when loading in URL context factories. The value of the property should be a colon-separated list of package prefixes for the class name of the factory class that will create a URL context factory. For the JBoss JNDI provider this must be org.jboss.naming:org.jnp.interfaces. This property is essential for locating the jnp: and java: URL context factories of the JBoss JNDI provider.

  • jnp.socketFactory: The fully qualified class name of the javax.net.SocketFactory implementation to use to create the bootstrap socket. The default value is org.jnp.interfaces.TimedSocketFactory. The TimedSocketFactory is a simple SocketFactory implementation that supports the specification of a connection and read timeout. These two properties are specified by:

  • jnp.timeout: The connection timeout in milliseconds. The default value is 0 which means the connection will block until the VM TCP/IP layer times out.

  • jnp.sotimeout: The connected socket read timeout in milliseconds. The default value is 0 which means reads will block. This is the value passed to the Socket.setSoTimeout on the newly connected socket.

When a client creates an InitialContext with these JBossNS properties available, the org.jnp.interfaces.NamingContextFactory object is used to create the Context instance that will be used in subsequent operations. The NamingContextFactory is the JBossNS implementation of the javax.naming.spi.InitialContextFactory interface. When the NamingContextFactory class is asked to create a Context, it creates an org.jnp.interfaces.NamingContext instance with the InitialContext environment and 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 information from the environment indicates from which server to obtain a NamingServer RMI reference.

The association of the NamingContext instance to a NamingServer instance is done in a lazy fashion on the first Context operation that is performed. When a Context operation is performed and the NamingContext has no NamingServer associated with it, it looks to see if its environment properties define a Context.PROVIDER_URL. A Context.PROVIDER_URL defines the host and port of the JBossNS server the Context is to use. If there is a provider URL, the NamingContext first checks to see if a Naming instance keyed by the host and port pair has already been created by checking a NamingContext class static map. It simply uses the existing Naming instance if one for the host port pair has already been obtained. If no Naming instance has been created for the given host and port, the NamingContext connects to the host and port using a java.net.Socket, and retrieves a Naming RMI stub from the server by reading a java.rmi.MarshalledObject from the socket and invoking its get method. The newly obtained Naming instance is cached in the NamingContext server map under the host and port pair. If no provider URL was specified in the JNDI environment associated with the context, the NamingContext simply uses the in VM Naming instance set by the Main MBean.

The NamingContext implementation of the Context interface delegates all operations to the Naming instance associated with the NamingContext. The NamingServer class that implements the Naming interface uses a java.util.Hashtable as the Context store. There is one unique NamingServer instance for each distinct JNDI Name for a given JBossNS server. There are zero or more transient NamingContext instances active at any given moment that refers to a NamingServer instance. The purpose of the NamingContext is to act as a Context to the Naming interface adaptor that manages translation of the JNDI names passed to the NamingContext . Because a JNDI name can be relative or a URL, it needs to be converted into an absolute name in the context of the JBossNS server to which it refers. This translation is a key function of the NamingContext.

3.2.1.1. Naming Discovery in Clustered Environments

When running in a clustered JBoss environment, you can choose not to specify a Context.PROVIDER_URL value and let the client query the network for available naming services. This only works with JBoss servers running with the all configuration, or an equivalent configuration that has org.jboss.ha.framework.server.ClusterPartition and org.jboss.ha.jndi.HANamingService services deployed. The discovery process consists of sending a multicast request packet to the discovery address/port and waiting for any node to respond. The response is a HA-RMI version of the Naming interface. The following InitialContext proerties affect the discovery configuration:

  • jnp.partitionName: The cluster partition name discovery should be restricted to. If you are running in an environment with multiple clusters, you may want to restrict the naming discovery to a particular cluster. There is no default value, meaning that any cluster response will be accepted.

  • jnp.discoveryGroup: The multicast IP/address to which the discovery query is sent. The default is 230.0.0.4.

  • jnp.discoveryPort: The port to which the discovery query is sent. The default is 1102.

  • jnp.discoveryTimeout: The time in milliseconds to wait for a discovery query response. The default value is 5000 (5 seconds).

  • jnp.disableDiscovery: A flag indicating if the discovery process should be avoided. Discovery occurs when either no Context.PROVIDER_URL is specified, or no valid naming service could be located among the URLs specified. If the jnp.disableDiscovery flag is true, then discovery will not be attempted.

3.2.1.2. The HTTP InitialContext Factory Implementation

The JNDI naming service can be accessed over HTTP. From a JNDI client's perspective this is a transparent change as they continue to use the JNDI Context interface. Operations through the Context interface are translated into HTTP posts to a servlet that passes the request to the NamingService using its JMX invoke operation. Advantages of using HTTP as the access protocol include better access through firewalls and proxies setup to allow HTTP, as well as the ability to secure access to the JNDI service using standard servlet role based security.

To access JNDI over HTTP you use the org.jboss.naming.HttpNamingContextFactory as the factory implementation. The complete set of support InitialContext environment properties for this factory are:

  • java.naming.factory.initial: The name of the environment property for specifying the initial context factory, which must be org.jboss.naming.HttpNamingContextFactory.

  • java.naming.provider.url (or Context.PROVIDER_URL): This must be set to the http URL of the JMX invoker servlet. It depends on the configuration of the http-invoker.sar and its contained WAR, but the default setup places the JMX invoker servlet under /invoker/JMXInvokerServlet. The full HTTP URL would be the public URL of the JBoss servlet container plus /invoker/JMXInvokerServlet. Examples include:

    • http://www.jboss.org:8080/invoker/JMXInvokerServlet

    • http://www.jboss.org/invoker/JMXInvokerServlet

    • https://www.jboss.org/invoker/JMXInvokerServlet

    The first example accesses the servlet using the port 8080. The second uses the standard HTTP port 80, and the third uses an SSL encrypted connection to the standard HTTPS port 443.

  • java.naming.factory.url.pkgs: For all JBoss JNDI provider this must be org.jboss.naming:org.jnp.interfaces. This property is essential for locating the jnp: and java: URL context factories of the JBoss JNDI provider.

The JNDI Context implementation returned by the HttpNamingContextFactory is a proxy that delegates invocations made on it to a bridge servlet which forwards the invocation to the NamingService through the JMX bus and marshalls the reply back over HTTP. The proxy needs to know what the URL of the bridge servlet is in order to operate. This value may have been bound on the server side if the JBoss web server has a well known public interface. If the JBoss web server is sitting behind one or more firewalls or proxies, the proxy cannot know what URL is required. In this case, the proxy will be associated with a system property value that must be set in the client VM. For more information on the operation of JNDI over HTTP see Section 3.2.2, “Accessing JNDI over HTTP”.

3.2.1.3. The Login InitialContext Factory Implementation

JAAS is the preferred method for authenticating a remote client to JBoss. However, for simplicity and to ease the migration from other application server environment that do not use JAAS, JBoss alows you the security credentials to be passed through the InitialContext. JAAS is still used under the covers, but there is no manifest use of the JAAS interfaces in the client application.

The factory class that provides this capability is the org.jboss.security.jndi.LoginInitialContextFactory. The complete set of support InitialContext environment properties for this factory are:

  • java.naming.factory.initial: The name of the environment property for specifying the initial context factory, which must be org.jboss.security.jndi.LoginInitialContextFactory.

  • java.naming.provider.url: This must be set to a NamingContextFactory provider URL. The LoginIntialContext is really just a wrapper around the NamingContextFactory that adds a JAAS login to the existing NamingContextFactory behavior.

  • java.naming.factory.url.pkgs: For all JBoss JNDI provider this must be org.jboss.naming:org.jnp.interfaces. This property is essential for locating the jnp: and java: URL context factories of the JBoss JNDI provider.

  • java.naming.security.principal (or Context.SECURITY_PRINCIPAL): The principal to authenticate. This may be either a java.security.Principal implementation or a string representing the name of a principal.

  • java.naming.security.credentials (or Context.SECURITY_CREDENTIALS), The credentials that should be used to authenticate the principal, e.g., password, session key, etc.

  • java.naming.security.protocol: (Context.SECURITY_PROTOCOL) This gives the name of the JAAS login module to use for the authentication of the principal and credentials.

3.2.2. Accessing JNDI over HTTP

In addition to the legacy RMI/JRMP with a socket bootstrap protocol, JBoss provides support for accessing its JNDI naming service over HTTP. This capability is provided by http-invoker.sar. The structure of the http-invoker.sar is:

http-invoker.sar
+- META-INF/jboss-service.xml
+- invoker.war
| +- WEB-INF/jboss-web.xml
| +- WEB-INF/classes/org/jboss/invocation/http/servlet/InvokerServlet.class
| +- WEB-INF/classes/org/jboss/invocation/http/servlet/NamingFactoryServlet.class
| +- WEB-INF/classes/org/jboss/invocation/http/servlet/ReadOnlyAccessFilter.class
| +- WEB-INF/classes/roles.properties
| +- WEB-INF/classes/users.properties
| +- WEB-INF/web.xml
| +- META-INF/MANIFEST.MF
+- META-INF/MANIFEST.MF

The jboss-service.xml descriptor defines the HttpInvoker and HttpInvokerHA MBeans. These services handle the routing of methods invocations that are sent via HTTP to the approriate target MBean on the JMX bus.

The http-invoker.war web application contains servlets that handle the details of the HTTP transport. The NamingFactoryServlet handles creation requests for the JBoss JNDI naming service javax.naming.Context implementation. The InvokerServlet handles invocations made by RMI/HTTP clients. The ReadOnlyAccessFilter allows one to secure the JNDI naming service while making a single JNDI context available for read-only access by unauthenticated clients.

The HTTP invoker proxy/server structure for a JNDI Context

Figure 3.2. The HTTP invoker proxy/server structure for a JNDI Context

Before looking at the configurations let's look at the operation of the http-invoker services. Figure 3.2, “The HTTP invoker proxy/server structure for a JNDI Context” shows a logical view of the structure of a JBoss JNDI proxy and its relationship to the JBoss server side components of the http-invoker. The proxy is obtained from the NamingFactoryServlet using an InitialContext with the Context.INITIAL_CONTEXT_FACTORY property set to org.jboss.naming.HttpNamingContextFactory, and the Context.PROVIDER_URL property set to the HTTP URL of the NamingFactoryServlet. The resulting proxy is embedded in an org.jnp.interfaces.NamingContext instance that provides the Context interface implementation.

The proxy is an instance of org.jboss.invocation.http.interfaces.HttpInvokerProxy, and implements the org.jnp.interfaces.Naming interface. Internally the HttpInvokerProxy contains an invoker that marshalls the Naming interface method invocations to the InvokerServlet via HTTP posts. The InvokerServlet translates these posts into JMX invocations to the NamingService, and returns the invocation response back to the proxy in the HTTP post reponse.

There are several configuration values that need to be set to tie all of these components together and Figure 3.3, “The relationship between configuration files and JNDI/HTTP component” illustrates the relationship between configuration files and the corresponding components.

The relationship between configuration files and JNDI/HTTP component

Figure 3.3. The relationship between configuration files and JNDI/HTTP component

The http-invoker.sar/META-INF/jboss-service.xml descriptor defines the HttpProxyFactory that creates the HttpInvokerProxy for the NamingService. The attributes that need to be configured for the HttpProxyFactory include:

  • InvokerName: The JMX ObjectName of the NamingService defined in the conf/jboss-service.xml descriptor. The standard setting used in the JBoss distributions is jboss:service=Naming.

  • InvokerURL or InvokerURLPrefix + InvokerURLSuffix + UseHostName. You can specify the full HTTP URL to the InvokerServlet using the InvokerURL attribute, or you can specify the hostname independent parts of the URL and have the HttpProxyFactory fill them in. An example InvokerURL value would be http://jbosshost1.dot.com:8080/invoker/JMXInvokerServlet. This can be broken down into:

    • InvokerURLPrefix: the URL prefix prior to the hostname. Typically this will be http:// or https:// if SSL is to be used.

    • InvokerURLSuffix: the URL suffix after the hostname. This will include the port number of the web server as well as the deployed path to the InvokerServlet . For the example InvokerURL value the InvokerURLSuffix would be :8080/invoker/JMXInvokerServlet without the quotes. The port number is determined by the web container service settings. The path to the InvokerServlet is specified in the http-invoker.sar/invoker.war/WEB-INF/web.xml descriptor.

    • UseHostName: a flag indicating if the hostname should be used in place of the host IP address when building the hostname portion of the full InvokerURL. If true, InetAddress.getLocalHost().getHostName method will be used. Otherwise, the InetAddress.getLocalHost().getHostAddress() method is used.

  • ExportedInterface: The org.jnp.interfaces.Naming interface the proxy will expose to clients. The actual client of this proxy is the JBoss JNDI implementation NamingContext class, which JNDI client obtain from InitialContext lookups when using the JBoss JNDI provider.

  • JndiName: The name in JNDI under which the proxy is bound. This needs to be set to a blank/empty string to indicate the interface should not be bound into JNDI. We can't use the JNDI to bootstrap itself. This is the role of the NamingFactoryServlet.

The http-invoker.sar/invoker.war/WEB-INF/web.xml descriptor defines the mappings of the NamingFactoryServlet and InvokerServet along with their initialzation parameters. The configuration of the NamingFactoryServlet relevant to JNDI/HTTP is the JNDIFactory entry which defines:

  • A namingProxyMBean initialzation parameter that maps to the HttpProxyFactory MBean name. This is used by the NamingFactoryServlet to obtain the Naming proxy which it will return in response to HTTP posts. For the default http-invoker.sar/META-INF/jboss-service.xml settings the name jboss:service=invoker,type=http,target=Naming.

  • A proxy initialzation parameter that defines the name of the namingProxyMBean attribute to query for the Naming proxy value. This defaults to an attribute name of Proxy.

  • The servlet mapping for the JNDIFactory configuration. The default setting for the unsecured mapping is /JNDIFactory/*. This is relative to the context root of the http-invoker.sar/invoker.war, which by default is the WAR name minus the .war suffix.

The configuration of the InvokerServlet relevant to JNDI/HTTP is the JMXInvokerServlet which defines:

  • The servlet mapping of the InvokerServlet. The default setting for the unsecured mapping is /JMXInvokerServlet/*. This is relative to the context root of the http-invoker.sar/invoker.war, which by default is the WAR name minus the .war suffix.

3.2.3. Accessing JNDI over HTTPS

To be able to access JNDI over HTTP/SSL you need to enable an SSL connector on the web container. The details of this are convered in the Integrating Servlet Containers for Tomcat. We will demonstrate the use of HTTPS with a simple example client that uses an HTTPS URL as the JNDI provider URL. We will provide an SSL connector configuration for the example, so unless you are interested in the details of the SSL connector setup, the example is self contained.

We also provide a configuration of the HttpProxyFactory setup to use an HTTPS URL. shows the section of the http-invoker.sar jboss-service.xml descriptor that the example installs to provide this configuration. All the has changed relative to the standard http configuration are the InvokerURLPrefix and InvokerURLSuffix attributes, which setup an HTTPS URL using the 8443 port.

<!-- Expose the Naming service interface via HTTPS -->
<mbean code="org.jboss.invocation.http.server.HttpProxyFactory" 
       name="jboss:service=invoker,type=https,target=Naming">
    <!-- The Naming service we are proxying -->
    <attribute name="InvokerName">jboss:service=Naming</attribute>
    <!-- Compose the invoker URL from the cluster node address -->
    <attribute name="InvokerURLPrefix">https://</attribute>
    <attribute name="InvokerURLSuffix">:8443/invoker/JMXInvokerServlet </attribute>
    <attribute name="UseHostName">true</attribute>
    <attribute name="ExportedInterface">org.jnp.interfaces.Naming </attribute>
    <attribute name="JndiName"/>
    <attribute name="ClientInterceptors">
        <interceptors>
            <interceptor>org.jboss.proxy.ClientMethodInterceptor </interceptor>
            <interceptor>org.jboss.proxy.SecurityInterceptor</interceptor>
            <interceptor>org.jboss.naming.interceptors.ExceptionInterceptor </interceptor>
            <interceptor>org.jboss.invocation.InvokerInterceptor </interceptor>
        </interceptors>
    </attribute>
</mbean>

At a minimum, a JNDI client using HTTPS requires setting up a HTTPS URL protocol handler. We will be using the Java Secure Socket Extension (JSSE) for HTTPS. The JSSE documentation does a good job of describing what is necessary to use HTTPS, and the following steps were needed to configure the example client shown in Example 3.16, “A JNDI client that uses HTTPS as the transport”:

  • A protocol handler for HTTPS URLs must be made available to Java. The JSSE release includes an HTTPS handler in the com.sun.net.ssl.internal.www.protocol package. To enable the use of HTTPS URLs you include this package in the standard URL protocol handler search property, java.protocol.handler.pkgs. We set the java.protocol.handler.pkgs property in the Ant script.

  • The JSSE security provider must be installed in order for SSL to work. This can be done either by installing the JSSE jars as an extension package, or programatically. We use the programatic approach in the example since this is less intrusive. Line 18 of the ExClient code demonstrates how this is done.

  • The JNDI provider URL must use HTTPS as the protocol. Lines 24-25 of the ExClient code specify an HTTP/SSL connection to the localhost on port 8443. The hostname and port are defined by the web container SSL connector.

  • The validation of the HHTPS URL hostname against the server certificate must be disabled. By default, the JSSE HTTPS protocol handler employs a strict validation of the hostname portion of the HTTPS URL against the common name of the server certificate. This is the same check done by web browsers when you connect to secured web site. We are using a self-signed server certificate that uses a common name of "Chapter 8 SSL Example" rather than a particular hostname, and this is likely to be common in development environments or intranets. The JBoss HttpInvokerProxy will override the default hostname checking if a org.jboss.security.ignoreHttpsHost system property exists and has a value of true. We set the org.jboss.security.ignoreHttpsHost property to true in the Ant script.

Example 3.16. A JNDI client that uses HTTPS as the transport

package org.jboss.chap3.ex1;

import java.security.Security;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
                    
public class ExClient
{
    public static void main(String args[]) throws Exception
    {
        Properties env = new Properties();
        env.setProperty(Context.INITIAL_CONTEXT_FACTORY,
                        "org.jboss.naming.HttpNamingContextFactory");
        env.setProperty(Context.PROVIDER_URL,
                        "https://localhost:8443/invoker/JNDIFactorySSL");

        Context ctx = new InitialContext(env);
        System.out.println("Created InitialContext, env=" + env);

        Object data = ctx.lookup("jmx/invoker/RMIAdaptor");
        System.out.println("lookup(jmx/invoker/RMIAdaptor): " + data);
    }
}

To test the client, first build the chapter 3 example to create the chap3 configuration fileset.

[examples]$ ant -Dchap=chap3 config

Next, start the JBoss server using the chap3 configuration fileset:

[bin]$ sh run.sh -c chap3

And finally, run the ExClient using:

[examples]$ ant -Dchap=chap3 -Dex=1 run-example
...
run-example1:
     [java] Created InitialContext, env={java.naming.provider.url=https://localhost:8443/invoker/JNDIFactorySSL, java.naming.factory.initial=org.jboss.naming.HttpNamingContextFactory}
     [java] lookup(jmx/invoker/RMIAdaptor): org.jboss.invocation.jrmp.interfaces.JRMPInvokerProxy@cac3fa

3.2.4. Securing Access to JNDI over HTTP

One benefit to accessing JNDI over HTTP is that it is easy to secure access to the JNDI InitialContext factory as well as the naming operations using standard web declarative security. This is possible because the server side handling of the JNDI/HTTP transport is implemented with two servlets. These servlets are included in the http-invoker.sar/invoker.war directory found in the default and all configuration deploy directories as shown previously. To enable secured access to JNDI you need to edit the invoker.war/WEB-INF/web.xml descriptor and remove all unsecured servlet mappings. For example, the web.xml descriptor shown in Example 3.17, “ An example web.xml descriptor for secured access to the JNDI servlets” only allows access to the invoker.war servlets if the user has been authenticated and has a role of HttpInvoker.

Example 3.17.  An example web.xml descriptor for secured access to the JNDI servlets

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC
          "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
          "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
    <!-- ### Servlets -->
    <servlet>
        <servlet-name>JMXInvokerServlet</servlet-name>
        <servlet-class>
            org.jboss.invocation.http.servlet.InvokerServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>   <servlet>
        <servlet-name>JNDIFactory</servlet-name>
        <servlet-class>
            org.jboss.invocation.http.servlet.NamingFactoryServlet
        </servlet-class>
        <init-param>
            <param-name>namingProxyMBean</param-name>
            <param-value>jboss:service=invoker,type=http,target=Naming</param-value>
        </init-param>
        <init-param>
            <param-name>proxyAttribute</param-name>
            <param-value>Proxy</param-value>
        </init-param>
        <load-on-startup>2</load-on-startup>
    </servlet>  
    <!-- ### Servlet Mappings -->
    <servlet-mapping>
        <servlet-name>JNDIFactory</servlet-name>
        <url-pattern>/restricted/JNDIFactory/*</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>JMXInvokerServlet</servlet-name>
        <url-pattern>/restricted/JMXInvokerServlet/*</url-pattern>
    </servlet-mapping>   <security-constraint>
        <web-resource-collection>
            <web-resource-name>HttpInvokers</web-resource-name>
            <description>An example security config that only allows users with
                the role HttpInvoker to access the HTTP invoker servlets </description>
            <url-pattern>/restricted/*</url-pattern>
            <http-method>GET</http-method>
            <http-method>POST</http-method>
        </web-resource-collection>
        <auth-constraint>
            <role-name>HttpInvoker</role-name>
        </auth-constraint>
    </security-constraint>
    <login-config>
        <auth-method>BASIC</auth-method>
        <realm-name>JBoss HTTP Invoker</realm-name>
    </login-config>   <security-role>
        <role-name>HttpInvoker</role-name>
    </security-role>
</web-app>

The web.xml descriptor only defines which sevlets are secured, and which roles are allowed to access the secured servlets. You must additionally define the security domain that will handle the authentication and authorization for the war. This is done through the jboss-web.xml descriptor, and an example that uses the http-invoker security domain is given below.

<jboss-web>
    <security-domain>java:/jaas/http-invoker</security-domain>
</jboss-web>

The security-domain element defines the name of the security domain that will be used for the JAAS login module configuration used for authentication and authorization. See Section 8.1.6, “Enabling Declarative Security in JBoss” for additional details on the meaning and configuration of the security domain name.

3.2.5. Securing Access to JNDI with a Read-Only Unsecured Context

Another feature available for the JNDI/HTTP naming service is the ability to define a context that can be accessed by unauthenticated users in read-only mode. This can be important for services used by the authentication layer. For example, the SRPLoginModule needs to lookup the SRP server interface used to perform authentication. We'll now walk through how read-only JNDI works in JBoss.

First, the ReadOnlyJNDIFactory is declared in invoker.sar/WEB-INF/web.xml. It will be mapped to /invoker/ReadOnlyJNDIFactory.

<servlet>
    <servlet-name>ReadOnlyJNDIFactory</servlet-name>
    <description>A servlet that exposes the JBoss JNDI Naming service stub
          through http, but only for a single read-only context. The return content 
          is serialized MarshalledValue containg the org.jnp.interfaces.Naming 
          stub.
    </description>
    <servlet-class>org.jboss.invocation.http.servlet.NamingFactoryServlet</servlet-class>
    <init-param>
        <param-name>namingProxyMBean</param-name>
        <param-value>jboss:service=invoker,type=http,target=Naming,readonly=true</param-value>
    </init-param>
    <init-param>
        <param-name>proxyAttribute</param-name>
        <param-value>Proxy</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
</servlet>

<!-- ... -->
                        
<servlet-mapping>
    <servlet-name>ReadOnlyJNDIFactory</servlet-name>
    <url-pattern>/ReadOnlyJNDIFactory/*</url-pattern>
</servlet-mapping>

The factory only provides a JNDI stub which needs to be connected to an invoker. Here the invoker is jboss:service=invoker,type=http,target=Naming,readonly=true. This invoker is declared in the http-invoker.sar/META-INF/jboss-service.xml file.

   <mbean code="org.jboss.invocation.http.server.HttpProxyFactory"
      name="jboss:service=invoker,type=http,target=Naming,readonly=true">
      <attribute name="InvokerName">jboss:service=Naming</attribute>
      <attribute name="InvokerURLPrefix">http://</attribute>
      <attribute name="InvokerURLSuffix">:8080/invoker/readonly/JMXInvokerServlet</attribute>
      <attribute name="UseHostName">true</attribute>
      <attribute name="ExportedInterface">org.jnp.interfaces.Naming</attribute>
      <attribute name="JndiName"></attribute>
      <attribute name="ClientInterceptors">
          <interceptors>
             <interceptor>org.jboss.proxy.ClientMethodInterceptor</interceptor>
             <interceptor>org.jboss.proxy.SecurityInterceptor</interceptor>
             <interceptor>org.jboss.naming.interceptors.ExceptionInterceptor</interceptor>
             <interceptor>org.jboss.invocation.InvokerInterceptor</interceptor>
          </interceptors>
      </attribute>
   </mbean>

The proxy on the client side needs to talk back to a specific invoker servlet on the server side. The configuration here has the actual invocations going to /invoker/readonly/JMXInvokerServlet. This is actually the standard JMXInvokerServlet with a read-only filter attached.

    <filter>
        <filter-name>ReadOnlyAccessFilter</filter-name>
        <filter-class>org.jboss.invocation.http.servlet.ReadOnlyAccessFilter</filter-class>
        <init-param>
            <param-name>readOnlyContext</param-name>
            <param-value>readonly</param-value>
            <description>The top level JNDI context the filter will enforce
                read-only access on. If specified only Context.lookup operations
                will be allowed on this context. Another other operations or
                lookups on any other context will fail. Do not associate this
                filter with the JMXInvokerServlets if you want unrestricted
                access. </description>
        </init-param>
        <init-param>
            <param-name>invokerName</param-name>
            <param-value>jboss:service=Naming</param-value>
            <description>The JMX ObjectName of the naming service mbean </description>
        </init-param>
    </filter>
    
    <filter-mapping>
        <filter-name>ReadOnlyAccessFilter</filter-name>
        <url-pattern>/readonly/*</url-pattern>
    </filter-mapping>

    <!-- ... -->
    <!-- A mapping for the JMXInvokerServlet that only allows invocations 
            of lookups under a read-only context. This is enforced by the
            ReadOnlyAccessFilter 
            -->
    <servlet-mapping>
        <servlet-name>JMXInvokerServlet</servlet-name>
        <url-pattern>/readonly/JMXInvokerServlet/*</url-pattern>
    </servlet-mapping>

The readOnlyContext parameter is set to readonly which means that when you access JBoss through the ReadOnlyJNDIFactory, you will only be able access data in the readonly context. Here is a code fragment that illustrates the usage:

Properties env = new Properties();
env.setProperty(Context.INITIAL_CONTEXT_FACTORY, 
                "org.jboss.naming.HttpNamingContextFactory");
env.setProperty(Context.PROVIDER_URL, 
                "http://localhost:8080/invoker/ReadOnlyJNDIFactory");

Context ctx2 = new InitialContext(env);
Object data = ctx2.lookup("readonly/data");

Attempts to look up any objects outside of the readonly context will fail. Note that JBoss doesn't ship with any data in the readonly context, so the readonly context won't be bound usable unless you create it.

3.2.6. Additional Naming MBeans

In addition to the NamingService MBean that configures an embedded JBossNS server within JBoss, there are three additional MBean services related to naming that ship with JBoss. They are the ExternalContext, NamingAlias, and JNDIView.

3.2.6.1. org.jboss.naming.ExternalContext MBean

The ExternalContext MBean allows you to federate external JNDI contexts into the JBoss server JNDI namespace. The term external refers to any naming service external to the JBossNS naming service running inside of the JBoss server VM. You can incorporate LDAP servers, file systems, DNS servers, and so on, even if the JNDI provider root context is not serializable. The federation can be made available to remote clients if the naming service supports remote access.

To incorporate an external JNDI naming service, you have to add a configuration of the ExternalContext MBean service to the jboss-service.xml configuration file. The configurable attributes of the ExternalContext service are as follows:

  • JndiName: The JNDI name under which the external context is to be bound.

  • RemoteAccess: A boolean flag indicating if the external InitialContext should be bound using a Serializable form that allows a remote client to create the external InitialContext . When a remote client looks up the external context via the JBoss JNDI InitialContext, they effectively create an instance of the external InitialContext using the same env properties passed to the ExternalContext MBean. This will only work if the client can do a new InitialContext(env) remotely. This requires that the Context.PROVIDER_URL value of env is resolvable in the remote VM that is accessing the context. This should work for the LDAP example. For the file system example this most likely won't work unless the file system path refers to a common network path. If this property is not given it defaults to false.

  • CacheContext: The cacheContext flag. When set to true, the external Context is only created when the MBean is started and then stored as an in memory object until the MBean is stopped. If cacheContext is set to false, the external Context is created on each lookup using the MBean properties and InitialContext class. When the uncached Context is looked up by a client, the client should invoke close() on the Context to prevent resource leaks.

  • InitialContext: The fully qualified class name of the InitialContext implementation to use. Must be one of: javax.naming.InitialContext, javax.naming.directory.InitialDirContext or javax.naming.ldap.InitialLdapContext. In the case of the InitialLdapContext a null Controls array is used. The default is javax.naming.InitialContex.

  • Properties: The Properties attribute is contains the JNDI properties for the external InitialContext. The input should be the text equivalent to what would go into a jndi.properties file.

  • PropertiesURL: This set the jndi.properties information for the external InitialContext from an extern properties file. This is either a URL, string or a classpath resource name. Examples are as follows:

    • file:///config/myldap.properties

    • http://config.mycompany.com/myldap.properties

    • /conf/myldap.properties

    • myldap.properties

The MBean definition below shows a binding to an external LDAP context into the JBoss JNDI namespace under the name external/ldap/jboss.

<!-- Bind a remote LDAP server -->
<mbean code="org.jboss.naming.ExternalContext" 
       name="jboss.jndi:service=ExternalContext,jndiName=external/ldap/jboss">
    <attribute name="JndiName">external/ldap/jboss</attribute>
    <attribute name="Properties">
        java.naming.factory.initial=com.sun.jndi.ldap.LdapCtxFactory
        java.naming.provider.url=ldap://ldaphost.jboss.org:389/o=jboss.org
        java.naming.security.principal=cn=Directory Manager
        java.naming.security.authentication=simple
        java.naming.security.credentials=secret
    </attribute>
    <attribute name="InitialContext"> javax.naming.ldap.InitialLdapContext </attribute>
    <attribute name="RemoteAccess">true</attribute>
</mbean>

With this configuration, you can access the external LDAP context located at ldap://ldaphost.jboss.org:389/o=jboss.org from within the JBoss VM using the following code fragment:

InitialContext iniCtx = new InitialContext();
LdapContext ldapCtx = iniCtx.lookup("external/ldap/jboss");

Using the same code fragment outside of the JBoss server VM will work in this case because the RemoteAccess property was set to true. If it were set to false, it would not work because the remote client would receive a Reference object with an ObjectFactory that would not be able to recreate the external IntialContext

<!-- Bind the /usr/local file system directory  -->
<mbean code="org.jboss.naming.ExternalContext" 
       name="jboss.jndi:service=ExternalContext,jndiName=external/fs/usr/local">
    <attribute name="JndiName">external/fs/usr/local</attribute>
    <attribute name="Properties">
        java.naming.factory.initial=com.sun.jndi.fscontext.RefFSContextFactory
        java.naming.provider.url=file:///usr/local
    </attribute>
    <attribute name="InitialContext">javax.naming.IntialContext</attribute>
</mbean>

This configuration describes binding a local file system directory /usr/local into the JBoss JNDI namespace under the name external/fs/usr/local.

With this configuration, you can access the external file system context located at file:///usr/local from within the JBoss VM using the following code fragment:

InitialContext iniCtx = new InitialContext();
                Context ldapCtx = iniCtx.lookup("external/fs/usr/local");

Note that the use the Sun JNDI service providers, which must be downloaded from http://java.sun.com/products/jndi/serviceproviders.html. The provider JARs should be placed in the server configuration lib directory.

3.2.6.2. The org.jboss.naming.NamingAlias MBean

The NamingAlias MBean is a simple utility service that allows you to create an alias in the form of a JNDI javax.naming.LinkRef from one JNDI name to another. This is similar to a symbolic link in the UNIX file system. To an alias you add a configuration of the NamingAlias MBean to the jboss-service.xml configuration file. The configurable attributes of the NamingAlias service are as follows:

  • FromName: The location where the LinkRef is bound under JNDI.

  • ToName: The to name of the alias. This is the target name to which the LinkRef refers. The name is a URL, or a name to be resolved relative to the InitialContext, or if the first character of the name is a dot (.), the name is relative to the context in which the link is bound.

The following example provides a mapping of the JNDI name QueueConnectionFactory to the name ConnectionFactory.

<mbean code="org.jboss.naming.NamingAlias" 
       name="jboss.mq:service=NamingAlias,fromName=QueueConnectionFactory">
    <attribute name="ToName">ConnectionFactory</attribute>
    <attribute name="FromName">QueueConnectionFactory</attribute>
</mbean>

3.2.6.3. The org.jboss.naming.JNDIView MBean

The JNDIView MBean allows the user to view the JNDI namespace tree as it exists in the JBoss server using the JMX agent view interface. To view the JBoss JNDI namespace using the JNDIView MBean, you connect to the JMX Agent View using the http interface. The default settings put this at http://localhost:8080/jmx-console/. On this page you will see a section that lists the registered MBeans sortyed by domain. It should look something like that shown in Figure 3.4, “The JMX Console view of the configured JBoss MBeans”.

The JMX Console view of the configured JBoss MBeans

Figure 3.4. The JMX Console view of the configured JBoss MBeans

Selecting the JNDIView link takes you to the JNDIView MBean view, which will have a list of the JNDIView MBean operations. This view should look similar to that shown in Figure 3.5, “The JMX Console view of the JNDIView MBean”.

The JMX Console view of the JNDIView MBean

Figure 3.5. The JMX Console view of the JNDIView MBean

The list operation dumps out the JBoss server JNDI namespace as an HTML page using a simple text view. As an example, invoking the list operation produces the view shown in Figure 3.6, “The JMX Console view of the JNDIView list operation output”.

The JMX Console view of the JNDIView list operation output

Figure 3.6. The JMX Console view of the JNDIView list operation output