Straatos Script service API

API Documentation for the Straatos Javascript activity

 

Target

The straatos engine provides a javascript activity. This document describes the available calls for the developer writing javascript activities.

 

 

Available variables

Constants are declared and initialized by Straatos. They cannot be changed, just queried.

 

These constants are (case sensitive!):

 

workflowId

Id of the workflow this workflowInstance is in. This workflowId changes every time the workflow is (re-)published.

workflowName Name of the workflow

workflowInstanceId

Unique id of every workflowInstance. This will not change as long as the instance is in the workflow.

activityId

Uniquely identifies the activity within the current workflow.

activityName Name of this Script activity

activityInstanceId

An increasing sequence number representing the logId of this activity

activityInstanceDate

The date that this activity execution started.

workflowInstanceDate

The date the workflowInstance arrived in the workflow

console

Object with method log(String). The output will appear in the efektif log.

 

 

Utility methods

The javascript activity provides a “straatos”-object containing several methods providing functionality. A description of these methods:

 

Generate a UUID

To generate a UUID (or GUID), use

var guid = straatos.uuid();

 

 

Sequence number

The method nextSequenceNumber(<string identifier>) generates a sequence number that is unique for the workflow.

The identifier makes it possible to have several sequences in one process.


 

nextSequenceNumber(<string identifier>)

Retrieves the next sequence number for the specified identifier

clearSequenceNumber(<string identifier>)

Clears the sequence (ie it will start at 1 again)

 

 

Example

var id = straatos.nextSequenceNumber('sequence1');

straatos.clearSequenceNumber('sequence1'); // clears the sequence


 

Getting variables from other workflowInstances in the same flow

Straatos provides two ways to get variables from other workflowInstances in the same workflow

 

variablesByWorkflowInstanceId('<workfloInstanceId>')

Gets the variables of the workflowInstance defined by <workflowInstanceId>

variablesByDocumentId(<documentId>)

Gets the variables of the workflowInstance defined by <documentId> (every workflowInstance also has a unique documentId attached)

 

 

Example

 

var DocumentId = 12345;
var frontVariables = 
JSON.parse(straatos.variabesByDocumentId(DocumentId));

function value(name) {
   var values = frontVariables.filter(function (entry) {
      return entry.variableId == name; 
   });    
   return values.length > 0 ? values[0].value : null;
}

var FirstName = value('FirstNameF');
var LastName = value('LastNameF');

 

Getting activityIds, documentId and workflowInstanceId

The activityId is used in several methods id the api(for example the message() method). The method activityIdForName returns the activityId when the activityName is provided. The activityName is the name/description you can assign to an activity.


 

activityIdForName(<string activityName>)

Returns the activityId for the given acivityName (only works for the current workflow, ie the workflow the workflowInstance is in)

getActivityIdsByDocumentId(<number documentId>)

Returns a list of activityIds where the workflowInstance defined by DocumentId is in (there is a 1:1 relation between a documentId and a workflowInstanceId).

getWorkflowInstanceIdByDocumentId(<number documentId>)

Get the workflowInstanceId (a string) for the specified documentId

documentIdsForFilter(<filter criteria>)

Perform search on all documents on the given variables

 

Example

var emailGroupId;
var documentIds = straatos.documentIdsForFilter({
    EmailUniqueId: emailGroupId
});

var activityId = straatos.activityIdForName('Wait for last Document');

var workflowInstances = [];

for (var i = 0; i < documentIds.length; i++) {
    var documentId = documentIds[i];
    
    if (documentId != _documentId) {
        workflowInstances.push({
            workflowInstanceId: straatos.getWorkflowInstanceIdByDocumentId(documentId)
        });      
    }
}

var workflowMessageData = {
    workflowId: workflowId,
    activityId: activityId,
    workflowInstances: workflowInstances
};

console.log('workflowMessageData input: ' + JSON.stringify(workflowMessageData));

straatos.sendWorkflowMessage(workflowMessageData).fail (function (jqXHR, error) {
    straatos.SetError('Send Workflow Message: ' + error);
});

 

Getting variable values

I is possible to get variables from other workflowInstances in the same workflow using these methods:

 

variablesByDocumentId(<documentId>)

Gets a JSON string containing all variables by documentId

variablesByWorkflowInstanceId(<string>)

Gets a JSON string containing all variables by workflowInstanceId

 

 

Converting to-and-from byte arrays

