Example usage for org.eclipse.jdt.core IJavaProject getResolvedClasspath

List of usage examples for org.eclipse.jdt.core IJavaProject getResolvedClasspath

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IJavaProject getResolvedClasspath.

Prototype

IClasspathEntry[] getResolvedClasspath(boolean ignoreUnresolvedEntry) throws JavaModelException;

Source Link

Document

This is a helper method returning the resolved classpath for the project as a list of simple (non-variable, non-container) classpath entries.

Usage

From source file:org.ebayopensource.turmeric.eclipse.buildsystem.utils.BuilderUtil.java

License:Open Source License

/**
 * Returns the required project for any given project. Scans the build bath
 * and finds all the project references and returns it back.
 *
 * @param project the project/*  w  ww. java  2s . co  m*/
 * @param natureIds the nature ids
 * @return the required projects
 */
public static IProject[] getRequiredProjects(IProject project, String... natureIds) {
    IJavaProject javaProject = JavaCore.create(project);
    if (javaProject == null)
        return new IProject[0];
    ArrayList<IProject> projects = new ArrayList<IProject>();
    try {
        for (final IClasspathEntry entry : javaProject.getResolvedClasspath(true)) {
            if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
                IProject reqProject = WorkspaceUtil.getProject(entry.getPath());
                if (reqProject != null && !projects.contains(reqProject)) {
                    if (natureIds != null) {
                        for (String natureId : natureIds) {
                            if (reqProject.hasNature(natureId)) {
                                projects.add(reqProject);
                                break;
                            }
                        }
                    } else {
                        projects.add(reqProject);
                    }
                }
            }
        }
    } catch (Exception e) {
        return new IProject[0];
    }
    IProject[] result = new IProject[projects.size()];
    projects.toArray(result);
    return result;
}

From source file:org.ebayopensource.turmeric.eclipse.utils.plugin.JDTUtil.java

License:Open Source License

private static void resolveClasspathToURLs(final IJavaProject javaProject, final Set<URL> resolvedEntries,
        final Set<String> visited) throws JavaModelException, IOException {
    if (javaProject == null || !javaProject.exists())
        return;//from   w  ww .j a v  a  2  s  .c  om
    final String projectName = javaProject.getProject().getName();
    if (visited.contains(projectName))
        return;
    visited.add(projectName);
    for (final IClasspathEntry entry : javaProject.getResolvedClasspath(true)) {
        if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
            resolveClasspathToURLs(JavaCore.create(WorkspaceUtil.getProject(entry.getPath())), resolvedEntries,
                    visited);
        } else if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
            resolvedEntries.add(WorkspaceUtil.getLocation(entry.getPath()).toFile().toURI().toURL());

        } else if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
            IPath location = entry.getOutputLocation() != null ? entry.getOutputLocation()
                    : javaProject.getOutputLocation();
            if (location.toString().startsWith(WorkspaceUtil.PATH_SEPERATOR + projectName)) {
                //it happens that the path is not absolute
                location = javaProject.getProject().getFolder(location.removeFirstSegments(1)).getLocation();
            }

            resolvedEntries.add(location.toFile().toURI().toURL());
        }
    }
}

From source file:org.ebayopensource.vjet.eclipse.core.ClassPathUtils.java

License:Open Source License

