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

The following examples show how to use org.eclipse.microprofile.config.spi.ConfigSource. 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: CustomConfigSourceTest.java    From microprofile-config with Apache License 2.0 6 votes vote down vote up
@Deployment
public static WebArchive deploy() {
    JavaArchive testJar = ShrinkWrap
            .create(JavaArchive.class, "customConfigSourceTest.jar")
            .addClasses(CustomConfigSourceTest.class, CustomDbConfigSource.class, CustomConfigSourceProvider.class)
            .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
            .addAsServiceProvider(ConfigSource.class, CustomDbConfigSource.class)
            .addAsServiceProvider(ConfigSourceProvider.class, CustomConfigSourceProvider.class)
            .as(JavaArchive.class);

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

    WebArchive war = ShrinkWrap
            .create(WebArchive.class, "customConfigSourceTest.war")
            .addAsLibrary(testJar);
    return war;
}
 
Example #2
Source File: HammockConfigSourceProvider.java    From hammock with Apache License 2.0 6 votes vote down vote up
@Override
public List<ConfigSource> getConfigSources(ClassLoader classLoader) {
    List<ConfigSource> configSources = new ArrayList<>();
    ConfigSource cli = CLIPropertySource.parseMainArgs(Bootstrap.ARGS);
    configSources.add(cli);
    String propertyValue = cli.getValue("hammock.external.config");
    if(propertyValue != null) {
        try {
            URL url = Paths.get(propertyValue).toUri().toURL();
            configSources.add(new PropertyFileConfigSource(url));
        } catch (MalformedURLException e) {
            throw new RuntimeException("Unable to load "+propertyValue,e);
        }
    }

    for(String prop : defaultPropertyFiles) {
        configSources.addAll(new PropertyFileConfigSourceProvider(prop, true, classLoader).getConfigSources(classLoader));
    }

    return configSources;
}
 
Example #3
Source File: SpringCloudConfigServerClientConfigSourceProvider.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public Iterable<ConfigSource> getConfigSources(ClassLoader forClassLoader) {
    try {
        final Response response = springCloudConfigClientGateway.exchange(applicationName, activeProfile);
        final List<Response.PropertySource> propertySources = response.getPropertySources();
        Collections.reverse(propertySources); // reverse the property sources so we can increment the ordinal from lower priority to higher
        final List<ConfigSource> result = new ArrayList<>(propertySources.size());
        for (int i = 0; i < propertySources.size(); i++) {
            final Response.PropertySource propertySource = propertySources.get(i);
            // Property sources obtained from Spring Cloud Config are expected to have a higher priority than even system properties
            // 400 is the ordinal of SysPropConfigSource, so we use 450 here
            result.add(new InMemoryConfigSource(450 + i, propertySource.getName(), propertySource.getSource()));
        }
        return result;
    } catch (Exception e) {
        final String errorMessage = "Unable to obtain configuration from Spring Cloud Config Server at "
                + springCloudConfigClientConfig.url;
        if (springCloudConfigClientConfig.failFast) {
            throw new RuntimeException(errorMessage, e);
        } else {
            log.error(errorMessage, e);
            return Collections.emptyList();
        }
    }
}
 
Example #4
Source File: ConfigSourceWrapperTestCase.java    From smallrye-config with Apache License 2.0 6 votes vote down vote up
@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 #5
Source File: EnvConfigSourceTestCase.java    From smallrye-config with Apache License 2.0 6 votes vote down vote up
@Test
public void testConversionOfEnvVariableNames() {
    String envProp = System.getenv("SMALLRYE_MP_CONFIG_PROP");
    assertNotNull(envProp);

    ConfigSource cs = new EnvConfigSource();
    assertEquals(envProp, cs.getValue("SMALLRYE_MP_CONFIG_PROP"));
    // the config source returns only the name of the actual env variable
    assertTrue(cs.getPropertyNames().contains("SMALLRYE_MP_CONFIG_PROP"));

    assertEquals(envProp, cs.getValue("smallrye_mp_config_prop"));
    assertFalse(cs.getPropertyNames().contains("smallrye_mp_config_prop"));

    assertEquals(envProp, cs.getValue("smallrye.mp.config.prop"));
    assertFalse(cs.getPropertyNames().contains("smallrye.mp.config.prop"));

    assertEquals(envProp, cs.getValue("SMALLRYE.MP.CONFIG.PROP"));
    assertFalse(cs.getPropertyNames().contains("SMALLRYE.MP.CONFIG.PROP"));

    assertEquals(envProp, cs.getValue("smallrye-mp-config-prop"));
    assertFalse(cs.getPropertyNames().contains("smallrye-mp-config-prop"));

    assertEquals(envProp, cs.getValue("SMALLRYE-MP-CONFIG-PROP"));
    assertFalse(cs.getPropertyNames().contains("SMALLRYE-MP-CONFIG-PROP"));
}
 
