The listenerUtil Object

You can access services, such as retrieving the server host name or IP address, using the listenerUtil JavaScript object. This object is available as you define JavaScript code for your listener execution.
You can access services, such as retrieving the server host name or IP address, using the
listenerUtil
JavaScript object. This object is available as you define JavaScript code for your listener execution.
This object is available from the listener code editor.
In this article:
2
getHostName() Method
You can retrieve the server host name using the
getHostName()
method.
getHostNameAddress() Method
You can retrieve the server IP address using the
getHostAddress()
method.
rest<verb> - Get, Put, Post, Patch, Delete() Method
You can invoke other RESTful services from business logic or row events using the following methods:
listenerUtil.
restGet
(url, params, settings)
listenerUtil.
rest
Put(url, params, settings, requestData)
listenerUtil.
rest
Post(url, params, settings, requestData)
listenerUtil.
rest
Patch(url, params, settings, requestData)
listenerUtil.
rest
Delete(url, params, settings)
In these calls, you pass the URL, parameters, settings, and request data.
restGet() Method
You can retrieve a stringified version of the result of a GET to the specified URL using the
restGet()
method:
var result = listenerUtil.
restGet
(url, params, settings); var myJson = JSON.parse(result);
restGet Example:
var params = { name: "Acme", country: "Elbonia" }; var json = listenerUtil.
restGet
('http://rest.example.com/myservice', params); var resultObject = JSON.parse(json);
The
params
object contains the parameters to the call. This is equivalent to adding these parameters to the URL, for example:
http://rest.example.com/myservice?name=Acme&country=Elbonia
Do not add parameters directly in the URL. Properly encode parameters and pass them in as an object.
The
settings
parameter contains the various settings for the call. It can have the following properties:
  • The
    headers
    setting. Add this setting to the call as HTTP headers. It must include name/value pairs.
    If you want to invoke this function so that you use it to pass the authorization header, this property is required.
    For more information about HTTP headers, see the Wikipedia entry for HTTP Headers.
  • The
    proxy
    setting. This setting ensures that the HTTP call is made using the specified HTTP proxy server. It can include the following properties:
    • hostname
      : Set the value to the host name of the HTTP proxy server.
    • port
      : Set the value to the port number for the HTTP proxy server.
    • username
      : To provide authentication information, set the value to the username for the HTTP proxy server.
    • password
      : To provide authentication information, set the value to the password for the HTTP proxy server.
restGet Example:
The following example converts the
requestData
JavaScript object to JSON before sending it:
You can send only JSON data using this method.
listenerUtil.
restGet
('http://rest.example.com/myservice',
{name: 'Acme', country: 'Elbonia'},
{headers: {
Authorization : "Basic <base64string>",
"Cache-Control" : "no-cache"
},
proxy: {
hostname: "proxy.example.com",
port: 8282
username: "admin2",
password: "password2"
}
});
restPut() Method
You can retrieve a stringified version of the response of a PUT to the specified URL using the
requestData
JSON object, perhaps obtained through the
restGet()
method, using the
restPut()
method:
listenerUtil.
restPut
(url, params, settings, requestData)
Example:
var result = listenerUtil.
restPut
(url, params, settings, requestData); // requestData is a JSON object var myJson = JSON.parse(result);
restPost Method
You can retrieve a stringified version of the response of a POST to the specified URL using the
requestData
JSON object, perhaps obtained through the
restGet()
method, using the
restPost()
method:
listenerUtil.
restPost
(url, params, settings, requestData)
Example:
var result = listenerUtil.
restPost
(url, params, settings, requestData); var myJson = JSON.parse(result);
restPost Example:
The following example converts the
requestData
JavaScript object to JSON before sending it:
You can send only JSON data using this method.
The following example is from the B2B sample.
var settings = { headers: { Authorization: "CALiveAPICreator supplier:1" }};
var pavlov_response = listenerUtil.
restPost
(url, null, settings,
supplierReport_response);
restPatch() Method
You can retrieve a stringified version of the response of a PATCH to the specified URL using the
requestData
object using the
restPatch()
method:
listenerUtil.
restPatch
(url, params, settings, requestData)
Layer7 Live API Creator
treats the PATCH verb like a PUT. Do not use this method against
Layer7 Live API Creator
APIs.
Example:
The following example converts the
requestData
JavaScript object to JSON before sending it:
You can send only JSON data using this method.
var settings = { headers: { "X-ACME-Token": "ABC123" }};
var requestData = {description: "Updated value here"};
var response = listenerUtil.
restPatch
(url, null, settings, requestData);
restDelete() Method
You can retrieve a stringified version of the response of a DELETE to the specified URL using the
restDelete()
method:
listenerUtil.
restDelete
(url, params, settings)
Example:
var result = listener.
restDelete
(url, params, settings);
log.debug(result);
var myJson = JSON.parse(result);
Only the
headers
property is examined. All other properties are ignored:
var settings = { headers : { Authorization : "Basic base64string", "Cache-Control" : "no-cache" } };
For more information about HTTP headers, see List of HTTP Headers page on the Wikipedia website.
restGetBinary() Method
You can retrieve a byte array value for a specific data column using a
/data/
link in a URL and the following
restGetBinary()
method:
listenerUtil.
restGetBinary
(resourceURL, params, settings)
Example:
var resourceURL = req.baseUrl + "/v1/demo:employee_picture/1/picture";
resourceURL = resourceURL.replace("rest","data");
var params = {};
var settings = { "headers": {"Authorization" : "CALiveAPICreator demo_full:1"}};
var byteArray = listenerUtil.
restGetBinary
(resourceURL, params , settings);
row.content = byteArray;// set the current row (type CLOB)
For more information about how to use data URLs, see Use Binary Data.
getBytes() Method
You can convert JavaScript or a Java object into a Java byte array using the
getBytes()
method:
listenerUtil.
getBytes
(message, charset)
This method can have the following parameters:
  • message
    . This value for this parameter must be a JavaScript or Java object.
  • charset
    . For String types, the
    charset
    parameter is the string representation of the character set used to encode the string. Otherwise, set this property to
    null
    .