public static URL[] getProjectDependencyUrls(List<IJavaProject> javaProjectList, List<URL> currentUrlList,
        HashMap<String, String> projectMap) throws JavaModelException, MalformedURLException {

    List<URL> projectDependencyUrlList = currentUrlList;

    if (projectDependencyUrlList == null) {
        projectDependencyUrlList = new ArrayList<URL>();
    }/*from  www  .  j av  a 2  s  .com*/

    for (IJavaProject project : javaProjectList) {

        if (projectMap.containsKey(project.getElementName()) == true) {
            continue;
        } else {
            projectMap.put(project.getElementName(), project.getElementName());
        }

        // Add the dependencies to the URL list
        IClasspathEntry[] entries;
        entries = project.getResolvedClasspath(true);

        for (IClasspathEntry entry : entries) {

            IPath path = entry.getPath();
            File f = path.toFile();
            URL entryUrl;
            entryUrl = f.toURI().toURL();
            switch (entry.getEntryKind()) {

            case IClasspathEntry.CPE_LIBRARY:
                if (projectDependencyUrlList.contains(entryUrl) == false) {
                    projectDependencyUrlList.add(entryUrl);
                }
                break;

            case IClasspathEntry.CPE_PROJECT:
                List<IJavaProject> subjavaProjectList = new ArrayList<IJavaProject>();
                IResource subResource = ResourcesPlugin.getWorkspace().getRoot().findMember(entry.getPath());
                if (subResource == null) {
                    // String projectName = entry.getPath().toString();
                    // String parentProjectName = project.getElementName();
                    // throw new EclipseProjectNotFoundException(
                    // projectName,
                    // MessageFormat
                    // .format(
                    // "The dependent project {0} of project {1} is not
                    // available.\nPlease update your workspace to include
                    // this project",
                    // projectName, parentProjectName));
                }
                if (subResource != null && subResource.getType() == IResource.PROJECT) {
                    IProject subProject = (IProject) subResource;
                    IJavaProject subJavaProject = JavaCore.create(subProject);
                    if (subJavaProject != null && subJavaProject.exists()) {
                        subjavaProjectList.add(subJavaProject);

                        // Recursively call our selves to populate the
                        // project
                        // dependency's for the sub projects.
                        getProjectDependencyUrls(subjavaProjectList, projectDependencyUrlList, projectMap);
                    }

                }
                break;

            default:
                break;
            }
        }

        IPath path = project.getOutputLocation();
        IPath projectResourceLocation = project.getResource().getLocation();
        File projectFilePath = projectResourceLocation.append(path.removeFirstSegments(1)).toFile();
        URL projectOutputUrl;
        projectOutputUrl = projectFilePath.toURI().toURL();

        if (projectDependencyUrlList.contains(projectOutputUrl) == false) {
            projectDependencyUrlList.add(projectOutputUrl);
        }
    }

    URL[] arrayList = new URL[projectDependencyUrlList.size()];
    URL[] returnURLArray = projectDependencyUrlList.toArray(arrayList);

    return returnURLArray;

}

From source file:org.ebayopensource.vjet.eclipse.internal.launching.LauncherUtil.java

License:Open Source License

public static void getTransitiveClosureProjectDependnecyList(IJavaProject javaProject,
        Map<String, IJavaProject> transitiveClosureProjectList) throws JavaModelException {

    IClasspathEntry[] classPathEntries = javaProject.getResolvedClasspath(true);

    if (classPathEntries != null) {
        for (IClasspathEntry classPathEntry : classPathEntries) {
            if (classPathEntry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
                IResource classPathProject = ResourcesPlugin.getWorkspace().getRoot()
                        .findMember(classPathEntry.getPath());
                if (classPathProject != null) {
                    if (!transitiveClosureProjectList.containsKey(classPathProject.getName())) {

                        IJavaProject subJavaProject = getJavaProject(classPathProject);
                        transitiveClosureProjectList.put(classPathProject.getName(), subJavaProject);

                        getTransitiveClosureProjectDependnecyList(subJavaProject, transitiveClosureProjectList);
                    }//from www  . j a v a  2 s  .c  o m
                }
            }
        }
    }

}

From source file:org.ebayopensource.vjet.eclipse.internal.launching.VjetInterpreterRunner.java

License:Open Source License

/**
 * Get all the source search paths from java project
 * //from w w  w . ja  va 2  s. c  o  m
 * @param javaProject
 * @param workspaceRoot
 * @return
 * @throws JavaModelException
 */