Example #6
Source File: HammockArchiveAppender.java    From hammock with Apache License 2.0 6 votes vote down vote up
@Override
public void process(Archive<?> archive, TestClass testClass) {
    EnableRandomWebServerPort annotation = testClass.getJavaClass().getAnnotation(EnableRandomWebServerPort.class);
    JavaArchive jar = archive.as(JavaArchive.class)
       .addPackage("io.astefanutti.metrics.cdi")
       .addAsResource(TOMCAT_BASE, "hammock.properties")
       .addAsManifestResource(BEANS_XML, "beans.xml");

    if(annotation != null) {
        if (annotation.enableSecure()) {
            jar.addAsServiceProviderAndClasses(ConfigSource.class, RandomWebServerPort.class, RandomWebServerSecuredPort.class);
        } else {
            jar.addAsServiceProviderAndClasses(ConfigSource.class, RandomWebServerPort.class);
        }
    }
}
 
Example #7
Source File: BuilderReuseTestCase.java    From smallrye-config with 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 #8
Source File: KubernetesConfigSourceProvider.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private List<ConfigSource> getConfigMapConfigSources(List<String> configMapNames) {
    List<ConfigSource> result = new ArrayList<>(configMapNames.size());

    try {
        for (String configMapName : configMapNames) {
            if (log.isDebugEnabled()) {
                log.debug("Attempting to read ConfigMap " + configMapName);
            }
            ConfigMap configMap = client.configMaps().withName(configMapName).get();
            if (configMap == null) {
                logMissingOrFail(configMapName, client.getNamespace(), "ConfigMap", config.failOnMissingConfig);
            } else {
                result.addAll(
                        configMapConfigSourceUtil.toConfigSources(configMap.getMetadata().getName(), configMap.getData()));
                if (log.isDebugEnabled()) {
                    log.debug("Done reading ConfigMap " + configMap);
                }
            }
        }
        return result;
    } catch (Exception e) {
        throw new RuntimeException("Unable to obtain configuration for ConfigMap objects for Kubernetes API Server at: "
                + client.getConfiguration().getMasterUrl(), e);
    }
}
 
Example #9
Source File: MockConfigProviderResolver.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public Iterable<ConfigSource> getConfigSources() {
    ConfigSource source = new ConfigSource() {
        @Override
        public Map<String, String> getProperties() {
            return configValues;
        }
        @Override
        public String getValue(String propertyName) {
            return (String) configValues.get(propertyName);
        }
        @Override
        public String getName() {
            return "stub";
        } };
    return Arrays.asList(source);
}
 
Example #10
Source File: MockConfigProviderResolver.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public Iterable<ConfigSource> getConfigSources() {
    ConfigSource source = new ConfigSource() {
        @Override
        public Map<String, String> getProperties() {
            return configValues;
        }
        @Override
        public String getValue(String propertyName) {
            return (String) configValues.get(propertyName);
        }
        @Override
        public String getName() {
            return "stub";
        } };
    return Arrays.asList(source);
}
 
Example #11
Source File: CustomConfigSourceProvider.java    From microprofile-config with Apache License 2.0 6 votes vote down vote up
@Override
public Iterable<ConfigSource> getConfigSources(ClassLoader forClassLoader) {
    List<ConfigSource> detectedConfigSources = new ArrayList<>();

    Enumeration<URL> yamlFiles = null;
    try {
        yamlFiles = forClassLoader.getResources("sampleconfig.yaml");
    }
    catch (IOException e) {
        throw new RuntimeException(e);
    }
    while (yamlFiles.hasMoreElements()) {
        detectedConfigSources.add(new SampleYamlConfigSource(yamlFiles.nextElement()));
    }
    return detectedConfigSources;
}
 
