Java Code Examples for org.eclipse.core.runtime.IPath#isPrefixOf()

The following examples show how to use org.eclipse.core.runtime.IPath#isPrefixOf() . 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: ClassPathDetector.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void detectSourceFolders(ArrayList<IClasspathEntry> resEntries) {
	ArrayList<IClasspathEntry> res= new ArrayList<IClasspathEntry>();
	Set<IPath> sourceFolderSet= fSourceFolders.keySet();
	for (Iterator<IPath> iter= sourceFolderSet.iterator(); iter.hasNext();) {
		IPath path= iter.next();
		ArrayList<IPath> excluded= new ArrayList<IPath>();
		for (Iterator<IPath> inner= sourceFolderSet.iterator(); inner.hasNext();) {
			IPath other= inner.next();
			if (!path.equals(other) && path.isPrefixOf(other)) {
				IPath pathToExclude= other.removeFirstSegments(path.segmentCount()).addTrailingSeparator();
				excluded.add(pathToExclude);
			}
		}
		IPath[] excludedPaths= excluded.toArray(new IPath[excluded.size()]);
		IClasspathEntry entry= JavaCore.newSourceEntry(path, excludedPaths);
		res.add(entry);
	}
	Collections.sort(res, new CPSorter());
	resEntries.addAll(res);
}
 
Example 2
Source File: EclipseBuildSupport.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean isBuildFile(IResource resource) {
	if (resource == null || resource.getProject() == null) {
		return false;
	}
	IProject project = resource.getProject();
	for (String file : files) {
		if (resource.equals(project.getFile(file))) {
			return true;
		}
	}
	IPath path = resource.getFullPath();
	for (String folder : folders) {
		IPath folderPath = project.getFolder(folder).getFullPath();
		if (folderPath.isPrefixOf(path)) {
			return true;
		}
	}
	return false;
}
 
Example 3
Source File: BuildPathsBlock.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private CPListElement findElement(IClasspathEntry entry) {
	CPListElement prefixMatch= null;
	int entryKind= entry.getEntryKind();
	for (int i= 0, len= fClassPathList.getSize(); i < len; i++) {
		CPListElement curr= fClassPathList.getElement(i);
		if (curr.getEntryKind() == entryKind) {
			IPath entryPath= entry.getPath();
			IPath currPath= curr.getPath();
			if (currPath.equals(entryPath)) {
				return curr;
			}
			// in case there's no full match, look for a similar container (same ID segment):
			if (prefixMatch == null && entryKind == IClasspathEntry.CPE_CONTAINER) {
				int n= entryPath.segmentCount();
				if (n > 0) {
					IPath genericContainerPath= n == 1 ? entryPath : entryPath.removeLastSegments(n - 1);
					if (n > 1 && genericContainerPath.isPrefixOf(currPath)) {
						prefixMatch= curr;
					}
				}
			}
		}
	}
	return prefixMatch;
}
 
Example 4
Source File: JarWriter3.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void registerInWorkspaceIfNeeded() {
	IPath jarPath= fJarPackage.getAbsoluteJarLocation();
	IProject[] projects= ResourcesPlugin.getWorkspace().getRoot().getProjects();
	for (int i= 0; i < projects.length; i++) {
		IProject project= projects[i];
		// The Jar is always put into the local file system. So it can only be
		// part of a project if the project is local as well. So using getLocation
		// is currently save here.
		IPath projectLocation= project.getLocation();
		if (projectLocation != null && projectLocation.isPrefixOf(jarPath)) {
			try {
				jarPath= jarPath.removeFirstSegments(projectLocation.segmentCount());
				jarPath= jarPath.removeLastSegments(1);
				IResource containingFolder= project.findMember(jarPath);
				if (containingFolder != null && containingFolder.isAccessible())
					containingFolder.refreshLocal(IResource.DEPTH_ONE, null);
			} catch (CoreException ex) {
				// don't refresh the folder but log the problem
				JavaPlugin.log(ex);
			}
		}
	}
}
 
