JSLEE API
JSLEE API
The JSLEE Lua API exposes JSLEE-wide functionality for use within the Lua script engine.
Functions
JSLEE.succeeded (response)
Description
This method returns a successful response back to the service that triggered the service logic. It may be done anywhere in the Lua code and may be followed by additional logic (including as many events as required to send).
The response sent back as part of this function is arbitrary, but should be something the initiator is going to understand.
Note that you can still error
in code following this. If no response
has already been sent, an error will be sent back. Otherwise, an error warning
will be written to the log.
Note also that JSLEE.succeeded
and JSLEE.failed
can only be called once
per event handler, i.e. a script cannot succeed or fail more than once for
the same event.
Arguments
Argument | Comments |
---|---|
response |
The (arbitrary) response to send to the initiator of the service logic request. |
Returns
Nothing.
Example
function h.handle (uuid, event, fromAddress)
logger = JSLEE.logger()
log:debug("[myhandler] Received request to handle event " .. event .. " from endpoint " .. fromAddress)
-- actual handling
-- return an appropriate value to the source of the event via reply
JSLEE.succeeded (0)
end
JSLEE.failed (errorCode, errorString)
This method returns a failure response back to the service that triggered the service logic. It may be done anywhere in the Lua code and may be followed by additional logic (including as many events as required to send).
The response should be an error code, along with a string describing what the error is.
Note that you can still error
in code following this. If no response
has already been sent, an error will be sent back. Otherwise, an error warning
will be written to the log.
Note also that JSLEE.succeeded
and JSLEE.failed
can only be called once
per event handler, i.e. a script cannot succeed or fail more than once for
the same event.
Arguments
Argument | Comments |
---|---|
errorCode |
The arbitrary code of the error to send to the initiator of the service logic request. |
errorString |
Freeform text detailing why the request failed. |
Returns
Nothing.
Example
-- unable to process message
JSLEE.failed (1024, "Failure parsing inbound parameters.")
JSLEE.isWrapped (object)
This method tests whether the given object appears to be a Lua-wrapped object, i.e. one that can be acted upon using the JSLEE Lua API. This may cause false positives if used with non-JSLEE objects.
Arguments
Argument | Comments |
---|---|
object |
The object to examine for Lua wrapping. |
Returns
true
if object
appears to be a Lua-wrapped object, false
otherwise.
Example
for k, v in ipairs{...} do
if JSLEE.isWrapped(v) then
t[k] = v:unwrap()
else
t[k] = v
end
end
JSLEE.wrapper (objectType, object)
This helper function should be called whenever you are using a Java object that
has a Lua helper library associated with it, e.g. SMPPMessage
.
It will wrap object
using the helper library’s own methods and then return it.
If there is no helper library matching the objectType
provided, object
is
returned unchanged. In the case of event-type objects, it will retrieve the
object that the event carries, not the event itself.
Note that events returned by JSLEE.send
and as received when the Lua
coroutine starts are automatically pre-wrapped. Manual wrapping is only necessary
if Lua JSLEE API use is desired and the object has been created manually.
Arguments
Argument | Comments |
---|---|
objectType |
The fully-qualified Java classname of the object. |
object |
The object to consider wrapping. |
Returns
object
if objectType
does not match a known JSLEE Lua-wrappable type, otherwise
a Lua-wrapped instance of object
.
Example
local oType = "nz.co.nsquared.slee.smpp.event.SMPPMessageEvent"
jsonDoc = JSLEE.createJavaObject (oType)
jsonDocWrapped = JSLEE.wrapper(oType, jsonDoc)
JSLEE.createJavaObject (className, ...)
Description
This method creates an instance of a Java class with the supplied arguments. If the object is of a known Lua-wrappable class object, it will be returned as a Lua-wrapped object, allowing API usage.
Arguments
Argument | Comments |
---|---|
className |
The Java class name to create. |
... |
Additional arguments, passed to the Java constructor. |
Returns
Number | Type | Comments |
---|---|---|
1 | Object | The created object. |
Example
jsonDoc = JSLEE.createJavaObject ("io.vertx.core.json.JsonObject")
smppHeader = smppRequest:header();
header = JSLEE.createJavaObject ("io.vertx.core.json.JsonObject")
header:put("command", tostring(smppHeader:getCommandCode()))
jsonDoc:put("header", header)
JSLEE.createJsonObject (input)
Description
This method creates an instance of a Java Vert.X JsonObject from the supplied
input
. This input
must be either a JSON string, a Lua table, or nil
.
If the input
is nil, then the created object will be empty.
The returned object may contain other JsonArray or JsonObject values as
present in the input
.
Arguments
Argument | Comments |
---|---|
input |
The Lua table, Lua string, or nil value to be used for construction. |
Returns
Number | Type | Comments |
---|---|---|
1 | JsonObject | The created JsonObject. |
Example
local obj = JSLEE.createJsonObject ()
obj:put ("key", "value")
JSLEE.decodeJsonObject (input)
Description
This method creates a Lua table from an input instance of a Java Vert.X JsonObject.
If the input
is nil, then the decoded table will be empty.
Arguments
Argument | Comments |
---|---|
input |
The JsonObject to decode. |
Returns
Number | Type | Comments |
---|---|---|
1 | Table | The decoded table. |
Example
local obj = JSLEE.createJsonObject ()
obj:put ("key", "value")
local t = JSLEE.decodeJsonObject (obj)
if t.key ~= "value" then -- something has gone very wrong
JSLEE.tableToJsonString (input)
Description
This method transforms a Lua table into a JSON string. If the input
is nil
or not a table, then the transformed string will be an JSON object.
Arguments
Argument | Comments |
---|---|
input |
The Lua table to transform. |
Returns
Number | Type | Comments |
---|---|---|
1 | String | The JSON representation of the table. |
Example
local t = { key = "value" }
local jsonString = JSLEE.tableToJsonString (t)
JSLEE.createJsonArray (input)
Description
This method creates an instance of a Java Vert.X JsonArray from the supplied
input
. This input
must be either a JSON string, a Lua table, or nil
.
If the input
is nil, then the created object will be empty.
The returned object may contain other JsonArray or JsonObject values as
present in the input
.
Arguments
Argument | Comments |
---|---|
input |
The Lua table, Lua string, or nil value to be used for construction. |
Returns
Number | Type | Comments |
---|---|---|
1 | JsonArray | The created JsonArray. |
Example
local arr = JSLEE.createJsonArray ()
arr:add ("item")
JSLEE.createEvent (eventClass, context, ...)
Description
This method creates a JSLEE event, i.e. an object that can be sent over the event bus. Additionally, it also passes any following arguments to that event’s constructor.
Note that events are not returned wrapped, as they are not usually used directly in JSLEE Lua API usage.
The JSLEE context may be created via JSLEE.createContext
or retrieved
from an event that has been received via a call to context ()
.
Arguments
Argument | Comments |
---|---|
eventClass |
The event class to create. |
context |
A JSLEE context object, created via JSLEE.createContext or extracted from a received event. |
... |
Additional arguments, passed to the Java constructor. |
Returns
Number | Type | Comments |
---|---|---|
1 | Object | The created object. |
Example
jsonSchemaDocumentEvent = JSLEE.createEvent ("nz.co.nsquared.slee.eventbus.JsonSchemaDocumentEvent",
request:context ():createSubEventContext (1), jsonDoc)
ok, result = JSLEE.send(targetEndpoint, jsonSchemaDocumentEvent)
if (ok) then
JSLEE.succeeded (0)
else
JSLEE.failed(-1, result)
end
JSLEE.createContext (sessionId, eventId)
Description
This method creates a JSLEE context object with the provided parameters. Such an object is required when creating events to pass across the JSLEE.
Arguments
Argument | Comments |
---|---|
sessionId |
An string identifier common to all events associated with a particular session or transaction, distinguishing that set of events from events associated with all other sessions or transactions. The session or transaction concept is determined by the particular use context. |
eventId |
An identifier common to all events triggered by a particular initiating event. This identifier is not expected to be unique by itself. However, it must uniquely identify events with in a session. Most often the value is expected to be numeric and sequential. |
Returns
Number | Type | Comments |
---|---|---|
1 | Object | The created JSLEE context object. |
Example
jsonSchemaDocumentEvent = JSLEE.createEvent (JSLEE.createContext (sessionId, eventId),
"nz.co.nsquared.slee.eventbus.JsonSchemaDocumentEvent", jsonDoc)
ok, result = JSLEE.send(targetEndpoint, jsonSchemaDocumentEvent)
if (ok) then
JSLEE.succeeded (0)
else
JSLEE.failed(-1, result)
end
JSLEE.send (addressToSendTo, eventToSend)
Description
This method will send the given event message over the JSLEE event bus to the given address string.
Once a response is received, the script will continue after the method call (even if the response is empty). This allows asynchronous messages to be viewed and handled synchronously by Lua code implementations.
If the message object received in the response is of a known Lua type, it will be automatically wrapped to allow API use on it.
Arguments
Argument | Comments |
---|---|
addressToSendTo |
The address to send the event to. |
eventToSend |
The constructed event to send. |
Returns
Number | Type | Comments |
---|---|---|
1 | Boolean | Whether the message was successfully handled or not. |
2 | Object or String | If ok is true , the returned (possibly wrapped) object. If ok is false , an error string detailing issues with processing the event. |
If an error string is returned, it can be passed to the JSLEE error-parsing
functions getErrorCode
and getErrorString
for convenience.
JSLEE.getErrorCode (errorResult)
Description
This method will parse an error string returned from JSLEE.send
and
return the error code portion, if any. If the error code is not parseable,
a value of nil
will be returned.
Arguments
Argument | Comments |
---|---|
errorResult |
The error string to parse. |
Returns
Number | Type | Comments |
---|---|---|
1 | Integer | The error code, if it exists. |
Example
event = JSLEE.createEvent ("nz.co.nsquared.slee.smpp.event.SMPPMessageEvent", context, sms)
ok, result = JSLEE.send(smppEndpoint, event)
if not ok then
local errorCode = JSLEE.getErrorCode (result)
JSLEE.getErrorMessage (errorResult)
Description
This method will parse an error string returned from JSLEE.send
and
return the error message portion, if any. If the error code is not parseable,
a value of nil
will be returned.
Arguments
Argument | Comments |
---|---|
errorResult |
The error string to parse. |
Returns
Number | Type | Comments |
---|---|---|
1 | String | The error message, if it exists. |
Example
event = JSLEE.createEvent ("nz.co.nsquared.slee.smpp.event.SMPPMessageEvent", context, sms)
ok, result = JSLEE.send(smppEndpoint, event)
if not ok then
local errorMessage = JSLEE.getErrorMessage (result)
JSLEE.getErrorDetails (errorResult)
Description
This method is shorthand for returning the results of both the getErrorCode
and getErrorMessage
functions.
Arguments
Argument | Comments |
---|---|
errorResult |
The error string to parse. |
Returns
Number | Type | Comments |
---|---|---|
1 | Integer | The error code, if it exists. |
2 | String | The error message, if it exists. |
Example
event = JSLEE.createEvent ("nz.co.nsquared.slee.smpp.event.SMPPMessageEvent", context, sms)
ok, result = JSLEE.send(smppEndpoint, event)
if not ok then
local errorCode, errorMessage = JSLEE.getErrorDetails (result)
JSLEE.logger ()
Description
This method returns an SLF4J logger object for logging output in Lua scripts.
Arguments
None.
Example
local logger = JSLEE.logger()
logger:info("[smpp-to-json-document.lua] Will send translated Json documents to '" .. targetEndpoint .. "'")
JSLEE.debug (target, [prefix])
Description
This method recursively outputs debug for the supplied target
. This output
is sent to the logger returned from JSLEE.logger()
and is prefixed with
the prefix
string, if it is provided.
Arguments
Argument | Comments |
---|---|
target |
The item to output as debug. Can be any Lua type that can be cast to a string, or a Lua table. Tables will output in a format that allows direct copying back to a Lua script |
prefix |
The string to prefix the debug output with. Optional, defaults to an empty string if not provided. |
Example
resp = SMPPMessage:create("SubmitSm")
resp:setMessage("Your balance is $123.45.")
resp:setSender("123")
resp:setDestination("456")
JSLEE.debug(resp)
Output from the above might be:
10:26:43.776 [Coroutine-1] DEBUG nz.co.nsquared.slee.scriptengine.LuaScriptEngineVerticle - LUA DEBUG: {
10:26:43.776 [Coroutine-1] DEBUG nz.co.nsquared.slee.scriptengine.LuaScriptEngineVerticle - LUA DEBUG: ['wrapped'] = '[submit_sm ESME_OK, SEQ 0, LEN ???][LEN: 70]'
10:26:43.776 [Coroutine-1] DEBUG nz.co.nsquared.slee.scriptengine.LuaScriptEngineVerticle - LUA DEBUG: }
JSLEE.enforceTable / enforceString / enforceNumber / enforceBoolean (value, message)
Description
This utility method raises a Lua error
with the provided message
if the
value
is not of the specified type:
JSLEE.enforceTable
:value
must be a Lua table.JSLEE.enforceString
:value
must be able to be used as a string.JSLEE.enforceNumber
:value
must be able to be used as a number.JSLEE.enforceBoolean
:value
must be able to be used as a boolean.
Arguments
Argument | Comments |
---|---|
value |
The value to check. |
message |
The message to raise in the Lua error if the check fails. |
Returns
Nothing.
Example
function sendMessage (t) end
JSLEE.enforceTable (t)
-- Safe to index now
local p = t["key"]
JSLEE.isTable / isString / isNumber / isBoolean (value)
Description
This utility method returns true
if the provided value
is of the
specified type:
JSLEE.isTable
:value
must be a Lua table.JSLEE.isString
:value
must be able to be used as a string.JSLEE.isNumber
:value
must be able to be used as a number.JSLEE.isBoolean
:value
must be able to be used as a boolean.
Arguments
Argument | Comments |
---|---|
value |
The value to check. |
Returns
Number | Type | Comments |
---|---|---|
1 | Boolean | Whether the input value conforms to the specified type or not. |
Example
function sendMessage (t) end
if JSLEE.isTable (t) and JSLEE.isTable (t.value) then
-- safe to use t.value as a table
local value = t.value.target
JSLEE.nval (value)
Description
This utility method returns the string “nil” if the input value
is nil
.
Otherwise, it returns the provided value
.
This is generally used for string concatenation to avoid Lua exiting with
an error if a nil
value is encountered.
Arguments
Argument | Comments |
---|---|
value |
The value to process. |
Returns
Number | Type | Comments |
---|---|---|
1 | String or Object | Either the string “nil” or the input value . |
Example
if not found then
JSLEE.failed (404,
"No matching request found for ID '" .. JSLEE.nval (id) .. "' with request " .. JSLEE.nval (name))
end
JSLEE.fileSeparator ()
Description
This utility method returns the file and path separator charcter for the
current locale, taken from the core Java File
class’s fileSeparator
function.
Arguments
None.
Returns
The character used by the current locale for separating filenames and paths.
Example
JSLEE.debug (JSLEE.fileSeparator (), "File separator character: ")
On Windows, the output from the above would be:
File separator character: \
On Linux, the output would be:
File separator character: /
JSLEE.pathSeparator ()
Description
This utility method returns the path list separator charcter for the
current locale, taken from the core Java File
class’s pathSeparator
function.
Arguments
None.
Returns
The character used by the current locale for separating paths in a list.
Example
JSLEE.debug (JSLEE.pathSeparator (), "Path separator character: ")
On Windows, the output from the above would be:
File separator character: ;
On Linux, the output would be:
File separator character: :
JSLEE.traceengine.addTrace (key, value)
This function allows addition of a traced key-value pair to the JSLEE tracing subsystem.
The values passed in are arbitrary strings that are interpreted by JSLEE services and business logic when deciding whether to output trace details.
If the key-value pair already exists, the addition is ignored.
Arguments
Argument | Comments |
---|---|
key |
The string to use as the trace item lookup key. |
value |
The string to use as the trace item comparison value. |
Returns
Nothing.
Example
local msisdn = "6421682277"
JSLEE.traceengine.addTrace ("msisdn", msisdn)
JSLEE.traceengine.trace ("msisdn", msisdn, event.id, "Lua logic", "Trace enabled.")
JSLEE.traceengine.removeTrace (key, value)
This function allows removal of a traced key-value pair from the JSLEE tracing subsystem.
If the key-value pair does not already exist, the removal is ignored.
Arguments
Argument | Comments |
---|---|
key |
The string used as the trace item lookup key. |
value |
The string used as the trace item comparison value. |
Returns
Nothing.
Example
local msisdn = "6421682277"
JSLEE.traceengine.trace ("msisdn", msisdn, event.id, "Lua logic", "Removing trace.")
JSLEE.traceengine.removeTrace ("msisdn", msisdn)
JSLEE.traceengine.isTraced (key, value)
This function allows runtime checking of whether a key-value pair is currently traced by the JSLEE tracing subsystem.
Arguments
Argument | Comments |
---|---|
key |
The string used as the trace item lookup key. |
value |
The string used as the trace item comparison value. |
Returns
true
if the key-value pair provided is currently traced, otherwise false
.
Example
local msisdn = "6421682277"
if JSLEE.traceengine.isTraced ("msisdn", msisdn) then
-- tracing is enabled, write details
file = io.open (traceOutputDetailFile, "a")
file:write (subscriberDetails, "\n")
end
JSLEE.traceengine.trace (key, value, id, source, output)
Calling this function will output a logged message at the log level TRACE
if the key-value pair provided is currently traced by the JSLEE tracing
subsystem. This output will include all details provided.
If the key-value pair is not traced, no output occurs.
Arguments
Argument | Comments |
---|---|
key |
The string used as the trace item lookup key. |
value |
The string used as the trace item comparison value. |
id |
For consistency, should be the unique ID of the JSLEE session (taken from the received event). However, it may be an arbitrary string. |
source |
The string to use as the source system details. |
output |
The string to output as traced information. |
Returns
Nothing.
Example
local msisdn = "6421682277"
JSLEE.traceengine.addTrace ("msisdn", msisdn)
JSLEE.traceengine.trace ("msisdn", msisdn, event.id, "Lua logic", "Trace enabled.")
JSLEE.traceengine.debug (key, value, id, source, output)
This function is identical to the JSLEE.traceengine.trace
trace function
but will output a logged message at the log level DEBUG
instead.
JSLEE.createSuccessEdr (event, type, message, timestamp, args)
, JSLEE.createFailureEdr (event, type, message, failureClass, failureCode, timestamp, args)
Description
These methods create an Event Data Record from the provided parameters and submits it to the configured EDR interface on the Lua service.
If required fields are not populated, a Lua error will be thrown. Additional required generic EDR parameters are inserted by the Lua service when the EDR is created; refer to the EDR documentation for details.
Note that EDRs will only be created if the Lua service instance has EDRs enabled. Refer to the EDR configuration documentation for details.
Arguments
Argument | Comments |
---|---|
event |
The JSLEE event that caused the EDR to be written. Will normally be the received event from the JSLEE (provided in the handler.handle() method signature), but may be a created event if required. This field must be populated with an appropriate object. |
type |
A string value indicating the type of EDR. This field must be populated, but its value is implementation-specific. |
message |
A string value indicating the outcome of the action that caused the EDR. For success EDRs, if this value is nil , the value OK will be inserted. For failure EDRs, this value must be provided. |
failureClass |
A string value indicating the failure type of the action that caused the EDR. If this value is nil , the value other will be inserted. |
failureCode |
A numeric value indicating the error code of the failure experienced. This field must be populated, but its value is implementation-specific. |
timestamp |
An ISO-8601 string indicating the time the message that triggered the EDR was received. If not populated, will be set to the time of EDR creation. |
args |
A optional table of additional EDR parameters of arbitrary depth and complexity. These values will be written to the EDR created as-received. If supplied, must be a Lua table. |
Returns
Number | Type | Comments |
---|---|---|
1 | Boolean | Whether the EDR was created and submitted to the EDR storage system. |
2 | String | Freeform text indicating the reason for the result received. |
Example
local edrOk, message = JSLEE.createSuccessEdr(receivedEvent, 'lua-edr', nil, nil, {
something = 1
})
if edrOk then
JSLEE.debug("EDR written successfully: " .. JSLEE.nval(message))
else
JSLEE.debug("EDR NOT written successfully: " .. JSLEE.nval(message))
end
The above EDR would render a result similar to:
{
"event-timestamp": "2017-10-19T01:53:17.333589300Z",
"node-name": "n2jslee",
"slee-event-id": "event1",
"slee-session-id": "392794ed-8614-4e3e-9233-88c7e4591a8e",
"something": 1,
"source-info": {
"source-service": "lua-service",
"source-system": "Lua"
},
"status-message": "OK",
"type": "lua-edr"
}
JSLEE.now ()
Description
This method returns a UTC ISO-8601 string with the current system time.
Arguments
None.
Returns
Number | Type | Comments |
---|---|---|
1 | String | An ISO-8601 UTC string representing the current system time. |
Example
local edrOk, message = JSLEE.createSuccessEdr(receivedEvent, 'lua-edr', nil, JSLEE.now ())
JSLEE.startsWith (str, start)
Description
This method returns true if the provided string str
starts with the provided string start
.
Arguments
Argument | Comments |
---|---|
str |
The string to analyse. |
start |
The prefix to compare. |
Returns
Number | Type | Comments |
---|---|---|
1 | Boolean | true if the provided string str starts with the provided string start , otherwise false . |
Example
if JSLEE.startsWith("abc", "c") then
JSLEE.endsWith (str, ending)
Description
This method returns true if the provided string str
ends with the provided string ending
.
Arguments
Argument | Comments |
---|---|
str |
The string to analyse. |
ending |
The suffix to compare. |
Returns
Number | Type | Comments |
---|---|---|
1 | Boolean | true if the provided string str ends with the provided string ending , otherwise false . |
Example
if JSLEE.endsWith("abc", "c") then
JSLEE.getPseudoUUID ()
Description
This method returns a random string in a UUID format. It is not a genuine UUID, but a pseudorandom string.
Arguments
None.
Returns
Number | Type | Comments |
---|---|---|
1 | String | A pseudorandom UUID string in the format xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx . |
Example
local context = JSLEE.createContext (JSLEE.getPseudoUUID(), '1')
JSLEE.natures ()
Description
This method returns all supported normalistion natures.
Arguments
None.
Returns
Number | Type | Comments |
---|---|---|
1 | Table | An array containing all supported normalisation nature values. |
Example
JSLEE.debug(JSLEE.natures(), "Supported natures: ")
The above would produce output similar to:
Supported natures: {
Supported natures: [1] = 'unknown',
Supported natures: [2] = 'national',
Supported natures: [3] = 'international',
Supported natures: [4] = 'network',
Supported natures: [5] = 'subscriber',
Supported natures: [6] = 'alphanumeric',
Supported natures: [7] = 'abbreviated'
Supported natures: }
JSLEE.getNormalisationService ()
Description
This method returns the JSLEE normalisation service for the Lua verticle.
Arguments
None.
Returns
Number | Type | Comments |
---|---|---|
1 | Object | The normalisation service for the verticle. |
Example
local normalisation = JSLEE.getNormalisationService()
JSLEE.normalise (nature, target)
Description
This method normalises the given target
assuming the provided nature
.
If either of the required fields are not populated, a Lua error will be thrown.
Similarly, if the nature
provided is not a valid value (i.e. does not match
one of the output values from JSLEE.natures()
), an error will be thrown.
Note that normalisation will only be performed if the Lua service instance has normalisation enabled. Refer to the normalisation configuration documentation for details.
Arguments
Argument | Comments |
---|---|
nature |
A string value indicating the nature of the target . Must match a returned value from JSLEE.natures() . |
target |
A string value to normalise. |
Returns
Number | Type | Comments |
---|---|---|
1 | Boolean | Whether the configured normalisation rules found a match to the target . |
2 | String | The (possibly transformed) target value after normalisation. |
Example
local matched, result = JSLEE.normalise("unknown", "12345")
if matched then
-- normalisation occurred
JSLEE.denormalise (target)
Description
This method denormalises the given target
.
If the target
is not populated, a Lua error will be thrown.
Note that denormalisation will only be performed if the Lua service instance has normalisation enabled. Refer to the normalisation configuration documentation for details.
Arguments
Argument | Comments |
---|---|
target |
A string value to denormalise. |
Returns
Number | Type | Comments |
---|---|---|
1 | Boolean | Whether the configured denormalisation rules found a match to the target . |
2 | String | The (possibly transformed) target value after denormalisation. |
3 | String | The numbering plan set after denormalisation. |
4 | String | The nature set after denormalisation. |
Example
local matched, result, plan, ton = JSLEE.denormalise("12345")
if matched then
-- denormalisation occurred