Java Code Examples for org.eclipse.emf.ecore.resource.ResourceSet#getResources()

The following examples show how to use org.eclipse.emf.ecore.resource.ResourceSet#getResources() . 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: N4JSResourceSetCleanerUtils.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Removes all non-N4 resources from the given resource set without sending any notification about the removal. This
 * specific resource set cleaning is required to avoid the accidental removal of the resources holding the built-in
 * types. For more details reference: IDEBUG-491.
 *
 * @param resourceSet
 *            the resource set to clean. Optional, can be {@code null}. If {@code null} this method has no effect.
 */
/* default */static void clearResourceSet(final ResourceSet resourceSet) {
	boolean wasDeliver = resourceSet.eDeliver();
	try {
		resourceSet.eSetDeliver(false);
		// iterate backwards to avoid costly shuffling in the underlying list
		EList<Resource> resources = resourceSet.getResources();
		// int originalSize = resources.size();
		for (int i = resources.size() - 1; i >= 0; i--) {
			final Resource resource = resources.get(i);
			final URI uri = resource.getURI();
			if (!isN4Scheme(uri)) {
				resources.remove(i);
			} else {
				LOGGER.info("Intentionally skipping the removal of N4 resource: " + uri);
			}
		}
	} finally {
		resourceSet.eSetDeliver(wasDeliver);
	}
}
 
Example 2
Source File: ForwardConverter.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
/** Determine the root nodes. */
protected void initResources(ResourceSet resourceSet) {
	for (final Resource resource : resourceSet.getResources()) {
		if (resource.getContents().isEmpty()) {
			continue;
		}
		final ModelResource modelResource = MigrationFactory.eINSTANCE
			.createModelResource();

		// For CDO we need the connection aware URI!
		modelResource.setUri(resource.getURI());
		if (resource instanceof XMLResource) {
			final XMLResource xmlResource = (XMLResource) resource;
			modelResource.setEncoding(xmlResource.getEncoding());
		}
		model.getResources().add(modelResource);
		for (final EObject element : resource.getContents()) {
			modelResource.getRootInstances().add(resolve(element));
		}
	}
}
 
Example 3
Source File: ResourceSetBasedSlotEntry.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected List<EObject> findEObjectsOfType(Set<EClass> eClasses, IResourceDescriptions resourceDescriptions,
		ResourceSet resourceSet) {
	List<EObject> result = Lists.newArrayList();
	for (Resource resource : resourceSet.getResources()) {
		if (!resource.isLoaded()) {
			try {
				resource.load(null);
			} catch (IOException e) {
				throw new WrappedException(e);
			}
		}
	}
	for (Iterator<Notifier> i = resourceSet.getAllContents(); i.hasNext();) {
		Notifier next = i.next();
		if (next instanceof EObject && matches(eClasses, (EObject) next)) {
			result.add((EObject) next);
		}
	}
	return result;
}
 
Example 4
Source File: ForwardConverter.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
/** Create a node for each EMF model element */
protected void initElements(ResourceSet resourceSet) {
	for (final Resource resource : resourceSet.getResources()) {
		for (final TreeIterator<EObject> i = resource.getAllContents(); i
			.hasNext();) {
			final EObject eObject = i.next();
			if (mapping.containsKey(eObject)) {
				i.prune();
			} else {
				final Instance instance = newInstance(eObject, eObject.eIsProxy());
				final String uuid = EcoreUtils.getUUID(eObject);
				instance.setUuid(uuid);
			}
		}
	}
}
 
Example 5
Source File: SyntheticResourceAwareScopeProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
public IScope scope_Codetemplates_language(Codetemplates templates, EReference reference) {
	if (TemplateResourceProvider.SYNTHETIC_SCHEME.equals(templates.eResource().getURI().scheme())) {
		ResourceSet resourceSet = templates.eResource().getResourceSet();
		List<Grammar> grammars = Lists.newArrayListWithExpectedSize(1);
		for(Resource resource: resourceSet.getResources()) {
			EObject root = resource.getContents().get(0);
			if (root instanceof Grammar) {
				grammars.add((Grammar) root);
			}
		}
		return Scopes.scopeFor(grammars, new Function<Grammar, QualifiedName>() {

			@Override
			public QualifiedName apply(Grammar from) {
				return qualifiedNameConverter.toQualifiedName(from.getName());
			}
			
		}, IScope.NULLSCOPE);
	} else {
		return delegateGetScope(templates, reference);
	}
}
 
Example 6
Source File: FormatterFacade.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Format the given code.
 *
 * @param sarlCode the code to format.
 * @param resourceSet the resource set that sohuld contains the code. This resource set may be
 *     used for resolving types by the underlying code.
 * @return the code to format.
 */
@Pure
public String format(String sarlCode, ResourceSet resourceSet) {
	try {
		final URI createURI = URI.createURI("synthetic://to-be-formatted." + this.fileExtension); //$NON-NLS-1$
		final Resource res = this.resourceFactory.createResource(createURI);
		if (res instanceof XtextResource) {
			final XtextResource resource = (XtextResource) res;
			final EList<Resource> resources = resourceSet.getResources();
			resources.add(resource);
			try (StringInputStream stringInputStream = new StringInputStream(sarlCode)) {
				resource.load(stringInputStream, Collections.emptyMap());
				return formatResource(resource);
			} finally {
				resources.remove(resource);
			}
		}
		return sarlCode;
	} catch (Exception exception) {
		throw Exceptions.sneakyThrow(exception);
	}
}
 
Example 7
Source File: BackupUtils.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
/** Copy a model based on a number of {@link URI}s. */
public static List<URI> copy(List<URI> sourceURIs, Metamodel metamodel,
	URIMapper mapper) throws IOException {
	final List<URI> targetURIs = new ArrayList<URI>();
	final ResourceSet model = ResourceUtils.loadResourceSet(sourceURIs, metamodel
		.getEPackages());
	for (final Resource resource : model.getResources()) {
		if (resource.getURI() == null
			|| resource.getURI().isPlatformPlugin()) {
			continue;
		}
		final URI targetURI = mapper.map(resource.getURI());
		if (targetURI != null) {
			resource.setURI(targetURI);
			targetURIs.add(targetURI);
		}
	}
	ResourceUtils.saveResourceSet(model, null);
	return targetURIs;
}
 
Example 8
Source File: Persistency.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
/** Create metamodel from a {@link ResourceSet}. */
public static Metamodel loadMetamodel(ResourceSet resourceSet) {
	ResourceUtils.resolveAll(resourceSet);
	final Metamodel metamodel = MigrationFactory.eINSTANCE.createMetamodel();
	for (final Resource resource : resourceSet.getResources()) {
		final MetamodelResource metamodelResource = MigrationFactory.eINSTANCE
			.createMetamodelResource();
		metamodelResource.setUri(resource.getURI());
		metamodel.getResources().add(metamodelResource);
		for (final EObject element : resource.getContents()) {
			if (element instanceof EPackage) {
				final EPackage ePackage = (EPackage) element;
				FactoryHelper.INSTANCE.overrideFactory(ePackage);
				for (final EPackage sub : ePackage.getESubpackages()) {
					FactoryHelper.INSTANCE.overrideFactory(sub);
				}
				metamodelResource.getRootPackages().add(ePackage);
			}
		}
	}

	return metamodel;
}
 
Example 9
Source File: ASTGraphProvider.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private List<Resource> getElements(ResourceSet resSet, final List<Object> result) {
	final List<Resource> ignoredResources = new ArrayList<>();

	for (Resource res : new ArrayList<>(resSet.getResources())) {
		final boolean isFirstResource = result.isEmpty();
		// only show contents of first resource + .n4js resources
		// (avoid showing built-in types or letting graph become to large)
		String uriStr = res.getURI().toString();
		if (isFirstResource || uriStr.endsWith(".n4js") || uriStr.endsWith(".n4jsd")) {
			getElementsForN4JSs(result, res);

		} else if (SHOW_BUILT_IN.length > 0
				&& (uriStr.endsWith("builtin_js.n4ts") || uriStr.endsWith("builtin_n4.n4ts"))) {

			getElementsForBuiltIns(result, ignoredResources, res);

		} else {
			// ignore the resource
			ignoredResources.add(res);
		}
	}
	return ignoredResources;
}
 
Example 10
Source File: ForwardConverter.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
/** Initialize the properties of the nodes. */
protected void initProperties(ResourceSet resourceSet) {
	final Set<EObject> done = new HashSet<EObject>();
	for (final Resource resource : resourceSet.getResources()) {
		for (final TreeIterator<EObject> i = resource.getAllContents(); i
			.hasNext();) {
			final EObject eObject = i.next();
			if (done.contains(eObject)) {
				i.prune();
			} else {
				initInstance(eObject);
				done.add(eObject);
			}
		}
	}
}
 
Example 11
Source File: OpenFileContext.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
public void refreshOpenFile(@SuppressWarnings("unused") int version,
		Iterable<? extends TextDocumentContentChangeEvent> changes, CancelIndicator cancelIndicator) {

	if (mainResource == null) {
		throw new IllegalStateException("trying to refresh a resource that was not yet initialized: " + mainURI);
	}
	if (!mainResource.isLoaded()) {
		throw new IllegalStateException("trying to refresh a resource that is not yet loaded: " + mainURI);
	}

	// TODO GH-1774 the following is only necessary for changed files (could be moved to #updateDirtyState())
	ResourceSet resSet = getResourceSet();
	for (Resource res : new ArrayList<>(resSet.getResources())) {
		if (res != mainResource) {
			res.unload(); // TODO GH-1774 better way to do this? (unload is expensive due to re-proxyfication)
			resSet.getResources().remove(res);
		}
	}

	for (TextDocumentContentChangeEvent change : changes) {
		Range range = change.getRange();
		int start = range != null ? document.getOffSet(range.getStart()) : 0;
		int end = range != null ? document.getOffSet(range.getEnd()) : document.getContents().length();
		String replacement = change.getText();

		document = document.applyTextDocumentChanges(Collections.singletonList(change));

		mainResource.update(start, end - start, replacement);
	}

	resolveAndValidateOpenFile(cancelIndicator);
}
 
Example 12
Source File: ResourceLoadingStatistics.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private int countN4JSResourcesLoadedFromIndex(ResourceSet resSet) {
	int n = 0;
	for (Resource res : resSet.getResources()) {
		if (!isBuiltInResource(res)) {
			if (res instanceof N4JSResource) {
				final N4JSResource resCasted = (N4JSResource) res;
				if (resCasted.isLoadedFromDescription()) {
					n++;
				}
			}
		}
	}
	return n;
}
 
Example 13
Source File: ResourceSetReferencingResourceSetImpl.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
private Resource findResourceInResourceSet(URI uri, ResourceSet set) {
	EList<Resource> resources = set.getResources();
	for (Resource resource : resources) {
		if (resource.getURI().equals(uri))
			return resource;
	}
	return null;
}
 
Example 14
Source File: ResourceLoadingStatistics.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private int countN4JSResourcesLoadedFromAST(ResourceSet resSet) {
	int n = 0;
	for (Resource res : resSet.getResources()) {
		if (!isBuiltInResource(res)) {
			if (res instanceof N4JSResource) {
				final N4JSResource resCasted = (N4JSResource) res;
				if (!resCasted.isLoadedFromDescription()) {
					n++;
				}
			}
		}
	}
	return n;
}
 
Example 15
Source File: BuilderParticipant.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Clears the content of the resource set without sending notifications.
 * This avoids unnecessary, explicit unloads.
 * @since 2.7
 */
protected void clearResourceSet(ResourceSet resourceSet) {
	boolean wasDeliver = resourceSet.eDeliver();
	try {
		resourceSet.eSetDeliver(false);
		for (Resource resource : resourceSet.getResources()) {
			resource.eSetDeliver(false);
		}
		resourceSet.getResources().clear();
	} finally {
		resourceSet.eSetDeliver(wasDeliver);
	}
}
 
Example 16
Source File: XtextBuilder.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @param toBeBuilt
 *            the URIs that will be processed in this build run.
 * @param removedProjects
 *            the projects that are no longer considered by XtextBuilders but are yet to be removed from the index.
 * @param monitor
 *            the progress monitor for the build.
 * @param type
 *            indicates the kind of build that is running.
 * 
 * @since 2.18
 */
protected void doBuild(ToBeBuilt toBeBuilt, Set<String> removedProjects, IProgressMonitor monitor, BuildType type) throws CoreException {
	buildLogger.log("Building " + getProject().getName());
	// return early if there's nothing to do.
	// we reuse the isEmpty() impl from BuildData assuming that it doesnT access the ResourceSet which is still null 
	// and would be expensive to create.
	boolean indexingOnly = type == BuildType.RECOVERY;
	if (new BuildData(getProject().getName(), null, toBeBuilt, queuedBuildData, indexingOnly, this::needRebuild, removedProjects).isEmpty())
		return;
	SubMonitor progress = SubMonitor.convert(monitor, 2);
	ResourceSet resourceSet = getResourceSetProvider().get(getProject());
	resourceSet.getLoadOptions().put(ResourceDescriptionsProvider.NAMED_BUILDER_SCOPE, Boolean.TRUE);
	BuildData buildData = new BuildData(getProject().getName(), resourceSet, toBeBuilt, queuedBuildData, indexingOnly, this::needRebuild, removedProjects);
	ImmutableList<Delta> deltas = builderState.update(buildData, progress.split(1));
	if (participant != null && !indexingOnly) {
		SourceLevelURICache sourceLevelURIs = buildData.getSourceLevelURICache();
		Set<URI> sources = sourceLevelURIs.getSources();
		participant.build(new BuildContext(this, resourceSet, deltas, sources, type),
				progress.split(1));
		try {
			getProject().getWorkspace().checkpoint(false);
		} catch(NoClassDefFoundError e) { // guard against broken Eclipse installations / bogus project configuration
			log.error(e.getMessage(), e);
		}
	} else {
		progress.worked(1);
	}
	resourceSet.eSetDeliver(false);
	for (Resource resource : resourceSet.getResources()) {
		resource.eSetDeliver(false);
	}
	resourceSet.getResources().clear();
	resourceSet.eAdapters().clear();
}
 
Example 17
Source File: CommandUtil.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
public static List<IFile> getAffectedFiles(ResourceSet resourceSet) {
	final List<IFile> affectedFiles = new ArrayList<IFile>();
	final TransactionalEditingDomain domain = TransactionUtil
			.getEditingDomain(resourceSet);
	for (final Resource next : resourceSet.getResources()) {
		if (!domain.isReadOnly(next)) {
			final IFile file = WorkspaceSynchronizer
					.getUnderlyingFile(next);
			Assert.isNotNull(file, next.getURI() + "");
			affectedFiles.add(file);
		}
	}
	return affectedFiles;
}
 
