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

The following examples show how to use org.eclipse.emf.ecore.resource.Resource#getURI() . 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: XStatefulIncrementalBuilder.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private boolean isResourceInOutputDirectory(Resource resource, IResourceServiceProvider serviceProvider) {
	XWorkspaceManager workspaceManager = serviceProvider.get(XWorkspaceManager.class);
	if (workspaceManager == null) {
		return false;
	}
	OutputConfigurationProvider outputConfProvider = serviceProvider.get(OutputConfigurationProvider.class);
	URI resourceUri = resource.getURI();
	IProjectConfig projectConfig = workspaceManager.getProjectConfig(resourceUri);
	Set<OutputConfiguration> outputConfigurations = outputConfProvider.getOutputConfigurations(resource);
	URI projectBaseUri = projectConfig.getPath();
	Path resourcePath = URIUtils.toPath(resourceUri);

	for (OutputConfiguration outputConf : outputConfigurations) {
		for (String outputDir : outputConf.getOutputDirectories()) {
			URI outputUri = projectBaseUri.appendSegment(outputDir);
			Path outputPath = URIUtils.toPath(outputUri);
			if (resourcePath.startsWith(outputPath)) {
				return true;
			}
		}
	}
	return false;
}
 
Example 2
Source File: XtextReferableElementsUnloader.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
private void caseEPackage(EPackage ePackage) {
	// guard against infinite recursion
	// EPackage.eSetProxyURI and friends tries to be smart thus
	// we have to make sure to compute all URIs before they are
	// set
	Resource resource = ePackage.eResource();
	URI resourceURI = resource.getURI();
	List<EClassifier> classifiers = ePackage.getEClassifiers();
	List<URI> uris = new ArrayList<URI>(classifiers.size());
	for(int i = 0, size = classifiers.size(); i < size; i++) {
		uris.add(resourceURI.appendFragment(resource.getURIFragment(classifiers.get(i))));
	}
	// and we have to set them in a proper order
	unload(ePackage);
	for(int i = 0, size = classifiers.size(); i < size; i++) {
		InternalEObject classifier = (InternalEObject) classifiers.get(i);
		classifier.eSetProxyURI(uris.get(i));
	}
}
 
Example 3
Source File: AbstractResourceDescription.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected URI getNormalizedURI(Resource resource) {
	URI uri = resource.getURI();
	URIConverter uriConverter = resource.getResourceSet()!=null?resource.getResourceSet().getURIConverter():null;
	if (uri != null && uriConverter != null) {
		if (!uri.isPlatform()) {
			return uriConverter.normalize(uri);
		}
		// This is a fix for resources which have been loaded using a platform:/plugin URI
		// This happens when one resource has absolute references using a platform:/plugin uri and the corresponding
		// ResourceDescriptionManager resolves references in the first phase, i.e. during EObjectDecription computation.
		// EMF's GenModelResourceDescriptionStrategy does so as it needs to call GenModel.reconcile() eagerly.
		if (uri.isPlatformPlugin()) {
			URI resourceURI = uri.replacePrefix(URI.createURI("platform:/plugin/"), URI.createURI("platform:/resource/"));
			if (uriConverter.normalize(uri).equals(uriConverter.normalize(resourceURI)))
				return resourceURI;
		}
	}
	return uri;
}
 
Example 4
Source File: WorkbenchTestHelper.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Replies the project for the given resource.
 * 
 * @param resource the resource to search for.
 * @param createOnDemand create the project if it does not exist yet.
 * @return the project.
 */
public IProject getProject(Resource resource, boolean createOnDemand) {
	if (resource != null) {
		final URI uri = resource.getURI();
		final String platformString = uri.toPlatformString(true);
		final IPath resourcePath = new Path(platformString);
		final IFile file = this.workspace.getRoot().getFile(resourcePath);
		if (file != null) {
			final IProject project = file.getProject();
			if (project != null && project.exists()) {
				return project;
			}
		}
	}
	return getProject(createOnDemand);
}
 
Example 5
Source File: GenconfUtils.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Gets the {@link Map} of options from the given {@link Generation}.
 * 
 * @param generation
 *            the {@link Generation}
 * @return the {@link Map} of options from the given {@link Generation}
 */
public static Map<String, String> getOptions(Generation generation) {
    final Map<String, String> res = new LinkedHashMap<String, String>();

    final Resource eResource = generation.eResource();
    if (eResource != null && eResource.getURI() != null) {
        res.put(GENCONF_URI_OPTION, eResource.getURI().toString());
    }
    if (generation.getTemplateFileName() != null) {
        res.put(M2DocUtils.TEMPLATE_URI_OPTION,
                getResolvedURI(generation, URI.createURI(generation.getTemplateFileName(), false)).toString());
    }
    if (generation.getResultFileName() != null) {
        res.put(M2DocUtils.RESULT_URI_OPTION,
                getResolvedURI(generation, URI.createURI(generation.getResultFileName(), false)).toString());
    }
    if (generation.getValidationFileName() != null) {
        res.put(M2DocUtils.VALIDATION_URI_OPTION,
                getResolvedURI(generation, URI.createURI(generation.getValidationFileName(), false)).toString());
    }
    for (Option option : generation.getOptions()) {
        res.put(option.getName(), option.getValue());
    }

    return res;
}
 
