156
Ed Merks Macro Modeling Introduction to the Eclipse Modeling Framework Thursday, November 13, 2008 1 © Macro Modeling Ltd. | EDL V1.0

Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

  • Upload
    donhi

  • View
    218

  • Download
    1

Embed Size (px)

Citation preview

Page 1: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Ed MerksMacro Modeling

Introduction to the Eclipse Modeling Framework

Thursday, November 13, 2008 1© Macro Modeling Ltd. | EDL V1.0

Page 2: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• Software is focused on manipulating data• Data has abstract structure

– It can be described at a high level– It can be represented in different ways– It’s always a model of something

• The description of the data is yet more data– It’s commonly referred to as metadata– Meta is a bit confusing– The model of a model is a model

• Whether it’s recognized or not, models drive software development

Model Driven Software Development

Thursday, November 13, 2008 2© Macro Modeling Ltd. | EDL V1.0

Page 3: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• A simple, pragmatic, Java-based approach that provides– The Ecore API for describing models– The EObject API for manipulating instances– A resource framework for RESTful persistence– A generator framework for producing development

artifacts– A runtime along with utilities for traversing, indexing,

copying, change recording, and so on– Tools for working with models and their instances

• EMF was used to develop EMF

Eclipse Modeling Framework

Thursday, November 13, 2008 3© Macro Modeling Ltd. | EDL V1.0

Page 4: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• Started at IBM in the late 90’s – It supported Object Management Group (OMG) specifications– It implemented Meta Object Facility (MOF)– It used XML Metadata Interface (XMI)– It’s closely related to Java Metadata Interface (JMI)

• Problems surfaced for adopters– The MOF model was far too complex – The generated code and runtime were bloated and performed poorly

• ETools Modeling Framework (EMF) was kicked off in 2000– Boiled MOF to its essential components resulting in Ecore – Revamped the runtime and tools to make them lean and mean

• Contributed to Eclipse in September 2002 – Rebrand as the Eclipse Modeling Framework– Feedback to OMG resulting in Essential MOF/Complete MOF split

A Brief History of EMF

Thursday, November 13, 2008 4© Macro Modeling Ltd. | EDL V1.0

Page 5: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• A simple model for describing models– Classification of objects– Attributes of those objects– Relationships/associations between those objects– Operations on those objects– Simple constraints on those objects, and their attributes

and relationships

• Ecore is self describing, i.e., it is its own model• Models higher up in the meta levels tend to all look

the same – They begin to conform to our mental model

Ecore: The Model of Models

Thursday, November 13, 2008 5© Macro Modeling Ltd. | EDL V1.0

Page 6: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Relationship of Ecore to Other Models

Thursday, November 13, 2008 6© Macro Modeling Ltd. | EDL V1.0

UML XML Schema

Java

Ecore

Page 7: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

A Model is a Model is a Model

Thursday, November 13, 2008 7© Macro Modeling Ltd. | EDL V1.0

<xsd:complexType name="Node"><xsd:sequence><xsd:element

name="children" type="tree:Node" minOccurs="0"maxOccurs="unbounded" ecore:opposite="parent"/>

</xsd:sequence><xsd:attributename="label" type="xsd:string"/>

</xsd:complexType>

public interface Node {String getLabel();void setLabel(String value);List<Node> getChildren();Node getParent();void setParent(Node value);

} // Node

UML XML Schema

Java

Ecore

Page 8: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Ecore Overview

Thursday, November 13, 2008 8© Macro Modeling Ltd. | EDL V1.0

Page 9: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Ecore Data Types

Thursday, November 13, 2008 9© Macro Modeling Ltd. | EDL V1.0

Page 10: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Ecore Annotations and EObject

Thursday, November 13, 2008 10© Macro Modeling Ltd. | EDL V1.0

Page 11: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Ecore Generics

Thursday, November 13, 2008 11© Macro Modeling Ltd. | EDL V1.0

Page 12: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

The Tree Ecore Model

Thursday, November 13, 2008 12© Macro Modeling Ltd. | EDL V1.0

name tree

nsURI http://www.example.org/tree

eClassifiers Node

name Node

eStructuralFeatures label, children, parent

name label

eType EString

lowerBound 0

upperBound 1

name children

eType Node

lowerBound 0

upperBound -1

containment true

eOpposite parent

name parent

eType Node

lowerBound 0

upperBound 1

containment false

eOpposite children

EPackage

EClass

EAttribute EReference EReference

Page 13: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

The Tree Ecore Model Serialized as XMI

Thursday, November 13, 2008 13© Macro Modeling Ltd. | EDL V1.0

<?xml version="1.0" encoding="UTF-8"?><ecore:EPackage xmi:version="2.0"

xmlns:xmi="http://www.omg.org/XMI" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:ecore="http://www.eclipse.org/emf/2002/Ecore"name="tree"nsURI="http://www.example.org/tree"nsPrefix="tree">

<eClassifiers xsi:type="ecore:EClass" name="Node"><eStructuralFeatures xsi:type="ecore:EAttribute" name="label"

eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EString"/><eStructuralFeatures xsi:type="ecore:EReference" name="children" upperBound="-1"

eType="#//Node" containment="true" eOpposite="#//Node/parent"/><eStructuralFeatures xsi:type="ecore:EReference" name="parent"

eType="#//Node" eOpposite="#//Node/children"/></eClassifiers>

</ecore:EPackage>

Page 14: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

The Tree Ecore Model Serialized as EMOF

Thursday, November 13, 2008 14© Macro Modeling Ltd. | EDL V1.0

<?xml version="1.0" encoding="UTF-8"?><emof:Package xmi:version="2.0"

xmlns:xmi="http://www.omg.org/XMI" xmlns:emof="http://schema.omg.org/spec/MOF/2.0/emof.xml" xmi:id="tree"name="tree" uri="http://www.example.org/tree">

<ownedType xmi:type="emof:Class" xmi:id="tree.Node" name="Node"><ownedAttribute xmi:id="tree.Node.label" name="label"

isOrdered="true" lower="0"><type xmi:type="emof:PrimitiveType"

href="http://schema.omg.org/spec/MOF/2.0/emof.xml#String"/></ownedAttribute><ownedAttribute xmi:id="tree.Node.children" name="children"

isOrdered="true" lower="0" upper="*" type="tree.Node" isComposite="true" opposite="tree.Node.parent"/>

<ownedAttribute xmi:id="tree.Node.parent" name="parent" isOrdered="true" lower="0" type="tree.Node" opposite="tree.Node.children"/>

</ownedType><xmi:Extension extender="http://www.eclipse.org/emf/2002/Ecore">

<nsPrefix>tree</nsPrefix></xmi:Extension>

</emof:Package>

Page 15: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

A Tree Instance Model

Thursday, November 13, 2008 15© Macro Modeling Ltd. | EDL V1.0

label Root

children A, B

parent

Node

label A

children X

parent Root

Node

label B

children Y

parent Root

Node

label X

children

parent A

Node

label Y

children

parent B

Node

Page 16: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

A Tree Instance Model Serialized as XMI

Thursday, November 13, 2008 16© Macro Modeling Ltd. | EDL V1.0

<tree:Node xmi:version="2.0"xmlns:xmi="http://www.omg.org/XMI" xmlns:tree="http://www.example.org/tree" label="root">

<children label="A"><children label="X"/>

</children> <children label="B">

<children label="Y"/></children>

</tree:Node>

Page 17: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• The GenModel is a decorator for tailoring the generated code

The EMF Generator Model

Thursday, November 13, 2008 17© Macro Modeling Ltd. | EDL V1.0

Page 18: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

EMF Application Architecture

Thursday, November 13, 2008 18© Macro Modeling Ltd. | EDL V1.0

Page 19: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• Demo time!– Show how to create the Ecore Tree model from scratch

using the Sample Ecore Editor– Show how to use Ecore Tools for diagrams– Show how to exploit dynamic models to create Tree

instances– Demonstrate the interchangeable nature of models

• Generate the Java realization• Export to XML Schema• Show how these round trip• Show how to run the example• Show how to run the generated editor

EMF in Action

Thursday, November 13, 2008 19© Macro Modeling Ltd. | EDL V1.0

Page 20: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• To show the full generation picture, we need examples of EDataTypes, EEnums, and EOperations

• An EDataType is effectively just a named alias for some existing Java class

– Most data types support conversion to and from a string representation in order to support persistence

– Values of data types generally should be treated as immutable leaves

• An EEnum is a specialized EDataType that specifies a list of EEnumLiterals which exhaustively enumerates all possible values of the data type

• An EOperation is simply the specification of the signature of an operation that can be invoked on a class

Completing the Picture

Thursday, November 13, 2008 20© Macro Modeling Ltd. | EDL V1.0

Page 21: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

The Richer Tree Ecore Model

Thursday, November 13, 2008 21© Macro Modeling Ltd. | EDL V1.0

Page 22: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Generated EPackage

Thursday, November 13, 2008 22© Macro Modeling Ltd. | EDL V1.0

package org.example.tree;// ...

public interface TreePackage extends EPackage{

String eNAME = "tree";String eNS_URI = "http://www.example.org/tree";String eNS_PREFIX = "tree";TreePackage eINSTANCE = TreePackageImpl.init();// ...

interface Literals{// ...

}}

package org.example.tree.impl;// ...

public class TreePackageImplextends EPackageImplimplements TreePackage

{// ...

}

Page 23: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Generated EFactory

Thursday, November 13, 2008 23© Macro Modeling Ltd. | EDL V1.0

package org.example.tree.impl;// ...

public class TreeFactoryImplextends EFactoryImplimplements TreeFactory

{// ...

}

package org.example.tree;// ...

public interface TreeFactory extends EFactory{TreeFactory eINSTANCE = TreeFactoryImpl.init();// ...

}

Page 24: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Generated EPackage Utility Classes

Thursday, November 13, 2008 24© Macro Modeling Ltd. | EDL V1.0

package org.example.tree.util;// ...

public class TreeAdapterFactoryextends AdapterFactoryImpl

{// ...

}

package org.example.tree.util;// ...

public class TreeSwitch<T>{// ...

}

package org.example.tree.util;// ...

public class TreeResourceImplextends XMIResourceImpl

{// ...

}

package org.example.tree.util;// ...

public class TreeResourceFactoryImplextends ResourceFactoryImpl

{// ...

}

Page 25: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Generated EClass

Thursday, November 13, 2008 25© Macro Modeling Ltd. | EDL V1.0

package org.example.tree;// ...

public interface Nodeextends EObject

{// ...

}

package org.example.tree.impl;// ...

public class NodeImplextends EObjectImplimplements Node

{// ...

}

Page 26: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Generated EClass Impact

Thursday, November 13, 2008 26© Macro Modeling Ltd. | EDL V1.0

public interface TreePackage //...

{

int NODE = 0;EClass getNode();// ...

interface Literals{

EClass NODE = eINSTANCE.getNode();// ...

}}

public interface TreeFactory //...

{

Node createNode();// ...

}

public class TreeAdapterFactory //...

{

public Adapter createNodeAdapter();// ...

}

public class TreeSwitch<T>{

public T caseNode(Node object);// ...

}

Page 27: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Generated EStructuralFeature

Thursday, November 13, 2008 27© Macro Modeling Ltd. | EDL V1.0

public interface Node // ... {

String getLabel();void setLabel(String value);// ...

}

