Java Code Examples for org.eclipse.microprofile.config.Config

The following examples show how to use org.eclipse.microprofile.config.Config. 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: pragmatic-microservices-lab   Source File: ServiceAdvertizer.java    License: MIT License 6 votes vote down vote up
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 2
@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
@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 4
Source Project: smallrye-config   Source File: BuilderReuseTestCase.java    License: Apache License 2.0 6 votes vote down vote up
@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 5
Source Project: quarkus   Source File: SmallRyeOpenApiProcessor.java    License: Apache License 2.0 6 votes vote down vote up
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 6
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 7
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 8
@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 9
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 10
Source Project: quarkus   Source File: ConfigGenerationBuildStep.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 Project: cxf   Source File: ConfigFacade.java    License: Apache License 2.0 6 votes vote down vote up
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 12
Source Project: quarkus   Source File: ConfigRecorder.java    License: Apache License 2.0 6 votes vote down vote up
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 13
Source Project: quarkus   Source File: SmallRyeOpenApiProcessor.java    License: Apache License 2.0 6 votes vote down vote up
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 14
Source Project: quarkus   Source File: InterfaceConfigPropertiesUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Add a method like this:
 * 
 * <pre>
 *  &#64;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 15
Source Project: apicurio-registry   Source File: ClusterIT.java    License: Apache License 2.0 5 votes vote down vote up
@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 16
Source Project: quarkus   Source File: ConfigBeanCreator.java    License: 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 17
@Test
public void profileExpressions() {
    final Config config = buildConfig("my.prop", "1",
            "%prof.my.prop", "${%prof.my.prop.profile}",
            "%prof.my.prop.profile", "2",
            SMALLRYE_PROFILE, "prof");

    assertEquals("2", config.getValue("my.prop", String.class));
}
 
Example 18
Source Project: quarkus   Source File: VaultMultiPathConfigITCase.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void defaultPath() {
    Config config = ConfigProviderResolver.instance().getConfig();
    assertEquals("red", config.getValue("color", String.class));
    assertEquals("XL", config.getValue("size", String.class));
    assertEquals("3", config.getValue("weight", String.class));
}
 
Example 19
@Override
public SubscriberBuilder<? extends Message<String>, Void> getSubscriberBuilder(Config config) {
    String channel = config.getValue(CHANNEL_NAME_ATTRIBUTE, String.class);
    LinkedBlockingQueue<Message<String>> queue = new LinkedBlockingQueue<>();
    outgoingQueues.put(channel, queue);
    return ReactiveStreams.<Message<String>>builder().forEach(queue::add);
}
 
Example 20
Source Project: quarkus   Source File: ConfigPropertiesUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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 21
Source Project: ci.maven   Source File: ConfigTestController.java    License: Apache License 2.0 5 votes vote down vote up
@Path("/lookup")
@GET
public String getLookupConfigValue() {
    Config config = ConfigProvider.getConfig();
    String value = config.getValue("value", String.class);
    return "Config value from ConfigProvider " + value;
}
 
Example 22
Source Project: smallrye-reactive-messaging   Source File: MySink.java    License: Apache License 2.0 5 votes vote down vote up
@Produces
public Config myConfig() {
    String prefix = "smallrye.messaging.source.data.";
    Map<String, Object> config = new HashMap<>();
    config.putIfAbsent(prefix + "name", "foo-out");
    config.put(prefix + "connector", CamelConnector.CONNECTOR_NAME);
    return new MapBasedConfig(config);
}
 
Example 23
@Test
public void testUndecorated() {
    final Config config = new SmallRyeConfigBuilder().addDefaultSources().build();
    final Iterator<ConfigSource> iterator = config.getConfigSources().iterator();
    ConfigSource source;

    assertTrue(iterator.hasNext());
    source = iterator.next();
    assertIsInstance(SysPropConfigSource.class, source);
    assertTrue(iterator.hasNext());
    source = iterator.next();
    assertIsInstance(EnvConfigSource.class, source);
    assertFalse(iterator.hasNext());
}
 
Example 24
Source Project: quarkus   Source File: ConfigChangeRecorder.java    License: Apache License 2.0 5 votes vote down vote up
public void handleConfigChange(Map<String, String> buildTimeConfig) {
    Config configProvider = ConfigProvider.getConfig();
    for (Map.Entry<String, String> entry : buildTimeConfig.entrySet()) {
        Optional<String> val = configProvider.getOptionalValue(entry.getKey(), String.class);
        if (val.isPresent()) {
            if (!val.get().equals(entry.getValue())) {
                log.warn("Build time property cannot be changed at runtime. " + entry.getKey() + " was "
                        + entry.getValue() + " at build time and is now " + val.get());
            }
        }
    }
}
 
Example 25
private static Config buildConfig(String... keyValues) {
    return new SmallRyeConfigBuilder()
            .withSources(KeyValuesConfigSource.config(keyValues))
            .withInterceptors(
                    new ProfileConfigSourceInterceptor("prof"),
                    new ExpressionConfigSourceInterceptor())
            .build();
}
 
Example 26
Source Project: smallrye-config   Source File: InterceptorChainTest.java    License: Apache License 2.0 5 votes vote down vote up
private static Config buildConfig(String... keyValues) {
    return new SmallRyeConfigBuilder()
            .addDefaultSources()
            .addDefaultInterceptors()
            .withSources(KeyValuesConfigSource.config(keyValues))
            .withInterceptors(
                    new RelocateConfigSourceInterceptor(s -> s.replaceAll("my\\.prop", "my.prop.relocate")))
            .build();
}
 
Example 27
Source Project: pragmatic-microservices-lab   Source File: ServiceAdvertizer.java    License: MIT License 5 votes vote down vote up
private static String getAddressFromAdvert(ServiceAdvertisement advertisment, Config config) {
    String serviceAddress = advertisment.getAddress();
    if (serviceAddress == null) {
        serviceAddress = ServiceInfo.getServiceAddress(config);
    }
    return serviceAddress;
}
 
Example 28
private static String getTopic(final Config config) {
    final String topic = config.getOptionalValue("topic", String.class)
            .orElse(null);
    if (topic != null) {
        return topic;
    }

    return config.getValue(ConnectorFactory.CHANNEL_NAME_ATTRIBUTE, String.class);
}
 
Example 29
Source Project: quarkus   Source File: SmallRyeOpenApiProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private boolean shouldScanAnnotations(Capabilities capabilities) {
    // Disabled via config
    Config config = ConfigProvider.getConfig();
    boolean scanDisable = config.getOptionalValue(OASConfig.SCAN_DISABLE, Boolean.class).orElse(false);
    if (scanDisable) {
        return false;
    }

    // Only scan if either JaxRS or Spring is used
    boolean isJaxrs = capabilities.isCapabilityPresent(Capabilities.RESTEASY);
    boolean isSpring = capabilities.isCapabilityPresent(Capabilities.SPRING_WEB);
    return isJaxrs || isSpring;
}
 
Example 30
Source Project: quarkus   Source File: CustomInvokeWithJsonPProviderTest.java    License: Apache License 2.0 5 votes vote down vote up
@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();
}