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.eclipse.ajdt.internal.ui.wizards.exports.AJJarFileExportOperation.java

License:Open Source License

/**
 * Exports the passed resource to the JAR file
 *
 * @param element the resource or JavaElement to export
 *///from www . ja  va2s.com
protected void exportElement(Object element, IProgressMonitor progressMonitor) throws InterruptedException {
    // AspectJ Change Begin
    if (!AspectJPlugin.USING_CU_PROVIDER) {
        // Don't export AJCompilationUnits because they are duplicates of files that we also export.
        if (element instanceof AJCompilationUnit) {
            return;
        }
    }
    // AspectJ Change End
    int leadSegmentsToRemove = 1;
    IPackageFragmentRoot pkgRoot = null;
    boolean isInJavaProject = false;
    IResource resource = null;
    IJavaProject jProject = null;
    if (element instanceof IJavaElement) {
        isInJavaProject = true;
        IJavaElement je = (IJavaElement) element;
        int type = je.getElementType();
        if (type != IJavaElement.CLASS_FILE && type != IJavaElement.COMPILATION_UNIT) {
            exportJavaElement(progressMonitor, je);
            return;
        }
        try {
            resource = je.getUnderlyingResource();
        } catch (JavaModelException ex) {
            addWarning(Messages.format(JarPackagerMessages.JarFileExportOperation_resourceNotFound,
                    je.getElementName()), ex);
            return;
        }
        jProject = je.getJavaProject();
        pkgRoot = JavaModelUtil.getPackageFragmentRoot(je);
    } else
        resource = (IResource) element;

    if (!resource.isAccessible()) {
        addWarning(Messages.format(JarPackagerMessages.JarFileExportOperation_resourceNotFound,
                resource.getFullPath()), null);
        return;
    }

    if (resource.getType() == IResource.FILE) {
        if (!isInJavaProject) {
            // check if it's a Java resource
            try {
                isInJavaProject = resource.getProject().hasNature(JavaCore.NATURE_ID);
            } catch (CoreException ex) {
                addWarning(
                        Messages.format(JarPackagerMessages.JarFileExportOperation_projectNatureNotDeterminable,
                                resource.getFullPath()),
                        ex);
                return;
            }
            if (isInJavaProject) {
                jProject = JavaCore.create(resource.getProject());
                try {
                    IPackageFragment pkgFragment = jProject
                            .findPackageFragment(resource.getFullPath().removeLastSegments(1));
                    if (pkgFragment != null)
                        pkgRoot = JavaModelUtil.getPackageFragmentRoot(pkgFragment);
                    else
                        pkgRoot = findPackageFragmentRoot(jProject,
                                resource.getFullPath().removeLastSegments(1));
                } catch (JavaModelException ex) {
                    addWarning(Messages.format(
                            JarPackagerMessages.JarFileExportOperation_javaPackageNotDeterminable,
                            resource.getFullPath()), ex);
                    return;
                }
            }
        }

        if (pkgRoot != null && jProject != null) {
            leadSegmentsToRemove = pkgRoot.getPath().segmentCount();
            boolean isOnBuildPath;
            isOnBuildPath = jProject.isOnClasspath(resource);
            if (!isOnBuildPath || (mustUseSourceFolderHierarchy()
                    && !pkgRoot.getElementName().equals(IPackageFragmentRoot.DEFAULT_PACKAGEROOT_PATH)))
                leadSegmentsToRemove--;
        }

        IPath destinationPath = resource.getFullPath().removeFirstSegments(leadSegmentsToRemove);

        boolean isInOutputFolder = false;
        if (isInJavaProject && jProject != null) {
            try {
                isInOutputFolder = jProject.getOutputLocation().isPrefixOf(resource.getFullPath());
            } catch (JavaModelException ex) {
                isInOutputFolder = false;
            }
        }

        exportClassFiles(progressMonitor, pkgRoot, resource, jProject, destinationPath);
        exportResource(progressMonitor, pkgRoot, isInJavaProject, resource, destinationPath, isInOutputFolder);

        progressMonitor.worked(1);
        ModalContext.checkCanceled(progressMonitor);

    } else
        exportContainer(progressMonitor, (IContainer) resource);
}

From source file:org.eclipse.ajdt.internal.ui.wizards.exports.AJJarFileExportOperation.java

License:Open Source License

