Friday, March 24, 2006

Using Standalone Ant Tasks in Java Code

Ant is a very good build management and automation tool. Moreover Ant tasks are very easy to use in java code as well. I mean, you don't have to write build.xml files in order to benefit from Ant tasks. You can as well use Ant tasks from java code directly.

Here is an example of code:


Project project = new Project();
project.setBasedir(".");
project.setName("DbUnit Test");
SQLExec sqlExec = new SQLExec();
sqlExec.setProject(project);
sqlExec.setDriver(driverName);
sqlExec.setUrl(url);
sqlExec.setUserid(username);
sqlExec.setPassword(password);
File createTable = new File("db/create-table.sql");
sqlExec.setSrc(createTable);
sqlExec.execute();
sqlExec.setSrc(null);
sqlExec.addText("" +
" INSERT INTO app_user (id, first_name, last_name) \n" +
" values (5, 'Julie', 'Raible');\n" +
" INSERT INTO app_user (id, first_name, last_name) \n" +
" values (6, 'Abbie', 'Raible');\n");
sqlExec.execute();


This is the same as the following build.xml excerpt:


<sql driver=\"${jdbc.driverClassName}\" url=\"${jdbc.url}\"
userid=\"${jdbc.username}\" password=\"${jdbc.password}\">
<classpath refid=\"compile.classpath\"/>
<![CDATA[
INSERT INTO app_user (id, first_name, last_name)
values (5, \'Julie\', \'Raible\');
INSERT INTO app_user (id, first_name, last_name)
values (6, \'Abbie\', \'Raible\');
]]>
</sql>


Although xml code is shorter, java code has some adequate use cases. For example, you want to reuse SQLExec's functions in your own application. You can reuse any of the Ant tasks which is a large library full with utilities.

But beware that all Ant tasks depend on a wrapping Project object. Therefore the first line in the above java code instantiates a dummy Project object.

No comments: