Workflow Functions

Reference

Index

Miscellaneous Api Functions

getResource(resource)

Reads a file or the contents of a classpath resource.

Parameters

resource : Either the class path reference (/mypropertyfile.properties) or absolute path to a file

Returns

content of the resource

Will replace key objects in the template string.

Parameters

template contains the complete string that needs to be translated, so containing the $key callbackOrData is an object containing the string to be replaced, key=value or a callback for when a key was found. eg.

Returns

content of the string with keys replaced by the actual values.

var person = {
   name: "doe",
   firstname : "john"
};

tb.templater('Hello $firstname $name',person); // 'Hello john doe'

tb.templater('Hello $firstname $name', function(key) {
   if(key === '$firstname')
    return 'World';
   else
    return '';
});  // 'Hello World'

tb.templater('Hello $firstname $name', function(key) {
   if(key === '$firstname')
    return 'World';
   else
    return key;
});  // 'Hello World $name'

Log a string to the logfile / console

Parameters

msg : Message to log component: Component that logs the message [optional] level: level to log to ('trace' =default /'debug'/'info'/'warn'/'error') [optional]

Encode a string to to a SHA1 encoded string SHA-1 produces a 160-bit message digest.

Encode a string to to a MD5 encoded string MD-5 produces a 160-bit message digest.

Generate a uuid

Convert given array into a Java list.

Convert a string into a byte[]

Decode a base64 string into a byte[] or string. Set Booelan to true to convert to string.

base32Encode encode a byte array into a base64 string

* @param base32String string to decode

 * @param decodingFormat base64/hex/string to re-encode the payload the bytes

base32Decode decode a base32 string into a byte array

 * @param base32String string to decode

 * @param decodingFormat base64/hex/string to re-encode the payload the bytes

Decrypts an encrpyted string, this way you can store password in scripts.

Encode a byte[] or string to a base64 string.

Decode a base64 string into a byte[] or string. Set Booelan to true to convert to string.

Encode a byte[] or string to a base64 string.

Decode a hex string into byte[]

Encode a byte[] into hex representation

call allows for services or plugins to be called from within the scripts

@param serviceId id of the service referenced in the config

@return service

get the encryption service

 generateResponse Helper function to generate response objects returned to the endpoints

 @param body plain string containing the body

 @param headers object containing the headers as key-value pairs

 @param cookies object containing the cookies as key-value pairs

 @param status status code to return to

 

  A cookie can have the following properties (value is mandatory):

  {

     value: '',

    comment: '',

    domain: '',

    path: '',

    maxage: 0, // maximum age of the cookie (-1 for session)

    secure: true/false

  }

parseRequest This object has the following properties/functions:

 @param endpointRequest

 @return {Object} native js-request with items

  •  headers: containing all headers
  • cookies: containing all cookies
  • parameters: containing all passed parameters (empty for every endpoint except html-endpoint), value is an array !!
  • parameter: function returning the value if there is only one value for a certain parameter, array in every other case
  • body: string containing the body
  • bodyAsXml: function returning the body as an xml object (if it actually is one)

 

storeInContext Add something in the current context

@param sessionHash string used as sticky session in load balancing

@return integer for future reference

Encrypt data with a shared secret via AES_128

Parameters

keyString [base64 string] or key [bytearray] used for shared secret dataString [base64 string] or data [bytearray] used for encryption cipherType : cipher to use (DESEDE/AES128/AES192/AES256) returnType: 'base64' / 'hex' / 'bytearray'

Returns

base64 encrypted string

Decrypt data with a shared secret via AES_128

Parameters

keyString [base64 string] or key [bytearray] used for shared secret dataString [base64 string] or data [bytearray] used for decryption cipherType : cipher to use (DESEDE/AES128/AES192/AES256) returnType: base64,hex,bytearray,string, base64 is the default

Returns

decrypted data as returnType

Encrypt data with a public/private keypair via RSA_1024

Parameters

publicKeyString [base64 string] or publicKey [bytearray] used for encryption dataString [base64 string] or data [bytearray] used for encryption

Returns

base64 encrypted string

Decrypt data with apublic/private keypair via RSA_1024

Parameters

privateKeyString [base64 string] or privateKey [bytearray] used for decryption dataString [base64 string] or data [bytearray] used for decryption

Returns

base64 decrypted data decrypt(encryptedString) Decrypt a base64 encrypted item via the tbPassword shell command.

Set an (sticky over the request) identifier allowing loadbalanced adapters to hit the same server over multiple requests. Can be used for example to have one client to be querying the same server with a multi-server adapter. This sessionHash doesn't require a real session, but if session management is enabled it will default to the session key by default.

Set a value in the session with a specific key. Note: this requires session management enabled (see session management)

Retrieve a value from the session with a specific key.

Set a value on the request which will be exposed in the workflow on the workitem

invalidateSession()

Invalidate the user session.

Set a number of seconds to timeout a session for a user.

Get a value from the request (this is also exposed in the workItem)

validate request and if not valid log errors and return null

Get an identifier for this particular request. By default this is a sequential number, but this is customisable (for adding eg. ip / principal)

Retrieve a service defined in the config.xml for executing inline functions

eg. getService(sessionService).put(key,value)

Would call the sessionService to put (get/delete) a key/value pair to the memory store.

Look up a string out of the jndi tree and return.

Bind a value to a key in the jndi tree.

Escape special characters for ldap search filters. Please make sure to check the input for special characters and make your filter injection proof !

This function is best used as the UrlEncode functions inline.

workItem.user = testuser\\saml
var search = ( + tb.ldapEncodeFilter(cn= + workItem.user) + );

// Testcase example 
tb.ldapEncodeFilter('testuser\\saml') === 'testuser2\5csaml'

Do not escape your search operators.

Escape special characters in a Rdn.

Add a step in the embedded flow. (See auditting)

Retrieve the current flow for this request

Xml Functions

parse the xml into a variable

Parameters

text : xml formatted text schema: (optional) if given must be path to xml schema or object containing key as namespace and value to the location of the xml schema

Returns

instance of the document eg.

var document = xml.parse(
    '<root> \
        <info><msg>1</msg></info> \
        <warn><msg>2</msg></warn> \
        <debug><msg>3</msg></debug> \
        <tb:msg xmlns:tb='http://www.trustbuilder.com'>b msg</tb:msg> \
    </root>'
);
document.registerNamespace('tb','http://www.trustbuilder.com');
var messages = document.getElements('//msg'); 
// [ element(<msg>1</msg>), element(<msg>2</msg>), element(<msg>3</msg>) ]
var messagesContent = document.getElementsAsString('//msg');
// [ '<msg>1</msg>', '<msg>2</msg>', '<msg>3</msg>' ]
var firstMessage = document.getFirstElement('//msg');
// element(<msg>1</msg>)
var firstMessageText = document.getFirstElementAsString('//msg');
// '<msg>1</msg>'
var firstValue = document.getFirstValue('//msg');
// '1'

var firstValuetb = document.getFirstValue('//tb:msg');
// 'b msg'

for(var i = 0;i<messages.length;i++){
  var value = messages[i].getValue();
  tb.log(value); //1,2,3
}

Parsing XML to JSON

Forming an XML to JSON is used the same way as parsing the xml.

//Example
<ResponseHasServiceAccess><result>true</result><errorCode>0</errorCode></ResponseHasServiceAccess>

When calling the xml parser with the .toJson() function an java json object will be made.

var xml = "<ResponseHasServiceAccess><result>true</result><errorCode>0</errorCode></ResponseHasServiceAccess>";

// Converting to JSON
var jsonobject = xml.parse(xml).toJson();

Parsing JSON back to XML

An Json object can be parsed to an XML object.

