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

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: ParameterProcessor.java    From smallrye-open-api with Apache License 2.0 6 votes vote down vote up
/**
 * Find the full path of the target. Method-level targets will include
 * both the path to the resource and the path to the method joined with a '/'.
 *
 * @param target target item for which the path is being generated
 * @return full path (excluding application path) of the target
 */
static String fullPathOf(AnnotationTarget target) {
    String pathSegment = null;

    switch (target.kind()) {
        case FIELD:
            pathSegment = pathOf(target.asField().declaringClass());
            break;
        case METHOD:
            pathSegment = methodPath(target.asMethod());
            break;
        case METHOD_PARAMETER:
            pathSegment = methodPath(target.asMethodParameter().method());
            break;
        default:
            break;
    }

    return pathSegment;
}
 
Example 2
Source File: BeanInfo.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private Type initProviderType(AnnotationTarget target, ClassInfo implClazz) {
    if (target != null) {
        switch (target.kind()) {
            case CLASS:
                return Types.getProviderType(target.asClass());
            case FIELD:
                return target.asField().type();
            case METHOD:
                return target.asMethod().returnType();
            default:
                break;
        }
    } else if (implClazz != null) {
        return Type.create(implClazz.name(), org.jboss.jandex.Type.Kind.CLASS);
    }
    throw new IllegalStateException("Cannot infer the provider type");
}
 
Example 3
Source File: Beans.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private static String initStereotypeName(List<StereotypeInfo> stereotypes, AnnotationTarget target) {
    if (stereotypes.isEmpty()) {
        return null;
    }
    for (StereotypeInfo stereotype : stereotypes) {
        if (stereotype.isNamed()) {
            switch (target.kind()) {
                case CLASS:
                    return getDefaultName(target.asClass());
                case FIELD:
                    return target.asField()
                            .name();
                case METHOD:
                    return getDefaultName(target.asMethod());
                default:
                    break;
            }
        }
    }
    return null;
}
 
Example 4
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 5
Source File: ParameterProcessor.java    From smallrye-open-api with Apache License 2.0 6 votes vote down vote up
/**
 * Find the full path of the target. Method-level targets will include
 * both the path to the resource and the path to the method joined with a '/'.
 *
 * @param target target item for which the path is being generated
 * @return full path (excluding application path) of the target
 */
static String fullPathOf(AnnotationTarget target) {
    String pathSegment = null;

    switch (target.kind()) {
        case FIELD:
            pathSegment = pathOf(target.asField().declaringClass());
            break;
        case METHOD:
            pathSegment = methodPath(target.asMethod());
            break;
        case METHOD_PARAMETER:
            pathSegment = methodPath(target.asMethodParameter().method());
            break;
        default:
            break;
    }

    return pathSegment;
}
 
Example 6
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 7
Source File: TypeUtil.java    From smallrye-open-api with Apache License 2.0 6 votes vote down vote up
public static ClassInfo getDeclaringClass(AnnotationTarget type) {
    switch (type.kind()) {
        case FIELD:
            return type.asField().declaringClass();
        case METHOD:
            return type.asMethod().declaringClass();
        case METHOD_PARAMETER:
            MethodParameterInfo parameter = type.asMethodParameter();
            return parameter.method().declaringClass();
        case CLASS:
        case TYPE:
            break;
    }

    return null;
}
 
Example 8
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 9
Source File: BuildTimeConditionBuildItem.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public BuildTimeConditionBuildItem(AnnotationTarget target, boolean enabled) {
    AnnotationTarget.Kind kind = target.kind();
    if ((kind != AnnotationTarget.Kind.CLASS) && (kind != AnnotationTarget.Kind.METHOD)
            && (kind != AnnotationTarget.Kind.FIELD)) {
        throw new IllegalArgumentException("'target' can only be a class, a field or a method");
    }
    this.target = target;
    this.enabled = enabled;
}
 
Example 10
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 11
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 12
Source File: ResteasyServerCommonProcessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private static boolean hasAnnotation(MethodInfo method, short paramPosition, DotName annotation) {
    for (AnnotationInstance annotationInstance : method.annotations()) {
        AnnotationTarget target = annotationInstance.target();
        if (target != null && target.kind() == Kind.METHOD_PARAMETER
                && target.asMethodParameter().position() == paramPosition
                && annotationInstance.name().equals(annotation)) {
            return true;
        }
    }
    return false;
}
 
Example 13
Source File: ParameterProcessor.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Determines the type of the target. Method annotations will give
 * the name of a single argument, assumed to be a "setter" method.
 *
 * @param target target object
 * @return object type
 */
static Type getType(AnnotationTarget target) {
    if (target == null) {
        return null;
    }

    Type type = null;

    switch (target.kind()) {
        case FIELD:
            type = target.asField().type();
            break;
        case METHOD:
            List<Type> methodParams = target.asMethod().parameters();
            if (methodParams.size() == 1) {
                // This is a bean property setter
                type = methodParams.get(0);
            }
            break;
        case METHOD_PARAMETER:
            type = getMethodParameterType(target.asMethodParameter());
            break;
        default:
            break;
    }

    return type;
}
 