Example #12
Source File: ApplicationYamlProvider.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public Iterable<ConfigSource> getConfigSources(final ClassLoader forClassLoader) {
    List<ConfigSource> yamlSources = getConfigSourcesForFileName(APPLICATION_YAML, APPLICATION_YAML_IN_JAR_ORDINAL,
            forClassLoader);
    List<ConfigSource> ymlSources = getConfigSourcesForFileName(APPLICATION_YML, APPLICATION_YML_IN_JAR_ORDINAL,
            forClassLoader);
    if (yamlSources.isEmpty() && ymlSources.isEmpty()) {
        return Collections.emptyList();
    } else if (yamlSources.isEmpty()) {
        return ymlSources;
    } else if (ymlSources.isEmpty()) {
        return yamlSources;
    }
    List<ConfigSource> result = new ArrayList<>(yamlSources.size() + ymlSources.size());
    result.addAll(yamlSources);
    result.addAll(ymlSources);
    return result;
}
 
Example #13
Source File: ArrayTest.java    From smallrye-config with Apache License 2.0 6 votes vote down vote up
@Test
public void array() {
    String yaml = "de:\n" +
            "  javahippie:\n" +
            "    mpadmin:\n" +
            "      instances:\n" +
            "        -\n" +
            "          name: \"Bing\"\n" +
            "          uri: \"https://bing.com\"\n" +
            "        -\n" +
            "          name: \"Google\"\n" +
            "          uri: \"https://www.google.com\"";

    ConfigSource src = new YamlConfigSource("Yaml", yaml);
    assertNotNull(src.getValue("de.javahippie.mpadmin.instances"));
}
 
Example #14
Source File: SmallRyeConfig.java    From smallrye-config with Apache License 2.0 6 votes vote down vote up
/**
 * Builds a representation of Config Sources, Interceptors and the Interceptor chain to be used in Config. Note
 * that this constructor must be used when the Config object is being initialized, because interceptors also
 * require initialization.
 *
 * Instances of the Interceptors are then kept in ConfigSources if the interceptor chain requires a reorder (in
 * the case a new ConfigSource is addded to Config).
 *
 * @param sources the Config Sources to be part of Config.
 * @param interceptors the Interceptors to be part of Config.
 */
ConfigSources(final List<ConfigSource> sources, final List<InterceptorWithPriority> interceptors) {
    final List<ConfigSourceInterceptorWithPriority> sortInterceptors = new ArrayList<>();
    sortInterceptors.addAll(sources.stream().map(ConfigSourceInterceptorWithPriority::new).collect(toList()));
    sortInterceptors.addAll(interceptors.stream().map(ConfigSourceInterceptorWithPriority::new).collect(toList()));
    sortInterceptors.sort(Comparator.comparingInt(ConfigSourceInterceptorWithPriority::getPriority));

    final List<ConfigSourceInterceptorWithPriority> initInterceptors = new ArrayList<>();
    SmallRyeConfigSourceInterceptorContext current = new SmallRyeConfigSourceInterceptorContext(EMPTY, null);
    for (ConfigSourceInterceptorWithPriority configSourceInterceptor : sortInterceptors) {
        final ConfigSourceInterceptorWithPriority initInterceptor = configSourceInterceptor.getInterceptor(current);
        current = new SmallRyeConfigSourceInterceptorContext(initInterceptor.getInterceptor(), current);
        initInterceptors.add(initInterceptor);
    }

    this.interceptorChain = current;
    // This init any ConfigSourceFactory with current build chain (regular sources + interceptors).
    initInterceptors.stream()
            .map(ConfigSourceInterceptorWithPriority::getInterceptor)
            .filter(SmallRyeConfigSourceInterceptor.class::isInstance)
            .map(SmallRyeConfigSourceInterceptor.class::cast)
            .forEach(interceptor -> interceptor.apply(interceptorChain::proceed));

    this.sources = Collections.unmodifiableList(getSources(initInterceptors));
    this.interceptors = Collections.unmodifiableList(initInterceptors);
}
 
