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

The following examples show how to use org.jboss.jandex.MethodInfo#annotation() . 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: ResteasyCommonProcessor.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private static boolean collectDeclaredProvidersForMethodAndMediaTypeAnnotation(Set<String> providersToRegister,
        MediaTypeMap<String> categorizedProviders, MethodInfo methodTarget, DotName mediaTypeAnnotation,
        boolean defaultsToAll) {
    AnnotationInstance mediaTypeAnnotationInstance = methodTarget.annotation(mediaTypeAnnotation);
    if (mediaTypeAnnotationInstance == null) {
        // let's consider the class
        Collection<AnnotationInstance> classAnnotations = methodTarget.declaringClass().classAnnotations();
        for (AnnotationInstance classAnnotation : classAnnotations) {
            if (mediaTypeAnnotation.equals(classAnnotation.name())) {
                if (collectDeclaredProvidersForMediaTypeAnnotationInstance(providersToRegister, categorizedProviders,
                        classAnnotation, methodTarget)) {
                    return true;
                }
                return false;
            }
        }
        return defaultsToAll;
    }
    if (collectDeclaredProvidersForMediaTypeAnnotationInstance(providersToRegister, categorizedProviders,
            mediaTypeAnnotationInstance, methodTarget)) {
        return true;
    }

    return false;
}
 
Example 2
Source File: PanacheRepositoryEnhancer.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public void visitEnd() {
    for (MethodInfo method : panacheRepositoryBaseClassInfo.methods()) {
        // Do not generate a method that already exists
        String descriptor = AsmUtil.getDescriptor(method, name -> typeArguments.get(name));
        if (!userMethods.contains(method.name() + "/" + descriptor)) {
            AnnotationInstance bridge = method.annotation(PanacheEntityEnhancer.DOTNAME_GENERATE_BRIDGE);
            if (bridge != null) {
                generateModelBridge(method, bridge.value("targetReturnTypeErased"));
                if (needsJvmBridge(method)) {
                    generateJvmBridge(method);
                }
            }
        }
    }
    super.visitEnd();
}
 
Example 3
Source File: PanacheEntityEnhancer.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public void visitEnd() {
    // FIXME: generate default constructor

    for (MethodInfo method : panacheEntityBaseClassInfo.methods()) {
        // Do not generate a method that already exists
        String descriptor = AsmUtil.getDescriptor(method, name -> null);
        if (!userMethods.contains(method.name() + "/" + descriptor)) {
            AnnotationInstance bridge = method.annotation(DOTNAME_GENERATE_BRIDGE);
            if (bridge != null) {
                generateMethod(method, bridge.value("targetReturnTypeErased"));
            }
        }
    }

    generateAccessors();

    super.visitEnd();
}
 
Example 4
Source File: QuarkusMediatorConfigurationUtil.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private static String getValue(MethodInfo methodInfo, DotName dotName) {
    AnnotationInstance annotationInstance = methodInfo.annotation(dotName);
    String value = null;

    if (annotationInstance != null) {
        if (annotationInstance.value() != null) {
            value = annotationInstance.value().asString();

        }
        if ((value == null) || value.isEmpty()) {
            throw new IllegalArgumentException(
                    "@" + dotName.withoutPackagePrefix() + " value cannot be blank. Offending method is: "
                            + fullMethodName(methodInfo));
        }

        // TODO: does it make sense to validate the name with the supplied configuration?
    }

    return value;
}
 
Example 5
Source File: JaxRsAnnotationScanner.java    From smallrye-open-api with Apache License 2.0 6 votes vote down vote up
static Optional<String[]> getMediaTypes(MethodInfo resourceMethod, DotName annotationName) {
    AnnotationInstance annotation = resourceMethod.annotation(annotationName);

    if (annotation == null) {
        annotation = JandexUtil.getClassAnnotation(resourceMethod.declaringClass(), annotationName);
    }

    if (annotation != null) {
        AnnotationValue annotationValue = annotation.value();

        if (annotationValue != null) {
            return Optional.of(annotationValue.asStringArray());
        }

        return Optional.of(OpenApiConstants.DEFAULT_MEDIA_TYPES.get());
    }

    return Optional.empty();
}
 