public class NodeImpl // ...

{

protected static final String LABEL_EDEFAULT = null;

protected String label = LABEL_EDEFAULT;

public String getLabel(){

return label;}

public void setLabel(String newLabel){

String oldLabel = label;label = newLabel;// ...

}

// ...}

Page 28: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Generated EStructuralFeature Impact

Thursday, November 13, 2008 28© Macro Modeling Ltd. | EDL V1.0

public interface TreePackage //...

{

int NODE__LABEL = 0;EAttribute getNode_Label();// ...

interface Literals{

EAttribute NODE__LABEL = eINSTANCE.getNode_Label();// ...

}}

Page 29: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Generated EOperation

Thursday, November 13, 2008 29© Macro Modeling Ltd. | EDL V1.0

public interface Node // ... {

boolean hasChildren();// ...

}

public class NodeImpl // ...

{

public boolean hasChildren(){

// TODO: implement this method

// Ensure that you remove @generated or mark it @generated NOT

throw new UnsupportedOperationException();}// ...

}

Page 30: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Generated EDataType Impact

Thursday, November 13, 2008 30© Macro Modeling Ltd. | EDL V1.0

public interface TreePackage //...

{

int LABEL= 2;EDataType getLabel();// ...

interface Literals{

EDataType LABEL = eINSTANCE.getLabel();// ...

}}

public class TreeFactoryImpl //...

{

public String createLabelFromString(EDataType eDataType, String initialValue)

{

return (String)super.createFromString(eDataType, initialValue);

}

public String convertLabelToString(EDataType eDataType, Object instanceValue)

{

return super.convertToString(eDataType, instanceValue);

} // ...

}

Page 31: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Generated EEnum

Thursday, November 13, 2008 31© Macro Modeling Ltd. | EDL V1.0

package org.example.tree;// ...

public enum NodeKind implements Enumerator{

// ...}

Page 32: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Generated EEnum Impact

Thursday, November 13, 2008 32© Macro Modeling Ltd. | EDL V1.0

public interface TreePackage //...

{

int NODE_KIND = 1;EEnum getNodeKind();// ...

interface Literals{

EEnum NODE_KIND = eINSTANCE.getNodeKind();// ...

}}

Page 33: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Generated EEnumLiteral

Thursday, November 13, 2008 33© Macro Modeling Ltd. | EDL V1.0

public enum NodeKind // ...{

SINGLETON(0, "Singleton", "Singleton"),// ...

}

Page 34: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• In addition to the generated Java code, generated projects also include the following artifacts– A MANIFEST.MF

• Information used by Equinox/OSGI and the PluginDevelopment Environment PDE to manage dependencies and classpaths

– A plugin.xml• Information used by Equinox to manage extension

points– A plugin.properties

• Properties that need to be translated– A build.properties

• Information used to produce a deployed binary result

Generated Project-level Artifacts

Thursday, November 13, 2008 34© Macro Modeling Ltd. | EDL V1.0

Page 35: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• The generated MANIFEST.MF is not regenerated once the corresponding plugin.xml exists so you can tailor it as needed

Generated Manifest

Thursday, November 13, 2008 35© Macro Modeling Ltd. | EDL V1.0

Manifest-Version: 1.0Bundle-ManifestVersion: 2Bundle-Name: %pluginNameBundle-SymbolicName: org.example.tree;singleton:=trueBundle-Version: 1.0.0Bundle-ClassPath: .Bundle-Vendor: %providerNameBundle-Localization: pluginBundle-RequiredExecutionEnvironment: J2SE-1.5Export-Package: org.example.tree,org.example.tree.impl,org.example.tree.utilRequire-Bundle: org.eclipse.core.runtime,org.eclipse.emf.ecore;visibility:=reexport,org.eclipse.emf.ecore.xmi;visibility:=reexportBundle-ActivationPolicy: lazy

Page 36: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• The generated plugin.xml is not regenerated so you can tailor it as needed

– But keep in mind that it contains extension points with data that might change when your model name changes

Generated Plugin XML

Thursday, November 13, 2008 36© Macro Modeling Ltd. | EDL V1.0

<plugin>

<extension point="org.eclipse.emf.ecore.generated_package"><package

uri="http://www.example.org/tree"class="org.example.tree.TreePackage"genModel="model/Tree.genmodel"/>

</extension>

<extension point="org.eclipse.emf.ecore.extension_parser"><parser

type="tree"class="org.example.tree.util.TreeResourceFactoryImpl"/>

</extension>

</plugin>

Page 37: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• The generated plugin.properties supports merging– Any property not already defined is added– Any property already defined retains it’s value

• The generated build.properties will not be modified once it exists it can be tailored as desired

Generated Build and Plugin Properties

Thursday, November 13, 2008 37© Macro Modeling Ltd. | EDL V1.0

pluginName = Tree ModelproviderName = www.example.org

bin.includes = .,\model/,\META-INF/,\plugin.xml,\plugin.properties

jars.compile.order = .source.. = src/output.. = bin/

Page 38: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• EMF’s generator supports merging generated changes with hand written changes

– All generated code is marked with @generated• Anything so marked will be updated or even deleted during

subsequent regeneration• Everything else is safe

Modifying Generated Code

Thursday, November 13, 2008 38© Macro Modeling Ltd. | EDL V1.0

/*** <!-- begin-user-doc -->* <!-- end-user-doc -->* @generated NOT*/public NodeKind getKind(){return

getParent() == null ?getChildren().isEmpty() ? NodeKind.SINGLETON : NodeKind.ROOT :getChildren().isEmpty() ? NodeKind.LEAF : NodeKind.INTERMEDIATE;

}

Page 39: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• Javadoc containing “user-doc” sections support merging– The text inside that section will be preserved– The text outside that section will be updated– The feature accessor has a comment that should be changed

Modifying Generated Javadoc

Thursday, November 13, 2008 39© Macro Modeling Ltd. | EDL V1.0

/*** Returns the value of the '<em><b>Label</b></em>' attribute.

* <!-- begin-user-doc -->* <p>* If the meaning of the '<em>Label</em>' attribute isn't clear,* there really should be more of a description here...* </p>

* <!-- end-user-doc -->* @return the value of the '<em>Label</em>' attribute.* @see #setLabel(String)* @see org.example.tree.TreePackage#getNode_Label()* @model dataType="org.example.tree.Label“* @generated*/String getLabel();

Page 40: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• A generated method can be renamed by adding a “Gen” suffix and then the original signature can be used to provide additional behavior

Augmenting Generated Methods

Thursday, November 13, 2008 40© Macro Modeling Ltd. | EDL V1.0

/*** <!-- begin-user-doc -->* <!-- end-user-doc -->* @generated*/public void setLabelGen(String newLabel){String oldLabel = label;label = newLabel;if (eNotificationRequired())

eNotify(new ENotificationImpl(this, Notification.SET, TreePackage.NODE__LABEL, oldLabel, label));}

public void setLabel(String newLabel){setLabelGen(newLabel == null ? null : newLabel.intern());

}

Page 41: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

label

children

parent

label Y

children

parent

label

children

parent

label B

children

parent

label B

children

parent Root

label

children

parent

label X

children

parent

label

children

parent

label A

children

parent

label A

children

parent Root

label

children

parent

label Root

children

parent

label Root

children A

parent

label Root

children A, B

parent

Node

Creating a Tree Instance Model

Thursday, November 13, 2008 41© Macro Modeling Ltd. | EDL V1.0

label A

children X

parent Root

Node

label B

children Y

parent Root

Node

label X

children

parent A

Node

label Y

children

parent B

Node

TreeFactory tree =TreeFactory.eINSTANCE;

Node root = tree.createNode();

root.setLabel("Root");

Node a = tree.createNode();

root.getChildren().add(a);

a.setLabel("A");

Node x = tree.createNode();

x.setLabel("X");

a.getChildren().add(x);

Node b = tree.createNode();

b.setLabel("B");

root.getChildren().add(b);

Node y = tree.createNode();

y.setLabel("Y");

b.getChildren().add(y);

Page 42: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Notifiers, Adapters, and Notification

Thursday, November 13, 2008 42© Macro Modeling Ltd. | EDL V1.0

public interface Notifier{EList<Adapter> eAdapters();void eNotify(Notification notification);boolean eDeliver();void eSetDeliver(boolean deliver);

}

public interface Adapter{void notifyChanged(Notification notification);// ...

}

int SET = 1;int UNSET = 2;int ADD = 3;int REMOVE = 4;int ADD_MANY = 5;int REMOVE_MANY = 6;int MOVE = 7; int REMOVING_ADAPTER = 8; int RESOLVE = 9;int EVENT_TYPE_COUNT = 10;

notifier.eAdapters().add(new AdapterImpl(){@Overridepublic void notifyChanged(Notification notification){// Process notifications produced by the notifier.

}});

public interface Notification{Object getNotifier();int getEventType();Object getFeature();Object getOldValue();Object getNewValue();int getPosition();// ...

}

Page 43: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• EObject is EMF’s equivalent to java.lang.Object– Just as java.lang.Object has getClass() to determine the object’s runtime

java.lang.Class, EObject has eClass() to determine the object’s runtime EClass– An EObject knows the EObject that contains it as well as the specific

containment EReference by which it is referenced– An EObject knows all its contained children

• An EObject is a notifier– Changes to its features fire notifications

EObject Reflection

Thursday, November 13, 2008 43© Macro Modeling Ltd. | EDL V1.0

public interface EObject extends Notifier{EClass eClass();EObject eContainer();EReference eContainmentFeature();EList<EObject> eContents();// ...

}

Page 44: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• Generated set (and unset) method as well as EMF’s specialized list implementations all produce notifications– The logic is optimized to produce them if and only if there

are listeners

EObject Notification

Thursday, November 13, 2008 44© Macro Modeling Ltd. | EDL V1.0

public void setLabel(String newLabel){String oldLabel = label;label = newLabel;if (eNotificationRequired())

eNotify(new ENotificationImpl

(this, Notification.SET, TreePackage.NODE__LABEL, oldLabel, label));}

Page 45: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• Ecore models associations as a pair of references related as opposites– Such references are referred to as bidirectional– EMF enforces the referential integrity of such references via the handshaking

protocol provided by InternalEObject’s eInverseAdd and eInverseRemove

• A containment reference induces a tree structure– It is implicitly bidirectional even if there is no explicitly defined opposite– EObject’s eContainer() is the implicit opposite of a containment reference

• A container reference is the explicit opposite of a containment reference– It is effectively derived from EObject.eContainer()

• Any other type of reference is referred to as a cross reference– It specifies cross links between the objects in the tree structure induced by

containment and container references

• When an object is added to a containment reference it is removed from its current containment reference

– Referential integrity is enforced, i.e., there can only be one eContainer()

References and Referential Integrity

Thursday, November 13, 2008 45© Macro Modeling Ltd. | EDL V1.0

Page 46: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Notifier Feature Type Old New

label

children

parent

label Y

children

parent

label

children

parent

label B

children

parent

label B

children

parent Root

label

children

parent

label X

children

parent

label

children

parent

label A

children

parent

label A

children

parent Root

label

children

parent

label Root

children

parent

label Root

children A

parent

label Root

children A, B

parent

Node

Updating a Tree Instance Model

46

Thursday, November 13, 2008

© Macro Modeling Ltd. | EDL V1.0

label A

