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

The following examples show how to use org.eclipse.microprofile.config.spi.ConfigSource. 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: hammock   Source File: HammockArchiveAppender.java    License: 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 2
@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 3
Source Project: quarkus   Source File: KubernetesConfigSourceProvider.java    License: 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 4
Source Project: cxf   Source File: MockConfigProviderResolver.java    License: 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 5
@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 6
Source Project: smallrye-config   Source File: ArrayTest.java    License: 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 7
@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 8
Source Project: smallrye-config   Source File: SmallRyeConfig.java    License: 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 9
Source Project: quarkus   Source File: ApplicationYamlProvider.java    License: 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 10
Source Project: cxf   Source File: MockConfigProviderResolver.java    License: 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 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 12
Source Project: smallrye-config   Source File: EnvConfigSourceTestCase.java    License: 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 13
@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 14
Source Project: hammock   Source File: HammockConfigSourceProvider.java    License: 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 15
@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 16
Source Project: quarkus   Source File: ConsulConfigSourceProviderTest.java    License: 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 17
Source Project: smallrye-jwt   Source File: JwtSignEncryptTest.java    License: Apache License 2.0 5 votes vote down vote up
private static JwtBuildConfigSource getConfigSource() {
    for (ConfigSource cs : ConfigProvider.getConfig().getConfigSources()) {
        if (cs instanceof JwtBuildConfigSource) {
            return (JwtBuildConfigSource) cs;
        }
    }
    return null;
}
 
Example 18
Source Project: quarkus   Source File: ConfigMapConfigSourceUtilTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void testOnlySingleMatchingPropertiesData() {
    ConfigMap configMap = configMapBuilder("testOnlySingleMatchingPropertiesData")
            .addToData("application.properties", "key1=value1\nkey2=value2\nsome.key=someValue").build();

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

    assertThat(configSources).hasOnlyOneElementSatisfying(c -> {
        assertThat(c.getProperties()).containsOnly(entry("key1", "value1"), entry("key2", "value2"),
                entry("some.key", "someValue"));
        assertThat(c.getName()).contains("testOnlySingleMatchingPropertiesData");
    });
}
 
Example 19
Source Project: smallrye-config   Source File: ConfigSourceProvider.java    License: Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void init() {
    if (this.configSourceMap.isEmpty()) {
        for (ConfigSource configSource : configProvider.get().getConfigSources()) {
            this.configSourceMap.put(configSource.getName(), configSource);
        }
    }
}
 
Example 20
Source Project: smallrye-config   Source File: ConfigSourceProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Produces
@Name("")
public ConfigSource produceConfigSource(final InjectionPoint injectionPoint) {
    Set<Annotation> qualifiers = injectionPoint.getQualifiers();
    String name = getName(qualifiers);
    return configSourceMap.get(name);
}
 
Example 21
Source Project: smallrye-config   Source File: HoconConfigSourceProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Iterable<ConfigSource> getConfigSources(ClassLoader classLoader) {
    final List<ConfigSource> configSources = new ArrayList<>(2);
    configSources.add(getConfigSource(classLoader, META_INF_MICROPROFILE_CONFIG_RESOURCE, 60));
    configSources.add(getConfigSource(classLoader, WEB_INF_MICROPROFILE_CONFIG_RESOURCE, 50));
    return Collections.unmodifiableList(configSources);
}
 
Example 22
Source Project: smallrye-config   Source File: HoconConfigSourceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testHocon() {
    final ConfigSource configSource = HoconConfigSourceProvider.getConfigSource(
            Thread.currentThread().getContextClassLoader(), "hocon/microprofile-config.conf", 100);
    assertEquals(HoconConfigSource.DEFAULT_ORDINAL, configSource.getOrdinal());
    assertArrayEquals(new String[] { "hello.world", "hello.foo.bar" }, configSource.getPropertyNames().toArray());
    assertArrayEquals(new String[] { "hello.world", "hello.foo.bar" }, configSource.getPropertyNames().toArray());
    assertEquals("1", configSource.getValue("hello.world"));
    assertEquals("Hell yeah!", configSource.getValue("hello.foo.bar"));
    assertEquals(2, configSource.getProperties().entrySet().size());
    assertEquals("1", configSource.getProperties().get("hello.world"));
    assertEquals("Hell yeah!", configSource.getProperties().get("hello.foo.bar"));
}
 
