Search in sources :

Example 71 with IMethod

use of org.eclipse.jdt.core.IMethod in project xtext-eclipse by eclipse.

the class JavaElementDelegateJunitLaunch method containsElementsSearchedFor.

@Override
protected boolean containsElementsSearchedFor(IFile file) {
    IJavaElement element = JavaCore.create(file);
    if (element == null || !element.exists() || !(element instanceof ICompilationUnit)) {
        return false;
    }
    try {
        ICompilationUnit cu = (ICompilationUnit) element;
        for (IType type : cu.getAllTypes()) {
            for (IMethod method : type.getMethods()) {
                int flags = method.getFlags();
                if (Modifier.isPublic(flags) && !Modifier.isStatic(flags) && method.getNumberOfParameters() == 0 && Signature.SIG_VOID.equals(method.getReturnType()) && method.getElementName().startsWith("test")) {
                    // $NON-NLS-1$
                    return true;
                }
                // $NON-NLS-1$
                IAnnotation annotation = method.getAnnotation("Test");
                if (annotation.exists())
                    return true;
            }
        }
    } catch (JavaModelException e) {
        log.error(e.getMessage(), e);
    }
    return super.containsElementsSearchedFor(file);
}
Also used : IAnnotation(org.eclipse.jdt.core.IAnnotation) IJavaElement(org.eclipse.jdt.core.IJavaElement) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) JavaModelException(org.eclipse.jdt.core.JavaModelException) IMethod(org.eclipse.jdt.core.IMethod) IType(org.eclipse.jdt.core.IType)

Example 72 with IMethod

use of org.eclipse.jdt.core.IMethod in project xtext-eclipse by eclipse.

the class JvmImplementationOpener method openImplementations.

/**
 * Main parts of the logic is taken from {@link org.eclipse.jdt.internal.ui.javaeditor.JavaElementImplementationHyperlink}
 *
 * @param element - Element to show implementations for
 * @param textviewer - Viewer to show hierarchy view on
 * @param region - Region where to show hierarchy view
 */
