org.jboss.jandex.AnnotationTarget.Kind Java Examples

The following examples show how to use org.jboss.jandex.AnnotationTarget.Kind. 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: Annotations.java    From quarkus with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @param annotations
 * @return the annotations for the given kind and name
 */
public static Set<AnnotationInstance> getAnnotations(Kind kind, DotName name, Collection<AnnotationInstance> annotations) {
    if (annotations.isEmpty()) {
        return Collections.emptySet();
    }
    Set<AnnotationInstance> ret = new HashSet<>();
    for (AnnotationInstance annotation : annotations) {
        if (kind != annotation.target().kind()) {
            continue;
        }
        if (name != null && !annotation.name().equals(name)) {
            continue;
        }
        ret.add(annotation);
    }
    return ret;
}
 
Example #2
Source File: TypeUtil.java    From smallrye-open-api with Apache License 2.0 6 votes vote down vote up
public static boolean hasAnnotation(AnnotationTarget target, DotName annotationName) {
    if (target == null) {
        return false;
    }
    switch (target.kind()) {
        case CLASS:
            return target.asClass().classAnnotation(annotationName) != null;
        case FIELD:
            return target.asField().hasAnnotation(annotationName);
        case METHOD:
            return target.asMethod().hasAnnotation(annotationName);
        case METHOD_PARAMETER:
            MethodParameterInfo parameter = target.asMethodParameter();
            return parameter.method()
                    .annotations()
                    .stream()
                    .filter(a -> a.target().kind() == Kind.METHOD_PARAMETER)
                    .filter(a -> a.target().asMethodParameter().position() == parameter.position())
                    .anyMatch(a -> a.name().equals(annotationName));
        case TYPE:
            break;
    }

    return false;
}
 
Example #3
Source File: TypeUtil.java    From smallrye-open-api with Apache License 2.0 6 votes vote down vote up
public static Collection<AnnotationInstance> getAnnotations(AnnotationTarget type) {
    switch (type.kind()) {
        case CLASS:
            return type.asClass().classAnnotations();
        case FIELD:
            return type.asField().annotations();
        case METHOD:
            return type.asMethod().annotations();
        case METHOD_PARAMETER:
            MethodParameterInfo parameter = type.asMethodParameter();
            return parameter
                    .method()
                    .annotations()
                    .stream()
                    .filter(a -> a.target().kind() == Kind.METHOD_PARAMETER)
                    .filter(a -> a.target().asMethodParameter().position() == parameter.position())
                    .collect(Collectors.toList());
        case TYPE:
            break;
    }
    return Collections.emptyList();
}
 
Example #4
Source File: TypeUtil.java    From smallrye-open-api with Apache License 2.0 6 votes vote down vote up
/**
 * Test whether testSubject is an instanceof type test.
 * <p>
 * For example, test whether List is a Collection.
 * <p>
 * Attempts to work with both Jandex and using standard class.
 *
 * @param index Jandex index
 * @param testSubject type to test
 * @param testObject type to test against
 * @return true if is of type
 */
public static boolean isA(IndexView index, Type testSubject, Type testObject) {
    // The types may be the same -- short circuit looking in the index
    if (getName(testSubject).equals(getName(testObject))) {
        return true;
    }
    if (testSubject.kind() == Type.Kind.PRIMITIVE && testObject.kind() != Type.Kind.PRIMITIVE) {
        return false;
    }

    // First, look in Jandex, as target might not be in our classloader
    ClassInfo subJandexKlazz = getClassInfo(index, testSubject);

    if (subJandexKlazz != null && superTypes(index, subJandexKlazz).contains(getName(testObject))) {
        return true;
    }

    return isAssignableFrom(testSubject.name(), testObject.name());
}
 
