Java Code Examples for org.jboss.jandex.AnnotationTarget#asMethod()

The following examples show how to use org.jboss.jandex.AnnotationTarget#asMethod() . 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: StockMethodsAdder.java    From quarkus with Apache License 2.0 6 votes vote down vote up
/**
 * Given an annotation target, generate the bytecode that is needed to obtain its value
 * either by reading the field or by calling the method.
 * Meant to be called for annotations alike {@code @Id} or {@code @Version}
 */
private ResultHandle generateObtainValue(MethodCreator methodCreator, DotName entityDotName, ResultHandle entity,
        AnnotationTarget annotationTarget) {
    if (annotationTarget instanceof FieldInfo) {
        FieldInfo fieldInfo = annotationTarget.asField();
        if (Modifier.isPublic(fieldInfo.flags())) {
            return methodCreator.readInstanceField(FieldDescriptor.of(fieldInfo), entity);
        }

        String getterMethodName = JavaBeanUtil.getGetterName(fieldInfo.name(), fieldInfo.type().name());
        return methodCreator.invokeVirtualMethod(
                MethodDescriptor.ofMethod(entityDotName.toString(), getterMethodName, fieldInfo.type().name().toString()),
                entity);
    }
    MethodInfo methodInfo = annotationTarget.asMethod();
    return methodCreator.invokeVirtualMethod(
            MethodDescriptor.ofMethod(entityDotName.toString(), methodInfo.name(),
                    methodInfo.returnType().name().toString()),
            entity);
}
 
Example 2
Source File: JpaSecurityDefinition.java    From quarkus with Apache License 2.0 6 votes vote down vote up
public static FieldOrMethod getFieldOrMethod(Index index, ClassInfo annotatedClass,
        AnnotationTarget annotatedFieldOrMethod, boolean isPanache) {
    switch (annotatedFieldOrMethod.kind()) {
        case FIELD:
            // try to find a getter for this field
            FieldInfo field = annotatedFieldOrMethod.asField();
            return new FieldOrMethod(field,
                    findGetter(index, annotatedClass, field, Modifier.isPublic(field.flags()) && isPanache));
        case METHOD:
            // skip the field entirely
            return new FieldOrMethod(null, annotatedFieldOrMethod.asMethod());
        default:
            throw new IllegalArgumentException(
                    "annotatedFieldOrMethod must be a field or method: " + annotatedFieldOrMethod);
    }
}
 
Example 3
Source File: ParameterProcessor.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves the "value" parameter from annotation to be used as the name.
 * If no value was specified or an empty value, return the name of the annotation
 * target.
 *
 * @param annotation parameter annotation
 * @return the name of the parameter
 */
static String paramName(AnnotationInstance annotation) {
    AnnotationValue value = annotation.value();
    String valueString = null;

    if (value != null) {
        valueString = value.asString();
        if (valueString.length() > 0) {
            return valueString;
        }
    }

    AnnotationTarget target = annotation.target();

    switch (target.kind()) {
        case FIELD:
            valueString = target.asField().name();
            break;
        case METHOD_PARAMETER:
            valueString = target.asMethodParameter().name();
            break;
        case METHOD:
            // This is a bean property setter
            MethodInfo method = target.asMethod();
            if (method.parameters().size() == 1) {
                String methodName = method.name();

                if (methodName.startsWith("set")) {
                    valueString = Introspector.decapitalize(methodName.substring(3));
                } else {
                    valueString = methodName;
                }
            }
            break;
        default:
            break;
    }

    return valueString;
}
 
Example 4
Source File: ParameterProcessor.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves the "value" parameter from annotation to be used as the name.
 * If no value was specified or an empty value, return the name of the annotation
 * target.
 *
 * @param annotation parameter annotation
 * @return the name of the parameter
 */
static String paramName(AnnotationInstance annotation) {
    AnnotationValue value = annotation.value();
    String valueString = null;

    if (value != null) {
        valueString = value.asString();
        if (valueString.length() > 0) {
            return valueString;
        }
    }

    AnnotationTarget target = annotation.target();

    switch (target.kind()) {
        case FIELD:
            valueString = target.asField().name();
            break;
        case METHOD_PARAMETER:
            valueString = target.asMethodParameter().name();
            break;
        case METHOD:
            // This is a bean property setter
            MethodInfo method = target.asMethod();
            if (method.parameters().size() == 1) {
                String methodName = method.name();

                if (methodName.startsWith("set")) {
                    valueString = Introspector.decapitalize(methodName.substring(3));
                } else {
                    valueString = methodName;
                }
            }
            break;
        default:
            break;
    }

    return valueString;
}
 
