Java Code Examples for org.jboss.jandex.MethodInfo#hasAnnotation()

The following examples show how to use org.jboss.jandex.MethodInfo#hasAnnotation() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MethodValidatedAnnotationsTransformer.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private boolean requiresValidation(MethodInfo method) {
    if (method.annotations().isEmpty()) {
        // This method has no annotations of its own: look for inherited annotations
        ClassInfo clazz = method.declaringClass();
        String methodName = method.name().toString();
        for (Map.Entry<DotName, Set<String>> validatedMethod : inheritedAnnotationsToBeValidated.entrySet()) {
            if (clazz.interfaceNames().contains(validatedMethod.getKey())
                    && validatedMethod.getValue().contains(methodName)) {
                return true;
            }
        }
        return false;
    }

    for (DotName consideredAnnotation : consideredAnnotations) {
        if (method.hasAnnotation(consideredAnnotation)) {
            return true;
        }
    }

    return false;
}
 
Example 2
Source File: JaxRsAnnotationScanner.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Process the JAX-RS Operation methods
 * 
 * @param context the scanning context
 * @param resourceClass the class containing the methods
 * @param openApi the OpenApi model being processed
 * @param locatorPathParameters path parameters
 */
private void processResourceMethods(final AnnotationScannerContext context,
        final ClassInfo resourceClass,
        OpenAPI openApi,
        List<Parameter> locatorPathParameters) {

    // Process tags (both declarations and references).
    Set<String> tagRefs = processTags(resourceClass, openApi, false);

    // Process exception mapper to auto generate api response based on method exceptions
    Map<DotName, AnnotationInstance> exceptionAnnotationMap = processExceptionMappers(context);

    for (MethodInfo methodInfo : getResourceMethods(context, resourceClass)) {
        final AtomicInteger resourceCount = new AtomicInteger(0);

        JaxRsConstants.HTTP_METHODS
                .stream()
                .filter(methodInfo::hasAnnotation)
                .map(DotName::withoutPackagePrefix)
                .map(PathItem.HttpMethod::valueOf)
                .forEach(httpMethod -> {
                    resourceCount.incrementAndGet();
                    processResourceMethod(context, resourceClass, methodInfo, httpMethod, openApi, tagRefs,
                            locatorPathParameters, exceptionAnnotationMap);
                });

        if (resourceCount.get() == 0 && methodInfo.hasAnnotation(JaxRsConstants.PATH)) {
            processSubResource(context, resourceClass, methodInfo, openApi, locatorPathParameters);
        }
    }
}
 
Example 3
Source File: SpringAnnotationScanner.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isPostMethod(final MethodInfo method) {
    if (hasRequestMappingMethod(method, RequestMethod.POST)) {
        return true;
    }
    return method.hasAnnotation(SpringConstants.POST_MAPPING);

}
 
Example 4
Source File: SpringAnnotationScanner.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isDeleteMethod(final MethodInfo method) {
    if (hasRequestMappingMethod(method, RequestMethod.DELETE)) {
        return true;
    }
    return method.hasAnnotation(SpringConstants.DELETE_MAPPING);
}
 
Example 5
Source File: SpringAnnotationScanner.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
private boolean hasRequestMappingMethod(final MethodInfo method, final RequestMethod requestMethod) {
    if (method.hasAnnotation(SpringConstants.REQUEST_MAPPING)) {
        AnnotationInstance annotation = method.annotation(SpringConstants.REQUEST_MAPPING);
        AnnotationValue value = annotation.value("method");
        return value != null && value.asEnumArray().length > 0
                && Arrays.asList(value.asEnumArray()).contains(requestMethod.name());
    }
    return false;
}
 
Example 6
Source File: ResponseReader.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
public static boolean hasResponseCodeValue(final MethodInfo method) {
    if (method.hasAnnotation(ResponseConstant.DOTNAME_API_RESPONSE)) {
        AnnotationInstance annotation = getResponseAnnotation(method);
        return annotation.value(ResponseConstant.PROP_RESPONSE_CODE) != null;
    }
    return false;
}
 
Example 7
Source File: Beans.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private static void collectCallbacks(ClassInfo clazz, List<MethodInfo> callbacks, DotName annotation, IndexView index) {
    for (MethodInfo method : clazz.methods()) {
        if (method.hasAnnotation(annotation) && method.returnType().kind() == Kind.VOID && method.parameters().isEmpty()) {
            callbacks.add(method);
        }
    }
    if (clazz.superName() != null) {
        ClassInfo superClass = getClassByName(index, clazz.superName());
        if (superClass != null) {
            collectCallbacks(superClass, callbacks, annotation, index);
        }
    }
}
 