children X

parent Root

Node

label B

children Y

parent Root

label X

children

parent A

label Y

children

parent B

Node

b.getChildren().set(0, x);

label B

children X

parent Root

Node

Notifier Feature Type Old New

b children SET y

Notifier Feature Type Old New

b children SET y x

Notifier Feature Type Old New

b children SET y x

y parent SET b

Notifier Feature Type Old New

b children SET y x

y parent SET b

x parent SET a

Notifier Feature Type Old New

b children SET y x

y parent SET b

x parent SET a b

label X

children

parent B

Node

Notifier Feature Type Old New

b children SET y x

y parent SET b

x parent SET a b

a children REMOVE x

Page 47: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• The principles of representation state transfer underlie EMF’s persistence architecture– Models are stored in one or more resources– Each resource is addressed via a Uniform Resource

Identifier, i.e., a URI– A resource supports save, load, unload, and delete– Specialized resources support arbitrary content types– Transfer of state is uniformly handled by a stateless URI

converter that supports• Any scheme accessible as a URL• Any scheme registered with Eclipse File System (EFS)

RESTful Persistence

Thursday, November 13, 2008 47© Macro Modeling Ltd. | EDL V1.0

Page 48: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• A URI is effectively a string with a well defined structure– Supported by org.eclipse.emf.common.util.URI

• It predates java.net.URI• They are immutable• They are created by static factory methods

Uniform Resource Identifiers

Thursday, November 13, 2008 48© Macro Modeling Ltd. | EDL V1.0

public final class URI{

public static URI createURI(String uri);public static URI createFileURI(String pathName);public static URI createPlatformResourceURI(String pathName, boolean encode);public static URI createPlatformPluginURI(String pathName, boolean encode);// …

}

Page 49: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• A URI typically consists of /-separated components– [scheme:][//authority][/path][?query][#fragment]– E.g.,

• http://www.eclipse.org/modeling/emf/?project=emf#related• file://c:/workspace/project/file.extension#id• platform:/resource/project/file.extension#id

Hierarchical URIs

Thursday, November 13, 2008 49© Macro Modeling Ltd. | EDL V1.0

public final class URI{

public boolean isHierarchical();public String scheme();public String authority();public String[] segments();public String path();public String query();public String fragment();// ...

}

Page 50: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• An absolute URI starts with a scheme– Always uses absolute URIs to identify resources!– Relative URIs are useful within resources for referring to

other resources within the same authority• This supports moving groups of related resources

– Examples of relative URIs• #id• ../directory/file.extension• file.extension

Absolute and Relative URIs

Thursday, November 13, 2008 50© Macro Modeling Ltd. | EDL V1.0

public final class URI{

public boolean isRelative();// ...

}

Page 51: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• Deresolving an absolute URI against a base absolute URI yields the URI relative to that base– E.g., deresolving platform:/resource/a/foo.html against

platform:/resource/b/bar.html yields ../a/foo.html

• Resolving a relative URI against a base absolute URI yields the absolute URI relative to that base– E.g., resolving ../a/foo.html against

platform:/resource/b/bar.html yields platform:/resource/a/foo.html

Resolving and Deresolving URIs

Thursday, November 13, 2008 51© Macro Modeling Ltd. | EDL V1.0

public final class URI{

public URI resolve(URI base);public URI deresolve(URI base);// ...

}

Page 52: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• A file system path is OS-specific!– It is not a URI and \ is not a separator in a URI– Use createFileURI to convert a file system path to a URI

• The path c:\a\foo.html becomes file:/c:/a/foo.html

– Use toFileString to convert back to a file system path– Ensure your file system path is also absolute

• URI.createFileURI(new java.io.File(<path>).getAbsolutePath());

URIs to Access the File System

Thursday, November 13, 2008 52© Macro Modeling Ltd. | EDL V1.0

public final class URI{public static URI createFileURI(String pathName)public boolean isFile();public String toFileString();// ...

}

Page 53: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• Use platform resource URIs to access the workspace– platform:/resource/project[/relative-path]– Be sure to encode the path

• URI.createPlatformResourceURI(iFile.getPath().toString(), true)

– Use workspaceRoot.getFile(new Path(uri.toPlatformResourceString(true)))

to convert back to an IFile

URIs to Access the Eclipse Workspace

Thursday, November 13, 2008 53© Macro Modeling Ltd. | EDL V1.0

public final class URI{public static URI createPlatformResourceURI(String pathName, boolean encode);public boolean isPlatformResource();public String toPlatformString(boolean decode);// ...

}

Page 54: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• Use platform plugin URIs to access the installation– platform:/plugin/plugin-id[/relative-path]– Be sure to encode the path

• URI.createPlatformPluginURI(<plugin-path>, true);

URIs to Access the Eclipse Installation

Thursday, November 13, 2008 54© Macro Modeling Ltd. | EDL V1.0

public final class URI{public static URI createPlatformPluginURI(String pathName, boolean encode);public boolean isPlatformPlugin();public String toPlatformString(boolean decode);// ...

}

Page 55: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• Use archive URIs to access zipped or jarred content– archive:absolute-uri{!/relative-path}+– E.g., archive:file:/c:/my.zip!/a/foo.zip!/b/bar.html

URIs to Access an Archive

Thursday, November 13, 2008 55© Macro Modeling Ltd. | EDL V1.0

public final class URI{public boolean isArchive();// ...

}

Page 56: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• All access to the state associated with a URI is directed to a URI converter– It supports URI normalization

• Relative URIs are made absolute• URI mappings are applied

– There is a global URI converter instance• Implementations should extend ExtensibleURIConverterImpl

URI Converter

Thursday, November 13, 2008 56© Macro Modeling Ltd. | EDL V1.0

public interface URIConverter{

URI normalize(URI uri);URIConverter INSTANCE = new ExtensibleURIConverterImpl();// ...

}

Page 57: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• A URI map provides support for redirection– Instance mappings, e.g.,

• http://www.example.org/foo.html -> platform:/plugin/org.example/foo.html

– Folder mappings (URIs ending with /), e.g.,• http://www.example.org/ ->

platform:/plugin/org.example/

– There’s a global instance that can be populated by the org.eclipse.emf.ecore.uri_mapping extension point

URI Converter Remapping

Thursday, November 13, 2008 57© Macro Modeling Ltd. | EDL V1.0

public interface URIConverter{

Map<URI, URI> getURIMap();Map<URI, URI> URI_MAP = /**/;// ...

}

Page 58: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• The URI converter acts as a factory for creating input and output streams

– Arbitrary client-defined options can be passed along– An OPTION_RESPONSE can be used to pass in a map to be populated

with additional information• The RESPONSE_TIME_STAMP_PROPERTY will be updated with the

time stamp of the resource at the time the stream was created

URI Converter Input and Output

Thursday, November 13, 2008 58© Macro Modeling Ltd. | EDL V1.0

public interface URIConverter{

String OPTION_RESPONSE = "RESPONSE";String RESPONSE_TIME_STAMP_PROPERTY = "TIME_STAMP";InputStream createInputStream(URI uri, Map<?, ?> options) throws IOException;OutputStream createOutputStream(URI uri, Map<?, ?> options) throws IOException;//...

}

Page 59: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• The URI converter can test whether there is any state associated with a URI– This is generally more efficient than fetching an input

stream, which could fail due to insufficient permission

• The state associated with a URI can be deleted– This was added in 2.4 to support the full create, read,

update, delete (CRUD) life cycle

URI Converter Deletion and Existence

Thursday, November 13, 2008 59© Macro Modeling Ltd. | EDL V1.0

public interface URIConverter{boolean exists(URI uri, Map<?, ?> options); void delete(URI uri, Map<?, ?> options) throws IOException;// ...

}

Page 60: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• Attributes associated with the state of a URI can be fetched and stored– An OPTION_REQUESTED_ATTRIBUTES map specifies the

attributes to be fetched

URI Converter

Thursday, November 13, 2008 60© Macro Modeling Ltd. | EDL V1.0

public interface URIConverter{

String ATTRIBUTE_TIME_STAMP = "timeStamp";long NULL_TIME_STAMP = -1;String ATTRIBUTE_LENGTH = "length";String ATTRIBUTE_READ_ONLY = "readOnly";String ATTRIBUTE_EXECUTABLE = "executable";String ATTRIBUTE_ARCHIVE = "archive";String ATTRIBUTE_HIDDEN = "hidden";String ATTRIBUTE_DIRECTORY = "directory";String OPTION_REQUESTED_ATTRIBUTES = "requestedAttributes";Map<String, ?> getAttributes(URI uri, Map<?, ?> options);void setAttributes(URI uri, Map<String, ?> attributes, Map<?, ?> options) throws IOException;// ...

}

Page 61: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• A URI converter can be asked to provide a content description of the state associated with a URI– The result is a map of properties describing the content

• The content description is typically determined by analyzing the input stream the URI– This analysis is done by content handlers– There is a configurable list of these handlers

URI Converter Content Description

Thursday, November 13, 2008 61© Macro Modeling Ltd. | EDL V1.0

public interface URIConverter{Map<String, ?> contentDescription(URI uri, Map<?, ?> options) throws IOException;EList<ContentHandler> getContentHandlers();// ...

}

Page 62: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• All the work of the URI converter is delegated to a URI handler– URIs are normalized before the handler is determined– The getURIHandler method determines the appropriate

handler for the given URI – There is a configurable list of URI handlers

• Initially populated with URIHandler.DEFAULTS

URI Converter Delegation To URI Handlers

Thursday, November 13, 2008 62© Macro Modeling Ltd. | EDL V1.0

public interface URIConverter{EList<URIHandler> getURIHandlers();URIHandler getURIHandler(URI uri);// ...

}

Page 63: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• The full complement of URI converter methods are supported for delegation

• The canHandle method indicates whether the handler is applicable for the given URI

• Facilitates composition of specialized URI converter behavior

URI Handler

Thursday, November 13, 2008 63© Macro Modeling Ltd. | EDL V1.0

public interface URIHandler{

boolean canHandle(URI uri);InputStream createInputStream(URI uri, Map<?, ?> options) throws IOException;OutputStream createOutputStream(URI uri, Map<?, ?> options) throws IOException;void delete(URI uri, Map<?, ?> options) throws IOException;Map<String, ?> contentDescription(URI uri, Map<?, ?> options) throws IOException;boolean exists(URI uri, Map<?, ?> options);Map<String, ?> getAttributes(URI uri, Map<?, ?> options);void setAttributes(URI uri, Map<String, ?> attributes, Map<?, ?> options) throws IOException;// ...

}

Page 64: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• Default URI handlers support the Eclipse workspace, the file system, the Eclipse File System, nested archives, and arbitrary URLs

URI Handler

Thursday, November 13, 2008 64© Macro Modeling Ltd. | EDL V1.0

public interface URIHandler{

List<URIHandler> DEFAULT_HANDLERS = Collections.unmodifiableList

(Arrays.asList(new URIHandler [] {

new PlatformResourceURIHandlerImpl(), new FileURIHandlerImpl(), new EFSURIHandlerImpl(), new ArchiveURIHandlerImpl(), new URIHandlerImpl()

}));// ...

}

Page 65: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• The URI converter creates an input stream along with an empty context and delegates to each content handler for which canHandle returns true

– The context cashes state to reduce duplicate computation costs

• Other than validity and content type, only the requested properties in the map supplied in the options are computed

Content Handler

Thursday, November 13, 2008 65© Macro Modeling Ltd. | EDL V1.0

public interface ContentHandler{

boolean canHandle(URI uri);String OPTION_REQUESTED_PROPERTIES = "REQUESTED_PROPERTIES";Map<String, ?> contentDescription

(URI uri, InputStream inputStream, Map<?, ?> options, Map<Object, Object> context) throws IOException;

// ...}

Page 66: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• Content validity is a three state result– The URI converter returns the description of the first handler that

yields a valid description– Failing that, it returns the first indeterminate description– Only when invalid is the content type not included in the description

Content Handler Validity Determination

Thursday, November 13, 2008 66© Macro Modeling Ltd. | EDL V1.0

public interface ContentHandler{

String VALIDITY_PROPERTY = "org.eclipse.emf.ecore:validity";

enum Validity{

INVALID,INDETERMINATE,VALID

}

String CONTENT_TYPE_PROPERTY = "org.eclipse.emf.ecore:contentType";String UNSPECIFIED_CONTENT_TYPE = "";Map<String, Object> INVALID_CONTENT_DESCRIPTION = /**/;

}

Page 67: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• Two standard description properties are supported– The character set used to encode the content– The byte order marker at the start of the stream

Content Handler Encodings

Thursday, November 13, 2008 67© Macro Modeling Ltd. | EDL V1.0

public interface ContentHandler{

String CHARSET_PROPERTY = "org.eclipse.core.runtime:charset";String BYTE_ORDER_MARK_PROPERTY = "org.eclipse.core.runtime:bom";

enum ByteOrderMark{

UTF_8,UTF_16BE,UTF_16LE;public byte [] bytes();public static ByteOrderMark read(InputStream inputStream) throws IOException;

}// ..

}

Page 68: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• There is a registry of content handlers populated by the org.eclipse.emf.ecore.content_handler extension point

– Handlers are sorted and applied based on priority– A flattened list view based on priority is provided– A single default handler that delegates to the platform is registered by EMF

so that org.eclipse.core.contenttype.contentTypes registrations are exploited

Content Handler Registration

Thursday, November 13, 2008 68© Macro Modeling Ltd. | EDL V1.0

public interface ContentHandler{

interface Registry extends SortedMap<Integer, List<ContentHandler>>{

int VERY_HIGH_PRIORITY = -10000;int HIGH_PRIORITY = -1000;int NORMAL_PRIORITY = 0;int LOW_PRIORITY = 1000;int VERY_LOW_PRIORITY = 10000;void put(int priority, ContentHandler contentHandler);List<ContentHandler> contentHandlers();Registry INSTANCE = new ContentHandlerRegistryImpl();

}}

Page 69: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• A resource set acts as a container for resources– The relationship from resource set to resource is

effectively bidirectional containment

• A resource set is a notifier– Changes to the resources list fire notifications for the

RESOURCE_SET__RESOURCES feature

Resource Set

Thursday, November 13, 2008 69© Macro Modeling Ltd. | EDL V1.0

public interface ResourceSet extends Notifier{int RESOURCE_SET__RESOURCES = 0;EList<Resource> getResources();// ...

}

Page 70: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• A resource acts as a container for EObjects– The relationship from resource to EObject is effectively bidirectional

containment

• A resource knows its containing resource set• A resource is a notifier

– Changes to its features fire notifications

Resource

Thursday, November 13, 2008 70© Macro Modeling Ltd. | EDL V1.0

public interface Resource extends Notifier{

int RESOURCE__RESOURCE_SET = 0;ResourceSet getResourceSet();int RESOURCE__URI = 1;URI getURI();void setURI(URI uri);int RESOURCE__CONTENTS = 2;EList<EObject> getContents();// ...

}

public interface EObject //...{

Resource eResource();// ...

}

Page 71: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• Resource set’s resources, a resource’s contents, and an EObject’s eContents() collectively induce a tree structure that can be walked by a tree iterator, which is simply an iterator that supports branch pruning

Tree Iterators over the Containment Tree

Thursday, November 13, 2008 71© Macro Modeling Ltd. | EDL V1.0

public interface Resource // ...{

TreeIterator<EObject> getAllContents();// ...

}

