Transform a Financial Message by Streaming

Following is an example dynamic logic to transform a financial message in a streaming way:

writer = outputWriters.getDataFileOutputWriter().xmlWriter()
writer.writeStartElement("root")

def xmlSlurper = new groovy.xml.XmlSlurper() // Reuse XmlSlurper for efficiency
genFinMessOutput.dataFiles.each { df ->
    reader = fileReader.xmlReader(df)
    while (reader.hasNext()) {
        finMess = reader.read('financialMessage') // this iterates the reader until the next 'financialMessage' object: No need to call reader.next()
        if (finMess != null) {
            log.debug('financialMessage found with id {0}', finMess.@id.text())
            transform(finMess, writer, xmlSlurper)
        }
    }
}

writer.writeEndElement() // root

Here, the transform(finMess, writer, xmlSlurper) method is used to read the data from the financial message, and write it to another datafile. An example of this method, which reads some attributes:

void transform(finMess, writer, xmlSlurper)
{
  writer.writeStartElement("messageID")
  writer.writeCharacters(finMess.@id.text())
  writer.writeEndElement()
  writer.writeStartElement("sourceSystemSourceID")
  writer.writeCharacters(finMess.invoices.invoice[0].@attribute1.text())
  writer.writeEndElement()
  finMess.invoices.invoice.invoiceLines.invoiceLine.each { invoiceLine ->
    writer.writeStartElement("premiumRateList")
    def tempRoot = xmlSlurper.parseText(invoiceLine.@attribute1.text())
    tempRoot.premiumRateList.each { premiumRateList ->
      writer.writeStartElement("premiumRate")
      writer.writeStartElement("policyNumber")
      writer.writeCharacters(premiumRateList.policyNumber.text())
      writer.writeEndElement() // policyNumber
      writer.writeStartElement("premiumAmount")
      def roundedPremiumAmount = new BigDecimal(premiumRateList.premiumAmount.text())
      writer.writeCharacters(roundedPremiumAmount.toString())
      writer.writeEndElement() // premiumAmount
      writer.writeEndElement() // premiumRate
    }
    writer.writeEndElement() // premiumRateList
  }
}