Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 64a4874e3be72a2a4b7ec13a0a24d5eb4b55b231 (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
/*
 * Copyright (c) 2013 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:
 *    Christian W. Damus (CEA LIST) - initial API and implementation
 */
package org.eclipse.emf.cdo.server.ocl;

import org.eclipse.emf.cdo.eresource.CDOResource;

import org.eclipse.emf.common.notify.impl.AdapterImpl;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.EDataType;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EOperation;
import org.eclipse.emf.ecore.EParameter;
import org.eclipse.emf.ecore.EcoreFactory;
import org.eclipse.emf.ecore.EcorePackage;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.util.EcoreUtil;

import org.eclipse.ocl.ecore.TypeType;
import org.eclipse.ocl.expressions.CollectionKind;
import org.eclipse.ocl.utilities.TypedElement;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Additional operations for use in OCL queries in the CDO context.
 *
 * @author Christian W. Damus
 * @since 4.2
 */
abstract class CDOAdditionalOperation extends AdapterImpl
{
  private final CDOEnvironment env;

  private final String name;

  private CDOAdditionalOperation(CDOEnvironment env, String name)
  {
    this.env = env;
    this.name = name;
  }

  public final CDOEnvironment getEnv()
  {
    return env;
  }

  public final String getName()
  {
    return name;
  }

  /**
   * Creates the ECore operation(s) that I implement and registers them in my environment on the appropriate owner type.
   */
  protected abstract void register();

  /**
   * Evaluates me on the specified {@code source} object with the given (possibly empty) {@code arguments}.
   */
  protected abstract Object evaluate(CDOEvaluationEnvironment evalEnv, Object source, Object[] arguments);

  /**
   * Resolves the possibly generic return type of an operation according to its relation to the source ({@code owner}) type and argument types.
   */
  protected EClassifier getResultType(EClassifier owner, EOperation operation,
      List<? extends TypedElement<EClassifier>> args)
  {
    EClassifier result = operation.getEType();
    return result != null ? result : env.getOCLStandardLibrary().getOclVoid();
  }

  protected final EOperation createEOperation(EClassifier resultType)
  {
    EOperation result = EcoreFactory.eINSTANCE.createEOperation();

    result.setName(getName());
    result.setEType(resultType);
    result.eAdapters().add(this);

    return result;
  }

  protected final EOperation createEOperation(EClassifier resultType, String paramName, EClassifier paramType)
  {
    EOperation result = createEOperation(resultType);

    EParameter param = EcoreFactory.eINSTANCE.createEParameter();
    param.setName(paramName);
    param.setEType(paramType);
    result.getEParameters().add(param);

    return result;
  }

  protected final EClassifier collectionType(CollectionKind kind, EClassifier elementType)
  {
    return (EClassifier)env.getTypeResolver().resolveCollectionType(kind, elementType);
  }

  static CDOAdditionalOperation getInstance(EOperation operation)
  {
    CDOAdditionalOperation result = null;

    // As a hacky filter to avoid the cost of iterating adapters for the vast majority of operations that
    // are not one of ours, check for our common prefix
    if (operation.getName().startsWith("cdo")) //$NON-NLS-1$
    {
      for (Object next : operation.eAdapters())
      {
        if (next instanceof CDOAdditionalOperation)
        {
          result = (CDOAdditionalOperation)next;
          break;
        }
      }
    }

    return result;
  }

  static void registerOperations(CDOEnvironment env)
  {
    new AllProperContents(env).register();
    new MatchesAnyStringAttribute(env).register();
  }

  /**
   * The <tt>cdoAllContents</tt> operation that collects all of the proper (non-cross-resource-contained)
   * elements within a {@link CDOResource} or an {@link EObject}.  An optional argument filters the result
   * to instances of a particular model class.
   *
   *  @author Christian W. Damus
   */
  private static class AllProperContents extends CDOAdditionalOperation
  {
    private static final String NAME = "cdoAllProperContents"; //$NON-NLS-1$

    private AllProperContents(CDOEnvironment env)
    {
      super(env, NAME);
    }

    @Override
    protected void register()
    {
      CDOEnvironment env = getEnv();
      EClassifier oclAny = env.getOCLStandardLibrary().getOclAny();
      EClassifier oclT = env.getOCLStandardLibrary().getT();
      EClassifier resultType = collectionType(CollectionKind.COLLECTION_LITERAL, oclT);

      // One variant without a filter type argument
      env.addHelperOperation(oclAny, createEOperation(resultType));

      // And one with
      env.addHelperOperation(oclAny, createEOperation(resultType, "type", env.getOCLStandardLibrary().getOclType())); //$NON-NLS-1$
    }

    @Override
    protected Object evaluate(CDOEvaluationEnvironment evalEnv, Object source, Object[] arguments)
    {
      Collection<EObject> result = new ArrayList<EObject>();

      // Only resources and EObjects have contents
      Iterator<EObject> iter;
      if (source instanceof Resource)
      {
        iter = EcoreUtil.getAllProperContents((Resource)source, false);
      }
      else if (source instanceof EObject)
      {
        iter = EcoreUtil.getAllProperContents((EObject)source, false);
      }
      else
      {
        iter = Collections.<EObject> emptyList().iterator();
      }

      if (arguments.length == 1)
      {
        // Get the type-filter argument
        EClassifier typeFilter = (EClassifier)arguments[0];
        if (typeFilter == null)
        {
          typeFilter = EcorePackage.Literals.EOBJECT;
        }

        while (iter.hasNext())
        {
          EObject next = iter.next();
          if (!next.eIsProxy() && typeFilter.isInstance(next)) // Because it could be a containment proxy
          {
            result.add(next);
          }
        }

      }
      else
      {
        while (iter.hasNext())
        {
          EObject next = iter.next();
          if (!next.eIsProxy()) // Because it could be a containment proxy
          {
            result.add(next);
          }
        }
      }

      return result;
    }

    @Override
    protected EClassifier getResultType(EClassifier owner, EOperation operation,
        List<? extends TypedElement<EClassifier>> args)
    {
      // The result type of the type-filtered variant is a collection of the filter type
      EClassifier elementType = args.isEmpty() ? getEnv().getOCLStandardLibrary().getOclAny() : ((TypeType)args.get(0)
          .getType()).getReferredType();
      return collectionType(CollectionKind.COLLECTION_LITERAL, elementType);
    }
  }

  /**
   * The <tt>cdoMatches</tt> operation queries whether a regular expression matches aany string-valued
   * attribute of an {@link EObject}.
   *
   * @author Christian W. Damus
   */
  private static class MatchesAnyStringAttribute extends CDOAdditionalOperation
  {
    private static final String NAME = "cdoMatches"; //$NON-NLS-1$

    private static final int CACHE_SIZE = 16;

    private Map<String, Matcher> matcherCache;

    private Map<EClass, List<EAttribute>> stringAttributes;

    private MatchesAnyStringAttribute(CDOEnvironment env)
    {
      super(env, NAME);
    }

    @Override
    protected void register()
    {
      CDOEnvironment env = getEnv();
      EClassifier oclAny = env.getOCLStandardLibrary().getOclAny();
      env.addHelperOperation(oclAny,
          createEOperation(env.getOCLStandardLibrary().getBoolean(), "regex", env.getOCLStandardLibrary().getString())); //$NON-NLS-1$
    }

    @Override
    protected Object evaluate(CDOEvaluationEnvironment evalEnv, Object source, Object[] arguments)
    {
      boolean result = false;

      // Only EObjects have String-valued attributes (or attributes at all!)
      if (source instanceof EObject)
      {
        EObject object = (EObject)source;
        Matcher m = getMatcher((String)arguments[0]);

        // Check all string-valued attributes of this EClass
        for (EAttribute next : getStringAttributes(object.eClass()))
        {
          if (!next.isMany())
          {
            String value = (String)object.eGet(next);
            result = value != null && m.reset(value).matches();
          }
          else
          {
            @SuppressWarnings("unchecked")
            List<String> valueList = (List<String>)object.eGet(next);
            for (int i = 0; !result && i < valueList.size(); i++)
            {
              String value = valueList.get(i);
              result = value != null && m.reset(value).matches();
            }
          }

          if (result)
          {
            break;
          }
        }
      }

      return result;
    }

    private Matcher getMatcher(String regex)
    {
      if (matcherCache == null)
      {
        matcherCache = new java.util.LinkedHashMap<String, Matcher>(CACHE_SIZE, 0.75f, true)
        {
          private static final long serialVersionUID = 1L;

          @Override
          protected boolean removeEldestEntry(Map.Entry<String, Matcher> eldest)
          {
            return size() > CACHE_SIZE;
          }
        };
      }

      Matcher result = matcherCache.get(regex);
      if (result == null)
      {
        result = Pattern.compile(regex).matcher(""); //$NON-NLS-1$
        matcherCache.put(regex, result);
      }

      return result;
    }

    private List<EAttribute> getStringAttributes(EClass eClass)
    {
      if (stringAttributes == null)
      {
        stringAttributes = new java.util.HashMap<EClass, List<EAttribute>>();
      }

      List<EAttribute> result = stringAttributes.get(eClass);
      if (result == null)
      {
        for (EAttribute next : eClass.getEAllAttributes())
        {
          EDataType type = next.getEAttributeType();
          if (type != null && type.getInstanceClass() == String.class)
          {
            if (result == null)
            {
              result = new ArrayList<EAttribute>();
            }
            result.add(next);
          }
        }

        if (result == null)
        {
          result = Collections.emptyList();
        }

        stringAttributes.put(eClass, result);
      }

      return result;
    }
  }
}

Back to the top