public interface EObject //...{

TreeIterator<EObject> eAllContents();// ...

}

public interface ResourceSet // ...{

TreeIterator<Notifier> getAllContents();// ...

}

public interface TreeIterator<E> extends Iterator<E>

{

void prune();}

Page 72: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• A resource set provides a complete context– A URI converter for accessing the state of the resources– A resource factory registry for determining the

appropriate factory when creating new resources– A package registry for determining the appropriate

package to associate with a namespace URI

Resource Set

Thursday, November 13, 2008 72© Macro Modeling Ltd. | EDL V1.0

public interface ResourceSet extends Notifier{URIConverter getURIConverter();Resource.Factory.Registry getResourceFactoryRegistry();EPackage.Registry getPackageRegistry();// ...

}

Page 73: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• A resource factory creates a resource given a URI– It is responsible for creating and configuring new

resources

• Resource factories are maintained in resource factory registries

Resource Factory

Thursday, November 13, 2008 73© Macro Modeling Ltd. | EDL V1.0

public interface Resource // ...{

interface Factory{

Resource createResource(URI uri);// ...

} }

Page 74: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• A resource factory registry determines the appropriate factory given a URI and a content type

– For null content type, no lookup based on content type is performed– For URIHandler.UNSPECIFIED_CONTENT_TYPE, the content type is

computed lazily when first required– A resource set’s local resource factory registry delegates to the global

instance when local lookup yields no match

Resource Factory Registry

Thursday, November 13, 2008 74© Macro Modeling Ltd. | EDL V1.0

public interface Resource // ...{interface Factory{

interface Registry{

Factory getFactory(URI uri, String contentType);Registry INSTANCE = new ResourceFactoryRegistryImpl();// ...

}}

}

Page 75: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• Registration based on URI scheme is supported– The org.eclipse.emf.ecore.protocol_parser extension

point is used to register such a factory with the global factory registry instance

– This mechanism is rarely used and is not very RESTful

Protocol Resource Factory Registration

Thursday, November 13, 2008 75© Macro Modeling Ltd. | EDL V1.0

public interface Resource // ...{interface Factory{

interface Registry{

Map<String, Object> getProtocolToFactoryMap();// ...

}}

}

public final class URI{

public String scheme();// ...

}

Page 76: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• Registration based on URI file extension is supported

– The org.eclipse.emf.ecore.extension_parser extension point is used to register such a factory with the global factory registry instance

– A registration against the default extension matches any extension– This mechanism is commonly used, efficient, but not very RESTful

File Extension Resource Factory Registration

Thursday, November 13, 2008 76© Macro Modeling Ltd. | EDL V1.0

public interface Resource // ...{interface Factory{

interface Registry{

String DEFAULT_EXTENSION = "*";Map<String, Object> getExtensionToFactoryMap();// ...

}}

}

public final class URI{

public String fileExtension();// ...

}

Page 77: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• Registration based on content type is supported– The org.eclipse.emf.ecore.content_parser extension point is used to

register such a factory with the global factory registry instance– A registration against the default content type matches any content

type– This is new to 2.4 and is more RESTful

Content Type Resource Factory Registration

Thursday, November 13, 2008 77© Macro Modeling Ltd. | EDL V1.0

public interface Resource // ...{interface Factory{

interface Registry{

String DEFAULT_CONTENT_TYPE_IDENTIFIER = "*";Map<String, Object> getContentTypeToFactoryMap();

}} // ...

}

Page 78: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• A package registry determines the appropriate EPackage or EFactorygiven a namespace URI

– The org.eclipse.emf.ecore.generated_package/dynamic_package extension points are used to register generated/dynamic packages with the global registry

– The org.eclipse.emf.ecore.factory_override extension point is used to register a factory that overrides the generated default

– A resource set’s local package registry delegates to the global instance when local lookup yields no match

• The org.eclipse.emf.ecore.package_registry_implementation can be used once to override the default implementation of the global instance

Package Registry

Thursday, November 13, 2008 78© Macro Modeling Ltd. | EDL V1.0

public interface EPackage // ...{

interface Registry{

EPackage getEPackage(String nsURI);EFactory getEFactory(String nsURI);Registry INSTANCE = EPackageRegistryImpl.createGlobalRegistry();// ...

}}

Page 79: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• A resource set acts as a factory for creating resources– Specifying no content type is equivalent to specifying null– The resource set’s resource factory registry is consulted to

determine the appropriate factory– That factory is used to create the resource– That resource is added to the list of resources

Creating a New Resource

Thursday, November 13, 2008 79© Macro Modeling Ltd. | EDL V1.0

public interface ResourceSet // ...{Resource createResource(URI uri);Resource createResource(URI uri, String contentType);// ...

}

Page 80: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• A newly created resource is initially considered not loaded– Adding an object to the contents list will change the state

to indicate that it is considered loaded

Populating a New Resource

Thursday, November 13, 2008 80© Macro Modeling Ltd. | EDL V1.0

public interface Resource // ...

{

int RESOURCE__IS_LOADED = 4;boolean isLoaded();// ...

}

Page 81: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• Resource has two save methods– The save method without an output stream argument

uses the URI converter of the containing resource set to create an output stream from the resource’s URI and then calls the second save method, after which it closes the stream

– The second save method writes a representation of the contained objects into the output stream

Saving a Resource

Thursday, November 13, 2008 81© Macro Modeling Ltd. | EDL V1.0

public interface Resource // ...{

void save(Map<?, ?> options) throws IOException;void save(OutputStream outputStream, Map<?, ?> options) throws IOException;// ...

}

Page 82: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Saving a Tree Model Instance

Thursday, November 13, 2008 82© Macro Modeling Ltd. | EDL V1.0

eContainer

eResourcelabelchildrenparent

eContainer

eResourcelabel Rootchildrenparent

eContainer

eResourcelabel Rootchildren Aparent

Node

resourcesResourceSet

eContainer

eResourcelabelchildrenparent

eContainer

eResourcelabel Achildrenparent

eContainer

eResourcelabel Achildrenparent Root

Node

resource.save(null);

root.getChildren().add(a);

a.setLabel("A");

Node a = tree.createNode();

resource.getContents().add(root);

root.setLabel("Root");

Node root = tree.createNode();

TreeFactory tree = TreeFactory.eINSTANCE;

Resource resource =resourceSet.createResource

(URI.createFileURI("c:/Root.tree"));

ResourceSet resourceSet =new ResourceSetImpl();

resourceSeturicontents

resourceSeturi file:/c:/Root.treecontents

Resource

<?xml version="1.0" encoding="ASCII"?><tree:Node xmi:version="2.0"

xmlns:xmi="http://www.omg.org/XMI"xmlns:tree="http://www.example.org/tree"label="Root">

<children label="A"/></tree:Node>

Page 83: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• Resource has two load methods– The load method without an input stream argument uses

the URI converter of the containing resource set to create an input stream from the resource’s URI and then calls the second load method, after which it closes the stream

– The second load method reads the representation and adds the resulting objects to the contents

– Resources are usually not loaded explicitly

Explicitly Loading a Resource

Thursday, November 13, 2008 83© Macro Modeling Ltd. | EDL V1.0

public interface Resource // ...{

