cancel
Showing results for 
Search instead for 
Did you mean: 

Groovy script udf to handling script length

learninghubx01
Explorer
0 Kudos

Hello Experts,

We have mapping requirement to check for the length of the  string of a array field. If it is a greater than 13, trim it to 13 and if it is empty or less than 13, send as it is.

I tried to write a code as below , it is not working. I'm getting the error.

 

The root message is: Exception:[com.sap.aii.mappingtool.tf7.rt.BehaviorInvocationException: java.lang.ArrayIndexOutOfBoundsException: while trying to load from index 1 of an object array with length 1, loaded from local variable 'a'] in class com.sap.aii.mappingtool.tf7.ScriptHandler method StringLen[[Ljava.lang.String;@6a975eaf, com.sap.aii.mappingtool.tf7.rt.ResultListImpl@27bbd186, com.sap.xi.mapping.camel.impl.MappingContextImpl@68693cd6, com.sap.aii.mappingtool.tf7.rt.Context@79fb94ab] on the exchange: Exchange[D10647C5A5BE62C-0000000000000003]

 

 

import com.sap.it.api.mapping.*;
def void StringLen(String[] arg1, Output output, MappingContext context)
{
def str = arg1[0]
for (int i = 0; i < str.length(); i++)
if(str[i].length() >= 13)
{
output.addValue(arg1[i].substring(0,12))
}
else
{
output.addValue(arg1[i])

}
}

Accepted Solutions (1)

Accepted Solutions (1)

Edrilan_Berisha
Product and Topic Expert
Product and Topic Expert
0 Kudos

Hi learninghubx01,

 

there are different options to your problem.

You can either do the following:

 

def str = arg1[0]
def output = str[0..10]
//strings are considered like arrays in groovy. So with this it's always truncated. You do not need your for loop with a lot of logic to add it to the output....

 

 

or you make use of the take() method:

 

 

def str = arg1[0]
def output = str.take(10)

 

 

I think it's better than what you try to do, where you would also need to handle different exceptions like, what if the string is not even 10 characters long, etc. because this is what your coding is missing.

 

Best,

Edrilan Berisha

SAP S/4HANA Cloud Financials Development

SATHEESHKUMAR_1
Explorer
0 Kudos

hi learninghubx01 ,

Below code will work for you

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

def void StringLen(String[] arg1, Output output, MappingContext context) {
    if (arg1 != null && arg1.length > 0) {
        def str = arg1[0]
        for (int i = 0; i < arg1.length; i++) { 
            if (arg1[i].length() >= 13) {
                output.addValue(arg1[i].substring(0, 13))
            } else {
                output.addValue(arg1[i])
            }
        }
    }
}

Regards,

Satheesh Kumar. 

Answers (0)