Example 6
Source File: SpringAnnotationScanner.java    From smallrye-open-api with Apache License 2.0 6 votes vote down vote up
static Optional<String[]> getMediaTypes(MethodInfo resourceMethod, MediaTypeProperty property) {
    Set<DotName> annotationNames = SpringConstants.HTTP_METHODS;

    for (DotName annotationName : annotationNames) {
        AnnotationInstance annotation = resourceMethod.annotation(annotationName);

        if (annotation == null || annotation.value(property.name()) == null) {
            annotation = JandexUtil.getClassAnnotation(resourceMethod.declaringClass(), SpringConstants.REQUEST_MAPPING);
        }

        if (annotation != null) {
            AnnotationValue annotationValue = annotation.value(property.name());

            if (annotationValue != null) {
                return Optional.of(annotationValue.asStringArray());
            }

            return Optional.of(OpenApiConstants.DEFAULT_MEDIA_TYPES.get());
        }
    }
    return Optional.empty();
}
 
Example 7
Source File: ResteasyCommonProcessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a collection of providers that are "inferred" based on certain rules applied to the passed
 * {@code mediaType}. Returns an empty collection if no providers were inferred.
 *
 * @param mediaType The MediaType to process
 * @param categorizedProviders Available providers that are categorized based on their media type. This map
 *        will be used to find possible providers that can be used for the passed
 *        {@code mediaType}
 * @return
 */
private static Collection<String> collectInferredProviders(final MediaType mediaType,
        final MediaTypeMap<String> categorizedProviders, final MethodInfo targetMethod) {

    // for SERVER_SENT_EVENTS media type, we do certain things:
    // - check if the @SseElementType (RestEasy) specific annotation is specified on the target.
    //   if it is, then include a provider which can handle that element type.
    // - if no @SseElementType is present, check if the media type has the "element-type" parameter
    //   and if it does then include the provider which can handle that element-type
    // - if neither of the above specifies an element-type then we by fallback to including text/plain
    //   provider as a default
    if (matches(MediaType.SERVER_SENT_EVENTS_TYPE, mediaType)) {
        final Set<String> additionalProvidersToRegister = new HashSet<>();
        // first check for @SseElementType
        final AnnotationInstance sseElementTypeAnnInst = targetMethod
                .annotation(ResteasyDotNames.RESTEASY_SSE_ELEMENT_TYPE);
        String elementType = null;
        if (sseElementTypeAnnInst != null) {
            elementType = sseElementTypeAnnInst.value().asString();
        } else if (mediaType.getParameters() != null
                && mediaType.getParameters().containsKey(SseConstants.SSE_ELEMENT_MEDIA_TYPE)) {
            // fallback on the MediaType parameter
            elementType = mediaType.getParameters().get(SseConstants.SSE_ELEMENT_MEDIA_TYPE);
        }
        if (elementType != null) {
            additionalProvidersToRegister.addAll(categorizedProviders.getPossible(MediaType.valueOf(elementType)));
        } else {
            // add text/plain provider as a fallback default for SSE mediatype
            additionalProvidersToRegister.addAll(categorizedProviders.getPossible(MediaType.TEXT_PLAIN_TYPE));
        }
        return additionalProvidersToRegister;
    }
    return Collections.emptySet();
}
 
Example 8
Source File: SpringScheduledProcessorTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void testBuildCronParam() {

    final MethodInfo target = index.getClassByName(DotName.createSimple(SpringScheduledMethodsBean.class.getName()))
            .method("checkEverySecondCron");
    AnnotationInstance annotation = target.annotation(SpringScheduledProcessor.SPRING_SCHEDULED);
    AnnotationValue annotationValue = springScheduledProcessor.buildCronParam(annotation.values());
    assertThat(annotationValue.name()).isEqualTo("cron");
    assertThat(annotationValue.value()).isEqualTo("0/1 * * * * ?");

}
 