Example #15
Source File: TestCustomConfigProfile.java    From microprofile-config with Apache License 2.0 6 votes vote down vote up
@Deployment
public static Archive deployment() {
    JavaArchive testJar = ShrinkWrap
            .create(JavaArchive.class, "TestConfigProfileTest.jar")
            .addClasses(TestCustomConfigProfile.class, ProfilePropertyBean.class, CustomConfigProfileConfigSource.class)
            .addAsServiceProvider(ConfigSource.class, CustomConfigProfileConfigSource.class)
            .addAsManifestResource(
                new StringAsset(
                    "mp.config.profile=prod\n" +
                    "%dev.vehicle.name=bus\n" +
                    "%prod.vehicle.name=bike\n" +
                    "%test.vehicle.name=coach\n" +
                    "vehicle.name=car"),
                    "microprofile-config.properties")
            .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
            .as(JavaArchive.class);

    WebArchive war = ShrinkWrap
            .create(WebArchive.class, "TestConfigProfileTest.war")
            .addAsLibrary(testJar);
    return war;
}
 
Example #16
Source File: KeycloakConfigSourceProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public Iterable<ConfigSource> getConfigSources(ClassLoader forClassLoader) {

    List<ConfigSource> sources = new ArrayList<>();

    String filePath = System.getProperty(KEYCLOAK_CONFIG_FILE_PROP);

    if (filePath == null)
        filePath = System.getenv(KEYCLOAK_CONFIG_FILE_ENV);

    if (filePath == null) {
        String homeDir = System.getProperty("keycloak.home.dir");

        if (homeDir != null) {
            File file = Paths.get(homeDir, "conf", KeycloakPropertiesConfigSource.KEYCLOAK_PROPERTIES).toFile();

            if (file.exists()) {
                filePath = file.getAbsolutePath();
            }
        }
    }

    if (filePath != null) {
        sources.add(wrap(new KeycloakPropertiesConfigSource.InFileSystem(filePath)));
    }

    // fall back to the default configuration within the server classpath
    if (sources.isEmpty()) {
        log.debug("Loading the default server configuration");
        sources.add(wrap(new KeycloakPropertiesConfigSource.InJar()));
    }

    return sources;

}
 
Example #17
Source File: DefaultConfigBuilder.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
@Override
public ConfigBuilder withSources(ConfigSource... sources) {
    for(ConfigSource cs : sources) {
        config.addConfigSource(cs);
    }
    return this;
}
 
Example #18
Source File: ConsulConfigSourceProviderTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
void testWithMissingKeysAndIgnoreFailureConfigured() throws IOException {
    ConsulConfig config = defaultConfig();
    config.rawValueKeys = keyValues("some/first", "some/second", "some/third");
    config.failOnMissingKey = false;

    ConsulConfigGateway mockGateway = mock(ConsulConfigGateway.class);
    // make sure the first is is properly resolved
    when(mockGateway.getValue("some/first")).thenReturn(createOptionalResponse("some/first", "whatever"));
    // make sure the second is not resolved
    when(mockGateway.getValue("some/second")).thenReturn(Optional.empty());
    // make sure the third is is properly resolved
    when(mockGateway.getValue("some/third")).thenReturn(createOptionalResponse("some/third", "other"));

    ConsulConfigSourceProvider sut = new ConsulConfigSourceProvider(config, mockGateway);

    Iterable<ConfigSource> configSources = sut.getConfigSources(null);
    assertThat(configSources).hasSize(2);
    assertThat(configSources).filteredOn(c -> c.getName().contains("first")).hasOnlyOneElementSatisfying(c -> {
        assertThat(c.getOrdinal()).isEqualTo(EXPECTED_ORDINAL);
        assertThat(c.getProperties()).containsOnly(entry("some.first", "whatever"));
    });
    assertThat(configSources).filteredOn(c -> c.getName().contains("third")).hasOnlyOneElementSatisfying(c -> {
        assertThat(c.getOrdinal()).isEqualTo(EXPECTED_ORDINAL);
        assertThat(c.getProperties()).containsOnly(entry("some.third", "other"));
    });

    //all keys should have been resolved because we resolve keys in the order they were given by the user
    verify(mockGateway, times(1)).getValue("some/first");
    verify(mockGateway, times(1)).getValue("some/second");
    verify(mockGateway, times(1)).getValue("some/third");
}
 