Several convenience methods are provided to convert to and from byte arrays

 

getBytes(inputString)

Converts the inputString to a byte array, using UTF-8 encoding.

getString(byte[])

Converts the byte array to a string, using utf-8 character set.

getString(<byte[]>, <string encoding>)

Converts the byte array to a string, using the specified character set. For possible character sets, see appendix a)

 


 

Base64 encoding and decoding

 

decodeBase64(<base64encodedString>)

Returns the (possibly binary) byteArray of the base64 encoded string.

encodeBase64(<byteArray>)

Retuns the base64 encoded string representation of the (binary-) byteArray.

 

 

Example

try {
    var dataAcceptingSystemUrl = "https://<someDataAcceptingSystems URL>/documentimportsrv";

    // variables need to be defined before call to multiString
    ReferenceNumber103 = straatos.getWorkflowData('some.ref.number.' + EmailUniqueId);
    var base64String;
    var documentBase = AttachmentFileName.replace('.pdf','');

    var documentInfo = straatos.adapter.getDocumentInfo();

    straatos.ajax({
        url: documentInfo.originalURL + '?w=' + straatos.webServiceKey,
        dataType: 'binary'
    }).done(function (pdf) {
        base64String = straatos.encodeBase64(pdf);

        var documentData = multiString(function() {/**
                <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:doc="http://nsServer.net/documentimportsrv">
                   <soapenv:Header/>
                   <soapenv:Body>
                      <doc:ImportDoc>
                         <doc:documentImportReq>
                            <doc:Docs>
                               <doc:Doc>
                                  <doc:Content>#base64String#</doc:Content>
                                  <doc:FileExt>pdf</doc:FileExt>
                                  <doc:Filename>#AttachmentFileName#</doc:Filename>
                                  <doc:FilenameBase>#documentBase#</doc:FilenameBase>
                               </doc:Doc>
                            </doc:Docs>
                            <doc:IdentifierNr>#ReferenceNumber103#</doc:IdentifierNr>
                            <doc:Type>DOCTYPE</doc:Type>
                         </doc:documentImportReq>
                      </doc:ImportDoc>
                   </soapenv:Body>
                </soapenv:Envelope>
                **/});

        straatos.ajax({
            url: dataAcceptingSystemUrl,
            data: documentData,
            method: 'POST',
            contentType: 'text/xml; charset=UTF-8',
            dataType: 'text/xml',
            headers: {
                SOAPAction: 'dataAcceptingSystemUrl + /IDocumentImportSrv/ImportDoc"'
            }
        }).done(function (responseString) {
            console.log('Document Import Response: ' + responseString);
            if (responseString != '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><ImportDocumentResponse xmlns="http://nsServer.net/documentimportsrv"/></s:Body></s:Envelope>') {
                straatos.SetError('Response from document import service: ' + responseString);
            }
        }).fail(function (jqXHR, error) {
            straatos.SetError('document import service: ' + error);
            console.log('Document Import Service: ' + error);

        });
    }).fail(function (jqXHR, error) {
        straatos.SetError('Get original: ' + error);
    });

} catch(err) {
    straatos.SetError('error: ' + error);
    console.log('error: ' + err);   
}

// Hack that converts multi line comment to multi line string
function multiString(f) {
    var result = f.toString().replace('function() {/**', '').replace('**/}', '');
    
    result = result.replace(/#([^#]+)#/g, function (match, variable) {
        // console.log('replacing ' + match + ', variable: ' + variable + ', value: ' + eval(variable));
        return eval(variable);
    });
    
    return result;
}


 

Workflow data

Functionality is provided to store and retrieve data on workflow level. This data remains available when the workflow is re-published.

 

setWorkflowData(<key>, <object value>)

Sets the workflow data.

getWorkflowData(<string key>)

Gets the workflow data for the specified key

removeWorkflowData(<string key>)

Removes the workflow data for the specified key

clearAllWorkflowData()

Removes all workflow data for the current workflow

 

 

Example

straatos.getWorkflowData('reference-' + EmailUniqueId);

 

Messaging other workflowInstances

Send other (waiting) workflowInstances a message() that they can continue the workflow.

 

sendWorkflowMessage({<parameters>})

Sends a message to the workflowInstance. The message should contain a workflowId, an activityId and and array of workflowInstances to message. Optionally variables per workflowInstance. See the example below.

 

 

Parameters:

workflowId: The id (a guid) of the current workflow