Example #5
Source File: InjectionPointInfo.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private static Type resolveType(Type type, ClassInfo beanClass, BeanDeployment beanDeployment,
        Map<ClassInfo, Map<TypeVariable, Type>> resolvedTypeVariables) {
    if (type.kind() == org.jboss.jandex.Type.Kind.TYPE_VARIABLE) {
        if (resolvedTypeVariables.containsKey(beanClass)) {
            return resolvedTypeVariables.get(beanClass).getOrDefault(type.asTypeVariable(), type);
        }
    } else if (type.kind() == org.jboss.jandex.Type.Kind.PARAMETERIZED_TYPE) {
        ParameterizedType parameterizedType = type.asParameterizedType();
        Type[] typeParams = new Type[parameterizedType.arguments().size()];
        for (int i = 0; i < typeParams.length; i++) {
            Type argument = parameterizedType.arguments().get(i);
            if (argument.kind() == org.jboss.jandex.Type.Kind.TYPE_VARIABLE
                    || argument.kind() == org.jboss.jandex.Type.Kind.PARAMETERIZED_TYPE) {
                typeParams[i] = resolveType(argument, beanClass, beanDeployment, resolvedTypeVariables);
            } else {
                typeParams[i] = argument;
            }
        }
        return ParameterizedType.create(parameterizedType.name(), typeParams, parameterizedType.owner());
    }
    return type;
}
 
Example #6
Source File: TypeResolver.java    From smallrye-open-api with Apache License 2.0 6 votes vote down vote up
/**
 * Returns whether a method follows the Java bean convention for an accessor
 * method (getter). The method name typically begins with "get", but may also
 * begin with "is" when the return type is boolean.
 *
 * @param method the method to check
 * @return true if the method is a Java bean getter, otherwise false
 */
private static boolean isAccessor(MethodInfo method) {
    Type returnType = method.returnType();

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

    String methodName = method.name();

    if (methodName.startsWith("get")) {
        return true;
    }

    return methodName.startsWith("is") && TypeUtil.equalTypes(returnType, BOOLEAN_TYPE);
}
 
Example #7
Source File: ParameterProcessor.java    From smallrye-open-api with Apache License 2.0 6 votes vote down vote up
/**
 * Scan and parse a Spring DefaultValue property on the mapping annotation.
 * If the target is a Java primitive, the value will be parsed into an equivalent
 * wrapper object.
 *
 * @param target target annotated with a Spring mapping
 * @return the default value
 */
static Object getDefaultValue(AnnotationTarget target) {
    AnnotationInstance defaultValueAnno = TypeUtil.getAnnotation(target, SpringConstants.QUERY_PARAM);
    Object defaultValue = null;

    if (defaultValueAnno != null) {
        AnnotationValue value = defaultValueAnno.value("defaultValue");
        if (value != null && !value.asString().isEmpty()) {
            String defaultValueString = value.asString();
            defaultValue = defaultValueString;
            Type targetType = getType(target);

            if (targetType != null && targetType.kind() == Type.Kind.PRIMITIVE) {
                Primitive primitive = targetType.asPrimitiveType().primitive();
                Object primitiveValue = primitiveToObject(primitive, defaultValueString);

                if (primitiveValue != null) {
                    defaultValue = primitiveValue;
                }
            }
        }
    }
    return defaultValue;
}
 
Example #8
Source File: BeanInfoQualifiersTest.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Test
public void testQualifiers() throws IOException {
    Index index = index(Foo.class, Bar.class, FooQualifier.class, AbstractList.class, AbstractCollection.class,
            List.class, Collection.class, Object.class, String.class, Iterable.class);
    DotName fooName = name(Foo.class);
    DotName fooQualifierName = name(FooQualifier.class);
    ClassInfo fooClass = index.getClassByName(fooName);

    BeanInfo bean = Beans.createClassBean(fooClass, BeanProcessor.builder().setIndex(index).build().getBeanDeployment(),
            null);

    AnnotationInstance requiredFooQualifier = index.getAnnotations(fooQualifierName).stream()
            .filter(a -> Kind.FIELD.equals(a.target().kind()) && a.target().asField().name().equals("foo")).findFirst()
            .orElse(null);

    assertNotNull(requiredFooQualifier);
    // FooQualifier#alpha() is @Nonbinding
    assertTrue(Beans.hasQualifier(bean, requiredFooQualifier));
}
 
