itu - mdd - emf

42
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.

Upload: tonny-madsen

Post on 11-May-2015

1.156 views

Category:

Education


0 download

DESCRIPTION

This presentation describes Eclipse Modeling Framework – EMF. It has two basic purposes:Introduce you to the EMF techniques needed in the rest of the courseIntroduce you to the architecture and components of the EMF projectThis presentation is developed for MDD 2010 course at ITU, Denmark.

TRANSCRIPT

Page 1: ITU - MDD - EMF

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 courseIntroduce you to the architecture and components of the EMF project

This presentation is developed for MDD 2010 course at ITU, Denmark.

Page 2: ITU - MDD - EMF

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!

Page 3: ITU - MDD - EMF

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

Page 4: ITU - MDD - EMF

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

IMPORT

GENERATE

EcoreModel

UML

XMLSchema

Javamodel

Javaedit

Javaeditor*

* Eclipse IDE-integrated or RCP-based

Javamodel

Page 5: ITU - MDD - EMF

L0061 - 2008-04-27

5

Model Importers Available in EMFAnnotated 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();

}

Page 6: ITU - MDD - EMF

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

Page 7: ITU - MDD - EMF

L0061 - 2008-04-27

7

Kick Start EMFEdit 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

Page 8: ITU - MDD - EMF

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..nfirstName,familyName

Location

0..n

type, street, city, country

Page 9: ITU - MDD - EMF

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

Page 10: ITU - MDD - EMF

L0061 - 2008-04-27

10

EMF Architecture

EMF Runtime

EMF Tools

Core Edit

Codegen

Model EditorApplication

Generates

Eclipse Platform

Page 11: ITU - MDD - EMF

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)

Page 12: ITU - MDD - EMF

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

Page 13: ITU - MDD - EMF

L0061 - 2008-04-27

13

The EMF Meta Information Model

0..1

EAttribute

EReference

EClass

EDataType

0..*

0..*

0..*

attributeType

opposite

superTypes

referenceType

Page 14: ITU - MDD - EMF

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

Page 15: ITU - MDD - EMF

L0061 - 2008-04-27

15

Ecore Model for Purchase Orders

PurchaseOrder

shipTo : StringbillTo : String

Item

productName : Stringquantity : intprice : 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

Page 16: ITU - MDD - EMF

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..*

type

opposite

superTypes

Page 17: ITU - MDD - EMF

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..*

type

opposite

superTypes

Page 18: ITU - MDD - EMF

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..*

type

opposite

superTypes

Page 19: ITU - MDD - EMF

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..*

type

opposite

superTypes

Page 20: ITU - MDD - EMF

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..*

type

opposite

superTypes

Page 21: ITU - MDD - EMF

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..*

type

opposite

superTypes

Page 22: ITU - MDD - EMF

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..*

type

opposite

superTypes

Page 23: ITU - MDD - EMF

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..*

type

opposite

superTypes

Page 24: ITU - MDD - EMF

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..*

type

opposite

superTypes

Page 25: ITU - MDD - EMF

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

Page 26: ITU - MDD - EMF

L0061 - 2008-04-27

26

Generated CodeOverriding 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) {

…}

Page 27: ITU - MDD - EMF

L0061 - 2008-04-27

27

Generated CodeSimple 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();

Page 28: ITU - MDD - EMF

L0061 - 2008-04-27

28

Generated CodeMulti-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);

Page 29: ITU - MDD - EMF

L0061 - 2008-04-27

29

Generated CodeVolatile Attributes and References

Volatile attributes and references get (near-)empty bodies

/** * @generated */public String getSurname() {

throw new UnsupportedOperationException();}

Page 30: ITU - MDD - EMF

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

Page 31: ITU - MDD - EMF

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

Page 32: ITU - MDD - EMF

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-loadresource 2

resource 1 uri 1 resource 1uri 2 resource 2

Page 33: ITU - MDD - EMF

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)

Page 34: ITU - MDD - EMF

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();

Page 35: ITU - MDD - EMF

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();

}

Page 36: ITU - MDD - EMF

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

Page 37: ITU - MDD - EMF

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);...

}

Tonny Madsen
Lab?
Page 38: ITU - MDD - EMF

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.

Page 39: ITU - MDD - EMF

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.

Page 40: ITU - MDD - EMF

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”…

Page 41: ITU - MDD - EMF

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

Page 42: ITU - MDD - EMF

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.