Groovy

1. General

Click here for general information about scripting in Intrexx.

2. Intrexx Standard Library




In the Groovy script editor, you can access the Intrexx Standard Library on the Libraries tab. If you select an entry in the library, you can access these buttons at the bottom right of this area:

Show description
Shows the description of the currently selected function with an example script.

Open link
Links to the corresponding page that provides more information. The page that opens also shows the classes, interfaces, methods or properties that the currently selected function can be used for.

2.1. Application structure

2.1.1. Application property from data record object

Reads application properties from a data record object. Replace "myMethode()" in the example script with the desired method.

Example

def appInfoValue = g_record.applicationInfo.getGuid()
Returns the GUID of the application that the record belongs to.

Snippet

def appInfoValue = g_record.applicationInfo.myMethod()
Class AbstractGroovyRecord

2.1.2. Data group property from data record object

Reads data group properties from a data record object. Replace "myMethode()" in the example script with the desired method.

Example

def dgInfoValue = g_record.dataGroupInfo.getGuid()
Returns the GUID of the data group that the record belongs to.

Snippet

def dgInfoValue = g_record.dataGroupInfo.myMethod()
Class AbstractGroovyRecord
Interface DataGroupInfo

2.1.3. Application info

Returns information about the application with the stated GUID. Replace "myMethode()" in the example script with the desired method.

Example

def appPropValue = app?.getGuid()
Returns the application GUID.

Snippet

def app = g_rtCache.applications["<Application GUID>"]
def appPropValue = app?.myMethod()
Interface ApplicationInfo

2.1.4. Control info

Returns information about the control with the stated GUID. Replace "myMethode()" in the example script with the desired method.

Example

def ctrlInfo = ctrl?.getPageGuid()
Returns the GUID of the page that contains the control.

Snippet

def ctrl = g_rtCache.controls["<Control GUID>"]
def ctrlInfo = ctrl?.myMethod()
Interface ControlInfo

2.1.5. Data group info

Returns information about the data group with the stated GUID. Replace "myMethode()" in the example script with the desired method.

Example

def dgInfo = dg?.getGuid()
Returns the GUID of the data group.

Snippet

def dg = g_rtCache.dataGroups["<Data group GUID>"]
def dgInfo = dg?.myMethod()
Interface DataGroupInfo

2.1.6. Data field info

Returns information about the data field with the stated GUID. Replace "myMethode()" in the example script with the desired method.

Example

def fldInfo = fld?.getGuid()
Returns the GUID of the data field.

Snippet

def fld = g_rtCache.fields["<Data field GUID>"]
def fldInfo = fld?.myMethod()
Interface FieldInfo

2.1.7. Reference info

Returns information about the reference with the stated GUID. Replace "myMethode()" in the example script with the desired method.

Example

def refInfo = ref?.getGuid()
Returns the GUID of the reference.

Snippet

def ref = g_rtCache.references["<Reference GUID>"]
def refInfo = ref?.myMethod()
Interface ReferenceInfo

2.2. Language constants

All standard text elements used in Intrexx are defined in the global language constants. Click here for more information about this subject.

2.2.1. Access global language constant

Returns the value that the global language constant has for the default portal language. Replace "PORTAL_CONST_NAME" in the example script with the name of the desired language constant.

Example

def strValue = g_i18n.BUTTON_NEXT
Returns "Next" (label for the "Next" button that can be found in many applications - in this case it is returned in English, the default language of this example portal).

Snippet

def strValue = g_i18n.PORTAL_CONST_NAME
Class GroovyLanguageConstants

2.2.2. Access global language constant in a specific language

Returns the value that the global language constant has for the specified language. Replace "PORTAL_CONST_NAME" in the example script with the name of the desired language constant.

Example

def lang = g_i18n.language("en")
Returns the value that the global language constant has for English.

Snippet

def lang = g_i18n.language("language code")
def strValue = lang.PORTAL_CONST_NAME
Class GroovyLanguageConstants

2.2.3. Access application language constant

Returns the value that the application language constant has for the default portal language. Replace "APP_CONST_NAME" in the example script with the name of the desired language constant.

Snippet

def app = g_i18n.application("<Application GUID>")
def strValue = app.APP_CONST_NAME
Class GroovyLanguageConstants

2.2.4. Access application language constant in a specific language

Returns the value that the application language constant has for the specified language. Replace "APP_CONST_NAME" in the example script with the name of the desired language constant. Replace the language code with the two-letter ISO code, e.g. "en" for English.

Snippet

def app = g_i18n.application("<Application GUID>")
def strLang  = app.language("<language code>")
def strValue = strLang.APP_CONST_NAME
Class GroovyLanguageConstants

2.3. Imports

2.3.1. Intrexx AccessController

Class that can be used to check whether access requests should be allowed or denied based on the security guidelines currently in effect.

Snippet

import de.uplanet.lucy.server.security.IxAccessController
Class IxAccessController

2.3.2. IFilter

import de.uplanet.util.filter.IFilter

Snippet

Interface IFilter<T>

2.3.3. WorkflowException

Exception handling of processes.

Snippet

import de.uplanet.lucy.server.workflow.WorkflowException
Class WorkflowException

2.4. Objects in the Groovy context

