Thursday, 21 November 2024

Groovy Script to form the dynamic http query for top and skip

When cant use the ODATA adapter if there is limitation on pulling the records from API

For ODATA - Using looping process can achieve it

For HTTP - there is no easy way so you can use this script and use iterating splitter and gather, in between use the request reply to pull 100, 100 records to get all records.

Groovy script

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

import groovy.xml.*;

import java.text.SimpleDateFormat;

import groovy.json.*;

import groovy.util.*;

import groovy.xml.MarkupBuilder;

def Message processData(Message message) {

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



def headers = message.getHeaders();

def count = headers.get("count");

count = count.toInteger();

// def count = 640;

int chunksize = 100



int iteration = Math.ceil(count / chunksize).toInteger()



StringWriter writer = new StringWriter()

MarkupBuilder xml = new MarkupBuilder(writer)


xml.Nodes {

for(int i=0;i < iteration;i++){

int skip = i * chunksize

println skip

int top = (i == iteration - 1)?(count % chunksize == 0 ? chunksize : count % chunksize): chunksize

//println top

Node {

if (skip == 0) {

query "\$top=${top}"

}

else{

query "\$top=${top}&\$skip=${skip}"

}

}

}
}


def resultXML =writer.toString()

message.setBody(resultXML)

return message;

}

Input => Header => Count =640


Output:


<Nodes>

<Node>

<query>$top=100</query>

</Node>

<Node>

<query>$top=100&amp;$skip=100</query>

</Node>

<Node>

<query>$top=100&amp;$skip=200</query>

</Node>

<Node>

<query>$top=100&amp;$skip=300</query>

</Node>

<Node>

<query>$top=100&amp;$skip=400</query>

</Node>

<Node>

<query>$top=100&amp;$skip=500</query>

</Node>

<Node>

<query>$top=40&amp;$skip=600</query>

</Node>

</Nodes>



No comments:

Post a Comment