Tutorials

Tutorials

OCLinEcore tutorial
Tutorial: Working with OCL
Complete OCL tutorial
Code Generation tutorial
Installing the Eclipse OCL Examples and Editors

The OCLinEcore tutorial shows how

The Working with OCL tutorial shows how

OCLinEcore tutorial

This tutorial was updated for Eclipse Juno; Eclipse 3.8/4.2, EMF 2.8, OCL 4.0.

  • Some screenshots may differ slightly.

Overview

In this example you will

  • Create an Ecore model using the OCLinEcore text editor

  • Create a dynamic instance of that Ecore model

  • Enrich the Ecore model with OCL using the OCLinEcore text editor

  • Validate the model and observe the OCL enrichments

  • Use the Interactive OCL Console to execute the OCL enrichments

The above is all performed without generating any Java code; the models exploit EMF’s dynamic capabilities and the OCL integration.

You may then

  • Create an Ecore genmodel

  • Generate Java code for the Ecore model that invokes the OCL expressions.

References

This tutorial assumes that the reader is familiar with generating models using EMF. The reader is referred to Generating an EMF Model.

Other references:

Installing the Eclipse OCL Examples

Please see the Instructions for installing the OCL Editors.

Troubleshooting

The editor currently provides syntax and semantic validation. It does not yet apply all the well-formedness validation rules, so some problems may be unreported. This is work in progress. Sometimes spurious errors are displayed, which may go away with a Save, but may require an editor close and reopen.

Using the OCLinEcore text editor for Ecore

There are many different (compatible) ways to create and edit Ecore models.

  • An Ecore Model may be created from an XSD schema file

  • An Ecore Model may be created from a Rose model file

  • An Ecore Model may be created from annotated Java file

  • The Sample Ecore Editor provides tree editing

  • The Ecore Tools project provides graphical editing

  • Papyrus provides UML editing that may be converted to Ecore

Here we introduce the OCLinEcore editor that provides text editing, which is appropriate when a non-trivial amount of OCL enrichment is required.

All the above approaches update a *.ecore file, so the user is free to choose whichever editing approach is best suited for the planned changes.

Create a New EMF Project

We will first create a new project for this example; so invoke File->New->Project... (left-click the File menu, then left-click New, then left-click Project...).

In the New Project dialog left-click to expand Eclipse Modeling Framework, then left-click to select Empty EMF Project.

Left-click on Next and in the New Empty EMF Project dialog type Tutorial as the project name.

Left-click on Finish.

Create a New Ecore Model

We will now create a new model for this example.

With many alternative editors for *.ecore files, the Eclipse platform is not always sure which to use; it seems to prefer the OCLinEcore editor over the Sample Ecore Editor, so there is an easy and harder way to create a new file.

For either approach, first right-click on the model folder in the Tutorial project to define the target folder and pop-up the context-sensitive menu.

The easy was is to select New->File... and enter Tutorial.ecore. If this opens up a text editor showing “package Tutorial” ... then the easy way works. You may skip the ‘harder way’ since you have already successfully opened your Ecore file with the OCLinEcore editor.

The harder way is to select New->Other....

In the New dialog left-click to expand Eclipse Modeling Framework, then left-click to select Ecore Model.

Left-click on Next and then in the New Ecore Model dialog type Tutorial.ecore as the file name.

Left-click on Finish; The Sample Ecore editor for Tutorial.ecore may open showing a tree view of a single unnamed EPackage. Alternatively the OCLinEcore editor may be opened by default, so you can skip the next change-editor step.

Close the editor by left-clicking the cross on the editor tab.

Edit Ecore Model as OCLinEcore

We will now open the Ecore model using the OCLinEcore text editor and provide some initial content.

Right-click on the Tutorial.ecore file to pop-up the context-sensitive menu and select Open With->OCLinEcore (Ecore) Editor.

An almost empty text file appears showing the module, the package keyword and an empty name and consequently an error.

Now type (or cut and paste) the following text into the editor and save the file.

[Text for cut and paste]

The syntax is defined in OCLinEcore. It emulates OMG specifications with ‘name : type[multiplicity] { properties }’.

  • import associates an alias with an external EPackage.

  • package introduces an EPackage with name, nsPrefix and nsURI.

  • class introduces an EClass with name and optional superclasses.

  • attribute introduces a property with a datatype type (an EAttribute).

  • property introduces a property with a class type (an EReference).

  • # introduces an opposite role name.

  • _'xxx' escapes an awkward or reserved word identifier.

