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

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

Introduction

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

Prototype

IPath getPath();

Source Link

Document

Returns the path of this classpath entry.

Usage

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

License:Open Source License

/**
 * Gets the correspondent classpath.//from w  ww .j a va  2s  . c o 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:byke.tests.workspaceutils.JavaProject.java

License:Open Source License

private boolean containsClasspathEntry(String absolutePath) throws JavaModelException {
    for (IClasspathEntry entry : _javaProject.getRawClasspath()) {
        if (IClasspathEntry.CPE_LIBRARY != entry.getEntryKind())
            continue;
        if (entry.getPath().toFile().getAbsolutePath().equals(absolutePath))
            return true;
    }//from   www  .j  a  v a  2s .  c  om
    return false;
}

From source file:bz.davide.dmeclipsesavehookplugin.builder.DMEclipseSaveHookPluginBuilder.java

License:Open Source License

static void findTransitiveDepProjects(IJavaProject current, ArrayList<IProject> projects,
        ArrayList<String> fullClasspath) throws CoreException {
    if (!projects.contains(current.getProject())) {
        projects.add(current.getProject());
    }/*  ww w . j a  va 2 s  .  c o m*/

    fullClasspath.add(ResourcesPlugin.getWorkspace().getRoot().findMember(current.getOutputLocation())
            .getLocation().toOSString() + "/");
    ArrayList<IClasspathEntry> classPaths = new ArrayList<IClasspathEntry>();
    classPaths.addAll(Arrays.asList(current.getRawClasspath()));

    for (int x = 0; x < classPaths.size(); x++) {
        IClasspathEntry cp = classPaths.get(x);
        if (cp.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
            String prjName = cp.getPath().lastSegment();
            IProject prj = ResourcesPlugin.getWorkspace().getRoot().getProject(prjName);
            if (prj.hasNature(JavaCore.NATURE_ID)) {
                IJavaProject javaProject = JavaCore.create(prj);
                findTransitiveDepProjects(javaProject, projects, fullClasspath);
            }
            continue;
        }
        if (cp.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
            String fullContainerName = cp.getPath().toString();
            if (!fullContainerName.startsWith("org.eclipse.jdt.launching.JRE_CONTAINER/")) {
                System.out.println("CP C: " + fullContainerName);
                IClasspathContainer container = JavaCore.getClasspathContainer(cp.getPath(), current);
                classPaths.addAll(Arrays.asList(container.getClasspathEntries()));

            }
        }
        if (cp.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
            IPath path = cp.getPath();
            // Check first if this path is relative to workspace
            IResource workspaceMember = ResourcesPlugin.getWorkspace().getRoot().findMember(path);
            if (workspaceMember != null) {
                String fullPath = workspaceMember.getLocation().toOSString();
                fullClasspath.add(fullPath);
            } else {
                fullClasspath.add(path.toOSString());
            }
        }
    }
}

From source file:ca.ecliptical.pde.ds.search.DescriptorQueryParticipant.java

License:Open Source License

