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

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

Introduction

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

Prototype

boolean isOnClasspath(IResource resource);

Source Link

Document

Returns whether the given resource is on the classpath of this project, that is, referenced from a classpath entry and not explicitly excluded using an exclusion pattern.

Usage

From source file:org.jactr.eclipse.core.parser.ProjectSensitiveParserImportDelegate.java

License:Open Source License

@Override
public URL resolveURL(String url, URL baseURL) {
    try {/*from  w w  w . j a  va2 s  .  c o m*/
        IJavaProject javaProject = JavaCore.create(_project);
        IClasspathEntry[] entries = javaProject.getResolvedClasspath(false);

        for (IClasspathEntry entry : entries)
            if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT
                    && entry.getContentKind() == IPackageFragmentRoot.K_SOURCE) {
                IPath path = entry.getPath();
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug("checking " + entry + " at " + path);

                IProject tmpProject = ResourcesPlugin.getWorkspace().getRoot().getProject(path.lastSegment());
                IFolder modelsFolder = tmpProject.getFolder("models");
                if (modelsFolder == null || !modelsFolder.exists())
                    continue;

                IFile modelFile = modelsFolder.getFile(url);
                if (modelFile == null || !modelFile.exists())
                    continue;

                // CorePlugin.debug("Found a matching file at "
                // + modelFile.getFullPath());

                if (javaProject.isOnClasspath(modelFile)) {
                    if (LOGGER.isDebugEnabled())
                        LOGGER.debug("Is on classpath, returning url");

                    URL rtn = modelFile.getLocation().toFile().toURI().toURL();

                    // CorePlugin.debug(String.format("On path at %s",
                    // rtn.toExternalForm()));

                    return rtn;
                } else if (LOGGER.isDebugEnabled())
                    LOGGER.debug("is not on classpath");
            }
    } catch (Exception e) {
        CorePlugin.error("Failed to extract location info for " + url, e);
    }
    return super.resolveURL(url, baseURL);
}

From source file:org.objectstyle.wolips.locate.result.LocalizedComponentsLocateResult.java

License:Open Source License

public void add(IResource resource) throws LocateException {
    super.add(resource);
    if (resource.getType() == IResource.FOLDER) {
        components.add((IFolder) resource);
    } else if (resource.getType() == IResource.FILE) {
        IFile file = (IFile) resource;//from   ww  w.  j  av  a 2s . c  o  m
        String extension = resource.getFileExtension();
        if (extension.equals("java")) {
            if (dotJava != null) {
                IJavaElement javaElement = JavaCore.create(file);
                try {
                    IJavaProject javaProject = javaElement.getJavaProject();
                    if (javaProject != null && javaProject.isOnClasspath(javaElement)) {
                        if (!isValidSubclass(javaElement)) {
                            file = null;
                        }
                    } else {
                        file = null;
                    }
                } catch (JavaModelException e) {
                    file = null;
                    LocatePlugin.getDefault().log(e);
                }
            }
            if (file != null && dotJava != null) {
                IJavaElement javaElement = JavaCore.create(dotJava);
                try {
                    IJavaProject javaProject = javaElement.getJavaProject();
                    if (javaProject != null && javaProject.isOnClasspath(javaElement)) {
                        if (!isValidSubclass(javaElement)) {
                            dotJava = null;
                        }
                    } else {
                        dotJava = null;
                    }
                } catch (JavaModelException e) {
                    dotJava = null;
                    LocatePlugin.getDefault().log(e);
                }
            }
            if (file != null && dotJava != null) {
                String message = "Duplicate located: " + dotJava + " " + file;
                alert(message);
                throw new LocateException(message);
            }
            if (file != null) {
                dotJava = file;
            }
        } else if (extension.equals("groovy")) {
            if (dotGroovy != null) {
                String message = "Duplicate located: " + dotGroovy + " " + file;
                alert(message);
                throw new LocateException(message);
            }
            dotGroovy = file;
        } else if (extension.equals("api")) {
            if (dotApi != null) {
                String message = "Duplicate located: " + dotApi + " " + file;
                alert(message);
                //throw new LocateException(message);
            } else {
                dotApi = file;
            }
        } else {
            String message = "unknown extension on " + file;
            alert(message);
            throw new LocateException(message);
        }

    } else {
        String message = "unsupported type " + resource;
        alert(message);
        throw new LocateException(message);
    }
}

