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

The following examples show how to use org.eclipse.emf.ecore.resource.Resource#getContents() . 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
/**
 * {@inheritDoc}
 * <p>
 * Registers all EPackages (transitively) referenced by registered GenModels prior to calling {@link LanguageConfig#setUri(String)}.
 */
@Override
public void setUri(final String uri) {
  ResourceSet rs = new ResourceSetImpl();
  Set<URI> result = Sets.newHashSet();
  @SuppressWarnings("deprecation")
  Map<String, URI> genModelLocationMap = EcorePlugin.getEPackageNsURIToGenModelLocationMap();
  for (Map.Entry<String, URI> entry : genModelLocationMap.entrySet()) {
    Resource resource = GenModelAccess.getGenModelResource(null, entry.getKey(), rs);
    if (resource != null) {
      for (EObject model : resource.getContents()) {
        if (model instanceof GenModel) {
          GenModel genModel = (GenModel) model;
          result.addAll(getReferencedEPackages(genModel));
        }
      }
    }
  }
  for (URI u : result) {
    addLoadedResource(u.toString());
  }
  super.setUri(uri);
}
 
Example 2
Source Project: neoscada   File: ModelLoader.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public T load ( final URI uri, final String contentTypeId ) throws IOException
{
    final ResourceSet rs = new ResourceSetImpl ();
    final Resource r = rs.createResource ( uri, contentTypeId );
    r.load ( null );

    for ( final Object o : r.getContents () )
    {
        if ( this.clazz.isAssignableFrom ( o.getClass () ) )
        {
            return this.clazz.cast ( o );
        }
    }

    throw new IllegalStateException ( String.format ( "Model %s does not contain an object of type %s", uri, this.clazz ) );
}
 
Example 3
@SuppressWarnings("rawtypes")
public void loadEcore(String name, InputStream inputStream) {
       ResourceSet resourceSet = new ResourceSetImpl();
       resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("ecore", new EcoreResourceFactoryImpl());
       Resource resource = resourceSet.createResource(URI.createURI(name));
       try {
		resource.load(inputStream, new HashMap());
		for (EObject eObject : resource.getContents()) {
			if (eObject instanceof EPackage) {
				EPackage ePackage = (EPackage)eObject;
				addEPackage(ePackage);
			}
		}
	} catch (IOException e) {
		LOGGER.error("", e);
	}
}
 
Example 4
/**
* @generated
*/
private static IEditorInput getEditorInput(Diagram diagram) {
	Resource diagramResource = diagram.eResource();
	for (EObject nextEObject : diagramResource.getContents()) {
		if (nextEObject == diagram) {
			return new FileEditorInput(WorkspaceSynchronizer.getFile(diagramResource));
		}
		if (nextEObject instanceof Diagram) {
			break;
		}
	}
	URI uri = EcoreUtil.getURI(diagram);
	String editorName = uri.lastSegment() + '#' + diagram.eResource().getContents().indexOf(diagram);
	IEditorInput editorInput = new URIEditorInput(uri, editorName);
	return editorInput;
}
 
Example 5
Source Project: n4js   File: CFGraphProvider.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/** Searches the script node in the given input. */
private Script findScript(Object input) {
	if (input instanceof ResourceSet) {
		ResourceSet rs = (ResourceSet) input;
		if (!rs.getResources().isEmpty()) {
			Resource res = rs.getResources().get(0);
			EList<EObject> contents = res.getContents();
			if (!contents.isEmpty()) {
				Script script = EcoreUtil2.getContainerOfType(contents.get(0), Script.class);
				return script;
			}
		}
	}
	return null;
}
 
Example 6
@Override
public void afterGenerate(Resource input, IFileSystemAccess2 fsa, IGeneratorContext context) {
	final IExtraLanguageGeneratorContext generatorContext = createGeneratorContext(fsa, context, input);
	final EList<EObject> contents = input.getContents();
	for (final EObject obj : contents) {
		if (canGenerateFor(obj)) {
			final Iterator<EObject> iterator = EcoreUtil.getAllContents(obj, false);
			while (iterator.hasNext()) {
				final EObject subobj = iterator.next();
				after(subobj, generatorContext);
			}
			after(obj, generatorContext);
		}
	}
}
 
