JSON processing on the IBM Datapower
JSON processing on the IBM Datapower
Starting with firmware version 7.0.0.0, the IBM Datapower supports GatewayScript to transform messages additional to the XSLT transformation language. GatewayScript implements the ECMAScript (JavaScript) 5.1 language specification. For more information refer to the IBM Documentation.
IBM offers a Datapower playground, that you can use to test your GatewayScripts, here.
As GatewayScript is essentially JavaScript it is very well suited to process and transform JavaScript Object Notation (JSON) payloads.
This post shows how you can use GatewayScript to easily read and process JSON payload
Processing JSON configuration file from the filesystem
The following example show how to read a configuration file from the Datapower filesystem:
/*
* Read JSON configuration file from the Datapower filesystem.
*/
var fs = require('fs');
fs.readAsJSON ('local:///Configuration/myConfigFile.json', function (JSONError, json) {
// This is an inline callback function to process the JSON message
if (JSONError) {
// Stop processing on an invalid JSON config file.
session.reject('JSON config file invalid.');
} else {
// Output JSON content to debug log
console.debug(json);
// ... do use useful stuf with your JSON file.
// Output version found in JSON Config file
if ("version" in json) {
console.info(json["version"]);
} else {
console.error("Missing version");
}
// Save JSON config to context so it's available to other scripts.
var myCtx = session.name('myContext') || session.createContext('myContext');
myCtx.setVariable('config', json);
}
});
Note that the readAsJSON method takes a callback function as the second argument which is provided as an inline function here. As it is a callback function beware that the processing will be asynchronous, in your code following the readAsJSON call you cannot assume the JSON processing has occured already or not.
The example code verifies if the input is indeed in JSON format and looks for the version member. The entire JSON configuration file is then stored in myContext.config for further use in other scripts in your processing policy.
Processing the JSON request payload
Similair to the filesystem example you can also access the JSON payload of a request using the readAsJSON method on the session.input object:
var util = require('util');
session.input.readAsJSON (function (readAsJSONError, jsonData) {
if (readAsJSONError) {
// What!? No JSON?
session.reject('Non-JSON message received.');
} else {
// Now process that JSON
// We expect to receive an array with values
if (util.isArray(jsonData)) {
for (var i = 0; i < jsonData.length; i++) {
// Output value member
console.error(jsonData[i].value);
// Do more useful stuff...
}
} else {
session.reject("Invalid message received");
}
}
}); // end of callback function
This example expects JSON payload with an array of objects with a value member:
[
{ "value" : "1" },
{ "value" : "2" }
]