urlopen
module
The urlopen
module provides APIs to establish a non-streaming connection
with target servers by HTTP, HTTPS, or IBM® MQ
protocol and open files in the DataPower file system. The APIs can also send and receive IBM MQ messages within a GatewayScript
action.
To access the APIs in the urlopen
module, use the
require('urlopen')
statement, such as var urlopen =
require('urlopen');
.
urlopen
module provides the urlopen.open()
API to conduct
the following behaviors.- When you want to use a user agent to initiate a request for a local service to establish a
connection to the target server dynamically, create a user agent object and use it in the
urlopen.open()
API.- The user agent object is used when the
urlopen.open()
API establishes a connection with the target server by HTTP, HTTPS, or IBM MQ protocol. The UserAgent object is assumed to represent the user agent object. - The HTTP-specific user agent object is used when the
urlopen.open()
API establishes a connection with the target server by HTTP or HTTPS protocol. The HttpUserAgent object is assumed to represent the HTTP-specific user agent object.
- The user agent object is used when the
- Establish a connection with the target server by HTTP, HTTPS, or IBM MQ protocol.
- After connections are established, the response from the target server is handled by the
callback parameter of the
urlopen.open()
API.- When errors occurs, the
urlopen.open()
API can receives error codes that provide information to help you recover from errors. - You can obtain the data by using a read API that is supported by the
response
object. Theresponse
object is assumed to be initialized by theurlopen.open()
API. The read APIs includeresponse.readAsBuffer()
,response.readAsBuffers()
,response.readAsXML()
, andresponse.readAsJSON()
.
- When errors occurs, the
- Open files in the DataPower file system.
UserAgent
object
urlopen.open()
API.When the GatewayScript file that includes the
urlopen.open()
API is called by the GatewayScript action, the GatewayScript user
agent property overrides the specific property that is configured in the user agent for the XML
manager or by variables. The specific property has the same functionality as the property of the
UserAgent object.
Class constructor for creating the UserAgent object: urlopen.UserAgent class constructor
APIs for managing the UserAgent object: UserAgent APIs
urlopen.UserAgent
class constructor
urlopen.UserAgent()
class constructor to create a
UserAgent user agent object.new urlopen.UserAgent()
Creates and initializes a UserAgent user agent object. The
UserAgent object is used when the urlopen.open()
API establishes
a connection with the target server by HTTP, HTTPS, or IBM MQ protocol.
Syntax
new urlopen.UserAgent([ua_options])
ua_options | A JSON object. |
Parameter
ua_options
parameter can include the following property. Invalid properties
make the new urlopen.UserAgent()
constructor throw exceptions. If you do not
specify the ua_options
parameter, the default value of the following property
applies for the created UserAgent object.persistentConnection
- Controls whether to prevent persistent connection. Set the
persistentConnection
property to false to prevent persistent connections. By default, thepersistentConnection
property value istrue
, which indicates that persistent connections are supported with an idle timeout set to 15 seconds.The
persistentConnection
property in a GatewayScript file overrides thevar://local/_extension/prevent-persistent-connection
variable.
Example
UserAgent
object.var urlopen = require(’urlopen’);
var UserAgent = new urlopen.UserAgent({persistentConnection: false});
UserAgent APIs
The UserAgent object provides the following APIs to manage the user agent.
urlopen.UserAgent()
class constructor.UserAgent.prototype.get()
Returns a specific property value of the UserAgent object or returns the UserAgent object.
Syntax
UserAgent.prototype.get([name])
name | The property name in the
UserAgent object. The valid property name is
persistenConnection . |
undefined
is returned.UserAgent.prototype.set()
Configures a specific property of the UserAgent object.
Syntax
UserAgent.prototype.set(name, value)
UserAgent.prototype.set({name: value})
name | The property name in the
UserAgent object. The valid property is defined in the
ua_options parameter of the urlopen.UserAgent()
API. |
value | The value to assign to the property. |
HttpUserAgent object
urlopen.open()
API.When the GatewayScript file that includes the
urlopen.open()
API is called by the GatewayScript action, the GatewayScript user
agent property overrides the specific property that is configured in the user agent for the XML
manager or by variables. The specific property has the same functionality as the property of the
HttpUserAgent object.
Class constructor for creating the HttpUserAgent object: urlopen.HttpUserAgent class constructor
APIs for managing the HttpUserAgent object: HttpUserAgent APIs
urlopen.HttpUserAgent
class constructor
urlopen.HttpUserAgent
class is derived from the
urlopen.UserAgent
class. Use the urlopen.HttpUserAgent()
class
constructor to create and initialize an HTTP-specific HttpUserAgent user agent
object.new urlopen.HttpUserAgent()
Creates and initializes an HTTP-specific HttpUserAgent user agent
object. The HttpUserAgent object is used when the urlopen.open()
API establishes a connection with the target server by HTTP or HTTPS protocol.
Syntax
new urlopen.HttpUserAgent([ua_options])
ua_options | A JSON object that consists of properties that are specific to HTTP or HTTPS protocol. |
Parameter
ua_options
parameter can include the following properties. You might not
define all properties. Invalid properties make the urlopen.HttpUserAgent()
constructor throw exceptions. If you do not specify the ua_options
parameter, the
default values of the following all properties apply for the created
HttpUserAgent object.allowCompression
- Controls whether to allows compression of outbound results and, if the underlying protocol
supports compression, negotiate the compression of the returned document. For HTTP or HTTPS, the
content-encoding and accept-encoding
headers are compression targets. The
allowCompression
property is Boolean data type. By default, the value isfalse
, which means that compression is disabled.The
allowCompression
property used in GatewayScript file overrides thevar://local/_extension/allow-compression
variable and the Allow Compression property that is configured in the user agent for the XML manager. followRedirect
- Controls whether HTTP or HTTPS redirect messages can be followed. The
followRedirect
property is Boolean data type. By default, the value istrue
, which means that redirect messages are followed. To prevent HTTP or HTTPS redirects, set thefollowRedirect
property tofalse
.The
followRedirect
property in a GatewayScript file overrides thevar://local/_extension/donot-follow-redirect
variable. http10Only
- Controls whether the HTTP or HTTPS protocol is restricted to version 1.0. The
http10Only
property is Boolean data type. By default, the value isfalse
, which means that protocol is not restricted to version 1.0. To prevent HTTP version 1.1, set thehttp10Only
property totrue
.The
http10Only
property used in GatewayScript file overrides thevar://local/_extension/http-10-only
variable and the Restrict to HTTP 1.0 property that is configured in the user agent for the XML manager. keepPayload
- Controls how to handle payloads for GET, DELETE, or HEAD requests. The
keepPayload
property is Boolean data type. By default, the value isfalse
.- When the value is
false
, ignores the given payload when sending the GET, DELETE, or HEAD method. - When the value is
true
, sends the given payload when sending the GET, DELETE, or HEAD method.
- When the value is
persistentConnection
- Controls whether to prevent persistent connection. Set the
persistentConnection
property to false to prevent persistent connections. By default, thepersistentConnection
property value istrue
, which indicates that persistent connections are supported with an idle timeout set to 15 seconds.The
persistentConnection
property in a GatewayScript file overrides thevar://local/_extension/prevent-persistent-connection
variable. maxRedirects
- Specifies the maximum number of HTTP or HTTPS redirect messages to receive before the DataPower® Gateway declares the target server unreachable.
Enter a value in the range 0 - 128. The default value is 8.
The
maxRedirects
property used in GatewayScript file overrides the Maximum Redirects property that is configured in the user agent for the XML manager. rewriteHost
- Controls whether to rewrite the HTTP or HTTPS
Host
header. TherewriteHost
property is Boolean data type. By default, the value isfalse
, which prevents the rewriting of theHost
header. When the value isfalse
, theHost
header that is defined in theheaders
property of theoptions
parameter inurlopen.open()
API takes effect.When the value is
true
, theHost
header is rewritten although thevar://local/_extension/donot-rewrite-host
variable istrue
. TherewriteHost
property used in GatewayScript file overrides thevar://local/_extension/donot-rewrite-host
variable.
Example
HttpUserAgent
object.var urlopen = require(’urlopen’);
// define the http-specific user agent properties
var ua_options = {
'persistentConnection': false,
'allowCompression': true,
'followRedirect': flase,
'maxRedirects': 16,
'http10Only': true,
'rewriteHost': false
};
var HttpUserAgent = new urlopen.HttpUserAgent(ua_options);
HttpUserAgent APIs
The HttpUserAgent object provides the following APIs manage the HTTP-specific user agent.
urlopen.httpUserAgent()
class constructor.HttpUserAgent.prototype.get()
Returns a specific property value of the HttpUserAgent object or returns the HttpUserAgent object.
Syntax
HttpUserAgent.prototype.get([name])
name | The property name in the
HttpUserAgent object. The valid properties are defined in the
ua_options parameter of the urlopen.HttpUserAgent()
API. |
undefined
is returned.HttpUserAgent.prototype.set()
Configures a specific property of the HttpUserAgent object.
Syntax
HttpUserAgent.prototype.set(name, value)
HttpUserAgent.prototype.set({name: value})
name | The property name in the
HttpUserAgent object. The valid properties are defined in the
ua_options parameter of the urlopen.HttpUserAgent()
API. |
value | The value to assign to the property. |
urlopen.open()
to connect with target servers
The urlopen.open()
API can establish a nonstreaming connection with
target servers. The urlopen.open()
API can configure a user agent to initiate a
request for a local service to establish a connection to the target server.
Syntax
var urlopen = require('urlopen'); urlopen.open(options, callback);
options | Several properties that are grouped as a JSON object or a single URL specification for a target server. |
callback | Specifies an asynchronous function to be called after the
urlopen.open() connects to the target, sends the data to the target, and the
response header is parsed. The callback is in the function (error, response) { }
form. |
Parameters
- options
- Consists of a single URL specification or a set of properties that are grouped as a JSON object
for a target server.
- The URL of the target server as a string. For
example:
urlopen.open('http://example.com/mydoc.json', callback)
- A set of properties as a JSON object.
target:
- The URL of the target server as a string. For
example:
target: 'http://example.com/test.xml'
method:
- The HTTP method as a string:
get
,delete
,head
,patch
,post
, orput
. For example:method: 'post'
headers:
- A JSON object that contains the headers that are sent to the target. For
example:
headers: {Accept: 'text/plain', 'Accept-Charset': 'utf-8' }
contentType:
- The data content type as a string. For
example:
contentType: 'application/json'
timeout:
- An integer timeout for the attempt to establish the connection in seconds. For a successful
connection, this time includes the time for the read API to take place. For
example:
timeout: 60
sslClientProfile:
- The SSL client profile as a string, as defined on the DataPower Gateway. This parameter is required for requests to
handle the client side of the SSL handshake with the HTTPS server. For
example:
Using thesslClientProfile: 'sslClientProfileName'
sslClientProfile
and thesslProxyProfile
properties together in the sameurlopen
call results in an exception. sslProxyProfile:(deprecated)
- The SSL proxy profile as a string, as defined on the DataPower Gateway. This parameter is required for requests to
handle the client side of the SSL handshake with the HTTPS server. For
example:
Using thesslProxyProfile: 'sslProxyProfileName'
sslProxyProfile
and thesslClientProfile
properties together in the sameurlopen
call results in an exception. data:
- The data sent to the target when the method is POST or PUT. For other methods, the
data
property is ignored. The following data types are supported.- A string that is encoded as UTF-8 before it is sent to the target.
- A buffer that consists of the bytes in the buffer.
- A buffers object that is sent to the target.
- xml_node that is converted to an XML string that is converted to UTF-8 encoding.
- xml_nodelist that is converted to an XML string that is converted to UTF-8 encoding.
- For all other types (such as object or primitive types like Boolean), the data is converted to a UTF-8 encoded JSON string before it is sent to the target.
agent:
- A UserAgent user agent object or an HTTP-specific HttpUserAgent user agent object that can initiate a request for a local service to establish a connection to the specified target server dynamically.
- The URL of the target server as a string. For
example:
- callback
- Specifies an asynchronous function to call after the
urlopen.open()
connects to the target, sends the data to the target, and parses the response header. The callback is in thefunction (error, response) { }
form. When a method has no response, use only the error object in the callback function; that is,function(error)
.error
- An instance of the GatewayScript error object, which extends the ECMA error object. If no error
occurs, the error variable is
null
. The error object containsurlopen.open()
errors. These errors are due to a problem with establishing the connection or with formatting the request. Make them visible (for example, by logging the error detail) to enable error recovery. Automatic recovery is not possible.
response
- An instance of the response object that is initialized by the
urlopen.open()
API. The response is read by a read API to obtain the data. The response status code, the response reason phrase, and all response headers are provided in the response object.
The URL of the target server supports HTTP, HTTPS protocols. For HTTPS protocol, ensure that the validation credentials in the SSL profile contains the correct authority. The authority is either the server-side certificate or the intermediate certificate authority for the target server.
response
object is initialized by the urlopen.open()
API.response.readAsBuffer()
response.readAsBuffers()
response.readAsJSON()
response.readAsXML()
When HTTP or HTTPS urlopen.open()
call completes, the connection to the target
is disconnected. When there is an error, the connection closes automatically. Extra action is not
needed to close a connection. The response.discard()
and
response.disconnect()
APIs can discard data and disconnect an open connection.
Examples
- Open a connection and read the response as a buffer
object.
var urlopen = require('urlopen'); var options = { target: 'http://example.com/mydoc.json', method: 'post', headers: { 'X-My-Header1' : 'value1' , 'X-My-Header2' : 'value2' }, contentType: 'text/plain', timeout: 60, sslClientProfile: 'alice-sslproxy-forward-trusted', data: "Hello DataPower GatewayScript"}; urlopen.open(options, function(error, response) { if (error) { // an error occurred during the request sending or response header parsing session.output.write("urlopen error: "+JSON.stringify(error)); } else { // get the response status code var responseStatusCode = response.statusCode; var responseReasonPhrase = response.reasonPhrase; console.log("Response status code: " + responseStatusCode); console.log("Response reason phrase: " + responseReasonPhrase); // reading response data response.readAsBuffer(function(error, responseData){ if (error){ throw error ; } else { session.output.write(responseData) ; } }); } });
- Use the HTTP-specific
HttpUserAgent
user agent object to establish a connection to the target server and read the response as a buffer object.var urlopen = require(’urlopen’); // define the http-specific user agent properties var ua_options = { 'persistentConnection': true, 'allowCompression': false, 'followRedirect': true, 'maxRedirects': 8, 'http10Only': false, 'rewriteHost': false }; var HttpUserAgent = new urlopen.HttpUserAgent(ua_options); // define the urlopen options var options = { target: 'http://127.0.0.1:42410/echo', //If the target is HTTPS like 'https://127.0.0.1:42409/echo', supply a sslClientProfile //sslClientProfile: 'alice-sslClient' method: 'post', headers: { 'X-My-Header1' : 'value1', 'X-My-Header2': 'value2' }, contentType: 'application/json', timeout: 60, data: "Hello DataPower GatewayScript", agent: HttpUserAgent }; urlopen.open(options, function(error, response) { if (error) { // an error occurred during the request sending or response header parsing session.output.write("urlopen error: "+JSON.stringify(error)); } else { // get the response status code var responseStatusCode = response.statusCode; var responseReasonPhrase = response.reasonPhrase; console.log("Response status code: " + responseStatusCode); console.log("Response reason phrase: " + responseReasonPhrase); // reading response data response.readAsBuffer(function(error, responseData){ if (error){ throw error ; } else { session.output.write(responseData) ; } }); } });
urlopen.open()
to open files on the DataPower Gateway
The urlopen.open()
API to open files in the DataPower file
system.
Syntax
var urlopen = require('urlopen'); urlopen.open(options, callback);
options | A set of properties that are grouped as a JSON object or a single URL specification for a target file. |
callback | Specifies an asynchronous function to be called after the
urlopen.open() connects to the target, sends the data to the target, and the
response header is parsed. The callback is in the function (error, response) { }
form. |
Parameters
- options
-
- The URL of the target file as a string.
For example,
urlopen.open('local:///test.xml', callback)
. In this case, themethod
defaults to theGET
method. - A set of properties as a JSON object. Only the following properties are valid.
target:
- The URL of the target file as a string. For
example:
target: 'local:///test.xml'
method:
- The only supported method is
GET
. This property is optional.
- The URL of the target file as a string.
- callback
- The callback function is the same as the
callback
parameter of theurlopen.open()
API.
The urlopen.open()
API opens files that are specified with the
target
property. The target can receive remote or local file content. Local file
access is distinguished by the properties
used.
- You can access files with the
target
property according to your permissions in thelocal:
,store:
, andtemporary:
protocol schemes. - Protocol scheme specifications are lowercase. For example,
local:
is valid. Uppercase and mixed-case forms are not correct. - File references are case-sensitive. For example,
local:///myArea/myFile.XML
is different fromlocal:///myArea/myFile.xml
. - Typically you can use the shortened, URL form of the
urlopen.open()
API, providing the local file in place of the URL.
Examples
- Access
mylocal_file.xml
inlocal:///mylocal_directory
, read the response as a Buffer object, and write the data to the output context.var urlopen = require('urlopen'); urlopen.open("local:///mylocal_directory/mylocal_file.xml", function (error, response) { if (error) { session.output.write("openCallback error: " + error.errorMessage+"\n"); } else { if (response.statusCode == 200) { // You have a 200, so you can read the file response.readAsBuffer (function (error, data) { session.output.write(data); }); } } });
- Attempt to access a nonexistent file returns a
404 File not found
status code.var urlopen = require('urlopen'); urlopen.open("local:///nonexisting.txt", function (error, response) { if (error) { session.output.write("openCallback error: " + error.errorMessage+"\n"); } else { if (response.statusCode != 200) { // in this case, a non-200 statusCode indicates a problem reading the file session.output.write("Unable to open the file, statusCode: " + response.statusCode + ", reasonPhrase: " + response.reasonPhrase); response.disconnect(); // Optional: You can call response.disconnect() // to do an explicit disconnection. Without this // call, urlopen does an implicit disconnection } else { response.readAsBuffer(function(readError, data) { if (readError) { session.output.write("read file error: " + readError.toString()); } else { session.output.write(data); } }); } } });
- Use a JSON object to specify the
options
parameter of theurlopen.open()
API.var urlopen = require('urlopen'); var open_options = { // the target URL target: 'local:///mylocal_directory/mylocal_file.xml', // method is optional, default is GET method: 'GET' }; urlopen.open(open_options, function (error, response) { if (error) { session.output.write("openCallback error: " + error.errorMessage+"\n"); } else { if (response.statusCode != 200) { // in this case, a non-200 statusCode indicates a problem reading the file session.output.write("Unable to open the file, statusCode: " + response.statusCode + ", reasonPhrase: " + response.reasonPhrase); response.disconnect(); // optional, urlopen will do an implicit disconnect() } else { response.readAsBuffer(function(readError, data) { if (readError) { session.output.write("read file error: " + readError.toString()); } else { session.output.write(data); } }); } } });
urlopen.open()
formats for IBM MQ messages
The urlopen.open()
API can send and receive IBM MQ messages within a GatewayScript action either
dynamically or statically. You can use a URL dynamically created by various properties that are
defined in the options
parameter of the urlopen.open()
API
specific to IBM MQ protocols. You can also use a
fully specified URL that can be defined in the options
parameter of the
urlopen.open()
API or the non-options specification.
Syntax
var urlopen = require('urlopen'); var options = { target: targetURL, data: message, headers: mqHeaders, agent: UserAgent, parameter1: parameter_value1, parameter2: parameter_value2 : parametern: parameter_valuen} ; var mqHeader = { "MQMD" : { "Version" : { $ , "1" }, "Format" : { $ , "MQSTR" } } }; urlopen.open(options, callback) ;
var urlopen = require('urlopen'); urlopen.open(targetURL, callback) ;
mqHeaders | The mqHeader identifies one or more header_name properties (such as, MQMD) and an associated header value containing a set of header_fields related to the specified header. The header may be specified as a JSON object or as an XML string. |
targetURL | The name of the IBM MQ URL for this urlopen call.
The protocol can be dpmq or mq . If targetURL is
specified as a JSON property, the URL can be complete or partial. Parameter properties in the JSON
object provide more specifications. |
UA | A UserAgent user agent object that can initiate a request for a local service to establish a connection to the specified target server. |
options | Consists of properties that are used to
specify IBM MQ behavior. The properties for
GatewayScript are the same as correspondent attributes of the dp:url-open extension
element. This includes the static and dynamic attributes for an IBM MQ queue manager. The list of properties
available are those from the query parameters and dynamic mq:/// queue manager
attributes of the dp:url-open
IBM MQ extension
element. |
callback | Specifies an asynchronous function to be called after the
urlopen.open() connects to the target, sends the data to the target, and the
response header is parsed. The callback is in the function (error, response) { }
form. |
- For more information about
options
, refer tourlopen.open()
, andurl-open()
generic and IBM MQ specific extension elements. - The IBM MQ disconnection is based on the cache timeout property of the queue manager.
- In GatewayScript, the
options
parameter takes the form of a JSON object that specifies a keyword and a value (parameter: value
). The properties contained inoptions
are not case-sensitive. In XSLT, the properties contained inoptions
take the form of parameters assigned values (parameter=value
). For some properties contained inoptions
, any value for the property defines its behavior. To not use this behavior, do not include this property. For more information, see theurl-open()
IBM MQ extension element topic. - The non-options form is provided for consistency with other
urlopen.open
protocols. However, it has limited usefulness because of the default MQMD header and an inability to specify message content. - GatewayScript uses the camel case naming format for attributes and parameters. The parameters
are for static and dynamic IBM MQ URLs. The
attributes specify queue manager connection properties for dynamic IBM MQ URLs. For a list and description of these
parameters, see
url-open
in the IBM MQ documentation.- Attributes
userName
,channelName
,channelTimeout
,channelLimit
,size
,mqcspUserId
,mqcspPassword
- Parameters
requestQueue
,replyQueue
,timeOut
,transactional
,sync
,gmo
,pmo
,parseHeaders
,setReplyTo
,asyncPut
,browse
,contentTypeHeader
,contentTypeXPath
,parseProperties
,publishTopicString
,selector
,subscribeTopicString
,subscriptionName
- If the MQMD header is not defined in the
options.headers
, then a default MQMD header is used. The MQMD default has aMsgType
field of 8. This usage implies that a datagram is used and no reply is expected. For more information about MQMD defaults and other parameter descriptions, refer to the IBM MQ documentation and search for MQMD. - The
options
parameter can be specified either individually or on the target URL. For example, the followingoptions
definitions are equivalentoptions = { target: 'dpmq://' + session.parameters.qm + '/?', requestQueue: session.parameters.requestQAlwaysReply, replyQueue: session.parameters.replyQ, transactional: true, sync: true, timeOut: 10000, headers: { ... }, data: putData };
and
options = { target: 'dpmq://' + session.parameters.qm + '/?RequestQueue=' + session.parameters.requestQAlwaysReply + ';ReplyQueue=' + session.parameters.replyQ + ';Transactional=true;Sync=true;TimeOut=10000', headers: { ... }, data: putData };
Specifying a property both individually and on the target URL results in an exception.
- Status codes that are returned by IBM MQ.
- 0
- Successful return.
- 2xxx
- Error return.
- For more information about IBM MQ headers,
refer to the IBM MQ documentation and search for
MQMD
. Alternatively access the IBM MQ documentation in IBM Knowledge Center and search fordata types that are used in the MQI
.
Considerations for MQ headers
- The IBM MQ protocol headers for a
transactions must be read or manipulated like other service-specific protocol headers. A
require('header-metadata')
statement is needed for access to the headers. You must have arequire
statement specifically in two cases.- For messages that are read by the IBM MQ handler.
- For messages where the request rule routing destination is an IBM MQ URL.
Headers for a
urlopen.open()
statement are specified within anoptions
JSON object and they do not require theheader-metadata
statement. - There is no non-options format for setting IBM MQ headers.
- IBM MQ headers that you specify must confirm
for the structure of the header that is being addressed. Some headers are more complicated to
specify than others. For example, the
MQMD
header can have various fields specified.var mqmd = { "MQMD": { "StructId": {"$":"MD"}, "Version": {"$":"1"}, "Report": {"$":"0"}, "MsgType": {"$":"8"}, "Expiry": {"$":"-1"}, "Feedback": {"$":"0"}, "Encoding": {"$":"546"}, "CodedCharSetId": {"$":"819"}, "Format": {"$":"MQSTR"}, "MsgId": {"$":"414d5120514d5f4a494d5f3130303530011cdf47020a0020"}, "CorrelId": {"$":"000000000000000000000000000000000000000000000000"}, "BackoutCount": {"$":"0"}, "ReplyToQ": {"$":""}, "ReplyToQMgr": {"$":"QM1"}, "UserIdentifier": {"$":"mqm"}, "AccountingToken": {"$":"0431303031000000000000000000000000000000000000000000000000000006"}, "ApplIdentityData": {"$":""}, "PutApplType": {"$":"6"}, "PutApplName": {"$":"putfile"}, "ApplOriginData": {"$":""} } }; var mqHeader = { "MQMD" : mqmd };
More complicated headers (such as the
MQRFH
andMQRFH2
headers) require more structure. For example, theMQRFH
header requires that theNameValueString
to be a JSON object that contains a name value list.var mqrfh = { "MQRFH": { "Format": { "$": "MQSTR" }, "NameValueString": { "NameValue": [ // Note, the NameValue value uses brackets to represent an array { "Name": {"$": "name1"}, "Value": {"$": "value1"} }, { "Name": {"$": "name2"}, "Value": {"$": "value2" } } ] } } }; var mqHeader = { "MQRFH" : mqrfh };
Examples
- Sample call to
MQ
in theoptions
JSON object format. Theheaders
label information in theoptions
object is in a different format from the information for the other labels.var urlopen = require ('urlopen'); var putData = '<MQRequest>Hello World</MQRequest>'; var options = { target: 'mq://192.0.2.0:1414?QueueManager=QM1;UserName=mqm;Channel=QM1.SVRCONN;ChannelTimeout=10;' + 'channelLimit=100;Size=1024000;RequestQueue=queue1;ReplyQueue=queue2', data : putData, headers : { MQMD : { // JSON object for specified header_name MQMD: { // JSON object for the MQMD header StructId : { $ : 'MD' } , Version : { $ : '1'} , } } } }; urlopen.open (options, function (error, response) {} );
- An example shows how more complicated IBM MQ
headers are set and
used.
var urlopen = require('urlopen'); var putData = '<MQRequest>Hello World</MQRequest>'; var urlopenHeaders = { // supply an MQMD header MQMD : { // This MQMD is the header name. MQMD: { // JSON object for the MQMD header StructId : { $ : 'MD' }, Version : { $ : '1' }, Format : { $ : 'MQHRF2' }, MsgType : { $ : '1' }, ReplyToQMgr : { $ : session.parameters.qm }, ReplyToQ : { $ : session.parameters.replyQ }, Expiry : { $ : '10000' }, Persistence : { $ : '1' }, Priority : { $ : '10' }, PutApplType : { $ : '6' }, PutApplName : { $ : 'My Datapower IBM MQClient' }, ApplOriginData : { $ : 'testUrlOpenMPGW' }, ApplIdentityData : { $ : 'mqUrlOpenDemo.js' } } }, // supply an MQRFH2 header MQRFH2 : { MQRFH2: { Format: { $ : 'MQSTR' }, NameValueData: { NameValue: [ { mcd : { property1 : { $ : '1111' } } }, { jms : { property2 : { '@dt': 'string', $ : 'value2'} } }, { usr : { group : { property3 : { $ : 'value3' }, property4 : { $ : 'value4'} } } } ] } } } }; var options = { target : 'dpmq://' + session.parameters.qm + '/?RequestQueue=' + session.parameters.requestQ, headers : urlopenHeaders, data : putData, replyQueue : session.parameters.replyQ, pmo : 2052 // MQPMO_NO_SYNCPOINT (4) + MQPMO_SET_ALL_CONTEXT (2048) }; try { urlopen.open(options, function(connectError, response) { if (connectError) { var errorMessage = connectError + 'errorCode=' + connectError.errorCode.toString(16); console.error(errorMessage); session.output.write(errorMessage); } else { var responseCode = response.statusCode; if (responseCode == 0) { console.info('Received MQ ' + response.statusCode + ' for target ' + options.target); response.readAsXML(function(readAsXMLError, xmlDom) { if (readAsXMLError) { var errorMessage = 'Error on readAsXML: ' + readAsXMLError; console.error(errorMessage); response.readAsBuffer(function(readAsBufferError, buffer) { if (readAsBufferError) { var errorMessage = 'Error on readAsBuffer: ' + readAsBufferError; console.error(errorMessage); session.output.write(errorMessage); } else { console.info('MQ Response headers: ' + response.headers); session.output.write(buffer); } }); } else { console.info('MQ Response headers: ' + response.headers); session.output.write(xmlDom); } }); } else { var errorMessage = 'Received MQ ' + response.statusCode + ' for target ' + options.target; session.reject(errorMessage); } } }); } catch (err) { var errorMessage = 'Thrown error on urlopen.open for target ' + options.target + ': ' + err.message + ', error object errorCode=' + err.errorCode.toString(16); session.reject(errorMessage);}
- An example of how
options
JSON object can be declared for anMQMP
header.var urlopenMQMPHeaders = { // supply an MQMD header MQMD : { // The property name 'MQMD' is the header name. MQMD: { // This 'MQMD' represents the root property. StructId : { $ : 'MD' }, Version : { $ : '2' }, Format : { $ : 'MQSTR' }, MsgType : { $ : '1' }, ReplyToQMgr : { $ : session.parameters.qm }, ReplyToQ : { $ : session.parameters.replyQ }, Expiry : { $ : '10000' }, Persistence : { $ : '1' }, Priority : { $ : '10' }, PutApplType : { $ : '6' }, PutApplName : { $ : 'My Datapower IBM MQClient' }, ApplOriginData : { $ : 'testUrlOpenMPGW' }, ApplIdentityData : { $ : 'testUrlOpen.js' } } }, // supply an MQMP header MQMP : { // The property name 'MQMP' is the header name. MQMP: { // This 'MQMP' represents the root property. Property : [ // an array of property { '@name' : 'car.brand', '@type':'string', $ : 'DataPower'}, { '@name' : 'car.color', '@type':'string', $ : 'GREEN'}, { '@name' : 'car.year', '@type':'int32', $ : '2005' } ] } } }; options = { target: 'dpmq://' + session.parameters.qm + '/?RequestQueue=GATEWAYSCRIPT.PROPERTIES.REQUEST' + ';ReplyQueue=' + session.parameters.replyQ, headers: urlopenMQMPHeaders, data: putData, pmo: 2052 // MQPMO_NO_SYNCPOINT (4) + MQPMO_SET_ALL_CONTEXT (2048)}; };
response
object
The response
object represents the response of a network connection in
the callback function. In all APIs specifications that use the response
object,
where not specified, the response
object is assumed to be initialized by
urlopen.open()
API. The response
object is the second parameter of
the callback
function that is a parameter of the urlopen.open()
API.
response.discard()
Discard the response. This API instructs the urlopen.open()
API to
receive but discard the bytes of the response message efficiently. You can access the header
metadata from the response object. Depending upon the error there might be no error to discard or
disconnect. An important use of discard()
is to obtain the status code of the
failing response.
Syntax
response.discard(function(error) { })
error | The error object in case an error occurs
during the response.discard() API. |
response.disconnect()
No response content is returned. This API instructs the urlopen.open()
API to stop immediately the backend connection. For responses besides IBM MQ responses, this action eliminates the latency
of reading a large payload but it can have adverse affects if persistent connections are
used.
Syntax
response.disconnect()
response.get()
Read the response header.
Syntax
response.get([headername])
response.get(options, headername)
headername | Specify the optional header name to retrieve a specific response header. |
options | A set of properties that are grouped as a JSON object. |
The response.get()
API returns the specific response header when the
headername
parameter is specified. For example, response.get('h1')
retrieves the h1
header, which is equivalent to
response.headers.h1
and response.headers['h1']
.
- If the header name is not provided,
response.get()
is equivalent toresponse.headers
that contains the entire collection of response headers. - The
response.get(headername)
form reads the unstructured (raw) header. Theresponse.get(options, headername)
form reads the structured header as specified by thetype
in the options. For more information about structured and unstructured headers, see the header module.
var urlopen = require('urlopen'); // access the module
urlopen.open (options, function (error, response) {
// get the response as a JSON object representing an MQ header structure
var structured = response.get({type: 'mq'}, 'MQMD');
response.headers
Read the entire collection of response headers into a JSON object.
Syntax
response.headers
response.readAsBuffer()
Read the response into a Buffer object.
Syntax
response.readAsBuffer(function(error, buffer) { })
error | The error object in case an error occurs
during the response.readAsBuffer() API. |
buffer | The buffer location that contains the
data that is read by a successful response.readAsBuffer()
API. |
response.readAsBuffer()
API reads the data as a buffer object. If
reading is successful, the data becomes the value of the buffer variable buffer.
Otherwise, a GatewayScript error object error describes the error.response.readAsBuffers()
Read the response into a Buffers object.
Syntax
response.readAsBuffers(function(error, buffers) { })
error | The error object in case an error occurs
during the response.readAsBuffers() API. |
buffers | The Buffers object containing the data
that is read by a successful response.readAsBuffers()
API. |
response.readAsBuffers()
API reads the data as a Buffers object. If
reading is successful, the data becomes the value of the Buffers variable
buffers. Otherwise, a GatewayScript error object error
describes the error.response.readAsJSON()
Read the response into a JSON object.
Syntax
response.readAsJSON(function(error, json) { })
error | The error object in case an error occurs
during the response.readAsJSON() API. |
json | The JSON object that contains the data
that is read by a successful response.readAsJSON()
API. |
response.readAsJSON()
API reads the data and parses it into a JSON
object. If reading is successful, the data becomes the value of the JSON variable
json. Otherwise, a GatewayScript error object error describes
the error.response.readAsXML()
Read the response into an XML object.
Syntax
response.readAsXML function(error, xml) { })
error | The error object in case an error occurs
during the response.readAsXML() API. |
xml | The XML object that contains the data that
is read by a successful response.readAsXML() API. |
response.readAsXML()
API reads the data as a
NodeList
. If reading is successful, the data becomes the value of the
NodeList
variable nodelist. Otherwise, a GatewayScript error
object error describes the error.response.reasonPhrase
Reads the reason phrase from the urlopen.open()
response. Reason phrases
are only available for HTTP targets.
response.statusCode
Reads the status code from the urlopen.open()
response.
response.types
Returns an array of supported structure types of the urlopen.open()
response headers.
var urlopen = require('urlopen');
var options = {
target: 'dpmq://qmgr/?RequestQueue=q1',
// Note that inMQMD and inMQRFH2 headers are in the same format
// as shown in urlopenMQMPHeaders in a previous example.
headers: {
'MQMD': inMQMD,
'MQRFH2': inMQRFH2
},
} ;
urlopen.open (options, function (error, response) {
// consume response MQMD header as JSON
var outMQMD = response.get({type: 'mq'}, 'MQMD');
// returns ['mq']
var types = response.types;
...
});