org.jboss.jandex.MethodInfo Java Examples

The following examples show how to use org.jboss.jandex.MethodInfo. 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: JpaSecurityDefinition.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private static MethodInfo findGetter(Index index, ClassInfo annotatedClass, String methodName) {
    MethodInfo method = annotatedClass.method(methodName);
    if (method != null) {
        return method;
    }
    DotName superName = annotatedClass.superName();
    if (superName != null && !superName.equals(QuarkusSecurityJpaProcessor.DOTNAME_OBJECT)) {
        ClassInfo superClass = index.getClassByName(superName);
        if (superClass != null) {
            method = findGetter(index, superClass, methodName);
            if (method != null) {
                return method;
            }
        }
    }
    for (DotName interfaceName : annotatedClass.interfaceNames()) {
        ClassInfo interf = index.getClassByName(interfaceName);
        if (interf != null) {
            method = findGetter(index, interf, methodName);
            if (method != null) {
                return method;
            }
        }
    }
    return null;
}
 
Example #2
Source File: SpringDIProcessorTest.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Test
public void getAnnotationsToAddBeanMethodDefaultsToSingleton() {
    final Map<DotName, Set<DotName>> scopes = processor.getStereotypeScopes(index);
    final MethodInfo target = index.getClassByName(DotName.createSimple(BeanConfig.class.getName()))
            .method("singletonBean");

    final Set<AnnotationInstance> ret = processor.getAnnotationsToAdd(target, scopes, null);

    final Set<AnnotationInstance> expected = setOf(
            AnnotationInstance.create(DotName.createSimple(Singleton.class.getName()), target,
                    Collections.emptyList()),
            AnnotationInstance.create(DotNames.PRODUCES, target, Collections.emptyList()),
            AnnotationInstance.create(DotName.createSimple(Named.class.getName()), target,
                    Collections.singletonList(AnnotationValue.createStringValue("value", "singletonBean"))));
    assertEquals(expected, ret);
}
 
Example #3
Source File: RestClientProcessor.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private void warnAboutNotWorkingFeaturesInNative(PackageConfig packageConfig, Map<DotName, ClassInfo> interfaces) {
    if (!packageConfig.type.equalsIgnoreCase(PackageConfig.NATIVE)) {
        return;
    }
    Set<DotName> dotNames = new HashSet<>();
    for (ClassInfo interfaze : interfaces.values()) {
        if (interfaze.classAnnotation(CLIENT_HEADER_PARAM) != null) {
            boolean hasDefault = false;
            for (MethodInfo method : interfaze.methods()) {
                if (isDefault(method.flags())) {
                    hasDefault = true;
                    break;
                }
            }
            if (hasDefault) {
                dotNames.add(interfaze.name());
            }
        }
    }
    if (!dotNames.isEmpty()) {
        log.warnf("rest-client interfaces that contain default methods and are annotated with '@" + CLIENT_HEADER_PARAM
                + "' might not work properly in native mode. Offending interfaces are: "
                + dotNames.stream().map(d -> "'" + d.toString() + "'").collect(Collectors.joining(", ")));
    }
}
 
Example #4
Source File: VertxProcessor.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@BuildStep
void collectEventConsumers(
        BeanRegistrationPhaseBuildItem beanRegistrationPhase,
        BuildProducer<EventConsumerBusinessMethodItem> messageConsumerBusinessMethods,
        BuildProducer<BeanConfiguratorBuildItem> errors) {
    // We need to collect all business methods annotated with @ConsumeEvent first
    AnnotationStore annotationStore = beanRegistrationPhase.getContext().get(BuildExtension.Key.ANNOTATION_STORE);
    for (BeanInfo bean : beanRegistrationPhase.getContext().beans().classBeans()) {
        for (MethodInfo method : bean.getTarget().get().asClass().methods()) {
            AnnotationInstance consumeEvent = annotationStore.getAnnotation(method, CONSUME_EVENT);
            if (consumeEvent != null) {
                // Validate method params and return type
                List<Type> params = method.parameters();
                if (params.size() != 1) {
                    throw new IllegalStateException(String.format(
                            "Event consumer business method must accept exactly one parameter: %s [method: %s, bean:%s",
                            params, method, bean));
                }
                messageConsumerBusinessMethods
                        .produce(new EventConsumerBusinessMethodItem(bean, method, consumeEvent));
                LOGGER.debugf("Found event consumer business method %s declared on %s", method, bean);
            }
        }
    }
}
 
