Java 8 code cleanup.

Replace nullable elements with Optional. Replace explicit type arguments with diamond syntax. Replace anonymous inner classes with lambdas.
This commit is contained in:
Mark Paluch
2017-04-25 17:34:25 +02:00
parent 6a6f8b937a
commit 2fadfaefd0
34 changed files with 320 additions and 506 deletions

View File

@@ -181,7 +181,7 @@ class VaultPropertySourceRegistrar implements ImportBeanDefinitionRegistrar,
static Set<AnnotationAttributes> attributesForRepeatable(AnnotationMetadata metadata,
String containerClassName, String annotationClassName) {
Set<AnnotationAttributes> result = new LinkedHashSet<AnnotationAttributes>();
Set<AnnotationAttributes> result = new LinkedHashSet<>();
addAttributesIfNotNull(result,
metadata.getAnnotationAttributes(annotationClassName, false));

View File

@@ -91,7 +91,7 @@ public class AppIdAuthentication implements ClientAuthentication {
private Map<String, String> getAppIdLogin(String appId, String userId) {
Map<String, String> login = new HashMap<String, String>();
Map<String, String> login = new HashMap<>();
login.put("app_id", appId);
login.put("user_id", userId);
return login;

View File

@@ -93,7 +93,7 @@ public class AppRoleAuthentication implements ClientAuthentication {
private Map<String, String> getAppRoleLogin(String roleId, String secretId) {
Map<String, String> login = new HashMap<String, String>();
Map<String, String> login = new HashMap<>();
login.put("role_id", roleId);
if (secretId != null) {
login.put("secret_id", secretId);

View File

@@ -49,13 +49,15 @@ public class AwsEc2Authentication implements ClientAuthentication {
private static final Log logger = LogFactory.getLog(AwsEc2Authentication.class);
private final static char[] EMPTY = new char[0];
private final AwsEc2AuthenticationOptions options;
private final RestOperations vaultRestOperations;
private final RestOperations awsMetadataRestOperations;
private final AtomicReference<char[]> nonce = new AtomicReference<char[]>();
private final AtomicReference<char[]> nonce = new AtomicReference<>(EMPTY);
/**
* Create a new {@link AwsEc2Authentication}.
@@ -77,7 +79,8 @@ public class AwsEc2Authentication implements ClientAuthentication {
* @param awsMetadataRestOperations must not be {@literal null}.
*/
public AwsEc2Authentication(AwsEc2AuthenticationOptions options,
RestOperations vaultRestOperations, RestOperations awsMetadataRestOperations) {
RestOperations vaultRestOperations,
RestOperations awsMetadataRestOperations) {
Assert.notNull(options, "AwsEc2AuthenticationOptions must not be null");
Assert.notNull(vaultRestOperations, "Vault RestOperations must not be null");
@@ -109,10 +112,9 @@ public class AwsEc2Authentication implements ClientAuthentication {
if (response.getAuth().get("metadata") instanceof Map) {
Map<Object, Object> metadata = (Map<Object, Object>) response
.getAuth().get("metadata");
logger.debug(String
.format("Login successful using AWS-EC2 authentication for instance %s, AMI %s",
metadata.get("instance_id"),
metadata.get("instance_id")));
logger.debug(String.format(
"Login successful using AWS-EC2 authentication for instance %s, AMI %s",
metadata.get("instance_id"), metadata.get("instance_id")));
}
else {
logger.debug("Login successful using AWS-EC2 authentication");
@@ -129,21 +131,21 @@ public class AwsEc2Authentication implements ClientAuthentication {
protected Map<String, String> getEc2Login() {
Map<String, String> login = new HashMap<String, String>();
Map<String, String> login = new HashMap<>();
if (StringUtils.hasText(options.getRole())) {
login.put("role", options.getRole());
}
if (this.nonce.get() == null) {
this.nonce.compareAndSet(null, createNonce());
if (this.nonce.get() == EMPTY) {
this.nonce.compareAndSet(EMPTY, createNonce());
}
login.put("nonce", new String(this.nonce.get()));
try {
String pkcs7 = awsMetadataRestOperations.getForObject(
options.getIdentityDocumentUri(), String.class);
String pkcs7 = awsMetadataRestOperations
.getForObject(options.getIdentityDocumentUri(), String.class);
if (StringUtils.hasText(pkcs7)) {
login.put("pkcs7", pkcs7.replaceAll("\\r", "").replace("\\n", ""));
}
@@ -151,9 +153,10 @@ public class AwsEc2Authentication implements ClientAuthentication {
return login;
}
catch (RestClientException e) {
throw new VaultException(String.format(
"Cannot obtain Identity Document from %s",
options.getIdentityDocumentUri()), e);
throw new VaultException(
String.format("Cannot obtain Identity Document from %s",
options.getIdentityDocumentUri()),
e);
}
}

View File

@@ -180,10 +180,9 @@ public class CubbyholeAuthentication implements ClientAuthentication {
try {
ResponseEntity<VaultResponse> entity = restOperations.exchange(
options.getPath(),
HttpMethod.GET,
new HttpEntity<Object>(VaultHttpHeaders.from(options
.getInitialToken())), VaultResponse.class);
options.getPath(), HttpMethod.GET,
new HttpEntity<>(VaultHttpHeaders.from(options.getInitialToken())),
VaultResponse.class);
return entity.getBody().getData();
}
@@ -222,10 +221,9 @@ public class CubbyholeAuthentication implements ClientAuthentication {
}
if (data == null || data.isEmpty()) {
throw new VaultException(
String.format(
"Cannot retrieve Token from Cubbyhole: Response at %s does not contain a token",
options.getPath()));
throw new VaultException(String.format(
"Cannot retrieve Token from Cubbyhole: Response at %s does not contain a token",
options.getPath()));
}
if (data.size() == 1) {
@@ -233,9 +231,8 @@ public class CubbyholeAuthentication implements ClientAuthentication {
return VaultToken.of(token);
}
throw new VaultException(
String.format(
"Cannot retrieve Token from Cubbyhole: Response at %s does not contain an unique token",
options.getPath()));
throw new VaultException(String.format(
"Cannot retrieve Token from Cubbyhole: Response at %s does not contain an unique token",
options.getPath()));
}
}

View File

@@ -17,6 +17,7 @@ package org.springframework.vault.authentication;
import java.util.Date;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -82,7 +83,7 @@ public class LifecycleAwareSessionManager implements SessionManager, DisposableB
private final Object lock = new Object();
private volatile VaultToken token;
private volatile Optional<VaultToken> token = Optional.empty();
/**
* Create a {@link LifecycleAwareSessionManager} given {@link ClientAuthentication},
@@ -126,19 +127,17 @@ public class LifecycleAwareSessionManager implements SessionManager, DisposableB
@Override
public void destroy() {
VaultToken token = this.token;
this.token = null;
Optional<VaultToken> token = this.token;
this.token = Optional.empty();
if (token instanceof LoginToken) {
revoke(token);
}
token.filter(LoginToken.class::isInstance).ifPresent(this::revoke);
}
private void revoke(VaultToken token) {
try {
restOperations.postForObject("/auth/token/revoke-self",
new HttpEntity<Object>(VaultHttpHeaders.from(token)), Map.class);
restOperations.postForObject("/auth/token/revoke-self", new HttpEntity<>(
VaultHttpHeaders.from(token)), Map.class);
}
catch (HttpStatusCodeException e) {
logger.warn(String.format("Cannot revoke VaultToken: %s",
@@ -159,14 +158,14 @@ public class LifecycleAwareSessionManager implements SessionManager, DisposableB
logger.info("Renewing token");
if (token == null) {
if (!token.isPresent()) {
getSessionToken();
return false;
}
try {
restOperations.postForObject("/auth/token/renew-self",
new HttpEntity<Object>(VaultHttpHeaders.from(token)), Map.class);
restOperations.postForObject("/auth/token/renew-self", new HttpEntity<>(
VaultHttpHeaders.from(token.get())), Map.class);
return true;
}
catch (HttpStatusCodeException e) {
@@ -189,12 +188,12 @@ public class LifecycleAwareSessionManager implements SessionManager, DisposableB
@Override
public VaultToken getSessionToken() {
if (token == null) {
if (!token.isPresent()) {
synchronized (lock) {
if (token == null) {
token = login();
if (!token.isPresent()) {
token = Optional.ofNullable(clientAuthentication.login());
if (isTokenRenewable()) {
scheduleRenewal();
@@ -203,7 +202,8 @@ public class LifecycleAwareSessionManager implements SessionManager, DisposableB
}
}
return token;
return token.orElseThrow(() -> new IllegalStateException(
"Cannot obtain VaultToken"));
}
protected VaultToken login() {
@@ -212,13 +212,12 @@ public class LifecycleAwareSessionManager implements SessionManager, DisposableB
protected boolean isTokenRenewable() {
if (token instanceof LoginToken) {
return token.filter(LoginToken.class::isInstance) //
.filter(it -> {
LoginToken loginToken = (LoginToken) token;
return loginToken.getLeaseDuration() > 0 && loginToken.isRenewable();
}
return false;
LoginToken loginToken = (LoginToken) it;
return loginToken.getLeaseDuration() > 0 && loginToken.isRenewable();
}).isPresent();
}
private void scheduleRenewal() {
@@ -246,7 +245,7 @@ public class LifecycleAwareSessionManager implements SessionManager, DisposableB
}
private OneShotTrigger createTrigger() {
return new OneShotTrigger(refreshTrigger.nextExecutionTime((LoginToken) token));
return new OneShotTrigger(refreshTrigger.nextExecutionTime((LoginToken) token.get()));
}
/**

View File

@@ -16,19 +16,18 @@
package org.springframework.vault.authentication;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.net.SocketException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
/**
@@ -42,10 +41,6 @@ import org.springframework.util.StringUtils;
*/
public class MacAddressUserId implements AppIdUserIdMechanism {
// Compatibility with Java 1.7 and greater
private static final Method GET_INDEX = ReflectionUtils
.findMethod(NetworkInterface.class, "getIndex");
private final Log log = LogFactory.getLog(MacAddressUserId.class);
private final String networkInterfaceHint;
@@ -92,7 +87,7 @@ public class MacAddressUserId implements AppIdUserIdMechanism {
try {
NetworkInterface networkInterface = null;
Optional<NetworkInterface> networkInterface = Optional.empty();
List<NetworkInterface> interfaces = Collections
.list(NetworkInterface.getNetworkInterfaces());
@@ -108,7 +103,7 @@ public class MacAddressUserId implements AppIdUserIdMechanism {
}
}
if (networkInterface == null) {
if (!networkInterface.isPresent()) {
if (StringUtils.hasText(networkInterfaceHint)) {
log.warn(String.format(
@@ -117,96 +112,79 @@ public class MacAddressUserId implements AppIdUserIdMechanism {
}
InetAddress localHost = InetAddress.getLocalHost();
networkInterface = NetworkInterface.getByInetAddress(localHost);
if (networkInterface == null
|| networkInterface.getHardwareAddress() == null) {
networkInterface = Optional
.ofNullable(NetworkInterface.getByInetAddress(localHost));
if (!networkInterface.filter(MacAddressUserId::hasNetworkAddress)
.isPresent()) {
networkInterface = getNetworkInterfaceWithHardwareAddress(interfaces);
}
if (networkInterface == null) {
throw new IllegalStateException(String.format(
"Cannot determine NetworkInterface for %s", localHost));
}
}
byte[] mac = networkInterface.getHardwareAddress();
if (mac == null) {
throw new IllegalStateException(
String.format("Network interface %s has no hardware address",
networkInterface.getName()));
}
return Sha256.toSha256(Sha256.toHexString(mac));
return networkInterface.map(MacAddressUserId::getRequiredNetworkAddress) //
.map(Sha256::toHexString) //
.map(Sha256::toSha256) //
.orElseThrow(() -> new IllegalStateException(
"Cannot determine NetworkInterface"));
}
catch (IOException e) {
throw new IllegalStateException(e);
}
}
private static NetworkInterface getNetworkInterface(Number hint,
private static Optional<NetworkInterface> getNetworkInterface(Number hint,
List<NetworkInterface> interfaces) {
if (interfaces.size() > hint.intValue() && hint.intValue() >= 0) {
return interfaces.get(hint.intValue());
return Optional.of(interfaces.get(hint.intValue()));
}
return null;
return Optional.empty();
}
private static NetworkInterface getNetworkInterface(String hint,
private static Optional<NetworkInterface> getNetworkInterface(String hint,
List<NetworkInterface> interfaces) {
for (NetworkInterface anInterface : interfaces) {
if (hint.equals(anInterface.getDisplayName())
|| hint.equals(anInterface.getName())) {
return anInterface;
}
}
return null;
return interfaces.stream() //
.filter(anInterface -> matchesHint(hint, anInterface)) //
.findFirst();
}
private static NetworkInterface getNetworkInterfaceWithHardwareAddress(
List<NetworkInterface> interfaces) throws IOException {
private static boolean matchesHint(String hint, NetworkInterface networkInterface) {
List<NetworkInterface> networkInterfacesToUse = interfaces;
if (GET_INDEX != null) {
networkInterfacesToUse = new ArrayList<NetworkInterface>(interfaces);
Collections.sort(networkInterfacesToUse,
NetworkInterfaceIndexComparator.INSTANCE);
}
for (NetworkInterface anInterface : networkInterfacesToUse) {
byte[] hardwareAddress = anInterface.getHardwareAddress();
if (hardwareAddress != null) {
return anInterface;
}
}
return null;
return hint.equals(networkInterface.getDisplayName())
|| hint.equals(networkInterface.getName());
}
/**
* @since 1.0.1
*/
enum NetworkInterfaceIndexComparator implements Comparator<NetworkInterface> {
INSTANCE;
private static Optional<NetworkInterface> getNetworkInterfaceWithHardwareAddress(
List<NetworkInterface> interfaces) {
@Override
public int compare(NetworkInterface o1, NetworkInterface o2) {
return interfaces.stream() //
.filter(MacAddressUserId::hasNetworkAddress) //
.sorted(Comparator.comparingInt(NetworkInterface::getIndex)) //
.findFirst();
}
try {
int left = (Integer) GET_INDEX.invoke(o1);
int right = (Integer) GET_INDEX.invoke(o2);
return (left < right) ? -1 : ((left == right) ? 0 : 1);
}
catch (Exception e) {
throw new IllegalStateException(
"Cannot retrieve index from NetworkInterface", e);
}
private static Optional<byte[]> getNetworkAddress(NetworkInterface it) {
try {
return Optional.ofNullable(it.getHardwareAddress());
}
catch (SocketException e) {
throw new IllegalStateException(String
.format("Cannot determine hardware address for %s", it.getName()));
}
}
private static byte[] getRequiredNetworkAddress(NetworkInterface it) {
return getNetworkAddress(it) //
.orElseThrow(() -> new IllegalStateException(String.format(
"Network interface %s has no hardware address", it.getName())));
}
private static boolean hasNetworkAddress(NetworkInterface it) {
return getNetworkAddress(it).isPresent();
}
}

View File

@@ -17,6 +17,7 @@
package org.springframework.vault.authentication;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
@@ -29,7 +30,7 @@ import org.springframework.util.Assert;
*/
class Sha256 {
private static final Charset US_ASCII = Charset.forName("US-ASCII");
private static final Charset US_ASCII = StandardCharsets.US_ASCII;
/**
* Generates a hex-encoded SHA256 checksum from the supplied {@code content}.
@@ -64,10 +65,11 @@ class Sha256 {
}
static String toHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (int i = 0; i < bytes.length; i++) {
sb.append(String.format("%X", bytes[i]));
for (byte b : bytes) {
sb.append(String.format("%X", b));
}
return sb.toString();

View File

@@ -15,6 +15,8 @@
*/
package org.springframework.vault.authentication;
import java.util.Optional;
import org.springframework.util.Assert;
import org.springframework.vault.support.VaultToken;
@@ -34,7 +36,7 @@ public class SimpleSessionManager implements SessionManager {
private final Object lock = new Object();
private volatile VaultToken token;
private volatile Optional<VaultToken> token = Optional.empty();
/**
* Create a new {@link SimpleSessionManager} using a {@link ClientAuthentication}.
@@ -51,14 +53,15 @@ public class SimpleSessionManager implements SessionManager {
@Override
public VaultToken getSessionToken() {
if (token == null) {
if (!token.isPresent()) {
synchronized (lock) {
if (token == null) {
token = clientAuthentication.login();
if (!token.isPresent()) {
token = Optional.of(clientAuthentication.login());
}
}
}
return token;
return token
.orElseThrow(() -> new IllegalStateException("Cannot obtain VaultToken"));
}
}

View File

@@ -15,17 +15,13 @@
*/
package org.springframework.vault.client;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
@@ -88,7 +84,7 @@ public class VaultClients {
*/
public static RestTemplate createRestTemplate() {
List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>(
List<HttpMessageConverter<?>> messageConverters = new ArrayList<>(
3);
messageConverters.add(new ByteArrayHttpMessageConverter());
messageConverters.add(new StringHttpMessageConverter());
@@ -96,14 +92,8 @@ public class VaultClients {
RestTemplate restTemplate = new RestTemplate(messageConverters);
restTemplate.getInterceptors().add(new ClientHttpRequestInterceptor() {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
ClientHttpRequestExecution execution) throws IOException {
return execution.execute(request, body);
}
});
restTemplate.getInterceptors()
.add((request, body, execution) -> execution.execute(request, body));
return restTemplate;
}

View File

@@ -1,63 +0,0 @@
/*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.vault.client;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Utility to obtain a Vault error message.
*
* @author Mark Paluch
*/
class VaultErrorMessage {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
/**
* Obtain the error message from a JSON response.
*
* @param json
* @return
*/
static String getError(String json) {
if (json.contains("\"errors\":")) {
try {
Map<String, Object> map = OBJECT_MAPPER.readValue(json.getBytes(),
Map.class);
if (map.containsKey("errors")) {
Collection<String> errors = (Collection<String>) map.get("errors");
if (errors.size() == 1) {
return errors.iterator().next();
}
return errors.toString();
}
}
catch (IOException o_O) {
// ignore
}
}
return json;
}
}

View File

@@ -129,6 +129,7 @@ public abstract class VaultResponses {
* @param json must not be {@literal null}.
* @return
*/
@SuppressWarnings("unchecked")
public static String getError(String json) {
Assert.notNull(json, "Error JSON must not be null!");

View File

@@ -25,11 +25,10 @@ import org.springframework.vault.client.VaultResponses;
import org.springframework.vault.support.VaultCertificateRequest;
import org.springframework.vault.support.VaultCertificateResponse;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestOperations;
/**
* Default implementation of {@link VaultPkiOperations}.
*
*
* @author Mark Paluch
*/
public class VaultPkiTemplate implements VaultPkiOperations {
@@ -41,7 +40,7 @@ public class VaultPkiTemplate implements VaultPkiOperations {
/**
* Create a new {@link VaultPkiTemplate} given {@link VaultPkiOperations} and the
* mount {@code path}.
*
*
* @param vaultOperations must not be {@literal null}.
* @param path must not be empty or {@literal null}.
*/
@@ -61,21 +60,17 @@ public class VaultPkiTemplate implements VaultPkiOperations {
Assert.hasText(roleName, "Role name must not be empty");
Assert.notNull(certificateRequest, "Certificate request must not be null");
final Map<String, Object> request = new HashMap<String, Object>();
final Map<String, Object> request = new HashMap<>();
request.put("common_name", certificateRequest.getCommonName());
if (!certificateRequest.getAltNames().isEmpty()) {
request.put(
"alt_names",
StringUtils.collectionToDelimitedString(
certificateRequest.getAltNames(), ","));
request.put("alt_names", StringUtils
.collectionToDelimitedString(certificateRequest.getAltNames(), ","));
}
if (!certificateRequest.getIpSubjectAltNames().isEmpty()) {
request.put(
"ip_sans",
StringUtils.collectionToDelimitedString(
certificateRequest.getIpSubjectAltNames(), ","));
request.put("ip_sans", StringUtils.collectionToDelimitedString(
certificateRequest.getIpSubjectAltNames(), ","));
}
if (certificateRequest.getTtl() != null) {
@@ -88,22 +83,16 @@ public class VaultPkiTemplate implements VaultPkiOperations {
request.put("exclude_cn_from_sans", true);
}
return vaultOperations
.doWithSession(new RestOperationsCallback<VaultCertificateResponse>() {
@Override
public VaultCertificateResponse doWithRestOperations(
RestOperations restOperations) {
return vaultOperations.doWithSession(restOperations -> {
try {
return restOperations.postForObject(
"{path}/issue/{roleName}", request,
VaultCertificateResponse.class, path, roleName);
}
catch (HttpStatusCodeException e) {
throw VaultResponses.buildException(e);
}
}
});
try {
return restOperations.postForObject("{path}/issue/{roleName}", request,
VaultCertificateResponse.class, path, roleName);
}
catch (HttpStatusCodeException e) {
throw VaultResponses.buildException(e);
}
});
}
}

View File

@@ -79,20 +79,16 @@ public class VaultSysTemplate implements VaultSysOperations {
@Override
public boolean isInitialized() {
return vaultOperations.doWithVault(new RestOperationsCallback<Boolean>() {
return vaultOperations.doWithVault(restOperations -> {
@Override
public Boolean doWithRestOperations(RestOperations restOperations) {
try {
Map<String, Boolean> body = restOperations.getForObject("/sys/init",
Map.class);
try {
Map<String, Boolean> body = restOperations.getForObject("/sys/init",
Map.class);
return body.get("initialized");
}
catch (HttpStatusCodeException e) {
throw VaultResponses.buildException(e);
}
return body.get("initialized");
}
catch (HttpStatusCodeException e) {
throw VaultResponses.buildException(e);
}
});
}
@@ -104,24 +100,20 @@ public class VaultSysTemplate implements VaultSysOperations {
Assert.notNull(vaultInitializationRequest, "VaultInitialization must not be null");
return vaultOperations
.doWithVault(new RestOperationsCallback<VaultInitializationResponse>() {
.doWithVault(
(RestOperationsCallback<VaultInitializationResponse>) restOperations -> {
@Override
public VaultInitializationResponse doWithRestOperations(
RestOperations restOperations) {
try {
ResponseEntity<VaultInitializationResponseImpl> exchange = restOperations
.exchange("/sys/init", HttpMethod.PUT,
new HttpEntity<Object>(
vaultInitializationRequest),
VaultInitializationResponseImpl.class);
try {
ResponseEntity<VaultInitializationResponseImpl> exchange = restOperations
.exchange("/sys/init", HttpMethod.PUT,
new HttpEntity<Object>(
vaultInitializationRequest),
VaultInitializationResponseImpl.class);
return exchange.getBody();
}
catch (HttpStatusCodeException e) {
throw VaultResponses.buildException(e);
}
return exchange.getBody();
}
catch (HttpStatusCodeException e) {
throw VaultResponses.buildException(e);
}
});
}
@@ -135,21 +127,16 @@ public class VaultSysTemplate implements VaultSysOperations {
public VaultUnsealStatus unseal(final String keyShare) {
return vaultOperations
.doWithVault(new RestOperationsCallback<VaultUnsealStatus>() {
@Override
public VaultUnsealStatus doWithRestOperations(
RestOperations restOperations) {
.doWithVault(
(RestOperationsCallback<VaultUnsealStatus>) restOperations -> {
ResponseEntity<VaultUnsealStatusImpl> response = restOperations
.exchange(
"/sys/unseal",
HttpMethod.PUT,
new HttpEntity<Object>(Collections.singletonMap(
"key", keyShare)),
VaultUnsealStatusImpl.class);
ResponseEntity<VaultUnsealStatusImpl> response = restOperations
.exchange("/sys/unseal", HttpMethod.PUT,
new HttpEntity<Object>(Collections
.singletonMap("key", keyShare)),
VaultUnsealStatusImpl.class);
return response.getBody();
}
return response.getBody();
});
}
@@ -259,7 +246,7 @@ public class VaultSysTemplate implements VaultSysOperations {
private static class VaultMountsResponse extends
VaultResponseSupport<Map<String, VaultMount>> {
private Map<String, VaultMount> topLevelMounts = new HashMap<String, VaultMount>();
private Map<String, VaultMount> topLevelMounts = new HashMap<>();
@JsonIgnore
public Map<String, VaultMount> getTopLevelMounts() {
@@ -316,7 +303,7 @@ public class VaultSysTemplate implements VaultSysOperations {
@Data
static class VaultInitializationResponseImpl implements VaultInitializationResponse {
private List<String> keys = new ArrayList<String>();
private List<String> keys = new ArrayList<>();
@JsonProperty("root_token")
private String rootToken;

View File

@@ -15,7 +15,6 @@
*/
package org.springframework.vault.core;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
@@ -24,13 +23,9 @@ import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.Assert;
import org.springframework.vault.authentication.ClientAuthentication;
@@ -126,17 +121,12 @@ public class VaultTemplate implements InitializingBean, VaultOperations, Disposa
RestTemplate restTemplate = VaultClients.createRestTemplate(endpoint,
requestFactory);
restTemplate.getInterceptors().add(new ClientHttpRequestInterceptor() {
restTemplate.getInterceptors().add((request, body, execution) -> {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
ClientHttpRequestExecution execution) throws IOException {
request.getHeaders().add(VaultHttpHeaders.VAULT_TOKEN,
sessionManager.getSessionToken().getToken());
request.getHeaders().add(VaultHttpHeaders.VAULT_TOKEN,
sessionManager.getSessionToken().getToken());
return execution.execute(request, body);
}
return execution.execute(request, body);
});
return restTemplate;
@@ -208,14 +198,15 @@ public class VaultTemplate implements InitializingBean, VaultOperations, Disposa
@SuppressWarnings("unchecked")
@Override
public <T> VaultResponseSupport<T> read(final String path, final Class<T> responseType) {
public <T> VaultResponseSupport<T> read(final String path,
final Class<T> responseType) {
final ParameterizedTypeReference<VaultResponseSupport<T>> ref = VaultResponses
.getTypeReference(responseType);
try {
ResponseEntity<VaultResponseSupport<T>> exchange = sessionTemplate.exchange(
path, HttpMethod.GET, null, ref);
ResponseEntity<VaultResponseSupport<T>> exchange = sessionTemplate
.exchange(path, HttpMethod.GET, null, ref);
return exchange.getBody();
}
@@ -303,27 +294,23 @@ public class VaultTemplate implements InitializingBean, VaultOperations, Disposa
private <T> T doRead(final String path, final Class<T> responseType) {
return doWithSession(new RestOperationsCallback<T>() {
return doWithSession(restOperations -> {
@Override
public T doWithRestOperations(RestOperations restOperations) {
try {
return restOperations.getForObject(path, responseType);
}
catch (HttpStatusCodeException e) {
try {
return restOperations.getForObject(path, responseType);
if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
return null;
}
catch (HttpStatusCodeException e) {
if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
return null;
}
throw VaultResponses.buildException(e, path);
}
throw VaultResponses.buildException(e, path);
}
});
}
private static class VaultListResponse extends
VaultResponseSupport<Map<String, Object>> {
private static class VaultListResponse
extends VaultResponseSupport<Map<String, Object>> {
}
}

View File

@@ -25,7 +25,6 @@ import org.springframework.vault.support.VaultToken;
import org.springframework.vault.support.VaultTokenRequest;
import org.springframework.vault.support.VaultTokenResponse;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestOperations;
/**
* Default implementation of {@link VaultTokenOperations}.
@@ -106,19 +105,15 @@ public class VaultTokenTemplate implements VaultTokenOperations {
Assert.hasText(path, "Path must not be empty");
return vaultOperations.doWithSession(new RestOperationsCallback<T>() {
return vaultOperations.doWithSession(restOperations -> {
try {
ResponseEntity<T> exchange = restOperations.exchange(path,
HttpMethod.POST, new HttpEntity<>(body), responseType);
@Override
public T doWithRestOperations(RestOperations restOperations) {
try {
ResponseEntity<T> exchange = restOperations.exchange(path,
HttpMethod.POST, new HttpEntity<Object>(body), responseType);
return exchange.getBody();
}
catch (HttpStatusCodeException e) {
throw VaultResponses.buildException(e, path);
}
return exchange.getBody();
}
catch (HttpStatusCodeException e) {
throw VaultResponses.buildException(e, path);
}
});
}

View File

@@ -144,7 +144,7 @@ public class VaultTransitTemplate implements VaultTransitOperations {
Assert.hasText(keyName, "KeyName must not be empty");
Assert.notNull(plaintext, "Plain text must not be null");
Map<String, String> request = new LinkedHashMap<String, String>();
Map<String, String> request = new LinkedHashMap<>();
request.put("plaintext", Base64Utils.encodeToString(plaintext.getBytes()));
@@ -160,7 +160,7 @@ public class VaultTransitTemplate implements VaultTransitOperations {
Assert.hasText(keyName, "KeyName must not be empty");
Assert.notNull(plaintext, "Plain text must not be null");
Map<String, String> request = new LinkedHashMap<String, String>();
Map<String, String> request = new LinkedHashMap<>();
request.put("plaintext", Base64Utils.encodeToString(plaintext));
@@ -179,7 +179,7 @@ public class VaultTransitTemplate implements VaultTransitOperations {
Assert.hasText(keyName, "KeyName must not be empty");
Assert.hasText(keyName, "Cipher text must not be empty");
Map<String, String> request = new LinkedHashMap<String, String>();
Map<String, String> request = new LinkedHashMap<>();
request.put("ciphertext", ciphertext);
@@ -197,7 +197,7 @@ public class VaultTransitTemplate implements VaultTransitOperations {
Assert.hasText(keyName, "KeyName must not be empty");
Assert.hasText(keyName, "Cipher text must not be empty");
Map<String, String> request = new LinkedHashMap<String, String>();
Map<String, String> request = new LinkedHashMap<>();
request.put("ciphertext", ciphertext);
@@ -218,7 +218,7 @@ public class VaultTransitTemplate implements VaultTransitOperations {
Assert.hasText(keyName, "KeyName must not be empty");
Assert.hasText(ciphertext, "Cipher text must not be empty");
Map<String, String> request = new LinkedHashMap<String, String>();
Map<String, String> request = new LinkedHashMap<>();
request.put("ciphertext", ciphertext);
return (String) vaultOperations
@@ -233,7 +233,7 @@ public class VaultTransitTemplate implements VaultTransitOperations {
Assert.hasText(keyName, "KeyName must not be empty");
Assert.hasText(ciphertext, "Cipher text must not be empty");
Map<String, String> request = new LinkedHashMap<String, String>();
Map<String, String> request = new LinkedHashMap<>();
request.put("ciphertext", ciphertext);

View File

@@ -60,7 +60,7 @@ public class LeaseAwareVaultPropertySource
private final RequestedSecret requestedSecret;
private final Map<String, String> properties = new ConcurrentHashMap<String, String>();
private final Map<String, String> properties = new ConcurrentHashMap<>();
private final PropertyTransformer propertyTransformer;

View File

@@ -49,7 +49,7 @@ public class VaultPropertySource extends EnumerablePropertySource<VaultOperation
private final String path;
private final Map<String, String> properties = new LinkedHashMap<String, String>();
private final Map<String, String> properties = new LinkedHashMap<>();
private final PropertyTransformer propertyTransformer;

View File

@@ -54,7 +54,6 @@ import org.springframework.vault.core.lease.event.LeaseErrorListener;
import org.springframework.vault.core.lease.event.LeaseListener;
import org.springframework.vault.support.VaultResponseSupport;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestOperations;
/**
* Event-based container to request secrets from Vault and renew the associated
@@ -128,9 +127,9 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher implements
private static final int STATUS_STARTED = 1;
private static final int STATUS_DESTROYED = 2;
private final List<RequestedSecret> requestedSecrets = new CopyOnWriteArrayList<RequestedSecret>();
private final List<RequestedSecret> requestedSecrets = new CopyOnWriteArrayList<>();
private final Map<RequestedSecret, LeaseRenewalScheduler> renewals = new ConcurrentHashMap<RequestedSecret, LeaseRenewalScheduler>();
private final Map<RequestedSecret, LeaseRenewalScheduler> renewals = new ConcurrentHashMap<>();
private final VaultOperations operations;
@@ -279,7 +278,7 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher implements
Assert.state(this.status != STATUS_DESTROYED,
"Container is destroyed and cannot be started");
Map<RequestedSecret, LeaseRenewalScheduler> renewals = new HashMap<RequestedSecret, LeaseRenewalScheduler>(
Map<RequestedSecret, LeaseRenewalScheduler> renewals = new HashMap<>(
this.renewals);
if (UPDATER.compareAndSet(this, STATUS_INITIAL, STATUS_STARTED)) {
@@ -429,24 +428,20 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher implements
}
leaseRenewal.scheduleRenewal(requestedSecret, new RenewLease() {
leaseRenewal.scheduleRenewal(requestedSecret, lease1 -> {
@Override
public Lease renewLease(Lease lease) {
Lease newLease = doRenewLease(requestedSecret, lease1);
Lease newLease = doRenewLease(requestedSecret, lease);
if (!Lease.none().equals(newLease)) {
if (!Lease.none().equals(newLease)) {
potentiallyScheduleLeaseRenewal(requestedSecret, newLease, leaseRenewal);
potentiallyScheduleLeaseRenewal(requestedSecret, newLease,
leaseRenewal);
onAfterLeaseRenewed(requestedSecret, newLease);
}
return newLease;
onAfterLeaseRenewed(requestedSecret, newLease);
}
return newLease;
}, lease, getMinRenewalSeconds(), getExpiryThresholdSeconds());
}
// -------------------------------------------------------------------------
@@ -483,7 +478,6 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher implements
protected Lease doRenewLease(final RequestedSecret requestedSecret, final Lease lease) {
try {
Lease renewed = lease.hasLeaseId() ? renew(lease) : lease;
if (!renewed.hasLeaseId() || renewed.getLeaseDuration() == 0
@@ -514,19 +508,10 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher implements
}
private Lease renew(final Lease lease) {
ResponseEntity<Map<String, Object>> entity = operations
.doWithSession(new RestOperationsCallback<ResponseEntity<Map<String, Object>>>() {
@Override
@SuppressWarnings("unchecked")
public ResponseEntity<Map<String, Object>> doWithRestOperations(
RestOperations restOperations) {
return (ResponseEntity) restOperations.exchange(
"/sys/renew/{leaseId}", HttpMethod.PUT, null, Map.class,
lease.getLeaseId());
}
});
.doWithSession(restOperations -> (ResponseEntity) restOperations
.exchange("/sys/renew/{leaseId}", HttpMethod.PUT, null,
Map.class, lease.getLeaseId()));
Map<String, Object> body = entity.getBody();
String leaseId = (String) body.get("lease_id");
@@ -567,17 +552,10 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher implements
onBeforeLeaseRevocation(requestedSecret, lease);
operations
.doWithSession(new RestOperationsCallback<ResponseEntity<Map<String, Object>>>() {
.doWithSession((RestOperationsCallback<ResponseEntity<Map<String, Object>>>) restOperations -> (ResponseEntity) restOperations
.exchange("/sys/revoke/{leaseId}", HttpMethod.PUT, null,
Map.class, lease.getLeaseId()));
@Override
@SuppressWarnings("unchecked")
public ResponseEntity<Map<String, Object>> doWithRestOperations(
RestOperations restOperations) {
return (ResponseEntity) restOperations.exchange(
"/sys/revoke/{leaseId}", HttpMethod.PUT, null,
Map.class, lease.getLeaseId());
}
});
onAfterLeaseRevocation(requestedSecret, lease);
}
catch (HttpStatusCodeException e) {
@@ -603,9 +581,9 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher implements
private final TaskScheduler taskScheduler;
final AtomicReference<Lease> currentLeaseRef = new AtomicReference<Lease>();
final AtomicReference<Lease> currentLeaseRef = new AtomicReference<>();
final Map<Lease, ScheduledFuture<?>> schedules = new ConcurrentHashMap<Lease, ScheduledFuture<?>>();
final Map<Lease, ScheduledFuture<?>> schedules = new ConcurrentHashMap<>();
/**
*
@@ -664,7 +642,7 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher implements
if (log.isDebugEnabled()) {
if (lease.hasLeaseId()) {
log.debug(String.format("Renewing lease %s for secret %s",
log.debug(String.format("Renewing lease %sfor secret %s",
lease.getLeaseId(), requestedSecret.getPath()));
}
else {
@@ -713,7 +691,7 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher implements
void disableScheduleRenewal() {
currentLeaseRef.set(null);
Set<Lease> leases = new HashSet<Lease>(schedules.keySet());
Set<Lease> leases = new HashSet<>(schedules.keySet());
for (Lease lease : leases) {
cancelSchedule(lease);

View File

@@ -49,9 +49,9 @@ import org.springframework.vault.core.lease.event.SecretLeaseExpiredEvent;
*/
public class SecretLeaseEventPublisher implements InitializingBean {
private final Set<LeaseListener> leaseListeners = new CopyOnWriteArraySet<LeaseListener>();
private final Set<LeaseListener> leaseListeners = new CopyOnWriteArraySet<>();
private final Set<LeaseErrorListener> leaseErrorListeners = new CopyOnWriteArraySet<LeaseErrorListener>();
private final Set<LeaseErrorListener> leaseErrorListeners = new CopyOnWriteArraySet<>();
/**
* Add a {@link LeaseListener} to the container. The listener starts receiving events

View File

@@ -44,7 +44,7 @@ public class SecretLeaseCreatedEvent extends SecretLeaseEvent {
Map<String, Object> secrets) {
super(requestedSecret, lease);
this.secrets = Collections.unmodifiableMap(new HashMap<String, Object>(secrets));
this.secrets = Collections.unmodifiableMap(new HashMap<>(secrets));
}
public Map<String, Object> getSecrets() {

View File

@@ -120,7 +120,7 @@ public abstract class PropertyTransformers {
@Override
public Map<String, String> transformProperties(Map<String, String> input) {
Map<String, String> target = new LinkedHashMap<String, String>(input.size(),
Map<String, String> target = new LinkedHashMap<>(input.size(),
1);
for (Entry<String, String> entry : input.entrySet()) {
@@ -165,7 +165,7 @@ public abstract class PropertyTransformers {
@Override
public Map<String, String> transformProperties(Map<String, String> input) {
Map<String, String> target = new LinkedHashMap<String, String>(input.size(),
Map<String, String> target = new LinkedHashMap<>(input.size(),
1);
for (Entry<String, String> entry : input.entrySet()) {

View File

@@ -35,16 +35,16 @@ import org.springframework.util.StringUtils;
* considered as sub-documents.
* <p>
* Input:
*
*
* <pre>
* <code>
* {"key": {"nested: "value"}, "another.key": ["one", "two"] }
* </code>
* </pre>
*
*
* <br>
* Result
*
*
* <pre>
* <code> key.nested=value
* another.key[0]=one
@@ -70,7 +70,7 @@ public abstract class JsonMapFlattener {
Assert.notNull(inputMap, "Input Map must not be null");
Map<String, String> resultMap = new LinkedHashMap<String, String>();
Map<String, String> resultMap = new LinkedHashMap<>();
doFlatten("", inputMap.entrySet().iterator(), resultMap);

View File

@@ -41,8 +41,8 @@ import java.util.List;
class KeystoreUtil {
/**
* Create a {@link KeyStore} containing the {@link KeySpec} and
* {@link X509Certificate certificates} using the given {@code keyAlias}.
* Create a {@link KeyStore} containing the {@link KeySpec} and {@link X509Certificate
* certificates} using the given {@code keyAlias}.
*
* @param keyAlias
* @param certificates
@@ -51,14 +51,15 @@ class KeystoreUtil {
* @throws IOException
*/
static KeyStore createKeyStore(String keyAlias, KeySpec privateKeySpec,
X509Certificate... certificates) throws GeneralSecurityException, IOException {
X509Certificate... certificates)
throws GeneralSecurityException, IOException {
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey privateKey = kf.generatePrivate(privateKeySpec);
KeyStore keyStore = createKeyStore();
List<X509Certificate> certChain = new ArrayList<X509Certificate>();
List<X509Certificate> certChain = new ArrayList<>();
Collections.addAll(certChain, certificates);
keyStore.setKeyEntry(keyAlias, privateKey, new char[0],
@@ -67,18 +68,15 @@ class KeystoreUtil {
return keyStore;
}
static X509Certificate getCertificate(byte[] source) throws CertificateException,
IOException {
static X509Certificate getCertificate(byte[] source)
throws CertificateException, IOException {
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
List<X509Certificate> certificates = getCertificates(certificateFactory, source);
if (certificates.isEmpty()) {
return null;
}
return certificates.get(0);
return certificates.stream().findFirst().orElseThrow(
() -> new IllegalArgumentException("No X509Certificate found"));
}
/**
@@ -88,7 +86,8 @@ class KeystoreUtil {
* @throws GeneralSecurityException
* @throws IOException
*/
private static KeyStore createKeyStore() throws GeneralSecurityException, IOException {
private static KeyStore createKeyStore()
throws GeneralSecurityException, IOException {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, new char[0]);
@@ -99,7 +98,7 @@ class KeystoreUtil {
private static List<X509Certificate> getCertificates(CertificateFactory cf,
byte[] source) throws CertificateException, IOException {
List<X509Certificate> x509Certificates = new ArrayList<X509Certificate>();
List<X509Certificate> x509Certificates = new ArrayList<>();
ByteArrayInputStream bis = new ByteArrayInputStream(source);
while (bis.available() > 0) {
@@ -299,8 +298,8 @@ class KeystoreUtil {
// We can't handle length longer than 4 bytes
if (i >= 0xFF || num > 4) {
throw new IllegalStateException("Invalid DER: length field too big (" + i
+ ")");
throw new IllegalStateException(
"Invalid DER: length field too big (" + i + ")");
}
byte[] bytes = new byte[num];

View File

@@ -107,8 +107,8 @@ public class VaultCertificateRequest {
public static class VaultCertificateRequestBuilder {
private String commonName;
private List<String> altNames = new ArrayList<String>();
private List<String> ipSubjectAltNames = new ArrayList<String>();
private List<String> altNames = new ArrayList<>();
private List<String> ipSubjectAltNames = new ArrayList<>();
private Integer ttl;
private Boolean excludeCommonNameFromSubjectAltNames;
@@ -249,7 +249,8 @@ public class VaultCertificateRequest {
altNames = java.util.Collections.singletonList(this.altNames.get(0));
break;
default:
altNames = java.util.Collections.unmodifiableList(new ArrayList<String>(
altNames = java.util.Collections
.unmodifiableList(new ArrayList<>(
this.altNames));
}
@@ -264,7 +265,7 @@ public class VaultCertificateRequest {
break;
default:
ipSubjectAltNames = java.util.Collections
.unmodifiableList(new ArrayList<String>(this.ipSubjectAltNames));
.unmodifiableList(new ArrayList<>(this.ipSubjectAltNames));
}
return new VaultCertificateRequest(commonName, altNames, ipSubjectAltNames,
@@ -273,7 +274,7 @@ public class VaultCertificateRequest {
private static <E> List<E> toList(Iterable<E> iter) {
List<E> list = new ArrayList<E>();
List<E> list = new ArrayList<>();
for (E item : iter) {
list.add(item);
}

View File

@@ -168,9 +168,9 @@ public class VaultTokenRequest {
private String id;
private List<String> policies = new ArrayList<String>();
private List<String> policies = new ArrayList<>();
private Map<String, String> meta = new LinkedHashMap<String, String>();
private Map<String, String> meta = new LinkedHashMap<>();
private Boolean noParent;
@@ -414,7 +414,7 @@ public class VaultTokenRequest {
policies = Collections.singletonList(this.policies.get(0));
break;
default:
policies = Collections.unmodifiableList(new ArrayList<String>(
policies = Collections.unmodifiableList(new ArrayList<>(
this.policies));
}
@@ -425,7 +425,7 @@ public class VaultTokenRequest {
break;
default:
meta = Collections
.unmodifiableMap(new LinkedHashMap<String, String>(this.meta));
.unmodifiableMap(new LinkedHashMap<>(this.meta));
}
return new VaultTokenRequest(id, policies, meta, noParent, noDefaultPolicy,
@@ -434,7 +434,7 @@ public class VaultTokenRequest {
private static <E> List<E> toList(Iterable<E> iter) {
List<E> list = new ArrayList<E>();
List<E> list = new ArrayList<>();
for (E item : iter) {
list.add(item);
}

View File

@@ -22,12 +22,10 @@ import org.junit.Before;
import org.junit.Test;
import org.springframework.vault.VaultException;
import org.springframework.vault.core.RestOperationsCallback;
import org.springframework.vault.support.VaultToken;
import org.springframework.vault.util.IntegrationTestSupport;
import org.springframework.vault.util.Settings;
import org.springframework.vault.util.TestRestTemplateFactory;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
@@ -47,27 +45,24 @@ public class AppIdAuthenticationIntegrationTests extends IntegrationTestSupport
}
prepare().getVaultOperations().doWithSession(
new RestOperationsCallback<Object>() {
@Override
public Object doWithRestOperations(RestOperations restOperations) {
restOperations -> {
Map<String, String> appIdData = new HashMap<String, String>();
appIdData.put("value", "dummy"); // policy
appIdData.put("display_name", "this is my test application");
Map<String, String> appIdData = new HashMap<String, String>();
appIdData.put("value", "dummy"); // policy
appIdData.put("display_name", "this is my test application");
restOperations.postForEntity("auth/app-id/map/app-id/myapp",
appIdData, Map.class);
restOperations.postForEntity("auth/app-id/map/app-id/myapp",
appIdData, Map.class);
Map<String, String> userIdData = new HashMap<String, String>();
userIdData.put("value", "myapp"); // name of the app-id
userIdData.put("cidr_block", "0.0.0.0/0");
Map<String, String> userIdData = new HashMap<String, String>();
userIdData.put("value", "myapp"); // name of the app-id
userIdData.put("cidr_block", "0.0.0.0/0");
restOperations.postForEntity(
"auth/app-id/map/user-id/static-userid-value",
userIdData, Map.class);
restOperations.postForEntity(
"auth/app-id/map/user-id/static-userid-value", userIdData,
Map.class);
return null;
}
return null;
});
}

View File

@@ -23,11 +23,9 @@ import org.junit.Before;
import org.junit.Test;
import org.springframework.vault.VaultException;
import org.springframework.vault.core.RestOperationsCallback;
import org.springframework.vault.core.VaultOperations;
import org.springframework.vault.support.VaultResponse;
import org.springframework.vault.util.IntegrationTestSupport;
import org.springframework.web.client.RestOperations;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.anyOf;
@@ -56,28 +54,25 @@ public class AppRoleAuthenticationIntegrationTests extends IntegrationTestSuppor
prepare().mountAuth("approle");
}
getVaultOperations().doWithSession(new RestOperationsCallback<Object>() {
@Override
public Object doWithRestOperations(RestOperations restOperations) {
getVaultOperations().doWithSession(restOperations -> {
Map<String, String> withSecretId = new HashMap<String, String>();
withSecretId.put("policies", "dummy"); // policy
withSecretId.put("bound_cidr_list", "0.0.0.0/0");
withSecretId.put("bind_secret_id", "true");
Map<String, String> withSecretId = new HashMap<String, String>();
withSecretId.put("policies", "dummy"); // policy
withSecretId.put("bound_cidr_list", "0.0.0.0/0");
withSecretId.put("bind_secret_id", "true");
restOperations.postForEntity("auth/approle/role/with-secret-id",
withSecretId, Map.class);
restOperations.postForEntity("auth/approle/role/with-secret-id", withSecretId,
Map.class);
Map<String, String> noSecretIdRole = new HashMap<String, String>();
noSecretIdRole.put("policies", "dummy"); // policy
noSecretIdRole.put("bound_cidr_list", "0.0.0.0/0");
noSecretIdRole.put("bind_secret_id", "false");
Map<String, String> noSecretIdRole = new HashMap<String, String>();
noSecretIdRole.put("policies", "dummy"); // policy
noSecretIdRole.put("bound_cidr_list", "0.0.0.0/0");
noSecretIdRole.put("bind_secret_id", "false");
restOperations.postForEntity("auth/approle/role/no-secret-id",
noSecretIdRole, Map.class);
restOperations.postForEntity("auth/approle/role/no-secret-id", noSecretIdRole,
Map.class);
return null;
}
return null;
});
}

View File

@@ -16,7 +16,7 @@
package org.springframework.vault.authentication;
import java.io.File;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Map;
@@ -36,7 +36,6 @@ import org.springframework.vault.support.VaultToken;
import org.springframework.vault.util.IntegrationTestSupport;
import org.springframework.vault.util.Settings;
import org.springframework.vault.util.TestRestTemplateFactory;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
@@ -48,8 +47,8 @@ import static org.springframework.vault.util.Settings.findWorkDir;
*
* @author Mark Paluch
*/
public class ClientCertificateAuthenticationIntegrationTests extends
IntegrationTestSupport {
public class ClientCertificateAuthenticationIntegrationTests
extends IntegrationTestSupport {
@Before
public void before() throws Exception {
@@ -58,19 +57,17 @@ public class ClientCertificateAuthenticationIntegrationTests extends
prepare().mountAuth("cert");
}
prepare().getVaultOperations().doWithSession(
new RestOperationsCallback<Object>() {
@Override
public Object doWithRestOperations(RestOperations restOperations) {
File workDir = findWorkDir();
prepare().getVaultOperations()
.doWithSession((RestOperationsCallback<Object>) restOperations -> {
File workDir = findWorkDir();
String certificate = Files.contentOf(new File(workDir,
"ca/certs/client.cert.pem"), Charset.forName("US-ASCII"));
String certificate = Files.contentOf(
new File(workDir, "ca/certs/client.cert.pem"),
StandardCharsets.US_ASCII);
return restOperations.postForEntity("auth/cert/certs/my-role",
Collections.singletonMap("certificate", certificate),
Map.class);
}
return restOperations.postForEntity("auth/cert/certs/my-role",
Collections.singletonMap("certificate", certificate),
Map.class);
});
}
@@ -106,9 +103,9 @@ public class ClientCertificateAuthenticationIntegrationTests extends
SslConfiguration original = createSslConfiguration();
SslConfiguration sslConfiguration = new SslConfiguration(new FileSystemResource(
new File(findWorkDir(), "client-cert.jks")), "changeit",
original.getTrustStore(), original.getTrustStorePassword());
SslConfiguration sslConfiguration = new SslConfiguration(
new FileSystemResource(new File(findWorkDir(), "client-cert.jks")),
"changeit", original.getTrustStore(), original.getTrustStorePassword());
return sslConfiguration;
}

View File

@@ -24,13 +24,11 @@ import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.vault.VaultException;
import org.springframework.vault.core.RestOperationsCallback;
import org.springframework.vault.support.VaultResponse;
import org.springframework.vault.support.VaultToken;
import org.springframework.vault.util.IntegrationTestSupport;
import org.springframework.vault.util.Settings;
import org.springframework.vault.util.TestRestTemplateFactory;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
@@ -49,18 +47,14 @@ public class CubbyholeAuthenticationIntegrationTests extends IntegrationTestSupp
ResponseEntity<VaultResponse> response = prepare().getVaultOperations()
.doWithSession(
new RestOperationsCallback<ResponseEntity<VaultResponse>>() {
@Override
public ResponseEntity<VaultResponse> doWithRestOperations(
RestOperations restOperations) {
restOperations -> {
HttpHeaders headers = new HttpHeaders();
headers.add("X-Vault-Wrap-TTL", "10m");
HttpHeaders headers = new HttpHeaders();
headers.add("X-Vault-Wrap-TTL", "10m");
return restOperations.exchange("auth/token/create",
HttpMethod.POST, new HttpEntity<Object>(headers),
VaultResponse.class);
}
return restOperations.exchange("auth/token/create",
HttpMethod.POST, new HttpEntity<Object>(headers),
VaultResponse.class);
});
Map<String, String> wrapInfo = response.getBody().getWrapInfo();

View File

@@ -25,13 +25,11 @@ import org.junit.Test;
import org.springframework.http.HttpStatus;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.vault.core.RestOperationsCallback;
import org.springframework.vault.core.VaultTokenOperations;
import org.springframework.vault.support.VaultToken;
import org.springframework.vault.support.VaultTokenRequest;
import org.springframework.vault.util.IntegrationTestSupport;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestOperations;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
@@ -114,23 +112,20 @@ public class LifecycleAwareSessionManagerIntegrationTests extends IntegrationTes
sessionManager.destroy();
prepare().getVaultOperations().doWithSession(
new RestOperationsCallback<Object>() {
@Override
public Object doWithRestOperations(RestOperations restOperations) {
restOperations -> {
try {
restOperations.getForEntity("auth/token/lookup/{token}",
Map.class, loginToken.toCharArray());
fail("Missing HttpStatusCodeException");
}
catch (HttpStatusCodeException e) {
// Compatibility across Vault versions.
assertThat(e.getStatusCode()).isIn(HttpStatus.BAD_REQUEST,
HttpStatus.NOT_FOUND, HttpStatus.FORBIDDEN);
}
return null;
try {
restOperations.getForEntity("auth/token/lookup/{token}",
Map.class, loginToken.toCharArray());
fail("Missing HttpStatusCodeException");
}
catch (HttpStatusCodeException e) {
// Compatibility across Vault versions.
assertThat(e.getStatusCode()).isIn(HttpStatus.BAD_REQUEST,
HttpStatus.NOT_FOUND, HttpStatus.FORBIDDEN);
}
return null;
});
}

View File

@@ -102,9 +102,7 @@ public class VaultTemplateTransitIntegrationTests extends IntegrationTestSupport
if (vaultVersion.isGreaterThanOrEqualTo(Version.parse("0.6.4"))) {
List<String> keys = vaultOperations.opsForTransit().getKeys();
for (String keyName : keys) {
deleteKey(keyName);
}
keys.forEach(this::deleteKey);
}
else {
deleteKey("mykey");

View File

@@ -35,7 +35,6 @@ import org.springframework.vault.client.VaultHttpHeaders;
import org.springframework.vault.support.VaultTokenRequest;
import org.springframework.vault.support.VaultTokenResponse;
import org.springframework.vault.util.IntegrationTestSupport;
import org.springframework.web.client.RestOperations;
import static org.assertj.core.api.Assertions.assertThat;
@@ -162,19 +161,14 @@ public class VaultTokenTemplateIntegrationTests extends IntegrationTestSupport {
private ResponseEntity<String> lookupSelf(final VaultTokenResponse tokenResponse) {
return vaultOperations
.doWithVault(new RestOperationsCallback<ResponseEntity<String>>() {
@Override
public ResponseEntity<String> doWithRestOperations(
RestOperations restOperations) {
HttpHeaders headers = new HttpHeaders();
headers.add(VaultHttpHeaders.VAULT_TOKEN, tokenResponse
.getToken()
.getToken());
.doWithVault(restOperations -> {
HttpHeaders headers = new HttpHeaders();
headers.add(VaultHttpHeaders.VAULT_TOKEN,
tokenResponse.getToken().getToken());
return restOperations.exchange("auth/token/lookup-self",
HttpMethod.GET, new HttpEntity<Object>(headers),
String.class);
}
return restOperations.exchange("auth/token/lookup-self",
HttpMethod.GET, new HttpEntity<Object>(headers),
String.class);
});
}