org.eclipse.microprofile.config.spi.ConfigProviderResolver Java Examples

The following examples show how to use org.eclipse.microprofile.config.spi.ConfigProviderResolver. 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: ArchiveProcessor.java    From smallrye-metrics with Apache License 2.0 7 votes vote down vote up
@Override
public void process(TestDeployment testDeployment, Archive<?> protocolArchive) {
    WebArchive war = (WebArchive) protocolArchive;
    war.addAsWebInfResource("WEB-INF/jboss-web.xml", "jboss-web.xml");
    String[] deps = {
            "io.smallrye:smallrye-config",
            "io.smallrye:smallrye-metrics",
            "io.smallrye:smallrye-metrics-testsuite-common",
            "org.eclipse.microprofile.metrics:microprofile-metrics-api",
            "org.jboss.weld.servlet:weld-servlet-core"
    };

    File[] dependencies = Maven.resolver().loadPomFromFile(new File("pom.xml")).resolve(deps).withTransitivity().asFile();

    war.addAsLibraries(dependencies);

    war.addClass(SmallRyeBeanArchiveHandler.class);
    war.addClass(MetricsHttpServlet.class);
    war.addClass(MetricsInitializer.class);
    war.addAsResource("io/smallrye/metrics/base-metrics.properties", "/io/smallrye/metrics/base-metrics.properties");
    war.addAsServiceProvider(BeanArchiveHandler.class, SmallRyeBeanArchiveHandler.class);
    war.addAsServiceProvider(Extension.class, ConfigExtension.class);
    war.addAsServiceProvider(ConfigProviderResolver.class, SmallRyeConfigProviderResolver.class);
}
 
Example #2
Source File: EnabledIfPropertyCondition.java    From camel-quarkus with Apache License 2.0 6 votes vote down vote up
private ConditionEvaluationResult map(EnabledIfProperty annotation) {
    final String name = annotation.named().trim();
    final String regex = annotation.matches();

    Preconditions.notBlank(name, () -> "The 'named' attribute must not be blank in " + annotation);
    Preconditions.notBlank(regex, () -> "The 'matches' attribute must not be blank in " + annotation);

    return ConfigProviderResolver.instance().getConfig().getOptionalValue(name, String.class)
            .map(actual -> {
                return actual.matches(regex)
                        ? enabled(
                                format("Config property [%s] with value [%s] matches regular expression [%s]",
                                        name, actual, regex))
                        : disabled(
                                format("Config property [%s] with value [%s] does not match regular expression [%s]",
                                        name, actual, regex));
            })
            .orElseGet(() -> {
                return disabled(
                        format("Config property [%s] does not exist", name));
            });
}
 
Example #3
Source File: ConverterTest.java    From microprofile-config with Apache License 2.0 6 votes vote down vote up
@Test
public void testDonaldConversionWithMultipleLambdaConverters() {
    // defines 2 config with the lambda converters defined in different orders.
    // Order must not matter, the lambda with the upper case must always be used as it has the highest priority
    Config config1 = ConfigProviderResolver.instance().getBuilder().addDefaultSources()
        .withConverter(Donald.class, 101, (s) -> Donald.iLikeDonald(s.toUpperCase()))
        .withConverter(Donald.class, 100, (s) -> Donald.iLikeDonald(s))
        .build();
    Config config2 = ConfigProviderResolver.instance().getBuilder().addDefaultSources()
        .withConverter(Donald.class, 100, (s) -> Donald.iLikeDonald(s))
        .withConverter(Donald.class, 101, (s) -> Donald.iLikeDonald(s.toUpperCase()))
        .build();

    Donald donald = config1.getConverter(Donald.class).get().convert("Duck");
    Assert.assertNotNull(donald);
    Assert.assertEquals(donald.getName(), "DUCK",
        "The converter with the highest priority (using upper case) must be used.");
    donald = config2.getConverter(Donald.class).get().convert("Duck");
    Assert.assertNotNull(donald);
    Assert.assertEquals(donald.getName(), "DUCK",
        "The converter with the highest priority (using upper case) must be used.");
}
 