Example 9
Source File: SpringScheduledProcessorTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void testBuildDelayParam() {

    final MethodInfo target = index.getClassByName(DotName.createSimple(BeanWithScheduledMethods.class.getName()))
            .method("checkEverySecondWithDelay");
    AnnotationInstance annotation = target.annotation(SpringScheduledProcessor.SPRING_SCHEDULED);
    List<AnnotationValue> annotationValues = springScheduledProcessor.buildDelayParams(annotation.values());
    AnnotationValue expectedDelayValue = AnnotationValue.createLongValue("delay", 1000L);
    AnnotationValue expectedDelayUnitValue = AnnotationValue.createEnumValue("delayUnit",
            DotName.createSimple("java.util.concurrent.TimeUnit"),
            TimeUnit.MILLISECONDS.name());
    assertThat(annotationValues).contains(expectedDelayValue);
    assertThat(annotationValues).contains(expectedDelayUnitValue);

}
 
Example 10
Source File: SpringScheduledProcessorTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void testBuildDelayParamFromString() {

    final MethodInfo target = index.getClassByName(DotName.createSimple(BeanWithScheduledMethods.class.getName()))
            .method("checkEverySecondWithDelayString");
    AnnotationInstance annotation = target.annotation(SpringScheduledProcessor.SPRING_SCHEDULED);
    List<AnnotationValue> annotationValues = springScheduledProcessor.buildDelayParams(annotation.values());
    AnnotationValue expectedDelayValue = AnnotationValue.createLongValue("delay", 1000L);
    AnnotationValue expectedDelayUnitValue = AnnotationValue.createEnumValue("delayUnit",
            DotName.createSimple("java.util.concurrent.TimeUnit"),
            TimeUnit.MILLISECONDS.name());
    assertThat(annotationValues).contains(expectedDelayValue);
    assertThat(annotationValues).contains(expectedDelayUnitValue);

}
 
Example 11
Source File: SpringScheduledProcessorTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void testBuildEveryParamFromInvalidFormat() {

    final MethodInfo target = index.getClassByName(DotName.createSimple(BeanWithScheduledMethods.class.getName()))
            .method("invalidFormatFixedRate");
    AnnotationInstance annotation = target.annotation(SpringScheduledProcessor.SPRING_SCHEDULED);
    try {
        springScheduledProcessor.buildEveryParam(annotation.values());
        fail();
    } catch (IllegalArgumentException expected) {

    }

}
 
Example 12
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 13
Source File: ResponseReader.java    From smallrye-open-api with Apache License 2.0 4 votes vote down vote up
public static AnnotationInstance getResponseAnnotation(final MethodInfo method) {
    return method.annotation(ResponseConstant.DOTNAME_API_RESPONSE);
}
 
Example 14
Source File: ResponseReader.java    From smallrye-open-api with Apache License 2.0 4 votes vote down vote up
public static AnnotationInstance getResponsesAnnotation(final MethodInfo method) {
    return method.annotation(ResponseConstant.DOTNAME_API_RESPONSES);
}
 
Example 15
Source File: ResponseReader.java    From smallrye-open-api with Apache License 2.0 4 votes vote down vote up
public static AnnotationInstance getResponseSchemaAnnotation(final MethodInfo method) {
    return method.annotation(ResponseConstant.DOTNAME_API_RESPONSE_SCHEMA);
}
 
Example 16
Source File: ExtensionMethodGenerator.java    From quarkus with Apache License 2.0 4 votes vote down vote up
public void generate(MethodInfo method, String matchName, Integer priority) {

        // Validate the method first
        validate(method);
        ClassInfo declaringClass = method.declaringClass();
        AnnotationInstance extensionAnnotation = method.annotation(TEMPLATE_EXTENSION);

        if (matchName == null && extensionAnnotation != null) {
            // No explicit name defined, try annotation
            AnnotationValue matchNameValue = extensionAnnotation.value(MATCH_NAME);
            if (matchNameValue != null) {
                matchName = matchNameValue.asString();
            }
        }
        if (matchName == null || matchName.equals(TemplateExtension.METHOD_NAME)) {
            matchName = method.name();
        }
        List<Type> parameters = method.parameters();
        if (matchName.equals(TemplateExtension.ANY)) {
            // Special constant used - the second parameter must be a string
            if (parameters.size() < 2 || !parameters.get(1).name().equals(STRING)) {
                throw new IllegalStateException(
                        "Template extension method matching multiple names must declare at least two parameters and the second parameter must be string: "
                                + method);
            }
        }

        if (priority == null && extensionAnnotation != null) {
            // No explicit priority set, try annotation
            AnnotationValue priorityValue = extensionAnnotation.value(PRIORITY);
            if (priorityValue != null) {
                priority = priorityValue.asInt();
            }
        }
        if (priority == null) {
            priority = TemplateExtension.DEFAULT_PRIORITY;
        }

        String baseName;
        if (declaringClass.enclosingClass() != null) {
            baseName = simpleName(declaringClass.enclosingClass()) + ValueResolverGenerator.NESTED_SEPARATOR
                    + simpleName(declaringClass);
        } else {
            baseName = simpleName(declaringClass);
        }
        String targetPackage = packageName(declaringClass.name());

        String suffix = SUFFIX + "_" + method.name() + "_" + sha1(parameters.toString());
        String generatedName = generatedNameFromTarget(targetPackage, baseName, suffix);
        generatedTypes.add(generatedName.replace('/', '.'));

        ClassCreator valueResolver = ClassCreator.builder().classOutput(classOutput).className(generatedName)
                .interfaces(ValueResolver.class).build();

        implementGetPriority(valueResolver, priority);
        implementAppliesTo(valueResolver, method, matchName);
        implementResolve(valueResolver, declaringClass, method, matchName);

        valueResolver.close();
    }
 
