Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: dea292b4ee633762375006a575ab8e8328f61d07 (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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
/*
 * Copyright (c) 2009-2013, 2015, 2016, 2018, 2019 Eike Stepper (Loehne, 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
 *    Victor Roldan Betancort - maintenance
 *    Simon McDuff - maintenance
 *    Christian W. Damus (CEA) - support registered dynamic UML profiles
 *    Christian W. Damus (CEA) - don't process EAnnotations for proxy resolution
 */
package org.eclipse.emf.cdo.common.model;

import org.eclipse.emf.cdo.spi.common.model.InternalCDOPackageRegistry;

import org.eclipse.net4j.util.WrappedException;

import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.notify.Notifier;
import org.eclipse.emf.common.util.BasicEList;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.TreeIterator;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EAnnotation;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.EcoreFactory;
import org.eclipse.emf.ecore.EcorePackage;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.EPackageImpl;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.ecore.util.FeatureMap;
import org.eclipse.emf.ecore.xmi.impl.EcoreResourceFactoryImpl;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

/**
 * Various static helper methods for dealing with EMF meta models.
 *
 * @author Eike Stepper
 * @since 2.0
 */
public final class EMFUtil
{
  /**
   * @since 3.0
   */
  public static final String CDO_ANNOTATION_SOURCE = "http://www.eclipse.org/emf/CDO";

  /**
   * @since 3.0
   */
  public static final String CDO_ANNOTATION_KEY_PERSISTENT = "persistent";

  /**
   * @since 4.2
   */
  public static final EReference EOPERATION_EEXCEPTIONS = EcorePackage.eINSTANCE.getEOperation_EExceptions();

  /**
   * @since 4.2
   */
  public static final EReference ETYPED_ELEMENT_ETYPE = EcorePackage.eINSTANCE.getETypedElement_EType();

  /**
   * @since 4.2
   */
  public static final EReference ECLASS_ESUPER_TYPES = EcorePackage.eINSTANCE.getEClass_ESuperTypes();

  /**
   * @since 4.2
   */
  public static final EAttribute ECLASSIFIER_INSTANCE_CLASS_NAME = EcorePackage.eINSTANCE.getEClassifier_InstanceClassName();

  /**
   * @since 4.2
   */
  public static final EReference EOPERATION_EGENERIC_EXCEPTIONS = EcorePackage.eINSTANCE.getEOperation_EGenericExceptions();

  /**
   * @since 4.2
   */
  public static final EReference ETYPED_ELEMENT_EGENERIC_TYPE = EcorePackage.eINSTANCE.getETypedElement_EGenericType();

  /**
   * @since 4.2
   */
  public static final EReference ECLASS_EGENERIC_SUPER_TYPES = EcorePackage.eINSTANCE.getEClass_EGenericSuperTypes();

  /**
   * @since 4.2
   */
  public static final EAttribute ECLASSIFIER_INSTANCE_TYPE_NAME = EcorePackage.eINSTANCE.getEClassifier_InstanceTypeName();

  /**
   * @since 4.2
   * @deprecated As of 4.9 use {@link EMFPredicates#ATTRIBUTES}.
   */
  @Deprecated
  public static final org.eclipse.net4j.util.Predicate<EStructuralFeature> ATTRIBUTES = new org.eclipse.net4j.util.Predicate<EStructuralFeature>()
  {
    @Override
    public boolean apply(EStructuralFeature feature)
    {
      return feature instanceof EAttribute;
    }
  };

  /**
   * @since 4.2
   * @deprecated As of 4.9 use {@link EMFPredicates#REFERENCES}.
   */
  @Deprecated
  public static final org.eclipse.net4j.util.Predicate<EStructuralFeature> REFERENCES = new org.eclipse.net4j.util.Predicate<EStructuralFeature>()
  {
    @Override
    public boolean apply(EStructuralFeature feature)
    {
      return feature instanceof EReference;
    }
  };

  /**
   * @since 4.2
   * @deprecated As of 4.9 use {@link EMFPredicates#CONTAINER_REFERENCES}.
   */
  @Deprecated
  public static final org.eclipse.net4j.util.Predicate<EStructuralFeature> CONTAINER_REFERENCES = new org.eclipse.net4j.util.Predicate<EStructuralFeature>()
  {
    @Override
    public boolean apply(EStructuralFeature feature)
    {
      if (feature instanceof EReference)
      {
        EReference reference = (EReference)feature;
        return reference.isContainer();
      }

      return false;
    }
  };

  /**
   * @since 4.2
   * @deprecated As of 4.9 use {@link EMFPredicates#CROSS_REFERENCES}.
   */
  @Deprecated
  public static final org.eclipse.net4j.util.Predicate<EStructuralFeature> CROSS_REFERENCES = new org.eclipse.net4j.util.Predicate<EStructuralFeature>()
  {
    @Override
    public boolean apply(EStructuralFeature feature)
    {
      if (feature instanceof EReference)
      {
        EReference reference = (EReference)feature;
        return !(reference.isContainer() || reference.isContainment());
      }

      return false;
    }
  };

  /**
   * @since 4.2
   * @deprecated As of 4.9 use {@link EMFPredicates#CONTAINMENT_REFERENCES}.
   */
  @Deprecated
  public static final org.eclipse.net4j.util.Predicate<EStructuralFeature> CONTAINMENT_REFERENCES = new org.eclipse.net4j.util.Predicate<EStructuralFeature>()
  {
    @Override
    public boolean apply(EStructuralFeature feature)
    {
      if (feature instanceof EReference)
      {
        EReference reference = (EReference)feature;
        return reference.isContainment();
      }

      return false;
    }
  };

  private EMFUtil()
  {
  }

  /**
   * @since 4.2
   */
  public static URI getPositionalURI(InternalEObject internalEObject)
  {
    List<String> uriFragmentPath = new ArrayList<>();
    Resource resource;
    for (InternalEObject container = internalEObject.eInternalContainer(); (resource = internalEObject.eDirectResource()) == null
        && container != null; container = internalEObject.eInternalContainer())
    {
      String segment = getPositionalURIFragmentSegment(container, internalEObject.eContainingFeature(), internalEObject);
      uriFragmentPath.add(segment);
      internalEObject = container;
    }

    StringBuilder builder = new StringBuilder("/");
    builder.append(resource.getContents().indexOf(internalEObject));
    for (int i = uriFragmentPath.size() - 1; i >= 0; --i)
    {
      builder.append('/');
      builder.append(uriFragmentPath.get(i));
    }

    return resource.getURI().appendFragment(builder.toString());
  }

  /**
   * @since 4.2
   */
  private static String getPositionalURIFragmentSegment(EObject container, EStructuralFeature eStructuralFeature, InternalEObject eObject)
  {
    StringBuilder builder = new StringBuilder();
    builder.append('@');
    builder.append(eStructuralFeature.getName());

    if (eStructuralFeature instanceof EAttribute)
    {
      FeatureMap featureMap = (FeatureMap)container.eGet(eStructuralFeature, false);
      for (int i = 0, size = featureMap.size(); i < size; ++i)
      {
        if (featureMap.getValue(i) == eObject)
        {
          EStructuralFeature entryFeature = featureMap.getEStructuralFeature(i);
          if (entryFeature instanceof EReference && ((EReference)entryFeature).isContainment())
          {
            builder.append('.');
            builder.append(i);
            return builder.toString();
          }
        }
      }

      builder.append(".-1");
    }
    else if (eStructuralFeature.isMany())
    {
      EList<?> eList = (EList<?>)container.eGet(eStructuralFeature, false);
      int index = eList.indexOf(eObject);
      builder.append('.');
      builder.append(index);
    }

    return builder.toString();
  }

  public static EPackage getGeneratedEPackage(EPackage ePackage)
  {
    String packageURI = ePackage.getNsURI();
    if (packageURI.equals(EcorePackage.eINSTANCE.getNsURI()))
    {
      return EcorePackage.eINSTANCE;
    }

    EPackage.Registry registry = EPackage.Registry.INSTANCE;
    return registry.getEPackage(packageURI);
  }

  public static Map.Entry<String, Object>[] getSortedRegistryEntries(EPackage.Registry packageRegistry)
  {
    Set<Map.Entry<String, Object>> entries = packageRegistry.entrySet();
    @SuppressWarnings("unchecked")
    Map.Entry<String, Object>[] array = entries.toArray(new Entry[entries.size()]);
    Arrays.sort(array, new Comparator<Map.Entry<String, Object>>()
    {
      @Override
      public int compare(Map.Entry<String, Object> o1, Map.Entry<String, Object> o2)
      {
        return o1.getKey().compareTo(o2.getKey());
      }
    });

    return array;
  }

  /**
   * @since 4.6
   */
  public static EList<EAnnotation> getAnnotations(EClass eClass, String sourceURI)
  {
    EList<EAnnotation> annotations = new BasicEList<>();
    getAnnotations(eClass, sourceURI, annotations, new HashSet<EClass>());
    return annotations;
  }

  private static void getAnnotations(EClass eClass, String sourceURI, EList<EAnnotation> annotations, Set<EClass> visited)
  {
    if (visited.add(eClass))
    {
      for (EAnnotation annotation : eClass.getEAnnotations())
      {
        if (sourceURI == null || sourceURI.equals(annotation.getSource()))
        {
          annotations.add(annotation);
        }
      }

      for (EClass superType : eClass.getESuperTypes())
      {
        getAnnotations(superType, sourceURI, annotations, visited);
      }
    }
  }

  public static EPackage getTopLevelPackage(EPackage ePackage)
  {
    EPackage superPackage = ePackage.getESuperPackage();
    return superPackage == null ? ePackage : getTopLevelPackage(superPackage);
  }

  /**
   * @since 2.0
   */
  public static EPackage createEPackage(String name, String nsPrefix, String nsURI)
  {
    EPackage ePackage = EcoreFactory.eINSTANCE.createEPackage();
    ePackage.setName(name);
    ePackage.setNsPrefix(nsPrefix);
    ePackage.setNsURI(nsURI);
    return ePackage;
  }

  /**
   * @since 2.0
   */
  public static EClass createEClass(EPackage ePackage, String name, boolean isAbstract, boolean isInterface)
  {
    EClass eClass = EcoreFactory.eINSTANCE.createEClass();
    eClass.setName(name);
    eClass.setAbstract(isAbstract);
    eClass.setInterface(isInterface);
    ePackage.getEClassifiers().add(eClass);
    return eClass;
  }

  /**
   * @since 2.0
   */
  public static EAttribute createEAttribute(EClass eClass, String name, EClassifier type)
  {
    EAttribute eAttribute = EcoreFactory.eINSTANCE.createEAttribute();
    eAttribute.setName(name);
    eAttribute.setEType(type);
    eClass.getEStructuralFeatures().add(eAttribute);
    return eAttribute;
  }

  /**
   * @since 2.0
   */
  public static EReference createEReference(EClass eClass, String name, EClassifier type, boolean isRequired, boolean isMany)
  {
    EReference eReference = EcoreFactory.eINSTANCE.createEReference();
    eReference.setName(name);
    eReference.setEType(type);
    eReference.setLowerBound(isRequired ? 1 : 0);
    eReference.setUpperBound(isMany ? -1 : 0);
    eClass.getEStructuralFeatures().add(eReference);
    return eReference;
  }

  /**
   * @since 4.2
   */
  public static EClass[] getConcreteClasses(EPackage ePackage)
  {
    List<EClass> result = new ArrayList<>(0);
    for (EClassifier classifier : ePackage.getEClassifiers())
    {
      if (classifier instanceof EClass)
      {
        EClass eClass = (EClass)classifier;
        if (!eClass.isAbstract() && !eClass.isInterface())
        {
          result.add(eClass);
        }
      }
    }

    return result.toArray(new EClass[result.size()]);
  }

  public static EClass[] getPersistentClasses(EPackage ePackage)
  {
    List<EClass> result = new ArrayList<>();
    for (EClassifier classifier : ePackage.getEClassifiers())
    {
      if (classifier instanceof EClass)
      {
        result.add((EClass)classifier);
      }
    }

    return result.toArray(new EClass[result.size()]);
  }

  /**
   * @since 3.0
   * @deprecated This method is expensive and will be removed in the future.
   * @see #isPersistent(EStructuralFeature)
   */
  @Deprecated
  public static List<EStructuralFeature> getPersistentFeatures(EList<EStructuralFeature> eFeatures)
  {
    List<EStructuralFeature> result = new ArrayList<>();
    for (EStructuralFeature feature : eFeatures)
    {
      if (isPersistent(feature))
      {
        result.add(feature);
      }
    }

    return result;
  }

  /**
   * Returns <code>true</code> if CDO considers the given feature <i>persistent</i>, <code>false</code> otherwise.
   * <p>
   * Note that CDO <i>persistent</i> is not identical to {@link EStructuralFeature#isTransient() non-transient} because that can be
   * overridden with {@link #CDO_ANNOTATION_KEY_PERSISTENT}. Another reason for possible deviations is that CDO considers transient
   * {@link EReference references} <i>persistent</i> if they have a <i>persistent</i> {@link EReference#getEOpposite() opposite}.
   * <p>
   * Note also that the checks for the aforementioned deviations from {@link EStructuralFeature#isTransient()} make this method somewhat
   * expensive. Whenever possible {@link CDOClassInfo#isPersistent(int) CDOClassInfo.isPersistent()} should be called instead.
   *
   * @since 3.0
   */
  public static boolean isPersistent(EStructuralFeature feature)
  {
    if (feature == ECLASS_ESUPER_TYPES || feature == ETYPED_ELEMENT_ETYPE || feature == EOPERATION_EEXCEPTIONS || feature == ECLASSIFIER_INSTANCE_CLASS_NAME)
    {
      // http://www.eclipse.org/newsportal/article.php?id=26780&group=eclipse.tools.emf#26780
      return false;
    }

    String persistent = EcoreUtil.getAnnotation(feature, CDO_ANNOTATION_SOURCE, CDO_ANNOTATION_KEY_PERSISTENT);
    if (persistent != null)
    {
      return "true".equalsIgnoreCase(persistent);
    }

    if (feature.isTransient())
    {
      // Bug 333950: Transient eRefs with a persistent eOpposite, must be considered persistent
      if (feature instanceof EReference)
      {
        EReference eOpposite = ((EReference)feature).getEOpposite();
        if (eOpposite != null && !eOpposite.isTransient())
        {
          return true;
        }
      }

      return false;
    }

    return true;
  }

  public static boolean isDynamicEPackage(Object value)
  {
    return value.getClass() == EPackageImpl.class;
  }

  public static String getParentURI(EPackage ePackage)
  {
    EPackage superPackage = ePackage.getESuperPackage();
    String parentURI = superPackage == null ? null : superPackage.getNsURI();
    return parentURI;
  }

  public static void registerPackage(EPackage ePackage, EPackage.Registry... packageRegistries)
  {
    ePackage.getClass(); // Initialize package in standalone mode
    if (packageRegistries == null || packageRegistries.length == 0)
    {
      EPackage.Registry[] globalRegistry = { EPackage.Registry.INSTANCE };
      packageRegistries = globalRegistry;
    }

    for (EPackage.Registry packageRegistry : packageRegistries)
    {
      packageRegistry.put(ePackage.getNsURI(), ePackage);
    }
  }

  public static byte[] getEPackageBytes(EPackage ePackage, boolean zipped, EPackage.Registry packageRegistry)
  {
    try
    {
      // The package may be nested in other content (e.g., a UML Profile).
      // Or, maybe it is just a dynamic package that was not loaded from a resource
      Resource resource = ((InternalEObject)ePackage).eDirectResource();
      if (resource == null)
      {
        ResourceSet resourceSet = newEcoreResourceSet(packageRegistry);
        resource = resourceSet.createResource(URI.createURI(ePackage.getNsURI()));

        // If the package is nested in some container, then copy it into the temporary
        // resource so that we don't send content that the server doesn't need
        resource.getContents().add(ePackage.eContainer() == null ? ePackage : EcoreUtil.copy(ePackage));
      }

      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      resource.save(baos, createResourceOptions(zipped));
      return baos.toByteArray();
    }
    catch (Exception ex)
    {
      throw WrappedException.wrap(ex);
    }
  }

  /**
   * @since 3.0
   */
  public static EPackage createEPackage(String uri, byte[] bytes, boolean zipped, ResourceSet resourceSet, boolean lookForResource)
  {
    try
    {
      Resource resource = null;
      if (lookForResource)
      {
        resource = resourceSet.getResource(URI.createURI(uri), true);
      }

      if (resource == null)
      {
        resource = resourceSet.createResource(URI.createURI(uri));
      }

      ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
      resource.load(bais, createResourceOptions(zipped));

      EList<EObject> contents = resource.getContents();
      return (EPackage)contents.get(0);
    }
    catch (Exception ex)
    {
      throw WrappedException.wrap(ex);
    }
  }

  private static Map<String, Object> createResourceOptions(boolean zipped)
  {
    Map<String, Object> options = new HashMap<>();
    if (zipped)
    {
      options.put(Resource.OPTION_ZIP, true);
    }

    return options;
  }

  /**
   * @since 4.2
   */
  public static <T> T getAdapter(Notifier notifier, Class<T> type)
  {
    @SuppressWarnings("unchecked")
    T adapter = (T)EcoreUtil.getAdapter(notifier.eAdapters(), type);
    return adapter;
  }

  public static void addAdapter(Notifier notifier, Adapter adapter)
  {
    synchronized (notifier)
    {
      EList<Adapter> adapters = notifier.eAdapters();
      if (!adapters.contains(adapter))
      {
        adapters.add(adapter);
      }
    }
  }

  public static EPackage[] getAllPackages(EPackage ePackage)
  {
    List<EPackage> result = new ArrayList<>();
    getAllPackages(ePackage, result);
    return result.toArray(new EPackage[result.size()]);
  }

  private static void getAllPackages(EPackage ePackage, List<EPackage> result)
  {
    result.add(ePackage);
    for (EPackage subPackage : ePackage.getESubpackages())
    {
      getAllPackages(subPackage, result);
    }
  }

  public static String getQualifiedName(EPackage ePackage, String separator)
  {
    StringBuilder builder = new StringBuilder();
    EPackage eSuperPackage = ePackage.getESuperPackage();
    if (eSuperPackage != null)
    {
      builder.append(getQualifiedName(eSuperPackage, separator));
      builder.append(separator);
    }

    builder.append(ePackage.getName());
    return builder.toString();
  }

  public static String getQualifiedName(EClassifier classifier, String separator)
  {
    StringBuilder builder = new StringBuilder();
    EPackage ePackage = classifier.getEPackage();
    if (ePackage != null)
    {
      builder.append(getQualifiedName(ePackage, separator));
      builder.append(separator);
    }

    builder.append(classifier.getName());
    return builder.toString();
  }

  public static ResourceSet newResourceSet(Resource.Factory resourceFactory)
  {
    ResourceSet resourceSet = new ResourceSetImpl();
    resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("*", resourceFactory); //$NON-NLS-1$
    return resourceSet;
  }

  public static ResourceSet newEcoreResourceSet(EPackage.Registry packageRegistry)
  {
    ResourceSet resourceSet = newResourceSet(new EcoreResourceFactoryImpl());
    resourceSet.setPackageRegistry(packageRegistry);
    return resourceSet;
  }

  public static ResourceSet newEcoreResourceSet()
  {
    return newEcoreResourceSet(EPackage.Registry.INSTANCE);
  }

  /**
   * @since 3.0
   */
  public static EObject safeResolve(EObject proxy, ResourceSet resourceSet)
  {
    if (!proxy.eIsProxy())
    {
      return proxy;
    }

    EObject resolved = EcoreUtil.resolve(proxy, resourceSet);
    if (resolved == proxy)
    {
      throw new IllegalStateException("Unresolvable proxy: " + ((InternalEObject)proxy).eProxyURI());
    }

    return resolved;
  }

  /**
   * @since 3.0
   */
  public static void safeResolveAll(ResourceSet resourceSet)
  {
    TreeIterator<Notifier> it = resourceSet.getAllContents();
    while (it.hasNext())
    {
      Notifier notifier = it.next();
      if (notifier instanceof EObject)
      {
        safeResolve((EObject)notifier, resourceSet);

        if (notifier instanceof EAnnotation)
        {
          // we don't need to validate the structure of annotations. The applications that
          // define annotations will have to take what they can get
          it.prune();
        }
        else
        {
          Iterator<EObject> it2 = ((EObject)notifier).eCrossReferences().iterator();
          while (it2.hasNext())
          {
            safeResolve(it2.next(), resourceSet);
          }
        }
      }
    }
  }

  /**
   * @see ExtResourceSet
   * @since 4.0
   */
  public static ExtResourceSet createExtResourceSet(InternalCDOPackageRegistry packageRegistry, boolean delegating, boolean demandLoading)
  {
    Resource.Factory resourceFactory = new EcoreResourceFactoryImpl();

    ExtResourceSet resourceSet = new ExtResourceSet(delegating, demandLoading);
    resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("*", resourceFactory); //$NON-NLS-1$
    resourceSet.setPackageRegistry(packageRegistry);
    return resourceSet;
  }

  /**
   * An extension of {@link ResourceSetImpl} that allows demandLoading of resources and delegation of resource lookups,
   * to be switched on/off as desired.
   *
   * @since 4.0
   */
  public static class ExtResourceSet extends ResourceSetImpl
  {
    private boolean delegating;

    private boolean demandLoading;

    /**
     * @since 4.7
     */
    public ExtResourceSet(boolean delegating, boolean demandLoading)
    {
      this.delegating = delegating;
      this.demandLoading = demandLoading;
    }

    public boolean isDelegating()
    {
      return delegating;
    }

    public void setDelegating(boolean delegating)
    {
      this.delegating = delegating;
    }

    public boolean isDemandLoading()
    {
      return demandLoading;
    }

    public void setDemandLoading(boolean demandLoading)
    {
      this.demandLoading = demandLoading;
    }

    @Override
    protected void demandLoad(Resource resource) throws IOException
    {
      if (demandLoading)
      {
        super.demandLoad(resource);
      }
    }

    @Override
    protected Resource delegatedGetResource(URI uri, boolean loadOnDemand)
    {
      if (delegating)
      {
        return super.delegatedGetResource(uri, loadOnDemand);
      }

      return null;
    }
  }
}

Back to the top