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:apet.utils.ClasspathUtils.java

License:Open Source License

/**
 * Returns the Eclipse Project class loader using project build path
 * @param javaProject Eclipse Java Project
 * @return A class loader using project build path
 * @throws Exception If the project is no valid
 */// ww w . jav a2  s .  com
public static ClassLoader getProjectClassLoader(IJavaProject javaProject) throws Exception {
    IClasspathEntry[] entries = javaProject.getResolvedClasspath(true);
    String wsPath = javaProject.getProject().getLocation().toPortableString();
    String firstEntryLocation = javaProject.getPath().toPortableString();
    int idx = wsPath.indexOf(firstEntryLocation);

    URL[] urls = null;
    int i = 0;

    //System.out.println("ClassLoader " + wsPath);
    //System.out.println("ClassLoader " + firstEntryLocation);

    String output = javaProject.getOutputLocation().toPortableString();
    urls = new URL[entries.length + 1];

    if (idx != -1) {
        wsPath = wsPath.substring(0, idx);
    } else {
        output = output.substring(firstEntryLocation.length());
    }
    urls[i++] = new File(wsPath + output).toURL();

    //System.out.println("ClassLoader " + output);

    String fullPath = null;

    for (IClasspathEntry entry : entries) {
        if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
            IResource project = ResourcesPlugin.getWorkspace().getRoot().findMember(entry.getPath());
            String projectPath = JavaCore.create(project.getProject()).getOutputLocation().toPortableString();
            fullPath = wsPath + projectPath;
        } else {
            Object resource = JavaModel.getTarget(entry.getPath(), true);

            if (resource instanceof IResource) {
                IResource iFile = (IResource) resource;
                fullPath = iFile.getLocation().toPortableString();
            } else if (resource instanceof File) {
                File file = (File) resource;
                fullPath = file.getAbsolutePath();
            }
        }

        urls[i++] = new File(fullPath).toURL();
        //System.out.println(fullPath);
    }

    URLClassLoader classLoader = new URLClassLoader(urls, String.class.getClassLoader());

    /*for (int j = 0; j < urls.length; j ++) {
       System.out.println(urls[j]);
    }*/

    return classLoader;
}

From source file:apet.utils.ClasspathUtils.java

License:Open Source License

/**
 * Returns a String with all libraries defined in build path
 * @param javaProject Eclipse Java Project
 * @return a String with all libraries defined in build path
 * @throws Exception If the project is no valid
 *//*w ww .j  a v  a 2 s  .co m*/
public static String getStringClasspath(IJavaProject javaProject) throws Exception {

    IClasspathEntry[] entries = javaProject.getResolvedClasspath(true);
    String wsPath = javaProject.getProject().getLocation().toPortableString();
    String firstEntryLocation = javaProject.getPath().toPortableString();
    int idx = wsPath.indexOf(firstEntryLocation);

    String[] urls = new String[entries.length + 1];
    String fullPath = null;
    int i = 0;
    String output = javaProject.getOutputLocation().toPortableString();

    if (idx != -1) {
        wsPath = wsPath.substring(0, idx);
    } else {
        output = output.substring(firstEntryLocation.length());
    }
    urls[i++] = wsPath + output;

    for (IClasspathEntry entry : entries) {
        if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
            IResource project = ResourcesPlugin.getWorkspace().getRoot().findMember(entry.getPath());
            String projectPath = JavaCore.create(project.getProject()).getOutputLocation().toPortableString();
            fullPath = wsPath + projectPath;
        } else {
            Object resource = JavaModel.getTarget(entry.getPath(), true);

            if (resource instanceof IResource) {
                IResource iFile = (IResource) resource;
                fullPath = iFile.getLocation().toPortableString();
            } else if (resource instanceof File) {
                File file = (File) resource;
                fullPath = file.getAbsolutePath();
            }
        }

        urls[i++] = fullPath;
    }

    StringBuffer buffer = new StringBuffer();
    for (String url : urls) {
        buffer.append(url);
        buffer.append(":");
    }

    return buffer.toString().substring(0, buffer.length() - 1);

}

From source file:at.spardat.xma.guidesign.presentation.XMAPropertyDescriptor.java

License:Open Source License

private String[] getSourceFolderStrings() {
    IProject project = editor.getResourceFile().getProject();
    File workspaceLocation = project.getWorkspace().getRoot().getLocation().toFile();
    IJavaProject jp = JavaCore.create(project);
    IClasspathEntry[] javacp;/*from   w w  w.j  ava  2s .  c  om*/
    try {
        javacp = jp.getResolvedClasspath(true);
    } catch (JavaModelException e) {
        GUIDesignerPlugin.INSTANCE.log(e);
        return new String[] { project.getLocation().toString() + "/src" };
    }
    ArrayList<String> result = new ArrayList<String>();
    for (IClasspathEntry classpathEntry : javacp) {
        if (classpathEntry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
            File f = new File(workspaceLocation, classpathEntry.getPath().toString());
            String s = f.getAbsolutePath();
            result.add(s);
        }
    }
    return result.toArray(new String[result.size()]);
}

