Model Transformations "Rien ne se perd, rien ne se crée, tout se transforme." Antoine-Laurent de...

Post on 30-Dec-2015

220 views 0 download

Transcript of Model Transformations "Rien ne se perd, rien ne se crée, tout se transforme." Antoine-Laurent de...

ModelModel TransformationsTransformations"Rien ne se perd, rien ne se crée, tout se transforme.""Rien ne se perd, rien ne se crée, tout se transforme."

Antoine-Laurent de Lavoisier (1743-1794)Antoine-Laurent de Lavoisier (1743-1794)

Marcellus TavaresRicardo Roberto de Lima

OutlineOutline

What is model General idea of model transformations Classification of model transformations Transformation techniques Comparison Conclusion References

Raising the level of abstractionRaising the level of abstraction

An Introduction to Model An Introduction to Model TransformationsTransformations

Model as key artifact of MDA Model transformations as central operation Model transformations are also modeled

The Model-Driven ArchitectureThe Model-Driven Architecture

Metamodel is defined by its metametamodel Metametamodel introduce semantics required to specify

metamodels Metametamodel is self defined

Its specified in term of its own semantics MOF e Ecore

The Model-Driven ArchitectureThe Model-Driven Architecture

Model TransformationsModel Transformations

Specify the way to produce target models from a number source models

Developers define the way source model elements must be matched and navigated in order to initialize the target models

A model transformation is a mapping of a set of models onto another set of models or onto themselves, where a mapping defines correspondences between elements in the source and target models

Caplat and Sourrouille

Model TransformationModel Transformation

ModelTransformation

Engine

ModelTransformation

Meta-model

ModelTransformations

Rules

PSMMeta-model

PSM

PIMMeta-model

PIM

MOF Meta-Meta-model

Model Transformation OntologyModel Transformation Ontology

Model Transformation

MonolithicTransformation

CompositionalTransformation

complete, disjoint

VerticalTransformation

HorizontalTransformation

complete, disjoint

EndogenousTransformation

ExogenousTransformation

complete, disjoint

DeclarativeTransformation

ImperativeTransformation

complete, disjoint

ViatraGReATOptimalJ

ForaQVTATL

Generalpurpose programming language

JETAndroMDA

QVTATL

QVTATL

MMa=MMb Mma!=MMb

Model Transformation OntologyModel Transformation Ontology

Vertical High-level to low-level representation Model refinement PIM to PSM

Horizontal Does not preserve source model structure Endogen transformation Refactoring, Update

Transformations categoriesTransformations categories

Model-to-codeVisitor-Based

Visitor mechanism to transverse model and write code

Jamda (OO FW providing set of classes to represent UML Models and a visitor mechanism “code writers”)

Template-basedJET, AndroMDA, OptimalJ

Transformations categoriesTransformations categories

Model-to-modelTranslate between source and target modelsMost existing MDA tools do not provide

Direct-Manipulation Approach (imperative)Internal model representation + APIOO frameworkTransformations rules implemented from

scratch Java

Transformations categoriesTransformations categories

Relational approach (declarative)Source and target as a relationLogic programming (predicates used to

describe relations)Flora

Hybrid approachCombine different techniques QVT, ATL

OthersXSLT

Desirable properties of a transformation Desirable properties of a transformation languagelanguage

Be executable; Be implementable in an efficient way; Be fully expressive, yet unambiguous. Facilitate developer productivity with precise,

concise and clear descriptions: Provide a means to combine transformations to form

composite ones [reuse] Provide a means to define scheduling Defined upon a Metamodel

General purpose General purpose programming languagesprogramming languages

Java, C++, C# Available via APIs,

however rules are implemented from scratch Advantage: No overhead to learn a new language Example: Java + EMF SDK

Book To Publication considering the Book To Publication considering the UML 2.0 metamodelUML 2.0 metamodel

Example Java + EMF SDKExample Java + EMF SDK

Metamodel using Ecore API provided by EMF Code Generation Model exported to XMI myBook.xmi