Example 5
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 6
Source File: StockMethodsAdder.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private FieldInfo getIdField(AnnotationTarget idAnnotationTarget) {
    if (idAnnotationTarget instanceof FieldInfo) {
        return idAnnotationTarget.asField();
    }

    MethodInfo methodInfo = idAnnotationTarget.asMethod();
    String propertyName = JavaBeanUtil.getPropertyNameFromGetter(methodInfo.name());
    ClassInfo entityClass = methodInfo.declaringClass();
    FieldInfo field = entityClass.field(propertyName);
    if (field == null) {
        throw new IllegalArgumentException("Entity " + entityClass + " does not appear to have a field backing method"
                + methodInfo.name() + " which is annotated with @Id");
    }
    return field;
}
 
Example 7
Source File: CamelDeploymentSettingsBuilderProcessor.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
private boolean annotationTargetIsCamelApi(AnnotationTarget target) {
    /**
     * Verify whether an annotation is applied to org.apache.camel types. If the declaring class
     * has the org.apache.camel package prefix, it is ignored since we are only interested in
     * annotations declared within user classes.
     */
    if (target != null) {
        if (target.kind().equals(Kind.CLASS)) {
            ClassInfo classInfo = target.asClass();
            if (isCamelApi(classInfo.name())) {
                return false;
            }

            Type superType = classInfo.superClassType();
            if (superType != null && isCamelApi(superType.name())) {
                return true;
            }

            return classInfo.interfaceNames().stream().anyMatch(interfaceName -> isCamelApi(interfaceName));
        } else if (target.kind().equals(Kind.FIELD)) {
            FieldInfo fieldInfo = target.asField();
            return !isCamelApi(fieldInfo.declaringClass().name()) && isCamelApi(fieldInfo.type().name());
        } else if (target.kind().equals(Kind.METHOD)) {
            MethodInfo methodInfo = target.asMethod();
            return !isCamelApi(methodInfo.declaringClass().name()) && isCamelApi(methodInfo.returnType().name());
        }
    }
    return false;
}
 
Example 8
Source File: IgnoreResolver.java    From smallrye-open-api with Apache License 2.0 4 votes vote down vote up
@Override
public boolean shouldIgnore(AnnotationTarget target, DataObjectDeque.PathEntry parentPathEntry) {
    Type classType;

    switch (target.kind()) {
        case FIELD:
            classType = target.asField().type();
            break;
        case METHOD:
            MethodInfo method = target.asMethod();
            if (method.returnType().kind().equals(Type.Kind.VOID)) {
                // Setter method
                classType = method.parameters().get(0);
            } else {
                // Getter method
                classType = method.returnType();
            }
            break;
        default:
            return false;
    }

    // Primitive and non-indexed types will result in a null
    if (classType.kind() == Type.Kind.PRIMITIVE ||
            classType.kind() == Type.Kind.VOID ||
            (classType.kind() == Type.Kind.ARRAY && classType.asArrayType().component().kind() == Type.Kind.PRIMITIVE)
            ||
            !index.containsClass(classType)) {
        return false;
    }

    // Find the real class implementation where the @JsonIgnoreType annotation may be.
    ClassInfo classInfo = index.getClass(classType);

    if (ignoredTypes.contains(classInfo.name())) {
        DataObjectLogging.log.ignoringType(classInfo.name());
        return true;
    }

    AnnotationInstance annotationInstance = TypeUtil.getAnnotation(classInfo, getName());
    if (annotationInstance != null && valueAsBooleanOrTrue(annotationInstance)) {
        // Add the ignored field or class name
        DataObjectLogging.log.ignoringTypeAndAddingToSet(classInfo.name());
        ignoredTypes.add(classInfo.name());
        return true;
    }
    return false;
}
 
