Skip navigation.

Using XMLBeans to Implement Dynamic Configuration Files

by Brodi Beartusk
04/02/2004

XMLBeans is a powerful tool that can be leveraged to simplify many development tasks that involve XML documents. One common task in developing a Web application is that of putting together a means of configuring the Web application's custom components. This article covers an approach to this task by using XMLBeans to easily consume from XML-formatted configuration files, coupled with some utility code that makes the process of adding new configuration files and consuming from them in iterative development mode easy.

Topics covered include:
  • A short introduction to XMLBeans
  • Developing a schema to support a custom configuration file
  • Generating XMLBeans classes from a schema file
  • A set of utility classes that aid in dynamic config file development and access
  • An example config file and usage

This article assumes that the reader is familiar with basic Web application concepts and some knowledge of the ant build system.

Overview of XMLBeans

XMLBeans is a framework that enables full, easy access to XML documents from the Java language. It is currently included in the Apache XML effort as an incubating project. Full details can be found on the Apache site at http://xml.apache.org/xmlbeans/.

For the purpose of this article, here is a brief overview of using XMLBeans to access an XML document from Java:
  1. Develop a schema that describes your document.
  2. Construct an XMLBeans configuration that will be consumed by the XMLBeans code generator.
  3. Build the XMLBeans Java classes that map to your schema.
  4. Instantiate an XMLBeans document from an XML file and use it to populate a config class.
  5. Use the config class to access information parsed from the XML document.

Example - Dynamic Configuration Files

As an example, this article will cover the construction of "dynamic configuration files". Dynamic in this case means that any changes made to the configuration file will be automatically picked up on the next access to a configuration class mapped to that file following a change to the file. This functionality will only be enabled if iterative development mode and is intended to aid developers in Web application development where it is useful to change configuration information without the need for redeploying the application.

Consider a configuration file that can be used to configure the style sheet that is applied to JSPs in a Web application. This configuration file is an XML document that contains a list of JSP to CSS file mappings. JSPs in the Web application can access this configuration information via a scriptlet that sets the CSS HTML link in the JSP output. A developer may then control the style sheet used by any JSP in the Web application by updating the configuration file, saving it, then reloading the JSP.

Step 1: Configuration file schema

Below is a schema listing that defines an XML document structure for our style mapping configuration file. It describes an XML document whose root level element is "styles", which then contains child "style" elements which have two attributes each, "jsp" and "css", to define a mapping between a JSP and a style sheet.

Here is an example styles-config.xml document:


<?xml version="1.0" encoding="UTF-8"?>
<styles    
                xmlns="http://www.bea.com/dev2dev/example/styles-config"    
                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    
                xsi:schemaLocation="http://www.bea.com/dev2dev/example/styles-config styles-config.xsd">
                
                <!-- First Style Mappings -->
                <style jsp="example1.jsp" css="a.css"/>    
                
                <!-- Second Style Mapping -->    
                <style jsp="example2.jsp" css="b.css"/>
</styles>




And here is the schema file for the document, styles-config.xsd:


<xs:schema targetNamespace="http://www.bea.com/dev2dev/example/styles-config" 
xmlns:xs="http://www.w3.org/2001/XMLSchema" 
xmlns="http://www.bea.com/dev2dev/example/styles-config" elementFormDefault="qualified">    
        <!-- All Jsp to Style Mappings -->    
        <xs:element name="styles">        
                <xs:annotation>            
                        <xs:documentation>Zero or more style elements that map jsps to css files.</xs:documentation>        
                </xs:annotation>        
                <xs:complexType>            
                        <xs:sequence>                
                                <xs:element ref="style" minOccurs="0" maxOccurs="unbounded"/>            
                        </xs:sequence>        
                </xs:complexType>   
        </xs:element>    
        
        <!-- A single Jsp to Style Mapping -->    
        <xs:element name="style">        
                <xs:annotation>            
                        <xs:documentation>Defines a single mapping between a jsp and a css file.</xs:documentation>        
                </xs:annotation>        
                <xs:complexType>            
                        <xs:attribute name="jsp" type="xs:string" use="required"/>            
                        <xs:attribute name="css" type="xs:string" use="required"/>        
                </xs:complexType>    
        </xs:element>
</xs:schema>




Step 2: XMLBeans configuration file

XMLBeans depends on a schema configuration file that is used to configure the schema of the target document and the package to which to generate the Java XMLBeans document classes. Here is the styles-config.xsdconfig file for our example:


