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

The following examples show how to use org.eclipse.emf.common.util.URI#isPlatformResource() . 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: XbaseHoverDocumentationProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected boolean handleDocRoot(TagElement node) {
	if (!TagElement.TAG_DOCROOT.equals(node.getTagName()))
		return false;
	URI uri = EcoreUtil.getURI(context);
	if (uri.isPlatformResource()) {
		IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(uri.toPlatformString(true)));
		IPath fullPath = file.getFullPath();
		IProject project = file.getProject();
		if (project.exists() && project.isOpen()) {
			for (IContainer f : sourceFolderProvider.getSourceFolders(project)) {
				if (f.getFullPath().isPrefixOf(fullPath)) {
					IPath location = f.getLocation();
					if (location != null) {
						buffer.append(location.toFile().toURI().toASCIIString());
						return true;
					}
				}
			}
		}
	}
	return true;
}
 
Example 2
Source File: IXtextDocument.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Supported adapter types are {@link IFile}, {@link IResource}, {@link URI} and real supertypes of the implementation class, e.g. all
 * document extensions.
 */
default public <T> T getAdapter(Class<T> adapterType) {
	if (adapterType.isInstance(this)) {
		return adapterType.cast(this);
	}
	if (URI.class.equals(adapterType)) {
		return adapterType.cast(getResourceURI());
	}
	if (IFile.class.equals(adapterType) || IResource.class.equals(adapterType)) {
		URI resourceURI = getResourceURI();
		if (resourceURI.isPlatformResource()) {
			return adapterType.cast(ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(resourceURI.toPlatformString(true))));
		}
	}
	return Platform.getAdapterManager().getAdapter(this, adapterType);
}
 
Example 3
Source File: CheckGenModelUtil.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Given a base URI, figure out which {@link IFolder}, if any, it refers to.
 *
 * @param baseURI
 *          to find the folder(s) for; must not be {@code null}
 * @return an array of all folders mapping to that URI, or an empty array if none do.
 */
private static IContainer[] determineContainersToCheck(final URI baseURI) {
  Preconditions.checkNotNull(baseURI);
  IContainer[] result = {};
  if (baseURI.isPlatformResource() || baseURI.isFile()) {
    IWorkspaceRoot workspace = EcorePlugin.getWorkspaceRoot();
    if (workspace != null) {
      if (baseURI.isFile()) {
        result = workspace.findContainersForLocationURI(java.net.URI.create(baseURI.toString()));
      } else {
        // Must be a platform/resource URI
        IPath platformPath = new Path(baseURI.toPlatformString(true));
        IFolder folder = workspace.getFolder(platformPath);
        if (folder != null) {
          result = new IContainer[] {folder};
        }
      }
    }
  }
  return result;
}
 
Example 4
Source File: EclipseBasedShouldGenerate.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean shouldGenerate(Resource resource, CancelIndicator cancelIndicator) {
	URI uri = resource.getURI();
	if (uri == null || !uri.isPlatformResource()) {
		return false;
	}

	IResource member = ResourcesPlugin.getWorkspace().getRoot().findMember(new Path(uri.toPlatformString(true)));
	if (member != null && member.getType() == IResource.FILE) {
		ProjectConfigAdapter projectConfigAdapter = ProjectConfigAdapter.findInEmfObject(resource.getResourceSet());
		if (projectConfigAdapter != null) {
			IProjectConfig projectConfig = projectConfigAdapter.getProjectConfig();
			if (projectConfig != null && Objects.equals(member.getProject().getName(), projectConfig.getName())) {
				try {
					return member.findMaxProblemSeverity(null, true, IResource.DEPTH_INFINITE) != IMarker.SEVERITY_ERROR;
				} catch (CoreException e) {
					LOG.error("The resource " + member.getName() + " does not exist", e);
					return false;
				}
			}
		}
	}
	return false;
}
 