From source file:org.sonarlint.eclipse.jdt.internal.JdtUtils.java

License:Open Source License

/**
 * SLE-34 Remove Java files that are not compiled.This should automatically exclude files that are excluded / unparseable. 
 *//*from www  .ja  va  2s  .  com*/
public static boolean isValidJavaFile(IFile file) {
    boolean hasJavaNature = hasJavaNature(file.getProject());
    IJavaProject javaProject = JavaCore.create(file.getProject());
    IJavaElement javaElt = JavaCore.create(file);
    return javaElt == null
            || (hasJavaNature && isStructureKnown(javaElt) && javaProject.isOnClasspath(javaElt));
}

From source file:org.sonatype.m2e.plexus.annotations.internal.PlexusBuildParticipant.java

License:Open Source License

@Override
public Set<IProject> build(int kind, final IProgressMonitor monitor) throws CoreException {
    final IProject project = getMavenProjectFacade().getProject();
    final IJavaProject javaProject = JavaCore.create(project);

    if (!javaProject.exists()) {
        return null;
    }//from  www  .  ja  v a2 s.  c  om

    boolean changed = false;

    final PlexusMetadata metadata = getPlexusMetadata();

    final Set<IResource> processed = new HashSet<IResource>();

    for (IClasspathEntry cpe : javaProject.getRawClasspath()) {
        if (cpe.getEntryKind() == IClasspathEntry.CPE_SOURCE && isTestEntry(cpe) == testMetadata) {
            changed = true; // XXX not specific enough!

            IPath path = cpe.getPath().removeFirstSegments(1);
            if (IncrementalProjectBuilder.FULL_BUILD == kind || metadata.isFullBuildRequired(project)) {
                IFolder folder = project.getFolder(path);
                if (!folder.exists()) {
                    // optional source folders may not exist
                    continue;
                }
                folder.accept(new IResourceVisitor() {
                    public boolean visit(IResource resource) throws CoreException {
                        if (!javaProject.isOnClasspath(resource)) {
                            return false;
                        }
                        if (resource instanceof IFile) {
                            IFile file = (IFile) resource;
                            processAnnotations(metadata, javaProject, file, processed, monitor);
                        }
                        return true; // keep visiting
                    }
                });
            } else {
                IResourceDelta delta = getDelta(project).findMember(path);

                if (delta == null) {
                    continue;
                }

                changed = true; // XXX not specific enough!

                delta.accept(new IResourceDeltaVisitor() {
                    public boolean visit(IResourceDelta delta) throws CoreException {
                        IResource resource = delta.getResource();
                        if (!javaProject.isOnClasspath(resource)) {
                            return false;
                        }
                        if (resource instanceof IFile && isInteresting(delta)) {
                            IFile file = (IFile) resource;
                            if (file.isAccessible()) {
                                processAnnotations(metadata, javaProject, file, processed, monitor);
                            } else {
                                metadata.remove(file);
                            }
                        }
                        return true; // keep visiting
                    }
                });
            }
        }
    }

    List<IResource> staleResources = metadata.getStaleResources(project, testMetadata);
    changed |= !staleResources.isEmpty();

    do {
        for (IResource resource : staleResources) {
            if (resource instanceof IFile) {
                processAnnotations(metadata, javaProject, (IFile) resource, processed, monitor);
            }
        }
        staleResources = metadata.getStaleResources(project, testMetadata);
        // this is actually a bug, but we report it later
        staleResources.removeAll(processed);
    } while (!staleResources.isEmpty());

    if (changed) {
        Set<IProject> dependencies = metadata.writeMetadata(project, testMetadata);
        return dependencies;
    }

    return null;
}

From source file:org.springframework.ide.eclipse.beans.core.internal.model.BeansModelUtils.java

License:Open Source License

/**
 * Checks if a given <code>type</code> is used as a bean class. The check iterates the complete {@link IBeansModel}
 * and not "only" the current {@link IBeansProject}.
 * <p>//from  ww w . j a  v a 2 s .c  o m
 * The implementation checks if the given <code>type</code> is on the project's classpath.
 * @param type
 * @since 2.2.1
 */