var jsonobject = JSON.parse('{ id : 2324, foo : bar })';
var xmlstring = xml.fromJson(jsonobject);

Validating against XSD Schema

Warning : This has heavy impact on performance !! Use Xpath where you can

var doc = xml.parse(notes,{
    http://www.w3.org/XML/1998/namespace:TB_HOME + /xsd/xml.xsd,
    http://www.w3.org/2003/05/soap-envelope:TB_HOME + /xsd/soap-envelope.xsd
});

or if you want to reuse the same schema over every single request

var parsed = xml.parseSchemas({
    http://www.w3.org/XML/1998/namespace:TB_HOME + /xsd/xml.xsd,
    http://www.w3.org/2003/05/soap-envelope:TB_HOME + /xsd/soap-envelope.xsd
});
var doc = xml.parse(myxml,parsed);

parse the xsd into a variable for later usage

Parameters

schema: path to xml schema or object containing key as namespace and value to the location of the xml schema

Returns

XMLSchema object to be passed into the xml.parse function

retrieves all elements matching the xpath, the return value is an array of elements (see below)

retrieves the elements matching the xpath as serialised text.

retrieves the first element of the matching xpath element array

retrieves the first element of the matching xpath text array

retrieves the first content of the element matching the xpath

document.serialise(): String

Serialise the document back into string form

If signing by something else than ID, this method can be used to sign via reference via this attribute.

Registers a namespace to be used with the xpath functions

Parameters

prefix : prefix you want to register uri : url of the Namespace used in the xml example : http://www.example.org/name/

returns the tagname of the element (eg. msg)

returns the textcontent from the element ('1'). The parameter childname is optional, if not null it looks for a child by that name and returns it's content. If the childname contains the same prefix as namespace as the document it will return the correct content. If the prefix of the document can't be trusted (only the uri) then the use of getValueByXpath is preferred.

returns the textcontent from a xpath relative to this element

returns the child elements from a xpath relative to this element

returns the namespace uri of this element

return the text content of this element

return the xml representation of this element (Including tags)

Change the name of the element to newName and return the element.

Get an attribute attributeName from the current element and return that value.

Add an attribute attributeName with value attributeValue to the current element and return that element.

Add an attribute attributeName with value attributeValue to the current element and return that element.

Example script

function testGetValues(){
    var doc = xml.parse("<errors><error>a</error><error>b<msg>b msg</msg></error><error>c</error></errors>");
    doc.registerNamespace('tb','http://www.trustbuilder.com');
    var elements = doc.getElements('//error');

    var expected = ['a','bb msg','c'];

    var childrenOfB = elements[1].getChildren();
    // childrenOfB[0] == 'b msg'
    // childrenOfB[0].getValue() === 'b msg'

    for(var i = 0;i<elements.length;i++){
        var value = elements[i].getValue();
        tb.log(value); //a,b,c
        if(value === 'bb msg'){
            // elements[i].getValue('msg') === 'b msg'
        }
    }

    doc.getFirstValue("//error[2]")); //'bb msg'

    doc.getFirstElementAsString("//error[2]"); //'<error>b<msg>b msg</msg></error>'
    doc.getElementsAsString("//error")[1]; // '<error>b<msg>b msg</msg></error>'
}

