Anvil
How-to guides

Anvil: create model elements

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

A resource creates model elements from code more often than a modeller draws them by hand: an importer builds a structure from a foreign file, a command refactors a subtree, an integration test assembles a fixture. ElementFactory names, owns and stereotypes an element in one guarded call, so that sequence stops repeating at every call site.

The one-line case

Construct one ElementFactory per project and reuse it. Each creator then takes a name, an owner and an optional stereotype:

import com.mbseconsulting.anvil.model.ElementFactory

val factory = ElementFactory(project)
val block = factory.createClass("Pump", library, SysML.Block)

The call above runs inside an open session, names the Class "Pump", checks that library can own it, sets the owner and applies SysML.Block. createProperty, createPort, createActivity, createCallBehaviorAction, createActivityParameterNode, createParameter, createPackage, createProfile, createComponent, createDataType, createPrimitiveType, createSignal, createEnumeration, createEnumerationLiteral and createOperation carry the same shape, one method per metaclass.

The owner setter places each element in the collection its metaclass belongs to. An EnumerationLiteral lands in its Enumeration's ownedLiteral, an Operation in its owner's ownedOperation, and a Constraint in its owner's ownedRule. createOperation takes any Classifier as owner, but only a Class, an Interface, a DataType or an Artifact owns operations. The metamodel check refuses any other owner by name, at every Permissions level.

Behaviors, constraints and generalizations

Three creators take arguments beyond the name, the owner and the stereotype:

CreatorExtra argumentsEffect
createOpaqueBehaviorlanguage, bodywrites one language and its body
createConstraintconstrainedElements, language, bodybuilds the OpaqueExpression specification in the same call
createGeneralizationspecific, general (and no name or owner)specific owns the generalization

createConstraint clears the language that createOpaqueExpressionInstance() pre-fills. The tool creates every OpaqueExpression with English as its language, and UML pairs each language with the body at the same index. An expression carrying English ahead of the caller's language would pair the caller's body with the wrong language. What the metamodel does not tell you records the default for code that builds an expression without the factory.

createGeneralization takes no owner because UML makes the specific classifier the owner of its generalizations. A Generalization is not a NamedElement, so it takes no name either. The containment checks run against specific.

val rule = factory.createConstraint("named", library, listOf(block), "OCL2.0", "self.name <> ''")
factory.createGeneralization(specific = pump, general = device)

Why the project is a constructor argument

ElementFactory takes project once, in its constructor, rather than reading Application.getInstance().project inside each creator. The active project is the wrong project under batch mode and under a second open project, and a factory that reads it cannot be tested against a project a suite manages itself. Construct one factory per project and hold it wherever the resource already holds that project.

Every call needs an open session

ElementFactory asserts a session before it creates anything, rather than letting a write outside one disappear silently at the next save. Calling a creator with no session open fails immediately:

java.lang.IllegalStateException: Model mutation requires an open session on project 'MyProject'.

Wrap every call in SessionManager.createSession / closeSession, the same as any other model mutation — see Trace model events for how a committed session is what a tracer or a rule engine reacts to.

The three checks

Every creator runs up to three questions before it sets an owner — Permissions selects how many — and each of the three answers something the other two cannot.

canAdd(child, false) asks whether the UML metamodel gives the owner a container for the child at all. A Port cannot own a Class, and no permission or customization changes that. This check runs at every Permissions level, because skipping it cannot make an illegal containment legal — it can only trade a message naming both elements for the platform's own IllegalArgumentException: can not find container for:.

canAddChild asks whether the platform's own permission handlers allow a write here — editions, ESI projects, read-only used projects, diagram features. It reads no metamodel: it returns true for a Port owning a Class. It is the check that turns a silent write into a read-only module into a named failure, where the Open API otherwise performs that write without complaint.

DSL.isPossibleOwner asks whether the loaded DSL Customization's Possible Owners admits the owner for the child's stereotype. Neither of the first two checks reads that constraint, which is why code reaches states the tool's own creation dialogs refuse. The list comes off the child's stereotype rather than off the child, so a bare Port under a plain Class passes while the same Port carrying «FullPort» fails — «FullPort» declares Block, External, Domain, Subsystem and System context as its possible owners.

Permissions selects which of the two gated checks run; the metamodel check is never gated:

PermissionscanAddcanAddChildisPossibleOwnerFor
ENFORCEDalwaysyesyesproduction code
WITHOUT_CUSTOMIZATIONalwaysyesnoa test that must build a state a customization forbids a modeller from reaching
NONEalwaysnonoa fixture reproducing an imported or pasted model