Example #9
Source File: ValueResolverGenerator.java    From quarkus with Apache License 2.0 6 votes vote down vote up
static ResultHandle loadParamType(BytecodeCreator creator, Type paramType) {
    if (org.jboss.jandex.Type.Kind.PRIMITIVE.equals(paramType.kind())) {
        switch (paramType.asPrimitiveType().primitive()) {
            case INT:
                return creator.loadClass(Integer.class);
            case LONG:
                return creator.loadClass(Long.class);
            case BOOLEAN:
                return creator.loadClass(Boolean.class);
            case BYTE:
                return creator.loadClass(Byte.class);
            case CHAR:
                return creator.loadClass(Character.class);
            case DOUBLE:
                return creator.loadClass(Double.class);
            case FLOAT:
                return creator.loadClass(Float.class);
            case SHORT:
                return creator.loadClass(Short.class);
            default:
                throw new IllegalArgumentException("Unsupported primitive type: " + paramType);
        }
    }
    // TODO: we should probably use the TCCL to load the param type
    return creator.loadClass(paramType.name().toString());
}
 
Example #10
Source File: ValueResolverGenerator.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private Predicate<AnnotationTarget> initFilters(AnnotationInstance templateData) {
    Predicate<AnnotationTarget> filter = ValueResolverGenerator::defaultFilter;
    if (templateData != null) {
        // @TemplateData is present
        AnnotationValue ignoreValue = templateData.value(IGNORE);
        if (ignoreValue != null) {
            List<Pattern> ignore = Arrays.asList(ignoreValue.asStringArray()).stream().map(Pattern::compile)
                    .collect(Collectors.toList());
            filter = filter.and(t -> {
                if (t.kind() == Kind.FIELD) {
                    return !ignore.stream().anyMatch(p -> p.matcher(t.asField().name()).matches());
                } else {
                    return !ignore.stream().anyMatch(p -> p.matcher(t.asMethod().name()).matches());
                }
            });
        }
        AnnotationValue propertiesValue = templateData.value(PROPERTIES);
        if (propertiesValue != null && propertiesValue.asBoolean()) {
            filter = filter.and(ValueResolverGenerator::propertiesFilter);
        }
    } else {
        // Include only properties: instance fields and methods without params
        filter = filter.and(ValueResolverGenerator::propertiesFilter);
    }
    return filter;
}
 
Example #11
Source File: TypeResolverTests.java    From smallrye-open-api with Apache License 2.0 6 votes vote down vote up
@Test
public void testAnnotatedInterfaceMethodOverridesStaticField() {
    AugmentedIndexView index = new AugmentedIndexView(indexOf(AbstractAnimal.class,
            Reptile.class,
            Lizard.class));

    ClassInfo leafKlazz = index.getClassByName(componentize(Lizard.class.getName()));
    Type leaf = Type.create(leafKlazz.name(), Type.Kind.CLASS);
    Map<String, TypeResolver> properties = TypeResolver.getAllFields(index, leaf, leafKlazz);

    TypeResolver resolver = properties.get("scaleColor");
    assertEquals(Kind.METHOD, resolver.getAnnotationTarget().kind());
    AnnotationInstance schema = TypeUtil.getSchemaAnnotation(resolver.getAnnotationTarget());
    assertEquals("scaleColor", schema.value("name").asString());
    assertNull(schema.value("deprecated"));
    assertEquals("The color of a reptile's scales", schema.value("description").asString());

    TypeResolver ageResolver = properties.get("age");
    assertEquals(Type.Kind.CLASS, ageResolver.getUnresolvedType().kind());
    assertEquals(DotName.createSimple(String.class.getName()), ageResolver.getUnresolvedType().name());
}
 
