Example usage for org.eclipse.jdt.core IJavaElement getUnderlyingResource

List of usage examples for org.eclipse.jdt.core IJavaElement getUnderlyingResource

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IJavaElement getUnderlyingResource.

Prototype

IResource getUnderlyingResource() throws JavaModelException;

Source Link

Document

Returns the smallest underlying resource that contains this element, or null if this element is not contained in a resource.

Usage

From source file:org.codecover.eclipse.InstrumentableItemsManager.java

License:Open Source License

private String getIJavaElementInfo(IJavaElement javaElement) {
    try {//from   w w w .  jav a 2  s.  c om
        return javaElement.getUnderlyingResource().getFullPath().toPortableString();
    } catch (JavaModelException e) {
        this.logger.error("A JavaModelException occured", e); //$NON-NLS-1$
        return null;
    }
}

From source file:org.eclipse.ajdt.internal.ui.editor.PointcutSourceHover.java

License:Open Source License

public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
    if (!(getEditor() instanceof AspectJEditor)) {
        return null;
    }/*w  ww  .  j ava 2 s. c  o  m*/
    IJavaElement input = SelectionConverter.getInput((JavaEditor) getEditor());
    int offset = hoverRegion.getOffset();
    if (input instanceof ICompilationUnit) {
        input = AJCompilationUnitManager.mapToAJCompilationUnit((ICompilationUnit) input);
    }
    if (input instanceof AJCompilationUnit) {
        AJCompilationUnit ajcu = (AJCompilationUnit) input;
        String source = PointcutUtilities.isInPointcutContext(ajcu, offset);
        if (source != null) {
            String id = PointcutUtilities.findIdentifier(source, offset);
            if (id != null) {
                try {
                    IJavaElement pc = PointcutUtilities.findPointcut(ajcu.getElementAt(offset), id);
                    if (pc != null) {
                        IResource res = pc.getUnderlyingResource();
                        AJCompilationUnit cu = AJCompilationUnitManager.INSTANCE
                                .getAJCompilationUnit((IFile) res);
                        if (cu != null) {
                            cu.requestOriginalContentMode();
                            String pcs = ((ISourceReference) pc).getSource();
                            cu.discardOriginalContentMode();
                            return pcs;
                        }
                        return ((ISourceReference) pc).getSource();
                    }
                } catch (JavaModelException e) {
                }
            }
        }
    }
    return null;
}

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

License:Open Source License

/**
 * Answers the number of file resources specified by the JAR package.
 *
 * @return int//from  w  w w .  j  a  v a  2s. c o  m
 */
protected int countSelectedElements() {
    Set<IJavaProject> enclosingJavaProjects = new HashSet<IJavaProject>(10);
    int count = 0;

    int n = fJarPackage.getElements().length;
    for (int i = 0; i < n; i++) {
        Object element = fJarPackage.getElements()[i];

        IJavaProject javaProject = getEnclosingJavaProject(element);
        if (javaProject != null)
            enclosingJavaProjects.add(javaProject);

        IResource resource = null;
        if (element instanceof IJavaElement) {
            IJavaElement je = (IJavaElement) element;
            try {
                resource = je.getUnderlyingResource();
            } catch (JavaModelException ex) {
                continue;
            }

            // Should not happen since we only export source files
            if (resource == null)
                continue;
        } else
            resource = (IResource) element;

        if (resource.getType() == IResource.FILE)
            count++;
        else
            count += getTotalChildCount((IContainer) resource);
    }

    if (fJarPackage.areOutputFoldersExported()) {
        if (!fJarPackage.areJavaFilesExported())
            count = 0;
        Iterator<IJavaProject> iter = enclosingJavaProjects.iterator();
        while (iter.hasNext()) {
            IJavaProject javaProject = iter.next();
            IContainer[] outputContainers;
            try {
                outputContainers = getOutputContainers(javaProject);
            } catch (CoreException ex) {
                addToStatus(ex);
                continue;
            }
            for (int i = 0; i < outputContainers.length; i++)
                count += getTotalChildCount(outputContainers[i]);

        }
    }

    return count;
}

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.j  a va 2  s  . co  m*/
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.contribution.visualiser.jdtImpl.JDTContentProvider.java

License:Open Source License

