Anvil
How-to guides

Open API: run a session

Every write to the model happens inside a session. A session names one entry in the undo history and groups every change it carries into it. The tool's element-management API throws when no session is open, while a direct property write outside one is simply not recorded, leaving no undo entry and no error.

Prefer the Editing API

import com.dassault_systemes.modeler.foundation.editing.Editing

Editing.getInstance(project).execute("Create blocks") {
    // model changes here
}

execute opens the session, runs the block and closes the session, and the name it takes is what the modeller sees in the undo history. This is the tool's recommended form and it needs no finally.

Drop to SessionManager when you need the lifecycle

import com.nomagic.magicdraw.openapi.uml.SessionManager

val sessions = SessionManager.getInstance()
sessions.createSession(project, "Create blocks")
try {
    // model changes here
} finally {
    sessions.closeSession(project)
}

Reach for this when the opening and the closing are separated by something the Editing API cannot hold — a dialog, a listener callback, an existing API that expects an open session.

One session per project, never nested

createSession on a project that already has one open throws IllegalStateException. Code that may run inside someone else's session tests first:

if (!sessions.isSessionCreated(project)) sessions.createSession(project, "Create blocks")

Always pair the call. A session left open leaves the model inconsistent and the undo stack broken.

Assert a created relationship after the session closes

The tool checks relationship integrity when a session closes, and removes what does not resolve — an ObjectFlow with no source, a Connector whose pre-created ends stayed roleless. The removal is silent. A test asserting inside the session passes against a model about to be emptied, so close the session first and assert afterwards.

Reference

  • Developer Guide — General › Model Modification, "Editing API" and "SessionManager API"
  • API — com.dassault_systemes.modeler.foundation.editing, com.nomagic.magicdraw.openapi.uml
  • Local digest — dev-env/ai-docs/reference/guide/editing-api.md, dev-env/ai-docs/reference/guide/sessionmanager-api.md

On this page