2.4.1. PageActionHandler and PageRenderingHandler

2.4.1.1. g_appGuid

2.4.1.2. g_handlerGuid

2.4.1.3. g_page

2.4.1.4. g_action

2.4.2. g_context

The current processing context.

Snippet

g_context
Interface IProcessingContext

2.4.3. g_ctx

BPEE processing context - only available in the context of a web service.

Snippet

g_ctx

2.4.4. g_dataCollection

The page that serves as a portlet or the DataCollection, which is then loaded.

Example 1

Access a table:
g_dataCollection.getDataRange("<GUID TABLERECORDS>").getNumberOfRecords() > 0

Example 2

Access a data record:
g_dataCollection.getValueHolder(String p_guid)

Snippet

g_dataCollection

2.4.5. g_dbConnections

Access available database connections.

Snippet

//System connection 
def conn = g_dbConnections.systemConnection

//External data connection
def connForeign = g_dbConnections["CONNECTION_NAME"]
Class GroovyContextConnections

2.4.6. g_dbQuery

Object for generating and performing database queries.

Snippet

//Prepared statement structure
def stmt = g_dbQuery.prepare(conn, "SELECT * FROM MYTABLE WHERE LID = ?")
stmt.setInt(1, iLid)
stmt.executeQuery()
stmt.close()

//Query a single value
def iMax = g_dbQuery.executeAndGetScalarValue(conn, "SELECT MAX(LID) FROM MYTABLE", 0)
Class DbQuery

2.4.7. g_defaultLanguage

Returns the current default portal language.

Snippet

assert g_defaultLanguage == 'en' : 'This script requires default language en.'

2.4.8. g_defaultLocaleId

Snippet

g_defaultLocaleId

2.4.9. g_dirWorkflow

Only available in processes - returns the directory of the current process. This directory should be read-only.

Snippet

g_dirWorkflow
Class File

2.4.10. g_dirWorkflowTmp

Access the process's temporary working directory on the server. The directory is available to all subsequent process elements until the process is ended.

Snippet

g_dirWorkflowTmp
Class File

2.4.11. g_event

Only available in processes - contains event that triggered the current workflow. Please note: comparisons to the current event (see script example) should always be performed to interfaces and never with specific classes.

Snippet

import de.uplanet.lucy.server.workflow.event.*

if (g_event instanceof IGlobalTimerWorkflowEvent)
	//Insert script that responds to the timer event
Interface IWorkflowEvent

2.4.12. g_fileScript

The path of the current script as a java.io.File. This object is not available in the context of a web service.

Example

println("Executing " + g_fileScript.path)

Snippet

g_fileScript
Class File

2.4.13. g_exception

Contains the exception that was caught. This needs to be examined so the ErrorHandler can decide whether it is responsible 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 (starts with "my-custom-prefix", for example). See the readme.txt and handler_50_xxx.groovy.example portal directory internal/system/vm/html/errorhandler/custom for more information.

Snippet

g_exception
Class ExceptionUtil

2.4.14. g_guidSelf

Contains the GUID of the current process object (action, condition or event handler). This variable is only available in processes.

Snippet

g_guidSelf

2.4.15. g_guidWf

Contains the GUID of the current process. This variable is only available in processes.

Snippet

g_guidWf

2.4.16. g_i18n

Access language constants.

Snippet

g_i18n
Class GroovyLanguageConstants

2.4.17. g_json

Snippet

g_json
Class GroovyJSON

2.4.18. g_language

This variable contains the current language of the current user.

Snippet

g_language

2.4.19. g_localeId

Snippet

g_localeId

2.4.20. g_log

Writes the entry in the log file that belongs to the processing context of the script.

Snippet

g_log.info("Process was performed without errors.")
g_log.error("An error has occurred.")
Logging

2.4.21. g_mutexSelf

Synchronizes with the surrounding process object (action, condition or event handler). This variable is only defined in processes.

Snippet

g_mutexSelf
Synchronized script block

2.4.22. g_om

Object for accessing the user management.

Snippet

g_om
g_om Details

2.4.22.1 Details

Intrexx provides a wide range of extended options for process-controlled user management. With access objects and methods, new users, among other things, can be created and managed in Groovy actions. The globally available, pre-initialized object "g_om" serves as an entry point for the portal organizational structure in processes. With this object, principle use cases such as searching for a user or generating a new password can be implemented. These methods can be used as "normal" method calls. Examples:
// Change the password of the stated user.
g_om.changePassword(g_session.user, "SECRET")
// Generate and send a new password to the stated user.
g_om.generateAndSendPassword(g_session.user)
// Get a user using a GUID.
def user = g_om.getUser("C10579449052F85D9C3FF3C2824348FCE020A22E")
// Classify a list of GUIDs. A list with GUIDs can
// be transferred or a text (e.g. content of a multiple selection data field).
def guids = ["AE39A904172F5867DA23DE289D1D6B7967420DC0", "6AA80844C3C99EF93BF4536EB18605BF86FDD3C5", g_session.user.guid]
			 
def classified = g_om.classifyGuids(guids) //guids = Collection or String

