SlideShare a Scribd company logo
Enrich Your Models with OCL Edward Willink,  Thales MDT/OCL Project Lead Axel Uhl,  SAP 21st March 2011
Part 1: OCL in isolation Installation Instructions OCL Basic Principles exercises OCL Collections and Iterators exercises OCL tools and usage exercises OCL in Java - analyzable language
Part 2: OCL beyond OCL State Machine Example Xtext Editor for States Model OCL document - independent validation language exercises
OCLinEcore - integrated validation language exercises Acceleo States to Java Classes transformation OCL in Acceleo - navigation/evaluation aid exercises QVTo State Flattening transformation OCL in QVT Operational - navigation/evaluation aid exercises
Tutorial Material EclipseCon Session Page http://www.eclipsecon.org/2011/sessions/?page=sessions&id=2271 link to these slides
link to a ZIP of ZIPs (only one file allowed) Individual ZIPs on USB stick and at MainWorkspaceProjects.zip (http:// www.eclipse.org /modeling/mdt/ocl/docs/publications/EclipseCon2011Tutorial/MainWorkspaceProjects.zip) RuntimeWorkspaceProjects.zip (http://www.eclipse.org/modeling/mdt/ocl/docs/publications/EclipseCon2011Tutorial/RuntimeWorkspaceProjects.zip) Import ... Existing Projects from Archive ESEExampleTree/model/People1.ecore Run nested Eclipse, Import ESEExampleTree ESEExampleTree/model/default.people_diagram
Preparation - Indigo M6 Platform Install Eclipse 3.7M6 (or M5) e.g. Download & Unzip eclipse-SDK-3.7M6-win32.zip or eclipse-modeling-indigo-M6-incubation-win32.zip known lower bounds: OCL M6, Xtext M6, EMF M5 Start Eclipse, with plenty of memory, e.g. C:\Tools\Eclipse\3.7M6EclipseCon\eclipse.exe   -data C:/EclipseCon/Workspace -vmargs -Xmx1g   -XX:PermSize=64M -XX:MaxPermSize=128M
Preparation - Indigo M6 Projects Help->Install New Software... from Indigo - http://download.eclipse.org/releases/indigo (after 18 Mar)  Indigo - http://download.eclipse.org/releases/staging (before) Modeling->Acceleo SDK
Modeling->Graphical Modeling Framework (GMF) Runtime
Modeling->OCL Examples and Editors
Modeling->Operational QVT SDK
Modeling->UML2 Extender SDK part of Modelling EPP Modeling->Xtext SDK uncheck "Contact all sites during install to find required software"
Next ... Restart Now
Preparation - Indigo M6a Updates M6a for OCL Examples optional but useful fixes for OCL
no help for adverse SWT/Modeling interaction  Help->Install New Software... from http://download.eclipse.org/modeling/mdt/ocl/updates/milestones or USB stick:  mdt-ocl-Update-3.1.0M6a.zip MDT/OCL (3.1.0-v20110320...)
Preparation - Main Workspace File->Import->General Existing Projects into Workspace
Next Select achive File: http://www.eclipse.org/modeling/mdt/ocl/docs/publications/EclipseCon2011Tutorial/MainWorkspaceProjects.zip Finish 9 projects
0 errors
98 warnings
Preparation - Runtime Eclipse Sun JVM Run->Eclipse OCL Tutorial sets VM arguments for plenty of memory, e.g. -Xms40m -Xmx512m   -XX:PermSize=64M -XX:MaxPermSize=128M Other JVM Run->Run Configurations Select Eclipse->Eclipse OCL Tutorial
Select the "Arguments" tab Set VM arguments for plenty of memory Run
Preparation - Runtime Workspace File->Import->General Existing Projects into Workspace
Next Select achive File: http://www.eclipse.org/modeling/mdt/ocl/docs/publications/EclipseCon2011Tutorial/RuntimeWorkspaceProjects.zip Finish 3 projects
2 errors
3 warnings
Models The world is full of data Models are good for controlling data EMF is good for (meta-)modeling Extended EMF even better EMF editors
Xtext editors Java is empowering What more could you want?
Rules The world is full of rules password must be at least 6 characters
password must contain only letters and numbers Models should be good for applying rules direct implementation for simple rules
semantic validation for complex rules EMF (meta-modeling) captures simple rules multiplicity, ordering, uniqueness, containment OCL supports complex rules used extensively in OMG specifications
Behaviors The world is full of behaviors things happen
changes occur EMF (and OCL) support static data models M2M supports changing/related models OCL underpins modern modeling specifications UML: state machine guards/transitions
M2M: OMG QVT, Eclipse QVTo, ATL, Epsilon
M2T: OMG MOFM2T, Eclipse Acceleo
Object Constraint Language Requirement: an expression language for models Fortran provided fundamental expression/function notation Evolution '.' operator for records/structures/objects/operations OCL extension from objects to collections of objects
Simple Meta-Modeling Graphics Box Class, enumeration Compartment Property, operation Line Association Decoration Composition, navigability Text Name, type, stereotype
Multiplicity Example Family Tree Meta-Model Ecore Diagram (similar to UML Class Diagram)
Richer Meta-Modelling Implicit constraints Up to  2 parents
MALE/FEMALE gender Arbitrary constraints At least 5 characters in name
1 MALE, 1 FEMALE parent
Self is not  an ancestor  of self
Example Family Tree Model Simple GMF Diagram Editor Runtime Workspace: ESEExampleTree/model/default.people_diagram
Simple Query Evaluation Window->Show View->Other... Console Console: New: Interactive Xtext OCL Select  Zeus  as the Model Context (in any model editor) Type  children  then carriage return
OCL Principles Natural/Formal Language compromise natural language error prone "press any key to continue", "press enter or stop" formal language unapproachable to many ∀ x ∈ y ∃ z(x) Specification (not Programming) Language declarative, modeling language
side effect free, no model changes, atomic execution
strongly typed, using UML generalization
Primitive Types and Literals Java (implementation) OCL (specification) boolean,Boolean,true,false Boolean,true,false short,int,long,Integer,BigInteger Integer , UnlimitedNatural float, double, BigDecimal Real Character, String, 'c',  " line\n " String, 'c',  ' line\n ' Object,this,null OclAny, self ,null Exception invalid Integer value value : Integer Java: practical implementation language OCL: simpler, idealistic, specification language
Mathematical Operators Java (implementation) OCL (specification) +, -, *, / +, -, *, / !, &&, ||, ^ not, and, or, xor, implies <, >, <=, >= <, >, <=, >= ==, != = , <> Math.max(4,5) 4.max(5) if  (a) b  else  c; if  a  then  b  else  c  endif Integer value = 5; doSomething(value); let  value : Integer = 5 in  doSomething(value)
More Complex Query Selecting  Hera  defines the implicit context variable self : Person =  Hera
Object Navigation Properties self.name   or just  name (cf.  this.getName()   or  getName() ) Operations self.child('John')   or just  child('John') (cf.  this.child('John')   or  child('John') )
OCL in context Pure OCL expressions academic interest OCL expressions for models useful for practice/experiment
adds values to model usage Essential OCL editor embedded in Console OCL expressions for meta-models adds value to meta-models
transforms the capabilties OCLinEcore editor
EMF Delegates (Helios) EOperations have no body genmodel: UnsupportedOperationException stub EOperation may have a special EAnnotation configures an Invocation Delegate Eclipse OCL provides OCL Invocation Delegate Similarly Validation Delegate for EClassifier invariants
Setting Delegate for EStructuralFeature initial value
Example Validation Delegate
The OCLinEcore Editor OCLinEcore editor maintains EAnnotations automatically OCLinEcore editor provides OCL syntax checking OCLinEcore editor will provide OCL semantic checking
OCLinEcore Editor Open with -> OCLinEcore
Save As *.ecore Loses formatting and comments Save As *.oclinecore Text file preserves comments Useful for plain Ecore too: Printable/reviewable text
Searchable/replaceable text
Example Validation Failure Open ESEExampleTree/model/People1.xmi in Main Eclipse, with Sample Reflective Ecore Editor Select Universe, Right button menu, Validate
Evaluator, OCLinEcore exercises In Runtime Eclipse identify parents of Zeus
determine the number of letters in Hephaestus hint: String::size() : Integer In Main Eclipse open people1.xmi inspect validation failures edit people1.ecore change name limit to at most five characters
revalidate
Multiplicities and Collections Meta-models specify multiplicities children : Person[*] {ordered,unique}
parents : Person[0..2] {unique} multiplicities are specification concepts; not objects Implementations (e.g. Ecore) reify multiplicities getName()  setName(newName) 'many' properties have extra implementation objects getChildren() returns a UniqueEList<Person>
getChildren().get(2)  getChildren().add(newChild) OCL needs more than just UML multiplicities
OCL 2.0 Collections Typed Collections partially reify multiplicities Collections are different to objects Navigation from a Collection uses  -> [Navigation from an Object (OclAny)  uses  . ] Collections have type parameters Collections have useful operations Collections have very useful iterations Collections are immutable Collection(T) Unordered Ordered Non-Unique Bag(T) Sequence(T) Unique Set(T) OrderedSet(T)
Example Collection Operations Collection::size()  self.children->size() 'get' Sequence::at(Integer)  self.children->at(1) nb  1  is the first index,  size()  is the last 'add' Collection(T)::including(T) : Collection(T) returns a new collection with added content 'contains' Collection(T)::includes(T) : Boolean tests existing content
Collection::select iteration Children self.children Sons self.children->select(gender = Gender::MALE) self.children->select(child | child.gender = Gender::MALE) self.children->select(child : Person | child.gender = Gender::MALE) select(iterator : type | body) filters to select elements for which the body is true reject(iterator : type | body) filters to reject elements for which the body is true cf multi-line Java loop
Collection::collect iteration Children self.children Grandchildren self.children->collect(children) self.children->collect(child | child.children) self.children->collect(child : Person | child.children) collect(iterator : type | body) creates a new collection comprising all the bodies any, exists, forAll, isUnique, iterate, one,
OCL Navigation Operators anObject.  ...  object navigation aCollection->  ...  collection navigation Shorthands aCollection.  ...  implicit collect anObject->  ...  implicit as set Object Collection . Navigation ? -> ? Navigation
Implicit Collect Query parents.parents = parents->collect(parents) 3 symbols, compared to 4 lines of Java 4 grandparents, but not all different!
Cleaned up query parents.parents->asSet()->sortedBy(name) ->asSet()  converts to Set(Person), removes duplicates ->sortedBy(name)  alphabeticizes
Implicit As Set Conversion self->notEmpty() Standard OCL idiom Converts  self  (if an object) to a Set of  self
If  self  is a defined object Implicit set is not empty -  true If  self  is an undefined object ( null ) Implicit set is empty -  false If  self  is an error ( invalid ) Implicit set is also an error -  invalid Object Collection . Navigation Implicit collect() -> Implicit as set Navigation
Collection::closure iteration children, grandchildren, greatgrandchildren etc self->closure(children) Implicit collection of self, then closure of all children [ closure in MDT/OCL 1.2, in OMG OCL 2.3 ]
OCL as Implementation any(x)  iteration selects an arbitrary element for which x is true.
Derived Properties For Hera invariant   MixedGenderParents:  father . gender  <>  mother . gender ; fails because father is  null  and mother is  null
Collection exercises
Other OCL Capabilities No time to mention Other iterators, operations
Tuples
Association Classes/Qualifiers
@pre values
Messages
States
OCL in Code - Java API MDT/OCL started as a Java API parsing OCL
evaluating OCL
Facade to hide internals
'Internal' API for derived language parse/evaluate  Evolution has added GUI functionality Console and Editors OCL can be much faster than Java! OCL amenable to analysis
The Re-Evaluation Problem System defined by a set of OCL expressions
System comprising a set of model elements
A model element changes ....
Which of the OCL expressions may have changed its value on which context elements?
Naïve approach re-evaluate all expressions for all their contexts
takes O(|expressions| * |modelElements|)
The Impact Analyzer Smart approach pre-evaluate all OCL expression dependencies
re-evaluate only changed model elements
only expression for which model element is changed Go to Efficient, Scalable Notification Handling for EMF (2 hours ago).
Benchmark Context Reduction (Average Case) Naive Event-Filtered (*6 Speed-Up) Event-Filtered and Context-Reduced (*1300 Speed-Up vs. Naive, *220 vs. Event-Filtered-Only) Total Re-Evaluation Time in Seconds Number of Model Elements
Benchmark Context Reduction (Worst Case) Naive Event-Filtered (*2.4 Speed-Up) Event-Filtered and Context-Reduced (*27 Speed-Up vs. Naive, *11 vs. Event-Filtered-Only) Total Re-Evaluation Time in Seconds Number of Model Elements (apply changes to very central elements, referenced by all other model packages)
State Machine Example Very simple hierarchical state machine Xtext DSL - similar to Xtext's FowlerDSL  Use OCL to add validation to Xtext Complete OCL to keep OCL independent
OCLinEcore to avoid OCL getting lost Use Acceleo and OCL to convert to Java
Use QVTo and OCL to flatten state machine
Xtext with independent OCL Main Eclipse meta-modeling Edit  states.xtext
Tailor Editor
Generate States Editor Edit  states.ocl Run-time Eclipse modeling Exit Run-time
Start Run-time
Edit  simple.states Exit Run-time
Start Run-time
Edit  simple.states with OCL validation
Simple State Machine DSL module   &quot;simple.states&quot; statemachine  Machine { events  START STOP; state  Start { STOP  => Stop } initial   state  Stop  { START => Start }  }
The Xtext States Grammar http://www.eclipse.org/modeling/mdt/ocl/docs/publications/EclipseCon2011Tutorial /org.eclipse.ocl.tutorial.eclipsecon2011.states/src/org/eclipse/ocl/tutorial/eclipsecon2011/States.xtext grammar  org.eclipse.ocl.tutorial.eclipsecon2011.States with  org.eclipse.xtext.common.Terminals generate  states  &quot;http://ocl.eclipse.org/tutorial/eclipsecon2011/States&quot; Module:  'module'  name=STRING (machines+=Statemachine)*; Statemachine:  (initial?= 'initial' )?  'statemachine'  name=ID ( 'value'  value=INT)?  '{' 'events'  (events+=Event)*  ';' (states+=State)*  '}' ; Event:  name=ID; State:  SimpleState | CompoundState; SimpleState:  (initial?= 'initial' )?  'state'  name=ID ( 'value'  value=INT)? '{'  (transitions+=Transition)*  '}' ; CompoundState:  'compound'  (initial?= 'initial' )?  'state'  name=ID 'machine'  machine=[ Statemachine ] '{'  (transitions+=Transition)*  '}' ; Transition:  event=[ Event ]  '=>'  state=[ State ];
Validation Diagnose inappropriate source text Xtext grammar validates syntax and some semantics typos:
inappropriate names:  Additional Java/Check Validator specialized validation External Complete OCL Validation
Embedded OCLinEcore Validation
External Complete OCL Validation Xtext States project src-gen/.../States.ecore auto-generated; don't want to edit it META-INF/MANIFEST.MF add dependency on org.eclipse.ocl.examples.xtext.completeocl src/.../validation/StatesJavaValidator.java generated once; can edit it Helpwanted:  validation.CompleteOCLValidatorFragment
StatesJavaValidator.java Use Java Validator to invoke Complete OCL import  org.eclipse.emf.common.util.URI; import  org.eclipse.ocl.examples.xtext.completeocl.validation.CompleteOCLEObjectValidator; import  org.eclipse.ocl.tutorial.eclipsecon2011.states.StatesPackage; import  org.eclipse.xtext.validation.EValidatorRegistrar; public   class  StatesJavaValidator  extends  AbstractStatesJavaValidator { @Override public   void  register(EValidatorRegistrar registrar) { super .register(registrar); StatesPackage ePackage = StatesPackage. eINSTANCE ; URI oclURI = URI. createPlatformResourceURI ( &quot;/org.eclipse.ocl.tutorial.eclipsecon2011.states.ocl/model/States.ocl&quot; ,  true ); registrar.register(ePackage, new  CompleteOCLEObjectValidator(ePackage, oclURI)); } }
Complete OCL Validation 1 /org.eclipse.ocl.tutorial.eclipsecon2011.states.ocl/model/States.ocl import   'http://ocl.eclipse.org/tutorial/eclipsecon2011/States' package   states context   Statemachine inv  HasInitialState( 'No initial state' ): states -> exists ( s  :  State  |  s . initial ) endpackage Evaluates:  states -> exists ( s  :  State  |  s . initial ) true => silent, invariant is satisfied false => invariant is not satisfied evaluates  'No initial state'  to determine warning diagnostic null => invariant is not satisfied evaluates  'No initial state'  to determine error diagnostic invalid => exception, evaluation failure

More Related Content

PDF
Moving OBIEE to Oracle Analytics Cloud
PPTX
Power BI: Introduction with a use case and solution
PPTX
PowerBI - Porto.Data - 20150219
PPTX
Power Bi Basics
PDF
Crafting a Winning Reporting Strategy with Oracle Cloud
PDF
Mongo DB: Operational Big Data Database
PPTX
Powerbi presentation from Microsoft Corporation
PPT
Hyperion essbase overview
Moving OBIEE to Oracle Analytics Cloud
Power BI: Introduction with a use case and solution
PowerBI - Porto.Data - 20150219
Power Bi Basics
Crafting a Winning Reporting Strategy with Oracle Cloud
Mongo DB: Operational Big Data Database
Powerbi presentation from Microsoft Corporation
Hyperion essbase overview

What's hot (17)

PPTX
Power bi overview
PPT
Speech Act Apologies
PPTX
Mainframe – CONTROL-M
PPTX
Always on in SQL Server 2012
PPTX
Bi Applications - Oracle
PPTX
Lesson 1 - Introduction to Power BI.pptx
PPT
Less07 storage
PPTX
Emv chip software Writer/Reader ( CHIPSO EMV)
PDF
Power BI - The self service BI Lifecycle in the cloud
PPTX
Power BI Made Simple
PDF
Advanced performance troubleshooting using esxtop
PDF
Discourse analysis session 8_23_11_2021 Speech acts.pdf
PDF
Oracle - Enterprise Manager 12c Overview
PDF
Flashback time travel vs Flash back Data Archive.pdf
PPTX
Translation Barriers
PPTX
JBoss Drools - Pure Java Rule Engine
PDF
power-bi-complete-guide-slides.pdf
Power bi overview
Speech Act Apologies
Mainframe – CONTROL-M
Always on in SQL Server 2012
Bi Applications - Oracle
Lesson 1 - Introduction to Power BI.pptx
Less07 storage
Emv chip software Writer/Reader ( CHIPSO EMV)
Power BI - The self service BI Lifecycle in the cloud
Power BI Made Simple
Advanced performance troubleshooting using esxtop
Discourse analysis session 8_23_11_2021 Speech acts.pdf
Oracle - Enterprise Manager 12c Overview
Flashback time travel vs Flash back Data Archive.pdf
Translation Barriers
JBoss Drools - Pure Java Rule Engine
power-bi-complete-guide-slides.pdf
Ad

Viewers also liked (20)

PPTX
OCL tutorial
PPTX
OCL in EMF
DOCX
Ocl exercises 1
ODP
Eclipse OCL Summary
PDF
Cours ocl
PPT
BEEM magnetic microscopy - Data Storage
PDF
Enriching Your Models with OCL
PDF
OCL'16 slides: Models from Code or Code as a Model?
PPTX
Progettazione Collaborativa di Scenari di Apprendimento/Insegnamento
PPT
Education 2.0: Leveraging Collaborative Tools for Teaching
PPTX
Collaborative Design of Teaching Scenarios
PDF
Automatic Support for the Analysis of Online Collaborative Learning Chat Conv...
PPTX
Online collaborative learning
PPT
Online Collaborative Learning in ELT
PPTX
Peer assessment in online collaborative learning
PPTX
From Research to Practice: The Instructional Design of Online Collaborative L...
PPT
Introduction to Google Apps For Education
PDF
You need to extend your models? EMF Facet vs. EMF Profiles
PPTX
Collaborative and cooperative learning
PPTX
Java vs .Net
OCL tutorial
OCL in EMF
Ocl exercises 1
Eclipse OCL Summary
Cours ocl
BEEM magnetic microscopy - Data Storage
Enriching Your Models with OCL
OCL'16 slides: Models from Code or Code as a Model?
Progettazione Collaborativa di Scenari di Apprendimento/Insegnamento
Education 2.0: Leveraging Collaborative Tools for Teaching
Collaborative Design of Teaching Scenarios
Automatic Support for the Analysis of Online Collaborative Learning Chat Conv...
Online collaborative learning
Online Collaborative Learning in ELT
Peer assessment in online collaborative learning
From Research to Practice: The Instructional Design of Online Collaborative L...
Introduction to Google Apps For Education
You need to extend your models? EMF Facet vs. EMF Profiles
Collaborative and cooperative learning
Java vs .Net
Ad

Similar to Enrich Your Models With OCL (20)

PDF
Erlang, an overview
PPT
PDF
55j7
PPT
Xml Java
PDF
A Survey of Concurrency Constructs
ODP
Bring the fun back to java
PDF
JDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go Wrong
PDF
Introduction to clojure
PPTX
PDF
New and improved: Coming changes to the unittest module
ODP
biopython, doctest and makefiles
PPT
Linq 1224887336792847 9
PPTX
Java history, versions, types of errors and exception, quiz
ODP
Fast, Faster and Super-Fast Queries
PPTX
ECMAScript 2015
PPTX
Eclipse Modeling Framework
PPT
Implementing the Genetic Algorithm in XSLT: PoC
PDF
Choose'10: Ralf Laemmel - Dealing Confortably with the Confusion of Tongues
ODP
Aligning OCL and UML
PDF
Java Interview Questions PDF By ScholarHat
Erlang, an overview
55j7
Xml Java
A Survey of Concurrency Constructs
Bring the fun back to java
JDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go Wrong
Introduction to clojure
New and improved: Coming changes to the unittest module
biopython, doctest and makefiles
Linq 1224887336792847 9
Java history, versions, types of errors and exception, quiz
Fast, Faster and Super-Fast Queries
ECMAScript 2015
Eclipse Modeling Framework
Implementing the Genetic Algorithm in XSLT: PoC
Choose'10: Ralf Laemmel - Dealing Confortably with the Confusion of Tongues
Aligning OCL and UML
Java Interview Questions PDF By ScholarHat

More from Edward Willink (20)

PDF
An OCL Map Type
PDF
OCL Visualization A Reality Check
PDF
OCL 2019 Keynote Retrospective and Prospective
ODP
A text model - Use your favourite M2M for M2T
ODP
Shadow Objects
ODP
Commutative Short Circuit Operators
ODP
Deterministic Lazy Mutable OCL Collections
ODP
The Micromapping Model of Computation
ODP
Optimized declarative transformation First Eclipse QVTc results
ODP
Local Optimizations in Eclipse QVTc and QVTr using the Micro-Mapping Model of...
ODP
The Importance of Opposites
ODP
OCL Specification Status
ODP
The OCLforUML Profile
ODP
At Last an OCL Debugger
ODP
QVT Traceability: What does it really mean?
ODP
Safe navigation in OCL
ODP
OCL 2.4. (... 2.5)
ODP
Embedded OCL Integration and Debugging
ODP
OCL 2.5 plans
ODP
OCL Integration and Code Generation
An OCL Map Type
OCL Visualization A Reality Check
OCL 2019 Keynote Retrospective and Prospective
A text model - Use your favourite M2M for M2T
Shadow Objects
Commutative Short Circuit Operators
Deterministic Lazy Mutable OCL Collections
The Micromapping Model of Computation
Optimized declarative transformation First Eclipse QVTc results
Local Optimizations in Eclipse QVTc and QVTr using the Micro-Mapping Model of...
The Importance of Opposites
OCL Specification Status
The OCLforUML Profile
At Last an OCL Debugger
QVT Traceability: What does it really mean?
Safe navigation in OCL
OCL 2.4. (... 2.5)
Embedded OCL Integration and Debugging
OCL 2.5 plans
OCL Integration and Code Generation

Recently uploaded (20)

PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
cloud_computing_Infrastucture_as_cloud_p
PPTX
A Presentation on Artificial Intelligence
PPTX
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
PDF
Web App vs Mobile App What Should You Build First.pdf
PDF
Mushroom cultivation and it's methods.pdf
PDF
Zenith AI: Advanced Artificial Intelligence
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
A Presentation on Touch Screen Technology
PDF
Getting Started with Data Integration: FME Form 101
PDF
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
OMC Textile Division Presentation 2021.pptx
PDF
A comparative study of natural language inference in Swahili using monolingua...
PDF
project resource management chapter-09.pdf
PDF
Hybrid model detection and classification of lung cancer
A comparative analysis of optical character recognition models for extracting...
Building Integrated photovoltaic BIPV_UPV.pdf
cloud_computing_Infrastucture_as_cloud_p
A Presentation on Artificial Intelligence
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
Web App vs Mobile App What Should You Build First.pdf
Mushroom cultivation and it's methods.pdf
Zenith AI: Advanced Artificial Intelligence
MIND Revenue Release Quarter 2 2025 Press Release
NewMind AI Weekly Chronicles - August'25-Week II
Assigned Numbers - 2025 - Bluetooth® Document
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
A Presentation on Touch Screen Technology
Getting Started with Data Integration: FME Form 101
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
Encapsulation_ Review paper, used for researhc scholars
OMC Textile Division Presentation 2021.pptx
A comparative study of natural language inference in Swahili using monolingua...
project resource management chapter-09.pdf
Hybrid model detection and classification of lung cancer

Enrich Your Models With OCL

  • 1. Enrich Your Models with OCL Edward Willink, Thales MDT/OCL Project Lead Axel Uhl, SAP 21st March 2011
  • 2. Part 1: OCL in isolation Installation Instructions OCL Basic Principles exercises OCL Collections and Iterators exercises OCL tools and usage exercises OCL in Java - analyzable language
  • 3. Part 2: OCL beyond OCL State Machine Example Xtext Editor for States Model OCL document - independent validation language exercises
  • 4. OCLinEcore - integrated validation language exercises Acceleo States to Java Classes transformation OCL in Acceleo - navigation/evaluation aid exercises QVTo State Flattening transformation OCL in QVT Operational - navigation/evaluation aid exercises
  • 5. Tutorial Material EclipseCon Session Page http://www.eclipsecon.org/2011/sessions/?page=sessions&id=2271 link to these slides
  • 6. link to a ZIP of ZIPs (only one file allowed) Individual ZIPs on USB stick and at MainWorkspaceProjects.zip (http:// www.eclipse.org /modeling/mdt/ocl/docs/publications/EclipseCon2011Tutorial/MainWorkspaceProjects.zip) RuntimeWorkspaceProjects.zip (http://www.eclipse.org/modeling/mdt/ocl/docs/publications/EclipseCon2011Tutorial/RuntimeWorkspaceProjects.zip) Import ... Existing Projects from Archive ESEExampleTree/model/People1.ecore Run nested Eclipse, Import ESEExampleTree ESEExampleTree/model/default.people_diagram
  • 7. Preparation - Indigo M6 Platform Install Eclipse 3.7M6 (or M5) e.g. Download & Unzip eclipse-SDK-3.7M6-win32.zip or eclipse-modeling-indigo-M6-incubation-win32.zip known lower bounds: OCL M6, Xtext M6, EMF M5 Start Eclipse, with plenty of memory, e.g. C:\Tools\Eclipse\3.7M6EclipseCon\eclipse.exe -data C:/EclipseCon/Workspace -vmargs -Xmx1g -XX:PermSize=64M -XX:MaxPermSize=128M
  • 8. Preparation - Indigo M6 Projects Help->Install New Software... from Indigo - http://download.eclipse.org/releases/indigo (after 18 Mar) Indigo - http://download.eclipse.org/releases/staging (before) Modeling->Acceleo SDK
  • 12. Modeling->UML2 Extender SDK part of Modelling EPP Modeling->Xtext SDK uncheck &quot;Contact all sites during install to find required software&quot;
  • 14. Preparation - Indigo M6a Updates M6a for OCL Examples optional but useful fixes for OCL
  • 15. no help for adverse SWT/Modeling interaction Help->Install New Software... from http://download.eclipse.org/modeling/mdt/ocl/updates/milestones or USB stick: mdt-ocl-Update-3.1.0M6a.zip MDT/OCL (3.1.0-v20110320...)
  • 16. Preparation - Main Workspace File->Import->General Existing Projects into Workspace
  • 17. Next Select achive File: http://www.eclipse.org/modeling/mdt/ocl/docs/publications/EclipseCon2011Tutorial/MainWorkspaceProjects.zip Finish 9 projects
  • 20. Preparation - Runtime Eclipse Sun JVM Run->Eclipse OCL Tutorial sets VM arguments for plenty of memory, e.g. -Xms40m -Xmx512m -XX:PermSize=64M -XX:MaxPermSize=128M Other JVM Run->Run Configurations Select Eclipse->Eclipse OCL Tutorial
  • 21. Select the &quot;Arguments&quot; tab Set VM arguments for plenty of memory Run
  • 22. Preparation - Runtime Workspace File->Import->General Existing Projects into Workspace
  • 23. Next Select achive File: http://www.eclipse.org/modeling/mdt/ocl/docs/publications/EclipseCon2011Tutorial/RuntimeWorkspaceProjects.zip Finish 3 projects
  • 26. Models The world is full of data Models are good for controlling data EMF is good for (meta-)modeling Extended EMF even better EMF editors
  • 27. Xtext editors Java is empowering What more could you want?
  • 28. Rules The world is full of rules password must be at least 6 characters
  • 29. password must contain only letters and numbers Models should be good for applying rules direct implementation for simple rules
  • 30. semantic validation for complex rules EMF (meta-modeling) captures simple rules multiplicity, ordering, uniqueness, containment OCL supports complex rules used extensively in OMG specifications
  • 31. Behaviors The world is full of behaviors things happen
  • 32. changes occur EMF (and OCL) support static data models M2M supports changing/related models OCL underpins modern modeling specifications UML: state machine guards/transitions
  • 33. M2M: OMG QVT, Eclipse QVTo, ATL, Epsilon
  • 34. M2T: OMG MOFM2T, Eclipse Acceleo
  • 35. Object Constraint Language Requirement: an expression language for models Fortran provided fundamental expression/function notation Evolution '.' operator for records/structures/objects/operations OCL extension from objects to collections of objects
  • 36. Simple Meta-Modeling Graphics Box Class, enumeration Compartment Property, operation Line Association Decoration Composition, navigability Text Name, type, stereotype
  • 37. Multiplicity Example Family Tree Meta-Model Ecore Diagram (similar to UML Class Diagram)
  • 38. Richer Meta-Modelling Implicit constraints Up to 2 parents
  • 39. MALE/FEMALE gender Arbitrary constraints At least 5 characters in name
  • 40. 1 MALE, 1 FEMALE parent
  • 41. Self is not an ancestor of self
  • 42. Example Family Tree Model Simple GMF Diagram Editor Runtime Workspace: ESEExampleTree/model/default.people_diagram
  • 43. Simple Query Evaluation Window->Show View->Other... Console Console: New: Interactive Xtext OCL Select Zeus as the Model Context (in any model editor) Type children then carriage return
  • 44. OCL Principles Natural/Formal Language compromise natural language error prone &quot;press any key to continue&quot;, &quot;press enter or stop&quot; formal language unapproachable to many ∀ x ∈ y ∃ z(x) Specification (not Programming) Language declarative, modeling language
  • 45. side effect free, no model changes, atomic execution
  • 46. strongly typed, using UML generalization
  • 47. Primitive Types and Literals Java (implementation) OCL (specification) boolean,Boolean,true,false Boolean,true,false short,int,long,Integer,BigInteger Integer , UnlimitedNatural float, double, BigDecimal Real Character, String, 'c', &quot; line\n &quot; String, 'c', ' line\n ' Object,this,null OclAny, self ,null Exception invalid Integer value value : Integer Java: practical implementation language OCL: simpler, idealistic, specification language
  • 48. Mathematical Operators Java (implementation) OCL (specification) +, -, *, / +, -, *, / !, &&, ||, ^ not, and, or, xor, implies <, >, <=, >= <, >, <=, >= ==, != = , <> Math.max(4,5) 4.max(5) if (a) b else c; if a then b else c endif Integer value = 5; doSomething(value); let value : Integer = 5 in doSomething(value)
  • 49. More Complex Query Selecting Hera defines the implicit context variable self : Person = Hera
  • 50. Object Navigation Properties self.name or just name (cf. this.getName() or getName() ) Operations self.child('John') or just child('John') (cf. this.child('John') or child('John') )
  • 51. OCL in context Pure OCL expressions academic interest OCL expressions for models useful for practice/experiment
  • 52. adds values to model usage Essential OCL editor embedded in Console OCL expressions for meta-models adds value to meta-models
  • 53. transforms the capabilties OCLinEcore editor
  • 54. EMF Delegates (Helios) EOperations have no body genmodel: UnsupportedOperationException stub EOperation may have a special EAnnotation configures an Invocation Delegate Eclipse OCL provides OCL Invocation Delegate Similarly Validation Delegate for EClassifier invariants
  • 55. Setting Delegate for EStructuralFeature initial value
  • 57. The OCLinEcore Editor OCLinEcore editor maintains EAnnotations automatically OCLinEcore editor provides OCL syntax checking OCLinEcore editor will provide OCL semantic checking
  • 58. OCLinEcore Editor Open with -> OCLinEcore
  • 59. Save As *.ecore Loses formatting and comments Save As *.oclinecore Text file preserves comments Useful for plain Ecore too: Printable/reviewable text
  • 61. Example Validation Failure Open ESEExampleTree/model/People1.xmi in Main Eclipse, with Sample Reflective Ecore Editor Select Universe, Right button menu, Validate
  • 62. Evaluator, OCLinEcore exercises In Runtime Eclipse identify parents of Zeus
  • 63. determine the number of letters in Hephaestus hint: String::size() : Integer In Main Eclipse open people1.xmi inspect validation failures edit people1.ecore change name limit to at most five characters
  • 65. Multiplicities and Collections Meta-models specify multiplicities children : Person[*] {ordered,unique}
  • 66. parents : Person[0..2] {unique} multiplicities are specification concepts; not objects Implementations (e.g. Ecore) reify multiplicities getName() setName(newName) 'many' properties have extra implementation objects getChildren() returns a UniqueEList<Person>
  • 67. getChildren().get(2) getChildren().add(newChild) OCL needs more than just UML multiplicities
  • 68. OCL 2.0 Collections Typed Collections partially reify multiplicities Collections are different to objects Navigation from a Collection uses -> [Navigation from an Object (OclAny) uses . ] Collections have type parameters Collections have useful operations Collections have very useful iterations Collections are immutable Collection(T) Unordered Ordered Non-Unique Bag(T) Sequence(T) Unique Set(T) OrderedSet(T)
  • 69. Example Collection Operations Collection::size() self.children->size() 'get' Sequence::at(Integer) self.children->at(1) nb 1 is the first index, size() is the last 'add' Collection(T)::including(T) : Collection(T) returns a new collection with added content 'contains' Collection(T)::includes(T) : Boolean tests existing content
  • 70. Collection::select iteration Children self.children Sons self.children->select(gender = Gender::MALE) self.children->select(child | child.gender = Gender::MALE) self.children->select(child : Person | child.gender = Gender::MALE) select(iterator : type | body) filters to select elements for which the body is true reject(iterator : type | body) filters to reject elements for which the body is true cf multi-line Java loop
  • 71. Collection::collect iteration Children self.children Grandchildren self.children->collect(children) self.children->collect(child | child.children) self.children->collect(child : Person | child.children) collect(iterator : type | body) creates a new collection comprising all the bodies any, exists, forAll, isUnique, iterate, one,
  • 72. OCL Navigation Operators anObject. ... object navigation aCollection-> ... collection navigation Shorthands aCollection. ... implicit collect anObject-> ... implicit as set Object Collection . Navigation ? -> ? Navigation
  • 73. Implicit Collect Query parents.parents = parents->collect(parents) 3 symbols, compared to 4 lines of Java 4 grandparents, but not all different!
  • 74. Cleaned up query parents.parents->asSet()->sortedBy(name) ->asSet() converts to Set(Person), removes duplicates ->sortedBy(name) alphabeticizes
  • 75. Implicit As Set Conversion self->notEmpty() Standard OCL idiom Converts self (if an object) to a Set of self
  • 76. If self is a defined object Implicit set is not empty - true If self is an undefined object ( null ) Implicit set is empty - false If self is an error ( invalid ) Implicit set is also an error - invalid Object Collection . Navigation Implicit collect() -> Implicit as set Navigation
  • 77. Collection::closure iteration children, grandchildren, greatgrandchildren etc self->closure(children) Implicit collection of self, then closure of all children [ closure in MDT/OCL 1.2, in OMG OCL 2.3 ]
  • 78. OCL as Implementation any(x) iteration selects an arbitrary element for which x is true.
  • 79. Derived Properties For Hera invariant MixedGenderParents: father . gender <> mother . gender ; fails because father is null and mother is null
  • 81. Other OCL Capabilities No time to mention Other iterators, operations
  • 87. OCL in Code - Java API MDT/OCL started as a Java API parsing OCL
  • 89. Facade to hide internals
  • 90. 'Internal' API for derived language parse/evaluate Evolution has added GUI functionality Console and Editors OCL can be much faster than Java! OCL amenable to analysis
  • 91. The Re-Evaluation Problem System defined by a set of OCL expressions
  • 92. System comprising a set of model elements
  • 93. A model element changes ....
  • 94. Which of the OCL expressions may have changed its value on which context elements?
  • 95. Naïve approach re-evaluate all expressions for all their contexts
  • 96. takes O(|expressions| * |modelElements|)
  • 97. The Impact Analyzer Smart approach pre-evaluate all OCL expression dependencies
  • 98. re-evaluate only changed model elements
  • 99. only expression for which model element is changed Go to Efficient, Scalable Notification Handling for EMF (2 hours ago).
  • 100. Benchmark Context Reduction (Average Case) Naive Event-Filtered (*6 Speed-Up) Event-Filtered and Context-Reduced (*1300 Speed-Up vs. Naive, *220 vs. Event-Filtered-Only) Total Re-Evaluation Time in Seconds Number of Model Elements
  • 101. Benchmark Context Reduction (Worst Case) Naive Event-Filtered (*2.4 Speed-Up) Event-Filtered and Context-Reduced (*27 Speed-Up vs. Naive, *11 vs. Event-Filtered-Only) Total Re-Evaluation Time in Seconds Number of Model Elements (apply changes to very central elements, referenced by all other model packages)
  • 102. State Machine Example Very simple hierarchical state machine Xtext DSL - similar to Xtext's FowlerDSL Use OCL to add validation to Xtext Complete OCL to keep OCL independent
  • 103. OCLinEcore to avoid OCL getting lost Use Acceleo and OCL to convert to Java
  • 104. Use QVTo and OCL to flatten state machine
  • 105. Xtext with independent OCL Main Eclipse meta-modeling Edit states.xtext
  • 107. Generate States Editor Edit states.ocl Run-time Eclipse modeling Exit Run-time
  • 109. Edit simple.states Exit Run-time
  • 111. Edit simple.states with OCL validation
  • 112. Simple State Machine DSL module &quot;simple.states&quot; statemachine Machine { events START STOP; state Start { STOP => Stop } initial state Stop { START => Start } }
  • 113. The Xtext States Grammar http://www.eclipse.org/modeling/mdt/ocl/docs/publications/EclipseCon2011Tutorial /org.eclipse.ocl.tutorial.eclipsecon2011.states/src/org/eclipse/ocl/tutorial/eclipsecon2011/States.xtext grammar org.eclipse.ocl.tutorial.eclipsecon2011.States with org.eclipse.xtext.common.Terminals generate states &quot;http://ocl.eclipse.org/tutorial/eclipsecon2011/States&quot; Module: 'module' name=STRING (machines+=Statemachine)*; Statemachine: (initial?= 'initial' )? 'statemachine' name=ID ( 'value' value=INT)? '{' 'events' (events+=Event)* ';' (states+=State)* '}' ; Event: name=ID; State: SimpleState | CompoundState; SimpleState: (initial?= 'initial' )? 'state' name=ID ( 'value' value=INT)? '{' (transitions+=Transition)* '}' ; CompoundState: 'compound' (initial?= 'initial' )? 'state' name=ID 'machine' machine=[ Statemachine ] '{' (transitions+=Transition)* '}' ; Transition: event=[ Event ] '=>' state=[ State ];
  • 114. Validation Diagnose inappropriate source text Xtext grammar validates syntax and some semantics typos:
  • 115. inappropriate names: Additional Java/Check Validator specialized validation External Complete OCL Validation
  • 117. External Complete OCL Validation Xtext States project src-gen/.../States.ecore auto-generated; don't want to edit it META-INF/MANIFEST.MF add dependency on org.eclipse.ocl.examples.xtext.completeocl src/.../validation/StatesJavaValidator.java generated once; can edit it Helpwanted: validation.CompleteOCLValidatorFragment
  • 118. StatesJavaValidator.java Use Java Validator to invoke Complete OCL import org.eclipse.emf.common.util.URI; import org.eclipse.ocl.examples.xtext.completeocl.validation.CompleteOCLEObjectValidator; import org.eclipse.ocl.tutorial.eclipsecon2011.states.StatesPackage; import org.eclipse.xtext.validation.EValidatorRegistrar; public class StatesJavaValidator extends AbstractStatesJavaValidator { @Override public void register(EValidatorRegistrar registrar) { super .register(registrar); StatesPackage ePackage = StatesPackage. eINSTANCE ; URI oclURI = URI. createPlatformResourceURI ( &quot;/org.eclipse.ocl.tutorial.eclipsecon2011.states.ocl/model/States.ocl&quot; , true ); registrar.register(ePackage, new CompleteOCLEObjectValidator(ePackage, oclURI)); } }
  • 119. Complete OCL Validation 1 /org.eclipse.ocl.tutorial.eclipsecon2011.states.ocl/model/States.ocl import 'http://ocl.eclipse.org/tutorial/eclipsecon2011/States' package states context Statemachine inv HasInitialState( 'No initial state' ): states -> exists ( s : State | s . initial ) endpackage Evaluates: states -> exists ( s : State | s . initial ) true => silent, invariant is satisfied false => invariant is not satisfied evaluates 'No initial state' to determine warning diagnostic null => invariant is not satisfied evaluates 'No initial state' to determine error diagnostic invalid => exception, evaluation failure
  • 121. Complete OCL Validation 2 context Statemachine def : asError(verdict : Boolean ) : Boolean = if verdict then true else null endif inv HasInitialState( 'No initial state' ): asError ( states -> exists ( s : State | s . initial )) context SimpleState inv NameLength( '\'' + name + '\' has ' + name . size (). toString () + ' characters when at least 4 wanted' ): name . size () >= 4 inv NameIsLeadingUpperCase( '\'' + name + '\' must be Leading Uppercase' ): let firstLetter : String = name . substring ( 1 , 1 ) in firstLetter . toUpperCase () = firstLetter
  • 122. Complete OCL Validation 3 context SimpleState def : statemachine : Statemachine = oclContainer ()-> oclAsType ( Statemachine ) inv UniqueInitialState( 'There is more than one initial state' ): initial implies statemachine . states -> select ( initial )-> size () = 1 inv EveryEventIsHandled( let allEvents : Set ( Event ) = statemachine . events -> asSet (), myEvents : Set ( Event ) = self . transitions . event -> asSet () in ( allEvents - myEvents )-> iterate ( e : Event ; s : String = 'The following events are not handled:' | s + ' ' + e . name )): let allEvents : Set ( Event ) = statemachine . events -> asSet (), myEvents : Set ( Event ) = self . transitions . event -> asSet () in ( allEvents - myEvents )-> isEmpty ()
  • 124. Complete OCL activation Xtext CompleteOCLEObjectValidator Interactive Xtext OCL Console Manual Load Resource eClass, eType load referredType ???? States.ecore simple.states Modeling Tool States.ocl
  • 125. Model URI Resolution Main Eclipse, no Global Package Registry platform:/resource/org.eclipse.ocl.tutorial.eclipsecon2011.states/ src-gen/org/eclipse/ocl/tutorial/eclipsecon2011/States.ecore Run-time Eclipse, no Project Resources http://ocl.eclipse.org/tutorial/eclipsecon2011/States Complete OCL editor runs in Main Eclipse
  • 126. executed in Run-time Eclipse OCL Model Registry, Project Package Registry
  • 127. OCL Model Registry URI mapping Defined for: org.eclipse.ocl.tutorial.eclipsecon2011.states.ocl
  • 129. Model URI: platform:/resource/org.eclipse.ocl.tutorial.eclipsecon2011.states/ src-gen/org/eclipse/ocl/tutorial/eclipsecon2011/States.ecore
  • 130. Complete OCL Exercises 1 Open Simple.states in Run-time Eclipse edit and see similar errors to previous slide
  • 131. add additional state Exit Run-time Eclipse edit States.ocl change NameIsLeadingUpperCase to NameIsUppercase restart Run-time Eclipse
  • 132. check that NameIsUppercase is working
  • 133. Complete OCL Exercises 2 Add a ...
  • 134. Add a StateIsReachable invariant tip 1: a sequence of transitions from an initial state reaches the state in question
  • 135. tip 2: the closure of all transitions from all initial states includes the state in question
  • 136. Complete OCL Exercises Answers inv NameIsUpperCase( '\'' + name + '\' must be Uppercase' ): name . toUpperCase () = name statemachine.events->select(initial)->closure(transitions.state)->includes(self)
  • 137. Complete OCL Validation Independent add-on to an Ecore file no need to edit the auto-generated Ecore file
  • 138. need to register the Complete OCL for validation Not part of the editor framework re-useable in other tool contexts
  • 139. need to inform tool of Complete OCL existence UML specified with additional Complete OCL
  • 140. Xtext with embedded OCL Main Eclipse meta-modeling Edit states.xtext
  • 142. Generate OCLStates Editor Edit states.ecore
  • 143. GenModel States Run-time Eclipse modeling Exit Run-time
  • 145. Edit simple.states Exit Run-time
  • 147. Edit simple.states with OCL validation
  • 148. Embedded OCL Validation OCLinEcore editor embeds OCL in Ecore no need to inform tools that OCL exists
  • 149. EMF automatically invokes OCL via delegates Ecore can no longer be autogenerated often appropriate for stable models anyway eClass, eType load OCLStates.ecore simple.oclstates Modeling Tool embedded OCL
  • 150. Move Ecore Move States.ecore, States.genmodel from org.eclipse.ocl.tutorial.eclipsecon2011.states/ src-gen/org/eclipse/ocl/tutorial/eclipsecon2011/States.ecore
  • 152. change all ... States.ecore refs to OCLStates.ecore
  • 153. set genmodel Operation Reflection to true
  • 154. Import rather than Generate Ecore grammar org.eclipse.ocl.tutorial.eclipsecon2011.States with org.eclipse.xtext.common.Terminals generate states &quot;http://ocl.eclipse.org/tutorial/eclipsecon2011/States&quot; import &quot;platform:/resource/org.eclipse.ocl.tutorial.eclipsecon2011.oclstates/model/OCLStates.ecore&quot; (Change MWE2 scipt to *.oclstates) The Generate OCLStates Editor launch may be used
  • 155. Optional Workaround Bug 322639 Use of EObjectValidator gives 'An object may not circularly contain itself' NoEObjectValidator setUseEObjectValidator( false ) import org.eclipse.ocl.examples.xtext.base.utilities.NoEObjectCompositeEValidator; import org.eclipse.xtext.validation.CompositeEValidator; /** * Use this class to register components to be used at runtime / without the Equinox extension registry . */ public class StatesRuntimeModule extends org.eclipse.ocl.tutorial.eclipsecon2011.AbstractStatesRuntimeModule { public Class<? extends CompositeEValidator> bindCompositeEValidator() { return NoEObjectCompositeEValidator. class ; } }
  • 156. Embedded Constraints 1 /org.eclipse.ocl.tutorial.eclipsecon2011.oclstates/model/OCLStates.ecore class Statemachine { invariant HasInitialState( 'No initial state' ): ( states )-> exists ( s : State | s . initial ); attribute _'initial' : Boolean [?] { ordered }; attribute name : String [?] { ordered }; attribute value : ecore :: EInt [?] { ordered }; property events : Event [*] { ordered composes }; property states : State [*] { ordered composes }; } _'initial' is OCL syntax for an awkward identifier
  • 157. ( states ) is over protective pretty-printing
  • 158. [?] is UML oriented [1] not [?] is the default
  • 159. { ordered } is UML oriented { ! ordered unique } is the default
  • 160. Embedded Constraints 2 invariant UniqueInitialState( 'There is more than one initial state' ): initial implies ((( statemachine ). states )-> select ( initial ))-> size () = 1 ; invariant NameIsLeadingUpperCase( '\'' + name + '\' must be Leading Uppercase' ): let firstLetter : String = ( name ). substring ( 1 , 1 ) in firstLetter . toUpperCase () = firstLetter ; invariant NameLength( '\'' + name + '\' has ' + (( name ). size ()). toString () + ' characters when at least 4 wanted' ): ( name ). size () >= 4 ; invariant EveryEventIsHandled( let allEvents : Set ( Event ) = (( statemachine ). events )-> asSet () in let myEvents : Set ( Event ) = (( self . transitions )-> collect ( event ))-> asSet () in ( allEvents - myEvents )-> iterate ( e : Event ; s : String = 'The following events are not handled:' | s + ' ' + e . name )): let allEvents : Set ( Event ) = (( statemachine ). events )-> asSet () in let myEvents : Set ( Event ) = (( self . transitions )-> collect ( event ))-> asSet () in ( allEvents - myEvents )-> isEmpty (); property statemachine : Statemachine [?] { derived } { derivation : ( oclContainer ()). oclAsType ( Statemachine ); }
  • 161. Enable Custom Validation Messages (Vote for EMF Bug 337792 to obviate this)
  • 162. Use an extended Validator API for
  • 163. /emf-gen/org/eclipse/ocl/tutorial/eclipsecon2011/ oclstates/util/OCLStatesValidator.java * @generated not */ public class OCLStatesValidator extends OCLinEcoreEObjectValidator { /META-INF/MANIFEST.MF add dependency on org.eclipse.ocl.examples.xtext.oclinecore
  • 164. Embedded OCL Exercises 1 Open model/OCLStates.ecore with OCLinEcore (in org.eclipse.ocl.tutorial.eclipsecon2011.oclstates) edit and verify semantic checking
  • 165. add additional state Open model/OCLStates.ecore with Sample Ecore browse to see xxx and xxx$message EAnnotations
  • 166. Embedded OCL Exercises 2 In Run-time Eclipse open simple.oclstates (in org.eclipse.ocl.tutorial.eclipsecon2011.states2classes) verify invariant checking Exit Run-time Eclipse
  • 167. Add a new constraint to OCLStates.ecore
  • 168. Regenerate Java with OCLStates.genmodel
  • 169. In Run-time Eclipse open simple.oclstates verify new invariant
  • 170. Acceleo with integral OCL Main Eclipse meta-modeling States Editor states.ecore Model Run-time Eclipse modeling Edit generate.mtl
  • 173. Run Generate Simple States
  • 174. Inspect *.java generate.mtl
  • 175. Use of OCL for M2T Acceleo is the Eclipse realisation of MOFM2T OMG specification for Model to Text transformation
  • 176. exploits/extends OCL for core expressions Tutorial Example generate Java classes from State Model
  • 177. one class for the State Machine
  • 178. one class for each State
  • 179. one method for each Event
  • 180. States to Java Classes module &quot;simple.states&quot; statemachine Machine { events START STOP; state Start { START => Start } initial state Stop { STOP => Stop } } package simple.states; public class Stop implements Machine.State { private final Machine sm ; public Stop(Machine sm) { this . sm = sm; } public void doSTOP() { sm .setState(STATES. STATE_Stop ); } } package simple.states; public class Machine { public interface State { public void doSTART(); public void doSTOP(); enum STATES { STATE_Start , STATE_Stop } }
  • 181. Xtext files as Eclipse Models Xtext maintains Concrete Syntax text files behave as EMF models
  • 182. Open With->Sample Ecore Model Editor shows CST as an Ecore model XtextResourceFactory not XMIResourceFactory defined by plugin.xml works in nested Eclipse
  • 184. Xtext files as Standalone Models XtextResourceFactory not registered invoke XXXStandaloneSetup.doSetup() injected references to org.eclipse.xtext
  • 185. org.apache.log4j either export from 'editor' plugin (Bug 339083) edit MANIFEST.mf to re-export or import to consumer plugin edit MANIFEST.mf to add dependencies
  • 186. Acceleo configuration to use Xtext /org.eclipse.ocl.tutorial.eclipsecon2011.states2classes/ src/org/eclipse/ocl/tutorial/eclipsecon2011/states2classes/files/Generate.java Acceleo generator runs Standalone
  • 187. Edit 'Generate.java'.registerPackages invoke 'editor' Standalone setup * @generated NOT */ @Override public void registerPackages(ResourceSet resourceSet) { super .registerPackages(resourceSet); StatesStandaloneSetup . doSetup (); // resourceSet.getPackageRegistry().put( // org.eclipse.xtext.example.fowlerdsl.FowlerdslPackage.eINSTANCE.getNsURI(), // org.eclipse.xtext.example.fowlerdsl.FowlerdslPackage.eINSTANCE); }
  • 188. Acceleo Control Logic [template public generate(m : Module)] [comment @main /] [for ( e : Statemachine | m.machines) ] [file (e.name + '.java' , false, 'UTF-8' ) ] [ generateStatemachineClass(m, e) /] [/file] [for ( s : State | e.states) ] [file (s.name + '.java' , false, 'UTF-8' ) ] [ generateStateClass(m, e, s) /] [/file] [/for] [/for] [/template] Whitespace copied to output; limited indentation
  • 189. OCL: e.name + '.java' e.states
  • 190. Acceleo Text Template 1 package simple.states; public class Stop implements Machine.State { private final Machine sm ; public Stop(Machine sm) { this . sm = sm; } public void doSTOP() { sm .setState(STATES. STATE_Stop ); } } [template public generateStateClass(m : Module, e : Statemachine, s : SimpleState)] package [ m.getPackageName() /] ; public class [ s.getStateClassName() /] implements [ e.name + '.State' /] { private final [ e.getStateMachineClassName() /] sm; public [ s.getStateClassName() /] ( [ e.getStateMachineClassName() /] sm) { this.sm = sm; } [for ( t : Transition | s.transitions) ] public void [ t.event.getEventMethodName() /] () { sm.setState(STATES. [ t.state.getStateEnumName() /] ); } [/for] } [/template] OCL: t.state.getStateEnumName()
  • 191. Acceleo Queries Queries support modularisation repeated sub-expression can be factored out [query getStateEnumName(s : State) : String = 'STATE_' + s.name /] [query getInitialState(e : Statemachine) : State = e.states->any(initial) /]
  • 192. package simple.states; public class Machine { public interface State { public void doSTART(); public void doSTOP(); enum STATES { STATE_Start , STATE_Stop } } Acceleo Text Template 2 [template public generateStatemachineClass(m : Module, e : Statemachine)] package [ m.getPackageName() /] ; public class [ e.getStateMachineClassName() /] { public interface State { [for ( v : Event | e.events) ] public void [ v.getEventMethodName() /] (); [/for] enum STATES { [for ( s : State | e.states) separator ( ',\n' ) after ( '\n' ) ] [ s.getStateEnumName() /] [/for] } } ... public [ e.getStateMachineClassName() /] () { setState(State.STATES. [ e.getInitialState().getStateEnumName() /] ); } public Machine() { setState(State.STATES. STATE_Stop ); }
  • 193. Acceleo Demonstration Generate BadStates view errors Edit badsimple.states to correct a initial error exit, generate, inspect Edit badsimple.states to correct handled errors exit, generate, inspect OCL provides model validation integration within editor for early diagnosis
  • 194. protects downstream from garbage in ...
  • 195. Acceleo Exercises Repeat demonstration
  • 196. Change the enums from STATE to ENUM prefix
  • 198. Change enums to all upper case hint String::toUpperCase() : String Change internal States interface to an abstract class with default no change event methods.
  • 200. QVTo with integral OCL Main Eclipse meta-modeling States Editor states.ecore Model Run-time Eclipse modeling Edit FlattenStates.qvto
  • 202. Run Flatten States to XMI or Flatten States
  • 203. Inspect flattened.xmi Inspect flattened.states FlattenStates.qvto
  • 204. Xtext feature (as output model) QVTo generator runs as a Plugin no action needed QVTo can transform 'Xtext' to 'Xtext' But to-'Xtext' must be serializable XMI no orphans, no missing objects obscure 'cannot write' diagnostics use 'Xtext' to *.xmi for debug
  • 205. QVTo feature (for re-runs) Output mode ill-defined by specification implemented as append by M2M/QVTo Transformation re-run appends additional root object in XMI file may be useful for manual comparison of old/new
  • 206. guarantees non-serializability to Xtext Manually delete output file before transformation
  • 207. Statemachine Flattening Example module &quot;compound.states&quot; statemachine Outer { events START STOP; initial state Start value 4 { START => CompoundA } state Stop value 5 { STOP => CompoundB } compound state CompoundA machine Inner { START => Stop } compound state CompoundB machine Inner { STOP => Stop } } statemachine Inner { events LEFT RIGHT; initial state Left value 1 { LEFT => Right } state Right { RIGHT => Left } } module &quot;flattened.compound.states&quot; statemachine Outer { events STOP RIGHT LEFT START; initial state Start value 4 { START => CompoundA_Left } state Stop value 5 { STOP => CompoundB_Left } state CompoundA_Left value 1 { LEFT => CompoundA_Right START => Stop } state CompoundA_Right { RIGHT => CompoundA_Left START => Stop } state CompoundB_Left value 1 { LEFT => CompoundB_Right STOP => Stop } state CompoundB_Right { RIGHT => CompoundB_Left STOP => Stop } }
  • 208. root mapping mapping HIER :: Module :: model2FLATModel () : FLAT :: Module { name := 'flattened.' + self . name ; var name2state : Dict ( String , HIER :: State ); var allMachines : Set ( HIER :: Statemachine ) = self . machines . allMachines ()-> asSet (); var allStates : Set ( HIER :: State ) = allMachines. states -> asSet (); var allCompoundStates : Set ( HIER :: CompoundState ) = allStates-> select ( oclIsTypeOf ( HIER :: CompoundState )) -> collect ( oclAsType ( HIER :: CompoundState ))-> asSet (); var rootMachines : Set ( HIER :: Statemachine ) = allMachines-> select (m : HIER :: Statemachine | not allCompoundStates-> exists ( machine = m)); machines := rootMachines-> map machine2machine (name2state); }
  • 209. transitive closure Warning because closure() not in OCL 2.0, 2.2 resolution adopted in OCL 2.3
  • 210. due for approval this week OMG, Arlington, VA Eclipse OCL has and continues to pioneer solutions to OMG OCL specification issues
  • 211. machine 2 machine mapping mapping HIER :: Statemachine :: machine2machine (name2state : Dict ( String , HIER :: State )) : FLAT :: Statemachine { var exitTransitions : Dict ( FLAT :: Event , FLAT :: State ); name := self . name ; events := self . allMachines (). events -> asSet (). map event2event (); states := self . states . map state2states (name2state, Sequence {}); self . states . map state2transitions (name2state, Sequence {}, exitTransitions); } pass 1 all events flattened
  • 212. pass 2 all states flattened name2state cache, hierarchy Sequence pass 3 transitions added to flattened states to-compound => initial
  • 213. from-compound => all exitTransitions
  • 214. iterate to form concatenated string query HIER :: State :: getStateName (hierarchy : Sequence ( HIER :: CompoundState )) : String { return hierarchy->iterate(c : HIER :: CompoundState ; s : String = self . name | c. name + '_' + s) }
  • 215. conditional hierachical selection query HIER :: State :: initialStateName (hierarchy : Sequence ( HIER :: CompoundState )) : String { var stateName : String = self . getStateName (hierarchy); return if self . oclIsKindOf ( HIER :: CompoundState ) then let compoundState : HIER :: CompoundState = self . oclAsType ( HIER :: CompoundState ) in compoundState. machine . states -> any ( initial ) . initialStateName (hierarchy-> append (compoundState)) else stateName endif }
  • 216. simple navigation/logic mapping HIER :: SimpleState :: simpleState2state ( name2state : Dict ( String , HIER :: State ), hierarchy : Sequence ( HIER :: CompoundState ) ) : FLAT :: SimpleState { var stateName : String = self . getStateName (hierarchy); name := stateName; value := self . value ; initial := hierarchy-> isEmpty () and self . initial ; name2state-> put (stateName, result ); }
  • 217. iterate to create objects mapping HIER :: SimpleState :: simpleState2transitions2 ( name2state : Dict ( String , HIER :: State ), hierarchy : Sequence ( HIER :: CompoundState ), exitTransitions : Dict ( FLAT :: Event , FLAT :: State ) ) : FLAT :: State { init { var stateName : String = self . getStateName (hierarchy); result := name2state-> get (stateName); } transitions := exitTransitions-> keys ()->iterate(v : FLAT :: Event ; acc : Sequence ( HIER :: Transition ) = self . transitions . map transition2transition (name2state, hierarchy) | acc-> append ( object FLAT :: Transition { state := exitTransitions-> get (v); event := v; }) ); }
  • 218. QVTo Demonstration Run Flatten States inspect flattened.states Run Flatten States to XMI inspect flattened.xmi Run Flatten States again show confusion Delete flattened.states
  • 219. Run Flatten States inspect flattened.states
  • 220. QVTo Exercises repeat demonstration
  • 222. change Flattened state names from x_y to y_x regenerate
  • 225. Run Generate Flattened States inspect flattened Java
  • 226. QVTo debugging tips QVTo debugger is good breakpoint, single line stepping, variable browser
  • 227. not perfect, variables may be wrong 'self' Debugger more useful if implement *Impl.toString() to explain self
  • 228. 'var' used to cache partial/temporary states
  • 229. Old Eclipse OCL Old code - stable from Helios, MDT/OCL 3.0 LPG-based
  • 230. org.eclipse.ocl.ecore, org.eclipse.ocl.uml templates for Ecore/UML binding no editors
  • 231. delegate URI: http://www.eclipse.org/emf/2002/Ecore/OCL limited bug fixing fundamental problems hard to address
  • 232. New Eclipse OCL Helios, MDT/OCL 3.0 Examples Partial functionality Xtext-based editors Indigo, MDT/OCL 3.1 Examples Full functionality Xtext-based editors
  • 233. Modelled Extensible Library and Evaluator org.eclipse.ocl.examples.pivot
  • 234. no templates, 'exact' UML-aligned OMG compliance delegate URI: http://www.eclipse.org/emf/2002/Ecore/OCL/Pivot Juno, MDT/OCL 3.2 Core + Tools org.eclipse.ocl.pivot
  • 235. Summary OCL, powerful model expression language model evaluation - Console, Essential OCL editor
  • 236. Ecore behavioral extension - OCLinEcore editor
  • 237. dynamic and genmodeled validation
  • 238. (UML support - Papyrus editor) OCL can be an Xtext validator embedded or independent - Complete OCL editor OCL resused by M2M and M2T Acceleo and QVTo tooling MDT/OCL originally focussed on Java API
  • 239. Eclipse OCL evolving an extensible GUI
  • 240. OCL Resources OCL 2.2 Specification http://www.omg.org/spec/OCL/2.2 Clause 7 is quite readable (many typos) The Object Constraint Language: Getting Your Models Ready For MDA Jos B. Warmer, Anneke Kleppe Eclipse MDT/OCL project http://www.eclipse.org/projects/project_summary.php?projectid=modeling.mdt.ocl