Example usage for org.eclipse.jdt.core.dom IBinding getJavaElement

List of usage examples for org.eclipse.jdt.core.dom IBinding getJavaElement

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.dom IBinding getJavaElement.

Prototype

public IJavaElement getJavaElement();

Source Link

Document

Returns the Java element that corresponds to this binding.

Usage

From source file:com.intel.ide.eclipse.mpt.ast.UnresolvedElementsSubProcessor.java

License:Open Source License

public static void addNewTypeProposals(ICompilationUnit cu, Name refNode, int kind, int relevance,
        Map<String, LinkedCorrectionProposal> proposals) throws CoreException {
    Name node = refNode;/*  ww w. java2  s .c om*/
    //      do {
    String typeName = ASTNodes.getSimpleNameIdentifier(node);
    Name qualifier = null;
    // only propose to create types for qualifiers when the name starts with upper case
    boolean isPossibleName = isLikelyTypeName(typeName) || node == refNode;
    if (isPossibleName) {
        IPackageFragment enclosingPackage = null;
        IType enclosingType = null;
        if (node.isSimpleName()) {
            enclosingPackage = (IPackageFragment) cu.getParent();
            return;
            // don't suggest member type, user can select it in wizard
        } else {
            Name qualifierName = ((QualifiedName) node).getQualifier();
            IBinding binding = qualifierName.resolveBinding();
            if (binding != null && binding.isRecovered()) {
                binding = null;
            }
            if (binding instanceof ITypeBinding) {
                enclosingType = (IType) binding.getJavaElement();
            } else if (binding instanceof IPackageBinding) {
                qualifier = qualifierName;
                enclosingPackage = (IPackageFragment) binding.getJavaElement();
            } else {
                IJavaElement[] res = cu.codeSelect(qualifierName.getStartPosition(), qualifierName.getLength());
                if (res != null && res.length > 0 && res[0] instanceof IType) {
                    enclosingType = (IType) res[0];
                } else {
                    qualifier = qualifierName;
                    enclosingPackage = JavaModelUtil.getPackageFragmentRoot(cu)
                            .getPackageFragment(ASTResolving.getFullName(qualifierName));
                }
            }
        }
        int rel = relevance;
        if (enclosingPackage != null && isLikelyPackageName(enclosingPackage.getElementName())) {
            rel += 3;
        }

        if (enclosingPackage != null
                && !enclosingPackage.getCompilationUnit(typeName + JavaModelUtil.DEFAULT_CU_SUFFIX).exists()
                || enclosingType != null && !enclosingType.isReadOnly()
                        && !enclosingType.getType(typeName).exists()) { // new member type
            IJavaElement enclosing = enclosingPackage != null ? (IJavaElement) enclosingPackage : enclosingType;

            String name = node.getFullyQualifiedName();

            if ((kind & SimilarElementsRequestor.CLASSES) != 0) {
                proposals.put(name, new NewCUProposal(cu, node, NewCUProposal.K_CLASS, enclosing, rel + 3));
            } else if ((kind & SimilarElementsRequestor.INTERFACES) != 0) {
                proposals.put(name, new NewCUProposal(cu, node, NewCUProposal.K_INTERFACE, enclosing, rel + 2));
            } else if ((kind & SimilarElementsRequestor.ENUMS) != 0) {
                proposals.put(name, new NewCUProposal(cu, node, NewCUProposal.K_ENUM, enclosing, rel));
            }
        }
    }
    node = qualifier;
    //      } while (node != null);
}

From source file:com.siteview.mde.internal.ui.correction.java.QuickFixProcessor.java

License:Open Source License

private void handleAccessRestrictionProblem(IInvocationContext context, IProblemLocation location,
        Collection results) {//from  w  w w.  ja  v  a 2  s .  c o m
    IBinding referencedElement = null;
    ASTNode node = location.getCoveredNode(context.getASTRoot());
    if (node instanceof Type) {
        referencedElement = ((Type) node).resolveBinding();
    } else if (node instanceof Name) {
        referencedElement = ((Name) node).resolveBinding();
    }
    if (referencedElement != null) {
        // get the project that contains the reference element
        // ensure it exists in the workspace and is a plug-in project
        IJavaProject referencedJavaProject = referencedElement.getJavaElement().getJavaProject();
        if (referencedJavaProject != null
                && WorkspaceModelManager.isPluginProject(referencedJavaProject.getProject())) {
            IPackageFragment referencedPackage = (IPackageFragment) referencedElement.getJavaElement()
                    .getAncestor(IJavaElement.PACKAGE_FRAGMENT);
            IJavaProject currentProject = context.getCompilationUnit().getJavaProject();
            // only find proposals for Plug-in projects
            if (!WorkspaceModelManager.isPluginProject(currentProject.getProject()))
                return;
            // get the packages exported by the referenced plug-in project
            if (!referencedJavaProject.equals(currentProject)) {
                IMonitorModelBase referencedModel = MonitorRegistry
                        .findModel(referencedJavaProject.getProject());
                ExportPackageDescription[] exportPackages = referencedModel.getBundleDescription()
                        .getExportPackages();
                // check if the required package is exported already
                boolean packageExported = false;
                if (referencedPackage != null) {
                    for (int i = 0; i < exportPackages.length; i++) {
                        if (exportPackages[i].getName().equals(referencedPackage.getElementName())) {
                            packageExported = true;
                            // check to see if access restriction is caused by Import-Package
                            handleAccessRestrictionByImportPackage(
                                    context.getCompilationUnit().getJavaProject().getProject(),
                                    exportPackages[i], results);
                            break;
                        }
                    }
                    // if the package is not exported, add the quickfix
                    if (!packageExported) {
                        Object proposal = JavaResolutionFactory.createExportPackageProposal(
                                referencedJavaProject.getProject(), referencedPackage,
                                JavaResolutionFactory.TYPE_JAVA_COMPLETION, 100);
                        if (proposal != null)
                            results.add(proposal);
                    }
                }
            } else {
                handleAccessRestrictionByImportPackage(referencedPackage, results);
            }
        }
    }
}

From source file:de.ovgu.cide.typing.jdt.checks.resolutions.ASTBindingFinderHelper.java

License:Open Source License

private static CompilationUnit getAST(IBinding binding) {
    IJavaElement element = binding.getJavaElement();
    if (element == null)
        return null;
    IResource res = element.getResource();
    if (!(res instanceof IFile))
        return null;

    try {//  www . j a  v  a 2  s.c o  m
        return JDTParserWrapper.parseJavaFile((IFile) res);
    } catch (ParseException e) {
        e.printStackTrace();
        // if in doubt no error
        return null;
    }

}

From source file:edu.buffalo.cse.green.relationship.alternateassociation.AssociationRemover.java

License:Open Source License

/**
 * @see edu.buffalo.cse.green.relationships.RelationshipRemover#finish()
 *//*from w  w w  .  j a va  2s. c o  m*/
protected void finish() {
    for (ExpressionStatement exp : lEXP) {
        Block block = (Block) exp.getParent();
        exp.delete();
        MethodDeclaration mdc = (MethodDeclaration) block.getParent();
        processAddInvocations(block);

        for (SingleVariableDeclaration varDec : (AbstractList<SingleVariableDeclaration>) mdc.parameters()) {
            IBinding binding = varDec.getName().resolveBinding();

            if (binding.getJavaElement().equals(lPAR.get(0))) {
                varDec.delete();
                break;
            }
        }

        lPAR.remove(0);
    }

    for (IField field : lFIE) {
        for (Object element : _typeInfo.bodyDeclarations()) {
            BodyDeclaration dec = (BodyDeclaration) element;

            if (dec.getNodeType() == FIELD_DECLARATION) {
                FieldDeclaration fieldDec = (FieldDeclaration) dec;

                List<VariableDeclarationFragment> fragments = (AbstractList<VariableDeclarationFragment>) fieldDec
                        .fragments();

                for (VariableDeclarationFragment fragment : fragments) {
                    IField dField = (IField) fragment.getName().resolveBinding().getJavaElement();

                    if (field.equals(dField)) {
                        fieldDec.delete();
                        break;
                    }
                }
            }
        }
    }
}

