Programmatically execute an OCL query on a UML model

491 views Asked by At

Can anyone provide an example of how to programmatically execute an OCL query on a UML model using Eclipse MDT/OCL implementation. I read the Eclipse documentation, but still could not find a working example and I keep getting different exceptions and errors.

Thanks for your help.

1

There are 1 answers

0
lanoxx On

Here is an example how you can instantiate an ocl query. There exist two environment factories for OCL, one for Ecore which is used in this example and another one for UML. Since UML is implemented with Ecore you can also use the Ecore factory if you want to evaluate UML Models.

private final OCL<?, EClassifier, ?, ?, ?, EParameter, ?, ?, ?, Constraint, EClass, EObject> ocl;
private final OCLHelper<EClassifier, ?, ?, Constraint> helper;

this.ocl = OCL.newInstance(EcoreEnvironmentFactory.INSTANCE);
this.helper = ocl.createOCLHelper();

After you have instantiated the OCL and OCLHelper objects its important to set the context object for the OCL query:

helper.setContext(UMLPackage.eINSTANCE.getClass_());

UMLPackage.eInstance has a couple of getters for Class_, Property, Operation and other UML Classes, there is a similar object for Ecore: EcorePackage.eINSTANCE. Next you need to create an OCLExpression and then from it the query.

OCLExpression<EClassifier> expression = helper.createQuery("self.attribute->size() > 0");
Query<EClassifier, EClass, EObject> query = ocl.createQuery(expression);

Now you can check the query on some element:

boolean success = query.check(myElement);

If the check method returns true, then your query is valid for the given model. In that code myElement would be an object of your ECore model with the type Class. The object that you pass to the check method must match the context type that you have set in the helper.