Groovy

1. General

With Groovy script, you can expand the functionality of Intrexx. Click here for more information about where the Groovy script editor can be found and used in the Intrexx Portal Manager. The following links provide additional helpful information about using Groovy in Intrexx:
The corresponding, sufficient programming knowhow is required to use Groovy in Intrexx. Please note that United Planet is not liable for errors, loss of data or security flaws that arise as a result of incorrect Groovy scripts.

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.
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.
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.
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.
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.
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.
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.
def ref = g_rtCache.references["<GUID der Referenz>"]
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).
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.
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.
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.
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.
import de.uplanet.lucy.server.security.IxAccessController
Class IxAccessController

2.3.2. IFilter

import de.uplanet.util.filter.IFilter
Interface IFilter<T>

2.3.3. WorkflowException

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

2.4. Obects 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.
g_context
Interface IProcessingContext

2.4.3. g_ctx

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

2.4.4. g_dbConnections

Access available database connections.
//System connection 
def conn = g_dbConnections.systemConnection

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

2.4.5. g_dbQuery

Object for generating and performing database queries.
//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.6. g_defaultLanguage

Returns the current default portal language.
assert g_defaultLanguage == 'en' : 'This script requires default language en.'

2.4.7. g_dirWorkflow

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

2.4.8. 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.
g_dirWorkflowTmp
Class File

2.4.9. 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.
import de.uplanet.lucy.server.workflow.event.*

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

2.4.10. 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)
g_fileScript
Class File

2.4.11. g_guidSelf

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

2.4.12. g_guidWf

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

2.4.13. g_i18n

Access language constants.
g_i18n
Class GroovyLanguageConstants

2.4.14. g_language

This variable contains the current language of the current user.
g_language

2.4.15. g_log

Writes the entry in the log file that belongs to the processing context of the script.
g_log.info("Process was performed without errors.")
g_log.error("An error has occurred.")
Logging

2.4.16. g_mutexSelf

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

2.4.17. g_om

Object for accessing the user management.
g_om
g_om Details

2.4.17.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()
Class GroovyOrgBuilder

2.4.18. g_portal

Object for accessing portal properties such as name or base URL.
Example: def strUrl = g_portal.baseUrl
g_portal
Class GroovyPortalInfo

2.4.19. g_record

Access the curren data record.
Example: def iLid = g_record["0D8F13B2B43B128DB23C0C1CC8C5DC1143C9D826"].value // datafield (PK) (S) ID
g_record
Class ReadOnlyGroovyRecord

2.4.20. 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
g_rwRecord
Class ReadWriteGroovyRecord

2.4.21. 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.
g_request
Class GroovyServerBridgeRequest

2.4.22. 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"}
g_rtCache
Class GroovyRtCache

2.4.23. g_session

The current session.
Example:
//Name of the currently logged-in user
def strUserName = g_session?.user?.name
g_session
Class GroovySession

2.4.24. 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
g_sharedState
Class SharedState

2.4.25. g_springApplicationContext

Spring application context
g_springApplicationContext
Interface ApplicationContext

2.4.26. 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')
g_sysDg
Class GroovySystemDataGroup

2.4.27. g_syslog

Logging object for writing to the portal log file (portal.log).
g_syslog.info("My message for portal.log.")

2.4.28. g_ws

Object for explicitly calling a web service. Only available in scripts that are defined in a web service.
//Call web service in a script
g_ws.invoke()

2.4.29. Closures

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

2.4.29.1. checkInterrupted()

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

2.4.29.2. createTemporaryDirectory()

Generates a temporary working directory that is available until the process has ended.
createTemporaryDirectory()
Class CreateTemporaryDirectoryClosure

2.4.29.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()
currentTimestamp()
Class CurrentTimestampClosure

2.4.29.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.
try
{
	trySomething()

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

	doSomethingWithStackTrace(strStackTrace)
}
Class CreateStackTraceStringClosure

2.4.29.5. newGuid()

Generates a new GUID.
newGuid()
Class NewGuidClosure

2.4.29.6. now()

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

2.4.29.7. vh()

Generates a new ValueHolder from the transferred object.
def vhTest = vh("Hello world!")
def vhInt  = vh(1000)
Class CreateValueHolderClosure

2.4.29.8. parseGuids(strText)

Parses GUIDs from the transferred string (e.g. as a pipe-separated list) and returns a TreeSet with the found GUIDs.
def strText = "18CC231E0A71F6F27091855C4C0FD0D6F2F26038||D0CACC8058DC36A9A499AB2DD3B993F427AB9200"
def guids   = parseGuids(strText)
guids.each {println it}
Class ParseGuidsClosure

2.5. Databases

2.5.1. Data groups

2.5.1.1. Find data group via GUID

