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

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

Introduction

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

Prototype

int CPE_PROJECT

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

Click Source Link

Document

Entry kind constant describing a classpath entry identifying a required project.

Usage

From source file:org.eclipse.emf.java.presentation.JavaEditor.java

License:Open Source License

public void setupClassLoader(IProject project) {
    JavaPackageResourceImpl javaPackageResource = (JavaPackageResourceImpl) editingDomain
            .loadResource(JavaUtil.JAVA_PACKAGE_RESOURCE);

    IWorkspaceRoot workspaceRoot = project.getWorkspace().getRoot();

    List<URL> libraryURLs = new UniqueEList<URL>();
    List<String> sourceURIs = new ArrayList<String>();
    try {/*from  w w w. ja  va 2 s.c o  m*/
        IJavaProject javaProject = JavaCore.create(project);
        IClasspathEntry[] classpath = javaProject.getResolvedClasspath(true);
        if (classpath != null) {
            for (int i = 0; i < classpath.length; ++i) {
                IClasspathEntry classpathEntry = classpath[i];
                switch (classpathEntry.getEntryKind()) {
                case IClasspathEntry.CPE_LIBRARY:
                case IClasspathEntry.CPE_CONTAINER: {
                    libraryURLs.add(new URL(URI.createFileURI(classpathEntry.getPath().toString()).toString()));
                    break;
                }
                case IClasspathEntry.CPE_SOURCE: {
                    sourceURIs.add(
                            URI.createPlatformResourceURI(classpathEntry.getPath().toString(), true) + "/");
                    break;
                }
                case IClasspathEntry.CPE_PROJECT: {
                    IProject referencedProject = workspaceRoot.getProject(classpathEntry.getPath().segment(0));
                    IJavaProject referencedJavaProject = JavaCore.create(referencedProject);
                    IContainer container = workspaceRoot.getFolder(referencedJavaProject.getOutputLocation());
                    libraryURLs.add(
                            new URL(URI.createFileURI(container.getLocation().toString() + "/").toString()));

                    getAllReferencedProjects(libraryURLs,
                            referencedProject.getDescription().getReferencedProjects());
                    getAllReferencedProjects(libraryURLs,
                            referencedProject.getDescription().getDynamicReferences());
                    break;
                }
                case IClasspathEntry.CPE_VARIABLE:
                default: {
                    break;
                }
                }
            }
        }

        javaPackageResource.setClassLoader(new URLClassLoader(libraryURLs.toArray(new URL[libraryURLs.size()]),
                new URLClassLoader(new URL[0], null)));
        javaPackageResource.getSourceURIs().addAll(sourceURIs);
    } catch (MalformedURLException exception) {
        exception.printStackTrace();
    } catch (JavaModelException exception) {
        exception.printStackTrace();
    } catch (CoreException exception) {
        exception.printStackTrace();
    }
}

From source file:org.eclipse.fx.ide.ui.preview.LivePreviewSynchronizer.java

License:Open Source License

