Using URL resources to manage J2EE property files in IBM WebSphere Application Server V5

This article discusses the technique of using a J2EE-compliant way of making a user-editable properties file available to a J2EE application, and also outlines the IBM WebSphere-centric implementation tasks from a component developer and deployer perspective.

Keys Botzum, Senior Technical Staff Member , IBM

Keys Botzum is a Senior Technical Staff Member with IBM Software Services for WebSphere. Mr. Botzum has over 10 years of experience in large scale distributed system design and additionally specializes in security. Mr. Botzum has worked with a variety of distributed technologies, including Sun RPC, DCE, CORBA, AFS, and DFS. Recently, he has been focusing on J2EE and related technologies. He holds a Masters degree in Computer Science from Stanford University and a B.S. in Applied Mathematics/Computer Science from Carnegie Mellon University. Mr. Botzum has published numerous papers on WebSphere and WebSphere security. Additional articles and presentations by Keys Botzum can be found at http://www.keysbotzum.com, as well as on IBM developerWorks WebSphere. He is also co-author of IBM WebSphere: Deployment and Advanced Configuration.


developerWorks Professional author
        level

Benedict Fernandes (bxf@us.ibm.com), Senior Managing Consultant, IBM Software Services for WebSphere, IBM

Benedict Fernandes is a Senior Managing Consultant with IBM Software Services for WebSphere in Research Triangle Park, NC. He holds an MS in Information Networking from Carnegie Mellon University, an MS in Computer Science from De La Salle University, and an MSc (Tech) from BITS-Pilani, India. You can contact Benedict at bxf@us.ibm.com.



16 February 2005

Introduction

One of the challenges when writing J2EE-compliant applications is the management of configuration properties. All non-trivial applications should externalize various configuration parameters from application code. This includes such things as host names, userids, file names, logging settings, and so on. J2EE does provide for some externalization of many of the J2EE-specific constructs (DataSource definitions, EJB endpoints, and others) via the idea of references, but this is not sufficient. Most applications also have non-J2EE configuration information.

Configuration information is also likely to be edited by administrators as part of -- or even after -- application deployment. Thus, configuration choices that can only be made prior to creating the application EAR file are not really acceptable. What is needed is a simple, end-administrator-editable, J2EE-compliant way of managing configuration information. Of course, applications can build and design their own configuration management infrastructure (perhaps via JMX), but that approach would be quite complicated and expensive.

The obvious and simplest way to manage configuration properties might be with the well-defined Java™ Properties class, which, in turn, uses a properties file. The nice thing about using this file is that no elaborate tools are required; it can be edited using almost any reasonable text editor. However, the problem with this file-based approach is twofold:

  • J2EE explicitly forbids portable applications from reading files using the java.io package.
  • There is the more subtle problem of where to place this file so it can be read by the application code at run time.

Historically in WebSphere Application Server, developers have generally placed properties files on the classpath of the application code within the EAR. This has worked well enough in the past, but this approach is too brittle with the administrative infrastructure of WebSphere Application Server V5. This is because the EAR is not expanded by WebSphere Application Server V5 within the deployment manager. Thus, if you wish to edit the custom properties file within the EAR, you need to explode the EAR, edit the properties file, recreate the EAR, and then redeploy the application. Clearly, this process is cumbersome and error prone.

Instead, what we need is a properties file that is external to the application EAR (yes, this does mean that one more artifact must be deployed by hand). There is a catch, though, in that J2EE forbids directly accessing files. J2EE application components are encouraged to access external resources using a resource manager connection factory (an object that is used to create connections to a resource manager), as specified in the J2EE 1.3 Resource Manager APIs. As such, J2EE 1.3-compliant application servers support five types of resource managers:

  • Database resources
  • JavaMail sessions
  • JMS connections
  • Enterprise resources (via JCA)
  • URL resources.

Fortunately, we can leverage the flexibility of WebSphere Application Server V5 support for URL resources to create a J2EE-compliant URL resource that points to a user-editable properties file; essentially, a win-win situation.

In this article, the development and deployment tasks for this approach are discussed in the context of a WebSphere-based environment, where WebSphere Studio is used for development and WebSphere Application Server is the deployment platform. This approach is described in these sections:


Basic steps of the application model

A J2EE application can access a URL resource through an application server-specific administrative object called a URL resource object. Figure 1 depicts the typical steps required to implement this functionality.