activityId: The id (a string) of the activity. See the activityForName() method to get the activityId via the activityName.

workflowInstances: A list of one or more workflowInstances that should recieve the mesage.

Each workflowInstance should contain the workflowInstanceId and optionally a list named variables of id-value pairs.

 

Example:

var workflowInstanceId = '';
var messageInput = {
    workflowId: workflowId,
    activityId: activityId,
    workflowInstances: [{
        workflowInstanceId: workflowInstanceId,
        variables: [
            {'id' : 'Variable1', 'value' : 'string123'},
            {'id' : 'Var2', 'value' : 123 }
        ]
    }]
};

straatos.sendWorkflowMessage(messageInput)
    .done(function () {
        console.log('Ok');
    }).fail(function (jqXHR, error) {
    straatos.SetError('Message error: ' + error);
});

 

Calling webservices (Ajax support)

Straatos provides an api to call webservices. The way it can be used is similar to a jQuery ajax call, however, it supports a subset of the functionality.

This ajax call can also be used to call additional functionality the Straatos REST API provides. For more information, see section Straatos adapter REST API

 

ajax(<request>)

Performs the call. See table below for the request options

 

 

Request specification

url

Required: The complete url to call. Calls to urls containing localhost are not allowed.

data

The data you want to pass, or the multipart object from the straatos.newFormData call

method

Possible values are GET, POST, PUT, DELETE and OPTIONS. When not specified, it defaults to GET

contentType

Optional contentType of the data to be sent, default is 'application/json'

dataType

Optional contentType of the expected data for example: 'binary' or 'text/html'

headers

Optional array with headers that will be passed to the call

timeout

Optional timeout in milliseconds. The default is 60 seconds. This one parameter specifies the connectTimout, requestTimeout and the socketTimeout.

 

 

Example

 try {
        straatos.ajax({
            url: externalAPIURL,
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            data: JSON.stringify({'client_id': '', 'client_secret': ''})
        }).done(function (output) {
            var response = JSON.parse(output);
            console.log('++ response: ' + JSON.stringify(response));
            token = response.access_token;
        }).fail(function (jqXHR, error) {
            straatos.setError('Access Token Error: ' + error);
            console.log('Access Token Error:  ' + error);
        });
    } catch(err) {
        console.log('Get Access Token Error:  ' + err);   
    } 

 

Multipart support

Multipart support is available to create multipart messages. If boundaries are needed between parts, they should be added manually by the developer (see example).

 

To get a new Multipart object, call straatos.newFormData()

 

Adding data

To add data to the multipart object, call one of these methods

 

append(<string>)

Adds a string, this string will be utf-8 encoded

append(<string>, <string charset>)

Adds a string with a custom character set. Values used can be ‘utf-8’, or any of the character sets from the table below.

append(<byte[]>)

Appends a byte array to the multipart object

 

 

For supported character sets, see appendix a)

Getting Data

To get the data from the multipart object, call one of these methods:

 

getByteArray()

Returns a byte array (byte[]) representing the multipart data

toString()

Returns a utf-8 decoded string of the multipart data

 

 

Example

var multipart = straatos.newFormData();
multipart.append(‘This is string 1’’);
multipart.append(‘’)

var boundaryName = 'Straatos-' + straatos.uuid();  //The Boundary Name must be unique as part of the entire post. Hence in this case we use 'Straatos- and a unique ID' to make it unique.
var boundary = '--' + boundaryName + 'rn';

var multipart = straatos.newFormData();
multipart.append(boundary);
multipart.append('Content-Type: ' + mimeType + 'rn');
multipart.append('Content-Disposition: document; name="' + documentName + '"; filename="' + fileName + '"rn');
multipart.append('rn');
multipart.append(fileContents);
multipart.append('rn');

multipart.append(boundary);
multipart.append('Content-Type: application/json; charset=UTF-8rn');
multipart.append('Content-Disposition: metarn');
multipart.append('rn');
multipart.append(JSON.stringify(metadata) + 'rn');

multipart.append('--' + boundaryName + '--rn'); //The last Boundary must have the two dashes (--) at the end.