Example 7
@Override
public IResolvedTypes resolveTypes(/* @NonNull */ Resource resource, /* @Nullable */ CancelIndicator monitor) {
	validateResourceState(resource);
	List<EObject> resourceContents = resource.getContents();
	if (resourceContents.isEmpty()) {
		IFeatureScopeSession session = scopeProvider.newSession(resource);
		return new EmptyResolvedTypes(session, featureScopes, new StandardTypeReferenceOwner(services, resource));
	} else {
		return resolveTypes(resourceContents.get(0), monitor);
	}
}
 
Example 8
@Override
public EObject getEObject(Resource resource, String fragment, IFragmentProvider.Fallback fallback) {
	if (!fragment.startsWith(PREFIX))
		return fallback.getEObject(fragment);
	String fragmentWithoutPrefix = fragment.substring(PREFIX.length());
	List<String> splitted = Strings.split(fragmentWithoutPrefix, '/');
	if (splitted.isEmpty()) {
		return fallback.getEObject(fragment);
	}
	String firstPart = splitted.get(0);
	Grammar grammar = null;
	for(EObject content: resource.getContents()) {
		if (content instanceof Grammar) {
			Grammar g = (Grammar) content;
			if (firstPart.equals(g.getName())) {
				grammar = g;
				if (splitted.size() == 1)
					return grammar;
				break;
			}
		}
	}
	if (splitted.size() == 2) {
		return GrammarUtil.findRuleForName(grammar, splitted.get(1));
	} else {
		return fallback.getEObject(fragment);
	}
}
 
Example 9
@Override
protected ISelectable internalGetAllDescriptions(final Resource resource) {
	List<IEObjectDescription> descriptions = Lists.newArrayList();
	for (EObject content: resource.getContents()) {
		if (content instanceof JvmDeclaredType) {
			JvmDeclaredType type = (JvmDeclaredType) content;
			if (!Strings.isEmpty(type.getIdentifier())) {
				doGetAllDescriptions(type, descriptions);
			}
		}
	}
	return new MultimapBasedSelectable(descriptions);
}
 
Example 10
public Diagram getDiagramCopy(Diagram diagram) {
	Resource resource = reload(WorkspaceSynchronizer.getFile(diagram.eResource()));
	EList<EObject> contents = resource.getContents();
	for (EObject eObject : contents) {
		if (EcoreUtil.getURI(diagram).equals(EcoreUtil.getURI(eObject)))
			return (Diagram) eObject;
	}
	// Fall back return the first diagram
	return (Diagram) resource.getContents().get(1);
}
 
Example 11
public Operation_Compare loadConditionExpression(final String comparisonExpression, final EObject context) throws ComparisonExpressionLoadException {
    final Resource resource = loadResource(comparisonExpression, context);
    final EList<EObject> contents = resource.getContents();
    if (contents.isEmpty()) {
        throw new ComparisonExpressionLoadException("Failed to load comparison expression " + comparisonExpression);
    }
    if (context != null && context.eResource() != null) {
        return resolveProxies(resource, context.eResource().getResourceSet());
    }
    return (Operation_Compare) contents.get(0);
}
 
Example 12
protected void findLocalReferencesInResource(final Predicate<URI> targetURIs, Resource resource,
		final IAcceptor<IReferenceDescription> acceptor) {
	Map<EObject, URI> exportedElementsMap = createExportedElementsMap(resource);
	for(EObject content: resource.getContents()) {
		findLocalReferencesFromElement(targetURIs, content, resource, acceptor, null, exportedElementsMap);
	}
}
 
Example 13
protected void diagnose(EObject object, String... expectedUnresolvedProxies) {
	Resource resource = object.eResource();
	for (EObject content : resource.getContents()) {
		Diagnostic diagnostic = diagnostician.validate(content);
		if (diagnostic.getSeverity() != Diagnostic.OK) {
			URI[] expectedUnresolvedProxyURIs = new URI[expectedUnresolvedProxies.length];
			for (int i = 0; i < expectedUnresolvedProxies.length; i++) {
				expectedUnresolvedProxyURIs[i] = URI.createURI(expectedUnresolvedProxies[i]);
			}
			diagnose(diagnostic, expectedUnresolvedProxyURIs);
		}

	}
}
 
Example 14
private Report getReportFromEditor(final IEditorPart editorPart) {
    if (editorPart instanceof DiagramEditor) {
        final Resource resource = ((DiagramEditor) editorPart).getDiagramEditPart().getNotationView().eResource();
        if (resource != null) {
            for (final EObject r : resource.getContents()) {
                if (r instanceof Report) {
                    return (Report) r;
                }
            }
        }
    }
    return null;
}
 