Choosing WITHOUT_CUSTOMIZATION over NONE

Reach for WITHOUT_CUSTOMIZATION when the state under test is UML-legal and platform-legal but customization-illegal — a paste or an import reaches it, and a modeller's own dialogs do not. A framework's derived properties are the case this level exists for: they filter a classifier's owned attributes by stereotype, and proving the filter excludes something requires creating the thing it excludes. A Port under a plain Class is exactly that shape once the port carries a stereotype whose Possible Owners excludes Class.

Reach for NONE only for a fixture that reproduces a state the platform itself would refuse to write — a read-only used project, most often — because the fixture stands in for an import or a paste that already put the element there. NONE skips the platform check too, so it is the level that can leave a write in a module the tool reports as read-only; use it to build a starting fixture, not to route around a refusal in production code.

Relationships: PathEnd and the relationship creators

A (name, owner, stereotype) element is something a container merely holds. A relationship carries ends instead, and PathEnd is the value every relationship creator takes for each one:

data class PathEnd(
    val role: Element,
    val propertyPath: List<Property> = emptyList(),
    val context: Classifier? = null,
)

role is what the end points at. propertyPath is the ordered list of Propertys walked to reach it when the end names something nested rather than direct. context is the Classifier the walk starts from — a question distinct from where the relationship itself is stored.

createObjectFlow(name, owner, source, target, stereotype) takes source and target as required ActivityNode arguments, not as part of a PathEnd. An ObjectFlow is a directed edge, and CATIA Magic's model-integrity check deletes one with no source and no target the moment its session closes, silently, with no exception raised — so the two ends are required rather than optional.

createConnector(name, owner, endA, endB, stereotype) derives a connector's context from its owning Classifier, so a PathEnd.context set by the caller is rejected rather than silently ignored. It fills the two ConnectorEnds that createConnectorInstance() already creates on the new Connector, instead of adding its own — adding a fresh pair leaves the original two roleless, and the model-integrity check drops the whole connector at session close for having no client and no supplier. An end carrying a propertyPath gets «NestedConnectorEnd» applied and the path written to that end's own propertyPath tag.

createAbstraction(name, owner, source, target, stereotype) writes its ends the other way round: an abstraction's two ends may root in different classifiers, so context is never defaulted to owner and must be set explicitly on any end that carries a propertyPath. owner and context answer different questions — owner is where the relationship is stored, context is the Classifier a path is walked from — and the factory never reads one for the other. An end with no path needs no context. Both paths land on the relationship itself, under «DirectedRelationshipPropertyPath», rather than on either end.

Both ends of any of the three must also resolve within owner's own containment. CATIA Magic removes a relationship whose ends do not resolve there when the session closes, silently and without raising, the same way it drops a sourceless ObjectFlow or a roleless Connector.

createRealization(name, owner, source, target, stereotype) and createDependency(name, owner, source, target, stereotype) take the same arguments and follow the same rules. Realization specialises Abstraction, which specialises Dependency, so all three carry their ends' paths under «DirectedRelationshipPropertyPath» — the stereotype extends the DirectedRelationship metaclass rather than Abstraction, which is what lets a plain dependency carry them too.

StereotypeReference<M> is what every relationship creator's stereotype parameter takes; see Use profile bindings for how a binding resolves and applies.

Letting the tool place a relationship

owner is optional on createAbstraction, createRealization and createDependency. A caller that omits it gets the owner CATIA Magic would choose, through CoreHelper.findParent(relationship, client, supplier, null) — the same rule that decides where a relationship drawn in a diagram is stored.

factory.createRealization("realizes", source = PathEnd(design), target = PathEnd(requirement))

Two properties are worth knowing before relying on it. The factory passes the caller's Permissions through to findParent, so the tool skips a parent the caller could not write into, and the same platform check runs again in the containment guards; under Permissions.NONE neither runs. And findParent returns null where it finds no parent, in which case the factory refuses by name rather than guessing — pass an owner explicitly when that happens.

Omitting owner also settles the containment constraint above by construction: findParent answers a parent the two ends already resolve within, so "both ends must resolve within owner's own containment" holds without a separate check.

Do not reach for CoreHelper.canAddChild to hand-roll this. Its own Javadoc describes two rules and then states "Current implementation returns false".

Logging

The factory logs nothing above trace — it names no INFO line of its own, because a library that narrates each creation under its own category puts Anvil's name in every consumer's log and floods a bulk import. A resource that wants a creation recorded logs it at its own call site, under its own category, which is where the reader of that log expects to find it — see Anvil: log from a resource.

On this page