private static String getSourceSearchPath(IJavaProject javaProject, IWorkspaceRoot workspaceRoot)
        throws JavaModelException {
    Map<String, IJavaProject> transitiveClosureProjectList = new LinkedHashMap<String, IJavaProject>();
    LauncherUtil.getTransitiveClosureProjectDependnecyList(javaProject, transitiveClosureProjectList);
    List<File> sourcePaths = new ArrayList<File>();
    getProjectSourcePaths(sourcePaths, workspaceRoot, javaProject.getResolvedClasspath(true));
    for (IJavaProject project : transitiveClosureProjectList.values()) {
        getProjectSourcePaths(sourcePaths, workspaceRoot, project.getResolvedClasspath(true));
    }
    StringBuilder sb = new StringBuilder();
    sb.append(javaProject.getPath().toFile().getAbsolutePath());
    for (File file : sourcePaths) {
        sb.append(PathSeparator).append(file.getAbsolutePath());
    }
    return sb.toString();
}

From source file:org.eclim.plugin.jdt.command.junit.JUnitCommand.java

License:Open Source License

private void createBatchTest(IJavaProject javaProject, JUnitTask junit, String pattern) throws Exception {
    if (!pattern.endsWith(".java")) {
        pattern += ".java";
    }//  w w w.j  a  v  a 2 s  .c o  m
    BatchTest batch = junit.createBatchTest();
    IClasspathEntry[] entries = javaProject.getResolvedClasspath(true);
    for (IClasspathEntry entry : entries) {
        if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
            String path = ProjectUtils.getFilePath(javaProject.getProject(), entry.getPath().toOSString());
            FileSet fileset = new FileSet();
            fileset.setDir(new File(path));
            fileset.setIncludes(pattern);
            batch.addFileSet(fileset);
        }
    }
}

From source file:org.eclim.plugin.jdt.command.launching.JavaCommand.java

License:Open Source License

private String findMainClass(IJavaProject javaProject) throws Exception {
    ArrayList<IJavaElement> srcs = new ArrayList<IJavaElement>();
    for (IClasspathEntry entry : javaProject.getResolvedClasspath(true)) {
        if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
            for (IPackageFragmentRoot root : javaProject.findPackageFragmentRoots(entry)) {
                srcs.add(root);//from   w w w .j  ava2 s. c  o m
            }
        }
    }

    final ArrayList<IMethod> methods = new ArrayList<IMethod>();
    int context = IJavaSearchConstants.DECLARATIONS;
    int type = IJavaSearchConstants.METHOD;
    int matchType = SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE;
    IJavaSearchScope scope = SearchEngine.createJavaSearchScope(srcs.toArray(new IJavaElement[srcs.size()]));
    SearchPattern pattern = SearchPattern.createPattern("main(String[])", type, context, matchType);
    SearchRequestor requestor = new SearchRequestor() {
        public void acceptSearchMatch(SearchMatch match) {
            if (match.getAccuracy() != SearchMatch.A_ACCURATE) {
                return;
            }

            try {
                IMethod method = (IMethod) match.getElement();
                String[] params = method.getParameterTypes();
                if (params.length != 1) {
                    return;
                }

                if (!Signature.SIG_VOID.equals(method.getReturnType())) {
                    return;
                }

                int flags = method.getFlags();
                if (!Flags.isPublic(flags) || !Flags.isStatic(flags)) {
                    return;
                }

                methods.add(method);
            } catch (JavaModelException e) {
                // ignore
            }
        }
    };

    SearchEngine engine = new SearchEngine();
    SearchParticipant[] participants = new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() };
    engine.search(pattern, participants, scope, requestor, null);

    // if we found only 1 result, we can use it.
    if (methods.size() == 1) {
        IMethod method = methods.get(0);
        ICompilationUnit cu = method.getCompilationUnit();
        IPackageDeclaration[] packages = cu.getPackageDeclarations();
        if (packages != null && packages.length > 0) {
            return packages[0].getElementName() + "." + cu.getElementName();
        }
        return cu.getElementName();
    }
    return null;
}

From source file:org.eclim.plugin.jdt.util.ClasspathUtils.java

License:Open Source License

/**
 * Gets an array of paths representing the project's source paths.
 *
 * @param project The java project instance.
 * @return Array of paths.//from  w ww.  ja  v  a2s.com
 */
