How to invoke R script function with JSON payload directly

How to invoke R script function with JSON payload directly

book

Article ID: KB0084250

calendar_today

Updated On:

Products Versions
TIBCO BusinessEvents Enterprise Edition 5.4.0

Description

R script function which takes JSON payload as a parameter directly, e.g.

# Get JSONPayload
# Input:
#    jsonData = a string of JSON data
getJSONPayload <- function(jsonData) {
     parent = fromJSON(jsonData)
     ...
}
How to invoke this function with TIBCO BusinessEvents rulefunction with a JSON payload.
{"parent" : { "Name": "test", "Address": "3301 testRoad" } }"

Environment

All

Resolution

In BE rulefunction, use the following function to invoke an R script function:
Object[] TerrResult = Analytics.Engine.invokeTERRFunction("TerrEngine","getJSONData",jsonData);
While passing JSON data directly to an R script as a parameter, you need to escape the (") inside the payload properly. Invoking the R script function from BE through TERR, there are two jumps:

From BE -> TERR 
then from TERR -> R engine

The payload string as shown in the example, three back slashes are needed to escape a (") properly:
String jsonData = "{\\\"parent\\\" : { \\\"Name\\\": \\\"test\\\", \\\"Address\\\": \\\"3301 testRoad\\\" } }";
Object[] TerrResult = Analytics.Engine.invokeTERRFunction("TerrEngine","getJSONData",jsonData);
If you already have the JSON String converted from other object, you can use the String.format function to escape the (") from the converted payload properly before invoking the TERR function:
			String jsonData = JSON.parseJSON(requestContent);
            String jsonDataFormat = String.replaceAll(jsonData,"\"","\\\\\"");
			Object[] TerrResult = Analytics.Engine.invokeTERRFunction("TerrEngine","getDwellTime",jsonDataFormat);

Issue/Introduction

How to invoke R script function with JSON payload directly.