Anvil
How-to guides

Anvil: commit a model change

The raw Open API version of this page is Open API: run a session.

Every write to the model runs inside a session, and every session must end exactly once: closed when the change succeeds, cancelled when it fails. commit pairs the two calls, so a resource writes the change and leaves the session handling to Anvil.

Wrap the change

import com.mbseconsulting.anvil.session.commit

val block = project.commit("Create Pump") {
    factory.createClass("Pump", library, SysML.Block)
}

commit opens a session named "Create Pump", runs the block, closes the session and returns what the block returned. The modeller sees the name as one entry in the undo history. A block that creates nothing and only sets tag values, documentation or a status takes the same call, with no factory.

What a failure does

The failurecommit does
The block throwsCancels the session and rethrows the same throwable. A failure to cancel rides on it as a suppressed exception.
closeSession throwsRethrows that failure. It cancels the session first only when the failed close left the session open.
A session is already open on the projectThrows IllegalStateException naming the open session, and leaves that session alone.

commit never joins an open session. A joined change has no boundary of its own, and its failure would cancel the work of the caller that opened the session. Code that may run inside someone else's session, such as a transaction commit listener, tests first:

if (SessionManager.getInstance().isSessionCreated(project)) {
    apply()
} else {
    project.commit("Apply rules") { apply() }
}

Assert after commit returns

The tool checks containment when the session closes, and silently removes an element whose owner does not resolve. An assertion inside the block passes against a model the close is about to empty. Assert on the value commit returns instead:

val flow = project.commit("Create flow") { factory.createObjectFlow("flow", activity, source, target) }

assertSame(activity, flow.owner)

On this page