//The result is a map with the categorized GUIDs.
//e.g. {containers=[], users=[7312F993D0DA4CECCA9AE5A9D865BE142DE413EA], 
//      unclassified=[AE39A904172F5867DA23DE289D1D6B7967420DC0], 
//      sets=[6AA80844C3C99EF93BF4536EB18605BF86FDD3C5]}
println(classified)

//Additional filters for specific object types
println(classified.users)
println(classified.containers)
println(classified.sets)
println(classified.unclassified)

//Returns the number of non-anonymous sesssions
g_om.getNonAnonymousActiveSessionCount()
In addition, the object "g_om" has access to more methods that can be called in conjunction with a closure to implement subsequent actions. These methods can be recognized by the stated parameter in the JavaDocs with the type "groovy.lang.Closure", such as "GroovyOrgBuilder.createUser(groovy.lang.Closure p_closure)". Within such a closure, methods of any class can be called that are documented in each of the defined links. The following methods can be called with a closure:
g_om.createUser(groovy.lang.Closure p_closure)
A new Intrexx user can be created with this. At the same time, the properties listed below can be set within the closure. The properties "name" and "loginName" are mandatory and the others are optional.

PropertyData type
birthdayDate
cityString
containerObject
countryString
defaultLanguageString
defaultLayoutString
deletableBoolean
deletedBoolean
descriptionString
disabledBoolean
dnString
emailBizString
emailHomeString
employeeNoString
enterDateDate
externalLogin1String
externalLogin2String
externalLogin3String
externalPassword1String
externalPassword2String
externalPassword3String
externalPrimaryGroupIdInteger
femaleBoolean
firstNameString
fullNameString
genderInteger
guidString
idInteger
internalUsnInteger
lastNameString
loginDomainString
loginDomainLwrString
loginNameString
loginNameLwrString
maleBoolean
memberOfCollection<?>
middleNameString
nameString
passwordString
passwordChangedDateDate
passwordExpiresBoolean
passwordHashString
phoneBizString
phoneFaxString
phoneHomeString
phoneMobileBizString
phoneMobileHomeString
phonePagerString
poBoxString
postalCodeString
priorityInteger
rplGuidString
saltString
showUserboolean
stateString
streetString
timeZoneTimeZone
titleString
userImageContentTypeString
userImageFileFile
userImageMetaInfoString

For the properties "container" and "memberOf", you can choose whether to enter the GUIDs or the unique names of the containers, roles, sets, groups and paths in the organizational structure.

Example

g_om.createUser {
	name      = "g_om"
	loginName = "g_om"
	birthday  = now()
	container = "0F8233A39555B28F6B32CFFE666A5151E1F41AD3"
	memberOf = ["8FBF199EE826D16742F0F131E0AB4CF0E6BA6CA3", "Users"]
	emailBiz  = "g_om@example.org"
	guid      = newGuid()
	male      = true
}
g_om.getLoggedOnUsers(boolean p_bIncludeAnonymous, groovy.lang.Closure p_closure)
Returns all currently logged-in users. "p_bIncludeAnonymous" allows you to define whether anonymous sessions should be included in the result. Additional filters can be applied via 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 without double entries. Additional filters can be applied via the Groovy closure in the same way as "g_om.getLoggedOnUsers(boolean p_bIncludeAnonymous, groovy.lang.Closure".
g_om.withOrgStructure(groovy.lang.Closure p_closure)
Allows you to work in the portal 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()
Generates a list of the GUIDs of all users that belong to a specific or multiple groups.

Example

def userGuids = g_om.getMembers(["00A303288634E154D755732E478F2BE0D9AD36F7"], false)*.guid
"00A303288634E154D755732E478F2BE0D9AD36F7" is the GUID of the group copied from the from the Users module. Multiple group GUIDs or set GUIDs can be entered. More information is available here:

https://docs.intrexx.com/intrexx/version/9400/api/groovy/jdk/de/uplanet/lucy/server/usermanager/groovy/GroovyOrgBuilder.html#getMembers(java.lang.Object,boolean)
https://docs.intrexx.com/intrexx/version/9400/api/groovy/jdk/de/uplanet/lucy/server/usermanager/groovy/GroovyOrgBuilder.html#getMembers(java.util.Collection,boolean)

Class GroovyOrgBuilder

2.4.23. g_permissions

This class is intended to check and query permissions. The usage is demonstrated in the template "JSON response" for the corresponding use case. checkPermission(Permission) and check(Closure) check whether the desired permissions have been granted. Otherwise, a java.security.AccessControlException is thrown. hasPermission(Permission) and has(Closure) function in the same way but return a Boolean value that states whether the requested permissions have been granted or not. The closure methods delegate to the above-mentioned GroovyIxAccessControllerDelegate object and demand a map that assigns actions to the object names.

Example

Check application permissions for the application <application GUID>, read permission for the data group <data group GUID> and write permission for the data group <another data group GUID>.
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

2.4.24. g_portal

Object for accessing portal properties such as name or base URL.

Example

def strUrl = g_portal.baseUrl

Snippet

g_portal
Class GroovyPortalInfo

2.4.25. g_portlet

Access the respective portlet that should be filtered (in the portlet pool or when rendering the portlet).

Snippet

g_portlet
Class GroovyPortlet

2.4.26. g_portletPool