Layer7 Live API Creator
stringifies JavaScript types before converting them using the standard
JSON.stringify()
JavaScript method. The default character set used for conversion is UTF-8.
Example:
The following example gets bytes from a JavaScript object:
var javascriptObject = {product : "CA Live API Creator", version : 5.4.00};
var asBytes = listenerUtil.getBytes(javascriptObject,null);
Example:
The following example gets bytes from a message string encoded with UTF-16:
var messageAsString = message.toString();
var asBytes = listenerUtil.getBytes(message,"UTF-16");
listenerUtil.publishMessage("MyConnection","MyTopic",asBytes,null);
getConnection() Method
You can retrieve the
connection
JavaScript object representing the connection identified by the string argument name using the
getConnection()
method:
listenerUtil.
getConnection
("<connection name>")
The JavaScript object that
Layer7 Live API Creator
returns is dependent on the connection type (MQTT, KafkaConsumer, KafkaProducer, or Db2iDataQueue).
For more information:
Example
:
The following example gets an MQTT connection and uses it in your code:
var connectionJSObject = listenerUtil.
getConnection
("MyMQTTConnection");
var javaMQTTClientObject = connectionJSObject.mqttClient;
// Checking if you have the connection
if(javaMQTTClientObject.isConnected()){
log.debug("I still have connection");
}
The connection JavaScript Object (MQTT)
MQTT connections are encapsulated in the
connection
JavaScript object of the following form:
{
mqttClient: < An instance of org.eclipse.paho.client.mqttv3.MqttClient >,
persistence: < An instance of org.eclipse.paho.client.mqttv3.persist.MemoryPersistence >,
startupEnv: < A JavaScript object containing objects that are specific to MQTT. >
}
For more information:
The connection JavaScript Object (Kafka)
KafkaConsumer and KafkaProducer connections are encapsulated in the
connection
JavaScript object of the following form:
{
props:
env.props
,
startupEnv: <A JavaScript object containing objects that are specific to Kafka. >
}
The
env.props
property object is passed to the open connection and publish functions.
The following example shows the
getConnection()
method with additional parameters:
var connectionJSObject = listenerUtil.
getConnection
("MyKafkaConnection");
env.props.put("PropertyName","PropertyValue")
var consumer = env.KafkaConsumer(env.props);
consumer.subscribe("myTopic");
//or
var KafkaProducer = new env.KafkaProducer(env.props);
For more information:
The connection JavaScript Object (Db2iDataQueue)
Db2iDataQueue connections are encapsulated in the
connection
JavaScript object of the following form:
{
mqttClient: < An instance of org.eclipse.paho.client.mqttv3.MqttClient >,
persistence: < An instance of org.eclipse.paho.client.mqttv3.persist.MemoryPersistence >,
startupEnv: < A JavaScript object containing objects that are specific to Db 2 for i data queues. >
}
For more information:
publishMessage() Method
You can publish a message to a topic in the MQTT broker, a Kafka broker, or an IBM Db2 for i data queue using the
publishMessage()
method:
listenerUtil.
publishMessage
(connectionName,topic,message,options)
This method can have the following parameters:
  • connectionName
    . The value for this parameter must be a string that represents the connection to use to connect to the broker.
  • topic
    . The value for this parameter must be a string that represents the topic you are publishing to.
  • message
    . The value for this parameter must be a JavaScript or Java object.
  • options
    . The value for this parameter must be a JavaScript object. You can define the way
    Layer7 Live API Creator
    sends the message to the receiver by setting additional properties.
    The properties you can set for the
    options
    parameter in the
    publishMessage()
    method are dependent on the connection type (MQTT, KafkaProducer, or Db2iDataQueue).
    For more information:
Response:
A boolean response of type is expected. If the message successfully publishes, the value of the variable is
true
.
Exception:
If there are errors during publishing, the method throws JSException. This object is a type of
java.lang.RuntimeException
and contains the following properties:
  • fileName
    . The value of this property is a String that represents the name of the JavaScript source file that caused the error. If unavailable, the value is blank.
  • lineNumber
    . The value of this property is a Number that represents the line number in the source file that caused the error. If unavailable, the value is -1.
  • stackString
    . The value of this property is a String that represents the JavaScript exception stack trace.
  • scriptFrames
    . The value of this property is an Array containing the stack frames related to the error.