Figure 1. URL Resources -- Application model
Figure 1. URL Resources -- Application model

A URL resource object is technically referred to as a URL resource manager connection factory in the J2EE 1.3 specification. A J2EE application can obtain an object reference to a URL resource manager connection factory by performing a JNDI lookup (Step 1 in Figure 1). The application then uses this reference to create a URLConnection object that represents a connection to the specific URL resource (Step 2). The underlying communication support between the URL resource objects and the specific URL resource is enabled via a mechanism called the URL provider (Step 3). The URL provider provides the necessary implementation level support for the requested protocols, such as HTTP, file, FTP, and so on (Step 4). The PropertyManager class, described next, is based on this model.


The PropertyManager class

The PropertyManager class is a reusable, singleton Java class that populates a local static Properties object from an administratively configured URL provider. This class is instantiated as part of the application startup and initialization, and therefore ensures that the Properties object will be available before application components start executing name or property lookups.

To facilitate easy debugging, the PropertyManager class has been instrumented with the IBM JRas toolkit. JRas is a set of Java APIs that enables developers to incorporate message logging and trace facilities into Java applications. IBM JRas has the added value of being integrated with the the WebSphere Application Server tracing facility. (See Resources section for more information on JRas.) The UML representation of the PropertyManager class is shown in Figure 2.

Figure 2. PropertyManager UML class diagram
Figure 2. PropertyManager UML class diagram

The workings of the PropertyManager class are described below, but we recommend you browse through the PropertyManager class code, included in the download file, before continuing.

As part of the PropertyManager object instantiation process, the private constructor invokes three other private helper methods in the following sequence:

  1. InitWASTracingAndLogging()
    Initializes WebSphere JRas tracing and logging components.
  2. initFromJNDI()
    The code below represents the core functionality of the initFromJND() method:

    InitialContext initCtx = new InitialContext();
    	. . .
    URL url = (java.net.URL) initCtx.lookup(jndi);
    URLConnection conn = url.openConnection();
    InputStream is = conn.getInputStream();

    This code obtains an initial JNDI naming context and uses this context to lookup the URL resource manager connection factory reference. The local JNDI reference java:comp/env/url/PropertyURL is the default name used to perform the lookup, unless overridden using PropertyManager.jndiName.

    The above code also assumes the component obtaining the InitialContext is running within a Web or EJB container. For the code to work from a J2EE application client container, the necessary JNDI naming properties would have to be passed to the InitialContext object.

    The return type of the naming lookup is cast to a java.net.URL type. The openConnection() method of the URL connection factory reference returned is then invoked to return a URLConnection object. The URLConnection object, "conn", represents a connection to the remote object referred to by the URL. The getInputStream() method of the URLConnection class is then called to extract and return the InputStream associated with the given remote object.
  3. hydratePropertiesObject()
    The InputStream object returned in the previous method is used as the input source stream to populate the Properties object. The hydrated Properties object is then cached as a static private attribute and available for subsequent access by any application component.

Here are brief descriptions of these public methods, which are inherently self-describing:

  • listProperty() -- enumerates through all the name/values pairs in the Properties object.
  • getProperty() -- returns the value of a named property.
  • setProperty() -- sets the value of a named property; these changes are not written back to the properties file.
  • isInitialized() -- returns a Boolean value depending on whether the local Properties object has been successfully initialized or not.
  • getInstance() -- public static factory method that returns the object reference to the sole instance of the class within a given classloader scope (typically an EAR).

J2EE application component provider tasks

Before using the sample application:

  1. Import the URLTestEAR.ear file, included in the download file, into WebSphere Studio. This file contains the code for the PropertyManager and URLTestServlet classes.
  2. Since the EAR file references JRas packages, make sure that ras.jar is present on the project build path; ras.jar can be obtained from the C:\WebSphere\AppServer\lib directory or the <StudioInstallDir>\runtimes\base_v51\lib directory.
  3. For this sample to function as configured in this article, place the studioURLTest.properties and was-URLTest.properties files on the root of the C: drive. (Naturally, in a production environment, you would use different locations.)

Now, to use the PropertyManager class, you must:

  1. Configure the URL resource factory object in WebSphere Studio.
  2. Setup the URL resource reference in the relevant deployment descriptor

as described next.

A. Configure the URL resource factory object in WebSphere Studio

To test the URL resource manager, it is necessary to administratively define a URL resource to the local WebSphere Application Server test environment in WebSphere Studio.