Sign (http://www.w3.org/TR/xmldsig-core/) a specific element given the required attributes

  • SigningKeyAlias : Alias to sign this element with [*]
  • SigningKeyPwd : Password to access the specific alias [*]
  • Reference : Reference to the element to sign [*]
  • SigningKeyname : KeyName to add to the signature
  • SignatureMethod : Method to sign with (default = http://www.w3.org/2000/09/xmldsig#rsa-sha1)
  • DigestMethod : Digest method (default = http://www.w3.org/2000/09/xmldsig#sha1)
  • excludeKeyName : Indicator to leave the keyName out of the signature
  • excludeX509Name : Indicator to leave the X509 certificate out of the signature
  • excludePKName : Indicator to leave the public key out of the signature

Verify (http://www.w3.org/TR/xmldsig-core/) a specific element and return with the results in a map

eg.

var sig = doc.getFirstElement('/errors/elToSign/ds:Signature');
tb.log(sig.verify(),'','info');

{
    signer.serial: 1cb8ec23, 
    issuer: CN=js, 
    signer: CN=js
}

Encrypt (http://www.w3.org/2001/04/xmlenc) a specific element given the required attributes

  • EncryptionKeyAlias : Alias to sign this element with [*]
  • EncryptionMethod : Encryption method (default = http://www.w3.org/2001/04/xmlenc#aes128-cbc)

Decrypt (http://www.w3.org/2001/04/xmlenc) a specific element given the required attributes

Example:

var doc = xml.parse("<content>" +
    "<error ID=\"test\" EncryptionMethod=\"http://www.w3.org/2001/04/xmlenc#tripledes-cbc\" EncryptionKeyAlias=\"c=be, cn=werk-encrypt\">a</error>" +
    "<b SigningKeyAlias='js' Reference=\"#test\" SigningKeyPwd=\"{plain}js\" SigningKeyname=\"ABC\">" +
    "   <a />" +
    "</b>" +
    "</content>");
elements = doc.getElements('/errors/b');
elements[0].sign();

elements = doc.getElements('//error');
elements[0].encrypt();


doc.registerNamespace('xenc','http://www.w3.org/2001/04/xmlenc#');
doc.registerNamespace('ds','http://www.w3.org/2000/09/xmldsig#');
var enc = doc.getFirstElement('/errors/xenc:EncryptedData');
enc.decrypt();

tb.log(doc.serialise(),'','info');

mapToObject(map)

@param map Flat map to turn into an object

@return {Object}

templater(template,callbackOrData)

log(msg,component,level)

sha1(stringValue)

md5(stringValue)

uuid()

asList(array)

asByteArray(stringValue)

base64Decode(base64String,boolean)

base32Encode(base32String, decodingFormat)

base32Decode(base32String, decodingFormat)

decrypt(stringValue)

base64Encode(bytearray)

y64Decode(base64String,boolean)

y64Encode(bytearray)

hexDecode(hexString)

hexEncode(bytearray)

getService(serviceId)

getEncryptionService()

generateResponse(body, headers, cookies, status)

parseRequest(endpointRequest)

setSessionHash(sessionHash)

symetricEncrypt(options)

symetricDecrypt(options)

asymetricEncrypt(options)

asymetricDecrypt(options)

setSessionHash(string)

setSessionVariable(key,value)

getSessionVariable(key)

setVariable(key,value)

setSessionTimeoutInSec()

getVariable(key)

requestOrNull(request)

getRequestId()

getService(serviceId)

jndiLookup(jndiName)

jndiBind(jndiName,value)

ldapEncodeFilter(string)

ldapEncodeRdn(string)

audit(step)

getAuditTrail()

xml.parse(text,schema): document

xml.parseSchemas(schemas): schemas

document.getElements(xpath): element[]

document.getElementsAsString(xpath): text[]

document.getFirstElement(xpath): element

document.getFirstElementAsString(xpath): text

document.getFirstValue(xpath): text

document.registerNamespace(prefix,uri): void

document.setLookupAttribute(id): void

registerNamespace(prefix,uri)

element.getName(): string

element.getValue([childname:optional]): string

element.getValueByXpath(xpath): string

element.getChildren(xpath): element[]

element.getNamespace(): string

element.tostring()

element.toXml(): string

element.setName(newName): element

element.getAttribute(attributeName): string

element.setAttribute(attributeName, attributeValue): element

element.addAttribute(attributeName, attributeValue): element

element.sign(): element

element.verify(): element

element.encrypt(): element

element.decrypt(): element

XPath Syntax

What is XPath ?

  • XPath is a syntax for defining parts of an XML document
  • XPath uses path expressions to navigate in XML documents
  • XPath contains a library of standard functions
  • XPath is a major element in XSLT
  • XPath is a W3C recommendation

Example

We will use the following XML document in the examples below.

<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book>
  <title lang="eng">Harry Potter</title>
  <price>29.99</price>
</book>
<book>
  <title lang="eng">Learning XML</title>
  <price>39.95</price>
</book>
</bookstore>

Selecting Nodes XPath uses path expressions to select nodes in an XML document. The node is selected by following a path or steps. The most useful path expressions are listed below.

Expression

  • nodename Selects all nodes with the name nodename
  • / Selects from the root node
  • // Selects nodes in the document from the current node that match the selection no matter where they are
  • . Selects the current node
  • .. Selects the parent of the current node
  • @ Selects attributes

In the table below we have listed some path expressions and the result of the expressions:

Path Expression : Result

  • bookstore Selects all nodes with the name bookstore
  • /bookstore Selects the root element bookstore (Note: If the path starts with a slash ( / ) it always represents an absolute path to an element!)
  • bookstore/book Selects all book elements that are children of bookstore
  • //book Selects all book elements no matter where they are in the document
  • bookstore//book Selects all book elements that are descendant of the bookstore element, no matter where they are under the bookstore element
  • //@lang Selects all attributes that are named lang

Predicates

Predicates are used to find a specific node or a node that contains a specific value. Predicates are always embedded in square brackets. In the table below we have listed some path expressions with predicates and the result of the expressions:

  • __Path Expression : Result
  • /bookstore/book[1] Selects the first book element that is the child of the bookstore element.
  • /bookstore/book[last()] Selects the last book element that is the child of the bookstore element
  • /bookstore/book[last()-1] Selects the last but one book element that is the child of the bookstore element
  • /bookstore/book[position()3] Selects the first two book elements that are children of the bookstore element
  • //title[@lang] Selects all the title elements that have an attribute named lang
  • //title[@lang='eng'] Selects all the title elements that have an attribute named lang with a value of 'eng'
  • /bookstore/book[price35.00] Selects all the book elements of the bookstore element that have a price element with a value greater than 35.00
  • /bookstore/book[price35.00]/title Selects all the title elements of the book elements of the bookstore element that have a price element with a value greater than 35.00

Selecting Unknown Nodes: XPath wildcards can be used to select unknown XML elements.

Wildcard

* Matches any element node @* Matches any attribute node node() Matches any node of any kind

In the table below we have listed some path expressions and the result of the expressions:

Path Expression

/bookstore/* Selects all the child nodes of the bookstore element //* Selects all elements in the document //title[@*] Selects all title elements which have any attribute

XPath Operators

Below is a list of the operators that can be used in XPath expressions:

Operator Description Example Return value
| Computes two node-sets //book | //cd Returns a node-set with all book and cd elements
+ Addition 6 + 4 10
- Subtraction 6 - 4 2
* Multiplication 6 * 4 24
div Division 8 div 4 2
= Equal price=9.80 true if price is 9.80 false if price is 9.90
!= Not equal price!=9.80 true if price is 9.90 false if price is 9.80
Less than price9.80 true if price is 9.00 false if price is 9.80
= Less than or equal to price=9.80 true if price is 9.00 false if price is 9.90
Greater than price9.80 true if price is 9.90 false if price is 9.80
= Greater than or equal to price=9.80 true if price is 9.90 false if price is 9.70
or or price=9.80 or price=9.70 true if price is 9.80 false if price is 9.50
and and price9.00 and price9.90 true if price is 9.80 false if price is 8.50
mod Modulus (division remainder) 5 mod 2 1

XML Namespaces

When using prefixes in XML, a so-called namespace for the prefix must be defined. The namespace is defined by the xmlns attribute in the start tag of an element. The namespace declaration has the following syntax. xmlns:prefix=URI. The purpose is to give the namespace a unique name. However, often companies use the namespace as a pointer to a web page containing namespace information. When a namespace is defined for an element, all child elements with the same prefix are associated with the same namespace. Namespaces can be declared in the elements where they are used or in the XML root element.

WorkItem Api Functions

Below are a couple of functions available on the workitem that are useful for error handling.

getTbEngineId()

Returns a unique id identifying the engine. Useful for error handling over multiple trustbuilders.

getTbWorkflowId()

Returns a unique id identifying the current workflow.

getTbActivityId()

Returns a unique id identifying the current activity.

getTbError()

Returns the error that caused an abnormal exit in the workflow. Only available in the error activity.

Was this article helpful?
0 out of 0 found this helpful
Have more questions? Submit a request

Comments

0 comments

Please sign in to leave a comment.