Groovy
Groovy is a scripting language that is very similar to Java. The syntax is nearly identical to that of Java, with a few extensions. In Groovy, it is possible to declare variables without specifying a type, if you choose to do so. Intrexx uses Groovy primarily to control processes, perform complex calculations, and execute equally complex queries. Because of its similarity to Java, in most cases it is possible to copy scripts from the diverse world of Java and reuse them in Groovy. Here, too, you can also integrate your own Java classes. The API provides a range of methods for accessing key Intrexx features and objects.
You can find general information on "scripting" here.
Intrexx Standard Library
In the Groovy script editor, you can access the Intrexx standard library in the "Libraries" section. Once you've selected an item in the library, you'll see the following buttons in the lower-right corner:
View description
Here you will find a description of the currently selected function, along with a sample script.
Open link
Provides links to relevant pages with additional information. This opens the specific page containing the classes, interfaces, methods, or properties that you can use for the currently selected function.
Below is a description of the features included.
Application Structure
Application property from a record object
Reads application properties from the dataset object. In the sample script, replace "myMethod()" with the method of your choice.
Example
def appInfoValue = g_record.applicationInfo.getGuid()
Returns the GUID of the application to which the record belongs.
Snippet
def appInfoValue = g_record.applicationInfo.myMethod()
Starting with Intrexx version 12.0.0
Data Group Property from Record Object
Reads data group properties from the dataset object. In the sample script, replace "myMethod()" with the method of your choice.
Example
def dgInfoValue = g_record.dataGroupInfo.getGuid()
Returns the GUID of the data group to which the record belongs.
Snippet
def dgInfoValue = g_record.dataGroupInfo.myMethod()
Starting with Intrexx version 12.0.0
Application Information
Returns information about the application with the specified GUID. In the sample script, replace "myMethod()" with the method of your choice.
Example
def appPropValue = app?.getGuid()
Returns the application's GUID.
Snippet
def app = g_rtCache.applications["<application GUID>"]
def appPropValue = app?.myMethod()
Starting with Intrexx version 12.0.0
Inspection Information
Returns information about the control associated with the specified GUID. In the sample script, replace "myMethod()" with the method of your choice.
Example
def ctrlInfo = ctrl?.getPageGuid()
Returns the GUID of the page on which the control is located.
Snippet
def ctrl = g_rtCache.controls["<control GUID>"]
def ctrlInfo = ctrl?.myMethod()
Starting with Intrexx version 12.0.0
Data Group Information
Returns information about the data group with the specified GUID. In the sample script, replace "myMethod()" with the method of your choice.
Example
Returns the GUID of the data group:
def dgInfo = dg?.getGuid()
Snippet
def dg = g_rtCache.dataGroups["<data group GUID>"]
def dgInfo = dg?.myMethod()
Starting with Intrexx version 12.0.0
Data Field Info
Returns information about the data field with the specified GUID. In the sample script, replace "myMethod()" with the method of your choice.
Example
Returns the GUID of the data field:
def fldInfo = fld?.getGuid()
Snippet
def fld = g_rtCache.fields["<data field GUID>"]
def fldInfo = fld?.myMethod()
Starting with Intrexx version 12.0.0
Reference Information
Returns information about the reference with the specified GUID. In the sample script, replace "myMethod()" with the method of your choice.
Example
Returns the GUID of the reference:
def refInfo = ref?.getGuid()
Snippet
def ref = g_rtCache.references["<reference GUID>"]
def refInfo = ref?.myMethod()
Starting with Intrexx version 12.0.0
Application API
JSON Response (for Groovy Endpoints)
The following snippet can be used in Groovy endpoints. It differs from the existing example in that it does not include the json() call and, most importantly, lacks error handling. The latter does not work in the Application API because it is handled by the framework.
Snippet
// write a JSON object that is defined in Groovy
// using maps, lists, strings, numbers, ...
writeJSON("person": [
givenName: "Donald",
lastName: "Duck",
age: 87,
nephews: ["Huey", "Dewey", "Louie"]
])
Parsing the JSON Body from a Request (Groovy Endpoints)
The following code snippet can be used to parse JSON content that was transmitted in the body of an HTTP request.
Snippet
def json = g_json.parse(request)
Accessing Path Variables
The following code snippet can be used to access path variables from Groovy endpoints. The values have the data type defined in the endpoint configuration.
"g_pathVariables" is also available in Groovy scripts within processes. However, the value may be zero if the process was not triggered by a call to the application API.
Example:
Check whether path variables exist
if (g_pathVariables) {
// do something
}
Snippet
def pathValue = g_pathVariables?.nameOfThePathVariable
Accessing Query Variables
The following code snippet allows you to access query variables from Groovy endpoints. The values have the data type defined in the endpoint configuration. "g_queryParameters" is also available in Groovy scripts within processes. However, the value may be zero if the process was not triggered by a call to the application API.
Example:
Check whether query variables exist
if (g_queryParameters) {
// do something
}
Snippet
def queryValue = g_queryParameters?.nameOfTheQueryParameter
Setting the HTTP Status Code When an Exception Occurs
Snippet
try
{
writeJSON("person": [
givenName: "Donald",
lastName: "Duck",
age: 87,
nephews: ["Huey", "Dewey", "Louie"]
])
throw new Exception("Let's test catching an exception.")
}
catch (e)
{
g_syslog.error("Exception has been caught.", e)
response.reset()
response.setStatus(406)
}
Class GroovyHttpServletResponse
Starting with Intrexx version 12.0.0
Class GroovyHttpServletResponse
Setting an HTTP Status Code via an Exception
Snippet
import de.uplanet.net.http.HttpBadRequestException
throw new HttpBadRequestException("Set HTTP status code by exception")
writeJSON("success": true)
Starting with Intrexx version 12.0.0
Language Constants
All text elements used in the standard Intrexx installation are defined in the global language constants. You can find general information on this topic here.
Accessing a Global Language Constant
Returns the value of the global language constant in the portal's default language. In the sample script, replace "PORTAL_CONST_NAME" with the name of the language constant you want to use.
Example
def strValue = g_i18n.BUTTON_NEXT
Displays "Next" (the label for the "Next" button, which you'll find in many dialog boxes, in German, the default language of the example portal).
Snippet
def strValue = g_i18n.PORTAL_CONST_NAME
Starting with Intrexx version 12.0.0
Accessing a global language constant in a specific language
Returns the value of the global language constant for a specific portal language. In the sample script, replace "PORTAL_CONST_NAME" with the name of the language constant you want to use.
Example
Returns the value of the global language constant for the English language setting.
def lang = g_i18n.language("en")
Snippet
def lang = g_i18n.language("language code")
def strValue = lang.PORTAL_CONST_NAME
Starting with Intrexx version 12.0.0
Accessing an Application's Language Constant
Returns the value of the application language constant in the portal's default language. In the sample script, replace "APP_CONST_NAME" with the name of the language constant you want to use.
Snippet
def app = g_i18n.application("<application GUID>")
def strValue = app.APP_CONST_NAME
Starting with Intrexx version 12.0.0
Accessing an application's language constant in a specific language
Returns the value of the application language constant in a specific portal language. In the sample script, replace "APP_CONST_NAME" with the name of the language constant you want to use. For the language code, enter "en" for English, for example.
Snippet
def app = g_i18n.application("<application GUID>")
def strLang = app.language("<language code>")
def strValue = strLang.APP_CONST_NAME
Starting with Intrexx version 12.0.0
Imports
Intrexx AccessController
A class that can be used to determine whether access requests should be granted or denied based on the currently valid security policy.
Snippet
import de.uplanet.lucy.server.security.IxAccessController
Starting with Intrexx version 12.0.0
IFilter
Snippet
import de.uplanet.util.filter.IFilter
Starting with Intrexx version 12.0.0
WorkflowException
Error Handling in Processes.
Snippet
import de.uplanet.lucy.server.workflow.WorkflowException
Objects in the Groovy Context
PageActionHandler and PageRenderingHandler
g_appGuid
g_handlerGuid
g_page
g_action
g_appUserProfile
Store data persistently for each user.
Snippet
g_appUserProfile
Class GroovyApplicationUserProfile
Starting with Intrexx version 12.0.0
Class GroovyApplicationUserProfile
g_binding
Access to all bindings that are available at the time of access.
Examples:
// Reading the content of a control via the current binding, e.g. in the ActionHandler of a page:
def strControlValue = g_binding.get("control['CONTROL_GUID']")
// Reading a processing context variable via the current binding:
def strSharedStateValue = g_binding.get("sharedState['NAME_VARIABLE']")
Snippet
g_binding
Starting with Intrexx version 12.0.0
g_context
The current processing context.
Snippet
g_context
Starting with Intrexx version 12.0.0
g_credentials
Starting with Intrexx version 12.0.0
Access to the credential store.
Example:
def strPassword = g_credentials.getSecret('credentialName')
The "credentialName" parameter is the name of the credential that was assigned in the credential store. g_credentials is available in all Groovy contexts.
Snippet
g_credentials
g_ctx
BPEE Processing Context - available only in the Web Service context.
Snippet
g_ctx
g_dataCollection
The page that serves as a portlet, or the DataCollection that is then loaded.
Example 1
Access to the table:
g_dataCollection.getDataRange("<GUID TABLERECORDS>").getNumberOfRecords() > 0
Example 2
Accessing a data record:
g_dataCollection.getValueHolder(String p_guid)
Snippet
g_dataCollection
Starting with Intrexx version 12.0.0
g_dbConnections
Access to available database connections.
Snippet
//System connection
def conn = g_dbConnections.systemConnection
//External data connection
def connForeign = g_dbConnections["CONNECTION_NAME"]
Class GroovyContextConnections
Starting with Intrexx version 12.0.0
Class GroovyContextConnections
g_dbQuery
An object for generating and executing database queries. Instead of "executeAndGetScalarValue," we recommend using the typed methods (e.g., executeAndGetScalarValueIntValue, executeAndGetScalarStringValue).
Snippet
//Build a prepared statement
def stmt = g_dbQuery.prepare(conn, "SELECT * FROM MYTABLE WHERE LID = ?")
stmt.setInt(1, iLid)
stmt.executeQuery()
stmt.close()
//Query of a single value
def iMax = g_dbQuery.executeAndGetScalarValue(conn, "SELECT MAX(LID) FROM MYTABLE", 0)
Starting with Intrexx version 12.0.0
g_defaultLanguage
This string contains the portal language that is selected as the default language in Portal Properties / Country Settings / Languages.
For example, `println(g_defaultLanguage)` can be used to output the corresponding language code to the process log file (e.g., "de" or "en").
Example:
assert g_defaultLanguage == 'en' : 'This script requires default language en.'
Snippet
g_defaultLanguage
g_defaultLocaleId
This string contains the location-specific format for the portal that is selected as the default in Portal Properties / Country Settings / Format.
For example, `println(g_defaultLocaleId)` can be used to output the corresponding language code to the process log file (e.g., "de" or "en").
Snippet
g_defaultLocaleId
g_dgFile
The Groovy handler can be used in Groovy workflow actions and in Groovy handlers in the Application API. It can be called using g_dgFile.
Copying Files
Examples:
g_dgFile.copy(guid: "DF GUID", id: "recordID", file: "/tmp/test.txt")g_dgFile.copy(guid: "DF GUID", id: "recordID", files: ["/tmp/test.txt", "tmp/test1.txt"])g_dgFile.copy(guid: "DF GUID", id: "recordID", file: [ file: "tmp/test.txt", name: "name.txt", contentType: "application/json", mode: "appendFirst"])g_dgFile.copy(guid: "DF GUID", id: "recordID", files: [ file: "tmp/test.txt", name: "name.txt", contentType: "application/json", mode: "appendFirst"], [ file: "tmp/test1.txt", name: "name1.txt", contentType: "application/json", mode: "append"])g_dgFile.copy(guid: "DF GUID", id: "recordID", file: "tmp/test.txt", name: "name2.txt", replaceName: "name.txt", contentType: "application/json", mode: "replace")g_dgFile.copy(guid: "DF GUID", id: "recordID", file: "tmp/test.txt", name: "name2.txt", pos: 1, contentType: "application/json", mode: "replace")g_dgFile.copy(guid: "DF GUID", id: "recordID", file: "tmp/test.txt", name: "name2.txt", fileId: 1, contentType: "application/json", mode: "replace")g_dgFile.copy(guid: "DF GUID", id: "recordID", files: [[file: "tmp/test.txt", name: "name2.txt", replaceName: "name.txt", contentType: "application/json", mode: "replace"], [file: "tmp/test1.txt", name: "name3.txt", contentType: "application/json", mode: "append"], [name: "file.txt", mode: "delete"])
Parameters:
guid: Data field GUID of the file field
id: Record ID (for composite primary keys, use the Intrexx serialization format (id=1, lang=de) or specify a separate value for each primary key)
id_%fieldname%: Value for the primary key field named
replaceMode: true/false (default: false) If set to "true," all existing files will be replaced
triggerWorkflow: true/false (default: false) If set to "true," the workflow is triggered whenever a change occurs
file: Can be of type "String," "File," "Path," "FileMap," or a FileInformation object
mode: append(default), appendFirst, replace, delete
file: The source file, type "String", "Path", "File", FileInformation (mode != delete)
For mode: append/appendFirst
name: The name of the file (must be unique; new feature in the API)
For the "replace" mode, specify either fileId, replaceName, or pos—see The following:
fileId: The file with the corresponding ID should be replaced
replaceName: The file with the corresponding name should be replaced
pos: The file at the corresponding position should be replaced (the first file has position 0)
If the "delete" mode is used with one of the following: fileId, name, or pos—see The following:
fileId: The file with the corresponding ID should be replaced
name: The file with the corresponding name should be replaced
pos: The file at the specified position should be replaced (the first file is at position 0)
files: Array of file, Strings (path to file), java.io.File, java.io.Path, FileInformation
Moving Files (Like Copying Files)
g_dgFile.move(guid: "DF GUID", id: "recordID", file: "/tmp/test.txt", deleteAlways: true)g_dgFile.move(guid: "DF GUID", id: "recordID", files: ["/tmp/test.txt", "tmp/test1.txt"])g_dgFile.move(guid: "DF GUID", id: "recordID", file: "tmp/test.txt", name: "name.txt", contentType: "application/json", mode: "appendFirst")g_dgFile.move(guid: "DF GUID", id: "recordID", files: [[file: "tmp/test.txt", name: "name.txt", contentType: "application/json", mode: "appendFirst"], [file: "tmp/test1.txt", name: "name1.txt", contentType: "application/json", mode: "append"], [ pos: 2, mode: "delete"]])g_dgFile.move(guid: "DF GUID", id: "recordID", file: "tmp/test.txt", name: "name2.txt", replaceName: "name.txt", contentType: "application/json", mode: "replace")g_dgFile.move(guid: "DF GUID", id: "recordID", files: [[file: "tmp/test.txt", name: "name2.txt", replaceName: "name.txt", contentType: "application/json", mode: "replace"], [file: "tmp/test2.txt", name: "name3.txt", contentType: "application/json", mode: "append"]])
Has an additional parameter "deleteAlways" (default: "false")
If `deleteAlways=true`, the source file is also deleted if an error occurs during the move operation.
"FileInformation" is not a valid source file for "move".
Deleting Files
g_dgFile.delete(guid: "DF GUID", id: "recordID")g_dgFile.delete(guid: "DF GUID", id: "recordID", fileId: 1)g_dgFile.delete(guid: "DF GUID", id: "recordID", name: "test.txt")g_dgFile.delete(guid: "DF GUID", id: "recordID", pos: 1)
Parameters:
guid: GUID data field of the file field
id: Record ID (For composite primary keys, use the Intrexx serialization format (id=1, lang=de) or specify a separate value for each primary key)
id_%fieldname%: Value for the primary key field named .
If fileId, name, or pos are not specified, all files will be deleted
fileId: The ID of the file to be deleted.
name: Name of the file to be deleted
pos: Position of the file to be deleted (0 = first file)
Get Files
g_dgFile.getFile(guid: "DF GUID", id: "recordID", fileId: 1) => Pathg_dgFile.getFile(guid: "DF GUID", id: "recordID", pos: 0) => Pathg_dgFile.getFile(guid: "DF GUID", id: "recordID", name: "test.txt") => Pathg_dgFile.getFileInformation(guid: "DF GUID", id: "recordID", name: "test.txt") => de.uplanet.lucy.server.businesslogic.util.FileInformationg_dgFile.getFiles(guid: "DF GUID", id: "recordID", count: 3) => List<Path> (maximum number 3)g_dgFile.getFilesInformation(guid: "DF GUID", id: "recordID", count: 3) => List<de.uplanet.lucy.server.businesslogic.util.FileDefinition>
Example of Copying Files Using Multiple PKs
def sourceFile = g_dgFile.getFile(guid:"D6A9628243660FDB691B70E02CD64E860F98A82F", id_STRID: strArticleId, id_STR_LANG: g_language, pos: 0)
if(sourceFile != null)
{
g_dgFile.copy(guid: "AC4DFDF9C27F23E721EAED68C276831962885FC3", id: strNewGuid, file: sourceFile, mode: "appendFirst")
}
Note on de.uplanet.lucy.server.businesslogic.util.FileDefinition and the "getFileInformation" and "getFilesInformation" methods
When copying, the FileInformation object can be used as the source file parameter. This allows you to copy files from another dataset.
Example:
def src = g_dgFile.getFileInformation(guid: "GUID1", id: "1", pos: 0)g_dgFile.copy(guid: "GUID1", id: 2, file: src, mode: "appendFirst") // Copies first file of record with id 1 to first position of record with id 2.def src = g_dgFile.getFilesInformation(guid: "GUID1", id: "1")g_dgFile.copy(guid: "GUID1", id: 2, replaceMode: true, files: src) // Copies all files from record with id 1 and replaces the files from record with id 2.
Starting with Intrexx version 12.0.0
g_dirWorkflow
Available only in processes —returns the directory of the current process. Access to this directory should be read-only.
Snippet
g_dirWorkflow
g_dirWorkflowTmp
Access to the process's temporary working directory on the server. The directory is available to all subsequent process elements until the process ends.
Snippet
g_dirWorkflowTmp
g_event
Available only in processes —includes the event that triggered the current process. Please note that comparisons should be based on the current event (see (Script example) should always be applied to the interfaces and never to the concrete classes.
Snippet
import de.uplanet.lucy.server.workflow.event.*
if (g_event instanceof IGlobalTimerWorkflowEvent)
//Insert script that responds to a timerevent here.
Starting with Intrexx version 12.0.0
g_exception
Contains the exception that was caught. This must be examined, and then a decision must be made as to whether the ErrorHandler will take responsibility for it. Common criteria for this include:
-
The exception was triggered by an exception of a specific type.
-
The exception was triggered by an exception of a specific type, and the error message has specific content (e.g., it begins with "my-custom-prefix:").
See also readme.txt and handler_50_xxx.groovy.example in the portal directory internal/system/vm/html/errorhandler/custom.
Snippet
g_exception
Starting with Intrexx version 12.0.0
g_fileScript
Path to the current script as a java.io.File. This object is not available in the web service environment.
Example
println("Executing " + g_fileScript.path)
Snippet
g_fileScript
g_guidSelf
Contains the GUID of the current process object (action, condition, or event handler). This variable is defined only in processes.
Snippet
g_guidSelf
g_guidWf
Contains the GUID of the current process. This variable is defined only in processes.
Snippet
g_guidWf
g_i18n
Access to language constants.
Snippet
g_i18n
Starting with Intrexx version 12.0.0
g_json
The `g_json` object implements a few simple use cases related to JSON:
-
Parsing JSON Text
-
Serializing Objects as JSON Text
-
Creating JSON Objects
-
Sending GET requests and parsing the response as JSON
Example of JSON Parsing
def strJson = '''{"person": {
"givenName": "Donald",
"lastName": "Duck",
"age": 87,
"nephews": ["Huey", "Dewey", "Louie"]
}}'''
def parsed = g_json.parse(strJson)
println(parsed.person.lastName)
println(parsed.person.givenName)
Snippet
g_json
Starting with Intrexx version 12.0.0
g_language
This string contains the current user's language, which is set in their account in User Management under "Organization."
For example, `println(g_language)` can be used to output the corresponding language code to the process log file (e.g., "de" or "en").
Snippet
g_language
g_localeId
This string contains the current user's format, which is specified in their account in User Management under "Organization."
For example, `println(g_localeId)` can be used to output the corresponding locale code to the process log file (e.g., "de" or "en").
Snippet
g_localeId
g_log
Writes an entry to the log file associated with the script's execution context.
Snippet
g_log.info("Process finished without errors.")
g_log.error("An error has occurred.")
g_om
Object for accessing user management.
Snippet
g_om
Intrexx offers a wide range of advanced options for process-driven user management. Access objects and methods in Groovy actions can be used, among other things, to create and manage new users. The globally available and already initialized object "g_om" serves as the starting point for the organizational structure of a portal in terms of processes. This allows for the implementation of basic use cases, such as searching for a user or generating a new password. These methods should be used just like "normal" method calls. Here you'll find all the available methods in our JavaDocs:
Class GroovyOrgStructureWrapper
Starting with Intrexx version 12.0.0
Starting with Intrexx version 12.0.0
Class GroovyOrgStructureWrapper
Examples
//Change password of the passed user
g_om.changePassword(g_session.user, "SECRET")//Generate and send a new password to the passed user
g_om.generateAndSendPassword(g_session.user)//Search a user by means of a GUID
def user = g_om.getUser("C10579449052F85D9C3FF3C2824348FCE020A22E")//Classify a list of GUIDs
//A list of GUIDs or a text can be passed, e.g. the content of a data field of a multiple selection element
def guids = ["AE39A904172F5867DA23DE289D1D6B7967420DC0", "6AA80844C3C99EF93BF4536EB18605BF86FDD3C5", g_session.user.guid]
def classified = g_om.classifyGuids(guids) //guids = Collection or String
//Results in a map with categorized GUIDs, e.g. {containers=[], users=[7312F993D0DA4CECCA9AE5A9D865BE142DE413EA],
// unclassified=[AE39A904172F5867DA23DE289D1D6B7967420DC0],
// sets=[6AA80844C3C99EF93BF4536EB18605BF86FDD3C5]}
println(classified)
//filter on object types
println(classified.users)
println(classified.containers)
println(classified.sets)
println(classified.unclassified)
//number of non anonymous sessions
g_om.getNonAnonymousActiveSessionCount()
In addition, the "g_om" object has several methods that are called in conjunction with a closure to perform further actions. These methods can be identified by the parameter of type "groovy.lang.Closure" specified in the JavaDocs, e.g., "GroovyOrgBuilder.createUser"(groovy.lang.Closure p_closure). Within such a closure, you can call methods of the class documented in the respective links provided. The following methods can be called using a closure:
g_om.createUser(groovy.lang.Closure p_closure)
This allows you to create a new Intrexx user. Within the Closure, the properties listed below can be set; the "name" and "loginName" properties are required, while the rest are optional.
|
Property |
Data Type |
|---|---|
|
birthday |
Date |
|
city |
String |
|
container |
Object |
|
country |
String |
|
defaultLanguage |
String |
|
defaultLayout |
String |
|
deletable |
boolean |
|
deleted |
boolean |
|
description |
String |
|
disabled |
boolean |
|
dn |
String |
|
emailBiz |
String |
|
emailHome |
String |
|
employeeNo |
String |
|
enterDate |
Date |
|
externalLogin1 |
String |
|
externalLogin2 |
String |
|
externalLogin3 |
String |
|
externalPassword1 |
String |
|
externalPassword2 |
String |
|
externalPassword3 |
String |
|
externalPrimaryGroupId |
int |
|
female |
boolean |
|
firstName |
String |
|
fullName |
String |
|
gender |
int |
|
guid |
String |
|
id |
int |
|
internalUsn |
int |
|
lastName |
String |
|
loginDomain |
String |
|
loginDomainLwr |
String |
|
loginName |
String |
|
loginNameLwr |
String |
|
male |
boolean |
|
memberOf |
Collection<?> |
|
middleName |
String |
|
name |
String |
|
password |
String |
|
passwordChangedDate |
Date |
|
passwordExpires |
boolean |
|
passwordHash |
String |
|
phoneBiz |
String |
|
phoneFax |
String |
|
phoneHome |
String |
|
phoneMobileBiz |
String |
|
phoneMobileHome |
String |
|
phonePager |
String |
|
poBox |
String |
|
postalCode |
String |
|
priority |
int |
|
rplGuid |
String |
|
salt |
String |
|
showUser |
boolean |
|
state |
String |
|
street |
String |
|
timeZone |
Time Zone |
|
title |
String |
|
userImageContentType |
String |
|
userImageFile |
File |
|
userImageMetaInfo |
String |
For the "container" and "memberOf" properties, you can specify either the GUIDs, the unique names of the containers, roles, sets, or groups, or paths within the organizational structure.
Example
g_om.createUser
{
name = "g_om"
loginName = "g_om"
birthday = now()
container = "0F8233A39555B28F6B32CFFE666A5151E1F41AD3"
memberOf = ["8FBF199EE826D16742F0F131E0AB4CF0E6BA6CA3", "Benutzer"]
emailBiz = "g_om@example.org"
guid = newGuid()
male = true
}g_om.getLoggedOnUsers(boolean p_bIncludeAnonymous, groovy.lang.Closure p_closure)
Displays all currently logged-in users. The "p_bIncludeAnonymous" parameter can be used to specify whether anonymous sessions should be included in the results. Additional filtering can be performed using the Groovy closure.
Example
def userOnline = g_om.getLoggedOnUsers(false) {
it.containerGuid == "9DABA9EE4F9F6F771704F75C79A1C3A124FF399C"
}g_om.getLoggedOnUsersDistinct(groovy.lang.Closure p_closure)
Returns all currently logged-in, non-anonymous users, excluding duplicates. Additional filtering can be performed using the Groovy closure in the same way as with `g_om.getLoggedOnUsers(boolean p_bIncludeAnonymous, groovy.lang.Closure p_closure)`.
g_om.withOrgStructure(groovy.lang.Closure p_closure)
Allows you to work on a portal's organizational structure.
Example
g_om.withOrgStructure {
println("9DABA9EE4F9F6F771704F75C79A1C3A124FF399C".isUser())
}
The following methods can be called within the OrgStructure closure:
-
isUser()
-
isSet()
-
isGroup()
-
isDistList()
-
isContainer()
-
isOrganization()
-
isOrgUnit()
g_om.getMembers(java.lang.Object,boolean)
Generates a list of the GUIDs of all users who belong to one or more specific groups.
Example
def userGuids = g_om.getMembers(["00A303288634E154D755732E478F2BE0D9AD36F7"], false)*.guid
"00A303288634E154D755732E478F2BE0D9AD36F7" is the group's GUID copied from the "Users" module. Multiple group GUIDs or set GUIDs are possible.
Determining the Default User for Processes
Call to determine the default user for processes as set in the portal properties.
Snippet
g_om.getStandardWorkflowUserGuid('system')
g_parameter
Object for accessing parameters.
Example
def customerid = g_parameter.get("customerid")
Snippet
g_parameter
Starting with Intrexx version 12.0.0
Page Properties - "Parameters" Tab
g_parameterReferences
Starting with Intrexx version 12.0.0
Access to the parameter store.
Example:
def strParam = g_parameterReferences.getParameter('myStringParam')
def intParam = g_parameterReferences.getParameter('myIntegerParam') as int
def boolParam = g_parameterReferences.getParameter('myBooleanParam') as boolean
The parameters myStringParam, myIntegerParam, and myBooleanParam are the names assigned to the respective parameters in the parameter store.
You can also use "as int" or "as boolean" to specify the return type of the call.
Snippet
g_parameterReferences
g_permissions
This class is used to check and query permissions. Its usage is demonstrated in the "JSON Response" template for the use case described there. checkPermission(Permission) and check(Closure) verify whether the desired permissions are granted. Otherwise, a java.security.AccessControlException is thrown. hasPermission(Permission) and has(Closure) work in the same way, but return a Boolean value indicating whether the requested permissions are granted or not. The closure methods delegate to the aforementioned GroovyIxAccessControllerDelegate object and require a map that maps object names to actions. Example: Check access permissions for the application <application GUID>, read permissions for the data group <data group GUID>, and write permissions for the data group <another data group GUID>.
Example
g_permissions.check {
application("<application GUID>": "access")
dataGroup("<data group GUID>": "read", "<another data group GUID>": "write,create")
}
Snippet
g_permissions
Class GroovyIxAccessController
Class GroovyIxAccessController.GroovyIxAccessControllerDelegate
Classes from de.uplanet.lucy.security.permission
Starting with Intrexx version 12.0.0
Class GroovyIxAccessController
Starting with Intrexx version 12.0.0
Class GroovyIxAccessController.GroovyIxAccessControllerDelegate
Starting with Intrexx version 12.0.0
Classes from de.uplanet.lucy.security.permission
g_portal
Object used to access portal properties such as name or base URL.
Example
def strUrl = g_portal.baseUrl
Snippet
g_portal
Starting with Intrexx version 12.0.0
g_portlet
Access to the specific portlet to be filtered (in the portlet pool or when the portlet is rendered).
Snippet
g_portlet
Starting with Intrexx version 12.0.0
g_portletPool
Access to the portlet pool to be filtered (collection of portlets)—both to ensure it is actually in the portlet pool and during the rendering of the portlets.
Snippet
g_portletPool
Starting with Intrexx version 12.0.0
g_record
Access to the current data set.
Example
def iLid = g_record["0D8F13B2B43B128DB23C0C1CC8C5DC1143C9D826"].value // datafield (PK) (S) ID
Snippet
g_record
Starting with Intrexx version 12.0.0
g_rwRecord
Read and write access to the current data record. Available only within Groovy PageActionHandlers.
Example
def iLid = g_rwRecord["0D8F13B2B43B128DB23C0C1CC8C5DC1143C9D826"].value // datafield (PK) (S) ID
Snippet
g_rwRecord
Starting with Intrexx version 12.0.0
g_request
Access to the current request, e.g., reading request variables during the process. This variable is defined only if the script was called by a web request.
Snippet
g_request
Class GroovyServerBridgeRequest
Starting with Intrexx version 12.0.0
Class GroovyServerBridgeRequest
g_rtCache
RtCache - Access to data groups, applications, fields, etc.
Example
//Find all data groups of the application with the GUID 68C97BF4D89E8466BDE08AF03A4EF95F5B23AF72
def datagroups = g_rtCache.dataGroups.findAll {it.appGuid == "68C97BF4D89E8466BDE08AF03A4EF95F5B23AF72"}
Snippet
g_rtCache
Starting with Intrexx version 12.0.0
g_session
The current session.
Example
//Name of the currently logged-in user
def strUserName = g_session?.user?.name
Snippet
g_session
Starting with Intrexx version 12.0.0
g_sharedState
Shared state, where variables and values can be written to and read from.
Example
//write variable to shared state
g_sharedState.meineVariable = "my value"
//read variable from shared state
def strValue = g_sharedState.myVariable
Snippet
g_sharedState
g_sourcePage
Returns, for example, the GUID, application GUID, or RecID of the page that is sending the parameters.
Example
def strMyPage = g_sourcePage.getPageGuid()
g_log.info(strMyPage)
Snippet
g_sourcePage
Starting with Intrexx version 12.0.0
g_springApplicationContext
Spring Application Context
Snippet
g_springApplicationContext
g_store
The following script demonstrates how to use `g_store.ephemeral` to set a system-wide, ephemeral name-value pair and retrieve it elsewhere.
Snippet
//------------------------------ supplier side ------------------------------
// initially no value exists for myUniqueKey
assert g_store.ephemeral.contains('myUniqueKey') == false
// insert an ephemeral value (does not survive portal service restart)
g_store.ephemeral.put('myUniqueKey', 'foo')
// now the value exists
assert g_store.ephemeral.contains('myUniqueKey') == true
//------------------------------ consumer side side ------------------------------
assert g_store.ephemeral.contains('myUniqueKey') == true
// get the ephemeral value
def val = g_store.ephemeral.remove('myUniqueKey')
assert val == 'foo'
// no the value does not exist anymore
assert g_store.ephemeral.contains('myUniqueKey') == false
Starting with Intrexx version 12.0.0
g_sysDg
This object can be used to read values from a system data group.
Example
//Specify the Guid of the system data field as GUID
def strValue = g_sysDg['C1BFDD165EBFD0713D306D3E2B124E80021E613F']
def strValueByFieldGuid = g_sysDg.getValueByFieldGuid('C1BFDD165EBFD0713D306D3E2B124E80021E613F')
def vhByFieldGuid = g_sysDg.getValueHolderByFieldGuid('C1BFDD165EBFD0713D306D3E2B124E80021E613F')
Snippet
g_sysDg
Starting with Intrexx version 12.0.0
g_syslog
Logging object for writing to the portal logog file (portal.log).
Snippet
g_syslog.info("my message in portal.log.")
g_ws
Object used to explicitly call a web service. Available only for scripts stored with a web service.
Snippet
g_ws.invoke()
Closures
The predefined closures can be called just like functions.
checkInterrupted()
Checks whether either
-
the thread executing the process has received an interrupt request from another thread, or
-
the timeout set for the process has been exceeded.
Use this call in scripts that are intended to behave cooperatively in such cases.
Snippet
checkInterrupted()
Starting with Intrexx version 12.0.0
createTemporaryDirectory()
Creates a temporary working directory that remains available until the process finishes running.
Snippet
createTemporaryDirectory()
Class CreateTemporaryDirectoryClosure
Starting with Intrexx version 12.0.0
Class CreateTemporaryDirectoryClosure
currentTimestamp()
This closure returns the timestamp of the current transaction. This value remains unchanged until the end of this transaction.
Example
def dtNow = currentTimestamp()
Snippet
currentTimestamp()
Starting with Intrexx version 12.0.0
getStackTraceString()
Returns the complete stack trace of an error that occurred as a string. The "getStackTraceString()" closure requires a parameter of type java.lang.Throwable, i.e., an exception.
Snippet
try
{
trySomething()
}
catch (e)
{
def strStackTrace = getStackTraceString(e)
doSomethingWithStackTrace(strStackTrace)
}
Class CreateStackTraceStringClosure
Starting with Intrexx version 12.0.0
Class CreateStackTraceStringClosure
newGuid()
Generates a new GUID.
Snippet
newGuid()
Starting with Intrexx version 12.0.0
now()
Creates a new date (Now) as a timestamp or as a ValueHolder.
Snippet
now()
Starting with Intrexx version 12.0.0
parseGuids(strText)
Parses GUIDs from the provided string (e.g., a pipe-separated list) and returns a TreeSet containing the GUIDs found.
Snippet
def strText = "18CC231E0A71F6F27091855C4C0FD0D6F2F26038||D0CACC8058DC36A9A499AB2DD3B993F427AB9200"
def guids = parseGuids(strText)
guids.each {println it}
Starting with Intrexx version 12.0.0
vh()
Creates a new ValueHolder from the passed-in object.
Snippet
def vhTest = vh("Hello world!")
def vhInt = vh(1000)
Class CreateValueHolderClosure
Starting with Intrexx version 12.0.0
Class CreateValueHolderClosure
Databases
Data Groups
Find a Data Group by GUID
Here is an example that shows how to determine the name of a data group:
def strName = g_rtCache.dataGroups["C399FB1F398D76E91BC7DC679E1E4DDB9F5CEB9C"].name
Snippet
def strName = g_rtCache.dataGroups["<data group GUID"].name
Starting with Intrexx version 12.0.0
Referencing a Data Group in SQL Using a GUID
Using this client function, a data group can be referenced by its GUID rather than by its name. This means that the name of the data group does not have to be hard-coded in SQL statements, which helps avoid problems during import or when changes are made to the data group. Available only through the Intrexx database API.
Example
g_dbQuery.executeAndGetScalarValue(conn, "SELECT COUNT(LID) FROM DATAGROUP('DAF7CECF66481FCABE50E529828116EAFE906962')")
Instead of "executeAndGetScalarValue," we recommend using the typed methods (e.g., executeAndGetScalarValueIntValue, executeAndGetScalarStringValue).
Snippet
def strName = g_rtCache.dataGroups["<data group GUID>"].name
Starting with Intrexx version 12.0.0
Column names in a data group
Returns a list of the names of all columns in the data group with the specified GUID.
Snippet
def fieldNames = g_rtCache.fields.findAll{it.dataGroupGuid == "DG-GUID"}*.columnName
Starting with Intrexx version 12.0.0
Intrexx Database API
Please use prepared statements correctly. Under //BAD, you'll find an example of incorrect usage, and under //BETTER, an example of correct usage:
// BAD
inputs.each {
try
{
stmt = conn.prepareStatement("INSERT INTO FOO (STRNAME, INTAGE) VALUES (?, ?)")
stmt.setString(1, it.name)
stmt.setInt(2, it.age)
stmt.executeUpdate()
}
finally
{
Safely.close(stmt)
}
}
// BETTER
try
{
stmt = conn.prepareStatement("INSERT INTO FOO (STRNAME, INTAGE) VALUES (?, ?)")
inputs.each {
stmt.setString(1, it.name)
stmt.setInt(2, it.age)
stmt.executeUpdate()
}
}
finally
{
Safely.close(stmt)
}
Prepared Statement with SELECT
Executes a prepared statement containing a SELECT statement. You can then iterate through the results in the result set.
Example
stmt = g_dbQuery.prepare(conn, "SELECT * FROM DATAGROUP('7AFAF7CB5DE281D35F05D96FCD96CE27692C110F') WHERE ID = ?")
stmt.setInt(1, 1)
stmt.executeQuery()
stmt = Safely.close(stmt)
Snippet
import de.uplanet.scripting.groovy.util.Safely
def conn = g_dbConnections.systemConnection
def stmt = null
def rs = null
try
{
stmt = g_dbQuery.prepare(conn, "SELECT <COLUMNS> FROM DATAGROUP('<DATAGROUP_GUID>') WHERE <CONDITION>")
//stmt.setInt(1, 1)
rs = stmt.executeQuery()
while (rs.next())
{
// do something
// rs.getIntValue(1)
// rs.getStringValue(2)
// rs.getBooleanValue(3)
// rs.getTimestampValue(4)
}
rs = Safely.close(rs)
stmt = Safely.close(stmt)
}
finally
{
rs = Safely.close(rs)
stmt = Safely.close(stmt)
}
Starting with Intrexx version 12.0.0
Prepared Statement with INSERT
Executes a prepared statement containing an INSERT statement.
Example
stmt = g_dbQuery.prepare(conn, "INSERT INTO DATAGROUP('7AFAF7CB5DE281D35F05D96FCD96CE27692C110F') (ID, STRTEXT, DTDATE, BBOOLEAN) VALUES (?,?,?,?)")
stmt.setInt(1, 1)
stmt.setString(2, "Example text")
stmt.setTimestamp(3, now().withoutFractionalSeconds)
stmt.setBoolean(4, true)
Snippet
import de.uplanet.scripting.groovy.util.Safely
def conn = g_dbConnections.systemConnection
def stmt = null
try
{
stmt = g_dbQuery.prepare(conn, "INSERT INTO DATAGROUP('<DATAGROUP_GUID>') (<COLUMNS>) VALUES ()")
//stmt.setInt(1, 1)
//stmt.setString(2, "Example text")
//stmt.setTimestamp(3, now().withoutFractionalSeconds)
//stmt.setBoolean(4, true)
stmt.executeUpdate()
stmt = Safely.close(stmt)
}
finally
{
stmt = Safely.close(stmt)
}
Starting with Intrexx version 12.0.0
Prepared Statement with INSERT (using a Closure)
Executes a prepared statement containing an INSERT statement using a closure.
Example
def conn = g_dbConnections.systemConnection
g_dbQuery.executeUpdate(conn, "INSERT INTO DATAGROUP('7AFAF7CB5DE281D35F05D96FCD96CE27692C110F') (LID, STRTEXT, DATE) VALUES (?,?,?)") {
setInt(1, 1)
setString(2, "Example text")
setTimestamp(3, now().withoutFractionalSeconds)
}
Please note: If the statement is to be reused—for example, within a loop—the variant implemented as a prepared statement without a closure is more efficient.
Snippet
def conn = g_dbConnections.systemConnection
g_dbQuery.executeUpdate(conn, "INSERT INTO DATAGROUP('<DATAGROUP_GUID>') (<COLUMNS>) VALUES ()") {
//setString(1, "Example text")
//setTimestamp(2, now().withoutFractionalSeconds)
//setBoolean(3, true)
}
Starting with Intrexx version 12.0.0
Prepared Statement with UPDATE
Executes a prepared statement containing an UPDATE statement.
Example
try
{
stmt = g_dbQuery.prepare(conn, "UPDATE DATAGROUP('7AFAF7CB5DE281D35F05D96FCD96CE27692C110F') SET STRTEXT = ?, DTDATE = ?, BBOOLEAN = ? WHERE ID = ?")
stmt.setString(1, "Example text")
stmt.setTimestamp(2, now().withoutFractionalSeconds)
stmt.setBoolean(3, true)
stmt.setInt(4, 1)
stmt.executeUpdate()
stmt = Safely.close(stmt)
}
finally
{
stmt = Safely.close(stmt)
}
Snippet
import de.uplanet.scripting.groovy.util.Safely
def conn = g_dbConnections.systemConnection
def stmt = null
try
{
stmt = g_dbQuery.prepare(conn, "UPDATE DATAGROUP('<DATAGROUP_GUID>') SET <COLUMNS> = ? WHERE <CONDITION>")
//stmt.setInt(1, 1)
//stmt.setString(2, "Example text")
//stmt.setTimestamp(3, now().withoutFractionalSeconds)
//stmt.setBoolean(4, true)
stmt.executeUpdate()
stmt = Safely.close(stmt)
}
finally
{
stmt = Safely.close(stmt)
}
Starting with Intrexx version 12.0.0
Prepared Statement with UPDATE (using a Closure)
Executes a prepared statement containing an UPDATE statement using a closure.
Example
def conn = g_dbConnections.systemConnection
g_dbQuery.executeUpdate(conn, "UPDATE DATAGROUP('7AFAF7CB5DE281D35F05D96FCD96CE27692C110F') SET STRTEXT = ? WHERE DATE < ?") {
setString(1, "Example text")
setTimestamp(2, now().withoutFractionalSeconds)
}
Please note: If the statement is to be reused—for example, within a loop—the variant as a prepared statement without a closure is more efficient.
Snippet
def conn = g_dbConnections.systemConnection
g_dbQuery.executeUpdate(conn, "UPDATE DATAGROUP('<DATAGROUP_GUID>') SET <COLUMNS> = ? WHERE <CONDITION>") {
//setString(1, "Example text")
//setTimestamp(2, now().withoutFractionalSeconds)
//setBoolean(3, true)
}
Starting with Intrexx version 12.0.0
Prepared Statement with DELETE
Executes a prepared statement containing a DELETE statement.
Example
def conn = g_dbConnections.systemConnection
def stmt = null
try
{
stmt = g_dbQuery.prepare(conn, "DELETE FROM DATAGROUP('7AFAF7CB5DE281D35F05D96FCD96CE27692C110F') WHERE ID > ?")
stmt.setInt(1, 5)
stmt.executeUpdate()
stmt = Safely.close(stmt)
}
finally
{
stmt = Safely.close(stmt)
}
Snippet
import de.uplanet.scripting.groovy.util.Safely
def conn = g_dbConnections.systemConnection
def stmt = null
try
{
stmt = g_dbQuery.prepare(conn, "DELETE FROM DATAGROUP('<DATAGROUP_GUID>') WHERE <CONDITION>")
//stmt.setInt(1, 1)
//stmt.setString(2, "Example text")
//stmt.setTimestamp(3, now().withoutFractionalSeconds)
//stmt.setBoolean(4, true)
stmt.executeUpdate()
stmt = Safely.close(stmt)
}
finally
{
stmt = Safely.close(stmt)
}
Starting with Intrexx version 12.0.0
Prepared Statement with DELETE (using Closure)
Executes a prepared statement containing a DELETE statement using Closure.
Example
def conn = g_dbConnections.systemConnection
g_dbQuery.executeUpdate(conn, "DELETE FROM DATAGROUP('7AFAF7CB5DE281D35F05D96FCD96CE27692C110F') WHERE ID > ?"){
setInt(1, 5)
}
Please note: If the statement is to be reused—for example, within a loop—the variant as a prepared statement without a closure is more efficient.
Snippet
def conn = g_dbConnections.systemConnection
g_dbQuery.executeUpdate(conn, "DELETE FROM DATAGROUP('<DATAGROUP_GUID>') WHERE <CONDITION>"){
//setInt(1, 1)
//setString(2, "Example text")
//setTimestamp(3, now().withoutFractionalSeconds)
//setBoolean(4, true)
Starting with Intrexx version 12.0.0
A single value from a database query
Reads a single value from a database query. If the result set is empty or zero, the value defined by `fallbackValue` is returned. If you want to specify the return data type more precisely, you can use typed method calls such as `executeAndGetScalarBooleanValue(...)`.
Example
def value = g_dbQuery.executeAndGetScalarValue(conn, "SELECT MAX(ID) FROM DATAGROUP('7AFAF7CB5DE281D35F05D96FCD96CE27692C110F')", 0)
or using a pre-written statement
def value = g_dbQuery.executeAndGetScalarValue(conn, "SELECT MAX(ID) FROM DATAGROUP('7AFAF7CB5DE281D35F05D96FCD96CE27692C110F') WHERE DTEDIT < ?", 0) {
setTimestamp(1, now().withoutFractionalSeconds)
Instead of "executeAndGetScalarValue," we recommend using the typed methods (e.g., executeAndGetScalarValueIntValue, executeAndGetScalarStringValue).
Snippet
def conn = g_dbConnections.systemConnection
def value = g_dbQuery.executeAndGetScalarValue(conn, "SELECT <COLUMNS> FROM DATAGROUP('<DATAGROUP_GUID>') WHERE <CONDITION>", <FALLBACK VALUE>) {
//setString(1, "Example text.")
}
Starting with Intrexx version 12.0.0
A single value from a prepared database query
Reads a single value from a database query. If the result set is empty or zero, the value defined by `fallbackValue` is returned. If you want to specify the return data type more precisely, you can use typed method calls such as `executeAndGetScalarBooleanValue(...)`.
Example
def stmt = g_dbQuery.prepare(conn, "SELECT MAX(LID) FROM DATAGROUP('7AFAF7CB5DE281D35F05D96FCD96CE27692C110F')")
def value = stmt.executeAndGetScalarValue(0)
stmt = Safely.close(stmt)
Instead of "executeAndGetScalarValue," we recommend using the typed methods (e.g., executeAndGetScalarValueIntValue, executeAndGetScalarStringValue).
Snippet
import de.uplanet.scripting.groovy.util.Safely
def conn = g_dbConnections.systemConnection
def stmt = null
def value
try
{
stmt = g_dbQuery.prepare(conn, "SELECT <COLUMN> FROM DATAGROUP('<DATAGROUP_GUID>') WHERE <CONDITION>")
//stmt.setInt(1, 1)
//stmt.setString(2 , "Example text")
//stmt.setTimestamp(3, now().withoutFractionalSeconds)
//stmt.setBoolean(4, false)
value = stmt.executeAndGetScalarValue(<FALLBACK_VALUE>)
stmt = Safely.close(stmt)
}
finally
{
stmt = Safely.close(stmt)
}
Starting with Intrexx version 12.0.0
Starting with Intrexx version 12.2.0
Preparing and Executing PreparedStatements with Automatic Resource Management
def conn = g_dbConnections.systemConnection
def strQuery = "SELECT STRGUID, STRLOGIN FROM DSUSER, DSOBJECT WHERE DSOBJECT.LID = DSUSER.LID"
def map = g_dbQuery.prepareWithStatement(conn, strQuery) { stmt ->
stmt.executeQueryWithResultSet { rs ->
rs.collectEntries([:]) {
[it.getStringValue(1), it.getStringValue(2)]
}
}
}
assert map == [
'7312F993D0DA4CECCA9AE5A9D865BE142DE413EA':'Administrator',
'05CE8CE3035924F7D3088895F1D87DADD65CFAE4':'Anonymous'
]
JDBC
Prepared Statement with SELECT
Executes a prepared statement containing a SELECT statement. You can then iterate over the results.
Snippet
import de.uplanet.scripting.groovy.util.Safely
def conn = g_dbConnections.systemConnection
def stmt = null
def rs = null
try
{
stmt = conn.prepareStatement("SELECT <COLUMNS> FROM <DATAGROUP_NAME> WHERE <CONDITION>")
//stmt.setInt(1, 42)
//stmt.setString(2, "Example text")
//stmt.setTimestamp(3, now().withoutFractionalSeconds)
//stmt.setBoolean(4, false)
rs = stmt.executeQuery()
while (rs.next())
{
// do something
// rs.getInt(1)
// rs.getString(2)
// rs.getTimestamp(3)
}
}
finally
{
rs = Safely.close(rs)
stmt = Safely.close(stmt)
}
Prepared Statement with INSERT
Executes a prepared statement containing an INSERT statement.
Snippet
import de.uplanet.scripting.groovy.util.Safely
def conn = g_dbConnections.systemConnection
def stmt = null
try
{
stmt = conn.prepareStatement("INSERT INTO <DATAGROUP_NAME> (<COLUMNS>) VALUES ()")
// stmt.setInt(1, 1234)
// stmt.setString(2, "Example text")
// stmt.setBoolean(3, true)
// stmt.setTimestamp(4, now().withoutFractionalSeconds)
stmt.executeUpdate()
}
finally
{
stmt = Safely.close(stmt)
}
Prepared Statement with UPDATE
Executes a prepared statement containing an UPDATE statement.
Snippet
import de.uplanet.scripting.groovy.util.Safely
def conn = g_dbConnections.systemConnection
def stmt = null
try
{
stmt = conn.prepareStatement("UPDATE <DATAGROUP_NAME> SET <COLUMNS> = ? WHERE <CONDITION>")
// stmt.setInt(1, 1234)
// stmt.setString(2, "Example text")
// stmt.setBoolean(3, true)
// stmt.setTimestamp(4, now().withoutFractionalSeconds)
stmt.executeUpdate()
}
finally
{
stmt = Safely.close(stmt)
}
Prepared Statement with DELETE
Executes a prepared statement containing a DELETE statement.
Snippet
import de.uplanet.scripting.groovy.util.Safely
def conn = g_dbConnections.systemConnection
def stmt = null
try
{
stmt = conn.prepareStatement("DELETE FROM <DATAGROUP_NAME> WHERE <CONDITION>")
// stmt.setInt(1, 1234)
// stmt.setString(2, "Example text")
// stmt.setBoolean(3, true)
// stmt.setTimestamp(4, now().withoutFractionalSeconds)
stmt.executeUpdate()
}
finally
{
stmt = Safely.close(stmt)
}
System Data Source
System Database Connection
Example
def conn = g_dbConnections.systemConnection
Snippet
g_dbConnections.systemConnection
Class GroovyContextConnections
Starting with Intrexx version 12.0.0
Class GroovyContextConnections
External Data Source
Connection to an external data source. Enter the name assigned to the external data connection in the Integration module.
Example
def conn = g_dbConnections["ForeignData"]
Snippet
g_dbConnections["<CONNECTION_NAME>"]
Class GroovyContextConnections
Starting with Intrexx version 12.0.0
Class GroovyContextConnections
Distinguish Between Database Types
Determines the database type.
Snippet
def conn = g_dbConnections.systemConnection
switch (conn.descriptor.databaseType)
{
case "Db2":
// DB2
break
case "Derby":
// Derby/Java DB
break
case "Firebird":
// Firebird
break
case "HSQLDB":
// HSQLDB
break
case "Ingres":
// Ingres
break
case "Oracle8":
// Oracle 8
break
case "Oracle9":
// Oracle 9
break
case "Oracle10":
// Oracle 10
break
case "PostgreSQL":
// PostgreSQL
break
case "MaxDB":
// MaxDB
break
case "MsSqlServer":
// Microsoft SQL Server
break
case "Standard":
// unspecified
break
default:
assert false : "Unexpected database type."
break
}
Class GroovyContextConnections
Starting with Intrexx version 12.0.0
Class GroovyContextConnections
Web Services
Execute a Web Service Call
Calls the underlying web service. Applies only to scripts defined within a web service.
Snippet
g_ws.invoke()
Read Web Service Input Values
Reading values that are passed to a web service as input parameters. The variable name should be the name of the control that contains the value.
Example
g_ctx.requestVars.textcontrolD72A9620
Snippet
g_ctx.requestVars.
Reading Web Service Return Values
Reading values that are passed to a web service as return parameters. The variable name should be the name of the control into which the return value is written.
Example
g_ctx.bpeeVars.textvcontrol72EF4A0B.value
Snippet
g_ctx.bpeeVars..value
Case Distinction
switch Statement for Groovy Conditions
Suitable for use in processes. The return values correspond to the outgoing connections (connection IDs) in the Groovy condition.
Snippet
switch (g_record[""].value)
{
case "expected value 1":
return connectionId1
case "expected value 2":
return connectionId2
default:
return connectionId3
}
switch Statement for Data Group Events
Suitable for use in processes.
Snippet
import de.uplanet.lucy.server.workflow.event.IAfterCreateDataGroupWorkflowEvent
import de.uplanet.lucy.server.workflow.event.IAfterUpdateDataGroupWorkflowEvent
import de.uplanet.lucy.server.workflow.event.IBeforeDeleteDataGroupWorkflowEvent
import de.uplanet.lucy.server.workflow.event.INotifyDataGroupWorkflowEvent
switch (g_event)
{
case IAfterCreateDataGroupWorkflowEvent:
g_log.info("A new record was inserted.")
break
case IAfterUpdateDataGroupWorkflowEvent:
g_log.info("A record was updated.")
break
case IBeforeDeleteDataGroupWorkflowEvent:
g_log.info("A record will be deleted.")
break
case INotifyDataGroupWorkflowEvent:
g_log.info("A timer resubmitted a record.")
break
default:
g_log.warn("Unhandled event ${g_event}.")
break
}
Starting with Intrexx version 12.0.0
Data Records for Global Data Group Timers
Distinguishing between the first and subsequent data records in global data group timers.
Snippet
if (g_sharedState["wasHere${g_guidSelf}"])
{
// we were here before
}
else
{
// we are here for the first time
g_sharedState["wasHere${g_guidSelf}"] = true
}
Mathematical Calculations
Commercial Rounding
Commercial rounding with optional specification of the number of decimal places.
Example
13,3749 -> 13,37
-13,3749 -> -13,37
13,3750 -> 13,38
-13,3750 -> -13,38
Snippet
import de.uplanet.util.math.RoundingUtil
RoundingUtil.roundHalfAwayFromZero(, 2)
Mathematical Rounding
Mathematical rounding with optional specification of the number of decimal places.
Example
2.2499 -> 2.2
2.2501 -> 2.3
2.2500 -> 2.2
2.3500 -> 2.4
Snippet
import de.uplanet.util.math.RoundingUtil
RoundingUtil.roundHalfEven(, 2)
Date / Time
Formatting Date Values
Here you'll find a script for formatting date values.
Snippet
import java.text.SimpleDateFormat
// specify the time zone
def tz = g_session.user.timeZone
//def tz = de.uplanet.lucy.server.DefaultTimeZone.get()
//def tz = TimeZone.getTimeZone("Europe/Berlin")
assert tz != null
// the date/time to be formatted
def dt = new Date()
// the date format
// https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/SimpleDateFormat.html
def fmt = new SimpleDateFormat("yyyy-MM-dd")
fmt.setTimeZone(tz)
println(fmt.format(dt))
Calculate Duration in Days
A data record contains data for a start date and an end date. The time interval between these two date values is calculated. Please note that time zones are not taken into account here.
Snippet
def conn = g_dbConnections.systemConnection
def dtStart = g_record["GUID"].value // datafield startDate
def dtEnd = g_record["GUID"].value // datafield endDate
def iID = g_record["GUID"].value // datafield (PK) (S) ID
use (groovy.time.TimeCategory)
{
def duration = dtEnd - dtStart
def stmt = g_dbQuery.prepare(conn, "UPDATE DATAGROUP('<DATAGROUP_GUID>') SET <COLUMN_DURATION> = ? WHERE LID = ?")
stmt.setInt(1, duration.days)
stmt.setInt(2, iID)
stmt.executeUpdate()
stmt.close()
}
Parse an ISO date string
Parses a string in ISO format into a `java.util.Date` object.
Example
def strDate = "2013-01-01T12:00:01Z"
def strDateMillis = "2013-01-01T15:00:01.000Z"
def dtDate1 = ISODateTimeUtil.parseISODateTime(strDate)
def dtDate2 = ISODateTimeUtil.parseISODateTimeMillis(strDateMillis)
def dtDate3 = ISODateTimeUtil.parseISODateTimeOptionalMillis(strDate)
def dtDate4 = ISODateTimeUtil.parseISODateTimeOptionalMillis(strDateMillis)
Snippet
import de.uplanet.util.ISODateTimeUtil
def dtDate = ISODateTimeUtil.parseISODateTimeOptionalMillis("<DATE_ISO_STRING>")
Starting with Intrexx version 12.0.0
Format a date as an ISO string
Formats a date object as an ISO string.
Example
println ISODateTimeUtil.formatISODateTime(currentTimestamp())
println ISODateTimeUtil.formatISODateTimeMillis(currentTimestamp())
Snippet
import de.uplanet.util.ISODateTimeUtil
ISODateTimeUtil.formatISODateTime(currentTimestamp())
Starting with Intrexx version 12.0.0
Now as a timestamp
Snippet
now().withoutFractionalSeconds
Timestamps for System Values
This closure returns the timestamp of the current transaction. This value remains unchanged until the end of this transaction.
Snippet
currentTimestamp()
Starting with Intrexx version 12.0.0
Groovy Email (Simple)
Create a simple text email.
Snippet
import de.uplanet.lucy.server.mail.GroovyMailBuilder
def mail = new GroovyMailBuilder().composeMail {
from = "sender@example.org"
to = "recipient@example.org"
subject = "Insert the subject here"
body << "Hello world"
}
mail.drop()
Starting with Intrexx version 12.0.0
Groovy Email
Create an HTML email with images and file attachments.
Snippet
import de.uplanet.lucy.server.mail.GroovyMailBuilder
def fileImg = new File(g_dirWorkflow, "theImage.png")
def fileAttachment = new File(g_dirWorkflow, "document.pdf")
def mail = new GroovyMailBuilder().composeMail {
headers = [
"Importance": "High",
"X-Priority": "1"
]
from = "sender@example.org"
to = ["recipient-1@example.org", "recipient-2@example.org"]
subject = "Insert the subject here"
contentType = "text/html; charset=UTF-8"
body << """<html>
<body>
<h1>Hello World</h1>
<p>
Look at this image
<br>
<img src="${srcInlineImage(fileImg)}">
<br>
Nice.
</p>
</body>
</html>"""
// note: name is an optional parameter
attachFile(file: fileAttachment, name: "nameOfTheAttachment.pdf", contentType: "application/pdf")
}
mail.drop()
Starting with Intrexx version 12.0.0
Send an email via Ant
Please note: Sending the email is not part of the transaction; it is carried out immediately, regardless of whether the transaction is successful.
Snippet
def strFromAddr = g_session?.user?.emailBiz
def strFromName = g_session?.user?.name
def strToAddr = "" // insert the recipient here
new AntBuilder().mail(mailhost:"localhost", messagemimetype:"text/plain", subject:"Hello World") {
from(address:"${strFromName} <${strFromAddr}>")
to(address:addrTo)
message("""Here goes the message text.
With kind regards
${strFromName}
""")
}
Files and Directories
Determine Hard Drive Space
Determines the free and total hard drive capacity.
Snippet
// the partition where the Intrexx portal resides
File partition = new File(".")
long totalSpace = partition.totalSpace
long freeSpace = partition.freeSpace
Directory of the current process
Returns the directory of the current process. Access to this directory should be read-only.
Snippet
g_dirWorkflow
Temporary Process Directory
Access to a temporary process directory. The directory is also visible to subsequent process objects. It will be deleted as soon as the process has been completed.
Snippet
g_dirWorkflowTmp
Work in a temporary directory
Uses a temporary directory for processing.
Snippet
import de.uplanet.io.IOHelper
File dirTemp = createTemporaryDirectory()
try
{
}
finally
{
IOHelper.deleteFileRecursively(dirTemp)
}
Import a text file
Reads the contents of a text file using the specified encoding. Do not use with large amounts of data.
Snippet
def fileIn = new File("<FILE_NAME>")
def strContent = fileIn.getText("UTF-8")
Read a text file line by line
Reads the contents of a text file line by line using the specified encoding.
Snippet
def fileIn = new File("_in.txt")
fileIn.eachLine("UTF-8") {line ->
//process line
}
Write to a text file
Writes text output to a text file using the specified encoding.
Example
def fileOut = new File("out.txt")
def strOutput = "This is my output text.\n"
fileOut.withWriter("UTF-8")
{
out -> out << strOutput
out.write(strOutput)
out.append(strOutput)
}
Snippet
def fileOut = new File("out.txt")
fileOut.withWriter("UTF-8")
{
out ->
//write output to file
}
Session / User
Current User's Name
Snippet
g_session?.user?.name
Current user's email address
Snippet
g_session?.user?.emailBiz
Anonymous session or not?
Snippet
g_session?.anonymous
Starting with Intrexx version 12.0.0
Access to the Organizational Structure
Snippet
g_om.getOrgStructure()
Logged-in users
List of all registered, non-anonymous users.
Snippet
de.uplanet.lucy.server.portalserver.LoggedOnUsers.getLoggedOnUsersDistinct()
Set a New Password for a User
Sets a new password for the specified user.
Snippet
g_om.changePassword(user, password)
Starting with Intrexx version 12.0.0
User Management
Create a User (Simple)
Snippet
g_om.createUser {
container = "System"
name = "user-${now().withoutFractionalSeconds}"
loginName = "UserU-${now().withoutFractionalSeconds}"
password = "secret"
emailBiz = "user@example.org"
description = "User created with Groovy at ${now().withoutFractionalSeconds}"
}
Create a user
Snippet
// provide the copy of an user image (optional)
def fileTemplImage = new File(g_dirWorkflow, "user.jpg")
def fileUserImage = new File(g_dirWorkflowTmp, "user.jpg")
de.uplanet.io.IOHelper.copyFile(fileUserImage, fileTemplImage)
def user = g_om.createUser {
container = "System"
name = "user-${now().withoutFractionalSeconds}"
loginName = "UserU-${now().withoutFractionalSeconds}"
password = "secret"
emailBiz = "user@example.org"
description = "User created with Groovy at ${now().withoutFractionalSeconds}"
nickname = "dodo" // this is a custom user field
userImageFile = fileUserImage
// provide a list of sets (group, role, dist list, ...) the user should be member of
// allowed are GUIDs, unique names, paths, or org structure set nodes
memberOf = ["importantRole", "36B3BFD54A57BE5D1EE51288D920CDA9B20A67A4"]
}
// create a new password and send it to the user's emailBiz address (optional)
g_om.generateAndSendPassword(user, g_defaultLanguage)
Edit Existing Users
Snippet
def user = g_om.getUser("LOGINNAME", "DOMAIN")
if (user != null)
{
// provide the copy of a user image (optional)
def fileTemplImage = new File(g_dirWorkflow, "user.jpg")
def fileUserImage = new File(g_dirWorkflowTmp, "user.jpg")
de.uplanet.io.IOHelper.copyFile(fileUserImage, fileTemplImage)
// get the GUID list of sets (group, role, dist list, ...) the user is member of
def membership = user.getDirectMemberSets()
membership.remove("EF16F15EDA8562E19D7CD56BF2E43001F119193C")
membership.add("36B3BFD54A57BE5D1EE51288D920CDA9B20A67A4")
user.containerGuid = "4B87C2470868AAB57BFB31958D1F73583FB3778E"
user.name = "user-${now().withoutFractionalSeconds}"
user.emailBiz = "user@example.org"
user.description = "User created with Groovy at ${now().withoutFractionalSeconds}"
user.nickName = "dodo" // this is a custom user field
user.userImageFile = fileUserImage
user.save()
}
Classify GUIDs
Classifying GUIDs by
-
User
-
Container (Organization, Organizational Unit, ...)
-
Set (Group, Role, Distribution List, ...)
-
Unclassifiable GUID
Snippet
def classified = g_om.classifyGuids(/* a list of GUIDs or text that contains GUIDs */)
// do something with the classified GUIDs
classified.users
classified.containers
classified.sets
classified.unclassified
Categories
Date / Time
Snippet
use (groovy.time.TimeCategory)
{
}
IValueHolder
Snippet
use (de.uplanet.lucy.server.scripting.groovy.GroovyIntrexxValueHolderCategory)
{
}
Class GroovyIntrexxValueHolderCategory
Info
System Information
Snippet
def osmbean = java.lang.management.ManagementFactory.operatingSystemMXBean
def sysInfo = """
name ${osmbean.name}
version ${osmbean.version}
arch ${osmbean.arch}
availableProcessors ${osmbean.availableProcessors}
processCpuTime ${osmbean.processCpuTime}
systemLoadAverage ${osmbean.systemLoadAverage}
committedVirtualMemorySize ${osmbean.committedVirtualMemorySize} bytes
totalPhysicalMemorySize ${osmbean.totalPhysicalMemorySize} bytes
freePhysicalMemorySize ${osmbean.freePhysicalMemorySize} bytes
totalSwapSpaceSize ${osmbean.totalSwapSpaceSize} bytes
freeSwapSpaceSize ${osmbean.freeSwapSpaceSize} bytes"""
g_log.info(sysInfo)
Intrexx Version
Returns the version of the Intrexx installation.
Snippet
de.uplanet.lucy.VERSION.CURRENT.toFormattedString()
Starting with Intrexx version 12.0.0
Error Handling and Troubleshooting
Stack trace as a string
Snippet
getStackTraceString()
Groovy Context
Snippet
def dumpBinding = {
def sbuf = new StringBuilder()
sbuf << "Dump the Groovy binding:\n"
binding.variables.each { k, v ->
if (v && v.metaClass && v.metaClass.respondsTo(v, "dump"))
sbuf << "${k} = ${v.dump()}\n"
else
sbuf << "${k} = ${v?.toString()}\n"
}
sbuf.toString()
}
g_log.info(dumpBinding())
Define an error handler for the script
Can be used in
-
Groovy Pages
-
Action and Rendering Handlers
Snippet
onError = { exception, err ->
err.title = ""
err.description = "Insert your description here. ${exception.message}"
}
Groovy Server Scripts
JSON Response
Please note that a permission check (IxAccessController) is required before any actions that can be triggered by users.
Snippet
response.json()
// define an error handler
response.onError =
{
e, err ->
//err.type = "default"
// either title/description, ...
err.title = "my error"
err.description = e.message
err.showEmbedded = true
// ... or a redirect
// err.redirectUrl = "https://www.example.org/"
err.redirectDelay = 1500 // milliseconds
}
// check permissions
g_permissions.check
{
// application("${application.guid}": "access")
// dataGroup("<data group GUID>": "read", "<another data group GUID>": "write,create")
}
// create some JSON content
writeJSON("person": [
givenName: "Donald",
lastName: "Duck",
age: 78,
nephews: ["Huey", "Dewey", "Louie"]
])
Possible variations of the script shown above
Closure with no parameters or exactly one parameter
If the closure declares a parameter, the exception that occurred is passed to the closure in the first parameter (e).
Snippet
// define an error handler
response.onError = {e ->
writeJSON("error": "Something bad happened.")
}
Closure with two parameters
The first parameter (e) passes the exception that occurred to the closure, and the second parameter (err) passes an to the closure. In the Closure, the ErrorResponseData object can be configured according to specific needs.
Snippet
// define an error handler
response.onError = {e, err ->
//err.type = "default"
// either title/description, ...
err.title = "my error"
err.description = e.message
err.showEmbedded = true
// ... or a redirect
// err.redirectUrl = "https://www.example.org/"
// err.redirectDelay = 1500 // milliseconds
}
With a thong
The specified string is sent to the client in the response body.
Snippet
response.onError = '{"error": "Something bad happened."}'
Assigning a Different Object
If the response is JSON, the system will attempt to generate JSON from the object. If the response is not in JSON format, the system will attempt to output the object as text in an appropriate manner.
Snippet
response.onError = [
"error": "Something bad happened.",
"solace": "But things could be worse."
]
Velocity
Generate Text from the Velocity Template
Snippet
import de.uplanet.lucy.server.scripting.velocity.VelocityContextUtil
import org.apache.velocity.app.Velocity
def fileVm = new File(g_dirWorkflow, "") // the Velocity input file
def vc = VelocityContextUtil.createDefaultContext(g_context)
// add additional variables to the Velocity context
// vc.put("PreparedQuery", g_dbQuery)
// vc.put("variableName", variableValue)
def template = Velocity.getTemplate(fileVm.path)
def writer = new StringWriter(4096) // 4 KiB initial buffer
template.merge(vc, writer)
g_log.info(writer.toString())
Generate a File from a Velocity Template
For security reasons, Velocity files can only be executed if they are located in one of the following subdirectories:
-
internal/system/vm
-
internal/layout/vm
-
internal/application/vm
-
internal/application/resource
-
internal/workflow/<GUID>/velocity
Request Variable
g_request.get(...)
Snippet
g_request.get("")
Class GroovyServerBridgeRequest
Starting with Intrexx version 12.0.0
Class GroovyServerBridgeRequest
rq_Lang
Returns the language currently in use by the logged-in user.
Snippet
rq_Lang
REMOTE_ADDR
IP address of the client computer.
Snippet
REMOTE_ADDR
SERVER_PORT
Snippet
SERVER_PORT
HTTP_HOST
Snippet
HTTP_HOST
HTTP_REFERER
Snippet
HTTP_REFERER
HTTP_COOKIE
Snippet
HTTP_COOKIE
HTTP_USER_AGENT
Snippet
HTTP_USER_AGENT
DIAGRAM
HTTP or HTTPS
Snippet
SCHEME
Pictures
Resize Image
Supported formats are PNG, JPEG (JPG), and BMP.
Snippet
import de.uplanet.lucy.server.scripting.groovy.ImageHelper
// Parameters: inputFile, outputFile, format?, width?, height?, maxWidth?,
// maxHeight?, scaleX?, scaleY?, shrinkOnly?, rotate?, crop?
ImageHelper.scaleImage(inputFile: , outputFile: <OUTPUT_FILE>)
Starting with Intrexx version 12.0.0
Determine Image Size
A file object or a path as a string can be passed as a parameter.
Snippet
import de.uplanet.lucy.server.scripting.groovy.ImageHelper
def (x, y) = ImageHelper.getImageSize()
Starting with Intrexx version 12.0.0
Iterating Over Image Metadata
Here is an example that demonstrates how to use metadata extraction in Groovy.
Snippet
import de.uplanet.lucy.server.scripting.groovy.ImageHelper
def file = ImageHelper.getImageMetaData(file).each {
tag, value -> println("$tag -> $value")
}
Starting with Intrexx version 12.0.0
Logging
Write information to the portal log file
Writes an INFO entry to the portal.log file. This method can be used when the log file associated with the script's execution context is not portal.log, but the output should still be written to portal.log.
Snippet
g_syslog.info("")
Write information to the log file
Writes an INFO entry to the log file associated with the script's execution context.
Snippet
g_log.info("")
Write a warning to the portal log file
Writes a WARN entry to the portal.log file. This method can be used when the log file associated with the script's execution context is not portal.log, but the output should still be written to portal.log.
Snippet
g_syslog.warn("")
Write a warning to the log file
Writes a WARN entry to the log file associated with the script's execution context.
Snippet
g_log.warn("")
Write errors to the portal log file
Writes an ERROR entry to the portal.log file. This method can be used when the log file associated with the script's execution context is not portal.log, but the output should still be written to portal.log.
Snippet
g_syslog.error("")
Write errors to the log file
Writes an ERROR entry to the log file associated with the script's execution context.
Snippet
g_log.error("")
Read Statistics Logs
Snippet
import de.uplanet.lucy.server.monitor.log.GroovyLogReader
// flush queued log entries to disk
GroovyLogReader.flushLogQueue()
// collect the log files
def logFiles = []
new File("internal/statistics").eachFile {
if (!it.name.startsWith(".")) // TODO check additional criteria
logFiles << it
}
// read the selected log files
logFiles.each { file ->
GroovyLogReader.readLog(file) { entry ->
// TODO do something with the entry
println("Time in millis = ${entry.time}, targetGuid = ${entry.targetGuid}")
}
}
Connector for Microsoft Exchange
Current Exchange Connection
Returns the current connection to Microsoft Exchange.
Snippet
import de.uplanet.lucy.server.businesslogic.exchange.util.ExchangeConnectionUtil
def connEx = ExchangeConnectionUtil.getConnectionForWorkflowAction(g_context)
Starting with Intrexx version 12.0.0
Mailbox name of the current Exchange user
Returns the name of the mailbox for the current Exchange connection.
Snippet
import de.uplanet.lucy.server.businesslogic.exchange.util.ExchangeConnectionUtil
import de.uplanet.lucy.server.businesslogic.exchange.util.ExchangeUtils
def connEx = ExchangeConnectionUtil.getConnectionForWorkflowAction(g_context)
def mailboxUtil = ExchangeUtils.getMailboxUtil(connEx)
def strMailboxName = mailboxUtil.getImpersonateUserAccount(g_context.impersonateUserGuid).exchangeMailbox
Starting with Intrexx version 12.0.0
Save an email locally as an EML file
Saves an email locally in EML format. Alternatively, you can use saveMessageAsMSG(..) to save the email in MSG format.
Parameters:
-
strMessageId - The ID of the email to be saved
-
fileMail - File object used to store the email
Snippet
import de.uplanet.lucy.server.businesslogic.exchange.util.ExchangeUtils
import de.uplanet.lucy.server.businesslogic.exchange.util.ExchangeConnectionUtil
def connEx = ExchangeConnectionUtil.getConnectionForWorkflowAction(g_context)
def messageUtil = ExchangeUtils.getMessageUtil(connEx)
messageUtil.saveMessageAsEML(strMessageId, fileMail)
Interface IExchangeMessageUtil
Starting with Intrexx version 12.0.0
Interface IExchangeMessageUtil
Saving Email Attachments
Saves the attachments for the email defined by strMessageId.
Snippet
import de.uplanet.lucy.server.businesslogic.exchange.util.ExchangeUtils
import de.uplanet.lucy.server.businesslogic.exchange.util.ExchangeConnectionUtil
def connEx = ExchangeConnectionUtil.getConnectionForWorkflowAction(g_context)
def itemUtil = ExchangeUtils.getItemUtil(connEx)
def attachments = itemUtil.getAttachments(strMessageId)
attachments.each{ item ->
def attachment = new File(g_dirWorkflowTmp, item.displayName)
itemUtil.saveAttachment(item, attachment)
}
Starting with Intrexx version 12.0.0
Set an out-of-office message
Write the text of the out-of-office message and set the status to "active." Note: The text is formatted as both an internal and an external message.
Snippet
import de.uplanet.lucy.server.businesslogic.exchange.util.ExchangeUtils
import de.uplanet.lucy.server.businesslogic.exchange.util.ExchangeConnectionUtil
def connEx = ExchangeConnectionUtil.getConnectionForWorkflowAction(g_context)
def mailboxUtil = ExchangeUtils.getMailboxUtil(connEx)
mailboxUtil.setOutOfOfficeMessage("Out of office till 2010/31/12")
mailboxUtil.setOutOfOffice(true)
Interface IExchangeMailboxUtil
Starting with Intrexx version 12.0.0
Interface IExchangeMailboxUtil
Get Folder Information
Retrieves information about a folder in the Exchange account.
Snippet
import de.uplanet.lucy.server.businesslogic.exchange.util.ExchangeUtils
import de.uplanet.lucy.server.businesslogic.exchange.util.ExchangeConnectionUtil
def connEx = ExchangeConnectionUtil.getConnectionForWorkflowAction(g_context)
def mailboxUtil = ExchangeUtils.getMailboxUtil(connEx)
def folderInfo = mailboxUtil.getFolderInfoByHref(mailboxUtil.getInboxFolderHref())
Starting with Intrexx version 12.0.0
Create a folder
Creates an Exchange folder (in this example, under the Inbox).
Parameters:
-
Name of the parent folder
-
Name of the new folder
-
Exchange content class
Snippet
import de.uplanet.lucy.server.businesslogic.exchange.util.ExchangeUtils
import de.uplanet.lucy.server.businesslogic.exchange.util.ExchangeConnectionUtil
def connEx = ExchangeConnectionUtil.getConnectionForWorkflowAction(g_context)
def mailboxUtil = ExchangeUtils.getMailboxUtil(connEx)
def strInboxFolder = mailboxUtil.getInboxFolderHref()
mailboxUtil.createFolder(strInboxFolder, "myFolder", "urn:content-classes:mailfolder")
Interface IExchangeMailboxUtil
Starting with Intrexx version 12.0.0
Interface IExchangeMailboxUtil
Add an attachment to an item
Adds an attachment to an existing item (e.g., an appointment).
Parameters:
-
strItemId - ID of the element to which the attachment is to be added
-
fileAttach - Attachment to be added
-
strFileName - Name of the attachment
-
strMimeType - The MIME type of the attachment. If zero, `application/octet-stream` is used
-
bIsContactPhoto - True if an image file is to be added to a contact
-
bDeleteAfter - True if the original file should be deleted after appending
Snippet
import de.uplanet.lucy.server.businesslogic.exchange.util.ExchangeUtils
def connEx = ExchangeConnectionUtil.getConnectionForWorkflowAction(g_context)
def itemUtil = ExchangeUtils.getItemUtil(connEx)
def strFileName = "myAttachment.txt"
def strMimeType = "text/plain"
def fileAttach = new File(strFileName)
itemUtil.addAttachmentToItem(strItemId, fileAttach, strFileName, strMimeType, bIsContactPhoto, bDeleteAfter)
Starting with Intrexx version 12.0.0
Create an Exchange Appointment
Creates a new appointment for the current Exchange user.
Parameters:
-
dtStartDate - Start date of the appointment
-
dtEndDate - End date of the appointment
-
strSubject - Event Title
-
strBody - Description of the appointment
If additional properties are defined using set() methods after the appointment has been created, you must save the appointment again using appointment.save() to apply the changes.
Example
def appointment = aptUtil.createNewAppointment(dtStartDate, dtEndDate, strSubject, strBody)
appointment.setLocation("Konferenzraum")
appointment.save()
Snippet
import de.uplanet.lucy.server.businesslogic.exchange.util.ExchangeConnectionUtil
import de.uplanet.lucy.server.businesslogic.exchange.util.ExchangeUtils
def connEx = ExchangeConnectionUtil.getConnectionForWorkflowAction(g_context)
def aptUtil = ExchangeUtils.getAppointmentUtil(connEx)
def appointment = aptUtil.createNewAppointment(dtStartDate, dtEndDate, strSubject, strBody)
Interface IExchangeAppointmentUtil
Starting with Intrexx version 12.0.0
Interface IExchangeAppointmentUtil
Create an Exchange Contact
Creates a new contact for the current Exchange user.
Parameters:
-
strLastName - Contact's last name
-
strFirstName - Contact's first name
-
strMail - Contact's email address
-
strMailbox - The mailbox of the user for whom the contact is to be created. If zero is specified, the current user's mailbox is used.
If additional properties are defined using set() methods after the contact has been created, the contact must be saved again using contact.save() to apply the changes.
Example
def contact = contactUtil.createNewContact("Doe", "John", "john.doe@example.org", null)
contact.setJobTitle("Developer")
contact.save()
Snippet
import de.uplanet.lucy.server.businesslogic.exchange.util.ExchangeConnectionUtil
import de.uplanet.lucy.server.businesslogic.exchange.util.ExchangeUtils
def connEx = ExchangeConnectionUtil.getConnectionForWorkflowAction(g_context)
def contactUtil = ExchangeUtils.getContactUtil(connEx)
def contact = contactUtil.createNewContact(strLastName, strFirstName, strMail, strMailbox)
Interface IExchangeContactUtil
Starting with Intrexx version 12.0.0
Interface IExchangeContactUtil
Generate and Send Exchange Emails
Creates a new email account for the current Exchange user.
Parameters:
-
strFrom - Sender's email address
-
strTo - Recipient Address
-
strSubject - Subject
-
strBody - Message text
If additional properties are defined using set() methods after the email has been created, the draft must be saved again using message.save() to apply the changes.
Example
def message = msgUtil.createNewDraft("sender@example.org", "recipient@example.org", "Example subject", "Example text")
message.setCc("cc_recipient@example.org")
message.save()
message.send()
Snippet
import de.uplanet.lucy.server.businesslogic.exchange.util.ExchangeConnectionUtil
import de.uplanet.lucy.server.businesslogic.exchange.util.ExchangeUtils
def connEx = ExchangeConnectionUtil.getConnectionForWorkflowAction(g_context)
def msgUtil = ExchangeUtils.getMessageUtil(connEx)
def message = msgUtil.createNewDraft(strSender, strRecipient, strSubject, strBody)
Interface IExchangeMessageUtil
Starting with Intrexx version 12.0.0
Interface IExchangeMessageUtil
Create an Exchange Note
Creates a new note for the current Exchange user.
Parameters:
-
strText - Text of the note
-
strMailBox - Name of the mailbox in which the note is to be created. If zero is specified, the current user's mailbox is used.
Example
def noteUtil = ExchangeUtils.getNoteUtil(connEx)
def note = noteUtil.createNewNote("My note", null)
Snippet
import de.uplanet.lucy.server.businesslogic.exchange.util.ExchangeConnectionUtil
import de.uplanet.lucy.server.businesslogic.exchange.util.ExchangeUtils
def connEx = ExchangeConnectionUtil.getConnectionForWorkflowAction(g_context)
def noteUtil = ExchangeUtils.getNoteUtil(connEx)
def note = noteUtil.createNewNote(strText, strMailBox)
Starting with Intrexx version 12.0.0
Create an Exchange task
Creates a new task for the current Exchange user.
Parameters:
-
dtStart - Task start date
-
dtDue - Task Due Date
-
strSubject - Assignment Title
-
strMailBox - Name of the mailbox in which the task should be created. If zero is specified, the current user's mailbox is used.
Example
def taskUtil = ExchangeUtils.getTaskUtil(connEx)
def dtStart, dtDue, reminder
use (groovy.time.TimeCategory)
{
dtStart = new Date() + 1.day
dtStart = dtStart.clearTime()
dtDue = dtStart + 5.days
reminder = dtDue - 12.hours
}
def task = taskUtil.createNewTask(dtStart, dtDue, "Task subject", null)
task.setPercentComplete(25.0)
task.setUserDefinedFieldValue("ReminderTime", VH.getValueHolder(reminder))
task.setUserDefinedFieldValue("ReminderSet", VH.getValueHolder(true))
task.save()
Snippet
import de.uplanet.lucy.server.businesslogic.exchange.util.ExchangeConnectionUtil
import de.uplanet.lucy.server.businesslogic.exchange.util.ExchangeUtils
def connEx = ExchangeConnectionUtil.getConnectionForWorkflowAction(g_context)
def taskUtil = ExchangeUtils.getTaskUtil(connEx)
def task = taskUtil.createNewTask(dtStart, dtDue, "Task subject", null)
Starting with Intrexx version 12.0.0
Portlets
Display the portlet only if the table contains records
The following script ensures that the portlet is displayed only if the table it contains has records and the "Restrict portlet display on the web via Groovy script" setting is enabled. The script can also be used for the setting "Restrict portlet selection on the web using a Groovy script"—in that case, the portlet will no longer appear in the portlet settings under "Portlets from Applications" and therefore cannot be embedded on the portal page.
Snippet
g_dataCollection.getDataRange("768A3C783F2BC9FD7EF20B1979FD3B27498779E2").getNumberOfRecords() > 0
Tips & Tricks - Filtering Portlets with Groovy
Restrictions on Portlets in the Portlet Container
To restrict portlets in the portlet container, a list of portlet objects must be returned as the return value. "g_portletPool" can be used to retrieve all available portlet objects. In this example, only the portlet with the GUID entered in place of the placeholder would be available.
Snippet
def portletsAus = []
for(portlet in g_portletPool){
if(portlet.getPageGuid() == "<GUID>)"{
portletsAus.add(portlet)
}
}
return portletsAus
Starting with Intrexx version 12.0.0
Controlling the display using a Boolean value
By returning a Boolean value, you can control—for example, in the portlet properties —whether a portlet is displayed or not:
Snippet
def isok = "<check if a portlet shall be displayed>"
if( isok)
return true
else
return false
Starting with Intrexx version 12.0.0
SSH
Examples of How to Use the SFTP API
Base Template, Authentication via SSH Key
This is the option recommended in most cases. For security reasons, the "root" user used in the example should be replaced in practice with a user who has lower privileges.
To do this, the portal's public key must be stored on the target server for the user in question.
Snippet
import java.nio.file.Files
def dirLocal = g_dirWorkflowTmp.toPath()
g_ssh.sftp(userName: 'root', host: 'host.example.org')
{
try
{
println(dirDefault)
println(dirRoot)
assert Files.isRegularFile(getPath('/etc/passwd'))
// copy on remote system
copy(from: getPath('/etc/passwd'), to: getPath('/tmp/passwd.bak'), replaceExisting: true)
// copy to local system
copy(from: getPath('/etc/passwd'), to: dirLocal.resolve('passwd'))
}
finally
{
deleteIfExists(getPath('/tmp/passwd.bak'))
}
}
https://docs.intrexx.com/apidocs/jdk21/api/java.base/java/nio/file/package-summary.html
Base template, authentication via SSH URI and password from the credential store
For security reasons, the "root" user used in the example should be replaced in practice with a user who has lower privileges.
Snippet
import java.nio.file.Files
def dirLocal = g_dirWorkflowTmp.toPath()
g_ssh.sftp(userName: 'root', host: 'host.example.org', password: g_credentials.getSecret('sshKeyRootHostExampleOrg'))
{
try
{
println(dirDefault)
println(dirRoot)
assert Files.isRegularFile(getPath('/etc/passwd'))
// copy on remote system
copy(from: getPath('/etc/passwd'), to: getPath('/tmp/passwd.bak'), replaceExisting: true)
// copy to local system
copy(from: getPath('/etc/passwd'), to: dirLocal.resolve('passwd'))
}
finally
{
deleteIfExists(getPath('/tmp/passwd.bak'))
}
}
https://docs.intrexx.com/apidocs/jdk21/api/java.base/java/nio/file/package-summary.html
Examples of How to Use SCP Uploads and Downloads
Authentication via SSH Key
This is the option recommended in most cases. To do this, the portal's public key must be stored on the target server for the user in question.
Snippet
//Upload (Datei)
g_ssh.scpUpload(
userName: 'fileman',
host: 'host.example.org',
from: fileLocal,
to: '/remote/path')
//Upload (Verzeichnis)
g_ssh.scpUpload(
userName: 'fileman',
host: 'host.example.org',
from: dirLocal,
to: '/remote/path',
recursive: true)
//Download (Datei)
g_ssh.scpDownload(
userName: 'fileman',
host: 'host.example.org',
from: '/remote/path',
to: fileLocal)
//Download (Verzeichnis)
g_ssh.scpDownload(
userName: 'fileman',
host: 'host.example.org',
from: '/remote/path',
to: dirLocal,
recursive: true)
Authentifizierung per SSH-URI und Passwort aus Anmeldeinformationsspeicher (Credential-Store)
//Upload (Verzeichnis)
g_ssh.scpUpload(
userName: 'fileman',
password: g_credentials.getSecret('sshKeyFilemanHostExampleOrg'),
host: 'host.example.org',
from: dirLocal,
to: '/remote/path',
recursive: true)
https://docs.intrexx.com/apidocs/jdk21/api/java.base/java/nio/file/package-summary.html
Examples of Using Remote Command Execution via SSH
Authentication via SSH Key
This is the option recommended in most cases. To do this, the portal's public key must be stored on the target server for the user in question. For security reasons, the "root" user used in the example should be replaced in practice with a user who has lower privileges.
Snippet
def result = g_ssh.execute(userName: 'root', host: 'host.example.org', command:
"""
cd /etc
pwd
head -5 passwd
""")
println(result.exitStatus) // 0 if nor error occurred in the remote execution
println(result.stdoutText)
Authentication via SSH URI and password from the credential store
In the example, the value "root@host.example.org" is stored in the credential store under the key "sshUriRootHostExampleOrg." For security reasons, the "root" user should be replaced in practice with a user who has lower privileges.
def result = g_ssh.execute(
uri: g_credentials.getSecret('sshUriRootHostExampleOrg'),
password: g_credentials.getSecret('sshKeyRootHostExampleOrg'),
command:
"""
cd /etc
pwd
head -5 passwd
""")
println(result.exitStatus) // 0 if nor error occurred in the remote execution
println(result.stdoutText)
https://docs.intrexx.com/apidocs/jdk21/api/java.base/java/nio/file/package-summary.html
WebSockets
Sending a Text Message
Example
import de.uplanet.lucy.server.websocket.groovy.GroovyWebSocketTopic
GroovyWebSocketTopic.sendTextMessage("D00F000000000000000000000000000000000000", "Hello world!")
Snippet
import de.uplanet.lucy.server.websocket.groovy.GroovyWebSocketTopic
GroovyWebSocketTopic.sendTextMessage("<topicGUID>", "<string>")
Starting with Intrexx version 12.0.0
Sending a JSON Message
Example
import de.uplanet.lucy.server.websocket.groovy.GroovyWebSocketTopic
def msg = [
seq: 1,
greet: "Hello world!"
]
GroovyWebSocketTopic.sendJsonMessage("D00F000000000000000000000000000000000000", msg)
Snippet
import de.uplanet.lucy.server.websocket.groovy.GroovyWebSocketTopic
def msg = [
seq: 1,
greet: "<string>"
]
GroovyWebSocketTopic.sendJsonMessage(${cursor}"<topicGUID>", msg)
Starting with Intrexx version 12.0.0
Check for an interrupt request
checkInterrupted()
Checks whether either
-
the thread executing the process has received an interrupt request from another thread, or
-
the timeout set for the process has been exceeded.
Use this call in scripts that are intended to behave cooperatively in such cases.
Snippet
checkInterrupted()
Starting with Intrexx version 12.0.0
Automatic logout of implicitly generated sessions
If a Groovy endpoint is called without the client sending a valid session ID, an anonymous session is implicitly created on the server. The following script prevents these sessions from remaining on the server until the anonymous session times out. The criterion for automatic logout is that the client has not sent a co_SId session cookie.
Snippet
import de.uplanet.server.transaction.TransactionManager
// if the client did not send a session cookie we logout
// the session after the current transaction has finished
if (!g_request.get('co_SId'))
TransactionManager.addAfterCommitAction {g_session.logout()}
Run an external program
Runs an external program. For more information, click here.
Snippet
def pOut = new StringBuffer()
def pErr = new StringBuffer()
def proc = [""].execute()
proc.consumeProcessOutput(pOut, pErr)
proc.waitForOrKill(10000) // 10 seconds
if (proc.exitValue() == 0)
{
// success
// ...
}
else
{
// an error occurred
g_log.error(pErr.toString())
}
Generate a GUID
Generates a new GUID.
Snippet
newGuid()
Starting with Intrexx version 12.0.0
Parsing GUIDs
Parse GUIDs from text input. Several parameters are possible.
Snippet
parseGuids()
Check GUID
Checks whether a given string is a GUID as defined by Intrexx. If the value passed is zero, the method returns false.
Example:
def valueToCheck = 'DAF7CECF66481FCABE50E529828116EAFE906962'
if (Guid.isStringRepresentation(valueToCheck))
{
//valid GUID
}
Snippet
Guid.isStringRepresentation('<GUID>')
Starting with Intrexx version 12.0.0
Starting with Intrexx version 12.2.0
Locksmith Service
The Locking API can be used to set and query locks across the portal in order to control or manage concurrent access to resources.
import de.uplanet.lucy.server.lockservice.scripting.groovy.GroovyLockService
if (GroovyLockService.tryFirstLock('lock-name', 'locker')) {
println('Successfully acquired lock-name.')
// ...
} else {
println('Could not acquire lock-name.')
// ...
}
Normalizing Phone Numbers
Starting with Intrexx 12.1.0:
Example of normalizing phone numbers to the E.164 format.
Snippet
assert '+494066969000' == ps.normalizePhoneNumber(number: '+494066969000')
assert '+494066969000' == ps.normalizePhoneNumber(number: '+49 4066969000')
assert '+494066969000' == ps.normalizePhoneNumber(number: '+49 40 66969000')
assert '+494066969000' == ps.normalizePhoneNumber(number: '+49 40 66969000')
assert '+494066969000' == ps.normalizePhoneNumber(number: '+49-40-66969000')
assert '+494066969000' == ps.normalizePhoneNumber(number: '+49 40 66969-000')
assert '+494066969000' == ps.normalizePhoneNumber(number: '+49 (40) 66969000')
assert '+494066969000' == ps.normalizePhoneNumber(number: '+49(40)66969000')
assert '+494066969000' == ps.normalizePhoneNumber(number: '+49 (0)40 66969000')
assert '+494066969000' == ps.normalizePhoneNumber(number: '+49(0)40 66969000')
assert '+494066969000' == ps.normalizePhoneNumber(number: '+49(0)4066969000')
assert '+494066969000' == ps.normalizePhoneNumber(number: '+49(0)40/66969-000')
assert '+494066969000' == ps.normalizePhoneNumber(number: '+49 (0)40/66969-000')
assert '+494066969000' == ps.normalizePhoneNumber(number: '+49 (0)40 / 66969-000')
assert '+494066969000' == ps.normalizePhoneNumber(number: '00494066969000', defaultCountry: 'DE')
assert '+494066969000' == ps.normalizePhoneNumber(number: '011494066969000', defaultCountry: 'US')
assert '+494066969000' == ps.normalizePhoneNumber(number: '04066969000', defaultCountry: 'DE')
assert '+494066969000' == ps.normalizePhoneNumber(number: '040 66969000', defaultCountry: 'DE')
assert '+494066969000' == ps.normalizePhoneNumber(number: '040-66969000', defaultCountry: 'DE')
assert '+494066969000' == ps.normalizePhoneNumber(number: '(0)40 / 66969-000', defaultCountry: 'DE')
assert '+12135550100' == ps.normalizePhoneNumber(number: '+12135550100', defaultCountry: 'DE')
assert '+12135550100' == ps.normalizePhoneNumber(number: '+12135550100', defaultCountry: 'US')
assert '+12135550100' == ps.normalizePhoneNumber(number: '+12135550100', defaultCountry: 'JP')
assert '+12135550100' == ps.normalizePhoneNumber(number: '0012135550100', defaultCountry: 'DE')
assert '+12135550100' == ps.normalizePhoneNumber(number: '01112135550100', defaultCountry: 'US')
assert '+12135550100' == ps.normalizePhoneNumber(number: '01012135550100', defaultCountry: 'JP')
Start a Scheduler Job
Input parameter: The job's ID or GUID. The parameters "testParam" and "greeting" from the following snippet are available in SharedState within the started timer process.
Snippet
import de.uplanet.lucy.server.scheduler.JobStarter
JobStarter.startJob("B39F3AA1C06E56FD06538F92F46C075333F97F68", [testParam: true, greeting: ' Hello world!'])
Tips & Tricks - Starting Processes
Send a text message
Starting with Intrexx 12.1.0:
Example of sending an SMS.
Possible providerParameters:
https://docs.seven.io/de/rest-api/endpunkte/sms#sms-versenden.
https://docs.seven.io/en/rest-api/endpunkte/sms
Snippet
import de.uplanet.lucy.server.phoneservice.scripting.groovy.GroovyPhoneService
def phoneService = GroovyPhoneService.createInstance()
phoneService.addSms(
to: ['+494066969012', '+494066969034'],
text: "Machete don't text.",
// optional provider parameters
providerParameters: [
from: 'Intrexx'
])
if (true) // your choice
phoneService.sendAsync()
else
phoneService.send()
Send an SMS - GroovyMfaService
Starting with Intrexx 12.1.0:
Please note that an external provider must be configured. By default, Intrexx uses the "seven.io" provider—please be sure to check the service configuration.
Snippet
import de.uplanet.lucy.server.mfa.scripting.groovy.GroovyMfaService
def mfaSvc = GroovyMfaService.createInstance()
// Send
def strRefId = mfaSvc.sendAuthenticationCodeSms(to: '+172 9925904', lang: 'en')
// The user has received the code via SMS and entered
def strCode = getCodeFromUser() // TODO implement this
// Validate challengeassert mfaSvc.verifyAuthenticationCode(refId: strRefId, code: strCode)
// Remove reference that is no longer required (otherwise it will be removed after 3 minutes)
assert mfaSvc.clearAuthenticationCode(strRefId)
Short Links
Template - Groovy API for short links.
Criteria for matching short links with a configured short link rule:
Criteria for the Match
1.) Same static path prefix
2.) The same number of path components or path components plus variables, and the same number of slashes
3.) Path components that are not variables must be the same
For path components that are variables, the variables are assigned the values of the corresponding path components.
Generating the Target URLs
Target URLs can be absolute or relative to the website's root directory. In the first case, any destinations can be specified. In the second case, the target is assumed to be the website that was opened in the user's browser.
The variables assigned during matching can be used in the destination URL both as part of the path and in the query string. Query string parameters that appear in the input URL but not in the configured destination URL are included in the output URL.
Examples
import de.uplanet.lucy.server.urlredirect.scripting.groovy.GroovyRedirectRules
//----------------------------------
// create a new empty configuration
//----------------------------------
def rules = GroovyRedirectRules.createNew()
assert rules.isEmpty() // no rules
assert rules.size() == 0 // no rules
//---------------------------------------
// create and append some redirect rules
//---------------------------------------
def rule1 = rules.createNewRule('/from/path/1', '/to/path1')
rules << rule1 // append it
assert rules.size() == 1
def rule2 = rules.createNewRule('/from/path/2', '/to/path2')
rules << rule2
assert rules.size() == 2
def rule3 = rules.createNewRule(
fromUrl: '/search/${term}',
toUrl: 'https://www.google.de/search?q=intrexx+${term}')
rules << rule3
assert rules.size() == 3
def rule4 = rules.createNewRule(
fromUrl: '/customer/${custNo}',
toUrl: '/foo/?customer=${custNo}',
appGuid: 'DEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEF')
rules << rule4
assert rules.size() == 4
def rule5 = rules.createNewRule(
fromUrl: '/invoice/${invoiceNo}',
toUrl: '/bar/?invoice=${invoiceNo}',
appGuid: 'DEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEF')
rules << rule5
assert rules.size() == 5
// check if a rule is in the rules list
assert rules.contains(rule1) == true
assert rules[1] == rule2
// save the newly created redirect rules; this overwites internal/cfg/urlredirect.cfg
// and thus deletes all existing rules defined therein
rules.save()
rules = null // no reference to the rules anymore
//-------------------------------------------------------
// load existing rules from internal/cfg/urlredirect.cfg
//-------------------------------------------------------
rules = GroovyRedirectRules.load()
assert rules.size() == 5
// list the from URLs
def froms = rules*.fromUrl
assert froms == [
'/from/path/1',
'/from/path/2',
'/search/${term}',
'/customer/${custNo}',
'/invoice/${invoiceNo}']
// find a certain rule
def rule = rules.find {it.fromUrl == '/customer/${custNo}'}
assert rules.indexOf(rule) == 3
assert rule.fromUrl == '/customer/${custNo}'
assert rule.toUrl == '/foo/?customer=${custNo}'
// modify the rule
rule.toUrl = '/bar/?customer=${custNo}'
assert rule.toUrl == '/bar/?customer=${custNo}'
// find all rules that belong to application with
// GUID DEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEF
def appRules = rules.findAll {it.appGuid == 'DEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEF'}
assert appRules.size() == 2
// remove these rules
rules.removeAll(appRules)
assert rules.size() == 3
Snippet
import de.uplanet.lucy.server.urlredirect.scripting.groovy.GroovyRedirectRules
def rules = GroovyRedirectRules.load()
// do something with the redirect rules
rules.save()
Starting with Intrexx version 12.0.0
Determine the portal's startup time and uptime
Snippet
g_portal.getStartTime()
g_portal.getUptimeMillis()
Starting with Intrexx version 12.0.0
Phone call
Starting with Intrexx 12.1.0:
Example of a phone call.
Possible providerParameters:
https://docs.seven.io/de/rest-api/endpunkte/voice#voice-anruf-senden.
https://docs.seven.io/en/rest-api/endpunkte/voice.
Snippet
import de.uplanet.lucy.server.phoneservice.scripting.groovy.GroovyPhoneService
def phoneService = GroovyPhoneService.createInstance()
phoneService.addVoiceCall(
to: "+494066969001",
text: "The rain in Spain stays mainly in the plain.")
if (true) // your choice
phoneService.sendAsync()
else
phoneService.send()
Create ValueHolder
Creates a ValueHolder for a simple data type. If zero is passed, a NullValueHolder is created. Its value is zero; hasValue() returns false.
Snippet
vh()
Determine the portal's time zone
Here you will find a script for determining the default time zone, which is specified in the portal properties under "Country Settings."
Snippet
import de.uplanet.lucy.server.DefaultTimeZone
def tz = DefaultTimeZone.get()
Starting with Intrexx version 12.0.0