The import URI is the URI of a Package, so in the example the http://www.eclipse.org/emf/2002/Ecore is the URI of the model, # is the fragment separator and / is the path to the Package at the root of the XMI document.

Completion assist (Ctrl Space) may be used for syntax assistance.

Format (Ctrl-Shift F) may be used to auto-format a selected range.

In order to discover a syntax for which completion assist is insufficient, you may use the Sample Ecore Editor on a test file to create the kind of Ecore element that you require, and then open the test file with the OCLinEcore editor to see the corresponding textual syntax.

The Tutorial Meta-Model

The example meta-model models a library with members and books and loans of books to members. It may be viewed graphically using the Ecore Tools (not part of this tutorial).

Note that this diagram is an Ecore Diagram rather than a UML Diagram and so the default multiplicities for attributes is Ecore’s [0..1] rather than OCLinEcore’s and UML’s [1..1].

Note also that the OCL types String and Integer map to EString and EBigInteger in Ecore.

Create a Dynamic Model Instance

At this point a corresponding EMF tutorial would show how to generate Java code for the meta-model and an editor for the meta-model. Here we are concerned with modeling, so we will continue with the models alone.

In order to create a model from the meta-model, we require the meta-model to exist as a file so that both meta-model and model editors can reference it. Therefore save the meta-model to a file by clicking the close cross on the editor tab and answering Yes when prompted to save changes. Now reopen the metamodel by selecting Tutorial.ecore and selecting Open With->OCLinEcore (Ecore) editor.

It is necessary to explicitly specify Open With->OCLinEcore (Ecore) editor once to ensure that the Eclipse platform registers your preference for the OCLinEcore rather than Sample Ecore Editor.

In the editor view, double-click on Library to select it and then right-click to show the context-sensitive menu and then left-click on Create Dynamic Instance... to start to create a new Dynamic Model with Library at its root.

Creating a Dynamic Instance requires a valid *.ecore file to exist. It does not work when editing *.oclinecore files.

In the Create Dynamic Instance dialog select Tutorial/model as the parent folder for the Tutorial.xmi dynamic model instance and left-click Finish.

The model is automatically opened for editing using the Sample Reflective Ecore Editor, which gives a tree-like presentation of the model. The properties of each node can be seen in the Properties View.

(If the Properties View is not visible, right-click within the editor and left-click on Show Properties View.)

Give the library a name such as lib.

From the right-button menu for Library use New Child->Books Book twice, use New Child->Loans Loan once and New Child->Members Member three times to populate the model with two books, one loan and three members.

Left-click to select each of the Books and Members in turn and enter a name such as b1 or m2 using the Properties View. Specify that b1 has one copy and that b2 has 2 copies.

The books and members now have distinct titles in the outline. When you left-click to select the Loan and edit its Book and Member attributes, the associated pull-down has meaningful entries. Specify that the Loan is for b2 by m3.

The configuration so far is simple, three members, two books and one loan. We can validate that this by right-clicking on the Library node, and left-clicking to Validate Library and all its children.

Since the model is so simple, it is difficult to have anything wrong; most of the illegal modeling options such as a Loan composing rather than referencing a Book are prevented by the Editor’s enforcement of the meta-model.

(If you have an error at this point, a Details button will lead you to some diagnostics that may clarify the problem. Pasting the following XMI into Tutorial.xmi should also resolve an entry problem.)

<?xml version="1.0" encoding="ASCII"?>
<tut:Library xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:tut="http://www.eclipse.org/mdt/ocl/oclinecore/tutorial"
    xsi:schemaLocation="http://www.eclipse.org/mdt/ocl/oclinecore/tutorial Tutorial.ecore"
    name="lib">
  <books name="b1" copies="1"/>
  <books name="b2" copies="2"/>
  <loans book="//@books.1" member="//@members.2"/>
  <members name="m1"/>
  <members name="m2"/>
  <members name="m3"/>
</tut:Library>