Example #4
Source File: ConverterTest.java    From microprofile-config with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetDonaldConverterWithMultipleLambdaConverters() {
    // defines 2 config with the lambda converters defined in different orders.
    // Order must not matter, the lambda with the upper case must always be used as it has the highest priority
    Config config1 = ConfigProviderResolver.instance().getBuilder().addDefaultSources()
        .withConverter(Donald.class, 101, (s) -> Donald.iLikeDonald(s.toUpperCase()))
        .withConverter(Donald.class, 100, (s) -> Donald.iLikeDonald(s))
        .build();
    Config config2 = ConfigProviderResolver.instance().getBuilder().addDefaultSources()
        .withConverter(Donald.class, 100, (s) -> Donald.iLikeDonald(s))
        .withConverter(Donald.class, 101, (s) -> Donald.iLikeDonald(s.toUpperCase()))
        .build();

    Donald donald = config1.getValue("tck.config.test.javaconfig.converter.donaldname", Donald.class);
    Assert.assertNotNull(donald);
    Assert.assertEquals(donald.getName(), "DUCK",
        "The converter with the highest priority (using upper case) must be used.");
    donald = config2.getValue("tck.config.test.javaconfig.converter.donaldname", Donald.class);
    Assert.assertNotNull(donald);
    Assert.assertEquals(donald.getName(), "DUCK",
        "The converter with the highest priority (using upper case) must be used.");
}
 
Example #5
Source File: ConfigBuildSteps.java    From quarkus with 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 #6
Source File: ConverterTest.java    From microprofile-config with Apache License 2.0 6 votes vote down vote up
@Test
public void testDuckConversionWithMultipleConverters() {
    // defines 2 config with the converters defined in different orders.
    // Order must not matter, the UpperCaseDuckConverter must always be used as it has the highest priority
    Config config1 = ConfigProviderResolver.instance().getBuilder().addDefaultSources()
        .withConverters(new UpperCaseDuckConverter(), new DuckConverter())
        .build();
    Config config2 = ConfigProviderResolver.instance().getBuilder().addDefaultSources()
        .withConverters(new DuckConverter(), new UpperCaseDuckConverter())
        .build();

    Duck duck = config1.getValue("tck.config.test.javaconfig.converter.duckname", Duck.class);
    Assert.assertNotNull(duck);
    Assert.assertEquals(duck.getName(), "HANNELORE",
        "The converter with the highest priority (UpperCaseDuckConverter) must be used.");

    duck = config2.getValue("tck.config.test.javaconfig.converter.duckname", Duck.class);
    Assert.assertNotNull(duck);
    // the UpperCaseDuckConverter has highest priority
    Assert.assertEquals(duck.getName(), "HANNELORE",
        "The converter with the highest priority (UpperCaseDuckConverter) must be used.");
}
 
Example #7
Source File: SimpleScheduler.java    From quarkus with Apache License 2.0 6 votes vote down vote up
public static Duration parseDuration(Scheduled scheduled, String value, String memberName) {
    value = value.trim();
    if (SchedulerContext.isConfigValue(value)) {
        value = ConfigProviderResolver.instance().getConfig().getValue(SchedulerContext.getConfigProperty(value),
                String.class);
    }
    if (Character.isDigit(value.charAt(0))) {
        value = "PT" + value;
    }
    try {
        return Duration.parse(value);
    } catch (Exception e) {
        // This could only happen for config-based expressions
        throw new IllegalStateException("Invalid " + memberName + "() expression on: " + scheduled, e);
    }
}
 
Example #8
Source File: ConverterTest.java    From microprofile-config with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetDuckConverterWithMultipleConverters() {
    // defines 2 config with the converters defined in different orders.
    // Order must not matter, the UpperCaseDuckConverter must always be used as it has the highest priority
    Config config1 = ConfigProviderResolver.instance().getBuilder().addDefaultSources()
        .withConverters(new UpperCaseDuckConverter(), new DuckConverter())
        .build();
    Config config2 = ConfigProviderResolver.instance().getBuilder().addDefaultSources()
        .withConverters(new DuckConverter(), new UpperCaseDuckConverter())
        .build();

    Duck duck = config1.getConverter(Duck.class).get().convert("Hannelore");
    Assert.assertNotNull(duck);
    Assert.assertEquals(duck.getName(), "HANNELORE",
        "The converter with the highest priority (UpperCaseDuckConverter) must be used.");

    duck = config2.getConverter(Duck.class).get().convert("Hannelore");
    Assert.assertNotNull(duck);
    // the UpperCaseDuckConverter has highest priority
    Assert.assertEquals(duck.getName(), "HANNELORE",
        "The converter with the highest priority (UpperCaseDuckConverter) must be used.");
}
 
Example #9
Source File: SpringScheduledProcessor.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private long valueOf(String paramName, String paramValueString) {
    long paramValue;
    if (paramValueString.startsWith("${")) {
        paramValueString = paramValueString.replace("${", "{").trim();
        paramValueString = ConfigProviderResolver.instance().getConfig().getValue(
                SchedulerContext.getConfigProperty(paramValueString),
                String.class);
    }
    try {
        paramValue = Long.valueOf(paramValueString);
    } catch (NumberFormatException e) {
        throw new IllegalArgumentException(
                "Invalid '" + paramName + "String' value \"" + paramValueString + "\" - cannot parse into long");
    }
    return paramValue;
}
 