Example 6
Source File: UserDataMapper.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private static Set<URI> getDependenciesLoadtimeForInheritance(N4JSResource resource) {
	final Set<URI> result = new LinkedHashSet<>();
	final TModule module = resource.getModule();
	if (module != null && !module.eIsProxy()) {
		for (RuntimeDependency dep : module.getDependenciesRuntime()) {
			if (dep.isLoadtimeForInheritance()) {
				final TModule targetModule = dep.getTarget();
				if (targetModule != null && !targetModule.eIsProxy()) {
					final Resource targetRes = targetModule.eResource();
					if (targetRes != null) {
						final URI uri = targetRes.getURI();
						if (uri != null) {
							result.add(uri);
						}
					}
				}
			}
		}
	}
	return result;
}
 
Example 7
Source File: ContainerQuery.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Execute the query on containers visible from a certain resource, and caches the results on that resource. The results will grouped by
 * container and in the order of
 * {@link IContainer.Manager#getVisibleContainers(org.eclipse.xtext.resource.IResourceDescription, org.eclipse.xtext.resource.IResourceDescriptions)}. The
 * result does <em>not</em> apply
 * any name shadowing.
 *
 * @param resource
 *          The resource.
 * @return The query results
 */
@SuppressWarnings("nls")
public Iterable<IEObjectDescription> execute(final Resource resource) {
  if (!(resource instanceof LazyLinkingResource)) {
    throw new IllegalStateException("Resource is not a LazyLinkingResource " + (resource != null ? resource.getURI() : ""));
  }
  final IScopeProvider scopeProvider = EObjectUtil.getScopeProviderByResource((LazyLinkingResource) resource);
  if (!(scopeProvider instanceof AbstractPolymorphicScopeProvider)) {
    throw new IllegalStateException("Scope provider is not an AbstractPolymorphicScopeProvider scope provider.");
  }
  return execute(((AbstractPolymorphicScopeProvider) scopeProvider).getVisibleContainers((LazyLinkingResource) resource));
}
 
Example 8
Source File: EcoreUtil2.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
private static URI getResolvedImportUri(Resource context, URI uri) {
	URI contextURI = context.getURI();
	if (contextURI.isHierarchical() && !contextURI.isRelative() && (uri.isRelative() && !uri.isEmpty())) {
		uri = uri.resolve(contextURI);
	}
	return uri;
}
 
Example 9
Source File: EmfAssert.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
private static Resource findResource(ResourceSet resources,
		String matchURIpart) {
	for (Resource r : resources.getResources())
		if (r.getURI() != null
				&& r.getURI().toString().contains(matchURIpart))
			return r;
	throw new RuntimeException("No Resource with '" + matchURIpart
			+ "' in it's URI found in ResourceSet.");
}
 
Example 10
Source File: CDOGenerateHandler.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the first local resource contained in the associated resource
 * set.
 * 
 * @param resources
 *            a resource contained in the target resource set.
 * @return a local resource;
 */
Resource getPlatformeResource(Set<Resource> resources) {
    for (Resource res : resources) {
        URI uri = res.getURI();
        if (uri.isPlatform()) {
            return res;
        }
    }
    return null;
}
 
Example 11
Source File: EObjectSnapshotProvider.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public ResourceSnapshot(EObjectSnapshotProvider strategy, Resource resource, boolean recordReferences) {
	this.resource = resource;
	this.regions = strategy.getTextRegionAccess(resource);
	if (recordReferences) {
		this.objects = strategy.createEObjectSnapshots(resource);
	} else {
		this.objects = Collections.emptyMap();
	}
	this.uri = resource.getURI();
}
 
Example 12
Source File: JvmModelAssociator.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected void checkSameResource(Resource eResource, Resource eResource2) {
	if (!LOG.isDebugEnabled())
		return;
	if (eResource != eResource2 && eResource2 != null) {
		IllegalArgumentException e = new IllegalArgumentException("Cross resource associations are not supported (resources were "+eResource.getURI()+" and "+eResource2.getURI());
		LOG.debug(e.getMessage(), e);
	}
}
 
Example 13
Source File: IModel.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
@Override
default URI getURI() {
	final ModelDescription md = (ModelDescription) getDescription();
	if (md == null) { return null; }
	final EObject o = md.getUnderlyingElement();
	if (o == null) { return null; }
	final Resource r = o.eResource();
	if (r == null) { return null; }
	return r.getURI();
}
 
Example 14
Source File: SourceContainerAwareResourceValidator.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private boolean isInSourceFolder(Resource resource) {
	URI uri = resource.getURI();
	Optional<? extends IN4JSSourceContainer> sourceContainerOpt = eclipseCore.findN4JSSourceContainer(uri);
	if (sourceContainerOpt.isPresent()) {
		IN4JSSourceContainer sourceContainer = sourceContainerOpt.get();
		return !sourceContainer.isExternal();
	}
	return false;
}
 
Example 15
Source File: GeneratorMarkerSupport.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void createMarker(Resource res, String message, Severity severity) {

	final int severityEclipse;
	switch (severity) {
	case INFO:
		severityEclipse = IMarker.SEVERITY_INFO;
		break;
	case WARNING:
		severityEclipse = IMarker.SEVERITY_WARNING;
		break;
	default:
		severityEclipse = IMarker.SEVERITY_ERROR;
		break;
	}

	try {
		IMarker marker = toIFile(res).createMarker(MARKER__ORG_ECLIPSE_IDE_N4JS_UI_COMPILER_ERROR);
		marker.setAttribute(IMarker.MESSAGE, message);
		marker.setAttribute(IMarker.SEVERITY, severityEclipse);
		marker.setAttribute(IMarker.LINE_NUMBER, 1);
	} catch (CoreException e) {
		LOGGER.error(e.getStatus());
		String resInfo = "";
		if (res != null) {
			if (res.getURI() != null) {
				resInfo = "on resource with uri=" + res.getURI();
			} else {
				resInfo = "on resource=" + res;
			}
		}
		throw new RuntimeException("Cannot create error marker with message='" + message + "' " + resInfo + ".", e);
	}
}
 
Example 16
Source File: EmfAssert.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
private static Resource findResource(ResourceSet resources,
		String matchURIpart) {
	for (Resource r : resources.getResources())
		if (r.getURI() != null
				&& r.getURI().toString().contains(matchURIpart))
			return r;
	throw new RuntimeException("No Resource with '" + matchURIpart
			+ "' in it's URI found in ResourceSet.");
}
 
Example 17
Source File: GenconfResourceStrategy.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean canHandle(Resource resource, ResourceStrategyType resourceStrategyType) {
    final boolean res;

    if (resource != null && resource.getURI() != null) {
        res = canHandle(resource.getURI(), resourceStrategyType);
    } else {
        res = super.canHandle(resource, resourceStrategyType);
    }

    return res;
}
 
Example 18
Source File: RelatedEmfResourceUpdater.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void applyChange(Deltas deltas, IAcceptor<IEmfResourceChange> changeAcceptor) {
	Resource res = lifecycleManager.openAndApplyReferences(getResourceSet(), getResource());
	EmfResourceChange change = new EmfResourceChange(res, res.getURI());
	changeAcceptor.accept(change);
}
 
Example 19
Source File: N4JSUnloader.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
private URI getResourceURI(EObject root) {
	Resource resource = root.eResource();
	if (resource != null)
		return resource.getURI();
	return EcoreUtil.getURI(root).trimFragment();
}
 
Example 20
Source File: XStatefulIncrementalBuilder.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
/** Generate code for the given resource */
protected void generate(Resource resource, XSource2GeneratedMapping newMappings,
		IResourceServiceProvider serviceProvider) {
	GeneratorDelegate generator = serviceProvider.get(GeneratorDelegate.class);
	if (generator == null) {
		return;
	}

	if (isResourceInOutputDirectory(resource, serviceProvider)) {
		return;
	}

	URI source = resource.getURI();
	Set<URI> previous = newMappings.deleteSource(source);
	URIBasedFileSystemAccess fileSystemAccess = this.createFileSystemAccess(serviceProvider, resource);
	fileSystemAccess.setBeforeWrite((uri, outputCfgName, contents) -> {
		newMappings.addSource2Generated(source, uri, outputCfgName);
		previous.remove(uri);
		request.setResultGeneratedFile(source, uri);
		return contents;
	});
	fileSystemAccess.setBeforeDelete((uri) -> {
		newMappings.deleteGenerated(uri);
		request.setResultDeleteFile(uri);
		return true;
	});
	fileSystemAccess.setContext(resource);
	if (request.isWriteStorageResources() && resource instanceof StorageAwareResource) {
		IResourceStorageFacade resourceStorageFacade = ((StorageAwareResource) resource)
				.getResourceStorageFacade();
		if (resourceStorageFacade != null) {
			resourceStorageFacade.saveResource((StorageAwareResource) resource, fileSystemAccess);
		}
	}
	if (request.canGenerate()) {
		GeneratorContext generatorContext = new GeneratorContext();
		generatorContext.setCancelIndicator(request.getCancelIndicator());
		generator.generate(resource, fileSystemAccess, generatorContext);
		XtextResourceSet resourceSet = request.getResourceSet();
		for (URI noLongerCreated : previous) {
			try {
				resourceSet.getURIConverter().delete(noLongerCreated, CollectionLiterals.emptyMap());
				request.setResultDeleteFile(noLongerCreated);
			} catch (IOException e) {
				Exceptions.sneakyThrow(e);
			}
		}
	}
}