Access the portlet pool that should be filtered (collection of portlets), on the one hand really in the portlet pool and on the other hand when rendering the portlet.

Snippet

g_portletPool
Class GroovyPortlet

2.4.27. g_record

Access the current data record.

Example

def iLid = g_record["0D8F13B2B43B128DB23C0C1CC8C5DC1143C9D826"].value // datafield (PK) (S) ID

Snippet

g_record
Class ReadOnlyGroovyRecord

2.4.28. g_rwRecord

Read and write access to the current data record. Can only be used within Groovy PageActionHandlers.

Example

def iLid = g_rwRecord["0D8F13B2B43B128DB23C0C1CC8C5DC1143C9D826"].value // datafield (PK) (S) ID

Snippet

g_rwRecord
Class ReadWriteGroovyRecord

2.4.29. g_request

Access the current request, e.g. to read request variables in the process. This variable is only defined if the script was called through a web request.

Snippet

g_request
Class GroovyServerBridgeRequest

2.4.30. 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
Class GroovyRtCache

2.4.31. g_session

The current session.

Example

//Name of the currently logged-in user
def strUserName = g_session?.user?.name

Snippet

g_session
Class GroovySession

2.4.32. g_sharedState

sharedState where variables and values can be written and read later.

Example

//Write variable to sharedState
g_sharedState.myVariable = "My value"
//Read variable from sharedState
def strValue = g_sharedState.myVariable

Snippet

g_sharedState
Class SharedState

2.4.33. g_springApplicationContext

Spring application context.

Snippet

g_springApplicationContext
Interface ApplicationContext

2.4.34. g_sysDg

With this object, values can be read from a system data group.

Example

//Replace the GUID with the GUID of the system data field
def strValue            = g_sysDg['C1BFDD165EBFD0713D306D3E2B124E80021E613F']
def strValueByFieldGuid = g_sysDg.getValueByFieldGuid('C1BFDD165EBFD0713D306D3E2B124E80021E613F')
def vhByFieldGuid       = g_sysDg.getValueHolderByFieldGuid('C1BFDD165EBFD0713D306D3E2B124E80021E613F')

Snippet

g_sysDg
Class GroovySystemDataGroup

2.4.35. g_syslog

Logging object for writing to the portal log file (portal.log).

Snippet

g_syslog.info("My message for portal.log.")

2.4.36. g_ws

Object for explicitly calling a web service. Only available in scripts that are defined in a web service.

Snippet

//Call web service in a script
g_ws.invoke()

2.5. Closures

The predefined closures can be called in the same way as functions.

2.5.1. checkInterrupted()

Checks whether either Use this call in scripts that should behave cooperatively in such cases.

Snippet

checkInterrupted()
Class CheckInterruptedClosure

2.5.2. createTemporaryDirectory()

Generates a temporary working directory that is available until the process has ended.

Snippet

createTemporaryDirectory()
Class CreateTemporaryDirectoryClosure

2.5.3. currentTimestamp()

This closure returns the timestamp of the current transaction. This value is not changed until the transaction has finished being processed.

Example

def dtNow = currentTimestamp()

Snippet

currentTimestamp()
Class CurrentTimestampClosure

2.5.4. getStackTraceString()

Returns the entire StackTrace of an occurred error as a string. The closure "getStackTraceString()" requires a parameter with the type java.lang.Throwable, i.e. an exception.

Snippet

try
{
	trySomething()

}
catch (e)
{
	def strStackTrace = getStackTraceString(e)

	doSomethingWithStackTrace(strStackTrace)
}
Class CreateStackTraceStringClosure

2.5.5. newGuid()

Generates a new GUID.

Snippet

newGuid()
Class NewGuidClosure

2.5.6. now()

Generates a new date (now) as a timestamp or ValueHolder.

Snippet

now()
Class NowClosure

2.5.7. parseGuids(strText)

Parses GUIDs from the transferred string (e.g. as a pipe-separated list) and returns a TreeSet with the found GUIDs.

Snippet

def strText = "18CC231E0A71F6F27091855C4C0FD0D6F2F26038||D0CACC8058DC36A9A499AB2DD3B993F427AB9200"
def guids   = parseGuids(strText)
guids.each {println it}
Class ParseGuidsClosure

2.5.8. vh()

Generates a new ValueHolder from the transferred object.

Snippet

def vhTest = vh("Hello world!")
def vhInt  = vh(1000)
Class CreateValueHolderClosure

2.6. Databases

2.6.1. Data groups

2.6.1.1. Find data group via GUID

Example

How to identify the name of a data group:
def strName = g_rtCache.dataGroups["C399FB1F398D76E91BC7DC679E1E4DDB9F5CEB9C"].name

Snippet

def strName = g_rtCache.dataGroups["<Data group GUID>"].name
Interface DataGroupInfo

2.6.1.2. Reference data group in SQL via GUID

So that you don't have to use a static data group name in SQL statements, thus avoiding problems when importing or making changes to the data group, a data group can be referenced using its GUID instead of its name with the aid of this client function. This is only available via the Intrexx database API.

Example

g_dbQuery.executeAndGetScalarValue(conn, "SELECT COUNT(LID) FROM DATAGROUP('DAF7CECF66481FCABE50E529828116EAFE906962')")

Snippet

