Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 51720d431256e9a247a87776baf233778c5a9e2b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
/*
 * Copyright (c) 2010-2015 Eike Stepper (Berlin, Germany) and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Eike Stepper - initial API and implementation
 *    Christian W. Damus (CEA LIST) - Additional OCL operations for efficient queries
 */
package org.eclipse.emf.cdo.server.ocl;

import org.eclipse.emf.cdo.common.commit.CDOChangeSetData;
import org.eclipse.emf.cdo.common.id.CDOID;
import org.eclipse.emf.cdo.common.model.CDOPackageInfo;
import org.eclipse.emf.cdo.common.model.CDOPackageRegistry;
import org.eclipse.emf.cdo.common.model.CDOPackageUnit;
import org.eclipse.emf.cdo.common.revision.CDORevision;
import org.eclipse.emf.cdo.common.revision.CDORevisionCacheAdder;
import org.eclipse.emf.cdo.common.revision.CDORevisionProvider;
import org.eclipse.emf.cdo.common.util.CDOQueryInfo;
import org.eclipse.emf.cdo.server.CDOServerUtil;
import org.eclipse.emf.cdo.server.IQueryContext;
import org.eclipse.emf.cdo.server.IQueryHandler;
import org.eclipse.emf.cdo.spi.common.commit.CDOChangeSetDataRevisionProvider;
import org.eclipse.emf.cdo.spi.server.QueryHandlerFactory;
import org.eclipse.emf.cdo.view.CDOView;

import org.eclipse.net4j.util.WrappedException;
import org.eclipse.net4j.util.container.IManagedContainer;
import org.eclipse.net4j.util.factory.ProductCreationException;

import org.eclipse.emf.common.util.Diagnostic;
import org.eclipse.emf.common.util.DiagnosticException;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.Enumerator;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.EEnumLiteral;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.spi.cdo.FSMUtil;
import org.eclipse.emf.spi.cdo.InternalCDOObject;

import org.eclipse.ocl.Environment;
import org.eclipse.ocl.EvaluationEnvironment;
import org.eclipse.ocl.OCL;
import org.eclipse.ocl.ParserException;
import org.eclipse.ocl.Query;
import org.eclipse.ocl.ecore.BooleanLiteralExp;
import org.eclipse.ocl.ecore.Constraint;
import org.eclipse.ocl.ecore.EcoreEnvironmentFactory;
import org.eclipse.ocl.ecore.EcoreFactory;
import org.eclipse.ocl.ecore.EnumLiteralExp;
import org.eclipse.ocl.ecore.IntegerLiteralExp;
import org.eclipse.ocl.ecore.RealLiteralExp;
import org.eclipse.ocl.ecore.StringLiteralExp;
import org.eclipse.ocl.expressions.OCLExpression;
import org.eclipse.ocl.expressions.Variable;
import org.eclipse.ocl.helper.OCLHelper;
import org.eclipse.ocl.options.ParsingOptions;
import org.eclipse.ocl.types.OCLStandardLibrary;
import org.eclipse.ocl.util.ProblemAware;
import org.eclipse.ocl.util.Tuple;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

/**
 * A {@link IQueryHandler query handler} that evaluates OCL query expressions.
 *
 * @author Eike Stepper
 */
public class OCLQueryHandler implements IQueryHandler
{
  public static final String LANGUAGE_NAME = "ocl"; //$NON-NLS-1$

  /**
   * @since 4.1
   */
  public static final String LAZY_EXTENTS_PARAMETER = "cdoLazyExtents";

  /**
   * Query parameter indicating the {@link EClass} to set as the implicit root class of the type
   * hierarchy.  The default is {@code null}.
   *
   * @since 4.2
   */
  public static final String IMPLICIT_ROOT_CLASS_PARAMETER = "cdoImplicitRootClass";

  private static final Set<String> SERVER_QUERY_PARAMETERS = Collections.unmodifiableSet(
      new java.util.HashSet<String>(Arrays.asList(LAZY_EXTENTS_PARAMETER, IMPLICIT_ROOT_CLASS_PARAMETER)));

  private static final EcoreFactory FACTORY = EcoreFactory.eINSTANCE;

  private boolean lazyExtents = true;

  private EClass implicitRootClass;

  public OCLQueryHandler()
  {
  }