Example 17
Source File: OperationReader.java    From smallrye-open-api with Apache License 2.0 4 votes vote down vote up
public static AnnotationInstance getOperationAnnotation(final MethodInfo method) {
    return method.annotation(OperationConstant.DOTNAME_OPERATION);
}
 
Example 18
Source File: SmallRyeMetricsProcessor.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@BuildStep
@Record(RUNTIME_INIT)
void registerMetricsFromProducers(
        SmallRyeMetricsRecorder recorder,
        ValidationPhaseBuildItem validationPhase,
        BeanArchiveIndexBuildItem beanArchiveIndex) {
    IndexView index = beanArchiveIndex.getIndex();
    for (io.quarkus.arc.processor.BeanInfo bean : validationPhase.getContext().beans().producers()) {
        ClassInfo implClazz = bean.getImplClazz();
        if (implClazz == null) {
            continue;
        }
        MetricType metricType = getMetricType(implClazz);
        if (metricType != null) {
            AnnotationTarget target = bean.getTarget().get();
            AnnotationInstance metricAnnotation = null;
            String memberName = null;
            if (bean.isProducerField()) {
                FieldInfo field = target.asField();
                metricAnnotation = field.annotation(METRIC);
                memberName = field.name();
            }
            if (bean.isProducerMethod()) {
                MethodInfo method = target.asMethod();
                metricAnnotation = method.annotation(METRIC);
                memberName = method.name();
            }
            if (metricAnnotation != null) {
                String nameValue = metricAnnotation.valueWithDefault(index, "name").asString();
                boolean absolute = metricAnnotation.valueWithDefault(index, "absolute").asBoolean();
                String metricSimpleName = !nameValue.isEmpty() ? nameValue : memberName;
                String declaringClassName = bean.getDeclaringBean().getImplClazz().name().toString();
                String metricsFinalName = absolute ? metricSimpleName
                        : MetricRegistry.name(declaringClassName, metricSimpleName);
                recorder.registerMetricFromProducer(
                        bean.getIdentifier(),
                        metricType,
                        metricsFinalName,
                        metricAnnotation.valueWithDefault(index, "tags").asStringArray(),
                        metricAnnotation.valueWithDefault(index, "description").asString(),
                        metricAnnotation.valueWithDefault(index, "displayName").asString(),
                        metricAnnotation.valueWithDefault(index, "unit").asString());
            }
        }
    }
}
 
Example 19
Source File: OperationReader.java    From smallrye-open-api with Apache License 2.0 4 votes vote down vote up
public static boolean operationIsHidden(final MethodInfo method) {
    AnnotationInstance operationAnnotation = method.annotation(OperationConstant.DOTNAME_OPERATION);
    // If the operation is marked as hidden, just bail here because we don't want it as part of the model.
    return operationAnnotation.value(OperationConstant.PROP_HIDDEN) != null
            && operationAnnotation.value(OperationConstant.PROP_HIDDEN).asBoolean();
}
 
Example 20
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);
    }
}