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:edu.clarkson.serl.critic.loader.SootClasspath.java

License:Open Source License

/**
 * This is an addition to the original SootClasspath class where
 * bug due to '\\' in the path string has been resolved.
 * (Added By: Ryan Edgar)//from  w  w w.  j  a  va2 s  . co m
 *  
 * @param javaProject The JavaProject to be analyzed.
 * @return An array of {@link URL}s corresponding to the classpath of the supplied project.
 */
public static URL[] projectClassPath2(IJavaProject javaProject) {
    IWorkspace workspace = CriticPlugin.getWorkspaceRoot().getWorkspace();
    IClasspathEntry[] cp;
    try {
        cp = javaProject.getResolvedClasspath(true);
        Set<URL> urls = new HashSet<URL>();
        String uriString = workspace.getRoot().getFile(javaProject.getOutputLocation()).getLocationURI()
                .toString() + "/";
        urls.add(new URI(uriString).toURL());
        for (IClasspathEntry entry : cp) {
            File file = entry.getPath().toFile();
            if (file.getPath().startsWith("\\")) {
                file = workspace.getRoot().getLocation().append(file.getPath()).toFile();
            }
            URL url = file.toURI().toURL();
            urls.add(url);
        }
        URL[] array = new URL[urls.size()];
        urls.toArray(array);
        return array;
    } catch (JavaModelException e) {
        e.printStackTrace();

        return new URL[0];
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return new URL[0];
    } catch (URISyntaxException e) {
        e.printStackTrace();
        return new URL[0];
    }
}

From source file:edu.rice.cs.drjava.plugins.eclipse.repl.EclipseInteractionsModel.java

License:BSD License

private void _addProjectToClasspath(IJavaProject jProj, IJavaModel jModel, IWorkspaceRoot root)
        throws CoreException {
    // Get the project's location on disk
    IProject proj = jProj.getProject();/* ww  w . java2  s.  c  o  m*/
    URI projRoot = proj.getDescription().getLocationURI();
    // Note: getLocation returns null if the default location is used
    //  (brilliant...)

    // Get the resolved classpath entries - this should filter out
    //   all CPE_VARIABLE and CPE_CONTAINER entries.
    IClasspathEntry entries[] = jProj.getResolvedClasspath(true);

    // For each of the classpath entries...
    for (int j = 0; j < entries.length; j++) {
        IClasspathEntry entry = entries[j];

        // Check what kind of entry it is...
        int kind = entry.getEntryKind();

        // And get the appropriate path.
        IPath path;
        switch (kind) {
        case IClasspathEntry.CPE_LIBRARY:
            // The raw location of a JAR.
            path = entry.getPath();
            //System.out.println("Adding library: " + path.toOSString());
            addToClassPath(path.toOSString());
            break;
        case IClasspathEntry.CPE_SOURCE:
            // The output location of source.
            // Need to append it to the user's workspace directory.
            path = entry.getOutputLocation();
            if (path == null) {
                path = jProj.getOutputLocation();
                //System.out.println(" output location from proj: " + path);
            }

            // At this point, the output location contains the project
            //  name followed by the actual output folder name

            if (projRoot != null && (!projRoot.isAbsolute() || projRoot.getScheme().equals("file"))) {
                // We have a custom project location, so the project name
                //  is not part of the *actual* output directory.  We need
                //  to remove the project name (first segment) and then
                //  append the rest of the output location to projRoot.
                path = path.removeFirstSegments(1);
                path = new Path(projRoot.getPath()).append(path);
            } else {
                // A null projRoot means use the default location, which
                //  *does* include the project name in the output directory.
                path = root.getLocation().append(path);
            }

            //System.out.println("Adding source: " + path.toOSString());
            //addToClassPath(path.toOSString());
            addBuildDirectoryClassPath(path.toOSString());
            break;
        case IClasspathEntry.CPE_PROJECT:
            // In this case, just the project name is given.
            // We don't actually need to add anything to the classpath,
            //  since the project is open and we will get its classpath
            //  on another pass.
            break;
        default:
            // This should never happen.
            throw new RuntimeException("Unsupported classpath entry type.");
        }
    }
}