def strName = g_rtCache.dataGroups["<Data group GUID>"].name
Interface DataGroupInfo

2.6.1.3. Get all column names of a data group

Returns a list of column names from the data group with the stated GUID.

Snippet

def fieldNames = g_rtCache.fields.findAll{it.dataGroupGuid == "DG-GUID"}*.columnName
Interface FieldInfo

2.6.2. Intrexx database API

2.6.2.1. Prepared statement with SELECT

Executes a SELECT statement as a prepared query. Afterwards it is iterated over 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)
}
Class DbPreparedStatement

2.6.2.2. Prepared statement with INSERT

Executes an INSERT statement as a prepared query.

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)
}
Class DbPreparedStatement

2.6.2.3. Prepared statement with INSERT (with closure)

Executes an INSERT statement with a closure as a prepared query.

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 should be used multiple times, e.g. within a loop, the prepared statement version 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)
}
Class DbQuery

2.6.2.4. Prepared statement with UPDATE

Executes an UPDATE statement as a prepared query.

Example

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)

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)
Class DbPreparedStatement

2.6.2.5. Prepared statement with UPDATE (with closure)

Executes an UPDATE statement with a closure as a prepared query.

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 should be used multiple times, e.g. within a loop, the prepared statement version 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)
}
Class DbQuery

2.6.2.6. Prepared statement with DELETE

Executes a DELETE statement as a prepared query.

Example

def conn = g_dbConnections.systemConnection
def stmt = null


stmt = g_dbQuery.prepare(conn, "DELETE FROM DATAGROUP('7AFAF7CB5DE281D35F05D96FCD96CE27692C110F') WHERE ID > ?")

stmt.setInt(1, 5)
stmt.executeUpdate()
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)
}
Class DbPreparedStatement

2.6.2.7. Prepared statement with DELETE (with closure)

Executes a DELETE statement with a closure as a prepared query.

Example

def conn = g_dbConnections.systemConnection

g_dbQuery.executeUpdate(conn, "DELETE FROM DATAGROUP('7AFAF7CB5DE281D35F05D96FCD96CE27692C110F') WHERE ID > ?"){

	setInt(1, 5)
}
Please note: If the statement should be used multiple times, e.g. within a loop, the prepared statement version 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)
Class DbPreparedStatement

2.6.2.8. Read a single value from a database query

Reads a single value from a database query. If the result set is empty, or the value is null, the fallbackValue is returned. If the return data type value should be defined explicitly, typified method calls such as executeAndGetScalarBooleanValue(...) can be used.

Example

def value = g_dbQuery.executeAndGetScalarValue(conn, "SELECT MAX(ID) FROM DATAGROUP('7AFAF7CB5DE281D35F05D96FCD96CE27692C110F')", 0)
or with a prepared statement
def value = g_dbQuery.executeAndGetScalarValue(conn, "SELECT MAX(ID) FROM DATAGROUP('7AFAF7CB5DE281D35F05D96FCD96CE27692C110F') WHERE DTEDIT < ?", 0) {
setTimestamp(1, now().withoutFractionalSeconds)

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.")
}
Class DbQuery

2.6.2.9. Read a single value using a prepared database query

Reads a single value using a prepared database query. If the result set is empty, or the value is null, the fallbackValue is returned. If the return data type value should be defined explicitly, typified method calls such as executeAndGetScalarBooleanValue(...) can be used.

Example

def stmt = g_dbQuery.prepare(conn, "SELECT MAX(LID) FROM DATAGROUP('7AFAF7CB5DE281D35F05D96FCD96CE27692C110F')")

def value = stmt.executeAndGetScalarValue(0)

stmt = Safely.close(stmt)

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)
}
Class DbPreparedStatement

2.6.3. JDBC

2.6.3.1. Prepared statement with SELECT

Executes a SELECT statement as a prepared query. Afterwards it is iterated over the results in the result set.

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)
}
Interface PreparedStatement

2.6.3.2. Prepared statement with INSERT

Executes an INSERT statement as a prepared query.

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)
}
Interface PreparedStatement

2.6.3.3. Prepared statement with UPDATE

Executes an UPDATE statement as a prepared query.

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)
}
Interface PreparedStatement

2.6.3.4. Prepared statement with DELETE

Executes a DELETE statement as a prepared query.

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)
}
Interface PreparedStatement

2.6.4. System data source

System database connection

Example

def conn = g_dbConnections.systemConnection

Snippet

g_dbConnections.systemConnection
Class GroovyContextConnections

2.6.5. External data source

Connection to an external data source. The name to use is the given name of the external connection defined in the Integration module.

Example

def conn = g_dbConnections["ExternalData"]

Snippet

g_dbConnections["<CONNECTION_NAME>"]
Class GroovyContextConnections

2.6.6. Distinguish the type of database

Identifies the type of database.

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 "MySQL":
		// MySQL
		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

2.7. Web services

2.7.1. Execute web service call

Calls the underlying web service. Only valid for scripts defined within a web service.

Snippet

g_ws.invoke()

2.7.2. Read web service input values

Read values defined as input parameters for a web service. Use the name of the control, which contains the value, as the variable name.

Example

g_ctx.requestVars.textcontrolD72A9620

Snippet

