The SysUtility Object

The SysUtility Object
lac51
You can send REST requests and access services, such as retrieving a resource or invoking another REST service, using the methods that are included with the
SysUtility
JavaScript object. Use this object in the JavaScript code for custom endpoints, resources, listeners, and event handlers.
This object includes the following methods:
 
 
2
 
 
getResource Method
You can retrieve the value of the specified resource using the following 
getResource()
 method:
SysUtility.
getResource
(resourceName, settings)
This method returns a stringified version of the response to a resource. This service operates on your resources in the API. The return value of this method is an object array, which is the JSON object that is returned by the call.
 You can retrieve a string by calling the 
getResourceAsString()
 method or by stringifying the result.
For more information about this method, see the "getResourceAsString method" section.
This method retrieves the value set for the 
settings
 parameter. The value must be an object that can have the following properties:
  • filter
    ,
    sysfilter
    userfilter
    . An object with the desired filters for each resource.
    Use aliased attribute names (not table attribute names) for 
    filter
     and 
    sort
    .
    By default, these properties work with
    SysUtility
    calls. If you have turned off regular filters and sorts, only named filters (the
    sysfilter and
    userfilter
    properties) work with
    SysUtility
    calls. For more information about how to turn off regular filters, see Structured Filters.
  • order
    ,
    sysorder
    ,
    userorder
    . An object with the desired sorting orders for each resource.
    By default, these properties work with
    SysUtility
    calls. If you have turned off regular filters and sorts, only named sorts (the
    sysorder
    and
    userorder
    properties) work with
    SysUtility
    calls. For more information about how to turn off regular sorts (and sorts), see Structured Sorts.
    For more information about using named sorts, see Structured Sorts.
  • pagesize
    . The maximum number of rows per resource level.
  •  
    offset
    . The number or records to skip from the top resource.
  • chunksize
    . Determines the number of queries 
    CA Live API Creator
     executes to return the rows for table-based subresources.
  • params
    . An object containing name/value pairs for parameters to, for example, SQL resources. The name must start with 
    arg_
    .
The 
settings
 parameter typically specifies your filter criteria (
filter
sysfilter
userfilter
), for example:
var settings = {sysfilter: "equal(OrderID:" + row.OrderID + ")"
,"sysfilter.SupplierAlert.Order_DetailsList.Product.Supplier":
"equal(CompanyName: '" + "Pavlova, Ltd." + "')" };
The 
settings
 parameter can also specify 
pagesize
offset
chunksize
, and 
params
, for example:
These properties are typically defaulted. They are not required, but shown for reference in this example.
var details = {
filter: "name like 'ABC%',
order: "name asc",
pagesize: 20,
offset: 0,
chunksize: 10,
params: {arg_minSalary: 90000, arg_province: 'BC'}
};
For example, in the Business to Business (B2B) sample, an instance of the 
SupplierAlert
 resource is created (to match the API agreement with the Pavlov supplier), as follows:
var supplierReport_response = SysUtility.getResource("SupplierAlert", options);
For more information:
 
Example:
 
var parts = SysUtility.
getResource
("main:Products", {sysfilter: "less(price:100)", sysorder: "(price:desc)"}); for (var i = 0 ; i < parts.length ; i++) { log.debug(JSON.stringify(parts[i])); }
For more information about how to use the JSON object, see JavaScript.
You can also pass an array of string as the value for 
sysfilter
 or 
sysorder
, for example:
sysfilter: ["less(total: 100)", "equal(name: 'Acme')"]
You can reference a subresource where the price of the product is less than 100 as a subresource or 
Customer.Orders.Product
 using '.' dot notation:
