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

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

Introduction

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

Prototype

IJavaElement getParent();

Source Link

Document

Returns the element directly containing this element, or null if this element has no parent.

Usage

From source file:com.codenvy.ide.ext.java.server.internal.core.Member.java

License:Open Source License

public Member getOuterMostLocalContext() {
    IJavaElement current = this;
    Member lastLocalContext = null;
    parentLoop: while (true) {
        switch (current.getElementType()) {
        case CLASS_FILE:
        case COMPILATION_UNIT:
            break parentLoop; // done recursing
        case TYPE:
            // cannot be a local context
            break;
        case INITIALIZER:
        case FIELD:
        case METHOD:
            // these elements can define local members
            lastLocalContext = (Member) current;
            break;
        }/* w w w .  j av  a  2s.  co  m*/
        current = current.getParent();
    }
    return lastLocalContext;
}

From source file:com.codenvy.ide.ext.java.server.internal.core.Member.java

License:Open Source License

/**
 * @see IMember#getTypeRoot()//from   w  w w. j av  a 2  s  .  c o m
 */
public ITypeRoot getTypeRoot() {
    IJavaElement element = getParent();
    while (element instanceof IMember) {
        element = element.getParent();
    }
    return (ITypeRoot) element;
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.IndexSelector.java

License:Open Source License

private char[][][] getQualifiedNames(ObjectVector types) {
    final int size = types.size;
    char[][][] focusQualifiedNames = null;
    IJavaElement javaElement = this.pattern.focus;
    int index = 0;
    while (javaElement != null && !(javaElement instanceof ITypeRoot)) {
        javaElement = javaElement.getParent();
    }/*from   w  w  w.  j  ava 2s.  c o  m*/
    if (javaElement != null) {
        IType primaryType = ((ITypeRoot) javaElement).findPrimaryType();
        if (primaryType != null) {
            focusQualifiedNames = new char[size + 1][][];
            focusQualifiedNames[index++] = CharOperation.splitOn('.',
                    primaryType.getFullyQualifiedName().toCharArray());
        }
    }
    if (focusQualifiedNames == null) {
        focusQualifiedNames = new char[size][][];
    }
    for (int i = 0; i < size; i++) {
        focusQualifiedNames[index++] = CharOperation.splitOn('.',
                ((IType) (types.elementAt(i))).getFullyQualifiedName().toCharArray());
    }
    return focusQualifiedNames.length == 0 ? null
            : ReferenceCollection.internQualifiedNames(focusQualifiedNames, true);
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.JavaSearchScope.java

License:Open Source License

/**
 * Add an element to the java search scope.
 *
 * @param element//from   w  w w.  j  av a  2 s  .  co  m
 *         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();
        IResource rootResource = root.resource();
        String projectPath = root.getJavaProject().getPath().toString();
        if (rootResource != null && rootResource.isAccessible()) {
            String relativePath = Util.relativePath(rootResource.getFullPath(), 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 = Util.concatWith(((PackageFragment) element).names, '/');
            containerPath = root.getPath();
            containerPathToString = containerPath.getDevice() == null ? containerPath.toString()
                    : containerPath.toOSString();
            add(projectPath, relativePath, containerPathToString, true/*package*/, null);
        } else {
            IResource 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(resource.getFullPath(), 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:com.codenvy.ide.ext.java.server.internal.core.search.JavaSearchScope.java

License:Open Source License

public boolean encloses(IJavaElement element) {
    if (this.elements != null) {
        for (int i = 0, length = this.elements.size(); i < length; i++) {
            IJavaElement scopeElement = (IJavaElement) this.elements.get(i);
            IJavaElement searchedElement = element;
            while (searchedElement != null) {
                if (searchedElement.equals(scopeElement))
                    return true;
                searchedElement = searchedElement.getParent();
            }/*ww w. j  a va 2 s  . c  o m*/
        }
        return false;
    }
    IPackageFragmentRoot root = (IPackageFragmentRoot) element.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
    if (root != null && root.isArchive()) {
        // external or internal jar
        IPath rootPath = root.getPath();
        String rootPathToString = rootPath.getDevice() == null ? rootPath.toString() : rootPath.toOSString();
        IPath relativePath = getPath(element, true/*relative path*/);
        return indexOf(rootPathToString, relativePath.toString()) >= 0;
    }
    // resource in workspace
    String fullResourcePathString = getPath(element, false/*full path*/).toString();
    return indexOf(fullResourcePathString) >= 0;
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.JavaSearchScope.java

License:Open Source License

private IPath getPath(IJavaElement element, boolean relativeToRoot) {
    switch (element.getElementType()) {
    case IJavaElement.JAVA_MODEL:
        return Path.EMPTY;
    case IJavaElement.JAVA_PROJECT:
        return element.getPath();
    case IJavaElement.PACKAGE_FRAGMENT_ROOT:
        if (relativeToRoot)
            return Path.EMPTY;
        return element.getPath();
    case IJavaElement.PACKAGE_FRAGMENT:
        String relativePath = Util.concatWith(((PackageFragment) element).names, '/');
        return getPath(element.getParent(), relativeToRoot).append(new Path(relativePath));
    case IJavaElement.COMPILATION_UNIT:
    case IJavaElement.CLASS_FILE:
        return getPath(element.getParent(), relativeToRoot).append(new Path(element.getElementName()));
    default:// w ww. j  a v  a  2s  .c o m
        return getPath(element.getParent(), relativeToRoot);
    }
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.matching.FieldLocator.java

License:Open Source License

protected void matchReportReference(ASTNode reference, IJavaElement element, IJavaElement localElement,
        IJavaElement[] otherElements, Binding elementBinding, int accuracy, MatchLocator locator)
        throws CoreException {
    if (this.isDeclarationOfAccessedFieldsPattern) {
        // need exact match to be able to open on type ref
        if (accuracy != SearchMatch.A_ACCURATE)
            return;

        // element that references the field must be included in the enclosing element
        DeclarationOfAccessedFieldsPattern declPattern = (DeclarationOfAccessedFieldsPattern) this.pattern;
        while (element != null && !declPattern.enclosingElement.equals(element))
            element = element.getParent();
        if (element != null) {
            if (reference instanceof FieldReference) {
                reportDeclaration(((FieldReference) reference).binding, locator, declPattern.knownFields);
            } else if (reference instanceof QualifiedNameReference) {
                QualifiedNameReference qNameRef = (QualifiedNameReference) reference;
                Binding nameBinding = qNameRef.binding;
                if (nameBinding instanceof FieldBinding)
                    reportDeclaration((FieldBinding) nameBinding, locator, declPattern.knownFields);
                int otherMax = qNameRef.otherBindings == null ? 0 : qNameRef.otherBindings.length;
                for (int i = 0; i < otherMax; i++)
                    reportDeclaration(qNameRef.otherBindings[i], locator, declPattern.knownFields);
            } else if (reference instanceof SingleNameReference) {
                reportDeclaration((FieldBinding) ((SingleNameReference) reference).binding, locator,
                        declPattern.knownFields);
            }//  ww w .ja  v a  2s .com
        }
    } else if (reference instanceof ImportReference) {
        ImportReference importRef = (ImportReference) reference;
        long[] positions = importRef.sourcePositions;
        int lastIndex = importRef.tokens.length - 1;
        int start = (int) ((positions[lastIndex]) >>> 32);
        int end = (int) positions[lastIndex];
        this.match = locator.newFieldReferenceMatch(element, localElement, elementBinding, accuracy, start,
                end - start + 1, importRef);
        locator.report(this.match);
    } else if (reference instanceof FieldReference) {
        FieldReference fieldReference = (FieldReference) reference;
        long position = fieldReference.nameSourcePosition;
        int start = (int) (position >>> 32);
        int end = (int) position;
        this.match = locator.newFieldReferenceMatch(element, localElement, elementBinding, accuracy, start,
                end - start + 1, fieldReference);
        locator.report(this.match);
    } else if (reference instanceof SingleNameReference) {
        int offset = reference.sourceStart;
        this.match = locator.newFieldReferenceMatch(element, localElement, elementBinding, accuracy, offset,
                reference.sourceEnd - offset + 1, reference);
        locator.report(this.match);
    } else if (reference instanceof QualifiedNameReference) {
        QualifiedNameReference qNameRef = (QualifiedNameReference) reference;
        int length = qNameRef.tokens.length;
        SearchMatch[] matches = new SearchMatch[length];
        Binding nameBinding = qNameRef.binding;
        int indexOfFirstFieldBinding = qNameRef.indexOfFirstFieldBinding > 0
                ? qNameRef.indexOfFirstFieldBinding - 1
                : 0;

        // first token
        if (matchesName(this.pattern.name, qNameRef.tokens[indexOfFirstFieldBinding])
                && !(nameBinding instanceof LocalVariableBinding)) {
            FieldBinding fieldBinding = nameBinding instanceof FieldBinding ? (FieldBinding) nameBinding : null;
            if (fieldBinding == null) {
                matches[indexOfFirstFieldBinding] = locator.newFieldReferenceMatch(element, localElement,
                        elementBinding, accuracy, -1, -1, reference);
            } else {
                switch (matchField(fieldBinding, false)) {
                case ACCURATE_MATCH:
                    matches[indexOfFirstFieldBinding] = locator.newFieldReferenceMatch(element, localElement,
                            elementBinding, SearchMatch.A_ACCURATE, -1, -1, reference);
                    break;
                case INACCURATE_MATCH:
                    this.match = locator.newFieldReferenceMatch(element, localElement, elementBinding,
                            SearchMatch.A_INACCURATE, -1, -1, reference);
                    if (fieldBinding.type != null && fieldBinding.type.isParameterizedType()
                            && this.pattern.hasTypeArguments()) {
                        updateMatch((ParameterizedTypeBinding) fieldBinding.type,
                                this.pattern.getTypeArguments(), locator);
                    }
                    matches[indexOfFirstFieldBinding] = this.match;
                    break;
                }
            }
        }

        // other tokens
        for (int i = indexOfFirstFieldBinding + 1; i < length; i++) {
            char[] token = qNameRef.tokens[i];
            if (matchesName(this.pattern.name, token)) {
                FieldBinding otherBinding = qNameRef.otherBindings == null ? null
                        : qNameRef.otherBindings[i - (indexOfFirstFieldBinding + 1)];
                if (otherBinding == null) {
                    matches[i] = locator.newFieldReferenceMatch(element, localElement, elementBinding, accuracy,
                            -1, -1, reference);
                } else {
                    switch (matchField(otherBinding, false)) {
                    case ACCURATE_MATCH:
                        matches[i] = locator.newFieldReferenceMatch(element, localElement, elementBinding,
                                SearchMatch.A_ACCURATE, -1, -1, reference);
                        break;
                    case INACCURATE_MATCH:
                        this.match = locator.newFieldReferenceMatch(element, localElement, elementBinding,
                                SearchMatch.A_INACCURATE, -1, -1, reference);
                        if (otherBinding.type != null && otherBinding.type.isParameterizedType()
                                && this.pattern.hasTypeArguments()) {
                            updateMatch((ParameterizedTypeBinding) otherBinding.type,
                                    this.pattern.getTypeArguments(), locator);
                        }
                        matches[i] = this.match;
                        break;
                    }
                }
            }
        }
        locator.reportAccurateFieldReference(matches, qNameRef);
    }
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.matching.JavaSearchPattern.java

License:Open Source License

void storeTypeSignaturesAndArguments(IType type) {
    if (type.isResolved()) {
        BindingKey bindingKey = new BindingKey(type.getKey());
        if (bindingKey.isParameterizedType() || bindingKey.isRawType()) {
            String signature = bindingKey.toSignature();
            this.typeSignatures = Util.splitTypeLevelsSignature(signature);
            setTypeArguments(Util.getAllTypeArguments(this.typeSignatures));
        }//from w w w  .j  a v  a 2  s  . c  om
        return;
    }

    // Scan hierarchy to store type arguments at each level
    char[][][] typeParameters = new char[10][][];
    int ptr = -1;
    boolean hasParameters = false;
    try {
        IJavaElement parent = type;
        ITypeParameter[] parameters = null;
        while (parent != null && parent.getElementType() == IJavaElement.TYPE) {
            if (++ptr > typeParameters.length) {
                System.arraycopy(typeParameters, 0, typeParameters = new char[typeParameters.length + 10][][],
                        0, ptr);
            }
            IType parentType = (IType) parent;
            parameters = parentType.getTypeParameters();
            if (parameters != null) {
                int length = parameters.length;
                if (length > 0) {
                    hasParameters = true;
                    typeParameters[ptr] = new char[length][];
                    for (int i = 0; i < length; i++)
                        typeParameters[ptr][i] = Signature
                                .createTypeSignature(parameters[i].getElementName(), false).toCharArray();
                }
            }
            parent = parent.getParent();
        }
    } catch (JavaModelException jme) {
        return;
    }

    // Store type arguments if any
    if (hasParameters) {
        if (++ptr < typeParameters.length)
            System.arraycopy(typeParameters, 0, typeParameters = new char[ptr][][], 0, ptr);
        setTypeArguments(typeParameters);
    }
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.matching.MatchLocator.java

License:Open Source License

public static IJavaElement getProjectOrJar(IJavaElement element) {
    while (!(element instanceof IJavaProject) && !(element instanceof JarPackageFragmentRoot)) {
        element = element.getParent();
    }//  w  w  w.j a  v  a 2 s.  c o m
    return element;
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.matching.MethodLocator.java

License:Open Source License

/**
 * @see PatternLocator#matchReportReference(org.eclipse.jdt.internal.compiler.ast.ASTNode, org.eclipse.jdt.core.IJavaElement, org.eclipse.jdt.internal.compiler.lookup.Binding, int, MatchLocator)
 *//*from  ww w  . j av a  2 s .  c  o  m*/
protected void matchReportReference(ASTNode reference, IJavaElement element, IJavaElement localElement,
        IJavaElement[] otherElements, Binding elementBinding, int accuracy, MatchLocator locator)
        throws CoreException {
    MethodBinding methodBinding = (reference instanceof MessageSend) ? ((MessageSend) reference).binding
            : ((elementBinding instanceof MethodBinding) ? (MethodBinding) elementBinding : null);

    if (this.isDeclarationOfReferencedMethodsPattern) {
        if (methodBinding == null)
            return;
        // need exact match to be able to open on type ref
        if (accuracy != SearchMatch.A_ACCURATE)
            return;

        // element that references the method must be included in the enclosing element
        DeclarationOfReferencedMethodsPattern declPattern = (DeclarationOfReferencedMethodsPattern) this.pattern;
        while (element != null && !declPattern.enclosingElement.equals(element))
            element = element.getParent();
        if (element != null) {
            reportDeclaration(methodBinding, locator, declPattern.knownMethods);
        }
    } else {
        MethodReferenceMatch methodReferenceMatch = locator.newMethodReferenceMatch(element, elementBinding,
                accuracy, -1, -1, false /*not constructor*/, false/*not synthetic*/, reference);
        methodReferenceMatch.setLocalElement(localElement);
        this.match = methodReferenceMatch;
        if (this.pattern.findReferences && reference instanceof MessageSend) {
            IJavaElement focus = this.pattern.focus;
            // verify closest match if pattern was bound
            // (see bug 70827)
            if (focus != null && focus.getElementType() == IJavaElement.METHOD) {
                if (methodBinding != null && methodBinding.declaringClass != null) {
                    boolean isPrivate = Flags.isPrivate(((IMethod) focus).getFlags());
                    if (isPrivate && !CharOperation.equals(methodBinding.declaringClass.sourceName,
                            focus.getParent().getElementName().toCharArray())) {
                        return; // finally the match was not possible
                    }
                }
            }
            matchReportReference((MessageSend) reference, locator, accuracy, ((MessageSend) reference).binding);
        } else {
            if (reference instanceof SingleMemberAnnotation) {
                reference = ((SingleMemberAnnotation) reference).memberValuePairs()[0];
                this.match.setImplicit(true);
            }
            int offset = reference.sourceStart;
            int length = reference.sourceEnd - offset + 1;
            this.match.setOffset(offset);
            this.match.setLength(length);
            locator.report(this.match);
        }
    }
}