/** 
 * Keeps the currentResource and currentProject information up to date
 * in this class, as this method is called whenever a user changes
 * their selection in the workspace.// ww w .j a  va2  s.  co m
 */
public void selectionChanged(IWorkbenchPart iwp, ISelection is) {
    if (!(ProviderManager.getContentProvider().equals(this))) {
        return;
    }

    boolean updateRequired = false;

    try {
        if (is instanceof IStructuredSelection) {
            IStructuredSelection structuredSelection = (IStructuredSelection) is;
            Object o = structuredSelection.getFirstElement();

            if (o != null) {
                if (o instanceof IResource) {
                    currentlySelectedResource = (IResource) o;
                } else if (o instanceof IJavaElement) {
                    IJavaElement je = (IJavaElement) o;
                    currentlySelectedJE = je;
                    if (je.getUnderlyingResource() != null) {
                        if (!je.getUnderlyingResource().equals(currentlySelectedResource))
                            updateRequired = true;
                        currentlySelectedResource = je.getUnderlyingResource();
                        // Might be null!
                    }
                    if (je.getJavaProject() != null) {
                        setCurrentProject(je.getJavaProject());
                    }
                }
            }
        } else if (is instanceof ITextSelection) {
        }
        if (updateRequired) {
            VisualiserPlugin.refresh();
        }
    } catch (JavaModelException jme) {
        VisualiserPlugin.logException(jme);
    }
}

From source file:org.eclipse.jst.j2ee.internal.dialogs.TypeJavaSearchScope.java

License:Open Source License

public void add(IJavaElement element) throws JavaModelException {
    IPackageFragmentRoot root = null;/* w  w  w.  j  a va 2  s  .c o  m*/
    switch (element.getElementType()) {
    case IJavaElement.JAVA_MODEL:
        // a workspace sope should be used
        break;
    case IJavaElement.JAVA_PROJECT:
        this.add((IJavaProject) element, true, new HashSet(2));
        break;
    case IJavaElement.PACKAGE_FRAGMENT_ROOT:
        root = (IPackageFragmentRoot) element;
        this.add(root.getPath(), true);
        break;
    case IJavaElement.PACKAGE_FRAGMENT:
        root = (IPackageFragmentRoot) element.getParent();
        if (root.isArchive()) {
            this.add(root.getPath().append(new Path(element.getElementName().replace('.', '/'))), false);
        } else {
            IResource resource = element.getUnderlyingResource();
            if (resource != null && resource.isAccessible()) {
                this.add(resource.getFullPath(), false);
            }
        }
        break;
    default:
        // remember sub-cu (or sub-class file) java elements
        if (element instanceof IMember) {
            if (this.elements == null) {
                this.elements = new ArrayList();
            }
            this.elements.add(element);
        }
        this.add(this.fullPath(element), true);

        // find package fragment root including this java element
        IJavaElement parent = element.getParent();
        while (parent != null && !(parent instanceof IPackageFragmentRoot)) {
            parent = parent.getParent();
        }
        if (parent instanceof IPackageFragmentRoot) {
            root = (IPackageFragmentRoot) parent;
        }
    }

    if (root != null) {
        if (root.getKind() == IPackageFragmentRoot.K_BINARY) {
            this.addEnclosingProjectOrJar(root.getPath());
        } else {
            this.addEnclosingProjectOrJar(root.getJavaProject().getProject().getFullPath());
        }
    }
}

From source file:org.eclipse.mylyn.internal.java.ui.LandmarkMarkerManager.java

License:Open Source License

private LandmarkUpdateOperation createAddLandmarkMarkerOperation(final IInteractionElement node) {
    if (node == null || node.getContentType() == null) {
        return null;
    }/*  w w w  .j ava  2 s. co  m*/
    if (JavaStructureBridge.CONTENT_TYPE.equals(node.getContentType())) {
        final IJavaElement element = JavaCore.create(node.getHandleIdentifier());
        if (!element.exists()) {
            return null;
        }
        if (element instanceof IMember) {
            try {
                final ISourceRange range = ((IMember) element).getNameRange();
                IResource resource = element.getUnderlyingResource();
                if (resource instanceof IFile) {
                    LandmarkUpdateOperation runnable = new LandmarkUpdateOperation(resource) {
                        public void run(IProgressMonitor monitor) throws CoreException {
                            IMarker marker = getResource().createMarker(ID_MARKER_LANDMARK);
                            if (marker != null && range != null) {
                                marker.setAttribute(IMarker.CHAR_START, range.getOffset());
                                marker.setAttribute(IMarker.CHAR_END, range.getOffset() + range.getLength());
                                marker.setAttribute(IMarker.MESSAGE, "Mylyn Landmark");
                                marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_INFO);
                                markerMap.put(node, marker.getId());
                            }
                        }
                    };
                    return runnable;
                }
            } catch (JavaModelException e) {
                StatusHandler.log(
                        new Status(IStatus.ERROR, JavaUiBridgePlugin.ID_PLUGIN, "Could not update marker", e)); //$NON-NLS-1$
            }
        }
    }
    return null;
}