Example 23
Source Project: smallrye-config   Source File: YamlConfigSourceProvider.java    License: Apache License 2.0 5 votes vote down vote up
static Optional<ConfigSource> getConfigSource(ClassLoader classLoader, String resource, int ordinal) {
    try {
        InputStream stream = classLoader.getResourceAsStream(resource);
        if (stream != null)
            try (Closeable c = stream) {
                return Optional.of(new YamlConfigSource(resource, stream, ordinal));
            }
    } catch (IOException e) {
        // ignored
    }
    return Optional.empty();
}
 
Example 24
Source Project: smallrye-config   Source File: BasicTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testBasicKeyValue() {
    String yaml = "foo:\n"
            + "    bar:\n"
            + "         baz: something\n"
            + "         zap: something else \n";

    ConfigSource src = new YamlConfigSource("Yaml", yaml);

    assertEquals("something", src.getValue("foo.bar.baz"));
    assertEquals("something else", src.getValue("foo.bar.zap"));
}
 
Example 25
Source Project: quarkus   Source File: KubernetesConfigSourceProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Iterable<ConfigSource> getConfigSources(ClassLoader forClassLoader) {
    if (!config.configMaps.isPresent()) {
        log.debug("No ConfigMaps were configured for config source lookup");
        return Collections.emptyList();
    }

    List<ConfigSource> result = new ArrayList<>();
    if (config.configMaps.isPresent()) {
        result.addAll(getConfigMapConfigSources(config.configMaps.get()));
    }
    return result;
}
 
Example 26
Source Project: smallrye-config   Source File: BasicTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@Disabled
public void testListOfListValue() {
    String yaml = "foo:\n"
            + "     bar:\n"
            + "        ~:\n"
            + "           - [cat, dog]\n"
            + "           - [mouse, rat]\n"
            + "           - [chicken, turkey]\n";

    ConfigSource src = new YamlConfigSource("Yaml", yaml);

    assertEquals("cat\\,dog,mouse\\,rat,chicken\\,turkey", src.getValue("foo.bar"));
}
 
Example 27
Source Project: hammock   Source File: CLIPropertySource.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Configure the main arguments, herby parsing and mapping the main arguments into
 * configuration properties.
 *
 * @return the parsed main arguments as key/value pairs.
 */
public static ConfigSource parseMainArgs(String...args) {
    Map<String, String> result;
    if (args == null) {
        result = Collections.emptyMap();
    } else {
        result = new HashMap<>();
        String prefix = System.getProperty("main.args.prefix","");
        String key = null;
        for (String arg : args) {
            if (arg.startsWith("--")) {
                arg = arg.substring(2);
                int index = arg.indexOf('=');
                if (index > 0) {
                    key = arg.substring(0, index).trim();
                    result.put(prefix + key, arg.substring(index + 1).trim());
                    key = null;
                } else {
                    result.put(prefix + arg, arg);
                }
            } else if (arg.charAt(0) == '-') {
                key = arg.substring(1);
            } else {
                if (key != null) {
                    result.put(prefix + key, arg);
                    key = null;
                } else {
                    result.put(prefix + arg, arg);
                }
            }
        }
    }
    return new CLIPropertySource(result);
}
 
Example 28
@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"));
}
 
Example 29
Source Project: microprofile-metrics   Source File: GlobalTagsTest.java    License: 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 30
Source Project: smallrye-config   Source File: SmallRyeConfig.java    License: 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;
}