Open API: listen to model events
Every session that closes commits a transaction, and a TransactionCommitListener receives the
PropertyChangeEvents that transaction carried. This is how a plugin reacts to what a modeller did.
Write a listener
import com.nomagic.uml2.transaction.TransactionCommitListener
import com.nomagic.uml2.ext.jmi.UML2MetamodelConstants
import java.beans.PropertyChangeEvent
class MyListener : TransactionCommitListener {
override fun transactionCommited(events: Collection<PropertyChangeEvent>): Runnable? {
val created = events.filter { it.propertyName == UML2MetamodelConstants.INSTANCE_CREATED }
if (created.isEmpty()) return null
return Runnable { created.forEach { /* write to the model here */ } }
}
}The method is spelled transactionCommited, with one t in the second word. It is the tool's
spelling, and an override that corrects it compiles as a new method nothing calls.
Read during the notification, write from the Runnable
The collection arrives while the transaction that produced it is closing. Decide what to do there,
and return a Runnable carrying the writes. The tool runs it afterwards, where opening a session of
your own is safe. Returning null says there is nothing to do.
Register per project, and per channel
project.repository.transactionManager.addTransactionCommitListener(listener)A listener attaches to one project. A plugin that installs one in init() reaches no project,
because none is open yet — attach to the projects already open, attach on each project that opens
afterwards, and detach on close().
Three registration methods carry three different event sets, and the choice decides what you see:
| Method | Reports |
|---|---|
addTransactionCommitListenerForExecute | First execution of a command or session. Silent on undo, redo and direct transactions |
addTransactionCommitListener | First command execution and direct transaction execution. Silent on undo and redo |
addTransactionCommitListenerIncludingUndoAndRedo | Command and session execution, undo, redo and direct transaction execution |
Do not guess which events fire
The event a modelling action produces is not the one the metamodel implies. Ownership of a Property
arrives as UMLClass, and ownership of a CallBehaviorAction as activity. Log what arrives,
perform the modelling action by hand, and read the result before writing a condition against a
property name.
Reference
- Developer Guide — UML-based › Event support, "Listening to transaction commit events on session closing"
- Sample plugin —
<install>/openapi/examples/events/ - API —
com.nomagic.uml2.transaction,com.nomagic.uml2.ext.jmi - Local digest —
dev-env/ai-docs/reference/guide/listening-to-transaction-commit-events-on-session-closing.md
Related
- Anvil: trace model events — the same listeners, through Anvil, plus the trace.
- Open API: run a session — the session whose closing produces these events.
- How auto-stereotyping works — what a listener that writes to the model has to respect.