Example 5
Source File: SARLProposalProvider.java    From sarl with Apache License 2.0 6 votes vote down vote up
private static String extractProjectPath(IPath fileWorkspacePath, IJavaProject javaProject) {
	if (javaProject != null && javaProject.exists() && javaProject.isOpen()) {
		try {
			for (final IPackageFragmentRoot root: javaProject.getPackageFragmentRoots()) {
				if (!root.isArchive() && !root.isExternal()) {
					final IResource resource = root.getResource();
					if (resource != null) {
						final IPath sourceFolderPath = resource.getFullPath();
						if (sourceFolderPath.isPrefixOf(fileWorkspacePath)) {
							final IPath claspathRelativePath = fileWorkspacePath.makeRelativeTo(sourceFolderPath);
							return claspathRelativePath.removeLastSegments(1)
									.toString().replace("/", "."); //$NON-NLS-1$//$NON-NLS-2$
						}
					}
				}
			}
		} catch (JavaModelException e) {
			Logger.getLogger(SARLProposalProvider.class).error(e.getLocalizedMessage(), e);
		}
	}
	return null;
}
 
Example 6
Source File: SVNWorkspaceRoot.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Gets the resources to which the local filesystem <code>location</code> is corresponding to.
   * The resources do not need to exists (yet)
   * @return IResource[]
   * @throws SVNException
   */
  public static IResource[] getResourcesFor(IPath location, boolean includeProjects) {
Set<IResource> resources = new LinkedHashSet<IResource>();
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IProject[] projects = root.getProjects();
for (IProject project : projects) {
	IResource resource = getResourceFor(project, location);
	if (resource != null) {
		resources.add(resource);
	}
	if (includeProjects && isManagedBySubclipse(project) && location.isPrefixOf(project.getLocation())) {
		resources.add(project);
	}
}
return (IResource[]) resources.toArray(new IResource[resources.size()]);
  }
 
Example 7
Source File: BinaryRefactoringHistoryWizard.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected boolean selectStatusEntry(final RefactoringStatusEntry entry) {
	if (fSourceFolder != null) {
		final IPath source= fSourceFolder.getFullPath();
		final RefactoringStatusContext context= entry.getContext();
		if (context instanceof JavaStatusContext) {
			final JavaStatusContext extended= (JavaStatusContext) context;
			final ICompilationUnit unit= extended.getCompilationUnit();
			if (unit != null) {
				final IResource resource= unit.getResource();
				if (resource != null && source.isPrefixOf(resource.getFullPath()))
					return false;
			}
		}
	}
	return super.selectStatusEntry(entry);
}
 
Example 8
Source File: GetFiles.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Gets an IFile inside a container given a path in the filesystem (resolves the full path of the container and
 * checks if the location given is under it).
 */
public static final IFile getFileInContainer(IPath location, IContainer container, boolean mustExist) {
    IPath containerLocation = container.getLocation();
    if (containerLocation != null) {
        if (containerLocation.isPrefixOf(location)) {
            int segmentsToRemove = containerLocation.segmentCount();
            IPath removingFirstSegments = location.removeFirstSegments(segmentsToRemove);
            if (removingFirstSegments.segmentCount() == 0) {
                //It's equal: as we want a file in the container, and the path to the file is equal to the
                //container, we have to return null (because it's equal to the container it cannot be a file).
                return null;
            }
            IFile file = container.getFile(removingFirstSegments);
            if (!mustExist || file.exists()) {
                return file;
            }
        }
    } else {
        if (container instanceof IProject) {
            Log.logInfo("Info: container: " + container + " has no associated location.");
        }
    }
    return null;
}
 
Example 9
Source File: ChangeCollector.java    From workspacemechanic with Eclipse Public License 1.0 5 votes vote down vote up
public void nodeRemoved(IPath parentPath, String childName) {
  // Remove all preference changes rooted at this node or below
  Set<IPath> removedKeys = new HashSet<IPath>();
  for (Map.Entry<IPath, String> entry : preferences.entrySet()) {
    IPath keyPath = entry.getKey();
    if (parentPath.isPrefixOf(keyPath)) {
      removedKeys.add(keyPath);
    }
  }

  for (IPath key : removedKeys) {
    preferences.remove(key);
  }
}
 
Example 10
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 11
Source File: JavaSynchronizationContentProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns whether the element has some children in the current scope.
 *
 * @param scope
 *            the synchronization scope
 * @param element
 *            the element
 * @param resource
 *            the resource
 * @return <code>true</code> if it has some children, <code>false</code>
 *         otherwise
 */
