org.zodic.kubernetes.confcenter.PropertySourceUtil Maven / Gradle / Ivy
package org.zodic.kubernetes.confcenter;
import static org.springframework.beans.factory.config.YamlProcessor.MatchStatus.ABSTAIN;
import static org.springframework.beans.factory.config.YamlProcessor.MatchStatus.FOUND;
import static org.springframework.beans.factory.config.YamlProcessor.MatchStatus.NOT_FOUND;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import org.springframework.core.io.ByteArrayResource;
import org.zodiac.sdk.toolkit.util.lang.StrUtil;
public final class PropertySourceUtil {
static final Function KEY_VALUE_TO_PROPERTIES = s -> {
Properties properties = new Properties();
try {
properties.load(new ByteArrayInputStream(s.getBytes()));
return properties;
} catch (IOException e) {
throw new IllegalArgumentException();
}
};
static final Function> PROPERTIES_TO_MAP = p -> p.entrySet().stream()
.collect(Collectors.toMap(e -> String.valueOf(e.getKey()), e -> String.valueOf(e.getValue())));
private PropertySourceUtil() {
throw new IllegalStateException("Can't instantiate a utility class");
}
static Function yamlParserGenerator(Environment environment) {
return s -> {
YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
yamlFactory.setDocumentMatchers(properties -> {
String profiles = properties.getProperty("spring.profiles");
if (environment != null && StrUtil.isNotBlank(profiles)) {
return environment.acceptsProfiles(Profiles.of(profiles)) ? FOUND : NOT_FOUND;
} else {
return ABSTAIN;
}
});
yamlFactory.setResources(new ByteArrayResource(s.getBytes()));
return yamlFactory.getObject();
};
}
}