From source file:br.ufal.cideei.handlers.DoAnalysisOnClassPath.java

License:Open Source License

@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    //#ifdef CACHEPURGE
    //@      br.Main.randomLong();
    //#endif//w  w  w  . ja va 2  s.  com

    // TODO: exteriorize this number as a configuration parameter. Abstract away the looping.
    try {
        IStructuredSelection selection = (IStructuredSelection) HandlerUtil.getActiveMenuSelection(event);
        Object firstElement = selection.getFirstElement();

        if (!(firstElement instanceof IJavaProject)) {
            throw new UnsupportedOperationException("Selected resource is not a java project");
        }

        IJavaProject javaProject = (IJavaProject) firstElement;

        IClasspathEntry[] classPathEntries = null;
        try {
            classPathEntries = javaProject.getResolvedClasspath(true);
        } catch (JavaModelException e) {
            e.printStackTrace();
            throw new ExecutionException("No source classpath identified");
        }

        /*
         * To build the path string variable that will represent Soot's classpath we will first iterate
         * through all libs (.jars) files, then through all source classpaths.
         * 
         * FIXME: WARNING: A bug was found on Soot, in which the FileSourceTag would contain incorrect
         * information regarding the absolute location of the source file. In this workaround, the classpath
         * must be injected into the FeatureModelInstrumentorTransformer class (done through its
         * constructor).
         * 
         * As a consequence, we CANNOT build an string with all classpaths that contains source code for the
         * project and thus one only source code classpath can be analysed at a given time.
         * 
         * This seriously restricts the range of projects that can be analysed with this tool.
         */
        List<IClasspathEntry> sourceClasspathEntries = new ArrayList<IClasspathEntry>();
        StringBuilder libsPaths = new StringBuilder();
        for (IClasspathEntry entry : classPathEntries) {
            if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
                File file = entry.getPath().makeAbsolute().toFile();
                if (file.isAbsolute()) {
                    libsPaths.append(file.getAbsolutePath() + File.pathSeparator);
                } else {
                    libsPaths.append(ResourcesPlugin.getWorkspace().getRoot().getFile(entry.getPath())
                            .getLocation().toOSString() + File.pathSeparator);
                }
            } else if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                sourceClasspathEntries.add(entry);
            }
        }

        if (sourceClasspathEntries.size() != 1) {
            throw new UnsupportedOperationException("project must have exactly one source classpath entry");
        }

        IClasspathEntry entry = sourceClasspathEntries.get(0);

        final int times = 10;
        for (int i = 0; i < times; i++) {
            // #ifdef METRICS
            String sinkFile = System.getProperty("user.home") + File.separator
                    + javaProject.getElementName().trim().toLowerCase().replace(' ', '-') + "-fs";
            // #ifdef LAZY
            sinkFile += "-lazy";
            // #endif
            // #ifdef FEATUREMODEL
            //@                  sinkFile += "-fm";
            // #endif
            sink = new MetricsSink(new MetricsTable(new File(sinkFile + ".xls")));
            // #endif

            this.addPacks(javaProject, entry, libsPaths.toString());
            SootManager.reset();
            // #ifdef METRICS
            sink.terminate();
            // #endif
            System.out.println("=============" + (i + 1) + "/" + times + "=============");
        }
        sink.createSummaryFile();
    } catch (Throwable e) {
        e.printStackTrace();
    } finally {
        SootManager.reset();
        // #ifdef METRICS
        if (sink != null && !sink.terminated()) {
            sink.terminate();
        }
        // #endif
    }

    return null;
}

From source file:br.ufal.cideei.handlers.DoFeatureObliviousAnalysisOnClassPath.java

License:Open Source License

