Example usage for org.eclipse.jdt.core IClasspathEntry CPE_LIBRARY

List of usage examples for org.eclipse.jdt.core IClasspathEntry CPE_LIBRARY

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IClasspathEntry CPE_LIBRARY.

Prototype

int CPE_LIBRARY

To view the source code for org.eclipse.jdt.core IClasspathEntry CPE_LIBRARY.

Click Source Link

Document

Entry kind constant describing a classpath entry identifying a library.

Usage

From source file:org.eclipse.che.jdt.internal.core.DeltaProcessor.java

License:Open Source License

private boolean createExternalArchiveDelta(HashSet refreshedElements, IProgressMonitor monitor) {

    HashMap externalArchivesStatus = new HashMap();
    boolean hasDelta = false;

    // find JARs to refresh
    HashSet archivePathsToRefresh = new HashSet();
    Iterator iterator = refreshedElements.iterator();
    while (iterator.hasNext()) {
        IJavaElement element = (IJavaElement) iterator.next();
        switch (element.getElementType()) {
        case IJavaElement.PACKAGE_FRAGMENT_ROOT:
            archivePathsToRefresh.add(element.getPath());
            break;
        case IJavaElement.JAVA_PROJECT:
            JavaProject javaProject = (JavaProject) element;
            if (!JavaProject.hasJavaNature(javaProject.getProject())) {
                // project is not accessible or has lost its Java nature
                break;
            }//  w w  w  . java  2  s  .  c  om
            IClasspathEntry[] classpath;
            try {
                classpath = javaProject.getResolvedClasspath();
                for (int j = 0, cpLength = classpath.length; j < cpLength; j++) {
                    if (classpath[j].getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
                        archivePathsToRefresh.add(classpath[j].getPath());
                    }
                }
            } catch (JavaModelException e) {
                // project doesn't exist -> ignore
            }
            break;
        case IJavaElement.JAVA_MODEL:
            //               Iterator projectNames = this.state.getOldJavaProjecNames().iterator();
            //               while (projectNames.hasNext()) {
            //                  String projectName = (String) projectNames.next();
            //                  IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
            //                  if (!JavaProject.hasJavaNature(project)) {
            //                     // project is not accessible or has lost its Java nature
            //                     continue;
            //                  }
            //                  javaProject = (JavaProject) JavaCore.create(project);
            //                  try {
            //                     classpath = javaProject.getResolvedClasspath();
            //                     for (int k = 0, cpLength = classpath.length; k < cpLength; k++){
            //                        if (classpath[k].getEntryKind() == IClasspathEntry.CPE_LIBRARY){
            //                           archivePathsToRefresh.add(classpath[k].getPath());
            //                        }
            //                     }
            //                  } catch (JavaModelException e2) {
            //                     // project doesn't exist -> ignore
            //                     continue;
            //                  }
            //               }
            throw new UnsupportedOperationException();
            //               break;
        }
    }

    //      // perform refresh
    //      Iterator projectNames = this.state.getOldJavaProjecNames().iterator();
    //      IWorkspaceRoot wksRoot = ResourcesPlugin.getWorkspace().getRoot();
    //      while (projectNames.hasNext()) {
    //
    //         if (monitor != null && monitor.isCanceled()) break;
    //
    //         String projectName = (String) projectNames.next();
    //         IProject project = wksRoot.getProject(projectName);
    //         if (!JavaProject.hasJavaNature(project)) {
    //            // project is not accessible or has lost its Java nature
    //            continue;
    //         }
    //         JavaProject javaProject = (JavaProject) JavaCore.create(project);
    //         IClasspathEntry[] entries;
    //         try {
    //            entries = javaProject.getResolvedClasspath();
    //         } catch (JavaModelException e1) {
    //            // project does not exist -> ignore
    //            continue;
    //         }
    //         boolean deltaContainsModifiedJar = false;
    //         for (int j = 0; j < entries.length; j++){
    //            if (entries[j].getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
    //               IPath entryPath = entries[j].getPath();
    //
    //               if (!archivePathsToRefresh.contains(entryPath)) continue; // not supposed to be refreshed
    //
    //               String status = (String)externalArchivesStatus.get(entryPath);
    //               if (status == null){
    //
    //                  // Clear the external file state for this path, since this method is responsible for updating it.
    //                  this.manager.clearExternalFileState(entryPath);
    //
    //                  // compute shared status
    //                  Object targetLibrary = JavaModel.getTarget(entryPath, true);
    //
    //                  if (targetLibrary == null){ // missing JAR
    //                     if (this.state.getExternalLibTimeStamps().remove(entryPath) != null /* file was known*/
    //                           && this.state.roots.get(entryPath) != null /* and it was on the classpath*/) {
    //                        externalArchivesStatus.put(entryPath, EXTERNAL_JAR_REMOVED);
    //                        // the jar was physically removed: remove the index
    //                        this.manager.indexManager.removeIndex(entryPath);
    //                     }
    //
    //                  } else if (targetLibrary instanceof File){ // external JAR
    //
    //                     File externalFile = (File)targetLibrary;
    //
    //                     // check timestamp to figure if JAR has changed in some way
    //                     Long oldTimestamp =(Long) this.state.getExternalLibTimeStamps().get(entryPath);
    //                     long newTimeStamp = getTimeStamp(externalFile);
    //                     if (oldTimestamp != null){
    //
    //                        if (newTimeStamp == 0){ // file doesn't exist
    //                           externalArchivesStatus.put(entryPath, EXTERNAL_JAR_REMOVED);
    //                           this.state.getExternalLibTimeStamps().remove(entryPath);
    //                           // remove the index
    //                           this.manager.indexManager.removeIndex(entryPath);
    //
    //                        } else if (oldTimestamp.longValue() != newTimeStamp){
    //                           externalArchivesStatus.put(entryPath, EXTERNAL_JAR_CHANGED);
    //                           this.state.getExternalLibTimeStamps().put(entryPath, new Long(newTimeStamp));
    //                           // first remove the index so that it is forced to be re-indexed
    //                           this.manager.indexManager.removeIndex(entryPath);
    //                           // then index the jar
    //                           this.manager.indexManager.indexLibrary(entryPath, project.getProject(), ((ClasspathEntry)entries[j])
    // .getLibraryIndexLocation(), true);
    //                        } else {
    //                           URL indexLocation = ((ClasspathEntry)entries[j]).getLibraryIndexLocation();
    //                           if (indexLocation != null) { // force reindexing, this could be faster rather than maintaining the list
    //                              this.manager.indexManager.indexLibrary(entryPath, project.getProject(), indexLocation);
    //                           }
    //                           externalArchivesStatus.put(entryPath, EXTERNAL_JAR_UNCHANGED);
    //                        }
    //                     } else {
    //                        if (newTimeStamp == 0){ // jar still doesn't exist
    //                           externalArchivesStatus.put(entryPath, EXTERNAL_JAR_UNCHANGED);
    //                        } else {
    //                           externalArchivesStatus.put(entryPath, EXTERNAL_JAR_ADDED);
    //                           this.state.getExternalLibTimeStamps().put(entryPath, new Long(newTimeStamp));
    //                           // index the new jar
    //                           this.manager.indexManager.removeIndex(entryPath);
    //                           this.manager.indexManager.indexLibrary(entryPath, project.getProject(), ((ClasspathEntry)entries[j])
    // .getLibraryIndexLocation());
    //                        }
    //                     }
    //                  } else { // internal JAR
    //                     externalArchivesStatus.put(entryPath, INTERNAL_JAR_IGNORE);
    //                  }
    //               }
    //               // according to computed status, generate a delta
    //               status = (String)externalArchivesStatus.get(entryPath);
    //               if (status != null){
    //                  if (status == EXTERNAL_JAR_ADDED){
    //                     PackageFragmentRoot root = (PackageFragmentRoot) javaProject.getPackageFragmentRoot(entryPath.toString());
    //                     if (VERBOSE){
    //                        System.out.println("- External JAR ADDED, affecting root: "+root.getElementName()); //$NON-NLS-1$
    //                     }
    //                     elementAdded(root, null, null);
    //                     deltaContainsModifiedJar = true;
    //                     this.state.addClasspathValidation(javaProject); // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=185733
    //                     hasDelta = true;
    //                  } else if (status == EXTERNAL_JAR_CHANGED) {
    //                     PackageFragmentRoot root = (PackageFragmentRoot) javaProject.getPackageFragmentRoot(entryPath.toString());
    //                     if (VERBOSE){
    //                        System.out.println("- External JAR CHANGED, affecting root: "+root.getElementName()); //$NON-NLS-1$
    //                     }
    //                     contentChanged(root);
    //                     deltaContainsModifiedJar = true;
    //                     hasDelta = true;
    //                  } else if (status == EXTERNAL_JAR_REMOVED) {
    //                     PackageFragmentRoot root = (PackageFragmentRoot) javaProject.getPackageFragmentRoot(entryPath.toString());
    //                     if (VERBOSE){
    //                        System.out.println("- External JAR REMOVED, affecting root: "+root.getElementName()); //$NON-NLS-1$
    //                     }
    //                     elementRemoved(root, null, null);
    //                     deltaContainsModifiedJar = true;
    //                     this.state.addClasspathValidation(javaProject); // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=185733
    //                     hasDelta = true;
    //                  }
    //               }
    //            }
    //         }
    //
    //         if (deltaContainsModifiedJar) {
    //            javaProject.resetResolvedClasspath();
    //         }
    //      }
    //
    //      if (hasDelta){
    //         // flush jar type cache
    //         JavaModelManager.getJavaModelManager().resetJarTypeCache();
    //      }
    return hasDelta;
}

