Simple XML Data Scrubbing

Worked on a project recently where the team had some XML data that they wanted to be 'scrubbed' before passing it along to other teams. Being that it was in XML, Groovy seemed like a perfect place to create a very fast and simple scrubbing program. To demonstrate, I created a simple XML file with some data that you know you don't want to pass around.

<Policy>
  <Party>
    <FirstName>Jason</FirstName>
    <LastName>Borne</LastName>
    <SSN>1234567890</SSN>
    <Address1>4994 Road</Address1>
    <State>MI</State>
  </Party>
  <Driver>
    <State>MI</State>
    <License>B20049595091</License>
  </Driver>
  <Risk>
    <Coverage type="A">20000</Coverage>
   </Risk>
</Policy>

Then I wrote a really simple script to show Groovy could easily update the important values. It pulls all the files from the 'files-to-filter' folder, filters them and writes the updated XML to the 'filtered-files' folder. Easy.


import groovy.util.slurpersupport.NodeChild
import groovy.xml.XmlUtil

def outputDirectory = new File('./filtered-files')
new File('./files-to-filter').eachFile { File input ->
  def output = new File(outputDirectory, input.name)
 
  def xml = new XmlSlurper().parseText(input.text)
  xml.'**'.each { NodeChild tag ->
    def names = generateNewName()
    def values = generateAdditionalNewValues()
  
    switch (tag.name()) {
      case 'FirstName':
        tag.replaceBody(names.'FirstName')
        break
      case 'LastName':
        tag.replaceBody(names.'LastName')
        break
      case 'SSN':
        tag.replaceBody(values.'SSN')
        break
      case 'Address1':
        tag.replaceBody(values.'Address1')
        break
      case 'State':
        if (tag.parent().name() == 'Driver') {
          tag.replaceBody(values.'State')
        }
        break
      case 'License':
        tag.replaceBody(values.'License')
        break
} output << XmlUtil.serialize(xml) } /** * @return generate a new name, maybe reading for dataset and using 'random' to pick one */ def generateNewName() { return ['FirstName': 'Johnny', 'LastName': 'Five'] } /** * @return newly generated values, could be accessing a database or something */ def generateAdditionalNewValues() { return ['SSN': '0987654321', 'Address1': '9848 SomewhereElse', 'State': 'IA',
          'License': 'I390398349834']
}

Groovy Method Tracer Transformer

In general I don't find trace logs for entering and exiting a method to be very useful, but occasionally I work with teams that do. There are great options using Spring or AspectJ, but I was in a Groovy project that didn't have either readily available. So, it made me wonder if we could just use AST transformations to build the loggers at compile time. Of course, as awesome as Groovy is, it's not hard. It already has a really cool feature to add code guards for logging statements, now I want to inject new logging statements into the code.

Groovy has an option to wrap methods on individual classes (see this metaClass example), but I was hoping to use an annotation, using an implementation of the ASTTransformation, to selectively add logging on methods. Thankfully, Groovy has an example in their documentation
(search for WithLogging). So here's a slightly tweaked implementation.

WithTracer.java
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@GroovyASTTransformationClass(classes = {WithTracerAstTransformer.class})
public @interface WithTracer {
  // marker annotation
}

WithTracerASTTransformer.groovy
import groovy.transform.CompileStatic
import org.codehaus.groovy.ast.ASTNode
import org.codehaus.groovy.ast.MethodNode
import org.codehaus.groovy.ast.expr.ArgumentListExpression
import org.codehaus.groovy.ast.expr.ConstantExpression
import org.codehaus.groovy.ast.expr.MethodCallExpression
import org.codehaus.groovy.ast.expr.VariableExpression
import org.codehaus.groovy.ast.stmt.BlockStatement
import org.codehaus.groovy.ast.stmt.ExpressionStatement
import org.codehaus.groovy.ast.stmt.ReturnStatement
import org.codehaus.groovy.ast.stmt.Statement
import org.codehaus.groovy.control.CompilePhase
import org.codehaus.groovy.control.SourceUnit
import org.codehaus.groovy.transform.ASTTransformation
import org.codehaus.groovy.transform.GroovyASTTransformation

@CompileStatic
@GroovyASTTransformation(phase=CompilePhase.SEMANTIC_ANALYSIS)
class WithTracerAstTransformer implements ASTTransformation {
  @Override
  void visit(ASTNode[] nodes, SourceUnit sourceUnit) {
    MethodNode method = (MethodNode) nodes[1]

    def startMessage = createPrintlnAst("Starting $method.name")
    def endMessage = createPrintlnAst("Ending $method.name")
    def existingStatements = ((BlockStatement)method.code).statements
    existingStatements.add(0, startMessage)

     //insert the trace before the return statement, or as the last statement
    if (existingStatements.last() instanceof ReturnStatement) {
      existingStatements.add(existingStatements.size() - 1, endMessage)
    } else {
      existingStatements.add(endMessage)
    }
  }

  private static Statement createPrintlnAst(String message) {
    new ExpressionStatement(
      new MethodCallExpression(
        new VariableExpression("log"),
        new ConstantExpression("trace"),
        new ArgumentListExpression(new ConstantExpression(message))
        )
    )
  }
}

The only problem with this simple approach is that the Groovy logging annotation which adds the code guards are applied before this new annotation. So if I wanted this to be production ready, the transformer would probably need to extend the existing Groovy logging transformer in some way. For my purposes though, I was able to convince the team that looking in AppDynamics to see the method execution path was a better option.

The other problem I ran into is that Eclipse is stupid. Every time that I clean the project the classes get wiped out and the Eclipse compiler fails on any class that was trying to use the annotation. So I had to put the code for this in a separate project.

Probably not something I'd use, but it was a really interesting experiment with ASTTransformation that might have other possibilities.

Parallel Processing of Directories/Files

I've been working with a rules engine product recently that stores all of it's instructions in XML files. To support their rating algorithms, my company now has over 11,000 XML files stored in over 800 directories. These files can relate to one another through a sort of cascading inheritance. Considering the amount of data, I was looking for a way to visualize, but before I could even begin putting the data into a graph, I had to parse through all of the files to build the relationships.

My first attempt used Groovy's eachFileRecursive method to spin through all files and parse them, but it took about 12 minutes to run, which was far too long. So, I tried to run the parsing in parallel, which improved the time considerably, but I was still running for several minutes.

ThreadPoolExecutor executor = Executors.newFixedThreadPool(20);
directory.eachFileRecurse (FileType.FILES) { File file ->
  executor.execute(buildParser(manuscripts, file))
}
private static Callable buildParser(List manuscripts, File file) {
  return { //do stuff } as Callable
}
executor.shutdown()
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS)

My next step was to change how I was parsing the XML files. Originally I was using the XmlParser.

String line
file.withReader {
  while ((line = it.readLine()) != null) {
    if (line =~ /^\s*<properties/) {
      line = line.replaceFirst('([^/])>\\s*$') { it[0][0] + '/>' }
      
      def properties = new XmlParser().parseText(line)
      def props = [manuscriptID: properties.@manuscriptID?.toString(),
             inherited: properties.@inherited?.toString(),
             caption: properties.@caption?.toString()]
      if (props.inherited) {
        manuscripts << props
      }
      break
    }
  }
}

Sometimes the properties tag was self closing, other times it had children, so I had to do some manipulation of the String before I could apply the XmlParser to it. It didn't seem that bad, but it definitely wasn't fast, so I decided to try a SAX parser and it made a drastic improvement, I was no down to 20-30 seconds to get through all 11,000+ files.

class SaxManuscriptPropertiesHandler extends DefaultHandler {
  Map manuscriptProperties
  
  void startElement(String ns, String localName, String qName, Attributes atts) {
    switch (qName) {
      case 'properties':
        manuscriptProperties = [id: atts.getValue('manuscriptID'),
                                desc: atts.getValue('caption')]
        if (atts.getValue('inherited')) {
          manuscriptProperties['parent'] = atts.getValue('inherited')
        }
        //purposeful fall through to end processing
      case 'model':
        throw new StopProcessingException()
    }
  }
  private static Map parseManuscript(File file) {
    SaxManuscriptPropertiesHandler handler = new SaxManuscriptPropertiesHandler()
    def reader = SAXParserFactory.newInstance().newSAXParser().XMLReader
    reader.setContentHandler(handler)

    try {
      reader.parse(new InputSource(file.newInputStream()))
    } catch (StopProcessingException e) {
      //finished reading XML document
    }
    return handler.manuscriptProperties
  }
}

Getting there, but I still wanted to see if it could better, so I set some timers in my code to see where the remaining time was being spent and discovered that reading through the directories to load up the files was still taking a lot of time. The eachFileRecursive method was still single threaded. So I decided to parallelize that as well. In the new approach, each directory is added to the thread pool and processed separately.

The only problem I ran into was that I couldn't use shutdown - awaitTermination approach anymore because the main thread would reach the shutdown call before all of the directories/files had been added to the executor pool, so I switch the wait condition to use sleep and wait until all of the threads were finished processing.

class ManuscriptDirectoryParser {
  def manuscripts = [] as CopyOnWriteArrayList
  ThreadPoolExecutor executor = Executors.newFixedThreadPool(20);
  
  public parseDirectory(String directory) {
    processDirectory(new File(directory))
    while (!executor.shutdown) {
      Thread.sleep(1000)
      if (executor.activeCount == 0) {
        executor.shutdown()
      }
    }
    //write results to file
  }
  private processDirectory(File file) {
    file.listFiles().each { File child ->
      if (child.directory) {
        executor.execute({processDirectory(child)} as Runnable)
      } else {
        executor.execute({
          manuscripts << SaxManuscriptPropertiesHandler.parseManuscript(child) 
        } as Runnable)
      }
    }
  }
}

The culmination to all the improvements meant that I could run the parsing job in 14 seconds now, considerably better than the 12+ minutes where I started.

Spring Controller With Groovy HTML Generation

I was working on a small Java POC and wanted to be able to quickly generate some HTML, so I decided to try Groovy's MarkupBuilder. In theory it meant that I had a single file that handle the entire view, instead of shipping the rendering work off to another file like a JSP. Pretty sure this was not the wisest move ever, but it was an interesting experiment.

The code was in a Spring Boot app, so I created a Controller with a couple of URL mappings. The data being displayed is coming from an XML file, so there are some references to Groovy's XmlParser as well.

The renderHtml method creates the HTML, HEAD, and BODY tags and accepts additional page contents as a closure. In the example, there are two different pages that can be generated, both of which share the same style declarations because they both use renderHtml.

As I said, I don't think I'd do this in an actual application, but it is a way of creating an entire page's contents in a single file.


@RestController
class TableController {
  @Autowired
  ManuscriptCatalog catalog
  
  @RequestMapping(value="/manuscripts/{manuscript}/tables")
  String displayTable(@PathVariable("manuscript") String manuscriptId) {
    def manuscript = new XmlParser().parse(
  new File(catalog.getManuscript(manuscriptId).@url))
    def tableXmls = manuscript.depthFirst().findAll {it.name() == 'table'}

    return renderHtml { builder ->
      builder.h2(manuscript.properties[0].@caption.toString())
      builder.ul {
        tableXmls.each { tableXml ->
          String tableName = tableXml.@id.toString()
          li { a(href: "/manuscripts/$manuscriptId/tables/$tableName",
                       tableName) }
        }
      }
    }
  }
  
  @RequestMapping(value="/manuscripts/{manuscript}/tables/{table}")
  String displayTable(
    @PathVariable("manuscript") String manuscriptId,
    @PathVariable("table") String tableName) {
 
    def manuscript = new XmlParser().parse(
      new File(catalog.getManuscript(manuscriptId).@url))
    def tableXml = manuscript.depthFirst().find {
      it.name() == 'table' && it.attributes()['id'] == tableName}
    def table = Table.parseTableData(tableXml)
    
    return generateTableHtml(table)
  }
  
  private String renderHtml(Closure pageContents) {
    StringWriter out = new StringWriter()
    def builder = new MarkupBuilder(out)
    builder.html {
      head {
        link(rel: 'stylesheet',
       href: 'http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css')
        style( '''\
          .table-nonfluid {
            width: auto !important;
          }
          th, .key { background-color: #669900; font-weight: bold; color: white }
          tr:hover {
            background-color: #a6a6a6 !important;
          }
        ''')
      }
      builder.body {
        pageContents(builder)
      }
    }
    return out.toString()
  }
  /**
   * Generate HTML based on the tables structure
   */
  private String generateTableHtml(Table table) {
    return renderHtml { builder ->
      builder.h2(table.name)
      builder.table('class' : "table table-condensed table-bordered table-nonfluid") {
        thead {
          table.colKeys.eachWithIndex { key, index ->
            tr {
              if (index == table.colKeys.size() - 1) {
                table.rowKeys.collect { rowKey -> th(rowKey.name) }
              } else {
                th(colspan: table.rowKeys.size())
              }
              key.repeated.times {
                key.values.each { keyValue ->
                  th(colspan : key.span, keyValue)
                }
              }
            }
          }
        }
        tbody {
          table.rows.eachWithIndex { row, rowIndex ->
            tr {
              row.keys.eachWithIndex { key, keyIndex ->
                if (table.rowKeys[keyIndex].span == 1
      || rowIndex % table.rowKeys[keyIndex].span == 0) {
                  td('class' : 'key', rowspan : table.rowKeys[keyIndex].span, key)
                }
              }
              row.values.collect { val -> td(val) }
            }
          }
        }
      }
    }
  }
}

Extension to MarkupBuilder to Support Dot-Notation

I'm working with a system that accepts XML as input to it's services, and there are times that the XML I need to generate is several layers deep, like so.

<session id="$sessionId">
  <data>
    <policy>
      <line>
        <Type>WorkersCompensation</Type>
        <linestate>
          <exposure>
            <Type>PremiumSelection</Type>
            <sValue>AssignedRisk</sValue>
          </exposure>
        </linestate>
      </line>
    </policy>
  </data>
</session>

Thankfully Groovy provides a nice MarkupBuilder that simplifies generating this XML. It looks like this.

StringWriter writer = new StringWriter()
new MarkupBuilder(writer).session {
  data {
    policy {
      line {
        Type('WorkersCompensation')
        linestate {
          exposure { Type('PremiumSelection'); sValue('AssignedRisk') }
        }
      }
    }
  }
}
println writer.toString()

But what I didn't particular like about this is all of the extra '}' at the end of the function. This is way easier than implementing it in Java, but there's still just too much code for my liking. What I really want to write is this.