public static String[] getSrcPaths(IJavaProject project) throws Exception {
    ArrayList<String> paths = new ArrayList<String>();
    IClasspathEntry[] entries = project.getResolvedClasspath(true);
    for (IClasspathEntry entry : entries) {
        if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
            paths.add(ProjectUtils.getFilePath(project.getProject(), entry.getPath().toOSString()));
        }
    }

    return paths.toArray(new String[paths.size()]);
}

From source file:org.eclim.plugin.jdt.util.ClasspathUtils.java

License:Open Source License

/**
 * Recursively collects classpath entries from the current and dependent
 * projects.//from   www .j  ava 2 s. c  o m
 */
private static void collect(IJavaProject javaProject, List<String> paths, Set<IJavaProject> visited,
        boolean isFirstProject) throws Exception {
    if (visited.contains(javaProject)) {
        return;
    }
    visited.add(javaProject);

    try {
        IPath out = javaProject.getOutputLocation();
        paths.add(ProjectUtils.getFilePath(javaProject.getProject(), out.addTrailingSeparator().toOSString()));
    } catch (JavaModelException ignore) {
        // ignore... just signals that no output dir was configured.
    }

    IProject project = javaProject.getProject();
    String name = project.getName();

    IClasspathEntry[] entries = null;
    try {
        entries = javaProject.getResolvedClasspath(true);
    } catch (JavaModelException jme) {
        // this may or may not be a problem.
        logger.warn("Unable to retrieve resolved classpath for project: " + name, jme);
        return;
    }

    final List<IJavaProject> nextProjects = new ArrayList<IJavaProject>();
    for (IClasspathEntry entry : entries) {
        switch (entry.getEntryKind()) {
        case IClasspathEntry.CPE_LIBRARY:
        case IClasspathEntry.CPE_CONTAINER:
        case IClasspathEntry.CPE_VARIABLE:
            String path = entry.getPath().toOSString().replace('\\', '/');
            if (path.startsWith("/" + name + "/")) {
                path = ProjectUtils.getFilePath(project, path);
            }
            paths.add(path);
            break;
        case IClasspathEntry.CPE_PROJECT:
            if (isFirstProject || entry.isExported()) {
                javaProject = JavaUtils.getJavaProject(entry.getPath().segment(0));
                if (javaProject != null) {
                    // breadth first, not depth first, to preserve dependency ordering
                    nextProjects.add(javaProject);
                }
            }
            break;
        case IClasspathEntry.CPE_SOURCE:
            IPath out = entry.getOutputLocation();
            if (out != null) {
                paths.add(ProjectUtils.getFilePath(javaProject.getProject(),
                        out.addTrailingSeparator().toOSString()));
            }
            break;
        }
    }
    // depth second
    for (final IJavaProject nextProject : nextProjects) {
        collect(nextProject, paths, visited, false);
    }
}

From source file:org.eclipse.acceleo.common.internal.utils.workspace.AcceleoWorkspaceUtil.java

License:Open Source License

/**
 * This will return the set of output folders name for the given (java) project.
 * <p>/*  ww w . j ava2s .com*/
 * For example, if a project has a source folder "src" with its output folder set as "bin" and a source
 * folder "src-gen" with its output folder set as "bin-gen", this will return a LinkedHashSet containing
 * both "bin" and "bin-gen".
 * </p>
 * 
 * @param project
 *            The project we seek the output folders of.
 * @return The set of output folders name for the given (java) project.
 */
private static Set<String> getOutputFolders(IProject project) {
    final Set<String> classpathEntries = new CompactLinkedHashSet<String>();
    final IJavaProject javaProject = JavaCore.create(project);
    try {
        for (IClasspathEntry entry : javaProject.getResolvedClasspath(true)) {
            if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                final IPath output = entry.getOutputLocation();
                if (output != null) {
                    classpathEntries.add(output.removeFirstSegments(1).toString());
                }
            }
        }
        /*
         * Add the default output location to the classpath anyway since source folders are not required
         * to have their own
         */
        final IPath output = javaProject.getOutputLocation();
        classpathEntries.add(output.removeFirstSegments(1).toString());
    } catch (JavaModelException e) {
        AcceleoCommonPlugin.log(e, false);
    }
    return classpathEntries;
}