From source file:org.eclipse.mylyn.internal.java.ui.LandmarkMarkerManager.java

License:Open Source License

private LandmarkUpdateOperation createRemoveLandmarkMarkerOperation(final IInteractionElement node) {
    if (node == null) {
        return null;
    }/*from  w w w  .  j a v a 2 s.  c  om*/
    if (JavaStructureBridge.CONTENT_TYPE.equals(node.getContentType())) {
        IJavaElement element = JavaCore.create(node.getHandleIdentifier());
        if (!element.exists()) {
            return null;
        }
        if (element.getAncestor(IJavaElement.COMPILATION_UNIT) != null // stuff
                // from .class files
                && element instanceof ISourceReference) {
            try {
                IResource resource = element.getUnderlyingResource();
                LandmarkUpdateOperation runnable = new LandmarkUpdateOperation(resource) {
                    public void run(IProgressMonitor monitor) throws CoreException {
                        if (getResource() != null) {
                            try {
                                if (markerMap.containsKey(node)) {
                                    long id = markerMap.get(node);
                                    IMarker marker = getResource().getMarker(id);
                                    if (marker != null) {
                                        marker.delete();
                                    }
                                }
                            } catch (NullPointerException e) {
                                // FIXME avoid NPE
                                StatusHandler.log(new Status(IStatus.ERROR, JavaUiBridgePlugin.ID_PLUGIN,
                                        "Could not update marker", e)); //$NON-NLS-1$
                            }
                        }
                    }
                };
                return runnable;
            } catch (JavaModelException e) {
                // ignore the Java Model errors
            }
        }
    }
    return null;
}

From source file:org.eclipse.mylyn.internal.monitor.monitors.SelectionMonitor.java

License:Open Source License

private String obfuscateJavaElementHandle(IJavaElement javaElement) {
    try {// w  w  w  .j ava2 s. co m
        StringBuffer obfuscatedPath = new StringBuffer();
        IResource resource;
        resource = (IResource) javaElement.getUnderlyingResource();
        if (resource != null && (resource instanceof IFile)) {
            IFile file = (IFile) resource;
            obfuscatedPath.append(obfuscator.obfuscateResourcePath(file.getProjectRelativePath()));
            obfuscatedPath.append(':');
            obfuscatedPath.append(obfuscator.obfuscateString(javaElement.getElementName()));
            return obfuscatedPath.toString();
        } else {
            return obfuscator.obfuscateString(javaElement.getHandleIdentifier());
        }
    } catch (JavaModelException e) {
        // ignore non-existing element
    }
    return ID_JAVA_UNKNOWN;
}

From source file:org.eclipse.wb.android.internal.editor.AndroidPairResourceProvider.java

License:Open Source License

/**
 * @return the Activity file which uses given xml layout.
 *//*from  w  ww .j a v  a  2 s . com*/
protected IFile getJavaFile(IFile layoutFile) throws Exception {
    IProject project = layoutFile.getProject();
    String packageName = AndroidUtils.getPackageFromManifest(project);
    if (packageName == null) {
        return null;
    }
    IJavaProject javaProject = JavaCore.create(project);
    IType rType = javaProject.findType(packageName, "R.layout");
    String layoutName = StringUtils.removeEnd(layoutFile.getName(), "." + layoutFile.getFileExtension());
    IField field = rType.getField(layoutName);
    List<IJavaElement> references = CodeUtils.searchReferences(field);
    for (IJavaElement element : references) {
        // TODO: ask the user if found more than one?
        return (IFile) element.getUnderlyingResource();
    }
    return null;
}