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 ...
Get Jakarta Commons Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.