General Guidelines

Transforming Attributes

If you create a groovy script, please take care of the following note.

Never modify mapping in a transformation!

Example:

The mapping is shared between the attribute transformations. If the groups attribute is used in another transformation after this one, it sees the modified group list.

def groups = mapping.get("groups")
groups.remove("someGroup")
GROOVY

Solution:

Explicitly copy the groups into a new list to mess around with.

def groups = []
groups.addAll(mapping.get("groups").asStringList())
groups.remove("someGroup")
CODE

Safe dereferencing

When a reference doesn’t point to any specific object, its value is null. When calling a method or accessing a field on a null reference, a NullPointerException (NPE) is thrown. This is useful to protect code from working on undefined preconditions, but it can easily get in the way of “best effort” code that should be executed for valid references and just be silent otherwise.

a.b.c  → If b is null, this will throw an error.

Solution: a.b?.c → if b is null, this will just return null

Example: 

return existing.ATTR_EMAIL
//if ATTR_EMAIL is NULL, this will throw an error
GROOVY

Solution:

return existing?.ATTR_EMAIL
//this will NOT fail if ATTR_EMAIL is NULL
GROOVY

Elvis operator

This is handy for returning a 'sensible default' value if an expression resolves to false-ish (i.e. when a value is null).

a ?: "replacement"  → returns "replacement if a is null

Example: 

displayName = con.user.name ?: 'Anonymous'
//displayName will have the value of con.user.name, but if con.user.name is NULL, then displayName will have the default value 'Anonymous' instead
GROOVY