public static boolean isBeanClass(IType type) {
    for (IBeansProject project : BeansCorePlugin.getModel().getProjects()) {
        IJavaProject javaProject = JdtUtils.getJavaProject(project.getProject());
        if (javaProject != null && javaProject.isOnClasspath(type)) {
            for (IBeansConfig config : project.getConfigs()) {
                if (config.isBeanClass(type.getFullyQualifiedName())) {
                    return true;
                }
            }
        }
    }
    return false;
}

From source file:org.springframework.ide.eclipse.beans.core.internal.model.namespaces.ProjectClasspathExtensibleUriResolver.java

License:Open Source License

private void resetForChangedElement(IJavaElement element) {
    if (element instanceof IJavaProject) {
        IProject project = ((IJavaProject) element).getProject();
        projectResolvers.remove(project);
        SpringCorePreferences.getProjectPreferences(project, BeansCorePlugin.PLUGIN_ID).getProjectPreferences()
                .removePreferenceChangeListener(this);
    }/*from w  ww.  j a  v a2s . c  o m*/

    for (IProject project : projectResolvers.keySet()) {
        IJavaProject javaProject = JdtUtils.getJavaProject(project);
        if (javaProject != null) {
            if (javaProject.isOnClasspath(element)) {
                projectResolvers.remove(project);

                SpringCorePreferences.getProjectPreferences(project, BeansCorePlugin.PLUGIN_ID)
                        .getProjectPreferences().removePreferenceChangeListener(this);
            }
        }
    }
}

From source file:org.springframework.ide.eclipse.beans.ui.properties.NonJavaResourceContentProvider.java

License:Open Source License

private Object[] getResources(IContainer container) {
    try {/*  www  . ja  v a  2  s .  co m*/
        IResource[] members = container.members();
        IJavaProject javaProject = JavaCore.create(container.getProject());
        if (javaProject == null || !javaProject.exists()) {
            return members;
        }
        boolean isFolderOnClasspath = javaProject.isOnClasspath(container);
        List<Object> nonJavaResources = new ArrayList<Object>();

        // Can be on classpath but as a member of non-java resource folder
        for (IResource member : members) {

            // A resource can also be a java element in the case of
            // exclusion and inclusion filters. We therefore exclude Java
            // elements from the list of non-Java resources.
            if (isFolderOnClasspath) {
                if (javaProject.findPackageFragmentRoot(member.getFullPath()) == null) {
                    nonJavaResources.add(member);
                }
            } else if (!javaProject.isOnClasspath(member)) {
                nonJavaResources.add(member);
            }
        }
        return nonJavaResources.toArray();
    } catch (CoreException e) {
        return NO_CHILDREN;
    }
}

From source file:org.springframework.ide.eclipse.beans.ui.refactoring.util.BeansRefactoringChangeUtils.java

License:Open Source License

public static void createRenameChange(TextChange textChange, TextEdit textEdit, IFile file,
        IJavaElement[] affectedElements, String[] newNames, IProgressMonitor monitor) throws CoreException {
    IJavaProject jp = JdtUtils.getJavaProject(file.getProject());
    IStructuredModel model = null;/*  w w w . j a v a  2  s.  c  o m*/
    try {
        model = StructuredModelManager.getModelManager().getModelForRead(file);

        if (model == null) {
            return;
        }

        IDOMDocument document = ((DOMModelImpl) model).getDocument();
        NodeList nodes = document.getChildNodes();
        for (int j = 0; j < affectedElements.length; j++) {

            IJavaElement je = affectedElements[j];

            // check that the element we are about to change is on the file's classpath
            if (jp == null || (jp != null && jp.isOnClasspath(je))) {
                for (int i = 0; i < nodes.getLength(); i++) {
                    Node n = nodes.item(i);
                    recursiveCreateTextEdit(newNames[j], textChange, textEdit, je, n);
                }
            }
        }
    } catch (IOException e) {
    } finally {
        if (model != null) {
            model.releaseFromRead();
        }
    }
}

From source file:org.springframework.ide.eclipse.beans.ui.search.jdt.BeansJavaSearchParticipant.java

License:Open Source License

