Model-Driven Engineering

Model-Driven Engineering (MDE) puts models at the heart of software development: models are no longer mere documentation, but first-class artifacts that are defined, checked, transformed and executed. These three hands-on labs follow the main steps of building a modeling language with the Eclipse Modeling ecosystem: defining its abstract syntax (metamodel), giving it a textual and a graphical concrete syntax, and manipulating models programmatically.

Key concepts

In MDE, every model conforms to a metamodel, which defines the concepts of a language and the relationships between them. The metamodel itself conforms to a meta-metamodel (MOF in the OMG standards, Ecore in the Eclipse world), which is defined in terms of itself. This four-layer architecture is what makes it possible to build generic tools — editors, validators, code generators — that work for any modeling language.

The four metamodeling layers M0 to M3
The four metamodeling layers: data (M0), model (M1), metamodel (M2) and meta-metamodel (M3); labels partly in German. Gubaer, Wikimedia Commons, public domain
Principle of a model transformation
A model transformation is defined between a source and a target metamodel, then applied to models (labels in French). Eneelk, Wikimedia Commons, CC BY-SA 4.0

A modeling language has an abstract syntax (its metamodel) and one or more concrete syntaxes (textual, with Xtext, or graphical, with Sirius). Models can then be manipulated by programs, transformed into other models, or used to generate code. The three labs follow exactly these steps.

Each lab is followed by solution notes, hidden by default: click on “Solution notes” to display them. Try to solve the lab on your own first.

Lab 1 – Metamodeling with Eclipse EMF

Context

The goal of this lab is to illustrate Model-Driven Engineering techniques. We want to handle relational database models in different technological spaces. First, we build a DSL corresponding to a relational DBMS: it must allow creating SQL models without using a tool such as MySQL or Oracle.

Then, for NoSQL users, a transformation of the SQL model into an XML model is needed in order to use tools such as BaseX. This transformation goes through a pivot model conforming to the KM3 metamodel (proposed by INRIA): a model-to-model (M2M) transformation SQL → KM3, then a transformation KM3 → XML. Finally, for knowledge-base users, an SQL → OWL transformation is needed; the resulting ontology can be used by a tool such as Protégé.

The first exercises aim at getting started with the metamodeling tools of Eclipse Modeling Tools, mainly those of EMF (Eclipse Modeling Framework).

Exercise 1 – Setup

Create an EMF project: File > New > Other > Eclipse Modeling Framework > Empty EMF Project. Name the project, for example IDM, then Finish. The project appears in the project explorer.

Exercise 2 – Creating the SQL metamodel

Select the model folder of the project, then New > Other > Eclipse Modeling Framework > Ecore Model, and name the metamodel SQL. Choose the Ecore perspective. When the file opens, the editor takes the central area; the Properties view, below it, lists and allows editing the properties of the selected element.

The Ecore file can be filled in two ways:

Exercise 3 – Validating an Ecore model

At any time, you can check that the Ecore file contains a model that conforms to the Ecore metamodel. First save the metamodel, then:

Exercise 4 – Building the metamodel

In the graphical editor, complete the provided SQL.ecore metamodel so that all the concepts appearing in the model of the figure below are supported.

SQL model euro2015 in the tree editor
SQL model euro2015 in the tree editor, and properties of a column

Exercise 5 – Generating the Java code and the tree editor

Once the metamodel is built, we generate the corresponding Java code and a tree editor for entering a model that conforms to the SQL metamodel.

Exercise 6 – Using the tree editor

Exercise 7 – Creating the XML metamodel

Proceeding as for SQL, define a metamodel for XML, then create an XML model that conforms to it.

Exercise 8 – Creating the SQL textual editor

Solution notes – Lab 1

Exercise 4 – SQL metamodel

The model of the figure shows a database, tables, and three kinds of columns (plain column, integer column, enumerated column) whose properties are: comment, default value, auto-increment (integer columns), primary key, name, nullable, table and type. A possible solution:

EClassFeatures
Databasename : EString [1]; tables : Table [0..*] (containment)
Tablename : EString [1]; columns : Column [0..*] (containment; opposite: table)
Columnname : EString [1]; type : EString; comment : EString; defaultValue : EString; nullable : EBoolean; isPrimaryKey : EBoolean; table : Table [1] (opposite of columns)
IntegerColumn → ColumnisAutoIncrement : EBoolean
EnumColumn → Columnvalues : EString [0..*] (allowed literals)

Database is the root element: tables and columns are reached through containment. The Table property displayed for a column is the opposite reference of the columns containment.

Exercise 7 – XML metamodel

EClassFeatures
Documentroot : Element [1] (containment)
Node (abstract)–
Element → Nodename : EString [1]; attributes : Attribute [0..*] (containment); children : Node [0..*] (containment)
Attributename : EString [1]; value : EString [1]
Text → Nodevalue : EString [1]

The abstract class Node lets an element contain both elements and text, in document order.

Exercise 8 – Xtext grammar

A possible grammar for the metamodel of exercise 4:

grammar ma.ensias.idm.Sql with org.eclipse.xtext.common.Terminals
import "http://ensias.ma/idm/sql" as sql

Database returns sql::Database:
    'database' name=ID '{' tables+=Table* '}';
Table returns sql::Table:
    'table' name=ID '{' (columns+=Column (',' columns+=Column)*)? '}';
Column returns sql::Column:
    IntegerColumn | EnumColumn
    | name=ID type=ID (isPrimaryKey?='primary')? (nullable?='null')?;
IntegerColumn returns sql::IntegerColumn:
    name=ID 'int' (isAutoIncrement?='auto')? (isPrimaryKey?='primary')? (nullable?='null')?;
EnumColumn returns sql::EnumColumn:
    name=ID 'enum' '(' values+=STRING (',' values+=STRING)* ')' (nullable?='null')?;

Example: table goals { goal_id int auto primary, own_goal enum ("yes", "no") }.

Lab 2 – Graphical modeling workbench with Sirius