private void resolveDataProject(IJavaProject project, Set<IPath> outputPath, Set<IPath> listRefLibraries) {
    //      System.err.println("START RESOLVE: " + project.getElementName());
    try {//  ww  w .jav  a 2s  . com
        IClasspathEntry[] entries = project.getRawClasspath();
        outputPath.add(project.getOutputLocation());
        for (IClasspathEntry e : entries) {
            //            System.err.println(e + " ====> " + e.getEntryKind());
            if (e.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
                IProject p = ResourcesPlugin.getWorkspace().getRoot().getProject(e.getPath().lastSegment());
                if (p.exists()) {
                    resolveDataProject(JavaCore.create(p), outputPath, listRefLibraries);
                }
            } else if (e.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
                //               System.err.println("CPE_LIBRARY PUSHING: " + e.getPath());
                listRefLibraries.add(e.getPath());
            } else if ("org.eclipse.pde.core.requiredPlugins".equals(e.getPath().toString())) {
                IClasspathContainer cpContainer = JavaCore.getClasspathContainer(e.getPath(), project);
                for (IClasspathEntry cpEntry : cpContainer.getClasspathEntries()) {
                    if (cpEntry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
                        IProject p = ResourcesPlugin.getWorkspace().getRoot()
                                .getProject(cpEntry.getPath().lastSegment());
                        if (p.exists()) {
                            resolveDataProject(JavaCore.create(p), outputPath, listRefLibraries);
                        }
                    } else if (cpEntry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
                        //                     System.err.println("requiredPlugins & CPE_LIBRARY PUSHING: " + e.getPath());
                        listRefLibraries.add(cpEntry.getPath());
                    }
                }
            } else if (e.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
                if (!e.getPath().toString().startsWith("org.eclipse.jdt.launching.JRE_CONTAINER")
                        && !e.getPath().toString().startsWith("org.eclipse.fx.ide.jdt.core.JAVAFX_CONTAINER")) {
                    //                  System.err.println("====> A container");

                    IClasspathContainer cp = JavaCore.getClasspathContainer(e.getPath(), project);
                    for (IClasspathEntry ce : cp.getClasspathEntries()) {
                        //                     System.err.println(ce.getEntryKind() + "=> " + ce);
                        if (ce.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
                            listRefLibraries.add(ce.getPath());
                        } else if (ce.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
                            IProject p = ResourcesPlugin.getWorkspace().getRoot()
                                    .getProject(ce.getPath().lastSegment());
                            if (p.exists()) {
                                resolveDataProject(JavaCore.create(p), outputPath, listRefLibraries);
                            }
                        }
                    }
                }
            }
        }
    } catch (JavaModelException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //      System.err.println("END RESOLVE");
}

From source file:org.eclipse.imp.java.hosted.ProjectUtils.java

License:Open Source License

public void addExtenderForJavaHostedProjects(Language lang) {
    ModelFactory.getInstance().installExtender(new IFactoryExtender() {
        public void extend(ISourceProject project) {
            initializeBuildPathFromJavaProject(project);
        }/*w  ww  . j ava2s . com*/

        public void extend(ICompilationUnit unit) {
        }

        /**
         * Read the IJavaProject classpath configuration and populate the ISourceProject's
         * build path accordingly.
         */
        public void initializeBuildPathFromJavaProject(ISourceProject project) {
            IJavaProject javaProject = JavaCore.create(project.getRawProject());
            if (javaProject.exists()) {
                try {
                    IClasspathEntry[] cpEntries = javaProject.getResolvedClasspath(true);
                    List<IPathEntry> buildPath = new ArrayList<IPathEntry>(cpEntries.length);
                    for (int i = 0; i < cpEntries.length; i++) {
                        IClasspathEntry entry = cpEntries[i];
                        IPathEntry.PathEntryType type;
                        IPath path = entry.getPath();

                        switch (entry.getEntryKind()) {
                        case IClasspathEntry.CPE_CONTAINER:
                            type = PathEntryType.CONTAINER;
                            break;
                        case IClasspathEntry.CPE_LIBRARY:
                            type = PathEntryType.ARCHIVE;
                            break;
                        case IClasspathEntry.CPE_PROJECT:
                            type = PathEntryType.PROJECT;
                            break;
                        case IClasspathEntry.CPE_SOURCE:
                            type = PathEntryType.SOURCE_FOLDER;
                            break;
                        default:
                            // case IClasspathEntry.CPE_VARIABLE:
                            throw new IllegalArgumentException("Encountered variable class-path entry: "
                                    + entry.getPath().toPortableString());
                        }
                        IPathEntry pathEntry = ModelFactory.createPathEntry(type, path);
                        buildPath.add(pathEntry);
                    }
                    project.setBuildPath(buildPath);
                } catch (JavaModelException e) {
                    ErrorHandler.reportError(e.getMessage(), e);
                }
            }
        }
    }, lang);
}

From source file:org.eclipse.jdt.internal.core.JavaModelManager.java

License:Open Source License

/**
 * Returns the package fragment root represented by the resource, or
 * the package fragment the given resource is located in, or <code>null</code>
 * if the given resource is not on the classpath of the given project.
 *//*from w  ww  .j ava 2s  .  c  o  m*/
public static IJavaElement determineIfOnClasspath(IResource resource, IJavaProject project) {
    IPath resourcePath = resource.getFullPath();
    boolean isExternal = ExternalFoldersManager.isInternalPathForExternalFolder(resourcePath);
    if (isExternal)
        resourcePath = resource.getLocation();

    try {
        JavaProjectElementInfo projectInfo = (JavaProjectElementInfo) getJavaModelManager().getInfo(project);
        ProjectCache projectCache = projectInfo == null ? null : projectInfo.projectCache;
        HashtableOfArrayToObject allPkgFragmentsCache = projectCache == null ? null
                : projectCache.allPkgFragmentsCache;
        boolean isJavaLike = org.eclipse.jdt.internal.core.util.Util
                .isJavaLikeFileName(resourcePath.lastSegment());
        IClasspathEntry[] entries = isJavaLike ? project.getRawClasspath() // JAVA file can only live inside SRC folder (on the raw path)
                : ((JavaProject) project).getResolvedClasspath();

        int length = entries.length;
        if (length > 0) {
            String sourceLevel = project.getOption(JavaCore.COMPILER_SOURCE, true);
            String complianceLevel = project.getOption(JavaCore.COMPILER_COMPLIANCE, true);
            for (int i = 0; i < length; i++) {
                IClasspathEntry entry = entries[i];
                if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT)
                    continue;
                IPath rootPath = entry.getPath();
                if (rootPath.equals(resourcePath)) {
                    if (isJavaLike)
                        return null;
                    return project.getPackageFragmentRoot(resource);
                } else if (rootPath.isPrefixOf(resourcePath)) {
                    // allow creation of package fragment if it contains a .java file that is included
                    if (!Util.isExcluded(resource, ((ClasspathEntry) entry).fullInclusionPatternChars(),
                            ((ClasspathEntry) entry).fullExclusionPatternChars())) {
                        // given we have a resource child of the root, it cannot be a JAR pkg root
                        PackageFragmentRoot root = isExternal
                                ? new ExternalPackageFragmentRoot(rootPath, (JavaProject) project)
                                : (PackageFragmentRoot) ((JavaProject) project)
                                        .getFolderPackageFragmentRoot(rootPath);
                        if (root == null)
                            return null;
                        IPath pkgPath = resourcePath.removeFirstSegments(rootPath.segmentCount());

                        if (resource.getType() == IResource.FILE) {
                            // if the resource is a file, then remove the last segment which
                            // is the file name in the package
                            pkgPath = pkgPath.removeLastSegments(1);
                        }
                        String[] pkgName = pkgPath.segments();

                        // if package name is in the cache, then it has already been validated
                        // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=133141)
                        if (allPkgFragmentsCache != null && allPkgFragmentsCache.containsKey(pkgName))
                            return root.getPackageFragment(pkgName);

                        if (pkgName.length != 0 && JavaConventions
                                .validatePackageName(Util.packageName(pkgPath, sourceLevel, complianceLevel),
                                        sourceLevel, complianceLevel)
                                .getSeverity() == IStatus.ERROR) {
                            return null;
                        }
                        return root.getPackageFragment(pkgName);
                    }
                }
            }
        }
    } catch (JavaModelException npe) {
        return null;
    }
    return null;
}

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