From source file:es.bsc.servicess.ide.PackagingUtils.java

License:Apache License

/** Get the classpath of the project
 * @param project/*from   w ww.jav a  2s .  co  m*/
 * @return
 * @throws JavaModelException
 */
public static String getClasspath(IJavaProject project) throws JavaModelException {
    String classpath = new String();
    IPath path = project.getProject().getWorkspace().getRoot().getLocation();
    boolean first = true;
    for (IClasspathEntry e : project.getResolvedClasspath(true)) {
        if (!first) {
            classpath = classpath.concat(":");

        } else {
            first = false;
        }
        if (e.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
            IPath entryPath = e.getPath();
            path.isPrefixOf(entryPath);
            classpath = classpath.concat(path.append(entryPath.makeRelative()).toOSString());
        } else {
            classpath = classpath.concat(e.getPath().toOSString());
        }
    }
    return classpath;
}

From source file:fede.workspace.eclipse.composition.java.JavaProjectExporter.java

License:Apache License

/**
 * Updates an existing packaged binary version of the content of the item in
 * this project./*  w ww .  ja v  a 2s  .co m*/
 * 
 * Scans all output directories of the java project and updates all modified
 * classes in the packaged item version.
 * 
 * If no resource delta is specified all the binary contents are copied to
 * the packaged version.
 * 
 * @param monitor
 *            the monitor
 * @param eclipseExportedContent
 *            the eclipse exported content
 * @param projectDelta
 *            the project delta
 * @param exporterType
 *            the exporter type
 * 
 * @throws CoreException
 *             the core exception
 */
@Override
protected void exportItem(EclipseExportedContent eclipseExportedContent, IResourceDelta projectDelta,
        IProgressMonitor monitor, String exporterType) throws CoreException {

    /*
     * skip empty notifications
     */
    if ((projectDelta != null) && (projectDelta.getKind() == IResourceDelta.NO_CHANGE)) {
        return;
    }

    /*
     * Verify this item is actually hosted in a Java Project
     */
    if (!JavaProjectManager.isJavaProject(MelusineProjectManager.getProject(getItem()))) {
        return;
    }

    IJavaProject javaProject = JavaProjectManager.getJavaProject(getItem());

    /*
     * TODO We scan all output directories, we should only scan the output
     * directory associated with the item.
     * 
     * We need to handle mapping variants in which there are many composites
     * in a single java project, this is the case for example when a
     * composite has parts that are themselves java composites.
     */
    Set<IPath> outputLocations = new HashSet<IPath>();
    for (IClasspathEntry entry : javaProject.getResolvedClasspath(true)) {
        if (entry.getEntryKind() != IClasspathEntry.CPE_SOURCE) {
            continue;
        }

        IPath outputPath = entry.getOutputLocation();
        if (outputPath == null) {
            outputPath = javaProject.getOutputLocation();
        }

        outputLocations.add(getRelativePath(outputPath));
    }

    Scanner scanner = new Scanner(eclipseExportedContent);
    for (IPath outputPath : outputLocations) {
        IFolder outputRoot = getFolder(outputPath);
        IResourceDelta outputDelta = (projectDelta != null)
                ? projectDelta.findMember(outputRoot.getProjectRelativePath())
                : null;

        // If no modification of the output location just skip it
        if ((projectDelta != null) && (outputDelta == null)) {
            return;
        }

        scanner.scan(outputRoot, outputDelta, monitor);
    }
}

From source file:fr.obeo.acceleo.tools.classloaders.AcceleoGenClassLoader.java

License:Open Source License