public void search(final ISearchRequestor requestor, QuerySpecification querySpecification,
        IProgressMonitor monitor) {/* w ww .  ja  va 2  s .c om*/

    if (querySpecification.getLimitTo() != LIMIT_TO_REF && querySpecification.getLimitTo() != LIMIT_TO_ALL) {
        return;
    }

    String search = null;
    List<String> requiredTypeNames = new ArrayList<String>();
    IJavaProject project = null;

    if (querySpecification instanceof ElementQuerySpecification) {
        ElementQuerySpecification elementQuerySpecification = (ElementQuerySpecification) querySpecification;
        if (elementQuerySpecification.getElement() instanceof IType) {
            search = ((IType) elementQuerySpecification.getElement()).getFullyQualifiedName();
            project = ((IType) elementQuerySpecification.getElement()).getJavaProject();
        } else if (elementQuerySpecification.getElement() instanceof IField) {
            IField field = ((IField) elementQuerySpecification.getElement());
            search = field.getElementName();
            getTypeHierachy(monitor, requiredTypeNames, field.getDeclaringType());
            project = field.getJavaProject();
        } else if (elementQuerySpecification.getElement() instanceof IMethod) {
            IMethod method = ((IMethod) elementQuerySpecification.getElement());
            search = method.getElementName();
            // do property name magic
            if (search.startsWith("set")) {
                search = StringUtils.uncapitalize(search.substring(3));
            }
            getTypeHierachy(monitor, requiredTypeNames, method.getDeclaringType());
            project = method.getJavaProject();
        } else {
            search = elementQuerySpecification.getElement().getElementName();
        }

        int type = ((ElementQuerySpecification) querySpecification).getElement().getElementType();
        if (type == IJavaElement.TYPE) {
            searchFor = SEARCH_FOR_TYPES;
        } else if (type == IJavaElement.FIELD || type == IJavaElement.METHOD) {
            searchFor = SEARCH_FOR_FIELDS;
        }
    } else {
        searchFor = ((PatternQuerySpecification) querySpecification).getSearchFor();
        search = ((PatternQuerySpecification) querySpecification).getPattern();
    }

    List<ISearchQuery> queries = new ArrayList<ISearchQuery>();
    BeansSearchScope scope = BeansSearchScope.newSearchScope();
    if (searchFor == SEARCH_FOR_TYPES) {
        queries.add(new BeanClassQuery(scope, search, true, false));
    } else if (searchFor == SEARCH_FOR_FIELDS) {
        queries.add(new BeanPropertyQuery(scope, search, true, false));
        queries.add(new BeanReferenceQuery(scope, search, true, false));
    }

    for (ISearchQuery query : queries) {
        query.run(monitor);

        BeansSearchResult searchResult = (BeansSearchResult) query.getSearchResult();
        for (Object obj : searchResult.getElements()) {
            Match[] matches = searchResult.getMatches(obj);
            if (matches != null && matches.length > 0) {
                for (Match match : matches) {
                    if (match.getElement() instanceof IBean) {
                        IBean bean = (IBean) match.getElement();
                        IType type = JdtUtils.getJavaType(bean.getElementResource().getProject(),
                                bean.getClassName());
                        if (project == null || (type != null && project.isOnClasspath(type))) {
                            if (searchFor == SEARCH_FOR_FIELDS) {
                                // check if the match fits to the selected class
                                String beanClass = BeansModelUtils.getBeanClass(bean, null);
                                if (requiredTypeNames.contains(beanClass)) {
                                    requestor.reportMatch(match);
                                }
                            } else {
                                requestor.reportMatch(match);
                            }
                        }
                    } else {
                        requestor.reportMatch(match);
                    }
                }
            }
        }
    }
}

From source file:org.summer.dsl.builder.JDTAwareEclipseResourceFileSystemAccess2.java

License:Open Source License

/**
 * @since 2.4/*from   w  w w .j  ava  2 s.  c  o  m*/
 */
@Override
protected void createContainer(IContainer container) throws CoreException {
    super.createContainer(container);
    // make it a source folder
    IJavaProject jp = JavaCore.create(container.getProject());
    if (jp.exists() && !jp.isOnClasspath(container)) {
        IClasspathEntry srcFolderClasspathEntry = JavaCore.newSourceEntry(container.getFullPath());
        IClasspathEntry[] classPath = jp.getRawClasspath();
        IClasspathEntry[] newClassPath = new IClasspathEntry[classPath.length + 1];
        System.arraycopy(classPath, 0, newClassPath, 1, classPath.length);
        newClassPath[0] = srcFolderClasspathEntry;
        jp.setRawClasspath(newClassPath, getMonitor());
    }
}