Step 4: Make the driver
The driver has three things to do:
- parse the parameter file
- create and initialize instances of the
classes specified
- call the
receive,
transform
and send methods
Parse the parameter file
We'll use JDOM for this task,
since it transforms the XML document into a tree-structure that
is easy to navigate within. Here's a method that does the
parsing:
private Element parseFile(String fileName)
throws JDOMException, IOException {
File parameters = new File(fileName);
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(parameters);
return doc.getRootElement();
}
Create and initialize instances of the three classes specified
With the root JDOM element available we can now create instances
of the three plug-ins:
IReceive reader =
(IReceive) initClass("Read", IReceive.class,
root.getChild("Read"));
ITransform transformer =
(ITransform) initClass("Transform", ITransform.class,
root.getChild("Transform"));
ISend writer =
(ISend) initClass("Write", ISend.class,
root.getChild("Write"));
I've made a helper method--initClass--that
pulls the name of a class from the JDOM tree, creates an
instance, and calls the initialize method on the
instance:
Listing 4: The initClass method
/*
* Initialize a plug-in.
* elementName: The name used in the JDOM tree
* clas: The Interface class
* child: The JDOM element holding the plug-in data
*/
private Object initClass(String elementName, Class clas, Element child)
throws Exception {
if (child == null)
throw new Exception("No '" + elementName
+ "' element in parameter file.");
// Get 'class' attribute
Attribute classAtt = child.getAttribute("class");
if (classAtt == null)
throw new Exception("No 'class' attribute for the '"
+ elementName + "' element.");
// Make an instance of this plug-in
String className = classAtt.getValue();
Object o = Class.forName(className).newInstance();
// Check for correct interface
if (!clas.isInstance(o))
throw new Exception("Not an "
+ clas.getName() + " class: " + o.getClass().getName());
((IPlugin)o).initialize(child);
return o;
}
Call the receive, transform and send methods
Now it's a simple thing to call these methods:
List list = reader.receive();
List out = transformer.transform(list);
writer.send(out);
New on the Java Boutique:
New Review:
Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling
API boasts simplicity, ease-of-integration, a well-rounded feature
set, and it's free!
New Applet:
Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA
sequences into three useful formats.
Elsewhere on internet.com:
WebDeveloper Java
Lots of Java information on webdeveloper.com
WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.
ScriptSearch Java
Hundreds of free Java code files to download.
jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.