From source file:org.eclipse.che.jdt.internal.core.JavaProject.java

License:Open Source License

/**
 * This is a helper method returning the resolved classpath for the project
 * as a list of simple (non-variable, non-container) classpath entries.
 * All classpath variable and classpath container entries in the project's
 * raw classpath will be replaced by the simple classpath entries they
 * resolve to./*from   w w  w.  j a v  a 2  s . c  o m*/
 * <p>
 * The resulting resolved classpath is accurate for the given point in time.
 * If the project's raw classpath is later modified, or if classpath
 * variables are changed, the resolved classpath can become out of date.
 * Because of this, hanging on resolved classpath is not recommended.
 * </p>
 * <p>
 * Note that if the resolution creates duplicate entries
 * (i.e. {@link IClasspathEntry entries} which are {@link Object#equals(Object)}),
 * only the first one is added to the resolved classpath.
 * </p>
 *
 * @see IClasspathEntry
 */
public IClasspathEntry[] getResolvedClasspath() throws JavaModelException {
    if (resolvedClasspath == null) {
        ResolvedClasspath result = new ResolvedClasspath();
        LinkedHashSet<IClasspathEntry> resolvedEntries = new LinkedHashSet<>();
        for (IClasspathEntry entry : getRawClasspath()) {
            switch (entry.getEntryKind()) {
            case IClasspathEntry.CPE_LIBRARY:
            case IClasspathEntry.CPE_SOURCE:
                addToResult(entry, entry, result, resolvedEntries);
                break;
            case IClasspathEntry.CPE_CONTAINER:
                IClasspathContainer container = JavaCore.getClasspathContainer(entry.getPath(), this);
                for (IClasspathEntry classpathEntry : container.getClasspathEntries()) {
                    addToResult(entry, classpathEntry, result, resolvedEntries);
                }
                break;
            }
        }
        result.resolvedClasspath = new IClasspathEntry[resolvedEntries.size()];
        resolvedEntries.toArray(result.resolvedClasspath);
        resolvedClasspath = result;
    }

    return resolvedClasspath.resolvedClasspath;
}

From source file:org.eclipse.che.jdt.internal.core.JavaProject.java

License:Open Source License

/**
 * Returns the package fragment roots identified by the given entry. In case it refers to
 * a project, it will follow its classpath so as to find exported roots as well.
 * Only works with resolved entry// ww  w . ja  v a2s . c  om
 *
 * @param resolvedEntry
 *         IClasspathEntry
 * @param accumulatedRoots
 *         ObjectVector
 * @param rootIDs
 *         HashSet
 * @param referringEntry
 *         the CP entry (project) referring to this entry, or null if initial project
 * @param retrieveExportedRoots
 *         boolean
 * @throws JavaModelException
 */
public void computePackageFragmentRoots(IClasspathEntry resolvedEntry, ObjectVector accumulatedRoots,
        HashSet rootIDs, IClasspathEntry referringEntry, boolean retrieveExportedRoots,
        Map rootToResolvedEntries) throws JavaModelException {

    String rootID = ((ClasspathEntry) resolvedEntry).rootID();
    if (rootIDs.contains(rootID))
        return;

    IPath projectPath = this.getFullPath();
    IPath entryPath = resolvedEntry.getPath();
    //        IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
    IPackageFragmentRoot root = null;

    switch (resolvedEntry.getEntryKind()) {

    // source folder
    case IClasspathEntry.CPE_SOURCE:

        //                if (projectPath.isPrefixOf(entryPath)) {
        Object target1 = JavaModelManager.getTarget(entryPath, true/*check existency*/);
        if (target1 == null)
            return;

        if (target1 instanceof File && ((File) target1).isDirectory()) {
            root = getPackageFragmentRoot((File) target1);
        }
        //                }
        break;

    // internal/external JAR or folder
    case IClasspathEntry.CPE_LIBRARY:
        if (referringEntry != null && !resolvedEntry.isExported())
            return;
        Object target = JavaModelManager.getTarget(entryPath, true/*check existency*/);
        if (target == null)
            return;

        //                if (target instanceof IResource){
        //                    // internal target
        //                } else
        if (target instanceof File) {
            // external target
            if (JavaModelManager.isFile(target)) {
                root = new JarPackageFragmentRoot((File) target, this, manager);
            } else if (((File) target).isDirectory()) {
                root = getPackageFragmentRoot((File) target, entryPath);
                //                        root = new ExternalPackageFragmentRoot(entryPath, this);
            }
        }
        break;

    // recurse into required project
    case IClasspathEntry.CPE_PROJECT:

        if (!retrieveExportedRoots)
            return;
        if (referringEntry != null && !resolvedEntry.isExported())
            return;
        //todo multiproject
        //                IResource member = workspaceRoot.findMember(entryPath);
        //                if (member != null && member.getType() == IResource.PROJECT) {// double check if bound to project (23977)
        //                    IProject requiredProjectRsc = (IProject)member;
        //                    if (JavaProject.hasJavaNature(requiredProjectRsc)) { // special builder binary output
        //                        rootIDs.add(rootID);
        //                        JavaProject requiredProject = (JavaProject)JavaCore.create(requiredProjectRsc);
        //                        requiredProject.computePackageFragmentRoots(
        //                                requiredProject.getResolvedClasspath(),
        //                                accumulatedRoots,
        //                                rootIDs,
        //                                rootToResolvedEntries == null ? resolvedEntry
        //                                                              : ((org.eclipse.jdt.internal.core.ClasspathEntry)resolvedEntry)
        //                                        .combineWith((org.eclipse.jdt.internal.core.ClasspathEntry)referringEntry),
        //                                // only combine if need to build the reverse map
        //                                retrieveExportedRoots,
        //                                rootToResolvedEntries);
        //                    }
        //                    break;
        //                }
    }
    if (root != null) {
        accumulatedRoots.add(root);
        rootIDs.add(rootID);
        if (rootToResolvedEntries != null)
            rootToResolvedEntries.put(root,
                    ((ClasspathEntry) resolvedEntry).combineWith((ClasspathEntry) referringEntry));
    }
}

From source file:org.eclipse.che.jdt.internal.core.search.IndexSelector.java

License:Open Source License

/**
 * Returns whether elements of the given project or jar can see the given focus (an IJavaProject or
 * a JarPackageFragmentRot) either because the focus is part of the project or the jar, or because it is
 * accessible throught the project's classpath
 *//* ww  w.  ja  v a  2 s  .co  m*/
public static int canSeeFocus(SearchPattern pattern, IPath projectOrJarPath) {
    try {
        IJavaModel model = JavaModelManager.getJavaModelManager().getJavaModel();
        IJavaProject project = getJavaProject(projectOrJarPath, model);
        IJavaElement[] focuses = getFocusedElementsAndTypes(pattern, project, null);
        if (focuses.length == 0)
            return PROJECT_CAN_NOT_SEE_FOCUS;
        if (project != null) {
            return canSeeFocus(focuses, (JavaProject) project, null);
        }

        // projectOrJarPath is a jar
        // it can see the focus only if it is on the classpath of a project that can see the focus
        int result = PROJECT_CAN_NOT_SEE_FOCUS;
        IJavaProject[] allProjects = model.getJavaProjects();
        for (int i = 0, length = allProjects.length; i < length; i++) {
            JavaProject otherProject = (JavaProject) allProjects[i];
            IClasspathEntry entry = otherProject.getClasspathEntryFor(projectOrJarPath);
            if (entry != null && entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
                int canSeeFocus = canSeeFocus(focuses, otherProject, null);
                if (canSeeFocus == PROJECT_CAN_SEE_FOCUS)
                    return PROJECT_CAN_SEE_FOCUS;
                if (canSeeFocus == PROJECT_SOURCE_CAN_NOT_SEE_FOCUS)
                    result = PROJECT_SOURCE_CAN_NOT_SEE_FOCUS;
            }
        }
        return result;
    } catch (JavaModelException e) {
        return PROJECT_CAN_NOT_SEE_FOCUS;
    }
}

From source file:org.eclipse.che.jdt.internal.core.search.IndexSelector.java

License:Open Source License

private static int canSeeFocus(IJavaElement focus, JavaProject javaProject, char[][][] focusQualifiedNames) {
    try {/*from  w  w w.j av  a  2  s .  c  o m*/
        if (focus == null)
            return PROJECT_CAN_NOT_SEE_FOCUS;
        if (focus.equals(javaProject))
            return PROJECT_CAN_SEE_FOCUS;

        if (focus instanceof JarPackageFragmentRoot) {
            // focus is part of a jar
            IPath focusPath = focus.getPath();
            IClasspathEntry[] entries = javaProject.getExpandedClasspath();
            for (int i = 0, length = entries.length; i < length; i++) {
                IClasspathEntry entry = entries[i];
                if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY && entry.getPath().equals(focusPath))
                    return PROJECT_CAN_SEE_FOCUS;
            }
            return PROJECT_CAN_NOT_SEE_FOCUS;
        }
        // look for dependent projects
        IPath focusPath = ((JavaProject) focus).getProject().getFullPath();
        IClasspathEntry[] entries = javaProject.getExpandedClasspath();
        for (int i = 0, length = entries.length; i < length; i++) {
            IClasspathEntry entry = entries[i];
            if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT && entry.getPath().equals(focusPath)) {
                if (focusQualifiedNames != null) { // builder state is usable, hence use it to try to reduce project which can see the focus...
                    State projectState = (State) JavaModelManager.getJavaModelManager()
                            .getLastBuiltState(javaProject.getProject(), null);
                    if (projectState != null) {
                        Object[] values = projectState.getReferences().valueTable;
                        int vLength = values.length;
                        for (int j = 0; j < vLength; j++) {
                            if (values[j] == null)
                                continue;
                            ReferenceCollection references = (ReferenceCollection) values[j];
                            if (references.includes(focusQualifiedNames, null, null)) {
                                return PROJECT_CAN_SEE_FOCUS;
                            }
                        }
                        return PROJECT_SOURCE_CAN_NOT_SEE_FOCUS;
                    }
                }
                return PROJECT_CAN_SEE_FOCUS;
            }
        }
        return PROJECT_CAN_NOT_SEE_FOCUS;
    } catch (JavaModelException e) {
        return PROJECT_CAN_NOT_SEE_FOCUS;
    }
}