From source file:edu.buffalo.cse.green.relationships.RelationshipVisitor.java

License:Open Source License

/**
 * @param name - The <code>Name</code> to check
 * @return True if the name is bound to a field, false otherwise
 *///  www  .  j a v  a2 s .c  o  m
protected boolean isField(Name name) {
    IBinding binding = name.resolveBinding();
    if (binding == null)
        return false;

    IJavaElement ije = binding.getJavaElement();
    //      System.out.println("binding is "+binding);
    //      System.out.println("ije is "+ije);
    int type = ije.getElementType();

    return type == FIELD;
}

From source file:edu.buffalo.cse.green.relationships.RelationshipVisitor.java

License:Open Source License

/**
 * @param name - The <code>Name</code> to check
 * @return True if the name is bound to a parameter, false otherwise
 *///from   ww w.j  a v a2s . com
protected boolean isParameter(Name name) {
    IBinding binding = name.resolveBinding();
    if (binding == null)
        return false;

    IJavaElement element = binding.getJavaElement();
    if (!(element.getElementType() == LOCAL_VARIABLE))
        return false;
    return isParameter((ILocalVariable) element);
}

From source file:edu.buffalo.cse.green.relationships.RelationshipVisitor.java

License:Open Source License

/**
 * @param name - The <code>Name</code> to check
 * @return True if the name is bound to a local variable, false otherwise
 *///w w w . j  av a2  s .  co m
protected boolean isLocalVariable(Name name) {
    IBinding binding = name.resolveBinding();
    if (binding == null)
        return false;

    IJavaElement element = binding.getJavaElement();
    if (element == null)
        return false;

    if (!(element.getElementType() == LOCAL_VARIABLE))
        return false;
    return isLocalVariable((ILocalVariable) element);
}

From source file:net.sf.j2s.core.astvisitors.Bindings.java

License:Open Source License

/**
 * Checks if the two bindings are equals. First an identity check is
 * made an then the key of the bindings are compared. 
 * @param b1 first binding treated as <code>this</code>. So it must
 *  not be <code>null</code>
 * @param b2 the second binding.//from ww w. j  a v  a  2  s . co  m
 * @return boolean
 */
public static boolean equals(IBinding b1, IBinding b2) {
    boolean isEqualTo = b1.isEqualTo(b2);
    if (!isEqualTo && b1 instanceof ITypeBinding && b2 instanceof ITypeBinding) {
        ITypeBinding bb1 = (ITypeBinding) b1;
        ITypeBinding bb2 = (ITypeBinding) b2;
        String bb1Name = bb1.getBinaryName();
        if (bb1Name != null) {
            isEqualTo = bb1Name.equals(bb2.getBinaryName());
        }
    }
    if (CHECK_CORE_BINDING_IS_EQUAL_TO) {
        boolean originalEquals = originalEquals(b1, b2);
        if (originalEquals != isEqualTo) {
            //String message= "Unexpected difference between Bindings.equals(..) and IBinding#isEqualTo(..)"; //$NON-NLS-1$
            String detail = "\nb1 == " + b1.getKey() + ",\nb2 == " //$NON-NLS-1$//$NON-NLS-2$
                    + (b2 == null ? "null binding" : b2.getKey()); //$NON-NLS-1$
            try {
                detail += "\nb1.getJavaElement() == " + b1.getJavaElement() + ",\nb2.getJavaElement() == " //$NON-NLS-1$//$NON-NLS-2$
                        + (b2 == null ? "null binding" : b2.getJavaElement().toString()); //$NON-NLS-1$
            } catch (Exception e) {
                detail += "\nException in getJavaElement():\n" + e; //$NON-NLS-1$
            }
            //JavaPlugin.logRepeatedMessage(message, detail);
        }
    }
    return isEqualTo;
}

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

