Thursday, 12 August 2021

SAP CPI message mapping groovy script for different scenarios with context handlings



Add all values of the context


import com.sap.it.api.mapping.*;


def void addContext(String[] values, Output output, MappingContext context) {


output.addValue(values.sum{it.toBigDecimal()})

}



Return last value of the context


import com.sap.it.api.mapping.*;

def void returnlast(String[] values, Output output, MappingContext context) {

output.addValue(values.last())

}


Replace Null


import com.sap.it.api.mapping.*;

def String replaceNull(String arg1){

def len = arg1.length()

def output

if (len > 1)

output = arg1

else

output = arg1.replaceAll("","NA")

return output

}



Filter null and Suppress Null:


import com.sap.it.api.mapping.*

def void filterNullAndSuppress(String[] values, Output output, MappingContext context) {
def filtered = values.findAll { v -> v != null && !output.isSuppress(v) }
filtered.each { v -> output.addValue(v) }
}



Remove Suppress:


def void removeSuppress(String[] values, Output output, MappingContext context) {

values.each { v ->

if (!output.isSuppress(v)) {

output.addValue(v)

}
}
}


Find elements incontext that starts with

import com.sap.it.api.mapping.*

def void filterStatus(String[] values, Output output, MappingContext context) {

def filtered = values.findAll { v -> v.startsWith('2') }

filtered.each { v -> output.addValue(v) }

}


Find elements incontext that starts with


import com.sap.it.api.mapping.*

def void filterStatus(String[] values, Output output, MappingContext context) {

def filtered = values.findAll { v -> v.startsWith('1')|| v.startsWith('Z6')}

filtered.each { v -> output.addValue(v.split(/@/)[1]) }

}


Read Value map and store in property


import com.sap.gateway.ip.core.customdev.util.Message;

import java.util.HashMap;

import com.sap.it.api.ITApiFactory

import com.sap.it.api.mapping.ValueMappingApi


def Message processData(Message message) {

//Body

def body = message.getBody(java.lang.String) as String;

def map = message.getProperties();

value=map.get("langcode")



def valueMapApi = ITApiFactory.getApi(ValueMappingApi.class, null)

def lang = valueMapApi.getMappedValue('c4c', 'language', value, 'ymkt', 'lang')

message.setProperty("lang", lang);

return message;

}


Split string with a delimiter


import com.sap.gateway.ip.core.customdev.util.Message;

import java.util.HashMap;

import com.sap.it.api.mapping.*;

def String split(String arg1){

def output = arg1.split("@");

return output[1]

}



To check the input is numeric or not ->returns true or false.


import com.sap.it.api.mapping.*;

def String customFunc(String arg1){

def output = arg1.isNumber()

return output

}

Output payload:

<?xml version="1.0" encoding="UTF-8"?>

 <test>
       <id>true</id>
</test>



No comments:

Post a Comment