From source file:org.eclipse.che.jdt.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));
        }//from ww w  . j a v a 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);
                    int canSeeFocus = canSeeFocus(focuses, project, focusQualifiedNames);
                    if (canSeeFocus == PROJECT_CAN_SEE_FOCUS) {
                        locations.add(indexManager.computeIndexLocation(path));
                    }
                    if (canSeeFocus != PROJECT_CAN_NOT_SEE_FOCUS) {
                        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:org.eclipse.che.jdt.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//ww  w  . j a va 2 s.com
 *         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(),
                            path.toOSString()
                                    .substring(projectPath.toString().length()
                                            + 1)/*Util.relativePath(path, 1*//*remove project segment*//*)*/,
                            projectPathString, false/*not a
                                                    package*/, access);
                }
            }
            break;
        }
    }
}

From source file:org.eclipse.che.jdt.internal.core.search.JavaWorkspaceScope.java

License:Open Source License

public IPath[] enclosingProjectsAndJars() {
    IPath[] result = this.enclosingPaths;
    if (result != null) {
        return result;
    }//from  w  w  w  . ja va 2s  .c  o m
    long start = org.eclipse.jdt.internal.core.search.BasicSearchEngine.VERBOSE ? System.currentTimeMillis()
            : -1;
    try {
        IJavaProject[] projects = JavaModelManager.getJavaModelManager().getJavaModel().getJavaProjects();
        // use a linked set to preserve the order during search: see bug 348507
        Set paths = new LinkedHashSet(projects.length * 2);
        for (int i = 0, length = projects.length; i < length; i++) {
            JavaProject javaProject = (JavaProject) projects[i];

            // Add project full path
            IPath projectPath = javaProject.getProject().getFullPath();
            paths.add(projectPath);
        }

        // add the project source paths first in a separate loop above
        // to ensure source files always get higher precedence during search.
        // see bug 348507

        for (int i = 0, length = projects.length; i < length; i++) {
            JavaProject javaProject = (JavaProject) projects[i];

            // Add project libraries paths
            IClasspathEntry[] entries = javaProject.getResolvedClasspath();
            for (int j = 0, eLength = entries.length; j < eLength; j++) {
                IClasspathEntry entry = entries[j];
                if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
                    IPath path = entry.getPath();
                    Object target = JavaModel.getTarget(path, false/*don't check existence*/);
                    if (target instanceof IFolder) // case of an external folder
                        path = ((IFolder) target).getFullPath();
                    paths.add(entry.getPath());
                }
            }
        }
        result = new IPath[paths.size()];
        paths.toArray(result);
        return this.enclosingPaths = result;
    } catch (JavaModelException e) {
        Util.log(e, "Exception while computing workspace scope's enclosing projects and jars"); //$NON-NLS-1$
        return new IPath[0];
    } finally {
        if (BasicSearchEngine.VERBOSE) {
            long time = System.currentTimeMillis() - start;
            int length = result == null ? 0 : result.length;
            Util.verbose("JavaWorkspaceScope.enclosingProjectsAndJars: " + length + " paths computed in " + time //$NON-NLS-1$//$NON-NLS-2$
                    + "ms."); //$NON-NLS-1$
        }
    }
}