private boolean hasChildrenInScope(final ISynchronizationScope scope, final Object element, final IResource resource) {
	final IResource[] roots= scope.getRoots();
	final IPath path= resource.getFullPath();
	if (element instanceof IPackageFragment) {
		for (int index= 0; index < roots.length; index++)
			if (path.equals(roots[index].getFullPath().removeLastSegments(1)))
				return true;
		return false;
	}
	for (int index= 0; index < roots.length; index++)
		if (path.isPrefixOf(roots[index].getFullPath()))
			return true;
	return false;
}
 
Example 12
Source File: AddSourceFolderWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void addExclusionPatterns(CPListElement newEntry, List<CPListElement> existing, Set<CPListElement> modifiedEntries) {
	IPath entryPath= newEntry.getPath();
	for (int i= 0; i < existing.size(); i++) {
		CPListElement curr= existing.get(i);
		IPath currPath= curr.getPath();
		if (curr != newEntry && curr.getEntryKind() == IClasspathEntry.CPE_SOURCE && currPath.isPrefixOf(entryPath)) {
			boolean added= curr.addToExclusions(entryPath);
			if (added) {
				modifiedEntries.add(curr);
			}
		}
	}
}
 
Example 13
Source File: ProjectUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static boolean addSourcePath(IPath sourcePath, IPath[] exclusionPaths, IJavaProject project) throws CoreException {
	IClasspathEntry[] existingEntries = project.getRawClasspath();
	List<IPath> parentSrcPaths = new ArrayList<>();
	List<IPath> exclusionPatterns = new ArrayList<>();
	for (IClasspathEntry entry : existingEntries) {
		if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
			if (entry.getPath().equals(sourcePath)) {
				return false;
			} else if (entry.getPath().isPrefixOf(sourcePath)) {
				parentSrcPaths.add(entry.getPath());
			} else if (sourcePath.isPrefixOf(entry.getPath())) {
				exclusionPatterns.add(entry.getPath().makeRelativeTo(sourcePath).addTrailingSeparator());
			}
		}
	}

	if (!parentSrcPaths.isEmpty()) {
		throw new CoreException(new Status(IStatus.ERROR, IConstants.PLUGIN_ID, Messages
				.format("Cannot add the folder ''{0}'' to the source path because it''s parent folder is already in the source path of the project ''{1}''.", new String[] { sourcePath.toOSString(), project.getProject().getName() })));
	}

	if (exclusionPaths != null) {
		for (IPath exclusion : exclusionPaths) {
			if (sourcePath.isPrefixOf(exclusion) && !sourcePath.equals(exclusion)) {
				exclusionPatterns.add(exclusion.makeRelativeTo(sourcePath).addTrailingSeparator());
			}
		}
	}

	IClasspathEntry[] newEntries = new IClasspathEntry[existingEntries.length + 1];
	System.arraycopy(existingEntries, 0, newEntries, 0, existingEntries.length);
	newEntries[newEntries.length - 1] = JavaCore.newSourceEntry(sourcePath, exclusionPatterns.toArray(new IPath[0]));
	project.setRawClasspath(newEntries, project.getOutputLocation(), null);
	return true;
}
 
Example 14
Source File: RenamePackageProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public IResource getRefactoredResource(IResource element) {
	IFolder packageFolder= (IFolder) fPackage.getResource();
	if (packageFolder == null) {
		return element;
	}

	IContainer newPackageFolder= (IContainer) getNewPackage().getResource();

	if (packageFolder.equals(element)) {
		return newPackageFolder;
	}

	IPath packagePath= packageFolder.getProjectRelativePath();
	IPath elementPath= element.getProjectRelativePath();

	if (packagePath.isPrefixOf(elementPath)) {
		if (fRenameSubpackages || (element instanceof IFile && packageFolder.equals(element.getParent()))) {
			IPath pathInPackage= elementPath.removeFirstSegments(packagePath.segmentCount());
			if (element instanceof IFile) {
				return newPackageFolder.getFile(pathInPackage);
			} else {
				return newPackageFolder.getFolder(pathInPackage);
			}
		}
	}
	return element;
}
 
Example 15
Source File: FileIndexLocation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public boolean startsWith(IPath path) {
	try {
		return path.isPrefixOf(new Path(this.indexFile.getCanonicalPath()));
	} catch (IOException e) {
		return false;
	}
}
 