Example #19
Source File: ConfigProviderTest.java    From microprofile-config with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetConfigSources() {
    Iterable<ConfigSource> configSources = config.getConfigSources();
    Assert.assertNotNull(configSources);

    // check descending sorting
    int prevOrdinal = Integer.MAX_VALUE;
    for (ConfigSource configSource : configSources) {
        Assert.assertTrue(configSource.getOrdinal() <= prevOrdinal);
        prevOrdinal = configSource.getOrdinal();
    }

}
 
Example #20
Source File: ConfigMapConfigSourceUtilTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
void testEmptyData() {
    ConfigMap configMap = configMapBuilder("testEmptyData").build();

    List<ConfigSource> configSources = sut.toConfigSources(configMap.getMetadata().getName(), configMap.getData());

    assertThat(configSources).isEmpty();
}
 
Example #21
Source File: ConfigConfigSourceTest.java    From smallrye-config with Apache License 2.0 5 votes vote down vote up
@Test
public void lowerPriority() {
    final SmallRyeConfig config = new SmallRyeConfigBuilder()
            .addDefaultSources()
            .addDefaultInterceptors()
            .withSources(KeyValuesConfigSource.config("my.prop", "1234"))
            .withSources(new ConfigSourceFactory() {
                @Override
                public ConfigSource getSource(final ConfigSourceContext context) {
                    return new AbstractConfigSource("test", 0) {
                        final ConfigValue value = context.getValue("my.prop");

                        @Override
                        public Map<String, String> getProperties() {
                            return null;
                        }

                        @Override
                        public String getValue(final String propertyName) {
                            return value != null ? value.getValue() : null;
                        }
                    };
                }

                @Override
                public OptionalInt getPriority() {
                    return OptionalInt.of(0);
                }
            })
            .build();

    assertEquals("1234", config.getRawValue("my.prop"));
    assertEquals("KeyValuesConfigSource", config.getConfigValue("my.prop").getConfigSourceName());
    assertEquals("1234", config.getRawValue("any"));
    assertEquals("test", config.getConfigValue("any").getConfigSourceName());
}
 
Example #22
Source File: KeyValuesConfigSource.java    From smallrye-config with Apache License 2.0 5 votes vote down vote up
public static ConfigSource config(String... keyValues) {
    if (keyValues.length % 2 != 0) {
        throw new IllegalArgumentException("keyValues array must be a multiple of 2");
    }

    Map<String, String> props = new HashMap<>();
    for (int i = 0; i < keyValues.length; i += 2) {
        props.put(keyValues[i], keyValues[i + 1]);
    }
    return new KeyValuesConfigSource(props);
}
 
Example #23
Source File: ConfigSourceWrapperTestCase.java    From smallrye-config with Apache License 2.0 5 votes vote down vote up
@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 File: HammockConfigSourceProviderTest.java    From hammock with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHaveCorrectPropertiesInFile() {
    Bootstrap.ARGS = new String[]{"--hammock.external.config=src/test/resources/testing.properties"};
    HammockConfigSourceProvider hammockConfigSourceProvider = new HammockConfigSourceProvider();
    ConfigSource configSource = hammockConfigSourceProvider.getConfigSources(getClass().getClassLoader()).get(1);
    assertEquals("1492", configSource.getValue("something.random"));
}
 
Example #25
Source File: VaultConfigSource.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private boolean retain(ConfigSource configSource) {
    String other;
    try {
        other = configSource.getName();
    } catch (NullPointerException e) {
        // FIXME at org.jboss.resteasy.microprofile.config.BaseServletConfigSource.getName(BaseServletConfigSource.java:51)
        other = null;
    }
    return !getName().equals(other);
}
 