public void search(ISearchRequestor requestor, QuerySpecification query, IProgressMonitor monitor)
        throws CoreException {
    if (debug.isDebugging())
        debug.trace(String.format("Query: %s", query)); //$NON-NLS-1$

    // we only look for straight references
    switch (query.getLimitTo()) {
    case IJavaSearchConstants.REFERENCES:
    case IJavaSearchConstants.ALL_OCCURRENCES:
        break;//  w  w w.j a  va 2 s .  co  m
    default:
        return;
    }

    // we only look for types and methods
    if (query instanceof ElementQuerySpecification) {
        searchElement = ((ElementQuerySpecification) query).getElement();
        switch (searchElement.getElementType()) {
        case IJavaElement.TYPE:
        case IJavaElement.METHOD:
            break;
        default:
            return;
        }
    } else {
        String pattern = ((PatternQuerySpecification) query).getPattern();
        boolean ignoreMethodParams = false;
        searchFor = ((PatternQuerySpecification) query).getSearchFor();
        switch (searchFor) {
        case IJavaSearchConstants.UNKNOWN:
        case IJavaSearchConstants.METHOD:
            int leftParen = pattern.lastIndexOf('(');
            int rightParen = pattern.indexOf(')');
            ignoreMethodParams = leftParen == -1 || rightParen == -1 || leftParen >= rightParen;
            // no break
        case IJavaSearchConstants.TYPE:
        case IJavaSearchConstants.CLASS:
        case IJavaSearchConstants.CLASS_AND_INTERFACE:
        case IJavaSearchConstants.CLASS_AND_ENUM:
        case IJavaSearchConstants.INTERFACE:
        case IJavaSearchConstants.INTERFACE_AND_ANNOTATION:
            break;
        default:
            return;
        }

        // searchPattern = PatternConstructor.createPattern(pattern, ((PatternQuerySpecification) query).isCaseSensitive());
        int matchMode = getMatchMode(pattern) | SearchPattern.R_ERASURE_MATCH;
        if (((PatternQuerySpecification) query).isCaseSensitive())
            matchMode |= SearchPattern.R_CASE_SENSITIVE;

        searchPattern = new SearchPatternDescriptor(pattern, matchMode, ignoreMethodParams);
    }

    HashSet<IPath> scope = new HashSet<IPath>();
    for (IPath path : query.getScope().enclosingProjectsAndJars()) {
        scope.add(path);
    }

    if (scope.isEmpty())
        return;

    this.requestor = requestor;

    // look through all active bundles
    IPluginModelBase[] wsModels = PluginRegistry.getWorkspaceModels();
    IPluginModelBase[] exModels = PluginRegistry.getExternalModels();
    monitor.beginTask(Messages.DescriptorQueryParticipant_taskName, wsModels.length + exModels.length);
    try {
        // workspace models
        for (IPluginModelBase model : wsModels) {
            if (monitor.isCanceled())
                throw new OperationCanceledException();

            if (!model.isEnabled() || !(model instanceof IBundlePluginModelBase)) {
                monitor.worked(1);
                if (debug.isDebugging())
                    debug.trace(String.format("Non-bundle model: %s", model)); //$NON-NLS-1$

                continue;
            }

            IProject project = model.getUnderlyingResource().getProject();
            if (!scope.contains(project.getFullPath())) {
                monitor.worked(1);
                if (debug.isDebugging())
                    debug.trace(String.format("Project out of scope: %s", project.getName())); //$NON-NLS-1$

                continue;
            }

            // we can only search in Java bundle projects (for now)
            if (!project.hasNature(JavaCore.NATURE_ID)) {
                monitor.worked(1);
                if (debug.isDebugging())
                    debug.trace(String.format("Non-Java project: %s", project.getName())); //$NON-NLS-1$

                continue;
            }

            PDEModelUtility.modifyModel(new ModelModification(project) {
                @Override
                protected void modifyModel(IBaseModel model, IProgressMonitor monitor) throws CoreException {
                    if (model instanceof IBundlePluginModelBase)
                        searchBundle((IBundlePluginModelBase) model, monitor);
                }
            }, new SubProgressMonitor(monitor, 1));
        }

        // external models
        SearchablePluginsManager spm = PDECore.getDefault().getSearchablePluginsManager();
        IJavaProject javaProject = spm.getProxyProject();
        if (javaProject == null || !javaProject.exists() || !javaProject.isOpen()) {
            monitor.worked(exModels.length);
            if (debug.isDebugging())
                debug.trace("External Plug-in Search project inaccessible!"); //$NON-NLS-1$

            return;
        }

        for (IPluginModelBase model : exModels) {
            if (monitor.isCanceled())
                throw new OperationCanceledException();

            BundleDescription bd;
            if (!model.isEnabled() || (bd = model.getBundleDescription()) == null) {
                monitor.worked(1);
                if (debug.isDebugging())
                    debug.trace(String.format("Non-bundle model: %s", model)); //$NON-NLS-1$

                continue;
            }

            // check scope
            ArrayList<IClasspathEntry> cpEntries = new ArrayList<IClasspathEntry>();
            ClasspathUtilCore.addLibraries(model, cpEntries);
            ArrayList<IPath> cpEntryPaths = new ArrayList<IPath>(cpEntries.size());
            for (IClasspathEntry cpEntry : cpEntries) {
                cpEntryPaths.add(cpEntry.getPath());
            }

            cpEntryPaths.retainAll(scope);
            if (cpEntryPaths.isEmpty()) {
                monitor.worked(1);
                if (debug.isDebugging())
                    debug.trace(String.format("External bundle out of scope: %s", model.getInstallLocation())); //$NON-NLS-1$

                continue;
            }

            if (!spm.isInJavaSearch(bd.getSymbolicName())) {
                monitor.worked(1);
                if (debug.isDebugging())
                    debug.trace(String.format("Non-searchable external model: %s", bd.getSymbolicName())); //$NON-NLS-1$

                continue;
            }

            searchBundle(model, javaProject, new SubProgressMonitor(monitor, 1));
        }
    } finally {
        monitor.done();
    }
}

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 va2 s. co  m
            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;/*ww w  .  ja  v a2 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.java  2 s .  c o  m*/
            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   ww  w  . ja  va  2 s  .c om
    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];
    }
}

From source file:cfgrecognition.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.
 *  //from w w  w .j a va 2s  .c o 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 = Activator.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:ch.mlutz.plugins.t4e.handlers.ClasspathContainerHandler.java

License:Open Source License

private Object onRemoveClasspathContainer(ExecutionEvent event) throws ExecutionException {
    // get workbench window
    IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
    // set selection service
    ISelectionService service = window.getSelectionService();
    // set structured selection
    IStructuredSelection structured = (IStructuredSelection) service.getSelection();

    //check if it is an IFile
    Object el = structured.getFirstElement();

    if (el instanceof IJavaProject) {

        IJavaProject javaProject = (IJavaProject) el;

        try {/*from  w ww.jav a  2  s. c  o  m*/
            // Set Classpath of Java Project
            List<IClasspathEntry> projectClassPath = new ArrayList<IClasspathEntry>(
                    Arrays.asList(javaProject.getRawClasspath()));

            IClasspathEntry entry;
            for (int i = projectClassPath.size() - 1; i >= 0; --i) {
                entry = projectClassPath.get(i);
                if (entry.getPath().equals(CONTAINER_PATH)) {
                    projectClassPath.remove(i);
                }
            }

            javaProject.setRawClasspath(projectClassPath.toArray(new IClasspathEntry[projectClassPath.size()]),
                    null);
        } catch (CoreException e) {
            log.error("Could not remove Classpath container: ", e);
        }
    }
    return null;
}