void load(Map<?, ?> options) throws IOException;void load(InputStream inputStream, Map<?, ?> options) throws IOException;// ...

}

Page 84: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• Resources are typically demand loaded into a resource set rather than being explicitly loaded

– The existing list of resources is first considered for a match– If there isn’t one, a new resource is created as before– If the matched resource isn’t already loaded or a new resource is

created, that resource is loaded• The default load options are passed to the load method

Demand Loading a Resource

Thursday, November 13, 2008 84© Macro Modeling Ltd. | EDL V1.0

public interface ResourceSet // ...{Map<Object, Object> getLoadOptions();Resource getResource(URI uri, boolean loadOnDemand);// ...

}

Page 85: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Loading a Tree Model Instance

Thursday, November 13, 2008 85© Macro Modeling Ltd. | EDL V1.0

eContainer

eResourcelabelchildrenparent

eContainer

eResourcelabel Rootchildrenparent

eContainer

eResourcelabel Rootchildren Aparent

eContainer

eResourcelabel Root’children Aparent

eContainer

eResourcelabel Root’children A’parent

Node

resourcesResourceSet

eContainer

eResourcelabelchildrenparent

eContainer

eResourcelabel Achildrenparent

eContainer

eResourcelabel Achildrenparent Root

eContainer

eResourcelabel Achildrenparent Root’

eContainer

eResourcelabel A’childrenparent Root’

Node

resource.save(System.out, null);

a.setLabel(a.getLabel() + "'");

Node a = root.getChildren().get(0);

root.setLabel(root.getLabel() + "'");

Node root = (Node)resource.getContents().get(0);

Resource resource =resourceSet.getResource

(URI.createFileURI("c:/Root.tree"),true);

ResourceSet resourceSet =new ResourceSetImpl();

resourceSeturicontents

resourceSeturi file:/c:/Root.treecontents

Resource

<?xml version="1.0" encoding="ASCII"?><tree:Node xmi:version="2.0"

xmlns:xmi="http://www.omg.org/XMI"xmlns:tree="http://www.example.org/tree"label="Root'">

<children label="A'"/></tree:Node>

Page 86: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• Both loading and saving update a resource’s time stamp– When loading, it’s the time stamp of the resource when the input

stream is opened– When saving, it’s the time stamp of the resource after the output

stream is closed– When populating a new resource, it’s the time stamp of the clock

when the first object is added

• This can be used to implement optimistic concurrency or to detect external changes

Resource Time Stamps

Thursday, November 13, 2008 86© Macro Modeling Ltd. | EDL V1.0

public interface Resource // ...{

int RESOURCE__TIME_STAMP = 8;long getTimeStamp();void setTimeStamp(long timeStamp);// ...

}

Page 87: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• A resource can track modification of its contents– It’s implemented using adapters on the tree of content– It’s quite expensive and hence is optional and not enabled by default– Typically the state of the command stack is used to track changes

• This provides better support for undo reversing a modification

Resource Modification Tracking

Thursday, November 13, 2008 87© Macro Modeling Ltd. | EDL V1.0

public interface Resource // ...{

int RESOURCE__IS_TRACKING_MODIFICATION = 5;boolean isTrackingModification();void setTrackingModification(boolean isTrackingModification);int RESOURCE__IS_MODIFIED = 3;boolean isModified();void setModified(boolean isModified);// ...

}

Page 88: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• Problems encountered when loading a resource are recorded as diagnostics describing the problem

Resource Diagnostics

Thursday, November 13, 2008 88© Macro Modeling Ltd. | EDL V1.0

public interface Resource // ...{

int RESOURCE__ERRORS = 6;EList<Diagnostic> getErrors();int RESOURCE__WARNINGS = 7;EList<Diagnostic> getWarnings();

interface Diagnostic{

String getMessage();String getLocation();int getLine();int getColumn();

}// ...

}

Page 89: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• A resource can be unloaded to discard any changes– It returns to the state it was in when first created– All the contained objects are converted to proxies so that

references to them will try to resolve again– The resource can subsequently be loaded again

Resource Unloading

Thursday, November 13, 2008 89© Macro Modeling Ltd. | EDL V1.0

public interface Resource // ...

{

void unload();// ...

}

Page 90: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• A resource can be deleted– The resource set’s URI converter is used to delete the

state associated with the resource’s URI– Then the resource is unloaded, hence converting all its

contents to proxies– Finally the resource is removed from the resource set

Resource Deletion

Thursday, November 13, 2008 90© Macro Modeling Ltd. | EDL V1.0

public interface Resource // ...

{

void delete(Map<?, ?> options) throws IOException;// ...

}

Page 91: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• In order to persist an object, it must be contained by a resource, i.e., – It must either be directly a member of a resource’s

contents list– Or it must be possible to reach such a direct member

object by walking up the eContainer() chain– Typically eResource() and eContainer() are mutually

exclusive• That means adding an object to a resource’s contents

removes it from it’s current container

Containment References Revisited

Thursday, November 13, 2008 91© Macro Modeling Ltd. | EDL V1.0

Page 92: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Moving a Tree Model Instance

Thursday, November 13, 2008 92© Macro Modeling Ltd. | EDL V1.0

eContainer

eResourcelabel Rootchildren Aparent

eContainer

eResourcelabel Rootchildrenparent

Node

resourcesResourceSet

eContainer

eResourcelabel Achildrenparent Root

eContainer

eResourcelabel Achildrenparent

Node

child.getContents().add(a);

Resource child =resourceSet.createResource

(URI.createFileURI("c:/Child.tree"));

resourceSeturi file:/c:/Root.treecontents

ResourceresourceSeturicontents

resourceSeturi file:/c:/Child.treecontents

Resource

Page 93: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• A reference that is neither a containment nor the opposite of a containment, i.e., a container, is a cross reference

– Cross references can span not only objects within a containment tree but also objects across different resources

– Cross references require specialized serialization support– An EObject knows all its cross references

Cross References Revisited

Thursday, November 13, 2008 93© Macro Modeling Ltd. | EDL V1.0

public interface EObject // ...{EList<EObject> eCrossReferences();// ...

}

Page 94: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• A full URI that includes a fragment denotes an EObject– The URI that is left when the fragment is trimmed denotes a resource– The fragment itself locates the object within that resource– The resource is responsible for producing a fragment that it can

subsequently use to locate the object• Given a Resource r and an EObject x the follow is always true

r.getEObject(r.getURIFragment(x)) == x

URI Access EObjects

Thursday, November 13, 2008 94© Macro Modeling Ltd. | EDL V1.0

public interface Resource // ...{

EObject getEObject(String uriFragment);String getURIFragment(EObject eObject);// ...

}

public final class URI{

public String fragment();public URI trimFragment();public URI appendFragment(String fragment);

// ...}

Page 95: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• An EObject can be located or demand loaded in a resource set– The URI fragment is trimmed and used to locate or

demand load the resource it denotes– If one is found, the fragment is used to locate the object

within that resource

Locating or Demand Loading an EObject

Thursday, November 13, 2008 95© Macro Modeling Ltd. | EDL V1.0

public interface ResourceSet // ...{

EObject getEObject(URI uri, boolean loadOnDemand);// ...

}

Page 96: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• URI fragment can take one of several different forms– Fragment paths

• The fragment is a path that consists of /-separated segments that are used to navigate to the object starting from the root of the resource

– Keys• A combination of attributes that uniquely identify the

object within a given reference– Intrinsic IDs

• A unique strings stored as data on the object itself– Extrinsic IDs

• Unique strings associated with the objects but maintained by the resource

URI Fragments

Thursday, November 13, 2008 96© Macro Modeling Ltd. | EDL V1.0

Page 97: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• The fragment starts with a root segment determined by the resource

– By default a numeric indexing scheme is used, i.e., the zero-based index of the root object in the resource’s contents• /0 denotes the first root object and the 0 is optional

– The remaining segments are computed by the objects themselves using the InternalEObject API

• The modeled objects may specialize their segment syntax• The default implementation uses @feature-name[.index]

URI Fragment Paths

Thursday, November 13, 2008 97© Macro Modeling Ltd. | EDL V1.0

public interface InternalEObject // ...{

String eURIFragmentSegment(EStructuralFeature eFeature, EObject eObject);EObject eObjectForURIFragmentSegment(String uriFragmentSegment);// ...

}

Page 98: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• The index-based default segment syntax within a multi-valued reference is fragile with respect to list reordering

• Keys can be used to make this more robust– An EReference can designate one or more of the EAttributes of its

referenced EClass as uniquely identifying each object in that reference

– This yields a syntax in the following form, where the square brackets are part of the actual segment rather than denoting optionality

@feature-name[key='value1',key2='value2']

URI Fragment Paths with Keys

Thursday, November 13, 2008 98© Macro Modeling Ltd. | EDL V1.0

public interface EReference // ...{

EList<EAttribute> getEKeys();// ...

}

Page 99: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• Any path-based mechanism will be fragile with respect to restructuring of the tree

• IDs can be used to make this more robust– An EAttribute can be designed as the ID of its containing EClass– The string value of this attribute will be used directly as the fragment– This string value must be unique with respect to all other objects (of

all types) within the same resource– This uniqueness requirement makes them a bit difficult and expensive

to maintain

URI Fragment Intrinsic IDs

Thursday, November 13, 2008 99© Macro Modeling Ltd. | EDL V1.0

public interface EAttribute// ...{

boolean isID();// ...

}

Page 100: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• Because not all models are able to maintain IDs as data within the instances themselves, a resource implementation can manage a two way object-to-ID mapping within the resource

– XMLResource supports that approach• A specific attribute can be set as corresponding to the ID in the

serialization, e.g., xmi:id• By specializing useUUIDs to return true, universally unique IDs are

generated automatically as needed• UUIDs and ID maps take up a lot of space! ~175 bytes per object

URI Fragment Extrinsic IDs

Thursday, November 13, 2008 100© Macro Modeling Ltd. | EDL V1.0

public class EcoreUtil{

public static String generateUUID();// ...

}

Page 101: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Saving Cross Document References

Thursday, November 13, 2008 101© Macro Modeling Ltd. | EDL V1.0

eContainer

eResourcelabelchildrenparentdata

eContainer

eResourcelabel Rootchildrenparentdata

eContainer

eResourcelabel Rootchildren Aparentdata

Node

resourcesResourceSet

eContainer

eResourcelabelchildrenparentdata

eContainer

eResourcelabel Achildrenparentdata

eContainer

eResourcelabel Achildrenparent Rootdata

Node

resource.save(null);

map.getContents().addAll(copier.copyAll

(resource.getContents()));

EcoreUtil.Copier copier =new EcoreUtil.Copier();

Resource map =resourceSet.createResource

(URI.createFileURI("c:/Map.tree"));

Resource resource =resourceSet.getResource

(URI.createFileURI("c:/Root.tree"),true);

ResourceSet resourceSet =new ResourceSetImpl();

resourceSeturicontents

resourceSeturi file:/c:/Root.treecontents

Resource

for (Iterator<EObject> i = resource.getAllContents();

i.hasNext(); ){

EObject eObject = i.next();((Node)copier.get(eObject)).

setData(eObject);}

eContainer

eResourcelabelchildrenparentdata

eContainer

eResourcelabel Rootchildrenparentdata

eContainer

eResourcelabel Rootchildren Aparentdata

Node

eContainer

eResourcelabelchildrenparentdata