We will now create two further identical loans of b2 by m3. This may conveniently be performed by left-clicking to select the existing loan, typing Ctrl-C to copy it, left-clicking to select the Library as the new parent, then typing Ctrl-V to paste it on the library. Repeat so that there are three identical loans.

Validating the library should still be successful, although it is clearly wrong for the two copies of b2 to participate in three loans.

Enrich the meta-model with OCL

The semantic constraint that a book cannot be borrowed more times than there are books is a simple example of a constraint that cannot be expressed by simple multiplicities; a more powerful capability is required that may potentially require evaluation of functions of almost arbitrary complexity. The Object Constraint Language provides this capability.

The constraint can be realized as an invariant on a book that specifies that that (the size of the (selection of loans involving the book)) is less than or equal to (the number of copies of the book).

    invariant SufficientCopies:
      library.loans->select(book=self)->size() <= copies;

In more detail:

  • an invariant is defined whose name is SufficientCopies

  • within the invariant on a Book, self is the instance of Book being validated.

  • library.loans, which is short for self.library.loans, navigates to the library and then to all loans in the library.

  • ->select(...) is a collection iteration over the loans. It selects each loan for which its argument expression is true

  • book=self, which is short for aLoan : Loan | aLoan.book = self, uses the aLoan iterator over each loan to select those for which the book is the book being validated

  • ->size() is a collection operation that just counts the number of selected loans

  • <= copies, which is short for <= self.copies converts the count to true if it is consistent, or false if inconsistent.

Close the Tutorial.xmi editor before modifying its meta-model. (Beware that a wide variety of unpleasant errors can occur if the meta-model is changed after the model is loaded.)

Add the invariant shown below to the meta-model.

[Text for cut and paste]

The required semantic is expressed by the SufficientCopies invariant constraint for a Book. For a valid model the SufficientCopies invariant must always be true.

If you reopen the Tutorial.xmi editor and invoke Validate for the Library, you will now get a validation error. Left click Details for details.

The Details identifies that the SufficientCopies invariant is not satisfied for the b2 book.

If you now change the first loan so that b1 is borrowed and then validate again, the problem is resolved. It is alright for m3 to borrow the one copy of b1 and the two copies of b2.

Before introducing a further constraint of no duplicate loans, we will show how OCL expressions can be exercised. OCL is a very powerful compact language; the example hides a loop over all the loans. More complex examples may easily involve three or four levels of hidden loops on a single line, but may equally easily have simple errors. It is therefore helpful to simplify expressions and use helper operations and properties to modularise them. These may then be exercised using the OCL Console.

The OCL Console

The OCL Console supports interactive execution of an OCL expression in the context of a model instance.

To make the OCL Console visible, first make the Console view visible by Window->Show View->Console. Then right click on the Open Console and left click on Interactive Xtext OCL.

Alternatively, you can just invoke Show Xtext OCL Console from the right button menu within the Sample Ecore Editor or Sample Reflective Ecore Editor.

The Xtext OCL console is new Xtext-based functionality that uses the Pivot binding. It is faster, and more compliant with the OCL specification, than the OCL console that uses the LPG parser and Ecore binding.

The Interactive Xtext OCL console comprises two main text panes. The upper pane displays results. The lower pane supports entry of queries.

Left-click to select the Library in the Tutorial.xmi as the context for a query, and then type books followed by a new line into the lower pane of the console.

The result of evaluating this query for the Library is shown.

Substantial OCL queries spanning many lines may be entered and so the cursor up and cursor down keys move across lines. If you want to access an earlier query, you may use the Page Up or Page Down keys to save typing them again.

You can examine the execution of the earlier query by selecting each of the books in turn and executing library.loans->select(book=self), to see that b1 has one Loan and b2 two.

Helper Features and Operations

We will now introduce some helper attributes and operations to make the OCL clearer and provide a richer meta-model API. Close the Tutorial.xmi editor and modify the meta-model to include the derived loans property and the helper operation isAvailable(). Simplify the invariant to use the derived property.

[Text for cut and paste]

Note that the derived property must also be volatile to avoid problems when a model is loaded but has no content.

The derived property is visible in the Properties view.

The helper operation can be evaluated in the Console view by selecting book b2 and typing isAvailable() for execution.

We will now add further helpers and constraints to enforce an at most two loans per member policy and to require loans to be unique.

(Don’t forget to close Tutorial.xmi while changing its meta-model.)