private static void computeURLs(IProject project, List URLs) {
    IFolder binFolder = Resources.getOutputFolder(project);
    if (binFolder != null) {
        String location = binFolder.getLocation().toString();
        if (location.startsWith("/")) { //$NON-NLS-1$
            location = '/' + location;
        }//from   w  w  w . j a v a2 s  . c  o  m
        try {
            URLs.add(new URL("file:/" + location + '/')); //$NON-NLS-1$
        } catch (MalformedURLException e) {
            // continue
        }
    }
    IJavaProject javaProject = JavaCore.create(project);
    IClasspathEntry[] entries;
    try {
        entries = javaProject.getResolvedClasspath(true);
    } catch (JavaModelException e1) {
        entries = new IClasspathEntry[] {};
    }
    for (IClasspathEntry entry : entries) {
        if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
            IProject reference = ResourcesPlugin.getWorkspace().getRoot()
                    .getProject(entry.getPath().toString());
            if (reference.exists()) {
                AcceleoGenClassLoader.computeURLs(reference, URLs);
            }
        } else if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
            try {
                IFile reference = ResourcesPlugin.getWorkspace().getRoot().getFile(entry.getPath());
                if (reference.exists()) {
                    URL url = (URL) AcceleoGenClassLoader.cacheURL.get(reference.getLocation().toFile());
                    if (url == null) {
                        url = reference.getLocation().toFile().toURL();
                        AcceleoGenClassLoader.cacheURL.put(reference.getLocation().toFile(), url);
                    }
                    URLs.add(url);
                } else {
                    URL url = (URL) AcceleoGenClassLoader.cacheURL.get(entry.getPath().toFile());
                    if (url == null) {
                        url = entry.getPath().toFile().toURL();
                        AcceleoGenClassLoader.cacheURL.put(entry.getPath().toFile(), url);
                    }
                    URLs.add(url);
                }
            } catch (MalformedURLException e) {
                // continue
            }
        } else {
            try {
                URL url = (URL) AcceleoGenClassLoader.cacheURL.get(entry.getPath().toFile());
                if (url == null) {
                    url = entry.getPath().toFile().toURL();
                    AcceleoGenClassLoader.cacheURL.put(entry.getPath().toFile(), url);
                }
                URLs.add(url);
            } catch (MalformedURLException e) {
                // continue
            }
        }
    }
}

From source file:io.sarl.m2e.MavenProjectSREProviderFactory.java

License:Apache License

@Override
public ProjectSREProvider getProjectSREProvider(IProject project) {
    try {/*from   www  .  j av a2 s  . c  om*/
        if (project.hasNature(IMavenConstants.NATURE_ID) && project.hasNature(JavaCore.NATURE_ID)
                && project.hasNature(SARLEclipseConfig.NATURE_ID)) {
            final IMavenProjectFacade facade = MavenPluginActivator.getDefault().getMavenProjectManager()
                    .getProject(project);
            if (facade == null) {
                return null;
            }
            final IJavaProject javaProject = JavaCore.create(project);
            final IClasspathEntry[] classpath = javaProject.getResolvedClasspath(true);
            if (classpath == null) {
                return null;
            }
            for (final IClasspathEntry dep : classpath) {
                final IPath depPath = dep.getPath();
                if (SARLRuntime.isPackedSRE(depPath)) {
                    return new MavenProjectSREProvider(
                            facade.getArtifactKey().toString() + ":" + depPath.lastSegment(), //$NON-NLS-1$
                            depPath);
                }
            }
        }
    } catch (CoreException e) {
        SARLMavenEclipsePlugin.getDefault().log(e);
    }
    return null;
}

From source file:jasima_gui.EclipseProjectClassLoader.java

License:Open Source License

protected Resource findResource(final String name, IJavaProject proj, boolean onlyExported)
        throws CoreException {
    IClasspathEntry[] classpath = proj.getResolvedClasspath(true);

    byte[] content;

    content = readResource(proj.getOutputLocation().makeRelative(), name);
    if (content != null) {
        return new Resource(proj.getOutputLocation().makeRelative(), content);
    }//from  w w w  . jav a 2s  .co m

    for (IClasspathEntry entry : classpath) {
        if (onlyExported && !entry.isExported())
            continue;

        if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
            content = readResource(entry.getPath(), name);
            if (content != null) {
                return new Resource(entry.getPath(), content);
            }
        } else if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
            IProject projEntry = (IProject) ResourcesPlugin.getWorkspace().getRoot()
                    .findMember(entry.getPath());
            Resource result = findResource(name, JavaCore.create(projEntry), true);
            if (result != null) {
                return result;
            }
        }
    }
    return null;
}