Example #10
Source File: SmallRyeConfigAuxiliaryArchiveAppender.java    From smallrye-config with Apache License 2.0 6 votes vote down vote up
@Override
public Archive<?> createAuxiliaryArchive() {
    JavaArchive configJar = ShrinkWrap
            .create(JavaArchive.class, "smallrye-config.jar")
            .addPackage(SmallRyeConfig.class.getPackage())
            .addPackage(ConfigExtension.class.getPackage())
            .addAsServiceProvider(Extension.class, ConfigExtension.class)
            .addAsServiceProvider(ConfigProviderResolver.class, SmallRyeConfigProviderResolver.class);
    return configJar;
}
 
Example #11
Source File: AutoDiscoveredConfigSourceTest.java    From microprofile-config with Apache License 2.0 5 votes vote down vote up
@Test
public void testAutoDiscoveredConverterManuallyAdded() {

    Config config = ConfigProviderResolver.instance().getBuilder().addDefaultSources().addDiscoveredSources().addDiscoveredConverters().build();
    Pizza dVaule = config.getValue("tck.config.test.customDbConfig.key3", Pizza.class);
    Assert.assertEquals(dVaule.getSize(), "big");
    Assert.assertEquals(dVaule.getFlavor(), "cheese");
}
 
Example #12
Source File: JaxrsHeaderPropagationTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void startServers() throws Exception {
    
    AbstractResourceInfo.clearAllMaps();
    //keep out of process due to stack traces testing failures
    assertTrue("server did not launch correctly", launchServer(Server.class, true));
    createStaticBus();
    System.out.println("Listening on port " + PORT);

    ConfigProviderResolver.setInstance(
        new MockConfigProviderResolver(Collections.singletonMap(
            "org.eclipse.microprofile.rest.client.propagateHeaders", "Header1,MultiHeader")));
}
 
Example #13
Source File: RestClientCdiTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testProvidersRegisteredViaMPConfigProperty() throws Exception {
    Map<String, String> configValues = new HashMap<>();
    configValues.put(InterfaceWithoutProvidersDefined.class.getName() + "/mp-rest/providers",
                     HighPriorityClientReqFilter.class.getName() + ","
                     + LowPriorityClientReqFilter.class.getName() + ","
                     + InvokedMethodClientRequestFilter.class.getName());
    configValues.put(InterfaceWithoutProvidersDefined.class.getName() + "/mp-rest/providers/" 
                     + LowPriorityClientReqFilter.class.getName() + "/priority", "3");
    ((MockConfigProviderResolver)ConfigProviderResolver.instance()).setConfigValues(configValues);

    IMocksControl control = EasyMock.createNiceControl();
    BeanManager mockedBeanMgr = control.createMock(BeanManager.class);
    mockedBeanMgr.isScope(Path.class);
    EasyMock.expectLastCall().andReturn(false);
    mockedBeanMgr.isScope(Produces.class);
    EasyMock.expectLastCall().andReturn(false);
    mockedBeanMgr.isScope(Consumes.class);
    EasyMock.expectLastCall().andReturn(false);
    control.replay();

    RestClientBean bean = new RestClientBean(InterfaceWithoutProvidersDefined.class, mockedBeanMgr);
    List<Class<?>> registeredProviders = bean.getConfiguredProviders();
    assertEquals(3, registeredProviders.size());
    assertTrue(registeredProviders.contains(HighPriorityClientReqFilter.class));
    assertTrue(registeredProviders.contains(LowPriorityClientReqFilter.class));
    assertTrue(registeredProviders.contains(InvokedMethodClientRequestFilter.class));

    Map<Class<?>, Integer> priorities = bean.getConfiguredProviderPriorities(registeredProviders);
    assertEquals(3, priorities.size());
    assertEquals(3, (int) priorities.get(LowPriorityClientReqFilter.class));
    assertEquals(10, (int) priorities.get(HighPriorityClientReqFilter.class));
    assertEquals(Priorities.USER, (int) priorities.get(InvokedMethodClientRequestFilter.class));

    control.verify();
}
 
Example #14
Source File: ConfigArchiveAppender.java    From hammock with 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 #15
Source File: ClusterIT.java    From apicurio-registry with 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 File: ConfigArchiveAppender.java    From hammock with 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 #17
Source File: ConverterTest.java    From microprofile-config with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetDonaldConverterWithLambdaConverter() {
    Config newConfig = ConfigProviderResolver.instance().getBuilder().addDefaultSources()
        .withConverter(Donald.class, 100, (s) -> Donald.iLikeDonald(s))
        .build();
    Donald donald = newConfig.getConverter(Donald.class).get().convert("Duck");
    Assert.assertNotNull(donald);
    Assert.assertEquals(donald.getName(), "Duck");
}
 
