/* (non-Javadoc) * @see IJavaSearchScope#encloses(IJavaElement) */ public boolean encloses(IJavaElement element) { if (this.elements != null) { for (int i = 0, length = this.elements.size(); i < length; i++) { IJavaElement scopeElement = (IJavaElement) this.elements.get(i); IJavaElement searchedElement = element; while (searchedElement != null) { if (searchedElement.equals(scopeElement)) return true; searchedElement = searchedElement.getParent(); } } return false; } IPackageFragmentRoot root = (IPackageFragmentRoot) element.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); if (root != null && root.isArchive()) { // external or internal jar IPath rootPath = root.getPath(); String rootPathToString = rootPath.getDevice() == null ? rootPath.toString() : rootPath.toOSString(); IPath relativePath = getPath(element, true /*relative path*/); return indexOf(rootPathToString, relativePath.toString()) >= 0; } // resource in workspace String fullResourcePathString = getPath(element, false /*full path*/).toString(); return indexOf(fullResourcePathString) >= 0; }
public String getText(Object element) { if (!(element instanceof IResource)) return null; IResource resource = (IResource) element; String text = null; if (!resource.exists()) text = SearchMessages.FileLabelProvider_removed_resource_label; else { IPath path = resource.getFullPath().removeLastSegments(1); if (path.getDevice() == null) path = path.makeRelative(); if (fOrder == SHOW_LABEL || fOrder == SHOW_LABEL_PATH) { text = fLabelProvider.getText(resource); if (path != null && fOrder == SHOW_LABEL_PATH) { fArgs[0] = text; fArgs[1] = path.toString(); text = MessageFormat.format(fgSeparatorFormat, fArgs); } } else { if (path != null) text = path.toString(); else text = ""; // $NON-NLS-1$ if (fOrder == SHOW_PATH_LABEL) { fArgs[0] = text; fArgs[1] = fLabelProvider.getText(resource); text = MessageFormat.format(fgSeparatorFormat, fArgs); } } } int matchCount = 0; AbstractTextSearchResult result = fPage.getInput(); if (result != null) matchCount = result.getMatchCount(element); if (matchCount <= 1) return text; String format = SearchMessages.FileLabelProvider_count_format; return MessageFormat.format(format, new Object[] {text, new Integer(matchCount)}); }
/** * Recreates the index for a given path, keeping the same read-write monitor. Returns the new * empty index or null if it didn't exist before. Warning: Does not check whether index is * consistent (not being used) */ public synchronized Index recreateIndex(IPath containerPath) { // only called to over write an existing cached index... String containerPathString = containerPath.getDevice() == null ? containerPath.toString() : containerPath.toOSString(); try { // Path is already canonical IPath indexLocation = computeIndexLocation(containerPath); Index index = (Index) this.indexes.get(indexLocation); ReadWriteMonitor monitor = index == null ? null : index.monitor; if (VERBOSE) Util.verbose( "-> recreating index: " + indexLocation + " for path: " + containerPathString); //$NON-NLS-1$ //$NON-NLS-2$ index = new Index(indexLocation.toString(), containerPathString, false /* reuse index file */); this.indexes.put(indexLocation, index); index.monitor = monitor; return index; } catch (IOException e) { // The file could not be created. Possible reason: the project has been deleted. if (VERBOSE) { Util.verbose("-> failed to recreate index for path: " + containerPathString); // $NON-NLS-1$ e.printStackTrace(); } return null; } }
public boolean isPrefixOf(IPath anotherPath) { if (anotherPath.getDevice().equals(device)) { if (segmentCount() <= anotherPath.segmentCount()) { int i = 0; for (String s : segments()) { if (!s.equals(anotherPath.segment(i++))) return false; } return true; } } return false; }
protected IBinaryType createInfoFromClassFileInJar(Openable classFile) { String filePath = (((ClassFile) classFile).getType().getFullyQualifiedName('$')).replace('.', '/') + SuffixConstants.SUFFIX_STRING_class; IPackageFragmentRoot root = classFile.getPackageFragmentRoot(); IPath path = root.getPath(); // take the OS path for external jars, and the forward slash path for internal jars String rootPath = path.getDevice() == null ? path.toString() : path.toOSString(); String documentPath = rootPath + IJavaSearchScope.JAR_FILE_ENTRY_SEPARATOR + filePath; IBinaryType binaryType = (IBinaryType) this.binariesFromIndexMatches.get(documentPath); if (binaryType != null) { this.infoToHandle.put(binaryType, classFile); return binaryType; } else { return super.createInfoFromClassFileInJar(classFile); } }
/** * Helper method - returns the targeted item (IResource if internal or java.io.File if external), * or null if unbound Internal items must be referred to using container relative paths. */ public static Object getTarget(IContainer container, IPath path, boolean checkResourceExistence) { if (path == null) return null; // lookup - inside the container if (path.getDevice() == null) { // container relative paths should not contain a device // (see http://dev.eclipse.org/bugs/show_bug.cgi?id=18684) // (case of a workspace rooted at d:\ ) IResource resource = container.findMember(path); if (resource != null) { if (!checkResourceExistence || resource.exists()) return resource; return null; } } // if path is relative, it cannot be an external path // (see http://dev.eclipse.org/bugs/show_bug.cgi?id=22517) if (!path.isAbsolute()) return null; // lookup - outside the container File externalFile = new File(path.toOSString()); if (!checkResourceExistence) { return externalFile; } else if (existingExternalFiles.contains(externalFile)) { return externalFile; } else { if (ModelWorkspaceManager.ZIP_ACCESS_VERBOSE) { System.out.println( "(" + Thread.currentThread() + ") [ModelWorkspaceImpl.getTarget(...)] Checking existence of " + path.toString()); // $NON-NLS-1$ //$NON-NLS-2$ } if (externalFile.exists()) { // cache external file existingExternalFiles.add(externalFile); return externalFile; } } return null; }
protected void checkIfPatternValid() { String pattern = fExclusionPatternDialog.getText().trim(); if (pattern.length() == 0) { fExclusionPatternStatus.setError(NewWizardMessages.ExclusionInclusionEntryDialog_error_empty); return; } IPath path = new Path(pattern); if (path.isAbsolute() || path.getDevice() != null) { fExclusionPatternStatus.setError( NewWizardMessages.ExclusionInclusionEntryDialog_error_notrelative); return; } if (fExistingPatterns.contains(pattern)) { fExclusionPatternStatus.setError( NewWizardMessages.ExclusionInclusionEntryDialog_error_exists); return; } fExclusionPattern = pattern; fExclusionPatternStatus.setOK(); }
public String getCPElementAttributeText(CPElementAttribute attrib) { String notAvailable = CPathEntryMessages.CPElementLabelProvider_none; StringBuffer buf = new StringBuffer(); String key = attrib.getKey(); if (key.equals(CPElement.SOURCEATTACHMENT)) { buf.append(CPathEntryMessages.CPElementLabelProvider_source_attachment_label); IPath path = (IPath) attrib.getValue(); if (path != null && !path.isEmpty()) { buf.append(getPathString(path, path.getDevice() != null)); } else { buf.append(notAvailable); } } else if (key.equals(CPElement.SOURCEATTACHMENTROOT)) { buf.append(CPathEntryMessages.CPElementLabelProvider_source_attachment_root_label); IPath path = (IPath) attrib.getValue(); if (path != null && !path.isEmpty()) { buf.append(path.toString()); } else { buf.append(notAvailable); } } if (key.equals(CPElement.EXCLUSION)) { buf.append(CPathEntryMessages.CPElementLabelProvider_exclusion_filter_label); IPath[] patterns = (IPath[]) attrib.getValue(); if (patterns != null && patterns.length > 0) { for (int i = 0; i < patterns.length; i++) { if (i > 0) { buf.append(CPathEntryMessages.CPElementLabelProvider_exclusion_filter_separator); } buf.append(patterns[i].toString()); } } else { buf.append(notAvailable); } } return buf.toString(); }
/* (non-Javadoc) * @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object) */ public String getText(Object element) { IRuntimeClasspathEntry entry = (IRuntimeClasspathEntry) element; switch (entry.getType()) { case IRuntimeClasspathEntry.PROJECT: IResource res = entry.getResource(); IJavaElement proj = JavaCore.create(res); if (proj == null) { return entry.getPath().lastSegment(); } else { return lp.getText(proj); } case IRuntimeClasspathEntry.ARCHIVE: IPath path = entry.getPath(); if (path == null) { return MessageFormat.format("Invalid path: {0}", new Object[] {"null"}); // $NON-NLS-1$ } if (!path.isAbsolute() || !path.isValidPath(path.toString())) { return MessageFormat.format("Invalid path: {0}", new Object[] {path.toOSString()}); } String[] segments = path.segments(); StringBuffer displayPath = new StringBuffer(); if (segments.length > 0) { String device = path.getDevice(); if (device != null) { displayPath.append(device); displayPath.append(File.separator); } for (int i = 0; i < segments.length - 1; i++) { displayPath.append(segments[i]).append(File.separator); } displayPath.append(segments[segments.length - 1]); // getDevice means that's a absolute path. if (path.getDevice() != null && !path.toFile().exists()) { displayPath.append(" (missing) "); } } else { displayPath.append(path.toOSString()); } return displayPath.toString(); case IRuntimeClasspathEntry.VARIABLE: path = entry.getPath(); IPath srcPath = entry.getSourceAttachmentPath(); StringBuffer buf = new StringBuffer(path.toString()); if (srcPath != null) { buf.append(" ["); // $NON-NLS-1$ buf.append(srcPath.toString()); IPath rootPath = entry.getSourceAttachmentRootPath(); if (rootPath != null) { buf.append(IPath.SEPARATOR); buf.append(rootPath.toString()); } buf.append(']'); } // append JRE name if we can compute it if (path.equals(new Path(JavaRuntime.JRELIB_VARIABLE)) && fLaunchConfiguration != null) { try { IVMInstall vm = JavaRuntime.computeVMInstall(fLaunchConfiguration); buf.append(" - "); // $NON-NLS-1$ buf.append(vm.getName()); } catch (CoreException e) { } } return buf.toString(); case IRuntimeClasspathEntry.CONTAINER: path = entry.getPath(); if (fLaunchConfiguration != null) { try { IJavaProject project = null; try { project = JavaRuntime.getJavaProject(fLaunchConfiguration); } catch (CoreException e) { } if (project == null) { } else { IClasspathContainer container = JavaCore.getClasspathContainer(entry.getPath(), project); if (container != null) { if (container.getDescription().startsWith("Persisted container")) { return container.getPath().toString(); } else { return container.getDescription(); } } } } catch (CoreException e) { } } return entry.getPath().toString(); case IRuntimeClasspathEntry.OTHER: IRuntimeClasspathEntry delegate = entry; if (entry instanceof ClasspathEntry) { delegate = ((ClasspathEntry) entry).getDelegate(); } String name = lp.getText(delegate); if (name == null || name.length() == 0) { return ((IRuntimeClasspathEntry2) delegate).getName(); } return name; } return ""; //$NON-NLS-1$ }
/** * Add an element to the java search scope. * * @param element The element we want to add to current java search scope * @throws JavaModelException May happen if some Java Model info are not available */ public void add(IJavaElement element) throws JavaModelException { IPath containerPath = null; String containerPathToString = null; PackageFragmentRoot root = null; int includeMask = SOURCES | APPLICATION_LIBRARIES | SYSTEM_LIBRARIES; switch (element.getElementType()) { case IJavaElement.JAVA_MODEL: // a workspace sope should be used break; case IJavaElement.JAVA_PROJECT: add((JavaProject) element, null, includeMask, new HashSet(2), new HashSet(2), null); break; case IJavaElement.PACKAGE_FRAGMENT_ROOT: root = (PackageFragmentRoot) element; IPath rootPath = root.internalPath(); containerPath = root.getKind() == IPackageFragmentRoot.K_SOURCE ? root.getParent().getPath() : rootPath; containerPathToString = containerPath.getDevice() == null ? containerPath.toString() : containerPath.toOSString(); IResource rootResource = root.resource(); String projectPath = root.getJavaProject().getPath().toString(); if (rootResource != null && rootResource.isAccessible()) { String relativePath = Util.relativePath(rootResource.getFullPath(), containerPath.segmentCount()); add(projectPath, relativePath, containerPathToString, false /*not a package*/, null); } else { add(projectPath, "", containerPathToString, false /*not a package*/, null); // $NON-NLS-1$ } break; case IJavaElement.PACKAGE_FRAGMENT: root = (PackageFragmentRoot) element.getParent(); projectPath = root.getJavaProject().getPath().toString(); if (root.isArchive()) { String relativePath = Util.concatWith(((PackageFragment) element).names, '/'); containerPath = root.getPath(); containerPathToString = containerPath.getDevice() == null ? containerPath.toString() : containerPath.toOSString(); add(projectPath, relativePath, containerPathToString, true /*package*/, null); } else { IResource resource = ((JavaElement) element).resource(); if (resource != null) { if (resource.isAccessible()) { containerPath = root.getKind() == IPackageFragmentRoot.K_SOURCE ? root.getParent().getPath() : root.internalPath(); } else { // for working copies, get resource container full path containerPath = resource.getParent().getFullPath(); } containerPathToString = containerPath.getDevice() == null ? containerPath.toString() : containerPath.toOSString(); String relativePath = Util.relativePath(resource.getFullPath(), containerPath.segmentCount()); add(projectPath, relativePath, containerPathToString, true /*package*/, null); } } break; default: // remember sub-cu (or sub-class file) java elements if (element instanceof IMember) { if (this.elements == null) { this.elements = new ArrayList(); } this.elements.add(element); } root = (PackageFragmentRoot) element.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); projectPath = root.getJavaProject().getPath().toString(); String relativePath; if (root.getKind() == IPackageFragmentRoot.K_SOURCE) { containerPath = root.getParent().getPath(); relativePath = Util.relativePath( getPath(element, false /*full path*/), root.getJavaProject().getPath().segmentCount() /*remove project segment*/); } else { containerPath = root.internalPath(); relativePath = getPath(element, true /*relative path*/).toString(); } containerPathToString = containerPath.getDevice() == null ? containerPath.toString() : containerPath.toOSString(); add(projectPath, relativePath, containerPathToString, false /*not a package*/, null); } if (root != null) addEnclosingProjectOrJar( root.getKind() == IPackageFragmentRoot.K_SOURCE ? root.getParent().getPath() : root.getPath()); }
/** * Add a path to current java search scope or all project fragment roots if null. Use project * resolved classpath to retrieve and store access restriction on each classpath entry. Recurse if * dependent projects are found. * * @param javaProject Project used to get resolved classpath entries * @param pathToAdd Path to add in case of single element or null if user want to add all project * package fragment roots * @param includeMask Mask to apply on classpath entries * @param projectsToBeAdded Set to avoid infinite recursion * @param visitedProjects Set to avoid adding twice the same project * @param referringEntry Project raw entry in referring project classpath * @throws JavaModelException May happen while getting java model info */ void add( JavaProject javaProject, IPath pathToAdd, int includeMask, HashSet projectsToBeAdded, HashSet visitedProjects, IClasspathEntry referringEntry) throws JavaModelException { IProject project = javaProject.getProject(); if (!project.isAccessible() || !visitedProjects.add(project)) return; IPath projectPath = project.getFullPath(); String projectPathString = projectPath.toString(); addEnclosingProjectOrJar(projectPath); IClasspathEntry[] entries = javaProject.getResolvedClasspath(); IJavaModel model = javaProject.getJavaModel(); JavaModelManager.PerProjectInfo perProjectInfo = javaProject.getPerProjectInfo(); for (int i = 0, length = entries.length; i < length; i++) { IClasspathEntry entry = entries[i]; AccessRuleSet access = null; ClasspathEntry cpEntry = (ClasspathEntry) entry; if (referringEntry != null) { // Add only exported entries. // Source folder are implicitly exported. if (!entry.isExported() && entry.getEntryKind() != IClasspathEntry.CPE_SOURCE) { continue; } cpEntry = cpEntry.combineWith((ClasspathEntry) referringEntry); // cpEntry = ((ClasspathEntry)referringEntry).combineWith(cpEntry); } access = cpEntry.getAccessRuleSet(); switch (entry.getEntryKind()) { case IClasspathEntry.CPE_LIBRARY: IClasspathEntry rawEntry = null; Map rootPathToRawEntries = perProjectInfo.rootPathToRawEntries; if (rootPathToRawEntries != null) { rawEntry = (IClasspathEntry) rootPathToRawEntries.get(entry.getPath()); } if (rawEntry == null) break; rawKind: switch (rawEntry.getEntryKind()) { case IClasspathEntry.CPE_LIBRARY: case IClasspathEntry.CPE_VARIABLE: if ((includeMask & APPLICATION_LIBRARIES) != 0) { IPath path = entry.getPath(); if (pathToAdd == null || pathToAdd.equals(path)) { Object target = JavaModel.getTarget(path, false /*don't check existence*/); if (target instanceof IFolder) // case of an external folder path = ((IFolder) target).getFullPath(); String pathToString = path.getDevice() == null ? path.toString() : path.toOSString(); add( projectPath.toString(), "", pathToString, false /*not a package*/, access); //$NON-NLS-1$ addEnclosingProjectOrJar(entry.getPath()); } } break; case IClasspathEntry.CPE_CONTAINER: IClasspathContainer container = JavaCore.getClasspathContainer(rawEntry.getPath(), javaProject); if (container == null) break; switch (container.getKind()) { case IClasspathContainer.K_APPLICATION: if ((includeMask & APPLICATION_LIBRARIES) == 0) break rawKind; break; case IClasspathContainer.K_SYSTEM: case IClasspathContainer.K_DEFAULT_SYSTEM: if ((includeMask & SYSTEM_LIBRARIES) == 0) break rawKind; break; default: break rawKind; } IPath path = entry.getPath(); if (pathToAdd == null || pathToAdd.equals(path)) { Object target = JavaModel.getTarget(path, false /*don't check existence*/); if (target instanceof IFolder) // case of an external folder path = ((IFolder) target).getFullPath(); String pathToString = path.getDevice() == null ? path.toString() : path.toOSString(); add( projectPath.toString(), "", pathToString, false /*not a package*/, access); //$NON-NLS-1$ addEnclosingProjectOrJar(entry.getPath()); } break; } break; case IClasspathEntry.CPE_PROJECT: if ((includeMask & REFERENCED_PROJECTS) != 0) { IPath path = entry.getPath(); if (pathToAdd == null || pathToAdd.equals(path)) { JavaProject referencedProject = (JavaProject) model.getJavaProject(path.toOSString()); if (!projectsToBeAdded.contains( referencedProject)) { // do not recurse if depending project was used to create // the scope add( referencedProject, null, includeMask, projectsToBeAdded, visitedProjects, cpEntry); } } } break; case IClasspathEntry.CPE_SOURCE: if ((includeMask & SOURCES) != 0) { IPath path = entry.getPath(); if (pathToAdd == null || pathToAdd.equals(path)) { add( projectPath.toString(), Util.relativePath(path, projectPath.segmentCount() /*remove project segment*/), projectPathString, false /*not a package*/, access); } } break; } } }
@Override String getSegment(IPath key) { return key.getDevice(); }
private boolean resourceExists(String location) { String bundleJar = null; IPath path = new Path(location); if ("platform:".equals(path.getDevice()) && path.segmentCount() > 2) { // $NON-NLS-1$ if ("plugin".equals(path.segment(0))) { // $NON-NLS-1$ String id = path.segment(1); IMonitorModelBase model = MonitorRegistry.findModel(id); if (model != null && model.isEnabled()) { path = path.setDevice(null).removeFirstSegments(2); String bundleLocation = model.getInstallLocation(); if (bundleLocation.endsWith(".jar")) { // $NON-NLS-1$ bundleJar = bundleLocation; } else { path = new Path(model.getInstallLocation()).append(path); } location = path.toString(); } } } else if (path.getDevice() == null && path.segmentCount() > 3 && "platform:".equals(path.segment(0))) { // $NON-NLS-1$ if ("plugin".equals(path.segment(1))) { // $NON-NLS-1$ String id = path.segment(2); IMonitorModelBase model = MonitorRegistry.findModel(id); if (model != null && model.isEnabled()) { path = path.removeFirstSegments(3); String bundleLocation = model.getInstallLocation(); if (bundleLocation.endsWith(".jar")) { // $NON-NLS-1$ bundleJar = bundleLocation; } else { path = new Path(model.getInstallLocation()).append(path); } location = path.toString(); } } } ArrayList paths = new ArrayList(); if (location.indexOf("$nl$") != -1) { // $NON-NLS-1$ StringTokenizer tokenizer = new StringTokenizer(TargetPlatform.getNL(), "_"); // $NON-NLS-1$ String language = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null; String country = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null; if (language != null && country != null) paths.add( location.replaceAll( "\\$nl\\$", "nl" + IPath.SEPARATOR + language + IPath.SEPARATOR + country)); //$NON-NLS-1$ //$NON-NLS-2$ if (language != null) paths.add( location.replaceAll( "\\$nl\\$", "nl" + IPath.SEPARATOR + language)); // $NON-NLS-1$ //$NON-NLS-2$ paths.add(location.replaceAll("\\$nl\\$", "")); // $NON-NLS-1$ //$NON-NLS-2$ } else { paths.add(location); } for (int i = 0; i < paths.size(); i++) { if (bundleJar == null) { IPath currPath = new Path(paths.get(i).toString()); if (currPath.isAbsolute() && currPath.toFile().exists()) return true; if (PDEProject.getBundleRoot(fFile.getProject()).findMember(currPath) != null) return true; if (fBuildModel != null && fBuildModel.getEntry("source." + paths.get(i)) != null) // $NON-NLS-1$ return true; } else { if (CoreUtility.jarContainsResource(new File(bundleJar), paths.get(i).toString(), false)) return true; } } return false; }
/** * Returns the index for a given project, according to the following algorithm: - if index is * already in memory: answers this one back - if (reuseExistingFile) then read it and return this * index and record it in memory - if (createIfMissing) then create a new empty index and record * it in memory Warning: Does not check whether index is consistent (not being used) */ public synchronized Index getIndex( IPath containerPath, IPath indexLocation, boolean reuseExistingFile, boolean createIfMissing) { // Path is already canonical per construction Index index = getIndex(indexLocation); if (index == null) { Object state = getIndexStates().get(indexLocation); Integer currentIndexState = state == null ? UNKNOWN_STATE : (Integer) state; if (currentIndexState == UNKNOWN_STATE) { // should only be reachable for query jobs // IF you put an index in the cache, then AddJarFileToIndex fails because it thinks there is // nothing to // do rebuildIndex(indexLocation, containerPath); return null; } // index isn't cached, consider reusing an existing index file String containerPathString = containerPath.getDevice() == null ? containerPath.toString() : containerPath.toOSString(); String indexLocationString = indexLocation.toOSString(); if (reuseExistingFile) { File indexFile = new File(indexLocationString); if (indexFile .exists()) { // check before creating index so as to avoid creating a new empty index if // file is missing try { index = new Index(indexLocationString, containerPathString, true /* reuse index file */); this.indexes.put(indexLocation, index); return index; } catch (IOException e) { // failed to read the existing file or its no longer compatible if (currentIndexState != REBUILDING_STATE) { // rebuild index if existing file is corrupt, unless the // index is already being rebuilt if (VERBOSE) Util.verbose( "-> cannot reuse existing index: " + indexLocationString + " path: " + containerPathString); //$NON-NLS-1$ //$NON-NLS-2$ rebuildIndex(indexLocation, containerPath); return null; } /* index = null; */ // will fall thru to createIfMissing & create a empty index for the rebuild // all job to populate } } if (currentIndexState == SAVED_STATE) { // rebuild index if existing file is missing rebuildIndex(indexLocation, containerPath); return null; } } // index wasn't found on disk, consider creating an empty new one if (createIfMissing) { try { if (VERBOSE) Util.verbose( "-> create empty index: " + indexLocationString + " path: " + containerPathString); //$NON-NLS-1$ //$NON-NLS-2$ index = new Index( indexLocationString, containerPathString, false /* do not reuse index file */); this.indexes.put(indexLocation, index); return index; } catch (IOException e) { if (VERBOSE) Util.verbose( "-> unable to create empty index: " + indexLocationString + " path: " + containerPathString); //$NON-NLS-1$ //$NON-NLS-2$ // The file could not be created. Possible reason: the project has been deleted. return null; } } } // System.out.println(" index name: " + path.toOSString() + " <----> " + // index.getIndexFile().getName()); return index; }