From source file:mt.com.southedge.jclockwork.plugin.classloader.JClockWorkClassLoader.java

License:Open Source License

/**
 * Creates a class loader including the classes found in the java project. Also adds the binary location to the
 * created class loader.//  w  ww  . j  av a2s  .  co  m
 * 
 * @param jp the java project
 * @return a class loader.
 * @throws CoreException core exception.
 */
public ClassLoader createClassLoader(IJavaProject jp) throws CoreException {

    IClasspathEntry[] javacp = jp.getResolvedClasspath(false);
    URL[] url = new URL[javacp.length + 1]; // Need also to add binary location

    for (int i = 0; i < javacp.length; i++) {
        try {
            IPath path = javacp[i].getPath();
            IResource resource = ResourcesPlugin.getWorkspace().getRoot().findMember(path);

            if (resource != null) {
                path = resource.getLocation();
            }

            url[i] = path.toFile().getAbsoluteFile().toURL();
        } catch (MalformedURLException e) {
            continue;
        }
    }

    IPath binPath = jp.getOutputLocation();
    binPath = ResourcesPlugin.getWorkspace().getRoot().findMember(binPath).getLocation();

    try {
        url[url.length - 1] = binPath.toFile().toURL();
    } catch (MalformedURLException e) {
        // Should not happen.
        e.printStackTrace();
    }
    return new URLClassLoader(url);
}

From source file:net.officefloor.eclipse.classpath.ClasspathUtil.java

License:Open Source License

/**
 * Obtains the children of the {@link IJavaElement}.
 * //from   ww  w  .j a va  2  s . c  o  m
 * @param javaElement
 *            {@link IJavaElement}.
 * @return Children.
 */
public static Object[] getChildren(IJavaElement javaElement) {
    try {
        // Children to return
        List<Object> children = new LinkedList<Object>();

        // Handle based on type of java element
        if (javaElement instanceof IJavaProject) {
            IJavaProject javaProject = (IJavaProject) javaElement;

            // Add the package fragment roots on the class path
            IClasspathEntry[] classPath = javaProject.getResolvedClasspath(true);
            for (IClasspathEntry entry : classPath) {
                // Obtain the Package Fragment Root of the class path entry
                IPath entryPath = entry.getPath();
                IPackageFragmentRoot fragmentRoot = javaProject.findPackageFragmentRoot(entryPath);

                // Add the package fragment root
                children.add(fragmentRoot);
            }

        } else if (javaElement instanceof IPackageFragmentRoot) {
            IPackageFragmentRoot fragmentRoot = (IPackageFragmentRoot) javaElement;

            // Add the package fragment root children
            children.addAll(Arrays.asList(fragmentRoot.getChildren()));
            children.addAll(Arrays.asList(fragmentRoot.getNonJavaResources()));

        } else if (javaElement instanceof IPackageFragment) {
            IPackageFragment fragment = (IPackageFragment) javaElement;

            // Add the fragment children
            children.addAll(Arrays.asList(fragment.getClassFiles()));
            children.addAll(Arrays.asList(fragment.getCompilationUnits()));
            children.addAll(Arrays.asList(fragment.getNonJavaResources()));

        } else if (javaElement instanceof ITypeRoot) {

            // No children of class file

        } else {
            // Unhandled java type
            MessageDialog.openWarning(null, "Unhandled java element type",
                    "Unhandled java element type " + javaElement.getClass().getName());
        }

        // Return the children
        return children.toArray();

    } catch (CoreException ex) {
        MessageDialog.openError(null, "Error", ex.getMessage());
        return new Object[0];
    }
}

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 v a  2  s.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;
    }
}