Willkommen auf Pelzkuh.de
Hier finden sich Neuigkeiten rund um interessante Themen aus der (Computer-)Technik und den Pelzkuh.de Development Server. Zugriff gibt es über die Trac Links.

Using Xtend's template expressions

Having programmed with Xtend for some time, using it mainly in small data migration and import projects, finally I wanted to give the template functions a try. As I had to create the binding descriptor file for the mapping of 60 LDAP roles to the same amount of Websphere groups this week, it was clear, that the time for Xtend templates has come.

Having a file with the role names, separated by a linebreak, I used the java.util.Scanner class to access the file:

        var scanner = new Scanner(new File("ldap.txt"))
        scanner.forEach[ s | println(xmlBinding(s)) ]

In the second line, I've used the power of Xtend's CollectionExtensions, combined with a lambda expression, to invoke the method, that contains the template code (xmlBinding()). It is executed for each line of the file and the result written to the console:

def static xmlBinding(String ldapEntry) {
     '''<security-role name="«ldapEntry.replace("FG_", "").toLowerCase»">
           <group name="«ldapEntry»"/>

The template method itself contains the pattern for the binding, framed by '''. We can add dynamic values to the template content, by surrounding the variables or method calls with « and ». So the task was accomplished, writing only a few lines of effective code, which you can easily conflate in one single line, if you like to.

If we want to create the complete deployment descriptor binding file with Xtend, we can adjust our example a little bit. Removing the foreach[] and giving the complete list of Strings to the template method, all of the magic is done inside this method:

    def static appBindingWithLoop(List<String> ldapEntries) {
       '''<?xml version="1.0" encoding="UTF-8"?>
         <application-bnd ...>

              «FOR e : ldapEntries»       
              <security-role name="«e.replace("FG_", "").toLowerCase»">
                   <group name="«e»"/>


As conclusion, the Xtend template expressions have done a good job, and I've used them for creating some more files, where I needed the 60 group names, too. Even if the Eclipse tooling for Xtend is not as good as it is for plain Java, for such small tasks, Xtend is a great tool. Just give it a go!

For more information about Xtend's template expressions, see: http://www.eclipse.org/xtend/documentation.html#templates

Keine Kommentare:

Kommentar veröffentlichen