cancel
Showing results for 
Search instead for 
Did you mean: 
Read only

Groovy CPI: String to Integer

anirban_pwc
Participant
0 Likes
6,245

Hi Experts -

I'm trying to increment a local variable value by 1, but when I read the header value, it maps to a String "value", then I'm trying to cast it to an Integer with the statement:

counter_var = Integer.parseInt(value)

but receiving a Java exception:

java.lang.Exception: java.lang.NumberFormatException: For input string

Please help me resolve this issue.

Thank you,

Anirban

import com.sap.gateway.ip.core.customdev.util.Message
import java.util.HashMap
def Message processData(Message message) {
       //Headers 
       def map = message.getHeaders()
       def value = map.get("INCREMENT")
       if(value == null)
       { 
           def counter_var = 0       
       }
       else 
       {
           counter_var = Integer.parseInt(value)
       }
       
       message.setHeader("INCREMENT", counter_var + 1)
       return message;
}
View Entire Topic
0 Likes

Hi amallick,

  1. As sunny.kapoor2 mentioned Declaration of counter_var should be outside. And
  2. If condition should verify empty string condition as well. - if(value == null || value == "")
  3. It's also better to use an additional condition value.isNumber() == true and handle the case before casting the string to integer. Below Nested condition is just an example. You can make changes and optimize the code as required.
import com.sap.gateway.ip.core.customdev.util.Message;
import java.util.HashMap;

def Message processData(Message message) {
       def map = message.getHeaders()
       def value = map.get("INCREMENT");
       def counter_var;
       if(value == null || value == "")
       { 
         counter_var = 0       
       }
       else 
       {
          if(value.isNumber() == false)
		{
		  //make the counter to zero / raise custom exception / take any other action
		}
	    else
		counter_var = Integer.parseInt(value)
       }
       
       message.setHeader("INCREMENT", counter_var + 1)
       return message;
}