Java Code Examples for org.jboss.jandex.AnnotationInstance#value()

The following examples show how to use org.jboss.jandex.AnnotationInstance#value() . 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: SchemaBuilder.java    From smallrye-graphql with Apache License 2.0 6 votes vote down vote up
private void addErrors(Schema schema) {
    Collection<AnnotationInstance> errorAnnotations = ScanningContext.getIndex().getAnnotations(Annotations.ERROR_CODE);
    if (errorAnnotations != null && !errorAnnotations.isEmpty()) {
        for (AnnotationInstance errorAnnotation : errorAnnotations) {
            AnnotationTarget annotationTarget = errorAnnotation.target();
            if (annotationTarget.kind().equals(AnnotationTarget.Kind.CLASS)) {
                ClassInfo exceptionClass = annotationTarget.asClass();
                AnnotationValue value = errorAnnotation.value();
                if (value != null && value.asString() != null && !value.asString().isEmpty()) {
                    schema.addError(new ErrorInfo(exceptionClass.name().toString(), value.asString()));
                } else {
                    LOG.warn("Ignoring @ErrorCode on " + annotationTarget.toString() + " - Annotation value is not set");
                }
            } else {
                LOG.warn("Ignoring @ErrorCode on " + annotationTarget.toString() + " - Wrong target, only apply to CLASS ["
                        + annotationTarget.kind().toString() + "]");
            }

        }
    }

}
 
Example 2
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 3
Source File: InterfaceConfigPropertiesUtil.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private static NameAndDefaultValue determinePropertyNameAndDefaultValue(MethodInfo method,
        ConfigProperties.NamingStrategy namingStrategy) {
    AnnotationInstance configPropertyAnnotation = method.annotation(DotNames.CONFIG_PROPERTY);
    if (configPropertyAnnotation != null) {
        AnnotationValue nameValue = configPropertyAnnotation.value("name");
        String name = (nameValue == null) || nameValue.asString().isEmpty() ? getPropertyName(method, namingStrategy)
                : nameValue.asString();
        AnnotationValue defaultValue = configPropertyAnnotation.value("defaultValue");

        return new NameAndDefaultValue(name, defaultValue != null ? defaultValue.asString() : null);
    }

    return new NameAndDefaultValue(getPropertyName(method, namingStrategy));
}
 
Example 4
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 5
Source File: ParameterProcessor.java    From smallrye-open-api with Apache License 2.0 6 votes vote down vote up
/**
 * Read a single annotation that is either {@link @Parameter} or
 * {@link @Parameters}. The results are stored in the private {@link #params}
 * collection.
 *
 * @param annotation a parameter annotation to be read and processed
 */
void readParameterAnnotation(AnnotationInstance annotation) {
    DotName name = annotation.name();

    if (ParameterConstant.DOTNAME_PARAMETER.equals(name)) {
        readAnnotatedType(annotation, null, false);
    } else if (ParameterConstant.DOTNAME_PARAMETERS.equals(name)) {
        AnnotationValue annotationValue = annotation.value();

        if (annotationValue != null) {
            /*
             * Unwrap annotations wrapped by @Parameters and
             * identify the target as the target of the @Parameters annotation
             */
            for (AnnotationInstance nested : annotationValue.asNestedArray()) {
                readAnnotatedType(AnnotationInstance.create(nested.name(),
                        annotation.target(),
                        nested.values()),
                        null,
                        false);
            }
        }
    }
}
 
Example 6
Source File: QuarkusMediatorConfigurationUtil.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private static String getValue(MethodInfo methodInfo, DotName dotName) {
    AnnotationInstance annotationInstance = methodInfo.annotation(dotName);
    String value = null;

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

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

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

    return value;
}
 
Example 7
Source File: ParameterProcessor.java    From smallrye-open-api with Apache License 2.0 6 votes vote down vote up
/**
 * Read a single annotation that is either {@link @Parameter} or
 * {@link @Parameters}. The results are stored in the private {@link #params}
 * collection.
 *
 * @param annotation a parameter annotation to be read and processed
 */
void readParameterAnnotation(AnnotationInstance annotation) {
    DotName name = annotation.name();

    if (ParameterConstant.DOTNAME_PARAMETER.equals(name)) {
        readAnnotatedType(annotation, null, false);
    } else if (ParameterConstant.DOTNAME_PARAMETERS.equals(name)) {
        AnnotationValue annotationValue = annotation.value();

        if (annotationValue != null) {
            /*
             * Unwrap annotations wrapped by @Parameters and
             * identify the target as the target of the @Parameters annotation
             */
            for (AnnotationInstance nested : annotationValue.asNestedArray()) {
                readAnnotatedType(AnnotationInstance.create(nested.name(),
                        annotation.target(),
                        nested.values()),
                        null,
                        false);
            }
        }
    }
}
 