public void openImplementations(final IJavaElement element, ITextViewer textviewer, IRegion region) {
    if (element instanceof IMethod) {
        ITypeRoot typeRoot = ((IMethod) element).getTypeRoot();
        CompilationUnit ast = SharedASTProvider.getAST(typeRoot, SharedASTProvider.WAIT_YES, null);
        if (ast == null) {
            openQuickHierarchy(textviewer, element, region);
            return;
        }
        try {
            ISourceRange nameRange = ((IMethod) element).getNameRange();
            ASTNode node = NodeFinder.perform(ast, nameRange);
            ITypeBinding parentTypeBinding = null;
            if (node instanceof SimpleName) {
                ASTNode parent = node.getParent();
                if (parent instanceof MethodInvocation) {
                    Expression expression = ((MethodInvocation) parent).getExpression();
                    if (expression == null) {
                        parentTypeBinding = Bindings.getBindingOfParentType(node);
                    } else {
                        parentTypeBinding = expression.resolveTypeBinding();
                    }
                } else if (parent instanceof SuperMethodInvocation) {
                    // Directly go to the super method definition
                    openEditor(element);
                    return;
                } else if (parent instanceof MethodDeclaration) {
                    parentTypeBinding = Bindings.getBindingOfParentType(node);
                }
            }
            final IType type = parentTypeBinding != null ? (IType) parentTypeBinding.getJavaElement() : null;
            if (type == null) {
                openQuickHierarchy(textviewer, element, region);
                return;
            }
            final String earlyExitIndicator = "EarlyExitIndicator";
            final ArrayList<IJavaElement> links = Lists.newArrayList();
            IRunnableWithProgress runnable = new IRunnableWithProgress() {

                @Override
                public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                    if (monitor == null) {
                        monitor = new NullProgressMonitor();
                    }
                    try {
                        String methodLabel = JavaElementLabels.getElementLabel(element, JavaElementLabels.DEFAULT_QUALIFIED);
                        monitor.beginTask(Messages.format("Searching for implementors of  ''{0}''", methodLabel), 100);
                        SearchRequestor requestor = new SearchRequestor() {

                            @Override
                            public void acceptSearchMatch(SearchMatch match) throws CoreException {
                                if (match.getAccuracy() == SearchMatch.A_ACCURATE) {
                                    IJavaElement element = (IJavaElement) match.getElement();
                                    if (element instanceof IMethod && !JdtFlags.isAbstract((IMethod) element)) {
                                        links.add(element);
                                        if (links.size() > 1) {
                                            throw new OperationCanceledException(earlyExitIndicator);
                                        }
                                    }
                                }
                            }
                        };
                        int limitTo = IJavaSearchConstants.DECLARATIONS | IJavaSearchConstants.IGNORE_DECLARING_TYPE | IJavaSearchConstants.IGNORE_RETURN_TYPE;
                        SearchPattern pattern = SearchPattern.createPattern(element, limitTo);
                        Assert.isNotNull(pattern);
                        SearchParticipant[] participants = new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() };
                        SearchEngine engine = new SearchEngine();
                        engine.search(pattern, participants, SearchEngine.createHierarchyScope(type), requestor, SubMonitor.convert(monitor, 100));
                        if (monitor.isCanceled()) {
                            throw new InterruptedException();
                        }
                    } catch (OperationCanceledException e) {
                        throw new InterruptedException(e.getMessage());
                    } catch (CoreException e) {
                        throw new InvocationTargetException(e);
                    } finally {
                        monitor.done();
                    }
                }
            };
            try {
                PlatformUI.getWorkbench().getProgressService().busyCursorWhile(runnable);
            } catch (InvocationTargetException e) {
                IStatus status = new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.OK, Messages.format("An error occurred while searching for implementations of method ''{0}''. See error log for details.", element.getElementName()), e.getCause());
                JavaPlugin.log(status);
                ErrorDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Open Implementation", "Problems finding implementations.", status);
            } catch (InterruptedException e) {
                if (e.getMessage() != earlyExitIndicator) {
                    return;
                }
            }
            if (links.size() == 1) {
                openEditor(links.get(0));
            } else {
                openQuickHierarchy(textviewer, element, region);
            }
        } catch (JavaModelException e) {
            log.error("An error occurred while searching for implementations", e.getCause());
        } catch (PartInitException e) {
            log.error("An error occurred while searching for implementations", e.getCause());
        }
    }
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) IStatus(org.eclipse.core.runtime.IStatus) JavaModelException(org.eclipse.jdt.core.JavaModelException) SimpleName(org.eclipse.jdt.core.dom.SimpleName) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) IType(org.eclipse.jdt.core.IType) IRunnableWithProgress(org.eclipse.jface.operation.IRunnableWithProgress) SearchParticipant(org.eclipse.jdt.core.search.SearchParticipant) SearchEngine(org.eclipse.jdt.core.search.SearchEngine) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) SearchPattern(org.eclipse.jdt.core.search.SearchPattern) IMethod(org.eclipse.jdt.core.IMethod) PartInitException(org.eclipse.ui.PartInitException) ISourceRange(org.eclipse.jdt.core.ISourceRange) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) IStatus(org.eclipse.core.runtime.IStatus) Status(org.eclipse.core.runtime.Status) IJavaElement(org.eclipse.jdt.core.IJavaElement) SearchMatch(org.eclipse.jdt.core.search.SearchMatch) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ITypeRoot(org.eclipse.jdt.core.ITypeRoot) InvocationTargetException(java.lang.reflect.InvocationTargetException) SearchRequestor(org.eclipse.jdt.core.search.SearchRequestor) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) CoreException(org.eclipse.core.runtime.CoreException) Expression(org.eclipse.jdt.core.dom.Expression)

Example 73 with IMethod

use of org.eclipse.jdt.core.IMethod in project xtext-eclipse by eclipse.