  public void executeQuery(CDOQueryInfo info, IQueryContext context)
  {
    CDOExtentMap extentMap = null;

    try
    {
      readParameters(info.getParameters());

      CDORevisionProvider revisionProvider = context.getView();
      CDOChangeSetData changeSetData = info.getChangeSetData();
      if (changeSetData != null)
      {
        revisionProvider = new CDOChangeSetDataRevisionProvider(revisionProvider, changeSetData);
      }

      CDOView view = CDOServerUtil.openView(context.getView().getSession(), context, revisionProvider);
      extentMap = createExtentMap(view, changeSetData, context);
      OCL<?, EClassifier, ?, ?, ?, ?, ?, ?, ?, Constraint, EClass, EObject> ocl = createOCL(view, extentMap);

      ContextParameter contextParameter = getContextParameter(info, view);
      Query<EClassifier, EClass, EObject> query = createQuery(view, info, contextParameter, ocl);

      Object result = evaluate(query, contextParameter.getObject());
      if (result == ocl.getEnvironment().getOCLStandardLibrary().getInvalid())
      {
        throw new Exception(
            "OCL query evaluated to 'invalid'. Run with '-Dorg.eclipse.ocl.debug=true' and visit the log for failure details.");
      }

      if (result instanceof Collection<?>)
      {
        for (Object element : (Collection<?>)result)
        {
          if (!addResult(element, context, view))
          {
            break;
          }
        }
      }
      else
      {
        addResult(result, context, view);
      }
    }
    catch (Exception ex)
    {
      throw WrappedException.wrap(ex, "Problem executing OCL query: " + info.getQueryString());
    }
    finally
    {
      if (extentMap != null)
      {
        extentMap.cancel();
      }
    }
  }

  protected boolean addResult(Object result, IQueryContext context, CDOView view)
  {
    result = convertResult(result, view);
    return context.addResult(result);
  }

  protected CDORevision getRevision(EObject object, CDOView view)
  {
    return FSMUtil.adapt(object, view).cdoRevision();
  }

  protected Object evaluate(Query<EClassifier, EClass, EObject> query, EObject object)
  {
    if (object == null)
    {
      return query.evaluate();
    }

    return query.evaluate(object);
  }

  protected CDOExtentMap createExtentMap(CDOView view, CDOChangeSetData changeSetData, IQueryContext context)
  {
    CDOExtentCreator creator = createsLazyExtents() ? new CDOExtentCreator.Lazy(view) : new CDOExtentCreator(view);
    creator.setChangeSetData(changeSetData);
    creator.setRevisionCacheAdder((CDORevisionCacheAdder)context.getView().getRepository().getRevisionManager());
    return new CDOExtentMap(creator);
  }

  protected boolean createsLazyExtents()
  {
    return lazyExtents;
  }

  /**
   * @since 4.2
   */
  protected OCL<?, EClassifier, ?, ?, ?, ?, ?, ?, ?, Constraint, EClass, EObject> createOCL(CDOView view,
      CDOExtentMap extentMap)
  {
    EcoreEnvironmentFactory envFactory = new CDOEnvironmentFactory(view.getSession().getPackageRegistry());

    OCL<?, EClassifier, ?, ?, ?, ?, ?, ?, ?, Constraint, EClass, EObject> ocl = OCL.newInstance(envFactory);
    CDOAdditionalOperation.registerOperations((CDOEnvironment)ocl.getEnvironment());
    ocl.setExtentMap(extentMap);
    return ocl;
  }

  /**
   * @since 4.2
   */
  protected Query<EClassifier, EClass, EObject> createQuery(CDOView view, CDOQueryInfo info,
      ContextParameter contextParameter, OCL<?, EClassifier, ?, ?, ?, ?, ?, ?, ?, Constraint, EClass, EObject> ocl)
      throws ParserException, DiagnosticException
  {
    Map<String, Object> parameters = new HashMap<String, Object>(info.getParameters());
    initEnvironment(ocl.getEnvironment(), view.getSession().getPackageRegistry(), parameters);

    OCLHelper<EClassifier, ?, ?, Constraint> helper = ocl.createOCLHelper();
    helper.setContext(contextParameter.getClassifier());

    OCLExpression<EClassifier> expr = helper.createQuery(info.getQueryString());
    Query<EClassifier, EClass, EObject> query = ocl.createQuery(expr);
    if (query instanceof ProblemAware)
    {
      ProblemAware problemAware = (ProblemAware)query;
      Diagnostic problems = problemAware.getProblems();
      if (problems != null)
      {
        throw new DiagnosticException(problems);
      }
    }

    setOCLQueryParameters(parameters, query);
    return query;
  }

  /**
   * @deprecated As of 4.2 no longer supported.
   */
  @Deprecated
  protected EClassifier getArbitraryContextClassifier(CDOPackageRegistry packageRegistry)
  {
    return ContextParameter.getArbitraryContextClassifier(packageRegistry);
  }