<?xml version="1.0" encoding="ASCII"?><xmi:XMI xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI" xmlns:book="http://book.ecore"> <book:Book title=“Java"/> <book:Chapter numPages=“10" title="Basic" author="Deitel"/> <book:Chapter numPages=“15" title="Advanced" author="Jose"/></xmi:XMI>

Example Java + EMF SDKExample Java + EMF SDK

public class JavaTransformation {

public static void main(String[] args) { // Create a resource set. ResourceSet resourceSet = new ResourceSetImpl();

// Register the default resource factory resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put( Resource.Factory.Registry.DEFAULT_EXTENSION, new XMIResourceFactoryImpl()); // Register the package -- only needed for stand-alone! BookPackage bookPackage = BookPackage.eINSTANCE; // Source model URI fileURI = URI.createFileURI(new File("mybook.xmi").getAbsolutePath()); // Get the resource Resource resource = resourceSet.getResource(fileURI, true); TreeIterator<EObject> treeIterator= resource.getAllContents(); PublicationFactory factory = PublicationFactory.eINSTANCE; Publication publication = factory.createPublication();

Example Java + EMF SDKExample Java + EMF SDK

String authors = null; while(treeIterator.hasNext()){

EObject object = treeIterator.next(); if (object instanceof Book){

publication.setTitle(((Book) object).getTitle()); } else {

String tmp = ((Chapter) object).getAuthor(); authors = publication.getAuthors(); if (authors != null){

authors = authors + "," + tmp; } else {

authors = tmp; } publication.setAuthors(authors); publication.setNbPages(

((Chapter) object).getNumPages() + publication.getNbPages()); }

}

Example Java + EMF SDKExample Java + EMF SDK

resourceSet = new ResourceSetImpl();

resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put( Resource.Factory.Registry.DEFAULT_EXTENSION, new XMIResourceFactoryImpl());

fileURI = URI.createFileURI(new File("mypublication.xmi").getAbsolutePath());

// Create a resource for this file. resource = resourceSet.createResource(fileURI);

// Add the publication objects to the contents. resource.getContents().add(publication);

// Save the contents of the resource to the file system. try {

resource.save(Collections.EMPTY_MAP); } catch (IOException e) {} }

} // end of class

Example Java + EMF SDKExample Java + EMF SDK

Generated Model myPublication.xmi

<?xml version="1.0" encoding="ASCII"?>

<publication:Publication xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI" xmlns:publication="http:///publication.ecore" title="Java" nbPages=“25" authors="Deitel,Jose"/>

Flora (F-Logic) Flora (F-Logic) IntroductionIntroduction

Flora-2 is a sophisticated object-oriented knowledge base language and application development platform.

FF-LLogic tRARAnslator Realizes the vision of logic-based KR with frames, meta, and

side-efects. Founded on F-logic HiLog Transaction Logic

Practical & usable KR and programming environment Declarative Object-oriented Logic-programming style Overcomes most of the usability problems with Prolog

Flora (F-Logic) Flora (F-Logic)

Implements Structural and Behavioural Inheritance with support for Single-source Multiple Inheritance

Flora is an implementation for F-logic over XSB Prolog Frame Logic is an object oriented deductive database

language Syntactical integration between Object Oriented Paradigm

and Rules Combines expressivity and declarative semantics to object

oriented concepts.

Flora - MetaModelFlora - MetaModel

Sequential Transaction Frame Logic Programming

Sequential Transaction Logic Programming

Frame Logic Programming

General Logic Programming

Hilog Logic Programming

Definit Logic Programming

Flora - MetaModelFlora - MetaModel

DLP Package

Flora - MetaModelFlora - MetaModel

DLP::Core

Flora - MetaModelFlora - MetaModel

criminal(X) :- american(X), sellsWeaponsTo(X,cuba).american(X) :- bornIn(X,usa).bornIn(west, usa).

Program

Exemple:

Flora - MetaModelFlora - MetaModel

