Java Code Examples for org.eclipse.emf.ecore.resource.Resource#getEObject()

The following examples show how to use org.eclipse.emf.ecore.resource.Resource#getEObject() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SCTResourceTest.java    From statecharts with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testFragments() throws Exception {
	SCTUnitTestModels models = new SCTUnitTestModels();
	List<Statechart> originalStatecharts = models.loadAllStatecharts();
	List<Statechart> targetStatecharts = models.loadAllStatecharts();
	for (int i = 0; i < originalStatecharts.size(); i++) {
		Statechart statechart = originalStatecharts.get(i);
		Statechart targetStatechart = targetStatecharts.get(i);
		Resource targetResource = targetStatechart.eResource();
		assertTrue(statechart != targetStatechart);
		assertTrue(EcoreUtil.equals(statechart, targetStatechart));
		TreeIterator<EObject> allContents = EcoreUtil.getAllContents(statechart.eResource(), true);
		while (allContents.hasNext()) {
			EObject next = allContents.next();
			String fragment = EcoreUtil.getURI(next).fragment();
			EObject targetObject = targetResource.getEObject(fragment);
			assertNotNull("Could not resolve fragment " + fragment + " for EObject " + next + "in statechart "
					+ statechart.getName(), targetObject);
			assertTrue(EcoreUtil.equals(next, targetObject));
		}
	}
}
 
