Skip to content

Commit

Permalink
Formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
spencergibb committed Sep 17, 2020
1 parent 13518fb commit baa1bd4
Show file tree
Hide file tree
Showing 234 changed files with 2,532 additions and 4,273 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -64,16 +64,14 @@ public static void createCertificates() throws Exception {
}

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();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,7 @@ public String root() {
}

private boolean tlsEnabled() {
return app.getEnvironment().getProperty("server.ssl.enabled", Boolean.class,
false);
return app.getEnvironment().getProperty("server.ssl.enabled", Boolean.class, false);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,7 @@ public KeyStore storeKeyAndCert(String keyPassword) throws Exception {
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;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,15 +50,12 @@ public KeyAndCert createCA(String ca) throws Exception {
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;
Expand All @@ -76,32 +73,25 @@ public KeyPair createKeyPair(int keySize) throws Exception {

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));

Expand All @@ -110,14 +100,11 @@ private JcaX509v3CertificateBuilder certBuilder(PublicKey publicKey, String issu
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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,15 @@ 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() {
property("server.ssl.enabled", "true");
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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,7 @@ public int getOrder() {

@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);
Expand All @@ -82,8 +81,7 @@ public ConfigData load(ConfigDataLoaderContext context, L location)
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
Expand All @@ -98,8 +96,8 @@ public ConfigData load(ConfigDataLoaderContext context, L location)
@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));
}
}

Expand All @@ -120,8 +118,7 @@ public ConfigData load(ConfigDataLoaderContext context, L location)
}
catch (HttpServerErrorException e) {
error = e;
if (MediaType.APPLICATION_JSON
.includes(e.getResponseHeaders().getContentType())) {
if (MediaType.APPLICATION_JSON.includes(e.getResponseHeaders().getContentType())) {
errorBody = e.getResponseBodyAsString();
}
}
Expand All @@ -136,23 +133,18 @@ public ConfigData load(ConfigDataLoaderContext context, L location)
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()) {
Expand All @@ -162,30 +154,25 @@ protected void log(Environment result) {
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;

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;
}
Expand All @@ -210,8 +197,7 @@ protected Environment getRemoteEnvironment(L location, String label, String stat

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) {
Expand All @@ -237,8 +223,7 @@ protected Environment getRemoteEnvironment(L location, String label, String stat

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);
Expand All @@ -248,17 +233,15 @@ protected Environment getRemoteEnvironment(L location, String label, String stat
}

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) {
throw e;
}
}
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;
}
Expand All @@ -278,13 +261,12 @@ protected Environment getRemoteEnvironment(L location, String label, String stat
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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -66,23 +66,19 @@ public boolean equals(Object o) {
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();

}

Expand Down
Loading

0 comments on commit baa1bd4

Please sign in to comment.