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

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

Introduction

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

Prototype

int METHOD

To view the source code for org.eclipse.jdt.core IJavaElement METHOD.

Click Source Link

Document

Constant representing a method or constructor.

Usage

From source file:org.jboss.tools.ws.jaxrs.core.jdt.JavaMethodSignaturesVisitor.java

License:Open Source License

@Override
public boolean visit(MethodDeclaration declaration) {
    try {//w  w w .  ja v a  2 s  .  co  m
        final IJavaElement element = compilationUnit.getElementAt(declaration.getStartPosition());
        if (element == null || element.getElementType() != IJavaElement.METHOD) {
            return true;
        }
        IMethod method = (IMethod) element;
        if (this.method != null && !this.method.getHandleIdentifier().equals(method.getHandleIdentifier())) {
            return true;
        }

        final IMethodBinding methodBinding = declaration.resolveBinding();
        // sometimes, the binding cannot be resolved
        if (methodBinding == null) {
            Logger.debug("Could not resolve bindings form method " + method.getElementName());
        } else {
            final IType returnedType = getReturnType(methodBinding);
            //.getReturnType().getJavaElement() : null;
            List<JavaMethodParameter> methodParameters = new ArrayList<JavaMethodParameter>();
            @SuppressWarnings("unchecked")
            List<SingleVariableDeclaration> parameters = declaration.parameters();
            for (int i = 0; i < parameters.size(); i++) {
                final SingleVariableDeclaration parameter = parameters.get(i);
                final String paramName = parameter.getName().getFullyQualifiedName();
                final IVariableBinding paramBinding = parameter.resolveBinding();
                final String paramTypeName = paramBinding.getType().getQualifiedName();
                final List<Annotation> paramAnnotations = new ArrayList<Annotation>();
                final IAnnotationBinding[] annotationBindings = paramBinding.getAnnotations();
                for (int j = 0; j < annotationBindings.length; j++) {
                    final ILocalVariable localVariable = method.getParameters()[i];
                    final IAnnotation javaAnnotation = localVariable.getAnnotations()[j];
                    final IAnnotationBinding javaAnnotationBinding = annotationBindings[j];
                    paramAnnotations.add(BindingUtils.toAnnotation(javaAnnotationBinding, javaAnnotation));
                }
                //final ISourceRange sourceRange = new SourceRange(parameter.getStartPosition(), parameter.getLength());
                methodParameters.add(new JavaMethodParameter(paramName, paramTypeName, paramAnnotations));
            }

            // TODO : add support for thrown exceptions
            this.methodSignatures.add(new JavaMethodSignature(method, returnedType, methodParameters));
        }
    } catch (JavaModelException e) {
        Logger.error("Failed to analyse compilation unit methods", e);
    }
    return true;
}

From source file:org.jboss.tools.ws.jaxrs.core.jdt.JaxrsAnnotationsScanner.java

License:Open Source License

/**
 * Search for methods annotated with one of the given annotations, in the search scope.
 * /*from  w w w .  ja  v a 2 s.  c  o m*/
 * @param annotationNames
 *            the annotations fully qualified names
 * @param searchScope
 *            the search scope
 * @param progressMonitor
 *            the progress monitor
 * @return the matching methods
 * @throws CoreException
 *             in case of underlying exception
 */
private static List<IMethod> searchForAnnotatedMethods(final List<String> annotationNames,
        final IJavaSearchScope searchScope, final IProgressMonitor progressMonitor) throws CoreException {
    JavaMemberSearchResultCollector collector = new JavaMemberSearchResultCollector(IJavaElement.METHOD,
            searchScope);
    SearchPattern pattern = null;
    for (String annotationName : annotationNames) {
        // TODO : apply on METHOD instead of TYPE ?
        SearchPattern subPattern = SearchPattern.createPattern(annotationName,
                IJavaSearchConstants.ANNOTATION_TYPE, IJavaSearchConstants.ANNOTATION_TYPE_REFERENCE,
                SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE);
        if (pattern == null) {
            pattern = subPattern;
        } else {
            pattern = SearchPattern.createOrPattern(pattern, subPattern);
        }
    }
    // perform search, results are added/filtered by the custom
    // searchRequestor defined above
    new SearchEngine().search(pattern, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() },
            searchScope, collector, progressMonitor);
    // FIXME : wrong scope : returns all the annotated resourceMethods of
    // the enclosing type
    return collector.getResult(IMethod.class);
}

