Previous Next Contents Index


Appendix A JavaScript API Reference

This appendix is an API reference of the objects and methods you can use when writing JavaScript scripts for PAE. The PAE Object Model includes the following objects:

The following global functions are also available for use in scripts:

All functions and methods are listed here:


ProcessInstance
A script can use the global function getProcessInstance() to get the processInstance for process in which the script is running.

Example:.

var pi = getProcessInstance ();

The following methods can be called on the processInstance object:


getConclusion()
Returns the name of the exit point node where the process instance is completed. Data is returned as a JavaScript string if the process instance is complete. If the process instance is still active, null is returned.

Example:.

var pi = getProcessInstance();

var exitNodeName = pi.getConclusion();

if( exitNodeName != null )

   java.lang.System.out.println( "Process instance completed at: " + exitNodeName );

It is recommended that you use getExitNodeName rather than getConclusion as getConclusion may be deprecated in future releases.

getCreationDate()
Returns a JavaScript date that represents the date when the process instance was first created.

Example:.

var pi = getProcessInstance();

java.lang.System.out.println( "Process isntance created on: " + pi.getCreationDate() );

getCreatorDN()
Returns the distinguished name (DN) of the user who first created the process instance.

Example:.

"uid=topper, o=airius.com"

getCreatorUser()
Returns an object that contains the attributes of the creator user in the corporate directory.

Example:.

var pi = getProcessInstance ();

var creator = pi.getCreatorUser ();

java.lang.System.out.println( "Process instance creator id: " + creator.getUserID() );

getData (fieldName)
Returns the value of the data field or undefined if the field is not defined. The returned value is in JavaScript format.

Parameter
Data Type
Description
fieldName
String
Name of the field whose value is returned.

Example:.

var pi = getProcessInstance ();

var cust_name = pi.getData( "customer_name" );

java.lang.System.out.println( "The value of Customer Name: " + cust_name );

getEntryNodeName()
Returns a JavaScript string containing the name of the entry point node where the current process instance was initiated. All process instances must start from an entry node, ensuring that this method never returns null.

Example:.

var pi = getProcessInstance();

java.lang.System.out.println( "Process instance entry node if " + pi.getEntryNodeName() );

getExitNodeName()
Returns a JavaScript string containing the name of the exit point node where the process instance has completed. If the process instance has not yet completed, returns null.

Example:.

var pi = getProcessInstance();

var exitNodeName = pi.getExitNodeName();

if( exitNodeName != null )

   java.lang.System.out.println( "Process instance completed at: " + exitNodeName );

getInstanceId ()
Returns the ID of the process instance, such as "2345". The id is generated by the engine to be unique across all process instances of all applications defined in the same cluster.

Example:.

var pi = getProcessInstance();

var pid = pi.getInstanceId();

java.lang.System.out.println( "The Process Instance ID: " + pid );

getPriority()
Returns a JavaScript number representing the priority value of the current process instance. The priority value ranges from 1 (highest) to 5 (lowest). The priority value is derived from the value of a data element. If the data element's type is INT/FLOAT, the priority value is fetched from the data element's value. Otherwise, the default value 3 is returned.

Example:.

var pi = getProcessInstance();

var priority = pi.getPriority();

if( priority == 1 )

   java.lang.System.out.println( "The process instance has hight priority" );

else if( priority == 5 )

   java.lang.System.out.println( "The process instance has low priority" );

else

   java.lang.System.out.println( "The current priority is " + priority );

getRoleDN(roleName)
Returns a string containing the distinguished name (DN) of the user that has been assigned to the role roleName. You can fetch the DN for the current user using this method.

Parameter
Data Type
Description
roleName
String
Name of the role whose full DN is returned.

Example:.

var pi = getProcessInstance ();

var cd = getCorporateDirectory();

