Java Code Examples for org.eclipse.microprofile.config.spi.Converter

The following examples show how to use org.eclipse.microprofile.config.spi.Converter. These examples are extracted from open source projects. 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 Project: microprofile-config   Source File: CustomConverterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Deployment
public static WebArchive deploy() {
    JavaArchive testJar = ShrinkWrap
        .create(JavaArchive.class, "customConverterTest.jar")
        .addClass(CustomConverterTest.class)
        .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
        .addAsServiceProvider(Converter.class,
                              IntegerConverter.class,
                              LongConverter.class,
                              DoubleConverter.class,
                              BooleanConverter.class,
                              CharacterConverter.class)
        .as(JavaArchive.class);

    AbstractTest.addFile(testJar, "META-INF/microprofile-config.properties");

    return ShrinkWrap
        .create(WebArchive.class, "customConverterTest.war")
        .addAsLibrary(testJar);
}
 
Example 2
Source Project: smallrye-config   Source File: SmallRyeConfig.java    License: Apache License 2.0 6 votes vote down vote up
private Map<Type, Converter<?>> buildConverters(final SmallRyeConfigBuilder builder) {
    final Map<Type, SmallRyeConfigBuilder.ConverterWithPriority> convertersToBuild = new HashMap<>(builder.getConverters());

    if (builder.isAddDiscoveredConverters()) {
        for (Converter converter : builder.discoverConverters()) {
            Type type = Converters.getConverterType(converter.getClass());
            if (type == null) {
                throw ConfigMessages.msg.unableToAddConverter(converter);
            }
            SmallRyeConfigBuilder.addConverter(type, converter, convertersToBuild);
        }
    }

    final ConcurrentHashMap<Type, Converter<?>> converters = new ConcurrentHashMap<>(Converters.ALL_CONVERTERS);
    convertersToBuild.forEach(
            (type, converterWithPriority) -> converters.put(type, converterWithPriority.getConverter()));

    return converters;
}
 
Example 3
Source Project: smallrye-config   Source File: SmallRyeConfig.java    License: Apache License 2.0 6 votes vote down vote up
public <T> T getValue(String name, Converter<T> converter) {
    String value = getRawValue(name);
    final T converted;
    if (value != null) {
        converted = converter.convert(value);
    } else {
        try {
            converted = converter.convert("");
        } catch (IllegalArgumentException ignored) {
            throw ConfigMessages.msg.propertyNotFound(name);
        }
    }
    if (converted == null) {
        throw ConfigMessages.msg.propertyNotFound(name);
    }
    return converted;
}
 
Example 4
Source Project: microprofile-jwt-auth   Source File: DefaultConfig.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Use the {@link Converter}s registered with the config to convert a String value to a target property type.
 * @param svalue - the string value representation of the property
 * @param propertyType - the desired Java type of the property
 * @return the converted value
 * @throws TypeNotPresentException if there is no registered Converter
 */
public <T> T convertValue(String svalue, Class<T> propertyType) {
    T value = null;
    if(propertyType.isAssignableFrom(String.class)) {
        value = propertyType.cast(svalue);
    }
    else {
        Converter<T> converter = converters.get(propertyType);
        if(converter != null) {
            value = converter.convert(svalue);
        }
        else {
            System.err.printf("Failed to find Converter for type: %s\n", propertyType);
            throw new TypeNotPresentException(propertyType.getTypeName(), null);
        }
    }
    return value;
}
 
Example 5
Source Project: smallrye-config   Source File: ConfigProducerUtil.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static <T> Converter<T> resolveConverter(final Type type, final SmallRyeConfig src) {
    Class<T> rawType = rawTypeOf(type);
    if (type instanceof ParameterizedType) {
        ParameterizedType paramType = (ParameterizedType) type;
        Type[] typeArgs = paramType.getActualTypeArguments();
        if (rawType == List.class) {
            return (Converter<T>) Converters.newCollectionConverter(resolveConverter(typeArgs[0], src), ArrayList::new);
        } else if (rawType == Set.class) {
            return (Converter<T>) Converters.newCollectionConverter(resolveConverter(typeArgs[0], src), HashSet::new);
        } else if (rawType == Optional.class) {
            return (Converter<T>) Converters.newOptionalConverter(resolveConverter(typeArgs[0], src));
        } else if (rawType == Supplier.class) {
            return resolveConverter(typeArgs[0], src);
        }
    }
    // just try the raw type
    return src.getConverter(rawType);
}
 
Example 6
Source Project: smallrye-config   Source File: ImplicitConverters.java    License: Apache License 2.0 6 votes vote down vote up
static <T> Converter<T> getConverter(Class<? extends T> clazz) {
    // implicit converters required by the specification
    Converter<T> converter = getConverterFromStaticMethod(clazz, "of", String.class);
    if (converter == null) {
        converter = getConverterFromStaticMethod(clazz, "of", CharSequence.class);
        if (converter == null) {
            converter = getConverterFromStaticMethod(clazz, "valueOf", String.class);
            if (converter == null) {
                converter = getConverterFromStaticMethod(clazz, "valueOf", CharSequence.class);
                if (converter == null) {
                    converter = getConverterFromStaticMethod(clazz, "parse", String.class);
                    if (converter == null) {
                        converter = getConverterFromStaticMethod(clazz, "parse", CharSequence.class);
                        if (converter == null) {
                            converter = getConverterFromConstructor(clazz, String.class);
                            if (converter == null) {
                                converter = getConverterFromConstructor(clazz, CharSequence.class);
                            }
                        }
                    }
                }
            }
        }
    }
    return converter;
}
 
Example 7
Source Project: microprofile-jwt-auth   Source File: DefaultConfig.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Use the {@link Converter}s registered with the config to try to convert a String value to a target property type.
 * @param svalue - the string value representation of the property
 * @param propertyType - the desired Java type of the property
 * @return the converted value if a matching converter is found, Optional.empty() otherwise
 */
public <T> Optional<T> tryConvertValue(String svalue, Class<T> propertyType) {
    Optional<T> value = Optional.empty();
    if(propertyType.isAssignableFrom(String.class)) {
        value = Optional.of((T)svalue);
    }
    else {
        Converter<T> converter = converters.get(propertyType);
        if(converter != null) {
            value = Optional.of(converter.convert(svalue));
        }
        else {
            System.err.printf("Failed to find Converter for type: %s\n", propertyType);
        }
    }
    return value;
}
 
Example 8
Source Project: microprofile-jwt-auth   Source File: DefaultConfig.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <T> Optional<T> getOptionalValue(String propertyName, Class<T> propertyType) {
    Optional<T> value = Optional.empty();
    for (ConfigSource cs : sources) {
        String svalue = cs.getValue(propertyName);
        if(svalue == null) {
            value = Optional.empty();
        }
        else if(propertyType.isAssignableFrom(String.class)) {
            value = Optional.of(propertyType.cast(svalue));
            break;
        }
        else {
            Converter<T> converter = converters.get(propertyType);
            if(converter != null) {
                value = Optional.of(converter.convert(svalue));
            }
            else {
                System.err.printf("Failed to find Converter for: %s of type: %s\n", propertyName, propertyType);
            }
            break;
        }
    }
    return value;
}
 
Example 9
Source Project: quarkus   Source File: ConfigBuildSteps.java    License: Apache License 2.0 6 votes vote down vote up
@BuildStep
void nativeServiceProviders(
        final BuildProducer<ServiceProviderBuildItem> providerProducer) throws IOException {
    providerProducer.produce(new ServiceProviderBuildItem(ConfigProviderResolver.class.getName(),
            SmallRyeConfigProviderResolver.class.getName()));
    final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    classLoader.getResources(SERVICES_PREFIX + ConfigSourceProvider.class.getName());
    for (Class<?> serviceClass : Arrays.asList(
            ConfigSource.class,
            ConfigSourceProvider.class,
            Converter.class)) {
        final String serviceName = serviceClass.getName();
        final Set<String> names = ServiceUtil.classNamesNamedIn(classLoader, SERVICES_PREFIX + serviceName);
        final List<String> list = names.stream()
                // todo: see https://github.com/quarkusio/quarkus/issues/5492
                .filter(s -> !s.startsWith("org.jboss.resteasy.microprofile.config.")).collect(Collectors.toList());
        if (!list.isEmpty()) {
            providerProducer.produce(new ServiceProviderBuildItem(serviceName, list));
        }
    }
}
 
Example 10
Source Project: smallrye-config   Source File: ConverterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Deployment
public static WebArchive deploy() {
    return ShrinkWrap
            .create(WebArchive.class, "CollectionWithConfiguredValueTest.war")
            .addClasses(ConverterTest.class, ConverterBean.class)
            .addClass(IntConverter.class)
            .addAsServiceProvider(Converter.class, IntConverter.class)
            .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
}
 
Example 11
Source Project: smallrye-config   Source File: SmallRyeConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Deprecated
protected SmallRyeConfig(List<ConfigSource> configSources, Map<Type, Converter<?>> converters) {
    this.configSources = new AtomicReference<>(
            new ConfigSources(configSources, buildInterceptors(new SmallRyeConfigBuilder())));
    this.converters = new ConcurrentHashMap<>(Converters.ALL_CONVERTERS);
    this.converters.putAll(converters);
}
 
Example 12
@Override
public ConfigBuilder withConverters(Converter<?>[] converters) {
    for(Converter converter : converters) {
        config.addConverter(converter);
    }
    return this;
}
 
Example 13
Source Project: smallrye-config   Source File: Converters.java    License: Apache License 2.0 5 votes vote down vote up
RangeCheckConverter(final Comparator<? super T> cmp, final Converter<? extends T> delegate, final T min,
        final boolean minInclusive, final T max, final boolean maxInclusive) {
    this.comparator = cmp;
    this.delegate = delegate;
    this.min = min;
    this.minInclusive = minInclusive;
    this.max = max;
    this.maxInclusive = maxInclusive;
}
 
Example 14
Source Project: hammock   Source File: ConfigArchiveAppender.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void process(Archive<?> archive, TestClass testClass) {
    archive.as(JavaArchive.class)
        .addPackages(true, ConfigImpl.class.getPackage())
        .addAsServiceProvider(Converter.class, DuckConverter.class)
        .addAsServiceProvider(ConfigProviderResolver.class, DefaultConfigProvider.class);
}
 
Example 15
Source Project: microprofile-jwt-auth   Source File: DefaultConfig.java    License: Apache License 2.0 5 votes vote down vote up
public void addConverter(Converter converter) {
    // Determine the target type of the converter
    Type[] genericInterfaces = converter.getClass().getGenericInterfaces();
    for(Type type : genericInterfaces) {
        if(type instanceof ParameterizedType) {
            ParameterizedType ptype = (ParameterizedType) type;
            if(ptype.getRawType().equals(Converter.class)) {
                Type actualType = ptype.getActualTypeArguments()[0];
                converters.put(actualType, converter);
                System.out.printf("+++ Added converter(%s) for type: %s\n", converter, actualType);
            }
        }
    }
}
 
Example 16
Source Project: quarkus   Source File: ConfigInstantiator.java    License: Apache License 2.0 5 votes vote down vote up
private static Converter<?> getConverterFor(Type type) {
    // hopefully this is enough
    final SmallRyeConfig config = (SmallRyeConfig) ConfigProvider.getConfig();
    Class<?> rawType = rawTypeOf(type);
    if (Enum.class.isAssignableFrom(rawType)) {
        return new HyphenateEnumConverter(rawType);
    } else if (rawType == Optional.class) {
        return Converters.newOptionalConverter(getConverterFor(typeOfParameter(type, 0)));
    } else if (rawType == List.class) {
        return Converters.newCollectionConverter(getConverterFor(typeOfParameter(type, 0)), ArrayList::new);
    } else {
        return config.getConverter(rawTypeOf(type));
    }
}
 
Example 17
Source Project: microprofile-config   Source File: ArrayConverterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Deployment
public static WebArchive deploy() {
    JavaArchive testJar = ShrinkWrap
            .create(JavaArchive.class, "arrayConverterTest.jar")
            .addPackage(PizzaConverter.class.getPackage())
            .addClasses(ArrayConverterTest.class, ArrayConverterBean.class)
            .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
            .addAsServiceProvider(Converter.class, PizzaConverter.class)
            .as(JavaArchive.class);
        addFile(testJar, "META-INF/microprofile-config.properties");
        WebArchive war = ShrinkWrap
            .create(WebArchive.class, "arrayConverterTest.war")
            .addAsLibrary(testJar);
        return war;
}
 
Example 18
Source Project: smallrye-config   Source File: ConfigExtension.java    License: 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 19
@Deployment
public static WebArchive deploy() {
    JavaArchive testJar = ShrinkWrap
            .create(JavaArchive.class, "customConfigSourceTest.jar")
            .addClasses(AutoDiscoveredConfigSourceTest.class, CustomDbConfigSource.class, Pizza.class, PizzaConverter.class)
            .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
            .addAsServiceProvider(ConfigSource.class, CustomDbConfigSource.class)
            .addAsServiceProvider(Converter.class, PizzaConverter.class)
            .as(JavaArchive.class);

    WebArchive war = ShrinkWrap
            .create(WebArchive.class, "customConfigSourceTest.war")
            .addAsLibrary(testJar);
    return war;
}
 
Example 20
Source Project: hammock   Source File: ConfigArchiveAppender.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void process(Archive<?> archive, TestClass testClass) {
    if (archive instanceof WebArchive) {
        JavaArchive jar = ShrinkWrap.create(JavaArchive.class, "geronimo-config.jar")
                .addPackages(true, ConfigImpl.class.getPackage())
                .addAsServiceProvider(Converter.class, DuckConverter.class)
                .addAsServiceProvider(ConfigProviderResolver.class, DefaultConfigProvider.class)
                .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
        archive.as(WebArchive.class).addAsLibrary(jar);
    }
}
 
Example 21
Source Project: smallrye-config   Source File: ImplicitConverters.java    License: Apache License 2.0 5 votes vote down vote up
private static <T> Converter<T> getConverterFromConstructor(Class<? extends T> clazz, Class<? super String> paramType) {
    try {
        final Constructor<? extends T> declaredConstructor = SecuritySupport.getDeclaredConstructor(clazz, paramType);
        if (!isAccessible(declaredConstructor)) {
            SecuritySupport.setAccessible(declaredConstructor, true);
        }
        return new ConstructorConverter<>(declaredConstructor);
    } catch (NoSuchMethodException e) {
        return null;
    }
}
 
Example 22
Source Project: smallrye-config   Source File: SmallRyeConfigBuilder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public SmallRyeConfigBuilder withConverters(Converter<?>[] converters) {
    for (Converter<?> converter : converters) {
        Type type = Converters.getConverterType(converter.getClass());
        if (type == null) {
            throw ConfigMessages.msg.unableToAddConverter(converter);
        }
        addConverter(type, getPriority(converter), converter, this.converters);
    }
    return this;
}
 
Example 23
Source Project: smallrye-config   Source File: SmallRyeConfigBuilder.java    License: Apache License 2.0 5 votes vote down vote up
static void addConverter(Type type, int priority, Converter<?> converter,
        Map<Type, ConverterWithPriority> converters) {
    // add the converter only if it has a higher priority than another converter for the same type
    ConverterWithPriority oldConverter = converters.get(type);
    int newPriority = getPriority(converter);
    if (oldConverter == null || priority > oldConverter.priority) {
        converters.put(type, new ConverterWithPriority(converter, newPriority));
    }
}
 
Example 24
Source Project: smallrye-config   Source File: SmallRyeConfigBuilder.java    License: Apache License 2.0 5 votes vote down vote up
private static int getPriority(Converter<?> converter) {
    int priority = 100;
    Priority priorityAnnotation = converter.getClass().getAnnotation(Priority.class);
    if (priorityAnnotation != null) {
        priority = priorityAnnotation.value();
    }
    return priority;
}
 
Example 25
@ParameterizedTest(name = "{0} - {2}")
@MethodSource("data")
public void testSimple(Class<T> type, T expected, String string) {
    SmallRyeConfig config = buildConfig();
    final Converter<T> converter = config.getConverter(type);
    assertEquals(expected, converter.convert(string));
}
 
Example 26
@ParameterizedTest(name = "{0} - {2}")
@MethodSource("data")
public void testLeadingSpace(Class<T> type, T expected, String string) {
    SmallRyeConfig config = buildConfig();
    final Converter<T> converter = config.getConverter(type);
    assertEquals(expected, converter.convert(" " + string));
}
 
Example 27
@ParameterizedTest(name = "{0} - {2}")
@MethodSource("data")
public void testLeadingAndTrailingWhitespaces(Class<T> type, T expected, String string) {
    SmallRyeConfig config = buildConfig();
    final Converter<T> converter = config.getConverter(type);
    assertEquals(expected, converter.convert(" \t " + string + "\t\t "));
}
 
Example 28
Source Project: quarkus   Source File: BuildTimeConfigurationReader.java    License: Apache License 2.0 5 votes vote down vote up
private void readConfigValue(String fullName, ClassDefinition.ItemMember member, Object instance) {
    Field field = member.getField();
    Converter<?> converter = getConverter(config, field, ConverterType.of(field));
    Object val = config.getValue(fullName, converter);
    try {
        field.set(instance, val);
    } catch (IllegalAccessException e) {
        throw toError(e);
    }
}
 
Example 29
protected AbstractSimpleDelegatingConverter(final Converter<? extends T> delegate) {
    super(delegate);
}
 
Example 30
Source Project: quarkus   Source File: ConverterClassHolder.java    License: Apache License 2.0 4 votes vote down vote up
public ConverterClassHolder(Class<?> type, Class<? extends Converter<?>> converterType) {
    this.type = type;
    this.converterType = converterType;
}