4/25/2012

Templatize Java Objects


In my recent project, there is so many places we are using templates. Like web pages with user based custom messages and information, email and letter templates etc. In Java we have MessageFormat class to do some simple templating. But in our case we need to fill these templates from pre-populated java objects. Something similar to JasperReports will do with jrxml templates.
I know we can write a utility to do this in java using Reflection. If I'm using reflection, then I will end up in writing so many lines of code, which I really hate. Groovy has this magical MOP which comes very handy. So I choose groovy to build this utility.

Here is the groovy code for the utility:
 @Log4j
 class Templatizer {
      
        def static final PATTERN = ~/[\$]{1}\{([^}]*)\}/
 
        def static String toString(final String template, def target) {
            def tempStr = template
            PATTERN.matcher(template).findAll {it ->
                try {
                    tempStr = tempStr.replace(it[0], target."${it[1]}")
                } catch(MissingPropertyException e) { }
            }
            tempStr
        }

        def static String toString(String template, List target) {
            toString(template, target, "\n")
        }
 
        def static String toString(String template, List target, String seperator) {
            def output = new StringBuilder()
            target.each { output.append(toString(template, it)).append(seperator) }
            output.toString()
        }
 }
 

Here is how we use it (Groovy Version):
 EmployedPerson p = new EmployedPerson([name: "David Foo", dob: new Date(), salary: 90000.00])
 println Templatizer.toString("Templatizing Test: My Name is ${name}. I born in ${dob} and I am earning a salary of ${salary}", p)
 

Java Version:
 EmployedPerson p = new EmployedPerson("David Foo", new Date(), 90000.00);
 System.out.println(Templatizer.toString("Templatizing Test: My Name is ${name}. I born in ${dob} and I am earning a salary of ${salary}", p));
 


You can compile this class and you can use with in your java objects. You can use Ant to compile groovy code. For more details on groovy-ant compilation, refer my previous blog


No comments:

Post a Comment