Java Code Examples for org.jboss.jandex.AnnotationValue#asString()

The following examples show how to use org.jboss.jandex.AnnotationValue#asString() . 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: 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 3
Source File: JandexUtil.java    From smallrye-open-api with Apache License 2.0 6 votes vote down vote up
/**
 * Reads a string property named "ref" value from the given annotation and converts it
 * to a value appropriate for setting on a model's "$ref" property.
 * 
 * @param annotation AnnotationInstance
 * @param refType RefType
 * @return String value
 */
public static String refValue(AnnotationInstance annotation, RefType refType) {
    AnnotationValue value = annotation.value(OpenApiConstants.REF);
    if (value == null) {
        return null;
    }

    String ref = value.asString();

    if (!COMPONENT_KEY_PATTERN.matcher(ref).matches()) {
        return ref;
    }

    if (refType != null) {
        ref = "#/components/" + refType.componentPath + "/" + ref;
    } else {
        throw UtilMessages.msg.refTypeNotNull();
    }

    return ref;
}
 
Example 4
Source File: QuteProcessor.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private void produceExtensionMethod(IndexView index, BuildProducer<TemplateExtensionMethodBuildItem> extensionMethods,
        MethodInfo method, AnnotationInstance extensionAnnotation) {
    // Analyze matchName and priority so that it could be used during validation 
    String matchName = null;
    AnnotationValue matchNameValue = extensionAnnotation.value(MATCH_NAME);
    if (matchNameValue != null) {
        matchName = matchNameValue.asString();
    }
    if (matchName == null) {
        matchName = method.name();
    }
    int priority = TemplateExtension.DEFAULT_PRIORITY;
    AnnotationValue priorityValue = extensionAnnotation.value(PRIORITY);
    if (priorityValue != null) {
        priority = priorityValue.asInt();
    }
    extensionMethods.produce(new TemplateExtensionMethodBuildItem(method, matchName,
            index.getClassByName(method.parameters().get(0).name()), priority));
}
 
Example 5
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 6
Source File: RestClientProcessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private String getAnnotationParameter(ClassInfo classInfo, String parameterName) {
    AnnotationInstance instance = classInfo.classAnnotation(REGISTER_REST_CLIENT);
    if (instance == null) {
        return "";
    }

    AnnotationValue value = instance.value(parameterName);
    if (value == null) {
        return "";
    }

    return value.asString();
}
 
Example 7
Source File: Annotations.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
private Optional<String> getStringValue(AnnotationValue annotationValue) {
    String value = null;
    if (annotationValue != null) {
        value = annotationValue.asString();
        if (value != null && !value.isEmpty()) {
            return Optional.of(value);
        }
    }
    return Optional.empty();
}
 
Example 8
Source File: SpringDIProcessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private static String determineName(AnnotationValue annotationValue) {
    if (annotationValue.kind() == AnnotationValue.Kind.ARRAY) {
        return annotationValue.asStringArray()[0];
    } else if (annotationValue.kind() == AnnotationValue.Kind.STRING) {
        return annotationValue.asString();
    }
    return null;
}
 
Example 9
Source File: SpringDIProcessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
/**
 * Meant to be called with instances of @Component, @Service, @Repository
 */
private String getBeanNameFromStereotypeInstance(AnnotationInstance annotationInstance) {
    if (annotationInstance.target().kind() != AnnotationTarget.Kind.CLASS) {
        throw new IllegalStateException(
                "AnnotationInstance " + annotationInstance + " is an invalid target. Only Class targets are supported");
    }
    final AnnotationValue value = annotationInstance.value();
    if ((value == null) || value.asString().isEmpty()) {
        return getDefaultBeanNameFromClass(annotationInstance.target().asClass().name().toString());
    } else {
        return value.asString();
    }
}
 