criminal(X) :- american(X), sellsWeaponsTo(X,cuba).american(X) :- bornIn(X,usa).bornIn(west, usa).

ClauseExemple:

Flora - MetaModelFlora - MetaModel

criminal(X) :- american(X), sellsWeaponsTo(X,cuba).american(X) :- bornIn(X,usa).bornIn(west, usa).

LogicalPredicativeAtomExemple:

Flora - MetaModelFlora - MetaModel

criminal(X) :- american(X), sellsWeaponsTo(X,cuba).american(X) :- bornIn(X,usa).bornIn(west, usa).

QueryExemple:

Flora - MetaModelFlora - MetaModel

criminal(X) :- american(X), sellsWeaponsTo(X,cuba).american(X) :- bornIn(X,usa).bornIn(west, usa).

OperatorExemple:

Flora - MetaModelFlora - MetaModel

DLP::Operations

a :- b , c.

Flora - MetaModelFlora - MetaModel

DLP::Operations

a :- b ; c.

Flora - MetaModelFlora - MetaModel

DLP::Atom

ff(a,b)g(A,2)

Flora - MetaModelFlora - MetaModel

DLP::Terms

2x2.78“teste”f(“teste”)

Flora - MetaModelFlora - MetaModel

GLP::Operators

solteiro(P) :- homem(P), not casado(P).

Flora - MetaModelFlora - MetaModel

HLP::Atom

fecho(R)(X,Y) :- R(X,Y).fecho(R)(X,Y) :- R(X,Z), fecho(R)(Z,Y).

Flora - MetaModelFlora - MetaModel

STLP::Atom

Flora - MetaModelFlora - MetaModel

STLP::Operators

newRule :- insert{p(X, Y) :- q(Y,Z)}, delete{p(2)}.

LogicalBacktrackableUpdateAtom

Flora - MetaModelFlora - MetaModel

FLP::PathExpression

Flora - MetaModelFlora - MetaModel

FLP::Atom

F-Logic OO ConceptsF-Logic OO Concepts

F-Logic

X::Y

X:Y

C[M->V]

C[M->>V]

C[M=>V]

C[M=>>V]

C[M*->V]

C[M*->>V]

C[M*=>V]

C[M*=>>V]

Taxonomic F-Atom

SignatureSpecification

ValueSpecification

Multiplicity: multi

Multiplicity: single

Inheritable

Non-Inheritable

Flora - MetaModelFlora - MetaModel

F-Logic OO ConceptsF-Logic OO Concepts

X:aposentado :- X[idade->I], I>65.

mary[spouse->john].

mary[spouse->joe].

john[son*->>frank].

Flora - MetaModelFlora - MetaModel

Definição de hierarquia de classes (SubclassFAtom) cachorro :: mamifero, jacare :: reptil mamifero :: animal, reptil :: animal

Definição de relações entre objetos/classes (InstanceFAtom): cao1 : cachorro, jacare1 : jacare

Definição de valores de atributos e métodos (AttributeValueSpecification / MethodValueSpecification): cao1[qtdPatas -> 4], joao[salario(2005)->1200]

Definição dos valores e tipos herdáveis para atributos e métodos de classes (AttributeValueSpecification / MethodValueSpecification – inheritable = true): cachorro[qtdPatas *-> 4], empregado[salario(2005)*->1200]

Definição de valores de atributos e métodos (AttributeValueSpecification / MethodValueSpecification): cao1[qtdPatas -> 4], joao[salario(2005)->1200]

Tipos de F-Atoms

Transformation ExampleTransformation Example

FloraFlora

Exemplo:

Livro[Titulo => string, capitulos =>> Capitulo[Numpaginas => integer, Titulo => string, Autor => string]].

Publicacao[Titulo => string, Numpaginas => integer, Autores =>> string].

P:Publicacao[Titulo -> T, Numpaginas -> N, Autores -> As] :- L:Livro[Titulo -> T, capitulos ->> C], N = sum{M|C[Numpaginas -> M]}, As = collectset{A|C[Autor -> A]}.