Example 8
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 9
Source File: ParameterProcessor.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a String path from the RequestMapping value
 * 
 * @param requestMappingAnnotation
 * @return
 */
static String requestMappingValuesToPath(AnnotationInstance requestMappingAnnotation) {
    StringBuilder sb = new StringBuilder();
    AnnotationValue value = requestMappingAnnotation.value();
    String[] parts = value.asStringArray();
    for (String part : parts) {
        sb.append(part);
    }
    return sb.toString();
}
 
Example 10
Source File: RegisterForReflectionBuildStep.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@BuildStep
public void build() {
    for (AnnotationInstance i : combinedIndexBuildItem.getIndex()
            .getAnnotations(DotName.createSimple(RegisterForReflection.class.getName()))) {

        boolean methods = getBooleanValue(i, "methods");
        boolean fields = getBooleanValue(i, "fields");
        boolean ignoreNested = getBooleanValue(i, "ignoreNested");

        AnnotationValue targetsValue = i.value("targets");
        AnnotationValue classNamesValue = i.value("classNames");

        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        if (targetsValue == null && classNamesValue == null) {
            ClassInfo classInfo = i.target().asClass();
            registerClass(classLoader, classInfo.name().toString(), methods, fields, ignoreNested);
            continue;
        }

        if (targetsValue != null) {
            Type[] targets = targetsValue.asClassArray();
            for (Type type : targets) {
                registerClass(classLoader, type.name().toString(), methods, fields, ignoreNested);
            }
        }

        if (classNamesValue != null) {
            String[] classNames = classNamesValue.asStringArray();
            for (String className : classNames) {
                registerClass(classLoader, className, methods, fields, ignoreNested);
            }
        }
    }
}
 
Example 11
Source File: ResourcePropertiesAccessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public String path(ClassInfo classInfo) {
    AnnotationInstance annotation = getAnnotation(classInfo);
    if (annotation == null || annotation.value("path") == null || "".equals(annotation.value("path").asString())) {
        return ResourceName.fromClass(classInfo.simpleName());
    }
    return annotation.value("path").asString();
}
 
Example 12
Source File: ExtensionMethodGenerator.java    From quarkus with Apache License 2.0 4 votes vote down vote up
public void generate(MethodInfo method, String matchName, Integer priority) {

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

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

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

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

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

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

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

        valueResolver.close();
    }
 
Example 13
Source File: CacheAnnotationsTransformer.java    From quarkus with Apache License 2.0 4 votes vote down vote up
private AnnotationValue getCacheName(AnnotationInstance annotation) {
    return annotation.value(CACHE_NAME_PARAM);
}
 
Example 14
Source File: OperationReader.java    From smallrye-open-api with Apache License 2.0 4 votes vote down vote up
public static boolean operationIsHidden(final MethodInfo method) {
    AnnotationInstance operationAnnotation = method.annotation(OperationConstant.DOTNAME_OPERATION);
    // If the operation is marked as hidden, just bail here because we don't want it as part of the model.
    return operationAnnotation.value(OperationConstant.PROP_HIDDEN) != null
            && operationAnnotation.value(OperationConstant.PROP_HIDDEN).asBoolean();
}
 
Example 15
Source File: TestResourceManager.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private List<TestResourceEntry> getTestResources(Class<?> testClass) {
    IndexView index = TestClassIndexer.readIndex(testClass);

    List<TestResourceEntry> testResourceEntries = new ArrayList<>();

    // we need to keep track of duplicate entries to make sure we don't start the same resource
    // multiple times even if there are multiple same @QuarkusTestResource annotations
    Set<TestResourceClassEntry> alreadyAddedEntries = new HashSet<>();
    for (AnnotationInstance annotation : findQuarkusTestResourceInstances(index)) {
        try {
            Class<? extends QuarkusTestResourceLifecycleManager> testResourceClass = (Class<? extends QuarkusTestResourceLifecycleManager>) Class
                    .forName(annotation.value().asString(), true, Thread.currentThread().getContextClassLoader());

            AnnotationValue argsAnnotationValue = annotation.value("initArgs");
            Map<String, String> args;
            if (argsAnnotationValue == null) {
                args = Collections.emptyMap();
            } else {
                args = new HashMap<>();
                AnnotationInstance[] resourceArgsInstances = argsAnnotationValue.asNestedArray();
                for (AnnotationInstance resourceArgsInstance : resourceArgsInstances) {
                    args.put(resourceArgsInstance.value("name").asString(), resourceArgsInstance.value().asString());
                }
            }

            TestResourceClassEntry testResourceClassEntry = new TestResourceClassEntry(testResourceClass, args);
            if (alreadyAddedEntries.contains(testResourceClassEntry)) {
                continue;
            }
            alreadyAddedEntries.add(testResourceClassEntry);

            testResourceEntries.add(new TestResourceEntry(testResourceClass.getConstructor().newInstance(), args));
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException
                | InvocationTargetException | NoSuchMethodException | SecurityException e) {
            throw new RuntimeException("Unable to instantiate the test resource " + annotation.value().asString());
        }
    }

    for (QuarkusTestResourceLifecycleManager quarkusTestResourceLifecycleManager : ServiceLoader
            .load(QuarkusTestResourceLifecycleManager.class, Thread.currentThread().getContextClassLoader())) {
        testResourceEntries.add(new TestResourceEntry(quarkusTestResourceLifecycleManager));
    }

    testResourceEntries.sort(new Comparator<TestResourceEntry>() {

        private final QuarkusTestResourceLifecycleManagerComparator lifecycleManagerComparator = new QuarkusTestResourceLifecycleManagerComparator();

        @Override
        public int compare(TestResourceEntry o1, TestResourceEntry o2) {
            return lifecycleManagerComparator.compare(o1.getTestResource(), o2.getTestResource());
        }
    });

    return testResourceEntries;
}
 
