GatewayScript scenario to route by content type

Sample configuration of GatewayScript that determines the format of message content and the route.

This scenario uses GatewayScript to determine the format of message content, which can be JSON, XML, or non-XML (binary). The message is then routed according to content type. The DataPower® service does the following tasks.
  • Examine the message content to determine type, or format
  • Apply the appropriate message processing policy
  • Route messages to an enterprise HTTP application server for processing
The following figure illustrates the message flow.
Figure 1. Message flow
Image is described in the following text.
Messages flow through the gateway as follows.
  1. Messages arrive at a GatewayScript action ( 1 ) which examines the content and sets a variable that is used by a subsequent Call action. This action also sets the destination for the message.
  2. A Call action ( 2 ) calls a predefined rule for further processing of the message. The variable set in the GatewayScript action determines which rule to call.
  3. The called rule, which can be any one of three possible rules is run.
    • JSON ( 3a )
    • XML ( 3b )
    • Non-XML ( 3c )

Each GatewayScript file in the message processing flow is explained in the following sections.

Initial GatewayScript file

The sample whatisit.js GatewayScript file determines content type of the request and sets critical variables.

After you deploy the sample pattern, the whatisit.js file is in the local: directory.

1 /*
2  * GatewayScript to determine the format of inbound content
3  * Set up appropriate processing paths
4  */
5  var hm = require('header-metadata');
6  var service = require('service-metadata');
7  session.input.readAsJSON (function (readAsJSONError, jsonData) {
8    if (readAsJSONError) {
9      session.input.readAsBuffers(function(readAsBuffersError, data) {
10       if (readAsBuffersError) {
11         console.error('Error on readAsBuffers: ' + readAsBuffersError);
12       } else {
13         if (data.slice(0,5).toString() === '<?xml') {
14           session.INPUT.setVariable('callrule', 'myxmlrule');
15           hm.current.set("Content-type", "text/xml");
16           service.routingUrl = 'http://127.0.0.1:8888/xml/charges';
17         } else {
18           session.INPUT.setVariable('callrule', 'mynonxmlrule');
19           hm.current.set("Content-type", "application/octet-stream");
20           service.routingUrl = 'http://127.0.0.1:8888/csv/charges';
21         } //end xml test
22       } //end read as buffers error
23     }); //end read as buffer function
24   } else {
25     session.INPUT.setVariable('callrule', 'myjsonrule');
26     hm.current.set("Content-type", "text/json");
27     service.routingUrl = 'http://127.0.0.1:8888/json/charges';
28   } // end read as json error
29 }); //end read as json function
The following table explains the GatewayScript calls in the whatisit.js file.
Table 1. Script features
Line Explanation
5 Makes available a library for reading and setting HTTP headers
6 Makes available a library for reading and setting the processing policy service variables
7 This session object call attempts to read the contents of the INPUT buffer (the message that is sent by the client) as JSON
8 Handle the case when call to read as JSON fails
9 Read the INPUT buffer as raw data, rather than a particular format
10 Handle the case when the call to read data fails
11 Raise an error and create a specific log message
13 Check to see whether the data in the buffer starts with the string that identifies the content as XML; use Buffers class method toString to convert to String
14 Set the context variable that determines what rule is called to handle this type of content. The Call action uses this variable
15 Set the outbound HTTP Content-type header
16 Set the variable that determines the destination for the message
18 - 20 Set the HTTP header, context variable, and destination if the content is not XML or JSON
25 - 27 Set the HTTP header, context variable, and destination if the content is JSON
29 Complete the original session call and function

GatewayScript file to process JSON

The sample charges.js GatewayScript file that processes JSON content.

After you deploy the sample pattern, the charges.js file is in the local: directory.

1 /*
2  * GatewayScript to parse JSON file
3  * Modify with additional information from query string
4  */
5  var hm = require('header-metadata');
6  var service = require('service-metadata');
7  session.input.readAsJSON(function (readAsJSONError, data) {
8    if (readAsJSONError) {
9      console.error('Error on readAsJSON: ' + readAsJSONError);
10   } else {
11     var arrayOfObjects = data;
12     // get service variable containing customer number
13     var query = new String(service.URI);
14     var querys = query.split("=");
15     // add the customer number to each object
16     for (var i = 0; i < arrayOfObjects.length; i++) {
17       arrayOfObjects[i]["customer"] = querys[1];
18     } //end for
19     session.output.write(arrayOfObjects);
20   } //end read as json error
21 }); //end read as json function
The following table explains the GatewayScript calls in the changes.js file.
Table 2. JSON script features
Line Explanation
5 Makes available a library for reading and setting HTTP headers
6 Makes available a library for reading and setting the processing policy service variables
7 This session object call attempts to read the contents of the INPUT buffer (the message that is sent by the client) as JSON
8-10 Handle the case when call to read as JSON fails
13 Get the value of the service variable URI to see the query string that is sent by the client
14 Split the query string
15 - 18 Modify the JSON document with values from the query string
19 Write out the modified JSON document

GatewayScript to process non-XML

The sample csver.js GatewayScript file processes comma-separated values (CSV) content with the readAsBuffer function.

After you deploy the sample pattern, the csver.js file is in the local: directory.

1 /*
2  * GatewayScript to read a CSV file
3  * Modify with additional information from query string
4  */
5  var hm = require('header-metadata');
6  var service = require('service-metadata');
7  session.input.readAsBuffer(function (readAsBufferError, data) {
8    if (readAsBufferError) {
9      console.error('Error on readAsBuffer: ' + readAsBufferError);
10   } else {
11     // insert the account # on each line
12     var content = data.toString();
13     var lines = content.split(/\r\n|\n|\r/);
14     // get service variable containing cust #
15     var query = new String(service.URI);
16     var querys = query.split("=");
17     var nlines = "";
18     for (var i = 0; i < lines.length; i++) {
19       nlines += querys[1] + "," + lines[i] + "\r\n";
20     } //end for
21     session.output.write(nlines);
22   } //end read as buffer error
23 }); //end read as buffer function
The following table explains the GatewayScript calls in the csver.js file.
Table 3. CSV script features
Line Explanation
5 Makes available a library for reading and setting HTTP headers
6 Makes available a library for reading and setting the processing policy service variables
7 This session object call attempts to read the contents of the INPUT buffer (the message that is sent by the client)
8-10 Handle the case when call to read the buffer fails
12 Use the Buffer class method toString to convert data to String
15 Get the value of the service variable URI to see the query string that is sent by the client
16 Split the query string
18 - 20 Modify the CSV document with values from the query string
21 Write out the modified CSV document

Importing the sample service

Before you begin

For this procedure, you must use material on the Resource Kit. You can download the Resource Kit from IBM® Fix Central. Enter the search term resourcekit. The results include a link to the most recent version.

Procedure

  1. Log in to the GUI with credentials that can create new services in the domain.
  2. In the search field, enter import.
  3. From the search results, click Import Configuration.
  4. Import the sample configuration file on the Resource Kit at /GatewayScript/Service_ContentDistributor.zip.
    You might need to change the port that is assigned to the HTTP handler to avoid conflicts with existing configurations. The assigned port in the configuration is port 8881.
  5. Use curl or another tool to submit the sample request files charges.jsn, charges.csv, or charges.xml to the sample service. If you did not change the listening port for the HTTP handler, the port is 8881. These files are in the same directory on the Resource Kit at /GatewayScript. Be sure to include the ?customer=445566 query string in the URL.