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 failure | commit does |
|---|---|
| The block throws | Cancels the session and rethrows the same throwable. A failure to cancel rides on it as a suppressed exception. |
closeSession throws | Rethrows that failure. It cancels the session first only when the failed close left the session open. |
| A session is already open on the project | Throws 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)Related
- Open API: run a session — the
SessionManagercallscommitmakes. - Anvil: create model elements — the creators that assert an open session.