org.eclipse.microprofile.config.Config Java Examples
The following examples show how to use
org.eclipse.microprofile.config.Config.
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: ConfiguredChannelFactory.java From smallrye-reactive-messaging with Apache License 2.0 | 6 votes |
static Map<String, ConnectorConfig> extractConfigurationFor(String prefix, Config root) { Iterable<String> names = root.getPropertyNames(); Map<String, ConnectorConfig> configs = new HashMap<>(); names.forEach(key -> { // $prefix$name.key=value (the prefix ends with a .) if (key.startsWith(prefix)) { // Extract the name String name = key.substring(prefix.length()); if (name.contains(".")) { // We must remove the part after the first dot String tmp = name; name = tmp.substring(0, tmp.indexOf('.')); } configs.put(name, new ConnectorConfig(prefix, root, name)); } }); return configs; }
Example #2
Source File: ProfileConfigSourceInterceptorTest.java From smallrye-config with Apache License 2.0 | 6 votes |
@Test public void priorityOverrideProfile() { final Config config = new SmallRyeConfigBuilder() .addDefaultSources() .withSources( new MapBackedConfigSource("higher", new HashMap<String, String>() { { put("my.prop", "higher"); } }, 200) { }, new MapBackedConfigSource("lower", new HashMap<String, String>() { { put("my.prop", "lower"); put("%prof.my.prop", "lower-profile"); } }, 100) { }) .withInterceptors( new ProfileConfigSourceInterceptor("prof"), new ExpressionConfigSourceInterceptor()) .build(); assertEquals("higher", config.getValue("my.prop", String.class)); }
Example #3
Source File: ServiceAdvertizer.java From pragmatic-microservices-lab with MIT License | 6 votes |
public void advertize(ServiceAdvertisement advertisement, ScheduledExecutorService scheduler) { Config config = ConfigProvider.getConfig(); String serviceAddress = getAddressFromAdvert(advertisement, config); Integer servicePort = getPortFromAdvert(advertisement, config); Registration service = ImmutableRegistration.builder().id(idFromAdvert(advertisement)) .name(advertisement.getName()).address(serviceAddress).port(servicePort) .check(Registration.RegCheck.ttl(3L)) // registers with a TTL of 3 seconds .meta(Collections.singletonMap(ConsulClient.KEY_CTX_ROOT, advertisement.getContextRoot())).build(); try { ConsulClient.build().agentClient().register(service); } catch (RuntimeException e) { Logger.getLogger(this.getClass().getName()).log(Level.WARNING, "Is consul running?", e); } // keep refreshing the status within the TTL scheduler.scheduleAtFixedRate(() -> refreshAdvertisement(advertisement), 2, 2, TimeUnit.SECONDS); }
Example #4
Source File: InterfaceConfigPropertiesUtil.java From quarkus with Apache License 2.0 | 6 votes |
/** * Add a method like this: * * <pre> * @Produces * public SomeConfig produceSomeClass(Config config) { * return new SomeConfigQuarkusImpl(config) * } * </pre> */ static void addProducerMethodForInterfaceConfigProperties(ClassCreator classCreator, DotName interfaceName, String prefix, boolean needsQualifier, String generatedClassName) { String methodName = "produce" + interfaceName.withoutPackagePrefix(); if (needsQualifier) { // we need to differentiate the different producers of the same class methodName = methodName + "WithPrefix" + HashUtil.sha1(prefix); } try (MethodCreator method = classCreator.getMethodCreator(methodName, interfaceName.toString(), Config.class.getName())) { method.addAnnotation(Produces.class); if (needsQualifier) { method.addAnnotation(AnnotationInstance.create(DotNames.CONFIG_PREFIX, null, new AnnotationValue[] { AnnotationValue.createStringValue("value", prefix) })); } else { method.addAnnotation(Default.class); } method.returnValue(method.newInstance(MethodDescriptor.ofConstructor(generatedClassName, Config.class), method.getMethodParam(0))); } }
Example #5
Source File: SmallRyeOpenApiProcessor.java From quarkus with Apache License 2.0 | 6 votes |
public OpenApiDocument loadDocument(OpenAPI staticModel, OpenAPI annotationModel) { Config config = ConfigProvider.getConfig(); OpenApiConfig openApiConfig = new OpenApiConfigImpl(config); OpenAPI readerModel = OpenApiProcessor.modelFromReader(openApiConfig, Thread.currentThread().getContextClassLoader()); OpenApiDocument document = createDocument(openApiConfig); if (annotationModel != null) { document.modelFromAnnotations(annotationModel); } document.modelFromReader(readerModel); document.modelFromStaticFile(staticModel); document.filter(filter(openApiConfig)); document.initialize(); return document; }
Example #6
Source File: CamelConnector.java From smallrye-reactive-messaging with Apache License 2.0 | 6 votes |
@PostConstruct @Inject public void init() { DefaultCamelReactiveStreamsServiceFactory factory = new DefaultCamelReactiveStreamsServiceFactory(); ReactiveStreamsEngineConfiguration configuration = new ReactiveStreamsEngineConfiguration(); Config config = ConfigProvider.getConfig(); config.getOptionalValue("camel.component.reactive-streams.internal-engine-configuration.thread-pool-max-size", Integer.class).ifPresent(configuration::setThreadPoolMaxSize); config.getOptionalValue("camel.component.reactive-streams.internal-engine-configuration.thread-pool-min-size", Integer.class).ifPresent(configuration::setThreadPoolMinSize); config.getOptionalValue("camel.component.reactive-streams.internal-engine-configuration.thread-pool-name", String.class).ifPresent(configuration::setThreadPoolName); this.reactive = factory.newInstance(camel, configuration); }
Example #7
Source File: ConfigRecorder.java From quarkus with Apache License 2.0 | 6 votes |
public void validateConfigProperties(Map<String, Set<String>> properties) { Config config = ConfigProvider.getConfig(); ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl == null) { cl = ConfigRecorder.class.getClassLoader(); } for (Entry<String, Set<String>> entry : properties.entrySet()) { Set<String> propertyTypes = entry.getValue(); for (String propertyType : propertyTypes) { Class<?> propertyClass = load(propertyType, cl); // For parameterized types and arrays, we only check if the property config exists without trying to convert it if (propertyClass.isArray() || propertyClass.getTypeParameters().length > 0) { propertyClass = String.class; } try { if (!config.getOptionalValue(entry.getKey(), propertyClass).isPresent()) { throw new DeploymentException( "No config value of type " + entry.getValue() + " exists for: " + entry.getKey()); } } catch (IllegalArgumentException e) { throw new DeploymentException(e); } } } }
Example #8
Source File: ConfigFacade.java From cxf with Apache License 2.0 | 6 votes |
public static OptionalLong getOptionalLong(String propNameFormat, Class<?> clientIntf) { Optional<Config> c = config(); if (c.isPresent()) { String propertyName = String.format(propNameFormat, clientIntf.getName()); Long value = c.get().getOptionalValue(propertyName, Long.class).orElseGet(() -> { RegisterRestClient anno = clientIntf.getAnnotation(RegisterRestClient.class); if (anno != null && !StringUtils.isEmpty(anno.configKey())) { String configKeyPropName = String.format(propNameFormat, anno.configKey()); return c.get().getOptionalValue(configKeyPropName, Long.class).orElse(null); } return null; }); return value == null ? OptionalLong.empty() : OptionalLong.of(value); } return OptionalLong.empty(); }
Example #9
Source File: BuilderReuseTestCase.java From smallrye-config with Apache License 2.0 | 6 votes |
@Test public void testBuilderReuse() { final SmallRyeConfigBuilder builder = new SmallRyeConfigBuilder(); builder.addDefaultSources(); final Config config1 = builder.build(); final Config config2 = builder.build(); final Iterable<ConfigSource> cs1 = config1.getConfigSources(); final Iterable<ConfigSource> cs2 = config2.getConfigSources(); final Iterator<ConfigSource> it1 = cs1.iterator(); final Iterator<ConfigSource> it2 = cs2.iterator(); assertTrue(it1.hasNext() && it2.hasNext()); assertEquals(it1.next().getClass(), it2.next().getClass()); assertTrue(it1.hasNext() && it2.hasNext()); assertEquals(it1.next().getClass(), it2.next().getClass()); assertFalse(it1.hasNext() || it2.hasNext()); }
Example #10
Source File: ConfigGenerationBuildStep.java From quarkus with Apache License 2.0 | 6 votes |
/** * Warns if build time config properties have been changed at runtime. */ @BuildStep @Record(ExecutionTime.RUNTIME_INIT) public void checkForBuildTimeConfigChange( ConfigChangeRecorder recorder, ConfigurationBuildItem configItem, LoggingSetupBuildItem loggingSetupBuildItem) { BuildTimeConfigurationReader.ReadResult readResult = configItem.getReadResult(); Config config = ConfigProvider.getConfig(); Map<String, String> values = new HashMap<>(); for (RootDefinition root : readResult.getAllRoots()) { if (root.getConfigPhase() == ConfigPhase.BUILD_AND_RUN_TIME_FIXED || root.getConfigPhase() == ConfigPhase.BUILD_TIME) { Iterable<ClassDefinition.ClassMember> members = root.getMembers(); handleMembers(config, values, members, "quarkus." + root.getRootName() + "."); } } values.remove("quarkus.profile"); recorder.handleConfigChange(values); }
Example #11
Source File: ConnectorConfig.java From smallrye-reactive-messaging with Apache License 2.0 | 6 votes |
protected ConnectorConfig(String prefix, Config overall, String channel) { this.prefix = Objects.requireNonNull(prefix, msg.prefixMustNotBeSet()); this.overall = Objects.requireNonNull(overall, msg.configMustNotBeSet()); this.name = Objects.requireNonNull(channel, msg.channelMustNotBeSet()); Optional<String> value = overall.getOptionalValue(channelKey(CONNECTOR_ATTRIBUTE), String.class); this.connector = value .orElseGet(() -> overall.getOptionalValue(channelKey("type"), String.class) // Legacy .orElseThrow(() -> ex.illegalArgumentChannelConnectorConfiguration(name))); // Detect invalid channel-name attribute for (String key : overall.getPropertyNames()) { if ((channelKey(CHANNEL_NAME_ATTRIBUTE)).equalsIgnoreCase(key)) { throw ex.illegalArgumentInvalidChannelConfiguration(name); } } }
Example #12
Source File: ConfigSourceWrapperTestCase.java From smallrye-config with Apache License 2.0 | 6 votes |
@Test public void testDecoratedTwice() { final Config config = new SmallRyeConfigBuilder().withWrapper(WrappedSource::new).withWrapper(WrappedSource::new) .addDefaultSources().build(); final Iterator<ConfigSource> iterator = config.getConfigSources().iterator(); ConfigSource source; assertTrue(iterator.hasNext()); source = iterator.next(); assertIsInstance(SysPropConfigSource.class, assertIsInstance(WrappedSource.class, assertIsInstance(WrappedSource.class, source).getDelegate()) .getDelegate()); assertTrue(iterator.hasNext()); source = iterator.next(); assertIsInstance(EnvConfigSource.class, assertIsInstance(WrappedSource.class, assertIsInstance(WrappedSource.class, source).getDelegate()) .getDelegate()); assertFalse(iterator.hasNext()); }
Example #13
Source File: SmallRyeOpenApiProcessor.java From quarkus with Apache License 2.0 | 6 votes |
private OpenAPI generateAnnotationModel(IndexView indexView, Capabilities capabilities) { Config config = ConfigProvider.getConfig(); OpenApiConfig openApiConfig = new OpenApiConfigImpl(config); String defaultPath = config.getValue("quarkus.http.root-path", String.class); List<AnnotationScannerExtension> extensions = new ArrayList<>(); // Add RestEasy if jaxrs if (capabilities.isCapabilityPresent(Capabilities.RESTEASY)) { extensions.add(new RESTEasyExtension(indexView)); } // Add path if not null if (defaultPath != null) { extensions.add(new CustomPathExtension(defaultPath)); } return new OpenApiAnnotationScanner(openApiConfig, indexView, extensions).scan(); }
Example #14
Source File: ConfiguredChannelFactory.java From smallrye-reactive-messaging with Apache License 2.0 | 6 votes |
ConfiguredChannelFactory(@Any Instance<IncomingConnectorFactory> incomingConnectorFactories, @Any Instance<OutgoingConnectorFactory> outgoingConnectorFactories, Instance<Config> config, @Any Instance<ChannelRegistry> registry, BeanManager beanManager, boolean logConnectors) { this.registry = registry.get(); if (config.isUnsatisfied()) { this.incomingConnectorFactories = null; this.outgoingConnectorFactories = null; this.config = null; } else { this.incomingConnectorFactories = incomingConnectorFactories; this.outgoingConnectorFactories = outgoingConnectorFactories; if (logConnectors) { log.foundIncomingConnectors(getConnectors(beanManager, IncomingConnectorFactory.class)); log.foundOutgoingConnectors(getConnectors(beanManager, OutgoingConnectorFactory.class)); } //TODO Should we try to merge all the config? // For now take the first one. this.config = config.stream().findFirst() .orElseThrow(() -> ex.illegalStateRetieveConfig()); } }
Example #15
Source File: ConfigFacade.java From cxf with Apache License 2.0 | 5 votes |
private static Optional<Config> config() { Config c; try { c = ConfigProvider.getConfig(); } catch (ExceptionInInitializerError | NoClassDefFoundError | IllegalStateException ex) { // expected if no MP Config implementation is available c = null; } return Optional.ofNullable(c); }
Example #16
Source File: NativeImageLauncher.java From quarkus with Apache License 2.0 | 5 votes |
private NativeImageLauncher(Class<?> testClass, Config config) { this(testClass, config.getValue("quarkus.http.test-port", OptionalInt.class).orElse(DEFAULT_PORT), config.getValue("quarkus.http.test-ssl-port", OptionalInt.class).orElse(DEFAULT_HTTPS_PORT), config.getValue("quarkus.test.native-image-wait-time", OptionalLong.class).orElse(DEFAULT_IMAGE_WAIT_TIME), config.getOptionalValue("quarkus.test.native-image-profile", String.class) .orElse(null)); }
Example #17
Source File: ServiceInfo.java From pragmatic-microservices-lab with MIT License | 5 votes |
public static Integer getServicePort(Config config) { Integer servicePort = config.getValue("payara.instance.http.port", Integer.class); if (servicePort == null) { servicePort = config.getValue("http.port", Integer.class); } if (servicePort == null) { servicePort = 80; } return servicePort; }
Example #18
Source File: KafkaStreamsPropertiesUtil.java From quarkus with Apache License 2.0 | 5 votes |
private static void includeKafkaStreamsProperty(Config config, Properties kafkaStreamsProperties, String prefix, String property) { Optional<String> value = config.getOptionalValue(property, String.class); if (value.isPresent()) { kafkaStreamsProperties.setProperty(property.substring(prefix.length()), value.get()); } }
Example #19
Source File: ConfiguredStreamFactoryTest.java From smallrye-reactive-messaging with Apache License 2.0 | 5 votes |
@Test public void testConnectorConfigurationLookup() { Map<String, Object> backend = new HashMap<>(); backend.put("mp.messaging.connector.my-connector.a", "A"); backend.put("mp.messaging.connector.my-connector.b", "B"); backend.put("io.prefix.name.connector", "my-connector"); backend.put("io.prefix.name.k1", "v1"); backend.put("io.prefix.name.k2", "v2"); backend.put("io.prefix.name.b", "B2"); backend.put("io.prefix.name2.connector", "my-connector"); backend.put("io.prefix.name2.k1", "v12"); backend.put("io.prefix.name2.k2", "v22"); backend.put("io.prefix.name2.b", "B22"); Config config = new DummyConfig(backend); Map<String, ConnectorConfig> map = ConfiguredChannelFactory.extractConfigurationFor("io.prefix.", config); assertThat(map).hasSize(2).containsKeys("name", "name2"); ConnectorConfig config1 = map.get("name"); assertThat(config1.getPropertyNames()).hasSize(6).contains("a", "b", "k1", "k2", "connector", "channel-name"); assertThat(config1.getValue("k1", String.class)).isEqualTo("v1"); assertThat(config1.getValue("a", String.class)).isEqualTo("A"); assertThat(config1.getValue("b", String.class)).isEqualTo("B2"); assertThat(config1.getOptionalValue("k1", String.class)).contains("v1"); assertThat(config1.getOptionalValue("a", String.class)).contains("A"); assertThat(config1.getOptionalValue("b", String.class)).contains("B2"); assertThat(config1.getOptionalValue("c", String.class)).isEmpty(); ConnectorConfig config2 = map.get("name2"); assertThat(config2.getPropertyNames()).hasSize(6).contains("a", "b", "k1", "k2", "connector", "channel-name"); assertThat(config2.getValue("k1", String.class)).isEqualTo("v12"); assertThat(config2.getValue("a", String.class)).isEqualTo("A"); assertThat(config2.getValue("b", String.class)).isEqualTo("B22"); }
Example #20
Source File: ConfiguredStreamFactoryTest.java From smallrye-reactive-messaging with Apache License 2.0 | 5 votes |
@Test(expected = IllegalArgumentException.class) public void testThatChannelNameIsDetected() { Map<String, Object> backend = new HashMap<>(); backend.put("foo", "bar"); backend.put("io.prefix.name.connector", "my-connector"); backend.put("io.prefix.name.k1", "v1"); backend.put("io.prefix.name.channel-name", "v2"); backend.put("io.prefix.name.k3.x", "v3"); Config config = new DummyConfig(backend); ConfiguredChannelFactory.extractConfigurationFor("io.prefix.", config); }
Example #21
Source File: SecretKeysTest.java From smallrye-config with Apache License 2.0 | 5 votes |
@Test public void unlock() { final Config config = buildConfig("secret", "12345678", "not.secret", "value"); SecretKeys.doUnlocked(() -> assertEquals("12345678", config.getValue("secret", String.class))); assertEquals("12345678", SecretKeys.doUnlocked(() -> config.getValue("secret", String.class))); assertThrows(SecurityException.class, () -> config.getValue("secret", String.class), "Not allowed to access secret key secret"); }
Example #22
Source File: CacheControlFilter.java From trellis with Apache License 2.0 | 5 votes |
/** * Create a CacheControl decorator. */ public CacheControlFilter() { final Config config = getConfig(); this.maxAge = config.getOptionalValue(CONFIG_HTTP_CACHE_MAX_AGE, Integer.class).orElse(86400); this.mustRevalidate = config.getOptionalValue(CONFIG_HTTP_CACHE_REVALIDATE, Boolean.class).orElse(Boolean.TRUE); this.noCache = config.getOptionalValue(CONFIG_HTTP_CACHE_NOCACHE, Boolean.class).orElse(Boolean.FALSE); }
Example #23
Source File: ProfileConfigSourceInterceptorTest.java From smallrye-config with Apache License 2.0 | 5 votes |
@Test public void customConfigProfile() { final String[] configs = { "my.prop", "1", "%prof.my.prop", "2", "config.profile", "prof" }; final Config config = new SmallRyeConfigBuilder() .addDefaultSources() .addDiscoveredInterceptors() .withSources(KeyValuesConfigSource.config(configs)) .build(); assertEquals("2", config.getValue("my.prop", String.class)); }
Example #24
Source File: MappingConfigSourceInterceptorTest.java From smallrye-config with Apache License 2.0 | 5 votes |
@Test public void relocateWithProfile() { final Config config = buildConfig( "mp.jwt.token.header", "Authorization", "%prof.mp.jwt.token.header", "Cookie", SMALLRYE_PROFILE, "prof"); assertEquals("Cookie", config.getValue("smallrye.jwt.token.header", String.class)); }
Example #25
Source File: VaultITCase.java From quarkus with Apache License 2.0 | 5 votes |
@Test public void configPropertyIndirection() { assertEquals(DB_PASSWORD, someSecretThroughIndirection); Config config = ConfigProviderResolver.instance().getConfig(); String value = config.getValue(MY_PASSWORD, String.class); assertEquals(DB_PASSWORD, value); }
Example #26
Source File: ServiceAdvertizer.java From pragmatic-microservices-lab with MIT License | 5 votes |
public void advertize(ServiceAdvertisement advertisement, ScheduledExecutorService scheduler) { Config config = ConfigProvider.getConfig(); String serviceAddress = getAddressFromAdvert(advertisement, config); Integer servicePort = getPortFromAdvert(advertisement, config); Registration service = new Registration() .id(idFromAdvert(advertisement)) .name(advertisement.getName()) .address(serviceAddress) .port(servicePort) .contextRoot(advertisement.getContextRoot()); register(service); // keep refreshing the status within the TTL scheduler.scheduleAtFixedRate(() -> refreshAdvertisement(service), 2, 2, TimeUnit.SECONDS); }
Example #27
Source File: KubernetesConfigUtil.java From quarkus with Apache License 2.0 | 5 votes |
public static List<String> getUserSpecifiedDeploymentTargets() { Config config = ConfigProvider.getConfig(); String configValue = config.getOptionalValue(DEPLOYMENT_TARGET, String.class) .orElse(config.getOptionalValue(OLD_DEPLOYMENT_TARGET, String.class).orElse("")); if (configValue.isEmpty()) { return Collections.emptyList(); } return Arrays.stream(configValue .split(",")) .map(String::trim) .map(String::toLowerCase) .collect(Collectors.toList()); }
Example #28
Source File: MappingConfigSourceInterceptorTest.java From smallrye-config with Apache License 2.0 | 5 votes |
@Test public void relocateWithProfileExpressionAndFallback() { final Config config = buildConfig( "mp.jwt.token.header", "Authorization", "%prof.mp.jwt.token.header", "${token.header}", "token.header", "Cookie", "smallrye.jwt.token.cookie", "jwt", "%prof.smallrye.jwt.token.cookie", "Basic", SMALLRYE_PROFILE, "prof"); assertEquals("Basic", config.getValue("smallrye.jwt.token.cookie", String.class)); }
Example #29
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 #30
Source File: MappingConfigSourceInterceptorTest.java From smallrye-config with Apache License 2.0 | 5 votes |
private static Config buildConfig(Set<String> secretKeys, String... keyValues) { return new SmallRyeConfigBuilder() .addDefaultSources() .addDefaultInterceptors() .withSources(KeyValuesConfigSource.config(keyValues)) .withInterceptors( new RelocateConfigSourceInterceptor( s -> s.replaceAll("smallrye\\.jwt\\.token\\.header", "mp.jwt.token.header")), new FallbackConfigSourceInterceptor( s -> s.replaceAll("smallrye\\.jwt", "mp.jwt"))) .withInterceptors(new LoggingConfigSourceInterceptor()) .withSecretKeys(secretKeys.toArray(new String[0])) .build(); }