  protected void initEnvironment(
      Environment<?, EClassifier, ?, ?, ?, ?, ?, ?, ?, Constraint, EClass, EObject> environment,
      CDOPackageRegistry packageRegistry, Map<String, Object> parameters)
  {

    // initialize parsing options
    EClass implicitRootClass = getImplicitRootClass();
    if (implicitRootClass != null)
    {
      ParsingOptions.setOption(environment, ParsingOptions.implicitRootClass(environment), implicitRootClass);
    }

    // create variables for query parameters that should be passed through to the OCL query expression
    OCLStandardLibrary<EClassifier> stdLib = environment.getOCLStandardLibrary();
    for (Entry<String, Object> parameter : parameters.entrySet())
    {
      String name = parameter.getKey();
      if (isOCLQueryParameter(name))
      {
        Object value = parameter.getValue();

        OCLExpression<EClassifier> initExpression = createInitExpression(stdLib, packageRegistry, value);

        Variable<EClassifier, ?> variable = FACTORY.createVariable();
        variable.setName(name);
        variable.setType(initExpression.getType());
        variable.setInitExpression(initExpression);

        addEnvironmentVariable(environment, variable);
      }
    }
  }

  /**
   * @since 4.2
   */
  protected EClass getImplicitRootClass()
  {
    return implicitRootClass;
  }

  protected OCLExpression<EClassifier> createInitExpression(OCLStandardLibrary<EClassifier> stdLib,
      CDOPackageRegistry packageRegistry, Object value)
  {
    if (value instanceof String)
    {
      String v = (String)value;
      StringLiteralExp literal = FACTORY.createStringLiteralExp();
      literal.setType(stdLib.getString());
      literal.setStringSymbol(v);
      return literal;
    }

    if (value instanceof Boolean)
    {
      Boolean v = (Boolean)value;
      BooleanLiteralExp literal = FACTORY.createBooleanLiteralExp();
      literal.setType(stdLib.getBoolean());
      literal.setBooleanSymbol(v);
      return literal;
    }

    Integer integerValue = getInteger(value);
    if (integerValue != null)
    {
      IntegerLiteralExp literal = FACTORY.createIntegerLiteralExp();
      literal.setType(stdLib.getInteger());
      literal.setIntegerSymbol(integerValue);
      return literal;
    }

    Double doubleValue = getDouble(value);
    if (doubleValue != null)
    {
      RealLiteralExp literal = FACTORY.createRealLiteralExp();
      literal.setType(stdLib.getReal());
      literal.setRealSymbol(doubleValue);
      return literal;
    }

    if (value instanceof Enumerator)
    {
      Enumerator v = (Enumerator)value;
      String name = v.getName();

      EEnumLiteral eEnumLiteral = packageRegistry.getEnumLiteralFor(v);
      if (eEnumLiteral == null)
      {
        throw new IllegalArgumentException("Enum literal not found: " + name);
      }

      EnumLiteralExp literal = FACTORY.createEnumLiteralExp();
      literal.setType(eEnumLiteral.getEEnum());
      literal.setReferredEnumLiteral(eEnumLiteral);
      return literal;
    }

    throw new IllegalArgumentException("Unrecognized parameter type: " + value.getClass().getName());
  }

  @SuppressWarnings({ "unchecked", "rawtypes" })
  protected void addEnvironmentVariable(
      Environment<?, EClassifier, ?, ?, ?, ?, ?, ?, ?, Constraint, EClass, EObject> environment,
      Variable<EClassifier, ?> variable)
  {
    environment.addElement(variable.getName(), (Variable)variable, true);
  }

  /**
   * @since 4.2
   */
  protected ContextParameter getContextParameter(CDOQueryInfo info, CDOView view)
  {
    return new ContextParameter(view, info);
  }

  /**
   * @since 4.2
   */
  protected void readParameters(Map<String, ?> queryParameters)
  {
    lazyExtents = readParameter(queryParameters, LAZY_EXTENTS_PARAMETER, lazyExtents);
    implicitRootClass = readParameter(queryParameters, IMPLICIT_ROOT_CLASS_PARAMETER, EClass.class, implicitRootClass);
  }

  /**
   * @since 4.2
   */
  protected boolean readParameter(Map<String, ?> queryParameters, String name, boolean defaultValue)
  {
    return readParameter(queryParameters, name, Boolean.class, defaultValue);
  }