Example 16
Source File: ResourcePropertiesAccessor.java    From quarkus with Apache License 2.0 4 votes vote down vote up
public boolean isPaged(ClassInfo classInfo) {
    AnnotationInstance annotation = getAnnotation(classInfo);
    return annotation == null
            || annotation.value("paged") == null
            || annotation.value("paged").asBoolean();
}
 
Example 17
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 18
Source File: ValueResolverGenerator.java    From quarkus with Apache License 2.0 4 votes vote down vote up
public void generate(ClassInfo clazz) {
    Objects.requireNonNull(clazz);
    String clazzName = clazz.name().toString();
    if (analyzedTypes.contains(clazzName)) {
        return;
    }
    analyzedTypes.add(clazzName);
    boolean ignoreSuperclasses = false;

    // @TemplateData declared on class takes precedence
    AnnotationInstance templateData = clazz.classAnnotation(TEMPLATE_DATA);
    if (templateData == null) {
        // Try to find @TemplateData declared on other classes
        templateData = uncontrolled.get(clazz.name());
    } else {
        AnnotationValue ignoreSuperclassesValue = templateData.value(IGNORE_SUPERCLASSES);
        if (ignoreSuperclassesValue != null) {
            ignoreSuperclasses = ignoreSuperclassesValue.asBoolean();
        }
    }

    Predicate<AnnotationTarget> filters = initFilters(templateData);

    LOGGER.debugf("Analyzing %s", clazzName);

    String baseName;
    if (clazz.enclosingClass() != null) {
        baseName = simpleName(clazz.enclosingClass()) + NESTED_SEPARATOR + simpleName(clazz);
    } else {
        baseName = simpleName(clazz);
    }
    String targetPackage = packageName(clazz.name());
    String generatedName = generatedNameFromTarget(targetPackage, baseName, SUFFIX);
    generatedTypes.add(generatedName.replace('/', '.'));

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

    implementGetPriority(valueResolver);
    implementAppliesTo(valueResolver, clazz);
    implementResolve(valueResolver, clazzName, clazz, filters);

    valueResolver.close();

    DotName superName = clazz.superName();
    if (!ignoreSuperclasses && (superName != null && !superName.equals(OBJECT))) {
        ClassInfo superClass = index.getClassByName(clazz.superClassType().name());
        if (superClass != null) {
            generate(superClass);
        } else {
            LOGGER.warnf("Skipping super class %s - not found in the index", clazz.superClassType());
        }
    }
}
 
Example 19
Source File: JandexUtil.java    From smallrye-open-api with Apache License 2.0 3 votes vote down vote up
/**
 * Reads a Boolean property value from the given annotation instance. If no value is found
 * this will return null.
 * 
 * @param annotation AnnotationInstance
 * @param propertyName String
 * @return Boolean value
 */
public static Optional<Boolean> booleanValue(AnnotationInstance annotation, String propertyName) {
    AnnotationValue value = annotation.value(propertyName);
    if (value != null) {
        return Optional.of(value.asBoolean());
    }
    return Optional.empty();
}
 
Example 20
Source File: JandexUtil.java    From smallrye-open-api with Apache License 2.0 3 votes vote down vote up
/**
 * Reads a String property value from the given annotation instance. If no value is found
 * this will return null.
 * 
 * @param annotation AnnotationInstance
 * @param propertyName String
 * @param clazz Class type of the Enum
 * @param <T> Type parameter
 * @return Value of property
 */
public static <T extends Enum<?>> T enumValue(AnnotationInstance annotation, String propertyName, Class<T> clazz) {
    AnnotationValue value = annotation.value(propertyName);
    if (value == null) {
        return null;
    }
    return enumValue(value.asString(), clazz);
}