g_ctx.requestVars.

2.7.3. Read web service response values

Read values defined as response parameters from a web service. Use the name of the control, where the response value will be written, as the variable name.

Example

g_ctx.bpeeVars.textvcontrol72EF4A0B.value

Snippet

g_ctx.bpeeVars..value

2.8. Case differentiation

2.8.1. switch statement for Groovy condition

Usable in processes. The returned values correspond to the outgoing connections (connection ID) of the Groovy condition.

Snippet

switch (g_record[""].value)
{
	case "expected value 1":
		return connectionId1
	case "expected value 2":
		return connectionId2
	default:
		return connectionId3
}
switch / case

2.8.2. switch statement for data group events

Usable 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
}
Interface IWorkflowEvent

2.8.3. Records from global data group timers

Distinguish the first record from the subsequent records that are delivered by a global data group timer.

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
}

2.9. Mathematical calculations

2.9.1. Round half away from zero

Round half away from zero with the option of defining 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)
Class Math

2.9.1. Round to even

Round to even with the option of defining 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)
Class Math

2.10. Date / Time

2.10.1. Formatting date values

Here you can find 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))
Class SimpleDateFormat

2.10.2. Duration in days

A data record contains data for a start and an end date. The duration between these two date values is calculated. Please note that time zones are not considered.

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()
}

2.10.3. Parse ISO date string

Parses an ISO formatted string into an "java.util.Date" object.

Example

def isoUtil           = ISODateTimeUtil.newInstance()
def strDate        = "2013-01-01T12:00:01Z"
def strDateMillis = "2013-01-01T15:00:01.000Z"

def dtDate1 = isoUtil.parseISODateTime(strDate)
def dtDate2 = isoUtil.parseISODateTimeMillis(strDateMillis)
def dtDate3 = isoUtil.parseISODateTimeOptionalMillis(strDate)
def dtDate4 = isoUtil.parseISODateTimeOptionalMillis(strDateMillis)

Snippet

import de.uplanet.util.ISODateTimeUtil

def isoUtil = ISODateTimeUtil.newInstance()
def dtDate  = isoUtil.parseISODateTimeOptionalMillis("<DATE_ISO_STRING>")
Class ISODateTimeUtil

2.10.4. Parse date to ISO string

Formats a date object as an ISO string.

Example

def isoUtil = ISODateTimeUtil.newInstance()
println isoUtil.formatISODateTime(currentTimestamp())
println isoUtil.formatISODateTimeMillis(currentTimestamp())

Snippet

import de.uplanet.util.ISODateTimeUtil

def isoUtil = ISODateTimeUtil.newInstance()
isoUtil.formatISODateTime(currentTimestamp())
Class ISODateTimeUtil

2.10.5. Now as timestamp

Snippet

now().withoutFractionalSeconds
Class ChimeraDate

2.10.6. Timestamp for system values

This closure returns the timestamp of the current transaction. This value remains unmodified until the end of this transaction.

Snippet

currentTimestamp()
Class CurrentTimestampClosure

2.11. Email

2.11.1. 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()

2.11.2. Groovy email

Create an HTML email with inline images and attachment.

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()

