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
Source File: CrossflowNavigatorActionProvider.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
/**
* @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 2
Source File: Schema.java    From BIMserver with GNU Affero General Public License v3.0 6 votes vote down vote up
@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 3
Source File: ModelLoader.java    From neoscada with 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 4
Source File: ExtendedLanguageConfig.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@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 5
Source File: UniqueClassNameValidator.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@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 6
Source File: CFGraphProvider.java    From n4js with 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 7
Source File: SCTResourceValidatorImpl.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
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 8
Source File: AbstractExtraLanguageGenerator.java    From sarl with Apache License 2.0 5 votes vote down vote up
@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 9
Source File: MigrationStatusView.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
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 10
Source File: AbstractTypeProviderTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
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 11
Source File: DefaultReferenceFinder.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
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 12
Source File: XtextComparisonExpressionLoader.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
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 13
Source File: SimulationImageRenderer.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
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 14
Source File: XtendImportedNamespaceScopeProvider.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@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 15
Source File: XtextFragmentProvider.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@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 16
Source File: AbstractBatchTypeResolver.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@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 17
Source File: AbstractExtraLanguageGenerator.java    From sarl with Apache License 2.0 5 votes vote down vote up
@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 18
Source File: XtextLinker.java    From xtext-core with 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;
		}
	}
}
 
Example 19
Source File: ReferenceFinder.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
@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 File: XProjectManager.java    From n4js with 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;
}