eContainer

eResourcelabel Achildrenparentdata

eContainer

eResourcelabel Achildrenparent Rootdata

Node

resourceSeturicontents

resourceSeturi file:/c:/Map.treecontents

Resource

<?xml version="1.0" encoding="ASCII"?><tree:Node xmi:version="2.0"

xmlns:xmi="http://www.omg.org/XMI"xmlns:tree="http://www.example.org/tree" label="Root">

<children label="A"><data href="Root.tree#//@children.0"/>

</children><data href="Root.tree#/"/>

</tree:Node>

Page 102: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• EMF supports the concept of a proxy– A proxy is just a regular instance that acts as a proxy– Internally it stores the proxy URI, i.e., the URI of the

EObject to which the proxy should resolve– The proxy URI can be set by the deserializer and is set for

each object when a resource is unloaded

Proxies

Thursday, November 13, 2008 102© Macro Modeling Ltd. | EDL V1.0

public interface EObject // ...

{

boolean eIsProxy();// ...

}

public interface InternalEObjectextends EObject

{

URI eProxyURI();void eSetProxyURI(URI uri);// ...

}

Page 103: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• Generated get methods as well as EMF’s specialized list implementations all resolve proxies on demand

– Resolution produces notifications– Resolution demand loads the proxy URI into the resource set

Proxy Resolution

Thursday, November 13, 2008 103© Macro Modeling Ltd. | EDL V1.0

public EObject getData(){

if (data != null && data.eIsProxy()){

InternalEObject oldData = (InternalEObject)data;data = eResolveProxy(oldData);if (data != oldData){

if (eNotificationRequired())eNotify(new ENotificationImpl

(this, Notification.RESOLVE, TreePackage.NODE__DATA, oldData, data));}

}

return data;}

Page 104: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Loading Cross Document References

Thursday, November 13, 2008 104© Macro Modeling Ltd. | EDL V1.0

eContainer

eResourcelabelchildrenparentdata

eContainer

eResourcelabel Rootchildrenparentdata

eContainer

eResourcelabel Rootchildren Aparentdata

Node

resourcesResourceSet

eContainer

eResourcelabelchildrenparentdata

eContainer

eResourcelabel Achildrenparentdata

eContainer

eResourcelabel Achildrenparent Rootdata

Node

Node child =node.getChildren().get(0);

assert !node.getData().eIsProxy();

Node node = (Node)resource.getContents().get(0);

Resource resource =resourceSet.getResource

(URI.createFileURI("c:/Map.tree"),true);

ResourceSet resourceSet =new ResourceSetImpl();

resourceSeturicontents

resourceSeturi file:/c:/Map.treecontents

Resource

assert child.getData().eIsProxy();

eContainer

eResourcelabelchildrenparentdata

eContainer

eResourcelabel Rootchildrenparentdata

eContainer

eResourcelabel Rootchildren Aparentdata

Node

eContainer

eResourcelabelchildrenparentdata

eContainer

eResourcelabel Achildrenparentdata

eContainer

eResourcelabel Achildrenparent Rootdata

Node

resourceSeturicontents

resourceSeturi file:/c:/Root.treecontents

Resource

eProxyURI file:/c:/Root.tree#/Node

eProxyURI file:/c:/Root.tree#//@children.0Node

Page 105: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• There is optional support for cross resource containment that applies only for proxy resolving containment references; in that case

– An object added to that reference will not be removed from its directly containing resource

– An object added to a resource’s contents will not be remove from such a containment

Cross Resource Containment

Thursday, November 13, 2008 105© Macro Modeling Ltd. | EDL V1.0

Page 106: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

A Cross Contained Tree Model Instance

Thursday, November 13, 2008 106© Macro Modeling Ltd. | EDL V1.0

eContainer

eResourcelabel Rootchildren Aparent

eContainer

eResourcelabel Rootchildrenparent

Node

resourcesResourceSet

eContainer

eResourcelabel Achildrenparent Root

eContainer

eResourcelabel Achildrenparent

Node

child.getContents().add(a);

Resource child =resourceSet.createResource

(URI.createFileURI("c:/Child.tree"));

resourceSeturi file:/c:/Root.treecontents

ResourceresourceSeturicontents

resourceSeturi file:/c:/Child.treecontents

Resource

resource.save(System.out, null);

child.save(System.out, null);

<?xml version="1.0" encoding="ASCII"?><tree:Node xmi:version="2.0"

xmlns:xmi="http://www.omg.org/XMI"xmlns:tree="http://www.example.org/tree" label="Root">

<children href="Child.tree#/"/></tree:Node>

<?xml version="1.0" encoding="ASCII"?><tree:Node xmi:version="2.0"

xmlns:xmi="http://www.omg.org/XMI"xmlns:tree="http://www.example.org/tree" label="A">

<parent href="Root.tree#/"/></tree:Node>

Page 107: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• Implementing a specialized resource involves overriding the doSave and doLoad methods of ResourceImpl

• EMF provides a number of specialized implementations that support– XML serialization - XMLResourceImpl– XMI serialization - XMIResourceImpl– Fast compact binary serialization - BinaryResourceImpl– Database persistence (Teneo)– Distributed shared access (CDO)– Repository (JCRM)

Specialized Resource Implementations

Thursday, November 13, 2008 107© Macro Modeling Ltd. | EDL V1.0

Page 108: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• The resource factory is the place to configure load and save options to be used by all clients

Options to Configure Resource Load and Save

Thursday, November 13, 2008 108© Macro Modeling Ltd. | EDL V1.0

public class TreeResourceFactoryImpl extends ResourceFactoryImpl{

@Overridepublic Resource createResource(URI uri){

XMLResource result = new TreeResourceImpl(uri);result.getDefaultSaveOptions().put(XMLResource.OPTION_EXTENDED_META_DATA, Boolean.TRUE);result.getDefaultLoadOptions().put(XMLResource.OPTION_EXTENDED_META_DATA, Boolean.TRUE);

result.getDefaultSaveOptions().put(XMLResource.OPTION_SCHEMA_LOCATION, Boolean.TRUE);

result.getDefaultLoadOptions().put(XMLResource.OPTION_USE_ENCODED_ATTRIBUTE_STYLE, Boolean.TRUE);result.getDefaultSaveOptions().put(XMLResource.OPTION_USE_ENCODED_ATTRIBUTE_STYLE, Boolean.TRUE);

result.getDefaultLoadOptions().put(XMLResource.OPTION_USE_LEXICAL_HANDLER, Boolean.TRUE);return result;

}// …

}

Page 109: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• Saving only if the result differs from the current content

– Resource.OPTION_SAVE_ONLY_IF_CHANGED• Resource. OPTION_SAVE_ONLY_IF_CHANGED_MEMORY_BUFFER• Resource. OPTION_SAVE_ONLY_IF_CHANGED_FILE_BUFFER

• Encrypting and decrypting the bytes– Resource. OPTION_CIPHER

• A URIConverter.Cipher instance– AESCipherImpl– DESCipherImpl

• Compressing and decompressing the bytes– Resource. OPTION_ZIP

• A Boolean.TRUE or Boolean.FALSE

General Resource Options

Thursday, November 13, 2008 109© Macro Modeling Ltd. | EDL V1.0

Page 110: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• The resource APIs work with InputStreams but you may need to process a String or a Reader and can avoid needless char -> byte -> char conversion

– A stream that implements URIConverter.Readable will be unwrapped and used directly if the underlying resource supports that

– A wrapper implementation is provided URIConverter.ReadableInputStream

• It converts to bytes using the encoding if necessary

Loading from a String or a Reader

Thursday, November 13, 2008 110© Macro Modeling Ltd. | EDL V1.0

interface Readable{

Reader asReader();String getEncoding();

}

class ReadableInputStream extends InputStream implements Readable{

public ReadableInputStream(Reader reader, String encoding)public ReadableInputStream(Reader xmlReader)public ReadableInputStream(String string, String encoding)public ReadableInputStream(String xmlString)

}

Page 111: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• The resource APIs work with OutputStreams but you may need to process a String or a Writer and can avoid needless char -> byte -> char conversion

– A stream that implements URIConverter.Writeable will be unwrapped and used directly if the underlying resource supports that

– A wrapper implementation is provided URIConverter.WriteableInputStream

• It converts to bytes using the encoding if necessary

Saving to a String or a Writer

Thursday, November 13, 2008 111© Macro Modeling Ltd. | EDL V1.0

interface Writeable{Writer asWriter();String getEncoding();

}

static class WriteableOutputStream extends OutputStream implements Writeable{public WriteableOutputStream(Writer writer, String encoding);

}

Page 112: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• Provides a simplified API for loading and saving single document XML instances– Hides registration, resource sets, and resources

• Simplifies the dynamic loading of schemas and their conversion to Ecore when processing dynamic instances

XML Processor

Thursday, November 13, 2008 112© Macro Modeling Ltd. | EDL V1.0

Page 113: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• EObject supports introspection– Getting the value of a feature

• With or without proxy resolution– Setting the value of a feature– Testing if a feature’s value is set– Unsetting the value of a feature

Introspection

Thursday, November 13, 2008 113© Macro Modeling Ltd. | EDL V1.0

public interface EObject // ...{Object eGet(EStructuralFeature feature);Object eGet(EStructuralFeature feature, boolean resolve);void eSet(EStructuralFeature feature, Object newValue);boolean eIsSet(EStructuralFeature feature);void eUnset(EStructuralFeature feature);// ...

}

Page 114: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• The generated reflective accessors are very efficient– EObject.eGet is more than twice as fast a HashMap.get

• Reflective introspect is the key ingredient in any data integration recipe– It provides a uniform mechanism for accessing all data

node.getLabel() == node.eGet(TreePackage.Literals.NODE__LABEL)

– It’s used for copying, persistence, indexing, and so

Introspection is Efficient

Thursday, November 13, 2008 114© Macro Modeling Ltd. | EDL V1.0

public Object eGet(int featureID, boolean resolve, boolean coreType){

switch (featureID){

case TreePackage.NODE__LABEL: return getLabel();}

}

Page 115: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• Ecore is a model like any other, so you can create an instance of it the same way as any other

Creating a Dynamic Ecore Model

Thursday, November 13, 2008 115© Macro Modeling Ltd. | EDL V1.0

EPackage treePackage = EcoreFactory.eINSTANCE.createEPackage();treePackage.setName("tree");treePackage.setNsPrefix("tree");treePackage.setNsURI("http://www.example.org/tree");

EClass nodeClass = EcoreFactory.eINSTANCE.createEClass();nodeClass.setName("Node");treePackage.getEClassifiers().add(nodeClass);

EAttribute labelAttribute = EcoreFactory.eINSTANCE.createEAttribute();labelAttribute.setName("label");labelAttribute.setEType(EcorePackage.Literals.ESTRING);nodeClass.getEStructuralFeatures().add(labelAttribute);

EReference childrenReference = EcoreFactory.eINSTANCE.createEReference();childrenReference.setName("children");childrenReference.setEType(nodeClass);childrenReference.setContainment(true);childrenReference.setUpperBound(EStructuralFeature.UNBOUNDED_MULTIPLICITY);nodeClass.getEStructuralFeatures().add(childrenReference);

Page 116: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• Instances of any Ecore model, including dynamic ones, can create reflectively

Creating Instances of a Dynamic Ecore Model