2.11.3. Send email via Ant

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}
""")
}

2.12. Files and directories

2.12.1. Identify disk space

Identifies the free and total disk space.

Snippet

// the partition where the Intrexx portal is stored
File partition = new File(".")

long totalSpace = partition.totalSpace
long freeSpace = partition.freeSpace
Class File

2.12.2. The directory of the current workflow

Returns the directory of the current process. This directory should be read-only.

Snippet

g_dirWorkflow
Class File

2.12.3. Temporary workflow directory

Access a temporary workflow directory. The directory is also available to subsequent workflow objects. It is deleted as soon as the workflow has been fully executed.

Snippet

g_dirWorkflowTmp
Class File

2.12.4. 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)
}
Class File

2.12.5. Add file to data record

Add a file to an existing record. With "copyFileToIntrexx(...)" the source file is copied and remains at its storage location. An analog call can be made with "moveFileToIntrexx(...)". In this case, the source file will be moved to Intrexx.

Parameters:
p_ctx - Current processing context (g_context)
p_fileSrc - File to be added to record
p_strFieldGUID - Data field GUID
p_recId - ID of record that the file should be added to
p_bTriggerWorkflow - Should a workflow be triggered that responds to data record changes?

Example

FileUCHelper.copyFileToIntrexx(g_context, fileInput, "0B5CFF839F946923DBB0D92F39BB5D79BEC8D94C", g_record.recId,  false)

Snippet

import de.uplanet.lucy.server.businesslogic.util.FileUCHelper
FileUCHelper.copyFileToIntrexx(g_context, p_fileSrc, p_strFieldGuid, p_recId, p_bTriggerWorkflow) 
Class FileUCHelper

2.12.6. Remove file from data record

Deletes a file from a record.

Parameters:
p_ctx - Current processing context (g_context)
p_strFieldGUID - Data field GUID
p_recId - ID of record where the file should be deleted

Example

FileUCHelper.deleteFileFromIntrexx(g_context, "0B5CFF839F946923DBB0D92F39BB5D79BEC8D94C", g_record.recId)

Snippet

import de.uplanet.lucy.server.businesslogic.util.FileUCHelper
FileUCHelper.deleteFileFromIntrexx(g_context, p_strFieldGuid, p_recId) 
Class FileUCHelper

2.12.7. Read text file

Reads the content of a text file with the stated encoding. Do not use for large volumes of data.

Snippet

def fileIn     = new File("<FILE_NAME>")
def strContent = fileIn.getText("UTF-8")
Class File

2.12.8. Read text file line by line

Reads the content of a text file line by line with the stated encoding.

Snippet

def fileIn     = new File("_in.txt")
fileIn.eachLine("UTF-8") {line ->
	//process line
}
Class File

2.12.9. Write to text file

Writes a text output to a file with the stated 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
}
Class File

2.13. Session/User

2.13.1. Name of the current user

Snippet

g_session?.user?.name
Interface IUser

2.13.2. Email address of the current user

Snippet

g_session?.user?.emailBiz
Interface IUser

2.13.3. Anonymous session or not?

Snippet

g_session?.anonymous
Class GroovySession

2.13.4. Access the organizational structure

Snippet

g_om.getOrgStructure()
g_om - Details

2.13.5. Logged-in users

Get a list of all non-anonymous logged-in users.

Snippet

de.uplanet.lucy.server.portalserver.LoggedOnUsers.getLoggedOnUsersDistinct()

2.13.6. Set new password for user

Sets a new password for the stated user.

Snippet

g_om.changePassword(user, password)
Class GroovyOrgBuilder

2.14. User management

2.14.1. Create user (basic)

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}"
}

2.14.2. Create a user

Snippet

/ provide copy of 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)

2.14.3. Classify GUIDs

Classify GUIDs by

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

2.15. Categories

2.15.1. Date / Time

Snippet

use (groovy.time.TimeCategory)
{
	
}	

2.15.2. IValueHolder

Snippet

use (de.uplanet.lucy.server.scripting.groovy.GroovyIntrexxValueHolderCategory)
{
	
}
Class GroovyIntrexxValueHolderCategory

12.16. Info

12.16.1. 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)

12.16.2. Intrexx version

Returns the Intrexx installation version.

Snippet

de.uplanet.lucy.VERSION.CURRENT.toFormattedString()
Class Version

2.17. Error handling and debugging

2.17.1. Stacktrace as string

Snippet

getStackTraceString()

2.17.2. Groovy context

Snippet

def dumpBinding = {
	def sbuf = new StringBuilder()

	sbuf << "Dump the Groovy binding:\n"

	binding.variables.each { k, v ->
		if (v && v.metaClass.respondsTo(v, "dump"))
			sbuf << "${k} = ${v.dump()}\n"
		else
			sbuf << "${k} = ${v.toString()}\n"
	}

	sbuf.toString()
}

g_log.info(dumpBinding())

2.17.3. Define an error handler for a script

Usable in

Snippet

onError = { exception, err ->
	err.title = ""
	err.description = "Insert your description here. ${exception.message}"
}

2.18. Groovy server scripts

2.18.1. JSON response

Please note that a permissions check (IxAccessController) is required before any action that is triggered by a user.

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 = "http://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 above

Closure without or with exactly one parameter

If the closure declares a parameter, the exception that occurred is transferred 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 exception that occurred is transferred to the closure in the first parameter (e) and a ErrorResponseData object is transferred in the second parameter (err). The ErrorResponseData object can be configured in the closure according to the respective requirements.

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 = "http://www.example.org/"
    // err.redirectDelay = 1500 // milliseconds
}

With a string

The stated string is sent to the client in the response body.

Snippet

response.onError = '{"error": "Something bad happened."}'

Assign another object

In a JSON response scenario, an attempt is made to generate JSON from the object. If the response is not JSON, an attempt is made to output the object in a suitable manner as text.

Snippet

response.onError = [
    "error": "Something bad happened.",
    "solace": "But things could be worse."
]

12.19. Velocity

2.19.1. Create text from a 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())

2.19.2. Create a file from a Velocity template

For security reasons, Velocity files can only be executed if they are stored in one of the following subfolders:

2.20. Request variable

2.20.1. g_request.get(...)

Snippet

g_request.get("")
Class GroovyServerBridgeRequest

2.20.2. rq_Lang

Returns the language the logged-in user is currently using.

Snippet

rq_Lang

2.20.3. REMOTE_ADDR

IP address of the client computer.

Snippet

REMOTE_ADDR

2.20.4. SERVER_PORT

Snippet

SERVER_PORT

2.20.5. HTTP_HOST

Snippet

HTTP_HOST

2.20.6. HTTP_REFERER

Snippet

HTTP_REFERER

Snippet

HTTP_COOKIE

2.20.8. HTTP_USER_AGENT

Snippet

HTTP_USER_AGENT

2.20.9. SCHEME

HTTP or HTTPS

Snippet

SCHEME

2.21. Images

2.21.1. Scale an 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>)
Class ImageHelper

2.21.2. Determine the size of an image

A file object or a path as a character string can be transferred as parameters.

Snippet

import de.uplanet.lucy.server.scripting.groovy.ImageHelper

def (x, y) = ImageHelper.getImageSize()
Class ImageHelper

2.21.3. Iterate over image metadata

Here is an example of metadata extraction.

Snippet

import de.uplanet.lucy.server.scripting.groovy.ImageHelper

def file = 

ImageHelper.getImageMetaData(file).each { tag, value ->
	println("$tag -> $value")
}
Class ImageHelper

2.22. Logging

2.22.1. Write info to the portal log

Writes an INFO log entry to the portal log file (portal.log). This method can be used if the log file of the current processing context is not portal.log, but portal.log should be used.

Snippet

g_syslog.info("")
Class GroovyLogger

2.22.2. Write info to the workflow log

Writes an INFO log entry to the log file associated with the scripts processing context.

Snippet

g_log.info("")
Class GroovyLogger

2.22.3. Write warning to the portal log

Writes a WARN log entry to the portal log file (portal.log). This method can be used if the log file of the current processing context is not the portal.log, but portal.log should be used.

Snippet

g_syslog.warn("")
Class GroovyLogger

2.22.4. Write warning to the workflow log

Writes a WARN log entry to the log file associated with the scripts processing context.

Snippet

g_log.warn("")
Class GroovyLogger

2.22.5. Write error to the portal log

Writes an ERROR log entry to the portal log file (portal.log). This method can be used if the log file of the current processing context is not the portal.log, but portal.log should be used.

Snippet

g_syslog.error("")
Class GroovyLogger

2.22.6. Write error to the workflow log

Writes an ERROR log entry to the log file associated with the scripts processing context.

Snippet

g_log.error("")
Class GroovyLogger

2.22.7. Read the 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}")
	}
}

2.23. Connector for Microsoft Exchange

2.23.1. 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)
Class ExchangeConnectionUtil

2.23.2. Mailbox name of the current Exchange user

Returns the mailbox name of the current Exchange user.

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
Class ExchangeUserMailboxInfo

2.23.3. Save email locally as an EML file

Saves an email locally as an EML file. Alternatively, saveMessageAsMSG can be used to save an email as a MSG file.

Parameters:

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

2.23.4. Save email attachments

Save attachments of an 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)
}
Interface IExchangeItemUtil

2.23.5. Set out-of-office message

Defines the out-of-office message and sets its status to active.
Caution: The given text is set as the internal and external out-of-office 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

2.23.6. Get folder information

Gets information about a folder from 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())
Interface IFolderInfo

2.23.7. Create folder

Create an Exchange folder (in this example in the default inbox folder)

Parameters:

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

2.23.8. Add attachment to an element

Adds an attachment to an existing item (e.g. an appointment).

Parameters:

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)
Interface IExchangeItemUtil

2.23.9. Create an Exchange appointment

Creates an appointment for the current Exchange user.

Parameters: If additional properties are set or updated with set()-methods after creating the appointment, they have to be saved with appointment.save() afterwards.

Example

def appointment = aptUtil.createNewAppointment(dtStartDate, dtEndDate, strSubject, strBody)

appointment.setLocation("Meeting room")
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

2.23.10. Create an Exchange contact

Creates a contact for the current user.

Parameters: If additional properties are set or updated with set()-methods after creating the contact, they have to be saved with contact.save() afterwards.

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

2.23.11. Create and send Exchange email

Creates a new email for the current Exchange user.

Parameters: If additional properties are set or updated with set()-methods after creating the message, they have to be saved with message.save() afterwards.

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

2.23.12. Create an Exchange note

Creates a note for the current user.

Parameters:

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)
Interface IExchangeNoteUtil

2.23.13. Create an Exchange task

Creates a task for the current user.

Parameters:

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)
Interface IExchangeTaskUtil

2.24. WebSockets

2.24.1. 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>")
Class GroovyWebSocketTopic

2.24.2. 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)
Class GroovyWebSocketTopic

2.25. Check for an interrupt request

checkInterrupted()
Checks whether either Use this call in scripts that should behave cooperatively in such cases.

Snippet

checkInterrupted()
Class CheckInterruptedClosure

2.26. Start a scheduler job

Input parameter: the ID or GUID of the job.

Snippet

de.uplanet.lucy.server.scheduler.JobStarter.startJob("")

2.27. Run an external program

Runs an external program. Click here for more information.

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())
}

2.28. Create a new GUID

Generates a new GUID.

Snippet

newGuid()
Class NewGuidClosure

2.29. Check GUID

Checks whether a specified string is a GUID in Intrexx terms. If the transferred value is null, the method returns false.

Snippet

Guid.isStringRepresentation()
Class Guid

2.30. Synchronized script block

Synchronizes with the surrounding process object (action, condition or event handler). This variable is only defined in processes.

Snippet

synchronized (g_mutexSelf)
{
	
}

2.31. Create a ValueHolder

Creates a ValueHolder for a simple data type.

If null is transferred, a NullValueHolder will be created. Its value is null, and hasValue() is false.

Snippet

vh()

2.32. Parse GUIDs

Parse GUIDs from textual input. Multiple parameters are possible.

Snippet

parseGuids()

2.33. Determining the time zone of the portal

Here you find script for determining the default time zone, which is set in the portal properties in the regional settings.

Snippet

import  de.uplanet.lucy.server.DefaultTimeZone
def tz = DefaultTimeZone.get()
Class DefaultTimeZone