Java Code Examples for org.eclipse.emf.common.util.URI#isPlatform()

The following examples show how to use org.eclipse.emf.common.util.URI#isPlatform() . 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: ProjectDescriptionUtils.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Given a URI as used internally to identify N4JS projects, this method returns the corresponding N4JS project name
 * which may or may not {@link #isProjectNameWithScope(String) include an npm scope}. The given URI may be a
 * {@link URI#isFile() file URI} (headless case) or a {@link URI#isPlatform() platform URI} (UI case).
 * <p>
 * For details on N4JS project name handling, see {@link #isProjectNameWithScope(String)}.
 */
public static String deriveN4JSProjectNameFromURI(URI uri) {
	if (uri == null) {
		return null;
	}
	int segCount = uri.segmentCount();
	String last = segCount > 0 ? uri.segment(segCount - 1) : null;
	if (uri.isPlatform()) {
		// due to Eclipse conventions we cannot influence, the scope name and plain project name are represented
		// within a single segment in platform URIs:
		if (last != null && last.startsWith(NPM_SCOPE_PREFIX)) {
			last = replaceFirst(last, NPM_SCOPE_SEPARATOR_ECLIPSE, NPM_SCOPE_SEPARATOR);
		}
		return last;
	} else if (uri.isFile()) {
		// due to conventions we cannot influence, the scope name and plain project name are represented as two
		// separate segments in file URIs:
		String secondToLast = segCount > 1 ? uri.segment(segCount - 2) : null;
		if (secondToLast != null && secondToLast.startsWith(NPM_SCOPE_PREFIX)) {
			return secondToLast + NPM_SCOPE_SEPARATOR + last;
		}
		return last;
	}
	throw new IllegalArgumentException("neither a file nor a platform URI: " + uri);
}
 
Example 2
Source File: ProjectDescriptionUtils.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/** Creates a new instance. Given URI should point to an N4JS project, not a file within an N4JS project. */
public static ProjectNameInfo of(URI projectUri) {
	if (projectUri.isFile()) {
		if (projectUri.lastSegment().isEmpty()) {
			// folders end with an empty segment?
			// projectUri = projectUri.trimSegments(1);
		}
		// a file URI actually represents the file system hierarchy -> no need to look up names on disk
		return new ProjectNameInfo(
				projectUri.lastSegment(),
				projectUri.trimSegments(1).lastSegment(),
				Optional.absent() // no Eclipse project name in this case
		);
	} else if (projectUri.isPlatform()) {
		// for platform URIs (i.e. UI case) we actually have to look up the folder name on disk
		final String platformURI = projectUri.toPlatformString(true);
		final IResource resource = ResourcesPlugin.getWorkspace().getRoot().findMember(platformURI);
		final IPath path = resource.getLocation();
		return new ProjectNameInfo(
				path.lastSegment(),
				path.removeLastSegments(1).lastSegment(),
				resource instanceof IProject ? Optional.of(resource.getName()) : Optional.absent());
	}
	throw new IllegalStateException("not a file or platform URI: " + projectUri);
}
 
Example 3
Source File: EObjectUtil.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Return the fie location of a given object in a text resource as the path to the file and the line number.
 * <p>
 * This is very similar to {@link #getLocationString(EObject)} but it will not include the {@link Object#toString()} representation of the object.
 *
 * @param object
 *          any EObject
 * @return a string representation of the location of this object in its file, never {@code null}
 */
public static String getFileLocation(final EObject object) {
  if (object == null || object.eResource() == null) {
    return ""; //$NON-NLS-1$
  }

  URI uri = object.eResource().getURI();
  // CHECKSTYLE:CHECK-OFF MagicNumber
  String path = uri.isPlatform() ? '/' + String.join("/", uri.segmentsList().subList(3, uri.segmentCount())) : uri.path(); //$NON-NLS-1$
  // CHECKSTYLE:CHECK-ON MagicNumber
  StringBuilder result = new StringBuilder(path);
  final ICompositeNode node = NodeModelUtils.getNode(object);
  if (node != null) {
    result.append(':').append(node.getStartLine());
  }

  return result.toString();
}
 
Example 4
Source File: CheckConfigurationStoreService.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Sets the project if an associated instance can be found for given context object.
 * <p>
 * This is the default implementation. Only platform URI-based schemas are supported. Other implementations may overwrite {@link #getProject()}.
 * </p>
 *
 * @param context
 *          the context object, potentially contained by an IProject
 */
protected void setProject(final Object context) {
  if (context instanceof IProject) {
    this.project = (IProject) context;
  } else if (context instanceof IFile) {
    this.project = ((IFile) context).getProject();
  } else {
    URI uri = null;
    if (context instanceof EObject && ((EObject) context).eResource() != null) {
      uri = ((EObject) context).eResource().getURI();
    }
    if (context instanceof Issue) {
      uri = ((Issue) context).getUriToProblem();
    }
    if (uri != null && uri.isPlatform()) {
      final IFile file = (IFile) ResourcesPlugin.getWorkspace().getRoot().findMember(uri.toPlatformString(true));
      this.project = file.getProject();
    }
  }
}
 
Example 5
Source File: EcoreUtil2.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * checks whether the given URI can be loaded given the context. I.e. there's a resource set with a corresponding
 * resource factory and the physical resource exists.
 */
public static boolean isValidUri(Resource resource, URI uri) {
	if (uri == null || uri.isEmpty()) {
		return false;
	}
	URI newURI = getResolvedImportUri(resource, uri);
	try {
		ResourceSet resourceSet = resource.getResourceSet();
		if (resourceSet.getResource(uri, false) != null)
			return true;
		URIConverter uriConverter = resourceSet.getURIConverter();
		URI normalized = uriConverter.normalize(newURI);
		if (normalized != null)
			// fix for https://bugs.eclipse.org/bugs/show_bug.cgi?id=326760
			if("platform".equals(normalized.scheme()) && !normalized.isPlatform()) 
				return false;
			return uriConverter.exists(normalized, Collections.emptyMap());
	} catch (RuntimeException e) { // thrown by org.eclipse.emf.ecore.resource.ResourceSet#getResource(URI, boolean)
		log.trace("Cannot load resource: " + newURI, e);
	}
	return false;
}
 
Example 6
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 7
Source File: GeneratedJsFileLocator.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private IFile tryLocateGeneratedFile(final IFile file) {
	final URI fileUri = createPlatformResourceURI(file.getFullPath().toOSString(), true);
	if (fileUri.isPlatform()) {
		final Optional<? extends IN4JSProject> project = core.findProject(fileUri);
		if (project.isPresent()) {
			try {
				final String targetFileName = resourceNameComputer.generateFileDescriptor(fileUri,
						JS_FILE_EXTENSION);
				// TODO replace hard coded ES5 sub-generator ID once it is clear how to use various
				// sub-generators for runners (IDE-1487)
				final String targetFileRelativeLocation = project.get().getOutputPath() + "/" + targetFileName;
				// file.getProject().
				final IFile targetFile = file.getProject().getFile(targetFileRelativeLocation);
				if (targetFile.exists()) {
					return targetFile;
				}
				final IFile targetFile2 = ResourcesPlugin.getWorkspace().getRoot()
						.getFile(new Path(targetFileRelativeLocation));
				if (targetFile2.exists()) {
					return targetFile2;
				}

				final String projectNameSegment = file.getProject().getName() + "/";
				if (targetFileRelativeLocation.startsWith(projectNameSegment)) {
					String targetFileRelativeLocation3 = targetFileRelativeLocation
							.substring(projectNameSegment.length() - 1);
					final IFile targetFile3 = file.getProject().getFile(targetFileRelativeLocation3);
					if (targetFile3.exists()) {
						return targetFile3;
					}
				}
			} catch (RuntimeException re) {
				// file is not contained in a source container.
				return null;
			}
		}
	}
	return null;
}
 
Example 8
Source File: Animator.java    From txtUML with Eclipse Public License 1.0 5 votes vote down vote up
private void addAnimationMarker(EObject eobject) {
	IResource resource = null;
	IWorkspace workspace = ResourcesPlugin.getWorkspace(); 
	if (workspace != null) {
		URI uri = eobject.eResource().getURI();
		if (uri.isPlatform()) {
			resource = workspace.getRoot().getFile(new Path(uri.toPlatformString(true)));
		} else {
			IPath fs = new Path(uri.toFileString());
			for (IProject proj : workspace.getRoot().getProjects()) {
				if (proj.getLocation().isPrefixOf(fs)) {
					IPath relative = fs.makeRelativeTo(proj.getLocation());
					resource = proj.findMember(relative);
				}
			}
		}
	}
	if (resource != null && resource.exists()) {
		IMarker imarker = null;
		try {
			imarker = resource.createMarker(AnimationConfig.TXTUML_ANIMATION_MARKER_ID);
			imarker.setAttribute(EValidator.URI_ATTRIBUTE, URI.createPlatformResourceURI(resource.getFullPath().toString(), true) + "#" + EcoreUtil.getURI(eobject).fragment());
		} catch (CoreException e) {
			e.printStackTrace();
		}
		if (imarker != null) {
			IPapyrusMarker marker = PapyrusMarkerAdapter.wrap(eobject.eResource(), imarker);
			eobjectToMarker.put(eobject, marker);
		}
	}
}
 
Example 9
Source File: DefaultGenArtifactConfigurations.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
protected String relative(URI uri) {
	if (uri.isFile()) {
		return uri.toFileString();
	} else if (uri.isPlatform()) {
		return uri.toPlatformString(true);
	}
	throw new IllegalArgumentException("Unknown URI " + uri);
}
 
Example 10
Source File: EObjectDescription.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected URI normalize(EObject element, URI uri) {
	if (uri != null && !uri.isPlatform() && element != null && element.eResource() != null) {
		ResourceSet resourceSet = element.eResource().getResourceSet();
		if (resourceSet != null)
			return resourceSet.getURIConverter().normalize(uri);
	}
	return uri;
}
 
Example 11
Source File: DefaultTraceURIConverter.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
private SourceRelativeURI getURIForTrace(URI qualifiedURI) {
	if (qualifiedURI.isPlatform()) {
		// create a URI that is relative to the containing project or bundle
		List<String> segments = qualifiedURI.segmentsList().subList(2, qualifiedURI.segmentCount());
		return new SourceRelativeURI(URI.createHierarchicalURI(segments.toArray(new String[segments.size()]), null, null));
	}
	return SourceRelativeURI.fromAbsolute(qualifiedURI);
}
 
Example 12
Source File: ResourceForIEditorInputFactory.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected Resource createResourceFor(IStorage storage) throws CoreException {
	ResourceSet resourceSet = getResourceSet(storage);
	URI uri = URI.createPlatformResourceURI(storage.getFullPath().toString(), true);
	configureResourceSet(resourceSet, uri);
	URI uriForResource = uri; 
	if (!uri.isPlatform()) {
		uriForResource = resourceSet.getURIConverter().normalize(uri);
	}
	XtextResource resource = (XtextResource) resourceFactory.createResource(uriForResource);
	resourceSet.getResources().add(resource);
	resource.setValidationDisabled(isValidationDisabled(uri, storage));
	return resource;
}
 
Example 13
Source File: JavaProjectsStateHelper.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected IPackageFragmentRoot getPackageFragmentRoot(URI uri) {
	if (uri.isArchive() || !uri.isPlatform()) {
		return getJarWithEntry(uri);
	}
	final IFile file = getWorkspaceRoot().getFile(new Path(uri.toPlatformString(true)));
	if (file == null) {
		return getJarWithEntry(uri);
	}
	IPackageFragmentRoot root = getJavaElement(file);
	if (root == null)
		return getJarWithEntry(uri);
	return root;
}
 
Example 14
Source File: WorkspaceProjectsStateHelper.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public String initHandle(URI uri) {
	if (!uri.isPlatform())
		return null;
	final IFile file = getWorkspaceRoot().getFile(new Path(uri.toPlatformString(true)));
	if (file == null) {
		return null;
	}
	final IProject project = file.getProject();
	return project.getName();
}
 
Example 15
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 16
Source File: EMFGeneratorFragment.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected static URI toPlatformResourceURI(URI uri) {
	if (uri.isPlatform())
		return uri;
	Map<String, URI> map = EcorePlugin.getPlatformResourceMap();
	for (Entry<String, URI> entries : map.entrySet()) {
		final URI newPrefix = URI.createURI("platform:/resource/" + entries.getKey() + "/");
		URI uri2 = uri.replacePrefix(entries.getValue(), newPrefix);
		if (uri2 != null)
			return uri2;
	}
	return uri;
}
 
Example 17
Source File: XtendUIResourceDescriptionManager.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
@Override
	public boolean isAffected(Collection<Delta> deltas, IResourceDescription candidate, IResourceDescriptions context) {
		// skip collecting the outgoing references since we don't index references anyway
//		Set<URI> outgoingReferences = getDescriptionUtils().collectOutgoingReferences(candidate);
//		if (!outgoingReferences.isEmpty()) {
//			for (IResourceDescription.Delta delta : deltas)
//				if (hasChanges(delta, candidate) && outgoingReferences.contains(delta.getUri()))
//					return true;
//		}
		
		// this is a tradeoff - we could either check whether a given delta uri is contained
		// in a reachable container and check for intersecting names afterwards, or we can do
		// the other way round
		// unfortunately there is no way to decide reliably which algorithm scales better
		// note that this method is called for each description so we have something like a 
		// number of deltas x number of resources which is not really nice
		List<IContainer> containers = null;
		Collection<QualifiedName> importedNames = getImportedNames(candidate);
		Map<String, Boolean> checkedProjects = Maps.newHashMap();
		for (IResourceDescription.Delta delta : deltas) {
			if (hasChanges(delta, candidate)) {
				// not a java resource - delta's resource should be contained in a visible container
				// as long as we did not delete the resource
				URI uri = delta.getUri();
				if ((uri.isPlatform() || uri.isArchive()) && delta.getNew() != null) {
					if (containers == null)
						containers = getContainerManager().getVisibleContainers(candidate, context);
					boolean descriptionIsContained = false;
					for (int i = 0; i < containers.size() && !descriptionIsContained; i++) {
						descriptionIsContained = containers.get(i).hasResourceDescription(uri);
					}
					if (!descriptionIsContained && !isProjectDependency(uri, candidate.getURI(), checkedProjects)) {
						return false;
					}
				}
				if (isAffected(importedNames, delta.getNew()) || isAffected(importedNames, delta.getOld())) {
					return true;
				}
			}
		}
		return false;
    }
 
Example 18
Source File: TraceRegionSerializer.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
public <Location, Region> Region doReadFrom(DataInput dataStream, Strategy<Region, Location> reader, Region parent, int version)
		throws IOException {
	int offset = dataStream.readInt();
	int length = dataStream.readInt();
	int lineNumber = dataStream.readInt();
	int endLineNumber = dataStream.readInt();
	boolean useForDebugging = version < VERSION_5 || dataStream.readBoolean();
	int locationSize = dataStream.readInt();
	List<Location> allLocations = Lists.newArrayListWithCapacity(locationSize);
	while(locationSize != 0) {
		int locationOffset = dataStream.readInt();
		int locationLength = dataStream.readInt();
		int locationLineNumber = dataStream.readInt();
		int locationEndLineNumber = dataStream.readInt();
		final SourceRelativeURI path;
		if (dataStream.readBoolean()) {
			if (version < VERSION_5) {
				URI uri = URI.createURI(dataStream.readUTF());
				if (version == VERSION_3 && !uri.isRelative()) {
					if (uri.isPlatform()) {
						String platformString = uri.toPlatformString(false);
						path = new SourceRelativeURI(platformString.substring(platformString.indexOf('/') + 1));
					} else if (uri.isFile()) {
						path = new SourceRelativeURI(uri.lastSegment());
					} else {
						path = SourceRelativeURI.fromAbsolute(uri);
					}
				} else {
					path = new SourceRelativeURI(uri);
				}
			} else {
				path = new SourceRelativeURI(dataStream.readUTF());
			}
		} else {
			path = null;
		}
		if(version == VERSION_3) {
			if (dataStream.readBoolean()) // true, if a project is specified
				dataStream.readUTF(); // read and skip the project name
		}
		allLocations.add(reader.createLocation(locationOffset, locationLength, locationLineNumber, locationEndLineNumber, path));
		locationSize--;
	}
	Region result = reader.createRegion(offset, length, lineNumber, endLineNumber, useForDebugging, allLocations, parent);
	int childrenSize = dataStream.readInt();
	while(childrenSize != 0) {
		doReadFrom(dataStream, reader, result, version);
		childrenSize--;
	}
	return result;
}
 
Example 19
Source File: ExternalPackagesPluginTest.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Checks if expected list of stringified file locations matches
 *
 * @param expected
 *            collection of entries
 * @param actual
 *            collection of entries
 */
public void assertResourceDescriptions(Collection<String> expected, Iterable<IResourceDescription> actual) {
	Set<String> extraDescriptions = new HashSet<>();
	Set<String> missingDescriptions = new HashSet<>(expected);

	for (IResourceDescription iResourceDescription : actual) {
		URI uri = iResourceDescription.getURI();
		String stringUri = uri.isPlatform() ? uri.toPlatformString(false) : uri.toFileString();

		String missingDescription = "";
		for (String missingDescr : missingDescriptions) {
			if (stringUri.endsWith(missingDescr)) {
				missingDescription = missingDescr;
				break;
			}
		}

		if (missingDescription.isEmpty()) {
			extraDescriptions.add(stringUri);
		} else {
			missingDescriptions.remove(missingDescription);
		}
	}

	if (missingDescriptions.isEmpty() && extraDescriptions.isEmpty()) {
		return;
	}

	StringBuilder msg = new StringBuilder("unexpected actual resources" + "\n");

	if (!extraDescriptions.isEmpty()) {
		msg.append("actual contains " + extraDescriptions.size() + " extra resources" + "\n");
	}

	if (!missingDescriptions.isEmpty()) {
		msg.append("actual is missing  " + missingDescriptions.size() + " expected resources" + "\n");
	}

	for (String extra : extraDescriptions) {
		msg.append("[extra] " + extra + "\n");
	}
	for (String missing : missingDescriptions) {
		msg.append("[missing] " + missing + "\n");
	}
	fail(msg.toString());
}
 
Example 20
Source File: GenerationPropertyTester.java    From M2Doc with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Returns <code>true</code> when the generation has a local URI (platform or file).
 * 
 * @param generation
 *            the tested generation.
 * @return <code>true</code> for local objects.
 */
private boolean isLocal(Generation generation) {
    URI uri = generation.eResource().getURI();
    return uri.isFile() || uri.isPlatform();
}