|
|
Programming Ant
Dhrubojyoti Kayal's Blog |
August 13, 2007 10:53 PM
|
Comments (0)
Recently i was busy building a Java snippet processing engine. The primary responsibilities of this engine were :
- Accept code snippets written in Java
- Dynamically generate Java code
- Compile the Java code
- Run the Java code
As you would expect, I started with the Runtime and Process classes from the standard Java API.
I was dynamically building a command string which was very large with classpath and system properties. Very soon, i ended up with a pretty dirty code full of StringBuffer.append.
More surprises awaited me.I had tested it on Windows and it did not work on other platforms. When i debugged, i realized that classpath setting was incorrect. Now i had to add a few if-else blocks depending on the platform. So i ended up with a lot of clumsy code, which i did not like. I had no option but to change because even PMD and Checkstyle were complaining.
I had already consumed a lot of time to implement the above functionality. So i had very little time to redesign and produce a clean solution. As one would expect, i started looking for existing libraries and the only useful one i found was none other than Apache Ant. Initially there were few glitches - lack of quick start guide was a problem. But soon i got used to the API docs and after that it was like a breeze.
Program Listing 1: Using Ant API to run a compiled Java program
public class JavaRunner{
private Project project;
private Path path
/*Accepts a list of folder containing the jars required
for running the compiled snippets*/
private JavaRunner(List classpathDirList){
this.project = new Project();
this.project.setName("JavaRunner");
this.path = new Path(project);
FileSet fileSet = null;
for(String cploc : classPathLocList){
fileSet = new FileSet();
fileSet.setDir(new File(cploc));
fileSet.setIncludes("**/*.jar");
path.addFileset(fileSet);
}
}
public int execute(String fullJavaClassName, Map sysParams){
javaExecutable = new Java();
javaExecutable.setProject(this.project);
javaExecutable.setClassname();
javaExecutable.setClasspath(this.path);
javaExecutable.setFork(true);
javaExecutable.setSpawn(false);
setNewJVMProperties(sysParams, javaExecutable);
status = javaExecutable.executeJava();
return status;
}
private void setNewJVMProperties(Map sysParams, Java java) {
Environment.Variable sysVar = new Environment.Variable();
sysVar.setKey("xml.config.loc");
sysVar.setValue(sysParams.get("xml.config.loc"));
java.addSysproperty(sysVar);
}
}
Comments
Comments are listed in date ascending order (oldest first) | Post Comment
|
|