Example #5
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 #6
Source File: Methods.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private static boolean skipForClientProxy(MethodInfo method) {
    if (Modifier.isStatic(method.flags()) || Modifier.isPrivate(method.flags())) {
        return true;
    }
    if (IGNORED_METHODS.contains(method.name())) {
        return true;
    }
    // skip all Object methods except for toString()
    if (method.declaringClass().name().equals(DotNames.OBJECT) && !method.name().equals(TO_STRING)) {
        return true;
    }
    if (Modifier.isFinal(method.flags())) {
        String className = method.declaringClass().name().toString();
        if (!className.startsWith("java.")) {
            LOGGER.warn(String.format(
                    "Final method %s.%s() is ignored during proxy generation and should never be invoked upon the proxy instance!",
                    className, method.name()));
        }
        return true;
    }
    return false;
}
 
Example #7
Source File: SpringDIProcessorTest.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Test
public void getAnnotationsToAddBeanMethodWithScope() {
    final Map<DotName, Set<DotName>> scopes = processor.getStereotypeScopes(index);
    final MethodInfo target = index.getClassByName(DotName.createSimple(BeanConfig.class.getName()))
            .method("requestBean");

    final Set<AnnotationInstance> ret = processor.getAnnotationsToAdd(target, scopes, null);

    final Set<AnnotationInstance> expected = setOf(
            AnnotationInstance.create(DotName.createSimple(RequestScoped.class.getName()), target,
                    Collections.emptyList()),
            AnnotationInstance.create(DotNames.PRODUCES, target, Collections.emptyList()),
            AnnotationInstance.create(DotName.createSimple(Named.class.getName()), target,
                    Collections.singletonList(AnnotationValue.createStringValue("value", "requestBean"))));
    assertEquals(expected, ret);
}
 
Example #8
Source File: IsDataClassWithDefaultValuesPredicate.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public boolean test(ClassInfo classInfo) {
    int ctorCount = 0;
    boolean hasCopyMethod = false;
    boolean hasStaticCopyMethod = false;
    boolean hasComponent1Method = false;
    List<MethodInfo> methods = classInfo.methods();
    for (MethodInfo method : methods) {
        String methodName = method.name();
        if ("<init>".equals(methodName)) {
            ctorCount++;
        } else if ("component1".equals(methodName) && Modifier.isFinal(method.flags())) {
            hasComponent1Method = true;
        } else if ("copy".equals(methodName) && Modifier.isFinal(method.flags())) {
            hasCopyMethod = true;
        } else if ("copy$default".equals(methodName) && Modifier.isStatic(method.flags())) {
            hasStaticCopyMethod = true;
        }
    }
    return ctorCount > 1 && hasComponent1Method && hasCopyMethod && hasStaticCopyMethod;
}
 
Example #9
Source File: AsmUtil.java    From quarkus with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the Java bytecode signature of a given Jandex MethodInfo using the given type argument mappings.
 * For example, given this method:
 * 
 * <pre>
 * {@code
 * public class Foo<T> {
 *  public <R> List<R> method(int a, T t){...} 
 * }
 * }
 * </pre>
 * 
 * This will return <tt>&lt;R:Ljava/lang/Object;>(ILjava/lang/Integer;)Ljava/util/List&lt;TR;>;</tt> if
 * your {@code typeArgMapper} contains {@code T=Ljava/lang/Integer;}.
 * 
 * @param method the method you want the signature for.
 * @param typeArgMapper a mapping between type argument names and their bytecode signature.
 * @return a bytecode signature for that method.
 */
