io.smallrye.config.SmallRyeConfig Java Examples
The following examples show how to use
io.smallrye.config.SmallRyeConfig.
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: DotEnvTestCase.java From quarkus with Apache License 2.0 | 6 votes |
private SmallRyeConfig buildConfig(Map<String, String> configMap) throws IOException { final SmallRyeConfigBuilder builder = new SmallRyeConfigBuilder(); final Path dotEnv = Files.createTempFile("test-", ".env"); try (OutputStream fos = Files.newOutputStream(dotEnv, StandardOpenOption.WRITE, StandardOpenOption.APPEND)) { try (OutputStreamWriter osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8)) { try (BufferedWriter bw = new BufferedWriter(osw)) { for (Map.Entry<String, String> entry : configMap.entrySet()) { bw.write(entry.getKey()); bw.write('='); bw.write(entry.getValue()); bw.newLine(); } } } } builder.withSources(new ConfigUtils.DotEnvConfigSource(dotEnv)); final SmallRyeConfig config = builder.build(); Files.delete(dotEnv); cpr.registerConfig(config, classLoader); return config; }
Example #2
Source File: ConfigProfileTestCase.java From quarkus with Apache License 2.0 | 6 votes |
@Test public void testBackwardCompatibleOrdinalProfile() { System.setProperty("quarkus-profile", "foo"); try { final SmallRyeConfigBuilder builder = new SmallRyeConfigBuilder(); builder.withInterceptors(new QuarkusProfileConfigSourceInterceptor(ProfileManager.getActiveProfile())); builder.withSources(new PropertiesConfigSource(new HashMap<String, String>() { { put("foo", "default"); } }, "source", Integer.MAX_VALUE)); builder.withSources(new PropertiesConfigSource(new HashMap<String, String>() { { put("%foo.foo", "profile"); } }, "source", Integer.MIN_VALUE)); final SmallRyeConfig config = builder.build(); cpr.registerConfig(config, classLoader); assertEquals("profile", config.getValue("foo", String.class)); } finally { System.clearProperty("quarkus-profile"); } }
Example #3
Source File: ConfigProfileTestCase.java From quarkus with Apache License 2.0 | 6 votes |
@Test public void testBackwardCompatibleOverridenProfile() { System.setProperty("quarkus-profile", "foo"); try { final SmallRyeConfig config = buildConfig(maps( singletonMap("foo.one", "v1"), singletonMap("foo.two", "v2"), singletonMap("%foo.foo.three", "f1"), singletonMap("%prod.foo.four", "v4"))); assertEquals("v1", config.getValue("foo.one", String.class)); assertEquals("v2", config.getValue("foo.two", String.class)); assertEquals("f1", config.getValue("foo.three", String.class)); assertFalse(config.getOptionalValue("foo.four", String.class).isPresent()); } finally { System.clearProperty("quarkus-profile"); } }
Example #4
Source File: ConfigProducerUtil.java From smallrye-config with Apache License 2.0 | 6 votes |
@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 #5
Source File: ConfigProfileTestCase.java From quarkus with Apache License 2.0 | 6 votes |
@Test public void testOverridenProfile() { System.setProperty("quarkus.profile", "foo"); try { final SmallRyeConfig config = buildConfig(maps( singletonMap("foo.one", "v1"), singletonMap("foo.two", "v2"), singletonMap("%foo.foo.three", "f1"), singletonMap("%prod.foo.four", "v4"))); assertEquals("v1", config.getValue("foo.one", String.class)); assertEquals("v2", config.getValue("foo.two", String.class)); assertEquals("f1", config.getValue("foo.three", String.class)); assertFalse(config.getOptionalValue("foo.four", String.class).isPresent()); } finally { System.clearProperty("quarkus.profile"); } }
Example #6
Source File: ConfigProfileTestCase.java From quarkus with Apache License 2.0 | 5 votes |
@Test public void testDefaultProfile() { final SmallRyeConfig config = buildConfig(maps( singletonMap("foo.one", "v1"), singletonMap("foo.two", "v2"), singletonMap("%foo.foo.three", "f1"), singletonMap("%prod.foo.four", "v4"))); assertEquals("v1", config.getValue("foo.one", String.class)); assertEquals("v2", config.getValue("foo.two", String.class)); assertFalse(config.getOptionalValue("foo.three", String.class).isPresent()); assertEquals("v4", config.getValue("foo.four", String.class)); }
Example #7
Source File: ConfigInstantiator.java From quarkus with Apache License 2.0 | 5 votes |
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 #8
Source File: QuarkusConfigFactory.java From quarkus with Apache License 2.0 | 5 votes |
public SmallRyeConfig getConfigFor(final SmallRyeConfigProviderResolver configProviderResolver, final ClassLoader classLoader) { if (config == null) { //TODO: this code path is only hit when start fails in dev mode very early in the process //the recovery code will fail without this as it cannot read any properties such as //the HTTP port or logging info return configProviderResolver.getBuilder().forClassLoader(classLoader) .addDefaultSources() .addDiscoveredSources() .addDiscoveredConverters() .build(); } return config; }
Example #9
Source File: ConfigurationSubstitutions.java From quarkus with Apache License 2.0 | 5 votes |
@Substitute public Config getConfig() { final SmallRyeConfig config = Target_io_quarkus_runtime_configuration_QuarkusConfigFactory.config; if (config == null) { throw new IllegalStateException("No configuration is available"); } return config; }
Example #10
Source File: ConfigExpanderTestCase.java From quarkus with Apache License 2.0 | 5 votes |
private SmallRyeConfig buildConfig(Map<String, String> configMap) { final SmallRyeConfigBuilder builder = new SmallRyeConfigBuilder(); builder.withInterceptors(new ExpressionConfigSourceInterceptor()); builder.withSources(new PropertiesConfigSource(configMap, "test input", 500)); final SmallRyeConfig config = (SmallRyeConfig) builder.build(); cpr.registerConfig(config, classLoader); this.config = config; return config; }
Example #11
Source File: ConfigExpanderTestCase.java From quarkus with Apache License 2.0 | 5 votes |
@Test public void testBasicExpander() { final SmallRyeConfig config = buildConfig(maps( singletonMap("foo.one", "value"), singletonMap("foo.two", "${foo.one}"), singletonMap("foo.three", "+${foo.two}+"))); assertEquals("value", config.getValue("foo.one", String.class)); assertEquals("value", config.getValue("foo.two", String.class)); assertEquals("+value+", config.getValue("foo.three", String.class)); }
Example #12
Source File: ConfigExpanderTestCase.java From quarkus with Apache License 2.0 | 5 votes |
@Test public void testExpanderDefaults() { final SmallRyeConfig config = buildConfig(maps( singletonMap("foo.two", "${foo.one:value}"), singletonMap("foo.three", "+${foo.two}+"))); assertEquals("value", config.getValue("foo.two", String.class)); assertEquals("+value+", config.getValue("foo.three", String.class)); }
Example #13
Source File: ConfigExpanderTestCase.java From quarkus with Apache License 2.0 | 5 votes |
@Test public void testExpanderOptional() { final SmallRyeConfig config = buildConfig(maps( singletonMap("foo.two", "${foo.one:}empty"), singletonMap("foo.three", "+${foo.two}+"))); assertEquals("empty", config.getValue("foo.two", String.class)); assertEquals("+empty+", config.getValue("foo.three", String.class)); }
Example #14
Source File: ConfigExpanderTestCase.java From quarkus with Apache License 2.0 | 5 votes |
@Test public void testStackBlowOut() { final SmallRyeConfig config = buildConfig(maps( singletonMap("foo.blowout", "${foo.blowout}"))); try { config.getValue("foo.blowout", String.class); fail("Expected exception"); } catch (IllegalArgumentException expected) { // OK } }
Example #15
Source File: ConfigProfileTestCase.java From quarkus with Apache License 2.0 | 5 votes |
private SmallRyeConfig buildConfig(Map<String, String> configMap) { final SmallRyeConfigBuilder builder = new SmallRyeConfigBuilder(); builder.withInterceptors(new QuarkusProfileConfigSourceInterceptor(ProfileManager.getActiveProfile())); builder.withSources(new PropertiesConfigSource(configMap, "test input", 500)); final SmallRyeConfig config = (SmallRyeConfig) builder.build(); cpr.registerConfig(config, classLoader); this.config = config; return config; }
Example #16
Source File: InjectionTestConfigFactory.java From smallrye-config with Apache License 2.0 | 5 votes |
@Override public SmallRyeConfig getConfigFor( final SmallRyeConfigProviderResolver configProviderResolver, final ClassLoader classLoader) { return configProviderResolver.getBuilder().forClassLoader(classLoader) .addDefaultSources() .withSources(new PropertiesConfigSource(new HashMap<String, String>() { { put("testkey", "testvalue"); } }, "memory", 0)) .addDefaultInterceptors() .build(); }
Example #17
Source File: DotEnvTestCase.java From quarkus with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") @Test public void testProperties() throws IOException { final SmallRyeConfig config = buildConfig(maps( singletonMap("FOO_BAR", "foo.bar"), singletonMap("foo.baz", "nothing"))); assertEquals("foo.bar", config.getValue("foo.bar", String.class)); assertFalse(config.getOptionalValue("foo.baz", String.class).isPresent()); }
Example #18
Source File: CustomInvokeWithJsonPProviderTest.java From quarkus with Apache License 2.0 | 5 votes |
@BeforeTest public void setupClient() throws Exception { SmallRyeConfig config = ConfigUtils.configBuilder(true).build(); QuarkusConfigFactory.setConfig(config); ConfigProviderResolver cpr = ConfigProviderResolver.instance(); try { Config old = cpr.getConfig(); if (old != config) { cpr.releaseConfig(old); } } catch (IllegalStateException ignored) { } super.setupClient(); }
Example #19
Source File: CustomInvokeWithJsonBProviderTest.java From quarkus with Apache License 2.0 | 5 votes |
@BeforeTest public void setupClient() throws Exception { SmallRyeConfig config = ConfigUtils.configBuilder(true).build(); QuarkusConfigFactory.setConfig(config); ConfigProviderResolver cpr = ConfigProviderResolver.instance(); try { Config old = cpr.getConfig(); if (old != config) { cpr.releaseConfig(old); } } catch (IllegalStateException ignored) { } super.setupClient(); }
Example #20
Source File: ConfigPropertiesUtil.java From quarkus with Apache License 2.0 | 5 votes |
/** * Generates code that uses Config#getValue for simple objects, or SmallRyeConfig#getValues if it is a Collection * type. * * @param propertyName Property name that needs to be fetched * @param resultType Type to which the property value needs to be converted to * @param declaringClass Config class where the type was encountered * @param bytecodeCreator Where the bytecode will be generated * @param config Reference to the MP config object */ static ResultHandle createReadMandatoryValueAndConvertIfNeeded(String propertyName, Type resultType, DotName declaringClass, BytecodeCreator bytecodeCreator, ResultHandle config) { if (isCollection(resultType)) { ResultHandle smallryeConfig = bytecodeCreator.checkCast(config, SmallRyeConfig.class); Class<?> factoryToUse = DotNames.SET.equals(resultType.name()) ? HashSetFactory.class : ArrayListFactory.class; ResultHandle collectionFactory = bytecodeCreator.invokeStaticMethod( MethodDescriptor.ofMethod(factoryToUse, "getInstance", factoryToUse)); return bytecodeCreator.invokeVirtualMethod( MethodDescriptor.ofMethod(SmallRyeConfig.class, "getValues", Collection.class, String.class, Class.class, IntFunction.class), smallryeConfig, bytecodeCreator.load(propertyName), bytecodeCreator.loadClass(determineSingleGenericType(resultType, declaringClass).name().toString()), collectionFactory); } else { return bytecodeCreator.invokeInterfaceMethod( MethodDescriptor.ofMethod(Config.class, "getValue", Object.class, String.class, Class.class), config, bytecodeCreator.load(propertyName), bytecodeCreator.loadClass(resultType.name().toString())); } }
Example #21
Source File: ClusterIT.java From apicurio-registry with Apache License 2.0 | 5 votes |
@BeforeAll public static void startCluster() throws Exception { // hack around Quarkus core config factory ... ClassLoader systemCL = new ClassLoader(null) {}; Config config = ConfigProviderResolver.instance().getConfig(systemCL); QuarkusConfigFactory.setConfig((SmallRyeConfig) config); ClusterUtils.startCluster(); }
Example #22
Source File: ConfigExtension.java From smallrye-config with Apache License 2.0 | 5 votes |
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 #23
Source File: ConfigProducerUtil.java From smallrye-config with Apache License 2.0 | 5 votes |
public static <T> T getValue(InjectionPoint injectionPoint, Config config) { String name = getName(injectionPoint); if (name == null) { return null; } final SmallRyeConfig src = (SmallRyeConfig) config; Converter<T> converter = resolveConverter(injectionPoint, src); String rawValue = getRawValue(name, src); if (rawValue == null) { rawValue = getDefaultValue(injectionPoint); } T converted; if (rawValue == null) { // convert an empty value try { converted = converter.convert(""); } catch (IllegalArgumentException ignored) { throw InjectionMessages.msg.propertyNotFound(name); } } else { converted = converter.convert(rawValue); } if (converted == null) { throw InjectionMessages.msg.propertyNotFound(name); } return converted; }
Example #24
Source File: ConfigProducerUtil.java From smallrye-config with Apache License 2.0 | 5 votes |
public static ConfigValue getConfigValue(InjectionPoint injectionPoint, Config config) { String name = getName(injectionPoint); if (name == null) { return null; } ConfigValue configValue = ((SmallRyeConfig) config).getConfigValue(name); if (configValue.getValue() == null) { configValue = configValue.withValue(getDefaultValue(injectionPoint)); } return configValue; }
Example #25
Source File: ConfigInjectionBean.java From smallrye-config with Apache License 2.0 | 5 votes |
@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 #26
Source File: InjectionTestConfigFactory.java From smallrye-config with Apache License 2.0 | 5 votes |
@Override public SmallRyeConfig getConfigFor( final SmallRyeConfigProviderResolver configProviderResolver, final ClassLoader classLoader) { return configProviderResolver.getBuilder().forClassLoader(classLoader) .addDefaultSources() .addDefaultInterceptors() .withSources(KeyValuesConfigSource.config("my.prop", "1234", "expansion", "${my.prop}", "secret", "12345678")) .withSources(new ConfigSource() { int counter = 1; @Override public Map<String, String> getProperties() { return new HashMap<>(); } @Override public String getValue(final String propertyName) { return "my.counter".equals(propertyName) ? "" + counter++ : null; } @Override public String getName() { return this.getClass().getName(); } }) .withSources(KeyValuesConfigSource.config("optional.int.value", "1", "optional.long.value", "2", "optional.double.value", "3.3")) .withSecretKeys("secret") .build(); }
Example #27
Source File: ConfigPropertiesUtil.java From quarkus with Apache License 2.0 | 5 votes |
/** * Generates code that uses Config#getOptionalValue for simple objects, or SmallRyeConfig#getOptionalValues if it * is a Collection type. * * @param propertyName Property name that needs to be fetched * @param resultType Type to which the property value needs to be converted to * @param declaringClass Config class where the type was encountered * @param bytecodeCreator Where the bytecode will be generated * @param config Reference to the MP config object */ static ReadOptionalResponse createReadOptionalValueAndConvertIfNeeded(String propertyName, Type resultType, DotName declaringClass, BytecodeCreator bytecodeCreator, ResultHandle config) { ResultHandle optionalValue; if (isCollection(resultType)) { ResultHandle smallryeConfig = bytecodeCreator.checkCast(config, SmallRyeConfig.class); Class<?> factoryToUse = DotNames.SET.equals(resultType.name()) ? HashSetFactory.class : ArrayListFactory.class; ResultHandle collectionFactory = bytecodeCreator.invokeStaticMethod( MethodDescriptor.ofMethod(factoryToUse, "getInstance", factoryToUse)); optionalValue = bytecodeCreator.invokeVirtualMethod( MethodDescriptor.ofMethod(SmallRyeConfig.class, "getOptionalValues", Optional.class, String.class, Class.class, IntFunction.class), smallryeConfig, bytecodeCreator.load(propertyName), bytecodeCreator.loadClass(determineSingleGenericType(resultType, declaringClass).name().toString()), collectionFactory); } else { optionalValue = bytecodeCreator.invokeInterfaceMethod( MethodDescriptor.ofMethod(Config.class, "getOptionalValue", Optional.class, String.class, Class.class), config, bytecodeCreator.load(propertyName), bytecodeCreator.loadClass(resultType.name().toString())); } ResultHandle isPresent = bytecodeCreator .invokeVirtualMethod(MethodDescriptor.ofMethod(Optional.class, "isPresent", boolean.class), optionalValue); BranchResult isPresentBranch = bytecodeCreator.ifNonZero(isPresent); BytecodeCreator isPresentTrue = isPresentBranch.trueBranch(); ResultHandle value = isPresentTrue.invokeVirtualMethod(MethodDescriptor.ofMethod(Optional.class, "get", Object.class), optionalValue); return new ReadOptionalResponse(value, isPresentTrue, isPresentBranch.falseBranch()); }
Example #28
Source File: ConfigBeanCreator.java From quarkus with Apache License 2.0 | 5 votes |
@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 #29
Source File: NativeImageLauncher.java From quarkus with Apache License 2.0 | 5 votes |
private static Config installAndGetSomeConfig() { final SmallRyeConfig config = ConfigUtils.configBuilder(false).build(); QuarkusConfigFactory.setConfig(config); final ConfigProviderResolver cpr = ConfigProviderResolver.instance(); try { final Config installed = cpr.getConfig(); if (installed != config) { cpr.releaseConfig(installed); } } catch (IllegalStateException ignored) { } return config; }
Example #30
Source File: ConfigInstantiator.java From quarkus with Apache License 2.0 | 5 votes |
public static void handleObject(Object o) { final SmallRyeConfig config = (SmallRyeConfig) ConfigProvider.getConfig(); final Class cls = o.getClass(); final String clsNameSuffix = getClassNameSuffix(o); if (clsNameSuffix == null) { // unsupported object type return; } final String name = dashify(cls.getSimpleName().substring(0, cls.getSimpleName().length() - clsNameSuffix.length())); handleObject("quarkus." + name, o, config); }