Example #18
Source File: ConverterTest.java    From microprofile-config with Apache License 2.0 5 votes vote down vote up
@Test
public void testDonaldConversionWithLambdaConverter() {
    Config newConfig = ConfigProviderResolver.instance().getBuilder().addDefaultSources()
        .withConverter(Donald.class, 100, (s) -> Donald.iLikeDonald(s))
        .build();
    Donald donald = newConfig.getValue("tck.config.test.javaconfig.converter.donaldname", Donald.class);
    Assert.assertNotNull(donald);
    Assert.assertEquals(donald.getName(), "Duck");
}
 
Example #19
Source File: GlobalTagsTest.java    From microprofile-metrics with Apache License 2.0 5 votes vote down vote up
public static void doWithConfig(Config config, Runnable runnable) {
    ClassLoader tccl = Thread.currentThread().getContextClassLoader();
    Config originalConfig = ConfigProviderResolver.instance().getConfig();
    try {
        ConfigProviderResolver.instance().releaseConfig(originalConfig);
        ConfigProviderResolver.instance().registerConfig(config, tccl);
        runnable.run();
    }
    finally {
        ConfigProviderResolver.instance().releaseConfig(config);
    }
}
 
Example #20
Source File: GlobalTagsTest.java    From microprofile-metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void customConfigSource() {
    ConfigSource s = new ConfigSource() {
        @Override
        public Map<String, String> getProperties() {
            return Collections.singletonMap("mp.metrics.tags", "foo=baz");
        }

        @Override
        public String getValue(String propertyName) {
            return propertyName.equals("mp.metrics.tags") ? "foo=baz" : null;
        }

        @Override
        public String getName() {
            return "Custom config source";
        }
    };
    Config config = ConfigProviderResolver.instance().getBuilder().withSources(s).build();
    doWithConfig(config, () -> {
        registry.counter("mycounter");
        MetricID actualMetricId = registry.getCounters().keySet().stream()
            .filter(id -> id.getName().equals("mycounter")).findAny().get();
        Assert.assertThat(actualMetricId.getTagsAsList(), containsInAnyOrder(
            new Tag("foo", "baz")
        ));
    });
}
 
Example #21
Source File: ConfigProducer.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
@PostConstruct
void init() {
    config = ConfigProviderResolver.instance().getBuilder()
        .addDefaultSources()
        .addDiscoveredSources()
        .addDiscoveredConverters()
        .build();
}
 
Example #22
Source File: CustomInvokeWithJsonBProviderTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@AfterTest
public void tearDownClient() {
    ConfigProviderResolver cpr = ConfigProviderResolver.instance();
    try {
        Config old = cpr.getConfig();
        cpr.releaseConfig(old);
    } catch (IllegalStateException ignored) {
    }
}
 
Example #23
Source File: CustomInvokeWithJsonBProviderTest.java    From quarkus with 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();
}
 
Example #24
Source File: CustomInvokeWithJsonPProviderTest.java    From quarkus with 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();
}
 
Example #25
Source File: VaultMultiPathConfigITCase.java    From quarkus with 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 #26
Source File: VaultMultiPathConfigITCase.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void prefixPath() {
    Config config = ConfigProviderResolver.instance().getConfig();
    assertEquals("green", config.getValue("singer.color", String.class));
    assertEquals("paul", config.getValue("singer.firstname", String.class));
    assertEquals("simon", config.getValue("singer.lastname", String.class));
    assertEquals("78", config.getValue("singer.age", String.class));
}
 
Example #27
Source File: VaultITCase.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@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 #28
Source File: ApplicationYamlTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@BeforeAll
public static void doBefore() {
    SmallRyeConfigBuilder builder = new SmallRyeConfigBuilder();
    builder.addDefaultSources().addDiscoveredConverters().addDiscoveredSources();
    QuarkusConfigFactory.setConfig(config = builder.build());
    Config conf = ConfigProvider.getConfig();
    if (conf != config) {
        ConfigProviderResolver cpr = ConfigProviderResolver.instance();
        cpr.releaseConfig(conf);
        ConfigProvider.getConfig();
    }
    System.out.println(System.getProperty("user.dir"));
}
 
Example #29
Source File: NativeImageLauncher.java    From quarkus with Apache License 2.0 5 votes vote down vote up
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: Application.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public final void close() {
    try {
        stop();
    } finally {
        try {
            ConfigProviderResolver.instance()
                    .releaseConfig(
                            ConfigProviderResolver.instance().getConfig(Thread.currentThread().getContextClassLoader()));
        } catch (Throwable ignored) {

        }
    }
}