Here as an example of how to identify the name of a data group:
def strName = g_rtCache.dataGroups["C399FB1F398D76E91BC7DC679E1E4DDB9F5CEB9C"].name
def strName = g_rtCache.dataGroups["<Data group GUID>"].name
Interface DataGroupInfo

2.5.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')")
def strName = g_rtCache.dataGroups["<Data group GUID>"].name
Interface DataGroupInfo

2.5.1.3. Get all column names of a data group

Returns a list of column names from the data group with the stated GUID.
def fieldNames = g_rtCache.fields.findAll{it.dataGroupGuid == "DG-GUID"}*.columnName
Interface FieldInfo

2.5.2. Intrexx database API

2.5.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)
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.5.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)
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.5.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.
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.5.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)

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.5.2.5. Prepared statement with UPDATE (with closure)

Executes an UPDATE statement with a closure as a prepared query. F├╝hrt eine Prepared statement with einem UPDATE-Statement with closure aus.
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.
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.5.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)
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.5.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.
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.5.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)
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.5.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)
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.5.3. JDBC

2.5.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.
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.5.3.2. Prepared statement with INSERT

Executes an INSERT statement as a prepared query.
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.5.3.3. Prepared statement with UPDATE

Executes an UPDATE statement as a prepared query.
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.5.3.4. Prepared statement with DELETE

Executes a DELETE statement as a prepared query.
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.5.4. System data source

System database connection
Example:
def conn = g_dbConnections.systemConnection
g_dbConnections.systemConnection
Class GroovyContextConnections

2.5.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"]
g_dbConnections["<CONNECTION_NAME>"]
Class GroovyContextConnections

2.5.6. Distinguish the type of database

Identifies the type of database
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.6. Web services

2.6.1. Execute web service call

Calls the underlying web service. Only valid for scripts defined within a web service.
g_ws.invoke()

2.6.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
g_ctx.requestVars.

2.6.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
g_ctx.bpeeVars..value

2.7. Case differentiation

2.7.1. switch statement for Groovy condition

Usable in processes. The returned values correspond to the outgoing connections (connection ID) of the Groovy condition.
switch (g_record[""].value)
{
	case "expected value 1":
		return connectionId1
	case "expected value 2":
		return connectionId2
	default:
		return connectionId3
}

2.7.2. switch statement for data group events

Usable in processes.
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.7.3. Records from global data group timers

Distinguish the first record from the subsequent records that are delivered by a global data group timer.
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.8. Mathematical calculations

2.8.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
import de.uplanet.util.math.RoundingUtil
RoundingUtil.roundHalfAwayFromZero(, 2)
Class Math

2.8.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
import de.uplanet.util.math.RoundingUtil
RoundingUtil.roundHalfEven(, 2)
Class Math

2.9. Date / Time

2.9.1. 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.
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.9.2. 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)
import de.uplanet.util.ISODateTimeUtil

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

2.9.3. 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())
import de.uplanet.util.ISODateTimeUtil

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

2.9.4. Now as timestamp

now().withoutFractionalSeconds
Class ChimeraDate

2.9.5. Timestamp for system values

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

2.10. Email

2.10.1. Groovy email (simple)

Create a simple text email. 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.10.2. Groovy email

Create an HTML email with inline images and attachment.
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.10.3. Send email via Ant

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.11. Files and directories

2.11.1. Identify disk space

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

long totalSpace = partition.totalSpace
long freeSpace = partition.freeSpace

2.11.2. The directory of the current workflow

g_dirWorkflow

2.11.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.
g_dirWorkflowTmp

2.11.4. Work in a temporary directory

import de.uplanet.io.IOHelper 

File dirTemp = createTemporaryDirectory()

try
{
	
}
finally
{
	IOHelper.deleteFileRecursively(dirTemp)
}

2.11.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)
import de.uplanet.lucy.server.businesslogic.util.FileUCHelper
FileUCHelper.copyFileToIntrexx(g_context, p_fileSrc, p_strFieldGuid, p_recId, p_bTriggerWorkflow) 
Class FileUCHelper

2.11.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)
import de.uplanet.lucy.server.businesslogic.util.FileUCHelper
FileUCHelper.deleteFileFromIntrexx(g_context, p_strFieldGuid, p_recId) 
Class FileUCHelper

2.11.7. Read text file

Reads the content of a text file with the stated encoding. Do not use for large volumes of data.
def fileIn     = new File("<FILE_NAME>")
def strContent = fileIn.getText("UTF-8")

2.11.8. Read text file line by line

Reads the content of a text file line by line with the stated encoding. def fileIn = new File("_in.txt")
fileIn.eachLine("UTF-8") {line ->
	//process line
}

2.11.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)
}
def fileOut = new File("out.txt")

fileOut.withWriter("UTF-8") {out ->
	//write output to  file
}

2.12. Session/User

2.12.1. Name of the current user