public static String getSignature(MethodInfo method, Function<String, String> typeArgMapper) {
    List<Type> parameters = method.parameters();

    StringBuilder signature = new StringBuilder("");
    for (TypeVariable typeVariable : method.typeParameters()) {
        if (signature.length() == 0)
            signature.append("<");
        else
            signature.append(",");
        signature.append(typeVariable.identifier()).append(":");
        // FIXME: only use the first bound
        toSignature(signature, typeVariable.bounds().get(0), typeArgMapper, false);
    }
    if (signature.length() > 0)
        signature.append(">");
    signature.append("(");
    for (Type type : parameters) {
        toSignature(signature, type, typeArgMapper, false);
    }
    signature.append(")");
    toSignature(signature, method.returnType(), typeArgMapper, false);
    return signature.toString();
}
 
Example #10
Source File: CacheProcessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@BuildStep
ValidationErrorBuildItem validateBeanDeployment(ValidationPhaseBuildItem validationPhase) {
    AnnotationStore annotationStore = validationPhase.getContext().get(Key.ANNOTATION_STORE);
    List<Throwable> throwables = new ArrayList<>();
    for (BeanInfo bean : validationPhase.getContext().get(Key.BEANS)) {
        if (bean.isClassBean()) {
            for (MethodInfo method : bean.getTarget().get().asClass().methods()) {
                if (annotationStore.hasAnyAnnotation(method, API_METHODS_ANNOTATIONS)) {
                    CacheMethodValidator.validateAnnotations(annotationStore, bean, method, throwables);
                }
            }
        }
    }
    return new ValidationErrorBuildItem(throwables.toArray(new Throwable[0]));
}
 
Example #11
Source File: Beans.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private static String getDefaultName(MethodInfo producerMethod) {
    String propertyName = getPropertyName(producerMethod.name());
    if (propertyName != null) {
        // getURLMatcher() becomes URLMatcher
        return propertyName;
    } else {
        return producerMethod.name();
    }
}
 
Example #12
Source File: MethodUtilsTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotFindNonOverridenFromSuperClass() {
    ClassInfo aClass = classInfo(SomeClass.class.getName());
    ClassInfo superClass = classInfo(SuperClass.class.getName());

    MethodInfo parentMethod = superClass.firstMethod("notOverridenFromSuperClass");
    assertThat(Methods.isOverriden(parentMethod, aClass.methods())).isFalse();
}
 
Example #13
Source File: ClassConfigPropertiesUtil.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private static boolean shouldCheckForDefaultValue(ClassInfo configPropertiesClassInfo, FieldInfo field) {
    String getterName = JavaBeanUtil.getGetterName(field.name(), field.type().name());
    MethodInfo getterMethod = configPropertiesClassInfo.method(getterName);
    if (getterMethod != null) {
        return Modifier.isPublic(getterMethod.flags());
    }

    return !Modifier.isFinal(field.flags()) && Modifier.isPublic(field.flags());
}
 
Example #14
Source File: AnnotationScanner.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Process the Extensions annotations
 * 
 * @param context the scanning context
 * @param method the current REST method
 * @param operation the current operation
 */
default void processExtensions(final AnnotationScannerContext context, final MethodInfo method, Operation operation) {
    List<AnnotationInstance> extensionAnnotations = ExtensionReader.getExtensionsAnnotations(method);

    if (extensionAnnotations.isEmpty()) {
        extensionAnnotations.addAll(ExtensionReader.getExtensionsAnnotations(method.declaringClass()));
    }
    for (AnnotationInstance annotation : extensionAnnotations) {
        if (annotation.target() == null || !METHOD_PARAMETER.equals(annotation.target().kind())) {
            String name = ExtensionReader.getExtensionName(annotation);
            operation.addExtension(name, ExtensionReader.readExtensionValue(context, name, annotation));
        }
    }
}
 