Thursday, November 13, 2008 116© Macro Modeling Ltd. | EDL V1.0

EFactory treeFactory = treePackage.getEFactoryInstance();

EObject root = treeFactory.create(nodeClass);root.eSet(labelAttribute, "Root");EObject a = treeFactory.create(nodeClass);a.eSet(labelAttribute, "a");((List<EObject>)root.eGet(childrenReference)).add(a);

ResourceSet resourceSet = new ResourceSetImpl();Resource resource = resourceSet.createResource(URI.createFileURI("c:/Root.tree"));resource.getContents().add(root);resource.save(null);

<?xml version="1.0" encoding="ASCII"?><tree:Node xmi:version="2.0"

xmlns:xmi="http://www.omg.org/XMI"xmlns:tree="http://www.example.org/tree" label="Root">

<children label="a"/></tree:Node>

Page 117: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• EMF provides a basic framework for validating instances against their model’s constraints– Validate an EObject– Validate an instance relative to a specific class– Validate a value relative to a specific data type

Validation

Thursday, November 13, 2008 117© Macro Modeling Ltd. | EDL V1.0

public interface EValidator{

boolean validate(EObject eObject, DiagnosticChain diagnostics, Map<Object, Object> context);

boolean validate(EClass eClass, EObject eObject, DiagnosticChain diagnostics, Map<Object, Object> context);

boolean validate(EDataType eDataType, Object value, DiagnosticChain diagnostics, Map<Object, Object> context);

//…}

Page 118: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• EObjectValidator checks basic constraints intrinsic to Ecore – Every value conforms to its multiplicity– Every data value conforms to the applicable XML Schema-based

simple type facet constraints• The value is in the range of its bounds• The value’s length is in range of the length bounds• The value is an instance of one of the union type’s members• The value is one of the enumerated values• The value’s string representation matches the expected pattern• The value’s factional and total digits are in the range of its bounds

– Every referenced object is properly contained; no dangling references– Every proxy resolves properly– Every object IDs is unique within its resource– Every key of reference is unique– Every key of map is unique

Basic Validation of Ecore Constraints

Thursday, November 13, 2008 118© Macro Modeling Ltd. | EDL V1.0

Page 119: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• A named constraint is declared on an EClassifier using an EAnnotation

• An invariant is declared on an EClass using an EOperationwith a specific signature

Declaring Constraints

Thursday, November 13, 2008 119© Macro Modeling Ltd. | EDL V1.0

Page 120: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Generated EValidator

Thursday, November 13, 2008 120© Macro Modeling Ltd. | EDL V1.0

package org.example.tree.util;// ...

public class TreeValidatorextends EObjectValidator

{// ...

}

Page 121: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Generated Validator Constraint

Thursday, November 13, 2008 121© Macro Modeling Ltd. | EDL V1.0

public boolean validateLabel_WellFormed(String label, DiagnosticChain diagnostics, Map<Object, Object> context)

{// TODO implement the constraint// -> specify the condition that violates the constraint// -> verify the diagnostic details, including severity, code, and message// Ensure that you remove @generated or mark it @generated NOTif (false){if (diagnostics != null){diagnostics.add(createDiagnostic(Diagnostic.ERROR,DIAGNOSTIC_SOURCE,0,"_UI_GenericConstraint_diagnostic",new Object[] { "WellFormed", getValueLabel(TreePackage.Literals.LABEL, label, context) },new Object[] { label },context));

}return false;

}return true;

}

Page 122: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Generated Class Invariant

Thursday, November 13, 2008 122© Macro Modeling Ltd. | EDL V1.0

public boolean isValid(DiagnosticChain diagnostics, Map<Object, Object> context){// TODO: implement this method// -> specify the condition that violates the invariant// -> verify the details of the diagnostic, including severity and message// Ensure that you remove @generated or mark it @generated NOTif (false){if (diagnostics != null){diagnostics.add(new BasicDiagnostic(Diagnostic.ERROR,TreeValidator.DIAGNOSTIC_SOURCE,TreeValidator.NODE__IS_VALID,EcorePlugin.INSTANCE.getString("_UI_GenericInvariant_diagnostic", new Object[] { "isValid", EObjectValidator.getObjectLabel(this, context) }),

new Object [] { this }));}return false;

}return true;

}

Page 123: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Checking for Constraint Violations

Thursday, November 13, 2008 123© Macro Modeling Ltd. | EDL V1.0

