The SysUtility Object
The SysUtility Object
lac42
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
JavaScript object.SysUtility
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.
If you need a string, call the
getResourceAsString()
method or stringify 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
,sysfilteruserfilter. An object with the desired filters for each resource.Use aliased attribute names (not table attribute names) forfilterandsort.By default, these properties work with
calls. If you have turned off regular filters and sorts, only named filters (theSysUtilitysysfilter and
properties) work withuserfilter
calls. For more information about how to turn off regular filters, see Structured Filters.SysUtility
,order
,sysorder
. An object with the desired sorting orders for each resource.userorderBy default, these properties work with
calls. If you have turned off regular filters and sorts, only named sorts (theSysUtility
andsysorder
properties) work withuserorder
calls. For more information about how to turn off regular sorts (and sorts), see Structured Sorts.SysUtilityFor more information about using named sorts, see Structured Sorts.
. The maximum number of rows per resource level.pagesize- offset. The number or records to skip from the top resource.
. Determines the number of querieschunksizeCA Live API Creatorexecutes to return the rows for table-based subresources.
. An object containing name/value pairs for parameters to, for example, SQL resources. The name must start withparamsarg_.
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:
- About how to disallow regular filters, see API Properties.
- About how to use URL parameters in GET, PUT, POST, and DELETE, see URL Parameters.
- About the B2B sample, see B2B API Sample.
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.getExtendedPropertiesFor("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:
- About how to use the JSON object, see JavaScript.
- About how to invoke stored procedures, see Manage Stored Procedures.
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
method in your JavaScript code:SysUtility.restGet()
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
setting. Add this setting to the call as HTTP headers. It must include name/value pairs.headers - The
setting. This setting ensures that the HTTP call is made using the specified HTTP proxy server. It must include theproxyhostnameproperty with a value set to the host name of the HTTP proxy server and theportproperty 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 }});
The
requestData
JavaScript object is converted to JSON before being sent. 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
method and theSysUtility.restPut()
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);
The
requestData
JavaScript object is converted to JSON before being sent. 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
method and theSysUtility.restPatch()
object. TherequestData
requestData
JavaScript object is converted to JSON before being sent. 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
method in your JavaScript code:SysUtility.restDelete()
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:
- About using data URLs, see Use Binary Data.
- About viewing an API sample that can store binary fields and can display them in a browser by way of Data Explorer, see Document Manager API Sample.
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, thecharsetparameter is the string representation of the character set used to encode the string. Otherwise, set this property tonull.
CA Live API Creator
stringifies JavaScript types before converting them using the standard
JavaScript method. The default character set used for conversion is UTF-8.JSON.stringify()
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 = 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
method is aware of the underlying database and emits the correct SQL fragment appropriate for the specific datatype and database in use:databaseNowDeferred()
SysUtility.databaseNowDeferred()
You can also have
CA Live API Creator
return an object and assign it to a row attribute using the
method and the database-specific SQL syntax to match the datatype.sqlSnippetDeferred()
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:
- About how to use this method in event rules and pre-insert event rules, see Event Rule Types.
- About how to use this method in formula rules, see Formula Rule Type.
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
, or any other SQL that you can use as the value for the column:select max(val) from mytable
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
method.databaseNowDeferred()
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:
- About how to use this method in event rules and pre-insert event rules, see Event Rule Types.
- About how to use this method in formula rules, see Formula Rule Type.
getConnection Method
You can have
CA Live API Creator
return the
JavaScript object representing the connection that is identified by the string argument name using theconnection
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 connectionif(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:
- About theMqttClientJava class, see the Eclipse documentation.
- About theMemoryPersistenceJava class, see the Eclipse documentation.
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 wayCA Live API Creatorsends the message to the receiver by setting extra properties.The properties that you can set for theoptionsparameter in thepublishMessage()method depend on the connection type (MQTT or KafkaProducer).For more information:
- About the properties for MQTT connections, see the "Properties for the options Parameter (MQTT)" section.
- About the properties for KafkaProducer connections, see the "Properties for the options Parameter (Kafka)" section.
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 belowtry {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
Parameteroptions
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 belowtry {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 2Default:
0Required:
Noretained
Determines whether you want the server to retain the message.
Values:
true or falseDefault:
falseRequired:
NoProperties 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:
numberDefault:
0Required:
Nokey
Determines the key that you want to use to define the message.
Values:
stringDefault:
nullRequired:
NoDebug 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: