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

The following examples show how to use org.eclipse.emf.ecore.resource.Resource#getResourceSet() . 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: 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 2
Source File: ResourceLoadMode.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the load mode to be used to load the given resource:
 * <ol>
 * <li>If the resource is not contained in any resource set this method will return {@link #PARSE}.</li>
 * <li>If the resource set's load options specify a load mode, that is returned.</li>
 * <li>If the resource is an instance of {@link LazyLinkingResource2} it will return {@link LazyLinkingResource2#getDefaultLoadMode()}.</li>
 * <li>Otherwise {@link #FULL} is returned.</li>
 * </ol>
 *
 * @param resource
 *          resource to be loaded, must not be {@code null}
 * @return load mode, never {@code null}
 */
static ResourceLoadMode get(final Resource resource) {
  ResourceSet resourceSet = resource.getResourceSet();
  if (resourceSet == null) {
    return PARSE;
  }
  ResourceLoadMode fromLoadOptions = (ResourceLoadMode) resourceSet.getLoadOptions().get(ResourceLoadMode.class);
  if (fromLoadOptions != null) {
    return fromLoadOptions;
  }
  if (resource instanceof LazyLinkingResource2) {
    ResourceLoadMode defaultMode = ((LazyLinkingResource2) resource).getDefaultLoadMode();
    if (defaultMode != null) {
      return defaultMode;
    }
  }
  return FULL;
}
 
Example 3
Source File: GeneratorConfigProvider.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public GeneratorConfig get(EObject context) {
	if (context != null) {
		Resource resource = context.eResource();
		if (resource != null) {
			ResourceSet resourceSet = resource.getResourceSet();
			if (resourceSet != null) {
				GeneratorConfigAdapter adapter = GeneratorConfigAdapter.findInEmfObject(resourceSet);
				if (adapter != null && adapter.language2GeneratorConfig.containsKey(languageId)) {
					return adapter.language2GeneratorConfig.get(languageId);
				}
			}
		}
	}
	return new GeneratorConfig();
}
 
Example 4
Source File: GrammarAccessFragment.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
public void replaceResourceURIsWithNsURIs(Grammar grammar, ResourceSet set) {
	for (AbstractMetamodelDeclaration metamodelDecl : grammar.getMetamodelDeclarations()) {
		EPackage pack = metamodelDecl.getEPackage();
		Resource packResource = pack.eResource();
		if (!packResource.getURI().toString().equals(pack.getNsURI())) {
			ResourceSet packResourceSet = packResource.getResourceSet();
			if (packResourceSet != null) {
				EPackage topMost = pack;
				// we need to be aware of empty subpackages
				while (topMost.getESuperPackage() != null
						&& topMost.getESuperPackage().eResource() == topMost.eResource())
					topMost = topMost.getESuperPackage();
				if (packResource.getContents().contains(topMost) && packResource.getContents().size() == 1) {
					if (!topMost.getEClassifiers().isEmpty())
						packResource.setURI(URI.createURI(topMost.getNsURI()));
					else
						moveSubpackagesToNewResource(topMost, set);
				}
				if (!topMost.eResource().getURI().toString().equals(topMost.getNsURI())) 
					movePackageToNewResource(topMost, set);
			}
		}
	}
}
 
Example 5
Source File: GeneratorConfigProvider2.java    From sarl with Apache License 2.0 6 votes vote down vote up
@Override
public GeneratorConfig2 get(EObject context) {
	final Resource eResource;
	if (context != null) {
		eResource = context.eResource();
	} else {
		eResource = null;
	}
	final ResourceSet resourceSet;
	if (eResource != null) {
		resourceSet = eResource.getResourceSet();
	} else {
		resourceSet = null;
	}
	if (resourceSet != null) {
		final GeneratorConfigAdapter adapter = GeneratorConfigAdapter.findInEmfObject(resourceSet);
		if (adapter != null && adapter.getLanguage2GeneratorConfig().containsKey(this.languageId)) {
			return adapter.getLanguage2GeneratorConfig().get(this.languageId);
		}
	}
	final GeneratorConfig2 config = new GeneratorConfig2();
	return config;
}
 
Example 6
Source File: XtextLinker.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
void discardGeneratedPackages(EObject root) {
	if (root instanceof Grammar) {
		// unload generated metamodels as they will be recreated during linking 
		for (AbstractMetamodelDeclaration metamodelDeclaration : ((Grammar) root).getMetamodelDeclarations()) {
			if (metamodelDeclaration instanceof GeneratedMetamodel) {
				EPackage ePackage = (EPackage) metamodelDeclaration.eGet(XtextPackage.Literals.ABSTRACT_METAMODEL_DECLARATION__EPACKAGE, false);
				if (ePackage != null && !ePackage.eIsProxy()) {
					Resource resource = ePackage.eResource();
					if (resource != null && resource.getResourceSet() != null) {
						if (unloader != null) {
							for (EObject content : resource.getContents()) {
								unloader.unloadRoot(content);
							}
						}
						resource.getResourceSet().getResources().remove(resource);
					}
				}
			}
		}
	}
}
 
Example 7
Source File: FormatScopeUtil.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Find URI of extended FormatConfiguration.
 * The following heuristic is used to find the URI: extract grammar name from the extensionName (path name) and then replace the file name segment of the
 * context's URI with the extracted grammar name.
 *
 * @param context
 *          the context
 * @param extensionName
 *          the extension name
 * @return the URI if found, otherwise null
 */
private URI findExtensionURI(final Resource context, final String extensionName) {
  URI uri = context.getURI().trimFileExtension();
  String name = convertPathNameToShortName(extensionName);
  final URI extensionURI = uri.trimSegments(1).appendSegment(name).appendFileExtension(FormatConstants.FILE_EXTENSION);
  final ResourceSet resourceSet = context.getResourceSet();
  final URIConverter uriConverter = resourceSet.getURIConverter();
  try {
    if (resourceSet.getResource(extensionURI, false) != null || uriConverter.exists(extensionURI, null)) {
      return extensionURI;
    }
    // CHECKSTYLE:OFF
  } catch (Exception e) {// NOPMD
    // no resource found - return null
    // CHECKSTYLE:ON
  }
  return null;
}
 
Example 8
Source File: ChangeSerializer.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected void beginRecordChanges(Resource resource) {
	RecordingResourceUpdater updater = updaters.get(resource);
	if (updater != null) {
		return;
	}
	if (resourceSet == null) {
		resourceSet = resource.getResourceSet();
	} else {
		if (resource.getResourceSet() != resourceSet) {
			throw new IllegalStateException("Wrong ResourceSet.");
		}
	}
	updater = createResourceUpdater(resource);
	updaters.put(resource, updater);
}
 
Example 9
Source File: FormatFragmentUtil.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Retrieve the format model associated with a given grammar.
 * <p>
 * <em>Note</em>: Expected to either be in same folder with the same name (except for the extension) or in the SRC outlet.
 * </p>
 *
 * @param grammar
 *          the grammar, must not be {@code null}
 * @param context
 *          xpand execution context, must not be {@code null}
 * @return the format model, or {@code null} if the resource could not be loaded
 * @throws FileNotFoundException
 *           thrown if the format file could not be found
 */
@SuppressWarnings("PMD.NPathComplexity")
public static FormatConfiguration getFormatModel(final Grammar grammar, final XpandExecutionContext context) throws FileNotFoundException {
  Variable resourceUriVariable = context.getVariable("resourceUri");
  if (resourceUriVariable == null) {
    return null;
  }
  URI uri = (URI) resourceUriVariable.getValue();
  final Resource grammarResource = grammar.eResource();
  final ResourceSet resourceSet = grammarResource.getResourceSet();
  Resource formatResource = null;
  try {
    formatResource = resourceSet.getResource(uri, true);
  } catch (final ClasspathUriResolutionException e) {
    // make another attempt
    uri = getDefaultFormatLocation(grammar, context);
    try {
      formatResource = resourceSet.getResource(uri, true);
    } catch (WrappedException e1) {
      formatResource = resourceSet.getResource(uri, false);
      if (formatResource != null) {
        resourceSet.getResources().remove(formatResource);
      }
      throw new FileNotFoundException(uri.toString()); // NOPMD
    }
  }
  if (formatResource == null) {
    throw new FileNotFoundException(uri.toString());
  }

  final List<Issue> issues = getModelValidator().validate(formatResource, LOG);

  for (final Issue issue : issues) {
    if (issue.isSyntaxError() || issue.getSeverity() == Severity.ERROR) {
      throw new WorkflowInterruptedException("Errors found in " + uri.toString() + ": " + issue.getMessage());
    }
  }

  return formatResource.getContents().size() == 0 ? null : (FormatConfiguration) formatResource.getContents().get(0);
}
 
Example 10
Source File: JavaDerivedStateComputer.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected CompilerOptions getCompilerOptions(Resource resource) {
	if (resource != null) {
		ResourceSet resourceSet = resource.getResourceSet();
		if (resourceSet != null) {
			return getCompilerOptions(resourceSet);
		}
	}
	return null;
}
 
Example 11
Source File: Utils.java    From slr-toolkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the resource file which contains the given bibtex document. Bases
 * on {@link http://www.eclipse.org/forums/index.php?t=msg&th=128695/}
 * 
 * @param doc
 *            {@link Document} whom's resource is wanted
 * @return {@link IFile} which contains doc. <code>null</code> if nothing
 *         was found.
 */
public static IFile getIFilefromEMFResource(Resource resource) {
	if (resource == null) {
		return null;
	}
	// TODO: remove logbuffer
	logBuffer = new StringBuffer();

	URI uri = resource.getURI();
	if(resource.getResourceSet() == null){
		return null;
	}
	uri = resource.getResourceSet().getURIConverter().normalize(uri);
	String scheme = uri.scheme();
	logBuffer.append("URI Scheme: " + scheme + "\n");

	if ("platform".equals(scheme) && uri.segmentCount() > 1
			&& "resource".equals(uri.segment(0))) {
		StringBuffer platformResourcePath = new StringBuffer();
		for (int j = 1, size = uri.segmentCount(); j < size; ++j) {
			platformResourcePath.append('/');
			platformResourcePath.append(uri.segment(j));
		}
		logBuffer.append("Platform path " + platformResourcePath.toString()
				+ "\n");

		IResource parent = ResourcesPlugin.getWorkspace().getRoot()
				.getFile(new Path(platformResourcePath.toString()));
		// TODO: remove syso
		logBuffer.append("IResource " + parent);

		if (parent instanceof IFile) {
			return (IFile) parent;
		}
	}
	// System.out.println(logBuffer.toString());
	return null;

}
 
Example 12
Source File: ImportUriProvider.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
public LinkedHashSet<URI> get(Resource resource) {
	final LinkedHashSet<URI> uniqueImportURIs = new LinkedHashSet<>(5);
	IAcceptor<String> collector = new URICollector(resource.getResourceSet(), uniqueImportURIs);
	
	collectFromImportScopes(resource, collector);
	collectImplicitImports(resource, collector);
	
	removeInvalidUris(resource, uniqueImportURIs);
	return uniqueImportURIs;
}
 
Example 13
Source File: EcoreUtil2.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @return the eobject's URI in the normalized form or as is if it is a platform:/resource URI.
 * @since 2.4
 */
public static URI getPlatformResourceOrNormalizedURI(EObject eObject) {
	URI rawURI = EcoreUtil.getURI(eObject);
	if (rawURI.isPlatformResource()) {
		return rawURI;
	}
	Resource resource = eObject.eResource();
	if(resource != null && resource.getResourceSet() != null) {
		return resource.getResourceSet().getURIConverter().normalize(rawURI);
	} else {
		return URIConverter.INSTANCE.normalize(rawURI);
	}
}
 
Example 14
Source File: DirtyStateEditorSupport.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.8
 */
protected void processDelta(IResourceDescription.Delta delta, Resource context, List<Resource> result) {
	ResourceSet resourceSet = context.getResourceSet();
	Resource resourceInResourceSet = resourceSet.getResource(delta.getUri(), false);
	if(resourceInResourceSet != null && resourceInResourceSet != context) {
		result.add(resourceInResourceSet);
	}
}
 
Example 15
Source File: RecordingXtextResourceUpdater.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void applyChange(Deltas deltas, IAcceptor<IEmfResourceChange> changeAcceptor) {
	Resource resource = snapshot.getResource();
	ResourceSet rs = resource.getResourceSet();
	ReferenceUpdaterContext ctx = new ReferenceUpdaterContext(deltas, document);
	if (serializer.isUpdateCrossReferences()) {
		referenceUpdater.update(ctx);
		for (Runnable run : ctx.getModifications()) {
			run.run();
		}
	}
	ChangeDescription recording = recorder.endRecording();
	if (recording != null) {
		List<IResourceSnapshot> snapshots = Collections.singletonList(snapshot);
		ResourceSetRecording tree = changeTreeProvider.createChangeTree(rs, snapshots, recording);
		ResourceRecording recordedResource = tree.getRecordedResource(resource);
		partialSerializer.serializeChanges(recordedResource, document);
	}
	recorder.dispose();
	List<IUpdatableReference> updatableReferences = ctx.getUpdatableReferences();
	for (IUpdatableReference upd : updatableReferences) {
		referenceUpdater.updateReference(document, upd);
	}
	ITextRegionAccessDiff rewritten = document.create();
	List<ITextReplacement> rep = formatter.format(rewritten);
	URI oldUri = snapshot.getURI();
	TextDocumentChange change = new TextDocumentChange(rewritten, oldUri, rep);
	changeAcceptor.accept(change);
}
 
Example 16
Source File: CatalogFromExtensionPointScopeHelper.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates an extension scope for each registered check catalog.
 *
 * @param parent
 *          the parent scope
 * @param context
 *          the context object
 * @return the check catalog scope
 */
public IScope createExtensionScope(final IScope parent, final Resource context) {
  IScope result = parent;
  NavigableSet<IModelLocation> locations = ICheckCatalogRegistry.INSTANCE.getAllCheckModelLocations();
  for (IModelLocation locationData : locations.descendingSet()) {
    // The UI proposes parent scope contents after each scope in the chain, so this scope chain must be created in reverse.
    result = new CatalogFromExtensionPointScope(result, locationData, (XtextResourceSet) context.getResourceSet());
  }
  return result;
}
 
Example 17
Source File: GrammarAccessFragment2.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
protected void addAllGrammarsToResource(final Resource resource, final Grammar grammar, final Set<Grammar> visitedGrammars) {
  boolean _add = visitedGrammars.add(grammar);
  boolean _not = (!_add);
  if (_not) {
    return;
  }
  resource.getContents().add(grammar);
  EList<AbstractMetamodelDeclaration> _metamodelDeclarations = grammar.getMetamodelDeclarations();
  for (final AbstractMetamodelDeclaration metamodelDecl : _metamodelDeclarations) {
    {
      final EPackage pack = metamodelDecl.getEPackage();
      final Resource packResource = pack.eResource();
      String _string = packResource.getURI().toString();
      String _nsURI = pack.getNsURI();
      boolean _notEquals = (!Objects.equal(_string, _nsURI));
      if (_notEquals) {
        final ResourceSet packResourceSet = packResource.getResourceSet();
        if ((packResourceSet != null)) {
          EPackage topMost = pack;
          while (((topMost.getESuperPackage() != null) && (topMost.getESuperPackage().eResource() == topMost.eResource()))) {
            topMost = topMost.getESuperPackage();
          }
          if ((packResource.getContents().contains(topMost) && (packResource.getContents().size() == 1))) {
            boolean _isEmpty = topMost.getEClassifiers().isEmpty();
            boolean _not_1 = (!_isEmpty);
            if (_not_1) {
              packResource.setURI(URI.createURI(topMost.getNsURI()));
            } else {
              this.moveSubpackagesToNewResource(topMost, resource.getResourceSet());
            }
          }
          boolean _equals = topMost.eResource().getURI().toString().equals(topMost.getNsURI());
          boolean _not_2 = (!_equals);
          if (_not_2) {
            this.movePackageToNewResource(topMost, resource.getResourceSet());
          }
        }
      }
    }
  }
  EList<Grammar> _usedGrammars = grammar.getUsedGrammars();
  for (final Grammar usedGrammar : _usedGrammars) {
    this.addAllGrammarsToResource(resource, usedGrammar, visitedGrammars);
  }
}
 
Example 18
Source File: AbstractBuilder.java    From sarl with Apache License 2.0 4 votes vote down vote up
public void dispose() {
	Resource resource = eResource();
	ResourceSet resourceSet = resource.getResourceSet();
	resourceSet.getResources().remove(resource);
}
 
Example 19
Source File: DefaultN4GlobalScopeProvider.java    From n4js with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Finds the built in type scope for the given resource and its applicable context.
 *
 * @param resource
 *            the resource that is currently linked
 * @return an instance of the {@link BuiltInTypeScope}
 */
protected BuiltInTypeScope getBuiltInTypeScope(Resource resource) {
	ResourceSet resourceSet = resource.getResourceSet();
	return BuiltInTypeScope.get(resourceSet);
}
 
Example 20
Source File: ResourceUtil.java    From xtext-eclipse with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Obtains the workspace file underlying the specified resource. If the resource has an {@link URI#isArchive()
 * archive} scheme, the {@linkplain URI#authority() authority} is considered instead. If the URI has a file scheme,
 * it's looked up in the workspace, just as in the {@link #getFile(Resource)} method. Otherwise, a platform scheme
 * is assumed.
 * <p>
 * Note that the resulting file, if not <code>null</code>, may nonetheless not actually exist (as the file is just a
 * handle).
 * </p>
 * 
 * @param resource
 *            an EMF resource
 * 
 * @return the underlying workspace file, or <code>null</code> if the resource's URI is not a platform-resource URI
 * 
 * @see #getFile(Resource)
 * @since 1.2
 */
public static IFile getUnderlyingFile(Resource resource) {
	ResourceSet rset = resource.getResourceSet();

	return getFile(resource.getURI(), (rset != null) ? rset.getURIConverter() : null, true);
}