Example 14
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 15
Source File: SwaggerArchivePreparer.java    From thorntail with Apache License 2.0 5 votes vote down vote up
/**
 * Get the JAX-RS application path configured this deployment. If the IndexView is not available, or if there is no class
 * that has the annotated @ApplicationPath, then this method will return an empty string.
 *
 * @return the JAX-RS application path configured this deployment.
 */
private String getRestApplicationPath() {
    String path = "";
    // Check to see if we have any class annotated with the @ApplicationPath. If found, ensure that we set the context path
    // for Swagger resources to webAppContextPath + applicationPath.
    if (indexView != null) {
        DotName dotName = DotName.createSimple(ApplicationPath.class.getName());
        Collection<AnnotationInstance> instances = indexView.getAnnotations(dotName);
        Set<String> applicationPaths = new HashSet<>();
        for (AnnotationInstance ai : instances) {
            AnnotationTarget target = ai.target();
            if (target.kind() == AnnotationTarget.Kind.CLASS) {
                Object value = ai.value().value();
                if (value != null) {
                    applicationPaths.add(String.valueOf(value));
                }
            }
        }
        if (applicationPaths.size() > 1) {
            // We wouldn't know which application path to pick for serving the swagger resources. Let the deployment choose
            // this value explicitly.
            SwaggerMessages.MESSAGES.multipleApplicationPathsFound(applicationPaths);
        } else if (!applicationPaths.isEmpty()) {
            // Update the context path for swagger
            path = applicationPaths.iterator().next();
        }
    }
    return path;
}
 
Example 16
Source File: ParameterProcessor.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Determines the type of the target. Method annotations will give
 * the name of a single argument, assumed to be a "setter" method.
 *
 * @param target target object
 * @return object type
 */
static Type getType(AnnotationTarget target) {
    if (target == null) {
        return null;
    }

    Type type = null;

    switch (target.kind()) {
        case FIELD:
            type = target.asField().type();
            break;
        case METHOD:
            List<Type> methodParams = target.asMethod().parameters();
            if (methodParams.size() == 1) {
                // This is a bean property setter
                type = methodParams.get(0);
            }
            break;
        case METHOD_PARAMETER:
            type = getMethodParameterType(target.asMethodParameter());
            break;
        default:
            break;
    }

    return type;
}
 
Example 17
Source File: ParameterProcessor.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Reads the {@link javax.ws.rs.Path @Path} annotation present on the
 * target and strips leading and trailing slashes.
 *
 * @param target target object
 * @return value of the {@link javax.ws.rs.Path @Path} without
 *         leading/trailing slashes.
 */
static String pathOf(AnnotationTarget target) {
    AnnotationInstance path = null;

    switch (target.kind()) {
        case CLASS:
            path = target.asClass().classAnnotation(JaxRsConstants.PATH);
            break;
        case METHOD:
            path = target.asMethod().annotation(JaxRsConstants.PATH);
            break;
        default:
            break;
    }

    if (path != null) {
        String pathValue = path.value().asString();

        if (pathValue.startsWith("/")) {
            pathValue = pathValue.substring(1);
        }

        if (pathValue.endsWith("/")) {
            pathValue = pathValue.substring(0, pathValue.length() - 1);
        }

        return pathValue;
    }

    return "";
}
 
Example 18
Source File: JandexMemberInfoAdapter.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Override
public MemberInfo convert(AnnotationTarget input) {
    MemberType memberType;
    AnnotationTarget.Kind kind = input.kind();
    if (kind.equals(AnnotationTarget.Kind.FIELD)) {
        memberType = MemberType.FIELD;
    } else {
        if (input.asMethod().name().equals("<init>")) {
            memberType = MemberType.CONSTRUCTOR;
        } else {
            memberType = MemberType.METHOD;
        }
    }

    final List<AnnotationInfo> annotationInformation;
    final String name, declaringClassSimpleName, declaringClassName;
    JandexAnnotationInfoAdapter annotationInfoAdapter = new JandexAnnotationInfoAdapter(indexView);
    if (input.kind().equals(AnnotationTarget.Kind.METHOD)) {
        declaringClassName = input.asMethod().declaringClass().name().toString();
        declaringClassSimpleName = input.asMethod().declaringClass().simpleName();
        name = input.asMethod().name();
        annotationInformation = input.asMethod()
                .annotations()
                .stream()
                .filter(SmallRyeMetricsDotNames::isMetricAnnotation)
                .map(annotationInfoAdapter::convert)
                .collect(Collectors.toList());
    } else {
        declaringClassName = input.asField().declaringClass().name().toString();
        declaringClassSimpleName = input.asField().declaringClass().simpleName();
        name = input.asField().name();
        annotationInformation = input.asField()
                .annotations()
                .stream()
                .filter(SmallRyeMetricsDotNames::isMetricAnnotation)
                .map(annotationInfoAdapter::convert)
                .collect(Collectors.toList());
    }

    return new RawMemberInfo(memberType,
            declaringClassName,
            declaringClassSimpleName,
            name,
            annotationInformation);
}
 
Example 19
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 20
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));
    }
}