| 1 | package de.uka.ipd.sdq.pcmsolver.visitors; |
| 2 | |
| 3 | import java.util.Iterator; |
| 4 | |
| 5 | import org.eclipse.emf.common.util.EList; |
| 6 | import org.eclipse.emf.ecore.EClassifier; |
| 7 | import org.eclipse.emf.ecore.EObject; |
| 8 | import org.eclipse.emf.ecore.EPackage; |
| 9 | import org.eclipse.ocl.ParserException; |
| 10 | import org.eclipse.ocl.ecore.OCL; |
| 11 | import org.eclipse.ocl.ecore.OCL.Query; |
| 12 | import org.eclipse.ocl.ecore.OCLExpression; |
| 13 | |
| 14 | public class EMFQueryHelper { |
| 15 | |
| 16 | @SuppressWarnings("unchecked") |
| 17 | public static Object getObjectByType(EList collection, Class c) { |
| 18 | Iterator i = collection.iterator(); |
| 19 | Object o = null; |
| 20 | while ((o = i.next()) != null) { |
| 21 | if (c.isAssignableFrom(o.getClass())) |
| 22 | break; |
| 23 | } |
| 24 | return o; |
| 25 | } |
| 26 | |
| 27 | protected static final OCL EOCL_ENV = OCL.newInstance(); |
| 28 | |
| 29 | public static EObject executeOCLQuery(EObject context, String query) |
| 30 | { |
| 31 | OCL.Helper helper = EOCL_ENV.createOCLHelper(); |
| 32 | helper.setContext(context.eClass()); |
| 33 | |
| 34 | // set our helper's context object to parse against it |
| 35 | |
| 36 | Object result = null; |
| 37 | try { |
| 38 | OCLExpression oclQuery = helper.createQuery(query); |
| 39 | result = EOCL_ENV.evaluate(context, oclQuery); |
| 40 | } catch (ParserException e) { |
| 41 | System.out.println("Query failed "+query); |
| 42 | throw new RuntimeException(e); |
| 43 | } |
| 44 | if (result == null) |
| 45 | { |
| 46 | System.out.println("Query resulted in an empty result :-( "+query); |
| 47 | throw new RuntimeException("Query resulted in an empty result :-( "+query); |
| 48 | } |
| 49 | return (EObject)result; |
| 50 | } |
| 51 | } |