The timerUtil Object

The timerUtil Object
lac42
You can access services, such as retrieving the server host name or IP address, using the 
timerUtil
 JavaScript object. This object is available as you define JavaScript code for your timer execution.
In this article:
2
getHostName Method
You can retrieve the server host name by inserting the 
getHostName()
 method into the time code.
This method does not always return the results that you expect, since servers can have multiple names. This method calls the 
InetAddress.getLocalHost().getHostName()
 Java method. If this Java method fails, it uses the first open interface from the 
NetworkInterface.getNetworkInterfaces()
method.
Best Practice:
Test this method to ensure that it returns what you expect.
getHostNameAddress Method
You can retrieve the server IP address by inserting the 
getHostAddress()
 method into the timer code.
This method does not always return the results that you expect, since servers can have multiple interfaces. This method calls the 
InetAddress.getLocalHost().getHostName()
 Java method. If this Java method fails, it uses the first open interface from the 
NetworkInterface.getNetworkInterfaces()
method.
Best Practice:
Test this method to ensure that it returns what you expect.
rest<verb> - GET, PUT, POST, PATCH, DELETE Method
You can invoke other RESTful services by inserting the following methods into the timer code:
timerUtil.
restGet
(url, params, settings)
timerUtil.
rest
Put(url, params, settings, requestData)
timerUtil.
rest
Post(url, params, settings, requestData)
timerUtil.
rest
Patch(url, params, settings, requestData)
timerUtil.
rest
Delete(url, params, settings)
In these calls, you can pass the URL, parameters, settings, and request data.
You must pass in the authentication token in the
settings
parameter.
restGet Method
You can retrieve a stringified version of the result of a GET to the specified URL by inserting the 
timerUtil.restGet()
 method into the timer code:
var result = timerUtil.
restGet
(url, params, settings);
var myJson = JSON.parse(result);
restGet Example:
var params = {
   name: "Acme",
   country: "Elbonia"
   };
var settings = { "headers": {"Authorization" : "CALiveAPICreator myAuthToken:1"}};
var myjson = timerUtil.restGet("http://rest.example.com/myservice", params, settings);
var resultObject = JSON.parse(myjson);
The 
params
 parameter contains the parameters to the call. Using this parameter 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. This parameter can have the following properties:
  • The 
    headers
     setting. Add this setting to the call as HTTP headers. This setting must include name and value pairs.
    If you want to invoke this function so that you can 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. This setting must include the 
    hostname
     property with a value set to the host name of the HTTP proxy server. This setting must also include the 
    port
     property with a value set to the port number for the HTTP proxy server.
restGet Example:
You can send only JSON data using this method.
var result = timerUtil.
restGet
('http://rest.example.com/myservice',
  {name: 'Acme', country: 'Elbonia'},
  {headers: {
    Authorization : "Basic <base64string>",
    "Content-Type" : "application/json"
  },
  proxy: {
    hostname: "proxy.example.com",
    port: 8282
  }
});
restPut Method
You can PUT an object (such as one obtained through the
timerUtil.restGet()
method) to the specified URL by inserting the 
timerUtil.restPut()
 method into the timer code:
var params = {}; var settings = { headers: { Authorization: "CALiveAPICreator supplier:1" }}; obj.quantity += 1; var result = timerUtil.restPut(obj["@metadata"].href, params, settings, obj);  // obj is a JSON object var myJson = JSON.parse(result);
restPost Method
You can POST an object to the specified URL by inserting the 
timerUtil.restPost()
 method into the timer code:
var settings = { headers: { Authorization: "CALiveAPICreator supplier:1" }};
var response = timerUtil.restPost(url, null, settings, {name: "Joe Pesci", age: 51});
var responseObject = JSON.parse(response);
You can send only JSON data using this method.
restPatch Method
You can retrieve a stringified version of the response of a PATCH to the specified URL using the 
requestData
 object by inserting the 
timerUtil.restPatch()
 method into the timer code:
CA Live API Creator
 treats the PATCH verb like a PUT. Do not use this method against APIs in API Creator.
restPatch Example:
The following example converts the 
requestData
 JavaScript object to JSON before sending it:
You can send only JSON data using this method.
var url = "https://api.acme.com/myApi/Widgets/42"; var settings = { headers: { "X-ACME-Token": "ABC123" }}; var requestData = {description: "Updated value here"}; var response = timerUtil.restPatch(url, null, settings, requestData);
restDelete Method
You can DELETE an object by inserting the 
timerUtil.restDelete()
 method into the timer code:
var settings = {   headers : {     Authorization : "CALiveAPICreator mytoken:1",     "Content-Type" : "application/json"   } }; var params = {checksum: myObject["@metadata"].checksum}; var result = timerUtil.restDelete(myObject["@metadata"].href, params, settings); var resultObj = JSON.parse(result);
The 
settings
object only considers the 
headers
 property. If you are calling a 
CA Live API Creator
 API, the 
checksum
parameter is required.
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 by inserting the following 
restGetBinary()
 method into the timer code:
timerUtil.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 = timerUtil.restGetBinary(resourceURL, params , settings); row.content = byteArray;// set the current row (type CLOB)
For more information:
getBytes Method
You can convert JavaScript or a Java object into a Java byte array by inserting the 
getBytes()
 method into the time code:
timerUtil.
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
    .
CA 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: Gets Bytes from a JavaScript Object
The following example gets bytes from a JavaScript object:
var javascriptObject = {product : "CA Live API Creator", version : 5.0};
var asBytes = timerUtil.getBytes(javascriptObject,null); 
Example: Gets Bytes from a Message String Encoded with UTF-16
The following example gets bytes from a message string encoded with UTF-16:
var messageAsString = message.toString();
var asBytes = timerUtil.getBytes(message,"UTF-16"); 
timerUtil.publishMessage("MyConnection","MyTopic",asBytes,null);
getConnection Method
You can retrieve the 
connection
 JavaScript object representing the connection that is identified by the string argument name by inserting the 
getConnection()
 method into the timer code:
timerUtil.
getConnection
("<connection name>")
 The JavaScript object that 
CA Live API Creator
 returns depends on the connection type (MQTT, KafkaConsumer, or KafkaProducer).
Example
:
The following example gets an MQTT connection and uses it in your code:
var connectionJSObject = timerUtil.
getConnection
("MyMQTTConnection");
var javaMQTTClientObject = connectionJSObject.mqttClient;
// Checking if you have the connection
if(javaMQTTClientObject.isConnected()){
log.debug("I still have connection");
}
publishMessage Method
You can publish a message to a topic in the MQTT or Kafka broker by inserting the 
publishMessage()
 method into the timer code:
timerUtil.
publishMessage
(connectionName, topic, message, options)
This method requires 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 for the topic name. 
  • 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 
    CA Live API Creator
     sends the message to the receiver by setting more properties.
    The properties you can set for the
    options
    parameter in the 
    publishMessage()
     method depend on the connection type (MQTT, KafkaConsumer, or KafkaProducer).
    For more information:
Response:
A boolean
 
response 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 a 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 that are 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; try{ var publishStatus = timerUtil.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}; try { var publishStatus = timerUtil.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."); }
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:
MQTT options Parameter Properties
qos
Defines the Quality of Service (QoS) at which 
CA Live API Creator
 should deliver the message.
Value:
 0, 1 or 2
Default:
 0
Required:
 No
retained
Determines whether 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 KafkaConsumer and KafkaProducer connection types:
Kafka options Parameter Properties
partition
The partition number to which the record should be sent.
Default:
 0
Required:
 No
key
The key (in the form of a string) that you want to include in the record.
Default:
 null
Required:
 No
getTeamSpaceInfo Method
You can retrieve information about a TeamSpace and adjust the behavior dynamically using the following 
getTeamSpaceInfo()
 method in the JavaScript code for your timer:
var teamspaceinfo = timerUtil.getTeamSpaceInfo();
log.debug(teamspaceinfo.urlFragment + " " + teamspaceinfo.name + " " + teamspaceinfo.isActive);
This method returns an object with information about the current 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 timer:
var apiinfo = timerUtil.getApiInfo();
log.debug(apiinfo.urlFragment + " " + apiinfo.name);
This method returns an object with information about the current API.
getExtendedPropertiesFor Method
You can retrieve the extended properties for a resource and adjust the behavior dynamically using the following 
getExtendedPropertiesFor()
 method in the JavaScript code for your timer:
timerUtil.
getExtendedPropertiesFor
(apiVersionName, name)
The 
apiVersion
 property is required. This call returns a JavaScript object with information about the extended properties for a resource.
Example:
var extendedProperties = timerUtil.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.