public boolean isValid(DiagnosticChain diagnostics, Map<Object, Object> context){// The root must have a labelif (getKind() == NodeKind.ROOT && getLabel() == null)// ...

public boolean validateLabel_WellFormed(String label, DiagnosticChain diagnostics, Map<Object, Object> context){// The empty string is not allowedif (label != null && label.length() == 0)// ...

TreeFactory tree = TreeFactory.eINSTANCE;Node root = tree.createNode();Node a = tree.createNode();root.getChildren().add(a);a.setLabel("");Diagnostic diagnostic = Diagnostician.INSTANCE.validate(root);if (diagnostic.getSeverity() > Diagnostic.OK){

for (Diagnostic child : diagnostic.getChildren()){

System.err.println(child.getMessage());}

}

The 'isValid' invariant is violated on 'org.example.tree.impl.NodeImpl@165a165a{#//}'The feature 'label' of 'org.example.tree.impl.NodeImpl@16661666{#///@children.0}' contains a bad value

Page 124: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• EMF provides support for maps in the form of EMap– A multi-valued containment list of objects that are map entries

• The key of an entry cannot change once the demand created map is created

– A map view is supported

EMap

Thursday, November 13, 2008 124© Macro Modeling Ltd. | EDL V1.0

public interface EMap<K, V> extends EList<Map.Entry<K, V>>{

V get(Object key);V put(K key, V value);void putAll(Map<? extends K, ? extends V> map);void putAll(EMap<? extends K, ? extends V> map);int indexOfKey(Object key);boolean containsKey(Object key);boolean containsValue(Object value);V removeKey(Object key);Map<K, V> map();Set<Map.Entry<K, V>> entrySet();Set<K> keySet();Collection<V> values();

}

Page 125: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• A modeled map is effectively just a containment list for which the referenced EClass wraps the Map.Entry API

– The key of an entry cannot change once the map is hashed

Ecore EMap

Thursday, November 13, 2008 125© Macro Modeling Ltd. | EDL V1.0

Page 126: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• An Ecore model can be defined directly using Java– The things that correspond to parts of the model are marked with

@model annotations– Information that’s missing from Java but needed in the model is

specified in the body of the @model annotation

Defining a Model With Annotated Java

Thursday, November 13, 2008 126© Macro Modeling Ltd. | EDL V1.0

/**

* @model*/

public interface Node{/**

* @model*/

String getLabel();

/**

* @model containment="true"*/

List<Node> getChildren();}

Page 127: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• An Ecore model can be defined directly in Java– Information that’s missing from schema but needed in the model is

specified using Ecore namespace annotations

Defining a Model with XML Schema

Thursday, November 13, 2008 127© Macro Modeling Ltd. | EDL V1.0

<?xml version="1.0" encoding="UTF-8"?><xsd:schema

xmlns:xsd="http://www.w3.org/2001/XMLSchema"xmlns:ecore="http://www.eclipse.org/emf/2002/Ecore"xmlns:tree="http://www.example.com/tree"ecore:nsPrefix="tree"ecore:package="com.example.tree"targetNamespace="http://www.example.com/tree">

<xsd:element name="tree" type="tree:Node"/><xsd:complexType name="Node">

<xsd:sequence><xsd:element ecore:opposite="parent"

maxOccurs="unbounded" minOccurs="0" name="children" type="tree:Node"/></xsd:sequence><xsd:attribute name="label" type="xsd:string"/><xsd:attribute ecore:reference="xsd:anyType" name="data" type="xsd:anyURI"/>

</xsd:complexType></xsd:schema>

Page 128: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Mapping XML Schema to Ecore

Thursday, November 13, 2008 128© Macro Modeling Ltd. | EDL V1.0

<?xml version="1.0" encoding="UTF-8"?><xsd:schema

xmlns:xsd="http://www.w3.org/2001/XMLSchema"xmlns:ecore="http://www.eclipse.org/emf/2002/Ecore"xmlns:tree="http://www.example.com/tree"ecore:nsPrefix="tree"ecore:package="com.example.tree"targetNamespace="http://www.example.com/tree">

<xsd:element name="tree" type="tree:Node"/><xsd:complexType name="Node">

<xsd:sequence><xsd:element ecore:opposite="parent"

maxOccurs="unbounded" minOccurs="0" name="children" type="tree:Node"/>

</xsd:sequence><xsd:attribute name="label" type="xsd:string"/><xsd:attribute ecore:reference="xsd:anyType"

name="data" type="xsd:anyURI"/></xsd:complexType>

</xsd:schema>

Page 129: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• The document root is a special EClass– It’s used only at the root of a resource– Only one of it’s containment features, corresponding to a

global element declaration may be populated• The feature’s XML name determines the root element

– It has a feature for manipulating the XML namespace declarations of the instance

– It has a feature for manipulating the XML Schema Instance declarations of the instance

Document Root

Thursday, November 13, 2008 129© Macro Modeling Ltd. | EDL V1.0

Page 130: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• Information that’s needed to produce a valid serialization but is not directly available in Ecore is recorded with extended metadata annotations– E.g., an XML identifier allows more characters than does

an Ecore identifier so even those need to be recorded• Constructs such as mixed content, substitution

groups, wildcards, and complex particle structure give rise to FeatureMaps

• A model generated from XML Schema must use the generated resource factory in order to produce a conforming serialization

Extended Meta Data

Thursday, November 13, 2008 130© Macro Modeling Ltd. | EDL V1.0

Page 131: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• A feature map is a list of entries representing feature/value pairs

– The entry’s value must be of the feature’s type– An entry is immutable

• The methods in FeatureMapUtil will come in handy for manipulating feature map content

– When possible, it’s best to avoid the constructs that lead to these

Feature Map

Thursday, November 13, 2008 131© Macro Modeling Ltd. | EDL V1.0

public interface FeatureMap extends EList<FeatureMap.Entry>{interface Entry{

EStructuralFeature getEStructuralFeature();Object getValue();// ...

}// ...

}

Page 132: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• A structural feature can be declared to be unsettable– This specifies that there is one additional state

distinguishable from all other states representing the state of not being set

– A feature in this state will return the default value for the feature

– For single valued features, isSetX and unsetX accessorswill be generated

– EObject’s eIsSet/eUnset inspect and update this state• Normally, they’d just test whether the current value is

the default value and set the value to this default

Unsettable Features

Thursday, November 13, 2008 132© Macro Modeling Ltd. | EDL V1.0

Page 133: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• EcoreUtil supports copying objects or collections of objects– It’s implemented using a Copier

• A Copier is a map from original object to its copy• The Copier can be specialized to tailor the copying behavior

– A bidirectional reference will be copied only if both ends of the reference are part of the copy

• This avoids being original objects affected by the copy

Copy

Thursday, November 13, 2008 133© Macro Modeling Ltd. | EDL V1.0

public static EObject copy(EObject eObject){

Copier copier = new Copier();EObject result = copier.copy(eObject);copier.copyReferences();return result;

}

public static <T> Collection<T> copyAll(Collection<? extends T> eObjects){

Copier copier = new Copier();EObject result = copier.copyAll(eObject);// ...

}

public static class Copier extends HashMap<EObject, EObject>

{// ...

}

Page 134: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• EcoreUtil supports testing two EObjects for structural equality– It’s implemented using an EqualityHelper

• An equality helper is a map from each object in the first tree to it’s equivalent in the second tree

• The equality helper can be specialized to tailor the behavior

Structural Equality

Thursday, November 13, 2008 134© Macro Modeling Ltd. | EDL V1.0

public static boolean equals(EObject eObject1, EObject eObject2){

EqualityHelper equalityHelper = new EqualityHelper();return equalityHelper.equals(eObject1, eObject2);

}

public static class EqualityHelper extends HashMap<EObject, EObject>{// ...

}

Page 135: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• InternalEObject supports the creation of Settings– A setting is just an object/feature pair that supports all the

reflective accessors supported directly by EObject

Settings

Thursday, November 13, 2008 135© Macro Modeling Ltd. | EDL V1.0

public interface InternalEObject extends EObject{

EStructuralFeature.Setting eSetting(EStructuralFeature feature);// ...

}

public interface EStructuralFeature{

interface Setting{

EObject getEObject();EStructuralFeature getEStructuralFeature();Object get(boolean resolve);void set(Object newValue);boolean isSet();void unset();

}}

Page 136: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• EcoreUtil provides CrossReferencers for indexing instances– A CrossReferencer is a map from an EObject to a

collection of Settings that contain references to it– Specialized references are provided to support

• Finding all external references• Finding all proxies without resolving them• Finding all unresolved proxies• Finding all uses of all objects

Cross Referencing

Thursday, November 13, 2008 136© Macro Modeling Ltd. | EDL V1.0

public static class CrossReferencerextends HashMap<EObject, Collection<EStructuralFeature.Setting>>

{// ...

}

Page 137: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• An EContentAdapter can be attached to any ResourceSet, Resource, or EObject

– Not only does it receive notification from that object, it attaches itself to all objects in the containment tree and hence receives notifications from all objects in the tree

– As new objects are attached to the containment tree, the content adapter attaches itself to those objects and their descendents

– As objects are detached from the containment tree, the content adapter removes itself from those objects and their descendents

Adapting all Objects in a Tree

Thursday, November 13, 2008 137© Macro Modeling Ltd. | EDL V1.0

resourceSet.eAdapters().add(new EContentAdapter(){

@Overridepublic void notifyChanged(Notification notification){

super.notifyChanged(notification);// Process notificationsfrom any objectin the tree

}});

Page 138: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• An ECrossAdapter can be attached to any ResourceSet, Resource, or EObject

– Not only does it receive notification from that object, it attaches itself to all objects in the containment tree and hence receives notifications from all objects in the tree

– As new objects are attached to the containment tree, the content adapter attaches itself to those objects and their descendents and stays attached

– It maintains a cross referencer that tracks the usage of all objects referenced via unidirectional cross references

Tracking all Non-navigable Inverses

Thursday, November 13, 2008 138© Macro Modeling Ltd. | EDL V1.0

public class ECrossReferenceAdapter implements Adapter.Internal{public Collection<EStructuralFeature.Setting> getNonNavigableInverseReferences(EObject eObject);

public Collection<EStructuralFeature.Setting> getNonNavigableInverseReferences(EObject eObject, boolean resolve);

// ...}

Page 139: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• A ChangeRecorder is a specialized adapter– It attaches itself to all objects in the containment tree

• Keeps track of the original value of each feature– When required, it can produce a ChangeDescription

• A reverse delta that describes how to get from the current state to the original state

• The apply or applyAndReverse methods can be used to undo a change

– by reversing it there is support for undo/redo

– EMF Edit’s Change Recording command uses it

• A ChangeDescription can be saved and loaded

Change Recording

Thursday, November 13, 2008 139© Macro Modeling Ltd. | EDL V1.0

Page 140: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Change Model

Thursday, November 13, 2008 140© Macro Modeling Ltd. | EDL V1.0

Page 141: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• A change recorder can be used to implement a transaction with rollback

Change Recording as a Transaction

Thursday, November 13, 2008 141© Macro Modeling Ltd. | EDL V1.0

ChangeRecord changeRecorder = new ChangeRecorder(resourceSet);try{

// Do stuff with anything in the resource set}catch (Exception exception){// Undo it if there’s a problem//changeRecorder.endRecording().apply();

}

Page 142: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• Platform neutral and runs stand alone• Item providers

– Platform independent interfaces for viewing objects– Default adapters that implement these interfaces– A fully reflective adapter implementation that works for any EObject– Item providers for ResourceSet and Resource– A Tree model along with its item providers

• Editing domain– A context in which editing occurs– Command creation is generally delegated to item providers– Extends the EMF Common command framework primitives– Generic undoable commands that work reflectively for any EObject

• Extension points– Registered item providers– Registered child creation extenders

EMF Edit

Thursday, November 13, 2008 142© Macro Modeling Ltd. | EDL V1.0

Page 143: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Generated Edit Project Artifacts

Thursday, November 13, 2008 143© Macro Modeling Ltd. | EDL V1.0

package org.example.tree.provider;// ...

public final class TreeEditPluginextends EMFPlugin

{// ...

}

Page 144: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Generated Item Provider Adapter Factory

Thursday, November 13, 2008 144© Macro Modeling Ltd. | EDL V1.0

package org.example.tree.provider;// ...

public class TreeItemProviderAdapterFactoryextends TreeAdapterFactoryimplements

ComposeableAdapterFactory, IChangeNotifier, IDisposable

{// ...

}

Page 145: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Generated Item Provider

Thursday, November 13, 2008 145© Macro Modeling Ltd. | EDL V1.0

public class TreeItemProviderAdapterFactory // ... {

protected NodeItemProvider nodeItemProvider;public Adapter createNodeAdapter(){

if (nodeItemProvider == null){

nodeItemProvider = new NodeItemProvider(this);}

return nodeItemProvider;}

// ...}

package org.example.tree.provider;// ...

public class NodeItemProviderextends ItemProviderAdapterimplements

IEditingDomainItemProvider,IStructuredItemContentProvider,ITreeItemContentProvider,IItemLabelProvider,IItemPropertySource

{// ...

}

Page 146: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Generated Item Provider Label

Thursday, November 13, 2008 146© Macro Modeling Ltd. | EDL V1.0

public class NodeItemProvider // ...

{

protected void addLabelPropertyDescriptor(Object object){

itemPropertyDescriptors.add(createItemPropertyDescriptor

(// ...TreePackage.Literals.NODE__LABEL,// ...

}

public String getText(Object object){

String label = ((Node)object).getLabel();// ...

}

public void notifyChanged(Notification notification){

//...

switch (notification.getFeatureID(Node.class)){

case TreePackage.NODE__LABEL:fireNotifyChanged(/**/);

//...}

}

// ...}

Page 147: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Generated Item Provider Children

Thursday, November 13, 2008 147© Macro Modeling Ltd. | EDL V1.0

public class NodeItemProvider // ...

{

public Collection<? extends EStructuralFeature> getChildrenFeatures(Object object)

{

if (childrenFeatures == null){

super.getChildrenFeatures(object);childrenFeatures.add(TreePackage.Literals.NODE__CHILDREN);

}

return childrenFeatures;}

protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object)

{// ...

newChildDescriptors.add(createChildParameter

(TreePackage.Literals.NODE__CHILDREN,TreeFactory.eINSTANCE.createNode()));

}

public void notifyChanged(Notification notification){//...

switch (notification.getFeatureID(Node.class)){

case TreePackage.NODE__CHILDREN:fireNotifyChanged(/**/);

//...}

}

// ...}

Page 148: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Generated Editor Project Artifacts

Thursday, November 13, 2008 148© Macro Modeling Ltd. | EDL V1.0

package org.example.tree.presentation;// ...

public final class TreeEditorPluginextends EMFPlugin

{// ...

}

Page 149: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Generated Editor and Action Bar Contributor

Thursday, November 13, 2008 149© Macro Modeling Ltd. | EDL V1.0

package org.example.tree.presentation;// ...

public class TreeActionBarContributorextends EditingDomainActionBarContributorimplements ISelectionChangedListener

{// ...

}

package org.example.tree.presentation;// ...

public class TreeEditorextends MultiPageEditorPartimplements

IEditingDomainProvider, ISelectionProvider, IMenuListener, IViewerProvider, IGotoMarker

{// ...

}

Page 150: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Generated Wizard

Thursday, November 13, 2008 150© Macro Modeling Ltd. | EDL V1.0

package org.example.tree.presentation;// ...

public class TreeModelWizardextends Wizard implements INewWizard

{// ...

}

Page 151: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Generated Test Project Artifacts

Thursday, November 13, 2008 151© Macro Modeling Ltd. | EDL V1.0

package org.example.tree.tests;// ...

public class TreeAllTestsextends TestSuite

{// ...

}

Page 152: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Generated Package Test Suite and Example

Thursday, November 13, 2008 152© Macro Modeling Ltd. | EDL V1.0

package org.example.tree.tests;// ...

public class TreeTestsextends TestSuite

{// ...

}

package org.example.tree.tests;// ...

public class TreeExample{// ...

}

Page 153: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

Generated Test Case

Thursday, November 13, 2008 153© Macro Modeling Ltd. | EDL V1.0

package org.example.tree.tests;// ...

public class NodeTestextends TestCase

{// ...

}

Page 154: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• Dynamic JET templates can be used to specialize what’s generated

– Import the org.eclipse.emf.codegen.ecore plugin into the workspace specifying you want it represented as source

– Copy the templates folder into some other project– Delete the org.eclipse.emf.codegen.ecore plugin again– In the GenModel

• Set the Dynamic Templates property to true• Use the Template Directory property specify the location

where you put the templates, e.g., /project-name/templates– If you have problems generating, turn off the

Navigator/Explorer filter that hides .* resources• Look for problems in the .JETEmitters project

– It contains the compiled templates– You can delete this project because it will be regenerated the

next time you generate.

Dynamic Templates

Thursday, November 13, 2008 154© Macro Modeling Ltd. | EDL V1.0

Page 155: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• EMF the defacto standard reference implementation• EMF is a low cost modeling solution for Java

– SD Times ranks it “top shelf” even relative to pricey commercial software

• http://www.sdtimes.com/content/article.aspx?ArticleID=32287

• It exploits the models already underlying the application• It supports iterative development that facilitates both

model-based changes and hand-written changes equally well

• It boosts productivity by automating routine and mundane development tasks

• It’s the foundation for data integration by providing a uniform way to access all models

Summary

Thursday, November 13, 2008 155© Macro Modeling Ltd. | EDL V1.0

Page 156: Introduction to the Eclipse Modeling Framework - TechJavamdsd08.techjava.de/emftutorial31.pdf · –Rebrand as the Eclipse Modeling Framework –Feedback to OMG resulting in Essential

• Online help– http://help.eclipse.org/ganymede/index.jsp?nav=/14

• Website– http://www.eclipse.org/emf

• Downloads• Wiki• FAQ• Newsgroup• Documentation

• Books– Eclipse Modeling Framework

• First Edition– http://safari.awprofessional.com/0131425420

• Second Edition– http://my.safaribooksonline.com/9780321331885

Resources

Thursday, November 13, 2008 156© Macro Modeling Ltd. | EDL V1.0