Example #12
Source File: TypeResolverTests.java    From smallrye-open-api with Apache License 2.0 6 votes vote down vote up
@Test
public void testAnnotatedInterfaceMethodOverridesImplMethod() {
    AugmentedIndexView index = new AugmentedIndexView(indexOf(AbstractAnimal.class,
            Canine.class,
            Dog.class));

    ClassInfo leafKlazz = index.getClassByName(componentize(Dog.class.getName()));
    Type leaf = Type.create(leafKlazz.name(), Type.Kind.CLASS);
    Map<String, TypeResolver> properties = TypeResolver.getAllFields(index, leaf, leafKlazz);
    assertEquals(5, properties.size());
    TypeResolver resolver = properties.get("name");
    assertEquals(Kind.METHOD, resolver.getAnnotationTarget().kind());
    AnnotationInstance schema = TypeUtil.getSchemaAnnotation(resolver.getAnnotationTarget());
    assertEquals("c_name", schema.value("name").asString());
    assertEquals(50, schema.value("maxLength").asInt());
    assertEquals("The name of the canine", schema.value("description").asString());
    assertArrayEquals(new String[] { "age", "type", "c_name", "bark", "extinct" },
            properties.values().stream().map(TypeResolver::getPropertyName).toArray());
}
 
Example #13
Source File: TypeResolverTests.java    From smallrye-open-api with Apache License 2.0 6 votes vote down vote up
@Test
public void testAnnotatedMethodOverridesParentSchema() {
    AugmentedIndexView index = new AugmentedIndexView(indexOf(AbstractAnimal.class,
            Feline.class,
            Cat.class));

    ClassInfo leafKlazz = index.getClassByName(componentize(Cat.class.getName()));
    Type leaf = Type.create(leafKlazz.name(), Type.Kind.CLASS);
    Map<String, TypeResolver> properties = TypeResolver.getAllFields(index, leaf, leafKlazz);
    TypeResolver resolver = properties.get("type");
    assertEquals(Kind.METHOD, resolver.getAnnotationTarget().kind());
    AnnotationInstance schema = TypeUtil.getSchemaAnnotation(resolver.getAnnotationTarget());
    assertEquals("type", schema.value("name").asString());
    assertEquals(false, schema.value("required").asBoolean());
    assertEquals("Cat", schema.value("example").asString());
    assertArrayEquals(new String[] { "age", "type", "name", "extinct" },
            properties.values().stream().map(TypeResolver::getPropertyName).toArray());
}
 
Example #14
Source File: UnremovableBeanBuildItem.java    From quarkus with Apache License 2.0 6 votes vote down vote up
/**
 * Match beans whose target (class, method or field) is annotated with the specified annotation.
 * 
 * @param annotationName
 * @return a new build item
 */
public static UnremovableBeanBuildItem targetWithAnnotation(DotName annotationName) {
    return new UnremovableBeanBuildItem(new Predicate<BeanInfo>() {
        @Override
        public boolean test(BeanInfo bean) {
            if (bean.isClassBean()) {
                return Annotations.contains(bean.getTarget().get().asClass().classAnnotations(), annotationName);
            } else if (bean.isProducerMethod()) {
                return !getAnnotations(Kind.METHOD, annotationName, bean.getTarget().get().asMethod().annotations())
                        .isEmpty();
            } else if (bean.isProducerField()) {
                return bean.getTarget().get().asField().hasAnnotation(annotationName);
            }
            // No target - synthetic bean
            return false;
        }
    });
}
 