Example 10
Source File: SpringDIProcessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
/**
 * Translate spring built-in scope identifiers to CDI scopes.
 *
 * @param target The annotated element declaring the @Scope
 * @return A CDI built in (or session) scope that mostly matches
 *         the spring one. Websocket scope is currently mapped to @Dependent
 *         and spring custom scopes are not currently handled.
 */
private DotName getScope(final AnnotationTarget target) {
    AnnotationValue value = null;
    if (target.kind() == AnnotationTarget.Kind.CLASS) {
        if (target.asClass().classAnnotation(SPRING_SCOPE_ANNOTATION) != null) {
            value = target.asClass().classAnnotation(SPRING_SCOPE_ANNOTATION).value();
        }
    } else if (target.kind() == AnnotationTarget.Kind.METHOD) {
        if (target.asMethod().hasAnnotation(SPRING_SCOPE_ANNOTATION)) {
            value = target.asMethod().annotation(SPRING_SCOPE_ANNOTATION).value();
        }
    }
    if (value != null) {
        switch (value.asString()) {
            case "singleton":
                return CDI_SINGLETON_ANNOTATION;
            case "request":
                return CDI_REQUEST_SCOPED_ANNOTATION;
            case "global session":
            case "application":
                return CDI_APP_SCOPED_ANNOTATION;
            case "session":
                return CDI_SESSION_SCOPED_ANNOTATION;
            case "websocket":
            case "prototype":
                return CDI_DEPENDENT_ANNOTATION;
        }
    }
    return null;
}
 
Example 11
Source File: HibernateUserTypeProcessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@BuildStep
public void build(BuildProducer<ReflectiveClassBuildItem> reflectiveClass, CombinedIndexBuildItem combinedIndexBuildItem) {
    IndexView index = combinedIndexBuildItem.getIndex();

    final Set<String> userTypes = new HashSet<>();

    Collection<AnnotationInstance> typeAnnotationInstances = index.getAnnotations(TYPE);
    Collection<AnnotationInstance> typeDefinitionAnnotationInstances = index.getAnnotations(TYPE_DEFINITION);
    Collection<AnnotationInstance> typeDefinitionsAnnotationInstances = index.getAnnotations(TYPE_DEFINITIONS);

    userTypes.addAll(getUserTypes(typeDefinitionAnnotationInstances));

    for (AnnotationInstance typeDefinitionAnnotationInstance : typeDefinitionsAnnotationInstances) {
        final AnnotationValue typeDefinitionsAnnotationValue = typeDefinitionAnnotationInstance.value();

        if (typeDefinitionsAnnotationValue == null) {
            continue;
        }

        userTypes.addAll(getUserTypes(Arrays.asList(typeDefinitionsAnnotationValue.asNestedArray())));
    }

    for (AnnotationInstance typeAnnotationInstance : typeAnnotationInstances) {
        final AnnotationValue typeValue = typeAnnotationInstance.value(TYPE_VALUE);
        if (typeValue == null) {
            continue;
        }

        final String type = typeValue.asString();
        final DotName className = DotName.createSimple(type);
        if (index.getClassByName(className) == null) {
            continue; // Either already registered through TypeDef annotation scanning or not present in the index
        }
        userTypes.add(type);
    }

    if (!userTypes.isEmpty()) {
        reflectiveClass.produce(new ReflectiveClassBuildItem(true, true, userTypes.toArray(new String[] {})));
    }
}
 
Example 12
Source File: JandexUtil.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Reads a Double property value from the given annotation instance. If no value is found
 * this will return null.
 * 
 * @param annotation AnnotationInstance
 * @param propertyName String
 * @return BigDecimal value
 */
public static BigDecimal bigDecimalValue(AnnotationInstance annotation, String propertyName) {
    AnnotationValue value = annotation.value(propertyName);
    if (value == null) {
        return null;
    }
    if (value.kind() == AnnotationValue.Kind.DOUBLE) {
        return BigDecimal.valueOf(value.asDouble());
    }
    if (value.kind() == AnnotationValue.Kind.STRING) {
        return new BigDecimal(value.asString());
    }
    throw new RuntimeException(
            "Call to bigDecimalValue failed because the annotation property was not a double or a String.");
}
 