Example 5
Source File: XtextProposalProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void completeGrammar_Name(EObject model, Assignment assignment, ContentAssistContext context,
		ICompletionProposalAcceptor acceptor) {
	Resource resource = model.eResource();
	URI uri = resource.getURI();
	if (uri.isPlatformResource()) {
		IPath path = new Path(uri.toPlatformString(true));
		IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
		IProject project = file.getProject();
		IJavaProject javaProject = JavaCore.create(project);
		if (javaProject != null) {
			try {
				for (IPackageFragmentRoot packageFragmentRoot : javaProject.getPackageFragmentRoots()) {
					IPath packageFragmentRootPath = packageFragmentRoot.getPath();
					if (packageFragmentRootPath.isPrefixOf(path)) {
						IPath relativePath = path.makeRelativeTo(packageFragmentRootPath);
						relativePath = relativePath.removeFileExtension();
						String result = relativePath.toString();
						result = result.replace('/', '.');
						acceptor.accept(createCompletionProposal(result, context));
						return;
					}
				}
			} catch (JavaModelException ex) {
				// nothing to do
			}
		}
	}
}
 
Example 6
Source File: AbstractFileSystemSupport.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected Path getPath(final URI absoluteURI, final URI baseURI, final Path basePath) {
  Path _xblockexpression = null;
  {
    URI _xifexpression = null;
    if ((baseURI.isPlatformResource() && absoluteURI.isPlatformResource())) {
      URI _xifexpression_1 = null;
      String _segment = baseURI.segment(1);
      String _segment_1 = absoluteURI.segment(1);
      boolean _notEquals = (!Objects.equal(_segment, _segment_1));
      if (_notEquals) {
        URI _xblockexpression_1 = null;
        {
          String _platformString = absoluteURI.toPlatformString(true);
          final org.eclipse.core.runtime.Path p = new org.eclipse.core.runtime.Path(_platformString);
          String _string = p.toString();
          String _plus = (".." + _string);
          _xblockexpression_1 = URI.createURI(_plus);
        }
        _xifexpression_1 = _xblockexpression_1;
      } else {
        _xifexpression_1 = absoluteURI.deresolve(baseURI);
      }
      _xifexpression = _xifexpression_1;
    } else {
      _xifexpression = absoluteURI.deresolve(baseURI);
    }
    final URI relativeURI = _xifexpression;
    if ((relativeURI.isEmpty() || Objects.equal(relativeURI, absoluteURI))) {
      return null;
    }
    _xblockexpression = basePath.getAbsolutePath(relativeURI.toString());
  }
  return _xblockexpression;
}
 
Example 7
Source File: EclipsePreferencesProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private IProject getProject(Resource resource) {
	URI uri = resource.getURI();
	if (uri.isPlatformResource()) {
		final IProject project = getWorkspaceRoot().getProject(uri.segment(1));
		if (project.isAccessible())
			return project;
	}
	return null;
}
 
Example 8
Source File: DefaultResourceUIServiceProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.9
 */
@Override
public boolean isSource(URI uri) {
	if (delegate instanceof IResourceServiceProviderExtension) {
		if (!((IResourceServiceProviderExtension) delegate).isSource(uri))
			return false;
	}
	if (workspace != null) {
		if (uri.isPlatformResource()) {
			String projectName = URI.decode(uri.segment(1));
			IProject project = workspace.getRoot().getProject(projectName);
			return project.isAccessible();
		}
		if (uri.isPlatformPlugin()) {
			return false;
		}
	}
	Iterable<Pair<IStorage, IProject>> storages = storage2UriMapper.getStorages(uri);
	for (Pair<IStorage, IProject> pair : storages) {
		IStorage storage = pair.getFirst();
		if (storage instanceof IFile) {
			return ((IFile)storage).isAccessible();
		} else {
			return false;
		}
	}
	return true;
}
 
Example 9
Source File: ParallelResourceLoader.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Make sure that all files that are about to be loaded are synchronized with the file system
 */
private void synchronizeResources(Collection<URI> toLoad) {
	IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
	for(URI uri : toLoad) {
		if (uri.isPlatformResource()) {
			Path path = new Path(uri.toPlatformString(true));
			IFile file = root.getFile(path);
			try {
				file.refreshLocal(IResource.DEPTH_ZERO, new NullProgressMonitor());
			} catch (CoreException e) {
				throw new RuntimeException(e);
			}
		}
	}
}
 