'sysfilter.Customer.Orders.Product': 'less(price:100)'
If the resource is a view, qualify it and the filter, for example:
var parts = SysUtility.getResource("
nw:
Customer Orders", {filter: {"
nw:
Customer Orders": "price < 100"}});
If the resource you are invoking is a stored procedure resource, then you can pass parameters as follows:
var orders = SysUtility.getResource("nw:MyProc", {procArgs: {empName: "Doe", amount: 123.45}});
getResourceAsString Method
You can retrieve a resource instance from the current API, with the specified filter parameters, using the specified settings, using the following 
getResourceAsString()
 method:
SysUtility.
getResourceAsString
(resourceName, settings)
This call returns a string object.
 
Example:
 
var prodResp = SysUtility.getResourceAsString("nw:Products", {sysfilter: "less(price:100)", sysorder: "(price:desc)"});
var parts - JSON.parse(prodResp);
for (var i in parts) {
log.debug(JSON.stringify(parts[i], null, 2));
}
getExtendedPropertiesFor Method
You can retrieve the extended properties for a resource and adjust the behavior dynamically using the following 
getExtendedPropertiesFor()
 method in your JavaScript code:
SysUtility.
getExtendedPropertiesFor
(apiVersionName, name)
The 
apiVersion
 property is optional. If you omit this property or it is null,  
CA Live API Creator
 uses the version of the API in the request. This call returns a JavaScript object.
 
Example:
 
var extendedProperties = SysUtility.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.
getFunction Method
You can retrieve the value of a specified top-level function using the following 
getFunction()
 method in your JavaScript code:
SysUtility.
getFunction
(functionName, parameterList)
The 
parameterList
 parameter is optional. This parameter is an object with the desired list of parameter names in JavaScript format.
 
Example:
 
var sum = SysUtility.
getFunction
("addNumbers", {parm1: 10, parm2: 20});
log.debug(sum);
For more information:
  • About how to use the JSON object, see JavaScript.
  • About functions, including how to call functions from within API Server using this method, see Manage Functions.
getProcedure Method
You can retrieve the value of a stored procedure using the following 
getProcedure()
 method in your JavaScript code:
SysUtility.
getProcedure
(procedureName, argsList)
The 
argsList
 parameter is optional. This parameter is an object with the desired list of arguments in JavaScript format. This method returns a JSON object.
 
Example:
 
var procresp = SysUtility.
getProcedure
("demo:get_employee", {given_employee_id: 1, plus_one: 2});
log.debug(JSON.stringify(procresp,null,2));
For more information:
rest<verb> - GET, PUT, POST, PATCH, DELETE Methods
You can invoke other RESTful services from business logic or row events using the following methods:
SysUtility.
restGet
(url, params, settings)
SysUtility.
restPut
(url, params, settings, requestData)
SysUtility.
restPost
(url, params, settings, requestData)
SysUtility.
restPatch
(url, params, settings, requestData)
SysUtility.
restDelete
(url, params, settings)
In these calls, you pass the URL, parameters, settings, and request data.
restGet Method
You can have 
CA Live API Creator
 return a stringified version of the result of a GET to the specified URL using the
SysUtility.restGet()
method in your JavaScript code:
var result = SysUtility.
restGet
(url, params, settings);
var myJson = JSON.parse(result);
 
restGet Example:
 
var params = { name: "Acme", country: "Elbonia" }; var json = SysUtility.
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 optional 
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.
  • The
    proxy
    setting. This setting ensures that the HTTP call is made using the specified HTTP proxy server. It must include the 
    hostname
     property with a value set to the host name of the HTTP proxy server and the 
    port
     property with a value set to the port number for the HTTP proxy server.
 
restGet Example:
 
SysUtility.
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
}
});
 
CA Live API Creator
 converts the 
requestData
 JavaScript object to JSON before sending it. You can send only JSON data using these methods.
restPut Method
You can have 
CA Live API Creator
 return a stringified version of the response of a PUT to the specified URL using the
SysUtility.restPut()
method and the 
requestData
 JSON object.
 You can obtain the 
requestData
 JSON object using the the 
SysUtility.restGet()
 method.
var result = SysUtility.
restPut
(url, params, settings, requestData); // requestData is a JSON object var myJson = JSON.parse(result);
restPost Method
You can have 
CA Live API Creator
 return a stringified version of the response of a POST to the specified URL using the 
SysUtility.restPost()
 method and the 
requestData
 JSON object.
 You can obtain the 
requestData
 JSON object using the the 
SysUtility.restGet()
 method.
var result = SysUtility.
restPost
(url, params, settings, requestData); var myJson = JSON.parse(result);
 
restPost Example:
 
The following example is from the B2B sample:
var settings = { headers: { Authorization: "CALiveAPICreator supplier:1" }};
var pavlov_response = SysUtility.
restPost
(url, null, settings,
supplierReport_response);
 
CA Live API Creator
 converts the 
requestData
 JavaScript object to JSON before sending it. You can send only JSON data using these methods.
restPatch Method
You can have 
CA Live API Creator
 return a stringified version of the response of a PATCH to the specified URL using the
SysUtility.restPatch()
method and the
requestData
object. 
CA Live API Creator
 converts the 
requestData
 JavaScript object to JSON before sending it. You can send only JSON data using these methods.
 
CA Live API Creator
 treats the PATCH verb like a PUT. Do not use this method against an API that you created using 
CA Live API Creator
.
 
Example:
 
var url = "https://api.acme.com/myApi/Widgets/42";
var settings = { headers: { "X-ACME-Token": "ABC123" }};
var requestData = {description: "Updated value here"};
var response = SysUtility.
restPatch
(url, null, settings, requestData);
restDelete Method
You can have 
CA Live API Creator
 return a stringified version of the response of a DELETE to the specified URL using the
SysUtility.restDelete()
method in your JavaScript code:
var result = SysUtility.
restDelete
(url, params, settings); log.debug(result); var myJson = JSON.parse(result);
The 
requestData
 JavaScript object is optional. 
CA Live API Creator
 examines only the 
headers
 id. It ignores all other ids:
var settings = {
"headers" : {
"Authorization" : "Basic base64string",
"Cache-Control" : "no-cache"
}
};
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 in your JavaScript code:
SysUtility.
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 = SysUtility.
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 using the 
getBytes()
 method in your JavaScript code:
SysUtility.
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.1};
var asBytes = SysUtility.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 = SysUtility.getBytes(message,"UTF-16");
SysUtility.publishMessage("MyConnection","MyTopic",asBytes,null);
getTeamSpaceInfo Method
You can retrieve information about a TeamSpace and adjust the behavior dynamically using the following 
getTeamSpaceInfo()
 method in your JavaScript code:
var teamspaceinfo = SysUtility
.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 your JavaScript code:
var apiinfo = SysUtility.
getApiInfo()
;
log.debug(apiinfo.urlFragment + " " + apiinfo.name);
This method returns an object with information about the current API.
postToFunction Method
The 
postToFunction() 
method posts the payload to a top-level function and returns a JavaScript JSON object:
SysUtility.
postToFunction
(functionName, parameterList, payload)
The 
parameterList
 parameter is optional. This parameter is an object with the desired list of parameter names in JavaScript format.
 
Example:
 
var sortedArray = SysUtility.postToFunction("sortWithPOST", {orderby: "desc"},{"fruits": ["Banana", "Orange", "Apple", "Mango"]});
log.debug(sortedArray);
return JSON.parse(sortedArray);
For more information:
  • About how to use the JSON object, see JavaScript.
  • About functions, including how to call functions from within API Server using this method, see Manage Functions.
databaseNowDeferred Method
You can have 
CA Live API Creator
 return an object and assign it to a row attribute. This object represents the current date, time, or timestamp on the database server at the instant the resulting SQL is executed on the database server. The
databaseNowDeferred()
method is aware of the underlying database and emits the correct SQL fragment appropriate for the specific datatype and database in use:
SysUtility
.databaseNowDeferred()
 You can also have 
CA Live API Creator
 return an object and assign it to a row attribute using the
sqlSnippetDeferred()
method and the database-specific SQL syntax to match the datatype.
You can add this method to the code for event rules, pre-insert event rules, and formula rules.
 
Example:
 
var databaseTimestamp = SysUtility.databaseNowDeferred();
row.last_updated = databaseTimestamp
For more information:
sqlSnippetDeferred Method
You can have 
CA Live API Creator
 return an object and assign it to a row attribute in events and formula rules. This object represents a small portion of the database SQL that 
CA Live API Creator
 executes as part of the SQL INSERT or UPDATE. This object can be a SQL function, a system, a user, a single-value select, such as
select max(val) from mytable
, or any other SQL that you can use as the value for the column:
SysUtility.
sqlSnippetDeferred
(timestamp)
 You can also have 
CA Live API Creator
 return an object and assign it to a row attribute in a rule using the
databaseNowDeferred()
method.
You can add this method to the code for event rules, pre-insert event rules, and formula rules.
 
Example:
 
var databaseTimestamp = SysUtility.sqlSnippetDeferred('current timestamp(12)');
return databaseTimestamp;
For more information:
getConnection Method
You can have 
CA Live API Creator
 return the
connection
JavaScript object representing the connection that is identified by the string argument name using the 
getConnection()
 method in your JavaScript code:
SysUtility.
getConnection
("<connection name>")
The JavaScript object that 
CA Live API Creator
 returns is dependent on the connection type (MQTT, KafkaConsumer, or KafkaProducer).
 For more information about the 
connection
 JavaScript object for MQTT connections, see the "The connection JavaScript object (MQTT)" section.
 
Example
:
The following example gets an MQTT connection and uses it in your code:
var connectionJSObject = SysUtility.
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:
publishMessage Method
You can publish a message to a topic in the MQTT or Kafka broker using the following 
publishMessage()
 method in your JavaScript code:
SysUtility.
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 
    CA Live API Creator
     sends the message to the receiver by setting extra properties.
    The properties that you can set for the 
    options
     parameter in the 
    publishMessage()
     method depend on the connection type (MQTT 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 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: Publish a Text Message to an MQTT Broker
 
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 = SysUtility.publishMessage(connectionName,topic,message,options);
} catch(e){
log.debug("Error during publishing. "+e);
}
if(publishStatus){
log.debug("Wohoo!. Message published to MQTT broker");
}
Example: Publish a Text Message to an MQTT Broker that Includes the
options
Parameter
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 = SysUtility.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: Publish a Text Message to a Kafka Broker
 
The following example publishes a text message to a Kafka broker:
var connectionName = "KafkaProducerConnection";
var topic = "MyTestTopic";
var options = {key: 'myKey',partition: 0};
var message = "My test Kafka message";
try{
var response = SysUtility.publishMessage(connectionName, topic, message, options);
} catch(e){
log.debug("Error during publishing. "+e);
}
if(response.isSuccess) {
log.debug(JSON.stringify(response));
log.debug("Publish Message to KafkaProducerConnection");
}
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 
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)
The Kafka producer is responsible for choosing which message to assign to which partition within the topic. It is the client’s responsibility to decide the partition to which to send the message. 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 (Kafka)
 
partition
 
Defines the partition in which you want to publish this message.
 
Value:
 number
 
Default:
 0
 
Required:
 No
 
key
 
Determines the key that you want to use to define the message.
 
Values:
 string
 
Default:
 null
 
Required:
 No
Debug the SysUtility Methods
Before coding 
SysUtility
 calls, verify your URL and headers using REST tools such as Postman. The following image shows an example of debugging using Postman: