O'Reilly logo

Jakarta Commons Cookbook by Timothy M. O'Brien

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

6.4. Creating a Simple XML Command Language

Problem

You would like to capture commands in an XML document, and create a framework to execute these commands.

Solution

Write a custom implementation of Rule, and create a rule set that instructs Commons Digester to invoke these rules when specific elements are parsed. Consider the example of a system that sends an encrypted email. The following XML document contains instructions for the primitive encryption of an email:

<?xml version="1.0"?>

<operations xmlns="http://discursive.com/textmanip">
  <email to="tobrien@discursive.com"
         from="root@discursive.com">
    <replace search="o" replace="q"/>
    <replace search="d" replace="z"/>
    <lower/>
    <reverse/>
  </email>
</operations>

The email tag surrounds three elements—replace, lower, and reverse. The system that executes these commands receives a message as a String and runs this String through three stages before sending an email to tobrien@discursive.com. When the parser encounters the replace element, it replaces all occurrences of the contents of the search attribute with the contents of the replace attribute. When the parser encounters a lower element, it translates all characters to lowercase; and when the parser encounters a reverse element, it reverses the String. When the parser encounters the end of the email element, the result of these four operations is sent to the recipient specified in the to attribute of the email element.

import org.apache.commons.digester.Digester; // Message object ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required