WebSphere Application Server comes pre-configured with a URL provider called Default URL provider (Figure 3). Support for the Default URL provider is built into the base JDK. The Default URL provider handles the standard J2SE 1.3.1 protocols such as HTTP, File, and FTP, and enables the communication between the application and a configured URL resource.

Figure 3. WebSphere Application Server Pre-configured Default URL Provider
Figure 3. WebSphere Application Server Pre-configured Default URL Provider

A property file can be made accessible to J2EE application components in a standards-compliant way by configuring it as a URL resource in the application server and making a reference to it available for lookup in the JNDI namespace. J2EE applications perform a JNDI lookup of the URL resource manager connection factory. A factory adhering to the java.net.URL interface is returned; this reference is then used to create a connection to the specified resource. The application can thereafter use the established connection to populate a Properties object that the applications can use to query any environment-specific properties.

To configure a URL resource that points to a file:

  1. From the admin console, navigate to Resources => URL Providers => Default URL Provider => URLs => < new >.
  2. For the name of the URL resource object, enter studioPropertyURL (Figure 4).
  3. For the JNDI name of the URL resource object, as registered in the application servers local name space, enter url/studioPropertyURL. (This includes the JNDI naming subcontext of URL in this case.)
  4. The specification field should contain a string from which a valid URL can be constructed. In our case, since the URL will point to a file, we specify a file URL.
Figure 4. URL Resource configuration in WebSphere Studio V5.1
Figure 4. URL Resource configuration in WebSphere Studio V5.1

B. Setup the URL resource reference in the relevant deployment descriptor

The J2EE application component provider needs to define the URL resource references for the URL resource in the deployment descriptor.

To define a URL resource manager:

  1. In WebSphere Studio, open the Web deployment descriptor file web.xml by double-clicking on it.
  2. Select the References tab, then the Resource tab, and define these fields (Figure 5):
    • URL Resource Reference name
    • Java Type
    • Authentication style
    • Sharing mode
    • A relevant description (optional).
Figure 5. WebSphere Studio URL Resource Reference Binding
Figure 5. WebSphere Studio URL Resource Reference Binding

As the J2EE 1.3 specification recommends, we have placed URLs under the URL sub-context within JNDI. The above configuration results in the addition of the <resource-ref> element in the deployment descriptor (Figure 6).

Figure 6. Resource Reference in web.xml
Figure 6. Resource Reference in web.xml

The component provider declares a lookup of the URL resource factory using the <resource-ref> element in the referencing components deployment descriptor.

The <res-ref-name> element of the deployment descriptor is the logical name -- relative to java:comp/env -- used within the application component code to refer to this resource manager connection factory reference. Hence, the application component will perform a JNDI lookup of the URL resource manager connection factory reference (java:comp/env/url/PropertyURL), as depicted in the PropertyManager.java class definition. The <res-type> element of the deployment descriptor is the Java programming language type of the resource manager connection factory reference.

Figure 5 essentially summarizes Figures 3 and 4.

Figure 7. The bindings file, ibm-web-bnd.xmi
Figure 7. The bindings file, ibm-web-bnd.xmi

The bindings file represents the binding between the resource reference ID above and the locally-defined URL resource object referenced via the url/studioPropertyURL global JNDI name defined in Figure 7.


J2EE application deployer tasks

The following two tasks are performed by the J2EE application deployer to enable the use of the PropertyManager class:

  1. Configure the URL resource factory object
  2. Bind resource manager connection factory reference to local URL resource object.

C. Configure the URL resource factory object

To configure a URL resource factory object:

  1. From the admin console, select Resources => URL Providers => Default URL Provider => URLs from the Additional Properties table, then New.
  2. Configure the PropertyURL as shown in Figure 8.
    Figure 8. WebSphere URL resource configuration
    Figure 8. WebSphere URL resource configuration
    The values specified in the URL resource configuration in Figure 8 correspond to the WebSphere Application Server deployment environment. The values specify the WebSphere Application Server administrative name, the JNDI name of this URL resource object, and the environment-specific properties file that can be accessed over a supported protocol, such as the file protocol in this example.

D. Bind resource manager connection factory reference to local URL resource object

