Scripting Function Reference
Note
If you need to request specific resource versions, see REST API Versioning.
Functions (access to managed objects, system objects, and configuration objects) within IDM are accessible to scripts via the openidm
object, which is included in the top-level scope provided to each script.
The script engine supports the following functions:
This function creates a new resource object.
- resourceName
string
The container in which the object will be created, for example,
managed/user
.- newResourceId
string
The identifier of the object to be created, if the client is supplying the ID. If the server should generate the ID, pass null here.
- content
JSON object
The content of the object to be created.
- params
JSON object (optional)
Additional parameters that are passed to the create request.
- fields
JSON array (optional)
An array of the fields that should be returned in the result. The list of fields can include wild cards, such as
*
or*_ref
. If no fields are specified, the entire new object is returned.
The created resource object.
An exception is thrown if the object could not be created.
openidm.create("managed/user", ID, JSON object);
This function performs a partial modification of a managed or system object. Unlike the update
function, only the modified attributes are provided, not the entire object.
- resourceName
string
The full path to the object being updated, including the ID.
- rev
string
The revision of the object to be updated. Use
null
if the object is not subject to revision control, or if you want to skip the revision check and update the object, regardless of the revision.- value
An array of one or more JSON objects
The value of the modifications to be applied to the object. The patch set includes the operation type, the field to be changed, and the new values. A PATCH request can
add
,remove
,replace
, orincrement
an attribute value.A
remove
operation removes a property if the value of that property equals the specified value, or if no value is specified in the request. The following examplevalue
removes themarital_status
property from the object, if the value of that property issingle
:[ { "operation": "remove", "field": "marital_status", "value": "single" } ]
For fields whose value is an array, it's not necessary to know the position of the value in the array, as long as you specify the full object. If the full object is found in the array, that value is removed. The following example removes user adonnelly from bjensen's
reports
:{ "operation": "remove", "field": "/manager", "value": { "_ref": "managed/user/adonnelly", "_refResourceCollection": "managed/user", "_refResourceId": "adonnelly", "_refProperties": { "_id": "ed6620e4-98ba-410c-abc0-e06dc1be7aa7", "_rev": "000000008815942b" } } }
If an invalid value is specified (that is a value that does not exist for that property in the current object) the patch request is silently ignored.
A
replace
operation replaces an existing value, or adds a value if no value exists.- params
JSON object (optional)
Additional parameters that are passed to the patch request.
- fields
JSON array (optional)
An array of the fields that should be returned in the result. The list of fields can include wild cards, such as
*
or*_ref
. If no fields are specified, the entire new object is returned.
The modified resource object.
An exception is thrown if the object could not be updated.
Patching an object to add a value to an array:
openidm.patch("managed/role/" + role._id, null, [{"operation":"add", "field":"/members/-", "value": {"_ref":"managed/user/" + user._id}}]);
Patching an object to remove an existing property:
openidm.patch("managed/user/" + user._id, null, [{"operation":"remove", "field":"marital_status", "value":"single"}]);
Patching an object to replace a field value:
openidm.patch("managed/user/" + user._id, null, [{"operation":"replace", "field":"/password", "value":"Passw0rd"}]);
Patching an object to increment an integer value:
openidm.patch("managed/user/" + user._id, null, [{"operation":"increment","field":"/age","value":1}]);
This function reads and returns a resource object.
- resourceName
string
The full path to the object to be read, including the ID.
- params
JSON object (optional)
The parameters that are passed to the read request. Generally, no additional parameters are passed to a read request, but this might differ, depending on the request. If you need to specify a list of
fields
as a third parameter, and you have no additionalparams
to pass, you must passnull
here. Otherwise, you simply omit both parameters.- fields
JSON array (optional)
An array of the fields that should be returned in the result. The list of fields can include wild cards, such as
*
or*_ref
. If no fields are specified, the entire object is returned.
The resource object, or
null
if not found.
openidm.read("managed/user/"+userId, null, ["*", "manager"]);
This function updates an entire resource object.
- id
string
The complete path to the object to be updated, including its ID.
- rev
string
The revision of the object to be updated. Use
null
if the object is not subject to revision control, or if you want to skip the revision check and update the object, regardless of the revision.- value
object
The complete replacement object.
- params
JSON object (optional)
The parameters that are passed to the update request.
- fields
JSON array (optional)
An array of the fields that should be returned in the result. The list of fields can include wild cards, such as
*
or*_ref
. If no fields are specified, the entire object is returned.
The modified resource object.
An exception is thrown if the object could not be updated.
In this example, the managed user entry is read (with an
openidm.read
, the user entry that has been read is updated with a new description, and the entire updated object is replaced with the new value.var user_read = openidm.read('managed/user/' + source._id); user_read['description'] = 'The entry has been updated'; openidm.update('managed/user/' + source._id, null, user_read);
This function deletes a resource object.
- resourceName
string
The complete path to the to be deleted, including its ID.
- rev
string
The revision of the object to be deleted. Use
null
if the object is not subject to revision control, or if you want to skip the revision check and delete the object, regardless of the revision.- params
JSON object (optional)
The parameters that are passed to the delete request.
- fields
JSON array (optional)
An array of the fields that should be returned in the result. The list of fields can include wild cards, such as
*
or*_ref
. If no fields are specified, the entire object is returned.
Returns the deleted object if successful.
An exception is thrown if the object could not be deleted.
openidm.delete('managed/user/'+ user._id, user._rev);
This function performs a query on the specified resource object. For more information, see "Construct Queries".
- resourceName
string
The resource object on which the query should be performed, for example,
"managed/user"
, or"system/ldap/account"
.- params
JSON object
The parameters that are passed to the query (
_queryFilter
, or_queryId
). Additional parameters passed to the query will differ, depending on the query.Certain common parameters can be passed to the query to restrict the query results. The following sample query passes paging parameters and sort keys to the query.
reconAudit = openidm.query("audit/recon", { "_queryFilter": queryFilter, "_pageSize": limit, "_pagedResultsOffset": offset, "_pagedResultsCookie": string, "_sortKeys": "-timestamp" });
For more information about
_queryFilter
syntax, see "Common Filter Expressions". For more information about paging, see "Page Query Results".- fields
list
A list of the fields that should be returned in the result. The list of fields can include wild cards, such as
*
or*_ref
. The following example returns only theuserName
and_id
fields:openidm.query("managed/user", { "_queryFilter": "/userName sw \"user.1\""}, ["userName", "_id"]);
This parameter is particularly useful in enabling you to return the response from a query without including intermediary code to massage it into the right format.
Fields are specified as JSON pointers.
The result of the query. A query result includes the following parameters:
- query-time-ms
(For JDBC repositories only) the time, in milliseconds, that IDM took to process the query.
- result
The list of entries retrieved by the query. The result includes the properties that were requested in the query.
The following example shows the result of a custom query that requests the ID, user name, and email address of all managed users in the repository.
{ "result": [ { "_id": "9dce06d4-2fc1-4830-a92b-bd35c2f6bcbb", "_rev": "00000000a059dc9f", "userName": "bjensen", "mail": "bjensen@example.com" }, { "_id": "42f8a60e-2019-4110-a10d-7231c3578e2b", "_rev": "00000000d84ade1c", "userName": "scarter", "mail": "scarter@example.com" } ], "resultCount": 2, "pagedResultsCookie": null, "totalPagedResultsPolicy": "NONE", "totalPagedResults": -1, "remainingPagedResults": -1 }
An exception is thrown if the given query could not be processed.
The following sample query uses a
_queryFilter
to query the managed user repository:openidm.query("managed/user", {'_queryFilter': userIdPropertyName + ' eq "' + security.authenticationId + '"'});
The following sample query references the
for-userName
query, defined in the repository configuration, to query the managed user repository:openidm.query("managed/user", {"_queryId": "for-userName", "uid": request.additionalParameters.uid });
This function performs an action on the specified resource object. The resource
and actionName
are required. All other parameters are optional.
- resource
string
The resource that the function acts upon, for example,
managed/user
.- actionName
string
The action to execute. Actions are used to represent functionality that is not covered by the standard methods for a resource (create, read, update, delete, patch, or query). In general, you should not use the
openidm.action
function for create, read, update, patch, delete or query operations. Instead, use the corresponding function specific to the operation (for example,openidm.create
).Using the operation-specific functions lets you benefit from the well-defined REST API, which follows the same pattern as all other standard resources in the system. Using the REST API enhances usability for your own API, and enforces the established patterns.
IDM-defined resources support a fixed set of actions. For user-defined resources (scriptable endpoints) you can implement whatever actions you require.
Supported Actions Per ResourceThe following list outlines the supported actions for each resource or endpoint. The actions listed here are also supported over the REST interface.
- Actions supported on the
authentication
endpoint (authentication/*
) reauthenticate
- Actions supported on the configuration resource (
config/
) No action parameter applies.
- Actions supported on custom endpoints
Custom endpoints enable you to run arbitrary scripts through the REST URI, and are routed at
endpoint/name
, where name generally describes the purpose of the endpoint. For more information on custom endpoints, see Create Custom Endpoints to Launch Scripts. You can implement whatever actions you require on a custom endpoint. IDM uses custom endpoints in its workflow implementation. Those endpoints, and their actions are as follows:endpoint/getprocessforuser
-create, complete
endpoint/gettasksview
-create, complete
- Actions supported on the
external
endpoint external/email
-send
, for example:{ emailParams = { "from" : 'admin@example.com', "to" : user.mail, "subject" : 'Password expiry notification', "type" : 'text/plain', "body" : 'Your password will expire soon. Please change it!' } openidm.action("external/email", "send", emailParams); }
external/rest
-call
, for example:openidm.action("external/rest", "call", params);
- Actions supported on the
info
endpoint (info/*
) No action parameter applies.
- Actions supported on managed resources (
managed/*
) patch, triggerSyncCheck
- Actions supported on the policy resource (
policy
) validateObject, validateProperty
For example:
openidm.action("policy/" + fullResourcePath, "validateObject", request.content, { "external" : "true" });
- Actions supported on the reconciliation resource (
recon
) recon, reconById, cancel
For example:
openidm.action("recon/_id", "cancel", content, params);
Note
A cancel action requires the entire reconciliation resource path (_id).
- Actions supported on the repository (
repo
) command
For example:
var r, command = { "commandId": "purge-by-recon-number-of", "numberOf": numOfRecons, "includeMapping": includeMapping, "excludeMapping": excludeMapping }; r = openidm.action("repo/audit/recon", "command", {}, command);
- Actions supported on the script resource (
script
) eval
For example:
openidm.action("script", "eval", getConfig(scriptConfig), {});
- Actions supported on the synchronization resource (
sync
) getLinkedResources, notifyCreate, notifyDelete, notifyUpdate, performAction
For example:
openidm.action('sync', 'performAction', content, params);
- Actions supported on system resources (
system/*
) availableConnectors, createCoreConfig, createFullConfig, test, testConfig, liveSync, authenticate, script
For example:
openidm.action("system/ldap/account", "authenticate", {"username" : "bjensen", "password" : "Passw0rd"});
- Actions supported on the task scanner resource (
taskscanner
) execute, cancel
- Actions supported on the workflow resource (
workflow/*
) On
workflow/processdefinition
create, completeOn
workflow/processinstance
create, completeFor example:
var params = { "_key":"contractorOnboarding" }; openidm.action('workflow/processinstance', 'create', params);
On
workflow/taskinstance
claim, create, completeFor example:
var params = { "userId":"manager1" }; openidm.action('workflow/taskinstance/15', 'claim', params);
- Actions supported on the
- content
object
Content given to the action for processing.
- params
object (optional)
Additional parameters passed to the script. The
params
object must be a set of simple key:value pairs, and cannot include complex values. The parameters must map directly to URL variables, which take the formname1=val1&name2=val2&...
.- fields
JSON array (optional)
An array of the fields that should be returned in the result. The list of fields can include wild cards, such as
*
or*_ref
. If no fields are specified, the entire object is returned.
The result of the action may be
null
.
If the action cannot be executed, an exception is thrown.
This function encrypts a value.
- value
any
The value to be encrypted.
- cipher
string
The cipher with which to encrypt the value, using the form "algorithm/mode/padding" or just "algorithm". Example:
AES/CBC/PKCS5Padding
.- alias
string
The key alias in the keystore, such as
openidm-sym-default
(deprecated) or a purpose defined in thesecrets.json
file, such asidm.password.encryption
.
The value, encrypted with the specified cipher and key.
An exception is thrown if the object could not be encrypted.
This function decrypts a value.
- value
object
The value to be decrypted.
A deep copy of the value, with any encrypted value decrypted.
An exception is thrown if the object could not be decrypted for any reason. An error is thrown if the value is passed in as a string - it must be passed in an object.
This function determines if a value is encrypted.
- object to check
any
The object whose value should be checked to determine if it is encrypted.
Boolean,
true
if the value is encrypted, andfalse
if it is not encrypted.
An exception is thrown if the server is unable to detect whether the value is encrypted, for any reason.
This function calculates a value using a salted hash algorithm.
- value
any
The value to be hashed.
- algorithm
string (optional)
The algorithm with which to hash the value. Example:
SHA-512
. If no algorithm is provided, anull
value must be passed, and the algorithm defaults to SHA-256. For a list of supported hash algorithms, see "Encoding Attribute Values by Using Salted Hash Algorithms".
The value, calculated with the specified hash algorithm.
An exception is thrown if the object could not be hashed for any reason.
This function detects whether a value has been calculated with a salted hash algorithm.
- value
any
The value to be reviewed.
Boolean,
true
if the value is hashed, andfalse
otherwise.
An exception is thrown if the server is unable to detect whether the value is hashed, for any reason.
This function detects whether a string, when hashed, matches an existing hashed value.
- string
any
A string to be hashed.
- value
any
A hashed value to compare to the string.
Boolean,
true
if the hash of the string matches the hashed value, andfalse
otherwise.
An exception is thrown if the string could not be hashed.
Log Functions
IDM also provides a logger
object to access the Simple Logging Facade for Java (SLF4J) facilities. The following code shows an example of the logger
object.
logger.info("Parameters passed in: {} {} {}", param1, param2, param3);
To set the log level for JavaScript scripts, add the following property to your project's conf/logging.properties
file:
org.forgerock.openidm.script.javascript.JavaScript.level
The level can be one of SEVERE
(highest value), WARNING, INFO, CONFIG, FINE, FINER
, or FINEST
(lowest value). For example:
org.forgerock.openidm.script.javascript.JavaScript.level=WARNING
In addition, JavaScript has a useful logging function named console.log()
. This function provides an easy way to dump data to the IDM standard output (usually the same output as the OSGi console). The function works well with the JavaScript built-in function JSON.stringify
and provides fine-grained details about any given object. For example, the following line will print a formatted JSON structure that represents the HTTP request details to STDOUT.
console.log(JSON.stringify(context.http, null, 4));
Note
These logging functions apply only to JavaScript scripts. To use the logging functions in Groovy scripts, the following lines must be added to the Groovy scripts:
import org.slf4j.*; logger = LoggerFactory.getLogger('logger');
The script engine supports the following log functions:
Logs a message at DEBUG level.
- message
string
The message format to log. Params replace
{}
in your message.- params
object
Arguments to include in the message.
A
null
value if successful.
An exception is thrown if the message could not be logged.
Logs a message at ERROR level.
- message
string
The message format to log. Params replace
{}
in your message.- params
object
Arguments to include in the message.
A
null
value if successful.
An exception is thrown if the message could not be logged.
Logs a message at INFO level.
- message
string
The message format to log. Params replace
{}
in your message.- params
object
Arguments to include in the message.
A
null
value if successful.
An exception is thrown if the message could not be logged.
Logs a message at TRACE level.
- message
string
The message format to log. Params replace
{}
in your message.- params
object
Arguments to include in the message.
A
null
value if successful.
An exception is thrown if the message could not be logged.
Logs a message at WARN level.
- message
string
The message format to log. Params replace
{}
in your message.- params
object
Arguments to include in the message.
A
null
value if successful.
An exception is thrown if the message could not be logged.