Example 13
Source File: JandexUtil.java    From smallrye-open-api with Apache License 2.0 5 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
 * @return String value
 */
public static String stringValue(AnnotationInstance annotation, String propertyName) {
    AnnotationValue value = annotation.value(propertyName);
    if (value == null) {
        return null;
    } else {
        return value.asString();
    }
}
 
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: 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 16
Source File: FormatHelper.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
private static String getStringValue(AnnotationValue annotationValue) {
    String value = null;
    if (annotationValue != null) {
        value = annotationValue.asString();
    }
    return value;
}
 
Example 17
Source File: ConfigBuildStep.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@BuildStep
void analyzeConfigPropertyInjectionPoints(BeanRegistrationPhaseBuildItem beanRegistrationPhase,
        BuildProducer<ConfigPropertyBuildItem> configProperties,
        BuildProducer<ReflectiveClassBuildItem> reflectiveClass,
        BuildProducer<BeanConfiguratorBuildItem> beanConfigurators) {

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

    for (InjectionPointInfo injectionPoint : beanRegistrationPhase.getContext().get(BuildExtension.Key.INJECTION_POINTS)) {
        if (injectionPoint.hasDefaultedQualifier()) {
            // Defaulted qualifier means no @ConfigProperty
            continue;
        }

        AnnotationInstance configProperty = injectionPoint.getRequiredQualifier(CONFIG_PROPERTY_NAME);
        if (configProperty != null) {
            AnnotationValue nameValue = configProperty.value("name");
            AnnotationValue defaultValue = configProperty.value("defaultValue");
            String propertyName;
            if (nameValue != null) {
                propertyName = nameValue.asString();
            } else {
                // org.acme.Foo.config
                if (injectionPoint.isField()) {
                    FieldInfo field = injectionPoint.getTarget().asField();
                    propertyName = getPropertyName(field.name(), field.declaringClass());
                } else if (injectionPoint.isParam()) {
                    MethodInfo method = injectionPoint.getTarget().asMethod();
                    propertyName = getPropertyName(method.parameterName(injectionPoint.getPosition()),
                            method.declaringClass());
                } else {
                    throw new IllegalStateException("Unsupported injection point target: " + injectionPoint);
                }
            }

            // Register a custom bean for injection points that are not handled by ConfigProducer
            Type requiredType = injectionPoint.getRequiredType();
            if (!isHandledByProducers(requiredType)) {
                customBeanTypes.add(requiredType);
            }

            if (DotNames.OPTIONAL.equals(requiredType.name())) {
                // Never validate Optional values
                continue;
            }
            if (defaultValue != null && !ConfigProperty.UNCONFIGURED_VALUE.equals(defaultValue.asString())) {
                // No need to validate properties with default values
                continue;
            }

            configProperties.produce(new ConfigPropertyBuildItem(propertyName, requiredType));
        }
    }

    for (Type type : customBeanTypes) {
        if (type.kind() != Kind.ARRAY) {
            // Implicit converters are most likely used
            reflectiveClass.produce(new ReflectiveClassBuildItem(true, false, type.name().toString()));
        }
        beanConfigurators.produce(new BeanConfiguratorBuildItem(beanRegistrationPhase.getContext().configure(
                type.kind() == Kind.ARRAY ? DotName.createSimple(ConfigBeanCreator.class.getName()) : type.name())
                .creator(ConfigBeanCreator.class)
                .providerType(type)
                .types(type)
                .qualifiers(AnnotationInstance.create(CONFIG_PROPERTY_NAME, null, Collections.emptyList()))
                .param("requiredType", type.name().toString())));
    }
}
 
