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

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

Introduction

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

Prototype

IJavaElement getAncestor(int ancestorType);

Source Link

Document

Returns this Java element or the first ancestor of this element that has the given type.

Usage

From source file:org.eclipse.ajdt.internal.ui.markers.UpdateAJMarkers.java

License:Open Source License

/**
 * check if this relationship comes from an aspect that has a custom marker
 * @see AJMarkersDialog/*from   w  w w  . j  a  v  a 2s.com*/
 */
private String getCustomMarker(IRelationship relationship) {
    // get the element in the aspect, it is source or target depending
    // on the kind of relationship
    List<IJavaElement> aspectEntities = new ArrayList<IJavaElement>();
    if (relationship.isAffects()) {
        aspectEntities.add(model.programElementToJavaElement(relationship.getSourceHandle()));
    } else {
        // all targets are from the same
        for (String target : relationship.getTargets()) {
            aspectEntities.add(model.programElementToJavaElement(target));
        }
    }

    for (IJavaElement elt : aspectEntities) {
        if (elt != null) { // will be null if the referent is not found.  Should only be in error cases
            IType typeElement = (IType) elt.getAncestor(IJavaElement.TYPE);
            if (typeElement != null) {
                String customImage = AspectJPreferences.getSavedIcon(typeElement.getJavaProject().getProject(),
                        AJMarkersDialog.getFullyQualifiedAspectName(typeElement));
                if (customImage != null) {
                    return customImage;
                }
            }
        }
    }
    return null;
}

From source file:org.eclipse.ajdt.internal.ui.refactoring.ITDRenameRefactoringProvider.java

License:Open Source License

/**
 * Lightweight rename refactoring is often broken inside of {@link AJCompilationUnit}s, 
 * so just disable it.//from   w  ww .  j a  v a 2s  .com
 * @param elt
 * @return true if the element is inside an {@link AJCompilationUnit}
 */
public boolean belongsToInterestingCompilationUnit(IJavaElement elt) {
    return elt.getAncestor(IJavaElement.COMPILATION_UNIT) instanceof AJCompilationUnit;
}

From source file:org.eclipse.ajdt.internal.ui.refactoring.pullout.PullOutRefactoring.java

License:Open Source License

/**
 * Retrieve package name of a IJavaElement.
 * @return The name of the package, or null if the IJavaElement is not nested inside a IPackagFragment.
 *///w ww.ja  va2  s.  c  o  m
private String getPackageName(IJavaElement el) {
    IPackageFragment pkg = (IPackageFragment) el.getAncestor(IJavaElement.PACKAGE_FRAGMENT);
    if (pkg == null)
        return null;
    return pkg.getElementName();
}

From source file:org.eclipse.ajdt.internal.ui.refactoring.pullout.PullOutRefactoring.java

License:Open Source License

private static RefactoringStatusContext makeContext(SearchMatch match) {
    try {/*w w w . ja v a2  s. c  o m*/
        IJavaElement element = (IJavaElement) match.getElement();
        ITypeRoot typeRoot = (ITypeRoot) element.getAncestor(IJavaElement.COMPILATION_UNIT);
        if (typeRoot == null) {
            typeRoot = (ITypeRoot) element.getAncestor(IJavaElement.CLASS_FILE);
        }
        ISourceRange range = new SourceRange(match.getOffset(), match.getLength());
        return JavaStatusContext.create(typeRoot, range);
    } catch (Throwable e) {
        return null;
    }
}

From source file:org.eclipse.ajdt.internal.ui.visualiser.AJDTMarkupProvider.java

License:Open Source License

