Introducing the Eclipse Modeling
Framework
Juan Manuel Vara
Kybele Research Group
University Rey Juan Carlos
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 20092 16/03/2009
References
• Fundamentals of the Eclipse Modeling Framework
EclipseCON2008, Dave Steinberg
• Model-Handling with EMF
Open Model CourseWare (OMDW), ATLAS group,University
of Nantes, 2007.
• Eclipse Modeling Framework
Frank Budinsky, Dave Steinberg, Ed Merks, Ray Ellersick,
Timothy J. Grose, Addison-Wesley Professional, 2003.
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 20093 16/03/2009
Goals
• Paper stands for all
Show how the MDE proposals can be deployed in a real
framework
• Introduce the Eclipse Modelling Framework (EMF), the
modeling platform most commonly used nowadays
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 20094 16/03/2009
Agenda
• Introduction
MDE & EMF
The Eclipse Platform
• Defining a Model with EMF
• EMF Architecture
• Code Generation
• Programming with EMF
• EMF.Edit
• Summary
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 20095 16/03/2009
MDE Principles
• Current engineering approaches
Models not part of engineering processes (documentation)
• MDE approach
Models as first class entities
Need for dedicated tools
• MDE basic concepts
System – real world situation
Model – abstraction of a system
Describe a given aspect of the system
Metamodel – rules to define an abstraction
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 20096 16/03/2009
Model Driven Architecture (MDA)
• A software architecture proposed by the OMG (Object
Management Group)
• Application specified in high-level, Platform
Independent Model (PIM)
• Transformation technologies used to convert PIM to
Platform Specific Model (PSM), implementation code
• Includes several open modeling standards:
UML™ (Unified Modeling Language)
MOF (Meta-Object Facility)
XMI (XML Metadata Interchange)
CWM (Common Warehouse Model)
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 20097 16/03/2009
Model-Driven Architecture
Metamodel
Metamodel element
Metametamodel
Metametamodel element
conformsTometa
conformsTo
Model
Model element
conformsTometa
repOfSystem
metaMOF
Relational
metamodel
M3
M2
M1
UML
metamodel…
… …
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 20098 16/03/2009
Model-Driven Architecture: Example
repOf
Relational Model
Book
conformsTo
Relational Metamodel
MOF Metametamodel
ClassAssociation
source
destination
conformsTo
conformsTo
System
…………
…………
AuthorIdPagesNbTitleBookId
Type
name: String
Table
name: String
+ type*+ col
+ owner
+ keyOf + key1..* *
*
Column
name: String{ordered}
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 20099 16/03/2009
MDA – Are We There Yet?
• Doubts exist about the ability of MDA to deliver on its
promises:
Ambitiousness of vision
Model expressiveness vs. complexity
Availability of implementations (“vaporware”)
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200910 16/03/2009
Operating on Models
• Model persistence
Loading/saving
• Model edition
Creation/deletion/modification
• Model navigation
conformsTo/meta relations
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200911 16/03/2009
EMF
• EMF is a Java-based environment for development
of tools and other applications based on a structured
model
• EMF is a simple, pragmatic approach to modeling:
Allows us to generate some of the code that we write over
and over, paving the way for more complex systems
(including more ambitious MDA tools)
Models are simple, but meant to be mixed with hand-written
code
It’s real, proven technology (since 2002)
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200912 16/03/2009
Model Driven Development with EMF
• Contrary to the belief of many programmers, modeling
is useful for more than just documentation
• Almost every program we write manipulates some
data model
Defined using UML, XML Schema, some other definition
language, or implicitly in Java™
• EMF aims to extract this intrinsic “model” and generate
some of the implementation code
Can be a tremendous productivity gain
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200913 16/03/2009
EMF at Eclipse.org
• Foundation for the Eclipse Modeling Project
EMF project incorporates core and additional mature components:
Query, Transaction, Validation
EMF Technology project incubates complementary components:
CDO, Teneo, Compare, Search, Temporality, Ecore Tools…
Other projects build on EMF: Graphical Modeling Framework (GMF),
Model Development Tools (MDT), Model to Model Transformation
(M2M), Model to Text Transformation (M2T)…
• Other uses: Web Tools Platform (WTP), Data Tools Platform
(DTP), Business Intelligence and Reporting Tools (BIRT), SOA
Tools Platform (STP)…
• Large open source user community
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200914 16/03/2009
Agenda
• Introduction
MDE & EMF
The Eclipse Platform
• Defining a Model with EMF
• EMF Architecture
• Code Generation
• Programming with EMF
• EMF.Edit
• Summary
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200915 16/03/2009
What is Eclipse?
• Eclipse is a universal platform for integrating
development tools
• Open, extensible architecture based on plug-ins
Java VMStandard Java2Virtual Machine
PlatformEclipse Platform
Java developmenttools
JDT
PDEPlug-in development
environment
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200916 16/03/2009
Eclipse Plug-in Architecture (1/2)
• Plug-in - smallest unit of Eclipse function
Big example: HTML editor
Small example: Action to create zip files
• Extension point - named entity for collecting
“contributions”
Example: extension point for workbench preference UI
• Extension - a contribution
Example: specific HTML editor preferences
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200917 16/03/2009
Eclipse Plug-in Architecture (2/2)
• Each plug-in
Contributes to 1 or more extension points
Optionally declares new extension points
Depends on a set of other plug-ins
Contains Java code libraries and other files
May export Java-based APIs for downstream plug-ins
Lives in its own plug-in subdirectory
• Details spelled out in the plug-in manifest
Manifest declares contributions
Code implements contributions and provides API
plugin.xml file in root of plug-in subdirectory
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200918 16/03/2009
Eclipse Platform Architecture
• Eclipse Platform Runtime is micro-kernel
All functionality supplied by plug-ins
• Eclipse Platform Runtime handles start up
Discovers plug-ins installed on disk
Matches up extensions with extension points
Builds global plug-in registry
Caches registry on disk for next time
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200919 16/03/2009
Agenda
• Introduction
• Defining a Model with EMF
• EMF Architecture
• Code Generation
• Programming with EMF
• EMF.Edit
• Summary
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200920 16/03/2009
What is an EMF “Model”?
• Specification of an application’s data
Object attributes
Relationships (associations) between objects
Operations available on each object
Simple constraints (e.g. multiplicity) on objects and
relationships
• Essentially, the Class Diagram subset of UML
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200921 16/03/2009
Model Sources
• EMF models can be defined in (at least) three ways:
1. Java Interfaces
2. UML Class Diagram
3. XML Schema
• Choose the one matching your perspective or skills
and EMF can create the others, as well as the
implementation code
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200922 16/03/2009
(Annotated) Java Interfaces
• Classes can be defined completely by a subset of
members, supplemented by annotations
public interface PurchaseOrder{String getShipTo();void setShipTo(String value);String getBillTo();void setBillTo(String value);List<Item> getItems(); // containment
}
EMF "would" introspect them
and deduce the model
properties
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200923 16/03/2009
UML Class Diagram
• Built-in support for Rational Rose®
• UML2 support available with UML2 (from MDT)
PurchaseOrder
shipTo : String
billTo : String
Item
productName : String
quantity : int
price : float0..*
items
0..*
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200924 16/03/2009
XML Schema
<?xml version="1.0" encoding="UTF-8"?><xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.example.com/SimplePO"xmlns:po="http://www.example.com/SimplePO">
<xsd:complexType name="PurchaseOrder"><xsd:sequence><xsd:element name="shipTo" type="xsd:string"/><xsd:element name="billTo" type="xsd:string"/><xsd:element name="items" type=“po:Item"
minOccurs="0" maxOccurs="unbounded"/></xsd:sequence>
</xsd:complexType><xsd:complexType name="Item"><xsd:sequence><xsd:element name="productName" type="xsd:string"/><xsd:element name="quantity" type="xsd:int"/><xsd:element name="price" type="xsd:float"/>
</xsd:sequence></xsd:complexType>
</xsd:schema>
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200925 16/03/2009
Unifying UML, XML and Java
• All three forms provide the same information
Different visualization/representation
The application’s data “model” or structure
Model importers can be added for different model
representations (e.g. RDB Schema)
• From a model definition, EMF can generate…
Java implementation code, including UI
XML Schemas
Eclipse “plug-in” artifacts
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200926 16/03/2009
Direct Ecore Modeling
• Ecore models can be created directly
Sample Ecore editor (in EMF)
Ecore Tools graphical editor (from EMFT)
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200927 16/03/2009
Ecore
• EMF’s metamodel (model of a model)
EStructuralFeature
name : String
EClass
name : String0..*
eStructuralFeatures
0..*
0..*
eSuperTypes
0..*
EReference
containment : boolean
lowerBound : int
upperBound : int
1eReferenceType 1
0..1eOpposite 0..1
EDataType
name : StringEAttribute
1
eAttributeType
1
The model used to represent EMF
models is called ECore.
ECore is itself an EMF model, so we
can say that it is the meta-model to
itself
It is usually used to specify platform
independent models.
It is actually also a meta-metamodel
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200928 16/03/2009
Ecore Modeling Concepts
•EClass - used for representing a modeled class. It
has a name, zero or more attributes, and zero or more
references
•EAttribute - used for representing a modeled
attribute. Attributes have a name and a type
•EReference - used for representing an association
end between classes. It has a name, a boolean
attribute that indicates if it implies containment, or
a destination reference type, which is another class.
•EDataType - used for representing attribute types.
This type can be primitive, such as int or float, or
object type, such as java.util.Date
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200929 16/03/2009
Ecore Modeling Concepts
• [Abstract] Classes, Interfaces
• Attributes and Operations
• Data types (…)
• User Defined and Enum Data Types
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200930 16/03/2009
Ecore Modeling Concepts
• References ↔ Associations
One-way
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200931 16/03/2009
Ecore Modeling Concepts
• References ↔ Associations
Bidirectional
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200932 16/03/2009
Ecore Modeling Concepts
• Containment Relationships
• Inheritance
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200933 16/03/2009
Ecore
• Application models (e.g. families model) are instances
of ECore
EClass
(name=“Family")
EClass
(name=“Daughter")
EAttribute
(name=“firstName")
EAttribute
(name=“lastName")EReference
(name=“daughters")
eReferenceType
EAttribute
(name=“firstName")
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200934 16/03/2009
Ecore
• Persistent format is XMI (.ecore file)
<eClassifiers xsi:type="ecore:EClass" name="Family"><eStructuralFeatures xsi:type="ecore:EAttribute"
name="lastName" ordered="false“ unique="false" lowerBound="1" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EString"/>
<eStructuralFeatures xsi:type="ecore:EReference" name="father" ordered="false“lowerBound="1" eType="#//Father" containment="true" eOpposite="#//Father/familyFather"/>
<eStructuralFeatures xsi:type="ecore:EReference“name="mother" ordered="false“lowerBound="1" eType="#//Mother" containment="true" eOpposite="#//Mother/familyMother"/>
…</eClassifiers>
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200935 16/03/2009
Agenda
• Introduction
• Defining a Model with EMF
• EMF Architecture
• Code Generation
• Programming with EMF
• EMF.Edit
• Summary
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200936 16/03/2009
EMF Architecture
EMF Runtime
EMF Tools
Core Edit
Codegen
Model EditorApplication
Generates
Eclipse Platform
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200937 16/03/2009
EMF Components
• Core Runtime
Notification framework
ECore metamodel
Persistence (XML/XMI), validation, change model
• EMF.Edit
Support for model-based editors and viewers
Default reflective editor
• Codegen
Code generator for application models and editors
Extensible model importer/exporter framework
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200938 16/03/2009
Model Import and Generation
Ecore
Model
UML
XML Schema
I
M
P
O
R
T
Java Edit Java Editor
GENERATE
Java Model
Generator features:
Customizable,
JSP-like templates
(JET)
JDT-integrated,
command-line or
Ant
Full support for
regen and merge
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200939 16/03/2009
Agenda
• Introduction
• Defining a Model with EMF
• EMF Architecture
• Code Generation
• Programming with EMF
• EMF.Edit
• Summary
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200940 16/03/2009
Summary of Generated Artifacts
• Model
Interfaces and classes
Type-safe enums
Package (metadata)
Factory
Switch utility
Adapter factory base
Validator
Custom resource
XML Processor
• Manifests, plug-in classes,
properties, icons…
• Edit (UI Independent)
Item providers
Item provider adapter factory
• Editor
Model Wizard
Editor
Action bar contributor
Advisor (RCP)
• Tests
Test cases
Test suite
Stand-alone example
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200941 16/03/2009
Code Generation
• Genmodel A generator model obtained from the Ecore model
It contains information that needs to be provided to the generator
where to put the generated code
what prefix to use for the generated factory and package class names
…
It is an EMF model that wraps the core model
That is, generator model classes are Decorators of Ecore classes
• We are separating the generator model from the core model the Ecore metamodel can remain pure and independent of
any information that is only relevant for code generation
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200942 16/03/2009
Generated Model Code
• Interface and implementation for each modeled class
Includes get/set accessors for attributes and references
public class FamilyImpl extends EObjectImpl
implements Family {
{public String getLastName()
public void setLastName(String newLastName)
public Father getFather()
…
}
public interface Family extends EObject {
{String getLastName();
void setLastName(String value);
Father getFather();
……
}
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200943 16/03/2009
Generated Model Code
• Plus a Package and a Factory class
Factory class includes creators for the rest of
classes
Package class includes accessors for all the
Ecore metadata for the model
Family aFamily = FamilyFactory.eINSTANCE.createFamily();
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200944 16/03/2009
Ecore
• ECore class hierarchy
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200945 16/03/2009
EObject capabilities
•EObject is conceptually equivalent to
java.lang.Object. All modeled objects, generated
or not, implement this interface to:
Using the eClass() method, you can retrieve the metadata
of the instance, i.e., its EClass.
You can use the reflective API (eGet(), eSet()) to access
its data.
From any instance object you can get its container (parent) using the eContainer() method.
Likewise, the eResource() method allows retrieving any
physical storage location used to persist the object
EObject also extends Notifier, which allows you to
monitor all changes to the object's data
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200946 16/03/2009
Change Notification
• Every EObject is also a notifier
Sends notification whenever an attribute
or reference is changed
Observers can update views, dependent
objects
Observers are also adapters
• We have to attach the
adapter to the observed
object
Adapter famObserver = ...myFamily.eAdapters().add(adapter);
public interface EObject extends Notifier {
{ … }
adapter.notifyChanged()
setLastName()
myFamily
famObserver
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200947 16/03/2009
Change Notification: Feature Accessors
• Efficient notification from set methods
Checks if there are listeners for such class
If so, a notification is sent
public String getLastName() {
return lastName;
}
public void setLastName(String newLastName) {
String oldLastName = lastName;
lastName = newLastName;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this,
Notification.SET,
FamiliesPackage.FAMILY__LAST_NAME,
oldLastName, lastName));
}
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200948 16/03/2009
Bidirectional References
public void setFather(Father newFather) {
if (newFather != father) {
NotificationChain msgs = null;
if (father != null)
msgs = ((InternalEObject)father).eInverseRemove(this,
FamiliesPackage.FATHER__FAMILY_FATHER,
Father.class, msgs);
if (newFather != null)
msgs = ((InternalEObject)newFather).eInverseAdd(this,
FamiliesPackage.FATHER__FAMILY_FATHER, Father.class,
msgs);
msgs = basicSetFather(newFather, msgs);
if (msgs != null)
msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET,
FamiliesPackage.FAMILY__FATHER, newFather, newFather));
}
Bidirectional reference imposes invariant:
fam.getFather().getFamily() == fam
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200949 16/03/2009
Bidirectional Reference Handshaking
• Multi-step procedure implemented using
InternalEObject methods:
eInverseRemove()
eInverseAdd()
• Framework list implementations and generated setters
directly invoke them on target objects as needed
• Notifications accumulated using a NotificationChain
and fired off at the end
Not used to implement the handshaking
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200950 16/03/2009
Factories and Packages
• Package provides constants and access to metadata
FamilyPackage famPackage = FamilyPackage.eINSTANCE;EClass fatherClass = FamilyPackage.Literals.ITEM;//or poPackage.getItem()
EAttribute priceAttr = POPackage.Literals.ITEM__PRICE;//or poPackage.getItem_Price()//or itemClass.getEStructuralFeature(POPackage.ITEM__PRICE)
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200951 16/03/2009
Factories and Packages
• Factory to create instances of model classes
FamiliesFactory famFact = FamiliesFactory.eINSTANCE;Family fam = famFact.createFamily();
public interface FamiliesFactory extends EFactory {
FamiliesFactory eINSTANCE = Families.impl.FamiliesFactoryImpl.init();
Family createFamily();
Father createFather();
Mother createMother();
Son createSon();
Daughter createDaughter();
FamiliesPackage getFamiliesPackage();
}
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200952 16/03/2009
Reflective EObject API
• All EMF classes implement EObject interface
• Provides an efficient API for manipulating objects
reflectively instead of using generated methods
Used by framework (e.g. persistence framework, copy utility,
editing commands)
Key to integrating EMF-based tools and applications
public interface EObject{EClass eClass();Object eGet(EStructuralFeature sf);void eSet(EStructuralFeature sf, Object val);...
}
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200953 16/03/2009
Reflective EObject API
• They are slightly less efficient than the generated
methods but they open up the model for completely
generic access.
The reflective methods are used by the EMF.Edit framework
to implement a full set of generic commands that can be used
on any model
AddCommand, RemoveCommand, SetCommand)
EObject myFamily = ……EAttribute lastName =
famPackage.getFamily_LastName(); myFamily.eSet(LastName, “Simpson");
EObject myFamily = ……myFamily.setName(“Simpson"); SIN REFLEXIÓN
CON REFLEXIÓN
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200954 16/03/2009
Reflective EObject API
• Efficient generated switch-based implementation of
reflective methodspublic void eSet(int featureID, Object newValue) {
switch (featureID) {
case FamiliesPackage.FAMILY__LAST_NAME:
setLastName((String)newValue);
return;
case FamiliesPackage.FAMILY__FATHER:
setFather((Father)newValue);
return;
case FamiliesPackage.FAMILY__MOTHER:
setMother((Mother)newValue);
return;
case FamiliesPackage.FAMILY__SONS:
getSons().clear();
getSons().addAll((Collection<?
extends Son>)newValue);
return;
case FamiliesPackage.FAMILY__DAUGHTERS:
getDaughters().clear();
getDaughters().addAll((Collection<?
extends Daughter>)newValue);
return;
}
super.eSet(featureID, newValue);
}
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200955 16/03/2009
Regeneration and Merge
• The EMF generator is a merging generator
• @generated elements are replaced/removed
• To preserve changes mark @generated NOT
/*** <!-- begin-user-doc -->* <!-- end-user-doc -->* @generated*/public String getName(){return name;
}
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200956 16/03/2009
Regeneration and Merge
• Generated methods can be extended through
redirection
public String getName(){return format(getNameGen());
}
/*** <!-- begin-user-doc -->* <!-- end-user-doc -->* @generated*/public String getNameGen(){return name;
}
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200957 16/03/2009
Agenda
• Introduction
• Defining a Model with EMF
• EMF Architecture
• Code Generation
• Programming with EMF
• EMF.Edit
• Summary
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200958 16/03/2009
Persistence
• EMF provides simple, yet powerful, mechanisms for
managing object persistence
• Core models are serialized using XMI
So could be done with terminal models
If the core model comes from a Schema, the code generation
allows persisting them as XML instances
• You may save your objects in any persistent form you
like
You’ll need to code it yourself
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200959 16/03/2009
Persistence: URI
• URI: open standard for identyfing data
• A URI is a string composed of three fundamental
parts: a scheme, a scheme-specific part, and an
optional fragment
• EMF URIs: org.eclipse.emf.common.util.URI
• Scheme: identify the protocol
File, Jar, Platform (…)
E.G: platform:/resource/project/po.xml
• The URI fragment identifies a part of the contents of
the resource.
It's separated from the rest of the URI by the "#" character.
file:/c:/dir1/dir2/myfile.xml#loc
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200960 16/03/2009
Persistence: URI
• EMF uses URIs with fragments to reference EObjects
in resources.
Each EMF resource has a unique URI based on XPath
Each object in a resource has a unique fragment that
identifies that object within it
• The getEObject() method on the Resource interface
can be used to retrieve an object, given its fragment
path:
• Determining the fragment path of a given object (that
is, the reverse operation) can be done using the
getURIFragment() method
Resource resource = ...
Item item = (Item)resource.getEObject("//@orders.0/@items.2");
Item item = ...
String fragment = resource.getURIFragment(item);
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200961 16/03/2009
Resource
• Container for objects that are to be persisted together
Convert to and from persistent form via save() and load()
Access contents of resource via getContents()
• EMF provides generic XMLResource implementation
Other, customized implementations, too (e.g. XMI, EMOF)
URI uri = URI.createFileURI("C:/data/po.xml");Resource resource = rs.createResource(uri);resource.getContents().add(p1);resource.save(null);
<PurchaseOrder><shipTo>John Doe</shipTo><next>p2.xml#p2</next>
</PurchaseOrder>
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200962 16/03/2009
Persistence: Resource Set
• Context for multiple resources that may have
references among them
• Usually just an instance of ResourceSetImpl
• Provides factory method for creating new resources in
the set
• ResourceSet keeps track of which URIs have already
been opened
• Also provides access to the registries, URI converter
and default load options for the set
ResourceSet rs = new ResourceSetImpl();URI uri = URI.createFileURI("C:/data/po.xml");Resource resource = rs.createResource(uri);
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200963 16/03/2009
Persistence
• Persisted data is referred to a resource
• Objects can be spread out among a number of
resources, within a resource set
• Proxies represent referenced objects in other
resources
Resource 2Resource 1
ResourceSet
Client
load
demand-loadresource 2
resource 1 uri 1 resource 1
uri 2 resource 2
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200964 16/03/2009
neighbour
Proxy Resolution and Demand Load
f1
fam1.xml
Family f1 = Family f = (Family) resource.getContents().get(0);
proxyURI=“Flanders.xml#family.0"
<?xml version="1.0" encoding="ISO-8859-1"?>
<xmi:XMI xmi:version="2.0"
xmlns:xmi="http://www.omg.org/XMI" xmlns="Families">
<Family lastName="Simpson">
<father firstName="Homer"/>
<neighbour href=kybele.es.Flanders.xml@//family.0>
</Family>
Simpsons.xml
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200965 16/03/2009
neighbourf2
Proxy Resolution and Demand Load
f1
Simpsons.xml Flanders.xml
Family f1 = Family f = (Family) resource.getContents().get(0);
Family f2 = fam1.getNeighbour();
proxyURI=“Flanders.xml#family.0"
<?xml version="1.0" encoding="ISO-8859-1"?>
<xmi:XMI xmi:version="2.0"
xmlns:xmi="http://www.omg.org/XMI" xmlns="Families">
<Family lastName="Simpson">
<father firstName="Homer"/>
<neighbour href=kybele.es.Flanders.xml@//family.0>
</Family>
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200966 16/03/2009
EMF Resource Implementations
• EMF provides two resource implementations
supporting serialization to XML or XMI
• Primary is provided by the XMLResourceImpl which
can be used to serialize any EMF model to XML
Flexible, you may customize it as needed
• Default EMF serialization is XMI:
XMIResourceImpl (extends XMLResourceImpl) provides
the support for serialization and loading of XMI 2.0
documents
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200967 16/03/2009
XML Schema-Conformant Serialization
• You can customize the format of your XML file to
conform to an XML Schema
• If you create your core model from a XMLSchema this
is done automatically
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200968 16/03/2009
XML Schema-Conformant Serialization
• To serialize an instance document
Use an XMLResource with extended metadata enabled
(e.g. use the resource factory generated with your model)
Use an instance of the DocumentRoot in the resource’s
contents
Set the appropriate reference to select the root element
PurchaseOrder p1 = ...
URI uri = URI.createFileURI("C:/data/order.po");resource resource = rs.createResource(uri);DocumentRoot root = POFactory.eINSTANCE.createDocumentRoot();resource.getContents().add(root);root.setOrder(p1);resource.save(null);
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200969 16/03/2009
XML Schema-Conformant Serialization
<?xml version="1.0" encoding="UTF-8"?>
<po:supplier xmlns:po="http://www.example.com/PurchaseOrder/po.xsd">
<name>MySupplier</name>
<order id="po-01" orderDate="2008-03-03">
<billTo country="US">
<name>MyBillAddress</name>
<street>Elm Street</street>
<city>CHICAGO</city>
<state>Illinois</state>
<zip>12345</zip>
</billTo>
<creditCard>
<number>123456789</number>
<expiry>2010-01</expiry>
</creditCard>
</order>
</po:supplier>
NAMESPACE declaration added to the root
element
Ns Prefix
Ns URI
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200970 16/03/2009
Dynamic EMF
• An Ecore model can also be defined at runtime using
Ecore API or loaded from persistent form
No generated code required
Dynamic implementation of reflective EObject API provides
same runtime behavior as generated code
Can create dynamic subclasses of generated classes
• The framework treats all model instances the same,
whether generated or dynamic
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200971 16/03/2009
Change Recording
• The change model represents changes to instances of
any EMF model
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200972 16/03/2009
Change Recording
• Change recorder
Adapter that creates change description based on
notifications, to describe reverse delta
Provides transaction capability
ChangeRecorder changeRecorder =new ChangeRecorder(resourceSet);
try {// modifications within resource set
}catch (Exception e) {changeRecorder.endRecording().apply();
}
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200973 16/03/2009
Validation
• Models can define named constraints and invariants
for batch validation
Invariant
Defined directly on class, as <<inv>> operation
Stronger statement about validity than a constraint
Constraint
Externally defined via a validator
• Invariants and constraints are invoked by a validator,
which is generated for a package, if needed
Bodies of invariants and constraints are usually hand-coded
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200974 16/03/2009
Agenda
• What is Modeling?
• Defining a Model with EMF
• EMF Architecture
• Code Generation
• Programming with EMF
• EMF.Edit
• Summary
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200975 16/03/2009
Using EMF editors
Ecore
Model
UML
XML Schema
I
M
P
O
R
T
Java Edit Java Editor
GENERATE
Java Model
The EMF.Edit
framework allows
adding user
interfaces to your
model and code
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200976 16/03/2009
EMF.Edit
• EMF.Edit is an Eclipse framework that includes generic reusable classes for building editors for EMF models
• Generated EMF.Edit code is divided into two parts
• UI-independent code is placed in an edit plug-in
Facilitates the viewing and editing of model objects by providing item providers
Item provider
Item provider adapter factory
Plug-in
• UI-dependent code is placed, by default, in a separate editor plug-in
uses the Eclipse workbench framework, including JFace and SWT, to provide the interface for creation and editing of EMF models
Editor
Action bar contributor
Wizard
Plug-in
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200977 16/03/2009
EMF.Edit Basics
PurchaseOrder
US Address Credit Card
Supplier.po
DocumentRoot root = resource.getContents(0);
root.get_Text();
root.get_Image();
List EObject nodes = root.getChildren();
……
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200978 16/03/2009
EMF.Edit Basics
PurchaseOrder
US Address Credit Card
Supplier.po
PropertySource ps =
PropertySourceProvider.getPropertySource();
List PropertyDescriptors ps_list =
ps.get_PropertyDescriptors();
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200979 16/03/2009
EMF.Edit Support
• To implement a tree viewer we need:
ITreeContentProvider interface that is capable of returning the
children of EMF model objects
ILabelProvider to return a suitable text string for the label, usually
based on one of the Ecore attributes
• For a property sheet viewer we need:
A way of producing a set of IPropertyDescriptors for the (subset of)
Ecore attributes and references that should be properties
• EMF.Edit supports two ways of implementing these things
using the reflective EObject API
Consults the core model at runtime to provide a "best guess"
implementation
using generated classes
you have an opportunity to influence some of the choices before the code
is generated
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200980 16/03/2009
Item Providers
• Item providers are the single most important objects in
EMF.Edit
• They "provide" functions on behalf of individual
editable model "items" (objects)
• They need to perform four major roles:
Implement content and label provider functions
Provide a property source (property descriptors) for EMF
objects
Act as a command factory for commands on their associated
model objects
Forward EMF model change notifications on to viewers
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200981 16/03/2009
Content and Label Item Providers
• EMF.Edit provides generic content and label provider
implementation classes
• They delegate delegate their implementation to item
providers
• Both of these classes are constructed with an adapter
factory which, like any other EMF adapter factory,
serves to create and locate EMF adapters of a specific
type
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200982 16/03/2009
Item Property Source
• The second major role of an item provider is to act as
a property source for the property sheet
• In EMF.Edit, the AdapterFactoryContentProvider also
implements the IPropertySourceProvider interface and
is used to provide a property source to the property
sheet
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200983 16/03/2009
Generating EMF.Edit Code
• Generate Edit Code: a complete plug-in containing
the UI independent portion of a model editor.
A set of typed item provider classes, one for each class in
the model.
An item provider adapter factory class that creates the
generated item providers.
A Plugin class that includes methods for locating the plug-
in's resource strings and icons.
A plug-in manifest file, plugin.xml, specifying the required
dependencies.
A property file, plugin.properties, containing the externalized
strings needed by the generated classes and the framework.
A directory of icons, one for each model class.
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200984 16/03/2009
Generating EMF.Edit Code
• Generate Editor Code: a fully functional editor plug-in
that will allow you to view instances of the model:
An integrated Eclipse workbench editor
A wizard for creating new model instance documents
An action bar contributor that manages the popup menus,
and toolbar and menu bar items
A Plugin class that includes methods for locating the plug-in's
resource strings and icons
A plug-in manifest file, plugin.xml, that specifies the required
dependencies and extensions of the editor, wizard, and action
workbench extension points
A property file, plugin.properties, containing the externalized
strings needed by the generated classes and the framework
A directory containing icons for the editor and model wizard
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200985 16/03/2009
Agenda
• What is Modeling?
• Defining a Model with EMF
• EMF Architecture
• Code Generation
• Programming with EMF
• EMF.Edit
• Summary
Example
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200986 16/03/2009
Example
• Create EMF model from XML Schema
Create an EMF project: kybele.example.po
Select XML Schema as source
• Generate the code
Change Model Name at root elment: Purchase Order
Change prefix at package element: PO
Disable tests generation
Test Directory = blank
Generate All over root node
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200987 16/03/2009
Example (II)
• Create new model Select kybele.es.po and run new Eclipse Application
Check plug-in is installed
Help About Eclipse Platform Plug-in details
Create new General project
Create new Example EMF Model Creation PO Model
Select Supplier as model object
• Create Family Change family name
Add Family child
• Validate the model
• Serialize the model and check that it conforms to the original Schema
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200988 16/03/2009
Summary
• EMF is low-cost modeling for the Java mainstream
• Leverages the intrinsic model in an application
No high-level modeling tools required
• Mixes modeling with programming to maximize the
effectiveness of both
• Boosts productivity and integrates integration
• The foundation for model-driven development and
data integration in Eclipse
Introducción al Eclipse Modeling Framework @MTISI.SISBM © Kybele 200989 16/03/2009
Resources
• EMF documentation in Eclipse Help
Overviews, tutorials, API reference
• EMF project Web site
http://www.eclipse.org/modeling/emf/
Downloads, documentation, FAQ,
newsgroup, Bugzilla, Wiki
• Eclipse Modeling Framework, by
Frank Budinsky et al.
ISBN: 0131425420
Rough cut of second edition available
http://my.safaribooksonline.com/9780321331885