Example #15
Source File: ParameterProcessor.java    From smallrye-open-api with Apache License 2.0 6 votes vote down vote up
boolean haveSameAnnotatedTarget(ParameterContext context, AnnotationTarget target, String name) {
    /*
     * Consider names to match if one is unspecified or they are equal.
     */
    boolean nameMatches = (context.name == null || name == null || Objects.equals(context.name, name));

    if (target.equals(context.target)) {
        /*
         * The name must match for annotations on a method because it is
         * ambiguous which parameters is being referenced.
         */
        return nameMatches || target.kind() != Kind.METHOD;
    }

    if (nameMatches && target.kind() == Kind.METHOD && context.target.kind() == Kind.METHOD_PARAMETER) {
        return context.target.asMethodParameter().method().equals(target);
    }

    return false;
}
 
Example #16
Source File: IgnoreResolver.java    From smallrye-open-api with Apache License 2.0 6 votes vote down vote up
@Override
public boolean shouldIgnore(AnnotationTarget target, PathEntry parentPathEntry) {
    if (target.kind() == AnnotationTarget.Kind.FIELD) {
        FieldInfo field = target.asField();
        // If field has transient modifier, e.g. `transient String foo;`, then hide it.
        if (Modifier.isTransient(field.flags())) {
            // Unless field is annotated with @Schema to explicitly un-hide it.
            AnnotationInstance schemaAnnotation = TypeUtil.getSchemaAnnotation(target);
            if (schemaAnnotation != null) {
                return JandexUtil.booleanValue(schemaAnnotation, SchemaConstant.PROP_HIDDEN).orElse(true);
            }
            return true;
        }
    }
    return false;
}
 
Example #17
Source File: ParameterProcessor.java    From smallrye-open-api with Apache License 2.0 6 votes vote down vote up
/**
 * Scan and parse a JAX-RS {@link javax.ws.rs.DefaultValue DefaultValue} annotation.
 * If the target is a Java primitive, the value will be parsed into an equivalent
 * wrapper object.
 *
 * @param target target annotated with {@link javax.ws.rs.DefaultValue @DefaultValue}
 * @return the default value
 */
static Object getDefaultValue(AnnotationTarget target) {
    AnnotationInstance defaultValueAnno = TypeUtil.getAnnotation(target, JaxRsConstants.DEFAULT_VALUE);
    Object defaultValue = null;

    if (defaultValueAnno != null) {
        String defaultValueString = stringValue(defaultValueAnno, ParameterConstant.PROP_VALUE);
        defaultValue = defaultValueString;
        Type targetType = getType(target);

        if (targetType != null && targetType.kind() == Type.Kind.PRIMITIVE) {
            Primitive primitive = targetType.asPrimitiveType().primitive();
            Object primitiveValue = primitiveToObject(primitive, defaultValueString);

            if (primitiveValue != null) {
                defaultValue = primitiveValue;
            }
        }
    }

    return defaultValue;
}
 
Example #18
Source File: QuteProcessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private Type resolveType(AnnotationTarget member, Match match, IndexView index) {
    Type matchType;
    if (member.kind() == Kind.FIELD) {
        matchType = member.asField().type();
    } else if (member.kind() == Kind.METHOD) {
        matchType = member.asMethod().returnType();
    } else {
        throw new IllegalStateException("Unsupported member type: " + member);
    }
    // If needed attempt to resolve the type variables using the declaring type
    if (Types.containsTypeVariable(matchType)) {
        // First get the type closure of the current match type
        Set<Type> closure = Types.getTypeClosure(match.clazz, Types.buildResolvedMap(
                match.getParameterizedTypeArguments(), match.getTypeParameters(),
                new HashMap<>(), index), index);
        DotName declaringClassName = member.kind() == Kind.METHOD ? member.asMethod().declaringClass().name()
                : member.asField().declaringClass().name();
        // Then find the declaring type with resolved type variables
        Type declaringType = closure.stream()
                .filter(t -> t.name().equals(declaringClassName)).findAny()
                .orElse(null);
        if (declaringType != null
                && declaringType.kind() == org.jboss.jandex.Type.Kind.PARAMETERIZED_TYPE) {
            matchType = Types.resolveTypeParam(matchType,
                    Types.buildResolvedMap(declaringType.asParameterizedType().arguments(),
                            index.getClassByName(declaringType.name()).typeParameters(),
                            Collections.emptyMap(),
                            index),
                    index);
        }
    }
    return matchType;
}
 