Example #26
Source File: DummyConfigSourceProvider.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public Iterable<ConfigSource> getConfigSources(ClassLoader forClassLoader) {
    InMemoryConfigSource configSource = new InMemoryConfigSource(Integer.MIN_VALUE, "dummy config source");
    for (int i = 0; i < dummyConfig.times; i++) {
        configSource.add(dummyConfig.name + ".key.i" + (i + 1), applicationConfig.name.get() + (i + 1));
    }
    return Collections.singletonList(configSource);
}
 
Example #27
Source File: SmallRyeConfig.java    From smallrye-config with Apache License 2.0 5 votes vote down vote up
private List<ConfigSource> buildConfigSources(final SmallRyeConfigBuilder builder) {
    final List<ConfigSource> sourcesToBuild = new ArrayList<>(builder.getSources());
    if (builder.isAddDiscoveredSources()) {
        sourcesToBuild.addAll(builder.discoverSources());
    }
    if (builder.isAddDefaultSources()) {
        sourcesToBuild.addAll(builder.getDefaultSources());
    }
    if (!builder.getDefaultValues().isEmpty()) {
        sourcesToBuild.add(new MapBackedConfigSource("DefaultValuesConfigSource", builder.getDefaultValues()) {
            private static final long serialVersionUID = -2569643736033594267L;

            @Override
            public int getOrdinal() {
                return Integer.MIN_VALUE;
            }
        });
    }

    // wrap all
    final Function<ConfigSource, ConfigSource> sourceWrappersToBuild = builder.getSourceWrappers();
    final ListIterator<ConfigSource> it = sourcesToBuild.listIterator();
    while (it.hasNext()) {
        it.set(sourceWrappersToBuild.apply(it.next()));
    }

    return sourcesToBuild;
}
 
Example #28
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 #29
Source File: ConsulConfigSourceProviderTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
void testPropertiesKeysWithoutPrefix() throws IOException {
    ConsulConfig config = defaultConfig();
    config.propertiesValueKeys = keyValues("first", "second");

    ConsulConfigGateway mockGateway = mock(ConsulConfigGateway.class);
    when(mockGateway.getValue("first"))
            .thenReturn(createOptionalResponse("first", "greeting.message=hi\ngreeting.name=quarkus"));
    when(mockGateway.getValue("second"))
            .thenReturn(createOptionalResponse("second", "other.key=value"));

    ConsulConfigSourceProvider sut = new ConsulConfigSourceProvider(config, mockGateway);

    Iterable<ConfigSource> configSources = sut.getConfigSources(null);
    assertThat(configSources).hasSize(2);
    assertThat(configSources).filteredOn(c -> c.getName().contains("first")).hasOnlyOneElementSatisfying(c -> {
        assertThat(c.getOrdinal()).isEqualTo(EXPECTED_ORDINAL);
        assertThat(c.getProperties()).containsOnly(entry("greeting.message", "hi"),
                entry("greeting.name", "quarkus"));
    });
    assertThat(configSources).filteredOn(c -> c.getName().contains("second")).hasOnlyOneElementSatisfying(c -> {
        assertThat(c.getOrdinal()).isEqualTo(EXPECTED_ORDINAL);
        assertThat(c.getProperties()).containsOnly(entry("other.key", "value"));
    });

    verify(mockGateway, times(1)).getValue("first");
    verify(mockGateway, times(1)).getValue("second");
}
 
Example #30
Source File: FileSystemConfigSourceTestCase.java    From smallrye-config with Apache License 2.0 5 votes vote down vote up
@Test
public void testCharacterReplacement() throws URISyntaxException {
    URL configDirURL = this.getClass().getResource("configDir");
    File dir = new File(configDirURL.toURI());

    ConfigSource configSource = new FileSystemConfigSource(dir);
    // the non-alphanumeric chars may be replaced by _ 
    assertEquals("http://localhost:8080/my-service", configSource.getValue("MyService/mp-rest/url"));
    // or the file name is uppercased
    assertEquals("http://localhost:8080/other-service", configSource.getValue("OtherService/mp-rest/url"));
    // but the key is still case sensitive 
    assertNull(configSource.getValue("myservice/mp-rest/url"));
    // you can't rewrite the key, only the file name 
    assertNull(configSource.getValue("MYSERVICE_MP_REST_URL"));
}