From source file:org.jboss.tools.ws.jaxrs.core.jdt.JdtUtils.java

License:Open Source License

/**
 * Finds the declaring {@link ASTNode} for the given {@link IMember}, using
 * the {@link NodeFinder} if the member was not resolved.
 * //ww  w. j a v  a2  s.com
 * @param member
 *            the member to find
 * @param ast
 *            the Compilation Unit
 * @return the associated declaring node
 * @throws JavaModelException
 */
private static ASTNode findDeclaringNode(final IMember member, final CompilationUnit ast)
        throws JavaModelException {
    switch (member.getElementType()) {
    case IJavaElement.TYPE:
        final IType type = (IType) member;
        if (type.isResolved()) {
            final ASTNode typeNode = ast.findDeclaringNode(type.getKey());
            // return if match found
            if (typeNode != null) {
                return typeNode;
            }
        }
        break;
    case IJavaElement.METHOD:
        final IMethod method = (IMethod) member;
        if (method.isResolved()) {
            final ASTNode methodNode = ast.findDeclaringNode(method.getKey());
            // return if match found
            if (methodNode != null) {
                return methodNode;
            }
        }
        break;
    case IJavaElement.FIELD:
        final IField field = (IField) member;
        if (field.isResolved()) {
            // in the case of a Field, the
            // CompilationUnit#findDeclaringNode(String key) method returns
            // a VariableDeclarationFragment in a FieldDeclaration
            final ASTNode variableDeclarationFragment = ast.findDeclaringNode(field.getKey());
            if (variableDeclarationFragment != null) {
                final ASTNode fieldNode = variableDeclarationFragment.getParent();
                if (fieldNode != null) {
                    // return if match found
                    return fieldNode;
                }
            }
        }
        break;
    default:
    }
    // fallback approach if everything above failed.
    final NodeFinder finder = new NodeFinder(ast, member.getSourceRange().getOffset(),
            member.getSourceRange().getLength());
    return finder.getCoveredNode();
}

From source file:org.jboss.tools.ws.jaxrs.core.jdt.JdtUtilsTestCase.java

License:Open Source License

@Test
public void shouldRetrieveMethodAtLocation() throws CoreException {
    // preconditions
    final IType customerType = projectMonitor
            .resolveType("org.jboss.tools.ws.jaxrs.sample.services.CustomerResource");
    final IMethod method = projectMonitor.resolveMethod(customerType, "getCustomer");
    // operation/* w w w. j av a  2 s .  c  om*/
    final IJavaElement element = JdtUtils.getElementAt(customerType.getCompilationUnit(),
            method.getSourceRange().getOffset(), IJavaElement.METHOD);
    // verification
    assertThat(element, notNullValue());
    assertThat((IMethod) element, equalTo(method));

}

From source file:org.jboss.tools.ws.jaxrs.core.jdt.MemberValuePairLocationRetriever.java

License:Open Source License

/**
 * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.MethodInvocation)
 *///from w  w  w .  j a v  a  2s  . co  m
@Override
public boolean visit(MethodDeclaration node) {
    final IJavaElement ancestor = javaAnnotation.getAncestor(IJavaElement.METHOD);
    if (ancestor != null && ancestor.exists()
            && ancestor.getElementName().equals(node.getName().getFullyQualifiedName())) {
        // keep searching
        return true;
    }
    // wrong path, stop searching from this branch of the AST
    return false;
}