Example #15
Source File: AnnotationScanner.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Process a certain method for server annotations.
 * 
 * @param method the method that contain the server annotation
 * @param operation the current Operation model being created
 */
default void processServerAnnotation(final MethodInfo method, Operation operation) {
    List<AnnotationInstance> serverAnnotations = ServerReader.getServerAnnotations(method);
    if (serverAnnotations.isEmpty()) {
        serverAnnotations.addAll(ServerReader.getServerAnnotations(method.declaringClass()));
    }
    for (AnnotationInstance annotation : serverAnnotations) {
        Server server = ServerReader.readServer(annotation);
        operation.addServer(server);
    }
}
 
Example #16
Source File: AnnotationScanner.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Process tags.
 * Tag and Tags annotations combines with the resource tags we've already found (passed in)
 * 
 * @param method the REST method
 * @param openApi the OpenApi model
 * @param resourceTags tags passed in
 * @param operation the current operation
 */
default void processOperationTags(final MethodInfo method, OpenAPI openApi, Set<String> resourceTags,
        final Operation operation) {
    // 
    Set<String> tags = processTags(method, openApi, true);
    if (tags == null) {
        if (!resourceTags.isEmpty()) {
            operation.setTags(new ArrayList<>(resourceTags));
        }
    } else if (!tags.isEmpty()) {
        operation.setTags(new ArrayList<>(tags));
    }
}
 
Example #17
Source File: StringPropertyAccessorData.java    From quarkus with Apache License 2.0 5 votes vote down vote up
/**
 * Called with data parsed from a Spring expression like #person.name that is places inside a Spring security annotation on
 * a method
 */
static StringPropertyAccessorData from(MethodInfo methodInfo, int matchingParameterIndex, String propertyName,
        IndexView index, String expression) {
    Type matchingParameterType = methodInfo.parameters().get(matchingParameterIndex);
    ClassInfo matchingParameterClassInfo = index.getClassByName(matchingParameterType.name());
    if (matchingParameterClassInfo == null) {
        throw new IllegalArgumentException(
                "Expression: '" + expression + "' in the @PreAuthorize annotation on method '" + methodInfo.name()
                        + "' of class '" + methodInfo.declaringClass() + "' references class "
                        + matchingParameterType.name() + " which could not be in Jandex");
    }
    FieldInfo matchingParameterFieldInfo = matchingParameterClassInfo.field(propertyName);
    if (matchingParameterFieldInfo == null) {
        throw new IllegalArgumentException(
                "Expression: '" + expression + "' in the @PreAuthorize annotation on method '" + methodInfo.name()
                        + "' of class '" + methodInfo.declaringClass() + "' references unknown property '"
                        + propertyName + "' of class " + matchingParameterClassInfo);
    }
    if (!DotNames.STRING.equals(matchingParameterFieldInfo.type().name())) {
        throw new IllegalArgumentException(
                "Expression: '" + expression + "' in the @PreAuthorize annotation on method '" + methodInfo.name()
                        + "' of class '" + methodInfo.declaringClass() + "' references property '"
                        + propertyName + "' which is not a string");
    }

    return new StringPropertyAccessorData(matchingParameterClassInfo, matchingParameterFieldInfo);
}
 
Example #18
Source File: Injection.java    From quarkus with Apache License 2.0 5 votes vote down vote up
static Injection forObserver(MethodInfo observerMethod, ClassInfo beanClass, BeanDeployment beanDeployment,
        InjectionPointModifier transformer) {
    return new Injection(observerMethod, InjectionPointInfo.fromMethod(observerMethod, beanClass, beanDeployment,
            annotations -> annotations.stream()
                    .anyMatch(a -> a.name().equals(DotNames.OBSERVES) || a.name().equals(DotNames.OBSERVES_ASYNC)),
            transformer));
}
 
Example #19
Source File: JandexUtil.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Returns all annotations configured for a single parameter of a method.
 * 
 * @param method MethodInfo
 * @param paramPosition parameter position
 * @return List of AnnotationInstance's
 */