Example 16
Source File: PackageExplorerLabelProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private String getNameDelta(IFolder parent, IPackageFragment fragment) {
	IPath prefix= parent.getFullPath();
	IPath fullPath= fragment.getPath();
	if (prefix.isPrefixOf(fullPath)) {
		StringBuffer buf= new StringBuffer();
		for (int i= prefix.segmentCount(); i < fullPath.segmentCount(); i++) {
			if (buf.length() > 0)
				buf.append('.');
			buf.append(fullPath.segment(i));
		}
		return buf.toString();
	}
	return fragment.getElementName();
}
 
Example 17
Source File: DefaultPathsForInterpreterInfo.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * States whether or not a given path is the child of at least one root path of a set of root paths.
 * @param data The path that will be checked for child status.
 * @param rootPaths A set of root paths.
 * @return True if the path of data is a child of any of the paths of rootPaths.
 */
public static boolean isChildOfRootPath(String data, Set<IPath> rootPaths) {
    IPath path = Path.fromOSString(data);
    for (IPath p : rootPaths) {
        if (p.isPrefixOf(path)) {
            return true;
        }
    }
    return false;
}
 
Example 18
Source File: NewTypeWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * A hook method that gets called when the package field has changed. The method
 * validates the package name and returns the status of the validation. The validation
 * also updates the package fragment model.
 * <p>
 * Subclasses may extend this method to perform their own validation.
 * </p>
 *
 * @return the status of the validation
 */
protected IStatus packageChanged() {
	StatusInfo status= new StatusInfo();
	IPackageFragmentRoot root= getPackageFragmentRoot();
	fPackageDialogField.enableButton(root != null);

	IJavaProject project= root != null ? root.getJavaProject() : null;

	String packName= getPackageText();
	if (packName.length() > 0) {
		IStatus val= validatePackageName(packName, project);
		if (val.getSeverity() == IStatus.ERROR) {
			status.setError(Messages.format(NewWizardMessages.NewTypeWizardPage_error_InvalidPackageName, val.getMessage()));
			return status;
		} else if (val.getSeverity() == IStatus.WARNING) {
			status.setWarning(Messages.format(NewWizardMessages.NewTypeWizardPage_warning_DiscouragedPackageName, val.getMessage()));
			// continue
		}
	} else {
		status.setWarning(NewWizardMessages.NewTypeWizardPage_warning_DefaultPackageDiscouraged);
	}

	if (project != null) {
		if (project.exists() && packName.length() > 0) {
			try {
				IPath rootPath= root.getPath();
				IPath outputPath= project.getOutputLocation();
				if (rootPath.isPrefixOf(outputPath) && !rootPath.equals(outputPath)) {
					// if the bin folder is inside of our root, don't allow to name a package
					// like the bin folder
					IPath packagePath= rootPath.append(packName.replace('.', '/'));
					if (outputPath.isPrefixOf(packagePath)) {
						status.setError(NewWizardMessages.NewTypeWizardPage_error_ClashOutputLocation);
						return status;
					}
				}
			} catch (JavaModelException e) {
				JavaPlugin.log(e);
				// let pass
			}
		}

		fCurrPackage= root.getPackageFragment(packName);
		IResource resource= fCurrPackage.getResource();
		if (resource != null){
			if (resource.isVirtual()){
				status.setError(NewWizardMessages.NewTypeWizardPage_error_PackageIsVirtual);
				return status;
			}
			if (!ResourcesPlugin.getWorkspace().validateFiltered(resource).isOK()) {
				status.setError(NewWizardMessages.NewTypeWizardPage_error_PackageNameFiltered);
				return status;
			}
		}
	} else {
		status.setError(""); //$NON-NLS-1$
	}
	return status;
}
 
Example 19
Source File: NewPackageWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Validates the package name and returns the status of the validation.
 * 
 * @param packName the package name
 * 
 * @return the status of the validation
 */