Example #19
Source File: BuildTimeEnabledProcessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private void disableBean(AnnotationTarget target, Transformation transform) {
    if (target.kind() == Kind.CLASS) {
        // Veto the class
        transform.add(DotNames.VETOED);
    } else {
        // Add @Alternative to the producer
        transform.add(DotNames.ALTERNATIVE);
    }
}
 
Example #20
Source File: SmallRyeFaultToleranceProcessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@BuildStep
AnnotationsTransformerBuildItem transformInterceptorPriority(BeanArchiveIndexBuildItem index) {
    return new AnnotationsTransformerBuildItem(new AnnotationsTransformer() {
        @Override
        public boolean appliesTo(Kind kind) {
            return kind == Kind.CLASS;
        }

        @Override
        public void transform(TransformationContext ctx) {
            if (ctx.isClass()) {
                if (!ctx.getTarget().asClass().name().toString()
                        .equals("io.smallrye.faulttolerance.FaultToleranceInterceptor")) {
                    return;
                }
                final Config config = ConfigProvider.getConfig();

                OptionalInt priority = config.getValue("mp.fault.tolerance.interceptor.priority", OptionalInt.class);
                if (priority.isPresent()) {
                    ctx.transform()
                            .remove(ann -> ann.name().toString().equals(Priority.class.getName()))
                            .add(Priority.class, AnnotationValue.createIntegerValue("value", priority.getAsInt()))
                            .done();
                }
            }
        }
    });
}
 
Example #21
Source File: SmallRyeMetricsProcessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
/**
 * Methods with a @Gauge annotation need to be registered for reflection because
 * gauges are registered at runtime and the registering interceptor must be able to see
 * the annotation.
 */
@BuildStep
void reflectiveMethodsWithGauges(BeanArchiveIndexBuildItem beanArchiveIndex,
        BuildProducer<ReflectiveMethodBuildItem> reflectiveMethods) {
    for (AnnotationInstance annotation : beanArchiveIndex.getIndex().getAnnotations(GAUGE)) {
        if (annotation.target().kind().equals(AnnotationTarget.Kind.METHOD)) {
            reflectiveMethods.produce(new ReflectiveMethodBuildItem(annotation.target().asMethod()));
        }
    }
}
 
Example #22
Source File: DisposerInfo.java    From quarkus with Apache License 2.0 5 votes vote down vote up
MethodParameterInfo initDisposedParam(MethodInfo disposerMethod) {
    List<MethodParameterInfo> disposedParams = new ArrayList<>();
    for (AnnotationInstance annotation : disposerMethod.annotations()) {
        if (Kind.METHOD_PARAMETER.equals(annotation.target().kind()) && annotation.name().equals(DotNames.DISPOSES)) {
            disposedParams.add(annotation.target().asMethodParameter());
        }
    }
    if (disposedParams.isEmpty()) {
        throw new DefinitionException("No disposed parameters found for " + disposerMethod);
    } else if (disposedParams.size() > 1) {
        throw new DefinitionException("Multiple disposed parameters found for " + disposerMethod);
    }
    return disposedParams.get(0);
}
 
Example #23
Source File: ValueResolverGenerator.java    From quarkus with Apache License 2.0 5 votes vote down vote up
static boolean defaultFilter(AnnotationTarget target) {
    // Always ignore constructors, static and non-public members, synthetic and void methods
    switch (target.kind()) {
        case METHOD:
            MethodInfo method = target.asMethod();
            return Modifier.isPublic(method.flags()) && !Modifier.isStatic(method.flags()) && !isSynthetic(method.flags())
                    && method.returnType().kind() != org.jboss.jandex.Type.Kind.VOID && !method.name().equals("<init>")
                    && !method.name().equals("<clinit>");
        case FIELD:
            FieldInfo field = target.asField();
            return Modifier.isPublic(field.flags()) && !Modifier.isStatic(field.flags());
        default:
            throw new IllegalArgumentException("Unsupported annotation target");
    }
}
 