From source file:org.jboss.tools.ws.jaxrs.ui.contentassist.PathParamAnnotationValueCompletionProposalComputer.java

License:Open Source License

/** {@inheritDoc} */
@Override// w  ww .  ja v a 2 s  .c  om
public final List<ICompletionProposal> computeCompletionProposals(final ContentAssistInvocationContext context,
        final IProgressMonitor monitor) {
    if (context instanceof JavaContentAssistInvocationContext) {
        final JavaContentAssistInvocationContext javaContext = (JavaContentAssistInvocationContext) context;
        try {
            final IJavaProject project = javaContext.getProject();
            final IJaxrsMetamodel metamodel = JaxrsMetamodelLocator.get(project);
            // skip if the JAX-RS Nature is not configured for this project
            if (metamodel == null) {
                return Collections.emptyList();
            }
            synchronized (metamodel) {
                final int invocationOffset = context.getInvocationOffset();
                final ICompilationUnit compilationUnit = javaContext.getCompilationUnit();
                final Annotation annotation = JdtUtils.resolveAnnotationAt(invocationOffset, compilationUnit);
                if (annotation != null && annotation.getFullyQualifiedName().equals(PATH_PARAM)) {
                    final IJavaElement javaMethod = annotation.getJavaAnnotation()
                            .getAncestor(IJavaElement.METHOD);
                    final IJaxrsResourceMethod resourceMethod = (IJaxrsResourceMethod) metamodel
                            .findElement(javaMethod);
                    if (resourceMethod != null) {
                        return internalComputePathParamProposals(javaContext, resourceMethod);
                    }
                }
            }

        } catch (Exception e) {
            Logger.error("Failed to compute completion proposal", e);
        }
    }
    return Collections.emptyList();
}

From source file:org.limy.eclipse.code.javadoc.LimyAddJavadocOperation.java

License:Open Source License

/**
 * ?oJavadocR?g???B//from w w w .j  av a2  s  .  co  m
 * @param member ?o
 * @param lineDelim f~^
 * @return ?oJavadocR?g
 * @throws CoreException RAO
 */
private String createComment(IMember member, String lineDelim) throws CoreException {

    String comment = null;
    switch (member.getElementType()) {
    case IJavaElement.TYPE:
        comment = createTypeComment((IType) member, lineDelim);
        break;
    case IJavaElement.FIELD:
        comment = createFieldComment((IField) member);
        break;
    case IJavaElement.METHOD:
        comment = createMethodComment((IMethod) member, lineDelim);
        break;
    default:
        break;
    }

    if (comment == null) {
        // K?Javadoc?????AJavadoc`??
        StringBuilder buf = new StringBuilder();
        buf.append("/**").append(lineDelim); //$NON-NLS-1$
        buf.append(" *").append(lineDelim); //$NON-NLS-1$
        buf.append(" */").append(lineDelim); //$NON-NLS-1$
        comment = buf.toString();
    } else {
        // ?f~^?I
        if (!comment.endsWith(lineDelim)) {
            comment = comment + lineDelim;
        }
    }
    return comment;
}

From source file:org.limy.eclipse.common.jdt.LimyJavaUtils.java

License:Open Source License