From source file:org.eclipse.che.plugin.java.plain.server.rest.ClasspathUpdaterService.java

License:Open Source License

private IClasspathEntry[] createModifiedEntry(List<ClasspathEntryDto> entries) {
    List<IClasspathEntry> coreClasspathEntries = new ArrayList<>(entries.size());
    for (ClasspathEntryDto entry : entries) {
        IPath path = fromOSString(entry.getPath());
        int entryKind = entry.getEntryKind();
        if (IClasspathEntry.CPE_LIBRARY == entryKind) {
            coreClasspathEntries.add(newLibraryEntry(path, null, null));
        } else if (IClasspathEntry.CPE_SOURCE == entryKind) {
            coreClasspathEntries.add(newSourceEntry(path));
        } else if (IClasspathEntry.CPE_VARIABLE == entryKind) {
            coreClasspathEntries.add(newVariableEntry(path, null, null));
        } else if (IClasspathEntry.CPE_CONTAINER == entryKind) {
            coreClasspathEntries.add(newContainerEntry(path));
        } else if (IClasspathEntry.CPE_PROJECT == entryKind) {
            coreClasspathEntries.add(newProjectEntry(path));
        }/*ww  w  . java2s. c  o m*/
    }
    return coreClasspathEntries.toArray(new IClasspathEntry[coreClasspathEntries.size()]);
}

