Blog / Groovy Series
Adventures in Groovy – Part 55a: Updating Valid Intersections without making every user an admin
This is post 1 of 4 in Part 55. More posts in this part are on the way, and each one will be linked here when it's up.
Letting planners lock and reopen their own periods with Valid Intersections sounds like a small request, until you find out the only way to change them is as an administrator. That was the problem I was handed: give users ownership of their own entities without making every one of them an admin. Solving it took a Groovy rule that exports every intersection, works out which parents and children conflict, rebuilds the spreadsheet in memory and writes it back to a ZIP one byte at a time.
This is the first of four posts on that rule. It starts with the problems, because they are the reason the code looks the way it does, then gets into the Groovy: the runtime prompts, the checks that refuse a bad request, a run lock so two people can't collide, and the export job the rule waits on. If you have ever thought about driving Valid Intersections from a rule, read this before you write a line.
How I got involved
This one came with a deadline. A Fortune 100 company couldn't go live on Planning until it was solved.
The business wanted people to own their security. The person responsible for an entity should be able to lock its periods when they're done and open them again when something changes. People with higher level security, the owners of the parent entities, needed to be able to override them: lock a whole branch at once, and keep it locked no matter what anyone below them did.
Valid Intersections are the right tool for that, because Planning enforces them everywhere a user can enter data. The catch is who can change them. Updating valid combinations is administrator work, and the only way to let every owner manage their own would have been to make every one of them an admin. Nobody wanted that.
So development and my VP asked me to find another way. The answer had to let a planner run something from a menu, change only what they were allowed to change, and respect every lock above them.
What the rule does
A user opens the rule and picks Read or Write, a scenario, a year, one or more entities and the periods they care about. Read locks those periods. Write opens them again. A lock on a parent covers every child under it, and a child can never open something its parent has locked. Saying that took a paragraph. Building it ran into everything below.
There is no call to change one rule
I couldn't find a REST call that edits a single Valid Intersection. What you get is a job that exports all of them and a job that imports all of them. The export is a ZIP with a workbook inside, and the workbook has two sheets: Rules, one row per group, and Sub Rules, the members each group covers.
So every change, even one period on one entity, is a round trip: export everything, find the right rows, change them, put the workbook back together and import it. And the import is a merge. Delete a row from the sheet and the rule is still there after the import. To remove a lock you have to keep the row and disable it.
Intersections conflict with each other
This is the one that took the most thought. Say a parent locks P1 to P5 and one of its children has its own lock on P5 and P6. The child is locked for P1 to P6. Now the parent opens P1 to P4. The child should open P1 to P4, keep P5 because the parent still holds it, and keep P6 because that lock was always its own.
The obvious shortcut is to copy the parent's periods into the child's row. Do that and the child stays locked forever after the parent opens up, because nothing remembers which periods the child asked for and which it only inherited. Grandparents make it worse: a lock two levels up applies the same way.
So every managed row has to remember two things: the periods it locked itself and the periods that are actually locked once every ancestor is counted. A change to a parent has to recalculate the second list for every child that already has a row, without touching the first. That's Part 55b.
Two people can run it at once
Export, change, import is not one transaction. If two people run the rule a few seconds apart, the second can export before the first imports, and its import puts the old rows back. The rule needs its own lock, a flag it sets before the export and clears after the import, and it has to clear it even when something fails. It also has to know when not to clear it: if an import job is still running and the rule can't tell how it ended, releasing the flag would let someone else in on top of it.
The spreadsheet fights back
Groovy in Planning can build a new workbook. I had no way to open an existing one and read its cells. An XLSX file is a ZIP of XML files, so the plan was to unzip it and read the sheet XML directly.
That ran into two walls. The file writer the rule gets for the repository writes text, not a spreadsheet. And the workbook the export produces is zipped in a way the Groovy ZIP reader can't open. Getting past both meant writing the workbook into the repository as text without changing a single byte, then fixing its ZIP headers by hand, one field at a time. That's the trick in Part 55d, and it's the reason this series exists.
Users run it without being admins
This is the piece that answers the original ask. Export and import jobs need an administrator, and the whole point was not to make planners into one. The rule calls the REST jobs through a named connection, Loopback_Admin_REST, that points back at the same application with an identity allowed to run them. A planner launches the rule from a menu, and the connection does the part their own security can't. Keep that connection's credentials tight and the rule's launch access tighter, because the rule is what decides what gets imported.
How the rule fits together
With all of that in mind, here is the shape of the rule. Every stage can stop the run with a message, and nothing is imported unless every stage before it passed.
Stage 0 Read the runtime prompts and validate themStage 1 Check the run lock, then set itStage 2 Export every Valid Intersection to a ZIP and wait for the jobStage 3 Pull the workbook out, read both sheets, apply the change to every entityStage 4 Write the rebuilt workbook into a new ZIPStage 5 Import the ZIP and wait for the jobFinally Release the run lock, unless a job's outcome is unknown
The prompts
Now the Groovy. Everything from here to the export is about refusing a bad request before the rule touches anything, because once the import runs there's no undo button.
The rule asks for five things. The first line of the script declares them so Planning shows them when the rule launches.
/*RTPS: {ChangeMode} {ScenarioSelection} {VIM_YearSelection} {VIM_EntitySelections} {VIM_PeriodSelection}*/
ChangeMode and VIM_YearSelection are Smart Lists, so the user picks from a list instead of typing. I read the entry, not the text, and check its ID. If someone renames an entry later, the rule still knows which one is Read and which is Write.
SmartList.Entry selectedMode = rtps.ChangeMode.smartListEntryif (selectedMode == null || !(selectedMode.entryId in [1L, 2L])) { throwVetoException("Select Read or Write from the Access mode Smart List.")}String requestedChangeMode = selectedMode.entryId == 1L ? "READ" : "WRITE"println("SMART LIST PASS: id=" + selectedMode.entryId + ", entry=" + selectedMode.name + ", action=" + requestedChangeMode)// ...String requestedScenario = rtps.ScenarioSelection.member.nameSmartList.Entry selectedYear = rtps.VIM_YearSelection.smartListEntryif (selectedYear == null) { throwVetoException("Select a year from the Year Smart List.") }String requestedYear = selectedYear.name
Read is entry 1 and Write is entry 2. Anything else stops the run. The year comes from a Smart List too, and the rule checks it against the live Years dimension before trusting it, so a stale entry can't send it after a year that no longer exists.
Entities that overlap
VIM_EntitySelections is a members prompt, so one run can change up to 100 entities. That's where the first conflict shows up. A change on a parent already reaches every child under it. If the user picks a parent and one of its children in the same run, the child would be processed twice, and the second pass would work from the first pass's half-finished state.
List<String> viRequestedEntities(List<Member> selected, Cube cube) { if (selected == null || selected.isEmpty()) { throwVetoException("Select at least one Entity.") } if (selected.size() > 100) { throwVetoException("Select no more than 100 Entities per run.") } Dimension dimension = operation.application.getDimension("Entity", cube) List<String> names = [] as List<String> for (Member selectedMember : selected) { if (selectedMember == null) { throwVetoException("Entity selection contains a blank member.") } Member currentMember = dimension.getMember(selectedMember.name, cube) if (currentMember == null) { throwVetoException("Selected Entity is not in Plan1: " + selectedMember.name) } if (!names.contains(currentMember.name)) { names.add(currentMember.name) } } for (String name : names) { Member member = dimension.getMember(name, cube) List<String> ancestors = viMembers(dimension, cube, "IAncestors(" + member.fixValue + ")") for (String ancestor : ancestors) { if (ancestor != name && names.contains(ancestor)) { throwVetoException("Entity selection overlaps: " + ancestor + " is an ancestor of " + name + ". Select one or the other; no changes were imported.") } } } println("ENTITY MEMBERS: selected=" + names + "; count=" + names.size()) return names}
For each selected entity the rule pulls its ancestors with IAncestors and checks whether any of them was also selected. If one was, the run stops and tells the user which pair to fix. I'd rather refuse the request than guess which of the two they meant.
This is the first half of knowing which children have to change. The prompts tell us the parents the user picked. Part 55b (more coming soon) walks down from each of them to the children that already have their own rows.
Let them pick a quarter
Valid Intersections lock base periods, but nobody wants to tick twelve months. The period prompt accepts parents, and the rule expands them to their level 0 members in outline order.
String viRequestedBasePeriods(List<Member> selected, Cube cube) { if (selected == null || selected.isEmpty()) { throwVetoException("Select at least one period or period parent.") } Dimension dimension = operation.application.getDimension("Period", cube) List<String> allowed = viMembers(dimension, cube, "IDescendants(YearTotal)") List<String> ordered = viMembers(dimension, cube, "ILvl0Descendants(YearTotal)") List<String> requestedNames = [] as List<String> List<String> expanded = [] as List<String> for (Member member : selected) { if (!allowed.contains(member.name)) { throwVetoException("Select periods within YearTotal: " + member.name) } requestedNames.add(member.name) List<String> leaves = ordered.contains(member.name) ? [member.name] as List<String> : viMembers(dimension, cube, "ILvl0Descendants(" + member.fixValue + ")") if (leaves.isEmpty()) { throwVetoException("Selected period has no base periods: " + member.name) } for (String leaf : leaves) { if (!ordered.contains(leaf)) { throwVetoException("Expanded period is outside YearTotal: " + leaf) } if (!expanded.contains(leaf)) { expanded.add(leaf) } } } List<String> expressions = [] as List<String> for (String leaf : ordered) { if (expanded.contains(leaf)) { expressions.add(dimension.getMember(leaf, cube).fixValue) } } String result = expressions.join(",") println("PERIOD MEMBERS: selected=" + requestedNames + "; basePeriods=" + result) return result}
Everything has to sit under YearTotal. Picking Q1 and January in the same run is fine; the duplicate is dropped. The result is a comma separated list of member references in outline order, which is the format the rest of the rule expects.
A lock so two runs can't collide
Export, change and import take a while, and they aren't one transaction. The rule uses a substitution variable as a flag. If it's already set, the run stops. If not, the rule sets it before the export.
String lockValue = operation.application.getSubstitutionVariableValue(lockVariableName)if (lockValue != null && (lockValue.equalsIgnoreCase("1") || lockValue.equalsIgnoreCase("yes"))) { throwVetoException("A Valid Intersections update is already running. Please try again shortly.")}setApplicationVariableViaRest(connectionName, lockVariableName, "1")lockAcquired = trueprintln("STAGE 1 PASS: update lock acquired")
The flag is set through REST rather than the Groovy API, so it uses the same connection as the jobs.
void setApplicationVariableViaRest(String connectionName, String variableName, String variableValue) { Map<String, Object> payload = [items: [[name: variableName, value: variableValue, planType: "ALL"]]] as Map<String, Object> HttpResponse<String> response = operation.application.getConnection(connectionName) .post("/HyperionPlanning/rest/v3/applications/PlanApp/substitutionvariables") .header("Content-Type", "application/json") .body(groovy.json.JsonOutput.toJson(payload)).asString() if (!checkRequest(response) || response.status != 204) { throwVetoException("Substitution variable update failed: " + variableName + "=" + variableValue + "; HTTP " + response.status + " " + response.statusText + "; expected 204 No Content.") } println("SUBSTITUTION VARIABLE REST PASS: " + variableName + "=" + variableValue + "; HTTP 204")}
Oracle answers a successful update with 204 and no body. Anything else stops the run. I don't retry a write like this: if the first call might have worked, a retry can leave the flag in a state nobody expects.
Releasing it is the part people forget. It lives in a finally block so it runs on success and on failure.
} finally { if (lockAcquired && !(childState.get("pending") as boolean)) { try { setApplicationVariableViaRest(connectionName, lockVariableName, "0") println("Lock released: " + lockVariableName) } catch (Exception cleanupError) { println("CLEANUP ERROR: guard reset failed: " + cleanupError.message) if (!executionFailed) { throw cleanupError } } } else if (lockAcquired) { println("GUARD RETAINED: child job state is unknown; job=" + childState.get("jobId") + ". Check active jobs before manual reset.") } else { println("Cleanup: this execution did not acquire the lock") }}
There's one case where the rule keeps the flag on purpose. If it started an import and lost track of how it ended, releasing the flag would let another run export while that import might still be writing. It logs the job ID instead, so an administrator can check the job and clear the flag by hand.
A caveat: this is a polite lock, not a true one. Two runs that read the variable in the same instant could both see it clear. In practice the window is tiny, but don't build anything that depends on it being perfect.
Running the export and waiting for it
The export is a REST job. The rule posts it through the connection, then hands the response to a helper that waits until the job finishes.
Map<String, Object> exportPayload = [jobType: "EXPORT_VALID_INTERSECTIONS", jobName: ("VIM MultiEntities Export " + runId).toString(), parameters: [fileName: sourceZipName]] as Map<String, Object>println("STAGE 2: submitting export job")childState.put("pending", true)HttpResponse<String> exportResponse = operation.application.getConnection(connectionName).post(jobsPath).header("Content-Type", "application/json").body(groovy.json.JsonOutput.toJson(exportPayload)).asString()awaitChildJob(exportResponse, connectionName, jobsPath, "EXPORT", childState)
void awaitChildJob(HttpResponse<String> response, String connectionName, String jobsPath, String stage, Map<String, Object> childState) { if (!checkRequest(response)) { throwVetoException(stage + " HTTP failure: " + response.status + " " + response.statusText) } ReadContext submitted = JsonPath.parse(response.body) String jobId = submitted.read('$.jobId').toString() int status = submitted.read('$.status') as int childState.put("jobId", jobId) println(stage + " JOB: " + jobId + "; status=" + status) int pollCount = 0 while ((status == -1 || status == 2) && pollCount < 90) { sleep(2000L) HttpResponse<String> polled = operation.application.getConnection(connectionName).get((jobsPath + "/" + jobId).toString()).asString() if (!checkRequest(polled)) { throwVetoException(stage + " status check failed for job " + jobId + ": HTTP " + polled.status) } ReadContext current = JsonPath.parse(polled.body) status = current.read('$.status') as int pollCount++ if (pollCount == 1 || pollCount % 5 == 0 || (status != -1 && status != 2)) { println(stage + " POLL: job=" + jobId + "; status=" + status + "; poll=" + pollCount) } } if (status == -1 || status == 2) { throwVetoException(stage + " timed out waiting for job " + jobId + ". Guard retained until an administrator verifies job completion.") } if (!(status in [0, 1, 3, 4])) { throwVetoException(stage + " returned unknown status " + status + " for job " + jobId + ". Guard retained for reconciliation.") } childState.put("pending", false) if (status != 0) { throwVetoException(stage + " failed: job=" + jobId + "; status=" + status + ". Inspect the child job and error file.") } println(stage + " PASS: terminal successful job " + jobId)}
Status -1 and 2 mean the job is still going, so the rule polls every two seconds, up to 90 times. Status 0 is the only success. When the job ends any other way, or the polling runs out, the rule stops and says which job to look at. Before it polls, it records the job ID in childState, which is what the finally block reads to decide whether the flag is safe to release.
What we covered
Valid Intersections can only be changed in bulk, by exporting and importing a workbook, and the import never deletes. A parent and a child lock have to be tracked separately, or a child can never open again. And the workbook itself can't be opened with the tools a rule normally has.
On the Groovy side: read Smart List entries by ID, not by name. Check member prompts against the live outline and refuse overlapping selections instead of guessing. Wrap any export and import pair in a flag that's released in finally, and kept when a job's outcome is unknown. Run the jobs through a connection so the people who own the data can run the rule without being admins.
Where the series goes from here
At this point the rule has a validated request and a ZIP from the export. More is coming. Part 55b works out which parents and children the change affects. Part 55c reads the workbook and builds the new one. Part 55d gets the bytes into and out of the ZIP files and has the complete script. I'll link each one here as it goes up, and I'll email subscribers when it does.

Comments
Moderated. New comments appear once Kyle approves them.