Formatting
This commit is contained in:
@@ -64,16 +64,14 @@ public abstract class AbstractTlsSetup {
|
||||
}
|
||||
|
||||
private static File saveKeyAndCert(KeyAndCert keyCert) throws Exception {
|
||||
return saveKeyStore(keyCert.subject(),
|
||||
() -> keyCert.storeKeyAndCert(KEY_PASSWORD));
|
||||
return saveKeyStore(keyCert.subject(), () -> keyCert.storeKeyAndCert(KEY_PASSWORD));
|
||||
}
|
||||
|
||||
private static File saveCert(KeyAndCert keyCert) throws Exception {
|
||||
return saveKeyStore(keyCert.subject(), () -> keyCert.storeCert());
|
||||
}
|
||||
|
||||
private static File saveKeyStore(String prefix, KeyStoreSupplier func)
|
||||
throws Exception {
|
||||
private static File saveKeyStore(String prefix, KeyStoreSupplier func) throws Exception {
|
||||
File result = File.createTempFile(prefix, ".p12");
|
||||
result.deleteOnExit();
|
||||
|
||||
|
||||
@@ -113,8 +113,7 @@ public class AppRunner implements AutoCloseable {
|
||||
}
|
||||
|
||||
private boolean tlsEnabled() {
|
||||
return app.getEnvironment().getProperty("server.ssl.enabled", Boolean.class,
|
||||
false);
|
||||
return app.getEnvironment().getProperty("server.ssl.enabled", Boolean.class, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -70,8 +70,7 @@ public class KeyAndCert {
|
||||
KeyStore result = KeyStore.getInstance("PKCS12");
|
||||
result.load(null);
|
||||
|
||||
result.setKeyEntry(subject(), keyPair.getPrivate(), keyPassword.toCharArray(),
|
||||
certChain());
|
||||
result.setKeyEntry(subject(), keyPair.getPrivate(), keyPassword.toCharArray(), certChain());
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
@@ -50,15 +50,12 @@ public class KeyTool {
|
||||
return new KeyAndCert(keyPair, certificate);
|
||||
}
|
||||
|
||||
public KeyAndCert signCertificate(String subject, KeyAndCert signer)
|
||||
throws Exception {
|
||||
public KeyAndCert signCertificate(String subject, KeyAndCert signer) throws Exception {
|
||||
return signCertificate(createKeyPair(), subject, signer);
|
||||
}
|
||||
|
||||
public KeyAndCert signCertificate(KeyPair keyPair, String subject, KeyAndCert signer)
|
||||
throws Exception {
|
||||
X509Certificate certificate = createCert(keyPair.getPublic(), signer.privateKey(),
|
||||
signer.subject(), subject);
|
||||
public KeyAndCert signCertificate(KeyPair keyPair, String subject, KeyAndCert signer) throws Exception {
|
||||
X509Certificate certificate = createCert(keyPair.getPublic(), signer.privateKey(), signer.subject(), subject);
|
||||
KeyAndCert result = new KeyAndCert(keyPair, certificate);
|
||||
|
||||
return result;
|
||||
@@ -76,32 +73,25 @@ public class KeyTool {
|
||||
|
||||
public X509Certificate createCert(KeyPair keyPair, String ca) throws Exception {
|
||||
JcaX509v3CertificateBuilder builder = certBuilder(keyPair.getPublic(), ca, ca);
|
||||
builder.addExtension(Extension.keyUsage, true,
|
||||
new KeyUsage(KeyUsage.keyCertSign));
|
||||
builder.addExtension(Extension.basicConstraints, false,
|
||||
new BasicConstraints(true));
|
||||
builder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign));
|
||||
builder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true));
|
||||
|
||||
return signCert(builder, keyPair.getPrivate());
|
||||
}
|
||||
|
||||
public X509Certificate createCert(PublicKey publicKey, PrivateKey privateKey,
|
||||
String issuer, String subject) throws Exception {
|
||||
public X509Certificate createCert(PublicKey publicKey, PrivateKey privateKey, String issuer, String subject)
|
||||
throws Exception {
|
||||
JcaX509v3CertificateBuilder builder = certBuilder(publicKey, issuer, subject);
|
||||
builder.addExtension(Extension.keyUsage, true,
|
||||
new KeyUsage(KeyUsage.digitalSignature));
|
||||
builder.addExtension(Extension.basicConstraints, false,
|
||||
new BasicConstraints(false));
|
||||
builder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature));
|
||||
builder.addExtension(Extension.basicConstraints, false, new BasicConstraints(false));
|
||||
|
||||
GeneralName[] names = new GeneralName[] {
|
||||
new GeneralName(GeneralName.dNSName, "localhost") };
|
||||
builder.addExtension(Extension.subjectAlternativeName, false,
|
||||
GeneralNames.getInstance(new DERSequence(names)));
|
||||
GeneralName[] names = new GeneralName[] { new GeneralName(GeneralName.dNSName, "localhost") };
|
||||
builder.addExtension(Extension.subjectAlternativeName, false, GeneralNames.getInstance(new DERSequence(names)));
|
||||
|
||||
return signCert(builder, privateKey);
|
||||
}
|
||||
|
||||
private JcaX509v3CertificateBuilder certBuilder(PublicKey publicKey, String issuer,
|
||||
String subject) {
|
||||
private JcaX509v3CertificateBuilder certBuilder(PublicKey publicKey, String issuer, String subject) {
|
||||
X500Name issuerName = new X500Name(String.format("dc=%s", issuer));
|
||||
X500Name subjectName = new X500Name(String.format("dc=%s", subject));
|
||||
|
||||
@@ -110,14 +100,11 @@ public class KeyTool {
|
||||
Date notBefore = new Date(now - ONE_DAY);
|
||||
Date notAfter = new Date(now + TEN_YEARS);
|
||||
|
||||
return new JcaX509v3CertificateBuilder(issuerName, serialNum, notBefore, notAfter,
|
||||
subjectName, publicKey);
|
||||
return new JcaX509v3CertificateBuilder(issuerName, serialNum, notBefore, notAfter, subjectName, publicKey);
|
||||
}
|
||||
|
||||
private X509Certificate signCert(JcaX509v3CertificateBuilder builder,
|
||||
PrivateKey privateKey) throws Exception {
|
||||
ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSA")
|
||||
.build(privateKey);
|
||||
private X509Certificate signCert(JcaX509v3CertificateBuilder builder, PrivateKey privateKey) throws Exception {
|
||||
ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSA").build(privateKey);
|
||||
X509CertificateHolder holder = builder.build(signer);
|
||||
|
||||
return new JcaX509CertificateConverter().getCertificate(holder);
|
||||
|
||||
@@ -23,8 +23,7 @@ public class TlsConfigServerRunner extends AppRunner {
|
||||
public TlsConfigServerRunner(Class<?> appClass) {
|
||||
super(appClass);
|
||||
property("spring.profiles.active", "native");
|
||||
property("spring.cloud.config.server.native.search-locations",
|
||||
"classpath:/test/config");
|
||||
property("spring.cloud.config.server.native.search-locations", "classpath:/test/config");
|
||||
}
|
||||
|
||||
public void enableTls() {
|
||||
@@ -32,8 +31,7 @@ public class TlsConfigServerRunner extends AppRunner {
|
||||
property("server.ssl.client-auth", "need");
|
||||
}
|
||||
|
||||
public void setKeyStore(File keyStore, String keyStorePassword, String key,
|
||||
String keyPassword) {
|
||||
public void setKeyStore(File keyStore, String keyStorePassword, String key, String keyPassword) {
|
||||
property("server.ssl.key-store", pathOf(keyStore));
|
||||
property("server.ssl.key-store-type", "PKCS12");
|
||||
property("server.ssl.key-store-password", keyStorePassword);
|
||||
|
||||
@@ -71,8 +71,7 @@ public abstract class AbstractConfigDataLoader<L extends AbstractConfigDataLocat
|
||||
|
||||
@Override
|
||||
// TODO: retry
|
||||
public ConfigData load(ConfigDataLoaderContext context, L location)
|
||||
throws IOException {
|
||||
public ConfigData load(ConfigDataLoaderContext context, L location) throws IOException {
|
||||
ConfigClientProperties properties = location.getProperties();
|
||||
// ConfigClientProperties properties =
|
||||
// this.defaultProperties.override(environment);
|
||||
@@ -82,8 +81,7 @@ public abstract class AbstractConfigDataLoader<L extends AbstractConfigDataLocat
|
||||
try {
|
||||
String[] labels = new String[] { "" };
|
||||
if (StringUtils.hasText(properties.getLabel())) {
|
||||
labels = StringUtils
|
||||
.commaDelimitedListToStringArray(properties.getLabel());
|
||||
labels = StringUtils.commaDelimitedListToStringArray(properties.getLabel());
|
||||
}
|
||||
String state = ConfigClientStateHolder.getState();
|
||||
// Try all the labels until one works
|
||||
@@ -98,8 +96,8 @@ public abstract class AbstractConfigDataLoader<L extends AbstractConfigDataLocat
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> map = translateOrigins(source.getName(),
|
||||
(Map<String, Object>) source.getSource());
|
||||
composite.add(0, new OriginTrackedMapPropertySource(
|
||||
"configserver:" + source.getName(), map));
|
||||
composite.add(0,
|
||||
new OriginTrackedMapPropertySource("configserver:" + source.getName(), map));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,8 +118,7 @@ public abstract class AbstractConfigDataLoader<L extends AbstractConfigDataLocat
|
||||
}
|
||||
catch (HttpServerErrorException e) {
|
||||
error = e;
|
||||
if (MediaType.APPLICATION_JSON
|
||||
.includes(e.getResponseHeaders().getContentType())) {
|
||||
if (MediaType.APPLICATION_JSON.includes(e.getResponseHeaders().getContentType())) {
|
||||
errorBody = e.getResponseBodyAsString();
|
||||
}
|
||||
}
|
||||
@@ -136,23 +133,18 @@ public abstract class AbstractConfigDataLoader<L extends AbstractConfigDataLocat
|
||||
else {
|
||||
reason = "the location is not optional";
|
||||
}
|
||||
throw new IllegalStateException("Could not locate PropertySource and "
|
||||
+ reason + ", failing" + (errorBody == null ? "" : ": " + errorBody),
|
||||
error);
|
||||
throw new IllegalStateException("Could not locate PropertySource and " + reason + ", failing"
|
||||
+ (errorBody == null ? "" : ": " + errorBody), error);
|
||||
}
|
||||
logger.warn("Could not locate PropertySource: "
|
||||
+ (error != null ? error.getMessage() : errorBody));
|
||||
logger.warn("Could not locate PropertySource: " + (error != null ? error.getMessage() : errorBody));
|
||||
return null;
|
||||
|
||||
}
|
||||
|
||||
protected void log(Environment result) {
|
||||
if (logger.isInfoEnabled()) {
|
||||
logger.info(String.format(
|
||||
"Located environment: name=%s, profiles=%s, label=%s, version=%s, state=%s",
|
||||
result.getName(),
|
||||
result.getProfiles() == null ? ""
|
||||
: Arrays.asList(result.getProfiles()),
|
||||
logger.info(String.format("Located environment: name=%s, profiles=%s, label=%s, version=%s, state=%s",
|
||||
result.getName(), result.getProfiles() == null ? "" : Arrays.asList(result.getProfiles()),
|
||||
result.getLabel(), result.getVersion(), result.getState()));
|
||||
}
|
||||
if (logger.isDebugEnabled()) {
|
||||
@@ -162,17 +154,14 @@ public abstract class AbstractConfigDataLoader<L extends AbstractConfigDataLocat
|
||||
for (PropertySource propertySource : propertySourceList) {
|
||||
propertyCount += propertySource.getSource().size();
|
||||
}
|
||||
logger.debug(String.format(
|
||||
"Environment %s has %d property sources with %d properties.",
|
||||
result.getName(), result.getPropertySources().size(),
|
||||
propertyCount));
|
||||
logger.debug(String.format("Environment %s has %d property sources with %d properties.",
|
||||
result.getName(), result.getPropertySources().size(), propertyCount));
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
protected Map<String, Object> translateOrigins(String name,
|
||||
Map<String, Object> source) {
|
||||
protected Map<String, Object> translateOrigins(String name, Map<String, Object> source) {
|
||||
Map<String, Object> withOrigins = new LinkedHashMap<>();
|
||||
for (Map.Entry<String, Object> entry : source.entrySet()) {
|
||||
boolean hasOrigin = false;
|
||||
@@ -180,12 +169,10 @@ public abstract class AbstractConfigDataLoader<L extends AbstractConfigDataLocat
|
||||
if (entry.getValue() instanceof Map) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> value = (Map<String, Object>) entry.getValue();
|
||||
if (value.size() == 2 && value.containsKey("origin")
|
||||
&& value.containsKey("value")) {
|
||||
Origin origin = new ConfigServicePropertySourceLocator.ConfigServiceOrigin(
|
||||
name, value.get("origin"));
|
||||
OriginTrackedValue trackedValue = OriginTrackedValue
|
||||
.of(value.get("value"), origin);
|
||||
if (value.size() == 2 && value.containsKey("origin") && value.containsKey("value")) {
|
||||
Origin origin = new ConfigServicePropertySourceLocator.ConfigServiceOrigin(name,
|
||||
value.get("origin"));
|
||||
OriginTrackedValue trackedValue = OriginTrackedValue.of(value.get("value"), origin);
|
||||
withOrigins.put(entry.getKey(), trackedValue);
|
||||
hasOrigin = true;
|
||||
}
|
||||
@@ -210,8 +197,7 @@ public abstract class AbstractConfigDataLoader<L extends AbstractConfigDataLocat
|
||||
|
||||
String path = "/{name}/{profile}";
|
||||
String name = properties.getName();
|
||||
String profile = StringUtils
|
||||
.collectionToCommaDelimitedString(location.getProfiles().getAccepted());
|
||||
String profile = StringUtils.collectionToCommaDelimitedString(location.getProfiles().getAccepted());
|
||||
String token = properties.getToken();
|
||||
int noOfUrls = properties.getUri().length;
|
||||
if (noOfUrls > 1) {
|
||||
@@ -237,8 +223,7 @@ public abstract class AbstractConfigDataLoader<L extends AbstractConfigDataLocat
|
||||
|
||||
try {
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setAccept(
|
||||
Collections.singletonList(MediaType.parseMediaType(V2_JSON)));
|
||||
headers.setAccept(Collections.singletonList(MediaType.parseMediaType(V2_JSON)));
|
||||
addAuthorizationToken(properties, headers, username, password);
|
||||
if (StringUtils.hasText(token)) {
|
||||
headers.add(TOKEN_HEADER, token);
|
||||
@@ -248,8 +233,7 @@ public abstract class AbstractConfigDataLoader<L extends AbstractConfigDataLocat
|
||||
}
|
||||
|
||||
final HttpEntity<Void> entity = new HttpEntity<>((Void) null, headers);
|
||||
response = restTemplate.exchange(uri + path, HttpMethod.GET, entity,
|
||||
Environment.class, args);
|
||||
response = restTemplate.exchange(uri + path, HttpMethod.GET, entity, Environment.class, args);
|
||||
}
|
||||
catch (HttpClientErrorException e) {
|
||||
if (e.getStatusCode() != HttpStatus.NOT_FOUND) {
|
||||
@@ -257,8 +241,7 @@ public abstract class AbstractConfigDataLoader<L extends AbstractConfigDataLocat
|
||||
}
|
||||
}
|
||||
catch (ResourceAccessException e) {
|
||||
logger.info("Connect Timeout Exception on Url - " + uri
|
||||
+ ". Will be trying the next url if available");
|
||||
logger.info("Connect Timeout Exception on Url - " + uri + ". Will be trying the next url if available");
|
||||
if (i == noOfUrls - 1) {
|
||||
throw e;
|
||||
}
|
||||
@@ -278,13 +261,12 @@ public abstract class AbstractConfigDataLoader<L extends AbstractConfigDataLocat
|
||||
return null;
|
||||
}
|
||||
|
||||
protected void addAuthorizationToken(ConfigClientProperties configClientProperties,
|
||||
HttpHeaders httpHeaders, String username, String password) {
|
||||
protected void addAuthorizationToken(ConfigClientProperties configClientProperties, HttpHeaders httpHeaders,
|
||||
String username, String password) {
|
||||
String authorization = configClientProperties.getHeaders().get(AUTHORIZATION);
|
||||
|
||||
if (password != null && authorization != null) {
|
||||
throw new IllegalStateException(
|
||||
"You must set either 'password' or 'authorization'");
|
||||
throw new IllegalStateException("You must set either 'password' or 'authorization'");
|
||||
}
|
||||
|
||||
if (password != null) {
|
||||
|
||||
@@ -33,8 +33,8 @@ public abstract class AbstractConfigDataLocation extends ConfigDataLocation {
|
||||
|
||||
private final Profiles profiles;
|
||||
|
||||
public AbstractConfigDataLocation(RestTemplate restTemplate,
|
||||
ConfigClientProperties properties, boolean optional, Profiles profiles) {
|
||||
public AbstractConfigDataLocation(RestTemplate restTemplate, ConfigClientProperties properties, boolean optional,
|
||||
Profiles profiles) {
|
||||
this.restTemplate = restTemplate;
|
||||
this.properties = properties;
|
||||
this.optional = optional;
|
||||
@@ -66,23 +66,19 @@ public abstract class AbstractConfigDataLocation extends ConfigDataLocation {
|
||||
return false;
|
||||
}
|
||||
AbstractConfigDataLocation that = (AbstractConfigDataLocation) o;
|
||||
return Objects.equals(this.restTemplate, that.restTemplate)
|
||||
&& Objects.equals(this.properties, that.properties)
|
||||
&& Objects.equals(this.optional, that.optional)
|
||||
&& Objects.equals(this.profiles, that.profiles);
|
||||
return Objects.equals(this.restTemplate, that.restTemplate) && Objects.equals(this.properties, that.properties)
|
||||
&& Objects.equals(this.optional, that.optional) && Objects.equals(this.profiles, that.profiles);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(this.restTemplate, this.properties, this.optional,
|
||||
this.profiles);
|
||||
return Objects.hash(this.restTemplate, this.properties, this.optional, this.profiles);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return new ToStringCreator(this).append("uris", properties.getUri())
|
||||
.append("optional", optional).append("profiles", profiles.getAccepted())
|
||||
.toString();
|
||||
return new ToStringCreator(this).append("uris", properties.getUri()).append("optional", optional)
|
||||
.append("profiles", profiles.getAccepted()).toString();
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -57,11 +57,9 @@ public abstract class AbstractConfigDataLocationResolver<L extends AbstractConfi
|
||||
|
||||
protected ConfigClientProperties loadProperties(Binder binder) {
|
||||
ConfigClientProperties configClientProperties = binder
|
||||
.bind(ConfigClientProperties.PREFIX,
|
||||
Bindable.of(ConfigClientProperties.class))
|
||||
.bind(ConfigClientProperties.PREFIX, Bindable.of(ConfigClientProperties.class))
|
||||
.orElse(new ConfigClientProperties());
|
||||
String applicationName = binder.bind("spring.application.name", String.class)
|
||||
.orElse("application");
|
||||
String applicationName = binder.bind("spring.application.name", String.class).orElse("application");
|
||||
configClientProperties.setName(applicationName);
|
||||
return configClientProperties;
|
||||
}
|
||||
@@ -82,9 +80,8 @@ public abstract class AbstractConfigDataLocationResolver<L extends AbstractConfi
|
||||
headers.remove(AUTHORIZATION); // To avoid redundant addition of header
|
||||
}
|
||||
if (!headers.isEmpty()) {
|
||||
template.setInterceptors(Collections.singletonList(
|
||||
new ConfigServicePropertySourceLocator.GenericRequestHeaderInterceptor(
|
||||
headers)));
|
||||
template.setInterceptors(Collections
|
||||
.singletonList(new ConfigServicePropertySourceLocator.GenericRequestHeaderInterceptor(headers)));
|
||||
}
|
||||
|
||||
return template;
|
||||
@@ -94,32 +91,27 @@ public abstract class AbstractConfigDataLocationResolver<L extends AbstractConfi
|
||||
return this.log;
|
||||
}
|
||||
|
||||
public boolean isResolvable(ConfigDataLocationResolverContext context,
|
||||
String location) {
|
||||
public boolean isResolvable(ConfigDataLocationResolverContext context, String location) {
|
||||
if (!location.startsWith(getPrefix())) {
|
||||
return false;
|
||||
}
|
||||
return context.getBinder()
|
||||
.bind(ConfigClientProperties.PREFIX + ".enabled", Boolean.class)
|
||||
.orElse(true);
|
||||
return context.getBinder().bind(ConfigClientProperties.PREFIX + ".enabled", Boolean.class).orElse(true);
|
||||
}
|
||||
|
||||
protected String getPrefix() {
|
||||
return PREFIX;
|
||||
}
|
||||
|
||||
public List<L> resolve(ConfigDataLocationResolverContext context, String location,
|
||||
boolean optional) {
|
||||
public List<L> resolve(ConfigDataLocationResolverContext context, String location, boolean optional) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
public List<L> resolveProfileSpecific(ConfigDataLocationResolverContext context,
|
||||
String location, boolean optional, Profiles profiles) {
|
||||
public List<L> resolveProfileSpecific(ConfigDataLocationResolverContext context, String location, boolean optional,
|
||||
Profiles profiles) {
|
||||
|
||||
ConfigClientProperties properties = loadProperties(context.getBinder());
|
||||
|
||||
String uris = (location.startsWith(getPrefix()))
|
||||
? location.substring(getPrefix().length()) : location;
|
||||
String uris = (location.startsWith(getPrefix())) ? location.substring(getPrefix().length()) : location;
|
||||
|
||||
if (StringUtils.hasText(uris)) {
|
||||
String[] uri = StringUtils.commaDelimitedListToStringArray(uris);
|
||||
@@ -129,8 +121,7 @@ public abstract class AbstractConfigDataLocationResolver<L extends AbstractConfi
|
||||
RestTemplate restTemplate = createRestTemplate(properties);
|
||||
|
||||
List<L> locations = new ArrayList<>();
|
||||
locations.add(
|
||||
createConfigDataLocation(optional, profiles, properties, restTemplate));
|
||||
locations.add(createConfigDataLocation(optional, profiles, properties, restTemplate));
|
||||
|
||||
return locations;
|
||||
}
|
||||
|
||||
@@ -43,13 +43,10 @@ import org.springframework.core.env.Environment;
|
||||
public class ConfigClientAutoConfiguration {
|
||||
|
||||
@Bean
|
||||
public ConfigClientProperties configClientProperties(Environment environment,
|
||||
ApplicationContext context) {
|
||||
if (context.getParent() != null
|
||||
&& BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
|
||||
context.getParent(), ConfigClientProperties.class).length > 0) {
|
||||
return BeanFactoryUtils.beanOfTypeIncludingAncestors(context.getParent(),
|
||||
ConfigClientProperties.class);
|
||||
public ConfigClientProperties configClientProperties(Environment environment, ApplicationContext context) {
|
||||
if (context.getParent() != null && BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context.getParent(),
|
||||
ConfigClientProperties.class).length > 0) {
|
||||
return BeanFactoryUtils.beanOfTypeIncludingAncestors(context.getParent(), ConfigClientProperties.class);
|
||||
}
|
||||
ConfigClientProperties client = new ConfigClientProperties(environment);
|
||||
return client;
|
||||
@@ -66,8 +63,7 @@ public class ConfigClientAutoConfiguration {
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ConfigServerHealthIndicator clientConfigServerHealthIndicator(
|
||||
ConfigClientHealthProperties properties,
|
||||
public ConfigServerHealthIndicator clientConfigServerHealthIndicator(ConfigClientHealthProperties properties,
|
||||
ConfigurableEnvironment environment) {
|
||||
return new ConfigServerHealthIndicator(environment, properties);
|
||||
}
|
||||
|
||||
@@ -295,8 +295,7 @@ public class ConfigClientProperties {
|
||||
if (StringUtils.isEmpty(userInfo) || ":".equals(userInfo)) {
|
||||
return result;
|
||||
}
|
||||
String bare = UriComponentsBuilder.fromHttpUrl(uri).userInfo(null).build()
|
||||
.toUriString();
|
||||
String bare = UriComponentsBuilder.fromHttpUrl(uri).userInfo(null).build().toUriString();
|
||||
result.uri = bare;
|
||||
|
||||
// if userInfo does not contain a :, then append a : to it
|
||||
@@ -342,34 +341,28 @@ public class ConfigClientProperties {
|
||||
return credentials;
|
||||
}
|
||||
|
||||
public ConfigClientProperties override(
|
||||
org.springframework.core.env.Environment environment) {
|
||||
public ConfigClientProperties override(org.springframework.core.env.Environment environment) {
|
||||
ConfigClientProperties override = new ConfigClientProperties();
|
||||
BeanUtils.copyProperties(this, override);
|
||||
override.setName(
|
||||
environment.resolvePlaceholders("${" + ConfigClientProperties.PREFIX
|
||||
+ ".name:${spring.application.name:application}}"));
|
||||
override.setName(environment.resolvePlaceholders(
|
||||
"${" + ConfigClientProperties.PREFIX + ".name:${spring.application.name:application}}"));
|
||||
if (environment.containsProperty(ConfigClientProperties.PREFIX + ".profile")) {
|
||||
override.setProfile(
|
||||
environment.getProperty(ConfigClientProperties.PREFIX + ".profile"));
|
||||
override.setProfile(environment.getProperty(ConfigClientProperties.PREFIX + ".profile"));
|
||||
}
|
||||
if (environment.containsProperty(ConfigClientProperties.PREFIX + ".label")) {
|
||||
override.setLabel(
|
||||
environment.getProperty(ConfigClientProperties.PREFIX + ".label"));
|
||||
override.setLabel(environment.getProperty(ConfigClientProperties.PREFIX + ".label"));
|
||||
}
|
||||
return override;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ConfigClientProperties [enabled=" + this.enabled + ", profile="
|
||||
+ this.profile + ", name=" + this.name + ", label=" + this.label
|
||||
+ ", username=" + this.username + ", password=" + this.password + ", uri="
|
||||
+ Arrays.toString(this.uri) + ", discovery=" + this.discovery
|
||||
+ ", failFast=" + this.failFast + ", token=" + this.token
|
||||
+ ", requestConnectTimeout=" + this.requestConnectTimeout
|
||||
+ ", requestReadTimeout=" + this.requestReadTimeout + ", sendState="
|
||||
+ this.sendState + ", headers=" + this.headers + "]";
|
||||
return "ConfigClientProperties [enabled=" + this.enabled + ", profile=" + this.profile + ", name=" + this.name
|
||||
+ ", label=" + this.label + ", username=" + this.username + ", password=" + this.password + ", uri="
|
||||
+ Arrays.toString(this.uri) + ", discovery=" + this.discovery + ", failFast=" + this.failFast
|
||||
+ ", token=" + this.token + ", requestConnectTimeout=" + this.requestConnectTimeout
|
||||
+ ", requestReadTimeout=" + this.requestReadTimeout + ", sendState=" + this.sendState + ", headers="
|
||||
+ this.headers + "]";
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -74,8 +74,7 @@ public class ConfigClientWatch implements Closeable, EnvironmentAware {
|
||||
}
|
||||
|
||||
/* for testing */ boolean stateChanged(String oldState, String newState) {
|
||||
return (!hasText(oldState) && hasText(newState))
|
||||
|| (hasText(oldState) && !oldState.equals(newState));
|
||||
return (!hasText(oldState) && hasText(newState)) || (hasText(oldState) && !oldState.equals(newState));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -18,8 +18,7 @@ package org.springframework.cloud.config.client;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
|
||||
public class ConfigServerConfigDataLoader
|
||||
extends AbstractConfigDataLoader<ConfigServerConfigDataLocation> {
|
||||
public class ConfigServerConfigDataLoader extends AbstractConfigDataLoader<ConfigServerConfigDataLocation> {
|
||||
|
||||
public ConfigServerConfigDataLoader(Log logger) {
|
||||
super(logger);
|
||||
|
||||
@@ -21,8 +21,8 @@ import org.springframework.web.client.RestTemplate;
|
||||
|
||||
public class ConfigServerConfigDataLocation extends AbstractConfigDataLocation {
|
||||
|
||||
public ConfigServerConfigDataLocation(RestTemplate restTemplate,
|
||||
ConfigClientProperties properties, boolean optional, Profiles profiles) {
|
||||
public ConfigServerConfigDataLocation(RestTemplate restTemplate, ConfigClientProperties properties,
|
||||
boolean optional, Profiles profiles) {
|
||||
super(restTemplate, properties, optional, profiles);
|
||||
}
|
||||
|
||||
|
||||
@@ -31,11 +31,9 @@ public class ConfigServerConfigDataLocationResolver
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ConfigServerConfigDataLocation createConfigDataLocation(boolean optional,
|
||||
Profiles profiles, ConfigClientProperties properties,
|
||||
RestTemplate restTemplate) {
|
||||
return new ConfigServerConfigDataLocation(restTemplate, properties, optional,
|
||||
profiles);
|
||||
protected ConfigServerConfigDataLocation createConfigDataLocation(boolean optional, Profiles profiles,
|
||||
ConfigClientProperties properties, RestTemplate restTemplate) {
|
||||
return new ConfigServerConfigDataLocation(restTemplate, properties, optional, profiles);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -40,8 +40,7 @@ public class ConfigServerHealthIndicator extends AbstractHealthIndicator {
|
||||
|
||||
private PropertySource<?> cached;
|
||||
|
||||
public ConfigServerHealthIndicator(ConfigurableEnvironment environment,
|
||||
ConfigClientHealthProperties properties) {
|
||||
public ConfigServerHealthIndicator(ConfigurableEnvironment environment, ConfigClientHealthProperties properties) {
|
||||
this.environment = environment;
|
||||
this.properties = properties;
|
||||
}
|
||||
@@ -52,8 +51,7 @@ public class ConfigServerHealthIndicator extends AbstractHealthIndicator {
|
||||
builder.up();
|
||||
if (propertySource instanceof CompositePropertySource) {
|
||||
List<String> sources = new ArrayList<>();
|
||||
for (PropertySource<?> ps : ((CompositePropertySource) propertySource)
|
||||
.getPropertySources()) {
|
||||
for (PropertySource<?> ps : ((CompositePropertySource) propertySource).getPropertySources()) {
|
||||
sources.add(ps.getName());
|
||||
}
|
||||
builder.withDetail("propertySources", sources);
|
||||
@@ -70,8 +68,7 @@ public class ConfigServerHealthIndicator extends AbstractHealthIndicator {
|
||||
long accessTime = System.currentTimeMillis();
|
||||
if (isCacheStale(accessTime)) {
|
||||
this.lastAccess = accessTime;
|
||||
MutablePropertySources propertySources = this.environment
|
||||
.getPropertySources();
|
||||
MutablePropertySources propertySources = this.environment.getPropertySources();
|
||||
this.cached = propertySources.get("configClient");
|
||||
}
|
||||
return this.cached;
|
||||
@@ -81,8 +78,7 @@ public class ConfigServerHealthIndicator extends AbstractHealthIndicator {
|
||||
if (this.cached == null) {
|
||||
return true;
|
||||
}
|
||||
return (accessTime - this.lastAccess) >= this.properties.getTimeToLive()
|
||||
.toMillis();
|
||||
return (accessTime - this.lastAccess) >= this.properties.getTimeToLive().toMillis();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -49,11 +49,10 @@ public class ConfigServerInstanceProvider {
|
||||
logger.debug("Locating configserver (" + serviceId + ") via discovery");
|
||||
List<ServiceInstance> instances = this.function.apply(serviceId);
|
||||
if (instances.isEmpty()) {
|
||||
throw new IllegalStateException(
|
||||
"No instances found of configserver (" + serviceId + ")");
|
||||
throw new IllegalStateException("No instances found of configserver (" + serviceId + ")");
|
||||
}
|
||||
logger.debug("Located configserver (" + serviceId
|
||||
+ ") via discovery. No of instances found: " + instances.size());
|
||||
logger.debug(
|
||||
"Located configserver (" + serviceId + ") via discovery. No of instances found: " + instances.size());
|
||||
return instances;
|
||||
}
|
||||
|
||||
|
||||
@@ -53,12 +53,9 @@ public class ConfigServiceBootstrapConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(ConfigServicePropertySourceLocator.class)
|
||||
@ConditionalOnProperty(name = ConfigClientProperties.PREFIX + ".enabled",
|
||||
matchIfMissing = true)
|
||||
public ConfigServicePropertySourceLocator configServicePropertySource(
|
||||
ConfigClientProperties properties) {
|
||||
ConfigServicePropertySourceLocator locator = new ConfigServicePropertySourceLocator(
|
||||
properties);
|
||||
@ConditionalOnProperty(name = ConfigClientProperties.PREFIX + ".enabled", matchIfMissing = true)
|
||||
public ConfigServicePropertySourceLocator configServicePropertySource(ConfigClientProperties properties) {
|
||||
ConfigServicePropertySourceLocator locator = new ConfigServicePropertySourceLocator(properties);
|
||||
return locator;
|
||||
}
|
||||
|
||||
@@ -72,12 +69,10 @@ public class ConfigServiceBootstrapConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(name = "configServerRetryInterceptor")
|
||||
public RetryOperationsInterceptor configServerRetryInterceptor(
|
||||
RetryProperties properties) {
|
||||
return RetryInterceptorBuilder.stateless()
|
||||
.backOffOptions(properties.getInitialInterval(),
|
||||
properties.getMultiplier(), properties.getMaxInterval())
|
||||
.maxAttempts(properties.getMaxAttempts()).build();
|
||||
public RetryOperationsInterceptor configServerRetryInterceptor(RetryProperties properties) {
|
||||
return RetryInterceptorBuilder.stateless().backOffOptions(properties.getInitialInterval(),
|
||||
properties.getMultiplier(), properties.getMaxInterval()).maxAttempts(properties.getMaxAttempts())
|
||||
.build();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -81,8 +81,7 @@ import static org.springframework.cloud.config.environment.EnvironmentMediaType.
|
||||
@Order(0)
|
||||
public class ConfigServicePropertySourceLocator implements PropertySourceLocator {
|
||||
|
||||
private static Log logger = LogFactory
|
||||
.getLog(ConfigServicePropertySourceLocator.class);
|
||||
private static Log logger = LogFactory.getLog(ConfigServicePropertySourceLocator.class);
|
||||
|
||||
private RestTemplate restTemplate;
|
||||
|
||||
@@ -94,26 +93,21 @@ public class ConfigServicePropertySourceLocator implements PropertySourceLocator
|
||||
|
||||
@Override
|
||||
@Retryable(interceptor = "configServerRetryInterceptor")
|
||||
public org.springframework.core.env.PropertySource<?> locate(
|
||||
org.springframework.core.env.Environment environment) {
|
||||
public org.springframework.core.env.PropertySource<?> locate(org.springframework.core.env.Environment environment) {
|
||||
ConfigClientProperties properties = this.defaultProperties.override(environment);
|
||||
CompositePropertySource composite = new OriginTrackedCompositePropertySource(
|
||||
"configService");
|
||||
RestTemplate restTemplate = this.restTemplate == null
|
||||
? getSecureRestTemplate(properties) : this.restTemplate;
|
||||
CompositePropertySource composite = new OriginTrackedCompositePropertySource("configService");
|
||||
RestTemplate restTemplate = this.restTemplate == null ? getSecureRestTemplate(properties) : this.restTemplate;
|
||||
Exception error = null;
|
||||
String errorBody = null;
|
||||
try {
|
||||
String[] labels = new String[] { "" };
|
||||
if (StringUtils.hasText(properties.getLabel())) {
|
||||
labels = StringUtils
|
||||
.commaDelimitedListToStringArray(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(restTemplate, properties,
|
||||
label.trim(), state);
|
||||
Environment result = getRemoteEnvironment(restTemplate, properties, label.trim(), state);
|
||||
if (result != null) {
|
||||
log(result);
|
||||
|
||||
@@ -123,9 +117,7 @@ public class ConfigServicePropertySourceLocator implements PropertySourceLocator
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> map = translateOrigins(source.getName(),
|
||||
(Map<String, Object>) source.getSource());
|
||||
composite.addPropertySource(
|
||||
new OriginTrackedMapPropertySource(source.getName(),
|
||||
map));
|
||||
composite.addPropertySource(new OriginTrackedMapPropertySource(source.getName(), map));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -138,8 +130,7 @@ public class ConfigServicePropertySourceLocator implements PropertySourceLocator
|
||||
}
|
||||
// the existence of this property source confirms a successful
|
||||
// response from config server
|
||||
composite.addFirstPropertySource(
|
||||
new MapPropertySource("configClient", map));
|
||||
composite.addFirstPropertySource(new MapPropertySource("configClient", map));
|
||||
return composite;
|
||||
}
|
||||
}
|
||||
@@ -147,8 +138,7 @@ public class ConfigServicePropertySourceLocator implements PropertySourceLocator
|
||||
}
|
||||
catch (HttpServerErrorException e) {
|
||||
error = e;
|
||||
if (MediaType.APPLICATION_JSON
|
||||
.includes(e.getResponseHeaders().getContentType())) {
|
||||
if (MediaType.APPLICATION_JSON.includes(e.getResponseHeaders().getContentType())) {
|
||||
errorBody = e.getResponseBodyAsString();
|
||||
}
|
||||
}
|
||||
@@ -156,13 +146,10 @@ public class ConfigServicePropertySourceLocator implements PropertySourceLocator
|
||||
error = e;
|
||||
}
|
||||
if (properties.isFailFast()) {
|
||||
throw new IllegalStateException(
|
||||
"Could not locate PropertySource and the fail fast property is set, failing"
|
||||
+ (errorBody == null ? "" : ": " + errorBody),
|
||||
error);
|
||||
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));
|
||||
logger.warn("Could not locate PropertySource: " + (error != null ? error.getMessage() : errorBody));
|
||||
return null;
|
||||
|
||||
}
|
||||
@@ -176,11 +163,8 @@ public class ConfigServicePropertySourceLocator implements PropertySourceLocator
|
||||
|
||||
private void log(Environment result) {
|
||||
if (logger.isInfoEnabled()) {
|
||||
logger.info(String.format(
|
||||
"Located environment: name=%s, profiles=%s, label=%s, version=%s, state=%s",
|
||||
result.getName(),
|
||||
result.getProfiles() == null ? ""
|
||||
: Arrays.asList(result.getProfiles()),
|
||||
logger.info(String.format("Located environment: name=%s, profiles=%s, label=%s, version=%s, state=%s",
|
||||
result.getName(), result.getProfiles() == null ? "" : Arrays.asList(result.getProfiles()),
|
||||
result.getLabel(), result.getVersion(), result.getState()));
|
||||
}
|
||||
if (logger.isDebugEnabled()) {
|
||||
@@ -190,17 +174,14 @@ public class ConfigServicePropertySourceLocator implements PropertySourceLocator
|
||||
for (PropertySource propertySource : propertySourceList) {
|
||||
propertyCount += propertySource.getSource().size();
|
||||
}
|
||||
logger.debug(String.format(
|
||||
"Environment %s has %d property sources with %d properties.",
|
||||
result.getName(), result.getPropertySources().size(),
|
||||
propertyCount));
|
||||
logger.debug(String.format("Environment %s has %d property sources with %d properties.",
|
||||
result.getName(), result.getPropertySources().size(), propertyCount));
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, Object> translateOrigins(String name,
|
||||
Map<String, Object> source) {
|
||||
private Map<String, Object> translateOrigins(String name, Map<String, Object> source) {
|
||||
Map<String, Object> withOrigins = new LinkedHashMap<>();
|
||||
for (Map.Entry<String, Object> entry : source.entrySet()) {
|
||||
boolean hasOrigin = false;
|
||||
@@ -208,11 +189,9 @@ public class ConfigServicePropertySourceLocator implements PropertySourceLocator
|
||||
if (entry.getValue() instanceof Map) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> value = (Map<String, Object>) entry.getValue();
|
||||
if (value.size() == 2 && value.containsKey("origin")
|
||||
&& value.containsKey("value")) {
|
||||
if (value.size() == 2 && value.containsKey("origin") && value.containsKey("value")) {
|
||||
Origin origin = new ConfigServiceOrigin(name, value.get("origin"));
|
||||
OriginTrackedValue trackedValue = OriginTrackedValue
|
||||
.of(value.get("value"), origin);
|
||||
OriginTrackedValue trackedValue = OriginTrackedValue.of(value.get("value"), origin);
|
||||
withOrigins.put(entry.getKey(), trackedValue);
|
||||
hasOrigin = true;
|
||||
}
|
||||
@@ -231,8 +210,8 @@ public class ConfigServicePropertySourceLocator implements PropertySourceLocator
|
||||
}
|
||||
}
|
||||
|
||||
private Environment getRemoteEnvironment(RestTemplate restTemplate,
|
||||
ConfigClientProperties properties, String label, String state) {
|
||||
private Environment getRemoteEnvironment(RestTemplate restTemplate, ConfigClientProperties properties, String label,
|
||||
String state) {
|
||||
String path = "/{name}/{profile}";
|
||||
String name = properties.getName();
|
||||
String profile = properties.getProfile();
|
||||
@@ -261,8 +240,7 @@ public class ConfigServicePropertySourceLocator implements PropertySourceLocator
|
||||
|
||||
try {
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setAccept(
|
||||
Collections.singletonList(MediaType.parseMediaType(V2_JSON)));
|
||||
headers.setAccept(Collections.singletonList(MediaType.parseMediaType(V2_JSON)));
|
||||
addAuthorizationToken(properties, headers, username, password);
|
||||
if (StringUtils.hasText(token)) {
|
||||
headers.add(TOKEN_HEADER, token);
|
||||
@@ -272,8 +250,7 @@ public class ConfigServicePropertySourceLocator implements PropertySourceLocator
|
||||
}
|
||||
|
||||
final HttpEntity<Void> entity = new HttpEntity<>((Void) null, headers);
|
||||
response = restTemplate.exchange(uri + path, HttpMethod.GET, entity,
|
||||
Environment.class, args);
|
||||
response = restTemplate.exchange(uri + path, HttpMethod.GET, entity, Environment.class, args);
|
||||
}
|
||||
catch (HttpClientErrorException e) {
|
||||
if (e.getStatusCode() != HttpStatus.NOT_FOUND) {
|
||||
@@ -281,8 +258,7 @@ public class ConfigServicePropertySourceLocator implements PropertySourceLocator
|
||||
}
|
||||
}
|
||||
catch (ResourceAccessException e) {
|
||||
logger.info("Connect Timeout Exception on Url - " + uri
|
||||
+ ". Will be trying the next url if available");
|
||||
logger.info("Connect Timeout Exception on Url - " + uri + ". Will be trying the next url if available");
|
||||
if (i == noOfUrls - 1) {
|
||||
throw e;
|
||||
}
|
||||
@@ -321,23 +297,20 @@ public class ConfigServicePropertySourceLocator implements PropertySourceLocator
|
||||
headers.remove(AUTHORIZATION); // To avoid redundant addition of header
|
||||
}
|
||||
if (!headers.isEmpty()) {
|
||||
template.setInterceptors(Arrays.<ClientHttpRequestInterceptor>asList(
|
||||
new GenericRequestHeaderInterceptor(headers)));
|
||||
template.setInterceptors(
|
||||
Arrays.<ClientHttpRequestInterceptor>asList(new GenericRequestHeaderInterceptor(headers)));
|
||||
}
|
||||
|
||||
return template;
|
||||
}
|
||||
|
||||
private ClientHttpRequestFactory createHttpRquestFactory(
|
||||
ConfigClientProperties client) {
|
||||
private ClientHttpRequestFactory createHttpRquestFactory(ConfigClientProperties client) {
|
||||
if (client.getTls().isEnabled()) {
|
||||
try {
|
||||
SSLContextFactory factory = new SSLContextFactory(client.getTls());
|
||||
SSLContext sslContext = factory.createSSLContext();
|
||||
HttpClient httpClient = HttpClients.custom().setSSLContext(sslContext)
|
||||
.build();
|
||||
HttpComponentsClientHttpRequestFactory result = new HttpComponentsClientHttpRequestFactory(
|
||||
httpClient);
|
||||
HttpClient httpClient = HttpClients.custom().setSSLContext(sslContext).build();
|
||||
HttpComponentsClientHttpRequestFactory result = new HttpComponentsClientHttpRequestFactory(httpClient);
|
||||
|
||||
result.setReadTimeout(client.getRequestReadTimeout());
|
||||
result.setConnectTimeout(client.getRequestConnectTimeout());
|
||||
@@ -346,8 +319,7 @@ public class ConfigServicePropertySourceLocator implements PropertySourceLocator
|
||||
}
|
||||
catch (GeneralSecurityException | IOException ex) {
|
||||
logger.error(ex);
|
||||
throw new IllegalStateException(
|
||||
"Failed to create config client with TLS.", ex);
|
||||
throw new IllegalStateException("Failed to create config client with TLS.", ex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -357,13 +329,12 @@ public class ConfigServicePropertySourceLocator implements PropertySourceLocator
|
||||
return result;
|
||||
}
|
||||
|
||||
private void addAuthorizationToken(ConfigClientProperties configClientProperties,
|
||||
HttpHeaders httpHeaders, String username, String password) {
|
||||
private void addAuthorizationToken(ConfigClientProperties configClientProperties, HttpHeaders httpHeaders,
|
||||
String username, String password) {
|
||||
String authorization = configClientProperties.getHeaders().get(AUTHORIZATION);
|
||||
|
||||
if (password != null && authorization != null) {
|
||||
throw new IllegalStateException(
|
||||
"You must set either 'password' or 'authorization'");
|
||||
throw new IllegalStateException("You must set either 'password' or 'authorization'");
|
||||
}
|
||||
|
||||
if (password != null) {
|
||||
@@ -379,8 +350,7 @@ public class ConfigServicePropertySourceLocator implements PropertySourceLocator
|
||||
/**
|
||||
* Adds the provided headers to the request.
|
||||
*/
|
||||
public static class GenericRequestHeaderInterceptor
|
||||
implements ClientHttpRequestInterceptor {
|
||||
public static class GenericRequestHeaderInterceptor implements ClientHttpRequestInterceptor {
|
||||
|
||||
private final Map<String, String> headers;
|
||||
|
||||
@@ -389,8 +359,8 @@ public class ConfigServicePropertySourceLocator implements PropertySourceLocator
|
||||
}
|
||||
|
||||
@Override
|
||||
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
|
||||
ClientHttpRequestExecution execution) throws IOException {
|
||||
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
|
||||
throws IOException {
|
||||
for (Entry<String, String> header : this.headers.entrySet()) {
|
||||
request.getHeaders().add(header.getKey(), header.getValue());
|
||||
}
|
||||
@@ -418,8 +388,7 @@ public class ConfigServicePropertySourceLocator implements PropertySourceLocator
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Config Server " + this.remotePropertySource + ":"
|
||||
+ this.origin.toString();
|
||||
return "Config Server " + this.remotePropertySource + ":" + this.origin.toString();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -43,15 +43,13 @@ import org.springframework.context.event.SmartApplicationListener;
|
||||
*
|
||||
* @author Dave Syer
|
||||
*/
|
||||
@ConditionalOnProperty(value = "spring.cloud.config.discovery.enabled",
|
||||
matchIfMissing = false)
|
||||
@ConditionalOnProperty(value = "spring.cloud.config.discovery.enabled", matchIfMissing = false)
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@Import({ UtilAutoConfiguration.class })
|
||||
@EnableDiscoveryClient
|
||||
public class DiscoveryClientConfigServiceBootstrapConfiguration {
|
||||
|
||||
private static Log logger = LogFactory
|
||||
.getLog(DiscoveryClientConfigServiceBootstrapConfiguration.class);
|
||||
private static Log logger = LogFactory.getLog(DiscoveryClientConfigServiceBootstrapConfiguration.class);
|
||||
|
||||
@Bean
|
||||
public ConfigServerInstanceProvider configServerInstanceProvider(
|
||||
@@ -63,8 +61,7 @@ public class DiscoveryClientConfigServiceBootstrapConfiguration {
|
||||
}
|
||||
DiscoveryClient client = discoveryClient.getIfAvailable();
|
||||
if (client == null) {
|
||||
throw new IllegalStateException(
|
||||
"ConfigServerInstanceProvider reqiures a DiscoveryClient or Function");
|
||||
throw new IllegalStateException("ConfigServerInstanceProvider reqiures a DiscoveryClient or Function");
|
||||
}
|
||||
return new ConfigServerInstanceProvider(client);
|
||||
}
|
||||
@@ -83,8 +80,7 @@ public class DiscoveryClientConfigServiceBootstrapConfiguration {
|
||||
|
||||
private final HeartbeatMonitor monitor = new HeartbeatMonitor();
|
||||
|
||||
private HeartbeatListener(ConfigClientProperties config,
|
||||
ConfigServerInstanceProvider instanceProvider) {
|
||||
private HeartbeatListener(ConfigClientProperties config, ConfigServerInstanceProvider instanceProvider) {
|
||||
this.config = config;
|
||||
this.instanceProvider = instanceProvider;
|
||||
}
|
||||
@@ -119,8 +115,7 @@ public class DiscoveryClientConfigServiceBootstrapConfiguration {
|
||||
try {
|
||||
String serviceId = this.config.getDiscovery().getServiceId();
|
||||
List<String> listOfUrls = new ArrayList<>();
|
||||
List<ServiceInstance> serviceInstances = this.instanceProvider
|
||||
.getConfigServerInstances(serviceId);
|
||||
List<ServiceInstance> serviceInstances = this.instanceProvider.getConfigServerInstances(serviceId);
|
||||
|
||||
for (int i = 0; i < serviceInstances.size(); i++) {
|
||||
|
||||
|
||||
@@ -60,13 +60,11 @@ public class Environment {
|
||||
* @param env Spring Environment
|
||||
*/
|
||||
public Environment(Environment env) {
|
||||
this(env.getName(), env.getProfiles(), env.getLabel(), env.getVersion(),
|
||||
env.getState());
|
||||
this(env.getName(), env.getProfiles(), env.getLabel(), env.getVersion(), env.getState());
|
||||
}
|
||||
|
||||
@JsonCreator
|
||||
public Environment(@JsonProperty("name") String name,
|
||||
@JsonProperty("profiles") String[] profiles,
|
||||
public Environment(@JsonProperty("name") String name, @JsonProperty("profiles") String[] profiles,
|
||||
@JsonProperty("label") String label, @JsonProperty("version") String version,
|
||||
@JsonProperty("state") String state) {
|
||||
super();
|
||||
@@ -161,10 +159,9 @@ public class Environment {
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Environment [name=" + this.name + ", profiles="
|
||||
+ Arrays.asList(this.profiles) + ", label=" + this.label
|
||||
+ ", propertySources=" + this.propertySources + ", version="
|
||||
+ this.version + ", state=" + this.state + "]";
|
||||
return "Environment [name=" + this.name + ", profiles=" + Arrays.asList(this.profiles) + ", label=" + this.label
|
||||
+ ", propertySources=" + this.propertySources + ", version=" + this.version + ", state=" + this.state
|
||||
+ "]";
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -35,8 +35,7 @@ public class PropertySource {
|
||||
private Map<?, ?> source;
|
||||
|
||||
@JsonCreator
|
||||
public PropertySource(@JsonProperty("name") String name,
|
||||
@JsonProperty("source") Map<?, ?> source) {
|
||||
public PropertySource(@JsonProperty("name") String name, @JsonProperty("source") Map<?, ?> source) {
|
||||
this.name = name;
|
||||
this.source = source;
|
||||
}
|
||||
|
||||
@@ -31,8 +31,7 @@ public final class PropertyValueDescriptor {
|
||||
private String origin;
|
||||
|
||||
@JsonCreator
|
||||
public PropertyValueDescriptor(@JsonProperty("value") Object value,
|
||||
@JsonProperty("origin") String origin) {
|
||||
public PropertyValueDescriptor(@JsonProperty("value") Object value, @JsonProperty("origin") String origin) {
|
||||
this.value = value;
|
||||
this.origin = origin;
|
||||
}
|
||||
|
||||
@@ -48,8 +48,7 @@ public abstract class BaseDiscoveryClientConfigServiceBootstrapConfigurationTest
|
||||
|
||||
protected DiscoveryClient client = Mockito.mock(DiscoveryClient.class);
|
||||
|
||||
protected ServiceInstance info = new DefaultServiceInstance("app:8877", "app", "foo",
|
||||
8877, false);
|
||||
protected ServiceInstance info = new DefaultServiceInstance("app:8877", "app", "foo", 8877, false);
|
||||
|
||||
@After
|
||||
public void close() {
|
||||
@@ -59,38 +58,30 @@ public abstract class BaseDiscoveryClientConfigServiceBootstrapConfigurationTest
|
||||
}
|
||||
|
||||
void givenDiscoveryClientReturnsNoInfo() {
|
||||
given(this.client.getInstances(DEFAULT_CONFIG_SERVER))
|
||||
.willReturn(Collections.<ServiceInstance>emptyList());
|
||||
given(this.client.getInstances(DEFAULT_CONFIG_SERVER)).willReturn(Collections.<ServiceInstance>emptyList());
|
||||
}
|
||||
|
||||
void givenDiscoveryClientReturnsInfo() {
|
||||
given(this.client.getInstances(DEFAULT_CONFIG_SERVER))
|
||||
.willReturn(Collections.singletonList(this.info));
|
||||
given(this.client.getInstances(DEFAULT_CONFIG_SERVER)).willReturn(Collections.singletonList(this.info));
|
||||
}
|
||||
|
||||
void givenDiscoveryClientReturnsInfoForMultipleInstances(ServiceInstance info1,
|
||||
ServiceInstance info2) {
|
||||
given(this.client.getInstances(DEFAULT_CONFIG_SERVER))
|
||||
.willReturn(Arrays.asList(info1, info2));
|
||||
void givenDiscoveryClientReturnsInfoForMultipleInstances(ServiceInstance info1, ServiceInstance info2) {
|
||||
given(this.client.getInstances(DEFAULT_CONFIG_SERVER)).willReturn(Arrays.asList(info1, info2));
|
||||
}
|
||||
|
||||
void givenDiscoveryClientReturnsInfoOnThirdTry() {
|
||||
given(this.client.getInstances(DEFAULT_CONFIG_SERVER))
|
||||
.willReturn(Collections.<ServiceInstance>emptyList())
|
||||
.willReturn(Collections.<ServiceInstance>emptyList())
|
||||
.willReturn(Collections.singletonList(this.info));
|
||||
given(this.client.getInstances(DEFAULT_CONFIG_SERVER)).willReturn(Collections.<ServiceInstance>emptyList())
|
||||
.willReturn(Collections.<ServiceInstance>emptyList()).willReturn(Collections.singletonList(this.info));
|
||||
}
|
||||
|
||||
void expectNoInstancesOfConfigServerException() {
|
||||
this.expectedException.expect(IllegalStateException.class);
|
||||
this.expectedException.expectMessage(
|
||||
"No instances found of configserver (" + DEFAULT_CONFIG_SERVER + ")");
|
||||
this.expectedException.expectMessage("No instances found of configserver (" + DEFAULT_CONFIG_SERVER + ")");
|
||||
}
|
||||
|
||||
void expectDiscoveryClientConfigServiceBootstrapConfigurationIsSetup() {
|
||||
assertThat(this.context.getBeanNamesForType(
|
||||
DiscoveryClientConfigServiceBootstrapConfiguration.class).length)
|
||||
.isEqualTo(1);
|
||||
assertThat(this.context.getBeanNamesForType(DiscoveryClientConfigServiceBootstrapConfiguration.class).length)
|
||||
.isEqualTo(1);
|
||||
}
|
||||
|
||||
void expectConfigClientPropertiesHasDefaultConfiguration() {
|
||||
@@ -102,16 +93,13 @@ public abstract class BaseDiscoveryClientConfigServiceBootstrapConfigurationTest
|
||||
}
|
||||
|
||||
void expectConfigClientPropertiesHasConfiguration(final String expectedUri) {
|
||||
ConfigClientProperties properties = this.context
|
||||
.getBean(ConfigClientProperties.class);
|
||||
ConfigClientProperties properties = this.context.getBean(ConfigClientProperties.class);
|
||||
Credentials credentials = properties.getCredentials(0);
|
||||
assertThat(credentials.getUri()).isEqualTo(expectedUri);
|
||||
}
|
||||
|
||||
void expectConfigClientPropertiesHasMultipleUris(final String expectedUri1,
|
||||
final String expectedUri2) {
|
||||
ConfigClientProperties properties = this.context
|
||||
.getBean(ConfigClientProperties.class);
|
||||
void expectConfigClientPropertiesHasMultipleUris(final String expectedUri1, final String expectedUri2) {
|
||||
ConfigClientProperties properties = this.context.getBean(ConfigClientProperties.class);
|
||||
assertThat(properties.getUri().length).isEqualTo(2);
|
||||
Credentials credentials1 = properties.getCredentials(0);
|
||||
Credentials credentials2 = properties.getCredentials(1);
|
||||
@@ -136,13 +124,11 @@ public abstract class BaseDiscoveryClientConfigServiceBootstrapConfigurationTest
|
||||
TestPropertyValues.of(env).applyTo(this.context);
|
||||
TestPropertyValues.of("eureka.client.enabled=false").applyTo(this.context);
|
||||
if (registerDiscoveryClient) {
|
||||
this.context.getDefaultListableBeanFactory()
|
||||
.registerSingleton("discoveryClient", this.client);
|
||||
this.context.getDefaultListableBeanFactory().registerSingleton("discoveryClient", this.client);
|
||||
}
|
||||
this.context.register(UtilAutoConfiguration.class,
|
||||
PropertyPlaceholderAutoConfiguration.class,
|
||||
DiscoveryClientConfigServiceBootstrapConfiguration.class,
|
||||
ConfigServiceBootstrapConfiguration.class, ConfigClientProperties.class);
|
||||
this.context.register(UtilAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class,
|
||||
DiscoveryClientConfigServiceBootstrapConfiguration.class, ConfigServiceBootstrapConfiguration.class,
|
||||
ConfigClientProperties.class);
|
||||
if (refresh) {
|
||||
this.context.refresh();
|
||||
}
|
||||
|
||||
@@ -32,18 +32,17 @@ public class ConfigClientAutoConfigurationTests {
|
||||
public void sunnyDay() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
ConfigClientAutoConfiguration.class);
|
||||
assertThat(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context,
|
||||
ConfigClientProperties.class).length).isEqualTo(1);
|
||||
assertThat(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context, ConfigClientProperties.class).length)
|
||||
.isEqualTo(1);
|
||||
context.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void withParent() {
|
||||
ConfigurableApplicationContext context = new SpringApplicationBuilder(
|
||||
ConfigClientAutoConfiguration.class).child(Object.class)
|
||||
.web(WebApplicationType.NONE).run();
|
||||
assertThat(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context,
|
||||
ConfigClientProperties.class).length).isEqualTo(1);
|
||||
ConfigurableApplicationContext context = new SpringApplicationBuilder(ConfigClientAutoConfiguration.class)
|
||||
.child(Object.class).web(WebApplicationType.NONE).run();
|
||||
assertThat(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context, ConfigClientProperties.class).length)
|
||||
.isEqualTo(1);
|
||||
context.close();
|
||||
}
|
||||
|
||||
|
||||
@@ -37,8 +37,7 @@ public class ConfigClientPropertiesTests {
|
||||
@Rule
|
||||
public ExpectedException expected = ExpectedException.none();
|
||||
|
||||
private ConfigClientProperties locator = new ConfigClientProperties(
|
||||
new StandardEnvironment());
|
||||
private ConfigClientProperties locator = new ConfigClientProperties(new StandardEnvironment());
|
||||
|
||||
@Test
|
||||
public void vanilla() {
|
||||
@@ -128,11 +127,9 @@ public class ConfigClientPropertiesTests {
|
||||
|
||||
@Test
|
||||
public void testThatExplicitUsernamePasswordTakePrecedence() {
|
||||
ConfigClientProperties properties = new ConfigClientProperties(
|
||||
new MockEnvironment());
|
||||
ConfigClientProperties properties = new ConfigClientProperties(new MockEnvironment());
|
||||
|
||||
properties.setUri(
|
||||
new String[] { "https://userInfoName:userInfoPW@localhost:8888/" });
|
||||
properties.setUri(new String[] { "https://userInfoName:userInfoPW@localhost:8888/" });
|
||||
properties.setUsername("explicitName");
|
||||
properties.setPassword("explicitPW");
|
||||
Credentials credentials = properties.getCredentials(0);
|
||||
@@ -142,8 +139,7 @@ public class ConfigClientPropertiesTests {
|
||||
|
||||
@Test
|
||||
public void checkIfExceptionThrownForNegativeIndex() {
|
||||
this.locator.setUri(
|
||||
new String[] { "http://localhost:8888", "http://localhost:8889" });
|
||||
this.locator.setUri(new String[] { "http://localhost:8888", "http://localhost:8889" });
|
||||
this.expected.expect(IllegalStateException.class);
|
||||
this.expected.expectMessage("Trying to access an invalid array index");
|
||||
Credentials credentials = this.locator.getCredentials(-1);
|
||||
@@ -151,8 +147,7 @@ public class ConfigClientPropertiesTests {
|
||||
|
||||
@Test
|
||||
public void checkIfExceptionThrownForPositiveInvalidIndex() {
|
||||
this.locator.setUri(
|
||||
new String[] { "http://localhost:8888", "http://localhost:8889" });
|
||||
this.locator.setUri(new String[] { "http://localhost:8888", "http://localhost:8889" });
|
||||
this.expected.expect(IllegalStateException.class);
|
||||
this.expected.expectMessage("Trying to access an invalid array index");
|
||||
Credentials credentials = this.locator.getCredentials(3);
|
||||
@@ -160,8 +155,7 @@ public class ConfigClientPropertiesTests {
|
||||
|
||||
@Test
|
||||
public void checkIfExceptionThrownForIndexEqualToLength() {
|
||||
this.locator.setUri(
|
||||
new String[] { "http://localhost:8888", "http://localhost:8889" });
|
||||
this.locator.setUri(new String[] { "http://localhost:8888", "http://localhost:8889" });
|
||||
this.expected.expect(IllegalStateException.class);
|
||||
this.expected.expectMessage("Trying to access an invalid array index");
|
||||
Credentials credentials = this.locator.getCredentials(2);
|
||||
|
||||
@@ -31,14 +31,13 @@ public class ConfigServerBootstrapConfigurationTests {
|
||||
@Test
|
||||
public void withHealthIndicator() {
|
||||
ConfigurableApplicationContext context = new SpringApplicationBuilder(
|
||||
PropertySourceBootstrapConfiguration.class,
|
||||
ConfigServiceBootstrapConfiguration.class)
|
||||
.child(ConfigClientAutoConfiguration.class)
|
||||
.web(WebApplicationType.NONE).run();
|
||||
assertThat(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context,
|
||||
ConfigClientProperties.class).length).isEqualTo(1);
|
||||
assertThat(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context,
|
||||
ConfigServerHealthIndicator.class).length).isEqualTo(1);
|
||||
PropertySourceBootstrapConfiguration.class, ConfigServiceBootstrapConfiguration.class)
|
||||
.child(ConfigClientAutoConfiguration.class).web(WebApplicationType.NONE).run();
|
||||
assertThat(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context, ConfigClientProperties.class).length)
|
||||
.isEqualTo(1);
|
||||
assertThat(
|
||||
BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context, ConfigServerHealthIndicator.class).length)
|
||||
.isEqualTo(1);
|
||||
context.close();
|
||||
}
|
||||
|
||||
|
||||
@@ -32,8 +32,7 @@ public class ConfigServerConfigDataLocationResolverTests {
|
||||
|
||||
private ConfigServerConfigDataLocationResolver resolver;
|
||||
|
||||
private ConfigDataLocationResolverContext context = mock(
|
||||
ConfigDataLocationResolverContext.class);
|
||||
private ConfigDataLocationResolverContext context = mock(ConfigDataLocationResolverContext.class);
|
||||
|
||||
private MockEnvironment environment;
|
||||
|
||||
|
||||
@@ -43,8 +43,8 @@ public class ConfigServerHealthIndicatorTests {
|
||||
|
||||
private ConfigurableEnvironment environment = mock(ConfigurableEnvironment.class);
|
||||
|
||||
private ConfigServerHealthIndicator indicator = new ConfigServerHealthIndicator(
|
||||
this.environment, new ConfigClientHealthProperties());
|
||||
private ConfigServerHealthIndicator indicator = new ConfigServerHealthIndicator(this.environment,
|
||||
new ConfigClientHealthProperties());
|
||||
|
||||
@Test
|
||||
public void testDefaultStatus() {
|
||||
@@ -66,8 +66,7 @@ public class ConfigServerHealthIndicatorTests {
|
||||
}
|
||||
|
||||
protected void setupPropertySources() {
|
||||
PropertySource<?> source = new MapPropertySource("configClient",
|
||||
Collections.emptyMap());
|
||||
PropertySource<?> source = new MapPropertySource("configClient", Collections.emptyMap());
|
||||
MutablePropertySources sources = new MutablePropertySources();
|
||||
sources.addFirst(source);
|
||||
doReturn(sources).when(this.environment).getPropertySources();
|
||||
|
||||
@@ -60,15 +60,12 @@ public class ConfigServiceBootstrapConfigurationTest {
|
||||
this.context.register(ConfigServiceBootstrapConfiguration.class);
|
||||
this.context.refresh();
|
||||
|
||||
ConfigServicePropertySourceLocator locator = this.context
|
||||
.getBean(ConfigServicePropertySourceLocator.class);
|
||||
ConfigServicePropertySourceLocator locator = this.context.getBean(ConfigServicePropertySourceLocator.class);
|
||||
|
||||
Field restTemplateField = ReflectionUtils
|
||||
.findField(ConfigServicePropertySourceLocator.class, "restTemplate");
|
||||
Field restTemplateField = ReflectionUtils.findField(ConfigServicePropertySourceLocator.class, "restTemplate");
|
||||
restTemplateField.setAccessible(true);
|
||||
|
||||
RestTemplate restTemplate = (RestTemplate) ReflectionUtils
|
||||
.getField(restTemplateField, locator);
|
||||
RestTemplate restTemplate = (RestTemplate) ReflectionUtils.getField(restTemplateField, locator);
|
||||
|
||||
assertThat(restTemplate).isNotNull();
|
||||
}
|
||||
|
||||
@@ -78,17 +78,15 @@ public class ConfigServicePropertySourceLocatorTests {
|
||||
mockRequestResponseWithoutLabel(new ResponseEntity<>(body, HttpStatus.OK));
|
||||
this.locator.setRestTemplate(this.restTemplate);
|
||||
|
||||
ArgumentCaptor<HttpEntity> argumentCaptor = ArgumentCaptor
|
||||
.forClass(HttpEntity.class);
|
||||
ArgumentCaptor<HttpEntity> argumentCaptor = ArgumentCaptor.forClass(HttpEntity.class);
|
||||
|
||||
assertThat(this.locator.locateCollection(this.environment)).isNotNull();
|
||||
|
||||
Mockito.verify(this.restTemplate).exchange(anyString(), any(HttpMethod.class),
|
||||
argumentCaptor.capture(), any(Class.class), anyString(), anyString());
|
||||
Mockito.verify(this.restTemplate).exchange(anyString(), any(HttpMethod.class), argumentCaptor.capture(),
|
||||
any(Class.class), anyString(), anyString());
|
||||
|
||||
HttpEntity httpEntity = argumentCaptor.getValue();
|
||||
assertThat(httpEntity.getHeaders().getAccept())
|
||||
.containsExactly(MediaType.parseMediaType(V2_JSON));
|
||||
assertThat(httpEntity.getHeaders().getAccept()).containsExactly(MediaType.parseMediaType(V2_JSON));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -96,26 +94,22 @@ public class ConfigServicePropertySourceLocatorTests {
|
||||
Environment body = new Environment("app", "master");
|
||||
mockRequestResponseWithLabel(new ResponseEntity<>(body, HttpStatus.OK), "v1.0.0");
|
||||
this.locator.setRestTemplate(this.restTemplate);
|
||||
TestPropertyValues.of("spring.cloud.config.label:v1.0.0")
|
||||
.applyTo(this.environment);
|
||||
TestPropertyValues.of("spring.cloud.config.label:v1.0.0").applyTo(this.environment);
|
||||
assertThat(this.locator.locateCollection(this.environment)).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sunnyDayWithLabelThatContainsASlash() {
|
||||
Environment body = new Environment("app", "master");
|
||||
mockRequestResponseWithLabel(new ResponseEntity<>(body, HttpStatus.OK),
|
||||
"release(_)v1.0.0");
|
||||
mockRequestResponseWithLabel(new ResponseEntity<>(body, HttpStatus.OK), "release(_)v1.0.0");
|
||||
this.locator.setRestTemplate(this.restTemplate);
|
||||
TestPropertyValues.of("spring.cloud.config.label:release/v1.0.0")
|
||||
.applyTo(this.environment);
|
||||
TestPropertyValues.of("spring.cloud.config.label:release/v1.0.0").applyTo(this.environment);
|
||||
assertThat(this.locator.locateCollection(this.environment)).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sunnyDayWithNoSuchLabel() {
|
||||
mockRequestResponseWithLabel(
|
||||
new ResponseEntity<>((Void) null, HttpStatus.NOT_FOUND), "nosuchlabel");
|
||||
mockRequestResponseWithLabel(new ResponseEntity<>((Void) null, HttpStatus.NOT_FOUND), "nosuchlabel");
|
||||
this.locator.setRestTemplate(this.restTemplate);
|
||||
assertThat(this.locator.locateCollection(this.environment)).isEmpty();
|
||||
}
|
||||
@@ -125,12 +119,9 @@ public class ConfigServicePropertySourceLocatorTests {
|
||||
ConfigClientProperties defaults = new ConfigClientProperties(this.environment);
|
||||
defaults.setFailFast(true);
|
||||
this.locator = new ConfigServicePropertySourceLocator(defaults);
|
||||
mockRequestResponseWithLabel(
|
||||
new ResponseEntity<>((Void) null, HttpStatus.NOT_FOUND),
|
||||
"release(_)v1.0.0");
|
||||
mockRequestResponseWithLabel(new ResponseEntity<>((Void) null, HttpStatus.NOT_FOUND), "release(_)v1.0.0");
|
||||
this.locator.setRestTemplate(this.restTemplate);
|
||||
TestPropertyValues.of("spring.cloud.config.label:release/v1.0.1")
|
||||
.applyTo(this.environment);
|
||||
TestPropertyValues.of("spring.cloud.config.label:release/v1.0.1").applyTo(this.environment);
|
||||
this.expected.expect(IsInstanceOf.instanceOf(IllegalStateException.class));
|
||||
this.expected.expectMessage(
|
||||
"Could not locate PropertySource and the fail fast property is set, failing: None of labels [release/v1.0.1] found");
|
||||
@@ -139,20 +130,18 @@ public class ConfigServicePropertySourceLocatorTests {
|
||||
|
||||
@Test
|
||||
public void failsQuietly() {
|
||||
mockRequestResponseWithoutLabel(
|
||||
new ResponseEntity<>("Wah!", HttpStatus.INTERNAL_SERVER_ERROR));
|
||||
mockRequestResponseWithoutLabel(new ResponseEntity<>("Wah!", HttpStatus.INTERNAL_SERVER_ERROR));
|
||||
this.locator.setRestTemplate(this.restTemplate);
|
||||
assertThat(this.locator.locateCollection(this.environment)).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void failFast() throws Exception {
|
||||
ClientHttpRequestFactory requestFactory = Mockito
|
||||
.mock(ClientHttpRequestFactory.class);
|
||||
ClientHttpRequestFactory requestFactory = Mockito.mock(ClientHttpRequestFactory.class);
|
||||
ClientHttpRequest request = Mockito.mock(ClientHttpRequest.class);
|
||||
ClientHttpResponse response = Mockito.mock(ClientHttpResponse.class);
|
||||
Mockito.when(requestFactory.createRequest(Mockito.any(URI.class),
|
||||
Mockito.any(HttpMethod.class))).thenReturn(request);
|
||||
Mockito.when(requestFactory.createRequest(Mockito.any(URI.class), Mockito.any(HttpMethod.class)))
|
||||
.thenReturn(request);
|
||||
RestTemplate restTemplate = new RestTemplate(requestFactory);
|
||||
ConfigClientProperties defaults = new ConfigClientProperties(this.environment);
|
||||
defaults.setFailFast(true);
|
||||
@@ -162,25 +151,21 @@ public class ConfigServicePropertySourceLocatorTests {
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
Mockito.when(response.getHeaders()).thenReturn(headers);
|
||||
Mockito.when(response.getStatusCode())
|
||||
.thenReturn(HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
Mockito.when(response.getBody())
|
||||
.thenReturn(new ByteArrayInputStream("{}".getBytes()));
|
||||
Mockito.when(response.getStatusCode()).thenReturn(HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
Mockito.when(response.getBody()).thenReturn(new ByteArrayInputStream("{}".getBytes()));
|
||||
this.locator.setRestTemplate(restTemplate);
|
||||
this.expected
|
||||
.expectCause(IsInstanceOf.instanceOf(IllegalArgumentException.class));
|
||||
this.expected.expectCause(IsInstanceOf.instanceOf(IllegalArgumentException.class));
|
||||
this.expected.expectMessage("fail fast property is set");
|
||||
this.locator.locateCollection(this.environment);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void failFastWhenNotFound() throws Exception {
|
||||
ClientHttpRequestFactory requestFactory = Mockito
|
||||
.mock(ClientHttpRequestFactory.class);
|
||||
ClientHttpRequestFactory requestFactory = Mockito.mock(ClientHttpRequestFactory.class);
|
||||
ClientHttpRequest request = Mockito.mock(ClientHttpRequest.class);
|
||||
ClientHttpResponse response = Mockito.mock(ClientHttpResponse.class);
|
||||
Mockito.when(requestFactory.createRequest(Mockito.any(URI.class),
|
||||
Mockito.any(HttpMethod.class))).thenReturn(request);
|
||||
Mockito.when(requestFactory.createRequest(Mockito.any(URI.class), Mockito.any(HttpMethod.class)))
|
||||
.thenReturn(request);
|
||||
RestTemplate restTemplate = new RestTemplate(requestFactory);
|
||||
ConfigClientProperties defaults = new ConfigClientProperties(this.environment);
|
||||
defaults.setFailFast(true);
|
||||
@@ -191,22 +176,19 @@ public class ConfigServicePropertySourceLocatorTests {
|
||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
Mockito.when(response.getHeaders()).thenReturn(headers);
|
||||
Mockito.when(response.getStatusCode()).thenReturn(HttpStatus.NOT_FOUND);
|
||||
Mockito.when(response.getBody())
|
||||
.thenReturn(new ByteArrayInputStream("".getBytes()));
|
||||
Mockito.when(response.getBody()).thenReturn(new ByteArrayInputStream("".getBytes()));
|
||||
this.locator.setRestTemplate(restTemplate);
|
||||
this.expected
|
||||
.expectCause(IsInstanceOf.instanceOf(IllegalArgumentException.class));
|
||||
this.expected.expectCause(IsInstanceOf.instanceOf(IllegalArgumentException.class));
|
||||
this.expected.expectMessage("fail fast property is set");
|
||||
this.locator.locateCollection(this.environment);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void failFastWhenBothPasswordAndAuthorizationPropertiesSet() throws Exception {
|
||||
ClientHttpRequestFactory requestFactory = Mockito
|
||||
.mock(ClientHttpRequestFactory.class);
|
||||
ClientHttpRequestFactory requestFactory = Mockito.mock(ClientHttpRequestFactory.class);
|
||||
ClientHttpRequest request = Mockito.mock(ClientHttpRequest.class);
|
||||
Mockito.when(requestFactory.createRequest(Mockito.any(URI.class),
|
||||
Mockito.any(HttpMethod.class))).thenReturn(request);
|
||||
Mockito.when(requestFactory.createRequest(Mockito.any(URI.class), Mockito.any(HttpMethod.class)))
|
||||
.thenReturn(request);
|
||||
ConfigClientProperties defaults = new ConfigClientProperties(this.environment);
|
||||
defaults.setFailFast(true);
|
||||
defaults.setUsername("username");
|
||||
@@ -214,21 +196,19 @@ public class ConfigServicePropertySourceLocatorTests {
|
||||
defaults.getHeaders().put(AUTHORIZATION, "Basic dXNlcm5hbWU6cGFzc3dvcmQNCg==");
|
||||
this.locator = new ConfigServicePropertySourceLocator(defaults);
|
||||
this.expected.expect(IllegalStateException.class);
|
||||
this.expected.expectMessage(
|
||||
"Could not locate PropertySource and the fail fast property is set, failing");
|
||||
this.expected.expectMessage("Could not locate PropertySource and the fail fast property is set, failing");
|
||||
this.locator.locateCollection(this.environment);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void interceptorShouldAddHeadersWhenHeadersPropertySet() throws Exception {
|
||||
MockClientHttpRequest request = new MockClientHttpRequest();
|
||||
ClientHttpRequestExecution execution = Mockito
|
||||
.mock(ClientHttpRequestExecution.class);
|
||||
ClientHttpRequestExecution execution = Mockito.mock(ClientHttpRequestExecution.class);
|
||||
byte[] body = new byte[] {};
|
||||
Map<String, String> headers = new HashMap<>();
|
||||
headers.put("X-Example-Version", "2.1");
|
||||
new ConfigServicePropertySourceLocator.GenericRequestHeaderInterceptor(headers)
|
||||
.intercept(request, body, execution);
|
||||
new ConfigServicePropertySourceLocator.GenericRequestHeaderInterceptor(headers).intercept(request, body,
|
||||
execution);
|
||||
Mockito.verify(execution).execute(request, body);
|
||||
assertThat(request.getHeaders().getFirst("X-Example-Version")).isEqualTo("2.1");
|
||||
}
|
||||
@@ -240,8 +220,7 @@ public class ConfigServicePropertySourceLocatorTests {
|
||||
this.locator = new ConfigServicePropertySourceLocator(defaults);
|
||||
String username = "user";
|
||||
String password = "pass";
|
||||
ReflectionTestUtils.invokeMethod(this.locator, "addAuthorizationToken", defaults,
|
||||
headers, username, password);
|
||||
ReflectionTestUtils.invokeMethod(this.locator, "addAuthorizationToken", defaults, headers, username, password);
|
||||
assertThat(headers).hasSize(1);
|
||||
}
|
||||
|
||||
@@ -253,8 +232,7 @@ public class ConfigServicePropertySourceLocatorTests {
|
||||
this.locator = new ConfigServicePropertySourceLocator(defaults);
|
||||
String username = "user";
|
||||
String password = null;
|
||||
ReflectionTestUtils.invokeMethod(this.locator, "addAuthorizationToken", defaults,
|
||||
headers, username, password);
|
||||
ReflectionTestUtils.invokeMethod(this.locator, "addAuthorizationToken", defaults, headers, username, password);
|
||||
assertThat(headers).hasSize(1);
|
||||
}
|
||||
|
||||
@@ -268,8 +246,7 @@ public class ConfigServicePropertySourceLocatorTests {
|
||||
String password = "pass";
|
||||
this.expected.expect(IllegalStateException.class);
|
||||
this.expected.expectMessage("You must set either 'password' or 'authorization'");
|
||||
ReflectionTestUtils.invokeMethod(this.locator, "addAuthorizationToken", defaults,
|
||||
headers, username, password);
|
||||
ReflectionTestUtils.invokeMethod(this.locator, "addAuthorizationToken", defaults, headers, username, password);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -298,15 +275,12 @@ public class ConfigServicePropertySourceLocatorTests {
|
||||
defaults.getHeaders().put(AUTHORIZATION, "Basic dXNlcm5hbWU6cGFzc3dvcmQNCg==");
|
||||
defaults.getHeaders().put("key", "value");
|
||||
this.locator = new ConfigServicePropertySourceLocator(defaults);
|
||||
RestTemplate restTemplate = ReflectionTestUtils.invokeMethod(this.locator,
|
||||
"getSecureRestTemplate", defaults);
|
||||
Iterator<ClientHttpRequestInterceptor> iterator = restTemplate.getInterceptors()
|
||||
.iterator();
|
||||
RestTemplate restTemplate = ReflectionTestUtils.invokeMethod(this.locator, "getSecureRestTemplate", defaults);
|
||||
Iterator<ClientHttpRequestInterceptor> iterator = restTemplate.getInterceptors().iterator();
|
||||
while (iterator.hasNext()) {
|
||||
GenericRequestHeaderInterceptor genericRequestHeaderInterceptor = (GenericRequestHeaderInterceptor) iterator
|
||||
.next();
|
||||
assertThat(genericRequestHeaderInterceptor.getHeaders().get(AUTHORIZATION))
|
||||
.isEqualTo(null);
|
||||
assertThat(genericRequestHeaderInterceptor.getHeaders().get(AUTHORIZATION)).isEqualTo(null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -315,32 +289,29 @@ public class ConfigServicePropertySourceLocatorTests {
|
||||
public void shouldPreserveOrder() {
|
||||
Environment body = new Environment("app", "master");
|
||||
LinkedHashMap<Object, Object> properties = new LinkedHashMap<>();
|
||||
properties.put("zuul.routes.specificproduct.path",
|
||||
originValue("/v1/product/electronics/**",
|
||||
"Config Server /config-repo/zuul-service/zuul-service.yml:5:13"));
|
||||
properties.put("zuul.routes.specificproduct.path", originValue("/v1/product/electronics/**",
|
||||
"Config Server /config-repo/zuul-service/zuul-service.yml:5:13"));
|
||||
|
||||
properties.put("zuul.routes.specificproduct.service-id",
|
||||
originValue("electronic-product-service",
|
||||
"Config Server /config-repo/zuul-service/zuul-service.yml:6:19"));
|
||||
properties.put("zuul.routes.specificproduct.service-id", originValue("electronic-product-service",
|
||||
"Config Server /config-repo/zuul-service/zuul-service.yml:6:19"));
|
||||
|
||||
properties.put("zuul.routes.specificproduct.strip-prefix", originValue("false",
|
||||
"Config Server /config-repo/zuul-service/zuul-service.yml:7:21"));
|
||||
properties.put("zuul.routes.specificproduct.strip-prefix",
|
||||
originValue("false", "Config Server /config-repo/zuul-service/zuul-service.yml:7:21"));
|
||||
|
||||
properties.put("zuul.routes.specificproduct.sensitiveHeaders", originValue("",
|
||||
"Config Server /config-repo/zuul-service/zuul-service.yml:8:24"));
|
||||
properties.put("zuul.routes.specificproduct.sensitiveHeaders",
|
||||
originValue("", "Config Server /config-repo/zuul-service/zuul-service.yml:8:24"));
|
||||
|
||||
properties.put("zuul.routes.genericproduct.path", originValue("/v1/product/**",
|
||||
"Config Server /config-repo/zuul-service/zuul-service.yml:10:13"));
|
||||
properties.put("zuul.routes.genericproduct.path",
|
||||
originValue("/v1/product/**", "Config Server /config-repo/zuul-service/zuul-service.yml:10:13"));
|
||||
|
||||
properties.put("zuul.routes.genericproduct.service-id", originValue(
|
||||
"product-service",
|
||||
"Config Server /config-repo/zuul-service/zuul-service.yml:11:19"));
|
||||
properties.put("zuul.routes.genericproduct.service-id",
|
||||
originValue("product-service", "Config Server /config-repo/zuul-service/zuul-service.yml:11:19"));
|
||||
|
||||
properties.put("zuul.routes.genericproduct.strip-prefix", originValue("false",
|
||||
"Config Server /config-repo/zuul-service/zuul-service.yml:12:21"));
|
||||
properties.put("zuul.routes.genericproduct.strip-prefix",
|
||||
originValue("false", "Config Server /config-repo/zuul-service/zuul-service.yml:12:21"));
|
||||
|
||||
properties.put("zuul.routes.genericproduct.sensitiveHeaders", originValue("",
|
||||
"Config Server /config-repo/zuul-service/zuul-service.yml:13:24"));
|
||||
properties.put("zuul.routes.genericproduct.sensitiveHeaders",
|
||||
originValue("", "Config Server /config-repo/zuul-service/zuul-service.yml:13:24"));
|
||||
body.add(new PropertySource("source1", properties));
|
||||
mockRequestResponseWithoutLabel(new ResponseEntity<>(body, HttpStatus.OK));
|
||||
this.locator.setRestTemplate(this.restTemplate);
|
||||
@@ -348,8 +319,7 @@ public class ConfigServicePropertySourceLocatorTests {
|
||||
List<org.springframework.core.env.PropertySource<?>> propertySources = new ArrayList<>(
|
||||
this.locator.locateCollection(this.environment));
|
||||
assertThat(propertySources).hasSize(2);
|
||||
org.springframework.core.env.PropertySource<?> propertySource = propertySources
|
||||
.get(1);
|
||||
org.springframework.core.env.PropertySource<?> propertySource = propertySources.get(1);
|
||||
Map source = (Map) propertySource.getSource();
|
||||
Iterator iterator = source.keySet().iterator();
|
||||
assertThat(iterator.next()).isEqualTo("zuul.routes.specificproduct.path");
|
||||
@@ -366,26 +336,23 @@ public class ConfigServicePropertySourceLocatorTests {
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private void mockRequestResponseWithLabel(ResponseEntity<?> response, String label) {
|
||||
Mockito.when(this.restTemplate.exchange(Mockito.any(String.class),
|
||||
Mockito.any(HttpMethod.class), Mockito.any(HttpEntity.class),
|
||||
Mockito.any(Class.class), anyString(), anyString(),
|
||||
Mockito.when(this.restTemplate.exchange(Mockito.any(String.class), Mockito.any(HttpMethod.class),
|
||||
Mockito.any(HttpEntity.class), Mockito.any(Class.class), anyString(), anyString(),
|
||||
ArgumentMatchers.eq(label))).thenReturn(response);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private void mockRequestResponseWithoutLabel(ResponseEntity<?> response) {
|
||||
Mockito.when(this.restTemplate.exchange(Mockito.any(String.class),
|
||||
Mockito.any(HttpMethod.class), Mockito.any(HttpEntity.class),
|
||||
Mockito.any(Class.class), anyString(), anyString())).thenReturn(response);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private void mockRequestResponseWithoutLabelWithExpectedName(
|
||||
ResponseEntity<?> response, String expectedName) {
|
||||
Mockito.when(this.restTemplate.exchange(Mockito.any(String.class),
|
||||
Mockito.any(HttpMethod.class), Mockito.any(HttpEntity.class),
|
||||
Mockito.any(Class.class), ArgumentMatchers.eq(expectedName), anyString()))
|
||||
Mockito.when(this.restTemplate.exchange(Mockito.any(String.class), Mockito.any(HttpMethod.class),
|
||||
Mockito.any(HttpEntity.class), Mockito.any(Class.class), anyString(), anyString()))
|
||||
.thenReturn(response);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private void mockRequestResponseWithoutLabelWithExpectedName(ResponseEntity<?> response, String expectedName) {
|
||||
Mockito.when(this.restTemplate.exchange(Mockito.any(String.class), Mockito.any(HttpMethod.class),
|
||||
Mockito.any(HttpEntity.class), Mockito.any(Class.class), ArgumentMatchers.eq(expectedName),
|
||||
anyString())).thenReturn(response);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -28,23 +28,19 @@ public class DiscoveryClientConfigServiceBootstrapConfigurationNoSpringRetryTest
|
||||
extends BaseDiscoveryClientConfigServiceBootstrapConfigurationTests {
|
||||
|
||||
@Test
|
||||
public void shouldFailWithExceptionGetConfigServerInstanceFromDiscoveryClient()
|
||||
throws Exception {
|
||||
public void shouldFailWithExceptionGetConfigServerInstanceFromDiscoveryClient() throws Exception {
|
||||
givenDiscoveryClientReturnsNoInfo();
|
||||
|
||||
expectNoInstancesOfConfigServerException();
|
||||
|
||||
setup("spring.cloud.config.discovery.enabled=true",
|
||||
"spring.cloud.config.fail-fast=true");
|
||||
setup("spring.cloud.config.discovery.enabled=true", "spring.cloud.config.fail-fast=true");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldFailWithMessageGetConfigServerInstanceFromDiscoveryClient()
|
||||
throws Exception {
|
||||
public void shouldFailWithMessageGetConfigServerInstanceFromDiscoveryClient() throws Exception {
|
||||
givenDiscoveryClientReturnsNoInfo();
|
||||
|
||||
setup("spring.cloud.config.discovery.enabled=true",
|
||||
"spring.cloud.config.fail-fast=false");
|
||||
setup("spring.cloud.config.discovery.enabled=true", "spring.cloud.config.fail-fast=false");
|
||||
|
||||
expectDiscoveryClientConfigServiceBootstrapConfigurationIsSetup();
|
||||
expectConfigClientPropertiesHasDefaultConfiguration();
|
||||
@@ -52,12 +48,10 @@ public class DiscoveryClientConfigServiceBootstrapConfigurationNoSpringRetryTest
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldSucceedGetConfigServerInstanceFromDiscoveryClient()
|
||||
throws Exception {
|
||||
public void shouldSucceedGetConfigServerInstanceFromDiscoveryClient() throws Exception {
|
||||
givenDiscoveryClientReturnsInfo();
|
||||
|
||||
setup("spring.cloud.config.discovery.enabled=true",
|
||||
"spring.cloud.config.fail-fast=true");
|
||||
setup("spring.cloud.config.discovery.enabled=true", "spring.cloud.config.fail-fast=true");
|
||||
|
||||
expectDiscoveryClientConfigServiceBootstrapConfigurationIsSetup();
|
||||
expectConfigClientPropertiesHasConfigurationFromEureka();
|
||||
|
||||
@@ -41,14 +41,11 @@ public class DiscoveryClientConfigServiceBootstrapConfigurationTests
|
||||
|
||||
@Test
|
||||
public void offByDefault() throws Exception {
|
||||
this.context = new AnnotationConfigApplicationContext(
|
||||
DiscoveryClientConfigServiceBootstrapConfiguration.class);
|
||||
this.context = new AnnotationConfigApplicationContext(DiscoveryClientConfigServiceBootstrapConfiguration.class);
|
||||
|
||||
assertThat(this.context.getBeanNamesForType(DiscoveryClient.class).length)
|
||||
assertThat(this.context.getBeanNamesForType(DiscoveryClient.class).length).isEqualTo(0);
|
||||
assertThat(this.context.getBeanNamesForType(DiscoveryClientConfigServiceBootstrapConfiguration.class).length)
|
||||
.isEqualTo(0);
|
||||
assertThat(this.context.getBeanNamesForType(
|
||||
DiscoveryClientConfigServiceBootstrapConfiguration.class).length)
|
||||
.isEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -64,14 +61,11 @@ public class DiscoveryClientConfigServiceBootstrapConfigurationTests
|
||||
|
||||
@Test
|
||||
public void configServerInstanceProviderFunction() {
|
||||
ConfigServerInstanceProvider.Function function = mock(
|
||||
ConfigServerInstanceProvider.Function.class);
|
||||
given(function.apply(DEFAULT_CONFIG_SERVER))
|
||||
.willReturn(Collections.singletonList(this.info));
|
||||
ConfigServerInstanceProvider.Function function = mock(ConfigServerInstanceProvider.Function.class);
|
||||
given(function.apply(DEFAULT_CONFIG_SERVER)).willReturn(Collections.singletonList(this.info));
|
||||
|
||||
setup(false, false, "spring.cloud.config.discovery.enabled=true");
|
||||
this.context.getDefaultListableBeanFactory().registerSingleton("myFunction",
|
||||
function);
|
||||
this.context.getDefaultListableBeanFactory().registerSingleton("myFunction", function);
|
||||
this.context.refresh();
|
||||
|
||||
expectDiscoveryClientConfigServiceBootstrapConfigurationIsSetup();
|
||||
@@ -108,10 +102,8 @@ public class DiscoveryClientConfigServiceBootstrapConfigurationTests
|
||||
|
||||
@Test
|
||||
public void multipleInstancesReturnedFromDiscovery() {
|
||||
ServiceInstance info1 = new DefaultServiceInstance("app1:8888", "app",
|
||||
"localhost", 8888, true);
|
||||
ServiceInstance info2 = new DefaultServiceInstance("app2:8888", "app",
|
||||
"localhost1", 8888, false);
|
||||
ServiceInstance info1 = new DefaultServiceInstance("app1:8888", "app", "localhost", 8888, true);
|
||||
ServiceInstance info2 = new DefaultServiceInstance("app2:8888", "app", "localhost1", 8888, false);
|
||||
givenDiscoveryClientReturnsInfoForMultipleInstances(info1, info2);
|
||||
|
||||
setup("spring.cloud.config.discovery.enabled=true");
|
||||
@@ -119,8 +111,7 @@ public class DiscoveryClientConfigServiceBootstrapConfigurationTests
|
||||
expectDiscoveryClientConfigServiceBootstrapConfigurationIsSetup();
|
||||
|
||||
verifyDiscoveryClientCalledOnce();
|
||||
expectConfigClientPropertiesHasMultipleUris("https://localhost:8888/",
|
||||
"http://localhost1:8888/");
|
||||
expectConfigClientPropertiesHasMultipleUris("https://localhost:8888/", "http://localhost1:8888/");
|
||||
|
||||
}
|
||||
|
||||
@@ -131,8 +122,7 @@ public class DiscoveryClientConfigServiceBootstrapConfigurationTests
|
||||
|
||||
setup("spring.cloud.config.discovery.enabled=true");
|
||||
|
||||
ConfigClientProperties locator = this.context
|
||||
.getBean(ConfigClientProperties.class);
|
||||
ConfigClientProperties locator = this.context.getBean(ConfigClientProperties.class);
|
||||
Credentials credentials = locator.getCredentials(0);
|
||||
assertThat(credentials.getUri()).isEqualTo("http://foo:8877/");
|
||||
assertThat(credentials.getPassword()).isEqualTo("bar");
|
||||
@@ -161,14 +151,11 @@ public class DiscoveryClientConfigServiceBootstrapConfigurationTests
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldRetryAndSucceedGetConfigServerInstanceFromDiscoveryClient()
|
||||
throws Exception {
|
||||
public void shouldRetryAndSucceedGetConfigServerInstanceFromDiscoveryClient() throws Exception {
|
||||
givenDiscoveryClientReturnsInfoOnThirdTry();
|
||||
|
||||
setup("spring.cloud.config.discovery.enabled=true",
|
||||
"spring.cloud.config.retry.maxAttempts=3",
|
||||
"spring.cloud.config.retry.initialInterval=10",
|
||||
"spring.cloud.config.fail-fast=true");
|
||||
setup("spring.cloud.config.discovery.enabled=true", "spring.cloud.config.retry.maxAttempts=3",
|
||||
"spring.cloud.config.retry.initialInterval=10", "spring.cloud.config.fail-fast=true");
|
||||
|
||||
expectDiscoveryClientConfigServiceBootstrapConfigurationIsSetup();
|
||||
verifyDiscoveryClientCalledThreeTimes();
|
||||
@@ -182,8 +169,7 @@ public class DiscoveryClientConfigServiceBootstrapConfigurationTests
|
||||
public void shouldNotRetryIfNotFailFastPropertySet() throws Exception {
|
||||
givenDiscoveryClientReturnsInfoOnThirdTry();
|
||||
|
||||
setup("spring.cloud.config.discovery.enabled=true",
|
||||
"spring.cloud.config.retry.maxAttempts=3",
|
||||
setup("spring.cloud.config.discovery.enabled=true", "spring.cloud.config.retry.maxAttempts=3",
|
||||
"spring.cloud.config.retry.initialInterval=10");
|
||||
|
||||
expectDiscoveryClientConfigServiceBootstrapConfigurationIsSetup();
|
||||
@@ -192,27 +178,21 @@ public class DiscoveryClientConfigServiceBootstrapConfigurationTests
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldRetryAndFailWithExceptionGetConfigServerInstanceFromDiscoveryClient()
|
||||
throws Exception {
|
||||
public void shouldRetryAndFailWithExceptionGetConfigServerInstanceFromDiscoveryClient() throws Exception {
|
||||
givenDiscoveryClientReturnsNoInfo();
|
||||
|
||||
expectNoInstancesOfConfigServerException();
|
||||
|
||||
setup("spring.cloud.config.discovery.enabled=true",
|
||||
"spring.cloud.config.retry.maxAttempts=3",
|
||||
"spring.cloud.config.retry.initialInterval=10",
|
||||
"spring.cloud.config.fail-fast=true");
|
||||
setup("spring.cloud.config.discovery.enabled=true", "spring.cloud.config.retry.maxAttempts=3",
|
||||
"spring.cloud.config.retry.initialInterval=10", "spring.cloud.config.fail-fast=true");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldRetryAndFailWithMessageGetConfigServerInstanceFromDiscoveryClient()
|
||||
throws Exception {
|
||||
public void shouldRetryAndFailWithMessageGetConfigServerInstanceFromDiscoveryClient() throws Exception {
|
||||
givenDiscoveryClientReturnsNoInfo();
|
||||
|
||||
setup("spring.cloud.config.discovery.enabled=true",
|
||||
"spring.cloud.config.retry.maxAttempts=3",
|
||||
"spring.cloud.config.retry.initialInterval=10",
|
||||
"spring.cloud.config.fail-fast=false");
|
||||
setup("spring.cloud.config.discovery.enabled=true", "spring.cloud.config.retry.maxAttempts=3",
|
||||
"spring.cloud.config.retry.initialInterval=10", "spring.cloud.config.fail-fast=false");
|
||||
|
||||
expectDiscoveryClientConfigServiceBootstrapConfigurationIsSetup();
|
||||
expectConfigClientPropertiesHasDefaultConfiguration();
|
||||
|
||||
@@ -28,8 +28,7 @@ import org.springframework.boot.context.config.ConfigData;
|
||||
import org.springframework.boot.context.config.ConfigDataLoaderContext;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
|
||||
public class TestConfigServerConfigDataLoader
|
||||
extends AbstractConfigDataLoader<TestConfigServerConfigDataLocation> {
|
||||
public class TestConfigServerConfigDataLoader extends AbstractConfigDataLoader<TestConfigServerConfigDataLocation> {
|
||||
|
||||
public TestConfigServerConfigDataLoader(Log logger) {
|
||||
super(logger);
|
||||
@@ -41,8 +40,8 @@ public class TestConfigServerConfigDataLoader
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigData load(ConfigDataLoaderContext context,
|
||||
TestConfigServerConfigDataLocation location) throws IOException {
|
||||
public ConfigData load(ConfigDataLoaderContext context, TestConfigServerConfigDataLocation location)
|
||||
throws IOException {
|
||||
// This could be a RetryTemplate
|
||||
Function<TestConfigServerConfigDataLocation, ConfigData> fn = dataLocation -> {
|
||||
try {
|
||||
@@ -57,11 +56,8 @@ public class TestConfigServerConfigDataLoader
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
new SpringApplicationBuilder(TestConfig.class)
|
||||
.properties("spring.config.testconfigdata.enabled=true",
|
||||
"spring.application.name=foo",
|
||||
"spring.config.import=configserver:")
|
||||
.run(args);
|
||||
new SpringApplicationBuilder(TestConfig.class).properties("spring.config.testconfigdata.enabled=true",
|
||||
"spring.application.name=foo", "spring.config.import=configserver:").run(args);
|
||||
}
|
||||
|
||||
@SpringBootConfiguration
|
||||
|
||||
@@ -21,8 +21,8 @@ import org.springframework.web.client.RestTemplate;
|
||||
|
||||
public class TestConfigServerConfigDataLocation extends AbstractConfigDataLocation {
|
||||
|
||||
public TestConfigServerConfigDataLocation(RestTemplate restTemplate,
|
||||
ConfigClientProperties properties, boolean optional, Profiles profiles) {
|
||||
public TestConfigServerConfigDataLocation(RestTemplate restTemplate, ConfigClientProperties properties,
|
||||
boolean optional, Profiles profiles) {
|
||||
super(restTemplate, properties, optional, profiles);
|
||||
}
|
||||
|
||||
|
||||
@@ -40,23 +40,18 @@ public class TestConfigServerConfigDataLocationResolver
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isResolvable(ConfigDataLocationResolverContext context,
|
||||
String location) {
|
||||
public boolean isResolvable(ConfigDataLocationResolverContext context, String location) {
|
||||
if (!location.startsWith(getPrefix())) {
|
||||
return false;
|
||||
}
|
||||
Boolean enabled = context.getBinder()
|
||||
.bind("spring.config.testconfigdata.enabled", Boolean.class)
|
||||
.orElse(false);
|
||||
Boolean enabled = context.getBinder().bind("spring.config.testconfigdata.enabled", Boolean.class).orElse(false);
|
||||
return enabled;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected TestConfigServerConfigDataLocation createConfigDataLocation(
|
||||
boolean optional, Profiles profiles, ConfigClientProperties properties,
|
||||
RestTemplate restTemplate) {
|
||||
return new TestConfigServerConfigDataLocation(restTemplate, properties, optional,
|
||||
profiles);
|
||||
protected TestConfigServerConfigDataLocation createConfigDataLocation(boolean optional, Profiles profiles,
|
||||
ConfigClientProperties properties, RestTemplate restTemplate) {
|
||||
return new TestConfigServerConfigDataLocation(restTemplate, properties, optional, profiles);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -27,18 +27,15 @@ import org.springframework.util.MultiValueMap;
|
||||
* @author Dave Syer
|
||||
*
|
||||
*/
|
||||
public abstract class BasePropertyPathNotificationExtractor
|
||||
implements PropertyPathNotificationExtractor {
|
||||
public abstract class BasePropertyPathNotificationExtractor implements PropertyPathNotificationExtractor {
|
||||
|
||||
@Override
|
||||
public PropertyPathNotification extract(MultiValueMap<String, String> headers,
|
||||
Map<String, Object> request) {
|
||||
public PropertyPathNotification extract(MultiValueMap<String, String> headers, Map<String, Object> request) {
|
||||
if (requestBelongsToGitRepoManager(headers)) {
|
||||
if (request.get("commits") instanceof Collection) {
|
||||
Set<String> paths = new LinkedHashSet<>();
|
||||
@SuppressWarnings("unchecked")
|
||||
Collection<Map<String, Object>> commits = (Collection<Map<String, Object>>) request
|
||||
.get("commits");
|
||||
Collection<Map<String, Object>> commits = (Collection<Map<String, Object>>) request.get("commits");
|
||||
addPaths(paths, commits);
|
||||
if (!paths.isEmpty()) {
|
||||
return new PropertyPathNotification(paths.toArray(new String[0]));
|
||||
@@ -64,7 +61,6 @@ public abstract class BasePropertyPathNotificationExtractor
|
||||
}
|
||||
}
|
||||
|
||||
protected abstract boolean requestBelongsToGitRepoManager(
|
||||
MultiValueMap<String, String> headers);
|
||||
protected abstract boolean requestBelongsToGitRepoManager(MultiValueMap<String, String> headers);
|
||||
|
||||
}
|
||||
|
||||
@@ -31,19 +31,16 @@ import org.springframework.util.StringUtils;
|
||||
*
|
||||
*/
|
||||
@Order(Ordered.LOWEST_PRECEDENCE - 100)
|
||||
public class BitbucketPropertyPathNotificationExtractor
|
||||
implements PropertyPathNotificationExtractor {
|
||||
public class BitbucketPropertyPathNotificationExtractor implements PropertyPathNotificationExtractor {
|
||||
|
||||
@Override
|
||||
public PropertyPathNotification extract(MultiValueMap<String, String> headers,
|
||||
Map<String, Object> request) {
|
||||
public PropertyPathNotification extract(MultiValueMap<String, String> headers, Map<String, Object> request) {
|
||||
if (("repo:push".equals(headers.getFirst("X-Event-Key"))
|
||||
|| "pullrequest:fulfilled".equals(headers.getFirst("X-Event-Key")))
|
||||
&& StringUtils.hasText(headers.getFirst("X-Hook-UUID"))) {
|
||||
// Bitbucket cloud
|
||||
Object push = request.get("push");
|
||||
if (push instanceof Map
|
||||
&& ((Map<?, ?>) push).get("changes") instanceof Collection) {
|
||||
if (push instanceof Map && ((Map<?, ?>) push).get("changes") instanceof Collection) {
|
||||
// Bitbucket doesn't tell us the files that changed so this is a
|
||||
// broadcast to all apps
|
||||
return new PropertyPathNotification("application.yml");
|
||||
|
||||
@@ -33,13 +33,11 @@ import org.springframework.util.MultiValueMap;
|
||||
* @author Dave Syer
|
||||
*
|
||||
*/
|
||||
public class CompositePropertyPathNotificationExtractor
|
||||
implements PropertyPathNotificationExtractor {
|
||||
public class CompositePropertyPathNotificationExtractor implements PropertyPathNotificationExtractor {
|
||||
|
||||
private List<PropertyPathNotificationExtractor> extractors;
|
||||
|
||||
public CompositePropertyPathNotificationExtractor(
|
||||
List<PropertyPathNotificationExtractor> extractors) {
|
||||
public CompositePropertyPathNotificationExtractor(List<PropertyPathNotificationExtractor> extractors) {
|
||||
this.extractors = new ArrayList<>();
|
||||
if (extractors != null) {
|
||||
this.extractors.addAll(extractors);
|
||||
@@ -49,8 +47,7 @@ public class CompositePropertyPathNotificationExtractor
|
||||
}
|
||||
|
||||
@Override
|
||||
public PropertyPathNotification extract(MultiValueMap<String, String> headers,
|
||||
Map<String, Object> request) {
|
||||
public PropertyPathNotification extract(MultiValueMap<String, String> headers, Map<String, Object> request) {
|
||||
for (PropertyPathNotificationExtractor extractor : this.extractors) {
|
||||
PropertyPathNotification result = extractor.extract(headers, request);
|
||||
if (result != null) {
|
||||
@@ -61,12 +58,10 @@ public class CompositePropertyPathNotificationExtractor
|
||||
}
|
||||
|
||||
@Order(Ordered.LOWEST_PRECEDENCE - 200)
|
||||
private static class SimplePropertyPathNotificationExtractor
|
||||
implements PropertyPathNotificationExtractor {
|
||||
private static class SimplePropertyPathNotificationExtractor implements PropertyPathNotificationExtractor {
|
||||
|
||||
@Override
|
||||
public PropertyPathNotification extract(MultiValueMap<String, String> headers,
|
||||
Map<String, Object> request) {
|
||||
public PropertyPathNotification extract(MultiValueMap<String, String> headers, Map<String, Object> request) {
|
||||
Object object = request.get("path");
|
||||
if (object instanceof String) {
|
||||
return new PropertyPathNotification((String) object);
|
||||
|
||||
@@ -41,8 +41,7 @@ public class EnvironmentMonitorAutoConfiguration {
|
||||
|
||||
@Bean
|
||||
public PropertyPathEndpoint propertyPathEndpoint(BusProperties busProperties) {
|
||||
return new PropertyPathEndpoint(
|
||||
new CompositePropertyPathNotificationExtractor(this.extractors),
|
||||
return new PropertyPathEndpoint(new CompositePropertyPathNotificationExtractor(this.extractors),
|
||||
busProperties.getId());
|
||||
}
|
||||
|
||||
@@ -50,46 +49,43 @@ public class EnvironmentMonitorAutoConfiguration {
|
||||
protected static class PropertyPathNotificationExtractorConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnProperty(
|
||||
value = "spring.cloud.config.server.monitor.github.enabled",
|
||||
havingValue = "true", matchIfMissing = true)
|
||||
@ConditionalOnProperty(value = "spring.cloud.config.server.monitor.github.enabled", havingValue = "true",
|
||||
matchIfMissing = true)
|
||||
public GithubPropertyPathNotificationExtractor githubPropertyPathNotificationExtractor() {
|
||||
return new GithubPropertyPathNotificationExtractor();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnProperty(
|
||||
value = "spring.cloud.config.server.monitor.gitlab.enabled",
|
||||
havingValue = "true", matchIfMissing = true)
|
||||
@ConditionalOnProperty(value = "spring.cloud.config.server.monitor.gitlab.enabled", havingValue = "true",
|
||||
matchIfMissing = true)
|
||||
public GitlabPropertyPathNotificationExtractor gitlabPropertyPathNotificationExtractor() {
|
||||
return new GitlabPropertyPathNotificationExtractor();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnProperty(
|
||||
value = "spring.cloud.config.server.monitor.bitbucket.enabled",
|
||||
havingValue = "true", matchIfMissing = true)
|
||||
@ConditionalOnProperty(value = "spring.cloud.config.server.monitor.bitbucket.enabled", havingValue = "true",
|
||||
matchIfMissing = true)
|
||||
public BitbucketPropertyPathNotificationExtractor bitbucketPropertyPathNotificationExtractor() {
|
||||
return new BitbucketPropertyPathNotificationExtractor();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnProperty(value = "spring.cloud.config.server.monitor.gitea.enabled",
|
||||
havingValue = "true", matchIfMissing = true)
|
||||
@ConditionalOnProperty(value = "spring.cloud.config.server.monitor.gitea.enabled", havingValue = "true",
|
||||
matchIfMissing = true)
|
||||
public GiteaPropertyPathNotificationExtractor giteaPropertyPathNotificationExtractor() {
|
||||
return new GiteaPropertyPathNotificationExtractor();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnProperty(value = "spring.cloud.config.server.monitor.gitee.enabled",
|
||||
havingValue = "true", matchIfMissing = true)
|
||||
@ConditionalOnProperty(value = "spring.cloud.config.server.monitor.gitee.enabled", havingValue = "true",
|
||||
matchIfMissing = true)
|
||||
public GiteePropertyPathNotificationExtractor giteePropertyPathNotificationExtractor() {
|
||||
return new GiteePropertyPathNotificationExtractor();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnProperty(value = "spring.cloud.config.server.monitor.gogs.enabled",
|
||||
havingValue = "true", matchIfMissing = true)
|
||||
@ConditionalOnProperty(value = "spring.cloud.config.server.monitor.gogs.enabled", havingValue = "true",
|
||||
matchIfMissing = true)
|
||||
public GogsPropertyPathNotificationExtractor gogsPropertyPathNotificationExtractor() {
|
||||
return new GogsPropertyPathNotificationExtractor();
|
||||
}
|
||||
|
||||
@@ -165,8 +165,7 @@ public class FileMonitorConfiguration implements SmartLifecycle, ResourceLoaderA
|
||||
this.watcher.close();
|
||||
}
|
||||
catch (IOException e) {
|
||||
log.error("Failed to close watcher for " + this.directory.toString(),
|
||||
e);
|
||||
log.error("Failed to close watcher for " + this.directory.toString(), e);
|
||||
}
|
||||
}
|
||||
this.running = false;
|
||||
@@ -182,8 +181,8 @@ public class FileMonitorConfiguration implements SmartLifecycle, ResourceLoaderA
|
||||
@Scheduled(fixedRateString = "${spring.cloud.config.server.monitor.fixedDelay:5000}")
|
||||
public void poll() {
|
||||
for (File file : filesFromEvents()) {
|
||||
this.endpoint.notifyByPath(new HttpHeaders(), Collections
|
||||
.<String, Object>singletonMap("path", file.getAbsolutePath()));
|
||||
this.endpoint.notifyByPath(new HttpHeaders(),
|
||||
Collections.<String, Object>singletonMap("path", file.getAbsolutePath()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -195,8 +194,7 @@ public class FileMonitorConfiguration implements SmartLifecycle, ResourceLoaderA
|
||||
for (AbstractScmEnvironmentRepository repository : scmRepositories) {
|
||||
repositoryUri = repository.getUri();
|
||||
Resource resource = this.resourceLoader.getResource(repositoryUri);
|
||||
if (resource instanceof FileSystemResource
|
||||
|| resource instanceof FileUrlResource) {
|
||||
if (resource instanceof FileSystemResource || resource instanceof FileUrlResource) {
|
||||
paths.add(Paths.get(resource.getURI()));
|
||||
}
|
||||
}
|
||||
@@ -235,14 +233,14 @@ public class FileMonitorConfiguration implements SmartLifecycle, ResourceLoaderA
|
||||
if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE
|
||||
|| event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
|
||||
Path item = (Path) event.context();
|
||||
File file = new File(((Path) key.watchable()).toAbsolutePath()
|
||||
+ File.separator + item.getFileName());
|
||||
File file = new File(
|
||||
((Path) key.watchable()).toAbsolutePath() + File.separator + item.getFileName());
|
||||
if (file.isDirectory()) {
|
||||
files.addAll(walkDirectory(file.toPath()));
|
||||
}
|
||||
else {
|
||||
if (!file.getPath().contains(".git") && !PatternMatchUtils
|
||||
.simpleMatch(this.excludes, file.getName())) {
|
||||
if (!file.getPath().contains(".git")
|
||||
&& !PatternMatchUtils.simpleMatch(this.excludes, file.getName())) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Watch Event: " + event.kind() + ": " + file);
|
||||
}
|
||||
@@ -252,8 +250,7 @@ public class FileMonitorConfiguration implements SmartLifecycle, ResourceLoaderA
|
||||
}
|
||||
else if (event.kind() == StandardWatchEventKinds.OVERFLOW) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Watch Event: " + event.kind() + ": context: "
|
||||
+ event.context());
|
||||
log.debug("Watch Event: " + event.kind() + ": context: " + event.context());
|
||||
}
|
||||
if (event.context() != null && event.context() instanceof Path) {
|
||||
files.addAll(walkDirectory((Path) event.context()));
|
||||
@@ -266,8 +263,7 @@ public class FileMonitorConfiguration implements SmartLifecycle, ResourceLoaderA
|
||||
}
|
||||
else {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Watch Event: " + event.kind() + ": context: "
|
||||
+ event.context());
|
||||
log.debug("Watch Event: " + event.kind() + ": context: " + event.context());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -284,8 +280,7 @@ public class FileMonitorConfiguration implements SmartLifecycle, ResourceLoaderA
|
||||
Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
|
||||
|
||||
@Override
|
||||
public FileVisitResult preVisitDirectory(Path dir,
|
||||
BasicFileAttributes attrs) throws IOException {
|
||||
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
|
||||
FileVisitResult fileVisitResult = super.preVisitDirectory(dir, attrs);
|
||||
// No need to monitor the git metadata
|
||||
if (dir.toFile().getPath().contains(".git")) {
|
||||
@@ -296,8 +291,7 @@ public class FileMonitorConfiguration implements SmartLifecycle, ResourceLoaderA
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
|
||||
throws IOException {
|
||||
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
|
||||
FileVisitResult fileVisitResult = super.visitFile(file, attrs);
|
||||
walkedFiles.add(file.toFile());
|
||||
return fileVisitResult;
|
||||
@@ -316,8 +310,7 @@ public class FileMonitorConfiguration implements SmartLifecycle, ResourceLoaderA
|
||||
log.debug("registering: " + dir + " for file creation events");
|
||||
}
|
||||
try {
|
||||
dir.register(this.watcher, StandardWatchEventKinds.ENTRY_CREATE,
|
||||
StandardWatchEventKinds.ENTRY_MODIFY);
|
||||
dir.register(this.watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY);
|
||||
}
|
||||
catch (IOException e) {
|
||||
throw e;
|
||||
|
||||
@@ -29,8 +29,7 @@ import org.springframework.util.MultiValueMap;
|
||||
*
|
||||
*/
|
||||
@Order(Ordered.LOWEST_PRECEDENCE - 100)
|
||||
public class GiteaPropertyPathNotificationExtractor
|
||||
extends BasePropertyPathNotificationExtractor {
|
||||
public class GiteaPropertyPathNotificationExtractor extends BasePropertyPathNotificationExtractor {
|
||||
|
||||
private static final String HEADERS_KEY = "X-Gitea-Event";
|
||||
|
||||
@@ -47,8 +46,7 @@ public class GiteaPropertyPathNotificationExtractor
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean requestBelongsToGitRepoManager(
|
||||
MultiValueMap<String, String> headers) {
|
||||
protected boolean requestBelongsToGitRepoManager(MultiValueMap<String, String> headers) {
|
||||
return HEADERS_VALUE.equals(headers.getFirst(HEADERS_KEY));
|
||||
}
|
||||
|
||||
|
||||
@@ -25,16 +25,14 @@ import org.springframework.util.MultiValueMap;
|
||||
*
|
||||
*/
|
||||
@Order(Ordered.LOWEST_PRECEDENCE - 100)
|
||||
public class GiteePropertyPathNotificationExtractor
|
||||
extends BasePropertyPathNotificationExtractor {
|
||||
public class GiteePropertyPathNotificationExtractor extends BasePropertyPathNotificationExtractor {
|
||||
|
||||
private static final String HEADERS_KEY = "x-git-oschina-event";
|
||||
|
||||
private static final String HEADERS_VALUE = "Push Hook";
|
||||
|
||||
@Override
|
||||
protected boolean requestBelongsToGitRepoManager(
|
||||
MultiValueMap<String, String> headers) {
|
||||
protected boolean requestBelongsToGitRepoManager(MultiValueMap<String, String> headers) {
|
||||
return HEADERS_VALUE.equals(headers.getFirst(HEADERS_KEY));
|
||||
}
|
||||
|
||||
|
||||
@@ -25,12 +25,10 @@ import org.springframework.util.MultiValueMap;
|
||||
*
|
||||
*/
|
||||
@Order(Ordered.LOWEST_PRECEDENCE - 300)
|
||||
public class GithubPropertyPathNotificationExtractor
|
||||
extends BasePropertyPathNotificationExtractor {
|
||||
public class GithubPropertyPathNotificationExtractor extends BasePropertyPathNotificationExtractor {
|
||||
|
||||
@Override
|
||||
protected boolean requestBelongsToGitRepoManager(
|
||||
MultiValueMap<String, String> headers) {
|
||||
protected boolean requestBelongsToGitRepoManager(MultiValueMap<String, String> headers) {
|
||||
return "push".equals(headers.getFirst("X-Github-Event"));
|
||||
}
|
||||
|
||||
|
||||
@@ -25,12 +25,10 @@ import org.springframework.util.MultiValueMap;
|
||||
*
|
||||
*/
|
||||
@Order(Ordered.LOWEST_PRECEDENCE - 100)
|
||||
public class GitlabPropertyPathNotificationExtractor
|
||||
extends BasePropertyPathNotificationExtractor {
|
||||
public class GitlabPropertyPathNotificationExtractor extends BasePropertyPathNotificationExtractor {
|
||||
|
||||
@Override
|
||||
protected boolean requestBelongsToGitRepoManager(
|
||||
MultiValueMap<String, String> headers) {
|
||||
protected boolean requestBelongsToGitRepoManager(MultiValueMap<String, String> headers) {
|
||||
return "Push Hook".equals(headers.getFirst("X-Gitlab-Event"));
|
||||
}
|
||||
|
||||
|
||||
@@ -25,16 +25,14 @@ import org.springframework.util.MultiValueMap;
|
||||
*
|
||||
*/
|
||||
@Order(Ordered.LOWEST_PRECEDENCE - 100)
|
||||
public class GogsPropertyPathNotificationExtractor
|
||||
extends BasePropertyPathNotificationExtractor {
|
||||
public class GogsPropertyPathNotificationExtractor extends BasePropertyPathNotificationExtractor {
|
||||
|
||||
private static final String HEADERS_KEY = "X-Gogs-Event";
|
||||
|
||||
private static final String HEADERS_VALUE = "push";
|
||||
|
||||
@Override
|
||||
protected boolean requestBelongsToGitRepoManager(
|
||||
MultiValueMap<String, String> headers) {
|
||||
protected boolean requestBelongsToGitRepoManager(MultiValueMap<String, String> headers) {
|
||||
return HEADERS_VALUE.equals(headers.getFirst(HEADERS_KEY));
|
||||
}
|
||||
|
||||
|
||||
@@ -57,8 +57,7 @@ public class PropertyPathEndpoint implements ApplicationEventPublisherAware {
|
||||
|
||||
private String busId;
|
||||
|
||||
public PropertyPathEndpoint(PropertyPathNotificationExtractor extractor,
|
||||
String busId) {
|
||||
public PropertyPathEndpoint(PropertyPathNotificationExtractor extractor, String busId) {
|
||||
this.extractor = extractor;
|
||||
this.busId = busId;
|
||||
}
|
||||
@@ -68,14 +67,12 @@ public class PropertyPathEndpoint implements ApplicationEventPublisherAware {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setApplicationEventPublisher(
|
||||
ApplicationEventPublisher applicationEventPublisher) {
|
||||
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
|
||||
this.applicationEventPublisher = applicationEventPublisher;
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST)
|
||||
public Set<String> notifyByPath(@RequestHeader HttpHeaders headers,
|
||||
@RequestBody Map<String, Object> request) {
|
||||
public Set<String> notifyByPath(@RequestHeader HttpHeaders headers, @RequestBody Map<String, Object> request) {
|
||||
PropertyPathNotification notification = this.extractor.extract(headers, request);
|
||||
if (notification != null) {
|
||||
|
||||
@@ -87,8 +84,8 @@ public class PropertyPathEndpoint implements ApplicationEventPublisherAware {
|
||||
if (this.applicationEventPublisher != null) {
|
||||
for (String service : services) {
|
||||
log.info("Refresh for: " + service);
|
||||
this.applicationEventPublisher.publishEvent(
|
||||
new RefreshRemoteApplicationEvent(this, this.busId, service));
|
||||
this.applicationEventPublisher
|
||||
.publishEvent(new RefreshRemoteApplicationEvent(this, this.busId, service));
|
||||
}
|
||||
return services;
|
||||
}
|
||||
@@ -97,10 +94,8 @@ public class PropertyPathEndpoint implements ApplicationEventPublisherAware {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST,
|
||||
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
|
||||
public Set<String> notifyByForm(@RequestHeader HttpHeaders headers,
|
||||
@RequestParam("path") List<String> request) {
|
||||
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
|
||||
public Set<String> notifyByForm(@RequestHeader HttpHeaders headers, @RequestParam("path") List<String> request) {
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
String key = "path";
|
||||
map.put(key, request);
|
||||
@@ -110,8 +105,7 @@ public class PropertyPathEndpoint implements ApplicationEventPublisherAware {
|
||||
private Set<String> guessServiceName(String path) {
|
||||
Set<String> services = new LinkedHashSet<>();
|
||||
if (path != null) {
|
||||
String stem = StringUtils.stripFilenameExtension(
|
||||
StringUtils.getFilename(StringUtils.cleanPath(path)));
|
||||
String stem = StringUtils.stripFilenameExtension(StringUtils.getFilename(StringUtils.cleanPath(path)));
|
||||
// TODO: correlate with service registry
|
||||
int index = stem.indexOf("-");
|
||||
while (index >= 0) {
|
||||
|
||||
@@ -70,8 +70,7 @@ public class PropertyPathNotification {
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return "PropertyPathNotification(paths="
|
||||
+ java.util.Arrays.deepToString(this.getPaths()) + ")";
|
||||
return "PropertyPathNotification(paths=" + java.util.Arrays.deepToString(this.getPaths()) + ")";
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -30,7 +30,6 @@ import org.springframework.util.MultiValueMap;
|
||||
*/
|
||||
public interface PropertyPathNotificationExtractor {
|
||||
|
||||
PropertyPathNotification extract(MultiValueMap<String, String> headers,
|
||||
Map<String, Object> payload);
|
||||
PropertyPathNotification extract(MultiValueMap<String, String> headers, Map<String, Object> payload);
|
||||
|
||||
}
|
||||
|
||||
@@ -104,8 +104,7 @@ public class BitbucketPropertyPathNotificationExtractorTests {
|
||||
assertThat(extracted).isNull();
|
||||
}
|
||||
|
||||
private void assertNotExtracted(String path, String eventKey)
|
||||
throws java.io.IOException {
|
||||
private void assertNotExtracted(String path, String eventKey) throws java.io.IOException {
|
||||
Map<String, Object> value = readPayload(path);
|
||||
setHeaders(eventKey);
|
||||
PropertyPathNotification extracted = this.extractor.extract(this.headers, value);
|
||||
@@ -125,8 +124,7 @@ public class BitbucketPropertyPathNotificationExtractorTests {
|
||||
@Test
|
||||
public void bitbucketServerSamplePullRequest() throws Exception {
|
||||
// https://confluence.atlassian.com/bitbucketserver/event-payload-938025882.html
|
||||
Map<String, Object> value = readPayload(
|
||||
"pathsamples/bitbucketserver-prmerged.json");
|
||||
Map<String, Object> value = readPayload("pathsamples/bitbucketserver-prmerged.json");
|
||||
setServerHeaders("pr:merged");
|
||||
PropertyPathNotification extracted = this.extractor.extract(this.headers, value);
|
||||
assertThat(extracted).isNotNull();
|
||||
@@ -140,8 +138,7 @@ public class BitbucketPropertyPathNotificationExtractorTests {
|
||||
|
||||
@Test
|
||||
public void notAPushOrPullRequestServer() throws Exception {
|
||||
assertNotExtractedServer("pathsamples/bitbucketserver.json",
|
||||
"repo:comment:added");
|
||||
assertNotExtractedServer("pathsamples/bitbucketserver.json", "repo:comment:added");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -156,15 +153,13 @@ public class BitbucketPropertyPathNotificationExtractorTests {
|
||||
@Test
|
||||
public void missingChangesServer() throws Exception {
|
||||
// https://confluence.atlassian.com/bitbucketserver/event-payload-938025882.html
|
||||
Map<String, Object> value = readPayload(
|
||||
"pathsamples/bitbucketserver-invalid.json");
|
||||
Map<String, Object> value = readPayload("pathsamples/bitbucketserver-invalid.json");
|
||||
setServerHeaders("repo:refs_changed");
|
||||
PropertyPathNotification extracted = this.extractor.extract(this.headers, value);
|
||||
assertThat(extracted).isNull();
|
||||
}
|
||||
|
||||
private void assertNotExtractedServer(String path, String eventKey)
|
||||
throws java.io.IOException {
|
||||
private void assertNotExtractedServer(String path, String eventKey) throws java.io.IOException {
|
||||
Map<String, Object> value = readPayload(path);
|
||||
setServerHeaders(eventKey);
|
||||
PropertyPathNotification extracted = this.extractor.extract(this.headers, value);
|
||||
|
||||
@@ -35,9 +35,8 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
*/
|
||||
public class CompositePropertyPathNotificationExtractorTests {
|
||||
|
||||
private CompositePropertyPathNotificationExtractor extractor = new CompositePropertyPathNotificationExtractor(
|
||||
Arrays.asList(new GitlabPropertyPathNotificationExtractor(),
|
||||
new GithubPropertyPathNotificationExtractor()));
|
||||
private CompositePropertyPathNotificationExtractor extractor = new CompositePropertyPathNotificationExtractor(Arrays
|
||||
.asList(new GitlabPropertyPathNotificationExtractor(), new GithubPropertyPathNotificationExtractor()));
|
||||
|
||||
private HttpHeaders headers = new HttpHeaders();
|
||||
|
||||
@@ -64,14 +63,12 @@ public class CompositePropertyPathNotificationExtractorTests {
|
||||
PropertyPathNotification extracted = this.extractor.extract(this.headers, value);
|
||||
assertThat(extracted).isNotNull();
|
||||
String[] paths = extracted.getPaths();
|
||||
assertThat(paths).as("paths was wrong").contains("oldapp.yml",
|
||||
"newapp.properties", "application.yml");
|
||||
assertThat(paths).as("paths was wrong").contains("oldapp.yml", "newapp.properties", "application.yml");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void fallback() throws Exception {
|
||||
Map<String, Object> value = Collections.<String, Object>singletonMap("path",
|
||||
"foo");
|
||||
Map<String, Object> value = Collections.<String, Object>singletonMap("path", "foo");
|
||||
PropertyPathNotification extracted = this.extractor.extract(this.headers, value);
|
||||
assertThat(extracted).isNotNull();
|
||||
assertThat(extracted.getPaths()[0]).isEqualTo("foo");
|
||||
|
||||
@@ -40,30 +40,24 @@ public class EnvironmentMonitorAutoConfigurationTests {
|
||||
|
||||
@Test
|
||||
public void testExtractorsCount() {
|
||||
ConfigurableApplicationContext context = new SpringApplicationBuilder(
|
||||
BusConfig.class, EnvironmentMonitorAutoConfiguration.class,
|
||||
ServletWebServerFactoryAutoConfiguration.class, ServerProperties.class,
|
||||
PropertyPlaceholderAutoConfiguration.class).properties("server.port=-1")
|
||||
.run();
|
||||
ConfigurableApplicationContext context = new SpringApplicationBuilder(BusConfig.class,
|
||||
EnvironmentMonitorAutoConfiguration.class, ServletWebServerFactoryAutoConfiguration.class,
|
||||
ServerProperties.class, PropertyPlaceholderAutoConfiguration.class).properties("server.port=-1").run();
|
||||
PropertyPathEndpoint endpoint = context.getBean(PropertyPathEndpoint.class);
|
||||
assertThat(((Collection<?>) ReflectionTestUtils.getField(
|
||||
ReflectionTestUtils.getField(endpoint, "extractor"), "extractors"))
|
||||
.size()).isEqualTo(7);
|
||||
assertThat(((Collection<?>) ReflectionTestUtils.getField(ReflectionTestUtils.getField(endpoint, "extractor"),
|
||||
"extractors")).size()).isEqualTo(7);
|
||||
context.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCanAddCustomPropertyPathNotificationExtractor() {
|
||||
ConfigurableApplicationContext context = new SpringApplicationBuilder(
|
||||
BusConfig.class, CustomPropertyPathNotificationExtractorConfig.class,
|
||||
EnvironmentMonitorAutoConfiguration.class,
|
||||
ConfigurableApplicationContext context = new SpringApplicationBuilder(BusConfig.class,
|
||||
CustomPropertyPathNotificationExtractorConfig.class, EnvironmentMonitorAutoConfiguration.class,
|
||||
ServletWebServerFactoryAutoConfiguration.class, ServerProperties.class,
|
||||
PropertyPlaceholderAutoConfiguration.class).properties("server.port=-1")
|
||||
.run();
|
||||
PropertyPlaceholderAutoConfiguration.class).properties("server.port=-1").run();
|
||||
PropertyPathEndpoint endpoint = context.getBean(PropertyPathEndpoint.class);
|
||||
assertThat(((Collection<?>) ReflectionTestUtils.getField(
|
||||
ReflectionTestUtils.getField(endpoint, "extractor"), "extractors"))
|
||||
.size()).isEqualTo(8);
|
||||
assertThat(((Collection<?>) ReflectionTestUtils.getField(ReflectionTestUtils.getField(endpoint, "extractor"),
|
||||
"extractors")).size()).isEqualTo(8);
|
||||
context.close();
|
||||
}
|
||||
|
||||
|
||||
@@ -79,8 +79,7 @@ public class FileMonitorConfigurationTest {
|
||||
public void testStart_withNativeEnvironmentRepository() {
|
||||
// given
|
||||
NativeEnvironmentRepository repository = createNativeEnvironmentRepository();
|
||||
ReflectionTestUtils.setField(fileMonitorConfiguration,
|
||||
"nativeEnvironmentRepository", repository);
|
||||
ReflectionTestUtils.setField(fileMonitorConfiguration, "nativeEnvironmentRepository", repository);
|
||||
|
||||
// when
|
||||
fileMonitorConfiguration.start();
|
||||
@@ -92,8 +91,7 @@ public class FileMonitorConfigurationTest {
|
||||
@Test
|
||||
public void testStart_withOneScmRepository() {
|
||||
// given
|
||||
AbstractScmEnvironmentRepository repository = createScmEnvironmentRepository(
|
||||
SAMPLE_PATH);
|
||||
AbstractScmEnvironmentRepository repository = createScmEnvironmentRepository(SAMPLE_PATH);
|
||||
addScmRepository(repository);
|
||||
|
||||
// when
|
||||
@@ -106,10 +104,8 @@ public class FileMonitorConfigurationTest {
|
||||
@Test
|
||||
public void testStart_withTwoScmRepositories() {
|
||||
// given
|
||||
AbstractScmEnvironmentRepository repository = createScmEnvironmentRepository(
|
||||
SAMPLE_PATH);
|
||||
AbstractScmEnvironmentRepository secondRepository = createScmEnvironmentRepository(
|
||||
"anotherPath");
|
||||
AbstractScmEnvironmentRepository repository = createScmEnvironmentRepository(SAMPLE_PATH);
|
||||
AbstractScmEnvironmentRepository secondRepository = createScmEnvironmentRepository("anotherPath");
|
||||
addScmRepository(repository);
|
||||
addScmRepository(secondRepository);
|
||||
|
||||
@@ -123,8 +119,7 @@ public class FileMonitorConfigurationTest {
|
||||
@Test
|
||||
public void testStart_withOneFileUrlScmRepository() {
|
||||
// given
|
||||
AbstractScmEnvironmentRepository repository = createScmEnvironmentRepository(
|
||||
SAMPLE_FILE_URL);
|
||||
AbstractScmEnvironmentRepository repository = createScmEnvironmentRepository(SAMPLE_FILE_URL);
|
||||
addScmRepository(repository);
|
||||
|
||||
// when
|
||||
@@ -137,10 +132,8 @@ public class FileMonitorConfigurationTest {
|
||||
@Test
|
||||
public void testStart_withTwoMixedPathAndFileUrlScmRepositories() {
|
||||
// given
|
||||
AbstractScmEnvironmentRepository repository = createScmEnvironmentRepository(
|
||||
SAMPLE_PATH);
|
||||
AbstractScmEnvironmentRepository secondRepository = createScmEnvironmentRepository(
|
||||
SAMPLE_FILE_URL);
|
||||
AbstractScmEnvironmentRepository repository = createScmEnvironmentRepository(SAMPLE_PATH);
|
||||
AbstractScmEnvironmentRepository secondRepository = createScmEnvironmentRepository(SAMPLE_FILE_URL);
|
||||
addScmRepository(repository);
|
||||
addScmRepository(secondRepository);
|
||||
|
||||
@@ -153,8 +146,7 @@ public class FileMonitorConfigurationTest {
|
||||
|
||||
private void addScmRepository(AbstractScmEnvironmentRepository... repository) {
|
||||
repositories.addAll(Arrays.asList(repository));
|
||||
ReflectionTestUtils.setField(fileMonitorConfiguration, "scmRepositories",
|
||||
repositories);
|
||||
ReflectionTestUtils.setField(fileMonitorConfiguration, "scmRepositories", repositories);
|
||||
}
|
||||
|
||||
private NativeEnvironmentRepository createNativeEnvironmentRepository() {
|
||||
@@ -183,8 +175,7 @@ public class FileMonitorConfigurationTest {
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private Set<Path> getDirectory() {
|
||||
return (Set<Path>) ReflectionTestUtils.getField(fileMonitorConfiguration,
|
||||
"directory");
|
||||
return (Set<Path>) ReflectionTestUtils.getField(fileMonitorConfiguration, "directory");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -48,8 +48,7 @@ public class GitlabPropertyPathNotificationExtractorTests {
|
||||
PropertyPathNotification extracted = this.extractor.extract(this.headers, value);
|
||||
assertThat(extracted).isNotNull();
|
||||
String[] paths = extracted.getPaths();
|
||||
assertThat(paths).as("paths was wrong").contains("oldapp.yml",
|
||||
"newapp.properties", "application.yml");
|
||||
assertThat(paths).as("paths was wrong").contains("oldapp.yml", "newapp.properties", "application.yml");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -35,8 +35,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
public class PropertyPathEndpointTests {
|
||||
|
||||
private PropertyPathEndpoint endpoint = new PropertyPathEndpoint(
|
||||
new CompositePropertyPathNotificationExtractor(Collections.emptyList()),
|
||||
"abc1");
|
||||
new CompositePropertyPathNotificationExtractor(Collections.emptyList()), "abc1");
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
@@ -52,9 +51,7 @@ public class PropertyPathEndpointTests {
|
||||
|
||||
@Test
|
||||
public void testNotifyByForm() {
|
||||
assertThat(
|
||||
this.endpoint.notifyByForm(new HttpHeaders(), new ArrayList<>()).size())
|
||||
.isEqualTo(0);
|
||||
assertThat(this.endpoint.notifyByForm(new HttpHeaders(), new ArrayList<>()).size()).isEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -62,59 +59,46 @@ public class PropertyPathEndpointTests {
|
||||
List<String> request = new ArrayList<>();
|
||||
request.add("/foo/bar.properties");
|
||||
request.add("/application.properties");
|
||||
assertThat(this.endpoint.notifyByForm(new HttpHeaders(), request).toString())
|
||||
.isEqualTo("[bar, *]");
|
||||
assertThat(this.endpoint.notifyByForm(new HttpHeaders(), request).toString()).isEqualTo("[bar, *]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNotifyAll() {
|
||||
assertThat(
|
||||
this.endpoint
|
||||
.notifyByPath(new HttpHeaders(),
|
||||
Collections.singletonMap("path", "application.yml"))
|
||||
.toString()).isEqualTo("[*]");
|
||||
assertThat(this.endpoint.notifyByPath(new HttpHeaders(), Collections.singletonMap("path", "application.yml"))
|
||||
.toString()).isEqualTo("[*]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNotifyAllWithProfile() {
|
||||
assertThat(this.endpoint
|
||||
.notifyByPath(new HttpHeaders(),
|
||||
Collections.singletonMap("path", "application-local.yml"))
|
||||
.toString()).isEqualTo("[*:local]");
|
||||
.notifyByPath(new HttpHeaders(), Collections.singletonMap("path", "application-local.yml")).toString())
|
||||
.isEqualTo("[*:local]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNotifyOne() {
|
||||
assertThat(this.endpoint.notifyByPath(new HttpHeaders(),
|
||||
Collections.singletonMap("path", "foo.yml")).toString())
|
||||
assertThat(
|
||||
this.endpoint.notifyByPath(new HttpHeaders(), Collections.singletonMap("path", "foo.yml")).toString())
|
||||
.isEqualTo("[foo]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNotifyOneWithWindowsPath() {
|
||||
assertThat(this.endpoint
|
||||
.notifyByPath(new HttpHeaders(),
|
||||
Collections.singletonMap("path", "C:\\config\\foo.yml"))
|
||||
.toString()).isEqualTo("[foo]");
|
||||
.notifyByPath(new HttpHeaders(), Collections.singletonMap("path", "C:\\config\\foo.yml")).toString())
|
||||
.isEqualTo("[foo]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNotifyOneWithProfile() {
|
||||
assertThat(
|
||||
this.endpoint
|
||||
.notifyByPath(new HttpHeaders(),
|
||||
Collections.singletonMap("path", "foo-local.yml"))
|
||||
.toString()).isEqualTo("[foo:local, foo-local]");
|
||||
assertThat(this.endpoint.notifyByPath(new HttpHeaders(), Collections.singletonMap("path", "foo-local.yml"))
|
||||
.toString()).isEqualTo("[foo:local, foo-local]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNotifyMultiDash() {
|
||||
assertThat(
|
||||
this.endpoint
|
||||
.notifyByPath(new HttpHeaders(),
|
||||
Collections.singletonMap("path", "foo-local-dev.yml"))
|
||||
.toString()).isEqualTo(
|
||||
"[foo:local-dev, foo-local:dev, foo-local-dev]");
|
||||
assertThat(this.endpoint.notifyByPath(new HttpHeaders(), Collections.singletonMap("path", "foo-local-dev.yml"))
|
||||
.toString()).isEqualTo("[foo:local-dev, foo-local:dev, foo-local-dev]");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -51,10 +51,8 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
|
||||
// Normally spring.cloud.config.enabled:true is the default but since we have the
|
||||
// config
|
||||
// server on the classpath we need to set it explicitly
|
||||
properties = { "spring.cloud.config.enabled:true", "",
|
||||
"spring.config.use-legacy-processing=true",
|
||||
"management.security.enabled=false",
|
||||
"management.endpoints.web.exposure.include=*" },
|
||||
properties = { "spring.cloud.config.enabled:true", "", "spring.config.use-legacy-processing=true",
|
||||
"management.security.enabled=false", "management.endpoints.web.exposure.include=*" },
|
||||
webEnvironment = RANDOM_PORT)
|
||||
public class ApplicationBootstrapTests {
|
||||
|
||||
@@ -70,17 +68,13 @@ public class ApplicationBootstrapTests {
|
||||
@BeforeClass
|
||||
public static void startConfigServer() throws IOException {
|
||||
System.setProperty("spring.cloud.bootstrap.name", "bootstrapservercomposite");
|
||||
String baseDir = ConfigServerTestUtils
|
||||
.getBaseDirectory("spring-cloud-config-sample");
|
||||
String repo = ConfigServerTestUtils.prepareLocalRepo(baseDir, "target/repos",
|
||||
"config-repo", "target/config");
|
||||
String baseDir = ConfigServerTestUtils.getBaseDirectory("spring-cloud-config-sample");
|
||||
String repo = ConfigServerTestUtils.prepareLocalRepo(baseDir, "target/repos", "config-repo", "target/config");
|
||||
System.setProperty("repo1", repo);
|
||||
server = SpringApplication.run(
|
||||
org.springframework.cloud.config.server.ConfigServerApplication.class,
|
||||
server = SpringApplication.run(org.springframework.cloud.config.server.ConfigServerApplication.class,
|
||||
// FIXME: configdata why is use legacy needed here and above?
|
||||
"--spring.config.use-legacy-processing=true",
|
||||
"--server.port=" + configPort, "--spring.config.name=compositeserver",
|
||||
"--repo1=" + repo);
|
||||
"--spring.config.use-legacy-processing=true", "--server.port=" + configPort,
|
||||
"--spring.config.name=compositeserver", "--repo1=" + repo);
|
||||
System.setProperty("config.port", "" + configPort);
|
||||
}
|
||||
|
||||
@@ -103,8 +97,8 @@ public class ApplicationBootstrapTests {
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void contextLoads() {
|
||||
Map res = new TestRestTemplate().getForObject(
|
||||
"http://localhost:" + this.port + BASE_PATH + "/env/info.foo", Map.class);
|
||||
Map res = new TestRestTemplate().getForObject("http://localhost:" + this.port + BASE_PATH + "/env/info.foo",
|
||||
Map.class);
|
||||
assertThat(res).containsKey("propertySources");
|
||||
Map<String, Object> property = (Map<String, Object>) res.get("property");
|
||||
assertThat(property).containsEntry("value", "bar");
|
||||
|
||||
@@ -29,16 +29,13 @@ public class ApplicationFailFastTests {
|
||||
@Test
|
||||
public void contextFails() {
|
||||
try {
|
||||
new SpringApplicationBuilder().sources(Application.class).run(
|
||||
"--spring.config.use-legacy-processing=true", "--server.port=0",
|
||||
"--spring.cloud.config.enabled=true",
|
||||
"--spring.cloud.config.fail-fast=true",
|
||||
new SpringApplicationBuilder().sources(Application.class).run("--spring.config.use-legacy-processing=true",
|
||||
"--server.port=0", "--spring.cloud.config.enabled=true", "--spring.cloud.config.fail-fast=true",
|
||||
"--spring.cloud.config.uri=http://serverhostdoesnotexist:1234");
|
||||
fail("failFast option did not produce an exception");
|
||||
}
|
||||
catch (Exception e) {
|
||||
assertThat(e.getMessage().contains("fail fast"))
|
||||
.as("Exception not caused by fail fast").isTrue();
|
||||
assertThat(e.getMessage().contains("fail fast")).as("Exception not caused by fail fast").isTrue();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -44,8 +44,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
|
||||
// server on the classpath we need to set it explicitly
|
||||
properties = { "spring.cloud.config.enabled:true",
|
||||
// FIXME: configdata why is this needed here?
|
||||
"spring.config.use-legacy-processing=true",
|
||||
"management.security.enabled=false",
|
||||
"spring.config.use-legacy-processing=true", "management.security.enabled=false",
|
||||
"management.endpoints.web.exposure.include=*" },
|
||||
webEnvironment = RANDOM_PORT)
|
||||
public class ApplicationTests {
|
||||
@@ -61,12 +60,9 @@ public class ApplicationTests {
|
||||
|
||||
@BeforeClass
|
||||
public static void startConfigServer() throws IOException {
|
||||
String baseDir = ConfigServerTestUtils
|
||||
.getBaseDirectory("spring-cloud-config-sample");
|
||||
String repo = ConfigServerTestUtils.prepareLocalRepo(baseDir, "target/repos",
|
||||
"config-repo", "target/config");
|
||||
server = SpringApplication.run(
|
||||
org.springframework.cloud.config.server.ConfigServerApplication.class,
|
||||
String baseDir = ConfigServerTestUtils.getBaseDirectory("spring-cloud-config-sample");
|
||||
String repo = ConfigServerTestUtils.prepareLocalRepo(baseDir, "target/repos", "config-repo", "target/config");
|
||||
server = SpringApplication.run(org.springframework.cloud.config.server.ConfigServerApplication.class,
|
||||
"--server.port=" + configPort, "--spring.config.name=server",
|
||||
"--spring.cloud.config.server.git.uri=" + repo);
|
||||
/*
|
||||
@@ -93,8 +89,8 @@ public class ApplicationTests {
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void contextLoads() {
|
||||
Map res = new TestRestTemplate().getForObject(
|
||||
"http://localhost:" + this.port + BASE_PATH + "/env/info.foo", Map.class);
|
||||
Map res = new TestRestTemplate().getForObject("http://localhost:" + this.port + BASE_PATH + "/env/info.foo",
|
||||
Map.class);
|
||||
assertThat(res).containsKey("propertySources");
|
||||
Map<String, Object> property = (Map<String, Object>) res.get("property");
|
||||
assertThat(property).containsEntry("value", "bar");
|
||||
|
||||
@@ -36,8 +36,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = Application.class, properties = "spring.application.name:bad",
|
||||
webEnvironment = RANDOM_PORT)
|
||||
@SpringBootTest(classes = Application.class, properties = "spring.application.name:bad", webEnvironment = RANDOM_PORT)
|
||||
public class ServerNativeApplicationTests {
|
||||
|
||||
private static int configPort = 0;
|
||||
@@ -53,11 +52,9 @@ public class ServerNativeApplicationTests {
|
||||
@BeforeClass
|
||||
public static void startConfigServer() throws IOException {
|
||||
String repo = ConfigServerTestUtils.prepareLocalRepo();
|
||||
server = SpringApplication.run(
|
||||
org.springframework.cloud.config.server.ConfigServerApplication.class,
|
||||
server = SpringApplication.run(org.springframework.cloud.config.server.ConfigServerApplication.class,
|
||||
"--server.port=" + configPort, "--spring.config.name=server",
|
||||
"--spring.cloud.config.server.git.uri=" + repo,
|
||||
"--spring.profiles.active=native");
|
||||
"--spring.cloud.config.server.git.uri=" + repo, "--spring.profiles.active=native");
|
||||
/*
|
||||
* FIXME configPort = ((EmbeddedWebApplicationContext) server)
|
||||
* .getEmbeddedServletContainer().getPort();
|
||||
|
||||
@@ -31,8 +31,8 @@ import org.springframework.context.annotation.Configuration;
|
||||
public class ConfigServerApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
new SpringApplicationBuilder(ConfigServerApplication.class)
|
||||
.properties("spring.config.name=configserver").run(args);
|
||||
new SpringApplicationBuilder(ConfigServerApplication.class).properties("spring.config.name=configserver")
|
||||
.run(args);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -56,8 +56,7 @@ public class ConfigServerBootstrapApplicationListener
|
||||
private int order = DEFAULT_ORDER;
|
||||
|
||||
private PropertySource<?> propertySource = new MapPropertySource("configServerClient",
|
||||
Collections.<String, Object>singletonMap("spring.cloud.config.enabled",
|
||||
"false"));
|
||||
Collections.<String, Object>singletonMap("spring.cloud.config.enabled", "false"));
|
||||
|
||||
@Override
|
||||
public int getOrder() {
|
||||
@@ -71,10 +70,8 @@ public class ConfigServerBootstrapApplicationListener
|
||||
@Override
|
||||
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
|
||||
ConfigurableEnvironment environment = event.getEnvironment();
|
||||
if (!environment.resolvePlaceholders("${spring.cloud.config.enabled:false}")
|
||||
.equalsIgnoreCase("true")) {
|
||||
if (!environment.getPropertySources()
|
||||
.contains(this.propertySource.getName())) {
|
||||
if (!environment.resolvePlaceholders("${spring.cloud.config.enabled:false}").equalsIgnoreCase("true")) {
|
||||
if (!environment.getPropertySources().contains(this.propertySource.getName())) {
|
||||
environment.getPropertySources().addLast(this.propertySource);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,8 +58,8 @@ public class ConfigServerBootstrapConfiguration {
|
||||
|
||||
@Bean
|
||||
public EnvironmentRepositoryPropertySourceLocator environmentRepositoryPropertySourceLocator() {
|
||||
return new EnvironmentRepositoryPropertySourceLocator(this.repository,
|
||||
this.client.getName(), this.client.getProfile(), getDefaultLabel());
|
||||
return new EnvironmentRepositoryPropertySourceLocator(this.repository, this.client.getName(),
|
||||
this.client.getProfile(), getDefaultLabel());
|
||||
}
|
||||
|
||||
private String getDefaultLabel() {
|
||||
|
||||
@@ -37,8 +37,7 @@ import org.springframework.core.env.Environment;
|
||||
*
|
||||
* @author Dylan Roberts
|
||||
*/
|
||||
public class CompositeEnvironmentBeanFactoryPostProcessor
|
||||
implements BeanFactoryPostProcessor {
|
||||
public class CompositeEnvironmentBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
|
||||
|
||||
private Environment environment;
|
||||
|
||||
@@ -47,24 +46,19 @@ public class CompositeEnvironmentBeanFactoryPostProcessor
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
|
||||
throws BeansException {
|
||||
List<String> typePropertyList = CompositeUtils
|
||||
.getCompositeTypeList(this.environment);
|
||||
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
|
||||
List<String> typePropertyList = CompositeUtils.getCompositeTypeList(this.environment);
|
||||
for (int i = 0; i < typePropertyList.size(); i++) {
|
||||
String type = typePropertyList.get(i);
|
||||
String factoryName = CompositeUtils.getFactoryName(type, beanFactory);
|
||||
|
||||
Type[] factoryTypes = CompositeUtils
|
||||
.getEnvironmentRepositoryFactoryTypeParams(beanFactory, factoryName);
|
||||
Type[] factoryTypes = CompositeUtils.getEnvironmentRepositoryFactoryTypeParams(beanFactory, factoryName);
|
||||
Class<? extends EnvironmentRepositoryProperties> propertiesClass;
|
||||
propertiesClass = (Class<? extends EnvironmentRepositoryProperties>) factoryTypes[1];
|
||||
EnvironmentRepositoryProperties properties = bindProperties(i,
|
||||
propertiesClass, this.environment);
|
||||
EnvironmentRepositoryProperties properties = bindProperties(i, propertiesClass, this.environment);
|
||||
|
||||
AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder
|
||||
.genericBeanDefinition(EnvironmentRepository.class)
|
||||
.setFactoryMethodOnBean("build", factoryName)
|
||||
.genericBeanDefinition(EnvironmentRepository.class).setFactoryMethodOnBean("build", factoryName)
|
||||
.addConstructorArgValue(properties).getBeanDefinition();
|
||||
String beanName = String.format("%s-env-repo%d", type, i);
|
||||
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
|
||||
@@ -72,13 +66,11 @@ public class CompositeEnvironmentBeanFactoryPostProcessor
|
||||
}
|
||||
}
|
||||
|
||||
private <P extends EnvironmentRepositoryProperties> P bindProperties(int index,
|
||||
Class<P> propertiesClass, Environment environment) {
|
||||
private <P extends EnvironmentRepositoryProperties> P bindProperties(int index, Class<P> propertiesClass,
|
||||
Environment environment) {
|
||||
Binder binder = Binder.get(environment);
|
||||
String environmentConfigurationPropertyName = String
|
||||
.format("spring.cloud.config.server.composite[%d]", index);
|
||||
P properties = binder.bindOrCreate(environmentConfigurationPropertyName,
|
||||
propertiesClass);
|
||||
String environmentConfigurationPropertyName = String.format("spring.cloud.config.server.composite[%d]", index);
|
||||
P properties = binder.bindOrCreate(environmentConfigurationPropertyName, propertiesClass);
|
||||
properties.setOrder(index + 1);
|
||||
return properties;
|
||||
}
|
||||
|
||||
@@ -48,10 +48,8 @@ public final class CompositeUtils {
|
||||
* @return list of matching types
|
||||
*/
|
||||
public static List<String> getCompositeTypeList(Environment environment) {
|
||||
return Binder.get(environment)
|
||||
.bind("spring.cloud.config.server", CompositeConfig.class).get()
|
||||
.getComposite().stream().map(map -> (String) map.get("type"))
|
||||
.collect(Collectors.toList());
|
||||
return Binder.get(environment).bind("spring.cloud.config.server", CompositeConfig.class).get().getComposite()
|
||||
.stream().map(map -> (String) map.get("type")).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -61,12 +59,10 @@ public final class CompositeUtils {
|
||||
* @param beanFactory Spring Bean Factory
|
||||
* @return name of the factory bean
|
||||
*/
|
||||
public static String getFactoryName(String type,
|
||||
ConfigurableListableBeanFactory beanFactory) {
|
||||
String[] factoryNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
|
||||
beanFactory, EnvironmentRepositoryFactory.class, true, false);
|
||||
return Arrays.stream(factoryNames).filter(n -> n.startsWith(type)).findFirst()
|
||||
.orElse(null);
|
||||
public static String getFactoryName(String type, ConfigurableListableBeanFactory beanFactory) {
|
||||
String[] factoryNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory,
|
||||
EnvironmentRepositoryFactory.class, true, false);
|
||||
return Arrays.stream(factoryNames).filter(n -> n.startsWith(type)).findFirst().orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -76,10 +72,9 @@ public final class CompositeUtils {
|
||||
* @param factoryName name of the factory
|
||||
* @return generic type params of the factory
|
||||
*/
|
||||
public static Type[] getEnvironmentRepositoryFactoryTypeParams(
|
||||
ConfigurableListableBeanFactory beanFactory, String factoryName) {
|
||||
MethodMetadata methodMetadata = (MethodMetadata) beanFactory
|
||||
.getBeanDefinition(factoryName).getSource();
|
||||
public static Type[] getEnvironmentRepositoryFactoryTypeParams(ConfigurableListableBeanFactory beanFactory,
|
||||
String factoryName) {
|
||||
MethodMetadata methodMetadata = (MethodMetadata) beanFactory.getBeanDefinition(factoryName).getSource();
|
||||
Class<?> factoryClass = null;
|
||||
try {
|
||||
factoryClass = Class.forName(methodMetadata.getReturnTypeName());
|
||||
@@ -87,11 +82,10 @@ public final class CompositeUtils {
|
||||
catch (ClassNotFoundException e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
Optional<AnnotatedType> annotatedFactoryType = Arrays
|
||||
.stream(factoryClass.getAnnotatedInterfaces()).filter(i -> {
|
||||
Optional<AnnotatedType> annotatedFactoryType = Arrays.stream(factoryClass.getAnnotatedInterfaces())
|
||||
.filter(i -> {
|
||||
ParameterizedType parameterizedType = (ParameterizedType) i.getType();
|
||||
return parameterizedType.getRawType()
|
||||
.equals(EnvironmentRepositoryFactory.class);
|
||||
return parameterizedType.getRawType().equals(EnvironmentRepositoryFactory.class);
|
||||
}).findFirst();
|
||||
ParameterizedType factoryParameterizedType = (ParameterizedType) annotatedFactoryType
|
||||
.orElse(factoryClass.getAnnotatedSuperclass()).getType();
|
||||
|
||||
@@ -35,35 +35,29 @@ import org.springframework.core.type.AnnotatedTypeMetadata;
|
||||
public class OnSearchPathLocatorPresent extends SpringBootCondition {
|
||||
|
||||
@Override
|
||||
public ConditionOutcome getMatchOutcome(ConditionContext context,
|
||||
AnnotatedTypeMetadata metadata) {
|
||||
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
|
||||
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
|
||||
List<String> types = CompositeUtils
|
||||
.getCompositeTypeList(context.getEnvironment());
|
||||
List<String> types = CompositeUtils.getCompositeTypeList(context.getEnvironment());
|
||||
|
||||
// get EnvironmentRepository types from registered factories
|
||||
List<Class<? extends EnvironmentRepository>> repositoryTypes = new ArrayList<>();
|
||||
for (String type : types) {
|
||||
String factoryName = CompositeUtils.getFactoryName(type, beanFactory);
|
||||
Type[] actualTypeArguments = CompositeUtils
|
||||
.getEnvironmentRepositoryFactoryTypeParams(beanFactory, factoryName);
|
||||
Type[] actualTypeArguments = CompositeUtils.getEnvironmentRepositoryFactoryTypeParams(beanFactory,
|
||||
factoryName);
|
||||
Class<? extends EnvironmentRepository> repositoryType;
|
||||
repositoryType = (Class<? extends EnvironmentRepository>) actualTypeArguments[0];
|
||||
repositoryTypes.add(repositoryType);
|
||||
}
|
||||
|
||||
boolean required = metadata
|
||||
.isAnnotated(ConditionalOnSearchPathLocator.class.getName());
|
||||
boolean foundSearchPathLocator = repositoryTypes.stream()
|
||||
.anyMatch(SearchPathLocator.class::isAssignableFrom);
|
||||
boolean required = metadata.isAnnotated(ConditionalOnSearchPathLocator.class.getName());
|
||||
boolean foundSearchPathLocator = repositoryTypes.stream().anyMatch(SearchPathLocator.class::isAssignableFrom);
|
||||
if (required && !foundSearchPathLocator) {
|
||||
return ConditionOutcome.noMatch(
|
||||
ConditionMessage.forCondition(ConditionalOnSearchPathLocator.class)
|
||||
.notAvailable(SearchPathLocator.class.getTypeName()));
|
||||
return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnSearchPathLocator.class)
|
||||
.notAvailable(SearchPathLocator.class.getTypeName()));
|
||||
}
|
||||
if (!required && foundSearchPathLocator) {
|
||||
return ConditionOutcome.noMatch(ConditionMessage
|
||||
.forCondition(ConditionalOnMissingSearchPathLocator.class)
|
||||
return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnMissingSearchPathLocator.class)
|
||||
.available(SearchPathLocator.class.getTypeName()));
|
||||
}
|
||||
return ConditionOutcome.match();
|
||||
|
||||
@@ -27,9 +27,9 @@ import org.springframework.context.annotation.Import;
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnBean(ConfigServerConfiguration.Marker.class)
|
||||
@EnableConfigurationProperties(ConfigServerProperties.class)
|
||||
@Import({ EnvironmentRepositoryConfiguration.class, CompositeConfiguration.class,
|
||||
ResourceRepositoryConfiguration.class, ConfigServerEncryptionConfiguration.class,
|
||||
ConfigServerMvcConfiguration.class, ResourceEncryptorConfiguration.class })
|
||||
@Import({ EnvironmentRepositoryConfiguration.class, CompositeConfiguration.class, ResourceRepositoryConfiguration.class,
|
||||
ConfigServerEncryptionConfiguration.class, ConfigServerMvcConfiguration.class,
|
||||
ResourceEncryptorConfiguration.class })
|
||||
public class ConfigServerAutoConfiguration {
|
||||
|
||||
}
|
||||
|
||||
@@ -65,19 +65,17 @@ public class ConfigServerHealthIndicator extends AbstractHealthIndicator {
|
||||
List<Map<String, Object>> details = new ArrayList<>();
|
||||
for (String name : this.repositories.keySet()) {
|
||||
Repository repository = this.repositories.get(name);
|
||||
String application = (repository.getName() == null) ? name
|
||||
: repository.getName();
|
||||
String application = (repository.getName() == null) ? name : repository.getName();
|
||||
String profiles = repository.getProfiles();
|
||||
|
||||
try {
|
||||
Environment environment = this.environmentRepository.findOne(application,
|
||||
profiles, repository.getLabel(), false);
|
||||
Environment environment = this.environmentRepository.findOne(application, profiles,
|
||||
repository.getLabel(), false);
|
||||
|
||||
HashMap<String, Object> detail = new HashMap<>();
|
||||
detail.put("name", environment.getName());
|
||||
detail.put("label", environment.getLabel());
|
||||
if (environment.getProfiles() != null
|
||||
&& environment.getProfiles().length > 0) {
|
||||
if (environment.getProfiles() != null && environment.getProfiles().length > 0) {
|
||||
detail.put("profiles", Arrays.asList(environment.getProfiles()));
|
||||
}
|
||||
|
||||
|
||||
@@ -65,10 +65,10 @@ public class ConfigServerMvcConfiguration implements WebMvcConfigurer {
|
||||
|
||||
@Bean
|
||||
@RefreshScope
|
||||
public EnvironmentController environmentController(
|
||||
EnvironmentRepository envRepository, ConfigServerProperties server) {
|
||||
EnvironmentController controller = new EnvironmentController(
|
||||
encrypted(envRepository, server), this.objectMapper);
|
||||
public EnvironmentController environmentController(EnvironmentRepository envRepository,
|
||||
ConfigServerProperties server) {
|
||||
EnvironmentController controller = new EnvironmentController(encrypted(envRepository, server),
|
||||
this.objectMapper);
|
||||
controller.setStripDocumentFromYaml(server.isStripDocumentFromYaml());
|
||||
controller.setAcceptEmpty(server.isAcceptEmpty());
|
||||
return controller;
|
||||
@@ -76,17 +76,16 @@ public class ConfigServerMvcConfiguration implements WebMvcConfigurer {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnBean(ResourceRepository.class)
|
||||
public ResourceController resourceController(ResourceRepository repository,
|
||||
EnvironmentRepository envRepository, ConfigServerProperties server) {
|
||||
ResourceController controller = new ResourceController(repository,
|
||||
encrypted(envRepository, server), this.resourceEncryptorMap);
|
||||
public ResourceController resourceController(ResourceRepository repository, EnvironmentRepository envRepository,
|
||||
ConfigServerProperties server) {
|
||||
ResourceController controller = new ResourceController(repository, encrypted(envRepository, server),
|
||||
this.resourceEncryptorMap);
|
||||
controller.setEncryptEnabled(server.getEncrypt().isEnabled());
|
||||
controller.setPlainTextEncryptEnabled(server.getEncrypt().isPlainTextEncrypt());
|
||||
return controller;
|
||||
}
|
||||
|
||||
private EnvironmentRepository encrypted(EnvironmentRepository envRepository,
|
||||
ConfigServerProperties server) {
|
||||
private EnvironmentRepository encrypted(EnvironmentRepository envRepository, ConfigServerProperties server) {
|
||||
EnvironmentEncryptorEnvironmentRepository encrypted = new EnvironmentEncryptorEnvironmentRepository(
|
||||
envRepository, environmentEncryptor);
|
||||
encrypted.setOverrides(server.getOverrides());
|
||||
|
||||
@@ -54,13 +54,11 @@ import org.springframework.util.StringUtils;
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@EnableConfigurationProperties(KeyProperties.class)
|
||||
@Import({ SingleTextEncryptorConfiguration.class,
|
||||
DefaultTextEncryptorConfiguration.class })
|
||||
@Import({ SingleTextEncryptorConfiguration.class, DefaultTextEncryptorConfiguration.class })
|
||||
public class EncryptionAutoConfiguration {
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnProperty(value = "spring.cloud.config.server.encrypt.enabled",
|
||||
matchIfMissing = true)
|
||||
@ConditionalOnProperty(value = "spring.cloud.config.server.encrypt.enabled", matchIfMissing = true)
|
||||
protected static class EncryptorConfiguration {
|
||||
|
||||
@Autowired(required = false)
|
||||
@@ -83,8 +81,7 @@ public class EncryptionAutoConfiguration {
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnClass(RsaSecretEncryptor.class)
|
||||
@ConditionalOnProperty(prefix = "encrypt.key-store", value = "location",
|
||||
matchIfMissing = false)
|
||||
@ConditionalOnProperty(prefix = "encrypt.key-store", value = "location", matchIfMissing = false)
|
||||
protected static class KeyStoreConfiguration {
|
||||
|
||||
@Autowired
|
||||
@@ -98,8 +95,7 @@ public class EncryptionAutoConfiguration {
|
||||
public TextEncryptorLocator textEncryptorLocator() {
|
||||
KeyStore keyStore = this.key.getKeyStore();
|
||||
KeyStoreTextEncryptorLocator locator = new KeyStoreTextEncryptorLocator(
|
||||
new KeyStoreKeyFactory(keyStore.getLocation(),
|
||||
keyStore.getPassword().toCharArray(),
|
||||
new KeyStoreKeyFactory(keyStore.getLocation(), keyStore.getPassword().toCharArray(),
|
||||
key.getKeyStore().getType()),
|
||||
keyStore.getSecret(), keyStore.getAlias());
|
||||
RsaAlgorithm algorithm = this.rsaProperties.getAlgorithm();
|
||||
|
||||
@@ -97,24 +97,19 @@ import org.springframework.vault.core.VaultTemplate;
|
||||
* @author Scott Frederick
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@EnableConfigurationProperties({ SvnKitEnvironmentProperties.class,
|
||||
CredhubEnvironmentProperties.class, JdbcEnvironmentProperties.class,
|
||||
NativeEnvironmentProperties.class, VaultEnvironmentProperties.class,
|
||||
@EnableConfigurationProperties({ SvnKitEnvironmentProperties.class, CredhubEnvironmentProperties.class,
|
||||
JdbcEnvironmentProperties.class, NativeEnvironmentProperties.class, VaultEnvironmentProperties.class,
|
||||
RedisEnvironmentProperties.class, AwsS3EnvironmentProperties.class })
|
||||
@Import({ CompositeRepositoryConfiguration.class, JdbcRepositoryConfiguration.class,
|
||||
VaultConfiguration.class, VaultRepositoryConfiguration.class,
|
||||
SpringVaultRepositoryConfiguration.class, CredhubConfiguration.class,
|
||||
CredhubRepositoryConfiguration.class, SvnRepositoryConfiguration.class,
|
||||
NativeRepositoryConfiguration.class, GitRepositoryConfiguration.class,
|
||||
RedisRepositoryConfiguration.class, GoogleCloudSourceConfiguration.class,
|
||||
@Import({ CompositeRepositoryConfiguration.class, JdbcRepositoryConfiguration.class, VaultConfiguration.class,
|
||||
VaultRepositoryConfiguration.class, SpringVaultRepositoryConfiguration.class, CredhubConfiguration.class,
|
||||
CredhubRepositoryConfiguration.class, SvnRepositoryConfiguration.class, NativeRepositoryConfiguration.class,
|
||||
GitRepositoryConfiguration.class, RedisRepositoryConfiguration.class, GoogleCloudSourceConfiguration.class,
|
||||
AwsS3RepositoryConfiguration.class, DefaultRepositoryConfiguration.class })
|
||||
public class EnvironmentRepositoryConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnProperty(value = "spring.cloud.config.server.health.enabled",
|
||||
matchIfMissing = true)
|
||||
public ConfigServerHealthIndicator configServerHealthIndicator(
|
||||
EnvironmentRepository repository) {
|
||||
@ConditionalOnProperty(value = "spring.cloud.config.server.health.enabled", matchIfMissing = true)
|
||||
public ConfigServerHealthIndicator configServerHealthIndicator(EnvironmentRepository repository) {
|
||||
return new ConfigServerHealthIndicator(repository);
|
||||
}
|
||||
|
||||
@@ -126,8 +121,7 @@ public class EnvironmentRepositoryConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(ConfigTokenProvider.class)
|
||||
public ConfigTokenProvider defaultConfigTokenProvider(
|
||||
ObjectProvider<HttpServletRequest> httpRequest) {
|
||||
public ConfigTokenProvider defaultConfigTokenProvider(ObjectProvider<HttpServletRequest> httpRequest) {
|
||||
return new HttpRequestConfigTokenProvider(httpRequest);
|
||||
}
|
||||
|
||||
@@ -164,10 +158,9 @@ public class EnvironmentRepositoryConfiguration {
|
||||
Optional<TransportConfigCallback> customTransportConfigCallback,
|
||||
Optional<GoogleCloudSourceSupport> googleCloudSourceSupport) {
|
||||
final TransportConfigCallbackFactory transportConfigCallbackFactory = new TransportConfigCallbackFactory(
|
||||
customTransportConfigCallback.orElse(null),
|
||||
googleCloudSourceSupport.orElse(null));
|
||||
return new MultipleJGitEnvironmentRepositoryFactory(environment, server,
|
||||
jgitHttpConnectionFactory, transportConfigCallbackFactory);
|
||||
customTransportConfigCallback.orElse(null), googleCloudSourceSupport.orElse(null));
|
||||
return new MultipleJGitEnvironmentRepositoryFactory(environment, server, jgitHttpConnectionFactory,
|
||||
transportConfigCallbackFactory);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -188,8 +181,7 @@ public class EnvironmentRepositoryConfiguration {
|
||||
static class AwsS3FactoryConfig {
|
||||
|
||||
@Bean
|
||||
public AwsS3EnvironmentRepositoryFactory awsS3EnvironmentRepositoryFactory(
|
||||
ConfigServerProperties server) {
|
||||
public AwsS3EnvironmentRepositoryFactory awsS3EnvironmentRepositoryFactory(ConfigServerProperties server) {
|
||||
return new AwsS3EnvironmentRepositoryFactory(server);
|
||||
}
|
||||
|
||||
@@ -200,8 +192,8 @@ public class EnvironmentRepositoryConfiguration {
|
||||
static class SvnFactoryConfig {
|
||||
|
||||
@Bean
|
||||
public SvnEnvironmentRepositoryFactory svnEnvironmentRepositoryFactory(
|
||||
ConfigurableEnvironment environment, ConfigServerProperties server) {
|
||||
public SvnEnvironmentRepositoryFactory svnEnvironmentRepositoryFactory(ConfigurableEnvironment environment,
|
||||
ConfigServerProperties server) {
|
||||
return new SvnEnvironmentRepositoryFactory(environment, server);
|
||||
}
|
||||
|
||||
@@ -217,8 +209,7 @@ public class EnvironmentRepositoryConfiguration {
|
||||
ObjectProvider<HttpServletRequest> request, EnvironmentWatch watch,
|
||||
Optional<VaultEnvironmentRepositoryFactory.VaultRestTemplateFactory> vaultRestTemplateFactory,
|
||||
ConfigTokenProvider tokenProvider) {
|
||||
return new VaultEnvironmentRepositoryFactory(request, watch,
|
||||
vaultRestTemplateFactory, tokenProvider);
|
||||
return new VaultEnvironmentRepositoryFactory(request, watch, vaultRestTemplateFactory, tokenProvider);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -245,22 +236,19 @@ public class EnvironmentRepositoryConfiguration {
|
||||
public SpringVaultEnvironmentRepositoryFactory vaultEnvironmentRepositoryFactory(
|
||||
ObjectProvider<HttpServletRequest> request, EnvironmentWatch watch,
|
||||
SpringVaultClientConfiguration vaultClientConfiguration) {
|
||||
return new SpringVaultEnvironmentRepositoryFactory(request, watch,
|
||||
vaultClientConfiguration);
|
||||
return new SpringVaultEnvironmentRepositoryFactory(request, watch, vaultClientConfiguration);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnClass(JdbcTemplate.class)
|
||||
@ConditionalOnProperty(value = "spring.cloud.config.server.jdbc.enabled",
|
||||
matchIfMissing = true)
|
||||
@ConditionalOnProperty(value = "spring.cloud.config.server.jdbc.enabled", matchIfMissing = true)
|
||||
static class JdbcFactoryConfig {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnBean(JdbcTemplate.class)
|
||||
public JdbcEnvironmentRepositoryFactory jdbcEnvironmentRepositoryFactory(
|
||||
JdbcTemplate jdbc) {
|
||||
public JdbcEnvironmentRepositoryFactory jdbcEnvironmentRepositoryFactory(JdbcTemplate jdbc) {
|
||||
return new JdbcEnvironmentRepositoryFactory(jdbc);
|
||||
}
|
||||
|
||||
@@ -272,8 +260,7 @@ public class EnvironmentRepositoryConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnBean(StringRedisTemplate.class)
|
||||
public RedisEnvironmentRepositoryFactory redisEnvironmentRepositoryFactory(
|
||||
StringRedisTemplate redis) {
|
||||
public RedisEnvironmentRepositoryFactory redisEnvironmentRepositoryFactory(StringRedisTemplate redis) {
|
||||
return new RedisEnvironmentRepositoryFactory(redis);
|
||||
}
|
||||
|
||||
@@ -286,8 +273,7 @@ public class EnvironmentRepositoryConfiguration {
|
||||
@Bean
|
||||
public CredhubEnvironmentRepositoryFactory credhubEnvironmentRepositoryFactory(
|
||||
Optional<CredHubOperations> credHubOperations) {
|
||||
return new CredhubEnvironmentRepositoryFactory(
|
||||
credHubOperations.orElse(null));
|
||||
return new CredhubEnvironmentRepositoryFactory(credHubOperations.orElse(null));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -306,8 +292,7 @@ public class EnvironmentRepositoryConfiguration {
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnMissingBean(value = EnvironmentRepository.class,
|
||||
search = SearchStrategy.CURRENT)
|
||||
@ConditionalOnMissingBean(value = EnvironmentRepository.class, search = SearchStrategy.CURRENT)
|
||||
class DefaultRepositoryConfiguration {
|
||||
|
||||
@Bean
|
||||
@@ -324,8 +309,7 @@ class DefaultRepositoryConfiguration {
|
||||
class NativeRepositoryConfiguration {
|
||||
|
||||
@Bean
|
||||
public NativeEnvironmentRepository nativeEnvironmentRepository(
|
||||
NativeEnvironmentRepositoryFactory factory,
|
||||
public NativeEnvironmentRepository nativeEnvironmentRepository(NativeEnvironmentRepositoryFactory factory,
|
||||
NativeEnvironmentProperties environmentProperties) {
|
||||
return factory.build(environmentProperties);
|
||||
}
|
||||
@@ -344,8 +328,7 @@ class AwsS3RepositoryConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(AwsS3EnvironmentRepository.class)
|
||||
public AwsS3EnvironmentRepository awsS3EnvironmentRepository(
|
||||
AwsS3EnvironmentRepositoryFactory factory,
|
||||
public AwsS3EnvironmentRepository awsS3EnvironmentRepository(AwsS3EnvironmentRepositoryFactory factory,
|
||||
AwsS3EnvironmentProperties environmentProperties) {
|
||||
return factory.build(environmentProperties);
|
||||
}
|
||||
@@ -357,8 +340,7 @@ class AwsS3RepositoryConfiguration {
|
||||
class SvnRepositoryConfiguration {
|
||||
|
||||
@Bean
|
||||
public SvnKitEnvironmentRepository svnKitEnvironmentRepository(
|
||||
SvnEnvironmentRepositoryFactory factory,
|
||||
public SvnKitEnvironmentRepository svnKitEnvironmentRepository(SvnEnvironmentRepositoryFactory factory,
|
||||
SvnKitEnvironmentProperties environmentProperties) {
|
||||
return factory.build(environmentProperties);
|
||||
}
|
||||
@@ -372,8 +354,7 @@ class SvnRepositoryConfiguration {
|
||||
class VaultRepositoryConfiguration {
|
||||
|
||||
@Bean
|
||||
public VaultEnvironmentRepository vaultEnvironmentRepository(
|
||||
VaultEnvironmentRepositoryFactory factory,
|
||||
public VaultEnvironmentRepository vaultEnvironmentRepository(VaultEnvironmentRepositoryFactory factory,
|
||||
VaultEnvironmentProperties environmentProperties) throws Exception {
|
||||
return factory.build(environmentProperties);
|
||||
}
|
||||
@@ -386,8 +367,7 @@ class VaultRepositoryConfiguration {
|
||||
class SpringVaultRepositoryConfiguration {
|
||||
|
||||
@Bean
|
||||
public SpringVaultEnvironmentRepository vaultEnvironmentRepository(
|
||||
SpringVaultEnvironmentRepositoryFactory factory,
|
||||
public SpringVaultEnvironmentRepository vaultEnvironmentRepository(SpringVaultEnvironmentRepositoryFactory factory,
|
||||
VaultEnvironmentProperties environmentProperties) {
|
||||
return factory.build(environmentProperties);
|
||||
}
|
||||
@@ -399,8 +379,7 @@ class SpringVaultRepositoryConfiguration {
|
||||
class CredhubRepositoryConfiguration {
|
||||
|
||||
@Bean
|
||||
public CredhubEnvironmentRepository credhubEnvironmentRepository(
|
||||
CredhubEnvironmentRepositoryFactory factory,
|
||||
public CredhubEnvironmentRepository credhubEnvironmentRepository(CredhubEnvironmentRepositoryFactory factory,
|
||||
CredhubEnvironmentProperties environmentProperties) {
|
||||
return factory.build(environmentProperties);
|
||||
}
|
||||
@@ -410,14 +389,12 @@ class CredhubRepositoryConfiguration {
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@Profile("jdbc")
|
||||
@ConditionalOnClass(JdbcTemplate.class)
|
||||
@ConditionalOnProperty(value = "spring.cloud.config.server.jdbc.enabled",
|
||||
matchIfMissing = true)
|
||||
@ConditionalOnProperty(value = "spring.cloud.config.server.jdbc.enabled", matchIfMissing = true)
|
||||
class JdbcRepositoryConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnBean(JdbcTemplate.class)
|
||||
public JdbcEnvironmentRepository jdbcEnvironmentRepository(
|
||||
JdbcEnvironmentRepositoryFactory factory,
|
||||
public JdbcEnvironmentRepository jdbcEnvironmentRepository(JdbcEnvironmentRepositoryFactory factory,
|
||||
JdbcEnvironmentProperties environmentProperties) {
|
||||
return factory.build(environmentProperties);
|
||||
}
|
||||
@@ -431,8 +408,7 @@ class RedisRepositoryConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnBean(StringRedisTemplate.class)
|
||||
public RedisEnvironmentRepository redisEnvironmentRepository(
|
||||
RedisEnvironmentRepositoryFactory factory,
|
||||
public RedisEnvironmentRepository redisEnvironmentRepository(RedisEnvironmentRepositoryFactory factory,
|
||||
RedisEnvironmentProperties environmentProperties) {
|
||||
return factory.build(environmentProperties);
|
||||
}
|
||||
|
||||
@@ -50,17 +50,13 @@ public class ResourceEncryptorConfiguration {
|
||||
@Bean
|
||||
Map<String, ResourceEncryptor> resourceEncryptors() {
|
||||
Map<String, ResourceEncryptor> resourceEncryptorMap = new HashMap<>();
|
||||
addSupportedExtensionsToMap(resourceEncryptorMap,
|
||||
new CipherResourceJsonEncryptor(encryptor));
|
||||
addSupportedExtensionsToMap(resourceEncryptorMap,
|
||||
new CipherResourcePropertiesEncryptor(encryptor));
|
||||
addSupportedExtensionsToMap(resourceEncryptorMap,
|
||||
new CipherResourceYamlEncryptor(encryptor));
|
||||
addSupportedExtensionsToMap(resourceEncryptorMap, new CipherResourceJsonEncryptor(encryptor));
|
||||
addSupportedExtensionsToMap(resourceEncryptorMap, new CipherResourcePropertiesEncryptor(encryptor));
|
||||
addSupportedExtensionsToMap(resourceEncryptorMap, new CipherResourceYamlEncryptor(encryptor));
|
||||
return resourceEncryptorMap;
|
||||
}
|
||||
|
||||
private void addSupportedExtensionsToMap(
|
||||
Map<String, ResourceEncryptor> resourceEncryptorMap,
|
||||
private void addSupportedExtensionsToMap(Map<String, ResourceEncryptor> resourceEncryptorMap,
|
||||
ResourceEncryptor resourceEncryptor) {
|
||||
for (String ext : resourceEncryptor.getSupportedExtensions()) {
|
||||
resourceEncryptorMap.put(ext, resourceEncryptor);
|
||||
|
||||
@@ -23,8 +23,7 @@ import org.springframework.cloud.config.server.environment.JGitEnvironmentReposi
|
||||
/**
|
||||
* @author Ryan Baxter
|
||||
*/
|
||||
public class GitUriFailureAnalyzer
|
||||
extends AbstractFailureAnalyzer<IllegalStateException> {
|
||||
public class GitUriFailureAnalyzer extends AbstractFailureAnalyzer<IllegalStateException> {
|
||||
|
||||
/**
|
||||
* Description of the failure.
|
||||
@@ -39,8 +38,7 @@ public class GitUriFailureAnalyzer
|
||||
+ "you need to use a composite configuration.";
|
||||
|
||||
@Override
|
||||
protected FailureAnalysis analyze(Throwable rootFailure,
|
||||
IllegalStateException cause) {
|
||||
protected FailureAnalysis analyze(Throwable rootFailure, IllegalStateException cause) {
|
||||
if (JGitEnvironmentRepository.MESSAGE.equalsIgnoreCase(cause.getMessage())) {
|
||||
return new FailureAnalysis(DESCRIPTION, ACTION, cause);
|
||||
}
|
||||
|
||||
@@ -51,25 +51,22 @@ abstract class AbstractCipherResourceEncryptor implements ResourceEncryptor {
|
||||
public abstract List<String> getSupportedExtensions();
|
||||
|
||||
@Override
|
||||
public abstract String decrypt(String text, Environment environment)
|
||||
throws IOException;
|
||||
public abstract String decrypt(String text, Environment environment) throws IOException;
|
||||
|
||||
protected String decryptWithJacksonParser(String text, String name, String[] profiles,
|
||||
JsonFactory factory) throws IOException {
|
||||
protected String decryptWithJacksonParser(String text, String name, String[] profiles, JsonFactory factory)
|
||||
throws IOException {
|
||||
Set<String> valsToDecrpyt = new HashSet<String>();
|
||||
JsonParser parser = factory.createParser(text);
|
||||
JsonToken token;
|
||||
|
||||
while ((token = parser.nextToken()) != null) {
|
||||
if (token.equals(JsonToken.VALUE_STRING)
|
||||
&& parser.getValueAsString().startsWith(CIPHER_MARKER)) {
|
||||
if (token.equals(JsonToken.VALUE_STRING) && parser.getValueAsString().startsWith(CIPHER_MARKER)) {
|
||||
valsToDecrpyt.add(parser.getValueAsString().trim());
|
||||
}
|
||||
}
|
||||
|
||||
for (String value : valsToDecrpyt) {
|
||||
String decryptedValue = decryptValue(value.replace(CIPHER_MARKER, ""), name,
|
||||
profiles);
|
||||
String decryptedValue = decryptValue(value.replace(CIPHER_MARKER, ""), name, profiles);
|
||||
text = text.replace(value, decryptedValue);
|
||||
}
|
||||
|
||||
@@ -78,8 +75,7 @@ abstract class AbstractCipherResourceEncryptor implements ResourceEncryptor {
|
||||
|
||||
protected String decryptValue(String value, String name, String[] profiles) {
|
||||
return encryptor
|
||||
.locate(this.helper.getEncryptorKeys(name,
|
||||
StringUtils.arrayToCommaDelimitedString(profiles), value))
|
||||
.locate(this.helper.getEncryptorKeys(name, StringUtils.arrayToCommaDelimitedString(profiles), value))
|
||||
.decrypt(this.helper.stripPrefix(value));
|
||||
}
|
||||
|
||||
|
||||
@@ -53,36 +53,31 @@ public class CipherEnvironmentEncryptor implements EnvironmentEncryptor {
|
||||
|
||||
@Override
|
||||
public Environment decrypt(Environment environment) {
|
||||
return this.encryptor != null ? decrypt(environment, this.encryptor)
|
||||
: environment;
|
||||
return this.encryptor != null ? decrypt(environment, this.encryptor) : environment;
|
||||
}
|
||||
|
||||
private Environment decrypt(Environment environment, TextEncryptorLocator encryptor) {
|
||||
Environment result = new Environment(environment);
|
||||
for (PropertySource source : environment.getPropertySources()) {
|
||||
Map<Object, Object> map = new LinkedHashMap<Object, Object>(
|
||||
source.getSource());
|
||||
Map<Object, Object> map = new LinkedHashMap<Object, Object>(source.getSource());
|
||||
for (Map.Entry<Object, Object> entry : new LinkedHashSet<>(map.entrySet())) {
|
||||
Object key = entry.getKey();
|
||||
String name = key.toString();
|
||||
if (entry.getValue() != null
|
||||
&& entry.getValue().toString().startsWith("{cipher}")) {
|
||||
if (entry.getValue() != null && entry.getValue().toString().startsWith("{cipher}")) {
|
||||
String value = entry.getValue().toString();
|
||||
map.remove(key);
|
||||
try {
|
||||
value = value.substring("{cipher}".length());
|
||||
value = encryptor
|
||||
.locate(this.helper.getEncryptorKeys(name,
|
||||
StringUtils.arrayToCommaDelimitedString(
|
||||
environment.getProfiles()),
|
||||
value))
|
||||
StringUtils.arrayToCommaDelimitedString(environment.getProfiles()), value))
|
||||
.decrypt(this.helper.stripPrefix(value));
|
||||
}
|
||||
catch (Exception e) {
|
||||
value = "<n/a>";
|
||||
name = "invalid." + name;
|
||||
String message = "Cannot decrypt key: " + key + " ("
|
||||
+ e.getClass() + ": " + e.getMessage() + ")";
|
||||
String message = "Cannot decrypt key: " + key + " (" + e.getClass() + ": " + e.getMessage()
|
||||
+ ")";
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug(message, e);
|
||||
}
|
||||
|
||||
@@ -33,8 +33,7 @@ import org.springframework.stereotype.Component;
|
||||
* @author Sean Stiglitz
|
||||
*/
|
||||
@Component
|
||||
public class CipherResourceJsonEncryptor extends AbstractCipherResourceEncryptor
|
||||
implements ResourceEncryptor {
|
||||
public class CipherResourceJsonEncryptor extends AbstractCipherResourceEncryptor implements ResourceEncryptor {
|
||||
|
||||
private static final List<String> SUPPORTED_EXTENSIONS = Arrays.asList("json");
|
||||
|
||||
@@ -52,8 +51,7 @@ public class CipherResourceJsonEncryptor extends AbstractCipherResourceEncryptor
|
||||
|
||||
@Override
|
||||
public String decrypt(String text, Environment environment) throws IOException {
|
||||
return decryptWithJacksonParser(text, environment.getName(),
|
||||
environment.getProfiles(), factory);
|
||||
return decryptWithJacksonParser(text, environment.getName(), environment.getProfiles(), factory);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -35,8 +35,7 @@ import org.springframework.stereotype.Component;
|
||||
* @author Sean Stiglitz
|
||||
*/
|
||||
@Component
|
||||
public class CipherResourcePropertiesEncryptor extends AbstractCipherResourceEncryptor
|
||||
implements ResourceEncryptor {
|
||||
public class CipherResourcePropertiesEncryptor extends AbstractCipherResourceEncryptor implements ResourceEncryptor {
|
||||
|
||||
private static final List<String> SUPPORTED_EXTENSIONS = Arrays.asList("properties");
|
||||
|
||||
@@ -64,8 +63,8 @@ public class CipherResourcePropertiesEncryptor extends AbstractCipherResourceEnc
|
||||
}
|
||||
|
||||
for (String value : valsToDecrpyt) {
|
||||
String decryptedValue = decryptValue(value.replace(CIPHER_MARKER, ""),
|
||||
environment.getName(), environment.getProfiles());
|
||||
String decryptedValue = decryptValue(value.replace(CIPHER_MARKER, ""), environment.getName(),
|
||||
environment.getProfiles());
|
||||
text = text.replace(value, decryptedValue);
|
||||
}
|
||||
|
||||
|
||||
@@ -33,8 +33,7 @@ import org.springframework.stereotype.Component;
|
||||
* @author Sean Stiglitz
|
||||
*/
|
||||
@Component
|
||||
public class CipherResourceYamlEncryptor extends AbstractCipherResourceEncryptor
|
||||
implements ResourceEncryptor {
|
||||
public class CipherResourceYamlEncryptor extends AbstractCipherResourceEncryptor implements ResourceEncryptor {
|
||||
|
||||
private static final List<String> SUPPORTED_EXTENSIONS = Arrays.asList("yml", "yaml");
|
||||
|
||||
@@ -52,8 +51,7 @@ public class CipherResourceYamlEncryptor extends AbstractCipherResourceEncryptor
|
||||
|
||||
@Override
|
||||
public String decrypt(String text, Environment environment) throws IOException {
|
||||
return decryptWithJacksonParser(text, environment.getName(),
|
||||
environment.getProfiles(), factory);
|
||||
return decryptWithJacksonParser(text, environment.getName(), environment.getProfiles(), factory);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -89,41 +89,37 @@ public class EncryptionController {
|
||||
|
||||
@RequestMapping(value = "encrypt/status", method = RequestMethod.GET)
|
||||
public Map<String, Object> status() {
|
||||
TextEncryptor encryptor = getEncryptor(defaultApplicationName, defaultProfile,
|
||||
"");
|
||||
TextEncryptor encryptor = getEncryptor(defaultApplicationName, defaultProfile, "");
|
||||
validateEncryptionWeakness(encryptor);
|
||||
return Collections.singletonMap("status", "OK");
|
||||
}
|
||||
|
||||
@RequestMapping(value = "encrypt", method = RequestMethod.POST)
|
||||
public String encrypt(@RequestBody String data,
|
||||
@RequestHeader("Content-Type") MediaType type) {
|
||||
public String encrypt(@RequestBody String data, @RequestHeader("Content-Type") MediaType type) {
|
||||
return encrypt(defaultApplicationName, defaultProfile, data, type);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/encrypt/{name}/{profiles}", method = RequestMethod.POST)
|
||||
public String encrypt(@PathVariable String name, @PathVariable String profiles,
|
||||
@RequestBody String data, @RequestHeader("Content-Type") MediaType type) {
|
||||
public String encrypt(@PathVariable String name, @PathVariable String profiles, @RequestBody String data,
|
||||
@RequestHeader("Content-Type") MediaType type) {
|
||||
TextEncryptor encryptor = getEncryptor(name, profiles, "");
|
||||
validateEncryptionWeakness(encryptor);
|
||||
String input = stripFormData(data, type, false);
|
||||
Map<String, String> keys = helper.getEncryptorKeys(name, profiles, input);
|
||||
String textToEncrypt = helper.stripPrefix(input);
|
||||
String encrypted = helper.addPrefix(keys,
|
||||
encryptorLocator.locate(keys).encrypt(textToEncrypt));
|
||||
String encrypted = helper.addPrefix(keys, encryptorLocator.locate(keys).encrypt(textToEncrypt));
|
||||
logger.info("Encrypted data");
|
||||
return encrypted;
|
||||
}
|
||||
|
||||
@RequestMapping(value = "decrypt", method = RequestMethod.POST)
|
||||
public String decrypt(@RequestBody String data,
|
||||
@RequestHeader("Content-Type") MediaType type) {
|
||||
public String decrypt(@RequestBody String data, @RequestHeader("Content-Type") MediaType type) {
|
||||
return decrypt(defaultApplicationName, defaultProfile, data, type);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/decrypt/{name}/{profiles}", method = RequestMethod.POST)
|
||||
public String decrypt(@PathVariable String name, @PathVariable String profiles,
|
||||
@RequestBody String data, @RequestHeader("Content-Type") MediaType type) {
|
||||
public String decrypt(@PathVariable String name, @PathVariable String profiles, @RequestBody String data,
|
||||
@RequestHeader("Content-Type") MediaType type) {
|
||||
TextEncryptor encryptor = getEncryptor(name, profiles, "");
|
||||
checkDecryptionPossible(encryptor);
|
||||
validateEncryptionWeakness(encryptor);
|
||||
@@ -144,8 +140,7 @@ public class EncryptionController {
|
||||
if (encryptorLocator == null) {
|
||||
throw new KeyNotInstalledException();
|
||||
}
|
||||
TextEncryptor encryptor = encryptorLocator
|
||||
.locate(helper.getEncryptorKeys(name, profiles, data));
|
||||
TextEncryptor encryptor = encryptorLocator.locate(helper.getEncryptorKeys(name, profiles, data));
|
||||
if (encryptor == null) {
|
||||
throw new KeyNotInstalledException();
|
||||
}
|
||||
@@ -159,8 +154,7 @@ public class EncryptionController {
|
||||
}
|
||||
|
||||
private void checkDecryptionPossible(TextEncryptor textEncryptor) {
|
||||
if (textEncryptor instanceof RsaSecretEncryptor
|
||||
&& !((RsaSecretEncryptor) textEncryptor).canDecrypt()) {
|
||||
if (textEncryptor instanceof RsaSecretEncryptor && !((RsaSecretEncryptor) textEncryptor).canDecrypt()) {
|
||||
throw new DecryptionNotSupportedException();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,8 +62,7 @@ class EnvironmentPrefixHelper {
|
||||
* @param text text to cipher
|
||||
* @return encryptor keys
|
||||
*/
|
||||
public Map<String, String> getEncryptorKeys(String name, String profiles,
|
||||
String text) {
|
||||
public Map<String, String> getEncryptorKeys(String name, String profiles, String text) {
|
||||
|
||||
Map<String, String> keys = new LinkedHashMap<String, String>();
|
||||
|
||||
@@ -129,8 +128,7 @@ class EnvironmentPrefixHelper {
|
||||
}
|
||||
|
||||
private String removeEnvironmentPrefix(String input) {
|
||||
return input.replaceFirst("\\{name:.*\\}", "").replaceFirst("\\{profiles:.*\\}",
|
||||
"");
|
||||
return input.replaceFirst("\\{name:.*\\}", "").replaceFirst("\\{profiles:.*\\}", "");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -55,8 +55,7 @@ public class KeyStoreTextEncryptorLocator implements TextEncryptorLocator {
|
||||
|
||||
private String salt = "deadbeef";
|
||||
|
||||
public KeyStoreTextEncryptorLocator(KeyStoreKeyFactory keys, String defaultSecret,
|
||||
String defaultAlias) {
|
||||
public KeyStoreTextEncryptorLocator(KeyStoreKeyFactory keys, String defaultSecret, String defaultAlias) {
|
||||
this.keys = keys;
|
||||
this.defaultAlias = defaultAlias;
|
||||
this.defaultSecret = defaultSecret;
|
||||
@@ -97,9 +96,8 @@ public class KeyStoreTextEncryptorLocator implements TextEncryptorLocator {
|
||||
}
|
||||
|
||||
private RsaSecretEncryptor rsaSecretEncryptor(String alias, String secret) {
|
||||
return new RsaSecretEncryptor(
|
||||
this.keys.getKeyPair(alias, this.secretLocator.locate(secret)),
|
||||
this.rsaAlgorithm, this.salt, this.strong);
|
||||
return new RsaSecretEncryptor(this.keys.getKeyPair(alias, this.secretLocator.locate(secret)), this.rsaAlgorithm,
|
||||
this.salt, this.strong);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -36,8 +36,7 @@ public class LocatorTextEncryptor implements TextEncryptor {
|
||||
|
||||
@Override
|
||||
public String encrypt(String text) {
|
||||
Map<String, String> keys = this.helper.getEncryptorKeys("configserver", "default",
|
||||
text);
|
||||
Map<String, String> keys = this.helper.getEncryptorKeys("configserver", "default", text);
|
||||
return getLocator().locate(keys).encrypt(this.helper.stripPrefix(text));
|
||||
}
|
||||
|
||||
@@ -47,8 +46,7 @@ public class LocatorTextEncryptor implements TextEncryptor {
|
||||
|
||||
@Override
|
||||
public String decrypt(String encryptedText) {
|
||||
Map<String, String> keys = this.helper.getEncryptorKeys("configserver", "default",
|
||||
encryptedText);
|
||||
Map<String, String> keys = this.helper.getEncryptorKeys("configserver", "default", encryptedText);
|
||||
return getLocator().locate(keys).decrypt(this.helper.stripPrefix(encryptedText));
|
||||
}
|
||||
|
||||
|
||||
@@ -44,23 +44,20 @@ public abstract class AbstractScmEnvironmentRepository extends AbstractScmAccess
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized Environment findOne(String application, String profile,
|
||||
String label) {
|
||||
public synchronized Environment findOne(String application, String profile, String label) {
|
||||
return findOne(application, profile, label, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized Environment findOne(String application, String profile,
|
||||
String label, boolean includeOrigin) {
|
||||
NativeEnvironmentRepository delegate = new NativeEnvironmentRepository(
|
||||
getEnvironment(), new NativeEnvironmentProperties());
|
||||
public synchronized Environment findOne(String application, String profile, String label, boolean includeOrigin) {
|
||||
NativeEnvironmentRepository delegate = new NativeEnvironmentRepository(getEnvironment(),
|
||||
new NativeEnvironmentProperties());
|
||||
Locations locations = getLocations(application, profile, label);
|
||||
delegate.setSearchLocations(locations.getLocations());
|
||||
Environment result = delegate.findOne(application, profile, "", includeOrigin);
|
||||
result.setVersion(locations.getVersion());
|
||||
result.setLabel(label);
|
||||
return this.cleaner.clean(result, getWorkingDirectory().toURI().toString(),
|
||||
getUri());
|
||||
return this.cleaner.clean(result, getWorkingDirectory().toURI().toString(), getUri());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -42,8 +42,7 @@ import static org.springframework.cloud.config.client.ConfigClientProperties.STA
|
||||
* @author Haytham Mohamed
|
||||
* @author Scott Frederick
|
||||
*/
|
||||
public abstract class AbstractVaultEnvironmentRepository
|
||||
implements EnvironmentRepository, Ordered {
|
||||
public abstract class AbstractVaultEnvironmentRepository implements EnvironmentRepository, Ordered {
|
||||
|
||||
// TODO: move to watchState:String on findOne?
|
||||
protected final ObjectProvider<HttpServletRequest> request;
|
||||
@@ -64,8 +63,8 @@ public abstract class AbstractVaultEnvironmentRepository
|
||||
|
||||
protected int order;
|
||||
|
||||
public AbstractVaultEnvironmentRepository(ObjectProvider<HttpServletRequest> request,
|
||||
EnvironmentWatch watch, VaultEnvironmentProperties properties) {
|
||||
public AbstractVaultEnvironmentRepository(ObjectProvider<HttpServletRequest> request, EnvironmentWatch watch,
|
||||
VaultEnvironmentProperties properties) {
|
||||
this.defaultKey = properties.getDefaultKey();
|
||||
this.profileSeparator = properties.getProfileSeparator();
|
||||
this.order = properties.getOrder();
|
||||
@@ -80,8 +79,7 @@ public abstract class AbstractVaultEnvironmentRepository
|
||||
|
||||
List<String> keys = findKeys(application, scrubbedProfiles);
|
||||
|
||||
Environment environment = new Environment(application, profiles, label, null,
|
||||
getWatchState());
|
||||
Environment environment = new Environment(application, profiles, label, null, getWatchState());
|
||||
|
||||
for (String key : keys) {
|
||||
// read raw 'data' key from vault
|
||||
@@ -115,8 +113,7 @@ public abstract class AbstractVaultEnvironmentRepository
|
||||
private List<String> findKeys(String application, List<String> profiles) {
|
||||
List<String> keys = new ArrayList<>();
|
||||
|
||||
if (StringUtils.hasText(this.defaultKey)
|
||||
&& !this.defaultKey.equals(application)) {
|
||||
if (StringUtils.hasText(this.defaultKey) && !this.defaultKey.equals(application)) {
|
||||
keys.add(this.defaultKey);
|
||||
addProfiles(keys, this.defaultKey, profiles);
|
||||
}
|
||||
@@ -138,8 +135,7 @@ public abstract class AbstractVaultEnvironmentRepository
|
||||
return scrubbedProfiles;
|
||||
}
|
||||
|
||||
private void addProfiles(List<String> contexts, String baseContext,
|
||||
List<String> profiles) {
|
||||
private void addProfiles(List<String> contexts, String baseContext, List<String> profiles) {
|
||||
for (String profile : profiles) {
|
||||
contexts.add(baseContext + this.profileSeparator + profile);
|
||||
}
|
||||
|
||||
@@ -37,8 +37,7 @@ import org.springframework.util.StringUtils;
|
||||
* @author Clay McCoy
|
||||
* @author Scott Frederick
|
||||
*/
|
||||
public class AwsS3EnvironmentRepository
|
||||
implements EnvironmentRepository, Ordered, SearchPathLocator {
|
||||
public class AwsS3EnvironmentRepository implements EnvironmentRepository, Ordered, SearchPathLocator {
|
||||
|
||||
private static final String AWS_S3_RESOURCE_SCHEME = "s3://";
|
||||
|
||||
@@ -52,8 +51,7 @@ public class AwsS3EnvironmentRepository
|
||||
|
||||
protected int order = Ordered.LOWEST_PRECEDENCE;
|
||||
|
||||
public AwsS3EnvironmentRepository(AmazonS3 s3Client, String bucketName,
|
||||
ConfigServerProperties server) {
|
||||
public AwsS3EnvironmentRepository(AmazonS3 s3Client, String bucketName, ConfigServerProperties server) {
|
||||
this.s3Client = s3Client;
|
||||
this.bucketName = bucketName;
|
||||
this.serverProperties = server;
|
||||
@@ -69,14 +67,12 @@ public class AwsS3EnvironmentRepository
|
||||
}
|
||||
|
||||
@Override
|
||||
public Environment findOne(String specifiedApplication, String specifiedProfiles,
|
||||
String specifiedLabel) {
|
||||
public Environment findOne(String specifiedApplication, String specifiedProfiles, String specifiedLabel) {
|
||||
final String application = StringUtils.isEmpty(specifiedApplication)
|
||||
? serverProperties.getDefaultApplicationName() : specifiedApplication;
|
||||
final String profiles = StringUtils.isEmpty(specifiedProfiles)
|
||||
? serverProperties.getDefaultProfile() : specifiedProfiles;
|
||||
final String label = StringUtils.isEmpty(specifiedLabel)
|
||||
? serverProperties.getDefaultLabel() : specifiedLabel;
|
||||
final String profiles = StringUtils.isEmpty(specifiedProfiles) ? serverProperties.getDefaultProfile()
|
||||
: specifiedProfiles;
|
||||
final String label = StringUtils.isEmpty(specifiedLabel) ? serverProperties.getDefaultLabel() : specifiedLabel;
|
||||
|
||||
String[] profileArray = parseProfiles(profiles);
|
||||
|
||||
@@ -90,13 +86,11 @@ public class AwsS3EnvironmentRepository
|
||||
|
||||
final Properties config = s3ConfigFile.read();
|
||||
config.putAll(serverProperties.getOverrides());
|
||||
StringBuilder propertySourceName = new StringBuilder().append("s3:")
|
||||
.append(application);
|
||||
StringBuilder propertySourceName = new StringBuilder().append("s3:").append(application);
|
||||
if (profile != null) {
|
||||
propertySourceName.append("-").append(profile);
|
||||
}
|
||||
environment
|
||||
.add(new PropertySource(propertySourceName.toString(), config));
|
||||
environment.add(new PropertySource(propertySourceName.toString(), config));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,18 +104,15 @@ public class AwsS3EnvironmentRepository
|
||||
return StringUtils.commaDelimitedListToStringArray(profiles);
|
||||
}
|
||||
|
||||
private S3ConfigFile getS3ConfigFile(String application, String profile,
|
||||
String label) {
|
||||
private S3ConfigFile getS3ConfigFile(String application, String profile, String label) {
|
||||
String objectKeyPrefix = buildObjectKeyPrefix(application, profile, label);
|
||||
|
||||
final S3ObjectIdBuilder s3ObjectIdBuilder = new S3ObjectIdBuilder()
|
||||
.withBucket(bucketName);
|
||||
final S3ObjectIdBuilder s3ObjectIdBuilder = new S3ObjectIdBuilder().withBucket(bucketName);
|
||||
|
||||
return getS3ConfigFile(s3ObjectIdBuilder, objectKeyPrefix);
|
||||
}
|
||||
|
||||
private String buildObjectKeyPrefix(String application, String profile,
|
||||
String label) {
|
||||
private String buildObjectKeyPrefix(String application, String profile, String label) {
|
||||
StringBuilder objectKeyPrefix = new StringBuilder();
|
||||
if (!StringUtils.isEmpty(label)) {
|
||||
objectKeyPrefix.append(label).append(PATH_SEPARATOR);
|
||||
@@ -133,27 +124,24 @@ public class AwsS3EnvironmentRepository
|
||||
return objectKeyPrefix.toString();
|
||||
}
|
||||
|
||||
private S3ConfigFile getS3ConfigFile(S3ObjectIdBuilder s3ObjectIdBuilder,
|
||||
String keyPrefix) {
|
||||
private S3ConfigFile getS3ConfigFile(S3ObjectIdBuilder s3ObjectIdBuilder, String keyPrefix) {
|
||||
try {
|
||||
final S3Object properties = s3Client.getObject(new GetObjectRequest(
|
||||
s3ObjectIdBuilder.withKey(keyPrefix + ".properties").build()));
|
||||
final S3Object properties = s3Client
|
||||
.getObject(new GetObjectRequest(s3ObjectIdBuilder.withKey(keyPrefix + ".properties").build()));
|
||||
return new PropertyS3ConfigFile(properties.getObjectMetadata().getVersionId(),
|
||||
properties.getObjectContent());
|
||||
}
|
||||
catch (Exception eProperties) {
|
||||
try {
|
||||
final S3Object yaml = s3Client.getObject(new GetObjectRequest(
|
||||
s3ObjectIdBuilder.withKey(keyPrefix + ".yml").build()));
|
||||
return new YamlS3ConfigFile(yaml.getObjectMetadata().getVersionId(),
|
||||
yaml.getObjectContent());
|
||||
final S3Object yaml = s3Client
|
||||
.getObject(new GetObjectRequest(s3ObjectIdBuilder.withKey(keyPrefix + ".yml").build()));
|
||||
return new YamlS3ConfigFile(yaml.getObjectMetadata().getVersionId(), yaml.getObjectContent());
|
||||
}
|
||||
catch (Exception eYaml) {
|
||||
try {
|
||||
final S3Object json = s3Client.getObject(new GetObjectRequest(
|
||||
s3ObjectIdBuilder.withKey(keyPrefix + ".json").build()));
|
||||
return new JsonS3ConfigFile(json.getObjectMetadata().getVersionId(),
|
||||
json.getObjectContent());
|
||||
final S3Object json = s3Client
|
||||
.getObject(new GetObjectRequest(s3ObjectIdBuilder.withKey(keyPrefix + ".json").build()));
|
||||
return new JsonS3ConfigFile(json.getObjectMetadata().getVersionId(), json.getObjectContent());
|
||||
}
|
||||
catch (Exception eJson) {
|
||||
return null;
|
||||
@@ -164,11 +152,9 @@ public class AwsS3EnvironmentRepository
|
||||
|
||||
@Override
|
||||
public Locations getLocations(String application, String profiles, String label) {
|
||||
String baseLocation = AWS_S3_RESOURCE_SCHEME + bucketName + PATH_SEPARATOR
|
||||
+ application;
|
||||
String baseLocation = AWS_S3_RESOURCE_SCHEME + bucketName + PATH_SEPARATOR + application;
|
||||
|
||||
return new Locations(application, profiles, label, null,
|
||||
new String[] { baseLocation });
|
||||
return new Locations(application, profiles, label, null, new String[] { baseLocation });
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -21,8 +21,8 @@ import com.amazonaws.services.s3.AmazonS3ClientBuilder;
|
||||
|
||||
import org.springframework.cloud.config.server.config.ConfigServerProperties;
|
||||
|
||||
public class AwsS3EnvironmentRepositoryFactory implements
|
||||
EnvironmentRepositoryFactory<AwsS3EnvironmentRepository, AwsS3EnvironmentProperties> {
|
||||
public class AwsS3EnvironmentRepositoryFactory
|
||||
implements EnvironmentRepositoryFactory<AwsS3EnvironmentRepository, AwsS3EnvironmentProperties> {
|
||||
|
||||
final private ConfigServerProperties server;
|
||||
|
||||
@@ -31,8 +31,7 @@ public class AwsS3EnvironmentRepositoryFactory implements
|
||||
}
|
||||
|
||||
@Override
|
||||
public AwsS3EnvironmentRepository build(
|
||||
AwsS3EnvironmentProperties environmentProperties) {
|
||||
public AwsS3EnvironmentRepository build(AwsS3EnvironmentProperties environmentProperties) {
|
||||
final AmazonS3ClientBuilder clientBuilder = AmazonS3ClientBuilder.standard();
|
||||
if (environmentProperties.getRegion() != null) {
|
||||
clientBuilder.withRegion(environmentProperties.getRegion());
|
||||
|
||||
@@ -37,8 +37,7 @@ public class CompositeEnvironmentRepository implements EnvironmentRepository {
|
||||
* @param environmentRepositories The list of {@link EnvironmentRepository}s to create
|
||||
* the composite from.
|
||||
*/
|
||||
public CompositeEnvironmentRepository(
|
||||
List<EnvironmentRepository> environmentRepositories) {
|
||||
public CompositeEnvironmentRepository(List<EnvironmentRepository> environmentRepositories) {
|
||||
// Sort the environment repositories by the priority
|
||||
Collections.sort(environmentRepositories, OrderComparator.INSTANCE);
|
||||
this.environmentRepositories = environmentRepositories;
|
||||
@@ -50,21 +49,18 @@ public class CompositeEnvironmentRepository implements EnvironmentRepository {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Environment findOne(String application, String profile, String label,
|
||||
boolean includeOrigin) {
|
||||
Environment env = new Environment(application, new String[] { profile }, label,
|
||||
null, null);
|
||||
public Environment findOne(String application, String profile, String label, boolean includeOrigin) {
|
||||
Environment env = new Environment(application, new String[] { profile }, label, null, null);
|
||||
if (this.environmentRepositories.size() == 1) {
|
||||
Environment envRepo = this.environmentRepositories.get(0).findOne(application,
|
||||
profile, label, includeOrigin);
|
||||
Environment envRepo = this.environmentRepositories.get(0).findOne(application, profile, label,
|
||||
includeOrigin);
|
||||
env.addAll(envRepo.getPropertySources());
|
||||
env.setVersion(envRepo.getVersion());
|
||||
env.setState(envRepo.getState());
|
||||
}
|
||||
else {
|
||||
for (EnvironmentRepository repo : environmentRepositories) {
|
||||
env.addAll(repo.findOne(application, profile, label, includeOrigin)
|
||||
.getPropertySources());
|
||||
env.addAll(repo.findOne(application, profile, label, includeOrigin).getPropertySources());
|
||||
}
|
||||
}
|
||||
return env;
|
||||
|
||||
@@ -23,7 +23,6 @@ import org.eclipse.jgit.transport.http.HttpConnectionFactory;
|
||||
*/
|
||||
public interface ConfigurableHttpConnectionFactory extends HttpConnectionFactory {
|
||||
|
||||
void addConfiguration(MultipleJGitEnvironmentProperties environmentProperties)
|
||||
throws Exception;
|
||||
void addConfiguration(MultipleJGitEnvironmentProperties environmentProperties) throws Exception;
|
||||
|
||||
}
|
||||
|
||||
@@ -102,8 +102,8 @@ public class ConsulEnvironmentWatch implements EnvironmentWatch {
|
||||
headers.add(CONSUL_TOKEN, this.token);
|
||||
}
|
||||
HttpEntity<Object> request = new HttpEntity<>(headers);
|
||||
ResponseEntity<List<String>> response = this.restTemplate.exchange(WATCH_URL,
|
||||
HttpMethod.GET, request, RESPONSE_TYPE, params.toArray());
|
||||
ResponseEntity<List<String>> response = this.restTemplate.exchange(WATCH_URL, HttpMethod.GET, request,
|
||||
RESPONSE_TYPE, params.toArray());
|
||||
|
||||
if (response.getStatusCode().is2xxSuccessful()) {
|
||||
String consulIndex = response.getHeaders().getFirst(CONSUL_INDEX);
|
||||
|
||||
@@ -57,15 +57,12 @@ public class CredhubEnvironmentRepository implements EnvironmentRepository {
|
||||
|
||||
String[] profiles = StringUtils.commaDelimitedListToStringArray(profilesList);
|
||||
|
||||
Environment environment = new Environment(application, profiles, label, null,
|
||||
null);
|
||||
Environment environment = new Environment(application, profiles, label, null, null);
|
||||
for (String profile : profiles) {
|
||||
environment.add(new PropertySource(
|
||||
"credhub-" + application + "-" + profile + "-" + label,
|
||||
environment.add(new PropertySource("credhub-" + application + "-" + profile + "-" + label,
|
||||
findProperties(application, profile, label)));
|
||||
if (!DEFAULT_APPLICATION.equals(application)) {
|
||||
addDefaultPropertySource(environment, DEFAULT_APPLICATION, profile,
|
||||
label);
|
||||
addDefaultPropertySource(environment, DEFAULT_APPLICATION, profile, label);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,35 +70,30 @@ public class CredhubEnvironmentRepository implements EnvironmentRepository {
|
||||
addDefaultPropertySource(environment, application, DEFAULT_PROFILE, label);
|
||||
}
|
||||
|
||||
if (!Arrays.asList(profiles).contains(DEFAULT_PROFILE)
|
||||
&& !DEFAULT_APPLICATION.equals(application)) {
|
||||
addDefaultPropertySource(environment, DEFAULT_APPLICATION, DEFAULT_PROFILE,
|
||||
label);
|
||||
if (!Arrays.asList(profiles).contains(DEFAULT_PROFILE) && !DEFAULT_APPLICATION.equals(application)) {
|
||||
addDefaultPropertySource(environment, DEFAULT_APPLICATION, DEFAULT_PROFILE, label);
|
||||
}
|
||||
|
||||
return environment;
|
||||
}
|
||||
|
||||
private void addDefaultPropertySource(Environment environment, String application,
|
||||
String profile, String label) {
|
||||
private void addDefaultPropertySource(Environment environment, String application, String profile, String label) {
|
||||
Map<Object, Object> properties = findProperties(application, profile, label);
|
||||
if (!properties.isEmpty()) {
|
||||
PropertySource propertySource = new PropertySource(
|
||||
"credhub-" + application + "-" + profile + "-" + label, properties);
|
||||
PropertySource propertySource = new PropertySource("credhub-" + application + "-" + profile + "-" + label,
|
||||
properties);
|
||||
environment.add(propertySource);
|
||||
}
|
||||
}
|
||||
|
||||
private Map<Object, Object> findProperties(String application, String profile,
|
||||
String label) {
|
||||
private Map<Object, Object> findProperties(String application, String profile, String label) {
|
||||
String path = "/" + application + "/" + profile + "/" + label;
|
||||
|
||||
return this.credHubOperations.credentials().findByPath(path).stream()
|
||||
.map(credentialSummary -> credentialSummary.getName().getName())
|
||||
.map(name -> this.credHubOperations.credentials()
|
||||
.getByName(new SimpleCredentialName(name), JsonCredential.class))
|
||||
.map(CredentialDetails::getValue)
|
||||
.flatMap(jsonCredential -> jsonCredential.entrySet().stream())
|
||||
.map(name -> this.credHubOperations.credentials().getByName(new SimpleCredentialName(name),
|
||||
JsonCredential.class))
|
||||
.map(CredentialDetails::getValue).flatMap(jsonCredential -> jsonCredential.entrySet().stream())
|
||||
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> b));
|
||||
}
|
||||
|
||||
|
||||
@@ -21,8 +21,8 @@ import org.springframework.credhub.core.CredHubOperations;
|
||||
/**
|
||||
* @author Alberto C. Ríos
|
||||
*/
|
||||
public class CredhubEnvironmentRepositoryFactory implements
|
||||
EnvironmentRepositoryFactory<CredhubEnvironmentRepository, CredhubEnvironmentProperties> {
|
||||
public class CredhubEnvironmentRepositoryFactory
|
||||
implements EnvironmentRepositoryFactory<CredhubEnvironmentRepository, CredhubEnvironmentProperties> {
|
||||
|
||||
private CredHubOperations credhubOperations;
|
||||
|
||||
@@ -31,8 +31,7 @@ public class CredhubEnvironmentRepositoryFactory implements
|
||||
}
|
||||
|
||||
@Override
|
||||
public CredhubEnvironmentRepository build(
|
||||
CredhubEnvironmentProperties environmentProperties) {
|
||||
public CredhubEnvironmentRepository build(CredhubEnvironmentProperties environmentProperties) {
|
||||
return new CredhubEnvironmentRepository(this.credhubOperations);
|
||||
}
|
||||
|
||||
|
||||
@@ -42,8 +42,7 @@ public class EnvironmentCleaner {
|
||||
protected Map<?, ?> clean(Map<?, ?> source, String uri) {
|
||||
for (Map.Entry<?, ?> entry : source.entrySet()) {
|
||||
if (entry.getValue() instanceof PropertyValueDescriptor) {
|
||||
PropertyValueDescriptor descriptor = (PropertyValueDescriptor) entry
|
||||
.getValue();
|
||||
PropertyValueDescriptor descriptor = (PropertyValueDescriptor) entry.getValue();
|
||||
if (!uri.endsWith("/")) {
|
||||
uri = uri + "/";
|
||||
}
|
||||
|
||||
@@ -62,8 +62,7 @@ import static org.springframework.cloud.config.server.support.EnvironmentPropert
|
||||
*
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping(method = RequestMethod.GET,
|
||||
path = "${spring.cloud.config.server.prefix:}")
|
||||
@RequestMapping(method = RequestMethod.GET, path = "${spring.cloud.config.server.prefix:}")
|
||||
public class EnvironmentController {
|
||||
|
||||
private EnvironmentRepository repository;
|
||||
@@ -78,8 +77,7 @@ public class EnvironmentController {
|
||||
this(repository, new ObjectMapper());
|
||||
}
|
||||
|
||||
public EnvironmentController(EnvironmentRepository repository,
|
||||
ObjectMapper objectMapper) {
|
||||
public EnvironmentController(EnvironmentRepository repository, ObjectMapper objectMapper) {
|
||||
this.repository = repository;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
@@ -101,42 +99,32 @@ public class EnvironmentController {
|
||||
this.acceptEmpty = acceptEmpty;
|
||||
}
|
||||
|
||||
@RequestMapping(path = "/{name}/{profiles:.*[^-].*}",
|
||||
produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public Environment defaultLabel(@PathVariable String name,
|
||||
@PathVariable String profiles) {
|
||||
@RequestMapping(path = "/{name}/{profiles:.*[^-].*}", produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public Environment defaultLabel(@PathVariable String name, @PathVariable String profiles) {
|
||||
return getEnvironment(name, profiles, null, false);
|
||||
}
|
||||
|
||||
@RequestMapping(path = "/{name}/{profiles:.*[^-].*}",
|
||||
produces = EnvironmentMediaType.V2_JSON)
|
||||
public Environment defaultLabelIncludeOrigin(@PathVariable String name,
|
||||
@PathVariable String profiles) {
|
||||
@RequestMapping(path = "/{name}/{profiles:.*[^-].*}", produces = EnvironmentMediaType.V2_JSON)
|
||||
public Environment defaultLabelIncludeOrigin(@PathVariable String name, @PathVariable String profiles) {
|
||||
return getEnvironment(name, profiles, null, true);
|
||||
}
|
||||
|
||||
@RequestMapping(path = "/{name}/{profiles}/{label:.*}",
|
||||
produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public Environment labelled(@PathVariable String name, @PathVariable String profiles,
|
||||
@PathVariable String label) {
|
||||
@RequestMapping(path = "/{name}/{profiles}/{label:.*}", produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public Environment labelled(@PathVariable String name, @PathVariable String profiles, @PathVariable String label) {
|
||||
return getEnvironment(name, profiles, label, false);
|
||||
}
|
||||
|
||||
@RequestMapping(path = "/{name}/{profiles}/{label:.*}",
|
||||
produces = EnvironmentMediaType.V2_JSON)
|
||||
public Environment labelledIncludeOrigin(@PathVariable String name,
|
||||
@PathVariable String profiles, @PathVariable String label) {
|
||||
@RequestMapping(path = "/{name}/{profiles}/{label:.*}", produces = EnvironmentMediaType.V2_JSON)
|
||||
public Environment labelledIncludeOrigin(@PathVariable String name, @PathVariable String profiles,
|
||||
@PathVariable String label) {
|
||||
return getEnvironment(name, profiles, label, true);
|
||||
}
|
||||
|
||||
public Environment getEnvironment(String name, String profiles, String label,
|
||||
boolean includeOrigin) {
|
||||
public Environment getEnvironment(String name, String profiles, String label, boolean includeOrigin) {
|
||||
name = normalize(name);
|
||||
label = normalize(label);
|
||||
Environment environment = this.repository.findOne(name, profiles, label,
|
||||
includeOrigin);
|
||||
if (!this.acceptEmpty
|
||||
&& (environment == null || environment.getPropertySources().isEmpty())) {
|
||||
Environment environment = this.repository.findOne(name, profiles, label, includeOrigin);
|
||||
if (!this.acceptEmpty && (environment == null || environment.getPropertySources().isEmpty())) {
|
||||
throw new EnvironmentNotFoundException("Profile Not found");
|
||||
}
|
||||
return environment;
|
||||
@@ -150,41 +138,34 @@ public class EnvironmentController {
|
||||
}
|
||||
|
||||
@RequestMapping("/{name}-{profiles}.properties")
|
||||
public ResponseEntity<String> properties(@PathVariable String name,
|
||||
@PathVariable String profiles,
|
||||
@RequestParam(defaultValue = "true") boolean resolvePlaceholders)
|
||||
throws IOException {
|
||||
public ResponseEntity<String> properties(@PathVariable String name, @PathVariable String profiles,
|
||||
@RequestParam(defaultValue = "true") boolean resolvePlaceholders) throws IOException {
|
||||
return labelledProperties(name, profiles, null, resolvePlaceholders);
|
||||
}
|
||||
|
||||
@RequestMapping("/{label}/{name}-{profiles}.properties")
|
||||
public ResponseEntity<String> labelledProperties(@PathVariable String name,
|
||||
@PathVariable String profiles, @PathVariable String label,
|
||||
@RequestParam(defaultValue = "true") boolean resolvePlaceholders)
|
||||
public ResponseEntity<String> labelledProperties(@PathVariable String name, @PathVariable String profiles,
|
||||
@PathVariable String label, @RequestParam(defaultValue = "true") boolean resolvePlaceholders)
|
||||
throws IOException {
|
||||
validateProfiles(profiles);
|
||||
Environment environment = labelled(name, profiles, label);
|
||||
Map<String, Object> properties = convertToProperties(environment);
|
||||
String propertiesString = getPropertiesString(properties);
|
||||
if (resolvePlaceholders) {
|
||||
propertiesString = resolvePlaceholders(prepareEnvironment(environment),
|
||||
propertiesString);
|
||||
propertiesString = resolvePlaceholders(prepareEnvironment(environment), propertiesString);
|
||||
}
|
||||
return getSuccess(propertiesString);
|
||||
}
|
||||
|
||||
@RequestMapping("{name}-{profiles}.json")
|
||||
public ResponseEntity<String> jsonProperties(@PathVariable String name,
|
||||
@PathVariable String profiles,
|
||||
@RequestParam(defaultValue = "true") boolean resolvePlaceholders)
|
||||
throws Exception {
|
||||
public ResponseEntity<String> jsonProperties(@PathVariable String name, @PathVariable String profiles,
|
||||
@RequestParam(defaultValue = "true") boolean resolvePlaceholders) throws Exception {
|
||||
return labelledJsonProperties(name, profiles, null, resolvePlaceholders);
|
||||
}
|
||||
|
||||
@RequestMapping("/{label}/{name}-{profiles}.json")
|
||||
public ResponseEntity<String> labelledJsonProperties(@PathVariable String name,
|
||||
@PathVariable String profiles, @PathVariable String label,
|
||||
@RequestParam(defaultValue = "true") boolean resolvePlaceholders)
|
||||
public ResponseEntity<String> labelledJsonProperties(@PathVariable String name, @PathVariable String profiles,
|
||||
@PathVariable String label, @RequestParam(defaultValue = "true") boolean resolvePlaceholders)
|
||||
throws Exception {
|
||||
validateProfiles(profiles);
|
||||
Environment environment = labelled(name, profiles, label);
|
||||
@@ -208,24 +189,19 @@ public class EnvironmentController {
|
||||
}
|
||||
|
||||
@RequestMapping({ "/{name}-{profiles}.yml", "/{name}-{profiles}.yaml" })
|
||||
public ResponseEntity<String> yaml(@PathVariable String name,
|
||||
@PathVariable String profiles,
|
||||
@RequestParam(defaultValue = "true") boolean resolvePlaceholders)
|
||||
throws Exception {
|
||||
public ResponseEntity<String> yaml(@PathVariable String name, @PathVariable String profiles,
|
||||
@RequestParam(defaultValue = "true") boolean resolvePlaceholders) throws Exception {
|
||||
return labelledYaml(name, profiles, null, resolvePlaceholders);
|
||||
}
|
||||
|
||||
@RequestMapping({ "/{label}/{name}-{profiles}.yml",
|
||||
"/{label}/{name}-{profiles}.yaml" })
|
||||
public ResponseEntity<String> labelledYaml(@PathVariable String name,
|
||||
@PathVariable String profiles, @PathVariable String label,
|
||||
@RequestParam(defaultValue = "true") boolean resolvePlaceholders)
|
||||
@RequestMapping({ "/{label}/{name}-{profiles}.yml", "/{label}/{name}-{profiles}.yaml" })
|
||||
public ResponseEntity<String> labelledYaml(@PathVariable String name, @PathVariable String profiles,
|
||||
@PathVariable String label, @RequestParam(defaultValue = "true") boolean resolvePlaceholders)
|
||||
throws Exception {
|
||||
validateProfiles(profiles);
|
||||
Environment environment = labelled(name, profiles, label);
|
||||
Map<String, Object> result = convertToMap(environment);
|
||||
if (this.stripDocument && result.size() == 1
|
||||
&& result.keySet().iterator().next().equals("document")) {
|
||||
if (this.stripDocument && result.size() == 1 && result.keySet().iterator().next().equals("document")) {
|
||||
Object value = result.get("document");
|
||||
if (value instanceof Collection) {
|
||||
return getSuccess(new Yaml().dumpAs(value, Tag.SEQ, FlowStyle.BLOCK));
|
||||
@@ -276,8 +252,7 @@ public class EnvironmentController {
|
||||
}
|
||||
|
||||
@ExceptionHandler(EnvironmentException.class)
|
||||
public void environmentException(HttpServletResponse response, EnvironmentException e)
|
||||
throws IOException {
|
||||
public void environmentException(HttpServletResponse response, EnvironmentException e) throws IOException {
|
||||
response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
|
||||
}
|
||||
|
||||
@@ -295,8 +270,7 @@ public class EnvironmentController {
|
||||
}
|
||||
|
||||
private ResponseEntity<String> getSuccess(String body) {
|
||||
return new ResponseEntity<>(body, getHttpHeaders(MediaType.TEXT_PLAIN),
|
||||
HttpStatus.OK);
|
||||
return new ResponseEntity<>(body, getHttpHeaders(MediaType.TEXT_PLAIN), HttpStatus.OK);
|
||||
}
|
||||
|
||||
private ResponseEntity<String> getSuccess(String body, MediaType mediaType) {
|
||||
@@ -461,8 +435,7 @@ public class EnvironmentController {
|
||||
break;
|
||||
}
|
||||
else if (!Character.isDigit(c)) {
|
||||
throw new IllegalArgumentException(
|
||||
"Invalid key: " + this.propertyKey);
|
||||
throw new IllegalArgumentException("Invalid key: " + this.propertyKey);
|
||||
}
|
||||
}
|
||||
// If no closing ] or if '[]'
|
||||
@@ -470,8 +443,7 @@ public class EnvironmentController {
|
||||
throw new IllegalArgumentException("Invalid key: " + this.propertyKey);
|
||||
}
|
||||
else {
|
||||
int index = Integer
|
||||
.parseInt(this.propertyKey.substring(start, this.currentPos));
|
||||
int index = Integer.parseInt(this.propertyKey.substring(start, this.currentPos));
|
||||
// Skip the closing ]
|
||||
this.currentPos++;
|
||||
if (this.currentPos == this.propertyKey.length()) {
|
||||
@@ -486,8 +458,7 @@ public class EnvironmentController {
|
||||
this.valueType = NodeType.ARRAY;
|
||||
break;
|
||||
default:
|
||||
throw new IllegalArgumentException(
|
||||
"Invalid key: " + this.propertyKey);
|
||||
throw new IllegalArgumentException("Invalid key: " + this.propertyKey);
|
||||
}
|
||||
}
|
||||
return index;
|
||||
|
||||
@@ -56,16 +56,13 @@ public class EnvironmentEncryptorEnvironmentRepository implements EnvironmentRep
|
||||
}
|
||||
|
||||
@Override
|
||||
public Environment findOne(String name, String profiles, String label,
|
||||
boolean includeOrigin) {
|
||||
Environment environment = this.delegate.findOne(name, profiles, label,
|
||||
includeOrigin);
|
||||
public Environment findOne(String name, String profiles, String label, boolean includeOrigin) {
|
||||
Environment environment = this.delegate.findOne(name, profiles, label, includeOrigin);
|
||||
if (this.environmentEncryptor != null) {
|
||||
environment = this.environmentEncryptor.decrypt(environment);
|
||||
}
|
||||
if (!this.overrides.isEmpty()) {
|
||||
environment.addFirst(
|
||||
new PropertySource("overrides", getOverridesMap(includeOrigin)));
|
||||
environment.addFirst(new PropertySource("overrides", getOverridesMap(includeOrigin)));
|
||||
}
|
||||
return environment;
|
||||
}
|
||||
@@ -76,8 +73,7 @@ public class EnvironmentEncryptorEnvironmentRepository implements EnvironmentRep
|
||||
}
|
||||
Map<Object, Object> map = new LinkedHashMap<>();
|
||||
for (Map.Entry entry : this.overrides.entrySet()) {
|
||||
map.put(entry.getKey(), new PropertyValueDescriptor(entry.getValue(),
|
||||
"Config server overrides"));
|
||||
map.put(entry.getKey(), new PropertyValueDescriptor(entry.getValue(), "Config server overrides"));
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
@@ -26,8 +26,7 @@ public interface EnvironmentRepository {
|
||||
|
||||
Environment findOne(String application, String profile, String label);
|
||||
|
||||
default Environment findOne(String application, String profile, String label,
|
||||
boolean includeOrigin) {
|
||||
default Environment findOne(String application, String profile, String label, boolean includeOrigin) {
|
||||
return findOne(application, profile, label);
|
||||
}
|
||||
|
||||
|
||||
@@ -39,8 +39,8 @@ public class EnvironmentRepositoryPropertySourceLocator implements PropertySourc
|
||||
|
||||
private String label;
|
||||
|
||||
public EnvironmentRepositoryPropertySourceLocator(EnvironmentRepository repository,
|
||||
String name, String profiles, String label) {
|
||||
public EnvironmentRepositoryPropertySourceLocator(EnvironmentRepository repository, String name, String profiles,
|
||||
String label) {
|
||||
this.repository = repository;
|
||||
this.name = name;
|
||||
this.profiles = profiles;
|
||||
@@ -48,11 +48,9 @@ public class EnvironmentRepositoryPropertySourceLocator implements PropertySourc
|
||||
}
|
||||
|
||||
@Override
|
||||
public org.springframework.core.env.PropertySource<?> locate(
|
||||
Environment environment) {
|
||||
public org.springframework.core.env.PropertySource<?> locate(Environment environment) {
|
||||
CompositePropertySource composite = new CompositePropertySource("configService");
|
||||
for (PropertySource source : this.repository
|
||||
.findOne(this.name, this.profiles, this.label, false)
|
||||
for (PropertySource source : this.repository.findOne(this.name, this.profiles, this.label, false)
|
||||
.getPropertySources()) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> map = (Map<String, Object>) source.getSource();
|
||||
|
||||
@@ -44,13 +44,11 @@ import static java.util.stream.Collectors.toMap;
|
||||
/**
|
||||
* @author Dylan Roberts
|
||||
*/
|
||||
public class HttpClientConfigurableHttpConnectionFactory
|
||||
implements ConfigurableHttpConnectionFactory {
|
||||
public class HttpClientConfigurableHttpConnectionFactory implements ConfigurableHttpConnectionFactory {
|
||||
|
||||
private static final String PLACEHOLDER_PATTERN_STRING = "\\{(\\w+)}";
|
||||
|
||||
private static final Pattern PLACEHOLDER_PATTERN = Pattern
|
||||
.compile(PLACEHOLDER_PATTERN_STRING);
|
||||
private static final Pattern PLACEHOLDER_PATTERN = Pattern.compile(PLACEHOLDER_PATTERN_STRING);
|
||||
|
||||
Log log = LogFactory.getLog(getClass());
|
||||
|
||||
@@ -72,36 +70,32 @@ public class HttpClientConfigurableHttpConnectionFactory
|
||||
|
||||
@Override
|
||||
public HttpConnection create(URL url, Proxy proxy) throws IOException {
|
||||
return new HttpClientConnection(url.toString(), null,
|
||||
lookupHttpClientBuilder(url).build());
|
||||
return new HttpClientConnection(url.toString(), null, lookupHttpClientBuilder(url).build());
|
||||
}
|
||||
|
||||
private void addHttpClient(JGitEnvironmentProperties properties)
|
||||
throws GeneralSecurityException {
|
||||
private void addHttpClient(JGitEnvironmentProperties properties) throws GeneralSecurityException {
|
||||
if (properties.getUri() != null && properties.getUri().startsWith("http")) {
|
||||
this.httpClientBuildersByUri.put(properties.getUri(),
|
||||
HttpClientSupport.builder(properties));
|
||||
this.httpClientBuildersByUri.put(properties.getUri(), HttpClientSupport.builder(properties));
|
||||
}
|
||||
}
|
||||
|
||||
private HttpClientBuilder lookupHttpClientBuilder(final URL url) {
|
||||
Map<String, HttpClientBuilder> builderMap = this.httpClientBuildersByUri
|
||||
.entrySet().stream().filter(entry -> {
|
||||
String key = entry.getKey();
|
||||
String spec = getUrlWithPlaceholders(url, key);
|
||||
if (spec.equals(key)) {
|
||||
return true;
|
||||
}
|
||||
int index = spec.lastIndexOf("/");
|
||||
while (index != -1) {
|
||||
spec = spec.substring(0, index);
|
||||
if (spec.equals(key)) {
|
||||
return true;
|
||||
}
|
||||
index = spec.lastIndexOf("/");
|
||||
}
|
||||
return false;
|
||||
}).collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
|
||||
Map<String, HttpClientBuilder> builderMap = this.httpClientBuildersByUri.entrySet().stream().filter(entry -> {
|
||||
String key = entry.getKey();
|
||||
String spec = getUrlWithPlaceholders(url, key);
|
||||
if (spec.equals(key)) {
|
||||
return true;
|
||||
}
|
||||
int index = spec.lastIndexOf("/");
|
||||
while (index != -1) {
|
||||
spec = spec.substring(0, index);
|
||||
if (spec.equals(key)) {
|
||||
return true;
|
||||
}
|
||||
index = spec.lastIndexOf("/");
|
||||
}
|
||||
return false;
|
||||
}).collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
|
||||
|
||||
if (builderMap.isEmpty()) {
|
||||
this.log.warn(String.format("No custom http config found for URL: %s", url));
|
||||
@@ -114,8 +108,7 @@ public class HttpClientConfigurableHttpConnectionFactory
|
||||
* which have no placeholders. That is the one we want to use in the case
|
||||
* there are multiple matches.
|
||||
*/
|
||||
List<String> keys = builderMap.keySet().stream()
|
||||
.filter(key -> !PLACEHOLDER_PATTERN.matcher(key).find())
|
||||
List<String> keys = builderMap.keySet().stream().filter(key -> !PLACEHOLDER_PATTERN.matcher(key).find())
|
||||
.collect(Collectors.toList());
|
||||
|
||||
if (keys.size() == 1) {
|
||||
@@ -140,8 +133,7 @@ public class HttpClientConfigurableHttpConnectionFactory
|
||||
List<String> values = getValues(spec, tokens);
|
||||
if (placeholders.size() == values.size()) {
|
||||
for (int i = 0; i < values.size(); i++) {
|
||||
spec = spec.replace(values.get(i),
|
||||
String.format("{%s}", placeholders.get(i)));
|
||||
spec = spec.replace(values.get(i), String.format("{%s}", placeholders.get(i)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,12 +27,10 @@ import org.springframework.web.client.RestTemplate;
|
||||
/**
|
||||
* @author Dylan Roberts
|
||||
*/
|
||||
public class HttpClientVaultRestTemplateFactory
|
||||
implements VaultEnvironmentRepositoryFactory.VaultRestTemplateFactory {
|
||||
public class HttpClientVaultRestTemplateFactory implements VaultEnvironmentRepositoryFactory.VaultRestTemplateFactory {
|
||||
|
||||
@Override
|
||||
public RestTemplate build(VaultEnvironmentProperties environmentProperties)
|
||||
throws GeneralSecurityException {
|
||||
public RestTemplate build(VaultEnvironmentProperties environmentProperties) throws GeneralSecurityException {
|
||||
HttpClient httpClient = HttpClientSupport.builder(environmentProperties).build();
|
||||
return new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
|
||||
}
|
||||
|
||||
@@ -29,8 +29,7 @@ public class HttpRequestConfigTokenProvider implements ConfigTokenProvider {
|
||||
|
||||
private ObjectProvider<HttpServletRequest> httpRequest;
|
||||
|
||||
public HttpRequestConfigTokenProvider(
|
||||
ObjectProvider<HttpServletRequest> httpRequest) {
|
||||
public HttpRequestConfigTokenProvider(ObjectProvider<HttpServletRequest> httpRequest) {
|
||||
this.httpRequest = httpRequest;
|
||||
}
|
||||
|
||||
@@ -44,8 +43,7 @@ public class HttpRequestConfigTokenProvider implements ConfigTokenProvider {
|
||||
String token = request.getHeader(ConfigClientProperties.TOKEN_HEADER);
|
||||
if (!StringUtils.hasLength(token)) {
|
||||
throw new IllegalArgumentException(
|
||||
"Missing required header in HttpServletRequest: "
|
||||
+ ConfigClientProperties.TOKEN_HEADER);
|
||||
"Missing required header in HttpServletRequest: " + ConfigClientProperties.TOKEN_HEADER);
|
||||
}
|
||||
|
||||
return token;
|
||||
|
||||
@@ -232,8 +232,7 @@ public class JGitEnvironmentProperties extends AbstractScmAccessorProperties
|
||||
return this.proxy;
|
||||
}
|
||||
|
||||
public void setProxy(
|
||||
Map<ProxyHostProperties.ProxyForScheme, ProxyHostProperties> proxy) {
|
||||
public void setProxy(Map<ProxyHostProperties.ProxyForScheme, ProxyHostProperties> proxy) {
|
||||
this.proxy = proxy;
|
||||
}
|
||||
|
||||
|
||||
@@ -147,8 +147,7 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository
|
||||
*/
|
||||
private boolean skipSslValidation;
|
||||
|
||||
public JGitEnvironmentRepository(ConfigurableEnvironment environment,
|
||||
JGitEnvironmentProperties properties) {
|
||||
public JGitEnvironmentRepository(ConfigurableEnvironment environment, JGitEnvironmentProperties properties) {
|
||||
super(environment, properties);
|
||||
this.cloneOnStart = properties.isCloneOnStart();
|
||||
this.defaultLabel = properties.getDefaultLabel();
|
||||
@@ -187,8 +186,7 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository
|
||||
return this.transportConfigCallback;
|
||||
}
|
||||
|
||||
public void setTransportConfigCallback(
|
||||
TransportConfigCallback transportConfigCallback) {
|
||||
public void setTransportConfigCallback(TransportConfigCallback transportConfigCallback) {
|
||||
this.transportConfigCallback = transportConfigCallback;
|
||||
}
|
||||
|
||||
@@ -200,8 +198,7 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository
|
||||
this.gitFactory = gitFactory;
|
||||
}
|
||||
|
||||
public void setGitCredentialsProviderFactory(
|
||||
GitCredentialsProviderFactory gitCredentialsProviderFactory) {
|
||||
public void setGitCredentialsProviderFactory(GitCredentialsProviderFactory gitCredentialsProviderFactory) {
|
||||
this.gitCredentialsProviderFactory = gitCredentialsProviderFactory;
|
||||
}
|
||||
|
||||
@@ -238,8 +235,7 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized Locations getLocations(String application, String profile,
|
||||
String label) {
|
||||
public synchronized Locations getLocations(String application, String profile, String label) {
|
||||
if (label == null) {
|
||||
label = this.defaultLabel;
|
||||
}
|
||||
@@ -269,8 +265,7 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository
|
||||
if (shouldPull(git)) {
|
||||
FetchResult fetchStatus = fetch(git, label);
|
||||
if (this.deleteUntrackedBranches && fetchStatus != null) {
|
||||
deleteUntrackedLocalBranches(fetchStatus.getTrackingRefUpdates(),
|
||||
git);
|
||||
deleteUntrackedLocalBranches(fetchStatus.getTrackingRefUpdates(), git);
|
||||
}
|
||||
// checkout after fetch so we can get any new branches, tags, ect.
|
||||
checkout(git, label);
|
||||
@@ -292,8 +287,7 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository
|
||||
throw new NoSuchRepositoryException("No such repository: " + getUri(), e);
|
||||
}
|
||||
catch (GitAPIException e) {
|
||||
throw new NoSuchRepositoryException(
|
||||
"Cannot clone or checkout repository: " + getUri(), e);
|
||||
throw new NoSuchRepositoryException("Cannot clone or checkout repository: " + getUri(), e);
|
||||
}
|
||||
catch (Exception e) {
|
||||
throw new IllegalStateException("Cannot load environment", e);
|
||||
@@ -316,16 +310,14 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository
|
||||
// merge results from fetch
|
||||
merge(git, label);
|
||||
if (!isClean(git, label)) {
|
||||
this.logger.warn(
|
||||
"The local repository is dirty or ahead of origin. Resetting"
|
||||
+ " it to origin/" + label + ".");
|
||||
this.logger.warn("The local repository is dirty or ahead of origin. Resetting" + " it to origin/"
|
||||
+ label + ".");
|
||||
resetHard(git, label, LOCAL_BRANCH_REF_PREFIX + label);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (GitAPIException e) {
|
||||
throw new NoSuchRepositoryException(
|
||||
"Cannot clone or checkout repository: " + getUri(), e);
|
||||
throw new NoSuchRepositoryException("Cannot clone or checkout repository: " + getUri(), e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -355,8 +347,7 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository
|
||||
* @param git git instance
|
||||
* @return list of deleted branches
|
||||
*/
|
||||
private Collection<String> deleteUntrackedLocalBranches(
|
||||
Collection<TrackingRefUpdate> trackingRefUpdates, Git git) {
|
||||
private Collection<String> deleteUntrackedLocalBranches(Collection<TrackingRefUpdate> trackingRefUpdates, Git git) {
|
||||
if (CollectionUtils.isEmpty(trackingRefUpdates)) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
@@ -366,10 +357,9 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository
|
||||
ReceiveCommand receiveCommand = trackingRefUpdate.asReceiveCommand();
|
||||
if (receiveCommand.getType() == DELETE) {
|
||||
String localRefName = trackingRefUpdate.getLocalName();
|
||||
if (StringUtils.startsWithIgnoreCase(localRefName,
|
||||
LOCAL_BRANCH_REF_PREFIX)) {
|
||||
String localBranchName = localRefName.substring(
|
||||
LOCAL_BRANCH_REF_PREFIX.length(), localRefName.length());
|
||||
if (StringUtils.startsWithIgnoreCase(localRefName, LOCAL_BRANCH_REF_PREFIX)) {
|
||||
String localBranchName = localRefName.substring(LOCAL_BRANCH_REF_PREFIX.length(),
|
||||
localRefName.length());
|
||||
branchesToDelete.add(localBranchName);
|
||||
}
|
||||
}
|
||||
@@ -391,16 +381,14 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository
|
||||
}
|
||||
}
|
||||
|
||||
private List<String> deleteBranches(Git git, Collection<String> branchesToDelete)
|
||||
throws GitAPIException {
|
||||
private List<String> deleteBranches(Git git, Collection<String> branchesToDelete) throws GitAPIException {
|
||||
DeleteBranchCommand deleteBranchCommand = git.branchDelete()
|
||||
.setBranchNames(branchesToDelete.toArray(new String[0]))
|
||||
// local branch can contain data which is not merged to HEAD - force
|
||||
// delete it anyway, since local copy should be R/O
|
||||
.setForce(true);
|
||||
List<String> resultList = deleteBranchCommand.call();
|
||||
this.logger.info(format("Deleted %s branches from %s branches to delete.",
|
||||
resultList, branchesToDelete));
|
||||
this.logger.info(format("Deleted %s branches from %s branches to delete.", resultList, branchesToDelete));
|
||||
return resultList;
|
||||
}
|
||||
|
||||
@@ -419,15 +407,13 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository
|
||||
protected boolean shouldPull(Git git) throws GitAPIException {
|
||||
boolean shouldPull;
|
||||
|
||||
if (this.refreshRate > 0 && System.currentTimeMillis()
|
||||
- this.lastRefresh < (this.refreshRate * 1000)) {
|
||||
if (this.refreshRate > 0 && System.currentTimeMillis() - this.lastRefresh < (this.refreshRate * 1000)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Status gitStatus = git.status().call();
|
||||
boolean isWorkingTreeClean = gitStatus.isClean();
|
||||
String originUrl = git.getRepository().getConfig().getString("remote", "origin",
|
||||
"url");
|
||||
String originUrl = git.getRepository().getConfig().getString("remote", "origin", "url");
|
||||
|
||||
if (this.forcePull && !isWorkingTreeClean) {
|
||||
shouldPull = true;
|
||||
@@ -437,17 +423,15 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository
|
||||
shouldPull = isWorkingTreeClean && originUrl != null;
|
||||
}
|
||||
if (!isWorkingTreeClean && !this.forcePull) {
|
||||
this.logger.info("Cannot pull from remote " + originUrl
|
||||
+ ", the working tree is not clean.");
|
||||
this.logger.info("Cannot pull from remote " + originUrl + ", the working tree is not clean.");
|
||||
}
|
||||
return shouldPull;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private void logDirty(Status status) {
|
||||
Set<String> dirties = dirties(status.getAdded(), status.getChanged(),
|
||||
status.getRemoved(), status.getMissing(), status.getModified(),
|
||||
status.getConflicting(), status.getUntracked());
|
||||
Set<String> dirties = dirties(status.getAdded(), status.getChanged(), status.getRemoved(), status.getMissing(),
|
||||
status.getModified(), status.getConflicting(), status.getUntracked());
|
||||
this.logger.warn(format("Dirty files found: %s", dirties));
|
||||
}
|
||||
|
||||
@@ -476,16 +460,15 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository
|
||||
configureCommand(fetch);
|
||||
try {
|
||||
FetchResult result = fetch.call();
|
||||
if (result.getTrackingRefUpdates() != null
|
||||
&& result.getTrackingRefUpdates().size() > 0) {
|
||||
this.logger.info("Fetched for remote " + label + " and found "
|
||||
+ result.getTrackingRefUpdates().size() + " updates");
|
||||
if (result.getTrackingRefUpdates() != null && result.getTrackingRefUpdates().size() > 0) {
|
||||
this.logger.info("Fetched for remote " + label + " and found " + result.getTrackingRefUpdates().size()
|
||||
+ " updates");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
catch (Exception ex) {
|
||||
String message = "Could not fetch remote for " + label + " remote: " + git
|
||||
.getRepository().getConfig().getString("remote", "origin", "url");
|
||||
String message = "Could not fetch remote for " + label + " remote: "
|
||||
+ git.getRepository().getConfig().getString("remote", "origin", "url");
|
||||
warn(message, ex);
|
||||
return null;
|
||||
}
|
||||
@@ -497,14 +480,13 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository
|
||||
merge.include(git.getRepository().findRef("origin/" + label));
|
||||
MergeResult result = merge.call();
|
||||
if (!result.getMergeStatus().isSuccessful()) {
|
||||
this.logger.warn("Merged from remote " + label + " with result "
|
||||
+ result.getMergeStatus());
|
||||
this.logger.warn("Merged from remote " + label + " with result " + result.getMergeStatus());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
catch (Exception ex) {
|
||||
String message = "Could not merge remote for " + label + " remote: " + git
|
||||
.getRepository().getConfig().getString("remote", "origin", "url");
|
||||
String message = "Could not merge remote for " + label + " remote: "
|
||||
+ git.getRepository().getConfig().getString("remote", "origin", "url");
|
||||
warn(message, ex);
|
||||
return null;
|
||||
}
|
||||
@@ -517,15 +499,13 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository
|
||||
try {
|
||||
Ref resetRef = reset.call();
|
||||
if (resetRef != null) {
|
||||
this.logger.info(
|
||||
"Reset label " + label + " to version " + resetRef.getObjectId());
|
||||
this.logger.info("Reset label " + label + " to version " + resetRef.getObjectId());
|
||||
}
|
||||
return resetRef;
|
||||
}
|
||||
catch (Exception ex) {
|
||||
String message = "Could not reset to remote for " + label + " (current ref="
|
||||
+ ref + "), remote: " + git.getRepository().getConfig()
|
||||
.getString("remote", "origin", "url");
|
||||
String message = "Could not reset to remote for " + label + " (current ref=" + ref + "), remote: "
|
||||
+ git.getRepository().getConfig().getString("remote", "origin", "url");
|
||||
warn(message, ex);
|
||||
return null;
|
||||
}
|
||||
@@ -582,8 +562,8 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository
|
||||
}
|
||||
|
||||
private Git cloneToBasedir() throws GitAPIException {
|
||||
CloneCommand clone = this.gitFactory.getCloneCommandByCloneRepository()
|
||||
.setURI(getUri()).setDirectory(getBasedir());
|
||||
CloneCommand clone = this.gitFactory.getCloneCommandByCloneRepository().setURI(getUri())
|
||||
.setDirectory(getBasedir());
|
||||
configureCommand(clone);
|
||||
try {
|
||||
return clone.call();
|
||||
@@ -602,8 +582,7 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository
|
||||
FileUtils.delete(file, FileUtils.RECURSIVE);
|
||||
}
|
||||
catch (IOException e) {
|
||||
throw new IllegalStateException("Failed to initialize base directory",
|
||||
e);
|
||||
throw new IllegalStateException("Failed to initialize base directory", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -614,8 +593,7 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository
|
||||
SshSessionFactory.setInstance(new JschConfigSessionFactory() {
|
||||
@Override
|
||||
protected void configure(Host hc, Session session) {
|
||||
session.setConfig("StrictHostKeyChecking",
|
||||
isStrictHostKeyChecking() ? "yes" : "no");
|
||||
session.setConfig("StrictHostKeyChecking", isStrictHostKeyChecking() ? "yes" : "no");
|
||||
}
|
||||
});
|
||||
this.initialized = true;
|
||||
@@ -634,17 +612,15 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository
|
||||
}
|
||||
|
||||
private CredentialsProvider getCredentialsProvider() {
|
||||
return this.gitCredentialsProviderFactory.createFor(this.getUri(), getUsername(),
|
||||
getPassword(), getPassphrase(), isSkipSslValidation());
|
||||
return this.gitCredentialsProviderFactory.createFor(this.getUri(), getUsername(), getPassword(),
|
||||
getPassphrase(), isSkipSslValidation());
|
||||
}
|
||||
|
||||
private boolean isClean(Git git, String label) {
|
||||
StatusCommand status = git.status();
|
||||
try {
|
||||
BranchTrackingStatus trackingStatus = BranchTrackingStatus
|
||||
.of(git.getRepository(), label);
|
||||
boolean isBranchAhead = trackingStatus != null
|
||||
&& trackingStatus.getAheadCount() > 0;
|
||||
BranchTrackingStatus trackingStatus = BranchTrackingStatus.of(git.getRepository(), label);
|
||||
boolean isBranchAhead = trackingStatus != null && trackingStatus.getAheadCount() > 0;
|
||||
return status.call().isClean() && !isBranchAhead;
|
||||
}
|
||||
catch (Exception e) {
|
||||
@@ -656,8 +632,7 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository
|
||||
}
|
||||
|
||||
private void trackBranch(Git git, CheckoutCommand checkout, String label) {
|
||||
checkout.setCreateBranch(true).setName(label)
|
||||
.setUpstreamMode(SetupUpstreamMode.TRACK)
|
||||
checkout.setCreateBranch(true).setName(label).setUpstreamMode(SetupUpstreamMode.TRACK)
|
||||
.setStartPoint("origin/" + label);
|
||||
}
|
||||
|
||||
@@ -669,8 +644,7 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository
|
||||
return containsBranch(git, label, null);
|
||||
}
|
||||
|
||||
private boolean containsBranch(Git git, String label, ListMode listMode)
|
||||
throws GitAPIException {
|
||||
private boolean containsBranch(Git git, String label, ListMode listMode) throws GitAPIException {
|
||||
ListBranchCommand command = git.branchList();
|
||||
if (listMode != null) {
|
||||
command.setListMode(listMode);
|
||||
|
||||
@@ -58,8 +58,7 @@ public class JdbcEnvironmentRepository implements EnvironmentRepository, Ordered
|
||||
|
||||
private String sql;
|
||||
|
||||
public JdbcEnvironmentRepository(JdbcTemplate jdbc,
|
||||
JdbcEnvironmentProperties properties) {
|
||||
public JdbcEnvironmentRepository(JdbcTemplate jdbc, JdbcEnvironmentProperties properties) {
|
||||
this.jdbc = jdbc;
|
||||
this.order = properties.getOrder();
|
||||
this.sql = properties.getSql();
|
||||
@@ -86,15 +85,13 @@ public class JdbcEnvironmentRepository implements EnvironmentRepository, Ordered
|
||||
profile = "default," + profile;
|
||||
}
|
||||
String[] profiles = StringUtils.commaDelimitedListToStringArray(profile);
|
||||
Environment environment = new Environment(application, profiles, label, null,
|
||||
null);
|
||||
Environment environment = new Environment(application, profiles, label, null, null);
|
||||
if (!config.startsWith("application")) {
|
||||
config = "application," + config;
|
||||
}
|
||||
List<String> applications = new ArrayList<String>(new LinkedHashSet<>(
|
||||
Arrays.asList(StringUtils.commaDelimitedListToStringArray(config))));
|
||||
List<String> envs = new ArrayList<String>(
|
||||
new LinkedHashSet<>(Arrays.asList(profiles)));
|
||||
List<String> applications = new ArrayList<String>(
|
||||
new LinkedHashSet<>(Arrays.asList(StringUtils.commaDelimitedListToStringArray(config))));
|
||||
List<String> envs = new ArrayList<String>(new LinkedHashSet<>(Arrays.asList(profiles)));
|
||||
Collections.reverse(applications);
|
||||
Collections.reverse(envs);
|
||||
for (String app : applications) {
|
||||
@@ -123,8 +120,7 @@ public class JdbcEnvironmentRepository implements EnvironmentRepository, Ordered
|
||||
class PropertiesResultSetExtractor implements ResultSetExtractor<Map<String, String>> {
|
||||
|
||||
@Override
|
||||
public Map<String, String> extractData(ResultSet rs)
|
||||
throws SQLException, DataAccessException {
|
||||
public Map<String, String> extractData(ResultSet rs) throws SQLException, DataAccessException {
|
||||
Map<String, String> map = new LinkedHashMap<>();
|
||||
while (rs.next()) {
|
||||
map.put(rs.getString(1), rs.getString(2));
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user