This lab is adapted from the official Eclipse Sirius tutorial (Creating a Domain-Specific Graphical Modeling Workbench with Eclipse Technologies, Obeo – https://eclipse.dev/sirius).

We build a graphical modeling workbench to describe the choreography of a Lego Mindstorms robot.

Sirius concepts used

Step 1 – The metamodel

Goal: create with Ecore Tools the metamodel of a robot choreography (Ecore file and the corresponding EMF Java code).

mindstorms metamodel
The mindstorms metamodel

Step 2 – Basic workbench

Goal: create a diagram to display and edit a simple choreography: nodes for the start (the choreography itself) and for the actions Rotate (left or right), GoForward, Grab and Release; an edge from the start to the first action; an edge from each action to the next one; tools to create the actions. All the following actions are done in the test Eclipse, in the .odesign file, except the creation of the Java services.

public Instruction getNextInstruction(Instruction instruction) {
    Choregraphy parentChoregraphy = (Choregraphy) instruction.eContainer();
    List<Instruction> actions = parentChoregraphy.getInstructions();
    int position = actions.indexOf(instruction);
    if (position == actions.size() - 1) {
        return null;
    } else {
        return actions.get(position + 1);
    }
}

Step 3 – Advanced workbench

Goal: declare specific colors, display choreographies inside a container, and add tools (link, double-click, direct editing of labels).

Step 4 – Properties views

Goal: customize the Properties view of rotations: the degrees field is disabled when random is checked; yellow background when the angle is not between −180 and 180; a warning when the angle is zero without being random.

Solution notes – Lab 2

Lab 2 is guided step by step; here are the points to check and the Java services.

Step 1

The test model, created with New Child, only accepts Choregraphy, Grab, Release, Rotate and GoForward inside a Choregraphy: Instruction and Action are abstract and do not appear in the menu. After changing the icons, the .genmodel must be regenerated (Edit code) for the new icons to be taken into account.

Step 2

  • The diagram of a choreography displays a Start node and one node per direct action; a sub-choreography is not an Action and is therefore not displayed by CD_Actions.
  • aql:self.instructions->at(1) denotes the first instruction (indices start at 1); the CD_First edge is drawn only if this instruction is an action.
  • getNextInstruction returns null for the last instruction: no edge is created then.
  • The creation tools work on var:container: the action is added to the instructions list of the displayed choreography.

Step 3 – editElement service

public Rotate editElement(Rotate rotate, String value) {
    String v = value.trim();
    if ("?".equals(v)) {
        rotate.setRandom(true);
    } else {
        rotate.setDegrees(Integer.parseInt(v.replace("°", "").trim()));
        rotate.setRandom(false);
    }
    return rotate;
}

Step 4

A non-random 0° rotation raises the warning “This rotation is useless”; the fix makes it random. A 270° rotation is displayed on a yellow background. When random is checked, the Degrees field is disabled (aql:not self.random).

Lab 3 – Manipulating models programmatically

Metamodel and model

Conformance relation. According to the MOF, a metamodel defines the structure that any model conforming to it must have: every model must respect the structure defined by its metamodel.

Conformance relation
Conformance relation between models and metamodel

Examples of metamodels. The UML metamodel states that UML models contain packages, packages contain classes, classes contain attributes and operations, and so on.

Simplified class diagram metamodel
Simplified metamodel of the class diagram

The metamodel of use case diagrams is also a kind of class diagram: each concept is represented by a class and each relation between concepts by an association. It contains three classes: actor (attribute name), system (attribute name) and use case (attribute title). The inherits association has the actor class as source and target; the extends and includes associations have the use case class as source and target. The figure below shows the relations between this metamodel and a use case diagram: the dashed arrows are instantiation relations; a model is said to be an instance of its metamodel.

Use case diagram and its metamodel
A use case diagram and its metamodel

The Ecore metamodel. EMF uses Ecore as the meta-metamodel to define DSLs and to define itself. The root element is the EPackage, which contains EClassifiers (EClass, EDataType, EEnum). An EClass has a name, super-types, attributes (EAttribute), references (EReference) and operations. An EReference models one end of an association: it has a name and a type (the target EClass). A bidirectional association is modeled by two references linked by eOpposite; a composition, by a reference whose containment property is true. The multiplicity of a reference or an attribute is given by lowerBound and upperBound.

The Ecore metamodel
The Ecore metamodel

Creating a metamodel and a model with EMF

Steps for the metamodel

  1. Create an empty EMF project (File > New > Other > Eclipse Modeling Framework > Empty EMF Project).
  2. Create a folder for the metamodel and the models.
  3. Create in it an Ecore metamodel (New > Other > Eclipse Modeling Framework > Ecore Model) named form.ecore.
  4. Open it with the Sample Ecore Model Editor (tree editor).
  5. Fill in the package: Name (package name), Ns Prefix (same value as the name) and Ns URI (absolute identifier of the metamodel).
  6. Add the elements one by one with New Child, setting for each feature the multiplicities (lowerBound, upperBound), the type (EType), the composition (Containment) and, for a bidirectional relation, the opposite (EOpposite).

Example. The metamodel of user-interface forms states that a form (Form) is made of fields (Field), themselves made of sub-fields.

Form metamodel
The form metamodel

Note. Compositions are essential in an Ecore metamodel: an element linked to another one by a composition can be created directly inside an instance of that other element in the model editor. To build a complete model, every metamodel must therefore have a root element from which all the other elements can be reached, directly or transitively, through compositions. Here, Form plays this role.

Steps for the model

  1. Register the metamodel with EMF: right-click on form.ecore, Register EPackages.
  2. File > New > Other…, then EMF Model (Epsilon).
  3. Name the model, choose the metamodel URI, then the root element.
  4. Add the content by right-clicking on the root, New Child.

Manipulating models in Java

Goal. Write a Java program able to modify any EMF model: add elements, modify their attributes and references, delete elements, then save the result. The program receives the metamodel (.ecore) and the model to modify (a conforming XMI file). It must work, without changing its code, on the form metamodel as well as on the graph metamodel seen in class or on any other metamodel.

Elements of the EMF API

MethodRole
Interface EObject (any model element)
eClass()the metaclass (EClass) of the element
eGet(feature)reads an attribute or a reference; for a multi-valued feature, returns a modifiable list
eSet(feature, value)sets a single-valued feature
eUnset(feature)resets the feature to its default value (empty for a list)
eIsSet(feature)does the feature have a value different from its default value?
eContainer() / eContents()the container / the directly contained elements
eResource()the resource containing the element, or null
Interfaces EPackage, EClass, EStructuralFeature, EAttribute, EReference (the metamodel)
EPackage.getEClassifier(name)looks up a metaclass, a data type or an enumeration
EPackage.getESubpackages() / getNsURI()sub-packages / nsURI
EClass.getEStructuralFeature(name)the attribute or reference with this name (inherited ones included), or null
EClass.getEAllAttributes() / getEAllReferences()all attributes / references, inherited ones included
EClass.isAbstract()an abstract metaclass cannot be instantiated
EClass.isSuperTypeOf(c) / isInstance(obj)type compatibility tests
EStructuralFeature.isMany() / getUpperBound()multi-valued feature? / upper bound (-1 for *)
EStructuralFeature.isChangeable() / isDerived()modifiable feature? / derived?
EAttribute.getEAttributeType()type of the attribute (EString, EInt, enumeration…)
EReference.isContainment() / getEReferenceType()composition? / target metaclass
Utility class EcoreUtil
create(eClass)creates an instance of the metaclass
createFromString(type, text) / convertToString(type, value)conversions text ↔ attribute value
delete(obj, recursive)deletes an element from the model (see the javadoc for recursive)
Interfaces ResourceSet and Resource
ResourceSet.getResource(uri, true) / createResource(uri)loads a file / creates an empty resource
ResourceSet.getResourceFactoryRegistry()maps an extension to a factory (EcoreResourceFactoryImpl, XMIResourceFactoryImpl)
ResourceSet.getPackageRegistry()maps an nsURI to an EPackage
Resource.getContents() / getAllContents()root elements / all elements, direct and indirect
Resource.save(options)saves the resource (see the XMLResource options)

Project setup

  1. Create a Java project (or a Plug-in project).
  2. Add to the build path the libraries org.eclipse.emf.common_*.jar, org.eclipse.emf.ecore_*.jar and org.eclipse.emf.ecore.xmi_*.jar from the Eclipse plugins folder (for a Plug-in project, add org.eclipse.emf.ecore and org.eclipse.emf.ecore.xmi to the dependencies of MANIFEST.MF).
  3. Copy the metamodel and the model into the project, for example into model/form/.

Work to do: the ModelManager class

All the operations are grouped in a ModelManager class. None of its methods may contain a name specific to a metamodel (Form, Field, name, Vertex…): these names are always received as parameters. Any error (unknown metaclass, missing feature, incompatible type…) throws an IllegalArgumentException with an explicit message.

public class ModelManager {
    private final ResourceSet resourceSet = new ResourceSetImpl();
    private EPackage metamodel;
    private Resource model;

    /** Maps the "ecore" extension to metamodels and all the other ones to XMI models. */
    public ModelManager()
    // ... the methods of questions 1 to 6
}

Question 1 – Loading

/** Loads the metamodel, registers it (with its sub-packages) in the ResourceSet and returns it. */
public EPackage loadMetamodel(String path)
/** Loads an existing model conforming to the already loaded metamodel. */
public Resource loadModel(String path)
/** Creates an empty model whose root is an instance of rootClassName; returns this root. */
public EObject createModel(String path, String rootClassName)
/** Returns the root element of the model. */
public EObject getRoot()

Question 2 – Searching

/** The metaclass with this name (sub-packages included), or null. */
public EClass getEClassByName(String name)
/** All the instances of className in the model, sub-classes included. */
public List<EObject> findAll(String className)
/** The first instance of className whose attribute attrName equals value (compared as text), or null. */
public EObject findByAttribute(String className, String attrName, String value)

getEClassByName only returns an EClass (a data type or an enumeration may have the same name); findByAttribute works whatever the type of the attribute.

Question 3 – Adding

/** Creates an instance of the metaclass className (which must be concrete). */
public EObject createInstance(String className)
/** Creates an instance of className, stores it in the containment refName of parent and returns it. */
public EObject addElement(EObject parent, String refName, String className)

addElement checks, using the metamodel, that refName is a containment of parent, that className is compatible with the type of the reference and that the upper bound is not exceeded; it works for single-valued as well as multi-valued references.

Question 4 – Modifying

/** Sets the attribute attrName of obj (value is converted to the declared type);
    for a multi-valued attribute, the value is added. */
public void setAttribute(EObject obj, String attrName, String value)
/** Links source to the existing element target through the reference refName (not a containment);
    for a multi-valued reference, target is added. */
public void setReference(EObject source, String refName, EObject target)
/** Removes value from the multi-valued feature featureName of obj. */
public void removeValue(EObject obj, String featureName, Object value)
/** Resets the feature featureName of obj to its default value. */
public void unset(EObject obj, String featureName)

Question 5 – Deleting

/** Deletes obj and everything it contains; afterwards, no element references obj anymore. */
public void deleteElement(EObject obj)
/** Deletes all the instances of className and returns the number of deleted elements. */
public int deleteAll(String className)

Question 6 – Saving and printing

/** Saves the model into its file, in UTF-8, with a link to the .ecore (xsi:schemaLocation). */
public void save() throws IOException
/** Saves the model into another file. */
public void saveAs(String path) throws IOException
/** Prints the model tree: one line per element (metaclass and set attributes),
    indented according to its depth. */
public void print()

Check that the saved model opens in the Eclipse reflective editor (Open With > Sample Reflective Ecore Model Editor).

Tests. With the following initial model:

<form:Form xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI"
    xmlns:form="http://poc.hms.form" name="ED EER Model">
  <fields name="id Patient">
    <fields name="first Name" type="text"/>
    <fields name="sexe" type="text"/>
  </fields>
  <fields name="id Doctor"/>
  <fields name="signature" type="text"/>
</form:Form>

the test program

public class Main {
    public static void main(String[] args) throws IOException {
        ModelManager mm = new ModelManager();
        mm.loadMetamodel("model/form/form.ecore");
        mm.loadModel("model/form/form.model");
        EObject form = mm.getRoot();

        EObject email = mm.addElement(form, "fields", "Field");
        mm.setAttribute(email, "name", "email");
        mm.setAttribute(email, "type", "text");

        EObject idPatient = mm.findByAttribute("Field", "name", "id Patient");
        EObject nationality = mm.addElement(idPatient, "fields", "Field");
        mm.setAttribute(nationality, "name", "nationality");

        EObject sexe = mm.findByAttribute("Field", "name", "sexe");
        mm.setAttribute(sexe, "type", "radio");

        mm.deleteElement(mm.findByAttribute("Field", "name", "signature"));

        mm.print();
        mm.saveAs("model/form/form-modified.model");
    }
}

must print:

Form name=ED EER Model
  Field name=id Patient
    Field name=first Name type=text
    Field name=sexe type=radio
    Field name=nationality
  Field name=id Doctor
  Field name=email type=text

Without modifying ModelManager, then use it on another metamodel and test all the operations.

Interactive program. Write a ModelEditor class that uses ModelManager to provide a console model editor (with Scanner):

  1. the user enters the path of the metamodel and that of the model (or chooses to create a new model);
  2. a menu offers: print the model, add an element, modify an attribute, link two elements, delete an element, save, quit;
  3. errors are displayed without stopping the program.

Bonus. When the user selects an element, display its attributes and references with their type and multiplicity. Before saving, check the metamodel constraints (lower bounds…) with Diagnostician.INSTANCE.validate(root) and display the errors.

Solution notes – Lab 3

Here is an implementation of the ModelManager class.

Constructor and question 1

public ModelManager() {
    Map<String, Object> m = resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap();
    m.put("ecore", new EcoreResourceFactoryImpl());
    m.put(Resource.Factory.Registry.DEFAULT_EXTENSION, new XMIResourceFactoryImpl());
}

public EPackage loadMetamodel(String path) {
    Resource r = resourceSet.getResource(URI.createFileURI(path), true);
    if (r.getContents().isEmpty() || !(r.getContents().get(0) instanceof EPackage))
        throw new IllegalArgumentException("No metamodel in " + path);
    metamodel = (EPackage) r.getContents().get(0);
    register(metamodel);
    return metamodel;
}
private void register(EPackage p) {
    resourceSet.getPackageRegistry().put(p.getNsURI(), p);
    for (EPackage sub : p.getESubpackages()) register(sub);
}

public Resource loadModel(String path) {
    model = resourceSet.getResource(URI.createFileURI(path), true);
    return model;
}

public EObject createModel(String path, String rootClassName) {
    model = resourceSet.createResource(URI.createFileURI(path));
    EObject root = createInstance(rootClassName);
    model.getContents().add(root);
    return root;
}

public EObject getRoot() {
    if (model == null || model.getContents().isEmpty())
        throw new IllegalArgumentException("No model loaded");
    return model.getContents().get(0);
}

Registering the nsURI in the registry of the ResourceSet lets the XMI loader find the package designated by xmlns:form.

Question 2

public EClass getEClassByName(String name) {
    return find(metamodel, name);
}
private EClass find(EPackage p, String name) {
    EClassifier c = p.getEClassifier(name);
    if (c instanceof EClass) return (EClass) c;          // neither EDataType nor EEnum
    for (EPackage sub : p.getESubpackages()) {
        EClass r = find(sub, name);
        if (r != null) return r;
    }
    return null;
}

public List<EObject> findAll(String className) {
    EClass c = getEClassByName(className);
    if (c == null) throw new IllegalArgumentException("Unknown metaclass: " + className);
    List<EObject> res = new ArrayList<>();
    for (Iterator<EObject> it = model.getAllContents(); it.hasNext(); ) {
        EObject o = it.next();
        if (c.isInstance(o)) res.add(o);                 // sub-classes included
    }
    return res;
}

public EObject findByAttribute(String className, String attrName, String value) {
    for (EObject o : findAll(className)) {
        EStructuralFeature f = o.eClass().getEStructuralFeature(attrName);
        if (!(f instanceof EAttribute))
            throw new IllegalArgumentException("Unknown attribute: " + attrName);
        Object v = o.eGet(f);
        if (v != null && value.equals(
                EcoreUtil.convertToString(((EAttribute) f).getEAttributeType(), v)))
            return o;
    }
    return null;
}

isInstance accepts instances of sub-classes; convertToString produces the text of a value whatever its type (EInt, enumeration…).

Question 3

public EObject createInstance(String className) {
    EClass c = getEClassByName(className);
    if (c == null) throw new IllegalArgumentException("Unknown metaclass: " + className);
    if (c.isAbstract() || c.isInterface())
        throw new IllegalArgumentException(className + " is abstract");
    return EcoreUtil.create(c);
}

@SuppressWarnings("unchecked")
public EObject addElement(EObject parent, String refName, String className) {
    EStructuralFeature f = parent.eClass().getEStructuralFeature(refName);
    if (!(f instanceof EReference) || !((EReference) f).isContainment())
        throw new IllegalArgumentException(refName + " is not a containment of "
                                           + parent.eClass().getName());
    EReference ref = (EReference) f;
    EObject child = createInstance(className);
    if (!ref.getEReferenceType().isInstance(child))
        throw new IllegalArgumentException(className + " is incompatible with "
                                           + ref.getEReferenceType().getName());
    if (ref.isMany()) {
        List<EObject> l = (List<EObject>) parent.eGet(ref);
        if (ref.getUpperBound() != ETypedElement.UNBOUNDED_MULTIPLICITY
                && l.size() >= ref.getUpperBound())
            throw new IllegalArgumentException("Upper bound reached: " + refName);
        l.add(child);
    } else {
        if (parent.eIsSet(ref))
            throw new IllegalArgumentException(refName + " is already set");
        parent.eSet(ref, child);
    }
    return child;
}

Question 4

private EStructuralFeature feature(EObject obj, String name) {
    EStructuralFeature f = obj.eClass().getEStructuralFeature(name);
    if (f == null)
        throw new IllegalArgumentException("Unknown feature: " + obj.eClass().getName() + "." + name);
    return f;
}

@SuppressWarnings("unchecked")
public void setAttribute(EObject obj, String attrName, String value) {
    EStructuralFeature f = feature(obj, attrName);
    if (!(f instanceof EAttribute) || !f.isChangeable())
        throw new IllegalArgumentException(attrName + " is not a modifiable attribute");
    EAttribute a = (EAttribute) f;
    Object v;
    try {
        v = EcoreUtil.createFromString(a.getEAttributeType(), value);
    } catch (RuntimeException e) {
        throw new IllegalArgumentException("Invalid value '" + value + "' for " + attrName, e);
    }
    if (a.isMany()) ((List<Object>) obj.eGet(a)).add(v);
    else obj.eSet(a, v);
}

@SuppressWarnings("unchecked")
public void setReference(EObject source, String refName, EObject target) {
    EStructuralFeature f = feature(source, refName);
    if (!(f instanceof EReference) || ((EReference) f).isContainment())
        throw new IllegalArgumentException(refName + " is not a non-containment reference");
    EReference r = (EReference) f;
    if (!r.getEReferenceType().isInstance(target))
        throw new IllegalArgumentException(target.eClass().getName() + " incompatible with " + refName);
    if (r.isMany()) ((List<EObject>) source.eGet(r)).add(target);
    else source.eSet(r, target);
}

public void removeValue(EObject obj, String featureName, Object value) {
    EStructuralFeature f = feature(obj, featureName);
    if (!f.isMany())
        throw new IllegalArgumentException(featureName + " is not multi-valued");
    ((List<?>) obj.eGet(f)).remove(value);
}

public void unset(EObject obj, String featureName) {
    obj.eUnset(feature(obj, featureName));
}

Question 5

public void deleteElement(EObject obj) {
    EcoreUtil.delete(obj, true);     // also removes the references to obj and its content
}

public int deleteAll(String className) {
    List<EObject> all = findAll(className);
    for (EObject o : all)
        if (o.eResource() != null)   // already deleted with its container?
            EcoreUtil.delete(o, true);
    return all.size();
}

Question 6

public void save() throws IOException {
    Map<String, Object> options = new HashMap<>();
    options.put(XMLResource.OPTION_ENCODING, "UTF-8");
    options.put(XMLResource.OPTION_SCHEMA_LOCATION, Boolean.TRUE);
    model.save(options);
}

public void saveAs(String path) throws IOException {
    model.setURI(URI.createFileURI(path));
    save();
}

public void print() {
    for (EObject root : model.getContents()) print(root, 0);
}
private void print(EObject o, int depth) {
    StringBuilder sb = new StringBuilder("  ".repeat(depth)).append(o.eClass().getName());
    for (EAttribute a : o.eClass().getEAllAttributes())
        if (o.eIsSet(a)) sb.append(' ').append(a.getName()).append('=').append(o.eGet(a));
    System.out.println(sb);
    for (EObject child : o.eContents()) print(child, depth + 1);
}

Interactive program (excerpt)

while (true) {
    System.out.println("1 Print  2 Add  3 Modify  4 Link  5 Delete  6 Save  0 Quit");
    String choice = sc.nextLine().trim();
    try {
        switch (choice) {
            case "1" -> mm.print();
            case "2" -> {
                EObject parent = select(sc, mm);
                System.out.print("Containment: ");  String ref = sc.nextLine();
                System.out.print("Metaclass: ");    String cls = sc.nextLine();
                mm.addElement(parent, ref, cls);
            }
            // 3, 4 and 5 on the same principle
            case "6" -> {
                Diagnostic d = Diagnostician.INSTANCE.validate(mm.getRoot());
                d.getChildren().forEach(c -> System.out.println(c.getMessage()));
                mm.save();
            }
            case "0" -> { return; }
            default -> System.out.println("Unknown choice");
        }
    } catch (IllegalArgumentException e) {
        System.out.println("Error: " + e.getMessage());   // the program goes on
    }
}

The select method can, for instance, designate an element by its metaclass and the value of an attribute (findByAttribute), then display its features (getEAllAttributes(), getEAllReferences(), type and bounds) for the bonus.

Further reading