This presentation describes Eclipse Modeling Framework – EMF. It has two basic purposes:
Introduce you to the EMF techniques needed in the rest of the course
Introduce you to the architecture and components of the EMF project
This presentation is developed for MDD 2010 course at ITU, Denmark.
DUST OF SNOW_BY ROBERT FROST_EDITED BY_ TANMOY MISHRA
ITU - MDD - EMF
1. L0079 - 2009-08-27
Redistribution and other use of this material requires written permission from The RCP Company.
ITU - MDD - EMF
This presentation describes Eclipse Modeling Framework – EMF. It has two basic
purposes:
Introduce you to the EMF techniques needed in the rest of the course
Introduce you to the architecture and components of the EMF project
This presentation is developed for MDD 2010 course at ITU, Denmark.
2. L0061 - 2008-04-27
2
What is EMF?
A modeling & data integration framework
Exploits the facilities offered in Eclipse to…
Generate code without losing user customizations (merge)
Automate important tasks (such as registering the runtime information)
Improve extensibility
Provide a UI layer
What is an EMF “model”?
Specification of your application’s data
Object attributes
Relationships (associations) between objects
Operations available on each object
Simple constraints (e.g. cardinality) on objects and relationships
Essentially it represents the class diagram of the application
Based on eMOF
Can be used to represent itself – so it is its own meta model!
3. L0061 - 2008-04-27
3
Creating the Ecore Model
Representing the modeled domain in Ecore is the first step in using EMF
Ecore can be created…
Directly using the EMF editors
Through a graphical UI provided by external contributions
By converting a model specification for which a Model Importer is available
Model Importers available in EMF
Java Interfaces
UML models expressed in Rational Rose® files
XML Schema
Choose the one matching your perspective or skills
4. L0061 - 2008-04-27
4
EMF Tools: Model Import and Generation
Generator Features:
Customizable JSP-like templates
(JET)
JDT-integrated, command-line,
or Ant
Fully supports regeneration and
merge
I
M
P
O
R
T
GENERATE
Ecore
Model
UML
XML
Schema
Java
model
Java
edit
Java
editor*
* Eclipse IDE-integrated
or RCP-based
Java
model
5. L0061 - 2008-04-27
5
Model Importers Available in EMF
Annotated Java Interfaces
/**
* @model
*/
public interface Contact {
/**
* Returns the name of the contact.
*
* @return the name
* @model
*/
public String getName();
/**
* Returns the locations of the contact.
* @return a list of the locations
* @model containment="true" opposite="contact"
*/
public EList<Location> getLocations();
}
6. L0061 - 2008-04-27
6
Kick Start EMF
Create “Empty EMF Project”
Create “Ecore Model”
Add “stuff” to the model
Create EMF Model
Edit genmodel file
Generate Java code
Test new model file
7. L0061 - 2008-04-27
7
Kick Start EMF
Edit Files If Needed
Change values using the Properties view
.ecore
Change Ns Prefix to “cm”
Change Ns URI to “http://rcpcompany.com/training/labs/L0061.ecore”
Change Containment to true for all 1:n references
.genmodel
Change Model Name to “CM”
Change Edit/Children and Edit/Create Child to true for all 1:n references
8. L0061 - 2008-04-27
8
Lab Exercise
Create EMF model and an editor for the following model
Optionally type is an enumeration with the values HOME and WORK
The rest of the attributes are Strings
Check that an editor can be created and write a file…
Check in alternative editor
Contact
Manager
0..n
firstName,
familyName
Location
0..n
type, street,
city, country
9. L0061 - 2008-04-27
9
EMF Files
modelname.ecore
Ecore model file in XMI format
Canonical form of the model
modelname.genmodel
A “generator model” for specifying generator options
Contains decorators for Ecore model elements, providing details that would
otherwise pollute the model (e.g. target directories for code generation)
EMF code generator is an EMF .genmodel editor
Automatically kept in synch with .ecore file
11. L0061 - 2008-04-27
11
Ecore Model Editor
A graphical editor is a better approach
GMF Ecore Diagram Example (http://www.eclipse.org/gmf/)
Omondo EclipseUML (http://www.omondo.com/)
UML2 project (http://www.eclipse.org/modeling/mdt/?project=uml2)
12. L0061 - 2008-04-27
12
EMF Generator
Similar layout to Ecore model editor
Automatically keeps in synch with .ecore
changes
Generate code with pop-up menu actions
Generate Model Code
Generate Edit Code
Generate Editor Code
Generate Test Code
Generate All
Code generation options in Properties
view
Generator > Reload to reload .genmodel
and .ecore files from original model
form
13. L0061 - 2008-04-27
13
The EMF Meta Information Model
0..1
EAttribute
EReference
EClass
EDataType
0..*
0..*
0..*
attributeType
opposite
superTypes
referenceType
14. L0061 - 2008-04-27
14
The EMF Meta Object Model
ENamedElement
EModelElement
0..1
ETypedElementEClassifier
EStructuralFeature
EAttribute
EReference
EClass
EDataType
0..*
0..*
0..*
type
opposite
superTypes
15. L0061 - 2008-04-27
15
Ecore Model for Purchase Orders
PurchaseOrder
shipTo : String
billTo : String
Item
productName : String
quantity : int
price : float0..*
items
0..*
EClass
(name="PurchaseOrder")
EAttribute
(name="shipTo")
EAttribute
(name="billTo")
EReference
(name="items")
EClass
(name="Item")
EAttribute
(name="productName")
. . .
eReferenceType
is represented in Ecore as
16. L0061 - 2008-04-27
16
EModelElement
Represents the base class for all other EMF meta entities
Includes annotations, which can save arbitrary data for all objects
documentation, XSD namespace, etc…
all non-core attributes from @model javadoc declarations are recorded as
annotations
ENamedElement
EModelElement
0..1
ETypedElementEClassifier
EStructuralFeature
EAttribute
EReference
EClass
EDataType
0..*
0..*
0..*
typ
e
opposite
superTypes
17. L0061 - 2008-04-27
17
ENamedElement
Represents an element with a name (just about everything)
Includes
name – the name of the element
ENamedElement
EModelElement
0..1
ETypedElementEClassifier
EStructuralFeature
EAttribute
EReference
EClass
EDataType
0..*
0..*
0..*
typ
e
opposite
superTypes
18. L0061 - 2008-04-27
18
ETypedElement
Represents an element with a type (attribute, reference, operation, parameter)
Includes
type – the type of the object (either EClass or EDataType)
lowerBound, upperBound, many (t) and required (t) – the cardinality of the
element in respect to the type
ordered – the ordering of elements
unique – for multiplicity-many elements, whether elements are unique in the
container
ENamedElement
EModelElement
0..1
ETypedElementEClassifier
EStructuralFeature
EAttribute
EReference
EClass
EDataType
0..*
0..*
0..*
typ
e
opposite
superTypes
19. L0061 - 2008-04-27
19
EClassifier
Represents the common functionality for classes and data types
typeParameters – the generic type parameters for the class
ENamedElement
EModelElement
0..1
ETypedElementEClassifier
EStructuralFeature
EAttribute
EReference
EClass
EDataType
0..*
0..*
0..*
typ
e
opposite
superTypes
20. L0061 - 2008-04-27
20
EClass
Represents a class with contained attributes and references
abstract – whether the class can be instantiated
interface – whether the implementation class is generated
ENamedElement
EModelElement
0..1
ETypedElementEClassifier
EStructuralFeature
EAttribute
EReference
EClass
EDataType
0..*
0..*
0..*
typ
e
opposite
superTypes
21. L0061 - 2008-04-27
21
EDataType
Represents a primitive data type
Many predefined data types
Enumerations
Ecore Data Type
Java Primitive
Type or Class
EBoolean boolean
EChar Char
EFloat Float
EString java.lang.String
EByteArtray byte[ ]
EBooleanObject java.lang.Boolean
EFloatObjhect java.lang.Float
EJavaObject java.lang.Object
ENamedElement
EModelElement
0..1
ETypedElementEClassifier
EStructuralFeature
EAttribute
EReference
EClass
EDataType
0..*
0..*
0..*
typ
e
opposite
superTypes
22. L0061 - 2008-04-27
22
EStructuralFeature
Represents a member of a class (attribute or reference)
Includes
transient – whether the value is stored in any external representations
volatile – whether the value is calculated when needed
changeable – whether the value can be changed via a set-method
unsettable – whether the value can be a special null value
derived – whether the value is derived from other attributes
defaultValue – any default value
ENamedElement
EModelElement
0..1
ETypedElementEClassifier
EStructuralFeature
EAttribute
EReference
EClass
EDataType
0..*
0..*
0..*
typ
e
opposite
superTypes
23. L0061 - 2008-04-27
23
EAttribute
Represents an attribute of a class
id – whether the attribute is an ID in the class – the first ID attribute is special
IDs are used for references in external representations – e.g. XML
ENamedElement
EModelElement
0..1
ETypedElementEClassifier
EStructuralFeature
EAttribute
EReference
EClass
EDataType
0..*
0..*
0..*
typ
e
opposite
superTypes
24. L0061 - 2008-04-27
24
EReference
Represents a reference to a class
opposite – the opposite relation
resolveProxies – whether references are resolved automatically
containment, container (t) – whether the reference is contained in/a container
for the opposite object
ENamedElement
EModelElement
0..1
ETypedElementEClassifier
EStructuralFeature
EAttribute
EReference
EClass
EDataType
0..*
0..*
0..*
typ
e
opposite
superTypes
25. L0061 - 2008-04-27
25
Generated Code
Code is generated using JET – Java Emitter Templates
Based on PHP-like or JSP-like language (.javajet files)
Consult plug-ins org.eclipse.emf.codegen.*
Many @model attributes change the generated code
Especially on EStructualFeature, EAttribute and EReference
26. L0061 - 2008-04-27
26
Generated Code
Overriding Methods
There are several ways to override generated code
All generated code annotated with @generated javadoc
If code is changed, change the comment to @generated NOT
Add Gen suffix to original method name to original code with custom code
Methods without @generated marker are left alone during regeneration
/**
* @generated NOT
*/
public void setName(String newName) {
assert newName != null;
setNameGen(newName);
}
/**
* @generated
*/
public void setNameGen(String newName) {
…
}
/**
* @generated
*/
public void setName(String newName) {
…
}
27. L0061 - 2008-04-27
27
Generated Code
Simple Attributes
Simple attributes hold no surprises
Notification constructed when needed
Attribute identified by ID
public String getName() {
return name;
}
public void setName(String newName) {
String oldName = name;
name = newName;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET,
ContactPackage.LOCATION__NAME, oldName, name));
}
/**
* @model
*/
public String getName();
28. L0061 - 2008-04-27
28
Generated Code
Multi-Valued Attributes and References
Different than the “normal” Java design pattern
Only one method per attribute or reference
public List<Location> getLocations();
public void addLocation(Location location);
public void removeLocation(Location location);
public void clearLocations();
public EList<Location> getLocations();
contact.addLocation(location); contact.getLocations().add(location);
29. L0061 - 2008-04-27
29
Generated Code
Volatile Attributes and References
Volatile attributes and references get (near-)empty bodies
/**
* @generated
*/
public String getSurname() {
throw new UnsupportedOperationException();
}
30. L0061 - 2008-04-27
30
Lab Exercise
Use previous model
Add new read-only attribute in Contact named fullName:
Returns “<firstName> <familyName>”
Remember to make it transient – why?
Check result in editor: correct and read-only
Extra: make the attribute changeable
31. L0061 - 2008-04-27
31
Model Change Notification
Every EMF object is also a Notifier
Send notification (Notification) whenever an attribute or reference is changed
EMF objects can be “observed” in order to update views and dependent objects
For various reasons a model change listener is also called an adaptor
Adapter poObserver = ...
purchaseOrder.eAdapters().add(poObserver);
adapter.notifyChanged()
setBillTo()
PurchaseOrder
Adapter
32. L0061 - 2008-04-27
32
Persistence and Serialization
Serialized data is referred to as a resource
Data can be spread out among a number
of resources in a resource set
One resource is loaded at a time, even if it
has references to objects in other
resources in the resource set
Proxies exist for objects in other
resources
Lazy or demand loading of other
resources as needed
A resource can be unloaded
Resource 2Resource 1
ResourceSet
Client
load
demand-load
resource 2
resource 1 uri 1 resource 1
uri 2 resource 2
33. L0061 - 2008-04-27
33
Recording Changes
EMF provides facilities for recording the changes made to instances of an Ecore model
Change Model
An EMF model for representing changes to objects
Directly references affected objects
Includes “apply changes” capability
Change Recorder
EMF adapter
Monitors objects to produce a change description (an instance of the change
model)
34. L0061 - 2008-04-27
34
Change Recorder
Can be attached to EObjects, Resources, and ResourceSets
Monitors changes to the objects and their contents trees
Produces a description of the changes needed to return to the original state (a reverse
delta)
Result: a change description with one change, setting billTo to “123 Elm St.”
PurchaseOrder order = ...
order.setBillTo("123 Elm St.");
ChangeRecorder recorder = new ChangeRecorder();
recorder.beginRecording(Collections.singleton(order));
order.setBillTo("456 Cherry St.");
ChangeDescription change = recorder.endRecording();
35. L0061 - 2008-04-27
35
Example: Transaction Capability
If any part of the transaction fails, undo the changes
ChangeRecorder changeRecorder = new ChangeRecorder(resourceSet);
try {
// modifications within resource set
} catch (Exception e) {
changeRecorder.endRecording().apply();
}
36. L0061 - 2008-04-27
36
What does the Transaction API Provide?
A transactional editing environment
Safe read and write access to EMF resources from multiple concurrent threads
Commit protocol providing mechanisms for ensuring model integrity:
Validation of the changes performed during the transaction (constraints) using
the Validation Framework
Pre-commit listeners proactively performing concomitant changes (triggers) to
maintain consistency of dependencies
Automatic rollback of changes on failure to validate or complete triggers
Supports transaction nesting
37. L0061 - 2008-04-27
37
Validation Framework
Model objects validated by external EValidator
Detailed results accumulated as Diagnostics
Essentially a non-Eclipse equivalent to IStatus
Records severity, source plug-in ID, status code, message, other arbitrary data,
and nested children
public interface Evalidator {
Boolean validate(EObject eObject,
DiagnosticChain diagnostics, Map Context);
boolean validate(EClass eClass, EOjbect eObject,
DiagnosticChain, diagnostics, Map context);
boolean validate(EDataType eDataType, Object value,
DiagnosticChain diagnostics, Map context);
...
}
38. L0079 - 2009-08-27
38
Question/Exercise 1
Implement the data model for Noware Travel as an ecore model in EMF
Take care that the model can be validated by the built-in tools of EMF
Which relations are containment relations?
In a real-world scenario, which attributes should be strings, enumerations or relations
to other entities – e.g. Parameter name, Flight destinationTown and Item name.
39. L0079 - 2009-08-27
39
Question/Exercise 2
Generate an EMF editor from the .ecore model
Implement the travel packages from previous lecture
Question 2: Model an “adventure” travel package to Thailand, which includes either
a trekking tour or a parachute tour. Model a “family” travel to Gran Canaria, which
includes renting a car. For each package, also what data is required for ordering
the package
Question 3: The family Hansen wants a Family travel package to Gran Canaria.
Draw the instance of the Family package with data for the Hansen family. For
instance, we need to know how many persons they are to order the right size of a
hotel room. This information is not present in the model from question 2. In the
model, we only described what data was required for model instances. The real
customer must provide the real data.
40. L0079 - 2009-08-27
40
Question/Exercise 3
Given your EMF model, informally describe the types of validation that can/should be
performed on a concrete instance of a family travel in the form “this attribute should
be equal to this attribute” and “this object should only have n children”…
41. L0087 - 2010-09-19
41
Syllabus (”Pensum”)
The reading materials for this lecture is in the form of the following three items:
These slides
"Essential EMF" by Ed Merks and James Sugrue -
http://refcardz.dzone.com/refcardz/essential-emf(direct link) - Very good and
quite essential overview of EMF
"Eclipse Modeling Framework (EMF) - Tutorial" by Lars Vogel - http://
www.vogella.de/articles/EclipseEMF/article.html - as always, a good tutorial by Lars
42. L0061 - 2008-04-27
42
More Information
“EMF – Eclipse Modeling Framework” by Frank Budinsky, David Steinberg, Ed Merks,
and Raymond Ellersick (ISBN 978- 0321331885)
“Eclipse Modeling Framework (EMF) and Java Emitter Template (JET) - Tutorial”
http://www.eclipse.org/resources/resource.php?id=419
Very good introduction JET – as well as a very short introduction to EMF itself.
“EMF – Eclipse Modeling Framework” by Frank Budinsky, David Steinberg, Ed Merks,
and Raymond Ellersick (ISBN 978- 0321331885)
“Eclipse Modeling Framework (EMF) and Java Emitter Template (JET) - Tutorial”
http://www.eclipse.org/resources/resource.php?id=419
Very good introduction JET – as well as a very short introduction to EMF itself.
Notas del editor
Now it’s time for the lab.
Class models classes themselves. Classes are identified by name and can have a number of attributes and references. To support inheritance, a class can refer to a number of other classes as its supertypes.
Attribute models attributes, the components of an object&apos;s data. They are identified by name, and they have a type.
DataType models the types of attributes, representing primitive and object data types that are defined in Java, but not in EMF. Data types are also identified by name.
Reference is used in modeling associations between classes; it models one end of such an association. Like attributes, references are identified by name and have a type. However, this type must be the Class at the other end of the association. If the association is navigable in the opposite direction, there will be another corresponding reference. A reference specifies lower and upper bounds on its multiplicity. Finally, a reference can be used to represent a stronger type of association, called containment; the reference specifies whether to enforce containment semantics.
The complete EMF data model for a specific domain model (your model!) is normally always presents and can be queried to get relevant meta information.
The model includes the following objects:
EModelElement is the base class for all model classes. Includes support for annotations.
ENamedElement specifies an element with a name – typically unique within the scope (e.g. attributes within a class).
ETypedElement specifies an element with a type (either primitive – see EDataType – or a class – see EClass). Includes cardinality (lowerbound, upperbound), ordering and uniqueness.
EStructuralFeature specifies a member of a class – either an attribute or a reference.
EClassifier represents a type in the model – either a class or a data type