the class CombinedJvmJdtRenameContextFactory method createLocalRenameElementContext.

@Override
public IRenameElementContext createLocalRenameElementContext(EObject targetElement, XtextEditor editor, ITextSelection selection, XtextResource resource) {
    EObject declarationTarget = getDeclarationTarget(targetElement);
    Set<EObject> jvmElements = filterJvmElements(associations.getJvmElements(declarationTarget));
    if (!jvmElements.isEmpty()) {
        Map<URI, IJavaElement> jvm2javaElement = newLinkedHashMap();
        for (JvmIdentifiableElement jvmElement : filter(jvmElements, JvmIdentifiableElement.class)) {
            JvmIdentifiableElement jvmElementToBeRenamed = (jvmElement instanceof JvmConstructor) ? ((JvmConstructor) jvmElement).getDeclaringType() : jvmElement;
            IJavaElement javaElement = getJavaElementFinder().findExactElementFor(jvmElementToBeRenamed);
            if (javaElement != null)
                if (javaElement instanceof IMethod)
                    addDeclaringMethod(jvmElementToBeRenamed, javaElement, jvm2javaElement);
                else
                    jvm2javaElement.put(EcoreUtil.getURI(jvmElementToBeRenamed), javaElement);
        }
        if (!jvm2javaElement.isEmpty()) {
            return new CombinedJvmJdtRenameContext(declarationTarget, jvm2javaElement, editor, selection, resource);
        }
    }
    if (targetElement instanceof JvmFormalParameter || targetElement instanceof JvmTypeParameter) {
        EObject sourceParameter = associations.getPrimarySourceElement(targetElement);
        if (sourceParameter != null)
            return super.createLocalRenameElementContext(sourceParameter, editor, selection, resource);
    }
    return super.createLocalRenameElementContext(targetElement, editor, selection, resource);
}
Also used : IJavaElement(org.eclipse.jdt.core.IJavaElement) JvmIdentifiableElement(org.eclipse.xtext.common.types.JvmIdentifiableElement) JvmFormalParameter(org.eclipse.xtext.common.types.JvmFormalParameter) EObject(org.eclipse.emf.ecore.EObject) JvmTypeParameter(org.eclipse.xtext.common.types.JvmTypeParameter) JvmConstructor(org.eclipse.xtext.common.types.JvmConstructor) IMethod(org.eclipse.jdt.core.IMethod) URI(org.eclipse.emf.common.util.URI)

Example 74 with IMethod

use of org.eclipse.jdt.core.IMethod in project xtext-eclipse by eclipse.

the class CombinedJvmJdtRenameContextFactory method addDeclaringMethod.

protected void addDeclaringMethod(JvmIdentifiableElement jvmElement, IJavaElement javaElement, Map<URI, IJavaElement> jvm2javaElement) {
    try {
        IType declaringType = ((IMethod) javaElement).getDeclaringType();
        ITypeHierarchy typeHierarchy = declaringType.newSupertypeHierarchy(new NullProgressMonitor());
        MethodOverrideTester methodOverrideTester = new MethodOverrideTester(declaringType, typeHierarchy);
        IMethod declaringMethod = methodOverrideTester.findDeclaringMethod((IMethod) javaElement, true);
        if (declaringMethod != null)
            jvm2javaElement.put(EcoreUtil.getURI(jvmElement), declaringMethod);
        else
            jvm2javaElement.put(EcoreUtil.getURI(jvmElement), javaElement);
    } catch (JavaModelException e) {
        throw new RuntimeException(e);
    }
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) ITypeHierarchy(org.eclipse.jdt.core.ITypeHierarchy) JavaModelException(org.eclipse.jdt.core.JavaModelException) MethodOverrideTester(org.eclipse.jdt.internal.corext.util.MethodOverrideTester) IMethod(org.eclipse.jdt.core.IMethod) IType(org.eclipse.jdt.core.IType)

Example 75 with IMethod