Example #24
Source File: ResteasyServerCommonProcessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private static void checkParameterNames(IndexView index,
        List<AdditionalJaxRsResourceMethodParamAnnotations> additionalJaxRsResourceMethodParamAnnotations) {

    final List<DotName> methodParameterAnnotations = new ArrayList<>(RESTEASY_PARAM_ANNOTATIONS.length);
    methodParameterAnnotations.addAll(Arrays.asList(RESTEASY_PARAM_ANNOTATIONS));
    for (AdditionalJaxRsResourceMethodParamAnnotations annotations : additionalJaxRsResourceMethodParamAnnotations) {
        methodParameterAnnotations.addAll(annotations.getAnnotationClasses());
    }

    OUTER: for (DotName annotationType : methodParameterAnnotations) {
        Collection<AnnotationInstance> instances = index.getAnnotations(annotationType);
        for (AnnotationInstance instance : instances) {
            // we only care about method parameters, because properties or fields always work
            if (instance.target().kind() != Kind.METHOD_PARAMETER) {
                continue;
            }
            MethodParameterInfo param = instance.target().asMethodParameter();
            if (param.name() == null) {
                log.warnv(
                        "Detected RESTEasy annotation {0} on method parameter {1}.{2} with no name. Either specify its name,"
                                + " or tell your compiler to enable debug info (-g) or parameter names (-parameters). This message is only"
                                + " logged for the first such parameter.",
                        instance.name(),
                        param.method().declaringClass(), param.method().name());
                break OUTER;
            }
        }
    }
}
 
Example #25
Source File: AnnotationStore.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private List<AnnotationsTransformer> initTransformers(Kind kind, Collection<AnnotationsTransformer> transformers) {
    List<AnnotationsTransformer> found = new ArrayList<>();
    for (AnnotationsTransformer transformer : transformers) {
        if (transformer.appliesTo(kind)) {
            found.add(transformer);
        }
    }
    if (found.isEmpty()) {
        return Collections.emptyList();
    }
    found.sort(BuildExtension::compare);
    return found;
}
 
Example #26
Source File: AnnotationStore.java    From quarkus with Apache License 2.0 5 votes vote down vote up
AnnotationStore(Collection<AnnotationsTransformer> transformers, BuildContext buildContext) {
    if (transformers == null || transformers.isEmpty()) {
        this.transformed = null;
        this.transformersMap = null;
    } else {
        this.transformed = new ConcurrentHashMap<>();
        this.transformersMap = new EnumMap<>(Kind.class);
        this.transformersMap.put(Kind.CLASS, initTransformers(Kind.CLASS, transformers));
        this.transformersMap.put(Kind.METHOD, initTransformers(Kind.METHOD, transformers));
        this.transformersMap.put(Kind.FIELD, initTransformers(Kind.FIELD, transformers));
    }
    this.buildContext = buildContext;
}
 
Example #27
Source File: Annotations.java    From quarkus with Apache License 2.0 5 votes vote down vote up
/**
 * Iterates over all annotations on a method and its parameters, filters out all non-parameter annotations
 * and returns a first encountered {@link AnnotationInstance} with Annotation specified as {@link DotName}.
 * Returns {@code null} if no such annotation exists.
 *
 * @param method MethodInfo to be searched for annotations
 * @param annotation Annotation we are looking for, represented as DotName
 * @return First encountered {@link AnnotationInstance} fitting the requirements, {@code null} if none is found
 */
public static AnnotationInstance getParameterAnnotation(MethodInfo method, DotName annotation) {
    for (AnnotationInstance annotationInstance : method.annotations()) {
        if (annotationInstance.target().kind().equals(Kind.METHOD_PARAMETER) &&
                annotationInstance.name().equals(annotation)) {
            return annotationInstance;
        }
    }
    return null;
}
 