/**
 * javaElement SJavat@C? results i[?B/*from   w w  w. j  a  v  a 2s . c  o  m*/
 * @param results i[?
 * @param javaElement ?[gJavavf
 * @param visitor IJavaResourceVisitor
 * @throws CoreException RAO
 */
public static void appendAllJavas(Collection<IJavaElement> results, IJavaElement javaElement)
        throws CoreException {

    if (javaElement == null || javaElement.getResource() == null) {
        // JarG?g???Aresource = null 
        return;
    }

    // Javav?WFNg?A\?[XpX?AJavapbP?[W
    appendForIParent(results, javaElement/*, visitor*/);

    // JavapbP?[WTupbP?[W
    if (javaElement instanceof IPackageFragment) {
        appendForIPackageFragment(results, (IPackageFragment) javaElement/*, visitor*/);
    }

    // JavaNX?A?\bh`?AtB?[h`
    int type = javaElement.getElementType();
    if (type == IJavaElement.IMPORT_DECLARATION || type == IJavaElement.PACKAGE_DECLARATION
            || type == IJavaElement.COMPILATION_UNIT || type == IJavaElement.TYPE || type == IJavaElement.METHOD
            || type == IJavaElement.FIELD) {

        results.add(javaElement);
    }
}

From source file:org.limy.eclipse.qalab.mark.cobertura.CoberturaMarkAppender.java

License:Open Source License

/**
 * eXg\?[X}?[J?[?B/*w w  w  .ja  va 2s .  co  m*/
 * @param env 
 * @param resources \?[X
 * @param testResults eXg
 * @throws IOException I/OO
 * @throws CoreException RAO
 */
public void addTestResultMarker(LimyQalabEnvironment env, IResource[] resources, Collection<Result> testResults)
        throws IOException, CoreException {

    this.env = env;
    // ?seXgP?[Xi[\?[XS?[v
    for (IResource resource : resources) {

        // eXgP?[XJavaNX
        String testClassName = QalabResourceUtils.getQualifiedTestClassName(env, resource);

        // eXgP?[X\?[X
        IResource testResource = QalabResourceUtils.getJavaResource(env, testClassName, false);

        if (testResource != null && testResource.exists()) {
            documentMap.put(testClassName, QalabResourceUtils.parseDocument(testResource));
            // failureerror}?[J?[??
            testResource.deleteMarkers(LimyQalabMarker.TEST_ID, true, IResource.DEPTH_INFINITE);
        }
    }

    for (Result result : testResults) {
        markFailures(result.getFailures(), false);
    }

    // ??\bh}?[LO
    for (IResource resource : resources) {

        // eXgP?[XJavaNX
        String testClassName = QalabResourceUtils.getQualifiedTestClassName(env, resource);

        IType type = env.getJavaProject().findType(testClassName);
        if (type != null) {
            for (IJavaElement el : type.getChildren()) {
                if (el.getElementType() == IJavaElement.METHOD && !failMethods.contains(el)) {
                    IMethod method = (IMethod) el;
                    IRegion region = getRegion(method);
                    if (region != null) {
                        markSuccess(method, region, documentMap.get(testClassName));
                    }
                }
            }
        }
    }

}

From source file:org.limy.eclipse.qalab.mark.cobertura.CoberturaMarkAppender.java

License:Open Source License

/**
 * @param failures G?[/*w ww.  j  a v  a2  s . c  o m*/
 * @param isError true: error, false: failure
 * @throws CoreException RAO
 */
private void markFailures(List<Failure> failures, boolean isError) throws CoreException {

    for (Failure failure : failures) {

        // faileXgNX?\bh
        String header = failure.getTestHeader();
        Matcher matcher = PATTERN_HEADER.matcher(header);

        String testClassName = header;
        String testMethodName = header;

        if (matcher.matches()) {
            testClassName = matcher.group(2);
            testMethodName = matcher.group(1);
        }

        // eXg?\bhfailMathods
        IMethod targetMethod = null;
        IType type = env.getJavaProject().findType(testClassName);
        for (IJavaElement el : type.getChildren()) {
            if (el.getElementType() == IJavaElement.METHOD && testMethodName.equals(el.getElementName())) {
                targetMethod = (IMethod) el;
                failMethods.add(el);
            }
        }

        if (targetMethod != null) {
            IRegion region = getRegion(targetMethod);
            if (region != null) {
                markFailure(targetMethod.getResource(), region, documentMap.get(testClassName), isError,
                        failure);
            }
        }
    }
}