use of org.eclipse.jdt.core.IMethod in project liferay-ide by liferay.

the class PortletURLHyperlinkDetector method detectHyperlinks.

public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) {
    IHyperlink[] retval = null;
    if (_shouldDetectHyperlinks(textViewer, region)) {
        IDocument document = textViewer.getDocument();
        int offset = region.getOffset();
        IDOMNode currentNode = DOMUtils.getNodeByOffset(document, offset);
        IRegion nodeRegion = new Region(currentNode.getStartOffset(), currentNode.getEndOffset() - currentNode.getStartOffset());
        if (_isActionURL(currentNode)) {
            Node name = currentNode.getAttributes().getNamedItem("name");
            if (name != null) {
                long modStamp = ((IDocumentExtension4) document).getModificationStamp();
                IFile file = DOMUtils.getFile(document);
                IMethod[] actionUrlMethods = null;
                if (file.equals(_lastFile) && (modStamp == _lastModStamp) && nodeRegion.equals(_lastNodeRegion)) {
                    actionUrlMethods = _lastActionUrlMethods;
                } else {
                    String nameValue = name.getNodeValue();
                    // search for this method in any portlet classes
                    actionUrlMethods = _findPortletMethods(document, nameValue);
                    _lastModStamp = modStamp;
                    _lastFile = file;
                    _lastNodeRegion = nodeRegion;
                    _lastActionUrlMethods = actionUrlMethods;
                }
                if (ListUtil.isNotEmpty(actionUrlMethods)) {
                    List<IHyperlink> links = new ArrayList<>();
                    for (IMethod method : actionUrlMethods) {
                        if (method.exists()) {
                            links.add(new BasicJavaElementHyperlink(nodeRegion, method));
                        }
                    }
                    if (ListUtil.isNotEmpty(links)) {
                        if (canShowMultipleHyperlinks) {
                            retval = links.toArray(new IHyperlink[0]);
                        } else {
                            retval = new IHyperlink[] { links.get(0) };
                        }
                    }
                }
            }
        }
    }
    return retval;
}
Also used : IFile(org.eclipse.core.resources.IFile) IDocumentExtension4(org.eclipse.jface.text.IDocumentExtension4) IDOMNode(org.eclipse.wst.xml.core.internal.provisional.document.IDOMNode) Node(org.w3c.dom.Node) ArrayList(java.util.ArrayList) IRegion(org.eclipse.jface.text.IRegion) IDOMNode(org.eclipse.wst.xml.core.internal.provisional.document.IDOMNode) IHyperlink(org.eclipse.jface.text.hyperlink.IHyperlink) Region(org.eclipse.jface.text.Region) IRegion(org.eclipse.jface.text.IRegion) IMethod(org.eclipse.jdt.core.IMethod) IDocument(org.eclipse.jface.text.IDocument)

Aggregations

IMethod (org.eclipse.jdt.core.IMethod)217 IType (org.eclipse.jdt.core.IType)112 IJavaElement (org.eclipse.jdt.core.IJavaElement)56 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)37 ArrayList (java.util.ArrayList)35 JavaModelException (org.eclipse.jdt.core.JavaModelException)32 RefactoringStatus (org.eclipse.ltk.core.refactoring.RefactoringStatus)29 IField (org.eclipse.jdt.core.IField)27 Test (org.junit.Test)22 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)19 ITypeHierarchy (org.eclipse.jdt.core.ITypeHierarchy)19 IMember (org.eclipse.jdt.core.IMember)15 SubProgressMonitor (org.eclipse.core.runtime.SubProgressMonitor)14 RenameJavaElementDescriptor (org.eclipse.jdt.core.refactoring.descriptors.RenameJavaElementDescriptor)13 IJavaProject (org.eclipse.jdt.core.IJavaProject)12 HashSet (java.util.HashSet)11 IPackageFragment (org.eclipse.jdt.core.IPackageFragment)10 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)10 ISourceRange (org.eclipse.jdt.core.ISourceRange)9 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)9