  /**
   * @since 4.2
   */
  protected <T> T readParameter(Map<String, ?> queryParameters, String name, Class<T> type, T defaultValue)
  {
    T result = defaultValue;

    Object o = queryParameters.get(name);
    if (o != null)
    {
      try
      {
        result = type.cast(o);
      }
      catch (ClassCastException ex)
      {
        throw new IllegalArgumentException("Parameter " + name + " must be a " + type.getSimpleName() + " but it is a "
            + o + " class " + o.getClass().getName(), ex);
      }
    }

    return result;
  }

  /**
   * @since 4.2
   */
  protected void setOCLQueryParameters(Map<String, Object> parameters, Query<EClassifier, EClass, EObject> query)
  {
    EvaluationEnvironment<EClassifier, ?, ?, EClass, EObject> evalEnv = query.getEvaluationEnvironment();
    for (Entry<String, Object> parameter : parameters.entrySet())
    {
      String key = parameter.getKey();

      if (isOCLQueryParameter(key))
      {
        Object value = parameter.getValue();
        evalEnv.add(key, value);
      }
    }
  }

  /**
   * @since 4.2
   */
  protected boolean isOCLQueryParameter(String name)
  {
    return !SERVER_QUERY_PARAMETERS.contains(name);
  }

  private Integer getInteger(Object value)
  {
    if (value instanceof Integer)
    {
      return (Integer)value;
    }

    if (value instanceof Short)
    {
      return (int)(Short)value;
    }

    if (value instanceof Byte)
    {
      return (int)(Byte)value;
    }

    return null;
  }

  private Double getDouble(Object value)
  {
    if (value instanceof Double)
    {
      return (Double)value;
    }

    if (value instanceof Float)
    {
      return (double)(Float)value;
    }

    return null;
  }

  @SuppressWarnings({ "unchecked", "rawtypes" })
  private Object convertResult(Object result, CDOView view)
  {
    if (result instanceof EObject)
    {
      return getRevision((EObject)result, view);
    }

    if (result instanceof Tuple)
    {
      Tuple tuple = (Tuple)result;
      EList properties = tuple.getTupleType().oclProperties();
      Object[] array = new Object[properties.size()];
      for (int i = 0; i < array.length; ++i)
      {
        array[i] = convertResult(tuple.getValue(properties.get(i)), view);
      }

      return array;
    }

    return result;
  }

  public static void prepareContainer(IManagedContainer container)
  {
    container.registerFactory(new Factory());
  }

  /**
   * Creates {@link OCLQueryHandler} instances.
   *
   * @author Eike Stepper
   */
  public static class Factory extends QueryHandlerFactory
  {
    public Factory()
    {
      super(LANGUAGE_NAME);
    }

    @Override
    public OCLQueryHandler create(String description) throws ProductCreationException
    {
      return new OCLQueryHandler();
    }
  }

  /**
   * An abstraction of the {@link EClassifier classifier} and/or {@link EObject obejct} of an OCL query context parameter.
   *
   * @author Eike Stepper
   * @since 4.2
   */
  protected static final class ContextParameter
  {
    private final EClassifier classifier;

    private final EObject object;

    public ContextParameter(CDOView view, CDOQueryInfo info)
    {
      Object contextParameter = info.getContext();
      if (contextParameter instanceof CDOID)
      {
        CDOID id = (CDOID)contextParameter;
        if (id.isNull())
        {
          CDOPackageRegistry packageRegistry = view.getSession().getPackageRegistry();
          classifier = getArbitraryContextClassifier(packageRegistry);
          object = null;
        }
        else
        {
          InternalCDOObject cdoObject = (InternalCDOObject)view.getObject(id);
          classifier = cdoObject.eClass();
          object = cdoObject.cdoInternalInstance();
        }
      }
      else if (contextParameter instanceof EClassifier)
      {
        classifier = (EClassifier)contextParameter;
        object = null;
      }
      else
      {
        CDOPackageRegistry packageRegistry = view.getSession().getPackageRegistry();
        classifier = getArbitraryContextClassifier(packageRegistry);
        object = null;
      }
    }

    public ContextParameter(EClassifier classifier, EObject object)
    {
      this.classifier = classifier;
      this.object = object;
    }

    public EClassifier getClassifier()
    {
      return classifier;
    }

    public EObject getObject()
    {
      return object;
    }

    protected static EClassifier getArbitraryContextClassifier(CDOPackageRegistry packageRegistry)
    {
      for (CDOPackageUnit packageUnit : packageRegistry.getPackageUnits())
      {
        for (CDOPackageInfo packageInfo : packageUnit.getPackageInfos())
        {
          for (EClassifier classifier : packageInfo.getEPackage().getEClassifiers())
          {
            return classifier;
          }
        }
      }

      throw new IllegalStateException("Context missing");
    }
  }
}

Back to the top