<xb:config xmlns:xb="http://www.bea.com/2002/09/xbean/config">    
        <xb:namespace uri="http://www.bea.com/dev2dev/example/styles-config">        
                <xb:package>com.bea.dev2dev.jsp2style</xb:package>    
        </xb:namespace>
</xb:config>




Step 3: Build the XMLBeans

In this example, the schema and XMLBeans configuration files are assumed to be in the WEB-INF/src/schema directory of the example Web application.

A build file is included with this sample, demonstrating how the XMLBeans source is used to generate document classes for the styles-config.xml document, which are in turn used in a StylesConfig class that is built in a separate compile target.

The build process is composed of two main stages: an XMLBeans build followed by a normal source build. Since XMLBeans generates document classes based on a schema, these document classes must be built prior to compiling any classes that rely on them.

Step 4: Instantiate an XMLBeans document from an XML file

To access the styles configuration information from within a JSP, a class named StyleConfig is used to manage the dynamic loading of the XMLBeans document and to provide an method that can be used to look up a CSS filename based on a JSP file name. StyleConfig is implemented as a singleton, and extends a DynamicConfig class that templates the dynamic loading behavior needed for automatically picking up changes to the styles-config.xml file. The source for both of these classes can be found in the xmlBeansConfig Web application in WEB-INF/src/com/bea/dev2dev/xmlBeansConfig.

Here is the loadConfig method of StyleConfig, which loads the generated XMLBeans documents from an input stream:


protected void loadConfig(InputStream is) throws XmlException, IOException    
        {        
                // initialize members        
                stylesMap = new HashMap();        
                
                StylesDocument.Styles styles = StylesDocument.Factory.parse(is).getStyles();        
                
                // populate stylesMap        
                StyleDocument.Style styleArray[] = styles.getStyleArray();        
                for (int i = 0; i < styleArray.length; i++)        
                {            
                
                        String jsp = styleArray[i].getJsp();            
                        String css = styleArray[i].getCss();            
                        
                        stylesMap.put(jsp, css);        
                }    
        }




Step 5: Use the config class to access information parsed from the XML document

Once the config class has loaded its information from the XML document using the XMLBeans generated classes, consumers of the configuration information can use it to control any desired configurable behavior.

For this example, the styles-config.xml file is meant to allow configurable association of style sheets with JSPs. Here is the JSP source for example1.jsp in the xmlBeansConfig sample Web application:


<%@page import="com.bea.dev2dev.xmlBeansConfig.StyleConfig"%>

<html>
<%    
        // determine the stylesheet to be used for this jsp    
        String css = StyleConfig.getInstance(request).getCssForJsp("example1.jsp");    
        
        if (!css.equals(""))    
        {
%>    
        <link REL=StyleSheet HREF="<%=css%>" TYPE="text/css" MEDIA=screen>
<%    
        }
%>    
        <head>        
                <title>XMLBeans Config Example 1</title>    
        </head>    
        
        <body>        
                <h1>XMLBeans Config Example 1</h1>        
                This jsp uses an XMLBeans based configuration file to select it's associated css file.        
                <table>            
                        <tr><td>JSP File Name:</td><td>CSS File Name:</td></tr>            
                        <tr><td>example1.jsp</td><td><%=css%></td></tr>        
                </table>    
        </body>
</html>




This JSP uses StyleConfig to determine whether or not there is a configured CSS file for this JSP. If there is a configured CSS file, a link tag is emitted by a scriptlet that specifies the configured CSS. When the styles-config.xml file changes on the file system, the changes are automatically picked up by StyleConfig, and the currently configured CSS mapping is always available to the JSP.

Conclusion

This article has shown how to use XMLBeans to easily implement a dynamic configuration file that allows updates to an XML file to be available to consumers of the configuration information immediately after the XML file is changes. The example leverages the power of XMLBeans to make the process of parsing the configuration XML file data extremely simple from a development standpoint.

Also shown here are some best practices for using XMLBeans within a Web application, including location of schema and XMLBeans generation config files, generation output directories and a build that properly sequences the XMLBeans generation and compilation before the building of any source that relies on the generated XMLBeans document classes.

Article Tools

Email E-mail
Print Print
Blog Blog

Bookmark Article

del.icio.us del.icio.us
Digg Digg
Furl Furl
Reddit Reddit
Rojo Rojo