License:Open Source License

/**
 * Internal computation of an expanded classpath. It will eliminate duplicates, and produce copies
 * of exported or restricted classpath entries to avoid possible side-effects ever after.
 *///w w w.jav a2 s.  c  o m
private void computeExpandedClasspath(ClasspathEntry referringEntry, HashSet rootIDs,
        ObjectVector accumulatedEntries) throws JavaModelException {

    String projectRootId = rootID();
    if (rootIDs.contains(projectRootId)) {
        return; // break cycles if any
    }
    rootIDs.add(projectRootId);

    IClasspathEntry[] resolvedClasspath = getResolvedClasspath();

    IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
    boolean isInitialProject = referringEntry == null;
    for (int i = 0, length = resolvedClasspath.length; i < length; i++) {
        ClasspathEntry entry = (ClasspathEntry) resolvedClasspath[i];
        if (isInitialProject || entry.isExported()) {
            String rootID = entry.rootID();
            if (rootIDs.contains(rootID)) {
                continue;
            }
            // combine restrictions along the project chain
            ClasspathEntry combinedEntry = entry.combineWith(referringEntry);
            accumulatedEntries.add(combinedEntry);

            // recurse in project to get all its indirect exports (only consider exported entries from there on)
            if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
                IResource member = workspaceRoot.findMember(entry.getPath());
                if (member != null && member.getType() == IResource.PROJECT) { // double check if bound to project (23977)
                    IProject projRsc = (IProject) member;
                    if (JavaProject.hasJavaNature(projRsc)) {
                        JavaProject javaProject = (JavaProject) JavaCore.create(projRsc);
                        javaProject.computeExpandedClasspath(combinedEntry, rootIDs, accumulatedEntries);
                    }
                }
            } else {
                rootIDs.add(rootID);
            }
        }
    }
}