From source file:org.eclipse.che.plugin.java.testing.MavenTestClasspathProvider.java

License:Open Source License

public URL[] getProjectClasspath(String projectAbsolutePath, String projectRelativePath, IWorkspaceRoot root)
        throws JavaModelException {
    Stream<ClasspathEntryDto> rawClasspath = classpathService.getClasspath(projectRelativePath).stream();
    Stream<ClasspathEntryDto> resolvedClasspath = toResolvedClassPath(rawClasspath);
    return resolvedClasspath.map(dto -> {
        try {/*from  w w w .  j  ava2 s  . co m*/
            String dtoPath = dto.getPath();
            IResource res = root.findMember(new Path(dtoPath));
            File path;
            switch (dto.getEntryKind()) {
            case IClasspathEntry.CPE_LIBRARY:
                if (res == null) {
                    path = new File(dtoPath);
                } else {
                    path = res.getLocation().toFile();
                }
                break;
            case IClasspathEntry.CPE_SOURCE:
                IPath relativePathFromProjectRoot = new Path(dtoPath).removeFirstSegments(1);
                String relativePathFromProjectRootStr = relativePathFromProjectRoot.toString();
                switch (relativePathFromProjectRootStr) {
                case "src/main/java":
                    path = Paths.get(projectAbsolutePath, "target", "classes").toFile();
                    break;
                case "src/test/java":
                    path = Paths.get(projectAbsolutePath, "target", "test-classes").toFile();
                    break;
                default:
                    path = Paths.get(projectAbsolutePath, "target", "classes").toFile();
                }
                break;
            default:
                path = new File(dtoPath);
            }
            return path.toURI().toURL();
        } catch (MalformedURLException e) {
            return null;
        }
    }).filter(url -> url != null).distinct().toArray(URL[]::new);
}