private void updateModel() {
    if (ProviderManager.getContentProvider() instanceof AJDTContentProvider) {
        IJavaProject jp = ((AJDTContentProvider) ProviderManager.getContentProvider()).getCurrentProject();
        if (jp != null) {
            AJProjectModelFacade model = AJProjectModelFactory.getInstance()
                    .getModelForProject(jp.getProject());

            Collection<IRelationship> allRelationships = model
                    .getRelationshipsForProject(new AJRelationshipType[] { AJRelationshipManager.ADVISED_BY,
                            AJRelationshipManager.ANNOTATED_BY, AJRelationshipManager.ASPECT_DECLARATIONS,
                            AJRelationshipManager.MATCHES_DECLARE });
            if (allRelationships != null) {
                for (IRelationship relationship : allRelationships) {
                    List<IMarkupKind> kinds = new ArrayList<IMarkupKind>();
                    IProgramElement sourceIpe = model.getProgramElement(relationship.getSourceHandle());
                    if (sourceIpe != null) {
                        List<String> targets = relationship.getTargets();
                        for (String targetStr : targets) {
                            IJavaElement target = model.programElementToJavaElement(targetStr);
                            String simpleName;
                            String qualifiedName;

                            if (!(target instanceof IAJCodeElement)) {
                                IJavaElement enclosingType = target.getAncestor(IJavaElement.TYPE);
                                if (enclosingType == null) {
                                    // Bug 324706  I don't know why the sloc is null.  Log the bug and
                                    // continue on.
                                    VisualiserPlugin.log(IStatus.WARNING,
                                            "Bug 324706: null containing type found for "
                                                    + target.getElementName() + "\nHandle identifier is: "
                                                    + target.getHandleIdentifier());
                                    // avoid an npe
                                    continue;
                                }//from   w w  w.j a v a  2  s.  c  om

                                simpleName = enclosingType.getElementName();
                                qualifiedName = ((IType) enclosingType).getFullyQualifiedName('.');

                            } else { // It's an injar aspect so we wno't be able to find the parents
                                qualifiedName = target.getElementName();
                                String[] parts = qualifiedName.split(" "); //$NON-NLS-1$
                                String aNameWithExtension = parts[parts.length - 1];
                                if (aNameWithExtension.indexOf('.') != -1) { // $NON-NLS-1$
                                    simpleName = aNameWithExtension.substring(0,
                                            aNameWithExtension.lastIndexOf('.')); // $NON-NLS-1$
                                } else {
                                    simpleName = aNameWithExtension;
                                }
                            }

                            if (sourceIpe.getSourceLocation() == null) {
                                // Bug 324706  I don't know why the sloc is null.  Log the bug and
                                // continue on.
                                VisualiserPlugin.log(IStatus.WARNING,
                                        "Bug 324706: Warning, null source location found in "
                                                + sourceIpe.getName() + "\nHandle identifier is: "
                                                + sourceIpe.getHandleIdentifier());
                                // avoid an npe
                                continue;
                            }

                            int lineNum = sourceIpe.getSourceLocation().getLine();
                            IJavaElement sourceJe = model
                                    .programElementToJavaElement(relationship.getSourceHandle());
                            if (sourceJe != null) {
                                IJavaElement compilationUnitAncestor = sourceJe
                                        .getAncestor(IJavaElement.COMPILATION_UNIT);
                                if (compilationUnitAncestor != null) {
                                    String memberName = compilationUnitAncestor.getElementName();
                                    memberName = memberName.substring(0, memberName.lastIndexOf(".")); //$NON-NLS-1$
                                    String packageName = sourceJe.getAncestor(IJavaElement.PACKAGE_FRAGMENT)
                                            .getElementName();
                                    if (!(packageName.equals(""))) { //$NON-NLS-1$
                                        memberName = packageName + "." + memberName; //$NON-NLS-1$
                                    }
                                    IMarkupKind markupKind = null;
                                    if (kindMap == null) {
                                        kindMap = new HashMap<String, IMarkupKind>();
                                    }
                                    if (relationship.getName()
                                            .equals(AJRelationshipManager.MATCHES_DECLARE.getDisplayName())) {
                                        String sourceName = target.getElementName();
                                        boolean errorKind = sourceName.startsWith(aspectJErrorKind);
                                        if (kindMap.get(
                                                sourceName + ":::" + qualifiedName) instanceof IMarkupKind) { //$NON-NLS-1$
                                            markupKind = kindMap.get(sourceName + ":::" + qualifiedName); //$NON-NLS-1$
                                        } else {
                                            markupKind = new ErrorOrWarningMarkupKind(
                                                    sourceName + ":::" + simpleName, errorKind); //$NON-NLS-1$
                                            kindMap.put(sourceName + ":::" + qualifiedName, markupKind); //$NON-NLS-1$
                                        }
                                    } else {
                                        if (kindMap.get(qualifiedName) instanceof IMarkupKind) {
                                            markupKind = kindMap.get(qualifiedName);
                                        } else {
                                            markupKind = new SimpleMarkupKind(simpleName, qualifiedName);
                                            kindMap.put(qualifiedName, markupKind);
                                        }
                                    }
                                    kinds.add(markupKind);
                                    Stripe stripe = new Stripe(kinds, lineNum, 1);
                                    addMarkup(memberName, stripe);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    processMarkups();
}

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

License:Open Source License

/**
 * Initializes all fields provided by the page with a given selection.
 * //from   w  ww  . j a  va 2  s  . c  om
 * @param elem the selection used to initialize this page or <code>
 * null</code> if no selection was available
 */
protected void initTypePage(IJavaElement elem) {
    String initSuperclass = "java.lang.Object"; //$NON-NLS-1$
    ArrayList initSuperinterfaces = new ArrayList(5);

    IJavaProject project = null;
    IPackageFragment pack = null;
    IType enclosingType = null;

    if (elem != null) {
        // evaluate the enclosing type
        project = elem.getJavaProject();
        pack = (IPackageFragment) elem.getAncestor(IJavaElement.PACKAGE_FRAGMENT);
        IType typeInCU = (IType) elem.getAncestor(IJavaElement.TYPE);
        if (typeInCU != null) {
            if (typeInCU.getCompilationUnit() != null) {
                enclosingType = typeInCU;
            }
        } else {
            ICompilationUnit cu = (ICompilationUnit) elem.getAncestor(IJavaElement.COMPILATION_UNIT);
            if (cu != null) {
                enclosingType = cu.findPrimaryType();
            }
        }

        try {
            IType type = null;
            if (elem.getElementType() == IJavaElement.TYPE) {
                type = (IType) elem;
                if (type.exists()) {
                    String superName = SuperInterfaceSelectionDialog.getNameWithTypeParameters(type);
                    if (type.isInterface()) {
                        initSuperinterfaces.add(superName);
                    } else {
                        initSuperclass = superName;
                    }
                }
            }
        } catch (JavaModelException e) {
            JavaPlugin.log(e);
            // ignore this exception now
        }
    }

    String typeName = ""; //$NON-NLS-1$

    ITextSelection selection = getCurrentTextSelection();
    if (selection != null) {
        String text = selection.getText();
        if (text != null && validateJavaTypeName(text, project).isOK()) {
            typeName = text;
        }
    }

    setPackageFragment(pack, true);
    setEnclosingType(enclosingType, true);
    setEnclosingTypeSelection(false, true);

    setTypeName(typeName, true);
    setSuperClass(initSuperclass, true);
    setSuperInterfaces(initSuperinterfaces, true);

    setAddComments(StubUtility.doAddComments(project), true); // from project or workspace
}

From source file:org.eclipse.che.jdt.internal.core.search.JavaSearchScope.java

License:Open Source License

/**
 * Add an element to the java search scope.
 *
 * @param element/* w  ww. ja v a  2  s .  c  om*/
 *         The element we want to add to current java search scope
 * @throws org.eclipse.jdt.core.JavaModelException
 *         May happen if some Java Model info are not available
 */
public void add(IJavaElement element) throws JavaModelException {
    IPath containerPath = null;
    String containerPathToString = null;
    PackageFragmentRoot root = null;
    int includeMask = SOURCES | APPLICATION_LIBRARIES | SYSTEM_LIBRARIES;
    switch (element.getElementType()) {
    case IJavaElement.JAVA_MODEL:
        // a workspace sope should be used
        break;
    case IJavaElement.JAVA_PROJECT:
        add((JavaProject) element, null, includeMask, new HashSet(2), new HashSet(2), null);
        break;
    case IJavaElement.PACKAGE_FRAGMENT_ROOT:
        root = (PackageFragmentRoot) element;
        IPath rootPath = root.internalPath();
        containerPath = root.getKind() == IPackageFragmentRoot.K_SOURCE ? root.getParent().getPath() : rootPath;
        containerPathToString = containerPath.getDevice() == null ? containerPath.toString()
                : containerPath.toOSString();
        File rootResource = root.resource();
        String projectPath = root.getJavaProject().getPath().toString();
        if (rootResource != null /*&& rootResource.isAccessible()*/) {
            String relativePath = Util.relativePath(new Path(rootResource.getAbsolutePath()),
                    containerPath.segmentCount());
            add(projectPath, relativePath, containerPathToString, false/*not a package*/, null);
        } else {
            add(projectPath, "", containerPathToString, false/*not a package*/, null); //$NON-NLS-1$
        }
        break;
    case IJavaElement.PACKAGE_FRAGMENT:
        root = (PackageFragmentRoot) element.getParent();
        projectPath = root.getJavaProject().getPath().toString();
        if (root.isArchive()) {
            String relativePath = org.eclipse.jdt.internal.core.util.Util
                    .concatWith(((PackageFragment) element).names, '/');
            containerPath = root.getPath();
            containerPathToString = containerPath.getDevice() == null ? containerPath.toString()
                    : containerPath.toOSString();
            add(projectPath, relativePath, containerPathToString, true/*package*/, null);
        } else {
            File resource = ((JavaElement) element).resource();
            if (resource != null) {
                //                  if (resource.isAccessible()) {
                containerPath = root.getKind() == IPackageFragmentRoot.K_SOURCE ? root.getParent().getPath()
                        : root.internalPath();
                //                  } else {
                //                     // for working copies, get resource container full path
                //                     containerPath = resource.getParent().getFullPath();
                //                  }
                containerPathToString = containerPath.getDevice() == null ? containerPath.toString()
                        : containerPath.toOSString();
                String relativePath = Util.relativePath(new Path(resource.getAbsolutePath()),
                        containerPath.segmentCount());
                add(projectPath, relativePath, containerPathToString, true/*package*/, null);
            }
        }
        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);
        }
        root = (PackageFragmentRoot) element.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
        projectPath = root.getJavaProject().getPath().toString();
        String relativePath;
        if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
            containerPath = root.getParent().getPath();
            relativePath = Util.relativePath(getPath(element, false/*full path*/), 1/*remove project segment*/);
        } else {
            containerPath = root.internalPath();
            relativePath = getPath(element, true/*relative path*/).toString();
        }
        containerPathToString = containerPath.getDevice() == null ? containerPath.toString()
                : containerPath.toOSString();
        add(projectPath, relativePath, containerPathToString, false/*not a package*/, null);
    }

    if (root != null)
        addEnclosingProjectOrJar(
                root.getKind() == IPackageFragmentRoot.K_SOURCE ? root.getParent().getPath() : root.getPath());
}

From source file:org.eclipse.che.jdt.util.JavaModelUtil.java

License:Open Source License

private static void addAllCus(HashSet<ICompilationUnit> collector, IJavaElement javaElement)
        throws JavaModelException {
    switch (javaElement.getElementType()) {
    case IJavaElement.JAVA_PROJECT:
        IJavaProject javaProject = (IJavaProject) javaElement;
        IPackageFragmentRoot[] packageFragmentRoots = javaProject.getPackageFragmentRoots();
        for (int i = 0; i < packageFragmentRoots.length; i++)
            addAllCus(collector, packageFragmentRoots[i]);
        return;/* www .ja v  a 2 s.  c om*/

    case IJavaElement.PACKAGE_FRAGMENT_ROOT:
        IPackageFragmentRoot packageFragmentRoot = (IPackageFragmentRoot) javaElement;
        if (packageFragmentRoot.getKind() != IPackageFragmentRoot.K_SOURCE)
            return;
        IJavaElement[] packageFragments = packageFragmentRoot.getChildren();
        for (int j = 0; j < packageFragments.length; j++)
            addAllCus(collector, packageFragments[j]);
        return;

    case IJavaElement.PACKAGE_FRAGMENT:
        IPackageFragment packageFragment = (IPackageFragment) javaElement;
        collector.addAll(Arrays.asList(packageFragment.getCompilationUnits()));
        return;

    case IJavaElement.COMPILATION_UNIT:
        collector.add((ICompilationUnit) javaElement);
        return;

    default:
        IJavaElement cu = javaElement.getAncestor(IJavaElement.COMPILATION_UNIT);
        if (cu != null)
            collector.add((ICompilationUnit) cu);
    }
}

From source file:org.eclipse.contribution.weaving.jdt.tests.refactoring.MockRefactoringProvider.java

License:Open Source License

public boolean isInterestingElement(IJavaElement element) {
    return element.getAncestor(IJavaElement.COMPILATION_UNIT) instanceof MockCompilationUnit;
}

From source file:org.eclipse.contribution.xref.internal.ui.utils.XRefUIUtils.java

License:Open Source License

public static List getXRefAdapterListForJavaElement(IJavaElement javaElement, boolean showParentCrosscutting) {
    List xrefAdapterList = new ArrayList();
    if (javaElement != null && !javaElement.exists()) {
        return xrefAdapterList;
    }//from w  w  w .j av a 2s  .  co m
    // if we've selected outside a javaElement, for example before
    // the aspect declaration, or we've opted to show crosscutting for
    // the entire file then want to return a list of everything.
    if (javaElement != null && (showParentCrosscutting || selectedOutsideJavaElement)) {

        ICompilationUnit parent = (ICompilationUnit) javaElement.getAncestor(IJavaElement.COMPILATION_UNIT);
        if (parent != null) {
            try {
                IType[] types = parent.getAllTypes();
                for (int i = 0; i < types.length; i++) {
                    if ((types[i] instanceof SourceType)
                            && (types[i].getParent() instanceof ICompilationUnit)) {
                        IAdaptable a = types[i];
                        if (a != null) {
                            xrefAdapterList.add(a.getAdapter(IXReferenceAdapter.class));
                        }
                    }
                }
            } catch (JavaModelException e) {
            }
        }
    } else {
        IAdaptable a = javaElement;
        if (a != null) {
            xrefAdapterList.add(a.getAdapter(IXReferenceAdapter.class));
        }
    }
    selectedOutsideJavaElement = false;
    return xrefAdapterList;
}