@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    try {/*from   w  w  w .j a  v a2  s  . com*/
        IStructuredSelection selection = (IStructuredSelection) HandlerUtil.getActiveMenuSelection(event);
        Object firstElement = selection.getFirstElement();

        if (!(firstElement instanceof IJavaProject)) {
            throw new UnsupportedOperationException("selected resource is not a java project");
        }

        IJavaProject javaProject = (IJavaProject) firstElement;

        IClasspathEntry[] classPathEntries = null;
        try {
            classPathEntries = javaProject.getResolvedClasspath(true);
        } catch (JavaModelException e) {
            e.printStackTrace();
            throw new ExecutionException("No source classpath identified");
        }

        /*
         * To build the path string variable that will represent Soot's classpath we will first iterate
         * through all libs (.jars) files, then through all source classpaths.
         * 
         * FIXME: WARNING: A bug was found on Soot, in which the FileSourceTag would contain incorrect
         * information regarding the absolute location of the source file. In this workaround, the classpath
         * must be injected into the FeatureModelInstrumentorTransformer class (done though its
         * constructor).
         * 
         * As a consequence, we CANNOT build an string with all classpaths that contains source code for the
         * project and thus only one source code classpath can be analysed at a given time.
         * 
         * This seriously restricts the range of projects that can be analysed with this tool.
         */
        List<IClasspathEntry> sourceClasspathEntries = new ArrayList<IClasspathEntry>();
        StringBuilder libsPaths = new StringBuilder();
        for (IClasspathEntry entry : classPathEntries) {
            if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
                File file = entry.getPath().makeAbsolute().toFile();
                if (file.isAbsolute()) {
                    libsPaths.append(file.getAbsolutePath() + File.pathSeparator);
                } else {
                    libsPaths.append(ResourcesPlugin.getWorkspace().getRoot().getFile(entry.getPath())
                            .getLocation().toOSString() + File.pathSeparator);
                }
            } else if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                sourceClasspathEntries.add(entry);
            }
        }

        if (sourceClasspathEntries.size() != 1) {
            throw new UnsupportedOperationException("project must have exactly one source classpath entry");
        }

        IClasspathEntry entry = sourceClasspathEntries.get(0);

        final int times = 10;
        for (int i = 0; i < times; i++) {
            // #ifdef METRICS
            String sinkFile = System.getProperty("user.home") + File.separator
                    + javaProject.getElementName().trim().toLowerCase().replace(' ', '-') + "-fo";
            // #ifdef LAZY
            sinkFile += "-lazy";
            // #endif
            // #ifdef FEATUREMODEL
            //@                  sinkFile += "-fm";
            // #endif
            sink = new MetricsSink(new MetricsTable(new File(sinkFile + ".xls")));
            // #endif

            this.addPacks(javaProject, entry, libsPaths.toString());
            SootManager.reset();
            // #ifdef METRICS
            sink.terminate();
            // #endif
            System.out.println("=============" + (i + 1) + "/" + times + "=============");
        }
        sink.createFeatureObliviousSummaryFile();
    } catch (Throwable e) {
        e.printStackTrace();
    } finally {
        SootManager.reset();
        // #ifdef METRICS
        if (sink != null && !sink.terminated()) {
            sink.terminate();
        }
        // #endif
    }

    return null;
}

From source file:br.ufal.cideei.util.MethodDeclarationSootMethodBridge.java

License:Open Source License

/**
 * Gets the correspondent classpath.//from   ww w. j a v  a 2 s  .  co m
 * 
 * @param file
 *            the file
 * @return the correspondent classpath
 * @throws ExecutionException
 *             the execution exception
 */
public static String getCorrespondentClasspath(IFile file) throws ExecutionException {
    /*
     * used to find out what the classpath entry related to the IFile of the
     * text selection. this is necessary for some algorithms that might use
     * the Soot framework
     */
    IProject project = file.getProject();
    IJavaProject javaProject = null;

    try {
        if (file.getProject().isNatureEnabled("org.eclipse.jdt.core.javanature")) {
            javaProject = JavaCore.create(project);
        }
    } catch (CoreException e) {
        e.printStackTrace();
        throw new ExecutionException("Not a Java Project");
    }

    /*
     * When using the Soot framework, we need the path to the package root
     * in which the file is located. There may be other ways to acomplish
     * this.
     */
    String pathToSourceClasspathEntry = null;

    IClasspathEntry[] classPathEntries = null;
    try {
        classPathEntries = javaProject.getResolvedClasspath(true);
    } catch (JavaModelException e) {
        e.printStackTrace();
        throw new ExecutionException("No source classpath identified");
    }
    for (IClasspathEntry entry : classPathEntries) {
        if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
            pathToSourceClasspathEntry = ResourcesPlugin.getWorkspace().getRoot().getFile(entry.getPath())
                    .getLocation().toOSString();
            break;
        }
    }

    return pathToSourceClasspathEntry;
}

From source file:ca.mcgill.sable.soot.examples.NewSootExampleWizard.java

License:Open Source License