Example 10
Source File: N4JSStorage2UriMapper.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * GH-1190: disable a new behavior of Xtext, which adds pairs <code>FileStoreStorage -> null</code> for file URIs
 * (see private method <code>#getStorages(URI, IFile)</code> of super class), because these pairs will lead to a
 * NullPointerException in Xtext's {@code ToBeBuiltComputer#doRemoveProject(IProject, IProgressMonitor)} when
 * applied to a project located in the external library workspace.
 */
@Override
public Iterable<Pair<IStorage, IProject>> getStorages(URI uri) {
	Iterable<Pair<IStorage, IProject>> storages = super.getStorages(uri);
	if (!uri.isPlatformResource() && uri.isFile()) {
		storages = super.getContribution().getStorages(uri);
	} else {
		storages = super.getStorages(uri);
	}
	return Iterables.filter(storages,
			pair -> !(pair != null && pair.getFirst() instanceof FileStoreStorage));
}
 
Example 11
Source File: XtendUIResourceDescriptionManager.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
private boolean isProjectDependency(URI deltaURI, URI candidateURI, Map<String, Boolean> checkedProjects) {
	if (deltaURI.isPlatformResource() && candidateURI.isPlatformResource()) {
		// replace escape sequence e.g. %20 by a proper char, e.g. ' ' (blank)
		String deltaProjectName = URI.decode(deltaURI.segment(1));
		// avoid checking the same project again
		Boolean prev = checkedProjects.get(deltaProjectName);
		if (prev == null) {
			IProject deltaProject = workspaceRoot.getProject(deltaProjectName);
			// check if the delta is for a resource from an IJavaProject
			if (deltaProject.isAccessible() && JavaCore.create(deltaProject).exists()) {
				// same here, replace escape sequences by proper chars
				String candidateProjectName = URI.decode(candidateURI.segment(1));
				IProject candidateProject = workspaceRoot.getProject(candidateProjectName);
				if (candidateProject.isAccessible() && JavaCore.create(deltaProject).exists()) {
					if (candidateProject.equals(deltaProject)) {
						return checked(checkedProjects, deltaProjectName, true);
					}
					try {
						if (Arrays.asList(candidateProject.getReferencedProjects()).contains(deltaProject)) {
							return checked(checkedProjects, deltaProjectName, true);
						}
					} catch (CoreException e) {
						return checked(checkedProjects, deltaProjectName, false);
					}
				}
			}
			return checked(checkedProjects, deltaProjectName, false);
		}
		return prev;
	}
	return false;
}
 
Example 12
Source File: GenerationFileNamesPage.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Gets the file name from the given {@link URI}.
 * 
 * @param uri
 *            the {@link URI}
 * @return the file name from the given {@link URI}
 */
private String getFileName(URI uri) {
    final String res;

    if (uri.isPlatformResource()) {
        res = uri.toPlatformString(true);
    } else {
        res = "";
    }

    return res;
}
 
Example 13
Source File: XtendRenameStrategy.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected IPath getPathToRename(URI elementURI, ResourceSet resourceSet) {
	EObject targetObject = resourceSet.getEObject(elementURI, false);
	if (targetObject instanceof XtendTypeDeclaration) {
		URI resourceURI = EcoreUtil2.getPlatformResourceOrNormalizedURI(targetObject).trimFragment();
		if (!resourceURI.isPlatformResource())
			throw new RefactoringException("Renamed type does not reside in the workspace");
		IPath path = new Path(resourceURI.toPlatformString(true));
		if(context instanceof IChangeRedirector.Aware) { 
			if(((IChangeRedirector.Aware) context).getChangeRedirector().getRedirectedPath(path) != path)
				return null;
		}
		return path;
	}
	return null;
}
 
Example 14
Source File: FileUtils.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
public static IFile getFile(final String path, final URI root, final boolean mustExist) {
	final URI uri = getURI(path, root);
	if (uri != null) {
		if (uri.isPlatformResource()) { return getWorkspaceFile(uri); }
		return createLinkToExternalFile(path, root);
	}
	return null;
}
 
Example 15
Source File: ProjectDescriptionLoadListener.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
void onDescriptionLoaded(URI location) {
	if (location.isPlatformResource() && location.segmentCount() == 2) {
		IN4JSEclipseProject n4project = eclipseCore.create(location);
		IProject eclipseProject = n4project.getProject();
		updateProjectReferencesIfNecessary(eclipseProject);
	}
}
 
Example 16
Source File: WorkingCopyOwnerProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public WorkingCopyOwner getWorkingCopyOwner(final IJavaProject javaProject, final ResourceSet resourceSet) {
	return new WorkingCopyOwner() {
		@Override
		public String findSource(String typeName, String packageName) {
			if (packageName.startsWith("java"))
				return super.findSource(typeName, packageName);
			QualifiedName qn = toQualifiedName(packageName, typeName);
			final IResourceDescriptions descriptions = descriptionsProvider.getResourceDescriptions(resourceSet);
			Iterator<IEObjectDescription> exportedObjects = descriptions.getExportedObjects(TypesPackage.Literals.JVM_DECLARED_TYPE, qn, false).iterator();
			while (exportedObjects.hasNext()) {
				IEObjectDescription candidate = exportedObjects.next();
				URI uri = candidate.getEObjectURI();
				if (uri.isPlatformResource() && URI.decode(uri.segment(1)).equals(javaProject.getElementName())) {
					IResourceDescription resourceDescription = descriptions.getResourceDescription(uri.trimFragment());
					return getSource(typeName, packageName, candidate, resourceSet, resourceDescription);
				}
			}
			return super.findSource(typeName, packageName);
		}
		
		
		/**
		 * not implemented because we don't have a proper index for Java package names and the very rare cases in which this would
		 * cause trouble are not worth the general degrade in performance.
		 */
		@Override public boolean isPackage(String[] pkg) {
			return super.isPackage(pkg);
		}
	};
}
 
Example 17
Source File: AbstractDefaultFeatureValueProvider.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
protected String getProjectName(EObject contextElement) {
	URI uri = EcoreUtil.getURI(contextElement);
	if (uri.isPlatformResource() && uri.segmentCount() > 1) {
		return URI.decode(uri.segment(1)); // 0 is resource
	}
	return "ProjectName";
}
 
Example 18
Source File: EclipseBasedN4JSWorkspace.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public PlatformResourceURI fromURI(URI uri) {
	if (!uri.isPlatformResource()) {
		return null;
	}
	return new PlatformResourceURI(uri);
}
 
Example 19
Source File: SCTFileEditorOpener.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
public IFile toFile(URI uri) {
	if (uri.isPlatformResource()) {
		String platformString = uri.toPlatformString(true);
		return (IFile) ResourcesPlugin.getWorkspace().getRoot().findMember(platformString);
	}
	return null;
}
 
Example 20
Source File: ResourceUtil.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Finds the file corresponding to the specified URI, using a URI converter if necessary (and provided) to normalize
 * it.
 * 
 * @param uri
 *            a URI
 * @param converter
 *            an optional URI converter (may be <code>null</code>)
 * 
 * @return the file, if available in the workspace
 */
private static IFile getFile(URI uri, URIConverter converter, boolean considerArchives) {
	IFile result = null;

	if (considerArchives && uri.isArchive()) {
		class MyArchiveURLConnection extends ArchiveURLConnection {
			public MyArchiveURLConnection(String url) {
				super(url);
			}

			public String getNestedURI() {
				try {
					return getNestedURL();
				} catch (IOException exception) {
					return ""; //$NON-NLS-1$
				}
			}
		}
		MyArchiveURLConnection archiveURLConnection = new MyArchiveURLConnection(uri.toString());
		result = getFile(URI.createURI(archiveURLConnection.getNestedURI()), converter, considerArchives);
	} else if (uri.isPlatformResource()) {
		IPath path = new Path(uri.toPlatformString(true));
		result = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
	} else if (uri.isFile() && !uri.isRelative()) {
		result = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(new Path(uri.toFileString()));
	} else {
		// normalize, to see whether we can resolve it this time
		if (converter != null) {
			URI normalized = converter.normalize(uri);

			if (!uri.equals(normalized)) {
				// recurse on the new URI
				result = getFile(normalized, converter, considerArchives);
			}
		}
	}

	if ((result == null) && !uri.isRelative()) {
		try {
			IFile[] files = ResourcesPlugin.getWorkspace().getRoot().findFilesForLocationURI(
					new java.net.URI(uri.toString()));
			if (files.length > 0) {
				// set the result to be the first file found
				result = files[0];
			}
		} catch (URISyntaxException e) {
			// won't get this because EMF provides a well-formed URI
		}
	}

	return result;
}