As mentioned in the previous section, the bean provider declares all the resource manager connection factory references in the deployment descriptor using the <resource-ref> elements. When installing an application that contains modules with URL resource references, the deployer must bind the URL resource manager connection factory references to the actual JNDI name of the resource factories that are configured in the target WebSphere Application Server environment. This binding is typically performed during the enterprise application deployment process, shown in Figure 9.

Figure 9. Binding a resource reference to a local resource
Figure 9. Binding a resource reference to a local resource

The url/PropertyURL resource reference referred to in the application is bound to the local URL resource object url/wasPropertyURL (Figure 8) during the application deployment process.


Testing the sample

The sample EAR file supplied should be installed as an enterprise application into WebSphere Application Server. Figure 10 depicts the URLTest application running as a WebSphere Application Server application. In this case, the URLTest.ear file was deployed to one-member WebSphere Application Server cluster.

Figure 10. URLTest Enterprise Application
Figure 10. URLTest Enterprise Application

After the EAR file is deployed to WebSphere Application Server and the application is started, the servlet bundled with the sample can be executed either with http://localhost:9081/URLWeb/URLTestServlet, or with an equivalent URL, depending on the host and port used. The SUCCESS output displayed in the browser output indicates that the values from the PropertyManager object were successfully retrieved (Figure 11).

Figure 11. URLTest Application sample execution
Figure 11. URLTest Application sample execution

The PropertyManager class is JRas enabled. Hence, additional trace can be obtained by setting the appropriate trace settings in WebSphere Application Server. Figure 12 shows the appropriate values relevant to the sample provided.

Figure 12. Sample trace settings
Figure 12. Sample Trace Settings

The trace log generated from the above settings (Figure 13) is in the trace.out file that resides in the same directory as other WebSphere Application Server logs for a given server.

Figure 13. Sample trace output
Figure 13. Sample trace output

As we indicated, the output shown is actually generated using JRAS calls. The second set of highlighted output lines in Figure 13 are generated using this code fragment in the listProperty method.

java.util.Enumeration keys = properties.propertyNames();
while (keys.hasMoreElements()) {
	key = (String) keys.nextElement();
	listPropertyMsg = key + " = " + properties.getProperty(key);
	msgLogger.textMessage(
		RASIMessageEvent.TYPE_INFO,
		this,
		"listProperty",
		listPropertyMsg);
}

Please refer to the complete sample code in the download file to understand this in context. Keep in mind that this sample uses a message logger that actually sends the properties loaded to the WebSphere Application Server serious event stream (which goes to the server output file as well as the administrative console). If there are a large number of properties, then this might not be a good idea, but it's nice for a demo. Notice that the listProperty() method must be explicitly called by the user of the PropertyManager. If your application has debugging hook points, this might be something you would want to call during those sessions. The other trace output shown in Figure 13 is generated using trace statements, as opposed to message statements. Tracing statements are low cost and dynamically configurable, unlike messages.


Typical deployment scenarios

After the EAR file is deployed to WebSphere Application Server, the property file should be copied to the desired file system location and edited to reflect the local environment-specific settings. The enterprise application can then be started.

If the application is deployed in a WebSphere Application Server Network Deployment (ND) topology, the properties file would have to be copied over to every node where the enterprise application is deployed. This task of property file propagation can be made simpler by placing the file on the WebSphere Application Server deployment manager under the <WebSphere Application Server_HOME>/config/cells/<CELL_NAME> directory. By doing this, the WebSphere Application Server ND replication infrastructure can manage the replication of the properties file from system to system. However, since this file is not a WebSphere Application Server administrative artifact -- it is not known to the WebSphere Application Server infrastructure -- this won't happen automatically when the file is changed. Instead, the replication will have to be forced by executing a Node synchronization from the WebSphere Application Server admin console or through wsadmin scripts. Either action will result in the file being propagated to the same file system location on all the nodes in the cell. You can then simply configure the property file location in the WebSphere Application Server admin console to point to that location.


Conclusion

This article discussed the technique of using a J2EE-compliant way of making a user-editable properties file available to a J2EE application, and also outlined the WebSphere-centric implementation tasks from a component developer and deployer perspective.


Acknowledgements

The authors would like to thank Peter Van Sickel of IBM for his contributions to this article.


Download

DescriptionNameSize
Code sampleURLProvider.zip12 KB

Resources

Learn

Discuss

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into WebSphere on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=WebSphere
ArticleID=352520
ArticleTitle=Using URL resources to manage J2EE property files in IBM WebSphere Application Server V5
publish-date=02162005