Example 9
Source File: EventBusCodecProcessor.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@BuildStep
public void registerCodecs(
        BeanArchiveIndexBuildItem beanArchiveIndexBuildItem,
        BuildProducer<MessageCodecBuildItem> messageCodecs) {

    final IndexView index = beanArchiveIndexBuildItem.getIndex();
    Collection<AnnotationInstance> consumeEventAnnotationInstances = index.getAnnotations(CONSUME_EVENT);
    Map<Type, DotName> codecByTypes = new HashMap<>();
    for (AnnotationInstance consumeEventAnnotationInstance : consumeEventAnnotationInstances) {
        AnnotationTarget typeTarget = consumeEventAnnotationInstance.target();
        if (typeTarget.kind() != AnnotationTarget.Kind.METHOD) {
            throw new UnsupportedOperationException("@ConsumeEvent annotation must target a method");
        }

        MethodInfo method = typeTarget.asMethod();
        Type codecTargetFromReturnType = extractPayloadTypeFromReturn(method);
        Type codecTargetFromParameter = extractPayloadTypeFromParameter(method);

        // If the @ConsumeEvent set the codec, use this codec. It applies to the parameter
        AnnotationValue codec = consumeEventAnnotationInstance.value("codec");
        if (codec != null && codec.asClass().kind() == Type.Kind.CLASS) {
            if (codecTargetFromParameter == null) {
                throw new IllegalStateException("Invalid `codec` argument in @ConsumeEvent - no parameter");
            }
            codecByTypes.put(codecTargetFromParameter, codec.asClass().asClassType().name());
        } else if (codecTargetFromParameter != null) {
            // Codec is not set, check if we have a built-in codec
            if (!hasBuiltInCodec(codecTargetFromParameter)) {
                // Ensure local delivery.
                AnnotationValue local = consumeEventAnnotationInstance.value("local");
                if (local != null && !local.asBoolean()) {
                    throw new UnsupportedOperationException(
                            "The generic message codec can only be used for local delivery,"
                                    + ", implement your own event bus codec for " + codecTargetFromParameter.name()
                                            .toString());
                } else if (!codecByTypes.containsKey(codecTargetFromParameter)) {
                    LOGGER.infof("Local Message Codec registered for type %s",
                            codecTargetFromParameter.toString());
                    codecByTypes.put(codecTargetFromParameter, LOCAL_EVENT_BUS_CODEC);
                }
            }
        }

        if (codecTargetFromReturnType != null && !hasBuiltInCodec(codecTargetFromReturnType)
                && !codecByTypes.containsKey(codecTargetFromReturnType)) {

            LOGGER.infof("Local Message Codec registered for type %s", codecTargetFromReturnType.toString());
            codecByTypes.put(codecTargetFromReturnType, LOCAL_EVENT_BUS_CODEC);
        }
    }

    // Produce the build items
    for (Map.Entry<Type, DotName> entry : codecByTypes.entrySet()) {
        messageCodecs.produce(new MessageCodecBuildItem(entry.getKey().toString(), entry.getValue().toString()));
    }

    // Register codec classes for reflection.
    codecByTypes.values().stream().map(DotName::toString).distinct()
            .forEach(name -> reflectiveClass.produce(new ReflectiveClassBuildItem(true, false, name)));
}
 
Example 10
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 11
Source File: HibernateSearchElasticsearchProcessor.java    From quarkus with Apache License 2.0 4 votes vote down vote up
private void registerReflection(IndexView index, BuildProducer<ReflectiveClassBuildItem> reflectiveClass,
        BuildProducer<ReflectiveHierarchyBuildItem> reflectiveHierarchy) {
    Set<DotName> reflectiveClassCollector = new HashSet<>();

    if (buildTimeConfig.defaultBackend.analysis.configurer.isPresent()) {
        reflectiveClass.produce(
                new ReflectiveClassBuildItem(true, false, buildTimeConfig.defaultBackend.analysis.configurer.get()));
    }

    if (buildTimeConfig.defaultBackend.layout.strategy.isPresent()) {
        reflectiveClass.produce(
                new ReflectiveClassBuildItem(true, false, buildTimeConfig.defaultBackend.layout.strategy.get()));
    }

    if (buildTimeConfig.backgroundFailureHandler.isPresent()) {
        reflectiveClass.produce(
                new ReflectiveClassBuildItem(true, false, buildTimeConfig.backgroundFailureHandler.get()));
    }

    Set<Type> reflectiveHierarchyCollector = new HashSet<>();

    for (AnnotationInstance propertyMappingMetaAnnotationInstance : index
            .getAnnotations(PROPERTY_MAPPING_META_ANNOTATION)) {
        for (AnnotationInstance propertyMappingAnnotationInstance : index
                .getAnnotations(propertyMappingMetaAnnotationInstance.name())) {
            AnnotationTarget annotationTarget = propertyMappingAnnotationInstance.target();
            if (annotationTarget.kind() == Kind.FIELD) {
                FieldInfo fieldInfo = annotationTarget.asField();
                addReflectiveClass(index, reflectiveClassCollector, reflectiveHierarchyCollector,
                        fieldInfo.declaringClass());
                addReflectiveType(index, reflectiveClassCollector, reflectiveHierarchyCollector,
                        fieldInfo.type());
            } else if (annotationTarget.kind() == Kind.METHOD) {
                MethodInfo methodInfo = annotationTarget.asMethod();
                addReflectiveClass(index, reflectiveClassCollector, reflectiveHierarchyCollector,
                        methodInfo.declaringClass());
                addReflectiveType(index, reflectiveClassCollector, reflectiveHierarchyCollector,
                        methodInfo.returnType());
            }
        }
    }

    for (AnnotationInstance typeBridgeMappingInstance : index.getAnnotations(TYPE_MAPPING_META_ANNOTATION)) {
        for (AnnotationInstance typeBridgeInstance : index.getAnnotations(typeBridgeMappingInstance.name())) {
            addReflectiveClass(index, reflectiveClassCollector, reflectiveHierarchyCollector,
                    typeBridgeInstance.target().asClass());
        }
    }

    reflectiveClassCollector.addAll(GSON_CLASSES);

    String[] reflectiveClasses = reflectiveClassCollector.stream().map(DotName::toString).toArray(String[]::new);
    reflectiveClass.produce(new ReflectiveClassBuildItem(true, true, reflectiveClasses));

    for (Type reflectiveHierarchyType : reflectiveHierarchyCollector) {
        reflectiveHierarchy.produce(new ReflectiveHierarchyBuildItem(reflectiveHierarchyType));
    }
}