public static List<AnnotationInstance> getParameterAnnotations(MethodInfo method, short paramPosition) {
    return method.annotations()
            .stream()
            .filter(annotation -> {
                AnnotationTarget target = annotation.target();
                return target != null && target.kind() == Kind.METHOD_PARAMETER
                        && target.asMethodParameter().position() == paramPosition;
            })
            .collect(toList());
}
 
Example #20
Source File: Types.java    From quarkus with Apache License 2.0 5 votes vote down vote up
static Set<Type> getProducerMethodTypeClosure(MethodInfo producerMethod, BeanDeployment beanDeployment) {
    Set<Type> types;
    Type returnType = producerMethod.returnType();
    if (returnType.kind() == Kind.PRIMITIVE || returnType.kind() == Kind.ARRAY) {
        types = new HashSet<>();
        types.add(returnType);
        types.add(OBJECT_TYPE);
        return types;
    } else {
        ClassInfo returnTypeClassInfo = getClassByName(beanDeployment.getIndex(), returnType);
        if (returnTypeClassInfo == null) {
            throw new IllegalArgumentException(
                    "Producer method return type not found in index: " + producerMethod.returnType().name());
        }
        if (Kind.CLASS.equals(returnType.kind())) {
            types = getTypeClosure(returnTypeClassInfo, producerMethod, Collections.emptyMap(), beanDeployment, null);
        } else if (Kind.PARAMETERIZED_TYPE.equals(returnType.kind())) {
            types = getTypeClosure(returnTypeClassInfo, producerMethod,
                    buildResolvedMap(returnType.asParameterizedType().arguments(), returnTypeClassInfo.typeParameters(),
                            Collections.emptyMap(), beanDeployment.getIndex()),
                    beanDeployment, null);
        } else {
            throw new IllegalArgumentException("Unsupported return type");
        }
    }
    return restrictBeanTypes(types, beanDeployment.getAnnotations(producerMethod));
}
 
Example #21
Source File: CacheAnnotationsTransformer.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private AnnotationInstance createCacheResultBinding(MethodInfo method, AnnotationInstance annotation,
        AnnotationTarget target) {
    List<AnnotationValue> parameters = new ArrayList<>();
    parameters.add(getCacheName(annotation));
    findCacheKeyParameters(method).ifPresent(parameters::add);
    findLockTimeout(annotation).ifPresent(parameters::add);
    return createBinding(CacheResultInterceptorBinding.class, target, toArray(parameters));
}
 
Example #22
Source File: AnnotationScanner.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
default void processResponse(final AnnotationScannerContext context, final MethodInfo method, Operation operation,
        Map<DotName, AnnotationInstance> exceptionAnnotationMap) {

    List<AnnotationInstance> apiResponseAnnotations = ResponseReader.getResponseAnnotations(method);
    for (AnnotationInstance annotation : apiResponseAnnotations) {
        addApiReponseFromAnnotation(context, annotation, operation);
    }

    AnnotationInstance responseSchemaAnnotation = ResponseReader.getResponseSchemaAnnotation(method);
    addApiReponseSchemaFromAnnotation(context, responseSchemaAnnotation, method, operation);

    /*
     * If there is no response from annotations, try to create one from the method return value.
     * Do not generate a response if the app has used an empty @ApiResponses annotation. This
     * provides a way for the application to indicate that responses will be supplied some other
     * way (i.e. static file).
     */
    AnnotationInstance apiResponses = ResponseReader.getResponsesAnnotation(method);
    if (apiResponses == null || !JandexUtil.isEmpty(apiResponses)) {
        createResponseFromRestMethod(context, method, operation);
    }

    //Add api response using list of exceptions in the methods and exception mappers
    List<Type> methodExceptions = method.exceptions();

    for (Type type : methodExceptions) {
        DotName exceptionDotName = type.name();
        if (exceptionAnnotationMap != null && !exceptionAnnotationMap.isEmpty()
                && exceptionAnnotationMap.keySet().contains(exceptionDotName)) {
            AnnotationInstance exMapperApiResponseAnnotation = exceptionAnnotationMap.get(exceptionDotName);
            if (!this.responseCodeExistInMethodAnnotations(exMapperApiResponseAnnotation, apiResponseAnnotations)) {
                addApiReponseFromAnnotation(context, exMapperApiResponseAnnotation, operation);
            }
        }
    }
}
 