[Text for cut and paste]

The additional books property may be evaluated in the OCL Console to show which books each member has on loan. The property may also be seen in the Properties view.

Select the library again and invoke Validate from the right button menu. There are now two validation failures.

Generating Java Code

We have shown how OCL may be used to enrich Ecore meta-models, how model instances can be created and validated and how expressions can be evaluated, all without generating any Java code.

Exactly the same facilities are available if you do generate Java code and as a result you gain some speed benefits. By default, in the Eclipse OCL 4.0.0 (Juno) release the generated Java code for OCL is interpreted and so the speed gains occur only for the EMF models. In the Code Generation Tutorial, a preliminary release of the OCL to Java code generator is described, giving an approximately five-fold speed improvement and eliminating the need for run-time compilation.

Generating Java code is exactly the same as for any other EMF project; with one important difference; you must set Operation Reflection to true.

Select the Tutorial.ecore file and invoke New->Other... from the right button menu and select Eclipse Modeling Framework and EMF Generator Model.

Select Next.

Select Next.

Select Next.

Select Load and Next.

Select Finish.

The Tutorial.genmodel editor opens.

Most of the default settings are suitable. The one that is not is highlighted. Select the root Tutorial and scroll down the Properties view and set Operation Reflection to true.

You may now invoke Generate Model Code from the right button menu of either Tutorial to generate Java models that invoke OCL.

Java Details

You can check that the OCL appears in your Java by looking at TutorialValidator.java where you’ll find the OCL expression as a String awaiting compilation at run-time, and the validate invocation that triggers that compilation and execution.

protected static final String MEMBER__AT_MOST_TWO_LOANS__EEXPRESSION = "\n" +
  "\t\t\tloans->size() <= 2";

public boolean validateMember_AtMostTwoLoans(Member member, DiagnosticChain
            diagnostics, Map<Object, Object> context) {
  return
    validate
      (TutorialPackage.Literals.MEMBER,
       member,
       diagnostics,
       context,
       "http://www.eclipse.org/emf/2002/Ecore/OCL",
       "AtMostTwoLoans",
       MEMBER__AT_MOST_TWO_LOANS__EEXPRESSION,
       Diagnostic.ERROR,
       DIAGNOSTIC_SOURCE,
       0);
}

Similarly in BookImpl you will find the declaration of a cached delegate and the dynamic invocation that provokes the first time compilation.

protected static final EOperation.Internal.InvocationDelegate
  IS_AVAILABLE__EINVOCATION_DELEGATE = ((EOperation.Internal)
    TutorialPackage.Literals.BOOK___IS_AVAILABLE).getInvocationDelegate();

public boolean isAvailable() {
  try {
    return (Boolean)
        IS_AVAILABLE__EINVOCATION_DELEGATE.dynamicInvoke(this, null);
  }
  catch (InvocationTargetException ite) {
    throw new WrappedException(ite);
  }
}

The OCL expression for the invocation delegate may be found in TutorialPackageImpl.createOCLAnnotations().

addAnnotation
  (getBook__IsAvailable(), 
   source, 
   new String[] {
   "body", "loans->size() < copies"
   });    

API Invariants

The invariants we have used so far do not contribute to the class API.

If you want to have fine grain control of which validations are performed, perhaps because in some incremental context not all are appropriate, you may use the operation form of an invariant.

  class Book
  {
    operation sufficientCopies(diagnostics : ecore::EDiagnosticChain,
      context : ecore::EMap<ecore::EJavaObject,ecore::EJavaObject>) : Boolean
    {
    body: library.loans->select(book=self)->size() <= copies;
    }
    attribute name : String;
    attribute copies : Integer;
    property library#books : Library;
  }

Note that the operation must have a Boolean return (true for valid) and diagnostics and context arguments.

Summary

To illustrate how to work with the OCL and Ecore as models we have

  • Created an Ecore meta-model using the OCLinEcore text editor

  • Created a dynamic model instance from that meta-model

  • Enriched the meta-model with embedded OCL

  • Used the embedded OCL while validating the model

  • Queried the model usng the Interactive OCL Console.

  • Evaluated OCL embedded in the meta-model in the Console.

To use OCL and Ecore as generated Java models we have

  • Generated Java that exploits the embedded OCL.