private IStatus getPackageStatus(String packName) {
	StatusInfo status= new StatusInfo();
	if (packName.length() > 0) {
		IStatus val= validatePackageName(packName);
		if (val.getSeverity() == IStatus.ERROR) {
			status.setError(Messages.format(NewWizardMessages.NewPackageWizardPage_error_InvalidPackageName, val.getMessage()));
			return status;
		} else if (val.getSeverity() == IStatus.WARNING) {
			status.setWarning(Messages.format(NewWizardMessages.NewPackageWizardPage_warning_DiscouragedPackageName, val.getMessage()));
		}
	} else {
		status.setError(NewWizardMessages.NewPackageWizardPage_error_EnterName);
		return status;
	}

	IPackageFragmentRoot root= getPackageFragmentRoot();
	if (root != null && root.getJavaProject().exists()) {
		IPackageFragment pack= root.getPackageFragment(packName);
		try {
			IPath rootPath= root.getPath();
			IPath outputPath= root.getJavaProject().getOutputLocation();
			if (rootPath.isPrefixOf(outputPath) && !rootPath.equals(outputPath)) {
				// if the bin folder is inside of our root, don't allow to name a package
				// like the bin folder
				IPath packagePath= pack.getPath();
				if (outputPath.isPrefixOf(packagePath)) {
					status.setError(NewWizardMessages.NewPackageWizardPage_error_IsOutputFolder);
					return status;
				}
			}
			if (pack.exists()) {
				// it's ok for the package to exist as long we want to create package level documentation
				// and the package level documentation doesn't exist
				if (!isCreatePackageDocumentation() || packageDocumentationAlreadyExists(pack)) {
					if (pack.containsJavaResources() || !pack.hasSubpackages()) {
						status.setError(NewWizardMessages.NewPackageWizardPage_error_PackageExists);
					} else {
						status.setError(NewWizardMessages.NewPackageWizardPage_error_PackageNotShown);
					}
				}
			} else {
				IResource resource= pack.getResource();
				if (resource != null && !ResourcesPlugin.getWorkspace().validateFiltered(resource).isOK()) {
					status.setError(NewWizardMessages.NewPackageWizardPage_error_PackageNameFiltered);
					return status;
				}
				URI location= pack.getResource().getLocationURI();
				if (location != null) {
					IFileStore store= EFS.getStore(location);
					if (store.fetchInfo().exists()) {
						status.setError(NewWizardMessages.NewPackageWizardPage_error_PackageExistsDifferentCase);
					}
				}
			}
		} catch (CoreException e) {
			JavaPlugin.log(e);
		}
	}
	return status;
}
 
Example 20
Source File: ClasspathModifier.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Remove <code>path</code> from inclusion/exlusion filters in all <code>existingEntries</code>
 *
 * @param path the path to remove
 * @param project the Java project
 * @param existingEntries a list of <code>CPListElement</code> representing the build path
 * entries of the project.
 * @return returns a <code>List</code> of <code>CPListElement</code> of modified elements, not null.
 */
public static List<CPListElement> removeFilters(IPath path, IJavaProject project, List<CPListElement> existingEntries) {
	if (path == null)
		return Collections.emptyList();

	IPath projPath= project.getPath();
	if (projPath.isPrefixOf(path)) {
		path= path.removeFirstSegments(projPath.segmentCount()).addTrailingSeparator();
	}

	List<CPListElement> result= new ArrayList<CPListElement>();
	for (Iterator<CPListElement> iter= existingEntries.iterator(); iter.hasNext();) {
		CPListElement element= iter.next();
		boolean hasChange= false;
		IPath[] exlusions= (IPath[])element.getAttribute(CPListElement.EXCLUSION);
		if (exlusions != null) {
			List<IPath> exlusionList= new ArrayList<IPath>(exlusions.length);
			for (int i= 0; i < exlusions.length; i++) {
				if (!exlusions[i].equals(path)) {
					exlusionList.add(exlusions[i]);
				} else {
					hasChange= true;
				}
			}
			element.setAttribute(CPListElement.EXCLUSION, exlusionList.toArray(new IPath[exlusionList.size()]));
		}

		IPath[] inclusion= (IPath[])element.getAttribute(CPListElement.INCLUSION);
		if (inclusion != null) {
			List<IPath> inclusionList= new ArrayList<IPath>(inclusion.length);
			for (int i= 0; i < inclusion.length; i++) {
				if (!inclusion[i].equals(path)) {
					inclusionList.add(inclusion[i]);
				} else {
					hasChange= true;
				}
			}
			element.setAttribute(CPListElement.INCLUSION, inclusionList.toArray(new IPath[inclusionList.size()]));
		}
		if (hasChange) {
			result.add(element);
		}
	}
	return result;
}