cancel
Showing results for 
Search instead for 
Did you mean: 

Groovy script mapping

vijender_p
Active Participant
0 Kudos

HI Experts,

Can you please suggest me any blog/scenario for Creating groovy script mapping into a target hierarchal structure if you have already done that.

Regards,

Accepted Solutions (0)

Answers (2)

Answers (2)

vijender_p
Active Participant
0 Kudos

HI Morten Wittrock,


Thanks a lot for your reply ! It will be really apprecited if you could help me in the which the groovy script can be used as one to one mapping from source to target for the strcuture

MortenWittrock
Active Contributor
0 Kudos

Hi Vijender

I'm afraid I don't quite follow. Using Groovy for mapping is about those two activities I described, and showed you code samples for.

Also, please note that you are replying to your own question right now, instead of commenting on my answer.

Regards,

Morten

MortenWittrock
Active Contributor
0 Kudos

Hi Vijender

It's not really complicated. There are two steps to it:

  1. Parsing the current message body
  2. Creating a new message body

Assuming the content is XML, step 1 is XML parsing and step 2 is building an XML document.

Parsing XML

To parse XML in Groovy, you have the groovy.util.XmlSlurper class available. In the following example, I'll be parsing this simple document:

<lines>
   <line>
      <num>10</num>
   </line>
   <line>
      <num>20</num>
   </line>
   <line>
      <num>30</num>
   </line>
</lines>

Here's a short code snippet that parses the document and sums up the numbers:

import groovy.util.XmlSlurper

def lines = new XmlSlurper().parseText('<lines><line><num>10</num></line><line><num>20</num></line><line><num>30</num></line></lines>')

def sum = 0

lines.line.num.each { num -> sum += num.text() as Integer }

println sum

To parse the message body, you would instead run:

new XmlSlurper().parseText(message.getBody(java.lang.String))

You can read more about XML parsing in Groovy here.

Building an XML document

With Groovy's groovy.xml.MarkupBuilder class, building an XML document is really easy. Here's a piece of code that generates a simple document and replaces the message body with it:

import com.sap.gateway.ip.core.customdev.util.Message
import groovy.xml.MarkupBuilder

def Message processData(Message message) {
   def sw = new StringWriter()
   def builder = new MarkupBuilder(sw)
   builder.xmldoc {
      message("Hello, world!")
   }
   message.setBody(sw.toString())
   return message
}

The code generates the following XML:

<xmldoc>
  <message>Hello, world!</message>
</xmldoc>

More MarkupBuilder examples can be found here.

So, what you need to do now, is combine the two techniques, and implement your specific requirements.

Have fun,

Morten