var userDN = pi.getRoleUser( "role1" 0;

if( userDN != null)

{

   var u = cd.getUserByDN( userDN );

   java.lang.System.out.println( "Role user id: " + u.getUserId() );

}

getRoleUser(roleName)
Returns a JavaScript User object that contains the attributes of the user that has been assigned to the role roleName. If a user is not associated with the role roleName yet, null is returned.

Parameter
Data Type
Description
roleName
String
Name of the role whose full DN is returned.

Example:.

var pi = getProcessInstance ();

var u = pi.getRoleUser( "role1" );

if(u != null )

   java.lang.System.out.println( "role user id: " + u.getUserId() );

getTitle()
Returns the current title string associated with the process instance. Calling this method is similar to calling getData() on the title data field and casting the value to a string. If the title data field has a type other than TEXT/LONG TEXT, returns a textual representation of the data element's value.

Example:.

var pi = getProcessInstance();

java.lang.System.out.println( "The current title is: " + pi.getTitle() );

setData (fieldName, fieldValue)
Associates the object fieldValue with the data element fieldName. The object passed by fieldValue can be any valid JavaScript object (such as String, Date, Array). The object can be a Java object if the data element is a custom field.

Parameter
Data Type
Description
fieldName
String
Name of the data element whose value is modified.
fieldValue
Object
Value associated with the data element fieldName.

Since each data element is configured with a particular dta type which is set at design time in Process Builder, be aware of the following data conversion guidelines:

Data element type
fieldValue type
fieldValue converted to...
TEXT/LONGTEXT
any type
String
INT
String
int
INT
Integer
int
FLOAT
String
float
FLOAT
Integer
float
DATE/DATETIME
String
Date
DATE/DATETIME
Date
Date

Example:.

var pi = getProcessInstance ();

pi.setData( "customer_name", "Joe" );

//Set value for custom field

//

var custAcct = new Packages.com.acme.Account();

pi.setData( "customer_acct", custAcct );

setPriority(value)
Changes the current priority value for the process instance to the integer value value. A valid priority value can range from 1 (highest) to 5 (lowest). If a value smaller than 1 is passed, the priority is set to 1. If a value larger than 5 is passed, the priority is set to 5. If a non-integral value is passed through vluae, an attempt is made to convert that value to an integer. If the value cannot be converted to an integer, the priority is left unchanged.

Parameter
Data Type
Description
value
Integer
Integer value set as the current priority for the process instance.

Example:.

var pi = getProcessInstance();

pi.setPriority( 3.141592 ); //priority := 3

pi.setPriority( -1 ); //priority := 1

pi.setPriority( "99" ); //priority := 5

setRoleByDN(roleName, userDN)
Changes the user associated with the role roleName by specifying the new user's Distinguished Name (DN) userDN. If userDN corresponds to an actual user in the corporate directory, the user associated with roleName is changed and true is returned. If the userDN does not correspond to an actual user entry, false is returned and roleName is left unchanged.

Parameter
Data Type
Description
roleName
String
Name of the role to alter.
userDN
String
DN of the user to associate with roleName.

Example: .

var pi = getProcessInstance ();

if( pi.setRoleByDN( "uid=joe, ou=People, o=acme.com" ) )

   java.lang.System.out.println( "role has been changed" );

else

   java.lang.System.out.println( "role has not been changed" );

setRoleById(roleName, userId)
Changes the user associated with the role roleName by specifying the new user's ID via userId. Returns true if userId corresponds to an actual user in the corporate directory and the user associated with roleName is changed. Returns false if userId does not correspond to an actual user entry and roleName is left unchanged.

Parameter
Data Type
Description
roleName
String
Name of the role to alter.
userDN
String
DN of the user to associate with roleName.

Example:.

var pi = getProcessInstance ();

if( pi.setRoleById( "joe" ) )

   java.lang.System.out.println( "role has been changed" );

else

   java.lang.System.out.println( "role has not been changed" );

setTitle(title)
Changes the current title for the process instance to the value contained in title.

title can be any valid JavaScript object, but the resulting title is the textual representation of the passed object. Calling setTitle(title) does not change the value of the title data element; the binding is uni-directoional from the data element to the process instance title.

Parameter
Data Type
Description
title
Object
Value set as the current title for the process instance.

Example:.

var pi = getProcessInstance();

pi.setTitle( "a new title" ); //title := "a new title"

pi.setTitle( new Date() ); //title := "Tue Oct 19 13:04:50 CDT 1999"

pi.setTitle( 3.141592 ); //title := "3.141592"


WorkItem
A script can use the global function getWorkItem() to get the work item in which the script is running.

Example:.

var wi = getWorkItem();

The following methods can be called on the workItem object:

assignTo(assigneeDnArray)
Re-assigns the work item to the users specified in the assigneeDnArray, which must be an array of valid distinguished names (DNs). This function automatically sets the work item back to running if it has expired.

Parameter
Data Type
Description
assigneeDnArray
Array
Lit of assignee DNs to assign to the work item.

The following script re-assigns the work item to the user whose uid is jocelynb. The toUserById() function returns an array containing the distinguished name of the user whose uid is specfied. For more information about toUserById() see the the section "Miscellaneous Global Functions."

Example:.

var wi = getWorkItem();

var cd = getCorporateDirectory();

var joe = cd.getUserById( "joe" );

var bob = cd.getUserById( "bob" );

var assignees = new Array( joe.getDN(), bob.getDN() );

wi.assignTo( assignees );

expire()
This function adds a flag indicating that the work item has expired. The function does not render the work item inactive.

Example:.

var wi = getWorkItem();

wi.expire();

if( wi.hasExpired() )

   java.lang.System.out.println( "The workitem has expired" );

else

   ;

extend(newDate)
Extends the duration of the work item by pushing out its expiration date. If the work item was expired, this function removes the expired flag.

Parameter
Data Type
Description
newDate
Date
New expiration date for the work item.

Example:.

var wi = getWorkItem();

var now = new Date();

// Set extension date to 1 hour in the future

var newDate = new Date( now.getTime() + (1 * 60 * 60 * 1000) );

wi.extend( newDate );

getAssigneesDN()
For work items that are running, this method returns a JavaScript array of the distinguished names of the assignees. Since automated activities are performed by Process Engine and do not require an assignee, use this method only from a user activity.

Example:.

var wi = getWorkItem();

var cd = getCorporateDirectory();

//Set the assignees for the workitem

var joe = cd.getUserById( "joe" );

var bob = cd.getUserByid( "bob" );

var assignees = new Array( joe.getDN(), bob.getDN() );

wi.assignTo( assignees );

var nAssignees = wi.getAssigneesDN();

for( var i = 0; i < nAssignees.length; i++)

   java.lang.System.out.println( "Assignee " + i + " is " + nAssignees[ i ] );

getCreationDate()
Returns a JavaScript date that represents the creation date of the work item.

Example:.

var wi = getWorkItem();

java.lang.System.out.println( "Work item created on: " + wi.getCreationDate() );

getCurrentActivityCN()
Returns a JavaScript string containing the name of the activity where the work item is positioned. When called from an exception activity, returns the name of that exception activity rather than the name of the activity where the exception condition occurred.

Example:.

var wi = getWorkItem();

java.lang.System.out.println( "Work item positioned at node " + wi.getCurrentActivityCN() );

getExpirationDate()
Returns a JavaScript Date object that represents the expiration date of the work item.

Example:.

var wi = getWorkItem();

java.lang.System.out.println( "Work item set to expire at " + wi.getExpirationDate() );

hasExpired()
Returns true if the work item has expired or false if it has not expired. If the work item has already expired, but has been extended via the extend() method, hasExpired() returns false if called again.

Example:.

var wi = getWorkItem();

if( wi.hasExpired() == false )

   wi.expire(); //expire immediately

isStateActive()
Returns true if the work item is active or false if the work item is inactive. A work item is considered active if there is only one assignee currently assigned to it. If a work item has been assigned to a group, the work item is not active, but running. Once one member of the group elects to work on the item, it is considered active.

Example:.

var wi = getWorkItem();

if( wi.isStateActive() 0

   java.lang.System.out.println( "Work item is active" );

else

{

   var nAssignees = wi.getAssigneesDN();

   if( nAssignees.length > 1 )

      java.lang.System.out.println( "Work item is running"

);

      else

      ; //work item could be suspended

}

isStateRunning()
Returns true if the work item is running or false if it is not running. A work item is running if more than one user is assigned to it. Once a user starts the work item, the work item changes state from running to active.

Example:.

var wi = getWorkItem();

if( wi.isStateRunning() )

{

   var nAssignees = wi.getAssigneesDN*();

   if( nAssignees.length > 1 )

      java.lang.System.out.println( "Work item is assigned to a group" );

   else

      ;

}

isStateSuspended()
Returns true if the work item is suspended or false if it is not suspended. You can suspend a work item through Process Administrator or by calling suspend().

Example:.

var wi = getWorkItem();

if( wi.isStateSuspended() )

   wi.resume(); //resume the work item immediately

moveTo(activityName)
Move the current work item to the activity specified in activityName. Only activities associated with a virtual transition can use this method. moveTo() can only be called from expriation handler scripts and completion scripts.

Note that moveTo() doesn't actually involve "moving." Rather, the current work item is destroyed and a new work item is created at the new activity.

Parameter
Data Type
Description
activityName
String
Activity to which to move the work item.

Example:.

var wi = getWorkItem(); //inside the expiration handler script

var activityName = "expired item";

if( wi.moveTo( activityName ) )

   java.lang.System.out.println( "Successfully moved to activity " + activityName );

else

   java.lang.System.out.println( "Failed to move to activity " + activityName ) ;

resume()
This function reactivates a suspended work item. If the work item is assigned to more than one user, the work item's state is set to running. If there is only one assignee, the work item's state is set to active.

Example:.

var wi = getWorkItem();

if( wi.isStateRunning() )

{

   wi.resume(); //resume work item immediately

   if( wi.isStateRunning() )

      java.lang.System.out.println( "Work item is assigned to a group: );

   else

      java.lang.System.out.println( "work item is assigned to one user" );

}

setExpirationDate(expDate)
Sets the expiration date of the work item. If the work item has expired, use the extend() function instead of setExpirationDate() to extend the expiration date, since extend() removes the expired flag and setExpirationDate() does not.

Parameter
Data Type
Description
expDate
Date
Expiration date for the work item.

Example:.

var wi = getWorkItem();

var now = new Date();

//Set expiration date to 1 hour in the future

var expDate = new Date( now.getTime() + (1 * 60 * 60 * 1000)

);

wi.setExpirationDate( expDate );

suspend()
This function makes the work item inactive. Users cannot work with the work item until it has been resumed through Process Administrator or via a call to resume().

Example:.

var wi = getWorkItem();

wi.suspend();

if( wi.isStateSuspended() )

   wi.resume(); //resume the work item immediately


ContentStore
Scripts can use the global function getContentStore() to get a contentStore object connected to the content store of the application. There are three different ways to call the function:

The following methods can be called on the contentStore object:



copy(srcURL, dstURL)
Copies the content at the srcURL to the dstURL. Both URLs have to be on the same content store. If dstURL already exists, it is overwritten.

Parameter
Data Type
Description
srcURL
String
An HTTP URL or URI of the content in the content store object.
dstURL
String
An HTTP URL or URI of the content in the content store object.

Example:.

var cs = getContentStore();

var result = cs.copy( cs.getBaseURL ( "shopping/documents" ) + "myFile.html",

cs.getBaseURL ( "shopping/old" ) + "myFile.html" ) ;

var httpcode = cs.getStatus ( result );

if (httpcode == 200)

{

}

download(url, file)
Downloads the content at the url into the specified file. If a username and password is specified for this content store, they are used in the request to retreive the content.

Parameter
Data Type
Description
url
String
An HTTP URL or URI of the content in the content store object.
file

File where the content is stored; if exists, it will be overwritten.

Example:.

var cs = getContentStore();

var result = cs.download ( cs.getBaseURL() + "myFile.html" , "C:/ myFile.html" );

var httpcode = cs.getStatus( result );

if (httpcode == 200)

{

// it went OK ...

}

exists(url)
Checks if the URL exists on the content store.

Parameter
Data Type
Description
url
String
An HTTP URL or URI of the content in the content store object.

Example:.

var cs = getContentStore();

var result = cs.exists( cs.getBaseURL ( "shopping/documents" ) + "myFile.html" );

var httpcode = cs.getStatus ( result );

if (httpcode == 200)

{

// it exists OK ...

}

getBaseURL()
Returns the root URL of this content store.

See getRootURL () for examples.

getBaseURL(path)
Returns a base container url which includes the path as postfix to the content store root url.

Parameter
Data Type
Description
path
String
A relative path segment.

Example:.

var cs = getContentStore();

java.lang.System.out.println("ContentStore ROOT URL " + cs.getBaseURL("shopping/documents"));

getBaseURL(path, instanceid)
Returns a base container URL which includes the path and the instanceid as postfix to the content store root URL.

Parameter
Data Type
Description
path
String
A relative path segment.
instanceid
Integer
An integer instance id of the process.

Example:.

var pi = getProcessInstance();

var cs = getContentStore();

java.lang.System.out.println("ContentStore ROOT URL " + cs.getBaseURL("shopping/documents", pi.getInstanceId() ));

getContent (url)
Returns a String of the content at the specified url, where url describes either an HTTP URL or URI of the content in the content store object. A URI is a path segment only, specified as an absolute or relative pathname.

Parameter
Data Type
Description
url
String
An HTTP URL or URI of the content in the content store object.

On an HTTP content store, getContent( ) is implemented as a GET request against the server. If a username and password have been specified for this content store, they will be used in the request to retrieve the content.

If the content cannot be retrieved or doesn't exist, getContent( ) returns null. Call the exists( ) method to check whether the URL exists in the content store. See also store( ) and upload( ).

Example:.

var cs = getContentStore();

// Relative URI

var content = cs.getContent ( "myFile.html" );

// Absolute URI

var content = cs.getContent ( "/CS/CheckOut/basket.xml" );

// If URL, then the host and port portion of the URL must be

// that of the content store URL. This is typically returned

// by the getBaseURL() method.

var content = cs.getContent ( cs.getBaseURL() +

"CheckOut/basket.xml" )

getException(result_string)
Gets the exception in string format that has occured in the operation move(), copy(), upload(), download(), store(), exists(), initialize(), remove(), mkdir(), rmdir().

Parameter
Data Type
Description
result_string
String
Result string from one of the methods listed above.

Example:.

var cs = getContentStore();

var result = cs.remove( cs.getBaseURL ( "shopping/documents" ) + "myFile.html" );

if ( cs.isException ( result ))

{

// it something went really wrong

java.lang.System.out.println("Exception: " + cs.getException ( result ));

}

else if ( cs.getStatus ( result ))

{

} else if ( cs.getStatus ( result ))

{

}

getRootURL ()
Returns a string of the root URL of the content store, including the ending /. This is a string version of the URL for the content store as specified in Process Builder.

Example:.

var cs = getContentStore();

java.lang.System.out.println("ContentStore ROOT URL " + cs.getRootURL());

getSize(url)
Returns the size in bytes of the content of the specified URL at the content store. On any error, -1 is returned.

Note that in certain rare circumstances, the length of the content of such a URL cannot be established.

Parameter
Data Type
Description
url
String
An HTTP URL or URI of the content in the content store object.

Example:.

var cs = getContentStore();

var result = cs.getSize( cs.getBaseURL ( "shopping/documents" ) + "myFile.html" );

if (result < 0)

{

}

getStatus(result)
Returns the status of the last successful Content Store operation by one of the methods: move(), copy(), upload(), download(), store(), exists(), initialize(), remove(), mkdir(), rmdir().

Parameter
Data Type
Description
result
String
Result string from one of the methods listed above.

Example:.

var cs = getContentStore();

var result = cs.remove( cs.getBaseURL ( "shopping/documents" ) + "myFile.html" );

if ( cs.getStatus(result) != 200)

{

}

getVersion()
Returns the version string of the the ContentStore implementation. Currently, this value is 0.1999100221-001.

Example:.

var cs = getContentStore();

java.lang.System.out.println("ContentStore Version " + cs.getVersion());

initialize(url)
Initializes the URL with basic content so the URL exists on the Content Store. This method returns either the status code from the content store for the operation or an exception. Note that no exception is actually thrown. To see if an exception is returned, call isException() on the return value from this method and call getStatus() to get the numeric HTTP protocol status of this content store request.

Parameter
Data Type
Description
url
String
An HTTP URL or URI of the content in the content store object.

Example:.

var pi = getProcessInstance();

var cs = getContentStore();

var result = cs.initialize ( cs.getBaseURL ( "shopping/documents" ) + "myFile.html" );

var httpcode = cs.getStatus ( result );

if (httpcode == 201 || httpcode == 204)

{

}

else

{

}

isException(exception)
Checks if the result string from move(), copy(), upload(), download(), store(), exists(), initialize(), remove(), mkdir(), rmdir() is an exception.

Parameter
Data Type
Description
exception
String
The result string from methods of Content Store that can return an exception.

Example:.

var cs = getContentStore();

var result = cs.remove( cs.getBaseURL ( "shopping/documents" ) + "myFile.html" );

if ( cs.isException ( result ))

{

}

else if ( cs.getStatus ( result ))

{

}

list(url)
Gets the container content (folder) listing of this content store container.

Parameter
Data Type
Description
url
String
An HTTP URL or URI of the content in the content store object.

mkdir (URLString)
Creates the appropriate folder structure on the web server being used as the content store. The URLString must be a full path name to the new directory. If the specified directory already exists, nothing happens.

Parameter
Data Type
Description
URLString
String
An HTTP URL or URI of the content in the content store object.

Example:.

var cs = getContentStore();

var result = cs.mkdir( cs.getBaseURL ( "shopping/documents" ) );

var httpcode = cs.getStatus ( result );

if (httpcode == 200)

{

}

move (String URLString1, String URLString2)
moves the file from the URLString1 to URLString2, overwriting any file that already exists at the destination file name. If the file to be moved URLString1, does not exist, this function gives an error.

Both file names must be full pathnames. The following code moves the file tempdoc.html from the temp directory to doc1.html in the docs directory on the web server pm.company.com.

Example:.

var myStore = getContentStore ();

var pi = getProcessInstance ();

var pid = pi.getInstanceId();

myStore.move("http://pm.company.com/temp/tempdoc.html",

      "http://pm.company.com/docs/doc1.html");

Note that the move() function does not create directories -- use mkdir() to create a directory before moving a file to it.

remove(url)
Deletes the content at the specified URL.

Parameter
Data Type
Description
url
String
An HTTP URL or URI of the content in the content store object.

Example:.

var cs = getContentStore();

var result = cs.remove( cs.getBaseURL ( "shopping/documents" ) + "myFile.html" );

var httpcode = cs.getStatus ( result );

if (httpcode == 200)

{

}

rmdir(url)
Removes the container (folder) at the specified URL. The folder must be empty to be removed or an error is returned.

Parameter
Data Type
Description
url
String
An HTTP URL or URI of the content in the content store object.

Example:.

var cs = getContentStore();

var result = cs.rmdir( cs.getBaseURL ( "shopping/documents" ) );

var httpcode = cs.getStatus ( result );

if (httpcode == 200)

{

}

store (content, url)
Stores the content specified by content in the given url. If a username and password has been specified for this content store, they are used in the request to store the content.

Parameter
Data Type
Description
content
String
Content to store in the content store as this URL.
url
String
An HTTP URL or URI of the content in the content store object.

Example:.

var cs = getContentStore();

var content = "<body><b>Hello</b> world ... </body>";

// Relative URI

var result = cs.store ( content, "myFile.html" );

// Absolute URI

var result = cs.store ( content, "/CS/myFile.html" );

// Absolute URL (for historical reasons)

var result = cs.store ( content, cs.getBaseURL () + "myFile.html" );

upload(file, url)
Uploads the file content to the URL specified. If a username and password has been specified for this content store, they are used in the request to upload the file.

Parameter
Data Type
Description
file

File to upload.
url
String
An HTTP URL or URI of the content in the content store object.

Example:.

var cs = getContentStore();

var result = cs.upload ( "C:/myFile.html", cs.getBaseURL() + "myFile.html" );

var httpcode = cs.getStatus( result );

if (httpcode == 201 || httpcode == 204)

{

}


CorporateDirectory
Scripts can use the global function getCorporateDirectory() to get a corporateDirectory object that is connected to the corporate directory in the Directory Server for the cluster.

Example:.

var corp = getCorporateDirectory ();

Scripts can then use the corporateDirectory object to access and modify information about users in the corporate directory.

The following methods can be called on the corporateDirectory object:



addUser (userDN, attributes, objectClasses)
Adds a user to the directory. The user's Distinguished Name (DN) is specified by userDN. The attributes for the user are specified as a JavaScript associative array indexed by attribute name. The objectClasses parameter specifies any additional object classes as a JavaScript array. If the addition of the user is successful, returns true, otherwise returns false.

Parameter
Data Type
Description
userDN
String
DN for the new user entry.
attributes
Object
Table of key/value pairs specifying user attributes.
objectClasses
Array
List of object classes with which the user entry is compliant.

Example:.

var attrs = new Object();

attrs[ "uid" ] = "joe";

attrs[ "cn" ] = "Joe Cool";

attrs[ "sn" ] = "Cool";

attrs[ "mail" ] = "joe@acme.com";

attrs[ "favoriteColor" ] = "green";

// Specify additional objectclasses

var OCs = new Array( "favoriteColorOC" );

if( cd.addUser( "uid=joe, ou=People, o=acme.com", attrs, OCs ) == false )

{

java.lang.System.out.println( "Problems adding user entry joe"

);

}

deleteUserByCN(userCN)
Deletes the user entry specified by the Common Name (CN) userCN from the corporate directory. Returns true if the deletion is successful. Returns false if the deletion failed.

Parameter
Data Type
Description
userCN
String
CN deleted by the user entry.

Example:.

var cd = getCorporateDirectory();

var joe = cd.getUserById( "joe" );

if( cd.deleteUserByCN( joe.cn ) )

   java.lang.System.out.println( "User entry joe deleted" );

else

   java.lang.System.out.println( "Problems deleting user entry joe" );

deleteUserByDN(userDN)
Deletes the user entry specified by the Distinguished Name (DN) userDN from the corporate directory. Returns true if the deletion is successful. Returns false if the deletion failed.

Parameter
Data Type
Description
userDN
String
DN deleted by the user entry.

Example:.

var cd = getCorporateDirectory();

var joe = cd.getUserById( "joe" );

if( cd.deleteUserByDN( joe.getDN ) )

   java.lang.System.out.println( "User entry joe deleted" );

else

   java.lang.System.out.println( "Problem deleting user entry joe" );

deleteUserById(uid)
Deletes the user entry specified by userID from the corporate directory. Returns true if the deletion is successful. Returns false if the deletion failed.

Parameter
Data Type
Description
userDN
String
DN deleted by the user entry.

Example:.

var cd = getCorporateDirectory();

var joe = cd.getUserById( "joe" );

if( cd.deleteUserByCN( joe.getUserId() ) )

   java.lang.System.out.println( "User entry joe deleted" );

else

   java.lang.System.out.println( "Problem deleting user entry joe" );

getUserByCN(userCN)
Returns the user entry corresponding to the Common Name (CN) userCN as a JavaScript User object. User object is a PAE-specific object. Returns null if no user entry corresponds to userDN.

Parameter
Data Type
Description
userCN
String
CN retrieved by the user entry.

Example:.

var cd = getCorporateDirectory();

var joe = cd.getUserByCN( "Joe Cool" );

if( joe == null )

   java.lang.System.out.println( "Cannot find entry for user joe" );

else

   java.lang.System.out.println( "Found user joe" );

getUserByDN (userDN)
Returns the user entry corresponding to the Distinguished Name (DN) userDN as a JavaScript User object. User object is a PAE-specific object. Returns null if no user entry corresponds to userDN.

Parameter
Data Type
Description
userDN
String
DN retrieved by the user entry.

Example:.

var cd = getCorporateDirectory();

var joe = cd.getUserByDN( "uid=joe, ou=People, o=acme.com" );

if( joe == null )

   java.lang.System.out.println( "Cannot find entry for user joe" );

else

   java.lang.System.out.println( "Found user joe" );

getUserById (uid)
Returns the user entry corresponding to the user id userId as a JavaScript User object. The User object is a PAE-specific object. Returns null if no user entry corresponds to userId.

Parameter
Data Type
Description
uid
String
User ID retrieved by the user entry.

Example:.

var cd = getCorporateDirectory();

var joe = cd.getUserByID( "joe" );

if( joe == null )

   java.lang.System.out.println( "Cannot find entry for user joe" );

else

   java.lang.System.out.println( "Found user joe" );

modifyUserByCN (userCN, attrName, attrValue, operation)
See modifyUserByDN (userDN, attrName, attrValue, operation).

Parameter
Data Type
Description
userCN
String
CN modified by the user entry.
attrName
String
Name of the user entry attribute to modify.
attrValue
String
Value of the user entry attribute to modify.
operation
String
Modification operation performed.

Example:.

var cd = getCorporateDirectory();

if(cd.modifyUserByCN( "uid=joe, ou=People, o=acme.com", "favoriteColor", "blue", "ADD" ) == false )

{

   java.lang.System.out.println( "Failed to modify user joe"

);

}

else if( cd.modifyUserByCN( "uid=joe, ou=People, o=acme.com", "favoriteColor", "red", "REPLACE" ) == false )

{

   java.lang.System.out.println( "Failed to modify user joe");

}

else if( cd.modifyUserByCN( "e, ou=People, o=acme.com", "favoriteColor", "", "DELETE" ) == false )

{

   java.lang.System.out.println( "Failed to modify user joe");

}

modifyUserByDN (userDN, attrName, attrValue, operation)
Modifies the user entry specified by the Distinguished Name (DN) userDN in the corporate directory. Returns true if the modification is successful. Returns false if the modification fails.

Parameter
Data Type
Description
userDN
String
DN modified by the user entry.
attrName
String
Name of the user entry attribute to modify.
attrValue
String
Value of the user entry attribute to modify.
operation
String
Modification operation performed.

The type of modification is specified by the operation, which can have the following values:

ADD: adds the attribute attrName with the value attrValue to the user entry. If attrName has multiple values, the operation can result in multiple instances of attrName in the user entry. attrName should be a valid attribute of one of the object classes with which the user entry complies.

REPLACE: replaces the value currently associated with attrName with the new value attrValue.

DELETE: deletes attrName from the user entry.

Example:.

var cd = getCorporateDirectory();

if(cd.modifyUserByDN( "uid=joe, ou=People, o=acme.com", "favoriteColor", "blue", "ADD" ) == false )

{

   java.lang.System.out.println( "Failed to modify user joe"

);

}

else if( cd.modifyUserByDN( "uid=joe, ou=People, o=acme.com", "favoriteColor", "red", "REPLACE" ) == false )

{

   java.lang.System.out.println( "Failed to modify user joe");

}

else if( cd.modifyUserByDN( "e, ou=People, o=acme.com", "favoriteColor", "", "DELETE" ) == false )

{

   java.lang.System.out.println( "Failed to modify user joe");

}

modifyUserById (userID)
See modifyUserByDN (userDN, attrName, attrValue, operation).

Parameter
Data Type
Description
userID
String
User ID modified by the user entry.

Example:.

See modifyUserByDN (userDN, attrName, attrValue, operation). You must pass in a user ID rather than a DN.


User
The User object has publically accessible methods and exposes the user attributes making up an LDAP user entry. You can treat the User object as a hashtable of attribute key/value pairs where the keys are the attribute names as they apear in the LDAP entry. In the following code sample, you can also access the attribute favoritecolor, which is an attribute available from the user joe's entry.

Example:.

var cd = getCorporateDirectory();

var u = cd.getUserById( "joe" );

java.lang.System.out.println( "joe's email is " + u.mail );

java.lang.System.out.println( "Joe's favorite color is " + u.favoritecolor );

The following methods can be called on the User object:

getUserId()
Returns the user ID for the current user. The user ID attribute can also be accessed directly as the id property of the user object.

Example:.

var cd = getCorporateDirectory();

var u = cd.getUserByDN( "uid=joe, ou=People, o=acme.com" );

java.lang.System.out.println( "Joe's user id is " + u.getUserID() );

var pi = getProcessInstance();

u = pi.getCreatorUser();

java.lang.System.out.println( "Creator's user id is " + u.getUserId() );

getDN()
Returns the Distinguished Name (DN) for the current user. The user DN attribute can also be accessed directly as the dn property of the user object.

Example:.

var cd = getCorporateDirectory();

var u = cd.getUserById( "joe" );

java.lang.System.out.println( "Joe's user DN is " + u.getDN() );

var pi = getProcessInstance();

u = pi.getCreatorUser();

java.lang.System.out.println( "Creator's user DN is " + u.getDN() )


Logging and Error Handling Global Functions
The following global functions are available for adding entries to error, informational, and history logs. Note that the two forms, Msg and Message, are identical. The duplicate names are provided for convenience only.

logErrorMsg (label, context)
Adds an entry in the error log of the application. This information is displayed to the administrator when viewing the error log.

Parameter
Data Type
Description
label
String
Label for the error log's entry.
context
Object
(Optional) Hashtable of key/value pairs to print in the log entry.

The following code could be used in a completion script or automation script to log an error message when a user tries to submit a document for review when the document is too long.

Example:.

// LOG AN ERROR MESSAGE

var pi = getProcessInstance():

var author = pi.getData("author");

var docName = pi.getData("docName");

var pageCount = parseInt (pi.getData("pageCount"));

if (pageCount > 5000) {

   var error1 = new Object ();

   error1.author = author;

   error1.docName = docName;

   error1.pageCount = pageCount;

   logErrorMsg ("PAGE_COUNT_TOO_LONG", error1);

}

logHistoryMsg (label, comment)
Adds a row in the history log. This information is displayed to users when viewing Details & History in a work item list.

Parameter
Data Type
Description
label
String
Label for the entry in the history log.
comment
String
(Optional) Additional comment for the history event.

The label is a string to be used as the label for the entry in the history log, and the optional argument comment is a string describing the entry.

Use this function to add information for the users about the work items. The following code could be used in a completion script to add details when an author submits a document for review.

Example:.

// LOG A HISTORY MESSAGE

var pi = getProcessInstance():

var author = pi.getData("author");

var docName = pi.getData("docName");

var pageCount = parseInt (pi.getData("pageCount"));

logHistoryMsg ("Doc Submitted for Review",

      " \nAuthor: " + author +

      " \nDocument name: " + docName +

      " \nPage count: " + pageCount);

logInfoMsg(label, context)
Adds an entry in the info log of the application. This information is displayed to the administrator when they view the info log.

Parameter
Data Type
Description
label
String
Label for the entry in the history log.
context
String
(Optional) Hashtable of key/value pairs to print in the log entry.

The label is a string to be used as the label for the entry in the info log, and the optional argument context is an object that has a variable for each property of the info message.

Use this function to show information about the execution of scripts. This is particularly useful for viewing the progress of script execution while debugging scripts. The following code could be used in a completion or automation script to log information about a document that has been submitted for review.

Example:.

// LOG AN INFO MESSAGE

var pi = getProcessInstance():

var author = pi.getData("author");

var docName = pi.getData("docName");

var pageCount = parseInt (pi.getData("pageCount"));

var info1 = new Object ();

info1.author = author;

info1.docName = docName;

logInfoMsg ("DOC_SUBMITTED_FOR_REVIEW", info1);

logSecurityMsg (label, context)
Adds an entry in the security log of the application. This information is displayed to the administrator when they view the security log.

Parameter
Data Type
Description
label
String
Label for the entry in the security log.
context
String
(Optional) Hashtable of key/value pairs to print in the log entry.

The label is a string to be used as the label for entry in the security log, and the optional argument context is an object that has a variable for each property of the error message.

The following code could be used in a completion script or automation script to log a warning when an unauthorized user tries to perform a task that accesses an external database.

Example:.

// LOG A SECURITY MESSAGE

var pi = getProcessInstance():

var username = pi.getData("username");

var password = pi.getData("password");

var externalDB = pi.getData("externalDBName");

var securityError1 = new Object ();

securityError1.username = username;

securityError1.password = password;

securityError1.externalDB = externalDB;

logSecurityMsg ("EXTERNAL_DB_ACCESS_NOT_ALLOWED", securityError1);

setErrorMsg (errMessage)
This function enables the designer to add additional information that describes why a script failed. This information is displayed to the participant as part of the error dialog box.

Parameter
Data Type
Description
errMessage
String
Added to the error dialog box when an error occurs during processing.

The following code could be used in a completion script to add a message explaining that the completion script failed because the submitted document has too many pages.

Example:.

function checkPageCount () {

// ADD A COMPLETION SCRIPT ERROR MESSAGE

var pi = getProcessInstance():

var docName = pi.getData("docName");

var pageCount = parseInt (pi.getData("pageCount"));

if (pageCount > 5000) {

   setErrorMsg ("The page count for " + docName +

      " is " + pageCount +

      " which exceeds the maximum page count allowed. " +

   " Did you really write such a long document?");

   return false;

   }

   else return true;

}


Assignment, Completion, and Email Scripts
This section lists the predefined assignment, completion, and email scripts available in Process Automation Edition. These predefined scripts (which are also global functions) can be called from other scripts. For example, an expiration handler script could call the predefined function toUserById(). The value returned by toUserById() could in turn be passed to the assignTo() method on a work item. The assignTo() method would then re-assign the work item to a user with a given user ID.

checkParallelApproval (dataField, stopAction)
This function is meant for use as a completion script for work items that use the toParallelApproval() assignment script. The dataField must be the name of the data field that was specified in toParallelApproval(), and is used to keep track of who has completed the work item so far. The stopAction is the name of the action that a user can take to stop the approval process.

Parameter
Data Type
Description
dataField
String
Name of a data field.
stopAction
String
Name of an action.

If an activity (work item) uses the toParallelApproval() assignment script, the activity should have two possible actions for the assignees to take when they complete the work item. One should indicate approval, and the other should indicate disapproval. The activity should also use the checkParallelApproval() completion script, which performs the "disapproval' action as soon as any one assignee selects it, the theory being that it takes everyone to approve the work item, but only one dissenter to disapprove it.

Example:.

checkParallelApproval( "trackerField", "Reject" );

defaultNotificationHeader()
Returns the default notification header for a notification message body. The header contains information about the current work item, such as the current activity name, the process instance ID, the creation date of the process instance and the expiration date (if any).

This function may be used as the notification body script by itself, or may be embedded in your own notification body script. You may also use this function from a template evaluated using evaluateTemplate(). The function may only be used successfully from a script associated with a notification; if used anywhere else, an empty string is returned.

The text returned from this function will depend upon the content-type of the notification. If the content-type is text/html, the header will be a series of HTML tags; if the content-type is text/plain, the header will be plain text.

Example:.

function emailBody( )

{

var body = "Email message body <br>";

body += defaultNotificationHeader();

return body;

}

defaultNotificationSubject()
Returns the default notification subject for the notification subject line. The subject contains information about the current process instance, such as the process instance ID the priority and the title string.

This function may be used as the notification subject script by itself, or may be embedded in your own notification subject script. The function may only be used successfully from a script associated with a notification; if used anywhere else, an empty string is returned.

Example:.

function emailSubject( )

{

var subject = "Subject: " + defaultNotificationSubject();

return subject;

}

emailByDN(DN)
Returns a string of comma-delimited email addresses for the user with the given Distinguished Name (DN). The mail attribute for the user must contain a valid email address in the corporate user directory. If the mail attribute of the user does not have a value, this function logs an error and returns null. This function is intended for use as a notification script, but can be used anywhere that a string of email addresses is needed.

Parameter
Data Type
Description
userDN
String
DN of the user whose email address is returned.

Example:.

function getEmailByDN( )

var cd = getCorporateDirectory();

var u = cd.getUserById( "joe" );

return emailByDN( u.getDN() );

}

emailById(userId)
Returns a string of comma-delimited email addresses for the user with the given user ID. The mail attribute for the user must contain a valid email address in the corporate user directory. If the mail attribute of the user does not have a value, this function logs an error and returns null. This function is intended for use as a notification script, but can be used anywhere that a string of email addresses is needed.

Parameter
Data Type
Description
userId
String
User whose email address is returned.

Example:.

emailById( "joe" );

emailOfAssignees()
Returns a string of comma-delimited email addresses for all the assignees of the work item. The mail attribute for each assignee must contain a valid email address in the corporate user directory. If the mail attribute is empty for any assignee, no address is added to the string for that assignee. If no assignee has a value in their mail attribute, the function logs an error message and returns null. This function is intended for use as a notification script, but can be used anywhere that a string of email addresses is needed.

Example:.

emailOfAssignees();

emailOfCreator()
Returns a string of the email address of the user who created the process instance. The user's mail attribute must contain a valid email address in the corporate user directory. If the mail attribute of the user does not have a value, this function logs an error and returns null. This function is intended for use as a notification script, but can be used anywhere that a string of email addresses is needed.

Example:.

var pi = getProcessInstance();

var creatorEmail = emailOfCreator();

pi.setData( "creatorEmail", creatorEmail );

emailOfRole(roleName)
Returns a string of the email address of the user performing the given role. The user's mail attribute must contain a valid email address in the corporate user directory. If the mail attribute of the user does not have a value, this function logs an error and returns null. This function is intended for use as a notification script, but can be used anywhere that a string of email addresses is needed.

Parameter
Data Type
Description
roleName
String
Role whose email address is returned.

Example:.

emailOfRole( "reviewer" );

randomToGroup(groupName)
This function returns an array containing a Distinguished Name (DN) of one member of the group. The group member is selected at random. This function is intended to be used as an assignment script but can be used anywhere that an array of DNs is needed.

Parameter
Data Type
Description
groupName
String
Name of a group.

Example:.

var userDNArray = randomToGroup( "helpDesk" );

java.lang.System.out.println( "The DN of a helpdesk user is: " + userDNArray[ 0 ] );

toCreator()
Returns a JavaScript array with the Distinguished Name (DN) of the user who created the process instance. This method is the default assignment script assigned to user activities when a node is created on the Process Map.

Example:.

var creatorDNArray = toCreator();

java.lang.System.out.println( "Creator's DN is " + craetorDNArray[ 0 ] );

toGroup(groupName)
Returns a JavaScript array of Distinguished Names (DNs) of all members of the specified group. If the parameter groupName does not correspond to an actual group in the application's Groups and Roles folder, returns null.

Parameter
Data Type
Description
groupName
String
Name of the group.

Example:.

var groupDNs = toGroup( "reviewers" );

if( groupDNs != null )

{

   java.lang.System.out.println( "Number of members in the group" + groupDNs.length );

   for (var i = 0; i <= groupDNs.length; i++)

   {

      java.lang.System.out.println( "Member #" + i + ": " + groupDNs[i ] );

   }

}

else

   java.lang.System.out.println( "No such group reviewers" );

toManagerOf (userId)
This function returns an array containing the Distinguished Name (DN) of the manager of the user with the given user ID. The manager attribute of the given user must contain a DN in the corporate user directory. This function is intended to be used as an assignment script but can be used anywhere that an array of DNs is needed.

Parameter
Data Type
Description
userId
String
A user ID.

Example:.

var managerDNArray = toManagerOf( "sijacic" );

java.lang.System.out.println( "Manager of user sijacic is: " + managerDNArray[0] );

toManagerOfCreator()
This function returns an array containing the Distinguished Name (DN) of the manager of the creator of the process instance. The manager attribute of the creator user must contain a DN in the corporate user directory. This function is intended to be used as an assignment script but can be used anywhere that an array of DNs is needed.

Example:.

var managerDNArray = toManagerOfCreator();

java.lang.System.out.println( "Manager of the process creator is: " + ManagerDNArray[ 0 ] );

toManagerOfRole(role)
This function returns an array containing the Distinguished Name (DN) of the manager of the user defined as the given role. The manager attribute of the user fulfilling the role must contain a DN in the corporate user directory. This function is intended to be used as an assignment script but can be used anywhere that an array of DNs is needed.

Parameter
Data Type
Description
role
String
Name of the role.

Example:.

var managerDNArray = toManagerOfRole( "reviewer" );

java.lang.System.out.println( "Manager of the reviewer is: " + managerDNArray[ 0 ] );

toParallelApproval(arrayOfUserDNs, dataField)
This function should be used as an assignment script to assign a work item to several users who must all complete the work item. The arrayOfUserDNs argument is an array of distinguished names, and dataField is a data field that keeps track of who has performed the work item and who still needs to do it. This field is a computed field of length 2000 that must add to the data dictionary.

Parameter
Data Type
Description
arrayOfUserDNs
String
Name of the role.
dataField
String
Name of a data field in the current process.

If an activity (work item) uses the toParallelApproval() assignment script, the activity should have two possible actions for the assignees to take when they complete the work item. One action should indicate approval, and the other should indicate disapproval. The activity should also use the checkParallelApproval() completion script, which performs the "disapproval" action as soon as any one assignee selects it. The idea is that it takes everyone to approve the work item, but only one dissenter to disapprove it.

Example:.

var cd = getCorporateDirectory();

var user1 = cd.getUserById( "user1" );

var user2 = cd.getUserByID( "user2" );

var user3 = cd.getUserByID( "user3" );

var approvers = new Array( user1.getDN(), user2.getDN(), user3.getDN() );

toParallelApproval( approvers, "trackerField" );

toParallelApproval(toGroup( "approvers" ), "trackerField" );

toUserById(userId)
This function returns an array containing the Distinguished Name (DN) of the user with the given user ID. This function is intended to be used as an assignment script but can be used anywhere that an array of DNs is needed.

Parameter
Data Type
Description
userId
String
A user ID.

Example:.

var userDNArray = toUserById( "sijacic" );

java.lang.System.out.println( "The DN of the user is: " + userDNArray[ 0 ] );

toUserFromField(dataField)
This function returns an array containing the Distinguished Name (DN) of the user whose user ID is the value of the given data field. This function is intended to be used as an assignment script but can be used anywhere that an array of DNs is needed.

Parameter
Data Type
Description
dataField
String
Name of a data field.

Example:.

var userDNArray = toUserFromField( "approver" );

java.lang.System.out.println( "The DN of the user is: " + userDNArray[ 0 ] );


Miscellaneous Global Functions
This section summarizes the global functions that are neither log and error functions nor predefined scripts.

checkUserDNs(arrayOfUserDNs)
Verifies that all the DNs defined in the arrayOfUserDNs are valid and exist in the corporate directory. Return true if all the DNs are valid (or if the array is empty) otherwise returns false.

Parameter
Data Type
Description
arrayOfUserDNs
Array
List of DNs.

Example:.

var dnArray = new Array( "uid=sijacic, o=mcom.com",

   "uid=atam, o=mcom.com",

   "uid=souvik, o=mcom.com",

   "uid=michal, o=mcom.com",

   "uid=raghavan, o=mcom.com" );

// Check to see if all of the DNs are valid

if( checkUserDNs( dnArray ) )

java.lang.System.out.println( "All DNs are valid" );

else

java.lang.System.out.println( "One of the DNs is not valid" );

ejbLookup(jndiName)
Looks up an EJB that can be found under the given JNDI name. If no EJB exists under this name, an EJB exception, javax.naming.NamingException, is thrown. PAE handles this exception by moving the process instance into the designated Exception Manager node.

If the bean can be found under the given JNDI name, the home interface of that bean is returned. The home interface is used to create new instance of the EJB or find existing instnaces of the given EJB. The definition of the home interface is completely application-dependent; it typically consists of several create() and finder() methods. This function call is equivalent to the getJndiNamingContext().lookup(jndiName) function call.

Parameter
Data Type
Description
jndiName
String
JNDI name of the EJB to look up.

Example:.

var home = ejbLookup("Netscape/CreditCardServer");

// Create a credit card server that can do card authorizations.

var creditCardServer = home.create ( "mastercard" );

evaluateTemplate(templateName)
Used primarily in email notifications, but can be used for any template-like evaluation.

For email notifications, use evaluateTemplate() in the email body. When you create an email notification in Process Builder, specify evaluateTemplate( "templateFile" ) as the body script, where templateFile is the name of the template file relative to the application directory on the server. From Process Builder, you should include your template files in a folder called templates, a directory located in the application directory of Process Builder. When you deploy, the same directory structure is replicated on the server.

evaluateTemplate() also evaluates JavaScript segments contained in the template file. These segments are identified by <script language="Rhino"> tags.

In an HTML page containing client-side JavaScript, you can replace

<script language="JavaScript">

with

<script language="Rhino">

The PAE engine will evaluate the JavaScript in the same manner the browser does.

You can access the entire engine API (e.g., getProcessInstance(), getWorkITem(), etc.) from within these segments. To send output to an HTML file, use document.write() with the output you want to send provided as an argument.

evaluateTemplate() returns a string. The string is made up of the contents of the template file with the Rhino segments evaluated. If there are no Rhino segments in the file, the string simply contains the file contents. If there are Rhino segments, the string contains the evaluated JavaScript rather than the Rhino segments.

Example: .

var fileContents = evaluateTemplate( "templateFile" );

var cs = getContentStore():

cs.upload( fileContents, url ):

expireIn(val, unit)
Returns a JavaScript Date object set to the absolute datetime when the current work item will expire.

Parameter
Data Type
Description
val
Integer
Numeric value specifying the number of units in which to expire the workitem.
unit
String
Specifies the unit of time measurement value represents.

This function is normally used to specify the expiration time for a particular activity, and is usually set by the designer through Process Builder. In the event that you choose to specify the arguments for this function manually, the parameter unit can contain the following values:

Example:.

expireIn( 6, "minutes" ); // expire in 6 minutes

expireIn( 30, "days" ); // expire in 30 days

expireIn( 1, "month" ); // expire in 30 days

getAction()
Returns the name of the action (the button name) used to complete the current activity. The action name corresponds to the name of the button clicked when the work item form is submitted. This function can be used in any script, but is best used from the completion script of a user activity.

Example:.

function completion( )

{

var pi = getProcessInstance();

pi.setData( "submittedAction", getAction() ):

return true;

}

getApplicationName()
Returns the name of the application (for example: "wfDataSheet") as a string.

Example:.

var appName = getApplicationName();

java.lang.System.out.println( "The application name is: " + appName );

getApplicationPath()
Returns the pathname of the directory containing the files for this application as a string.

Example:.

var appPath = getApplicationPath();

java.lang.System.out.println( "The application path is: " + appPath );

getApplicationPrettyName()
Returns the pretty name of the application (for example: "DataSheet Management") as a string.

Example:.

var appPN = getApplicationPrettyName();

java.lang.System.out.println( "The application pretty name is: " + appPN );

getBaseForFileName (processId)
Given a unique process instance ID, this function returns a string of the base file name for the content store for that process instance.

Parameter
Data Type
Description
processId
String
A process ID.

The following code creates a path name for the file myFile.html in the content store. Note that this code does NOT create the file, it simply creates a string that can be used as the file name by methods on a contentStore object, such as move() and store().

Example:.

var pi = getProcessInstance();

var pid = pi.getInstanceId();

var contentStorePath = getBaseForFileName (pid);

var newFileName = contentStorePath + "myFile.html";

getConnector(connectorKey)
Given a connector key, returns a connector object from the list of connector objects available for use by scripts.

Parameter
Data Type
Description
connectorKey
String
A connector ID (previously set by setConnector()).

Example:.

function initialisationScript( )

{

   var c = new Packages.com.acme.DBConnection();

   setConnector( "dbConnector" );

   return true;

}

var c = getConnector( "dbConnector" );

getContentStore ()
Returns a contentStore object connected to the content store. See the section ContentStore for details of the methods on this object.

Example:.

var cs = getContentStore();

getContentStore(httpURL,user,password)
General purpose content store method. This method enables you to authenticate to arbitrary HTTP servers for file manipulation. You must have a content store object to use any of the content store methods.

Parameter
Data Type
Description
httpURL
String
URL of an HTTP server capable of acting as a content store.
user
String
User ID of the user who will authenticate the content store specified by httpURL.
password
String
Password for the specified user.

Example:.

var publishCS = getContentStore(

"http://publish.netscape.com/CS", "sijacic", "password");

getCreatorUserId ()
Returns the user ID for the creator user of the current process instance.

This function is intended to be used as the initiate-as script for sub-process nodes. When the child process instance is created, its creator must be determined. Normally, the creator of the child process instance is the same user that authenticated with the server at the time the sub-process node was executed. However, it may be desirable (or necessary) to set the child creator to the same user as the creator of the parent process instance.

If you choose to use this function to change the child creator user, the authenticating (or current) user must be a member of the trusted users group in the child application.

Example:.

var pi = getProcessInstance();

var creatorUser = pi.getCreatorUser();

var creatorUserId = creatorUser.getUserId();

getCorporateDirectory ()
Returns a corporateDirectory object connected to the corporate directory in the Directory Server. See the section CorporateDirectory for details of the methods on this object.

Example:.

var corpDir = getCorporateDirectory();

__getIncludePath ()
Returns the current inclusion path used by the server to search for JavaScript source files. This search path resembles in behavior the PATH mechanism used in Windows NT and UNIX to search for executables and libraries when a file name is not absolute.

The directory installDir/resources/server/js (where installDir is PAE installation directory on the server machine) is included in the search path by default.

Example:.

// Returns the current search path

var includePath = __getIncludePath();

// Add our own directory to the search path

includePath += ';' + "d:\\tmp";

// Set the search path

__setIncludePath( includePath );

getJndiNamingContext()
Returns the current NAS JNDI naming context used to look up the home interface of an EJB.

Use this function to access EJBs from within a Custom Activity. You can pass the instance of the naming context to the Custom Activity and use the lookup() method on this context to obtain home interfaces of the beans.

Example:.

var namingContext = getJndiNamingContext()

getProcessInstance ()
Returns a JavaScript ProcessInstance object associated with the current work item.

See the section ProcessInstance for details of the methods on this object.

Example:.

var wi = getWorkItem();

var pi = getProcessInstance();

java.lang.System.out.println( "The Process Instance ID: " + pi.getInstanceId() );

getSubProcessInstance ()
Returns a ProcessInstance object corresponding to the completed child process instance. This function should only be used from the completion script of a sub-process node. The object returned by this function has all the same methods expected of a ProcessInstance object, except that the information contained within corresponds to the completed child process instance instead of the parent. If this function is called from any location other than the completion script of a sub-process node, null is returned.

Example:.

// Completion script of sub-process node

function parentCompletion( )

{

var pi = getProcessInstance(); // parent process instance

var spi = getSubProcessInstance(); // child process instance

// Map some of the data elements from the child back to the

// parent process instance

pi.setData( "childStatus", spi.getData( "status" ) );

pi.setData( "numApprovers", spi.getData( "numApprovers" ) );

return true;

}

getWorkItem ()
Returns a workItem object that represents the current work item. See the section WorkItem for details of the methods on this object.

Example:.

var wi = getWorkItem();

__includeFile (fileName)
Reads in the contents of a JavaScript source file and evaluates the contents. Any JavaScript functions and objects defined within the file are available to all user scripts.

__includeFile() and its "helper" functions, __getIncludePath() and __setIncludePath(), are used by the server to define the built-in JavaScript functions available to user scripts.

If you want to access JavaScript functions or objects from user scripts and do not want to include the script files with every application you develop, you can externalize the functions in a separate JavaScript file and include the functions in the server's global run-time scope using __includeFile().

Parameter
Data Type
Description
fileName
String
Pathname of the JavaScript file to evaluate.

Example 1:.

// Sample JavaScript file

function checkCreator( userId )

{

var pi = getProcessInstance();

var u = pi.getCreatorUser();

// If the process instance creator matches the

// userId, return true, else false.

if( userId == u.getUserId() )

return true;

else

return false;

}

Example 2.

// Sample includeList.js file

var myIncludePath = "d:\\tmp";

var includePath = __getIncludePath() + ';' + myIncludePath;

__setIncludePath( includePath );

__includeFile( "myFunctions.js" );

mapTo(fieldName)
Used only from a custom activity as a means of mapping values from the output hashtable back to the process instance. The fieldName parameter specifies the name of a data element in the process instance. This data element receives the value of the current output parameter. When the custom activity's perform() call is complete, the server iterates through the hashtable, one element at a time, and attempts to map the element's value to a field in the process instance. Returns true if data mapping succeeds. Returns false if a problem has occurred.

Parameter
Data Type
Description
fieldName
String
Name of a data element in the process instance.

Example:.

mapTo( "customerName" );

mount(jndiName)
Looks up and creates an instance of a stateless session bean, or EJB, found under the given JNDI name. If no bean exists under this name, a javax.naming.NamingException is thrown. PAE handles this exception by moving the process instance into the designated Exception Manager node. If the EJB can be found under the given JNDI name, an instance of it is created by calling the create() method on the returned home interface of the bean. This function call is equivalent to the ejbLookup(jndiName).create() function call.

Parameter
Data Type
Description
jndiName
String
JNDI name of the EJB to "mount."

Example:.

var creditServer = mount("Netscape/CreditCardServer");

setConnector(connKey, connObject)
Adds a connector object (such as a database connection) indexed by key to the list of connector objects that can be used by scripts.

Parameter
Data Type
Description
connKey
String
Key used to retrieve the associated object (through getConnector()).
connObject
Object
Object stored and associated with the specified key.

Example:.

var pi = getProcessInstance();

var obj = new Object();

obj.machinename = "lint";

obj.username = "admin";

obj.passwd = "netscape";

setConnector("myConnector", obj);

__setIncludePath (includePath)
Allows the user to specify the path the server uses to search for JavaScript source files. The path is a delimited list of absolute directory path names. The delimiter depends upon the system:

Searches start from the first directory and proceed to the last directory until the file is located. The directory installDir/resources/server/js (where installDir is where PAE is installed on the server machine) is included in the search path by default. However, once you set your own path using this function, the current search path is overwritten. Thus, calls to __setIncludePath should specify the entire search path by appending the new search directory to the current search path.

Parameter
Data Type
Description
includePath
String
Ssearch path the server uses to locate JavaScript source files.

Example:.

var includePath = __getIncludePath();

includePath += ';' + "d:\\tmp";

// Set the search path. Note how the variable includePath also

// specifies the existing search path. Every call to __setIncludePath

// overwrites the previous search path.

__setIncludePath( includePath );

setRedirectionURL(stringURL)
Redirects the participant's browser to the specified location in stringURL.

Invoke this method from a completion script. setRedirectionURL() is typically used for multiple-screen data entry where the same person may enter data across several screens or user activities. The process subsequently becomes a wizard-like forms entry screen.

Parameter
Data Type
Description
stringURL
String
A valid URL.

Example:.

function scriptComplete( )

{

// Redirect to the Netscape Home Page

setRedirectionURL( "http://home.netscape.com" );

// This will cause the same process instance to display after the

// user clicks an action button

setRedirectionURL( url_OnDisplayProcessInstance() );

// Don't forget to return true; this is still a completion script

return true;

}

url_OnDisplayHistory()
Returns a string containing the URL that points to the history list for the current process instance. This function is usually used in conjunction with setRedirectionURL() to redirect a user to the history page of the current process instance.

Example:.

function scriptComplete( )

{

// Redirect to the History Page of this process instance

setRedirectionURL( url_OnDisplayHistory() );

}

url_OnDisplayProcessInstance()
Returns a string containing the URL that points the current process instance. This function is usually used in conjuction with setRedirectionURL() to redirect a user to the current process instance.

Example:.

function scriptComplete( )

{

// Redirect to the current process instance

setRedirectionURL( url_OnDisplayProcessInstance() );

}

url_OnDisplayWorkItem()
Returns a string containing the URL that points to the current work item. This function is usually used in conjuction with setRedirectionURL() method to redirect a user to the current work item.

Example:.

function scriptComplete( )

{

// Redirect to the current work item

setRedirectionURL( url_OnDisplayWorkItem() );

}

url_OnDisplayWorklist()
Returns a string containing the URL that points to the user's work list. This function is usually used in conjuction with setRedirectionURL() to redirect a user to their work list.

Example:.

function scriptComplete( )

{

// Redirect to the user to their work list

setRedirectionURL( url_OnDisplayWorklist() );

}

url_OnListApplications()
Returns a string containing the URL listing applications installed on the PAE cluster. This function is usually used in conjunction with setRedirectionURL() to redirect a user to the list of applications installed on the cluster.

Example:.

function scriptComplete( )

{

// Redirect to the list of applications on this cluster

setRedirectionURL( url_OnListApplications() );

}

url_OnListEntryNodes()
Returns a string containing the URL that points to the list of entry points in the current application. This function is usually used in conjunction with setRedirectionURL() to redirect a user to the list of entry points in the current application.

Example:.

function scriptComplete( )

{

// Redirect to the list of entry points of the current application

setRedirectionURL( url_OnListEntryNodes() );

}


Alphabetical Summary of JavaScript Objects
The following table lists the JavaScript methods and functions available in Process Automation Edition (PAE):

JavaScript method or function
Where Used in PAE
__getIncludePath
global function
__includeFile
global function
__setIncludePath
global function
addUser
corporateDirectory
assignTo
workItem
checkParallelApproval
predefined script
checkUserDNs
global function
deleteUserByCN
corporateDirectory
deleteUserByDN
corporateDirectory
deleteUserById
corporateDirectory
download
contentStore
emailByDN
predefined script
emailById
predefined script
emailOfAssignees
predefined script
emailOfCreator
predefined script
emailOfRole
predefined script
evaluateTemplate
global function
exists
contentStore
expire
workItem
expireIn
global function
extend
workItem
getApplicationName
global function
getApplicationPath
global function
getApplicationPrettyName
global function
getAssigneesDN
workItem
getBaseForFileName
global function
getConclusion
global function
getConnector
global function
getContent
contentStore
getContentStore
global function
getCorporateDirectory
global function
getCreationDate
processInstance
getCreationDate
workItem
getCreatorDN
processInstance
getCreatorUser
processInstance
getCreatorUserId
global function
getCurrentActivityCN
workItem
getData
processInstance
getEntryNodeName
processInstance
getException
contentStore
getExitNodeName
processInstance
getExpirationDate
workItem
getInstanceId
processInstance
getPriority
processInstance
getProcessInstance
global function
getRoleDN
processInstance
getRoleUser
processInstance
getRootURL
contentStore
getStatus
contentStore
getSubProcessInstance
global function
getTitle
processInstance
getUserByCN
corporateDirectory
getUserByDN
corporateDirectory
getUserById
corporateDirectory
getVersion
contentStore
getWorkItem
global function
hasExpired
workItem
initialize
contentStore
isException
contentStore
isStateActive
workItem
isStateRunning
workItem
isStateSuspended
workItem
logErrorMsg
global function
logHistoryMsg
global function
logInfoMsg
global function
logSecurityMsg
global function
mapTo
global function
mkdir
contentStore
modifyUserByCN
corporateDirectory
modifyUserByDN
corporateDirectory
modifyUserById
corporateDirectory
mount
global function
move
contentStore
moveTo
workItem
randomToGroup
predefined script
resume
workItem
rmdir
contentStore
setConnector
global function
setData
processInstance
setErrorMessage
global function
setErrorMsg
global function
setExpirationDate
workItem
setPriority
processInstance
setRedirectionURL
global function
setRoleByDN
processInstance
setRoleById
processInstance
setTitle
processInstance
store
contentStore
suspend
workItem
toCreator
predefined script
toGroup
predefined script
toManagerOf
predefined script
toManagerOfCreator
predefined script
toManagerOfRole
predefined script
toParallelApproval
predefined script
toUserById
predefined script
toUserFromField
predefined script
upload
contentStore

 

Copyright © 1999 Netscape Communications Corp. All rights reserved.