sys.utils.text
This package contains methods to manipulate text.
findTokens(text)
Finds all tokens in a string (can be multi-line string). Tokens are started with #
and have the following format:
#name:value
#name:value1,value2,value3
#name
This way you could have a text like this:
#project:test
#assignee:user1
#important
There is a bug with user profile popup!
This way you can use this method to easily extract the tokens project
, assignee
, and important
.
This method is very useful to parse commands in plain text messages, for example, emails or instant messages.
Parameters
Name | Type | Required | Default | Description |
---|---|---|---|---|
text |
|
yes |
Text to parse to find tokens. |
Returns
object
- A key-value structure where the key is the token name. Value could be an array if there is more than one value.
For example, given the following text:
#project:test1
#assignee:admin
#watchers:user1,user2
#important
This is an important issue! Please fix.
Also related to #project:test2
Tokens will be:
{
project: ['test1', 'test2'],
assignee: 'admin',
watchers: ['user1', 'user2'],
important: true
}
Notice that when you don’t specify a value for the token, it will be set to true
.
Samples
// finds tokens in a string
var str = "this is a ticker #project:test1 #type:bug #hotfix";
var tokens = sys.utils.text.findTokens(str);
log('tokens: '+JSON.stringify(tokens));
processTemplate(template, options)
Allows to process a Freemarker template. You can find more information about Freemarker here.
Parameters
Name | Type | Required | Default | Description |
---|---|---|---|---|
template |
|
yes |
The Freemarker template |
|
options |
|
no |
Options to process the template. These are the available options:
|
Returns
string
- The processed template
Samples
// process a template for an email for a contact
var record = sys.data.findOne('contacts', {email: 'gowensb1@google.ca'});
var recordStr = record.toJson({relationshipsToFetch: 'company', user: 'gowensb1@google.ca '});
var template = "Hi ${contact.firstName} ${contact.lastName}:\n\n We want to say hi!\n\nThanks!";
var emailContent = sys.utils.text.processTemplate(template, {
model: {
contact: recordStr
}
});
log('email content: '+emailContent);
htmlToText(html)
Allows to convert an html text into a plain text by removing html tags.
Parameters
Name | Type | Required | Default | Description |
---|---|---|---|---|
html |
|
yes |
The html text to be parsed |
Returns
string
- A plain text with html tags removed
Samples
// convert an html text into a plain text
var html = "<strong>This is sparta</strong>";
var text = sys.utils.text.htmlToText(html);
log('Text: ' + text);
textToHtml(text)
Allows to convert a plain text into an html text.
Parameters
Name | Type | Required | Default | Description |
---|---|---|---|---|
text |
|
yes |
The text to be parsed |
Returns
string
- An html text with plain text tokens removed
Samples
// convert a plain text into an html text
var text = "This is sparta\n";
var html = sys.utils.text.textToHtml(text);
log('HTML: ' + html);
markdownToHtml(markdownText)
Allows to convert a markdown text into an html text by transforming markdown tokens into html tags.
Parameters
Name | Type | Required | Default | Description |
---|---|---|---|---|
markdownText |
|
yes |
The markdown text to be parsed |
Returns
string
- An html text with markdown tokens transformed into html tags
Samples
// convert a markdown text into an html text
var markdown = "**This is sparta**";
var html = sys.utils.text.markdownToHtml(markdown);
log('HTML: ' + html);
htmlToMarkdown(html)
Allows to converts an html text into a markdown text by transforming html tags into markdown tokens.
Parameters
Name | Type | Required | Default | Description |
---|---|---|---|---|
html |
|
yes |
The html text to be parsed |
Returns
string
- A markdown text with html tags transformed into html tags.
Samples
// convert an html text into a markdown text
var html = "<strong>This is sparta</strong><br/>";
var markdown = sys.utils.text.htmlToMarkdown(html);
log('Markdown text: ' + markdown);
sys.utils.xml
This package contains methods to manipulate xml format.
xmlToJson(xml)
Allows to convert a XML text into a JSON object.
Parameters
Name | Type | Required | Default | Description |
---|---|---|---|---|
xml |
|
yes |
The xml text to be converted |
Returns
object
- the JSON representation of the given XML
Samples
// convert an XML text into a JSON object
var xml = '<note><to>Tove</to><from>Jani</from></note>';
var json = sys.utils.xml.xmlToJson(xml);
log('Json: ' + JSON.stringify(json));
// this will print {"note":{"to":"Tove","from":"Jani"}}
jsonToXml(json)
Allows to convert a JSON object into a XML string.
Parameters
Name | Type | Required | Default | Description |
---|---|---|---|---|
json |
|
yes |
The JSON object to be parsed |
Returns
string
- A XML text
Samples
// convert a JSON object into a XML text
var json = {"note":{"to":"Tove","from":"Jani"}};
var xml = sys.utils.xml.jsonToXml(json);
log('XML: ' + xml);
sys.utils.base64
This package contains utilities for Base64 encoding. This is used to represent binary data in an ASCII format.
encode(string)
Encodes binary data using the base64 algorithm. It does not chunk the output.
Parameters
Name | Type | Required | Default | Description |
---|---|---|---|---|
string |
|
yes |
Data to be encoded |
Returns
string
- A string containing Base64 characters in their UTF-8 representation.
Samples
// encode a string
var pass = 'This_is_a_pass';
var encodedPass = sys.utils.base64.encode(pass);
log('Encoded pass: ' + encodedPass);
decode(base64String)
Decodes a Base64 string into octets.
Parameters
Name | Type | Required | Default | Description |
---|---|---|---|---|
base64String |
|
yes |
String containing base 64 data |
Returns
string
- Decoded data.
Samples
// decode an encoded string
var pass = 'VGhpc19pc19hX3Bhc3M=';
var rawPass = sys.utils.base64.decode(pass);
log('Pass: ' + rawPass);
sys.utils.numbers
This package contains methods to help manage numbers.
BigNumber()
A library for arbitrary-precision decimal and non-decimal arithmetic. For more information: http://mikemcl.github.io/bignumber.js/
Samples
// Returns a BigNumber whose value is the value of this BigNumber plus n
var n = 0.2;
var bigNumber = sys.utils.numbers.BigNumber(0.1);
return bigNumber.plus(n);
format(value, options)
Returns a string of formatted number of the value or string without format.
Parameters
Name | Type | Required | Default | Description |
---|---|---|---|---|
value |
|
yes |
The value to be formatted |
|
options |
|
no |
Display options parameters used to format value. If it is empty the default display options are used to format.
|
Returns
string
- string of formatted value of number.
Samples
// prints the formatted value of a decimal value
var options = {thousandsSeparator: true, limitNumberOfDecimals:true, numberOfDecimals: 3};
var formattedNumber = sys.utils.numbers.format(12345.12345, options);
log('Result: ' + formattedNumber);
getRandomValue()
Using a random number algorithm generates a strong cryptographic decimal number between 0.0 and 1.0.
Returns
number
- A decimal number between 0.0 and 1.0.
Samples
// prints a random number.
var randomNumber = sys.utils.numbers.getRandomValue();
log('Result: ' + randomNumber);
sys.utils.crypto
This package contains methods to work with simple cryptographic operations.
sha1(message)
Calculates the SHA-1 digest and returns the value as a hex string.
Parameters
Name | Type | Required | Default | Description |
---|---|---|---|---|
message |
|
yes |
The string to be converted |
Returns
string
- The result hash as String.
Samples
// converts a company to the string representation
var convertedMessage = sys.utils.crypto.sha1('my custom message');
log('SHA-1 string: '+convertedMessage);
sha3(message, bits)
Calculates the SHA-3 digest and returns the value as a hex string.
Parameters
Name | Type | Required | Default | Description |
---|---|---|---|---|
message |
|
yes |
The string to be converted |
|
bits |
|
no |
Valid number of bits for conversion (default 256) |
Returns
string
- The result hash as String.
Samples
// converts a company to the string representation
var convertedMessage = sys.utils.crypto.sha3('my custom message');
log('SHA-3 string: '+convertedMessage);
keccak(message, bits)
Calculates the KECCAK digest and returns the value as a hex string.
Parameters
Name | Type | Required | Default | Description |
---|---|---|---|---|
message |
|
yes |
The string to be converted |
|
bits |
|
no |
Valid number of bits for conversion (default 256) |
Returns
string
- The result hash as String.
Samples
// converts a company to the string representation
var convertedMessage = sys.utils.crypto.keccak('my custom message');
log('Keccak string: '+convertedMessage);
sys.utils.time
This package contains methods to work with time.
getTimeZoneOffset(timeZoneId, timestamp)
Obtains the offset in milliseconds between given time zone and standard time zone (GMT). If daylight saving time is in effect at the specified time zone, the offset value is adjusted with the amount of daylight saving.
Parameters
Name | Type | Required | Default | Description |
---|---|---|---|---|
timeZoneId |
|
yes |
The ID for a time zone. Valid time zone codes are:
|
|
timestamp |
|
no |
The point in time the time zone offset should be calculated. If it is not specified then the current date time is going to be used. |
Returns
number
- The timezone offset in milliseconds.
Samples
// Logs the specific time zone in hours
var offset = sys.utils.time.getTimeZoneOffset('America/Buenos_Aires');
log('offset in hours: '+offset/1000/60/60);
setTimeZone(date, timeZoneId)
Apply the offset between given time zone and standard time zone (GMT) to the passed date.
Parameters
Name | Type | Required | Default | Description |
---|---|---|---|---|
date |
|
yes |
The date to apply the given offset |
|
timeZoneId |
|
yes |
The ID for a time zone. Valid time zone codes are:
|
Returns
object
- The date with the time zone applied.
Samples
// Apply the specified time zone to the given date
var dateWithOffset = sys.utils.time.setTimeZone(new Date(), 'America/Buenos_Aires');
log('date modified: ' + dateWithOffset);
format(date, pattern, timezone)
Apply the pattern and the time zone to a date and return it as string.
Parameters
Name | Type | Required | Default | Description |
---|---|---|---|---|
date |
|
yes |
The date to apply the given pattern and offset |
|
pattern |
|
yes |
The pattern to format the date |
|
timezone |
|
no |
Timezone configuration object or the string code for a time zone. If it is not specified the default app timezone is going to be used. Valid time zone codes are:
|
Returns
string
- The date with the time zone applied.
Samples
// Apply the specified format and time zone to the given date
var formattedDate = sys.utils.time.format(new Date(), 'yyyy-MM-dd HH:mm Z', 'America/Buenos_Aires');
log('date formatted is: ' + formattedDate);
parse(date, pattern, timezone)
Parse a date string using pattern and time zone and return it as date object.
Parameters
Name | Type | Required | Default | Description |
---|---|---|---|---|
date |
|
yes |
The date string to parse using the given pattern and timezone |
|
pattern |
|
yes |
The pattern to parse the date string |
|
timezone |
|
no |
Timezone configuration object or the string code for a time zone. If it is not specified the default app timezone is going to be used. Valid time zone codes are:
|
Returns
object
- The final parsed date object with the time zone applied.
Samples
// Parse given date using a specific pattern and timezone
var parsedDate = sys.utils.time.parse('2020-07-17 13:30', 'yyyy-MM-dd HH:mm', 'America/Buenos_Aires');
log('date is: ' + parsedDate);
sys.utils.concurrency
This package contains methods to help manage cases with concurrency issues.
tryLock(key, timeout)
Tries to acquire a lock for a specified key.
This method could be used when multiple threads need some sort of synchronization.
Important Developers have to make sure to release locks. We recommend to always use try/finally clauses to perform that. The platform will release locks automatically after the script is fully executed, but it is better to do it explicitly.
Parameters
Name | Type | Required | Default | Description |
---|---|---|---|---|
key |
|
yes |
Key to be locked. |
|
timeout |
|
yes |
Maximum time in seconds to wait for the lock. |
Returns
boolean
- true
if the lock was acquired, false
otherwise.
Samples
// locks the key 'lock1'
if (sys.utils.concurrency.tryLock('lock1')) {
try {
sys.logs.info('lock acquired!');
} finally {
sys.utils.concurrency.unlock('lock1');
}
}
lock(key, timeoutOrSuccessCallback, successCallback)
Acquires a lock for a specified key.
This method could be used when multiple threads need some sort of synchronization.
Important Developers have to make sure to release locks. We recommend to always use try/finally clauses to perform that. The platform will release locks automatically after the script is fully executed, but it is better to do it explicitly.
Parameters
Name | Type | Required | Default | Description |
---|---|---|---|---|
key |
|
yes |
Key to be locked. |
|
timeoutOrSuccessCallback |
|
no |
Maximum time in seconds to wait for the lock or callback executed after the lock is acquired successfully. If this parameter is a function then the lock is released automatically. |
|
successCallback |
|
no |
Maximum time in seconds to wait for the lock or callback to beexecuted after the lock is acquired successfully. If this parameter is used then the lock is released automatically. |
Exceptions
timeout
If lock could not have been acquired.
Samples
// locks the key 'lock1'
try {
sys.utils.concurrency.lock('lock1');
sys.logs.info('lock acquired!');
//do something
sys.utils.concurrency.unlock('lock1');
} catch (e) {
sys.logs.error('lock NOT acquired!')
}
// locks the key 'lock1' using a callback
sys.utils.concurrency.lock('lock1', function () {
sys.logs.info('lock acquired!');
});
// lock will be released automatically
unlock(key)
Releases a lock for a specified key.
Parameters
Name | Type | Required | Default | Description |
---|---|---|---|---|
key |
|
yes |
Key to be released. |
Samples
// acquires and release the lock over key 'lock1'
if (sys.utils.concurrency.lock('lock1')) {
try {
log('lock acquired!');
} finally {
sys.utils.concurrency.unlock('lock1');
}
}
forceUnlock(key)
Releases a lock for a specified key. This is useful for mantenaince purposes.
Parameters
Name | Type | Required | Default | Description |
---|---|---|---|---|
key |
|
yes |
Key to be released. |
Samples
// acquires and force to release the lock over key 'lock1'
if (sys.utils.concurrency.lock('lock1')) {
try {
log('lock acquired!');
} finally {
sys.utils.concurrency.forceUnlock('lock1');
}
}
sys.utils.script
This package contains misc methods useful when scripting.
wait(timeToWait)
Waits blocking the execution of the script.
Parameters
Name | Type | Required | Default | Description |
---|---|---|---|---|
timeToWait |
|
yes |
The number of milliseconds to wait. |
Samples
// waits for 2 seconds
sys.utils.script.wait(2000);
// continue execution
eval(scriptToEval, context)
Evaluates JavaScript code represented as a string as classic eval but storing code to be displayed in case of errors.
Parameters
Name | Type | Required | Default | Description |
---|---|---|---|---|
scriptToEval |
|
yes |
Script to be evaluated. |
|
context |
|
no |
Object that will be used as |
Returns
object
- result of eval
Samples
// log message through eval
var code = 'sys.logs.debug("My custom message")';
sys.utils.script.eval(code); - title: log message through eval
// indirect call trying to use a callback
var message = 'My custom message';
var code = '\nvar callback = function(msg) {';
code += '\n\tsys.utils.script.eval("sys.logs.debug(\'"+msg+"\')");';
code += '\n}';
code += '\ncallback(context.msg)';//note that `context` usage is required to work with indirect callback
sys.utils.script.eval(code, {msg: message}); //here the second parameter is the context that will be used as `this` object in `eval`