use of org.springframework.boot.env.OriginTrackedMapPropertySource in project spring-cloud-config by spring-cloud.
the class PassthruEnvironmentRepositoryTests method originTrackedPropertySourceWithoutOriginWorks.
@Test
public void originTrackedPropertySourceWithoutOriginWorks() {
MockEnvironment mockEnvironment = new MockEnvironment();
mockEnvironment.setProperty("normalKey", "normalValue");
mockEnvironment.getPropertySources().addFirst(new OriginTrackedMapPropertySource("myorigintrackedsource", Collections.singletonMap("keyNoOrigin", "valueNoOrigin")));
PassthruEnvironmentRepository repository = new PassthruEnvironmentRepository(mockEnvironment);
Environment environment = repository.findOne("testapp", "default", "master", true);
assertThat(environment).isNotNull();
List<PropertySource> propertySources = environment.getPropertySources();
assertThat(propertySources).hasSize(2);
for (PropertySource propertySource : propertySources) {
Map source = propertySource.getSource();
if (propertySource.getName().equals("myorigintrackedsource")) {
assertThat(source).containsEntry("keyNoOrigin", "valueNoOrigin");
} else if (propertySource.getName().equals("mockProperties")) {
assertThat(source).containsEntry("normalKey", "normalValue");
}
}
}
use of org.springframework.boot.env.OriginTrackedMapPropertySource in project spring-cloud-config by spring-cloud.
the class ConfigServerConfigDataLoader method doLoad.
public ConfigData doLoad(ConfigDataLoaderContext context, ConfigServerConfigDataResource resource) {
ConfigClientProperties properties = resource.getProperties();
List<PropertySource<?>> propertySources = new ArrayList<>();
Exception error = null;
String errorBody = null;
try {
String[] labels = new String[] { "" };
if (StringUtils.hasText(properties.getLabel())) {
labels = StringUtils.commaDelimitedListToStringArray(properties.getLabel());
}
String state = ConfigClientStateHolder.getState();
// Try all the labels until one works
for (String label : labels) {
Environment result = getRemoteEnvironment(context, resource, label.trim(), state);
if (result != null) {
log(result);
// result.getPropertySources() can be null if using xml
if (result.getPropertySources() != null) {
for (org.springframework.cloud.config.environment.PropertySource source : result.getPropertySources()) {
@SuppressWarnings("unchecked") Map<String, Object> map = translateOrigins(source.getName(), (Map<String, Object>) source.getSource());
propertySources.add(0, new OriginTrackedMapPropertySource("configserver:" + source.getName(), map));
}
}
HashMap<String, Object> map = new HashMap<>();
if (StringUtils.hasText(result.getState())) {
putValue(map, "config.client.state", result.getState());
}
if (StringUtils.hasText(result.getVersion())) {
putValue(map, "config.client.version", result.getVersion());
}
// the existence of this property source confirms a successful
// response from config server
propertySources.add(0, new MapPropertySource(CONFIG_CLIENT_PROPERTYSOURCE_NAME, map));
if (ALL_OPTIONS.size() == 1) {
// boot 2.4.2 and prior
return new ConfigData(propertySources);
} else if (ALL_OPTIONS.size() == 2) {
// boot 2.4.3 and 2.4.4
return new ConfigData(propertySources, Option.IGNORE_IMPORTS, Option.IGNORE_PROFILES);
} else if (ALL_OPTIONS.size() > 2) {
// boot 2.4.5+
return new ConfigData(propertySources, propertySource -> {
String propertySourceName = propertySource.getName();
List<Option> options = new ArrayList<>();
options.add(Option.IGNORE_IMPORTS);
options.add(Option.IGNORE_PROFILES);
// https://github.com/spring-cloud/spring-cloud-config/issues/1874
for (String profile : resource.getAcceptedProfiles()) {
// - is the default profile-separator for property sources
if (propertySourceName.matches(".*[-,]" + profile + ".*")) {
// // TODO: switch to Options.with() when implemented
options.add(Option.PROFILE_SPECIFIC);
}
}
return Options.of(options.toArray(new Option[0]));
});
}
}
}
errorBody = String.format("None of labels %s found", Arrays.toString(labels));
} catch (HttpServerErrorException e) {
error = e;
if (MediaType.APPLICATION_JSON.includes(e.getResponseHeaders().getContentType())) {
errorBody = e.getResponseBodyAsString();
}
} catch (Exception e) {
error = e;
}
if (properties.isFailFast() || !resource.isOptional()) {
String reason;
if (properties.isFailFast()) {
reason = "the fail fast property is set";
} else {
reason = "the resource is not optional";
}
throw new ConfigClientFailFastException("Could not locate PropertySource and " + reason + ", failing" + (errorBody == null ? "" : ": " + errorBody), error);
}
logger.warn("Could not locate PropertySource (" + resource + "): " + (error != null ? error.getMessage() : errorBody));
return null;
}
use of org.springframework.boot.env.OriginTrackedMapPropertySource in project spring-cloud-config by spring-cloud.
the class ConfigServicePropertySourceLocator method locate.
@Override
@Retryable(interceptor = "configServerRetryInterceptor")
public org.springframework.core.env.PropertySource<?> locate(org.springframework.core.env.Environment environment) {
ConfigClientProperties properties = this.defaultProperties.override(environment);
if (StringUtils.startsWithIgnoreCase(properties.getName(), "application-")) {
InvalidApplicationNameException exception = new InvalidApplicationNameException(properties.getName());
if (properties.isFailFast()) {
throw exception;
} else {
logger.warn(NAME_PLACEHOLDER + " resolved to " + properties.getName() + ", not going to load remote properties. Ensure application name doesn't start with 'application-'");
return null;
}
}
CompositePropertySource composite = new OriginTrackedCompositePropertySource("configService");
ConfigClientRequestTemplateFactory requestTemplateFactory = new ConfigClientRequestTemplateFactory(logger, properties);
Exception error = null;
String errorBody = null;
try {
String[] labels = new String[] { "" };
if (StringUtils.hasText(properties.getLabel())) {
labels = StringUtils.commaDelimitedListToStringArray(properties.getLabel());
}
String state = ConfigClientStateHolder.getState();
// Try all the labels until one works
for (String label : labels) {
Environment result = getRemoteEnvironment(requestTemplateFactory, label.trim(), state);
if (result != null) {
log(result);
// result.getPropertySources() can be null if using xml
if (result.getPropertySources() != null) {
for (PropertySource source : result.getPropertySources()) {
@SuppressWarnings("unchecked") Map<String, Object> map = translateOrigins(source.getName(), (Map<String, Object>) source.getSource());
composite.addPropertySource(new OriginTrackedMapPropertySource(source.getName(), map));
}
}
HashMap<String, Object> map = new HashMap<>();
if (StringUtils.hasText(result.getState())) {
putValue(map, "config.client.state", result.getState());
}
if (StringUtils.hasText(result.getVersion())) {
putValue(map, "config.client.version", result.getVersion());
}
// the existence of this property source confirms a successful
// response from config server
composite.addFirstPropertySource(new MapPropertySource("configClient", map));
return composite;
}
}
errorBody = String.format("None of labels %s found", Arrays.toString(labels));
} catch (HttpServerErrorException e) {
error = e;
if (MediaType.APPLICATION_JSON.includes(e.getResponseHeaders().getContentType())) {
errorBody = e.getResponseBodyAsString();
}
} catch (Exception e) {
error = e;
}
if (properties.isFailFast()) {
throw new IllegalStateException("Could not locate PropertySource and the fail fast property is set, failing" + (errorBody == null ? "" : ": " + errorBody), error);
}
logger.warn("Could not locate PropertySource: " + (error != null ? error.getMessage() : errorBody));
return null;
}
use of org.springframework.boot.env.OriginTrackedMapPropertySource in project cf-ops-automation-broker by orange-cloudfoundry.
the class YamlCataloglAsEnvironmentVarApplicationContextInitializerTest method converts_legacy_to_scosb_keys.
@Test
public void converts_legacy_to_scosb_keys() {
// given
Map<String, String> source = new HashMap<>();
source.put("servicebroker.catalog.services[0].id", "ondemand-service");
source.put("servicebroker.catalog.services[0].name", "ondemand");
// when
OriginTrackedMapPropertySource convertedSource = contextInitializer.convertPropertySourceToScOsbKeyPrefix(source);
// then
assertThat(convertedSource.getSource()).containsOnly(entry("spring.cloud.openservicebroker.catalog.services[0].id", "ondemand-service"), entry("spring.cloud.openservicebroker.catalog.services[0].name", "ondemand"));
}
use of org.springframework.boot.env.OriginTrackedMapPropertySource in project spring-cloud-alibaba by alibaba.
the class NacosDataParserHandler method parseNacosData.
/**
* Parsing nacos configuration content.
* @param configName name of nacos-config
* @param configValue value from nacos-config
* @param extension identifies the type of configValue
* @return result of Map
* @throws IOException thrown if there is a problem parsing config.
*/
public List<PropertySource<?>> parseNacosData(String configName, String configValue, String extension) throws IOException {
if (StringUtils.isEmpty(configValue)) {
return Collections.emptyList();
}
if (StringUtils.isEmpty(extension)) {
extension = this.getFileExtension(configName);
}
for (PropertySourceLoader propertySourceLoader : propertySourceLoaders) {
if (!canLoadFileExtension(propertySourceLoader, extension)) {
continue;
}
NacosByteArrayResource nacosByteArrayResource;
if (propertySourceLoader instanceof PropertiesPropertySourceLoader) {
// PropertiesPropertySourceLoader internal is to use the ISO_8859_1,
// the Chinese will be garbled, needs to transform into unicode.
nacosByteArrayResource = new NacosByteArrayResource(NacosConfigUtils.selectiveConvertUnicode(configValue).getBytes(), configName);
} else {
nacosByteArrayResource = new NacosByteArrayResource(configValue.getBytes(), configName);
}
nacosByteArrayResource.setFilename(getFileName(configName, extension));
List<PropertySource<?>> propertySourceList = propertySourceLoader.load(configName, nacosByteArrayResource);
if (CollectionUtils.isEmpty(propertySourceList)) {
return Collections.emptyList();
}
return propertySourceList.stream().filter(Objects::nonNull).map(propertySource -> {
if (propertySource instanceof EnumerablePropertySource) {
String[] propertyNames = ((EnumerablePropertySource) propertySource).getPropertyNames();
if (propertyNames != null && propertyNames.length > 0) {
Map<String, Object> map = new LinkedHashMap<>();
Arrays.stream(propertyNames).forEach(name -> {
map.put(name, propertySource.getProperty(name));
});
return new OriginTrackedMapPropertySource(propertySource.getName(), map, true);
}
}
return propertySource;
}).collect(Collectors.toList());
}
return Collections.emptyList();
}
Aggregations