@Override
public boolean performFinish() {
    boolean performFinish = super.performFinish();

    if (performFinish) {
        IJavaProject newProject = (IJavaProject) getCreatedElement();
        try {//from  w w  w  .j  a v a2s  . com
            IClasspathEntry[] originalCP = newProject.getRawClasspath();
            IClasspathEntry ajrtLIB = JavaCore.newVariableEntry(
                    new Path(SootClasspathVariableInitializer.VARIABLE_NAME_CLASSES),
                    new Path(SootClasspathVariableInitializer.VARIABLE_NAME_SOURCE), null);
            // Update the raw classpath with the new entry
            int originalCPLength = originalCP.length;
            IClasspathEntry[] newCP = new IClasspathEntry[originalCPLength + 1];
            System.arraycopy(originalCP, 0, newCP, 0, originalCPLength);
            newCP[originalCPLength] = ajrtLIB;
            newProject.setRawClasspath(newCP, new NullProgressMonitor());
        } catch (JavaModelException e) {
        }

        String templateFilePath = fromFile;
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            is = SootPlugin.getDefault().getBundle().getResource(templateFilePath).openStream();
            if (is == null) {
                new RuntimeException("Resource " + templateFilePath + " not found!").printStackTrace();
            } else {

                IClasspathEntry[] resolvedClasspath = newProject.getResolvedClasspath(true);
                IClasspathEntry firstSourceEntry = null;
                for (IClasspathEntry classpathEntry : resolvedClasspath) {
                    if (classpathEntry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                        firstSourceEntry = classpathEntry;
                        break;
                    }
                }
                if (firstSourceEntry != null) {
                    IPath path = SootPlugin.getWorkspace().getRoot().getFile(firstSourceEntry.getPath())
                            .getLocation();
                    String srcPath = path.toString();
                    String newfileName = toFile;
                    final IPath newFilePath = firstSourceEntry.getPath().append(newfileName);
                    fos = new FileOutputStream(srcPath + File.separator + newfileName);
                    int temp = is.read();
                    while (temp > -1) {
                        fos.write(temp);
                        temp = is.read();
                    }
                    fos.close();
                    //refresh project
                    newProject.getProject().refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());

                    final IWorkbenchPage activePage = JavaPlugin.getActivePage();
                    if (activePage != null) {
                        final Display display = getShell().getDisplay();
                        if (display != null) {
                            display.asyncExec(new Runnable() {
                                public void run() {
                                    try {
                                        IResource newResource = SootPlugin.getWorkspace().getRoot()
                                                .findMember(newFilePath);
                                        IDE.openEditor(activePage, (IFile) newResource, true);
                                    } catch (PartInitException e) {
                                        JavaPlugin.log(e);
                                    }
                                }
                            });
                        }
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null)
                    is.close();
                if (fos != null)
                    fos.close();
            } catch (IOException e) {
            }
        }
    }

    return performFinish;
}

From source file:ca.mcgill.sable.soot.launching.SootClasspath.java

License:Open Source License

public static URL[] projectClassPath(IJavaProject javaProject) {
    IWorkspace workspace = SootPlugin.getWorkspace();
    IClasspathEntry[] cp;//from  ww  w . j  a v  a  2 s.co  m
    try {
        cp = javaProject.getResolvedClasspath(true);
        List<URL> urls = new ArrayList<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();
            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:ccw.builder.ClojureBuilder.java

License:Open Source License

private static Map<IFolder, IFolder> getSrcFolders(IProject project) throws CoreException {
    Map<IFolder, IFolder> srcFolders = new HashMap<IFolder, IFolder>();

    IJavaProject jProject = JavaCore.create(project);
    IClasspathEntry[] entries = jProject.getResolvedClasspath(true);
    IPath defaultOutputFolder = jProject.getOutputLocation();
    for (IClasspathEntry entry : entries) {
        switch (entry.getEntryKind()) {
        case IClasspathEntry.CPE_SOURCE:
            IFolder folder = project.getWorkspace().getRoot().getFolder(entry.getPath());
            IFolder outputFolder = project.getWorkspace().getRoot().getFolder(
                    (entry.getOutputLocation() == null) ? defaultOutputFolder : entry.getOutputLocation());
            if (folder.exists())
                srcFolders.put(folder, outputFolder);
            break;
        case IClasspathEntry.CPE_LIBRARY:
            break;
        case IClasspathEntry.CPE_PROJECT:
            // TODO should compile here ?
            break;
        case IClasspathEntry.CPE_CONTAINER:
        case IClasspathEntry.CPE_VARIABLE:
            // Impossible cases, since entries are resolved
        default://ww w . ja v a  2  s.c  om
            break;
        }
    }
    return srcFolders;
}

From source file:cfgrecognition.loader.SootClasspath.java

License:Open Source License

public static URL[] projectClassPath(IJavaProject javaProject) {
    IWorkspace workspace = Activator.getWorkspaceRoot().getWorkspace();
    IClasspathEntry[] cp;/*from   w  w  w.j av a2 s .  co m*/
    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();
            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];
    }
}