Example 15
@Override
public void beforeGenerate(Resource input, IFileSystemAccess2 fsa, IGeneratorContext context) {
	final IExtraLanguageGeneratorContext generatorContext = createGeneratorContext(fsa, context, input);
	final EList<EObject> contents = input.getContents();
	for (final EObject obj : contents) {
		if (canGenerateFor(obj)) {
			before(obj, generatorContext);
			final Iterator<EObject> iterator = EcoreUtil.getAllContents(obj, false);
			while (iterator.hasNext()) {
				final EObject subobj = iterator.next();
				before(subobj, generatorContext);
			}
		}
	}
}
 
Example 16
protected void validate(Resource resource, final CheckMode mode, final CancelIndicator monitor,
		IAcceptor<Issue> acceptor) {
	for (EObject ele : resource.getContents()) {
		if (!(ele instanceof Statechart)) {
			continue;
		}
		if (!monitor.isCanceled()) {
			validate(null, ele, mode, monitor, acceptor);
		}
	}
}
 
Example 17
@Check
public void checkUniqueName(EObject root) {
	if (root.eContainer() == null) {
		Resource resource = root.eResource();
		if (Objects.equal(Iterables.getFirst(resource.getContents(), null), root)) {
			for (EObject o : resource.getContents()) {
				if (o instanceof JvmDeclaredType) {
					doCheckUniqueName((JvmDeclaredType) o);
				}
			}
		}
	}
}
 
Example 18
Source Project: n4js   File: XProjectManager.java    License: Eclipse Public License 1.0 4 votes vote down vote up
/** Get the resource with the given URI. */
public Resource getResource(URI uri) {
	Resource resource = resourceSet.getResource(uri, true);
	resource.getContents();
	return resource;
}
 
Example 19
@Override
public void findReferences(Predicate<URI> targetURIs, Resource resource, Acceptor acceptor, IProgressMonitor monitor) {
	for (EObject content : resource.getContents()) {
		findReferences(targetURIs, content, acceptor, monitor);
	}
}
 
Example 20
Source Project: xtext-core   File: XtextLinker.java    License: Eclipse Public License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void notifyChanged(Notification msg) {
	super.notifyChanged(msg);
	if (!msg.isTouch() && msg.getOldValue() != null) {
		ResourceSet set;
		Resource notifyingResource;
		if (!(msg.getNotifier() instanceof Resource)) {
			Object feature = msg.getFeature();
			if (!(feature instanceof EReference))
				return;
			EReference ref = (EReference) feature;
			if (!ref.isContainment())
				return;
			notifyingResource = ((EObject) msg.getNotifier()).eResource();
		} else {
			notifyingResource = ((Resource) msg.getNotifier());
		}
		if (notifyingResource == null)
			return;
		set = notifyingResource.getResourceSet();
		if (set == null)
			return;
		switch (msg.getEventType()) {
			case Notification.REMOVE_MANY:
			case Notification.REMOVE:
			case Notification.SET:
				Object oldValue = msg.getOldValue();
				Collection<Resource> resourcesToRemove = Sets.newHashSet();
				Collection<Resource> resourcesToUnload = Sets.newHashSet();
				Collection<Resource> referencedResources = Sets.newHashSet(notifyingResource);
				if (oldValue instanceof Grammar) {
					processMetamodelDeclarations(((Grammar) oldValue).getMetamodelDeclarations(), set, resourcesToRemove,
							resourcesToUnload, referencedResources);
				} else if (oldValue instanceof AbstractMetamodelDeclaration) {
					processMetamodelDeclarations(Collections
							.singletonList((AbstractMetamodelDeclaration) oldValue), set, resourcesToRemove, resourcesToUnload, referencedResources);
				} else if (oldValue instanceof Collection<?>) {
					if (XtextPackage.Literals.GRAMMAR__METAMODEL_DECLARATIONS == msg.getFeature()) {
						Collection<AbstractMetamodelDeclaration> metamodelDeclarations = (Collection<AbstractMetamodelDeclaration>) oldValue;
						processMetamodelDeclarations(metamodelDeclarations, set, resourcesToRemove, resourcesToUnload, referencedResources);
					}
				}
				resourcesToRemove.removeAll(referencedResources);
				if (unloader != null) {
					resourcesToUnload.removeAll(referencedResources);
					for (Resource resource : resourcesToUnload) {
						if(resource.getResourceSet() == set) {
							for (EObject content : resource.getContents())
								unloader.unloadRoot(content);
						}
					}
				}
				set.getResources().removeAll(resourcesToRemove);
				break;
			default:
				break;
		}
	}
}