From source file:org.eclipse.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/*from w  w w  .  j a  va 2s  .c  o  m*/
 * @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.project.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 target = JavaModel.getTarget(entryPath, true/*check existency*/);
            if (target == null)
                return;

            if (target instanceof IFolder || target instanceof IProject) {
                root = getPackageFragmentRoot((IResource) target);
            }
        }
        break;

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

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

    // recurse into required project
    case IClasspathEntry.CPE_PROJECT:

        if (!retrieveExportedRoots)
            return;
        if (referringEntry != null && !resolvedEntry.isExported())
            return;

        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
                                : ((ClasspathEntry) resolvedEntry).combineWith((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.jdt.internal.core.JavaProject.java

License:Open Source License

public boolean isOnClasspath(IJavaElement element) {
    IClasspathEntry[] rawClasspath;/*from   w w  w  . ja  v a2  s.co  m*/
    try {
        rawClasspath = getRawClasspath();
    } catch (JavaModelException e) {
        return false; // not a Java project
    }
    int elementType = element.getElementType();
    boolean isPackageFragmentRoot = false;
    boolean isFolderPath = false;
    boolean isSource = false;
    switch (elementType) {
    case IJavaElement.JAVA_MODEL:
        return false;
    case IJavaElement.JAVA_PROJECT:
        break;
    case IJavaElement.PACKAGE_FRAGMENT_ROOT:
        isPackageFragmentRoot = true;
        break;
    case IJavaElement.PACKAGE_FRAGMENT:
        isFolderPath = !((IPackageFragmentRoot) element.getParent()).isArchive();
        break;
    case IJavaElement.COMPILATION_UNIT:
        isSource = true;
        break;
    default:
        isSource = element.getAncestor(IJavaElement.COMPILATION_UNIT) != null;
        break;
    }
    IPath elementPath = element.getPath();

    // first look at unresolved entries
    int length = rawClasspath.length;
    for (int i = 0; i < length; i++) {
        IClasspathEntry entry = rawClasspath[i];
        switch (entry.getEntryKind()) {
        case IClasspathEntry.CPE_LIBRARY:
        case IClasspathEntry.CPE_PROJECT:
        case IClasspathEntry.CPE_SOURCE:
            if (isOnClasspathEntry(elementPath, isFolderPath, isPackageFragmentRoot, entry))
                return true;
            break;
        }
    }

    // no need to go further for compilation units and elements inside a compilation unit
    // it can only be in a source folder, thus on the raw classpath
    if (isSource)
        return false;

    // https://bugs.eclipse.org/bugs/show_bug.cgi?id=304081
    // All the resolved classpath entries need to be considered, including the referenced classpath entries
    IClasspathEntry[] resolvedClasspath = null;
    try {
        resolvedClasspath = getResolvedClasspath();
    } catch (JavaModelException e) {
        return false; // Perhaps, not a Java project
    }

    for (int index = 0; index < resolvedClasspath.length; index++) {
        if (isOnClasspathEntry(elementPath, isFolderPath, isPackageFragmentRoot, resolvedClasspath[index]))
            return true;
    }

    return false;
}

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

License:Open Source License

public String[] projectPrerequisites(IClasspathEntry[] resolvedClasspath) throws JavaModelException {

    ArrayList prerequisites = new ArrayList();
    for (int i = 0, length = resolvedClasspath.length; i < length; i++) {
        IClasspathEntry entry = resolvedClasspath[i];
        if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
            prerequisites.add(entry.getPath().lastSegment());
        }//from  w w  w.  j a v a  2 s  . c  om
    }
    int size = prerequisites.size();
    if (size == 0) {
        return NO_PREREQUISITES;
    } else {
        String[] result = new String[size];
        prerequisites.toArray(result);
        return result;
    }
}

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

License:Open Source License

/**
 * If a cycle is detected, then cycleParticipants contains all the paths of projects involved in this cycle (directly and indirectly),
 * no cycle if the set is empty (and started empty)
 * @param prereqChain ArrayList/*from  w ww .  j av  a2s . c  o m*/
 * @param cycleParticipants HashSet
 * @param workspaceRoot IWorkspaceRoot
 * @param traversed HashSet
 * @param preferredClasspaths Map
 */
public void updateCycleParticipants(ArrayList prereqChain, LinkedHashSet cycleParticipants,
        IWorkspaceRoot workspaceRoot, HashSet traversed, Map preferredClasspaths) {

    IPath path = getPath();
    prereqChain.add(path);
    traversed.add(path);
    try {
        IClasspathEntry[] classpath = null;
        if (preferredClasspaths != null)
            classpath = (IClasspathEntry[]) preferredClasspaths.get(this);
        if (classpath == null)
            classpath = getResolvedClasspath();
        for (int i = 0, length = classpath.length; i < length; i++) {
            IClasspathEntry entry = classpath[i];

            if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
                IPath prereqProjectPath = entry.getPath();
                int index = cycleParticipants.contains(prereqProjectPath) ? 0
                        : prereqChain.indexOf(prereqProjectPath);
                if (index >= 0) { // refer to cycle, or in cycle itself
                    for (int size = prereqChain.size(); index < size; index++) {
                        cycleParticipants.add(prereqChain.get(index));
                    }
                } else {
                    if (!traversed.contains(prereqProjectPath)) {
                        IResource member = workspaceRoot.findMember(prereqProjectPath);
                        if (member != null && member.getType() == IResource.PROJECT) {
                            JavaProject javaProject = (JavaProject) JavaCore.create((IProject) member);
                            javaProject.updateCycleParticipants(prereqChain, cycleParticipants, workspaceRoot,
                                    traversed, preferredClasspaths);
                        }
                    }
                }
            }
        }
    } catch (JavaModelException e) {
        // project doesn't exist: ignore
    }
    prereqChain.remove(path);
}

From source file:org.eclipse.jem.internal.beaninfo.core.BeaninfoEntry.java

License:Open Source License

static String kindToString(int kind) {

    switch (kind) {
    case IClasspathEntry.CPE_PROJECT:
        return "src"; // backward compatibility //$NON-NLS-1$
    case IClasspathEntry.CPE_SOURCE:
        return "src"; //$NON-NLS-1$
    case IClasspathEntry.CPE_LIBRARY:
        return "lib"; //$NON-NLS-1$
    case IClasspathEntry.CPE_VARIABLE:
        return "var"; //$NON-NLS-1$
    case IClasspathEntry.CPE_CONTAINER:
        return "con"; //$NON-NLS-1$
    case BIE_PLUGIN:
        return "plugin"; //$NON-NLS-1$
    default://w  w  w . j  a  v a2 s  .c  o  m
        return "unknown"; //$NON-NLS-1$
    }
}