License:Open Source License

private static void addNewTypeProposals(ICompilationUnit cu, Name refNode, int kind, int relevance,
        Collection proposals) throws JavaModelException {
    Name node = refNode;/*from  ww w  .  j a  v a2s  .c  o m*/
    do {
        String typeName = ASTNodes.getSimpleNameIdentifier(node);
        Name qualifier = null;
        // only propose to create types for qualifiers when the name starts with upper case
        boolean isPossibleName = isLikelyTypeName(typeName) || (node == refNode);
        if (isPossibleName) {
            IPackageFragment enclosingPackage = null;
            IType enclosingType = null;
            if (node.isSimpleName()) {
                enclosingPackage = (IPackageFragment) cu.getParent();
                // don't suggest member type, user can select it in wizard
            } else {
                Name qualifierName = ((QualifiedName) node).getQualifier();
                IBinding binding = qualifierName.resolveBinding();
                if (binding instanceof ITypeBinding) {
                    enclosingType = (IType) binding.getJavaElement();
                } else if (binding instanceof IPackageBinding) {
                    qualifier = qualifierName;
                    enclosingPackage = (IPackageFragment) binding.getJavaElement();
                } else {
                    IJavaElement[] res = cu.codeSelect(qualifierName.getStartPosition(),
                            qualifierName.getLength());
                    if (res != null && res.length > 0 && res[0] instanceof IType) {
                        enclosingType = (IType) res[0];
                    } else {
                        qualifier = qualifierName;
                        enclosingPackage = JavaModelUtil.getPackageFragmentRoot(cu)
                                .getPackageFragment(ASTResolving.getFullName(qualifierName));
                    }
                }
            }
            int rel = relevance;
            if (enclosingPackage != null && isLikelyPackageName(enclosingPackage.getElementName())) {
                rel += 3;
            }

            if ((enclosingPackage != null && !enclosingPackage
                    .getCompilationUnit(typeName + JavaModelUtil.DEFAULT_CU_SUFFIX).exists()) // new top level type
                    || (enclosingType != null && !enclosingType.isReadOnly()
                            && !enclosingType.getType(typeName).exists())) { // new member type
                IJavaElement enclosing = enclosingPackage != null ? (IJavaElement) enclosingPackage
                        : enclosingType;

                if ((kind & SimilarElementsRequestor.CLASSES) != 0) {
                    proposals.add(new NewCUUsingWizardProposal(cu, node, NewCUUsingWizardProposal.K_CLASS,
                            enclosing, rel + 2));
                }
                if ((kind & SimilarElementsRequestor.INTERFACES) != 0) {
                    proposals.add(new NewCUUsingWizardProposal(cu, node, NewCUUsingWizardProposal.K_INTERFACE,
                            enclosing, rel + 1));
                }
                if ((kind & SimilarElementsRequestor.ENUMS) != 0) {
                    proposals.add(new NewCUUsingWizardProposal(cu, node, NewCUUsingWizardProposal.K_ENUM,
                            enclosing, rel));
                }
                if (kind == SimilarElementsRequestor.ANNOTATIONS) { // only when in annotation
                    proposals.add(new NewCUUsingWizardProposal(cu, node, NewCUUsingWizardProposal.K_ANNOTATION,
                            enclosing, rel + 4));
                }
            }
        }
        node = qualifier;
    } while (node != null);

    // type parameter proposals
    if (refNode.isSimpleName() && ((kind & SimilarElementsRequestor.VARIABLES) != 0)) {
        CompilationUnit root = (CompilationUnit) refNode.getRoot();
        String name = ((SimpleName) refNode).getIdentifier();
        BodyDeclaration declaration = ASTResolving.findParentBodyDeclaration(refNode);
        int baseRel = relevance;
        if (isLikelyTypeParameterName(name)) {
            baseRel += 4;
        }
        while (declaration != null) {
            IBinding binding = null;
            int rel = baseRel;
            if (declaration instanceof MethodDeclaration) {
                binding = ((MethodDeclaration) declaration).resolveBinding();
            } else if (declaration instanceof TypeDeclaration) {
                binding = ((TypeDeclaration) declaration).resolveBinding();
                rel++;
            }
            if (binding != null) {
                AddTypeParameterProposal proposal = new AddTypeParameterProposal(cu, binding, root, name, null,
                        rel);
                proposals.add(proposal);
            }
            if (!Modifier.isStatic(declaration.getModifiers())) {
                declaration = ASTResolving.findParentBodyDeclaration(declaration.getParent());
            } else {
                declaration = null;
            }
        }
    }
}

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

