List of usage examples for org.eclipse.jdt.internal.core JavaModel getTarget
public static Object getTarget(IPath path, boolean checkResourceExistence)
null if checkResourceExistence is true and the entity referred to by the path does not exist on the file system From source file:apet.utils.ClasspathUtils.java
License:Open Source License
/** * Returns the Eclipse Project class loader using project build path * @param javaProject Eclipse Java Project * @return A class loader using project build path * @throws Exception If the project is no valid *//*from w w w . ja v a 2 s . co m*/ public static ClassLoader getProjectClassLoader(IJavaProject javaProject) throws Exception { IClasspathEntry[] entries = javaProject.getResolvedClasspath(true); String wsPath = javaProject.getProject().getLocation().toPortableString(); String firstEntryLocation = javaProject.getPath().toPortableString(); int idx = wsPath.indexOf(firstEntryLocation); URL[] urls = null; int i = 0; //System.out.println("ClassLoader " + wsPath); //System.out.println("ClassLoader " + firstEntryLocation); String output = javaProject.getOutputLocation().toPortableString(); urls = new URL[entries.length + 1]; if (idx != -1) { wsPath = wsPath.substring(0, idx); } else { output = output.substring(firstEntryLocation.length()); } urls[i++] = new File(wsPath + output).toURL(); //System.out.println("ClassLoader " + output); String fullPath = null; for (IClasspathEntry entry : entries) { if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) { IResource project = ResourcesPlugin.getWorkspace().getRoot().findMember(entry.getPath()); String projectPath = JavaCore.create(project.getProject()).getOutputLocation().toPortableString(); fullPath = wsPath + projectPath; } else { Object resource = JavaModel.getTarget(entry.getPath(), true); if (resource instanceof IResource) { IResource iFile = (IResource) resource; fullPath = iFile.getLocation().toPortableString(); } else if (resource instanceof File) { File file = (File) resource; fullPath = file.getAbsolutePath(); } } urls[i++] = new File(fullPath).toURL(); //System.out.println(fullPath); } URLClassLoader classLoader = new URLClassLoader(urls, String.class.getClassLoader()); /*for (int j = 0; j < urls.length; j ++) { System.out.println(urls[j]); }*/ return classLoader; }
From source file:apet.utils.ClasspathUtils.java
License:Open Source License
/** * Returns a String with all libraries defined in build path * @param javaProject Eclipse Java Project * @return a String with all libraries defined in build path * @throws Exception If the project is no valid *///w w w. j a v a 2s.c o m public static String getStringClasspath(IJavaProject javaProject) throws Exception { IClasspathEntry[] entries = javaProject.getResolvedClasspath(true); String wsPath = javaProject.getProject().getLocation().toPortableString(); String firstEntryLocation = javaProject.getPath().toPortableString(); int idx = wsPath.indexOf(firstEntryLocation); String[] urls = new String[entries.length + 1]; String fullPath = null; int i = 0; String output = javaProject.getOutputLocation().toPortableString(); if (idx != -1) { wsPath = wsPath.substring(0, idx); } else { output = output.substring(firstEntryLocation.length()); } urls[i++] = wsPath + output; for (IClasspathEntry entry : entries) { if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) { IResource project = ResourcesPlugin.getWorkspace().getRoot().findMember(entry.getPath()); String projectPath = JavaCore.create(project.getProject()).getOutputLocation().toPortableString(); fullPath = wsPath + projectPath; } else { Object resource = JavaModel.getTarget(entry.getPath(), true); if (resource instanceof IResource) { IResource iFile = (IResource) resource; fullPath = iFile.getLocation().toPortableString(); } else if (resource instanceof File) { File file = (File) resource; fullPath = file.getAbsolutePath(); } } urls[i++] = fullPath; } StringBuffer buffer = new StringBuffer(); for (String url : urls) { buffer.append(url); buffer.append(":"); } return buffer.toString().substring(0, buffer.length() - 1); }
From source file:com.codenvy.ide.ext.java.server.core.search.SearchParticipant.java
License:Open Source License
/** * Schedules the indexing of the given document. * Once the document is ready to be indexed, * {@link #indexDocument(SearchDocument, org.eclipse.core.runtime.IPath) indexDocument(document, indexPath)} * will be called in a different thread than the caller's thread. * <p>/*from w w w . j a v a 2s .com*/ * The given index location must represent a path in the file system to a file that * either already exists or is going to be created. If it exists, it must be an index file, * otherwise its data might be overwritten. * </p><p> * When the index is no longer needed, clients should use {@link #removeIndex(org.eclipse.core.runtime.IPath) } * to discard it. * </p> * * @param document the document to index * @param indexPath the location on the file system of the index */ public final void scheduleDocumentIndexing(SearchDocument document, IPath indexPath) { IPath documentPath = new Path(document.getPath()); Object file = JavaModel.getTarget(documentPath, true); IPath containerPath = documentPath; if (file instanceof IResource) { containerPath = ((IResource) file).getProject().getFullPath(); } else if (file == null) { containerPath = documentPath.removeLastSegments(1); } //todo index manager IndexManager manager = null; //JavaModelManager.getIndexManager(); // TODO (frederic) should not have to create index manually, should expose API that recreates index instead IndexLocation indexLocation; indexLocation = new FileIndexLocation(indexPath.toFile(), true); manager.ensureIndexExists(indexLocation, containerPath); manager.scheduleDocumentIndexing(document, containerPath, indexLocation, this); if (!indexPath.equals(this.lastIndexLocation)) { manager.updateParticipant(indexPath, containerPath); this.lastIndexLocation = indexPath; } }
From source file:com.codenvy.ide.ext.java.server.internal.core.ClasspathEntry.java
License:Open Source License
private static List getCalledFileNames(IPath jarPath) { Object target = JavaModel.getTarget(jarPath, true/*check existence, otherwise the manifest cannot be read*/); if (!(target instanceof IFile || target instanceof File)) return null; JavaModelManager manager = JavaModelManager.getJavaModelManager(); ZipFile zip = null;//from www .ja v a 2 s . com InputStream inputStream = null; List calledFileNames = null; try { zip = manager.getZipFile(jarPath); ZipEntry manifest = zip.getEntry("META-INF/MANIFEST.MF"); //$NON-NLS-1$ if (manifest == null) return null; // non-null implies regular file ManifestAnalyzer analyzer = new ManifestAnalyzer(); inputStream = zip.getInputStream(manifest); boolean success = analyzer.analyzeManifestContents(inputStream); calledFileNames = analyzer.getCalledFileNames(); if (!success || analyzer.getClasspathSectionsCount() == 1 && calledFileNames == null) { if (JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) { Util.verbose("Invalid Class-Path header in manifest of jar file: " + jarPath.toOSString()); //$NON-NLS-1$ } return null; } else if (analyzer.getClasspathSectionsCount() > 1) { if (JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) { Util.verbose("Multiple Class-Path headers in manifest of jar file: " + jarPath.toOSString()); //$NON-NLS-1$ } return null; } } catch (CoreException e) { // not a zip file if (JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) { Util.verbose("Could not read Class-Path header in manifest of jar file: " + jarPath.toOSString()); //$NON-NLS-1$ e.printStackTrace(); } } catch (IOException e) { // not a zip file if (JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) { Util.verbose("Could not read Class-Path header in manifest of jar file: " + jarPath.toOSString()); //$NON-NLS-1$ e.printStackTrace(); } } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { // best effort } } manager.closeZipFile(zip); } return calledFileNames; }
From source file:com.codenvy.ide.ext.java.server.internal.core.ClasspathEntry.java
License:Open Source License
/** * Returns a printable representation of this classpath entry. *//*from w ww .java 2 s . c o m*/ public String toString() { StringBuffer buffer = new StringBuffer(); Object target = JavaModel.getTarget(getPath(), true); if (target instanceof File) buffer.append(getPath().toOSString()); else buffer.append(String.valueOf(getPath())); buffer.append('['); switch (getEntryKind()) { case IClasspathEntry.CPE_LIBRARY: buffer.append("CPE_LIBRARY"); //$NON-NLS-1$ break; case IClasspathEntry.CPE_PROJECT: buffer.append("CPE_PROJECT"); //$NON-NLS-1$ break; case IClasspathEntry.CPE_SOURCE: buffer.append("CPE_SOURCE"); //$NON-NLS-1$ break; case IClasspathEntry.CPE_VARIABLE: buffer.append("CPE_VARIABLE"); //$NON-NLS-1$ break; case IClasspathEntry.CPE_CONTAINER: buffer.append("CPE_CONTAINER"); //$NON-NLS-1$ break; } buffer.append("]["); //$NON-NLS-1$ switch (getContentKind()) { case IPackageFragmentRoot.K_BINARY: buffer.append("K_BINARY"); //$NON-NLS-1$ break; case IPackageFragmentRoot.K_SOURCE: buffer.append("K_SOURCE"); //$NON-NLS-1$ break; case ClasspathEntry.K_OUTPUT: buffer.append("K_OUTPUT"); //$NON-NLS-1$ break; } buffer.append(']'); if (getSourceAttachmentPath() != null) { buffer.append("[sourcePath:"); //$NON-NLS-1$ buffer.append(getSourceAttachmentPath()); buffer.append(']'); } if (getSourceAttachmentRootPath() != null) { buffer.append("[rootPath:"); //$NON-NLS-1$ buffer.append(getSourceAttachmentRootPath()); buffer.append(']'); } buffer.append("[isExported:"); //$NON-NLS-1$ buffer.append(this.isExported); buffer.append(']'); IPath[] patterns = this.inclusionPatterns; int length; if ((length = patterns == null ? 0 : patterns.length) > 0) { buffer.append("[including:"); //$NON-NLS-1$ for (int i = 0; i < length; i++) { buffer.append(patterns[i]); if (i != length - 1) { buffer.append('|'); } } buffer.append(']'); } patterns = this.exclusionPatterns; if ((length = patterns == null ? 0 : patterns.length) > 0) { buffer.append("[excluding:"); //$NON-NLS-1$ for (int i = 0; i < length; i++) { buffer.append(patterns[i]); if (i != length - 1) { buffer.append('|'); } } buffer.append(']'); } if (this.accessRuleSet != null) { buffer.append('['); buffer.append(this.accessRuleSet.toString(false/*on one line*/)); buffer.append(']'); } if (this.entryKind == CPE_PROJECT) { buffer.append("[combine access rules:"); //$NON-NLS-1$ buffer.append(this.combineAccessRules); buffer.append(']'); } if (getOutputLocation() != null) { buffer.append("[output:"); //$NON-NLS-1$ buffer.append(getOutputLocation()); buffer.append(']'); } if ((length = this.extraAttributes == null ? 0 : this.extraAttributes.length) > 0) { buffer.append("[attributes:"); //$NON-NLS-1$ for (int i = 0; i < length; i++) { buffer.append(this.extraAttributes[i]); if (i != length - 1) { buffer.append(','); } } buffer.append(']'); } return buffer.toString(); }
From source file:com.codenvy.ide.ext.java.server.internal.core.search.HierarchyScope.java
License:Open Source License
public HierarchyScope(IType type, WorkingCopyOwner owner) throws JavaModelException { this.focusType = type; this.owner = owner; this.enclosingProjectsAndJars = computeProjectsAndJars(type); // resource path IPackageFragmentRoot root = (IPackageFragmentRoot) type.getPackageFragment().getParent(); if (root.isArchive()) { IPath jarPath = root.getPath();/*from w w w .j a v a2 s. com*/ Object target = JavaModel.getTarget(jarPath, true); String zipFileName; if (target instanceof IFile) { // internal jar zipFileName = jarPath.toString(); } else if (target instanceof File) { // external jar zipFileName = ((File) target).getPath(); } else { return; // unknown target } this.focusPath = zipFileName + JAR_FILE_ENTRY_SEPARATOR + type.getFullyQualifiedName().replace('.', '/') + SUFFIX_STRING_class; } else { this.focusPath = type.getPath().toString(); } this.needsRefresh = true; //disabled for now as this could be expensive //JavaModelManager.getJavaModelManager().rememberScope(this); }
From source file:com.codenvy.ide.ext.java.server.internal.core.search.HierarchyScope.java
License:Open Source License
private void buildResourceVector() { HashMap resources = new HashMap(); HashMap paths = new HashMap(); IType[] types = null;/*from w w w . j ava 2s. co m*/ if (this.subTypes != null) { types = this.hierarchy.getAllSubtypes(this.focusType); if (this.includeFocusType) { int len = types.length; System.arraycopy(types, 0, types = new IType[len + 1], 0, len); types[len] = this.focusType; } } else { types = this.hierarchy.getAllTypes(); } for (int i = 0; i < types.length; i++) { IType type = types[i]; if (this.subTypes != null) { // remember subtypes for later use in encloses() this.subTypes.add(type); } IResource resource = ((JavaElement) type).resource(); if (resource != null && resources.get(resource) == null) { resources.put(resource, resource); add(resource); } IPackageFragmentRoot root = (IPackageFragmentRoot) type.getPackageFragment().getParent(); if (root instanceof JarPackageFragmentRoot) { // type in a jar JarPackageFragmentRoot jar = (JarPackageFragmentRoot) root; IPath jarPath = jar.getPath(); Object target = JavaModel.getTarget(jarPath, true); String zipFileName; if (target instanceof IFile) { // internal jar zipFileName = jarPath.toString(); } else if (target instanceof File) { // external jar zipFileName = ((File) target).getPath(); } else { continue; // unknown target } String resourcePath = zipFileName + JAR_FILE_ENTRY_SEPARATOR + type.getFullyQualifiedName().replace('.', '/') + SUFFIX_STRING_class; this.resourcePaths.add(resourcePath); paths.put(jarPath, type); } else { // type is a project paths.put(type.getJavaProject().getProject().getFullPath(), type); } } this.enclosingProjectsAndJars = new IPath[paths.size()]; int i = 0; for (Iterator iter = paths.keySet().iterator(); iter.hasNext();) { this.enclosingProjectsAndJars[i++] = (IPath) iter.next(); } }
From source file:com.codenvy.ide.ext.java.server.internal.core.search.indexing.IndexManager.java
License:Open Source License
private void rebuildIndex(IndexLocation indexLocation, IPath containerPath) { Object target = JavaModel.getTarget(containerPath, true); if (target == null) return;/*from w w w. ja v a2s . co m*/ if (VERBOSE) Util.verbose("-> request to rebuild index: " + indexLocation + " path: " + containerPath); //$NON-NLS-1$ //$NON-NLS-2$ updateIndexState(indexLocation, REBUILDING_STATE); IndexRequest request = null; //TODO // if (target instanceof IProject) { // IProject p = (IProject)target; // if (JavaProject.hasJavaNature(p)) // request = new IndexAllProject(p, this); //// } else if (target instanceof IFolder) { //// request = new IndexBinaryFolder((IFolder) target, this); //// } else if (target instanceof IFile) { //// request = new AddJarFileToIndex((IFile) target, null, this); // } else if (target instanceof File) { // request = new AddJarFileToIndex(containerPath, null, this); // } if (request != null) request(request); }
From source file:com.codenvy.ide.ext.java.server.internal.core.search.IndexSelector.java
License:Open Source License
private void initializeIndexLocations() { IPath[] projectsAndJars = this.searchScope.enclosingProjectsAndJars(); // use a linked set to preserve the order during search: see bug 348507 LinkedHashSet locations = new LinkedHashSet(); IJavaElement focus = MatchLocator.projectOrJarFocus(this.pattern); if (focus == null) { for (int i = 0; i < projectsAndJars.length; i++) { IPath path = projectsAndJars[i]; Object target = new File(path.toOSString());//JavaModel.getTarget(path, false/*don't check existence*/); if (target instanceof IFolder) // case of an external folder path = ((IFolder) target).getFullPath(); locations.add(indexManager.computeIndexLocation(path)); }/* w w w. j a va 2s . c o m*/ } else { try { // See whether the state builder might be used to reduce the number of index locations // find the projects from projectsAndJars that see the focus then walk those projects looking for the jars from projectsAndJars int length = projectsAndJars.length; JavaProject[] projectsCanSeeFocus = new JavaProject[length]; SimpleSet visitedProjects = new SimpleSet(length); int projectIndex = 0; SimpleSet externalLibsToCheck = new SimpleSet(length); ObjectVector superTypes = new ObjectVector(); IJavaElement[] focuses = getFocusedElementsAndTypes(this.pattern, focus, superTypes); char[][][] focusQualifiedNames = null; boolean isAutoBuilding = ResourcesPlugin.getWorkspace().getDescription().isAutoBuilding(); if (isAutoBuilding && focus instanceof IJavaProject) { focusQualifiedNames = getQualifiedNames(superTypes); } IJavaModel model = JavaModelManager.getJavaModelManager().getJavaModel(); for (int i = 0; i < length; i++) { IPath path = projectsAndJars[i]; JavaProject project = (JavaProject) getJavaProject(path, model); if (project != null) { visitedProjects.add(project); if (canSeeFocus(focuses, project, focusQualifiedNames)) { locations.add(indexManager.computeIndexLocation(path)); projectsCanSeeFocus[projectIndex++] = project; } } else { externalLibsToCheck.add(path); } } for (int i = 0; i < projectIndex && externalLibsToCheck.elementSize > 0; i++) { IClasspathEntry[] entries = projectsCanSeeFocus[i].getResolvedClasspath(); for (int j = entries.length; --j >= 0;) { IClasspathEntry entry = entries[j]; if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) { IPath path = entry.getPath(); if (externalLibsToCheck.remove(path) != null) { Object target = JavaModel.getTarget(path, false/*don't check existence*/); if (target instanceof IFolder) // case of an external folder path = ((IFolder) target).getFullPath(); locations.add(indexManager.computeIndexLocation(path)); } } } } // jar files can be included in the search scope without including one of the projects that references them, so scan all projects that have not been visited if (externalLibsToCheck.elementSize > 0) { IJavaProject[] allProjects = model.getJavaProjects(); for (int i = 0, l = allProjects.length; i < l && externalLibsToCheck.elementSize > 0; i++) { JavaProject project = (JavaProject) allProjects[i]; if (!visitedProjects.includes(project)) { IClasspathEntry[] entries = project.getResolvedClasspath(); for (int j = entries.length; --j >= 0;) { IClasspathEntry entry = entries[j]; if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) { IPath path = entry.getPath(); if (externalLibsToCheck.remove(path) != null) { Object target = JavaModel.getTarget(path, false/*don't check existence*/); if (target instanceof IFolder) // case of an external folder path = ((IFolder) target).getFullPath(); locations.add(indexManager.computeIndexLocation(path)); } } } } } } } catch (JavaModelException e) { // ignored } } locations.remove(null); // Ensure no nulls this.indexLocations = (IndexLocation[]) locations.toArray(new IndexLocation[locations.size()]); }
From source file:com.codenvy.ide.ext.java.server.internal.core.search.JavaSearchScope.java
License:Open Source License
/** * 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/*from ww w. j a v a 2s. co m*/ * 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 org.eclipse.jdt.core.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 = javaProject.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 (cpEntry.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.lastSegment()); // 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, 1/*remove project segment*/), projectPathString, false/*not a package*/, access); } } break; } } }