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

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

Introduction

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

Prototype

int getEntryKind();

Source Link

Document

Returns the kind of this classpath entry.

Usage

From source file:net.rim.ejde.internal.core.RimIDEUtil.java

License:Open Source License

/**
 * Gets a file that exists in an Eclipse project.
 * <p>//from w  ww. j  a va 2s.  c  o  m
 * TODO: Someone can probably optimize this method better. Like using some of the IWorkspaceRoot.find*() methods...
 *
 * @param project
 *            the Eclipse project the file belongs to
 * @param file
 *            the File which is in the Eclipse project
 * @return the Eclipse resource file associated with the file
 */
public static IResource getResource(IProject project, File file) {
    IJavaProject javaProject = JavaCore.create(project);
    IPath filePath = new Path(file.getAbsolutePath());
    try {
        IClasspathEntry[] classpathEntries = javaProject.getResolvedClasspath(true);

        IFile input = null;
        // Look for a source folder
        for (IClasspathEntry classpathEntry : classpathEntries) {
            if (classpathEntry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {

                // Try to resolve the source container
                IWorkspaceRoot workspaceRoot = project.getWorkspace().getRoot();
                IResource resource = workspaceRoot.findMember(classpathEntry.getPath());
                if (resource instanceof IContainer) {
                    try {
                        IContainer sourceContainer = (IContainer) resource;
                        File sourceContainerFile = EFS.getStore(resource.getLocationURI()).toLocalFile(EFS.NONE,
                                null);
                        IPath sourceFolderPath = new Path(sourceContainerFile.getAbsolutePath());

                        // See if the file path is within this source folder
                        // path
                        if (sourceFolderPath.isPrefixOf(filePath)) {
                            int segmentCount = sourceFolderPath.segmentCount();
                            IPath relativePath = filePath.removeFirstSegments(segmentCount);
                            input = sourceContainer.getFile(relativePath);

                            break;
                        }
                    } catch (CoreException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
        return input;
    } catch (JavaModelException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:net.rim.ejde.internal.packaging.PackagingManager.java

License:Open Source License

static private void getCompileImportsRecusively(IClasspathEntry[] entries, IJavaProject jProject,
        Vector<ImportedJar> imports, boolean isMainProject) throws CoreException {
    if (imports == null) {
        imports = new Vector<ImportedJar>();
    }//from   w  ww. j a  v a  2  s. com
    // Workspace imports; if there aren't any specified, default to
    // using the runtime libraries.
    IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
    // String jarPathString;
    try {
        BlackBerryProperties properties = null;
        boolean needAddBBJar = false;
        IPath jarPath = null;
        ImportedJar importedJar = null;
        for (IClasspathEntry entry : entries) {
            switch (entry.getEntryKind()) {
            case IClasspathEntry.CPE_CONTAINER: {
                // libraries
                IClasspathContainer container = JavaCore.getClasspathContainer(entry.getPath(),
                        jProject.getJavaProject());
                if (container == null) {
                    continue;
                }

                IVMInstall containerVM;
                if (!(container instanceof JREContainer)) {
                    // We need to verify the type of the container because the path of Maven container only has one
                    // segment and JavaRuntime.getVMInstall(IPath) return the default VM install if the entry path has one
                    // segment.
                    containerVM = null;
                } else {
                    containerVM = JavaRuntime.getVMInstall(entry.getPath());
                }

                try {
                    if (containerVM != null) {
                        if (containerVM.getVMInstallType().getId().equals(BlackBerryVMInstallType.VM_ID)) {
                            if (isMainProject) {
                                // Add jars to a list
                                IClasspathEntry[] classpathEntries = container.getClasspathEntries();
                                if (classpathEntries != null && classpathEntries.length > 0) {
                                    getCompileImportsRecusively(classpathEntries, jProject, imports, false);
                                }
                            }
                        } else {
                            if (!jProject.getProject().hasNature(BlackBerryProjectCoreNature.NATURE_ID)) {
                                needAddBBJar = true;
                                continue;
                            }
                        }
                    } else {
                        // Add jars to a list
                        IClasspathEntry[] classpathEntries = container.getClasspathEntries();
                        if (classpathEntries != null && classpathEntries.length > 0) {
                            getCompileImportsRecusively(classpathEntries, jProject, imports, false);
                        }
                    }
                } catch (CoreException e) {
                    _log.error(e.getMessage());
                    continue;
                }
                break;
            }
            case IClasspathEntry.CPE_LIBRARY: {
                // imported jars
                jarPath = PackageUtils.getAbsoluteEntryPath(entry);
                // the jar path can be null if the jar file does not exist
                if (jarPath == null) {
                    throw new CoreException(StatusFactory.createErrorStatus(
                            NLS.bind(Messages.PackagingManager_Entry_Not_Found_MSG, entry.getPath())));
                }
                if (jarPath.lastSegment().equals(IConstants.RIM_API_JAR) && needAddBBJar) {
                    needAddBBJar = false;
                }

                importedJar = null;
                if (PackagingUtils.getPackagExportedJar()) {
                    if (entry.isExported()) {
                        if (isMainProject) {
                            // if the exported jar is not in the main project but a dependent project, the classes it
                            // contains are packaged into the dependent project jar. We don't add it to classpath.
                            importedJar = new ImportedJar(jarPath.toOSString(), true,
                                    getJarFileType(jarPath.toFile()));
                        }
                    } else {
                        importedJar = new ImportedJar(jarPath.toOSString(), false,
                                getJarFileType(jarPath.toFile()));
                    }
                } else {
                    importedJar = new ImportedJar(jarPath.toOSString(), false,
                            getJarFileType(jarPath.toFile()));
                }
                if (importedJar != null && !existingJar(imports, importedJar)) {
                    imports.add(importedJar);
                }
                break;
            }
            case IClasspathEntry.CPE_PROJECT: {
                // dependency projects
                IProject project = workspaceRoot.getProject(entry.getPath().toString());
                IJavaProject javaProject = JavaCore.create(project);
                try {
                    if (project.hasNature(BlackBerryProjectCoreNature.NATURE_ID)) {
                        properties = ContextManager.PLUGIN.getBBProperties(javaProject.getProject().getName(),
                                false);
                        if (properties == null) {
                            _log.error("BlackBerry properties is null");
                            break;
                        }
                    } else {
                        properties = BlackBerryPropertiesFactory.createBlackBerryProperties(javaProject);
                    }
                } catch (CoreException e) {
                    _log.error(e.getMessage());
                    continue;
                }
                if (PackagingManager.getProjectTypeID(properties._application.getType()) == Project.LIBRARY) {
                    IPath absoluteJarPath = PackagingUtils
                            .getAbsoluteStandardOutputFilePath(new BlackBerryProject(javaProject, properties));
                    File jarFile = new File(
                            absoluteJarPath.toOSString() + IConstants.DOT_MARK + IConstants.JAR_EXTENSION);
                    importedJar = new ImportedJar(jarFile.getAbsolutePath(), false, getJarFileType(jarFile));
                    if (!existingJar(imports, importedJar)) {
                        imports.add(importedJar);
                    }
                    IClasspathEntry[] subEntries = javaProject.getRawClasspath();
                    if (subEntries != null && subEntries.length > 0) {
                        getCompileImportsRecusively(subEntries, javaProject, imports, false);
                    }
                }
                break;
            }
            case IClasspathEntry.CPE_VARIABLE: {
                // variables
                String e = entry.getPath().toString();
                int index = e.indexOf('/');
                if (index == -1) {
                    index = e.indexOf('\\');
                }
                String variable = e;
                IPath cpvar = JavaCore.getClasspathVariable(variable);
                if (cpvar == null) {
                    String msg = NLS.bind(Messages.PackagingManager_Variable_Not_Defined_MSG, variable);
                    throw new CoreException(StatusFactory.createErrorStatus(msg));
                }
                if (cpvar.lastSegment().equals(IConstants.RIM_API_JAR) && needAddBBJar) {
                    needAddBBJar = false;
                }
                // TODO RAPC does not support a class folder. We may support it later on
                if (cpvar.lastSegment().endsWith("." + IConstants.JAR_EXTENSION)) {
                    importedJar = new ImportedJar(cpvar.toOSString(), false, getJarFileType(cpvar.toFile()));
                    if (!existingJar(imports, importedJar)) {
                        imports.add(importedJar);
                    }
                }
                break;
            }
            }
        }
        if (needAddBBJar && isMainProject) {
            // insert the default BB jre lib if needed
            IVMInstall bbVM = VMUtils.getDefaultBBVM();
            if (bbVM != null) {
                LibraryLocation[] libLocations = bbVM.getLibraryLocations();
                if (libLocations != null) {
                    for (LibraryLocation location : libLocations) {
                        importedJar = new ImportedJar(location.getSystemLibraryPath().toOSString(), false,
                                getJarFileType(location.getSystemLibraryPath().toFile()));
                        if (!existingJar(imports, importedJar)) {
                            imports.add(importedJar);
                        }
                    }
                }
            }
        }
    } catch (JavaModelException e) {
        _log.error(e.getMessage());
    }
}

From source file:net.rim.ejde.internal.sourcelookup.RIMSourcePathProvider.java

License:Open Source License

/**
 * Computes and returns the default unresolved runtime classpath for the given project.
 *
 * @return runtime classpath entries// w ww .ja v a  2 s. c  o m
 * @exception CoreException
 *                if unable to compute the runtime classpath
 * @see IRuntimeClasspathEntry
 */
public static IRuntimeClasspathEntry[] computeUnresolvedRuntimeClasspath(IJavaProject project)
        throws CoreException {
    IClasspathEntry[] entries = project.getRawClasspath();
    List<IRuntimeClasspathEntry> classpathEntries = new ArrayList<IRuntimeClasspathEntry>();
    for (int i = 0; i < entries.length; i++) {
        IClasspathEntry entry = entries[i];
        switch (entry.getEntryKind()) {
        case IClasspathEntry.CPE_CONTAINER:
            IClasspathContainer container = JavaCore.getClasspathContainer(entry.getPath(), project);
            if (container != null) {
                switch (container.getKind()) {
                case IClasspathContainer.K_APPLICATION:
                    // don't look at application entries
                    break;
                case IClasspathContainer.K_DEFAULT_SYSTEM:
                    classpathEntries.add(JavaRuntime.newRuntimeContainerClasspathEntry(container.getPath(),
                            IRuntimeClasspathEntry.STANDARD_CLASSES, project));
                    break;
                case IClasspathContainer.K_SYSTEM:
                    classpathEntries.add(JavaRuntime.newRuntimeContainerClasspathEntry(container.getPath(),
                            IRuntimeClasspathEntry.BOOTSTRAP_CLASSES, project));
                    break;
                }
            }
            break;
        case IClasspathEntry.CPE_VARIABLE:
            if (JavaRuntime.JRELIB_VARIABLE.equals(entry.getPath().segment(0))) {
                IRuntimeClasspathEntry jre = JavaRuntime.newVariableRuntimeClasspathEntry(entry.getPath());
                jre.setClasspathProperty(IRuntimeClasspathEntry.STANDARD_CLASSES);
                classpathEntries.add(jre);
            }
            break;
        default:
            break;
        }
    }
    classpathEntries.add(JavaRuntime.newDefaultProjectClasspathEntry(project));
    return classpathEntries.toArray(new IRuntimeClasspathEntry[classpathEntries.size()]);
}

From source file:net.rim.ejde.internal.util.ImportUtils.java

License:Open Source License

/**
 * Get the set of output paths of the given <code>IJavaProject</code>.
 *
 * @param javaProject/* w w w . j a  v a  2s. c  om*/
 * @return
 * @throws JavaModelException
 */
static public Set<IPath> getOutputPathSet(IJavaProject javaProject) {
    HashSet<IPath> outputPathSet = new HashSet<IPath>();

    try {
        // get the output folder path of the project
        IPath outputFolderPath = javaProject.getOutputLocation();
        if (outputFolderPath != null) {
            outputPathSet.add(outputFolderPath);
        }

        IClasspathEntry[] _classPathEntries = javaProject.getRawClasspath();

        IClasspathEntry entry;

        for (int i = 0; i < _classPathEntries.length; i++) {
            entry = _classPathEntries[i];
            if (IClasspathEntry.CPE_SOURCE == entry.getEntryKind()) {
                // get the output folder of the entry
                outputFolderPath = entry.getOutputLocation();
                if (outputFolderPath != null) {
                    outputPathSet.add(outputFolderPath);
                }
            }
        }
    } catch (JavaModelException e) {
        _log.debug(e.getMessage(), e);
    }

    return outputPathSet;
}

From source file:net.rim.ejde.internal.util.ImportUtils.java

License:Open Source License

/**
 * Applies the Java Path exclusion patterns to a given project and returns the list of filtered IClasspathEntry
 *
 * @param eclipseProject//from  w  ww.  jav  a 2 s  .com
 * @param legacyProject
 * @param originalClasspathEntries
 * @return
 */
static public List<IClasspathEntry> applyExclusionPatterns(IProject eclipseProject, Project legacyProject,
        List<IClasspathEntry> originalClasspathEntries) {
    if (null == eclipseProject) {
        throw new IllegalArgumentException("Can't process undefined Eclipse project!");
    }

    if (null == legacyProject) {
        throw new IllegalArgumentException("Can't process undefined legacy project!");
    }

    if (null == originalClasspathEntries) {
        throw new IllegalArgumentException("Can't process undefined Eclipse classpath entries!");
    }

    // TODO: call this when importing projects, rather than from the
    // Compilation Participant
    List<WorkspaceFile> excludedWorkspaceFiles = getFilesToBeExcluded(legacyProject);

    if (excludedWorkspaceFiles.isEmpty() && originalClasspathEntries.isEmpty()) {
        return originalClasspathEntries;
    }

    List<IClasspathEntry> excludedClasspathEntries = new ArrayList<IClasspathEntry>();
    HashMap<IPath, IClasspathEntry> filterMap = new HashMap<IPath, IClasspathEntry>();
    String projectNamePattern = IPath.SEPARATOR + eclipseProject.getName() + IPath.SEPARATOR;
    List<IPath> exclusionPatterns;
    IPath classpathEntryPath, exclusionPatternPath;
    boolean forProject;
    String lastSegment;
    IFolder folder;
    IPath srcLocation;
    IClasspathEntry newEntry;
    IPath[] excludedPaths;
    File file;
    String workspaceFilePath;
    String packageId;

    for (IClasspathEntry entry : originalClasspathEntries) {
        exclusionPatterns = new ArrayList<IPath>();

        classpathEntryPath = entry.getPath();

        if (IClasspathEntry.CPE_SOURCE == entry.getEntryKind()) {
            lastSegment = classpathEntryPath.lastSegment();

            if (lastSegment.equalsIgnoreCase(
                    ImportUtils.getImportPref(ResourceBuilder.LOCALE_INTERFACES_FOLDER_NAME))) {
                continue;
            }

            folder = eclipseProject.getFolder(lastSegment);

            if (folder.isDerived() || !folder.exists()) {
                continue;
            }

            forProject = classpathEntryPath.toString().startsWith(projectNamePattern);

            if (forProject) {
                srcLocation = folder.getLocation();

                if (srcLocation == null || srcLocation.isEmpty()) {
                    return originalClasspathEntries;
                }

                for (WorkspaceFile workspaceFile : excludedWorkspaceFiles) {
                    workspaceFilePath = workspaceFile.toString();
                    file = workspaceFile.getFile();

                    if (null != file && file.exists() && file.isFile()) {
                        // Fix for IDT 149988 - Check type of source folder and file type to prevent duplication for exclusion
                        // patterns
                        if (lastSegment.equalsIgnoreCase(
                                ImportUtils.getImportPref(LegacyImportHelper.PROJECT_SRC_FOLDER_NAME_KEY))) {
                            if (!workspaceFile.getIsJava()) {
                                continue;
                            }
                        } else {
                            if (workspaceFile.getIsJava()) {
                                continue;
                            }
                        }

                        if (workspaceFile.getIsJava() || workspaceFile.getIsResourceHeader()
                                || workspaceFile.getIsResource()) {
                            packageId = IConstants.EMPTY_STRING;
                            try {
                                packageId = PackageUtils.getFilePackageString(file, legacyProject);
                            } catch (CoreException e) {
                                _log.error(e.getMessage());
                                packageId = IConstants.EMPTY_STRING;
                            }
                            workspaceFilePath = File.separator + packageId + File.separator + workspaceFilePath;
                        }
                        exclusionPatternPath = getExclusionPattern(workspaceFile, lastSegment, eclipseProject,
                                legacyProject);

                        if (!exclusionPatternPath.isEmpty()) {
                            exclusionPatterns.add(exclusionPatternPath);
                        }
                    }
                }
            }

            if (exclusionPatterns.isEmpty()) {
                excludedPaths = new IPath[] {};
            } else {
                excludedPaths = exclusionPatterns.toArray(new IPath[exclusionPatterns.size()]);
            }

            newEntry = JavaCore.newSourceEntry(classpathEntryPath, entry.getInclusionPatterns(), excludedPaths,
                    entry.getOutputLocation(), entry.getExtraAttributes());
            filterMap.put(classpathEntryPath, newEntry);
        } else {// IClasspathEntry of type other than CPE_SOURCE
            filterMap.put(classpathEntryPath, entry);
        }
    }

    IPath elementPath;

    for (IClasspathEntry element : originalClasspathEntries) {
        elementPath = element.getPath();
        newEntry = filterMap.get(elementPath);
        if (null != newEntry) {
            excludedClasspathEntries.add(newEntry);
        }
    }

    return excludedClasspathEntries;
}

From source file:net.rim.ejde.internal.util.LegacyModelUtil.java

License:Open Source License

static public void setSource(Project proj, IJavaProject eclipseJavaProject, String source) {
    if (null == proj)// Don't process for a non existing legacy project
        return;//from   w ww. ja  v a2 s .c o  m

    if (StringUtils.isBlank(source))// Don't process for a non existing
        // source folder
        return;

    if (null == eclipseJavaProject)// Don't process for a non existing
        // Eclipse equivalent
        return;

    try {
        IClasspathEntry[] classpathEntries = eclipseJavaProject.getRawClasspath();

        IWorkspace workspace = ResourcesPlugin.getWorkspace();
        IWorkspaceRoot workspaceRoot = workspace.getRoot();

        IPath classpathEntryPath;
        String classpathEntryLastSegment;
        IFolder folder;

        for (IClasspathEntry classpathEntry : classpathEntries) {
            if (IClasspathEntry.CPE_SOURCE == classpathEntry.getEntryKind()) {
                classpathEntryPath = classpathEntry.getPath();
                classpathEntryLastSegment = classpathEntryPath.lastSegment();

                if (source.equalsIgnoreCase(classpathEntryLastSegment)) {// if
                    // the
                    // string
                    // can't
                    // be
                    // matched
                    // to
                    // an
                    // existing
                    // classpath
                    // entry
                    // why
                    // should
                    // we
                    // add
                    // it
                    // to
                    // the
                    // legacy
                    // metadata?!
                    if (ImportUtils.getImportPref(ResourceBuilder.LOCALE_INTERFACES_FOLDER_NAME)
                            .equalsIgnoreCase(classpathEntryLastSegment)) {
                        return;
                    }
                    if (!classpathEntryPath.toOSString().equals(IConstants.EMPTY_STRING)) {

                        folder = workspaceRoot.getFolder(classpathEntryPath);

                        if (folder.isDerived())// Don't process for
                            // Eclipse
                            // derived directories
                            return;
                    }

                }
            }
        }
    } catch (JavaModelException e) {
        log.error(e.getMessage(), e);
    }

    String udata = proj.getUserData();

    if (StringUtils.isNotBlank(udata)) {
        int idx1 = udata.indexOf(DELIM_SECTION);
        if (idx1 >= 0) {
            int idx2 = udata.indexOf(DELIM_SECTION, idx1 + 1);
            String udata_new = (idx1 > 0 ? udata.substring(0, idx1) : EMPTY_STRING) + DELIM_SECTION + source
                    + (idx2 > idx1 ? udata.substring(idx2) : EMPTY_STRING);
            if (!udata.equals(udata_new)) {
                proj.setUserData(udata_new);
            }
        }
    } else {
        proj.setUserData(DELIM_SECTION + source);
    }
}

From source file:net.rim.ejde.internal.util.LegacyModelUtil.java

License:Open Source License

static public void syncSources(Project proj, IJavaProject eclipseJavaProject) {
    if (null == proj)// Don't process for a non existing legacy project
        return;//from  w  w  w .  j  a v  a2s .c  o m

    if (null == eclipseJavaProject)// Don't process for a non existing
        // Eclipse equivalent
        return;

    String sources = "";
    StringBuffer buf = new StringBuffer();

    try {
        IClasspathEntry[] classpathEntries = eclipseJavaProject.getRawClasspath();

        IWorkspace workspace = ResourcesPlugin.getWorkspace();
        IWorkspaceRoot workspaceRoot = workspace.getRoot();

        IPath classpathEntryPath;
        String classpathEntryLastSegment;
        IFolder folder;

        for (IClasspathEntry classpathEntry : classpathEntries) {
            if (IClasspathEntry.CPE_SOURCE == classpathEntry.getEntryKind()) {
                classpathEntryPath = classpathEntry.getPath();
                classpathEntryLastSegment = classpathEntryPath.lastSegment();

                if (ImportUtils.getImportPref(ResourceBuilder.LOCALE_INTERFACES_FOLDER_NAME)
                        .equalsIgnoreCase(classpathEntryLastSegment)) {
                    continue;
                }

                if (classpathEntryPath.toOSString().equals(IConstants.EMPTY_STRING)) {
                    continue;
                }

                folder = workspaceRoot.getFolder(classpathEntryPath);

                if (folder.isDerived()) {// Don't process for Eclipse
                    // derived directories
                    continue;
                }

                buf.append(DELIM_SECTION + classpathEntryLastSegment);
            }
        }
    } catch (JavaModelException e) {
        log.error(e.getMessage(), e);
    }

    sources = buf.toString();

    String udata = proj.getUserData();

    if (StringUtils.isNotBlank(udata)) {

        int idx1 = udata.indexOf(DELIM_SECTION);

        if (idx1 >= 0) {
            int idx2 = udata.indexOf(DELIM_SECTION, idx1 + 1);
            String udata_new = (idx1 > 0 ? udata.substring(0, idx1) : EMPTY_STRING) + DELIM_SECTION + sources
                    + (idx2 > idx1 ? udata.substring(idx2) : EMPTY_STRING);
            if (!udata.equals(udata_new)) {
                proj.setUserData(udata_new);
            }
        }
    } else {
        proj.setUserData(sources);
    }
}

From source file:net.rim.ejde.internal.util.PackageUtils.java

License:Open Source License

/**
 * Return the absolute path of the given entry.
 *
 * @param currentEntry/*from www .j  a va  2  s . c o  m*/
 * @return the absolute path of the give entry. Return <code>null<code> if the entry can not be found.
 */
public static IPath getAbsolutePath(IClasspathEntry currentEntry) {
    if (currentEntry == null) {
        return null;
    }
    if (currentEntry.getEntryKind() != IClasspathEntry.CPE_LIBRARY) {
        return currentEntry.getPath();
    }
    IPath absolutePath = null;
    IPath path = currentEntry.getPath();
    Object target = JavaModel.getTarget(path, true);
    if (target instanceof IResource) {
        // if the target was found inside workspace
        IResource resource = (IResource) target;
        absolutePath = resource.getLocation();
    } else if (target instanceof File) {
        // if the target was found outside of the workspace
        absolutePath = new Path(((File) target).getAbsolutePath());
    }
    return absolutePath;
}

From source file:net.rim.ejde.internal.util.PackageUtils.java

License:Open Source License

/**
 * Gets all the source folders of the given <code>iJavaProject</code>.
 *
 * @param iJavaProject/*from w w w  .ja  v  a  2 s .  co m*/
 * @return
 */
public static ArrayList<IContainer> getAllSrcFolders(IJavaProject iJavaProject) {
    ArrayList<IContainer> result = new ArrayList<IContainer>();
    IProject iProject = iJavaProject.getProject();
    IClasspathEntry[] classPathEntries = null;
    IFolder srcFolder = null;
    IPath srcFolderPath = null;
    IPath relativeSrcFolderPath = null;
    try {
        classPathEntries = iJavaProject.getRawClasspath();
        for (IClasspathEntry classPathEntry : classPathEntries) {
            if (classPathEntry.getEntryKind() != IClasspathEntry.CPE_SOURCE) {
                continue;
            }
            srcFolderPath = classPathEntry.getPath();
            if (srcFolderPath.segment(0).equals(iProject.getName())) {
                // remove the project name from the path
                relativeSrcFolderPath = srcFolderPath.removeFirstSegments(1);
            }
            if (relativeSrcFolderPath == null || relativeSrcFolderPath.isEmpty()) {
                result.add(iProject);
            } else {
                srcFolder = iProject.getFolder(relativeSrcFolderPath);
                if (srcFolder.exists()) {
                    result.add(srcFolder);
                }
            }
        }
    } catch (Throwable e) {
        _logger.error(e.getMessage(), e);
    }
    return result;
}

From source file:net.rim.ejde.internal.util.ProjectUtils.java

License:Open Source License

/**
 * Gets a file that exists in an Eclipse project.
 * <p>/*from  w w w .jav a  2  s  .co  m*/
 * TODO: Someone can probably optimize this method better. Like using some of the IWorkspaceRoot.find*() methods...
 *
 * @param project
 *            the Eclipse project the file belongs to
 * @param file
 *            the File which is in the Eclipse project
 * @return the Eclipse resource file associated with the file
 */
public static IResource getResource(IProject project, File file) {
    IJavaProject javaProject = JavaCore.create(project);
    IPath filePath = new Path(file.getAbsolutePath());
    try {
        IClasspathEntry[] classpathEntries = javaProject.getResolvedClasspath(true);

        IFile input = null;
        // Look for a source folder
        for (IClasspathEntry classpathEntry : classpathEntries) {
            if (classpathEntry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {

                // Try to resolve the source container
                IWorkspaceRoot workspaceRoot = project.getWorkspace().getRoot();
                IResource resource = workspaceRoot.findMember(classpathEntry.getPath());
                if (resource instanceof IContainer) {
                    IContainer sourceContainer = (IContainer) resource;
                    File sourceContainerFile = resource.getLocation().toFile();
                    IPath sourceFolderPath = new Path(sourceContainerFile.getAbsolutePath());

                    // See if the file path is within this source folder
                    // path
                    if (sourceFolderPath.isPrefixOf(filePath)) {
                        int segmentCount = sourceFolderPath.segmentCount();
                        IPath relativePath = filePath.removeFirstSegments(segmentCount);
                        input = sourceContainer.getFile(relativePath);
                        break;
                    }
                }
            }
        }
        return input;
    } catch (JavaModelException e) {
        e.printStackTrace();
        return null;
    }
}