Example 18
Source File: XtendResourceSetBasedResourceDescriptionsTest.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testUnloadedInstallDerivedStateThrowsException() {
  try {
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("package foo class ClassA extends bar.ClassB {}");
    Pair<String, String> _mappedTo = Pair.<String, String>of("foo/ClassA.xtend", _builder.toString());
    StringConcatenation _builder_1 = new StringConcatenation();
    _builder_1.append("package bar class ClassB { public foo.ClassA myField }");
    Pair<String, String> _mappedTo_1 = Pair.<String, String>of("bar/ClassB.xtend", _builder_1.toString());
    final ResourceSet resourceSet = this.compiler.unLoadedResourceSet(_mappedTo, _mappedTo_1);
    final List<? extends Resource> resources = resourceSet.getResources();
    ArrayList<Resource> _arrayList = new ArrayList<Resource>(resources);
    for (final Resource res : _arrayList) {
      {
        Assert.assertFalse(res.isLoaded());
        try {
          ((DerivedStateAwareResource) res).installDerivedState(true);
          Assert.fail("expected exception");
        } catch (final Throwable _t) {
          if (_t instanceof IllegalStateException) {
          } else {
            throw Exceptions.sneakyThrow(_t);
          }
        }
      }
    }
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 19
Source File: DOTRendering.java    From textuml with Eclipse Public License 1.0 4 votes vote down vote up
private static void unloadResources(ResourceSet resourceSet) {
    for (Resource current : resourceSet.getResources())
        current.unload();
}
 
Example 20
Source File: GenModelUtil2.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
public static Resource getGenModelResource(final String locationInfo, final String nsURI, final ResourceSet resourceSet) {
  final URI genModelURI = EcorePlugin.getEPackageNsURIToGenModelLocationMap(false).get(nsURI);
  if ((genModelURI == null)) {
    boolean _equals = Objects.equal(EcorePackage.eNS_URI, nsURI);
    if (_equals) {
      return null;
    }
    EList<Resource> _resources = resourceSet.getResources();
    for (final Resource res : _resources) {
      EList<EObject> _contents = res.getContents();
      for (final EObject obj : _contents) {
        if ((obj instanceof GenModel)) {
          EList<GenPackage> _genPackages = ((GenModel)obj).getGenPackages();
          for (final GenPackage genPackage : _genPackages) {
            String _nSURI = genPackage.getNSURI();
            boolean _equals_1 = Objects.equal(_nSURI, nsURI);
            if (_equals_1) {
              return genPackage.eResource();
            }
          }
        }
      }
    }
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("Could not find a GenModel for EPackage \'");
    _builder.append(nsURI);
    _builder.append("\'");
    {
      boolean _isNullOrEmpty = StringExtensions.isNullOrEmpty(locationInfo);
      boolean _not = (!_isNullOrEmpty);
      if (_not) {
        _builder.append(" from ");
        _builder.append(locationInfo);
      }
    }
    _builder.append(".");
    _builder.newLineIfNotEmpty();
    _builder.append("If the missing GenModel has been generated via ");
    String _simpleName = EMFGeneratorFragment2.class.getSimpleName();
    _builder.append(_simpleName);
    _builder.append(", make sure to run it first in the workflow.");
    _builder.newLineIfNotEmpty();
    _builder.append("If you have a *.genmodel-file, make sure to register it via StandaloneSetup.registerGenModelFile(String).");
    _builder.newLine();
    throw new RuntimeException(_builder.toString());
  }
  if ((resourceSet == null)) {
    StringConcatenation _builder_1 = new StringConcatenation();
    _builder_1.append("There is no ResourceSet for EPackage \'");
    _builder_1.append(nsURI);
    _builder_1.append("\'. Please make sure the EPackage has been loaded from a .ecore file and not from the generated Java file.");
    throw new RuntimeException(_builder_1.toString());
  }
  final Resource genModelResource = resourceSet.getResource(genModelURI, true);
  if ((genModelResource == null)) {
    StringConcatenation _builder_2 = new StringConcatenation();
    _builder_2.append("Error loading GenModel ");
    _builder_2.append(genModelURI);
    throw new RuntimeException(_builder_2.toString());
  }
  EList<EObject> _contents_1 = genModelResource.getContents();
  for (final EObject content : _contents_1) {
    if ((content instanceof GenModel)) {
      ((GenModel)content).reconcile();
    }
  }
  return genModelResource;
}