• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Enrich Your Models With OCL
 

Enrich Your Models With OCL

on

  • 9,135 views

EclipseCon 2011 Tutorial

EclipseCon 2011 Tutorial

Statistics

Views

Total Views
9,135
Views on SlideShare
8,554
Embed Views
581

Actions

Likes
4
Downloads
224
Comments
3

5 Embeds 581

http://www.eclipsecon.org 450
http://eclipsecon.org 124
http://translate.googleusercontent.com 3
https://www.eclipsecon.org 3
https://twitter.com 1

Accessibility

Categories

Upload Details

Uploaded via as OpenOffice

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel

13 of 3 previous next Post a comment

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
  • My apologies. I did not expect my comment be delivered to the author of the slide. In English: This is a great slide on eclipse OCL from 2011, and we wish to see this slide updated for 2013.
    Are you sure you want to
    Your message goes here
    Processing…
  • THese slides are in English. Please use English for any comments.
    Are you sure you want to
    Your message goes here
    Processing…
  • 最新版が欲しくなりますね。
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Enrich Your Models With OCL Enrich Your Models With OCL Presentation Transcript

    • Enrich Your Models with OCL Edward Willink, Thales Eclipse (MDT) OCL Project Lead Axel Uhl, SAP Eclipse (MDT) OCL Committer 21st March 2011
    • 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 Overview
      • Strongly recommended (Wifi) - see slides
        • Unzip ZippedZip.zip from EclipseCon session page
        • Install Eclipse 3.7M6 (Indigo)
        • Install New Software ... for Indigo, 6 projects
        • (Install New Software ... OCL M6b)
        • Load MainWorkspaceProjects.zip in Eclipse
        • Load RuntimeWorkspaceProjects.zip in RT Eclipse
      • Slow last ditch resort (USB stick)
        • Numerous Installs (see USB stick README)
    • Preparation from USB stick alone
      • Copy one platform from Eclipse3.7M6Platforms
      • Copy all projects from Eclipse3.7M6Projects
      • Copy all files from EclipseCon2011OCL
      • Follow instructions in README.noWiFi
    • 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:ToolsEclipse3.7M6EclipseConeclipse.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
        • 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 M6b Updates
      • M6b 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.0M6b.zip
        • MDT/OCL (3.1.0-v20110320...)
    • Preparation - Main Workspace
      • Close Wecome
      • File->Import->General
        • Existing Projects into Workspace
        • Next
      • Select achive File: MainWorkspaceProjects.zip
        • Finish
          • 9 projects
          • 0 errors
          • 98 warnings
    • Preparation - Runtime Eclipse
      • Run->Run Configurations
        • Select Eclipse->Eclipse OCL Tutorial
      • Sun JVM
        • Run
          • sets VM arguments for plenty of memory, e.g.
      -Xms40m -Xmx512m -XX:PermSize=64M -XX:MaxPermSize=128M
      • Other JVM
        • Select the "Arguments" tab
          • Set VM arguments for plenty of memory
        • Run
    • Preparation - Runtime Workspace
      • Close Wecome
      • File->Import->General
        • Existing Projects into Workspace
        • Next
      • Select achive File: RuntimeWorkspaceProjects.zip
        • Finish
          • 3 projects
          • 0 errors
          • 3 warnings
    • Part 1: OCL in isolation Why OCL? Easy - similar Java
        • OCL Basic Facilities exercises
      Sensible - different to Java
        • OCL Collections
      Powerful - more relevant than Java
        • OCL Iterators exercises
      Tool support - available and improving
    • Part 2: OCL in combination 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
    • The OCL Landscape Java Modeler Informal Debug Specification Author EMF Modeler DSL Modeler M2T Modeler M2M Modeler
    • Part 1: OCL in isolation Why OCL? Easy - similar Java
        • OCL Basic Facilities exercises
      Sensible - different to Java
        • OCL Collections
      Powerful - more relevant than Java
        • OCL Iterators exercises
      Tool support - available and improving
    • 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: ATL, Epsilon, VIATRA, QVTo (OMG QVT)
        • M2T: Acceleo (OMG MOFM2T)
    • Object Constraint Language
      • Requirement:
        • an expression language for models
      • Influences:
        • Fortran
          • provided fundamental expression/function notation
        • Evolution
          • '.' operator for records/structures/objects/operations
      • OCL extension
        • from objects
        • to collections of model elements
    • 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: ...playspace/model/default.people_diagram
    • Simple Query Evaluation Window->Show View->Other... Console Console: New: Interactive Xtext OCL Select Zeus as the Model Context Type children then carriage return
    • Part 1: OCL in isolation Why OCL? Easy - similar Java
        • OCL Basic Facilities exercises
      Sensible - different to Java
        • OCL Collections
      Powerful - more relevant than Java
        • OCL Iterators exercises
      Tool support - available and improving
    • 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', " linen " String, 'c', ' linen ' 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(&quot;John&quot;) or child(&quot;John&quot;) )
    • OCL in context
      • Pure OCL expressions
        • academic interest
      • OCL expressions for models
        • useful for practice/experiment
        • adds value 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 exercises
      • In Runtime Eclipse
        • open ...playspace/model/default.people_diagram
        • open Console, then Interactive Xtext Console
        • identify parents of Zeus
        • determine the number of letters in Hephaestus
          • hint: String::size() : Integer
    • OCLinEcore exercises
      • In Main Eclipse
        • open ESEExampleTree/model/people1.xmi
          • Validate
          • inspect validation failures
        • edit people1.ecore as OCLinEcore
          • change name limit to at most five characters
          • save
          • revalidate
        • open your own favourite Ecore file as OCLinEcore
    • Part 1: OCL in isolation Why OCL? Easy - similar Java
        • OCL Basic Facilities exercises
      Sensible - different to Java
        • OCL Collections
      Powerful - more relevant than Java
        • OCL Iterators exercises
      Tool support - available and improving
    • 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
    • Part 1: OCL in isolation Why OCL? Easy - similar Java
        • OCL Basic Facilities exercises
      Sensible - different to Java
        • OCL Collections
      Powerful - more relevant than Java
        • OCL Iterators exercises
      Tool support - available and improving
    • 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
    • Some Other Collection Iterators
      • any(iterator : type | body)
        • (an arbitrary) any element for which body is true
      • exists(iterator : type | body) exists(iterator1 : type, iterator2 : type | body)
        • true if body is true for some element
      • forAll(iterator : type | body) forAll(iterator1 : type, iterator2 : type | body)
        • true if body is true for all elements
      • isUnique(iterator : type | body)
        • true if body is distinct for all elements
      • one(iterator : type | body)
        • true if body is true for exactly one element
    • Some OrderedCollection Iterators
      • sortedBy(iterator : type | body)
        • an ordered of the elements
          • ordered by the < operation of the body's type
    • The iterate Iterators All iterations are degenerate iterate calls.
      • iterate(iterator : T1; accumulator : T2 = initializer | body) : T2
        • initialization
          • accumulator = initializer
        • iteration using iterator
          • accumulator = body
          • body may involve accumulator and/or iterator
        • result
          • accumulator
    • 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 object - >
        • Co nverts object (if a defined) to a Set of object
      object->notEmpty()
        • Standard OCL idiom
      Object Collection . Navigation Implicit collect() -> Implicit as set Navigation object as set result notEmpty() result defined object Set{object} true null, undefined object Set{} false invalid, error invalid invalid
    • 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, Iteration exercises
      • In Runtime Eclipse
        • open ...playspace/model/default.people_diagram
        • open Console, then Interactive Xtext Console
        • repeat slide examples
        • determine all ancestors of Zeus
        • determine all ancestors of Hephaestus
        • determine all four-lettered ancestors of Ares
        • determine the number of siblings of Perseus
    • Other OCL Capabilities No time to mention
      • Other 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
      • 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 expressions 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)
    • Part 2: OCL in combination 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
    • 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
    • Xtext with independent OCL Main Eclipse
        • meta-modeling
      • Edit states.xtext
      • Tailor Editor
      • Generate States Editor
        • Generate states.ecore
      • 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
    • Example Invariant Violation
    • 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
    • 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 ()
    • Composite Validation Errors
    • Complete OCL Exercises 1
      • Open Simple.states in Run-time Eclipse
        • edit and see similar errors to previous slide
        • add additional state
      • Exit Run-time Eclipse
        • edit States.ocl
          • change NameIsLeadingUpperCase to NameIsUppercase
        • restart Run-time Eclipse
        • check that NameIsUppercase is working
    • Complete OCL Exercises 2
      • Add a StateIsReachable invariant
        • tip 1: a sequence of transitions from an initial state reaches the state in question
        • tip 2: the closure of all transitions from all initial states includes the state in question
    • Complete OCL activation
      • Xtext
        • CompleteOCLEObjectValidator
      • Interactive Xtext OCL Console
        • Manual Load Resource
      eClass, eType load referredType ???? States.ecore simple.states Modeling Tool States.ocl
    • 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
        • executed in Run-time Eclipse
      • OCL Model Registry, Project Package Registry
    • OCL Model Registry URI mapping
      • Defined for: org.eclipse.ocl.tutorial.eclipsecon2011.states.ocl
      • AccessorName: http://ocl.eclipse.org/tutorial/eclipsecon2011/States
      • Model URI:
      platform:/resource/org.eclipse.ocl.tutorial.eclipsecon2011.states/ src-gen/org/eclipse/ocl/tutorial/eclipsecon2011/States.ecore
    • Complete OCL Validation
      • Independent add-on to an Ecore file
        • no need to edit the auto-generated Ecore file
        • need to register the Complete OCL for validation
      • Not part of the editor framework
        • re-useable in other tool contexts
        • need to inform tool of Complete OCL existence
      • UML specified with additional Complete OCL
    • Part 2: OCL in combination 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
    • Xtext with embedded OCL Main Eclipse
        • meta-modeling
      • Edit states.xtext or states.ecore with OCL
      • Tailor Editor
      • Generate OCLStates Editor
      • GenModel States
      Run-time Eclipse
        • modeling
      • Exit Run-time
      • Start Run-time
      • Edit simple.states
        • with OCL validation
    • Embedded OCL Validation
      • OCLinEcore editor embeds OCL in Ecore
        • no need to inform tools that OCL exists
        • 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
    • Move Ecore
      • Move States.ecore, States.genmodel
        • from org.eclipse.ocl.tutorial.eclipsecon2011.states/ src-gen/org/eclipse/ocl/tutorial/eclipsecon2011/States.ecore
        • to org.eclipse.ocl.tutorial.eclipsecon2011.oclstates/ model/OCLStates.ecore
        • change all ... States.ecore refs to OCLStates.ecore
    • 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 script to *.oclstates)
      • The Generate OCLStates Editor launch may be used
    • 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 ; } }
    • 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 }; }
    • 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 ); }
    • Enable Custom Validation Messages
      • (Vote for EMF Bug 337792 to obviate this)
      • Use an extended Validator API for
      • /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
    • Embedded OCL Exercises 1 In Main Eclipse
      • Open model/OCLStates.ecore with OCLinEcore (in org.eclipse.ocl.tutorial.eclipsecon2011.oclstates)
        • edit and verify semantic checking
        • add additional state
      • Open model/OCLStates.ecore with Sample Ecore
        • browse to see xxx and xxx$message EAnnotations
    • 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
      • Add a new constraint to OCLStates.ecore
      • Regenerate Java with OCLStates.genmodel
      • In Run-time Eclipse open simple.oclstates
        • verify new invariant
    • Part 2: OCL in combination 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
    • Acceleo with integral OCL Main Eclipse
        • meta-modeling
      • States Editor
      • states.ecore Model
      Run-time Eclipse
        • modeling
      • Edit generate.mtl
      • or simple.states
      • Close simple.states
      • Run Generate Simple States
      • Inspect *.java
      generate.mtl
    • Use of OCL for M2T
      • Acceleo is the Eclipse realisation of MOFM2T
        • OMG specification for Model to Text transformation
        • exploits/extends OCL for core expressions
      • Tutorial Example
        • generate Java classes from State Model
        • one class for the State Machine
        • one class for each State
        • one method for each Event
    • 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 } }
    • Xtext files as Eclipse Models
      • Xtext maintains Concrete Syntax text files
        • behave as EMF models
        • Open With->Sample Ecore Model Editor
          • shows CST as an Ecore model
      • XtextResourceFactory not XMIResourceFactory
        • defined by plugin.xml
          • works in nested Eclipse
          • doesn't work standalone
    • Xtext files as Standalone Models
      • XtextResourceFactory not registered
        • invoke XXXStandaloneSetup.doSetup()
          • injected references to
            • org.eclipse.xtext
            • 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
    • 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
      • 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); }
    • 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
      • OCL: e.name + '.java' e.states
    • 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()
    • 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) /]
    • 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 ); }
    • 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
        • protects downstream from garbage in ...
    • Acceleo Exercises
      • Repeat demonstration
      • Change the enums from STATE to ENUM prefix
      • ReLaunch, verify changes
      • Change enums to all upper case
        • hint String::toUpperCase() : String
      • Change internal States interface to an abstract class with default no change event methods.
      • Eliminate the 'EveryStateIsHandled' editor validation
      • Change brace positions to your own style
    • Part 2: OCL in combination 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
    • QVTo with integral OCL Main Eclipse
        • meta-modeling
      • States Editor
      • states.ecore Model
      Run-time Eclipse
        • modeling
      • Edit FlattenStates.qvto
      • or compound.states
      • Run Flatten States to XMI or Flatten States
      • Inspect flattened.xmi Inspect flattened.states
      FlattenStates.qvto
    • 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 strictly valid XMI
        • no orphans, no missing objects
          • obscure 'cannot write' diagnostics
        • use 'Xtext' to *.xmi for debug
    • 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
          • guarantees non-serializability to Xtext
      • Manually delete output file before transformation
    • 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 } }
    • root mapping 1 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); }
    • root mapping 2 var allCompoundStates : Set ( HIER :: CompoundState ) = allStates-> select ( oclIsKindOf ( HIER :: CompoundState )) -> collect ( oclAsType ( HIER :: CompoundState ))-> asSet (); oclIsKindOf(T)...oclAsType(T) ... => filter(T) in Acceleo allStates allCompoundStates
    • root mapping 3 var rootMachines : Set ( HIER :: Statemachine ) = allMachines-> select (m : HIER :: Statemachine | not allCompoundStates-> exists ( machine = m)); allMachines allCompoundStates
    • transitive closure 1
      • Find all self and all sub-statemachines - states.machine for derived CompoundStates
    • transitive closure 2
      • Warning because closure() not in OCL 2.0, 2.2
        • resolution adopted in OCL 2.3
        • due for approval this week OMG, Arlington, VA
      • Eclipse OCL has and continues to pioneer solutions to OMG OCL specification issues
    • 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
        • pass 2 all states flattened
          • name2state cache, hierarchy Sequence
        • pass 3 transitions added to flattened states
          • to-compound => initial
          • from-compound => all exitTransitions
    • 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
      • Run Flatten States
        • inspect flattened.states
    • QVTo Exercises In Runtime Eclipse
      • repeat demonstration
      • regenerate
      • add more hierachical states
      • regenerate
      • Run Generate Flattened States
        • inspect flattened Java
      • inspect Flattened.qvto
      • change Flattened state names from
      x_y to y_x
    • Old Eclipse OCL
      • Old code - stable from Helios, MDT/OCL 3.0
        • LPG-based
        • org.eclipse.ocl.ecore, org.eclipse.ocl.uml
          • templates for Ecore/UML binding
        • no editors
        • delegate URI:
          • http://www.eclipse.org/emf/2002/Ecore/OCL
        • limited bug fixing
          • fundamental problems hard to address
    • 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
        • Modelled Extensible Library and Evaluator
          • org.eclipse.ocl.examples.pivot
          • 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
    • Summary OCL: simple, sensible, powerful modeling language Useable in isolation
      • Java API, Ecore elaboration, EMF delegates
      Useavle in combination
      • Xtext validation, Acceleo, QVTo core
      Tooling available
      • Evaluation Console
      • OCL Editors
      • ? Papyrus Editor
    • 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