println TestDataBuilder.build {
  session.data.policy.line {
    Type('WorkersCompensation')
    linestate.exposure { Type('PremiumSelection'); sValue('AssignedRisk') }
  }
}

The big difference is the use of dot-notation to handle nesting when there's no additional elements contained within the element. I also wrapped the declaration of the StringWriter into a convenience method since in my scenario I'm always looking to get a String back. So, that's the goal, what does the code to do this look like?

Well, I created two classes, the first TestDataBuilder just abstracts the creation of the StringWriter and passing back the string, the more complicated class, the DeepMarkupBuilder (not sure if that's a good name... naming is hard) extends the Groovy MarkupBuilder class and adds functionality to look for 'missing properties', aka, the tags I want to generate that don't have an associated closure.


class TestDataBuilder {
  public static String build(Closure data) {
    Writer writer = new StringWriter()
    DeepMarkupBuilder builder = new DeepMarkupBuilder(writer)
    data.setDelegate(builder)
    data.run()
    return writer.toString()
  }
}


class DeepMarkupBuilder extends MarkupBuilder {
  Stack openTags = [] as Stack
  Map closeableTags = [:]
 
  public DeepMarkupBuilder(Writer writer) {
    super(writer);
  }
  def propertyMissing(String property) {
    openTags.add(property)
    super.invokeMethod(property, null)
    return this
  }
  public Object invokeMethod(String name, Object args) {
    if (args && args[0] instanceof Closure) {
      closeableTags[name] = openTags
      openTags = [] as Stack
    }
    return super.invokeMethod(name, args)
  }
  protected void nodeCompleted(Object parent, Object node) {
    if (!openTags || openTags.peek() != node) {
      super.nodeCompleted(parent, node)
   
      Stack closeable = closeableTags[node]
      while (closeable) {
        super.nodeCompleted(null, closeable.pop())
      }
    }
  }
}

The propertyMissing function is called by Groovy whenever a property is referenced that doesn't exist in the object. The 'session', 'data', and 'policy' parts of the XML will be treated as properties, so the class creates them as open tags. The openTags check in the nodeCompleted method ensures that they are not closed as soon as they are encountered.

The 'line' attribute will be treated as method call since it accepts a Closure as an argument. The invokeMethod method will handle this attribute, and most of the existing super implementation of the method can be used. However, we need to track what tags were opened prior to this tag, so that when this tag is closed, those parents tags can be closed as well. So, the stack of 'closeableTags' is stored off in a map related to this node. Then when the nodeCompleted method is called, those closeable tags, can be closed.

Simple implementation to achieve that concise XML generation I was looking for.

Populating a Holiday Table

Our company has a Java service which determines if a date is a holiday, but we were working on some reports that needed that data in a database. So the following groovy script was used to populate a holiday table for the holidays for the remainder of the century.
def sql= new Sql(datasource)

def dateString = '20100101'
def date = Date.parse('yyyyMMdd', dateString)

while (dateString < '20991231') {
  if (HolidayService.isDayOffDueToHoliday(dateString)) {
    sql.execute '''INSERT INTO HOLIDAYS (HOLIDAY_DATE)
                   VALUES (?, 'E010152')''',
          date.format('yyyy-MM-dd')
  }

  date = date.next()
  dateString = date.format('yyyyMMdd')
}

Groovy Copybook Slurper


In order to call CICS from Java, we've traditionally used RDz to generate a J2C bean via an Ant script. But I don't have RDz anymore (it doesn't support Groovy and always running older versions of Eclipse), so my only alternative was to use a JCL to generate a bean via IBM's JZOS library.

I'm still not a big fan, it takes time to run the JCL, download the generated file from the mainframe and tweak the object names, packages, etc.. What if I could just declare my copylib structure in my Java code and call CICS? To that end, I've been working on a parser which converts a byte stream to/from a map.

Leaving the CICS call of it out for the moment, here's an idea of want the read code would look like.

def slurper = new CopybookSlurper("""\
01 TESTING-COPYBOOK.
   03 STATES OCCURS 10 TIMES .
      05 STATE PIC XX.
""")
def data = slurper.getReader('MIOHINWINVCAKYFLNCSC'.getBytes())
data.STATES.each {
  print it.STATE  //will print each two byte state
}
assert 'IN' == data.STATES[2].STATE //zero-based indexed of the STATES list

And here's the write code

def slurper = new CopybookSlurper("""\
  01 TOP-LEVEL.
     03 STATES OCCURS 2 TIMES.
        05 STATE-NUM        PIC X(3).
        05 STATE-NAME       PIC X(10).
        05 NUMERIC-STATE    PIC 9(2). """)
    
def writer = slurper.getWriter(new byte[slurper.length])
writer.with {
  STATES[0].with {
 STATE_NUM = '1'
 STATE_NAME = 'MICHIGAN'
 NUMERIC_STATE = 2
  }
  STATES[1].with {
 STATE_NUM = '2'
 STATE_NAME = 'OHIO'
 NUMERIC_STATE = 3
  }
}
assert new String(writer.getBytes(), 'IBM-37') ==
       '1  MICHIGAN  022  OHIO      03'

The slurper name and map structure is inspired by Groovy's XmlSlurper and JsonSlurper. My parser implementation is written in groovy to take advantage of the dynamic nature of the maps and closures. I used the JZOS library under the covers to handle parsing the individual data elements so it can handle binary fields (COMP-3 stuff). Unfortunately JZOS didn't provide any simple hooks for getting a data type based on a PIC definition, so I had to rewrite that logic. I know my parser isn't as robust as the IBM version, it doesn't handle some of the weird datatypes for instance, but it's good enough for the normal copybooks that we'd be using from the web.

I also wanted to make my map lazy so that the bytes are only parsed if requested, after all sometimes COBOL copybooks have a ton of data in them, and I only want a small piece. So rather than parsing the field right away, the parser creates a map of closures with instructions on how to parse the data. Likewise, the writer stores a closure for each variable with instructions on how to write data to a shared byte array. The getReader method is shown below. There's a lot of complexity involved in occurrences and groups that you can't see here, but I just wanted to show the mapping of the variable names to closures.

public Map<String, ?> getReader(byte [] bytes) {
  Map readers = [:]
  fieldProcessors.each { DataVariable variable ->
    if (variable.read) {
      readers[variable.name] = { variable.read(bytes) }
    }
  }
  return new LazyProperties(readers, bytes)
}

The LazyProperties class extends HashMap and invokes the closures from the map when referenced, then caches the results for the next call. The getWriter method works in a similar fashion with closures, though it doesn't cache results because any call to the write methods should write data to the byte stream.

That's what I have working so far, the next step is to look into the javax.resource.cci.Record and javax.resource.cci.Streamable interfaces and perhaps Spring's org.springframework.jca.cci.core.support.CciDaoSupport to call down to CICS.

Generating Lots Values From A DB2 Sequence Object

I was working on a Groovy script that inserts lots of data into a database, but I needed to generate a new key from a sequence object and keep track of the old one. So I need to invoke NEXTVAL for each key, but considering how many thousands of records I was inserting, I didn't want to call the database for each key individually.

There's no way to batch up SELECT statements, but I thought I could perhaps generate a big SELECT statement that includes all the keys I needed.

SELECT 1 AS OLD_KEY, MYSEQUENCE.NEXTVAL FROM SYSIBM.SYSDUMMY1
UNION ALL
SELECT 2 AS OLD_KEY, MYSEQUENCE.NEXTVAL FROM SYSIBM.SYSDUMMY1

The problem with this approach is that when you request NEXTVAL multiple times in the same SELECT statement, it returns the same value each time. So I ended up generating one new key assigned to all of my old keys. No good, so I had to try something else. I decided to insert into a GLOBAL TEMPORARY TABLE.

db.execute('''DECLARE GLOBAL TEMPORARY TABLE SESSION.GEN_IDS (
  ORIG_ID DECIMAL(12,0), NEW_ID DECIMAL(12,0)) ON COMMIT PRESERVE ROWS''')

db.withBatch('INSERT INTO SESSION.GEN_IDS VALUES (?, MYSEQ.NEXTVAL)') { 
  BatchingPreparedStatementWrapper ps ->
    oldKeys.each { ps.addBatch(it) }
  }

def mappings = target.rows('SELECT * FROM SESSION.GEN_IDS').collectEntries {
 Map data -> [(data.ORIG_ID) : data.NEW_ID]
}

db.execute('DROP TABLE SESSION.GEN_IDS')

Problem solved. The collectEntries method will create a map for the old and new values. Of course, then I learned about the JDBC getGeneratedKeys method, which makes this approach much less useful, but I'm still glad I learned how to use the GLOBAL TEMPORARY TABLEs.

Groovy Overload (of Operators)

I was recently working on a pretty long class which mapped a web-service response to a set of 'activity codes' in our Java application. The class ends up mapping some 60+ different codes based on various scenarios, and appends some extra data for some. The code was original written in Java and pretty well organized (okay I wrote it, so I may be bias), but it was very wordy, there were a lot of repeated words/verbs in the class.

So, I set about re-writing this class in Groovy, not just for the wordiness, there were some additional complexities to the rules that I needed to apply, but I wanted to make this monstrosity easier to understand. I made use of Groovy's capability to use Strings in switch statements (coincidentally, we were given the okay to use Java 7 the following week...), which helped (previously I had been converting the Strings into enum), and I made use of Groovy's implicit calls to setters and it's concise map notation. All of which made a big difference. I also used static imports for my enums so the names were shorter. So the code looked like this in the end.

details.activityCode = PAYMENT_TRANSFER_IN
details.activityProperties[REVERSAL_REAPPLIED_TO] = pay.transferAcct
details.activityProperties[ACCOUNT_NUMBER] = pay.transferAcct

But I wanted to go one step further, every single one of our activities had an activityCode, that's the primary data we're mapping, and the activity properties was only the only map in the object. So saying .activityCode and .activityProperties was redundant. What I really wanted was something more concise like this:

details << PAYMENT_TRANSFER_IN
details[REVERSAL_REAPPLIED_TO] = pay.transferAcct
details[ACCOUNT_NUMBER] = pay.transferAcct

And thanks to Groovy's ability to add methods which override operators, that was an easy task. These are the relevant parts of my POJO to support this notation. 

private String activityCode;
private Map<ActivityType, String> activityProperties = new HashMap<>();

//Overrides the '<<' operator in groovy code to set the account activity code.
public void leftShift(ActivityCode value) {
  this.setActivityCode(value);
}

// Used with groovy map notation to get activityProperties values.
public String getAt(Object key) {
  return this.sapProperties.get(key);
}

// Used with groovy map notation to set activityProperties values.
public String putAt(AccountActivityTypeDescriptor key, Object value) {
  if (value != null) {
    return this.sapProperties.put(key, String.valueOf(value));
  }
  return null;
}

Note: I could add leftShift methods for other object types too, like the amount, which is also often set on these objects, but I still want the code to be readable, that's the whole reason I was exploring this change, so since the activity code is the one that gets used repeatedly, that's the only value where I implemented leftShift.

The finally effect is much less code to read through, which makes understanding this massive class considerably easier.

Groovy Tabular Data DSL

After using Spock, I became really interested in the tabular input of data into my services, not just into my test. The project I'm working on has a lot of transaction data with various associated properties. So transaction type 1, has fee type A associated with it.

Traditionally I've done that type of property mapping using enums, or maybe a switch statement.This works well, but there's still a good amount of code, and I'd like to make the mapping as readable as possible for the next guy. Especially since in the particular case I'm working on, the enum has some 700+ transaction types and only a handful of them need additional properties.

Groovy made property mapping easier with it's slick map syntax, and that worked really well too, but I kept thinking about Spock, and that tabular data syntax, which I thought was even more readable than a map. I had this:

[Transaction.SERVICE_CHARGE : 
  [feeType: FeeType.SERVICE_FEE,
   waiveTransaction : Transaction.SERVICE_CHARGE_WAIVED,
   reapplyTransaction : Transaction.SERVICE_CHARGE_REAPPLIED
   desc: 'PAID SERVICE CHARGE'
  ],
Transaction.NSF_FEE_CHARGE : 
  [feeType: FeeType.NSF_FEE,
   waiveTransaction : Transaction.NSF_WAIVED,
   reapplyTransaction : Transaction.NSF_REAPPLIED
   desc: 'NSF CHARGE'
  ]
]

But I was really hoping to see something more like this (values omitted for formatting):

transType                  | feeType             | desc
Transaction.SERVICE_CHARGE | FeeType.SERVICE_FEE | 'PAID SERVICE CHARGE'
Transaction.NSF_FEE_CHARGE | FeeType.NSF_FEE     | 'NSF CHARGE'

During my research I ran across a blog entry by Christian Baranowski that did an excellent job of showing how to use Groovy's category and override properties features to create a simple table DSL. I took what he did and added a few more features for my own benefit, so my version supports three different outputs:

* data - returns a  list of lists, just giving the values from the table
* dataWithTitleRow - returns a list of mapped properties that represent each row, the title row column names are used as the key in the map
* dataWithTitleRow (def key) - returns a keyed map using the value from the value from the column identified from the 'key' parameter as the key.

def data = Table.withTitleRow('transType') {
transType                  | feeType             | desc
Transaction.SERVICE_CHARGE | FeeType.SERVICE_FEE | 'PAID SERVICE CHARGE'
Transaction.NSF_FEE_CHARGE | FeeType.NSF_FEE     | 'NSF CHARGE'
}
assert data[Transaction.SERVICE_CHARGE].desc == 'PAID SERVICE CHARGE'

Here's what my version looks like

import groovy.transform.Canonical

/**
 * Parses tubular data into 'rows' of just values, or mapped values (if there
 * is a title row in the data), or a map of keyed values.
 *
 * <p>
 * Based on blog entry at
 * http://tux2323.blogspot.com/2013/04/simple-table-dsl-in-groovy.html
 */
public class Table {
  /**
   * The Groovy category feature used to implement this DSL uses static
   * methods, so thread local is used to store off the parsed content as it
   * is processed.
   */
  private static ThreadLocal<List> PARSING_CONTEXT = new ThreadLocal<List>()

  /**
   * Parses a list of tabular data.
   *
   * <pre>
   * def data = Table.data {
   * Donald | Duck | Mallard
   * Mickey | Mouse | Rodent
   * }
   * assert data.first() == ['Donald', 'Duck', 'Mallard']
   * </pre>
   *
   * @param tabularData contains all the data to parse delimited by |
   * @return a list of lists of data
   */
  public static List data(Closure tabularData) {
    PARSING_CONTEXT.set([])
    use(Table) {
      tabularData.delegate = new PropertyVarConvertor()
      tabularData.resolveStrategy = Closure.DELEGATE_FIRST
      tabularData()
    }
    return PARSING_CONTEXT.get().collect { Row row -> row.values }
  }

  /**
   * Parses a list of tabular data with a title row, returns a list of
   * mapped properties.
   *
   * <pre>
   * def data = Table.dataWithTitleRow {
   * firstName | lastName | type
   * Donald | Duck | Mallard
   * Mickey | Mouse | Rodent
   * }
   * assert data.first() ==
   *   [firstName: 'Donald', lastName: 'Duck', type: 'Mallard']
   * </pre>
   *
   * @param tabularData contains all the data to parse delimited by |
   * @return a list of lists of data
   */
  public static List dataWithTitleRow(Closure tabularData) {
    List rows = data(tabularData)
    def titleRow = rows.first()

    return rows[1..<rows.size()].collect { List row ->
      def mappedRows = [:]
      row.eachWithIndex { it, index ->
        mappedRows[titleRow[index]] = it
      }
      return mappedRows
    }
  }

  /**
   * Parses a list of tabular data with a title row and specifies the column
   * that should be used as a key in the output map.
   *
   * <pre>
   * def data = Table.dataWithTitleRow('firstName') {
   * firstName | lastName | type
   * Donald | Duck | Mallard
   * Mickey | Mouse | Rodent
   * }
   * assert data['Donald'] ==
   *   [firstName: 'Donald', lastName: 'Duck', type: 'Mallard']
   * </pre>
   *
   * @param key the name of the column that should be used as the key in
   * the output map
   * @param tabularData contains all the data to parse delimited by |
   * @return a list of lists of data
   */
  public static Map dataWithTitleRow(def key, Closure tabularData) {
    Map keyed = [:]
    dataWithTitleRow(tabularData).each {
      keyed[it[key]] = it
    }
    return keyed
  }

  /**
   * Groovy treats a new line as the end of statement (with some exceptions),
   * so each new line will invoke this method which creates a new table row
   * which then is used to 'or' each value in the row together.
   *
   * @param self the left argument in the OR operator, the current value
   * @param arg the right argument in the OR operator, the next value
   *
   * @return a reference to the next argument, so that it can 'or-ed' against.
   */
  public static Row or(self, arg) {
    def row = new Row([self])
    PARSING_CONTEXT.get().add(row)
    return row.or(arg)
  }

  /**
   * Implements the 'or' operator to append each value in a row to a list.
   * Returns a reference to itself so the next or operation can append the
   * next value.
   */
  @Canonical
  static class Row {
    List values = []
    def Row or(arg) {
      values << arg
      return this
    }
  }

  /**
   * Handler to treat any properties that cannot be found as strings.
   */
  static class PropertyVarConvertor {
    def getProperty(String property) {
      return property
    }
  }
}