Example:
The following example publishes a text message to an MQTT broker:
var connectionName = "MyMQTTConnection";
var topic = "ca/liveapicreator";
var message = "Hello World";
var options = null;
// Publishing done below
try{
var publishStatus = listenerUtil.publishMessage(connectionName,topic,message,options);
}
catch(e){
log.debug("Error during publishing. "+e);
}
if(publishStatus){
log.debug("Wohoo!. Message published to MQTT broker");
}
Example:
The following example publishes a text message to an MQTT broker that includes the
options
parameter:
var connectionName = "MyMQTTConnection";
var topic = "ca/liveapicreator";
var message = "Hello World - IMPORTANT";
// Set MQTT options.
var opts = {"qos":2,"retained":true};
// Publishing done below
try {
var publishStatus = listenerUtil.publishMessage(connectionName,topic,message,opts);
}
catch(e){
log.debug("Error during publishing. "+e);
}
if(publishStatus){
log.debug("Message published to MQTT broker with Quality of Service as 2 and Retained as TRUE.");
}
Example:
The following example publishes a text message to a data queue residing on Db2 for i:
var connectionName = "MyMQTTConnection";
var topic = "ca/liveapicreator";
var message = "Hello World";
var options = null;
// Publishing done below
try{
var publishStatus = listenerUtil.publishMessage(connectionName,topic,message,options);
}
catch(e){
log.debug("Error during publishing. "+e);
}
if(publishStatus){
log.debug("Wohoo!. Message published to MQTT broker");
}
Properties for the options Parameter (MQTT)
You can set the following properties as part of the
options
parameter in the
publishMessage
function for MQTT connection types:
Properties for the options Parameter (MQTT)
qos
Defines the Quality of Service (QOS) at which
Layer7 Live API Creator
should deliver the message.
Value:
0, 1 or 2
Default:
0
Required:
No
retained
Determines whether or not you want the server to retain the message.
Values:
true or false
Default:
false
Required:
No
Properties for the options Parameter (Kafka)
You can set the following properties as part of the
options
parameter in the
publishMessage
function for the KafkaProducer connection type:
Properties for the options Parameter for KafkaProducer Connection Types
partition
Defines the partition in which you want to publish this message.
Value:
number
Default:
0
Required:
No
key
Determines the key you want to use to define the message.
Values:
string
Default:
null
Required:
No
Properties for the options Parameter (Db2iDataQueue)
You can set the following properties as part of the
options
parameter in the
publishMessage
function for Db2iDataQueue connection types:
Properties for the options Parameter (Db2iDataQueue)
qos
Defines the Quality of Service (QOS) at which
Layer7 Live API Creator
should deliver the message.
Value:
0, 1 or 2
Default:
0
Required:
No
retained
Determines whether or not you want the server to retain the message.
Values:
true or false
Default:
false
Required:
No
getTeamSpaceInfo() Method
You can retrieve information about a TeamSpace and adjust the behavior dynamically using the following
getApiInfo()
method in the JavaScript code for your listener:
var teamspaceinfo = listenerUtil.getTeamSpaceInfo();
log.debug(teamspaceinfo.urlFragment + " " + teamspaceinfo.name + " " + teamspaceinfo.isActive);
The method returns an object with information about the TeamSpace.
getApiInfo() Method
You can retrieve information about an API and adjust the behavior dynamically using the following
getApiInfo()
method in the JavaScript code for your listener:
var apiinfo = listenerUtil.getApiInfo();
log.debug(apiinfo.urlFragment + " " + apiinfo.name);
The method returns an object with information about the API.
getExtendedPropertiesFor() Method
You can access the extended properties for a resource and adjust the behavior dynamically by adding the following
getExtendedPropertiesFor()
method in the JavaScript code for your listener:
listenerUtil.
getExtendedPropertiesFor
(apiVersionName, name)
The
apiVersion
property is required. This call returns a JavaScript object with information about the extended properties for the resource.
Example:
var extendedProperties = listenerUtil.get
ExtendedPropertiesFor
("v1", "AllCustomers");
if (extendedProperties && extendedProperties.MyExtension) {
out.printIn("v1/AllCustomers has an extendedProperties 'MyExtension' value of ", JSON.stringify(extendedProperties.MyExtension));
}
For more information about how to access the extended properties for a resource using this method, see Manage the Extended Properties for Resources.
processHTTPInParallel() Method
You can have
Layer7 Live API Creator
call multiple HTTP requests in parallel by adding the
processHTTPInParallel()
method in the JavaScript for your listener. This method optimizes your API by creating separate threads to call the HTTP service requests, and then it returns and array of JSON responses. You can iterate through the responses to perform any additional processing or API mashups before returning the response to the client.
This method uses the following syntax:
listenerUtil.
processHTTPInParallel
(httpRequestArray)
This method is also available in the
SysUtility
object. For more information about this method, including how to pass in the
httpRequestArray
parameter and read the responses, see The SysUtility Object.