> For the complete documentation index, see [llms.txt](https://docs.openiam.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.openiam.com/developer-guide/transformation-scripts.md).

# Transformation scripts

Map an inbound synchronisation row onto an OpenIAM user, group or role — the base classes, the return signals, the caches, and an annotated shipped example.

A transformation script maps one inbound row from a source system onto one OpenIAM object.

**Start here if you are new to OpenIAM scripting.** It does one thing, its inputs are simple, and its result is easy to see.

## What this builds, and how long it takes

|                |                                                                                   |
| -------------- | --------------------------------------------------------------------------------- |
| **You get**    | A script that turns rows from a source feed into OpenIAM users, groups or roles   |
| **Time**       | An hour for a first script, including a test synchronisation                      |
| **You need**   | A deployment, a synchronisation configuration, and a source with a few rows in it |
| **Reversible** | Yes — increment the version and the previous script is still there                |

## Before you start

* [*Set up your environment*](/developer-guide/set-up-your-environment.md), so the script compiles before you deploy it.
* [*How scripting works*](/developer-guide/how-scripting-works.md), for the conventions.
* **A source you can run against with a handful of rows.** Not the full feed.

***

## Build it

### 1. Understand what the script receives

```groovy
int execute(LineObject rowObj, ProvisionUser pUser)
```

`rowObj` is the inbound row. `pUser` is the object you populate. **The return value is a signal telling synchronisation what to do with this row**, not a status code:

| Constant                      | Value | Means                                  |
| ----------------------------- | ----: | -------------------------------------- |
| `SKIP`                        |    -1 | Ignore this row entirely               |
| `NO_DELETE`                   |     0 | Process normally. **The usual return** |
| `DELETE`                      |     1 | Delete the matched object              |
| `DISABLE`                     |     2 | Disable it                             |
| `ENABLE`                      |     3 | Enable it                              |
| `EXCEPTION`                   |     4 | Treat as an error                      |
| `INITIATE_NEW_HIRE_WORKFLOW`  |     5 | Start the new-hire workflow            |
| `INITIATE_EDIT_USER_WORKFLOW` |     6 | Start the edit-user workflow           |

They are inherited, so write `NO_DELETE`, not `TransformScript.NO_DELETE`.

### 2. Pick the base class

| Base class                             | Second argument | For           |
| -------------------------------------- | --------------- | ------------- |
| `AbstractUserTransformScript`          | `ProvisionUser` | Users         |
| `AbstractGroupTransformScript`         | `Group`         | Groups        |
| `AbstractRoleTransformScript`          | `Role`          | Roles         |
| `AbstractOrganizationTransformScript`  | `Organization`  | Organizations |
| `AbstractResourceTransformationScript` | `Resource`      | Resources     |

All extend `AbstractTransformScript<T>`, which is where the shared behaviour lives.

**The user case takes a `ProvisionUser`, not a `User`.** That catches people out, because most of the rest of the API deals in `User`.

### 3. Write it

```groovy
import org.openiam.idm.srvc.synch.dto.LineObject
import org.openiam.provision.dto.ProvisionUser
import org.openiam.sync.service.impl.service.AbstractUserTransformScript

class HRFeedTransform extends AbstractUserTransformScript {

    @Override
    int execute(LineObject rowObj, ProvisionUser pUser) {
        def columnMap = rowObj.columnMap

        pUser.firstName = columnMap.get("FIRST_NAME")?.value
        pUser.lastName  = columnMap.get("LAST_NAME")?.value
        pUser.email     = columnMap.get("EMAIL")?.value

        return NO_DELETE
    }
}
```

**`?.value`, not `.value`.** A column absent from the row gives `null` from the map, and `?.` stops that becoming a `NullPointerException` that fails the run.

### 4. Use what the base class gives you

`AbstractTransformScript` provides more than the method signature:

| Member                                                                                                                              | Is                                                                                                     |
| ----------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
| `isNewUser`                                                                                                                         | `true` when this row creates an object rather than updating one. **The most useful flag on the class** |
| `log`                                                                                                                               | A logger. Do not declare your own                                                                      |
| `context`                                                                                                                           | The Spring `ApplicationContext`                                                                        |
| `rolesByName`, `groupsByName`, `resourcesByName`, `usersByLogin`, `organizationByName`, `managedSystemByName`, `resourceTypeByName` | Name-keyed caches, populated for you                                                                   |
| `rolesById`, `groupsById`, `resourcesById`                                                                                          | The same, keyed by id                                                                                  |
| `metadataTypesByGroupingAndName`                                                                                                    | Metadata types by grouping and name                                                                    |

**Use the caches.** Looking the same role up for every row of a fifty-thousand-row feed is what makes a synchronisation slow.

### 5. Read a shipped example

From `conf/iamscripts/sync/role/csv/CSVRoleSampleTransformationScript_1.0.groovy`, abridged:

```groovy
import org.openiam.dto.Role
import org.openiam.sync.service.TransformScript
import org.openiam.idm.srvc.synch.dto.LineObject
import org.openiam.sync.service.impl.service.AbstractRoleTransformScript

class CSVRoleSampleTransformationScript extends AbstractRoleTransformScript {

    @Override
    int execute(LineObject rowObj, Role role) {
        try {
            populateObject(rowObj, role)
        } catch (Exception ex) {
            ex.printStackTrace()
            return -1                                  // SKIP
        }
        return TransformScript.NO_DELETE
    }

    private void populateObject(LineObject rowObj, Role role) {
        def columnMap = rowObj.columnMap
        if (isNewUser) {
            role.id = null                             // let the platform assign one
        }
        role.name = columnMap.get("NAME")?.value
        role.description = columnMap.get("DESCRIPTION")?.value

        Role parentRole = getRoleByName(columnMap.get("PARENT")?.value, config.getManagedSysId())
        Role childRole  = getRoleByName(columnMap.get("NAME")?.value,   config.getManagedSysId())
        if (parentRole && childRole) {
            roleRabbitMQService.addChildRole(parentRole.id, childRole.id)
        }
    }
}
```

**Four things worth taking from it:**

* **`if (isNewUser) { role.id = null }`** — clearing the id on creation lets the platform assign one. Carrying an id from a previous row is a common way to update the wrong object.
* **The work is in a private method.** `execute` handles the outcome; `populateObject` does the mapping. Worth copying — it keeps error handling in one place.
* **It catches and returns a signal** rather than letting the exception escape. An uncaught exception fails the row, and depending on configuration can fail the run.
* **It reaches a service directly** to build a relationship the row implies. Transformation is not limited to setting fields.

### 6. Deploy it

1. Webconsole → **Administration → Groovy Manager**.
2. Expand the folder for your synchronisation configuration under `sync/`.
3. **New Script**, paste, **Save**. It compiles on save; a compilation error appears with its stack trace.
4. Reference the script by name in the synchronisation configuration.

***

## Verify it

**Run the synchronisation against a small source first.**

| Check                           | Where                                                                          |
| ------------------------------- | ------------------------------------------------------------------------------ |
| The script was called           | Your `log` output, or a `println`, in the service log                          |
| Objects were created or updated | The console, on the objects the rows describe                                  |
| Rows were skipped               | The synchronisation result — a processed count lower than the source row count |

**Then run it a second time against the same source.** The first run tests creation; the second tests the update path, and they fail differently.

## If it goes wrong

| What you see                                             | What it means                                                               | What to do                                                                                                         |
| -------------------------------------------------------- | --------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
| Compilation fails on save with `unable to resolve class` | An import is wrong, or the class is not on the platform's classpath         | Check the import. Compile locally first — [*Set up your environment*](/developer-guide/set-up-your-environment.md) |
| `NullPointerException` on a column                       | The column is absent from that row                                          | Use `?.value`, and decide what an absent column should mean                                                        |
| Every row is skipped                                     | `execute` is returning `SKIP`, usually from the `catch`                     | Log the exception in the catch block. It is being swallowed                                                        |
| Objects are created but fields are empty                 | Column names do not match the source                                        | Log `rowObj.columnMap.keySet()` once and compare                                                                   |
| Updates create duplicates                                | The id is cleared on update, or matching is not finding the existing object | Guard the id reset with `isNewUser`, and check the matching configuration                                          |
| The run is very slow                                     | Per-row lookups instead of the caches                                       | Use `rolesByName` and the other caches                                                                             |

## What this procedure does not cover

Configuring the synchronisation itself — the source connection, the schedule and the matching rules are the [Administration Guide](/administration-guide/admin.md)'s subject. Deciding which source is authoritative for which attribute is a design question, and belongs in the [Solution Architecture and Design Guide](/solution-architecture/solution-architecture.md).

## Related

* [*Validation and attribute scripts*](/developer-guide/validation-and-attribute-scripts.md) — what runs before this
* [*How scripting works*](/developer-guide/how-scripting-works.md)

*Applies to OpenIAM 2026.8.1.*


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.openiam.com/developer-guide/transformation-scripts.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
