Apache Digester Example – Make Easy Configuration
Transforming an XML document into a corresponding hierarchy of Java bean objects is a fairly easy using Apache Digester. See Digester in action below.
Digester introduces three important concepts:
- element matching patterns
- processing rules
- the object stack.
Element matching patterns associate XML elements with processing rules.
Example :
What you have:
- Java Classes
- XML files containing data
You have java classes and corresponding xml files. You want java classses instances to be created from xml data.
What extra code you need to write.
Step by step tasks:
- Add Apache Digester 3 jar file, Commons logging jar, Beanutils jar,cglib jar in your class path
- If don’t have the java classes, create java classes for corresponding xml file.Or if don’t have xml files, create it as per the java classes.Note- property name,hierarchy in xml and java class should match, otherwise you need to provide mapping in your digester xml rule not mentioned here.
- Create a digester rule xml file as mentioned in the example below
- Use few lines of to load java objects from xml
Now In Action –
Here is my eclipse project structure :
Task 2 – create data xml file as below you want data from which to be loaded say – chain-config.xml
<?xml version="1.0" encoding="UTF-8"?> <catalogs> <!-- Default Catalog: "Path Info" example --> <catalog> <!-- Command that maps "Path Info" patterns to Commands --> <chain name="COMMAND_MAPPER"> <command className="org.apache.commons.chain.web.servlet.PathInfoMapper"/> <command forward="/pathinfo.jsp" className="org.apache.commons.chain.apps.example.ForwardCommand"/> </chain> <!-- Foo Command --> <chain name="/foo"> <command attribute="pathinfoFooCount" className="org.apache.commons.chain.apps.example.CountCommand"/> </chain> <!-- Bar Command --> <chain name="/bar"> <command attribute="pathinfoBarCount" className="org.apache.commons.chain.apps.example.CountCommand"/> </chain> </catalog> <!-- Catalog for "Request Parameter" example --> <catalog name="reqparam"> <!-- Command that maps a "Request Parameter" to Commands --> <chain name="COMMAND_MAPPER"> <command catalogName="reqparam" className="org.apache.commons.chain.web.servlet.RequestParameterMapper"/> <command forward="/reqparam.jsp" className="org.apache.commons.chain.apps.example.ForwardCommand"/> </chain> <!-- Foo Command --> <chain name="foo"> <command attribute="reqparamFooCount" className="org.apache.commons.chain.apps.example.CountCommand"/> </chain> <!-- Bar Command --> <chain name="bar"> <command attribute="reqparamBarCount" className="org.apache.commons.chain.apps.example.CountCommand"/> </chain> </catalog> </catalogs>
Create corresponding java classses Catalog.java :
import java.util.ArrayList; import java.util.List; public class Catalog { /** * @uml.property name="name" */ private String name; /** * Getter of the property <tt>name</tt> * @return Returns the name. * @uml.property name="name" */ public String getName() { return name; } /** * Setter of the property <tt>name</tt> * @param name The name to set. * @uml.property name="name" */ public void setName(String name) { this.name = name; } /** * @uml.property name="chains" */ private List<Chain> chains=new ArrayList<Chain>(); public void addChains(Chain chain) { this.chains.add(chain); } }
Chain.java :
import java.util.ArrayList; import java.util.List; public class Chain { /** * @uml.property name="name" */ private String name; /** * Getter of the property <tt>name</tt> * @return Returns the name. * @uml.property name="name" */ public String getName() { return name; } /** * Setter of the property <tt>name</tt> * @param name The name to set. * @uml.property name="name" */ public void setName(String name) { this.name = name; } /** * @uml.property name="commands" */ private List<Command> commands=new ArrayList<Command>(); /** * Setter of the property <tt>commands</tt> * @param commands The commands to set. * @uml.property name="commands" */ public void addCommands(Command command) { this.commands.add(command); } }
Command.java :
import java.util.ArrayList; import java.util.List; public class Chain { /** * @uml.property name="name" */ private String name; /** * Getter of the property <tt>name</tt> * @return Returns the name. * @uml.property name="name" */ public String getName() { return name; } /** * Setter of the property <tt>name</tt> * @param name The name to set. * @uml.property name="name" */ public void setName(String name) { this.name = name; } /** * @uml.property name="commands" */ private List<Command> commands=new ArrayList<Command>(); /** * Getter of the property <tt>commands</tt> * @return Returns the commands. * @uml.property name="commands" */ public List getCommands() { return commands; } /** * Setter of the property <tt>commands</tt> * @param commands The commands to set. * @uml.property name="commands" */ public void addCommands(Command command) { this.commands.add(command); } }
Task 3 – Create digester rules digester-catalog-rules.xml
<?xml version="1.0"?> <!DOCTYPE digester-rules PUBLIC "-//Apache Commons //DTD digester-rules XML V1.0//EN" "http://commons.apache.org/digester/dtds/digester-rules-3.0.dtd"> <digester-rules> <pattern value="catalogs/catalog"> <object-create-rule classname="Catalog"/> <set-properties-rule/> <!-- comment : <bean-property-setter-rule pattern="name"/> use as shown above if say <catalog><name>reparam</name> </catalog> instead of <catalog name="reparam"> </catalog> --> <!-- Nested Pattern for Characters --> <pattern value="chain"> <object-create-rule classname="Chain"/> <set-properties-rule/> <!-- Nested Pattern for Characters --> <pattern value="command"> <object-create-rule classname="Command"/> <set-properties-rule/> <set-next-rule methodname="addCommands" paramtype="Command"/> </pattern> <set-next-rule methodname="addChains" paramtype="Chain"/> </pattern> <set-next-rule methodname="add" paramtype="Catalog"/> </pattern> </digester-rules>
Task 4 – Client program to load xml data
import java.io.IOException; import java.io.InputStream; import java.net.URL; import org.apache.commons.digester3.Digester; import org.apache.commons.digester3.binder.DigesterLoader; import org.apache.commons.digester3.xmlrules.FromXmlRulesModule; import org.xml.sax.SAXException; import java.util.ArrayList; import java.util.List; public class runProgram { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub // Create an instance of the Digester from the XML rule set DigesterLoader digesterLoader = DigesterLoader.newLoader(new FromXmlRulesModule() { @Override protected void loadRules() { // TODO Auto-generated method stub loadXMLRules( getClass( ).getResource("/com/tatu/resources/digester-catalog-rules.xml")); } }); Digester digester = digesterLoader.newDigester(); List<Catalog> catalogs = new ArrayList<Catalog>(); // Push a reference to the plays List on to the Stack digester.push(catalogs); // Parse the XML document InputStream input = Digester.class.getClass().getResourceAsStream("/com/tatu/resources/chain-config.xml"); try { Object root = digester.parse(input); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Done. So have loaded the catalogs object with the xml data.
Points to be noted from the above solution:
- object-create-rule creates an object
- Rest of the rules are straightforward as their name suggests, object-create-rule creates a new instance, set-properties-rule sets the properties of the object from xml attributes like name attribute of catalog element whereas bean-property-setter-rule sets properties of the object from nested xml elements like say <catalog><name>reparam</name> </catalog> instead of <catalog name=’reparam’> </catalog>
- – set-next-rule: (used for recursion) The set-next-rulerule moves to the next catalog, chain, and command tags. You have also specified the method to call in each case which will add the objects to a collection defined in the parent class, example : <set-next-rule methodname=’addCommands’ paramtype=’Command’/>, here addCommands() method adds a command object to commands collection object defined in parent chain class.
- You want new custom rules,create your own Rule class deriving from digester Rule class.
Any question, put your comments.
One more thought, you don’t want all these shit inbetween the xml files and java classes. Guess what, there is a trick to avoid that. But I don’t like this trick unless you are in hurry. But everytime you use shortcut, you have to lose flexibilities.
Trick is to use Apache Betwixt. Remember to use Betwixt, you need to use apache digester 2.1. For more go to apache Betwixt site.
Use Betwixt BeanWriter to write the java beans to a file and then, use BeanReader to read from that file. Once you get the file generated from BeanWriter, you can change the values abd load it with BeanReader. (Need to configure betwixt mapping omitted here)
Happy coding and don’t forget to share!
Reference: Using Apache Digester with Example -Make Easy Configuration from our JCG partner Bijay Deo at the My Software Development Blog blog.
You didn’t provide Command.java code, Chain.java its duplicated.
Thanks in advance.
Ditto what Bernardo said. Did you even try this code before posting it?
Yes, What happened? Where are you facing problem, the code is actually copied from eclipse editor.
Yes you copied it from the eclipse editor, problem is you copied the wrong page into the place where you are trying to show the command class code. This guide would be clearer with the correct page given that is also the class you wrote rules for
public class Command {
private String className;
private String forward;
private String attribute;
private String catalogName;
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getForward() {
return forward;
}
public void setForward(String forward) {
this.forward = forward;
}
public String getAttribute() {
return attribute;
}
public void setAttribute(String attribute) {
this.attribute = attribute;
}
public String getCatalogName() {
return catalogName;
}
public void setCatalogName(String catalogName) {
this.catalogName = catalogName;
}
}