Anvil
How-to guides

Anvil: trace model events

The raw Open API version of this page is Open API: listen to model events.

A plugin that needs to know what the model reports installs a trace and reads CATIA Magic's log. The events package carries everything this page uses, and it stands alone: a plugin with no rules and no auto-stereotyping engine traces a project's commits with ModelEventTrace by itself.

Two situations call for a trace. An author establishing an auto-stereotype rule needs the events a modelling action actually fires, because the UML metamodel does not predict them — see Anvil: write an auto-stereotype rule. A plugin that reacts to model changes at all needs the same reading before it registers a listener of its own.

Install the trace

ModelEventTrace attaches to every project as it opens and detaches on uninstall:

import com.mbseconsulting.anvil.events.ModelEventTrace
import com.mbseconsulting.anvil.logging.ResourceLog

class Main : Plugin() {
    private val trace = ModelEventTrace(ResourceLog.of("ACME"))

    override fun init() {
        trace.install()
    }

    override fun close(): Boolean {
        trace.uninstall()
        return true
    }

    override fun isSupported(): Boolean = true
}

install() and uninstall() run on the EDT, which Plugin.init() and Plugin.close() both satisfy. A transaction manager belongs to a project rather than to the application, so the trace registers a project event listener and does the per-project work when a project reports itself open. uninstall() removes every registration install() added, which a plugin close requires: a listener left on a transaction manager runs against unloaded classes. Both calls are idempotent.

The trace writes under the category the logger names. A resource that already runs an engine passes its rule set's logger, so trace lines and engine lines share one category.

Raise the category

Nothing is written while the tool's root logger sits at info. One entry in <install>/data/log4j2.xml raises the resource's category:

<Logger name="ACME" level="debug"/>

The level decides which channels write. debug prints the commit channel, and trace adds execute and undoredo. The tool's configuration carries monitorInterval="30", so the entry takes effect within thirty seconds and needs no restart. Anvil: log from a resource covers the configuration in full.

Read a block

Each committed transaction writes one header and one line per event:

── trace #7 [commit] project "Demo" — 3 events (addTransactionCommitListener)
[1] type | src=Property "speed" (…41088_3224) | old=null | new=Class "Concept B" «Concept» (…9163_3258) | owner=Class "Holder" «Concept» | type=Class "Concept B" «Concept»

The header carries the block number, the channel that delivered the transaction, the project and the event count. Block numbers run in one sequence across a project's three channels, so a reader can order the three against each other.

FieldCarries
[1]The event's index within the block
typePropertyChangeEvent.propertyName — the property that changed
srcThe element the event was reported on
old, newThe values before and after
owner, type, behaviorAppended for a Property or a CallBehaviorAction only

Those three context fields are the surroundings an auto-stereotyping condition reads, and they are restricted to the two metatypes the rules are written against. Reporting the owning package of every Class a transaction happens to touch buries the events that matter.

Identifiers are shortened to their last two segments, which distinguish two elements within one session. A field that cannot be read renders as <unreadable>, and the rest of the line and of the block still arrives: an element the transaction has just deleted answers owner or type by throwing from the JMI layer, and one such element must not cost the trace.

Choose the channel from what the trace shows

A TransactionManager fans the same transaction out to three listener lists, and the lists cover different actions. The trace registers on all three and stamps each block with the channel that delivered it, so a listener's channel can be chosen from what the log shows rather than from the JavaDoc.

ChannelRegisters throughReportsWritten at
EXECUTEaddTransactionCommitListenerForExecuteFirst execution of a command or session. Silent on undo, redo and direct transactions.trace
COMMITaddTransactionCommitListenerFirst command execution and direct transaction execution. Silent on undo and redo.debug
UNDO_REDOaddTransactionCommitListenerIncludingUndoAndRedoCommand and session execution, undo, redo and direct transaction execution.trace

The auto-stereotyping engine registers its rules on COMMIT, which is why that channel writes at the lower level: it is the one a rule author reads. EXECUTE misses transactions driven from code rather than from a command, and UNDO_REDO fires while the user is undoing.

Picking the wrong channel is the classic way a commit listener fires twice on an undo, or not at all when a script drives the model. Reading all three for the same modelling action settles it.

What the trace costs

Every line is built inside a lambda that the level check discards, so a trace left installed costs one boolean per event while the category sits at info. The tracer reads the model and prints; it returns null from transactionCommited, so it adds no work to the commit and cannot disturb the undo stack. A failure inside the trace is caught and logged as a warning rather than taken into the modelling session.

Those properties are why a trace ships in a released plugin rather than being removed before release. It is then available on a workstation where a model misbehaves and no rebuild is possible.

Annotate the events

ModelEventTrace takes a second argument that appends the caller's own reading to each event's description:

ModelEventTrace(log) { event -> " | mine=${event.source.fString(IdStyle.SHORT)}" }

The auto-stereotyping engine passes a function that reports every rule's verdict for the event, which turns the raw trace into an answer to the question a rule author asks — which event makes a condition become true. See How auto-stereotyping works.

Build a listener that is not a tracer

A plugin that needs a listener of its own — on one channel, or one that modifies the model — builds it against CommitListenerInstaller rather than against the tool's registration methods:

private val installer =
    CommitListenerInstaller(
        log = log,
        label = "my listener",
        listenersFor = { project -> mapOf(CommitChannel.COMMIT to MyListener(project)) },
    )

The installer covers the project lifecycle: it attaches to projects already open, attaches to each project that opens afterwards, and detaches on uninstall. listenersFor is called once per project rather than once per project and channel, so a listener can share state across a project's channels — which is how the trace shares one block counter across its three.

A second install() call registers nothing twice: ProjectsManager.addProjectListener tests contains before adding, so the installer's own project listener cannot be held twice, and it skips a project already attached.

A failed attachment costs a warning by default. A caller for which a missing listener is not cosmetic passes onAttachFailure and decides what it costs; the auto-stereotyping engine raises it to an error, because a rule listener that never attached leaves a model unstereotyped.

A listener that modifies the model does so from the Runnable it returns, never during the notification. See How auto-stereotyping works for the reasoning and the session rules that follow from it.

On this page