Example 8
Source File: MethodValidatedAnnotationsTransformer.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private boolean isJaxrsMethod(MethodInfo method) {
    for (DotName jaxrsMethodAnnotation : effectiveJaxRsMethodDefiningAnnotations) {
        if (method.hasAnnotation(jaxrsMethodAnnotation)) {
            return true;
        }
    }
    return false;
}
 
Example 9
Source File: JaxRsAnnotationScanner.java    From smallrye-open-api with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isPostMethod(final MethodInfo method) {
    return method.hasAnnotation(JaxRsConstants.POST);
}
 
Example 10
Source File: JaxRsAnnotationScanner.java    From smallrye-open-api with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isDeleteMethod(final MethodInfo method) {
    return method.hasAnnotation(JaxRsConstants.DELETE);
}
 
Example 11
Source File: OperationReader.java    From smallrye-open-api with Apache License 2.0 4 votes vote down vote up
public static boolean methodHasOperationAnnotation(final MethodInfo method) {
    return method.hasAnnotation(OperationConstant.DOTNAME_OPERATION);
}
 
Example 12
Source File: InterceptorInfo.java    From quarkus with Apache License 2.0 4 votes vote down vote up
/**
 *
 * @param target
 * @param beanDeployment
 * @param bindings
 * @param injections
 */
InterceptorInfo(AnnotationTarget target, BeanDeployment beanDeployment, Set<AnnotationInstance> bindings,
        List<Injection> injections, int priority) {
    super(target, beanDeployment, BuiltinScope.DEPENDENT.getInfo(),
            Collections.singleton(Type.create(target.asClass().name(), Kind.CLASS)), new HashSet<>(), injections,
            null, null, null, Collections.emptyList(), null, false);
    this.bindings = bindings;
    this.priority = priority;
    MethodInfo aroundInvoke = null;
    MethodInfo aroundConstruct = null;
    MethodInfo postConstruct = null;
    MethodInfo preDestroy = null;
    for (MethodInfo method : target.asClass().methods()) {
        if (aroundInvoke == null && method.hasAnnotation(DotNames.AROUND_INVOKE)) {
            aroundInvoke = method;
        } else if (method.hasAnnotation(DotNames.AROUND_CONSTRUCT)) {
            // validate compliance with rules for AroundConstruct methods
            if (!method.parameters().equals(Collections.singletonList(
                    Type.create(DotName.createSimple("javax.interceptor.InvocationContext"), Type.Kind.CLASS)))) {
                throw new IllegalStateException(
                        "@AroundConstruct must have exactly one argument of type javax.interceptor.InvocationContext, but method "
                                + method.asMethod() + " declared by " + method.declaringClass()
                                + " violates this.");
            }
            if (!method.returnType().kind().equals(Type.Kind.VOID) &&
                    !method.returnType().name().equals(DotNames.OBJECT)) {
                throw new IllegalStateException("Return type of @AroundConstruct method must be Object or void, but method "
                        + method.asMethod() + " declared by " + method.declaringClass()
                        + " violates this.");
            }
            aroundConstruct = method;
        } else if (postConstruct == null && method.hasAnnotation(DotNames.POST_CONSTRUCT)) {
            postConstruct = method;
        } else if (preDestroy == null && method.hasAnnotation(DotNames.PRE_DESTROY)) {
            preDestroy = method;
        }
    }
    this.aroundInvoke = aroundInvoke;
    this.aroundConstruct = aroundConstruct;
    this.postConstruct = postConstruct;
    this.preDestroy = preDestroy;
    if (aroundConstruct == null && aroundInvoke == null && preDestroy == null && postConstruct == null) {
        LOGGER.warnf("%s declares no around-invoke method nor a lifecycle callback!", this);
    }
}
 
Example 13
Source File: ResteasyServerCommonProcessor.java    From quarkus with Apache License 2.0 4 votes vote down vote up
private Set<DotName> findSubresources(IndexView index, Map<DotName, ClassInfo> scannedResources) {
    // First identify sub-resource candidates
    Set<DotName> subresources = new HashSet<>();
    for (DotName annotation : METHOD_ANNOTATIONS) {
        Collection<AnnotationInstance> annotationInstances = index.getAnnotations(annotation);
        for (AnnotationInstance annotationInstance : annotationInstances) {
            DotName declaringClassName = annotationInstance.target().asMethod().declaringClass().name();
            if (scannedResources.containsKey(declaringClassName)) {
                // Skip resource classes
                continue;
            }
            subresources.add(declaringClassName);
        }
    }
    if (!subresources.isEmpty()) {
        // Collect sub-resource locator return types
        Set<DotName> subresourceLocatorTypes = new HashSet<>();
        for (ClassInfo resourceClass : scannedResources.values()) {
            ClassInfo clazz = resourceClass;
            while (clazz != null) {
                for (MethodInfo method : clazz.methods()) {
                    if (method.hasAnnotation(ResteasyDotNames.PATH)) {
                        subresourceLocatorTypes.add(method.returnType().name());
                    }
                }
                if (clazz.superName().equals(DotNames.OBJECT)) {
                    clazz = null;
                } else {
                    clazz = index.getClassByName(clazz.superName());
                }
            }
        }
        // Remove false positives
        for (Iterator<DotName> iterator = subresources.iterator(); iterator.hasNext();) {
            DotName subresource = iterator.next();
            for (DotName type : subresourceLocatorTypes) {
                // Sub-resource may be a subclass of a locator return type
                if (!subresource.equals(type)
                        && index.getAllKnownSubclasses(type).stream().noneMatch(c -> c.name().equals(subresource))) {
                    iterator.remove();
                    break;
                }
            }
        }
    }
    log.trace("Sub-resources found: " + subresources);
    return subresources;
}
 