private void exportClassFiles(IProgressMonitor progressMonitor, IPackageFragmentRoot pkgRoot,
        IResource resource, IJavaProject jProject, IPath destinationPath) {
    if (fJarPackage.areClassFilesExported() && isJavaFile(resource) && pkgRoot != null) {
        try {//from w  w w .java2 s.  co  m
            if (!jProject.isOnClasspath(resource))
                return;

            // find corresponding file(s) on classpath and export
            Iterator<IFile> iter = filesOnClasspath((IFile) resource, destinationPath, jProject, pkgRoot,
                    progressMonitor);
            IPath baseDestinationPath = destinationPath.removeLastSegments(1);
            while (iter.hasNext()) {
                IFile file = (IFile) iter.next();
                IPath classFilePath = baseDestinationPath.append(file.getName());
                progressMonitor.subTask(Messages.format(JarPackagerMessages.JarFileExportOperation_exporting,
                        classFilePath.toString()));
                fJarWriter.write(file, classFilePath);
            }
        } catch (CoreException ex) {
            addToStatus(ex);
        }
    }
}

From source file:org.eclipse.ajdt.internal.ui.wizards.exports.StandardJavaElementContentProvider.java

License:Open Source License

private Object[] getResources(IFolder folder) {
    try {/*w w w. ja v a  2 s  .  com*/
        IResource[] members = folder.members();
        IJavaProject javaProject = JavaCore.create(folder.getProject());
        if (javaProject == null || !javaProject.exists())
            return members;
        boolean isFolderOnClasspath = javaProject.isOnClasspath(folder);
        List nonJavaResources = new ArrayList();
        // Can be on classpath but as a member of non-java resource folder
        for (int i = 0; i < members.length; i++) {
            IResource member = members[i];
            // 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.eclipse.edt.ide.testserver.ClasspathUtil.java

License:Open Source License

public static void addEGLPathToJavaPathIfNecessary(IJavaProject javaProject, IProject currProject,
        Set<IProject> seen, List<String> classpath) {
    if (seen.contains(currProject)) {
        return;//from  w  ww  . j a v  a  2 s.  com
    }
    seen.add(currProject);

    try {
        if (currProject.hasNature(EGLCore.NATURE_ID)) {
            IEGLProject eglProject = EGLCore.create(currProject);
            for (IEGLPathEntry pathEntry : eglProject.getResolvedEGLPath(true)) {
                if (pathEntry.getEntryKind() == IEGLPathEntry.CPE_PROJECT) {
                    IPath path = pathEntry.getPath();
                    IResource resource = ResourcesPlugin.getWorkspace().getRoot().findMember(path);
                    try {
                        if (resource != null && resource.getType() == IResource.PROJECT
                                && !seen.contains(resource)
                                && ((IProject) resource).hasNature(JavaCore.NATURE_ID)
                                && !javaProject.isOnClasspath(resource)) {
                            classpath.add(getWorkspaceProjectClasspathEntry(resource.getName()));
                            addEGLPathToJavaPathIfNecessary(javaProject, (IProject) resource, seen, classpath);
                        }
                    } catch (CoreException ce) {
                    }
                }
            }
        }
    } catch (EGLModelException e) {
    } catch (CoreException e) {
    }
}

From source file:org.eclipse.jpt.common.core.internal.resource.SimpleJavaResourceLocator.java

License:Open Source License

protected boolean locationIsValid_(IProject project, IContainer container) throws JavaModelException {
    IJavaProject javaProject = this.getJavaProject(project);
    if (javaProject.isOnClasspath(container)) {
        return true;
    }//from   w  w  w  . j a v  a  2 s.  com

    Set<IPath> outputPaths = new LinkedHashSet<IPath>();
    outputPaths.add(javaProject.getOutputLocation());
    IClasspathEntry[] entries = javaProject.getRawClasspath();
    for (int i = 0; i < entries.length; i++) {
        IClasspathEntry entry = entries[i];
        if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE && entry.getOutputLocation() != null) {
            outputPaths.add(entry.getOutputLocation());
        }
    }
    IPath containerPath = container.getFullPath();
    for (IPath outputPath : outputPaths) {
        if (container.equals(project) && outputPath.isPrefixOf(containerPath)) {
            return true;
        }
        if (outputPath.isPrefixOf(containerPath)) {
            return false;
        }
    }

    for (Object resource : javaProject.getNonJavaResources()) {
        if (resource instanceof IFolder) {
            IFolder folder = (IFolder) resource;
            if (folder.getFullPath().isPrefixOf(containerPath)) {
                return true;
            }
        }
    }

    return false;
}

From source file:org.eclipse.jst.jsf.common.ui.internal.dialogfield.SourceFolderButtonDialogField.java

License:Open Source License

/**
 * This method updates the model and returns an error status. The underlying
 * model is only valid if the returned status is OK.
 * // w  w w  .  j  a v a2s  . c  o m
 * @return the model's error status
 */
public IStatus getChangedStatus() {
    StatusInfo status = new StatusInfo();

    _fCurrRoot = null;
    String str = getPackageFragmentRootText();
    if (str.length() == 0) {
        // SourceFolderButtonDialogField.error.EnterContainerName = Folder
        // name is empty.
        status.setError(DialogFieldResources.getInstance()
                .getString("SourceFolderButtonDialogField.error.EnterContainerName")); //$NON-NLS-1$
        return status;
    }
    IPath path = new Path(str);
    IResource res = ResourcesPlugin.getWorkspace().getRoot().findMember(path);
    if (res != null) {
        int resType = res.getType();
        if (resType == IResource.PROJECT || resType == IResource.FOLDER) {
            IProject proj = res.getProject();
            if (!proj.isOpen()) {
                status.setError(DialogFieldResources.getInstance().getString(
                        "SourceFolderButtonDialogField.error.ProjectClosed", proj.getFullPath().toString())); //$NON-NLS-1$
                return status;
            }
            if (_project != null && proj != _project) {
                // HibernateWizardPage.error.NotSameProject = The project
                // should be \''{0}\''.
                status.setError(DialogFieldResources.getInstance()
                        .getString("SourceFolderButtonDialogField.error.NotSameProject", _project.getName())); //$NON-NLS-1$
                return status;
            }
            IJavaProject jproject = JavaCore.create(proj);
            _fCurrRoot = jproject.getPackageFragmentRoot(res);
            if (res.exists()) {
                try {
                    if (!proj.hasNature(JavaCore.NATURE_ID)) {
                        if (resType == IResource.PROJECT) {
                            status.setError(DialogFieldResources.getInstance().getString(
                                    "SourceFolderButtonDialogField.warning.NotAJavaProject", proj.getName())); //$NON-NLS-1$
                        } else {
                            status.setWarning(DialogFieldResources.getInstance().getString(
                                    "SourceFolderButtonDialogField.warning.NotInAJavaProject", proj.getName())); //$NON-NLS-1$
                        }
                        return status;
                    }
                } catch (CoreException e) {
                    status.setWarning(DialogFieldResources.getInstance().getString(
                            "SourceFolderButtonDialogField.warning.NotAJavaProject", proj.getName())); //$NON-NLS-1$
                }
                if (!jproject.isOnClasspath(_fCurrRoot)) {
                    status.setWarning(DialogFieldResources.getInstance()
                            .getString("SourceFolderButtonDialogField.warning.NotOnClassPath", str)); //$NON-NLS-1$
                }
                if (_fCurrRoot.isArchive()) {
                    status.setError(DialogFieldResources.getInstance()
                            .getString("SourceFolderButtonDialogField.error.ContainerIsBinary", str)); //$NON-NLS-1$
                    return status;
                }
            }
            return status;
        }
        status.setError(DialogFieldResources.getInstance()
                .getString("SourceFolderButtonDialogField.error.NotAFolder", str)); //$NON-NLS-1$
        return status;
    }
    status.setError(DialogFieldResources.getInstance()
            .getString("SourceFolderButtonDialogField.error.ContainerDoesNotExist", str)); //$NON-NLS-1$
    return status;
}

From source file:org.eclipse.jst.jsf.common.ui.internal.utils.JavaModelUtil.java

License:Open Source License

/**
 * Tests if the given element is on the class path of its containing
 * project. Handles the case that the containing project isn't a Java
 * project.// w w  w . j a v a2  s . c  o m
 * @param element 
 * @return true if element in on the class path?
 */
public static boolean isOnClasspath(IJavaElement element) {
    IJavaProject project = element.getJavaProject();
    if (!project.exists())
        return false;
    return project.isOnClasspath(element);
}

From source file:org.eclipse.jst.jsf.common.ui.internal.utils.PathUtil.java

License:Open Source License

/**
 * @param javaProject/*www. ja va  2s.co  m*/
 * @param parent
 * @return the IPath for a a classpath object (?)
 */
public static IPath getPathOnClasspath(IJavaProject javaProject, Object parent) {
    IPath result = null;
    if (javaProject == null || parent == null) {
        return new Path(""); //$NON-NLS-1$
    }
    IClasspathEntry[] entries = javaProject.readRawClasspath();
    IPath classPath = null;
    if (parent instanceof IResource) {
        if (((javaProject != null) && !javaProject.isOnClasspath((IResource) parent))) {
            return new Path(""); //$NON-NLS-1$
        }
        if (parent instanceof IFile) {
            IPath elementPath = ((IFile) parent).getFullPath();
            if (((IFile) parent).getFileExtension().equalsIgnoreCase(IFileFolderConstants.EXT_PROPERTIES)) {
                int machings = 0;
                try {
                    for (int i = 0; i < entries.length; i++) {
                        // Determine whether on this classentry's path
                        int n = entries[i].getPath().matchingFirstSegments(elementPath);
                        if (n > machings) {
                            // Get package name
                            machings = n;
                            classPath = elementPath.removeFirstSegments(machings).removeLastSegments(1);
                        }
                    }

                    // Not on the classpath?
                    if (classPath == null) {
                        return null;
                    } else if (classPath.segmentCount() > 0) {
                        IJavaElement element = javaProject.findElement(classPath);
                        if (element != null) {
                            IPath path = element.getPath();
                            if (path != null) {
                                IPath path1 = path.removeFirstSegments(machings);

                                String fileName = ((IFile) parent).getName();
                                if (fileName != null) {
                                    result = path1.append(fileName);
                                }
                            }
                        }

                    } else {
                        result = ((IFile) parent).getFullPath().removeFirstSegments(machings);
                    }
                } catch (Exception e) {
                    return null;
                }
            }
        }
    } else if (parent instanceof IJarEntryResource) {
        IPath elementPath = ((IJarEntryResource) parent).getFullPath();
        if (elementPath.getFileExtension().equalsIgnoreCase(IFileFolderConstants.EXT_PROPERTIES)) {
            result = elementPath;
        }
    }
    if (result != null) {
        return result;
    }
    return new Path(""); //$NON-NLS-1$
}

From source file:org.eclipse.jst.pagedesigner.utils.JavaUtil.java

License:Open Source License

/**
 * /*from   w  ww.jav a2s .  co m*/
 * @param javaProject
 * @param parent
 * @return the path in javaProject or new Path("") if not found on a class path
 * @author mengbo
 */
public static IPath getPathOnClasspath(IJavaProject javaProject, Object parent) {
    IPath result = null;
    if (javaProject == null || parent == null) {
        return new Path(""); //$NON-NLS-1$
    }
    IClasspathEntry[] entries = javaProject.readRawClasspath();
    IPath classPath = null;
    if (parent instanceof IResource) {
        if (((javaProject != null) && !javaProject.isOnClasspath((IResource) parent))) {
            return new Path(""); //$NON-NLS-1$
        }
        if (parent instanceof IFile) {
            IPath elementPath = ((IFile) parent).getFullPath();
            if (((IFile) parent).getFileExtension().equalsIgnoreCase(IFileFolderConstants.EXT_PROPERTIES)) {
                int machings = 0;
                try {
                    for (int i = 0; i < entries.length; i++) {
                        // Determine whether on this classentry's path
                        machings = entries[i].getPath().matchingFirstSegments(elementPath);
                        if (machings > 0) {
                            // Get package name
                            classPath = elementPath.removeFirstSegments(machings).removeLastSegments(1);
                            break;
                        }
                    }
                    // Not on the classpath?
                    if (classPath == null) {
                        return null;
                    } else if (classPath.segmentCount() > 0)
                        result = javaProject.findElement(classPath).getPath().removeFirstSegments(machings)
                                .append(((IFile) parent).getName());
                    else
                        result = ((IFile) parent).getFullPath().removeFirstSegments(machings);
                } catch (Exception e) {
                    // Error.DesignerPropertyTool.NatureQuerying = Error in
                    // project java nature querying
                    PDPlugin.getLogger(JavaUtil.class).error("Error.DesignerPropertyTool.NatureQuerying", e); //$NON-NLS-1$
                    return null;
                }
            }
        }
    } else if (parent instanceof IJarEntryResource) {
        IPath elementPath = ((IJarEntryResource) parent).getFullPath();
        if (elementPath.getFileExtension().equalsIgnoreCase(IFileFolderConstants.EXT_PROPERTIES)) {
            result = elementPath;
        }
    }
    if (result != null) {
        return result;
    }
    return new Path(""); //$NON-NLS-1$
}

From source file:org.eclipse.objectteams.otdt.debug.ui.internal.actions.OTToggleBreakpointAdapter.java

License:Open Source License

/**
 * Performs the actual toggling of the line breakpoint
 * @param selection the current selection (from the editor or view)
 * @param part the active part//  www  .j  a  v  a 2 s.  c o m
 * @param locator the locator, may be <code>null</code>
 * @param bestMatch if we should consider the best match rather than an exact match
 * @param monitor progress reporting
 * @return the status of the toggle
 * @since 3.8
 */
IStatus doLineBreakpointToggle(ISelection selection, IWorkbenchPart part,
        ValidBreakpointLocationLocator locator, boolean bestMatch, IProgressMonitor monitor) {
    ITextEditor editor = getTextEditor(part);
    if (editor != null && selection instanceof ITextSelection) {
        if (monitor.isCanceled()) {
            return Status.CANCEL_STATUS;
        }
        ITextSelection tsel = (ITextSelection) selection;
        if (tsel.getStartLine() < 0) {
            return Status.CANCEL_STATUS;
        }
        try {
            report(null, part);
            ISelection sel = selection;
            if (!(selection instanceof IStructuredSelection)) {
                sel = translateToMembers(part, selection);
            }
            if (sel instanceof IStructuredSelection) {
                IMember member = (IMember) ((IStructuredSelection) sel).getFirstElement();
                IType type = null;
                //{ObjectTeams: also handle IOTJavaElement.{ROLE,TEAM}:
                /* orig:
                                    if(member.getElementType() == IJavaElement.TYPE) {
                  :giro */
                if (member instanceof IType) {
                    // SH}
                    type = (IType) member;
                } else {
                    type = member.getDeclaringType();
                }
                String tname = null;
                IJavaProject project = type.getJavaProject();
                if (locator == null || (project != null && !project.isOnClasspath(type))) {
                    tname = createQualifiedTypeName(type);
                } else {
                    tname = locator.getFullyQualifiedTypeName();
                }
                IResource resource = BreakpointUtils.getBreakpointResource(type);
                int lnumber = locator == null ? tsel.getStartLine() + 1 : locator.getLineLocation();
                IJavaLineBreakpoint existingBreakpoint = JDIDebugModel.lineBreakpointExists(resource, tname,
                        lnumber);
                if (existingBreakpoint != null) {
                    deleteBreakpoint(existingBreakpoint, editor, monitor);
                    return Status.OK_STATUS;
                }
                Map<String, Object> attributes = new HashMap<String, Object>(10);
                IDocumentProvider documentProvider = editor.getDocumentProvider();
                if (documentProvider == null) {
                    return Status.CANCEL_STATUS;
                }
                IDocument document = documentProvider.getDocument(editor.getEditorInput());
                int charstart = -1, charend = -1;
                try {
                    IRegion line = document.getLineInformation(lnumber - 1);
                    charstart = line.getOffset();
                    charend = charstart + line.getLength();
                } catch (BadLocationException ble) {
                    JDIDebugUIPlugin.log(ble);
                }
                BreakpointUtils.addJavaBreakpointAttributes(attributes, type);
                IJavaLineBreakpoint breakpoint = JDIDebugModel.createLineBreakpoint(resource, tname, lnumber,
                        charstart, charend, 0, true, attributes);
                if (locator == null) {
                    //{ObjectTeams: replace BreakpointLocationVerifierJob with own OTBreakpointLocationVerifierJob
                    /* orig:
                                      new BreakpointLocationVerifierJob(document, parseCompilationUnit(type.getTypeRoot()), breakpoint, lnumber, tname, type, editor, bestMatch).schedule();
                      :giro */
                    new OTBreakpointLocationVerifierJob(document, breakpoint, lnumber, bestMatch, tname, type,
                            resource, editor).schedule();
                    //ike}                         
                }
            } else {
                report(ActionMessages.ToggleBreakpointAdapter_3, part);
                return Status.OK_STATUS;
            }
        } catch (CoreException ce) {
            return ce.getStatus();
        }
    }
    return Status.OK_STATUS;
}