Example 18
Source File: ConfigPropertiesBuildStep.java    From quarkus with Apache License 2.0 4 votes vote down vote up
private String getPrefix(AnnotationInstance annotationInstance) {
    AnnotationValue value = annotationInstance.value("prefix");
    return value == null ? null : value.asString();
}
 
Example 19
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 20
Source File: Beans.java    From quarkus with Apache License 2.0 4 votes vote down vote up
/**
 *
 * @param producerField
 * @param declaringBean
 * @param beanDeployment
 * @param disposer
 * @return a new bean info
 */
static BeanInfo createProducerField(FieldInfo producerField, BeanInfo declaringBean, BeanDeployment beanDeployment,
        DisposerInfo disposer) {
    Set<AnnotationInstance> qualifiers = new HashSet<>();
    List<ScopeInfo> scopes = new ArrayList<>();
    Set<Type> types = Types.getProducerFieldTypeClosure(producerField, beanDeployment);
    Integer alternativePriority = null;
    boolean isAlternative = false;
    boolean isDefaultBean = false;
    List<StereotypeInfo> stereotypes = new ArrayList<>();
    String name = null;

    for (AnnotationInstance annotation : beanDeployment.getAnnotations(producerField)) {
        if (DotNames.NAMED.equals(annotation.name())) {
            AnnotationValue nameValue = annotation.value();
            if (nameValue != null) {
                name = nameValue.asString();
            } else {
                name = producerField.name();
            }
        }
        Collection<AnnotationInstance> qualifierCollection = beanDeployment.extractQualifiers(annotation);
        for (AnnotationInstance qualifierAnnotation : qualifierCollection) {
            // Qualifiers
            qualifiers.add(qualifierAnnotation);
        }
        if (!qualifierCollection.isEmpty()) {
            // we needn't process it further, the annotation was a qualifier (or multiple repeating ones)
            continue;
        }
        if (DotNames.ALTERNATIVE.equals(annotation.name())) {
            isAlternative = true;
            continue;
        }
        if (DotNames.ALTERNATIVE_PRIORITY.equals(annotation.name())) {
            isAlternative = true;
            alternativePriority = annotation.value().asInt();
            continue;
        }
        ScopeInfo scopeAnnotation = beanDeployment.getScope(annotation.name());
        if (scopeAnnotation != null) {
            scopes.add(scopeAnnotation);
            continue;
        }
        StereotypeInfo stereotype = beanDeployment.getStereotype(annotation.name());
        if (stereotype != null) {
            stereotypes.add(stereotype);
            continue;
        }
        if (DotNames.DEFAULT_BEAN.equals(annotation.name())) {
            isDefaultBean = true;
            continue;
        }
    }

    if (scopes.size() > 1) {
        throw multipleScopesFound("Producer field " + producerField, scopes);
    }
    ScopeInfo scope;
    if (scopes.isEmpty()) {
        scope = initStereotypeScope(stereotypes, producerField);
    } else {
        scope = scopes.get(0);
    }
    if (!isAlternative) {
        isAlternative = initStereotypeAlternative(stereotypes);
    }
    if (name == null) {
        name = initStereotypeName(stereotypes, producerField);
    }

    if (isAlternative) {
        if (alternativePriority == null) {
            alternativePriority = declaringBean.getAlternativePriority();
        }
        alternativePriority = initAlternativePriority(producerField, alternativePriority, stereotypes, beanDeployment);
        // after all attempts, priority is still null
        if (alternativePriority == null) {
            LOGGER.debugf(
                    "Ignoring producer field %s - declared as an @Alternative but not selected by @Priority, @AlternativePriority or quarkus.arc.selected-alternatives",
                    producerField);
            return null;

        }
    }

    BeanInfo bean = new BeanInfo(producerField, beanDeployment, scope, types, qualifiers, Collections.emptyList(),
            declaringBean, disposer, alternativePriority, stereotypes, name, isDefaultBean);
    return bean;
}