g_session?.user?.name
Interface IUser

2.12.2. Email address of the current user

g_session?.user?.emailBiz
Interface IUser

2.12.3. Anonymous session or not?

g_session?.anonymous
Class GroovySession

2.12.4. Access the organizational structure

g_om.getOrgStructure()
g_om - Details

2.12.5. Logged-in users

Get a list of all non-anonymous logged-in users.
de.uplanet.lucy.server.portalserver.LoggedOnUsers.getLoggedOnUsersDistinct()

2.12.6. Set new password for user

Sets a new password for the stated user.
g_om.changePassword(user, password)
Class GroovyOrgBuilder

2.13. User management

2.13.1. Create user (basic)

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.13.2. Create a user

/ 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.13.3. Classify GUIDs

Classify GUIDs by
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.14. Categories

2.14.1. Date / Time

use (groovy.time.TimeCategory)
{
	
}	

2.14.2. IValueHolder

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

12.15. Info

12.15.1. System information

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.15.2. Intrexx version

Returns the Intrexx installation version.
de.uplanet.lucy.VERSION.CURRENT.toFormattedString()

2.16. Error handling and debugging

2.16.1. Stacktrace as string

getStackTraceString()

2.16.2. Groovy context

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.16.3. Define an error handler for a script

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

2.17. Groovy server scripts

2.17.1. JSON response

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

12.18. Velocity

2.18.1. Create text from a Velocity template

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.18.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.19. Request variable

2.19.1. g_request.get(...)

g_request.get("")
Class GroovyServerBridgeRequest

2.19.2. rq_Lang

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

2.19.3. rq_command

rq_command

2.19.4. rq_RecId

rq_RecId

2.19.5. rq_AppGuid

rq_AppGuid

2.19.6. rq_TargetPageGuid

rq_TargetPageGuid

2.19.7. REMOTE_ADDR

IP address of the client computer.
REMOTE_ADDR

2.19.8. SERVER_PORT

SERVER_PORT

2.19.9. HTTP_HOST

HTTP_HOST

2.19.10. HTTP_REFERER

HTTP_REFERER
HTTP_COOKIE

2.19.12. HTTP_USER_AGENT

HTTP_USER_AGENT

2.19.13. SCHEME

HTTP or HTTPS
SCHEME

2.20. Images

2.20.1. Scale an image

Supported formats are PNG, JPEG (JPG), and BMP.
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.20.2. Determine the size of an image

A file object or a path as a character string can be transferred as parameters.
import de.uplanet.lucy.server.scripting.groovy.ImageHelper

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

2.20.3. Iterate over image metadata

Here is an example of metadata extraction.
import de.uplanet.lucy.server.scripting.groovy.ImageHelper

def file = 

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

2.21. Logging

2.21.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.
g_syslog.info("")

2.21.2. Write info to the workflow log

Writes an INFO log entry to the log file associated with the scripts processing context.
g_log.info("")

2.21.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.
g_syslog.warn("")

2.21.4. Write warning to the workflow log

Writes a WARN log entry to the log file associated with the scripts processing context.
g_log.warn("")

2.21.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.
g_syslog.error("")

2.21.6. Write error to the workflow log

Writes an ERROR log entry to the log file associated with the scripts processing context.
g_log.error("")

2.21.7. Read the statistics logs

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.22. Connector for Microsoft Exchange

2.22.1. Current Exchange connection

Returns the current connection to Microsoft Exchange.
import de.uplanet.lucy.server.businesslogic.exchange.util.ExchangeConnectionUtil

def connEx = ExchangeConnectionUtil.getConnectionForWorkflowAction(g_context)
Class ExchangeConnectionUtil

2.22.2. Mailbox name of the current Exchange user

Returns the mailbox name of the current Exchange user.
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.22.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:
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.22.4. Save email attachments

Save attachments of an email defined by strMessageId.
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.22.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.
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.22.6. Get folder information

Gets information about a folder from the Exchange account.
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.22.7. Create folder

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

Parameters:
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.22.8. Add attachment to an element

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

Parameters:
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.22.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()
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.22.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()
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.22.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()
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.22.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)
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.22.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()
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.23. Check for an interrupt request

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

2.24. Start a scheduler job

Input parameter: the ID or GUID of the job.
de.uplanet.lucy.server.scheduler.JobStarter.startJob("")

2.25. Run an external program

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.26. Create a new GUID

Generates a new GUID.
newGuid()
Class NewGuidClosure

2.27. Synchronized script block

Synchronizes with the surrounding process object (action, condition or event handler). This variable is only defined in processes.
synchronized (g_mutexSelf)
{
	
}
Synchronized script block

2.28. 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.
vh()

2.29. GUIDs parsen

Parse GUIDs from textual input. Multiple parameters are possible.
parseGuids()