straatos.ajax({
    url: APIBaseURL + '/api/v1/delivery',
    method: 'POST',
    data: multipart,
    contentType: 'multipart/related; boundary="' + boundaryName + '"',  //Note: The Boundary Name needs to be in double quotes and must be defined here.
    headers: {
        'Authorization': 'Bearer ' + tokenResult.access_token
    }
}).done(function (response) {
    console.log('Peax response: ' + response);

    PeaxUploadId = JSON.parse(response).id;
}).fail(function (jqXHR, error) {
    straatos.setError('Peax upload: ' + error);
});

 

Getting History or Audit Trail info

This API call returns a JSON string containing the history of the document. This will not include the currently executed step.

 

straatos.history() returns a json string containing the history of the current workflowInstance (not including the current running activity)

 

straatos.history(number documentId) returns a json string containing the history of the workflowInstance identified by the documentId provided. This document must be part of the same workflow as the calling document.

 

Since string is returned, JSON.parse() should be called on the string before accessing the json objects within the returned data.

 

// Example:
var hist_str = straatos.history();
var hist = JSON.parse(hist_str);

console.log(JSON.stringify(hist));	// prints the whole history object
console.log('WorkflowInstance started at: ' + JSON.stringify(hist.start));
console.log('Nr of log entries: ' + hist.activityInstances.length);

// Example with documentId:
var hist_str2 = straatos.history(877603);
var hist2 = JSON.parse(hist_str2);

console.log(JSON.stringify(hist2));	// prints the whole history object
console.log(JSON.stringify(hist2.start));
console.log('Second: ' + hist2.activityInstances.length);

 

setSecret and getSecret

The Set Secret and Get Secret functions provided by the Script task or Interact API enable the secure storage of sensitive data such as passwords, tokens, API keys, and connection strings.

How It Works:

Best Practices:

It is crucial not to store secrets directly in script code. Instead, utilize the setSecret and getSecret functions to manage sensitive data securely.

Storing a Secret:

To create or update a secret, use the following script code. Replace 'mySecretName' with a unique identifier for your secret and 'mySecretValue' with the actual data you wish to secure (e.g., API key, password, connection string, or token)

 

var result = straatos.setSecret('mySecretName', 'mySecretValue');

 

The above code stores the return value in a variable. That variable will either contain a 'true' or 'false' value, depending on if the storing of the secret was successful. This result should be checked by the code.

Retrieving a Secret:

To access a stored secret within your script, use the code below. This example assigns the retrieved secret to a variable named secret.

 

var secret = straatos.getSecret('mySecretName'));

 

 

Database (SQL) Queries

Sthe straatos.data.query lets user connecto to a database and execuite SQL queries. This function can be used to read data from Database (Select), but also to update, truncate, drop databases (tables).

 

The sample below shows how a database is update.

var sqlUpdate = 'DECLARE @UNI UNIQUEIDENTIFIER ' +
                'SET @UNI = NEWID() ' +
                'INSERT INTO BBAuditLog (id,AuditLogRecordId,UserName, EventDate, WorkflowStep, BatchId, Area, RecordName, RecordValue) ' +
                'OUTPUT @@RowCount as RowsAffected ' + 
                'VALUES (NewID(),@AuditLogRecordId,@UserName,@EventDate,@WorkflowStep,@BatchId,@Area,@RecordName,@RecordValue);';

var sqlParam = {
     '@AuditLogRecordId': AuditLogRecordId,
     '@UserName': LastSavedBy,
     '@EventDate': moment(LastSavedDateTime).format('YYYY-MM-DDThh:mm:ssZ'),// LastSavedDateTime,
     '@WorkflowStep': ReportType,
     '@BatchId':BatchId,
     '@Area':'Header'
};    

var dbConnString = 'Server=<ServerName>,1433;Database=<DBName>;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;TrustServerCertificate=False';
var dbUser = '<Username>';
var dbPassword = '<Password>';
    
var query = {
    ConnectionString: dbConnString,
    User: dbUser,
    Password: dbPassword,
    SqlQuery: sqlUpdate,
    Parameters: sqlParam
};
    
var sqlresult = straatos.data.query(query);

 

Supported character sets

Supported charsets (java might support more, but this is the minimum)

 

US-ASCII Seven-bit ASCII, a.k.a. ISO646-US

ISO-8859-1   ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1

UTF-8 Eight-bit UCS Transformation Format

UTF-16BE Sixteen-bit UCS Transformation Format, big-endian byte order

UTF-16LE Sixteen-bit UCS Transformation Format, little-endian byte order

UTF-16 Sixteen-bit UCS Transformation Format, byte order identified by an optional byte-order mark

Create your own Knowledge Base