Post on 13-May-2018
A light introduction to the
Eclipse Modeling Framework
Juan Manuel Vara
Kybele Research Group
University Rey Juan Carlos
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 20102 23/02/2010
References
• Eclipse Modeling Project: A Domain Specific
Language (DSL) Toolkit
Richard C. Gronback. Addison-Wesley Profesional,
2009.
• Eclipse Modeling Framework (Second Edition)
Dave Steinberg, Frank Budinsky, Marcelo Paternostro,
Ed Merks. Addison-Wesley Professional, 2008.
• Fundamentals of the Eclipse Modeling Framework
EclipseCON2008, Dave Steinberg
• Model-Handling with EMF
Open Model CourseWare (OMDW), ATLAS
group,University of Nantes, 2007.
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 20103 23/02/2010
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
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 20104 23/02/2010
Agenda
• Introduction
MDE & EMF
The Eclipse Platform
• Defining a Model with EMF
• EMF Architecture
• Code Generation
• Programming with EMF
• EMF.Edit
• Summary
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 20105 23/02/2010
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
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 20106 23/02/2010
Model-Driven Engineering (using MOF)
Metamodel
Metamodel element
Metametamodel
Metametamodel element
conformsTometa
conformsTo
Model
Model element
conformsTometa
repOfSystem
metaMOF
Relational
metamodel
M3
M2
M1
UML
metamodel…
… …
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 20107 23/02/2010
Model-Driven Engineering (using MOF): 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}
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 20108 23/02/2010
MDE – Are We There Yet?
• Doubts exist about the ability of MDE to deliver
on its promises:
Ambitiousness of vision
Model expressiveness vs. complexity
Availability of implementations (“vaporware”)
A (kind of)
conceptual
model for
MDE
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 20109 23/02/2010
Operating on Models
• Model persistence
Loading/saving
• Model edition
Creation/deletion/modification
• Model navigation
conformsTo/meta relations
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201010 23/02/2010
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)
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201011 23/02/2010
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
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201012 23/02/2010
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
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201013 23/02/2010
Agenda
• Introduction
MDE & EMF
The Eclipse Platform
• Defining a Model with EMF
• EMF Architecture
• Code Generation
• Programming with EMF
• EMF.Edit
• Summary
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201014 23/02/2010
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
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201015 23/02/2010
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 - Declarations of functionality that
it makes available to other plug-ins
Example: extension point for workbench preference UI
• Extension - a contribution. Use (implementation)
of other plug-ins‟ extension points
Example: specific HTML editor preferences
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201016 23/02/2010
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
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201017 23/02/2010
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
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 2010
The Eclipse Projects
• The development work in Eclipse is divided into
numerous top-level projects
18 23/02/2010
Eclipse Project
ModellingProject
Tools Project
TechnologyProject
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 2010
The Projects
• The Eclipse Modeling Project can be seen as a DSL
toolkit providing support for the different tasks related
with deploying MDE proposals
19 23/02/2010
Abstract
Syntax
CDO
Net4j
Teneo
Model Query
Model Transaction
Validation Framework
Model
Transformation
M2M
QVTo
QVTd
M2TJET
Acceleo
XpandTechnology &
Research
AM3
AMW
MOFScript
UMLX
Epsilon
VIATRA
GEMS
MoDisco
Model
Dev. Tools
BPMN2
OCL
UML2
UML2
Tools
XSD
Concrete
Syntax
VisualGMF
TextualTMF
Xtext TCS
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201020 23/02/2010
Agenda
• Introduction
• Defining a Model with EMF
• EMF Architecture
• Code Generation
• Programming with EMF
• EMF.Edit
• Summary
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201021 23/02/2010
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
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201022 23/02/2010
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
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201023 23/02/2010
(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
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201024 23/02/2010
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..*
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201025 23/02/2010
XML Schema
<?xml version="1.0" encoding="UTF-8"?><xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.kybele.es/PurchaseOrder/po"xmlns:po=“http://www.kybele.es/PurchaseOrder/po">
<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>
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201026 23/02/2010
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
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201027 23/02/2010
Direct Ecore Modeling
• Ecore models can be created directly
Sample Ecore editor (in EMF)
Ecore Tools graphical editor (from EMFT)
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201028 23/02/2010
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
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 2010
OMG 4-layer Modelling Stack in terms of EMF
29
EClass EStructuralFeature
Class ::EClass Property:: EStructuralFeature
Customer:: Class
name : String
ECore
UML
My_Customer::Customer
name : John Doe
UML
Model
Instantiation
of UML model
metaobject conforms to
ECoreMetametamodel
The UML
Metamodel
Some UML
Models
Varios usage
of these models
METAMETAMODEL
METAMODEL
MODEL
THE REAL WORLD
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201030 23/02/2010
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
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201031 23/02/2010
Ecore Modeling Concepts
• [Abstract] Classes, Interfaces
• Attributes and Operations
• Data types (…)
• User Defined and Enum Data Types
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201032 23/02/2010
Ecore Modeling Concepts
• References ↔ Associations
One-way
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201033 23/02/2010
Ecore Modeling Concepts
• References ↔ Associations
Bidirectional
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201034 23/02/2010
Ecore Modeling Concepts
• Containment Relationships
• Inheritance
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201035 23/02/2010
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")
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201036 23/02/2010
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>
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201037 23/02/2010
Agenda
• Introduction
• Defining a Model with EMF
• EMF Architecture
• Code Generation
• Programming with EMF
• EMF.Edit
• Summary
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201038 23/02/2010
EMF Architecture
EMF Runtime
EMF Tools
Core Edit
Codegen
Model EditorApplication
Generates
Eclipse Platform
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201039 23/02/2010
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
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201040 23/02/2010
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
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201041 23/02/2010
Agenda
• Introduction
• Defining a Model with EMF
• EMF Architecture
• Code Generation
• Programming with EMF
• EMF.Edit
• Summary
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201042 23/02/2010
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
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201043 23/02/2010
Code Generation
• Genmodel A generator model obtained from the Ecore model
It contains information that needs to be provided to thegenerator
where to put the generated code
what prefix to use for the generated factory and packageclass 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 thecore model The Ecore metamodel can remain pure and independent
of any information that is only relevant for codegeneration
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201044 23/02/2010
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();
……
}
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201045 23/02/2010
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();
public void setShipTo( String newShipTo){String oldShipTo = shipTo;shipTo = newShipTo;if (eNotificationRequired())
eNotify(new ENotificationImpl(this,Notification.SET,POPackage.PURCHASE_ORDER__SHIP_TO,oldShipTo, shipTo) ) ;
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201046 23/02/2010
Ecore
• ECore class hierarchy
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201047 23/02/2010
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
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201048 23/02/2010
Change Notification
• Every EObject is also a notifier
Sends notification whenever an
attribute or reference is changed
Observers (or Listeners) can update
views, dependent objects
Observers are known as adapters
„cause they are used to extend the
behavior of the object without
subclassing
• We have to attach the
adapter to the observed
object
public interface EObject extends Notifier {
{ … }
adapter.notifyChanged()
setLastName()
myFamily
famObserver
Adapter famObserver = ...myFamily.eAdapters().add(famObserver);
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201049 23/02/2010
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));
}
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201050 23/02/2010
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)
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201051 23/02/2010
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();
}
Indeed, EMF constructors are protected to impose the use of the
Factory object to create new objects from your classes
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201052 23/02/2010
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);...
}
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201053 23/02/2010
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
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201054 23/02/2010
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);
}
EObject myFamily = ……EAttribute lastName =
famPackage.getFamily_LastName(); myFamily.eSet(lastName, “Simpson");
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201055 23/02/2010
Regeneration and Merge
• The EMF generator is a merging generator
• @generated elements are replaced/removed
/*** <!-- begin-user-doc -->* <!-- end-user-doc -->* @generated*/public String getName(){return name;
}
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201056 23/02/2010
Regeneration and Merge
• The EMF generator is a merging generator
• To preserve changes mark @generated NOT or
delete the @generated tag
If we regenerate the model, the generator detects the
collision and discards the generated version of the
method
/*** <!-- begin-user-doc -->* <!-- end-user-doc -->* @generated*/public String getName(){return name;
}
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201057 23/02/2010
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;
}
Before discarding a generated
method, the generator first checks
if there is another generated
method in the file with the same
name, but with Gen appended.
If so, then instead of discarding
the newly generated version of the
method it redirects the output to it
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201058 23/02/2010
Agenda
• Introduction
• Defining a Model with EMF
• EMF Architecture
• Code Generation
• Programming with EMF
• EMF.Edit
• Summary
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201059 23/02/2010
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
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201060 23/02/2010
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
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201061 23/02/2010
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);
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201062 23/02/2010
Resource
• Container for objects that are to be persisted
together
Represents a physical storage location
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>
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201063 23/02/2010
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);
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201064 23/02/2010
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
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201065 23/02/2010
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
When we load the first
Familiy object, a proxy
is created to refer to its
neighbour
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201066 23/02/2010
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>
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201067 23/02/2010
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
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201068 23/02/2010
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
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201069 23/02/2010
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 = ...( … filling the p1 object …)
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);
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201070 23/02/2010
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
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201071 23/02/2010
Change Recording
• The change model represents changes to
instances of any EMF model
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201072 23/02/2010
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();
}
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201073 23/02/2010
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
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201074 23/02/2010
Agenda
• What is Modeling?
• Defining a Model with EMF
• EMF Architecture
• Code Generation
• Programming with EMF
• EMF.Edit
• Summary
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201075 23/02/2010
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
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201076 23/02/2010
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
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201077 23/02/2010
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();
……
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201078 23/02/2010
EMF.Edit Basics
PurchaseOrder
US Address Credit Card
Supplier.po
PropertySource ps =
PropertySourceProvider.getPropertySource();
List PropertyDescriptors ps_list =
ps.get_PropertyDescriptors();
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201079 23/02/2010
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
getChildren ↔ eContents() or getLabel() ↔ getName()
using generated classes
you have an opportunity to influence some of the choices before
the code is generated. E.g: setting a different attribute for the label
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201080 23/02/2010
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
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201081 23/02/2010
Content and Label Item Providers
• EMF.Edit provides generic content and label
provider implementation classes
• They 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
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201082 23/02/2010
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
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201083 23/02/2010
Generating EMF.Edit Code
• 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.
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201084 23/02/2010
Generating EMF.Edit Code
• 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
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201085 23/02/2010
Agenda
• What is Modeling?
• Defining a Model with EMF
• EMF Architecture
• Code Generation
• Programming with EMF
• EMF.Edit
• Summary
Example
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201086 23/02/2010
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 element: Purchase Order
Change prefix at package element: PO
Disable tests generation
Test Directory = blank
Generate All over root node
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201087 23/02/2010
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
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201088 23/02/2010
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
A light introduction to the Eclipse Modeling Framework @MTISI.SISBM © Kybele 201089 23/02/2010
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