Tuesday, March 15, 2011

Using JDOM to read a web.xml file

Now let's see JDOM in action by looking at how you could use it to parse a web.xml file, the Web application deployment descriptor from Servlet API 2.2. Let's assume that you want to look at the Web application to see which servlets have been registered, how many init parameters each servlet has, what security roles are defined, and whether or not the Web application is marked as distributed.
Here's a sample web.xml file:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
    "http://java.sun.com/j2ee/dtds/web-app_2.2.dtd">
<web-app>
    <servlet>
        <servlet-name>snoop</servlet-name>
        <servlet-class>SnoopServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>file</servlet-name>
        <servlet-class>ViewFile</servlet-class>
        <init-param>
            <param-name>initial</param-name>
            <param-value>1000</param-value>
            <description>
                The initial value for the counter  <!-- optional -->
            </description>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>mv</servlet-name>
        <url-pattern>*.wm</url-pattern>
    </servlet-mapping>
    <distributed/>
    <security-role>
      <role-name>manager</role-name>
      <role-name>director</role-name>
      <role-name>president</role-name>
    </security-role>
</web-app>


On processing that file, you'd want to get output that looks like this:
This WAR has 2 registered servlets:
        snoop for SnoopServlet (it has 0 init params)
        file for ViewFile (it has 1 init params)
This WAR contains 3 roles:
        manager
        director
        president
This WAR is distributed


With JDOM, achieving that output is easy. The following example reads the WAR file, builds a JDOM document representation in memory, then extracts the pertinent information from it:
import java.io.*;
import java.util.*;
import org.jdom.*;
import org.jdom.input.*;
import org.jdom.output.*;
public class WarReader {
  public static void main(String[] args) {
    PrintStream out = System.out;
    if (args.length != 1 && args.length != 2) {
      out.println("Usage: WarReader [web.xml]");
      return;
    }
    try {
      // Request document building without validation
      SAXBuilder builder = new SAXBuilder(false);
      Document doc = builder.build(new File(args[0]));
      // Get the root element
      Element root = doc.getRootElement();
      // Print servlet information
      List servlets = root.getChildren("servlet");
      out.println("This WAR has "+ servlets.size() +" registered servlets:");
      Iterator i = servlets.iterator();
      while (i.hasNext()) {
        Element servlet = (Element) i.next();
        out.print("\t" + servlet.getChild("servlet-name")
                                .getText() +
                  " for " + servlet.getChild("servlet-class")
                                .getText());
        List initParams = servlet.getChildren("init-param");
        out.println(" (it has " + initParams.size() + " init params)");
      }
      // Print security role information
      List securityRoles = root.getChildren("security-role");
      if (securityRoles.size() == 0) {
        out.println("This WAR contains no roles");
      }
      else {
        Element securityRole = (Element) securityRoles.get(0);
        List roleNames = securityRole.getChildren("role-name");
        out.println("This WAR contains " + roleNames.size() + " roles:");
        i = roleNames.iterator();
        while (i.hasNext()) {
          Element e = (Element) i.next();
          out.println("\t" + e.getText());
        }
      }
      // Print distributed information (notice this is out of order)
      List distrib = root.getChildren("distributed");
      if (distrib.size() == 0) {
        out.println("This WAR is not distributed");
      } else {
        out.println("This WAR is distributed");
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

No comments:

Post a Comment

Chitika