Example 2
Source File: N4JSDocHelper.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Same as {@link #getDoc(EObject)}, but will never change the containing resource of the given element.
 * <p>
 * If the containing resource of the given element is not fully loaded (i.e. AST not loaded yet because only the
 * TModule was loaded from the Xtext index), then the given resource set will be used to load the resource, then the
 * corresponding EObject for element will be searched in that temporary resource, and the documentation will be
 * retrieved from there.
 */
public String getDocSafely(ResourceSet resourceSetForDocRetrieval, EObject element) {
	if (resourceSetForDocRetrieval == null)
		throw new IllegalArgumentException("resourceSetForDocRetrieval may not be null");
	if (element == null || element.eIsProxy())
		throw new IllegalArgumentException("element may not be null or a proxy");
	final Resource res = element.eResource();
	final ResourceSet resSet = res != null ? res.getResourceSet() : null;
	if (resSet == null || res == null)
		throw new IllegalArgumentException("element must be contained in a resource set");
	if (resourceSetForDocRetrieval != resSet) {
		final Resource resSafe = resourceSetForDocRetrieval.getResource(res.getURI(), true);
		final EObject elementSafe = resSafe.getEObject(res.getURIFragment(element));
		return elementSafe != null ? getDoc(elementSafe) : null;
	} else {
		return getDoc(element);
	}
}
 
Example 3
Source File: ResourceLifecycleManager.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
public Resource openAndApplyReferences(ResourceSet resourceSet, RelatedResource toLoad) {
	Resource resource = resourceSet.getResource(toLoad.getUri(), true);
	for (IReferenceSnapshot desc : toLoad.outgoingReferences) {
		EObject source = resource.getEObject(desc.getSourceEObjectUri().fragment());
		EObject target = desc.getTarget().getObject();
		EReference reference = desc.getEReference();
		if (reference.isMany()) {
			@SuppressWarnings("unchecked")
			List<Object> list = (EList<Object>) source.eGet(reference, false);
			list.set(desc.getIndexInList(), target);
		} else {
			source.eSet(reference, target);
		}
	}
	return resource;
}
 
Example 4
Source File: ElementIssueProvider.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
public void attachData(Resource resource) {
	if (findDataAdapter(resource) != null) {
		return;
	}
	List<Issue> issues = collectIssues(resource);
	Data adapter = new Data();
	for (Issue issue : issues) {
		URI uriToProblem = issue.getUriToProblem();
		if (uriToProblem != null && uriToProblem.trimFragment().equals(resource.getURI())) {
			EObject erroneousElement = resource.getEObject(uriToProblem.fragment());
			adapter.addIssue(erroneousElement, issue);
			for(EObject jvmElement: associations.getJvmElements(erroneousElement)) {
				adapter.addIssue(jvmElement, issue);
			}
		}
	}
	resource.eAdapters().add(adapter);
}
 
Example 5
Source File: ReferenceAcceptor.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected void computeExportedObjectsMap(EObject source) {
	Resource resource = source.eResource();
	IResourceServiceProvider resourceServiceProvider = resourceServiceProviderRegistry
			.getResourceServiceProvider(resource.getURI());
	if (resourceServiceProvider != null) {
		exportedContainersInCurrentResource = new HashMap<>();
		Iterable<IEObjectDescription> exportedObjects = resourceServiceProvider.getResourceDescriptionManager()
				.getResourceDescription(resource).getExportedObjects();
		for (IEObjectDescription description : exportedObjects) {
			EObject instance = description.getEObjectOrProxy();
			if (instance.eIsProxy()) {
				instance = resource.getEObject(description.getEObjectURI().fragment());
			}
			exportedContainersInCurrentResource.put(instance, description.getEObjectURI());
		}
	} else {
		exportedContainersInCurrentResource = Collections.emptyMap();
	}
}
 
Example 6
Source File: DiagramEditorInputFactory.java    From statecharts with Eclipse Public License 1.0 6 votes vote down vote up
public IAdaptable createElement(IMemento memento) {
	String uriStr = memento.getString(EMF_URI);
	if (uriStr == null) {
		return null;
	}
	URI uri = URI.createURI(uriStr);
	ResourceSet resourceSet = DiagramPartitioningUtil.getSharedDomain().getResourceSet();
	Resource resource = resourceSet.getResource(uri, false);
	if (resource == null)
		resource = resourceSet.createResource(uri);
	try {
		resource.load(Collections.emptyMap());
	} catch (IOException e) {
		e.printStackTrace();
	}
	Diagram diagram = (Diagram) resource.getEObject(uri.fragment());
	return new DiagramEditorInput(diagram);
}
 
Example 7
Source File: XtextGrammarRefactoringIntegrationTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testRefactorXtextGrammarWithGeneratedClassifier() throws Exception {
	ResourceSet rs = resourceSetProvider.get();
	Resource ecoreResource = createEcoreModel(rs, ecoreURI, initialModelRoot);
	final EClass greetingClass = getGreetingClass(ecoreResource);
	final EReference greetingRef = getReferenceoGreeting(ecoreResource, greetingClass);
	String greetingClassFragment = EcoreUtil.getURI(greetingClass).fragment();
	String greetingRefFragment = EcoreUtil.getURI(greetingRef).fragment();
	ecoreResource.unload();
	waitForBuild();
	final XtextEditor editor = openEditor(grammarFile);
	doRefactoring(editor);
	waitForBuild();
	checkConsistenceOfGrammar(editor);
	ecoreResource.load(null);
	assertEquals(REFACTOREDCLASSIFIERNAME, SimpleAttributeResolver.NAME_RESOLVER.apply(ecoreResource
			.getEObject(greetingClassFragment.replaceFirst(CLASSIFIERNAME, REFACTOREDCLASSIFIERNAME))));
	EReference greetingReference = (EReference) ecoreResource.getEObject(greetingRefFragment);
	EClassifier eType = greetingReference.getEType();
	assertFalse(eType.eIsProxy());
	assertEquals(REFACTOREDCLASSIFIERNAME, eType.getName());
}
 
Example 8
Source File: DotReferenceFinder.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Using the @Override notation leads to a compile error on some (e.g NEON,
 * OXYGEN, PHOTON, ...) platforms, since this internal Xtext API has been
 * changed over time.
 *
 * see
 * https://github.com/eclipse/xtext-core/commit/69064ac12f0144b60d8c7511d41c834db44a67f2
 *
 * This method will be invoked on ...LUNA, MARS, platforms
 */
public void findReferences(TargetURIs targetURIs, Resource resource,
		Acceptor acceptor, IProgressMonitor monitor) {
	// add DOT specific references
	for (URI targetURI : targetURIs) {
		EObject target = resource.getEObject(targetURI.fragment());
		// currently, only a selection of a nodeId is supported
		if (target instanceof NodeId) {
			acceptor.accept(target, targetURI, null, -1, target, targetURI);
			NodeId selectedNodeId = (NodeId) target;
			for (NodeId source : DotAstHelper
					.getAllNodeIds(selectedNodeId)) {
				URI sourceURI = EcoreUtil2
						.getPlatformResourceOrNormalizedURI(source);
				acceptor.accept(source, sourceURI, null, -1, target,
						targetURI);
			}
		}
	}
}
 
Example 9
Source File: AbstractTypeProviderTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected void getAndResolveAllFragments(Resource resource) {
	Iterator<EObject> iter = EcoreUtil.getAllContents(resource, false);
	while (iter.hasNext()) {
		EObject next = iter.next();
		String fragment = resource.getURIFragment(next);
		EObject resolved = resource.getEObject(fragment);
		assertSame(fragment + " / " + next.eClass().getName(), next, resolved);
	}
}
 
Example 10
Source File: SerializationExtensions.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T extends ENamedElement> T readEcoreElement(ObjectInput in) throws IOException {
	URI uri = readURI(in);
	EPackage ePackage = EPackage.Registry.INSTANCE.getEPackage(uri.trimFragment().toString());
	if (ePackage == null)
		return null;
	Resource eResource = ePackage.eResource();
	if (eResource == null)
		return null;
	return (T) eResource.getEObject(uri.fragment());
}
 
Example 11
Source File: DiagramEditorProvider.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
private EObject retrieveElementInURIForFragment(final URI uri, final String fragment) {
    final ResourceSet resourceSet = new ResourceSetImpl();
    final Resource resource = resourceSet.getResource(uri, true);
    try {
        resource.load(null);
    } catch (final IOException e) {
        BonitaStudioLog.error(e);
    }
    final EObject eObject = resource.getEObject(fragment);
    return eObject;
}
 
Example 12
Source File: DefaultReferenceFinder.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Deprecated
protected Map<EObject, URI> createExportedElementsMap(final Resource resource) {
	return new ForwardingMap<EObject, URI>() {

		private Map<EObject, URI> delegate;
		
		@Override
		protected Map<EObject, URI> delegate() {
			if (delegate != null) {
				return delegate;
			}
			URI uri = EcoreUtil2.getPlatformResourceOrNormalizedURI(resource);
			IResourceServiceProvider resourceServiceProvider = getServiceProviderRegistry().getResourceServiceProvider(uri);
			if (resourceServiceProvider == null) {
				return delegate = Collections.emptyMap();
			}
			IResourceDescription.Manager resourceDescriptionManager = resourceServiceProvider.getResourceDescriptionManager();
			if (resourceDescriptionManager == null) {
				return delegate = Collections.emptyMap();
			}
			IResourceDescription resourceDescription = resourceDescriptionManager.getResourceDescription(resource);
			Map<EObject, URI> exportedElementMap = newIdentityHashMap();
			if (resourceDescription != null) {
				for (IEObjectDescription exportedEObjectDescription : resourceDescription.getExportedObjects()) {
					EObject eObject = resource.getEObject(exportedEObjectDescription.getEObjectURI().fragment());
					if (eObject != null)
						exportedElementMap.put(eObject, exportedEObjectDescription.getEObjectURI());
				}
			}
			return delegate = exportedElementMap;
		}

		
	};
}
 
Example 13
Source File: ProjectStatePersister.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private ENamedElement readEcoreElement(DataInput input) throws IOException {
	URI uri = URI.createURI(input.readUTF());
	EPackage ePackage = EPackage.Registry.INSTANCE.getEPackage(uri.trimFragment().toString());
	if (ePackage != null) {
		Resource resource = ePackage.eResource();
		return (ENamedElement) resource.getEObject(uri.fragment());
	}
	return null;
}
 
Example 14
Source File: ClasspathTypeProvider.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
public JvmType findTypeByClass(BinaryClass clazz, Resource resource) {
	// TODO: Maybe iterate the resource without computing a fragment
	String fragment = clazz.getURIFragment();
	JvmType result = (JvmType) resource.getEObject(fragment);
	if (result == null) {
		throw new IllegalStateException("Resource has not been loaded");
	} 
	return result;
}
 
Example 15
Source File: AbstractTypeProviderTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected void getAndResolveAllFragments(Resource resource) {
	Iterator<EObject> iter = EcoreUtil.getAllContents(resource, false);
	while (iter.hasNext()) {
		EObject next = iter.next();
		String fragment = resource.getURIFragment(next);
		EObject resolved = resource.getEObject(fragment);
		assertSame(fragment + " / " + next.eClass().getName(), next, resolved);
	}
}
 
Example 16
Source File: AbstractTypeProviderTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected void getAndResolveAllFragments(Resource resource) {
	Iterator<EObject> iter = EcoreUtil.getAllContents(resource, false);
	while (iter.hasNext()) {
		EObject next = iter.next();
		String fragment = resource.getURIFragment(next);
		EObject resolved = resource.getEObject(fragment);
		assertSame(fragment + " / " + next.eClass().getName(), next, resolved);
	}
}
 
Example 17
Source File: UserDataAwareScope.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@link EcoreUtil#resolve(EObject, EObject)} pretty much does the same thing but will eagerly load the resource.
 * We are happy with the content that we just put into it.
 */
private EObject resolveObject(URI objectURI, Resource resource) {
	if (resource.isLoaded())
		throw new IllegalStateException("Should not be loaded beforehand");
	EObject result = resource.getEObject(objectURI.fragment());
	if (resource.isLoaded())
		throw new IllegalStateException("Should not be loaded due to fragment traversal");
	return result;
}
 
Example 18
Source File: XtextGrammarRefactoringIntegrationTest.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testRefactorXtextGrammarWithGeneratedClassifierAndModelWithRefToClassifier() throws Exception {
	ResourceSet rs = resourceSetProvider.get();
	EcoreFactory eInstance = EcoreFactory.eINSTANCE;
	Resource ecoreModelResource = createEcoreModel(rs, ecoreURI, initialModelRoot);
	EClass greetingClass = getGreetingClass(ecoreModelResource);
	EReference greetingRefLocal = getReferenceoGreeting(ecoreModelResource, greetingClass);
	String greetingClassFragment = EcoreUtil.getURI(greetingClass).fragment();
	String greetingRefFragment = EcoreUtil.getURI(greetingRefLocal).fragment();

	EPackage refPackage = eInstance.createEPackage();
	refPackage.setName("myDsl2");
	refPackage.setNsPrefix("myDsl2");
	refPackage.setNsURI("http://testrefactoring2");
	EClass modelRefClass = eInstance.createEClass();
	refPackage.getEClassifiers().add(modelRefClass);
	modelRefClass.setName("ModelRef");
	EReference reference = eInstance.createEReference();
	reference.setName("ref");
	reference.setLowerBound(0);
	reference.setUpperBound(-1);
	reference.setEType(greetingClass);
	modelRefClass.getEStructuralFeatures().add(reference);
	Resource refToGreetingResource = createEcoreModel(rs,
			URI.createPlatformResourceURI(TEST_PROJECT + "/src/org/xtext/example/mydsl/" + "MyDsl2.ecore", true),
			refPackage);
	refToGreetingResource.unload();
	ecoreModelResource.unload();
	waitForBuild();
	waitForDisplay();
	XtextEditor editor = openEditor(grammarFile);
	doRefactoring(editor);
	waitForBuild();
	checkConsistenceOfGrammar(editor);
	ecoreModelResource.load(null);
	String renamedGreetingClassFragment = greetingClassFragment.replaceFirst(CLASSIFIERNAME, REFACTOREDCLASSIFIERNAME);
	EObject renamedGreetingClass = ecoreModelResource.getEObject(renamedGreetingClassFragment);
	assertNotNull(renamedGreetingClass);
	assertEquals(REFACTOREDCLASSIFIERNAME, SimpleAttributeResolver.NAME_RESOLVER.apply(renamedGreetingClass));
	EReference greetingReference = (EReference) ecoreModelResource.getEObject(greetingRefFragment);
	EClassifier eType = greetingReference.getEType();
	assertFalse(eType.eIsProxy());
	assertEquals(REFACTOREDCLASSIFIERNAME, eType.getName());

	refToGreetingResource.load(null);
	EReference externalReferenceToGreeting = getReferenceoGreeting(refToGreetingResource, eType);
	assertFalse(externalReferenceToGreeting.getEType().eIsProxy());
	assertEquals(REFACTOREDCLASSIFIERNAME, externalReferenceToGreeting.getEType().getName());

}
 
Example 19
Source File: ResourceSetReferencingResourceSetImpl.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public EObject getEObject(URI uri, boolean loadOnDemand) {
	Resource resource = getResource(uri.trimFragment(), loadOnDemand);
	return resource.getEObject(uri.fragment());
}
 
Example 20
Source File: EMFGeneratorFragment2.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
protected GenModel getGenModel(final ResourceSet rs, final Grammar grammar) {
  try {
    final URI genModelUri = this.getGenModelUri(grammar);
    final Resource resource = rs.getResource(genModelUri, false);
    if ((resource != null)) {
      resource.unload();
      rs.getResources().remove(resource);
    }
    final Resource genModelFile = rs.createResource(genModelUri, ContentHandler.UNSPECIFIED_CONTENT_TYPE);
    GenModel genModel = null;
    boolean _exists = rs.getURIConverter().exists(genModelUri, null);
    if (_exists) {
      genModelFile.load(null);
      boolean _hasFragment = genModelUri.hasFragment();
      if (_hasFragment) {
        EObject _eObject = genModelFile.getEObject(genModelUri.fragment());
        genModel = ((GenModel) _eObject);
      } else {
        EObject _head = IterableExtensions.<EObject>head(genModelFile.getContents());
        genModel = ((GenModel) _head);
      }
    } else {
      genModel = new GenModelImpl() {
        @Override
        public GenPackage createGenPackage() {
          return new GenPackageImpl() {
            @Override
            public String getSerializedPackageFilename() {
              String _name = this.getName();
              return (_name + ".loadinitialization_ecore");
            }
          };
        }
      };
      genModel.setModelName(this.getModelName(grammar));
      genModel.setModelPluginID(this.getModelPluginID());
      genModel.setModelDirectory(this.getJavaModelDirectory());
      if (this.generateEdit) {
        genModel.setEditPluginID(this.getEditPluginID());
        genModel.setEditDirectory(this.getEditDirectory());
      }
      if (this.generateEditor) {
        genModel.setEditorPluginID(this.getEditorPluginID());
        genModel.setEditorDirectory(this.getEditorDirectory());
      }
      genModel.setValidateModel(false);
      genModel.setForceOverwrite(true);
      genModel.setFacadeHelperClass(null);
      genModel.setBundleManifest(true);
      genModel.setUpdateClasspath(false);
      genModel.setComplianceLevel(this.jdkLevel);
      genModel.setRuntimeVersion(this.emfRuntimeVersion);
      genModel.setRootExtendsClass(this.rootExtendsClass);
      genModel.setLineDelimiter(this.codeConfig.getLineDelimiter());
      String _fileHeader = this.codeConfig.getFileHeader();
      boolean _tripleNotEquals = (_fileHeader != null);
      if (_tripleNotEquals) {
        genModel.setCopyrightText(this.trimMultiLineComment(this.codeConfig.getFileHeader()));
      }
    }
    genModelFile.getContents().add(genModel);
    return genModel;
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}