Example #28
Source File: Annotations.java    From quarkus with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param beanDeployment
 * @param method
 * @param position
 * @return the parameter annotations for the given position
 */
public static Set<AnnotationInstance> getParameterAnnotations(BeanDeployment beanDeployment, MethodInfo method,
        int position) {
    Set<AnnotationInstance> annotations = new HashSet<>();
    for (AnnotationInstance annotation : beanDeployment.getAnnotations(method)) {
        if (Kind.METHOD_PARAMETER == annotation.target().kind()
                && annotation.target().asMethodParameter().position() == position) {
            annotations.add(annotation);
        }
    }
    return annotations;
}
 
Example #29
Source File: SmallRyeMetricsProcessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@BuildStep
AnnotationsTransformerBuildItem annotationTransformers() {
    // attach @MetricsBinding to each class that contains any metric annotations
    return new AnnotationsTransformerBuildItem(new AnnotationsTransformer() {

        @Override
        public boolean appliesTo(Kind kind) {
            return kind == Kind.CLASS;
        }

        @Override
        public void transform(TransformationContext context) {
            // skip classes in package io.smallrye.metrics.interceptors
            ClassInfo clazz = context.getTarget().asClass();
            if (clazz.name().toString()
                    .startsWith(io.smallrye.metrics.interceptors.MetricsInterceptor.class.getPackage().getName())) {
                return;
            }
            if (clazz.annotations().containsKey(GAUGE)) {
                BuiltinScope beanScope = BuiltinScope.from(clazz);
                if (!isJaxRsEndpoint(clazz) && beanScope != null &&
                        !beanScope.equals(BuiltinScope.APPLICATION) &&
                        !beanScope.equals(BuiltinScope.SINGLETON)) {
                    LOGGER.warnf("Bean %s declares a org.eclipse.microprofile.metrics.annotation.Gauge " +
                            "but is of a scope that typically " +
                            "creates multiple instances. Gauges are forbidden on beans " +
                            "that create multiple instances, this will cause errors " +
                            "when constructing them. Please use annotated gauges only in beans with " +
                            "@ApplicationScoped or @Singleton scopes, or in JAX-RS endpoints.",
                            clazz.name().toString());
                }
                context.transform().add(MetricsBinding.class).done();
            }
        }

    });
}
 
Example #30
Source File: PolicyProcessor.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@BuildStep
void bannedReflectiveClasses(
        CombinedIndexBuildItem combinedIndex,
        List<ReflectiveClassBuildItem> reflectiveClasses,
        List<UnbannedReflectiveBuildItem> unbannedReflectives,
        BuildProducer<GeneratedResourceBuildItem> dummy // to force the execution of this method
) {
    final DotName uriParamsDotName = DotName.createSimple("org.apache.camel.spi.UriParams");

    final Set<String> bannedClassNames = combinedIndex.getIndex()
            .getAnnotations(uriParamsDotName)
            .stream()
            .filter(ai -> ai.target().kind() == Kind.CLASS)
            .map(ai -> ai.target().asClass().name().toString())
            .collect(Collectors.toSet());

    final Set<String> unbannedClassNames = unbannedReflectives.stream()
            .map(UnbannedReflectiveBuildItem::getClassNames)
            .flatMap(Collection::stream)
            .collect(Collectors.toSet());

    Set<String> violations = reflectiveClasses.stream()
            .map(ReflectiveClassBuildItem::getClassNames)
            .flatMap(Collection::stream)
            .filter(cl -> !unbannedClassNames.contains(cl))
            .filter(bannedClassNames::contains)
            .collect(Collectors.toSet());

    if (!violations.isEmpty()) {
        throw new IllegalStateException(
                "The following classes should either be whitelisted via an UnbannedReflectiveBuildItem or they should not be registered for reflection via ReflectiveClassBuildItem: "
                        + violations);
    }
}