Example #23
Source File: TypeResolver.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Returns whether a method follows the Java bean convention for a mutator
 * method (setter).
 *
 * @param method the method to check
 * @return true if the method is a Java bean setter, otherwise false
 */
private static boolean isMutator(MethodInfo method) {
    Type returnType = method.returnType();

    if (method.parameters().size() != 1 || !Type.Kind.VOID.equals(returnType.kind())) {
        return false;
    }

    return method.name().startsWith("set");
}
 
Example #24
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 #25
Source File: MethodPropertiesAccessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private Optional<MethodInfo> getMethodInfo(ClassInfo classInfo, MethodMetadata methodMetadata) {
    return classInfo.methods()
            .stream()
            .filter(methodInfo -> methodMetadata.getName().equals(methodInfo.name()))
            .filter(methodInfo -> doParametersMatch(methodInfo, methodMetadata.getParameterTypes()))
            .findFirst();
}
 
Example #26
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 #27
Source File: SchedulerProcessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@BuildStep
void validateScheduledBusinessMethods(SchedulerConfig config, List<ScheduledBusinessMethodItem> scheduledMethods,
        ValidationPhaseBuildItem validationPhase, BuildProducer<ValidationErrorBuildItem> validationErrors) {
    List<Throwable> errors = new ArrayList<>();
    Map<String, AnnotationInstance> encounteredIdentities = new HashMap<>();

    for (ScheduledBusinessMethodItem scheduledMethod : scheduledMethods) {
        MethodInfo method = scheduledMethod.getMethod();

        // Validate method params and return type
        List<Type> params = method.parameters();
        if (params.size() > 1
                || (params.size() == 1 && !params.get(0).equals(SCHEDULED_EXECUTION_TYPE))) {
            errors.add(new IllegalStateException(String.format(
                    "Invalid scheduled business method parameters %s [method: %s, bean: %s]", params,
                    method, scheduledMethod.getBean())));
        }
        if (!method.returnType().kind().equals(Type.Kind.VOID)) {
            errors.add(new IllegalStateException(
                    String.format("Scheduled business method must return void [method: %s, bean: %s]",
                            method, scheduledMethod.getBean())));
        }
        // Validate cron() and every() expressions
        CronParser parser = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(config.cronType));
        for (AnnotationInstance scheduled : scheduledMethod.getSchedules()) {
            Throwable error = validateScheduled(parser, scheduled, encounteredIdentities);
            if (error != null) {
                errors.add(error);
            }
        }
    }

    if (!errors.isEmpty()) {
        validationErrors.produce(new ValidationErrorBuildItem(errors));
    }
}
 
Example #28
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 #29
Source File: CacheAnnotationsTransformer.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private AnnotationInstance createCacheInvalidateBinding(MethodInfo method, AnnotationInstance annotation,
        AnnotationTarget target) {
    List<AnnotationValue> parameters = new ArrayList<>();
    parameters.add(getCacheName(annotation));
    findCacheKeyParameters(method).ifPresent(parameters::add);
    return createBinding(CacheInvalidateInterceptorBinding.class, target, toArray(parameters));
}
 
Example #30
Source File: InterfaceConfigPropertiesUtil.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private static String getPropertyName(MethodInfo method, ConfigProperties.NamingStrategy namingStrategy) {
    String effectiveName = method.name();
    try {
        effectiveName = JavaBeanUtil.getPropertyNameFromGetter(method.name());
    } catch (IllegalArgumentException ignored) {

    }
    return namingStrategy.getName(effectiveName);
}