Livro2Publicacao :- L:Livro[Titulo -> T, capitulos ->> C], N = sum{M|C[Numpaginas -> M]}, As = collectset{A|C[Autor -> A], Ltinsert{Publicacao[Titulo -> T, Numpaginas -> N, Autores -> As]}.

XSLTXSLT

eXtensible Stylesheet Language Transformation (XSLT) Language (XML) for creation of documents that contains

rules for processing XML documents. Documents written in XSLT are called leaves of styles and contain:

Element XSLT: <template>, <if>, <foreach>, … Expression XPath us to find the tree-source Text or XML to be generated in the document-result.

XSLTXSLT

XSLT – How?XSLT – How?

In the process of transformation, XSLT uses XPath to define parts of the document of origin which combine with one or more moulds.

When a combination is found, XSLT transform the combinante part of the document of origin in the outcome document of.

Parts of the document of origin that do not match a template will remain unchanged in the outcome document.

XSLT – TransformationsXSLT – Transformations

XMLDocument 1

XMLSDocument 1

Valid

XSLTDocument

XSLTEngine

SourceSchema

FragmentMatchingPatterns

XMLDocument 2

XMLSDocument 2

Valid

TargetSchema

FragmentInsertion Actions

MatchedSource Fragments

Transformation process: Source document matching patterns XSLT document specifying actions that copy matched elements and

attributes from source document and assemble them in a novel way Target document matching transformations

XSLT – Example of Transformation 1/3XSLT – Example of Transformation 1/3

Consider the following document-source:<aeronave id="PTGWZ"><origem partida="08:15">Rio de Janeiro</origem><destino>Itabuna</destino></aeronave>

XSLT – Example of Transformation 2/3XSLT – Example of Transformation 2/3

The following template (part of a style sheet XSLT) can extract data from the source document.

XSLT – Example of Transformation 3/3XSLT – Example of Transformation 3/3

XSLT elements are generally used with a prefix related to its namespace: <xsl:elemento> to avoid conflicts with the document-result. After processing the result will be:

<p>A aeronave de prefixo

PTGWZ decolou

de Rio de Janeiro às

8:15

tendo como destino o aeroporto de

Itabuna.</p>

XSLT – Other example.XSLT – Other example.

Example:

<model xmlns:uml="http://www.eclipse.org/uml2/1.0.0/UML" xmlns:xmi="http://www.omg.org/XMI">

<package id="pck1" name=“library"> <class id="c1" name=“Livro"> <association aggregationType="composite" id="c1_ass1" name=“capitulos"

targetClass="c2"/> <attribute cardinality="1..1" id="c1_atr1" name=“Titulo" type="dt1"/> </class> <class id="c2" name=“Capitulo"> <attribute cardinality="1..1" id="c2_atr1" name=“Numpaginas" type="dt2"/> <attribute cardinality="1..1" id="c2_atr2" name=“Titulo" type="dt2"/> <attribute cardinality="1..1" id="c2_atr3" name=“Autor" type="dt1"/> <association aggregationType="none" id="c2_ass1" name=“Livro"

targetClass="c1"/> </class> </package></model>

Source file: livro.xmi

XSLT – Other Example.XSLT – Other Example.

Example:

<?xml version="1.0" encoding="UTF-8"?><xsl:transform version="1.0"

xmlns:xsl="http://www.w3.org/1999/XSL/Transform" > <xsl:output method="xml" /> <xsl:template match=“publicacao.Livro" > <xsl:variable name=“Titulo" select="@Titulo" /> <xsl:variable name=“Autores" select="concat(@capitulos.autor, ',')"/> <xsl:variable name=“Numpaginas" select="sum(@capitulos.Numpaginas)"/>

<xsl:call-template name="createPublication"> <xsl:with-param name=“Titulo" select="$Titulo"/> <xsl:with-param name=“Autores" select="$Autores"/> < xsl:with-param name=“Numpaginas" select="$Numpaginas"/> </xsl:call-template> </xsl:template></xsl:transform>

Source file: Livro2Publicacao.xslt

XSLT – Other example.XSLT – Other example.

Example:

<model xmlns:uml="http://www.eclipse.org/uml2/1.0.0/UML" xmlns:xmi="http://www.omg.org/XMI">

<package id="pck1" name=“library"> <class id="c1" name=“Publicação"> <attribute cardinality="1..1" id="c1_atr1" name=“Titulo" type="dt1"/> <attribute cardinality="1..1" id="c1_atr2" name=“Numpaginas"

type="dt2"/> <attribute cardinality="1..1" id="c1_atr3" name=“Autores"

type="dt1"/> </class> <datatype id="dt1" name="String"/> <datatype id="dt2" name="Integer"/> </package></model>

Source file: Publicacao.xmi

QVTQVT

Standard for model transformation proposed by OMG RFP issued by OMG on MOF Query/Views/Transformations Key ideas

Source and target models conform to MOF metamodels. Transformation program as a model

Hybrid nature Two level declarative model

QVT OverviewQVT Overview

Core Pattern matching over a flat set of variables Defined using minimal extensions to EMOF and OCL Fine grained (one mapped identity per rule) Simple transformation language

Relations Object pattern matching and object template creation Coarse grained (many mapped identities per rule) Specification of relations over model elements

Operational Procedural definition Extends Relations language with imperative constructs Two mechanisms for invoking imperative implementations

Operational Mapping (standard) Black box MOF Operations implementations

Relationship between Relations and CoreRelationship between Relations and Core

Core is a small extension of EMOF classes and OCL expressions manipulates trace models explicitly

Relations adds extended pattern syntax implicit trace models

Both languages have a similar evaluation semantics multi-direction execution incremental update / change propagation semantics implicit object creation and deletion

Relations is mapped (reduced) to Core to provide its full semantics

QVT - Package dependenciesQVT - Package dependencies

Relation Language – Abstract SyntaxRelation Language – Abstract Syntax

QVT – Relation LanguageQVT – Relation Language

Relation Transformation between candidate model is specified as a set of relations

that must hold

transformation umlRdbms (uml : SimpleUML, rdbms : SimpleRDBMS) { }

A relation declare constraints that must be satisfied by the elements of candidate models

Domains When Pattern Where Pattern

QVT – Relation LanguageQVT – Relation Language

Domaindistinguished typed variable that can be matched in a model

of a given model typeA domain has patterns

Set of variables and a set of constraints that model elements bound to those variables must satisfy to qualify as a valid binding of the pattern

relation PackageToSchema /* map each package to a schema */ { domain uml p:Package {name=pn}

domain rdbms s:Schema {name=pn} }

QVT – Relation LanguageQVT – Relation Language

Whenspecifies the conditions under which the

relationship needs to hold Where

specifies the condition that must be satisfied by all model elements participating in the relation

The when and where clauses may contain any arbitrary OCL expressions in addition to the relation invocation expressions.

Example QVT RelationalExample QVT Relational

QVT - Core LanguageQVT - Core Language

Transformation consists of a number of Mapping Rules.

Each Mapping Rule consists of a constellation of Patterns

Patterns consist of variables and OCL expressions. A binding of a pattern is a unique set of values for all

of its variables, for which all the OCL expressions hold

Core Language - Abstract SyntaxCore Language - Abstract Syntax

QVT – Core LanguageQVT – Core Language

Domain Has an associated model type of the transformation (model candidates)

Area Consists of two patterns

Pattern Set of variables, predicates and assignments Can be matched or enforced Can depend on each other

Guard Pattern Narrow the selection of model elements to be considered for the mapping Only used for defined a context

Bottom Pattern Defines the derivations Can have realized variables, assignments and black-box operation

Mapping One are for the trace and one for each model type Defines a relation between bottom patterns

Mapping Rule ExampleMapping Rule Example

c : Class

a : Attribute |a.class := c;

c2t : ClassTable |c2t.table = t;c2t.class = c;

t : Table

a2c : AttrColumn |a2c.owner := c2t;

a2c.attr := a;a2c.column := c;

c : Column |c.table := t;

* * *

111 1

111

Class to Table

Attribute to Column

UML RelationalUML/Rel

Bottom pattern is evaluated using the variable values of the valid binding of the guard pattern.

Core/Relational comparisonCore/Relational comparison

Aspects that have to be defined explicitly when using core language The patterns that match against, and create the instances of the

classes that are the trace objects of the transformation (e.g. the links between the transformed model elements).

Atomic sets of model elements that are created or deleted as a whole, specified in smaller patterns than commonly specified in the Relational Language.

QVT Operational – Abstract Syntax QVT Operational – Abstract Syntax

QVT - Operational LanguageQVT - Operational Language

Operational Transformations Definition of a unidirectional transformations that is expressed

imperatively Its signature defines

Models involved in transformation Entry operation for execution

QVT - Operational LanguageQVT - Operational Language

Mapping operation that implements a mapping between one or more source

model elements into one or more target model elements.

Libraries contains definitions that can be reused by transformations It may define specific types and may define operations

QVTQVT

Helper Allow writing complex navigations in a confortable way Reuse

Model Transformation expressed inModel Transformation expressed inOperational Mappings LanguageOperational Mappings Language

Overall structure of a transformation program:

metamodel 'http://www.borland.com/together/uml20';transformation BookToPublication (in InputMetamodel):

OutputMetamodel…………………………………………………………………

main () {…………………………………………………………………

}

…………………………………………………………………

…helpers……………………………………………

…mapping operations………………

…………………………………………………

Signature:Declares the identifier of the transformation

Entry point:The execution of the transformation starts here by executing the operations in the body of main.It also declares the source and target metamodels. in keywords indicate source and target model variables. The target is represented by the return of main.

Transformation elements:Transformation consists of mapping operations and helpers. They form the transformation logic.

BookToPublication Example in the BookToPublication Example in the OMG QVT SpecificationOMG QVT Specification

metamodel BOOK { class Book {title: String; composite chapters: Chapter;} class Chapter {title : String; nbPages : Integer;} }metamodel PUB { class Publication {title : String; nbPages : Integer;} }

transformation Book2Publication(in bookModel:BOOK,out pubModel:PUB)

main() { bookModel->objectOfType(Book)->map book_to_publication(); }mapping Class::book_to_publication () : Publication { title := self.title; nbPages := self.chapters->nbPages->sum();}

Java FLORA XSLT QVT

Concise + + - +/-

well-know languages - - + -

Efficient + + - -

Executable + + + -

Expressive + + + +

Metamodel + + - +

Formal semantics - + - -

Standards + - +/- +

All OO/MOF concepts + +/- +/- +

Tools + - - +/-

Comparation Table Comparation Table

Legend:+:requirement well fulfilled +/-: requirement partially, weakly, impractically fulfilled -: not fulfilled

Legend:+:requirement well fulfilled +/-: requirement partially, weakly, impractically fulfilled -: not fulfilled

ConclusionsConclusions

Model Transformations are assetsguided by sound Soft. Engineering principles

Analysis, Design, Implementation, V & V (Test), and Configuration Management (evolution)

Transformations should also be models (principles of MDE) In order to tackle complexity

ReferencesReferences

http://en.wikipedia.org/wiki/QVT http://en.wikipedia.org/wiki/XSLT http://en.wikipedia.org/wiki/VIATRA http://en.wikipedia.org/wiki/GReAT http://en.wikipedia.org/wiki/Visitor_pattern http://modelware.inria.fr http://www.modelware-ist.org (Main Repository Page \ Training) http://www.eclipse.org/gmt/EMF Czarnecki and Helsen: Classification of Model Transformation

Approaches. Shane Sendall and Wojtek Kozaczynski: Model Transformation – the

Heart and Soul of Model-Driven Software Development Anna Gerber at al: Transformation: The Missing Link of MDA QVT Specification Dariusz Gall, Michal Molenda: EDOC to EJB transformations within

MDA