org.eclipse.microprofile.config.inject.ConfigProperty Java Examples

The following examples show how to use org.eclipse.microprofile.config.inject.ConfigProperty. 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: ConfigProducerUtil.java    From smallrye-config with Apache License 2.0 6 votes vote down vote up
public static String getDefaultValue(InjectionPoint injectionPoint) {
    for (Annotation qualifier : injectionPoint.getQualifiers()) {
        if (qualifier.annotationType().equals(ConfigProperty.class)) {
            String str = ((ConfigProperty) qualifier).defaultValue();
            if (!ConfigProperty.UNCONFIGURED_VALUE.equals(str)) {
                return str;
            }
            Class<?> rawType = rawTypeOf(injectionPoint.getType());
            if (rawType.isPrimitive()) {
                if (rawType == char.class) {
                    return null;
                } else if (rawType == boolean.class) {
                    return "false";
                } else {
                    return "0";
                }
            }
            return null;
        }
    }
    return null;
}
 
Example #2
Source File: ConfigProducerUtil.java    From smallrye-config with Apache License 2.0 6 votes vote down vote up
static String getConfigKey(InjectionPoint ip, ConfigProperty configProperty) {
    String key = configProperty.name();
    if (!key.trim().isEmpty()) {
        return key;
    }
    if (ip.getAnnotated() instanceof AnnotatedMember) {
        AnnotatedMember<?> member = (AnnotatedMember<?>) ip.getAnnotated();
        AnnotatedType<?> declaringType = member.getDeclaringType();
        if (declaringType != null) {
            String[] parts = declaringType.getJavaClass().getCanonicalName().split("\\.");
            StringBuilder sb = new StringBuilder(parts[0]);
            for (int i = 1; i < parts.length; i++) {
                sb.append(".").append(parts[i]);
            }
            sb.append(".").append(member.getJavaMember().getName());
            return sb.toString();
        }
    }
    throw InjectionMessages.msg.noConfigPropertyDefaultName(ip);
}
 
Example #3
Source File: ConfigPropertyProducer.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
private <T> T getValue(InjectionPoint injectionPoint, Class<T> target, boolean isOptional) {
    String name = getName(injectionPoint);
    if (name == null || name.isEmpty() || this.config == null) {
        return null;
    }

    Optional<T> configValue = this.config.getOptionalValue(name, target);
    if(!configValue.isPresent()) {
        // Check for a default value
        String defaultValue = getDefaultValue(injectionPoint);
        if(defaultValue != null && !defaultValue.contentEquals(ConfigProperty.UNCONFIGURED_VALUE)) {
            configValue = this.config.tryConvertValue(defaultValue, target);
        }
    }
    if(!isOptional && !configValue.isPresent()) {
        System.err.printf("Failed to find ConfigProperty for: %s\n", injectionPoint);
        throw new DeploymentException(String.format("%s has no configured value", name));
    }
    return configValue.orElse(null);
}
 
Example #4
Source File: ResourceManager.java    From hammock with Apache License 2.0 5 votes vote down vote up
@Inject
public ResourceManager( @ConfigProperty(name = "static.resource.location", defaultValue = "META-INF/resources/")
            String baseUri) {
   this();
   String cleanBaseUri = baseUri;
   if(cleanBaseUri.startsWith(SLASH)) {
      cleanBaseUri = cleanBaseUri.replaceFirst(SLASH, "");
   }
   if(!cleanBaseUri.endsWith(SLASH)) {
      cleanBaseUri = cleanBaseUri + SLASH;
   }
   this.cleanBaseUri = cleanBaseUri;
}
 
Example #5
Source File: ConfigExtension.java    From smallrye-config with Apache License 2.0 5 votes vote down vote up
protected void validate(@Observes AfterDeploymentValidation adv) {
    Config config = ConfigProvider.getConfig(getContextClassLoader());
    Set<String> configNames = StreamSupport.stream(config.getPropertyNames().spliterator(), false).collect(toSet());
    for (InjectionPoint injectionPoint : injectionPoints) {
        Type type = injectionPoint.getType();

        // We don't validate the Optional / Provider / Supplier / ConfigValue for defaultValue.
        if (type instanceof Class && ConfigValue.class.isAssignableFrom((Class<?>) type)
                || type instanceof Class && OptionalInt.class.isAssignableFrom((Class<?>) type)
                || type instanceof Class && OptionalLong.class.isAssignableFrom((Class<?>) type)
                || type instanceof Class && OptionalDouble.class.isAssignableFrom((Class<?>) type)
                || type instanceof ParameterizedType
                        && (Optional.class.isAssignableFrom((Class<?>) ((ParameterizedType) type).getRawType())
                                || Provider.class.isAssignableFrom((Class<?>) ((ParameterizedType) type).getRawType())
                                || Supplier.class.isAssignableFrom((Class<?>) ((ParameterizedType) type).getRawType()))) {
            return;
        }

        ConfigProperty configProperty = injectionPoint.getAnnotated().getAnnotation(ConfigProperty.class);
        String name = ConfigProducerUtil.getConfigKey(injectionPoint, configProperty);

        // Check if the name is part of the properties first. Since properties can be a subset, then search for the actual property for a value.
        if (!configNames.contains(name) && ConfigProducerUtil.getRawValue(name, (SmallRyeConfig) config) == null) {
            if (configProperty.defaultValue().equals(ConfigProperty.UNCONFIGURED_VALUE)) {
                adv.addDeploymentProblem(InjectionMessages.msg.noConfigValue(name));
            }
        }

        try {
            // Check if there is a Converter registed for the injected type
            Converter<?> resolvedConverter = ConfigProducerUtil.resolveConverter(injectionPoint, (SmallRyeConfig) config);

            // Check if the value can be converted. The TCK checks this, but this requires to get the value eagerly.
            // This should not be required!
            SecretKeys.doUnlocked(() -> ((SmallRyeConfig) config).getOptionalValue(name, resolvedConverter));
        } catch (IllegalArgumentException e) {
            adv.addDeploymentProblem(e);
        }
    }
}
 
Example #6
Source File: ConfigProducerUtil.java    From smallrye-config with Apache License 2.0 5 votes vote down vote up
public static String getName(InjectionPoint injectionPoint) {
    for (Annotation qualifier : injectionPoint.getQualifiers()) {
        if (qualifier.annotationType().equals(ConfigProperty.class)) {
            ConfigProperty configProperty = ((ConfigProperty) qualifier);
            return getConfigKey(injectionPoint, configProperty);
        }
    }
    return null;
}
 
Example #7
Source File: ConfigInjectionBean.java    From smallrye-config with Apache License 2.0 5 votes vote down vote up
@Override
public T create(CreationalContext<T> context) {
    InjectionPoint ip = (InjectionPoint) bm.getInjectableReference(new InjectionPointMetadataInjectionPoint(), context);
    Annotated annotated = ip.getAnnotated();
    ConfigProperty configProperty = annotated.getAnnotation(ConfigProperty.class);
    String key = ConfigProducerUtil.getConfigKey(ip, configProperty);
    String defaultValue = configProperty.defaultValue();

    if (annotated.getBaseType() instanceof ParameterizedType) {
        ParameterizedType paramType = (ParameterizedType) annotated.getBaseType();
        Type rawType = paramType.getRawType();

        // handle Provider<T> and Instance<T>
        if (rawType instanceof Class
                && (((Class<?>) rawType).isAssignableFrom(Provider.class)
                        || ((Class<?>) rawType).isAssignableFrom(Instance.class))
                && paramType.getActualTypeArguments().length == 1) {
            Class<?> paramTypeClass = (Class<?>) paramType.getActualTypeArguments()[0];
            return (T) getConfig().getValue(key, paramTypeClass);
        }
    } else {
        Class annotatedTypeClass = (Class) annotated.getBaseType();
        if (defaultValue == null || defaultValue.length() == 0) {
            return (T) getConfig().getValue(key, annotatedTypeClass);
        } else {
            Config config = getConfig();
            Optional<T> optionalValue = config.getOptionalValue(key, annotatedTypeClass);
            if (optionalValue.isPresent()) {
                return optionalValue.get();
            } else {
                return (T) ((SmallRyeConfig) config).convert(defaultValue, annotatedTypeClass);
            }
        }
    }

    throw InjectionMessages.msg.unhandledConfigProperty();
}
 
Example #8
Source File: JwtTokenProvider.java    From realworld-api-quarkus with MIT License 5 votes vote down vote up
public JwtTokenProvider(
    @ConfigProperty(name = "jwt.issuer") String issuer,
    @ConfigProperty(name = "jwt.secret") String secret,
    @ConfigProperty(name = "jwt.expiration.time.minutes") Integer expirationTimeInMinutes) {

  this.issuer = issuer;
  this.algorithm = Algorithm.HMAC512(secret);
  this.jwtVerifier = JWT.require(algorithm).withIssuer(issuer).build();
  this.expirationTimeInMinutes = expirationTimeInMinutes;
}
 
Example #9
Source File: ConfigBeanCreator.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public Object create(CreationalContext<Object> creationalContext, Map<String, Object> params) {
    String requiredType = params.get("requiredType").toString();
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    if (cl == null) {
        cl = ConfigBeanCreator.class.getClassLoader();
    }
    Class<?> clazz;
    try {
        clazz = Class.forName(requiredType, true, cl);
    } catch (ClassNotFoundException e) {
        throw new IllegalStateException("Cannot load required type: " + requiredType);
    }

    InjectionPoint injectionPoint = InjectionPointProvider.get();
    if (injectionPoint == null) {
        throw new IllegalStateException("No current injection point found");
    }

    ConfigProperty configProperty = getConfigProperty(injectionPoint);
    if (configProperty == null) {
        throw new IllegalStateException("@ConfigProperty not found");
    }

    String key = configProperty.name();
    String defaultValue = configProperty.defaultValue();

    if (defaultValue.isEmpty() || ConfigProperty.UNCONFIGURED_VALUE.equals(defaultValue)) {
        return getConfig().getValue(key, clazz);
    } else {
        Config config = getConfig();
        Optional<?> value = config.getOptionalValue(key, clazz);
        if (value.isPresent()) {
            return value.get();
        } else {
            return ((SmallRyeConfig) config).convert(defaultValue, clazz);
        }
    }
}
 
Example #10
Source File: ConfigBeanCreator.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private ConfigProperty getConfigProperty(InjectionPoint injectionPoint) {
    for (Annotation qualifier : injectionPoint.getQualifiers()) {
        if (qualifier.annotationType().equals(ConfigProperty.class)) {
            return (ConfigProperty) qualifier;
        }
    }
    return null;
}
 
Example #11
Source File: ConfigDescriptionBuildStep.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private void processConfig(ConfigPatternMap<Container> patterns, List<ConfigDescriptionBuildItem> ret,
        Properties javadoc) {

    patterns.forEach(new Consumer<Container>() {
        @Override
        public void accept(Container node) {
            Field field = node.findField();
            ConfigItem configItem = field.getAnnotation(ConfigItem.class);
            final ConfigProperty configProperty = field.getAnnotation(ConfigProperty.class);
            String defaultDefault;
            final Class<?> valueClass = field.getType();
            if (valueClass == boolean.class) {
                defaultDefault = "false";
            } else if (valueClass.isPrimitive() && valueClass != char.class) {
                defaultDefault = "0";
            } else {
                defaultDefault = null;
            }
            String defVal = defaultDefault;
            if (configItem != null) {
                final String itemDefVal = configItem.defaultValue();
                if (!itemDefVal.equals(ConfigItem.NO_DEFAULT)) {
                    defVal = itemDefVal;
                }
            } else if (configProperty != null) {
                final String propDefVal = configProperty.defaultValue();
                if (!propDefVal.equals(ConfigProperty.UNCONFIGURED_VALUE)) {
                    defVal = propDefVal;
                }
            }
            String javadocKey = field.getDeclaringClass().getName().replace("$", ".") + "." + field.getName();
            ret.add(new ConfigDescriptionBuildItem("quarkus." + node.getPropertyName(),
                    node.findEnclosingClass().getConfigurationClass(),
                    defVal, javadoc.getProperty(javadocKey)));
        }
    });
}
 
Example #12
Source File: PublicKeyEndpoint.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
/**
 * Check a token without an iss can be used when mp.jwt.verify.requireiss=false
 * @return result of validation test
 */
@GET
@Path("/verifyMissingIssIsOk")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed("Tester")
public JsonObject verifyMissingIssIsOk() {
    boolean pass = false;
    String msg;

    if(iss.getValue().isPresent()) {
        // The iss claim should not be provided for this endpoint
        msg = String.format("MP-JWT has iss(%s) claim", iss.getValue().get());
    }
    else if(issuer.isPresent()) {
        // Double check this as I have seen ConfigProperty.UNCONFIGURED_VALUE leak through
        if(!issuer.get().equals(ConfigProperty.UNCONFIGURED_VALUE)) {
            msg = String.format("mp.jwt.verify.issuer was provided(%s) but there was no iss in MP-JWT", issuer.get());
        }
        else {
            msg = "endpoint accessed without iss as expected PASS";
            pass = true;
        }
    }
    else {
        msg = "endpoint accessed without iss as expected PASS";
        pass = true;
    }
    JsonObject result = Json.createObjectBuilder()
        .add("pass", pass)
        .add("msg", msg)
        .build();
    return result;
}
 
Example #13
Source File: ConfigPropertyProducer.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
@Produces
@ConfigProperty
@Dependent
private Object produceConfigProperty(InjectionPoint injectionPoint) {
    System.out.printf("produceConfigProperty: %s\n", injectionPoint);
    boolean isOptional = injectionPoint.getAnnotated().getBaseType().getTypeName().startsWith("java.util.Optional");
    Class<?> toType = unwrapType(injectionPoint.getAnnotated().getBaseType());

    Object value = getValue(injectionPoint, toType, isOptional);
    return isOptional ? Optional.ofNullable(value) : value;
}
 
Example #14
Source File: ConfigPropertyProducer.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
private String getName(InjectionPoint injectionPoint) {
    for (Annotation qualifier : injectionPoint.getQualifiers()) {
        if (qualifier.annotationType().equals(ConfigProperty.class)) {
            // Check for a non-default value
            String name = ((ConfigProperty) qualifier).name();
            if(name.length() == 0) {
                //
                name = injectionPoint.getBean().getBeanClass().getTypeName() + "." + injectionPoint.getMember().getName();
            }
            return name;
        }
    }
    return null;
}
 
Example #15
Source File: ConfigPropertyProducer.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
private String getDefaultValue(InjectionPoint injectionPoint) {
    String defaultValue = null;
    for (Annotation qualifier : injectionPoint.getQualifiers()) {
        if (qualifier.annotationType().equals(ConfigProperty.class)) {
            // Check for a non-default value
            defaultValue = ((ConfigProperty) qualifier).defaultValue();
            if(defaultValue.length() == 0) {
                defaultValue = null;
            }
            break;
        }
    }
    return defaultValue;
}
 
Example #16
Source File: MPConfigExtension.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
/**
 * Collect the types of all injection points annotated with @ConfigProperty.
 * @param pip - the injection point event information
 */
void processConfigPropertyInjections(@Observes ProcessInjectionPoint pip) {
    System.out.printf("pip: %s\n", pip.getInjectionPoint());
    InjectionPoint ip = pip.getInjectionPoint();
    if (ip.getAnnotated().isAnnotationPresent(ConfigProperty.class)) {
        configPropertyTypes.add(ip.getType());
        System.out.printf("+++ Added ConfigProperty target type: %s\n", ip.getType());
    }
}
 
Example #17
Source File: MPConfigExtension.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
void doProcessBeanAttributes(@Observes ProcessBeanAttributes pba) {
    System.out.printf("pab: %s\n", pba.getAnnotated());
    if (pba.getAnnotated().isAnnotationPresent(ConfigProperty.class)) {
        System.out.printf("\t+++ has ConfigProperty annotation\n");
        //pba.setBeanAttributes(new ConverterBeanAttribute(pba.getBeanAttributes(), types));
    }
}
 
Example #18
Source File: MPConfigExtension.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
void doProcessBean(@Observes ProcessBean pb) {
    System.out.printf("pb: %s, class:%s, types:%s\n", pb.getAnnotated(), pb.getBean().getBeanClass(), pb.getBean().getTypes());
    if (pb.getAnnotated().isAnnotationPresent(ConfigProperty.class)) {
        System.out.printf("\t+++ has ConfigProperty annotation\n");
        //pba.setBeanAttributes(new ConverterBeanAttribute(pba.getBeanAttributes(), types));
    }
}
 
Example #19
Source File: VertxJobsService.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Inject
public VertxJobsService(@ConfigProperty(name = "kogito.jobs-service.url") String jobServiceUrl,
                        @ConfigProperty(name = "kogito.service.url") String callbackEndpoint,
                        Vertx vertx,
                        Instance<WebClient> providedWebClient) {
    super(jobServiceUrl, callbackEndpoint);
    this.vertx = vertx;
    this.providedWebClient = providedWebClient;
}
 
Example #20
Source File: MPConfigExtension.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
/**
 * Replace our {@linkplain ConfigPropertyProducer#produceConfigProperty(InjectionPoint)} BeanAttributes with
 * {@linkplain ConfigPropertyBeanAttribute} to properly reflect all of the type locations the producer method applies to.
 * @see ConfigPropertyBeanAttribute
 * @param pba
 */
public void addTypeToConfigProperty(@Observes ProcessBeanAttributes<Object> pba) {
    if (pba.getAnnotated().isAnnotationPresent(ConfigProperty.class)) {
        System.out.printf("addTypeToConfigProperty: %s", pba);
        pba.setBeanAttributes(new ConfigPropertyBeanAttribute(pba.getBeanAttributes(), configPropertyTypes));
    }
}
 
Example #21
Source File: InterfaceNoGetterWithMissingConfigPropertiesTest.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@ConfigProperty(name = "foo")
String foo();
 
Example #22
Source File: TypicalInterfaceConfigPropertiesTest.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@ConfigProperty(name = "optionalIntList")
Optional<List<Integer>> intListOptional();
 
Example #23
Source File: MPConfigExtension.java    From microprofile-jwt-auth with Apache License 2.0 4 votes vote down vote up
void findNeededConfigPropertyProducers(@Observes ProcessInjectionTarget<ConfigProperty> pit) {
    System.out.printf("ConfigPropertyTarget: %s", pit.getInjectionTarget());
}
 
Example #24
Source File: TypicalInterfaceConfigPrefixTest.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@ConfigProperty(name = "optionalIntList")
Optional<List<Integer>> intListOptional();
 
Example #25
Source File: TypicalInterfaceConfigPrefixTest.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@ConfigProperty(name = "optionalStringList")
Optional<List<String>> stringListOptional();
 
Example #26
Source File: TypicalInterfaceConfigPrefixTest.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@ConfigProperty(name = "optionalString")
Optional<String> stringOptional();
 
Example #27
Source File: TypicalInterfaceConfigPrefixTest.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@ConfigProperty(name = "name")
String getFirstName();
 
Example #28
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 #29
Source File: TypicalInterfaceConfigPrefixTest.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@ConfigProperty(name = "boolWD", defaultValue = "false")
boolean isBoolWithDef();
 
Example #30
Source File: TypicalInterfaceConfigPrefixTest.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@ConfigProperty(name = "doubleWithDefault", defaultValue = "1.0")
Double doubleWithDefault();