Example 14
Source File: SmallRyeReactiveMessagingProcessor.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@BuildStep
@Record(STATIC_INIT)
public void build(SmallRyeReactiveMessagingRecorder recorder, RecorderContext recorderContext,
        BeanContainerBuildItem beanContainer,
        List<MediatorBuildItem> mediatorMethods,
        List<EmitterBuildItem> emitterFields,
        BuildProducer<GeneratedClassBuildItem> generatedClass,
        BuildProducer<ReflectiveClassBuildItem> reflectiveClass,
        ReactiveMessagingConfiguration conf) {

    List<QuarkusMediatorConfiguration> configurations = new ArrayList<>(mediatorMethods.size());

    ClassOutput classOutput = new GeneratedClassGizmoAdaptor(generatedClass, true);

    /*
     * Go through the collected MediatorMethods and build up the corresponding MediaConfiguration
     * This includes generating an invoker for each method
     * The configuration will then be captured and used at static init time to push data into smallrye
     */
    for (MediatorBuildItem mediatorMethod : mediatorMethods) {
        MethodInfo methodInfo = mediatorMethod.getMethod();
        BeanInfo bean = mediatorMethod.getBean();

        String generatedInvokerName = generateInvoker(bean, methodInfo, classOutput);
        /*
         * We need to register the invoker's constructor for reflection since it will be called inside smallrye.
         * We could potentially lift this restriction with some extra CDI bean generation but it's probably not worth it
         */
        reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, generatedInvokerName));

        if (methodInfo.hasAnnotation(ReactiveMessagingDotNames.BLOCKING)) {
            AnnotationInstance blocking = methodInfo.annotation(ReactiveMessagingDotNames.BLOCKING);
            String poolName = blocking.value() == null ? Blocking.DEFAULT_WORKER_POOL : blocking.value().asString();

            recorder.configureWorkerPool(beanContainer.getValue(), methodInfo.declaringClass().toString(),
                    methodInfo.name(), poolName);
        }

        try {
            QuarkusMediatorConfiguration mediatorConfiguration = QuarkusMediatorConfigurationUtil
                    .create(methodInfo, bean,
                            generatedInvokerName, recorderContext,
                            Thread.currentThread().getContextClassLoader());
            configurations.add(mediatorConfiguration);
        } catch (IllegalArgumentException e) {
            throw new DeploymentException(e); // needed to pass the TCK
        }
    }
    recorder.registerMediators(configurations, beanContainer.getValue());

    for (EmitterBuildItem it : emitterFields) {
        Config config = ConfigProvider.getConfig();
        int defaultBufferSize = config.getOptionalValue("mp.messaging.emitter.default-buffer-size", Integer.class)
                .orElseGet(new Supplier<Integer>() {
                    @Override
                    public Integer get() {
                        return config
                                .getOptionalValue("smallrye.messaging.emitter.default-buffer-size", Integer.class)
                                .orElse(127);
                    }
                });
        recorder.configureEmitter(beanContainer.getValue(), it.getEmitterConfig(), defaultBufferSize);
    }
}
 
Example 15
Source File: ParameterProcessor.java    From smallrye-open-api with Apache License 2.0 3 votes vote down vote up
/**
 * Determines if the given method is a JAX-RS sub-resource locator method
 * annotated by {@code @Path} but NOT annotated with one of the HTTP method
 * annotations.
 *
 * @param method method to check
 * @return true if the method is JAX-RS sub-resource locator, false otherwise
 */
boolean isSubResourceLocator(MethodInfo method) {
    return method.returnType().kind() == Type.Kind.CLASS &&
            method.hasAnnotation(JaxRsConstants.PATH) &&
            method.annotations().stream()
                    .map(AnnotationInstance::name)
                    .noneMatch(JaxRsConstants.HTTP_METHODS::contains);
}