License:Open Source License

private void checkOutgoingReferences(final ITDCreator itd, final RefactoringStatus status)
        throws CoreException, OperationCanceledException {
    if (willBePrivileged())
        return; //Always OK!

    // Walk the AST to find problematic references (e.g. references to private members from within the moved method)
    itd.getMemberNode().accept(new ASTVisitor() {
        /**/* w w w .  jav a 2  s.  com*/
         * Check for various problems that may be caused by moving a reference into
         * a different context.
         */
        private void checkReference(ASTNode node, final IBinding binding, RefactoringStatus status) {
            if (isField(binding) || isMethod(binding) || isType(binding)) {
                if (isTypeParameter(binding))
                    return; //Exclude these, or they'll look like package restricted types in code below.
                if (isMoved(binding))
                    return; //OK: anything moved to the aspect will be accessible from the aspect
                int mods = binding.getModifiers();
                if (Modifier.isPrivate(mods)) {
                    status.addWarning(
                            "private member '" + binding.getName()
                                    + "' accessed and refactored aspect is not privileged",
                            makeContext(itd.getMember(), node));
                }
                if (JdtFlags.isProtected(binding) || JdtFlags.isPackageVisible(binding)) {
                    // FIXKDV: separate case for protected
                    // These are really two separate cases, but the cases where this matters (i.e.
                    // aspects that have a super type are rare so I'm not dealing with that
                    // right now (this is relatively harmless: will result in a spurious warning message 
                    // in rare case where the pulled member is protected and is pulled from target aspect's
                    // supertype that is not in the same package as target aspect)
                    String referredPkg = getPackageName(binding.getJavaElement());
                    if (referredPkg != null) {
                        //If it has no package, we'll just ignore it, whatever it is, it's probably not subject to
                        // package scope :-)
                        String aspectPkg = targetAspect.getPackageFragment().getElementName();
                        if (!referredPkg.equals(aspectPkg)) {
                            String keyword = JdtFlags.isProtected(binding) ? "protected" : "package restricted";
                            status.addWarning(
                                    keyword + " member '" + binding.getName()
                                            + "' is accessed and refactored aspect is not privileged",
                                    makeContext(itd.getMember(), node));
                        }
                    }
                }
            }
        }

        private boolean isField(IBinding binding) {
            return (binding instanceof IVariableBinding) && ((IVariableBinding) binding).isField();
        }

        private boolean isMethod(IBinding binding) {
            return (binding instanceof IMethodBinding);
        }

        private boolean isType(IBinding binding) {
            return binding instanceof ITypeBinding;
        }

        private boolean isTypeParameter(IBinding binding) {
            return binding instanceof ITypeBinding
                    && (((ITypeBinding) binding).isCapture() || ((ITypeBinding) binding).isTypeVariable());
        }

        @Override
        public boolean visit(SimpleName node) {
            IBinding binding = node.resolveBinding();
            checkReference(node, binding, status);
            return true;
        }

    });
}