3.2 Eclipse Modeling Framework
From the project description, EMF is “a modeling framework and code generation facility for building tools and other applications based on a structured data model.” This pretty much sums it up, but there’s a lot to know about EMF. I highly recommend that you first read, or at least have available, the book on EMF [38] to better understand its use in the context of this book. Alternatively, reading through the online documentation and tutorials on EMF should make its use in this book easy to follow. In other words, the examples in this book only scratch the surface of what is possible using EMF.
You can create models using EMF in many ways. You can use the provided editor (a tree with properties view) or import a set of annotated Java classes. An Ecore diagram is available from the EMFT project. If you have the XSD component installed, you can import an XSD file. If you have the Unified Modeling Language (UML) version 2 (UML2) component installed, you can import a UML2 model. If you have Graphical Modeling Framework (GMF) installed, you can use its example Ecore diagram editor. If you download and install Emfatic [42], you can work in a textual syntax and synchronize with your Ecore model. In the future, you will be able to design your own concrete textual syntax for Ecore, or any model, using the Textual Modeling Framework (TMF) project.
Regardless of the method you choose for importing or working with your domain model, you will find an .ecore file in your workspace—that is, unless you take a purely programmatic approach. If you open this file in a text editor, you will see that it is an XML Metadata Interchange (XMI) serialization of your Ecore-based model. By default, EMF enables you to edit models in a basic (generated) tree editor with a Properties view. You can easily generate a similar editor for your own model.
Before getting into more detail, let’s take a look at the Ecore metamodel.
3.2.1 Ecore Metamodel
The EMF book describes the Ecore metamodel in detail, but here you find a simplified diagram for reference (Figure 3-1), along with some discussion of the more relevant aspects used as we develop our DSL abstract syntax. It’s a fairly simple model, which is part of its strength. In most cases, you can compensate for the lack of features in Ecore by using some of the more advanced modeling techniques, which are discussed in the EMF book. A longstanding topic of debate among EMF users is the lack of an EAssociation class, but we don’t get into that here.
Figure 3-1 Ecore model
Annotations
Sometimes it’s important to add information to a model element for documentation purposes, or to provide parameters to be considered during transformation or generation. EAnnotations provide these for all model elements in EMF. An EAnnotation has a Source field, which serves as a key, and a list of References. An EAnnotation may have zero or more Details Entry children, which have Key and Value properties. This simple capability of annotating models is quite flexible and turns out to be useful for many purposes, including XSD support.
Another particularly useful application of annotations is to declare OCL constraints, method bodies, and derived feature implementation, as discussed in Section 3.2.4, “Applying OCL.”
3.2.2 Runtime Features
The EMF runtime includes facilities for working with instances of your models. No strict dependencies exist on the Eclipse platform for the runtime and generated model and edit code, so these bundles can be used outside of the Eclipse workbench. As bundles, they can be deployed in any Equinox OSGi container, even within a server environment.
The generated code for your model has a dependency on the underlying EMF runtime components. A significant benefit is gained from the generated Application Programming Interface (API) and model implementation working with the provided runtime features. An efficient observer pattern implementation is provided to alert listeners to model change events. A generated reflective API provides an efficient means of working with models dynamically. In fact, EMF can be used in a purely dynamic fashion, requiring neither an .ecore model nor code generation. Finally, it’s possible to have static registration of a dynamic package, but that’s an advanced use case left to the EMF documentation.
When working with model instances, changes can be recorded in a change model that provides a reverse delta and allows for transaction support. A validation framework provides for invariant and constraint support with batch processing. The Model Transaction and Validation Framework components provide enhanced transaction and validation support, respectively.
For persistence of models, the EMF runtime provides a default XML serialization. The persistence layer is flexible, allowing for XMI, Universally Unique Identifiers (UUIDs), and even a zip option. A resource set consists of one or more resources, making it possible to persist objects in multiple files, including cross-containment references. Proxy resolution and demand loading improve performance when working with large models across resources. Additionally, use of EMF Technology (EMFT) components Teneo and CDO allow for the persistence of models to a relational database.
The generated editor for EMF models includes a multipage editor and properties view. Drag-and-drop support is provided, as is copy/paste support. A number of menu actions are available in the generated editor, including validation invocation and dynamic instance model creation. Each generated editor comes with a default creation wizard. Figure 3-2 shows an example of the editor, including a context menu showing options to create new elements, cut, copy, paste, delete, validate, and so on.
Figure 3-2 EMF-generated editor
3.2.3 Code Generation
From an *.ecore (Ecore) model, you need to produce a generator model and supply additional information required for code generation. An EMF generator model has a *.genmodel file extension and is essentially a decorator model for a corresponding *.ecore model. This generator model is fed to Java Emitter Templates (JETs) that are used to write Java and other files. JET is the Java Server Pages (JSP)-like technology used by default when generating text from Ecore models. This book does not cover it in detail, but a tutorial is available online [51] if you want to know more.
You can customize the existing generation output using custom templates. Furthermore, you can extract constraint, pre-/post-condition, and body implementations from OCL annotations for use in generation and invocation at runtime. This is not a native EMF capability, but you can add it using the MDT OCL component. You will use this technique in the context of the sample projects.
When regenerating code, the JMerge component is used to prevent overwriting user modifications. Generated Java code is annotated with @generated javadoc style tags to identify it and distinguish it from user code. Removing the tag or adding NOT after the tag ensures that JMerge will not overwrite the modified code. Typically, using @generated NOT is preferred because it allows the Toolsmith to identify code that was generated and modified, as opposed to newly added code. Note that not all code benefits from merging. Specifically, plugin.xml and MANIFEST.MF files need to be deleted before an update can occur.
3.2.4 Applying OCL
Many opportunities arise for using OCL in EMF models. Class constraints, method bodies, and derived feature implementations can all be provided using MDT OCL and EMF dynamic templates. The approach of using OCL and custom templates in this book comes from an Eclipse Corner article [44] and has been modified only slightly to conform to a similar approach taken to leverage OCL added to models in QVT, as discussed in Section 6.5.6, “Leveraging OCL in EMF Models.” The templates are generic and can easily be added to any project that needs to provide OCL-based implementations in its generated model code. It is also worth noting that GMF uses OCL extensively in its models, employing an EMF Validator to maintain the integrity of its models.
To add an OCL expression to a model element, we begin by adding a normal EAnnotation. For the Source property, enter http://www.eclipse.org/2007/OCL. This URI allows our custom templates and QVT engine to recognize this annotation as OCL, where it can expect to find Details Entry children of type constraint, derive, or body. Note that the original article [44] used http://www.eclipse.org/ocl/examples/OCL as the URI.
Depending on the context, add the appropriate Key (EMF constraint key, derive, or body) to a child Details Entry of the EAnnotation and specify the OCL in the Value property. For invariant constraints, the OCL annotations complement the normal EMF constraint annotations by providing implementation for the validation framework to enforce constraints.
To invoke the provided OCL at runtime, you must use custom JET templates for your domain model. The generated code retrieves the OCL statement from the model element and invokes it, evaluating the result. An alternative to this is to generate a Java implementation of the OCL during generation and avoid invoking the OCL interpreter at runtime.
The referenced article covers the details of the custom templates, so they are not covered here. Also, the templates are included in the book’s sample projects and are touched upon during the development of the sample projects. For now, we take a look at just the derived feature implementation, both before and after using the OCL with a custom template approach. First, consider the default generated code for a derived reference—in this case, the rootTopics reference from the MapImpl class in our mindmap example.
/** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<Topic> getRootTopics() { // TODO: implement this method to return the 'Root Topics' // reference list // Ensure that you remove @generated or mark it @generated NOT // The list is expected to implement // org.eclipse.emf.ecore.util.InternalEList and // org.eclipse.emf.ecore.EStructuralFeature.Setting // so it's likely that an appropriate subclass of // org.eclipse.emf.ecore.util.EcoreEList should be used. throw new UnsupportedOperationException(); }
Let’s add the following OCL statement to the derived feature using the previous convention. Here we see the annotation within the mindmap.ecore model in its native XMI serialization. Note that this OCL statement could be simplified by using the parent eOpposite relationship on our Topic’s subtopics reference, which was added to facilitate the diagram definition of Section 4.3.5, “Subtopic Figure.”
<eStructuralFeatures xsi:type="ecore:EReference" name="rootTopics" upperBound="-1" eType="#//Topic" volatile="true" transient="true" derived="true"> <eAnnotations source="http://www.eclipse.org/2007/OCL"> <details key="derive" value="let topics : Set(mindmap::Topic) = self.elements-> select(oclIsKindOf(mindmap::Topic))-> collect(oclAsType(mindmap::Topic))->asSet() in topics->symmetricDifference(topics.subtopics-> asSet())"/> </eAnnotations> </eStructuralFeatures>
Before regeneration, we need to make some changes in the genmodel. To allow the OCL plug-in to be added to our generated manifest dependencies, we need to add OCL_ECORE=org.eclipse.ocl.ecore to the Model Plug-in Variables property of the genmodel root. Also, we need to set the Dynamic Templates property to true and enter the templates path (such as /org.eclipse.dsl.mindmap/templates/domain) to the Template Directory property. After we generate, we can see the following implementation in our MapImpl class.
private static OCLExpression<EClassifier> rootTopicsDeriveOCL; private static final String OCL_ANNOTATION_SOURCE = "http://www.eclipse.org/2007/OCL"; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<Topic> getRootTopics() { EStructuralFeature eFeature = MindmapPackage.Literals.MAP__ROOT_TOPICS; if (rootTopicsDeriveOCL == null) { Helper helper = OCL_ENV.createOCLHelper(); helper.setAttributeContext(MindmapPackage.Literals.MAP, eFeature); EAnnotation ocl = eFeature.getEAnnotation(OCL_ANNOTATION_SOURCE); String derive = (String) ocl.getDetails().get("derive"); try { rootTopicsDeriveOCL = helper.createQuery(derive); } catch (ParserException e) { throw new UnsupportedOperationException(e.getLocalizedMessage()); } } Query<EClassifier, ?, ?> query = OCL_ENV.createQuery(rootTopicsDeriveOCL); @SuppressWarnings("unchecked") Collection<Topic> result = (Collection<Topic>) query.evaluate(this); return new EcoreEList.UnmodifiableEList<Topic>(this, eFeature, result.size(), result.toArray()); }
The generated code checks to see if the OCLExpression for this derivation has been created already; if not, it initializes it by retrieving the statement from the EAnnotation and its detail with key derive. Then the expression is evaluated and the list of Topic elements is returned.
As mentioned in the article, some improvements could be made to this approach, but it illustrates the usefulness of adding OCL statements to your EMF models. It’s not hard to imagine how a significant portion of an application could be generated from a model adorned with OCL for invariant constraints, method bodies, and derived features. In GMF, we can see how OCL is used to augment the diagram-mapping model to provide for constraints, feature initialization, audit definition, and model metric definition.
3.2.5 Dynamic Instances
A powerful feature of EMF, and one that is useful to a Toolsmith developing a new DSL, is the capability to create dynamic instances of a model. The reflective framework of EMF is leveraged to allow instantiation of a model element without generating code beforehand. This can be done from within the default Ecore editor by selecting an element and choosing the Create Dynamic Instance context menu item. The instance is stored in an XMI file within the development workspace, so the generation or launch of plug-ins is not required to test a model or, more importantly, to test Xpand templates and QVT transformations under development. This is one important distinction when comparing JET to Xpand. Dynamic instances are used in the context of our sample projects.
Figure 3-3 is an example of a dynamic instance model for our mindmap domain model, along with the Properties view. It’s similar in functionality to the generated EMF editor, although it requires the metamodel to be loaded and reflected upon, as you can see from the loaded mindmap.ecore resource file.
Figure 3-3 Mindmap dynamic instance model