diff --git a/etc/ide/eclipse-code-formatter.xml b/etc/ide/eclipse-code-formatter.xml
index b5515c19..6f7bc030 100644
--- a/etc/ide/eclipse-code-formatter.xml
+++ b/etc/ide/eclipse-code-formatter.xml
@@ -1,291 +1,296 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
+
+
+
+
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
+
\ No newline at end of file
diff --git a/etc/ide/eclipse.importorder b/etc/ide/eclipse.importorder
new file mode 100644
index 00000000..c83990a9
--- /dev/null
+++ b/etc/ide/eclipse.importorder
@@ -0,0 +1,7 @@
+#Organize Import Order
+#Thu Oct 13 16:40:43 CEST 2016
+4=\#
+3=org.springframework
+2=
+1=javax
+0=java
diff --git a/spring-vault-core/src/main/java/org/springframework/vault/annotation/VaultPropertySource.java b/spring-vault-core/src/main/java/org/springframework/vault/annotation/VaultPropertySource.java
index 63479b89..aba844c1 100644
--- a/spring-vault-core/src/main/java/org/springframework/vault/annotation/VaultPropertySource.java
+++ b/spring-vault-core/src/main/java/org/springframework/vault/annotation/VaultPropertySource.java
@@ -26,41 +26,47 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
/**
- * Annotation providing a convenient and declarative mechanism for adding a {@link VaultPropertySource} to Spring's
- * {@link org.springframework.core.env.Environment Environment}. To be used in conjunction with @{@link Configuration}
- * classes.
- *
Example usage
+ * Annotation providing a convenient and declarative mechanism for adding a
+ * {@link VaultPropertySource} to Spring's
+ * {@link org.springframework.core.env.Environment Environment}. To be used in conjunction
+ * with @{@link Configuration} classes. Example usage
*
* Given a Vault path {@code secret/my-application} containing the configuration data pair
- * {@code database.password=mysecretpassword}, the following {@code @Configuration} class uses
- * {@code @VaultPropertySource} to contribute {@code secret/my-application} to the {@code Environment}'s set of
- * {@code PropertySources}.
+ * {@code database.password=mysecretpassword}, the following {@code @Configuration} class
+ * uses {@code @VaultPropertySource} to contribute {@code secret/my-application} to the
+ * {@code Environment}'s set of {@code PropertySources}.
*
*
* @Configuration
- * @VaultPropertySource("secret/my-application")
+ * @VaultPropertySource("secret/my-application")
* public class AppConfig {
- * @Autowired Environment env;
- *
+ * @Autowired
+ * Environment env;
+ *
* @Bean
* public TestBean testBean() {
* TestBean testBean = new TestBean();
- * testBean.setPassword(env.getProperty("database.password"));
+ * testBean.setPassword(env.getProperty("database.password"));
* return testBean;
* }
* }
*
*
- * Notice that the {@code Environment} object is @{@link org.springframework.beans.factory.annotation.Autowired
- * Autowired} into the configuration class and then used when populating the {@code TestBean} object. Given the
- * configuration above, a call to {@code testBean.getPassword()} will return "mysecretpassword".
+ * Notice that the {@code Environment} object is @
+ * {@link org.springframework.beans.factory.annotation.Autowired Autowired} into the
+ * configuration class and then used when populating the {@code TestBean} object. Given
+ * the configuration above, a call to {@code testBean.getPassword()} will return
+ * "mysecretpassword".
*
- * In certain situations, it may not be possible or practical to tightly control property source ordering when using
- * {@code @VaultPropertySource} annotations. For example, if the {@code @Configuration} classes above were registered
- * via component-scanning, the ordering is difficult to predict. In such cases - and if overriding is important - it is
- * recommended that the user fall back to using the programmatic PropertySource API. See
- * {@link org.springframework.core.env.ConfigurableEnvironment ConfigurableEnvironment} and
- * {@link org.springframework.core.env.MutablePropertySources MutablePropertySources} javadocs for details.
+ * In certain situations, it may not be possible or practical to tightly control property
+ * source ordering when using {@code @VaultPropertySource} annotations. For example, if
+ * the {@code @Configuration} classes above were registered via component-scanning, the
+ * ordering is difficult to predict. In such cases - and if overriding is important - it
+ * is recommended that the user fall back to using the programmatic PropertySource API.
+ * See {@link org.springframework.core.env.ConfigurableEnvironment
+ * ConfigurableEnvironment} and
+ * {@link org.springframework.core.env.MutablePropertySources MutablePropertySources}
+ * javadocs for details.
*
* @author Mark Paluch
*/
@@ -72,17 +78,17 @@ import org.springframework.context.annotation.Import;
public @interface VaultPropertySource {
/**
- * Indicate the Vault path(s) of the properties to be retrieved. For example, {@code "secret/myapp"} or
- * {@code "secret/my-application/profile"}.
+ * Indicate the Vault path(s) of the properties to be retrieved. For example,
+ * {@code "secret/myapp"} or {@code "secret/my-application/profile"}.
*
- * Each location will be added to the enclosing {@code Environment} as its own property source, and in the order
- * declared.
+ * Each location will be added to the enclosing {@code Environment} as its own
+ * property source, and in the order declared.
*/
String[] value();
/**
- * Configure the name of the {@link org.springframework.vault.core.VaultTemplate} bean to be used with the property
- * sources.
+ * Configure the name of the {@link org.springframework.vault.core.VaultTemplate} bean
+ * to be used with the property sources.
*/
String vaultTemplateRef() default "vaultTemplate";
}
diff --git a/spring-vault-core/src/main/java/org/springframework/vault/annotation/VaultPropertySourceRegistrar.java b/spring-vault-core/src/main/java/org/springframework/vault/annotation/VaultPropertySourceRegistrar.java
index b25955ab..76504062 100644
--- a/spring-vault-core/src/main/java/org/springframework/vault/annotation/VaultPropertySourceRegistrar.java
+++ b/spring-vault-core/src/main/java/org/springframework/vault/annotation/VaultPropertySourceRegistrar.java
@@ -35,20 +35,23 @@ import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
- * Registrar to register {@link org.springframework.vault.core.env.VaultPropertySource}s based on
- * {@link VaultPropertySource}.
+ * Registrar to register {@link org.springframework.vault.core.env.VaultPropertySource}s
+ * based on {@link VaultPropertySource}.
*
- * This class registers potentially multiple property sources based on different Vault paths.
- * {@link org.springframework.vault.core.env.VaultPropertySource}s are resolved and added to
- * {@link ConfigurableEnvironment} once the bean factory is post-processed. This allows injection of Vault properties
- * and and lookup using the {@link org.springframework.core.env.Environment}.
+ * This class registers potentially multiple property sources based on different Vault
+ * paths. {@link org.springframework.vault.core.env.VaultPropertySource}s are resolved and
+ * added to {@link ConfigurableEnvironment} once the bean factory is post-processed. This
+ * allows injection of Vault properties and and lookup using the
+ * {@link org.springframework.core.env.Environment}.
*
* @author Mark Paluch
*/
-class VaultPropertySourceRegistrar implements ImportBeanDefinitionRegistrar, BeanFactoryPostProcessor {
+class VaultPropertySourceRegistrar implements ImportBeanDefinitionRegistrar,
+ BeanFactoryPostProcessor {
@Override
- public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
+ public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
+ throws BeansException {
ConfigurableEnvironment env = beanFactory.getBean(ConfigurableEnvironment.class);
Map beans = beanFactory
@@ -56,7 +59,8 @@ class VaultPropertySourceRegistrar implements ImportBeanDefinitionRegistrar, Bea
MutablePropertySources propertySources = env.getPropertySources();
- for (org.springframework.vault.core.env.VaultPropertySource vaultPropertySource : beans.values()) {
+ for (org.springframework.vault.core.env.VaultPropertySource vaultPropertySource : beans
+ .values()) {
if (propertySources.contains(vaultPropertySource.getName())) {
continue;
@@ -67,7 +71,8 @@ class VaultPropertySourceRegistrar implements ImportBeanDefinitionRegistrar, Bea
}
@Override
- public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry registry) {
+ public void registerBeanDefinitions(AnnotationMetadata annotationMetadata,
+ BeanDefinitionRegistry registry) {
Assert.notNull(annotationMetadata, "AnnotationMetadata must not be null!");
Assert.notNull(registry, "BeanDefinitionRegistry must not be null!");
@@ -78,19 +83,22 @@ class VaultPropertySourceRegistrar implements ImportBeanDefinitionRegistrar, Bea
.setRole(BeanDefinition.ROLE_INFRASTRUCTURE) //
.getBeanDefinition());
- Set propertySources = attributesForRepeatable(annotationMetadata,
- VaultPropertySources.class.getName(), VaultPropertySource.class.getName());
+ Set propertySources = attributesForRepeatable(
+ annotationMetadata, VaultPropertySources.class.getName(),
+ VaultPropertySource.class.getName());
int counter = 0;
for (AnnotationAttributes propertySource : propertySources) {
String[] paths = propertySource.getStringArray("value");
- Assert.isTrue(paths.length > 0, "At least one @VaultPropertySource(value) location is required");
+ Assert.isTrue(paths.length > 0,
+ "At least one @VaultPropertySource(value) location is required");
String ref = propertySource.getString("vaultTemplateRef");
- Assert.hasText(ref, "'vaultTemplateRef' in @EnableVaultPropertySource must not be empty");
+ Assert.hasText(ref,
+ "'vaultTemplateRef' in @EnableVaultPropertySource must not be empty");
for (String propertyPath : paths) {
@@ -106,7 +114,8 @@ class VaultPropertySourceRegistrar implements ImportBeanDefinitionRegistrar, Bea
builder.addConstructorArgValue(propertyPath);
builder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
- registry.registerBeanDefinition("vaultPropertySource#" + counter, builder.getBeanDefinition());
+ registry.registerBeanDefinition("vaultPropertySource#" + counter,
+ builder.getBeanDefinition());
counter++;
}
@@ -114,22 +123,26 @@ class VaultPropertySourceRegistrar implements ImportBeanDefinitionRegistrar, Bea
}
@SuppressWarnings("unchecked")
- static Set attributesForRepeatable(AnnotationMetadata metadata, String containerClassName,
- String annotationClassName) {
+ static Set attributesForRepeatable(AnnotationMetadata metadata,
+ String containerClassName, String annotationClassName) {
Set result = new LinkedHashSet();
- addAttributesIfNotNull(result, metadata.getAnnotationAttributes(annotationClassName, false));
+ addAttributesIfNotNull(result,
+ metadata.getAnnotationAttributes(annotationClassName, false));
- Map container = metadata.getAnnotationAttributes(containerClassName, false);
+ Map container = metadata.getAnnotationAttributes(
+ containerClassName, false);
if (container != null && container.containsKey("value")) {
- for (Map containedAttributes : (Map[]) container.get("value")) {
+ for (Map containedAttributes : (Map[]) container
+ .get("value")) {
addAttributesIfNotNull(result, containedAttributes);
}
}
return Collections.unmodifiableSet(result);
}
- private static void addAttributesIfNotNull(Set result, Map attributes) {
+ private static void addAttributesIfNotNull(Set result,
+ Map attributes) {
if (attributes != null) {
result.add(AnnotationAttributes.fromMap(attributes));
}
diff --git a/spring-vault-core/src/main/java/org/springframework/vault/annotation/VaultPropertySources.java b/spring-vault-core/src/main/java/org/springframework/vault/annotation/VaultPropertySources.java
index 618f545f..278d9f3d 100644
--- a/spring-vault-core/src/main/java/org/springframework/vault/annotation/VaultPropertySources.java
+++ b/spring-vault-core/src/main/java/org/springframework/vault/annotation/VaultPropertySources.java
@@ -26,10 +26,11 @@ import org.springframework.context.annotation.Import;
/**
* Container annotation that aggregates several {@link VaultPropertySource} annotations.
*
- * Can be used natively, declaring several nested {@link VaultPropertySource} annotations. Can also be used in
- * conjunction with Java 8's support for repeatable annotations , where {@link VaultPropertySource} can simply
- * be declared several times on the same {@linkplain ElementType#TYPE type}, implicitly generating this container
- * annotation.
+ * Can be used natively, declaring several nested {@link VaultPropertySource} annotations.
+ * Can also be used in conjunction with Java 8's support for
+ * repeatable annotations , where {@link VaultPropertySource} can simply be
+ * declared several times on the same {@linkplain ElementType#TYPE type}, implicitly
+ * generating this container annotation.
*
* @author Mark Paluch
* @see VaultPropertySource
diff --git a/spring-vault-core/src/main/java/org/springframework/vault/annotation/package-info.java b/spring-vault-core/src/main/java/org/springframework/vault/annotation/package-info.java
index 9255910c..5a5491c9 100644
--- a/spring-vault-core/src/main/java/org/springframework/vault/annotation/package-info.java
+++ b/spring-vault-core/src/main/java/org/springframework/vault/annotation/package-info.java
@@ -2,3 +2,4 @@
* Annotation support for the Spring Vault.
*/
package org.springframework.vault.annotation;
+
diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppIdAuthentication.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppIdAuthentication.java
index cf698ea0..ac63f54e 100644
--- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppIdAuthentication.java
+++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppIdAuthentication.java
@@ -20,6 +20,7 @@ import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+
import org.springframework.util.Assert;
import org.springframework.vault.client.VaultClient;
import org.springframework.vault.client.VaultException;
@@ -28,25 +29,28 @@ import org.springframework.vault.support.VaultResponse;
import org.springframework.vault.support.VaultToken;
/**
- * AppId implementation of {@link ClientAuthentication}. {@link AppIdAuthentication} uses a configured
- * {@link AppIdUserIdMechanism} to obtain or calculate a UserId. AppId and UserId are sent in the login request to Vault
- * to obtain a {@link VaultToken}.
+ * AppId implementation of {@link ClientAuthentication}. {@link AppIdAuthentication} uses
+ * a configured {@link AppIdUserIdMechanism} to obtain or calculate a UserId. AppId and
+ * UserId are sent in the login request to Vault to obtain a {@link VaultToken}.
*
* @author Mark Paluch
* @see AppIdAuthenticationOptions
* @see VaultClient
- * @see Auth Backend: App ID
+ * @see Auth Backend: App
+ * ID
*/
public class AppIdAuthentication implements ClientAuthentication {
- private final static Logger logger = LoggerFactory.getLogger(AppIdAuthentication.class);
+ private final static Logger logger = LoggerFactory
+ .getLogger(AppIdAuthentication.class);
private final AppIdAuthenticationOptions options;
private final VaultClient vaultClient;
/**
- * Creates a {@link AppIdAuthentication} using {@link AppIdAuthenticationOptions} and {@link VaultClient}.
+ * Creates a {@link AppIdAuthentication} using {@link AppIdAuthenticationOptions} and
+ * {@link VaultClient}.
*
* @param options must not be {@literal null}.
* @param vaultClient must not be {@literal null}.
@@ -67,13 +71,16 @@ public class AppIdAuthentication implements ClientAuthentication {
private VaultToken createTokenUsingAppId() {
- Map login = getAppIdLogin(options.getAppId(), options.getUserIdMechanism().createUserId());
+ Map login = getAppIdLogin(options.getAppId(), options
+ .getUserIdMechanism().createUserId());
- VaultResponseEntity entity = vaultClient
- .postForEntity(String.format("auth/%s/login", options.getPath()), login, VaultResponse.class);
+ VaultResponseEntity entity = vaultClient.postForEntity(
+ String.format("auth/%s/login", options.getPath()), login,
+ VaultResponse.class);
if (!entity.isSuccessful()) {
- throw new VaultException(String.format("Cannot login using app-id: %s", entity.getMessage()));
+ throw new VaultException(String.format("Cannot login using app-id: %s",
+ entity.getMessage()));
}
logger.debug("Login successful using AppId authentication");
diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppIdAuthenticationOptions.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppIdAuthenticationOptions.java
index 1024d9f3..a7551a14 100644
--- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppIdAuthenticationOptions.java
+++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppIdAuthenticationOptions.java
@@ -20,8 +20,9 @@ import org.springframework.util.Assert;
/**
* Authentication options for {@link AppIdAuthentication}.
*
- * Authentication options provide the path, appId and a {@link AppIdUserIdMechanism}. {@link AppIdAuthentication} can be
- * constructed using {@link #builder()}. Instances of this class are immutable once constructed.
+ * Authentication options provide the path, appId and a {@link AppIdUserIdMechanism}.
+ * {@link AppIdAuthentication} can be constructed using {@link #builder()}. Instances of
+ * this class are immutable once constructed.
*
* @author Mark Paluch
* @see AppIdAuthentication
@@ -47,7 +48,8 @@ public class AppIdAuthenticationOptions {
*/
private final AppIdUserIdMechanism userIdMechanism;
- private AppIdAuthenticationOptions(String path, String appId, AppIdUserIdMechanism userIdMechanism) {
+ private AppIdAuthenticationOptions(String path, String appId,
+ AppIdUserIdMechanism userIdMechanism) {
this.path = path;
this.appId = appId;
@@ -93,7 +95,8 @@ public class AppIdAuthenticationOptions {
private AppIdUserIdMechanism userIdMechanism;
- AppIdAuthenticationOptionsBuilder() {}
+ AppIdAuthenticationOptionsBuilder() {
+ }
/**
* Configure the mount path.
@@ -130,7 +133,8 @@ public class AppIdAuthenticationOptions {
* @param userIdMechanism must not be {@literal null}.
* @return {@code this} {@link AppIdAuthenticationOptionsBuilder}.
*/
- public AppIdAuthenticationOptionsBuilder userIdMechanism(AppIdUserIdMechanism userIdMechanism) {
+ public AppIdAuthenticationOptionsBuilder userIdMechanism(
+ AppIdUserIdMechanism userIdMechanism) {
Assert.notNull(userIdMechanism, "AppIdUserIdMechanism must not be null");
@@ -139,8 +143,8 @@ public class AppIdAuthenticationOptions {
}
/**
- * Build a new {@link AppIdAuthenticationOptions} instance. Requires {@link #userIdMechanism(AppIdUserIdMechanism)}
- * to be configured.
+ * Build a new {@link AppIdAuthenticationOptions} instance. Requires
+ * {@link #userIdMechanism(AppIdUserIdMechanism)} to be configured.
*
* @return a new {@link AppIdAuthenticationOptions}.
*/
diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppIdUserIdMechanism.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppIdUserIdMechanism.java
index 3238b4a1..13a75b4d 100644
--- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppIdUserIdMechanism.java
+++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppIdUserIdMechanism.java
@@ -17,7 +17,8 @@
package org.springframework.vault.authentication;
/**
- * Interface to obtain a UserId for AppId authentication. Implementations are used by {@link AppIdAuthentication}.
+ * Interface to obtain a UserId for AppId authentication. Implementations are used by
+ * {@link AppIdAuthentication}.
*
* @author Mark Paluch
* @see AppIdAuthentication
diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppRoleAuthentication.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppRoleAuthentication.java
index 332538fa..724d48d8 100644
--- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppRoleAuthentication.java
+++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppRoleAuthentication.java
@@ -20,6 +20,7 @@ import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+
import org.springframework.util.Assert;
import org.springframework.vault.client.VaultClient;
import org.springframework.vault.client.VaultException;
@@ -28,8 +29,8 @@ import org.springframework.vault.support.VaultResponse;
import org.springframework.vault.support.VaultToken;
/**
- * AppRole implementation of {@link ClientAuthentication}. RoleId and SecretId (optional) are sent in the login request
- * to Vault to obtain a {@link VaultToken}.
+ * AppRole implementation of {@link ClientAuthentication}. RoleId and SecretId (optional)
+ * are sent in the login request to Vault to obtain a {@link VaultToken}.
*
* {@link AppRoleAuthentication} can be configured for push and pull mode by setting
* {@link AppRoleAuthenticationOptions#getSecretId()}.
@@ -37,23 +38,27 @@ import org.springframework.vault.support.VaultToken;
* @author Mark Paluch
* @see AppRoleAuthenticationOptions
* @see VaultClient
- * @see Auth Backend: AppRole
+ * @see Auth Backend:
+ * AppRole
*/
public class AppRoleAuthentication implements ClientAuthentication {
- private final static Logger logger = LoggerFactory.getLogger(AppRoleAuthentication.class);
+ private final static Logger logger = LoggerFactory
+ .getLogger(AppRoleAuthentication.class);
private final AppRoleAuthenticationOptions options;
private final VaultClient vaultClient;
/**
- * Creates a {@link AppRoleAuthentication} using {@link AppRoleAuthenticationOptions} and {@link VaultClient}.
+ * Creates a {@link AppRoleAuthentication} using {@link AppRoleAuthenticationOptions}
+ * and {@link VaultClient}.
*
* @param options must not be {@literal null}.
* @param vaultClient must not be {@literal null}.
*/
- public AppRoleAuthentication(AppRoleAuthenticationOptions options, VaultClient vaultClient) {
+ public AppRoleAuthentication(AppRoleAuthenticationOptions options,
+ VaultClient vaultClient) {
Assert.notNull(options, "AppRoleAuthenticationOptions must not be null");
Assert.notNull(vaultClient, "VaultClient must not be null");
@@ -69,13 +74,16 @@ public class AppRoleAuthentication implements ClientAuthentication {
private VaultToken createTokenUsingAppRole() {
- Map login = getAppRoleLogin(options.getRoleId(), options.getSecretId());
+ Map login = getAppRoleLogin(options.getRoleId(),
+ options.getSecretId());
- VaultResponseEntity entity = vaultClient
- .postForEntity(String.format("auth/%s/login", options.getPath()), login, VaultResponse.class);
+ VaultResponseEntity entity = vaultClient.postForEntity(
+ String.format("auth/%s/login", options.getPath()), login,
+ VaultResponse.class);
if (!entity.isSuccessful()) {
- throw new VaultException(String.format("Cannot login using AppRole: %s", entity.getMessage()));
+ throw new VaultException(String.format("Cannot login using AppRole: %s",
+ entity.getMessage()));
}
logger.debug("Login successful using AppRole authentication");
diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppRoleAuthenticationOptions.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppRoleAuthenticationOptions.java
index 4e1850cc..9e32abdf 100644
--- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppRoleAuthenticationOptions.java
+++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AppRoleAuthenticationOptions.java
@@ -20,8 +20,9 @@ import org.springframework.util.Assert;
/**
* Authentication options for {@link AppRoleAuthentication}.
*
- * Authentication options provide the path, roleId and pull/push mode. {@link AppRoleAuthentication} can be
- * constructed using {@link #builder()}. Instances of this class are immutable once constructed.
+ * Authentication options provide the path, roleId and pull/push mode.
+ * {@link AppRoleAuthentication} can be constructed using {@link #builder()}. Instances of
+ * this class are immutable once constructed.
*
* @author Mark Paluch
* @see AppRoleAuthentication
@@ -92,7 +93,8 @@ public class AppRoleAuthenticationOptions {
private String secretId;
- AppRoleAuthenticationOptionsBuilder() {}
+ AppRoleAuthenticationOptionsBuilder() {
+ }
/**
* Configure the mount path.
@@ -138,7 +140,8 @@ public class AppRoleAuthenticationOptions {
}
/**
- * Build a new {@link AppRoleAuthenticationOptions} instance. Requires {@link #roleId(String)} to be configured.
+ * Build a new {@link AppRoleAuthenticationOptions} instance. Requires
+ * {@link #roleId(String)} to be configured.
*
* @return a new {@link AppRoleAuthenticationOptions}.
*/
diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AwsEc2Authentication.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AwsEc2Authentication.java
index dc119dd8..76bac05e 100644
--- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AwsEc2Authentication.java
+++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AwsEc2Authentication.java
@@ -22,6 +22,7 @@ import java.util.concurrent.atomic.AtomicReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.vault.client.VaultClient;
@@ -35,17 +36,19 @@ import org.springframework.web.client.RestTemplate;
/**
* AWS-EC2 login implementation.
*
- * AWS-EC2 login uses the EC2 identity document and a nonce to login into Vault. AWS-EC2 login obtains the PKCS#7 signed
- * EC2 identity document and generates a {@link #createNonce() nonce}. Instances of this class are immutable once
- * constructed.
+ * AWS-EC2 login uses the EC2 identity document and a nonce to login into Vault. AWS-EC2
+ * login obtains the PKCS#7 signed EC2 identity document and generates a
+ * {@link #createNonce() nonce}. Instances of this class are immutable once constructed.
*
* @author Mark Paluch
* @see AwsEc2AuthenticationOptions
- * @see Auth Backend: aws-ec2
+ * @see Auth Backend:
+ * aws-ec2
*/
public class AwsEc2Authentication implements ClientAuthentication {
- private final static Logger logger = LoggerFactory.getLogger(AwsEc2Authentication.class);
+ private final static Logger logger = LoggerFactory
+ .getLogger(AwsEc2Authentication.class);
private final AwsEc2AuthenticationOptions options;
@@ -61,18 +64,21 @@ public class AwsEc2Authentication implements ClientAuthentication {
* @param vaultClient must not be {@literal null}.
*/
public AwsEc2Authentication(VaultClient vaultClient) {
- this(AwsEc2AuthenticationOptions.DEFAULT, vaultClient, vaultClient.getRestTemplate());
+ this(AwsEc2AuthenticationOptions.DEFAULT, vaultClient, vaultClient
+ .getRestTemplate());
}
/**
- * Creates a new {@link AwsEc2Authentication} specifying {@link AwsEc2AuthenticationOptions}, {@link VaultClient} and
- * a {@link RestTemplate}.
+ * Creates a new {@link AwsEc2Authentication} specifying
+ * {@link AwsEc2AuthenticationOptions}, {@link VaultClient} and a {@link RestTemplate}
+ * .
*
* @param options must not be {@literal null}.
* @param vaultClient must not be {@literal null}.
* @param restTemplate must not be {@literal null}.
*/
- public AwsEc2Authentication(AwsEc2AuthenticationOptions options, VaultClient vaultClient, RestTemplate restTemplate) {
+ public AwsEc2Authentication(AwsEc2AuthenticationOptions options,
+ VaultClient vaultClient, RestTemplate restTemplate) {
Assert.notNull(options, "AwsEc2AuthenticationOptions must not be null");
Assert.notNull(vaultClient, "VaultEndpoint must not be null");
@@ -95,10 +101,12 @@ public class AwsEc2Authentication implements ClientAuthentication {
Map login = getEc2Login();
- VaultResponseEntity entity = this.vaultClient.postForEntity(path, login, VaultResponse.class);
+ VaultResponseEntity entity = this.vaultClient.postForEntity(path,
+ login, VaultResponse.class);
if (!entity.isSuccessful()) {
- throw new VaultException(String.format("Cannot login using AWS-EC2: %s", entity.getMessage()));
+ throw new VaultException(String.format("Cannot login using AWS-EC2: %s",
+ entity.getMessage()));
}
VaultResponse body = entity.getBody();
@@ -106,10 +114,13 @@ public class AwsEc2Authentication implements ClientAuthentication {
if (logger.isDebugEnabled()) {
if (body.getAuth().get("metadata") instanceof Map) {
- Map metadata = (Map) body.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")));
- } else {
+ Map metadata = (Map) body.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")));
+ }
+ else {
logger.debug("Login successful using AWS-EC2 authentication");
}
}
@@ -132,15 +143,18 @@ public class AwsEc2Authentication implements ClientAuthentication {
login.put("nonce", new String(this.nonce.get()));
try {
- String pkcs7 = restTemplate.getForObject(options.getIdentityDocumentUri(), String.class);
+ String pkcs7 = restTemplate.getForObject(options.getIdentityDocumentUri(),
+ String.class);
if (StringUtils.hasText(pkcs7)) {
login.put("pkcs7", pkcs7.replaceAll("\\r", "").replace("\\n", ""));
}
return login;
- } catch (RestClientException e) {
- throw new VaultException(
- String.format("Cannot obtain Identity Document from %s", options.getIdentityDocumentUri()), e);
+ }
+ catch (RestClientException e) {
+ throw new VaultException(String.format(
+ "Cannot obtain Identity Document from %s",
+ options.getIdentityDocumentUri()), e);
}
}
diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AwsEc2AuthenticationOptions.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AwsEc2AuthenticationOptions.java
index 04e79cde..1a70eaa9 100644
--- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/AwsEc2AuthenticationOptions.java
+++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/AwsEc2AuthenticationOptions.java
@@ -22,9 +22,9 @@ import org.springframework.util.Assert;
/**
* Authentication options for {@link AwsEc2Authentication}.
*
- * Authentication options provide the path, the Identity Document URI and an optional role.
- * {@link AwsEc2AuthenticationOptions} can be constructed using {@link #builder()}. Instances of this class are
- * immutable once constructed.
+ * Authentication options provide the path, the Identity Document URI and an optional
+ * role. {@link AwsEc2AuthenticationOptions} can be constructed using {@link #builder()}.
+ * Instances of this class are immutable once constructed.
*
* @author Mark Paluch
* @see AwsEc2Authentication
@@ -38,7 +38,8 @@ public class AwsEc2AuthenticationOptions {
public final static String DEFAULT_AWS_AUTHENTICATION_PATH = "aws-ec2";
/**
- * Default {@link AwsEc2AuthenticationOptions} using {@link #DEFAULT_AWS_AUTHENTICATION_PATH} and
+ * Default {@link AwsEc2AuthenticationOptions} using
+ * {@link #DEFAULT_AWS_AUTHENTICATION_PATH} and
* {@link #DEFAULT_PKCS7_IDENTITY_DOCUMENT_URI}.
*/
public final static AwsEc2AuthenticationOptions DEFAULT = new AwsEc2AuthenticationOptions();
@@ -106,7 +107,8 @@ public class AwsEc2AuthenticationOptions {
private URI identityDocumentUri = DEFAULT_PKCS7_IDENTITY_DOCUMENT_URI;
private String role;
- AwsEc2AuthenticationOptionsBuilder() {}
+ AwsEc2AuthenticationOptionsBuilder() {
+ }
/**
* Configure the mount path.
@@ -129,15 +131,17 @@ public class AwsEc2AuthenticationOptions {
* @return {@code this} {@link AwsEc2AuthenticationOptionsBuilder}.
* @see #DEFAULT_PKCS7_IDENTITY_DOCUMENT_URI
*/
- public AwsEc2AuthenticationOptionsBuilder identityDocumentUri(URI identityDocumentUri) {
+ public AwsEc2AuthenticationOptionsBuilder identityDocumentUri(
+ URI identityDocumentUri) {
this.identityDocumentUri = identityDocumentUri;
return this;
}
/**
- * Configure the name of the role against which the login is being attempted.If role is not specified, then the
- * login endpoint looks for a role bearing the name of the AMI ID of the EC2 instance that is trying to login.
+ * Configure the name of the role against which the login is being attempted.If
+ * role is not specified, then the login endpoint looks for a role bearing the
+ * name of the AMI ID of the EC2 instance that is trying to login.
*
* @param role may be empty or {@literal null}.
* @return {@code this} {@link AwsEc2AuthenticationOptionsBuilder}.
diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/ClientAuthentication.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/ClientAuthentication.java
index 14c5a165..0a1dcdba 100644
--- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/ClientAuthentication.java
+++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/ClientAuthentication.java
@@ -19,15 +19,17 @@ import org.springframework.vault.client.VaultException;
import org.springframework.vault.support.VaultToken;
/**
- * {@link ClientAuthentication} provides {@link VaultToken} to be used for authenticated Vault access. Implementing
- * classes usually use a login method to login and return a {@link VaultToken} when implementing {@link #login()}.
+ * {@link ClientAuthentication} provides {@link VaultToken} to be used for authenticated
+ * Vault access. Implementing classes usually use a login method to login and return a
+ * {@link VaultToken} when implementing {@link #login()}.
*
* @author Mark Paluch
*/
public interface ClientAuthentication {
/**
- * Return a {@link VaultToken}. This method can optionally log into Vault to obtain a {@link VaultToken token}.
+ * Return a {@link VaultToken}. This method can optionally log into Vault to obtain a
+ * {@link VaultToken token}.
*
* @return a {@link VaultToken}.
*/
diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/ClientCertificateAuthentication.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/ClientCertificateAuthentication.java
index 71d68b3b..530892db 100644
--- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/ClientCertificateAuthentication.java
+++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/ClientCertificateAuthentication.java
@@ -19,6 +19,7 @@ import java.util.Collections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+
import org.springframework.util.Assert;
import org.springframework.vault.client.VaultClient;
import org.springframework.vault.client.VaultException;
@@ -33,7 +34,8 @@ import org.springframework.vault.support.VaultToken;
*/
public class ClientCertificateAuthentication implements ClientAuthentication {
- private final static Logger logger = LoggerFactory.getLogger(ClientCertificateAuthentication.class);
+ private final static Logger logger = LoggerFactory
+ .getLogger(ClientCertificateAuthentication.class);
private final VaultClient vaultClient;
@@ -56,11 +58,13 @@ public class ClientCertificateAuthentication implements ClientAuthentication {
private VaultToken createTokenUsingTlsCertAuthentication(String path) {
- VaultResponseEntity entity = vaultClient.postForEntity(String.format("auth/%s/login", path),
- Collections.emptyMap(), VaultResponse.class);
+ VaultResponseEntity entity = vaultClient.postForEntity(
+ String.format("auth/%s/login", path), Collections.emptyMap(),
+ VaultResponse.class);
if (!entity.isSuccessful()) {
- throw new VaultException(String.format("Cannot login using TLS certificates: %s", entity.getMessage()));
+ throw new VaultException(String.format(
+ "Cannot login using TLS certificates: %s", entity.getMessage()));
}
logger.debug("Login successful using TLS certificates");
diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/CubbyholeAuthentication.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/CubbyholeAuthentication.java
index a590c6ae..e2557c99 100644
--- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/CubbyholeAuthentication.java
+++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/CubbyholeAuthentication.java
@@ -19,6 +19,7 @@ import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+
import org.springframework.util.Assert;
import org.springframework.vault.client.VaultClient;
import org.springframework.vault.client.VaultException;
@@ -29,22 +30,23 @@ import org.springframework.vault.support.VaultToken;
/**
* Cubbyhole {@link ClientAuthentication} implementation.
*
- * Cubbyhole authentication uses Vault primitives to provide a secured authentication workflow. Cubbyhole authentication
- * uses {@link VaultToken tokens} as primary login method. An ephemeral token is used to obtain a second, login
- * {@link VaultToken} from Vault's Cubbyhole secret backend. The login token is usually longer-lived and used to
- * interact with Vault. The login token can be retrieved either from a wrapped response or from the {@code data}
- * section.
+ * Cubbyhole authentication uses Vault primitives to provide a secured authentication
+ * workflow. Cubbyhole authentication uses {@link VaultToken tokens} as primary login
+ * method. An ephemeral token is used to obtain a second, login {@link VaultToken} from
+ * Vault's Cubbyhole secret backend. The login token is usually longer-lived and used to
+ * interact with Vault. The login token can be retrieved either from a wrapped response or
+ * from the {@code data} section.
*
Wrapped token response usage Create a Token
*
*
*
- $ vault token-create -wrap-ttl="10m"
- Key Value
- --- -----
- wrapping_token: 397ccb93-ff6c-b17b-9389-380b01ca2645
- wrapping_token_ttl: 0h10m0s
- wrapping_token_creation_time: 2016-09-18 20:29:48.652957077 +0200 CEST
- wrapped_accessor: 46b6aebb-187f-932a-26d7-4f3d86a68319
+ * $ vault token-create -wrap-ttl="10m"
+ * Key Value
+ * --- -----
+ * wrapping_token: 397ccb93-ff6c-b17b-9389-380b01ca2645
+ * wrapping_token_ttl: 0h10m0s
+ * wrapping_token_creation_time: 2016-09-18 20:29:48.652957077 +0200 CEST
+ * wrapped_accessor: 46b6aebb-187f-932a-26d7-4f3d86a68319
*
*
*
@@ -52,12 +54,12 @@ import org.springframework.vault.support.VaultToken;
*
*
*
- CubbyholeAuthenticationOptions options = CubbyholeAuthenticationOptions
- .builder()
- .initialToken(VaultToken.of("397ccb93-ff6c-b17b-9389-380b01ca2645"))
- .wrapped()
- .build();
- CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, vaultClient);
+ * CubbyholeAuthenticationOptions options = CubbyholeAuthenticationOptions
+ * .builder()
+ * .initialToken(VaultToken.of("397ccb93-ff6c-b17b-9389-380b01ca2645"))
+ * .wrapped()
+ * .build();
+ * CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, vaultClient);
*
*
*
@@ -65,26 +67,26 @@ import org.springframework.vault.support.VaultToken;
*
*
*
- $ vault token-create
- Key Value
- --- -----
- token f9e30681-d46a-cdaf-aaa0-2ae0a9ad0819
- token_accessor 4eee9bd9-81bb-06d6-af01-723c54a72148
- token_duration 0s
- token_renewable false
- token_policies [root]
-
- $ token-create -use-limit=2 -orphan -no-default-policy -policy=none
- Key Value
- --- -----
- token 895cb88b-aef4-0e33-ba65-d50007290780
- token_accessor e84b661c-8aa8-2286-b788-f258f30c8325
- token_duration 0s
- token_renewable false
- token_policies [none]
-
- $ export VAULT_TOKEN=895cb88b-aef4-0e33-ba65-d50007290780
- $ vault write cubbyhole/token token=f9e30681-d46a-cdaf-aaa0-2ae0a9ad0819
+ * $ vault token-create
+ * Key Value
+ * --- -----
+ * token f9e30681-d46a-cdaf-aaa0-2ae0a9ad0819
+ * token_accessor 4eee9bd9-81bb-06d6-af01-723c54a72148
+ * token_duration 0s
+ * token_renewable false
+ * token_policies [root]
+ *
+ * $ token-create -use-limit=2 -orphan -no-default-policy -policy=none
+ * Key Value
+ * --- -----
+ * token 895cb88b-aef4-0e33-ba65-d50007290780
+ * token_accessor e84b661c-8aa8-2286-b788-f258f30c8325
+ * token_duration 0s
+ * token_renewable false
+ * token_policies [none]
+ *
+ * $ export VAULT_TOKEN=895cb88b-aef4-0e33-ba65-d50007290780
+ * $ vault write cubbyhole/token token=f9e30681-d46a-cdaf-aaa0-2ae0a9ad0819
*
*
*
@@ -92,36 +94,42 @@ import org.springframework.vault.support.VaultToken;
*
*
*
- CubbyholeAuthenticationOptions options = CubbyholeAuthenticationOptions
- .builder()
- .initialToken(VaultToken.of("895cb88b-aef4-0e33-ba65-d50007290780"))
- .path("cubbyhole/token")
- .build();
- CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, vaultClient);
+ * CubbyholeAuthenticationOptions options = CubbyholeAuthenticationOptions
+ * .builder()
+ * .initialToken(VaultToken.of("895cb88b-aef4-0e33-ba65-d50007290780"))
+ * .path("cubbyhole/token")
+ * .build();
+ * CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, vaultClient);
*
*
*
* @author Mark Paluch
* @see CubbyholeAuthenticationOptions
* @see Auth Backend: Token
- * @see Cubbyhole Secret Backend
- * @see Response Wrapping
+ * @see Cubbyhole
+ * Secret Backend
+ * @see Response
+ * Wrapping
*/
public class CubbyholeAuthentication implements ClientAuthentication {
- private final static Logger logger = LoggerFactory.getLogger(CubbyholeAuthentication.class);
+ private final static Logger logger = LoggerFactory
+ .getLogger(CubbyholeAuthentication.class);
private final CubbyholeAuthenticationOptions options;
private final VaultClient vaultClient;
/**
- * Create a new {@link CubbyholeAuthentication} given {@link CubbyholeAuthenticationOptions} and {@link VaultClient}.
+ * Create a new {@link CubbyholeAuthentication} given
+ * {@link CubbyholeAuthenticationOptions} and {@link VaultClient}.
*
* @param options must not be {@literal null}.
* @param vaultClient must not be {@literal null}.
*/
- public CubbyholeAuthentication(CubbyholeAuthenticationOptions options, VaultClient vaultClient) {
+ public CubbyholeAuthentication(CubbyholeAuthenticationOptions options,
+ VaultClient vaultClient) {
Assert.notNull(options, "CubbyholeAuthenticationOptions must not be null");
Assert.notNull(vaultClient, "VaultClient must not be null");
@@ -133,8 +141,8 @@ public class CubbyholeAuthentication implements ClientAuthentication {
@Override
public VaultToken login() throws VaultException {
- VaultResponseEntity entity = vaultClient.getForEntity(options.getPath(), options.getInitialToken(),
- VaultResponse.class);
+ VaultResponseEntity entity = vaultClient.getForEntity(
+ options.getPath(), options.getInitialToken(), VaultResponse.class);
if (entity.isSuccessful() && entity.hasBody()) {
@@ -149,21 +157,26 @@ public class CubbyholeAuthentication implements ClientAuthentication {
}
}
- throw new VaultException(
- String.format("Cannot retrieve Token from cubbyhole: %s %s", entity.getStatusCode(), entity.getMessage()));
+ throw new VaultException(String.format(
+ "Cannot retrieve Token from cubbyhole: %s %s", entity.getStatusCode(),
+ entity.getMessage()));
}
- private VaultToken getToken(VaultResponseEntity entity, Map data) {
+ private VaultToken getToken(VaultResponseEntity entity,
+ Map data) {
if (options.isWrappedToken()) {
- VaultResponse response = vaultClient.unwrap((String) data.get("response"), VaultResponse.class);
+ VaultResponse response = vaultClient.unwrap((String) data.get("response"),
+ VaultResponse.class);
return LoginTokenUtil.from(response.getAuth());
}
if (data == null || data.isEmpty()) {
- throw new VaultException(String
- .format("Cannot retrieve Token from cubbyhole: Response at %s does not contain a token", entity.getUri()));
+ throw new VaultException(
+ String.format(
+ "Cannot retrieve Token from cubbyhole: Response at %s does not contain a token",
+ entity.getUri()));
}
if (data.size() == 1) {
@@ -171,7 +184,9 @@ 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", entity.getUri()));
+ throw new VaultException(
+ String.format(
+ "Cannot retrieve Token from cubbyhole: Response at %s does not contain an unique token",
+ entity.getUri()));
}
}
diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/CubbyholeAuthenticationOptions.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/CubbyholeAuthenticationOptions.java
index f476ccd2..09a88ce8 100644
--- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/CubbyholeAuthenticationOptions.java
+++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/CubbyholeAuthenticationOptions.java
@@ -21,8 +21,8 @@ import org.springframework.vault.support.VaultToken;
/**
* Authentication options for {@link CubbyholeAuthentication}.
*
- * Authentication options provide the path below cubbyhole and the cubbyhole mode. Instances of this class are immutable
- * once constructed.
+ * Authentication options provide the path below cubbyhole and the cubbyhole mode.
+ * Instances of this class are immutable once constructed.
*
* @author Mark Paluch
* @see CubbyholeAuthentication
@@ -45,7 +45,8 @@ public class CubbyholeAuthenticationOptions {
*/
private final boolean wrappedToken;
- private CubbyholeAuthenticationOptions(VaultToken initialToken, String path, boolean wrappedToken) {
+ private CubbyholeAuthenticationOptions(VaultToken initialToken, String path,
+ boolean wrappedToken) {
this.initialToken = initialToken;
this.path = path;
@@ -74,8 +75,9 @@ public class CubbyholeAuthenticationOptions {
}
/**
- * @return {@literal true} indicates that the Cubbyhole response contains a wrapped token, otherwise {@literal false}
- * to expect a token in the {@literal data} response.
+ * @return {@literal true} indicates that the Cubbyhole response contains a wrapped
+ * token, otherwise {@literal false} to expect a token in the {@literal data}
+ * response.
*/
public boolean isWrappedToken() {
return wrappedToken;
@@ -92,7 +94,8 @@ public class CubbyholeAuthenticationOptions {
private boolean wrappedToken;
- CubbyholeAuthenticationOptionsBuilder() {}
+ CubbyholeAuthenticationOptionsBuilder() {
+ }
/**
* Configure the initial {@link VaultToken} to access Cubbyhole.
@@ -109,7 +112,8 @@ public class CubbyholeAuthenticationOptions {
}
/**
- * Configure the cubbyhole path, such as {@code cubbyhole/token}. Expects a token in the {@code data} response.
+ * Configure the cubbyhole path, such as {@code cubbyhole/token}. Expects a token
+ * in the {@code data} response.
*
* @param path must not be empty or {@literal null}.
* @return {@code this} {@link CubbyholeAuthenticationOptionsBuilder}.
@@ -135,8 +139,8 @@ public class CubbyholeAuthenticationOptions {
}
/**
- * Build a new {@link CubbyholeAuthenticationOptions} instance. Requires {@link #path(String)} or
- * {@link #wrapped()} to be configured.
+ * Build a new {@link CubbyholeAuthenticationOptions} instance. Requires
+ * {@link #path(String)} or {@link #wrapped()} to be configured.
*
* @return a new {@link CubbyholeAuthenticationOptions}.
*/
diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/IpAddressUserId.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/IpAddressUserId.java
index 5d08c093..bd475872 100644
--- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/IpAddressUserId.java
+++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/IpAddressUserId.java
@@ -20,8 +20,8 @@ import java.io.IOException;
import java.net.InetAddress;
/**
- * Mechanism to generate a SHA-256 hashed and hex-encoded representation of the IP address. Can be calculated with
- * {@code echo -n 192.168.99.1 | sha256sum}.
+ * Mechanism to generate a SHA-256 hashed and hex-encoded representation of the IP
+ * address. Can be calculated with {@code echo -n 192.168.99.1 | sha256sum}.
*
* @author Mark Paluch
* @see AppIdUserIdMechanism
@@ -32,7 +32,8 @@ public class IpAddressUserId implements AppIdUserIdMechanism {
public String createUserId() {
try {
return Sha256.toSha256(InetAddress.getLocalHost().getHostAddress());
- } catch (IOException e) {
+ }
+ catch (IOException e) {
throw new IllegalStateException(e);
}
}
diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/LifecycleAwareSessionManager.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/LifecycleAwareSessionManager.java
index a7c0cd31..0729e3b2 100644
--- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/LifecycleAwareSessionManager.java
+++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/LifecycleAwareSessionManager.java
@@ -22,6 +22,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+
import org.springframework.beans.factory.DisposableBean;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.TaskScheduler;
@@ -36,15 +37,18 @@ import org.springframework.vault.client.VaultResponseEntity;
import org.springframework.vault.support.VaultToken;
/**
- * Lifecycle-aware Session Manager. This {@link SessionManager} obtains tokens from a {@link ClientAuthentication} upon
- * {@link #getSessionToken() request}. Tokens are renewed asynchronously if a token has a lease duration. This happens 5
- * seconds before the token expires, see {@link #REFRESH_PERIOD_BEFORE_EXPIRY}.
+ * Lifecycle-aware Session Manager. This {@link SessionManager} obtains tokens from a
+ * {@link ClientAuthentication} upon {@link #getSessionToken() request}. Tokens are
+ * renewed asynchronously if a token has a lease duration. This happens 5 seconds before
+ * the token expires, see {@link #REFRESH_PERIOD_BEFORE_EXPIRY}.
*
- * This {@link SessionManager} also implements {@link DisposableBean} to revoke the {@link LoginToken} once it's not
- * required anymore. Token revocation will stop regular token refresh.
+ * This {@link SessionManager} also implements {@link DisposableBean} to revoke the
+ * {@link LoginToken} once it's not required anymore. Token revocation will stop regular
+ * token refresh.
*
- * If Token renewal runs into a client-side error, it assumes the token was revoked/expired and discards the token state
- * so the next attempt will lead to another login attempt.
+ * If Token renewal runs into a client-side error, it assumes the token was
+ * revoked/expired and discards the token state so the next attempt will lead to another
+ * login attempt.
*
* @author Mark Paluch
* @see LoginToken
@@ -55,7 +59,8 @@ public class LifecycleAwareSessionManager implements SessionManager, DisposableB
public static final int REFRESH_PERIOD_BEFORE_EXPIRY = 5;
- private final static Logger logger = LoggerFactory.getLogger(LifecycleAwareSessionManager.class);
+ private final static Logger logger = LoggerFactory
+ .getLogger(LifecycleAwareSessionManager.class);
private final ClientAuthentication clientAuthentication;
private final VaultClient vaultClient;
@@ -65,15 +70,15 @@ public class LifecycleAwareSessionManager implements SessionManager, DisposableB
private volatile VaultToken token;
/**
- * Create a {@link LifecycleAwareSessionManager} given {@link ClientAuthentication}, {@link AsyncTaskExecutor} and
- * {@link VaultClient}.
+ * Create a {@link LifecycleAwareSessionManager} given {@link ClientAuthentication},
+ * {@link AsyncTaskExecutor} and {@link VaultClient}.
*
* @param clientAuthentication must not be {@literal null}.
* @param taskExecutor must not be {@literal null}.
* @param vaultClient must not be {@literal null}.
*/
- public LifecycleAwareSessionManager(ClientAuthentication clientAuthentication, AsyncTaskExecutor taskExecutor,
- VaultClient vaultClient) {
+ public LifecycleAwareSessionManager(ClientAuthentication clientAuthentication,
+ AsyncTaskExecutor taskExecutor, VaultClient vaultClient) {
Assert.notNull(clientAuthentication, "ClientAuthentication must not be null");
Assert.notNull(taskExecutor, "AsyncTaskExecutor must not be null");
@@ -91,21 +96,24 @@ public class LifecycleAwareSessionManager implements SessionManager, DisposableB
this.token = null;
if (token instanceof LoginToken) {
- VaultResponseEntity response = vaultClient.postForEntity("auth/token/revoke-self", token, null, Map.class);
+ VaultResponseEntity response = vaultClient.postForEntity(
+ "auth/token/revoke-self", token, null, Map.class);
if (!response.isSuccessful()) {
- logger.warn("Cannot revoke VaultToken: {}", buildExceptionMessage(response));
+ logger.warn("Cannot revoke VaultToken: {}",
+ buildExceptionMessage(response));
}
}
}
/**
- * Performs a token refresh. Creates a new token if no token was obtained before. If a token was obtained before, it
- * uses self-renewal to renew the current token. Client-side errors (like permission denied) indicate the token cannot
- * be renewed because it's expired or simply not found.
+ * Performs a token refresh. Creates a new token if no token was obtained before. If a
+ * token was obtained before, it uses self-renewal to renew the current token.
+ * Client-side errors (like permission denied) indicate the token cannot be renewed
+ * because it's expired or simply not found.
*
- * @return {@literal true} if the refresh was successful. {@literal false} if a new token was obtained or refresh
- * failed.
+ * @return {@literal true} if the refresh was successful. {@literal false} if a new
+ * token was obtained or refresh failed.
*/
protected boolean renewToken() {
@@ -116,12 +124,14 @@ public class LifecycleAwareSessionManager implements SessionManager, DisposableB
return false;
}
- VaultResponseEntity response = vaultClient.postForEntity("auth/token/renew-self", token, null, Map.class);
+ VaultResponseEntity response = vaultClient.postForEntity(
+ "auth/token/renew-self", token, null, Map.class);
if (!response.isSuccessful()) {
if (response.getStatusCode().is4xxClientError()) {
- logger.debug("Cannot refresh token, resetting token and performing re-login: {}",
+ logger.debug(
+ "Cannot refresh token, resetting token and performing re-login: {}",
buildExceptionMessage(response));
token = null;
return false;
@@ -169,19 +179,23 @@ public class LifecycleAwareSessionManager implements SessionManager, DisposableB
logger.info("Scheduling Token renewal");
LoginToken loginToken = (LoginToken) token;
- final int seconds = NumberUtils.convertNumberToTargetClass(
- Math.max(1, loginToken.getLeaseDuration() - REFRESH_PERIOD_BEFORE_EXPIRY), Integer.class);
+ final int seconds = NumberUtils
+ .convertNumberToTargetClass(
+ Math.max(1, loginToken.getLeaseDuration()
+ - REFRESH_PERIOD_BEFORE_EXPIRY), Integer.class);
final Runnable task = new Runnable() {
@Override
public void run() {
try {
- if (LifecycleAwareSessionManager.this.token != null && isTokenRenewable()) {
+ if (LifecycleAwareSessionManager.this.token != null
+ && isTokenRenewable()) {
if (renewToken()) {
scheduleRenewal();
}
}
- } catch (Exception e) {
+ }
+ catch (Exception e) {
logger.error("Cannot renew VaultToken", e);
}
}
@@ -196,12 +210,15 @@ public class LifecycleAwareSessionManager implements SessionManager, DisposableB
@Override
public void run() {
try {
- // TODO: Revisit this approach since it blocks a thread. Spinning up a managed
- // TaskScheduler just for once-in-a-while token renewal seemed a bit over-sophisticated
+ // TODO: Revisit this approach since it blocks a thread. Spinning up a
+ // managed
+ // TaskScheduler just for once-in-a-while token renewal seemed a bit
+ // over-sophisticated
// that's why we emulate a scheduler by blocking a Thread resource
Thread.sleep(TimeUnit.SECONDS.toMillis(seconds));
task.run();
- } catch (InterruptedException e) {
+ }
+ catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
@@ -215,14 +232,17 @@ public class LifecycleAwareSessionManager implements SessionManager, DisposableB
private static String buildExceptionMessage(VaultResponseEntity> response) {
if (StringUtils.hasText(response.getMessage())) {
- return String.format("Status %s URI %s: %s", response.getStatusCode(), response.getUri(), response.getMessage());
+ return String.format("Status %s URI %s: %s", response.getStatusCode(),
+ response.getUri(), response.getMessage());
}
- return String.format("Status %s URI %s", response.getStatusCode(), response.getUri());
+ return String.format("Status %s URI %s", response.getStatusCode(),
+ response.getUri());
}
/**
- * This one-shot trigger creates only one execution time to trigger an execution only once.
+ * This one-shot trigger creates only one execution time to trigger an execution only
+ * once.
*/
private static class OneShotTrigger implements Trigger {
@@ -237,7 +257,8 @@ public class LifecycleAwareSessionManager implements SessionManager, DisposableB
public Date nextExecutionTime(TriggerContext triggerContext) {
if (fired.compareAndSet(false, true)) {
- return new Date(System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(seconds));
+ return new Date(System.currentTimeMillis()
+ + TimeUnit.SECONDS.toMillis(seconds));
}
return null;
diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/LoginToken.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/LoginToken.java
index d29101e3..cdfad194 100644
--- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/LoginToken.java
+++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/LoginToken.java
@@ -15,11 +15,11 @@
*/
package org.springframework.vault.authentication;
+import lombok.ToString;
+
import org.springframework.util.Assert;
import org.springframework.vault.support.VaultToken;
-import lombok.ToString;
-
/**
* Value object for a Vault token obtained by a login method.
*
diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/MacAddressUserId.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/MacAddressUserId.java
index 9742d9cd..e22e121a 100644
--- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/MacAddressUserId.java
+++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/MacAddressUserId.java
@@ -24,13 +24,15 @@ import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
- * Mechanism to generate a UserId based on the Mac address. {@link MacAddressUserId} creates a hex-encoded
- * representation of the Mac address without any separators (0123456789AB). A network interface hint can be specified
- * optionally to select a network interface (index/name).
+ * Mechanism to generate a UserId based on the Mac address. {@link MacAddressUserId}
+ * creates a hex-encoded representation of the Mac address without any separators
+ * (0123456789AB). A network interface hint can be specified optionally to select a
+ * network interface (index/name).
*
* @author Mark Paluch
* @see AppIdUserIdMechanism
@@ -50,22 +52,24 @@ public class MacAddressUserId implements AppIdUserIdMechanism {
}
/**
- * Creates a new {@link MacAddressUserId} using a {@code networkInterfaceIndex}. The index is applied to
- * {@link NetworkInterface#getNetworkInterfaces()} to obtain the desired network interface.
+ * Creates a new {@link MacAddressUserId} using a {@code networkInterfaceIndex}. The
+ * index is applied to {@link NetworkInterface#getNetworkInterfaces()} to obtain the
+ * desired network interface.
*
* @param networkInterfaceIndex must be greater or equal to zero.
*/
public MacAddressUserId(int networkInterfaceIndex) {
- Assert.isTrue(networkInterfaceIndex >= 0, "NetworkInterfaceIndex must be greater or equal to 0");
+ Assert.isTrue(networkInterfaceIndex >= 0,
+ "NetworkInterfaceIndex must be greater or equal to 0");
this.networkInterfaceHint = "" + networkInterfaceIndex;
}
/**
- * Creates a new {@link MacAddressUserId} using a {@code networkInterfaceName}. This name is compared with
- * {@link NetworkInterface#getName()} and {@link NetworkInterface#getDisplayName()} to obtain the desired network
- * interface.
+ * Creates a new {@link MacAddressUserId} using a {@code networkInterfaceName}. This
+ * name is compared with {@link NetworkInterface#getName()} and
+ * {@link NetworkInterface#getDisplayName()} to obtain the desired network interface.
*
* @param networkInterfaceName must not be {@literal null}.
*/
@@ -82,44 +86,54 @@ public class MacAddressUserId implements AppIdUserIdMechanism {
try {
NetworkInterface networkInterface = null;
- List interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
+ List interfaces = Collections.list(NetworkInterface
+ .getNetworkInterfaces());
if (StringUtils.hasText(networkInterfaceHint)) {
try {
- networkInterface = getNetworkInterface(Integer.parseInt(networkInterfaceHint), interfaces);
- } catch (NumberFormatException e) {
- networkInterface = getNetworkInterface((networkInterfaceHint), interfaces);
+ networkInterface = getNetworkInterface(
+ Integer.parseInt(networkInterfaceHint), interfaces);
+ }
+ catch (NumberFormatException e) {
+ networkInterface = getNetworkInterface((networkInterfaceHint),
+ interfaces);
}
}
if (networkInterface == null) {
if (StringUtils.hasText(networkInterfaceHint)) {
- log.warn(String.format("Did not find a NetworkInterface applying hint %s", networkInterfaceHint));
+ log.warn(String.format(
+ "Did not find a NetworkInterface applying hint %s",
+ networkInterfaceHint));
}
InetAddress localHost = InetAddress.getLocalHost();
networkInterface = NetworkInterface.getByInetAddress(localHost);
if (networkInterface == null) {
- throw new IllegalStateException(String.format("Cannot determine NetworkInterface for %s", localHost));
+ 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()));
+ throw new IllegalStateException(String.format(
+ "Network interface %s has no hardware address",
+ networkInterface.getName()));
}
return Sha256.toSha256(Sha256.toHexString(mac));
- } catch (IOException e) {
+ }
+ catch (IOException e) {
throw new IllegalStateException(e);
}
}
- private NetworkInterface getNetworkInterface(Number hint, List interfaces) {
+ private NetworkInterface getNetworkInterface(Number hint,
+ List interfaces) {
if (interfaces.size() > hint.intValue() && hint.intValue() >= 0) {
return interfaces.get(hint.intValue());
@@ -128,10 +142,12 @@ public class MacAddressUserId implements AppIdUserIdMechanism {
return null;
}
- private NetworkInterface getNetworkInterface(String hint, List interfaces) {
+ private NetworkInterface getNetworkInterface(String hint,
+ List interfaces) {
for (NetworkInterface anInterface : interfaces) {
- if (hint.equals(anInterface.getDisplayName()) || hint.equals(anInterface.getName())) {
+ if (hint.equals(anInterface.getDisplayName())
+ || hint.equals(anInterface.getName())) {
return anInterface;
}
}
diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/SessionManager.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/SessionManager.java
index 1099b83b..d470a4a6 100644
--- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/SessionManager.java
+++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/SessionManager.java
@@ -18,10 +18,12 @@ package org.springframework.vault.authentication;
import org.springframework.vault.support.VaultToken;
/**
- * Strategy interface that encapsulates the creation and management of Vault sessions based on {@link VaultToken}.
+ * Strategy interface that encapsulates the creation and management of Vault sessions
+ * based on {@link VaultToken}.
*
- * {@link SessionManager} is used by {@link org.springframework.vault.core.VaultTemplate} to initiate a session.
- * Implementing classes usually use {@link ClientAuthentication} to log into Vault and obtain tokens.
+ * {@link SessionManager} is used by {@link org.springframework.vault.core.VaultTemplate}
+ * to initiate a session. Implementing classes usually use {@link ClientAuthentication} to
+ * log into Vault and obtain tokens.
*
* @author Mark Paluch
* @see SimpleSessionManager
diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/Sha256.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/Sha256.java
index e36b4ec8..162bac3e 100644
--- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/Sha256.java
+++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/Sha256.java
@@ -47,16 +47,18 @@ class Sha256 {
}
/**
- * Get a MessageDigest instance for the given algorithm. Throws an IllegalArgumentException if algorithm is
- * unknown
+ * Get a MessageDigest instance for the given algorithm. Throws an
+ * IllegalArgumentException if algorithm is unknown
*
* @return MessageDigest instance
* @throws IllegalArgumentException if NoSuchAlgorithmException is thrown
*/
- private static MessageDigest getMessageDigest(String algorithm) throws IllegalArgumentException {
+ private static MessageDigest getMessageDigest(String algorithm)
+ throws IllegalArgumentException {
try {
return MessageDigest.getInstance(algorithm);
- } catch (NoSuchAlgorithmException e) {
+ }
+ catch (NoSuchAlgorithmException e) {
throw new IllegalArgumentException("No such algorithm [" + algorithm + "]");
}
}
diff --git a/spring-vault-core/src/main/java/org/springframework/vault/authentication/SimpleSessionManager.java b/spring-vault-core/src/main/java/org/springframework/vault/authentication/SimpleSessionManager.java
index 99744661..c4b2a8db 100644
--- a/spring-vault-core/src/main/java/org/springframework/vault/authentication/SimpleSessionManager.java
+++ b/spring-vault-core/src/main/java/org/springframework/vault/authentication/SimpleSessionManager.java
@@ -21,8 +21,8 @@ import org.springframework.vault.support.VaultToken;
/**
* Default implementation of {@link SessionManager}.
*
- * Uses a synchronized login method to log into Vault and reuse the resulting {@link VaultToken} throughout session
- * lifetime.
+ * Uses a synchronized login method to log into Vault and reuse the resulting
+ * {@link VaultToken} throughout session lifetime.
*
* @author Mark Paluch
* @see ClientAuthentication
diff --git a/spring-vault-core/src/main/java/org/springframework/vault/client/VaultAccessor.java b/spring-vault-core/src/main/java/org/springframework/vault/client/VaultAccessor.java
index 26f38b52..352d286b 100644
--- a/spring-vault-core/src/main/java/org/springframework/vault/client/VaultAccessor.java
+++ b/spring-vault-core/src/main/java/org/springframework/vault/client/VaultAccessor.java
@@ -27,7 +27,8 @@ import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;
/**
- * Base class for Vault accessing helpers, defining common properties such as the {@link RestTemplate} to operate on.
+ * Base class for Vault accessing helpers, defining common properties such as the
+ * {@link RestTemplate} to operate on.
*
* Not intended to be used directly. See {@link VaultClient}.
*
@@ -66,41 +67,49 @@ public abstract class VaultAccessor {
return callback.doWithRestTemplate(uri, getRestTemplate());
}
- public VaultResponseEntity exchange(URI uri, HttpMethod httpMethod, HttpEntity> httpEntity,
- Class returnType) {
+ public VaultResponseEntity exchange(URI uri,
+ HttpMethod httpMethod, HttpEntity> httpEntity, Class returnType) {
Assert.notNull(uri, "URI must not be null");
Assert.notNull(httpMethod, "HttpMethod must not be null");
Assert.notNull(returnType, "Return type must not be null");
try {
- ResponseEntity response = this.getRestTemplate().exchange(uri, httpMethod, httpEntity, returnType);
+ ResponseEntity response = this.getRestTemplate().exchange(uri, httpMethod,
+ httpEntity, returnType);
- return new VaultResponseEntity((S) response.getBody(), response.getStatusCode(), uri,
- response.getStatusCode().getReasonPhrase());
- } catch (HttpStatusCodeException e) {
+ return new VaultResponseEntity((S) response.getBody(),
+ response.getStatusCode(), uri, response.getStatusCode()
+ .getReasonPhrase());
+ }
+ catch (HttpStatusCodeException e) {
return handleCodeException(uri, e);
}
}
- public VaultResponseEntity exchange(URI uri, HttpMethod httpMethod, HttpEntity> httpEntity,
- ParameterizedTypeReference returnType) {
+ public VaultResponseEntity exchange(URI uri,
+ HttpMethod httpMethod, HttpEntity> httpEntity,
+ ParameterizedTypeReference returnType) {
Assert.notNull(uri, "URI must not be null");
Assert.notNull(httpMethod, "HttpMethod must not be null");
Assert.notNull(returnType, "Return type must not be null");
try {
- ResponseEntity response = this.getRestTemplate().exchange(uri, httpMethod, httpEntity, returnType);
+ ResponseEntity response = this.getRestTemplate().exchange(uri, httpMethod,
+ httpEntity, returnType);
- return new VaultResponseEntity((S) response.getBody(), response.getStatusCode(), uri,
- response.getStatusCode().getReasonPhrase());
- } catch (HttpStatusCodeException e) {
+ return new VaultResponseEntity((S) response.getBody(),
+ response.getStatusCode(), uri, response.getStatusCode()
+ .getReasonPhrase());
+ }
+ catch (HttpStatusCodeException e) {
return handleCodeException(uri, e);
}
}
- private VaultResponseEntity handleCodeException(URI uri, HttpStatusCodeException e) {
+ private VaultResponseEntity handleCodeException(URI uri,
+ HttpStatusCodeException e) {
String message = e.getResponseBodyAsString();
diff --git a/spring-vault-core/src/main/java/org/springframework/vault/client/VaultClient.java b/spring-vault-core/src/main/java/org/springframework/vault/client/VaultClient.java
index 4e879842..29d3a0d0 100644
--- a/spring-vault-core/src/main/java/org/springframework/vault/client/VaultClient.java
+++ b/spring-vault-core/src/main/java/org/springframework/vault/client/VaultClient.java
@@ -39,12 +39,14 @@ import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
/**
- * Implementation of the low-level Vault client. This client uses the Vault HTTP API to issue requests using different
- * {@link HttpMethod HTTP methods}. {@link VaultClient} is configured with an {@link VaultEndpoint} and
- * {@link RestTemplate}. It does not maintain any session or token state. See {@link VaultTemplate} and
- * {@link org.springframework.vault.authentication.SessionManager} for authenticated and stateful Vault access.
- * {@link VaultClient} encapsulates base URI and path construction and uses {@link VaultAccessor} for request and error
- * handling by returning {@link VaultResponseEntity} for requests.
+ * Implementation of the low-level Vault client. This client uses the Vault HTTP API to
+ * issue requests using different {@link HttpMethod HTTP methods}. {@link VaultClient} is
+ * configured with an {@link VaultEndpoint} and {@link RestTemplate}. It does not maintain
+ * any session or token state. See {@link VaultTemplate} and
+ * {@link org.springframework.vault.authentication.SessionManager} for authenticated and
+ * stateful Vault access. {@link VaultClient} encapsulates base URI and path construction
+ * and uses {@link VaultAccessor} for request and error handling by returning
+ * {@link VaultResponseEntity} for requests.
*
* @author Mark Paluch
* @see VaultResponseEntity
@@ -59,7 +61,8 @@ public class VaultClient extends VaultAccessor {
private final VaultEndpoint endpoint;
/**
- * Creates a new {@link VaultClient} with a default a {@link RestTemplate} and {@link VaultEndpoint}.
+ * Creates a new {@link VaultClient} with a default a {@link RestTemplate} and
+ * {@link VaultEndpoint}.
*
* @see VaultEndpoint
*/
@@ -68,7 +71,8 @@ public class VaultClient extends VaultAccessor {
}
/**
- * Creates a new {@link VaultClient} for a {@link ClientHttpRequestFactory} and {@link VaultEndpoint}.
+ * Creates a new {@link VaultClient} for a {@link ClientHttpRequestFactory} and
+ * {@link VaultEndpoint}.
*
* @param requestFactory must not be {@literal null}.
* @param endpoint must not be {@literal null}.
@@ -82,9 +86,11 @@ public class VaultClient extends VaultAccessor {
}
/**
- * Create a {@link RestTemplate} using an interceptor given a {@link ClientHttpRequestFactory}. This forces
- * {@link RestTemplate} to create the body representation instead of streaming the body to the TCP channel. Streaming
- * the body without knowing the size in advance will skip the {@link HttpHeaders#CONTENT_LENGTH} makes Vault upset.
+ * Create a {@link RestTemplate} using an interceptor given a
+ * {@link ClientHttpRequestFactory}. This forces {@link RestTemplate} to create the
+ * body representation instead of streaming the body to the TCP channel. Streaming the
+ * body without knowing the size in advance will skip the
+ * {@link HttpHeaders#CONTENT_LENGTH} makes Vault upset.
*
* @param requestFactory must not be {@literal null}.
* @return the {@link RestTemplate}
@@ -97,8 +103,8 @@ public class VaultClient extends VaultAccessor {
restTemplate.getInterceptors().add(new ClientHttpRequestInterceptor() {
@Override
- public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
- throws IOException {
+ public ClientHttpResponse intercept(HttpRequest request, byte[] body,
+ ClientHttpRequestExecution execution) throws IOException {
return execution.execute(request, body);
}
});
@@ -107,7 +113,8 @@ public class VaultClient extends VaultAccessor {
}
/**
- * Creates a new {@link VaultClient} for a {@link RestTemplate} and {@link VaultEndpoint}.
+ * Creates a new {@link VaultClient} for a {@link RestTemplate} and
+ * {@link VaultEndpoint}.
*
* @param restTemplate must not be {@literal null}.
* @param endpoint must not be {@literal null}.
@@ -121,19 +128,23 @@ public class VaultClient extends VaultAccessor {
}
/**
- * Retrieve a resource by GETting from the path, and returns the response as {@link VaultResponseEntity}.
+ * Retrieve a resource by GETting from the path, and returns the response as
+ * {@link VaultResponseEntity}.
*
* @param path the path.
* @param responseType the type of the return value
* @return the response as entity.
* @see VaultResponseEntity
*/
- public VaultResponseEntity getForEntity(String path, Class responseType) {
- return exchange(path, HttpMethod.GET, new HttpEntity(null), responseType, null);
+ public VaultResponseEntity getForEntity(String path,
+ Class responseType) {
+ return exchange(path, HttpMethod.GET, new HttpEntity(null), responseType,
+ null);
}
/**
- * Retrieve a resource by GETting from the path, and returns the response as {@link VaultResponseEntity}.
+ * Retrieve a resource by GETting from the path, and returns the response as
+ * {@link VaultResponseEntity}.
*
* @param path the path.
* @param vaultToken the {@link VaultToken}.
@@ -141,14 +152,16 @@ public class VaultClient extends VaultAccessor {
* @return the response as entity.
* @see VaultResponseEntity
*/
- public VaultResponseEntity getForEntity(String path, VaultToken vaultToken,
- Class responseType) {
+ public VaultResponseEntity getForEntity(String path,
+ VaultToken vaultToken, Class responseType) {
- return exchange(path, HttpMethod.GET, new HttpEntity(null, createHeaders(vaultToken)), responseType, null);
+ return exchange(path, HttpMethod.GET, new HttpEntity(null,
+ createHeaders(vaultToken)), responseType, null);
}
/**
- * Issue a POST request using the given object to the path, and returns the response as {@link VaultResponseEntity}.
+ * Issue a POST request using the given object to the path, and returns the response
+ * as {@link VaultResponseEntity}.
*
* @param path the path.
* @param request the Object to be POSTed, may be {@code null}.
@@ -156,12 +169,15 @@ public class VaultClient extends VaultAccessor {
* @return the response as entity.
* @see VaultResponseEntity
*/
- public VaultResponseEntity postForEntity(String path, Object request, Class responseType) {
- return exchange(path, HttpMethod.POST, new HttpEntity(request), responseType, null);
+ public VaultResponseEntity postForEntity(String path,
+ Object request, Class responseType) {
+ return exchange(path, HttpMethod.POST, new HttpEntity(request),
+ responseType, null);
}
/**
- * Issue a POST request using the given object to the path, and returns the response as {@link VaultResponseEntity}.
+ * Issue a POST request using the given object to the path, and returns the response
+ * as {@link VaultResponseEntity}.
*
* @param path the path.
* @param vaultToken the {@link VaultToken}.
@@ -170,15 +186,15 @@ public class VaultClient extends VaultAccessor {
* @return the response as entity.
* @see VaultResponseEntity
*/
- public VaultResponseEntity postForEntity(String path, VaultToken vaultToken, Object request,
- Class responseType) {
- return exchange(path, HttpMethod.POST, new HttpEntity(request, createHeaders(vaultToken)), responseType,
- null);
+ public VaultResponseEntity postForEntity(String path,
+ VaultToken vaultToken, Object request, Class responseType) {
+ return exchange(path, HttpMethod.POST, new HttpEntity(request,
+ createHeaders(vaultToken)), responseType, null);
}
/**
- * Create a new resource by PUTting the given object to the path, and returns the response as
- * {@link VaultResponseEntity}.
+ * Create a new resource by PUTting the given object to the path, and returns the
+ * response as {@link VaultResponseEntity}.
*
* @param path the path.
* @param request the Object to be PUT.
@@ -186,13 +202,15 @@ public class VaultClient extends VaultAccessor {
* @return the response as entity.
* @see VaultResponseEntity
*/
- public VaultResponseEntity putForEntity(String path, Object request, Class responseType) {
- return exchange(path, HttpMethod.PUT, new HttpEntity(request), responseType, null);
+ public VaultResponseEntity putForEntity(String path,
+ Object request, Class responseType) {
+ return exchange(path, HttpMethod.PUT, new HttpEntity(request),
+ responseType, null);
}
/**
- * Create a new resource by PUTting the given object to the path, and returns the response as
- * {@link VaultResponseEntity}.
+ * Create a new resource by PUTting the given object to the path, and returns the
+ * response as {@link VaultResponseEntity}.
*
* @param path the path.
* @param vaultToken the {@link VaultToken}.
@@ -201,14 +219,15 @@ public class VaultClient extends VaultAccessor {
* @return the response as entity.
* @see VaultResponseEntity
*/
- public VaultResponseEntity putForEntity(String path, VaultToken vaultToken, Object request,
- Class responseType) {
- return exchange(path, HttpMethod.PUT, new HttpEntity(request, createHeaders(vaultToken)), responseType,
- null);
+ public VaultResponseEntity putForEntity(String path,
+ VaultToken vaultToken, Object request, Class responseType) {
+ return exchange(path, HttpMethod.PUT, new HttpEntity(request,
+ createHeaders(vaultToken)), responseType, null);
}
/**
- * Delete a resource by DELETEing from the path, and returns the response as {@link VaultResponseEntity}.
+ * Delete a resource by DELETEing from the path, and returns the response as
+ * {@link VaultResponseEntity}.
*
* @param path the path.
* @param vaultToken the {@link VaultToken}.
@@ -216,79 +235,93 @@ public class VaultClient extends VaultAccessor {
* @return the response as entity.
* @see VaultResponseEntity
*/
- public VaultResponseEntity deleteForEntity(String path, VaultToken vaultToken,
- Class responseType) {
+ public VaultResponseEntity deleteForEntity(String path,
+ VaultToken vaultToken, Class responseType) {
- return exchange(path, HttpMethod.DELETE, new HttpEntity(null, createHeaders(vaultToken)), responseType,
- null);
+ return exchange(path, HttpMethod.DELETE, new HttpEntity(null,
+ createHeaders(vaultToken)), responseType, null);
}
/**
- * Execute the HTTP method to the given URI template, writing the given request entity to the request, and returns the
- * response as {@link VaultResponseEntity}. URI Template variables are using the given URI variables, if any.
+ * Execute the HTTP method to the given URI template, writing the given request entity
+ * to the request, and returns the response as {@link VaultResponseEntity}. URI
+ * Template variables are using the given URI variables, if any.
*
* @param pathTemplate the path template.
* @param method the HTTP method (GET, POST, etc).
- * @param requestEntity the entity (headers and/or body) to write to the request, may be {@code null}.
+ * @param requestEntity the entity (headers and/or body) to write to the request, may
+ * be {@code null}.
* @param responseType the type of the return value.
* @param uriVariables the variables to expand in the template.
* @return the response as entity.
*/
- public VaultResponseEntity exchange(String pathTemplate, HttpMethod method,
- HttpEntity> requestEntity, Class responseType, Map uriVariables) throws RestClientException {
+ public VaultResponseEntity exchange(String pathTemplate,
+ HttpMethod method, HttpEntity> requestEntity, Class responseType,
+ Map uriVariables) throws RestClientException {
Assert.hasText(pathTemplate, "Path template must not be null or empty");
- Assert.isTrue(!pathTemplate.startsWith("/"), "Path template must not start with a slash (/)");
+ Assert.isTrue(!pathTemplate.startsWith("/"),
+ "Path template must not start with a slash (/)");
- URI uri = uriVariables != null ? buildUri(pathTemplate, uriVariables) : getEndpoint().createUri(pathTemplate);
+ URI uri = uriVariables != null ? buildUri(pathTemplate, uriVariables)
+ : getEndpoint().createUri(pathTemplate);
return exchange(uri, method, requestEntity, responseType);
}
/**
- * Execute the HTTP method to the given path template, writing the given request entity to the request, and returns
- * the response as {@link VaultResponseEntity}. The given {@link ParameterizedTypeReference} is used to pass generic
- * type information:
+ * Execute the HTTP method to the given path template, writing the given request
+ * entity to the request, and returns the response as {@link VaultResponseEntity}. The
+ * given {@link ParameterizedTypeReference} is used to pass generic type information:
*
*
- * ParameterizedTypeReference<List<MyBean>> myBean = new ParameterizedTypeReference<List<MyBean>>() {};
- * ResponseEntity<List<MyBean>> response = client.exchange("http://example.com", HttpMethod.GET, null, myBean, null);
+ * ParameterizedTypeReference<List<MyBean>> myBean = new ParameterizedTypeReference<List<MyBean>>() {
+ * };
+ * ResponseEntity<List<MyBean>> response = client.exchange("http://example.com",
+ * HttpMethod.GET, null, myBean, null);
*
*
* @param pathTemplate the path template.
* @param method the HTTP method (GET, POST, etc).
- * @param requestEntity the entity (headers and/or body) to write to the request, may be {@code null}.
+ * @param requestEntity the entity (headers and/or body) to write to the request, may
+ * be {@code null}.
* @param responseType the type of the return value.
* @param uriVariables the variables to expand in the template.
* @return the response as entity.
*/
- public VaultResponseEntity exchange(String pathTemplate, HttpMethod method,
- HttpEntity> requestEntity, ParameterizedTypeReference responseType, Map uriVariables)
+ public VaultResponseEntity exchange(String pathTemplate,
+ HttpMethod method, HttpEntity> requestEntity,
+ ParameterizedTypeReference responseType, Map uriVariables)
throws RestClientException {
Assert.hasText(pathTemplate, "Path template must not be null or empty");
- Assert.isTrue(!pathTemplate.startsWith("/"), "Path template must not start with a slash (/)");
+ Assert.isTrue(!pathTemplate.startsWith("/"),
+ "Path template must not start with a slash (/)");
- URI uri = uriVariables != null ? buildUri(pathTemplate, uriVariables) : getEndpoint().createUri(pathTemplate);
+ URI uri = uriVariables != null ? buildUri(pathTemplate, uriVariables)
+ : getEndpoint().createUri(pathTemplate);
return exchange(uri, method, requestEntity, responseType);
}
/**
- * Executes a {@link RestTemplateCallback}. Allows to interact with the underlying {@link RestTemplate} and benefit
- * from optional parameter expansion.
+ * Executes a {@link RestTemplateCallback}. Allows to interact with the underlying
+ * {@link RestTemplate} and benefit from optional parameter expansion.
*
* @param pathTemplate the path template.
* @param uriVariables the variables to expand in the template
* @param callback the request.
* @return the {@link RestTemplateCallback} return value.
*/
- public T doWithRestTemplate(String pathTemplate, Map uriVariables, RestTemplateCallback callback) {
+ public T doWithRestTemplate(String pathTemplate, Map uriVariables,
+ RestTemplateCallback callback) {
Assert.hasText(pathTemplate, "Path template must not be null or empty");
- Assert.isTrue(!pathTemplate.startsWith("/"), "Path template must not start with a slash (/)");
+ Assert.isTrue(!pathTemplate.startsWith("/"),
+ "Path template must not start with a slash (/)");
- URI uri = uriVariables != null ? buildUri(pathTemplate, uriVariables) : getEndpoint().createUri(pathTemplate);
+ URI uri = uriVariables != null ? buildUri(pathTemplate, uriVariables)
+ : getEndpoint().createUri(pathTemplate);
return super.doWithRestTemplate(uri, callback);
}
@@ -301,8 +334,9 @@ public class VaultClient extends VaultAccessor {
}
/**
- * Build the Vault {@link URI} based on the given {@link VaultEndpoint} and {@code pathTemplate}. URI template
- * variables will be expanded using {@code uriVariables}.
+ * Build the Vault {@link URI} based on the given {@link VaultEndpoint} and
+ * {@code pathTemplate}. URI template variables will be expanded using
+ * {@code uriVariables}.
*
* @param pathTemplate must not be empty or {@literal null}.
* @param uriVariables must not be {@literal null}.
@@ -313,7 +347,8 @@ public class VaultClient extends VaultAccessor {
Assert.hasText(pathTemplate, "Path must not be empty");
- return getRestTemplate().getUriTemplateHandler().expand(getEndpoint().createUriString(pathTemplate), uriVariables);
+ return getRestTemplate().getUriTemplateHandler().expand(
+ getEndpoint().createUriString(pathTemplate), uriVariables);
}
/**
@@ -355,7 +390,8 @@ public class VaultClient extends VaultAccessor {
return new HttpHeaders();
}
});
- } catch (IOException e) {
+ }
+ catch (IOException e) {
throw new IllegalStateException(e);
}
}
diff --git a/spring-vault-core/src/main/java/org/springframework/vault/client/VaultEndpoint.java b/spring-vault-core/src/main/java/org/springframework/vault/client/VaultEndpoint.java
index da3d3b56..0661a60b 100644
--- a/spring-vault-core/src/main/java/org/springframework/vault/client/VaultEndpoint.java
+++ b/spring-vault-core/src/main/java/org/springframework/vault/client/VaultEndpoint.java
@@ -18,14 +18,15 @@ package org.springframework.vault.client;
import java.io.Serializable;
import java.net.URI;
-import org.springframework.util.Assert;
-
import lombok.EqualsAndHashCode;
+import org.springframework.util.Assert;
+
/**
* Value object that defines Vault connection coordinates.
*
- * A {@link VaultEndpoint} defines the hostname, TCP port and the protocol scheme (HTTP or HTTPS).
+ * A {@link VaultEndpoint} defines the hostname, TCP port and the protocol scheme (HTTP or
+ * HTTPS).
*
* @author Mark Paluch
*/
@@ -71,7 +72,8 @@ public class VaultEndpoint implements Serializable {
/**
* Create a {@link VaultEndpoint} given a {@link URI}.
*
- * @param uri must contain hostname, port and scheme, must not be empty or {@literal null}.
+ * @param uri must contain hostname, port and scheme, must not be empty or
+ * {@literal null}.
* @return a new {@link VaultEndpoint}.
*/
public static VaultEndpoint from(URI uri) {
@@ -117,7 +119,8 @@ public class VaultEndpoint implements Serializable {
*/
public void setPort(int port) {
- Assert.isTrue(port >= 1 && port <= 65535, "Port must be a valid port in the range between 1 and 65535");
+ Assert.isTrue(port >= 1 && port <= 65535,
+ "Port must be a valid port in the range between 1 and 65535");
this.port = port;
}
@@ -134,7 +137,8 @@ public class VaultEndpoint implements Serializable {
*/
public void setScheme(String scheme) {
- Assert.isTrue("http".equals(scheme) || "https".equals(scheme), "Scheme must be http or https");
+ Assert.isTrue("http".equals(scheme) || "https".equals(scheme),
+ "Scheme must be http or https");
this.scheme = scheme;
}
@@ -159,7 +163,8 @@ public class VaultEndpoint implements Serializable {
Assert.hasText(path, "Path must not be empty");
- return String.format("%s://%s:%s/%s/%s", getScheme(), getHost(), getPort(), API_VERSION, path);
+ return String.format("%s://%s:%s/%s/%s", getScheme(), getHost(), getPort(),
+ API_VERSION, path);
}
@Override
diff --git a/spring-vault-core/src/main/java/org/springframework/vault/client/VaultException.java b/spring-vault-core/src/main/java/org/springframework/vault/client/VaultException.java
index 05b03ee7..b869ad9c 100644
--- a/spring-vault-core/src/main/java/org/springframework/vault/client/VaultException.java
+++ b/spring-vault-core/src/main/java/org/springframework/vault/client/VaultException.java
@@ -35,7 +35,8 @@ public class VaultException extends NestedRuntimeException {
}
/**
- * Creates a {@code NestedRuntimeException} with the specified detail message and nested exception.
+ * Creates a {@code NestedRuntimeException} with the specified detail message and
+ * nested exception.
*
* @param msg the detail message
* @param cause the nested exception
diff --git a/spring-vault-core/src/main/java/org/springframework/vault/client/VaultResponseEntity.java b/spring-vault-core/src/main/java/org/springframework/vault/client/VaultResponseEntity.java
index 94670f58..b31a0d3c 100644
--- a/spring-vault-core/src/main/java/org/springframework/vault/client/VaultResponseEntity.java
+++ b/spring-vault-core/src/main/java/org/springframework/vault/client/VaultResponseEntity.java
@@ -20,8 +20,9 @@ import java.net.URI;
import org.springframework.http.HttpStatus;
/**
- * Encapsulates the client response used in {@link VaultAccessor}. Consists of the body, status code the location and a
- * message. The {@code body} is empty for all non-successful results. This class is immutable.
+ * Encapsulates the client response used in {@link VaultAccessor}. Consists of the body,
+ * status code the location and a message. The {@code body} is empty for all
+ * non-successful results. This class is immutable.
*
* @author Mark Paluch
*/
@@ -78,8 +79,8 @@ public class VaultResponseEntity {
}
/**
- * @return the message of this entity. {@literal null} for successful responses but provided usually when the response
- * yielded an error.
+ * @return the message of this entity. {@literal null} for successful responses but
+ * provided usually when the response yielded an error.
*/
public String getMessage() {
return message;
diff --git a/spring-vault-core/src/main/java/org/springframework/vault/config/AbstractVaultConfiguration.java b/spring-vault-core/src/main/java/org/springframework/vault/config/AbstractVaultConfiguration.java
index 25122712..ba7b0c48 100644
--- a/spring-vault-core/src/main/java/org/springframework/vault/config/AbstractVaultConfiguration.java
+++ b/spring-vault-core/src/main/java/org/springframework/vault/config/AbstractVaultConfiguration.java
@@ -44,12 +44,14 @@ import org.springframework.vault.support.SslConfiguration;
public abstract class AbstractVaultConfiguration {
/**
- * @return Vault endpoint coordinates for HTTP/HTTPS communication, must not be {@literal null}.
+ * @return Vault endpoint coordinates for HTTP/HTTPS communication, must not be
+ * {@literal null}.
*/
public abstract VaultEndpoint vaultEndpoint();
/**
- * Annotate with {@link Bean} in case you want to expose a {@link ClientAuthentication} instance to the
+ * Annotate with {@link Bean} in case you want to expose a
+ * {@link ClientAuthentication} instance to the
* {@link org.springframework.context.ApplicationContext}.
*
* @return the {@link ClientAuthentication} to use. Must not be {@literal null}.
@@ -57,10 +59,11 @@ public abstract class AbstractVaultConfiguration {
public abstract ClientAuthentication clientAuthentication();
/**
- * Create a {@link AsyncTaskExecutor} used by {@link LifecycleAwareSessionManager}. Annotate with {@link Bean} in case
- * you want to expose a {@link AsyncTaskExecutor} instance to the
- * {@link org.springframework.context.ApplicationContext}. This might be useful to supply managed executor instances
- * or {@link AsyncTaskExecutor}s using a queue/pooled threads.
+ * Create a {@link AsyncTaskExecutor} used by {@link LifecycleAwareSessionManager}.
+ * Annotate with {@link Bean} in case you want to expose a {@link AsyncTaskExecutor}
+ * instance to the {@link org.springframework.context.ApplicationContext}. This might
+ * be useful to supply managed executor instances or {@link AsyncTaskExecutor}s using
+ * a queue/pooled threads.
*
* @return the {@link AsyncTaskExecutor} to use. Must not be {@literal null}.
* @see AsyncTaskExecutor
@@ -70,8 +73,9 @@ public abstract class AbstractVaultConfiguration {
}
/**
- * Construct a {@link LifecycleAwareSessionManager} using {@link #clientAuthentication()} and {@link #vaultClient()}.
- * This {@link SessionManager} uses {@link #asyncTaskExecutor()}.
+ * Construct a {@link LifecycleAwareSessionManager} using
+ * {@link #clientAuthentication()} and {@link #vaultClient()}. This
+ * {@link SessionManager} uses {@link #asyncTaskExecutor()}.
*
* @return the {@link SessionManager} for Vault session management.
* @see SessionManager
@@ -86,7 +90,8 @@ public abstract class AbstractVaultConfiguration {
ClientAuthentication clientAuthentication = clientAuthentication();
Assert.notNull(clientAuthentication, "ClientAuthentication must not be null");
- return new LifecycleAwareSessionManager(clientAuthentication, asyncTaskExecutor(), vaultClient());
+ return new LifecycleAwareSessionManager(clientAuthentication,
+ asyncTaskExecutor(), vaultClient());
}
/**
@@ -107,18 +112,21 @@ public abstract class AbstractVaultConfiguration {
}
/**
- * Create a {@link ClientFactoryWrapper} containing a {@link ClientHttpRequestFactory}.
- * {@link ClientHttpRequestFactory} is not exposed as root bean because {@link ClientHttpRequestFactory} is configured
- * with {@link ClientOptions} and {@link SslConfiguration} which are not necessarily applicable for the whole
+ * Create a {@link ClientFactoryWrapper} containing a {@link ClientHttpRequestFactory}
+ * . {@link ClientHttpRequestFactory} is not exposed as root bean because
+ * {@link ClientHttpRequestFactory} is configured with {@link ClientOptions} and
+ * {@link SslConfiguration} which are not necessarily applicable for the whole
* application.
*
- * @return the {@link ClientFactoryWrapper} to wrap a {@link ClientHttpRequestFactory} instance.
+ * @return the {@link ClientFactoryWrapper} to wrap a {@link ClientHttpRequestFactory}
+ * instance.
* @see #clientOptions()
* @see #sslConfiguration()
*/
@Bean
public ClientFactoryWrapper clientHttpRequestFactoryWrapper() {
- return new ClientFactoryWrapper(ClientHttpRequestFactoryFactory.create(clientOptions(), sslConfiguration()));
+ return new ClientFactoryWrapper(ClientHttpRequestFactoryFactory.create(
+ clientOptions(), sslConfiguration()));
}
/**
@@ -128,12 +136,14 @@ public abstract class AbstractVaultConfiguration {
*/
@Bean
public VaultClient vaultClient() {
- return new VaultClient(clientHttpRequestFactoryWrapper().getClientHttpRequestFactory(), vaultEndpoint());
+ return new VaultClient(clientHttpRequestFactoryWrapper()
+ .getClientHttpRequestFactory(), vaultEndpoint());
}
/**
- * Creates the {@link VaultClientFactory} to be used with {@link VaultTemplate}. Uses by default
- * {@link DefaultVaultClientFactory} with the configured {@link #vaultClient()} instance.
+ * Creates the {@link VaultClientFactory} to be used with {@link VaultTemplate}. Uses
+ * by default {@link DefaultVaultClientFactory} with the configured
+ * {@link #vaultClient()} instance.
*
* @return the {@link VaultClientFactory}.
*/
diff --git a/spring-vault-core/src/main/java/org/springframework/vault/config/ClientHttpRequestFactoryFactory.java b/spring-vault-core/src/main/java/org/springframework/vault/config/ClientHttpRequestFactoryFactory.java
index e1f2e5e1..a66232fc 100644
--- a/spring-vault-core/src/main/java/org/springframework/vault/config/ClientHttpRequestFactoryFactory.java
+++ b/spring-vault-core/src/main/java/org/springframework/vault/config/ClientHttpRequestFactoryFactory.java
@@ -28,12 +28,16 @@ import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
+import com.squareup.okhttp.OkHttpClient;
+import io.netty.handler.ssl.SslContextBuilder;
+import io.netty.handler.ssl.SslProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+
import org.springframework.core.io.Resource;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
@@ -43,42 +47,44 @@ import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
-
-import com.squareup.okhttp.OkHttpClient;
-
-import io.netty.handler.ssl.SslContextBuilder;
-import io.netty.handler.ssl.SslProvider;
import org.springframework.vault.support.ClientOptions;
import org.springframework.vault.support.SslConfiguration;
/**
- * Factory for {@link ClientHttpRequestFactory} that supports Apache HTTP Components, OkHttp, Netty and the JDK HTTP
- * client (in that order). This factory configures a {@link ClientHttpRequestFactory} depending on the available
- * dependencies.
+ * Factory for {@link ClientHttpRequestFactory} that supports Apache HTTP Components,
+ * OkHttp, Netty and the JDK HTTP client (in that order). This factory configures a
+ * {@link ClientHttpRequestFactory} depending on the available dependencies.
*
* @author Mark Paluch
*/
public class ClientHttpRequestFactoryFactory {
- private static final Logger logger = LoggerFactory.getLogger(ClientHttpRequestFactoryFactory.class);
+ private static final Logger logger = LoggerFactory
+ .getLogger(ClientHttpRequestFactoryFactory.class);
- private static final boolean HTTP_COMPONENTS_PRESENT = ClassUtils.isPresent("org.apache.http.client.HttpClient",
+ private static final boolean HTTP_COMPONENTS_PRESENT = ClassUtils.isPresent(
+ "org.apache.http.client.HttpClient",
ClientHttpRequestFactoryFactory.class.getClassLoader());
- private static final boolean OKHTTP_PRESENT = ClassUtils.isPresent("com.squareup.okhttp.OkHttpClient",
+ private static final boolean OKHTTP_PRESENT = ClassUtils.isPresent(
+ "com.squareup.okhttp.OkHttpClient",
ClientHttpRequestFactoryFactory.class.getClassLoader());
- private static final boolean NETTY_PRESENT = ClassUtils.isPresent("io.netty.channel.nio.NioEventLoopGroup",
+ private static final boolean NETTY_PRESENT = ClassUtils.isPresent(
+ "io.netty.channel.nio.NioEventLoopGroup",
ClientHttpRequestFactoryFactory.class.getClassLoader());
/**
- * Creates a {@link ClientHttpRequestFactory} for the given {@link ClientOptions} and {@link SslConfiguration}.
+ * Creates a {@link ClientHttpRequestFactory} for the given {@link ClientOptions} and
+ * {@link SslConfiguration}.
*
* @param options must not be {@literal null}
* @param sslConfiguration must not be {@literal null}
- * @return a new {@link ClientHttpRequestFactory}. Lifecycle beans must be initialized after obtaining.
+ * @return a new {@link ClientHttpRequestFactory}. Lifecycle beans must be initialized
+ * after obtaining.
*/
- public static ClientHttpRequestFactory create(ClientOptions options, SslConfiguration sslConfiguration) {
+ public static ClientHttpRequestFactory create(ClientOptions options,
+ SslConfiguration sslConfiguration) {
Assert.notNull(options, "ClientOptions must not be null");
Assert.notNull(sslConfiguration, "SslConfiguration must not be null");
@@ -97,9 +103,11 @@ public class ClientHttpRequestFactoryFactory {
return Netty.usingNetty(options, sslConfiguration);
}
- } catch (GeneralSecurityException e) {
+ }
+ catch (GeneralSecurityException e) {
throw new IllegalStateException(e);
- } catch (IOException e) {
+ }
+ catch (IOException e) {
throw new IllegalStateException(e);
}
@@ -114,14 +122,13 @@ public class ClientHttpRequestFactoryFactory {
private static SSLContext getSSLContext(SslConfiguration sslConfiguration)
throws GeneralSecurityException, IOException {
- KeyManager[] keyManagers = sslConfiguration.getKeyStore() != null
- ? createKeyManagerFactory(sslConfiguration.getKeyStore(), sslConfiguration.getKeyStorePassword())
- .getKeyManagers()
- : null;
+ KeyManager[] keyManagers = sslConfiguration.getKeyStore() != null ? createKeyManagerFactory(
+ sslConfiguration.getKeyStore(), sslConfiguration.getKeyStorePassword())
+ .getKeyManagers() : null;
- TrustManager[] trustManagers = sslConfiguration.getTrustStore() != null
- ? createTrustManagerFactory(sslConfiguration.getTrustStore(), sslConfiguration.getTrustStorePassword())
- .getTrustManagers()
+ TrustManager[] trustManagers = sslConfiguration.getTrustStore() != null ? createTrustManagerFactory(
+ sslConfiguration.getTrustStore(),
+ sslConfiguration.getTrustStorePassword()).getTrustManagers()
: null;
SSLContext sslContext = SSLContext.getInstance("TLS");
@@ -130,21 +137,24 @@ public class ClientHttpRequestFactoryFactory {
return sslContext;
}
- private static KeyManagerFactory createKeyManagerFactory(Resource keystoreFile, String storePassword)
- throws GeneralSecurityException, IOException {
+ private static KeyManagerFactory createKeyManagerFactory(Resource keystoreFile,
+ String storePassword) throws GeneralSecurityException, IOException {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
loadKeyStore(keystoreFile, storePassword, keyStore);
- KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
- keyManagerFactory.init(keyStore, StringUtils.hasText(storePassword) ? storePassword.toCharArray() : new char[0]);
+ KeyManagerFactory keyManagerFactory = KeyManagerFactory
+ .getInstance(KeyManagerFactory.getDefaultAlgorithm());
+ keyManagerFactory.init(keyStore,
+ StringUtils.hasText(storePassword) ? storePassword.toCharArray()
+ : new char[0]);
return keyManagerFactory;
}
- private static TrustManagerFactory createTrustManagerFactory(Resource trustFile, String storePassword)
- throws GeneralSecurityException, IOException {
+ private static TrustManagerFactory createTrustManagerFactory(Resource trustFile,
+ String storePassword) throws GeneralSecurityException, IOException {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
@@ -157,14 +167,18 @@ public class ClientHttpRequestFactoryFactory {
return trustManagerFactory;
}
- private static void loadKeyStore(Resource keyStoreResource, String storePassword, KeyStore keyStore)
- throws IOException, NoSuchAlgorithmException, CertificateException {
+ private static void loadKeyStore(Resource keyStoreResource, String storePassword,
+ KeyStore keyStore) throws IOException, NoSuchAlgorithmException,
+ CertificateException {
InputStream inputStream = null;
try {
inputStream = keyStoreResource.getInputStream();
- keyStore.load(inputStream, StringUtils.hasText(storePassword) ? storePassword.toCharArray() : null);
- } finally {
+ keyStore.load(inputStream,
+ StringUtils.hasText(storePassword) ? storePassword.toCharArray()
+ : null);
+ }
+ finally {
if (inputStream != null) {
inputStream.close();
}
@@ -172,7 +186,8 @@ public class ClientHttpRequestFactoryFactory {
}
private static boolean hasSslConfiguration(SslConfiguration sslConfiguration) {
- return sslConfiguration.getTrustStore() != null || sslConfiguration.getKeyStore() != null;
+ return sslConfiguration.getTrustStore() != null
+ || sslConfiguration.getKeyStore() != null;
}
/**
@@ -182,15 +197,17 @@ public class ClientHttpRequestFactoryFactory {
*/
static class HttpComponents {
- static ClientHttpRequestFactory usingHttpComponents(ClientOptions options, SslConfiguration sslConfiguration)
- throws GeneralSecurityException, IOException {
+ static ClientHttpRequestFactory usingHttpComponents(ClientOptions options,
+ SslConfiguration sslConfiguration) throws GeneralSecurityException,
+ IOException {
HttpClientBuilder httpClientBuilder = HttpClients.custom();
if (hasSslConfiguration(sslConfiguration)) {
SSLContext sslContext = getSSLContext(sslConfiguration);
- SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);
+ SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
+ sslContext);
httpClientBuilder.setSSLSocketFactory(sslSocketFactory);
httpClientBuilder.setSSLContext(sslContext);
}
@@ -214,12 +231,14 @@ public class ClientHttpRequestFactoryFactory {
*/
static class OkHttp {
- static ClientHttpRequestFactory usingOkHttp(ClientOptions options, SslConfiguration sslConfiguration)
- throws GeneralSecurityException, IOException {
+ static ClientHttpRequestFactory usingOkHttp(ClientOptions options,
+ SslConfiguration sslConfiguration) throws GeneralSecurityException,
+ IOException {
final OkHttpClient okHttpClient = new OkHttpClient();
- OkHttpClientHttpRequestFactory requestFactory = new OkHttpClientHttpRequestFactory(okHttpClient) {
+ OkHttpClientHttpRequestFactory requestFactory = new OkHttpClientHttpRequestFactory(
+ okHttpClient) {
@Override
public void destroy() throws IOException {
@@ -233,7 +252,8 @@ public class ClientHttpRequestFactoryFactory {
};
if (hasSslConfiguration(sslConfiguration)) {
- okHttpClient.setSslSocketFactory(getSSLContext(sslConfiguration).getSocketFactory());
+ okHttpClient.setSslSocketFactory(getSSLContext(sslConfiguration)
+ .getSocketFactory());
}
requestFactory.setConnectTimeout(options.getConnectionTimeout());
@@ -250,8 +270,9 @@ public class ClientHttpRequestFactoryFactory {
*/
static class Netty {
- static ClientHttpRequestFactory usingNetty(ClientOptions options, SslConfiguration sslConfiguration)
- throws GeneralSecurityException, IOException {
+ static ClientHttpRequestFactory usingNetty(ClientOptions options,
+ SslConfiguration sslConfiguration) throws GeneralSecurityException,
+ IOException {
final Netty4ClientHttpRequestFactory requestFactory = new Netty4ClientHttpRequestFactory();
@@ -261,16 +282,19 @@ public class ClientHttpRequestFactoryFactory {
.forClient();
if (sslConfiguration.getTrustStore() != null) {
- sslContextBuilder.trustManager(
- createTrustManagerFactory(sslConfiguration.getTrustStore(), sslConfiguration.getTrustStorePassword()));
+ sslContextBuilder.trustManager(createTrustManagerFactory(
+ sslConfiguration.getTrustStore(),
+ sslConfiguration.getTrustStorePassword()));
}
if (sslConfiguration.getKeyStore() != null) {
- sslContextBuilder.keyManager(
- createKeyManagerFactory(sslConfiguration.getKeyStore(), sslConfiguration.getKeyStorePassword()));
+ sslContextBuilder.keyManager(createKeyManagerFactory(
+ sslConfiguration.getKeyStore(),
+ sslConfiguration.getKeyStorePassword()));
}
- requestFactory.setSslContext(sslContextBuilder.sslProvider(SslProvider.JDK).build());
+ requestFactory.setSslContext(sslContextBuilder.sslProvider(
+ SslProvider.JDK).build());
}
requestFactory.setConnectTimeout(options.getConnectionTimeout());
diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/DefaultVaultClientFactory.java b/spring-vault-core/src/main/java/org/springframework/vault/core/DefaultVaultClientFactory.java
index 5e150087..e2f8de50 100644
--- a/spring-vault-core/src/main/java/org/springframework/vault/core/DefaultVaultClientFactory.java
+++ b/spring-vault-core/src/main/java/org/springframework/vault/core/DefaultVaultClientFactory.java
@@ -21,7 +21,8 @@ import org.springframework.vault.client.VaultEndpoint;
import org.springframework.web.client.RestTemplate;
/**
- * Default implementation of {@link VaultClientFactory}. Returns the provided {@link VaultClient}.
+ * Default implementation of {@link VaultClientFactory}. Returns the provided
+ * {@link VaultClient}.
*
* @author Mark Paluch
*/
@@ -30,7 +31,8 @@ public class DefaultVaultClientFactory implements VaultClientFactory {
private final VaultClient vaultClient;
/**
- * Creates a new {@link DefaultVaultClientFactory} returning always the same {@link VaultClient}.
+ * Creates a new {@link DefaultVaultClientFactory} returning always the same
+ * {@link VaultClient}.
*
* @param vaultClient must not be {@literal null}.
*/
@@ -42,8 +44,8 @@ public class DefaultVaultClientFactory implements VaultClientFactory {
}
/**
- * Creates a new {@link DefaultVaultClientFactory} using a default {@link VaultClient} and {@link VaultEndpoint}. Will
- * use Vault at {@code https://localhost:8200} .
+ * Creates a new {@link DefaultVaultClientFactory} using a default {@link VaultClient}
+ * and {@link VaultEndpoint}. Will use Vault at {@code https://localhost:8200} .
*
* @see VaultClient
* @see VaultEndpoint
diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultOperations.java b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultOperations.java
index 052a716e..404209d4 100644
--- a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultOperations.java
+++ b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultOperations.java
@@ -21,20 +21,22 @@ import java.util.Map;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
-import org.springframework.vault.client.VaultAccessor.RestTemplateCallback;
import org.springframework.vault.client.VaultClient;
import org.springframework.vault.client.VaultResponseEntity;
+import org.springframework.vault.client.VaultAccessor.RestTemplateCallback;
import org.springframework.vault.support.VaultResponse;
import org.springframework.vault.support.VaultResponseSupport;
/**
- * Interface that specifies a basic set of Vault operations, implemented by {@link VaultTemplate}. This is the main
- * entry point to interact with Vault in an authenticated and unauthenticated context with configured
- * {@link VaultClient} instances.
+ * Interface that specifies a basic set of Vault operations, implemented by
+ * {@link VaultTemplate}. This is the main entry point to interact with Vault in an
+ * authenticated and unauthenticated context with configured {@link VaultClient}
+ * instances.
*
- * {@link VaultOperations} resolves {@link VaultClient} instances and allows execution of callback methods on various
- * levels. Callbacks can execute requests within a {@link #doWithVault(SessionCallback) session}, the
- * {@link #doWithVault(ClientCallback) client (without requiring a session)} and a
+ * {@link VaultOperations} resolves {@link VaultClient} instances and allows execution of
+ * callback methods on various levels. Callbacks can execute requests within a
+ * {@link #doWithVault(SessionCallback) session}, the {@link #doWithVault(ClientCallback)
+ * client (without requiring a session)} and a
* {@link #doWithRestTemplate(String, Map, RestTemplateCallback) low-level}
* {@link org.springframework.web.client.RestTemplate} level.
*
@@ -65,7 +67,8 @@ public interface VaultOperations {
VaultTransitOperations opsForTransit();
/**
- * Returns {@link VaultTransitOperations} if the transit backend is mounted on a different path than {@code transit}.
+ * Returns {@link VaultTransitOperations} if the transit backend is mounted on a
+ * different path than {@code transit}.
*
* @param path the mount path
* @return the operations interface to interact with the Vault transit backend.
@@ -78,7 +81,8 @@ public interface VaultOperations {
VaultPkiOperations opsForPki();
/**
- * Returns {@link VaultPkiOperations} if the PKI backend is mounted on a different path than {@code pki}.
+ * Returns {@link VaultPkiOperations} if the PKI backend is mounted on a different
+ * path than {@code pki}.
*
* @param path the mount path
* @return the operations interface to interact with the Vault PKI backend.
@@ -86,8 +90,8 @@ public interface VaultOperations {
VaultPkiOperations opsForPki(String path);
/**
- * Read from a secret backend. Reading data using this method is suitable for secret backends that do not require a
- * request body.
+ * Read from a secret backend. Reading data using this method is suitable for secret
+ * backends that do not require a request body.
*
* @param path must not be {@literal null}.
* @return the data. May be {@literal null} if the path does not exist.
@@ -95,8 +99,8 @@ public interface VaultOperations {
VaultResponse read(String path);
/**
- * Read from a secret backend. Reading data using this method is suitable for secret backends that do not require a
- * request body.
+ * Read from a secret backend. Reading data using this method is suitable for secret
+ * backends that do not require a request body.
*
* @param path must not be {@literal null}.
* @param responseType must not be {@literal null}.
@@ -129,8 +133,8 @@ public interface VaultOperations {
void delete(String path);
/**
- * Executes a Vault {@link ClientCallback}. Allows to interact with Vault using {@link VaultClient} without requiring
- * a session.
+ * Executes a Vault {@link ClientCallback}. Allows to interact with Vault using
+ * {@link VaultClient} without requiring a session.
*
* @param clientCallback the request.
* @return the {@link ClientCallback} return value.
@@ -138,7 +142,8 @@ public interface VaultOperations {
T doWithVault(ClientCallback clientCallback);
/**
- * Executes a Vault {@link SessionCallback}. Allows to interact with Vault in an authenticated session.
+ * Executes a Vault {@link SessionCallback}. Allows to interact with Vault in an
+ * authenticated session.
*
* @param sessionCallback the request.
* @return the {@link SessionCallback} return value.
@@ -146,15 +151,19 @@ public interface VaultOperations {
T doWithVault(SessionCallback sessionCallback);
/**
- * Executes {@link RestTemplateCallback}. Expands the {@code pathTemplate} to an {@link java.net.URI} and allows
- * low-level interaction with the underlying {@link org.springframework.web.client.RestTemplate}.
+ * Executes {@link RestTemplateCallback}. Expands the {@code pathTemplate} to an
+ * {@link java.net.URI} and allows low-level interaction with the underlying
+ * {@link org.springframework.web.client.RestTemplate}.
*
- * @param pathTemplate the path of the resource, e.g. {@code transit/{key}/foo}, must not be empty or {@literal null}.
- * @param variables the variables for expansion of the {@code pathTemplate}, must not be {@literal null}.
+ * @param pathTemplate the path of the resource, e.g. {@code transit/ key}/foo}, must
+ * not be empty or {@literal null}.
+ * @param variables the variables for expansion of the {@code pathTemplate}, must not
+ * be {@literal null}.
* @param callback the request callback.
* @return the {@link RestTemplateCallback} return value.
*/
- T doWithRestTemplate(String pathTemplate, Map variables, RestTemplateCallback callback);
+ T doWithRestTemplate(String pathTemplate, Map variables,
+ RestTemplateCallback callback);
/**
* A callback for executing arbitrary operations on the {@link VaultClient}.
@@ -189,25 +198,28 @@ public interface VaultOperations {
}
/**
- * An authenticated Vault session. {@link VaultSession} exposes request accessor methods to be executed in an
- * authenticated context.
+ * An authenticated Vault session. {@link VaultSession} exposes request accessor
+ * methods to be executed in an authenticated context.
*
* @author Mark Paluch
*/
public interface VaultSession {
/**
- * Retrieve a resource by GETting from the path, and returns the response as {@link VaultResponseEntity}.
+ * Retrieve a resource by GETting from the path, and returns the response as
+ * {@link VaultResponseEntity}.
*
* @param path the path.
* @param responseType the type of the return value
* @return the response as entity.
* @see VaultResponseEntity
*/
- VaultResponseEntity getForEntity(String path, Class responseType);
+ VaultResponseEntity getForEntity(String path,
+ Class responseType);
/**
- * Issue a POST request using the given object to the path, and returns the response as {@link VaultResponseEntity}.
+ * Issue a POST request using the given object to the path, and returns the
+ * response as {@link VaultResponseEntity}.
*
* @param path the path.
* @param request the Object to be POSTed, may be {@code null}.
@@ -215,11 +227,12 @@ public interface VaultOperations {
* @return the response as entity.
* @see VaultResponseEntity
*/
- VaultResponseEntity postForEntity(String path, Object request, Class responseType);
+ VaultResponseEntity postForEntity(String path,
+ Object request, Class responseType);
/**
- * Create a new resource by PUTting the given object to the path, and returns the response as
- * {@link VaultResponseEntity}.
+ * Create a new resource by PUTting the given object to the path, and returns the
+ * response as {@link VaultResponseEntity}.
*
* @param path the path.
* @param request the Object to be PUT.
@@ -227,53 +240,62 @@ public interface VaultOperations {
* @return the response as entity.
* @see VaultResponseEntity
*/
- VaultResponseEntity putForEntity(String path, Object request, Class responseType);
+ VaultResponseEntity putForEntity(String path, Object request,
+ Class responseType);
/**
- * Delete a resource by DELETEing from the path, and returns the response as {@link VaultResponseEntity}.
+ * Delete a resource by DELETEing from the path, and returns the response as
+ * {@link VaultResponseEntity}.
*
* @param path the path.
* @param responseType the type of the return value
* @return the response as entity.
* @see VaultResponseEntity
*/
- VaultResponseEntity deleteForEntity(String path, Class responseType);
+ VaultResponseEntity deleteForEntity(String path,
+ Class responseType);
/**
- * Execute the HTTP method to the given URI template, writing the given request entity to the request, and returns
- * the response as {@link VaultResponseEntity}.
+ * Execute the HTTP method to the given URI template, writing the given request
+ * entity to the request, and returns the response as {@link VaultResponseEntity}.
*
* URI Template variables are using the given URI variables, if any.
*
* @param pathTemplate the path template.
* @param method the HTTP method (GET, POST, etc).
- * @param requestEntity the entity (headers and/or body) to write to the request, may be {@code null}.
+ * @param requestEntity the entity (headers and/or body) to write to the request,
+ * may be {@code null}.
* @param responseType the type of the return value.
* @param uriVariables the variables to expand in the template.
* @return the response as entity.
*/
- VaultResponseEntity exchange(String pathTemplate, HttpMethod method,
- HttpEntity> requestEntity, Class responseType, Map uriVariables);
+ VaultResponseEntity exchange(String pathTemplate,
+ HttpMethod method, HttpEntity> requestEntity, Class responseType,
+ Map uriVariables);
/**
- * Execute the HTTP method to the given path template, writing the given request entity to the request, and returns
- * the response as {@link VaultResponseEntity}. The given {@link ParameterizedTypeReference} is used to pass generic
- * type information:
+ * Execute the HTTP method to the given path template, writing the given request
+ * entity to the request, and returns the response as {@link VaultResponseEntity}.
+ * The given {@link ParameterizedTypeReference} is used to pass generic type
+ * information:
*
*
- * ParameterizedTypeReference<List<MyBean>> myBean = new ParameterizedTypeReference<List<MyBean>>() {};
- * ResponseEntity<List<MyBean>> response = session.exchange("http://example.com", HttpMethod.GET, null, myBean,
- * null);
+ * ParameterizedTypeReference<List<MyBean>> myBean = new ParameterizedTypeReference<List<MyBean>>() {
+ * };
+ * ResponseEntity<List<MyBean>> response = session.exchange("http://example.com",
+ * HttpMethod.GET, null, myBean, null);
*
*
* @param pathTemplate the path template.
* @param method the HTTP method (GET, POST, etc).
- * @param requestEntity the entity (headers and/or body) to write to the request, may be {@code null}.
+ * @param requestEntity the entity (headers and/or body) to write to the request,
+ * may be {@code null}.
* @param responseType the type of the return value.
* @param uriVariables the variables to expand in the template.
* @return the response as entity.
*/
- VaultResponseEntity exchange(String pathTemplate, HttpMethod method,
- HttpEntity> requestEntity, ParameterizedTypeReference responseType, Map uriVariables);
+ VaultResponseEntity exchange(String pathTemplate,
+ HttpMethod method, HttpEntity> requestEntity,
+ ParameterizedTypeReference responseType, Map uriVariables);
}
}
diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultPkiOperations.java b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultPkiOperations.java
index bff137f5..70cea782 100644
--- a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultPkiOperations.java
+++ b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultPkiOperations.java
@@ -23,27 +23,33 @@ import org.springframework.vault.support.VaultCertificateResponse;
/**
* Interface that specifies PKI backend-related operations.
*
- * The PKI secret backend for Vault generates X.509 certificates dynamically based on configured roles. This means
- * services can get certificates needed for both client and server authentication without going through the usual manual
- * process of generating a private key and CSR, submitting to a CA, and waiting for a verification and signing process
- * to complete. Vault's built-in authentication and authorization mechanisms provide the verification functionality.
+ * The PKI secret backend for Vault generates X.509 certificates dynamically based on
+ * configured roles. This means services can get certificates needed for both client and
+ * server authentication without going through the usual manual process of generating a
+ * private key and CSR, submitting to a CA, and waiting for a verification and signing
+ * process to complete. Vault's built-in authentication and authorization mechanisms
+ * provide the verification functionality.
*
* @author Mark Paluch
* @see https://www.vaultproject.io/docs/secrets/pki/index.html
+ * "https://www.vaultproject.io/docs/secrets/pki/index.html">https://www.vaultproject.io/docs/secrets/pki/index.html
*/
public interface VaultPkiOperations {
/**
- * Requests a certificate bundle (private key and certificate) from Vault's PKI backend given a {@code roleName} and
- * {@link VaultCertificateRequest}. The issuing CA certificate is returned as well, so that only the root CA need be
- * in a client's trust store. Certificates use DER format and are base64 encoded.
+ * Requests a certificate bundle (private key and certificate) from Vault's PKI
+ * backend given a {@code roleName} and {@link VaultCertificateRequest}. The issuing
+ * CA certificate is returned as well, so that only the root CA need be in a client's
+ * trust store. Certificates use DER format and are base64 encoded.
*
* @param roleName must not be empty or {@literal null}.
* @param certificateRequest must not be {@literal null}.
- * @return the {@link VaultCertificateResponse} containing a {@link CertificateBundle}.
- * @see POST /pki/issue/[role name]
+ * @return the {@link VaultCertificateResponse} containing a {@link CertificateBundle}
+ * .
+ * @see POST
+ * /pki/issue/[role name]
*/
- VaultCertificateResponse issueCertificate(String roleName, VaultCertificateRequest certificateRequest)
- throws VaultException;
+ VaultCertificateResponse issueCertificate(String roleName,
+ VaultCertificateRequest certificateRequest) throws VaultException;
}
diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultPkiTemplate.java b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultPkiTemplate.java
index 154b0291..95639540 100644
--- a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultPkiTemplate.java
+++ b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultPkiTemplate.java
@@ -37,7 +37,8 @@ public class VaultPkiTemplate implements VaultPkiOperations {
private final String path;
/**
- * Create a new {@link VaultPkiTemplate} given {@link VaultPkiOperations} and the mount {@code path}.
+ * 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}.
@@ -52,8 +53,8 @@ public class VaultPkiTemplate implements VaultPkiOperations {
}
@Override
- public VaultCertificateResponse issueCertificate(final String roleName, VaultCertificateRequest certificateRequest)
- throws VaultException {
+ public VaultCertificateResponse issueCertificate(final String roleName,
+ VaultCertificateRequest certificateRequest) throws VaultException {
Assert.hasText(roleName, "Role name must not be empty");
Assert.notNull(certificateRequest, "Certificate request must not be null");
@@ -62,11 +63,17 @@ public class VaultPkiTemplate implements VaultPkiOperations {
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) {
@@ -82,9 +89,11 @@ public class VaultPkiTemplate implements VaultPkiOperations {
VaultResponseEntity entity = vaultOperations
.doWithVault(new VaultOperations.SessionCallback>() {
@Override
- public VaultResponseEntity doWithVault(VaultOperations.VaultSession session) {
+ public VaultResponseEntity doWithVault(
+ VaultOperations.VaultSession session) {
- return session.postForEntity(String.format("%s/issue/%s", path, roleName), request,
+ return session.postForEntity(
+ String.format("%s/issue/%s", path, roleName), request,
VaultCertificateResponse.class);
}
});
@@ -99,9 +108,11 @@ public class VaultPkiTemplate implements VaultPkiOperations {
private static String buildExceptionMessage(VaultResponseEntity> response) {
if (StringUtils.hasText(response.getMessage())) {
- return String.format("Status %s URI %s: %s", response.getStatusCode(), response.getUri(), response.getMessage());
+ return String.format("Status %s URI %s: %s", response.getStatusCode(),
+ response.getUri(), response.getMessage());
}
- return String.format("Status %s URI %s", response.getStatusCode(), response.getUri());
+ return String.format("Status %s URI %s", response.getStatusCode(),
+ response.getUri());
}
}
diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultSysOperations.java b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultSysOperations.java
index 2d48ebbe..69b60411 100644
--- a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultSysOperations.java
+++ b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultSysOperations.java
@@ -33,7 +33,8 @@ public interface VaultSysOperations {
/**
* @return {@literal true} if Vault is initialized.
- * @see GET /sys/init
+ * @see GET
+ * /sys/init
*/
boolean isInitialized() throws VaultException;
@@ -42,14 +43,17 @@ public interface VaultSysOperations {
*
* @param vaultInitializationRequest must not be {@literal null}.
* @return the {@link VaultInitializationResponse}.
- * @see PUT /sys/init
+ * @see PUT
+ * /sys/init
*/
- VaultInitializationResponse initialize(VaultInitializationRequest vaultInitializationRequest) throws VaultException;
+ VaultInitializationResponse initialize(
+ VaultInitializationRequest vaultInitializationRequest) throws VaultException;
/**
* Seal vault.
*
- * @see PUT /sys/seal
+ * @see PUT
+ * /sys/seal
*/
void seal() throws VaultException;
@@ -58,13 +62,15 @@ public interface VaultSysOperations {
*
* @param keyShare must not be empty and not {@literal null}.
* @return the {@link VaultUnsealStatus}.
- * @see PUT /sys/unseal
+ * @see PUT
+ * /sys/unseal
*/
VaultUnsealStatus unseal(String keyShare) throws VaultException;
/**
* @return the {@link VaultUnsealStatus}.
- * @see GET /sys/unseal
+ * @see GET
+ * /sys/unseal
*/
VaultUnsealStatus getUnsealStatus() throws VaultException;
@@ -73,13 +79,15 @@ public interface VaultSysOperations {
*
* @param path must not be empty or {@literal null}.
* @param vaultMount must not be {@literal null}.
- * @see POST /sys/mounts/{mount}
+ * @see POST
+ * /sys/mounts/{mount}
*/
void mount(String path, VaultMount vaultMount) throws VaultException;
/**
* @return {@link Map} of all secret backend {@link VaultMount mounts}.
- * @see GET /sys/mounts/
+ * @see GET
+ * /sys/mounts/
*/
Map getMounts() throws VaultException;
@@ -87,7 +95,8 @@ public interface VaultSysOperations {
* Unmounts the secret backend mount at {@code path}.
*
* @param path must not be empty or {@literal null}.
- * @see DELETE /sys/mounts/{mount}
+ * @see DELETE
+ * /sys/mounts/{mount}
*/
void unmount(String path) throws VaultException;
@@ -96,13 +105,15 @@ public interface VaultSysOperations {
*
* @param path must not be empty or {@literal null}.
* @param vaultMount must not be {@literal null}.
- * @see POST /sys/auth/{mount}
+ * @see POST
+ * /sys/auth/{mount}
*/
void authMount(String path, VaultMount vaultMount) throws VaultException;
/**
* @return {@link Map} of all auth backend {@link VaultMount mounts}.
- * @see GET /sys/auth/
+ * @see GET
+ * /sys/auth/
*/
Map getAuthMounts() throws VaultException;
@@ -110,7 +121,8 @@ public interface VaultSysOperations {
* Unmounts the auth backend mount at {@code path}.
*
* @param path must not be empty or {@literal null}.
- * @see DELETE /sys/auth/{mount}
+ * @see DELETE
+ * /sys/auth/{mount}
*/
void authUnmount(String path) throws VaultException;
@@ -118,7 +130,8 @@ public interface VaultSysOperations {
* Returns the health status of Vault.
*
* @return the {@link VaultHealth}.
- * @see GET /sys/health
+ * @see GET
+ * /sys/health
*/
VaultHealth health() throws VaultException;
}
diff --git a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultSysTemplate.java b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultSysTemplate.java
index c324a9fb..9eb91a57 100644
--- a/spring-vault-core/src/main/java/org/springframework/vault/core/VaultSysTemplate.java
+++ b/spring-vault-core/src/main/java/org/springframework/vault/core/VaultSysTemplate.java
@@ -22,6 +22,13 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import com.fasterxml.jackson.annotation.JsonAnySetter;
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import lombok.Data;
+
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
@@ -43,14 +50,6 @@ import org.springframework.vault.support.VaultUnsealStatus;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;
-import com.fasterxml.jackson.annotation.JsonAnySetter;
-import com.fasterxml.jackson.annotation.JsonIgnore;
-import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
-import com.fasterxml.jackson.annotation.JsonProperty;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-import lombok.Data;
-
/**
* Default implementation of {@link VaultSysOperations}.
*
@@ -90,7 +89,8 @@ public class VaultSysTemplate implements VaultSysOperations {
@Override
public Boolean doWithVault(VaultClient client) {
- VaultResponseEntity> response = client.getForEntity("sys/init", Map.class);
+ VaultResponseEntity> response = client.getForEntity(
+ "sys/init", Map.class);
if (response.isSuccessful() && response.hasBody()) {
return response.getBody().get("initialized");
@@ -102,25 +102,28 @@ public class VaultSysTemplate implements VaultSysOperations {
}
@Override
- public VaultInitializationResponse initialize(final VaultInitializationRequest vaultInitializationRequest) {
+ public VaultInitializationResponse initialize(
+ final VaultInitializationRequest vaultInitializationRequest) {
Assert.notNull(vaultInitializationRequest, "VaultInitialization must not be null");
- return vaultOperations.doWithVault(new ClientCallback() {
+ return vaultOperations
+ .doWithVault(new ClientCallback() {
- @Override
- public VaultInitializationResponse doWithVault(VaultClient client) {
+ @Override
+ public VaultInitializationResponse doWithVault(VaultClient client) {
- VaultResponseEntity response = client.putForEntity("sys/init",
- vaultInitializationRequest, VaultInitializationResponseImpl.class);
+ VaultResponseEntity response = client
+ .putForEntity("sys/init", vaultInitializationRequest,
+ VaultInitializationResponseImpl.class);
- if (response.isSuccessful() && response.hasBody()) {
- return response.getBody();
- }
+ if (response.isSuccessful() && response.hasBody()) {
+ return response.getBody();
+ }
- throw new VaultException(buildExceptionMessage(response));
- }
- });
+ throw new VaultException(buildExceptionMessage(response));
+ }
+ });
}
@Override
@@ -136,8 +139,10 @@ public class VaultSysTemplate implements VaultSysOperations {
@Override
public VaultUnsealStatus doWithVault(VaultClient client) {
- VaultResponseEntity response = client.putForEntity("sys/unseal",
- Collections.singletonMap("key", keyShare), VaultUnsealStatusImpl.class);
+ VaultResponseEntity response = client
+ .putForEntity("sys/unseal",
+ Collections.singletonMap("key", keyShare),
+ VaultUnsealStatusImpl.class);
if (response.isSuccessful() && response.hasBody()) {
return response.getBody();
@@ -176,7 +181,8 @@ public class VaultSysTemplate implements VaultSysOperations {
}
@Override
- public void authMount(final String path, final VaultMount vaultMount) throws VaultException {
+ public void authMount(final String path, final VaultMount vaultMount)
+ throws VaultException {
Assert.hasText(path, "Path must not be empty");
Assert.notNull(vaultMount, "VaultMount must not be null");
@@ -199,16 +205,19 @@ public class VaultSysTemplate implements VaultSysOperations {
@Override
public VaultHealth health() {
- return vaultOperations.doWithRestTemplate("sys/health", Collections. emptyMap(), HEALTH);
+ return vaultOperations.doWithRestTemplate("sys/health",
+ Collections.emptyMap(), HEALTH);
}
private static String buildExceptionMessage(VaultResponseEntity> response) {
if (StringUtils.hasText(response.getMessage())) {
- return String.format("Status %s URI %s: %s", response.getStatusCode(), response.getUri(), response.getMessage());
+ return String.format("Status %s URI %s: %s", response.getStatusCode(),
+ response.getUri(), response.getMessage());
}
- return String.format("Status %s URI %s", response.getStatusCode(), response.getUri());
+ return String.format("Status %s URI %s", response.getStatusCode(),
+ response.getUri());
}
private static class GetUnsealStatus implements ClientCallback {
@@ -216,8 +225,8 @@ public class VaultSysTemplate implements VaultSysOperations {
@Override
public VaultUnsealStatus doWithVault(VaultClient client) {
- VaultResponseEntity response = client.getForEntity("sys/seal-status",
- VaultUnsealStatusImpl.class);
+ VaultResponseEntity response = client.getForEntity(
+ "sys/seal-status", VaultUnsealStatusImpl.class);
if (response.isSuccessful() && response.hasBody()) {
return response.getBody();
@@ -232,7 +241,8 @@ public class VaultSysTemplate implements VaultSysOperations {
@Override
public Void doWithVault(VaultOperations.VaultSession session) {
- VaultResponseEntity response = session.putForEntity("sys/seal", null, Map.class);
+ VaultResponseEntity response = session.putForEntity("sys/seal", null,
+ Map.class);
if (!response.isSuccessful()) {
throw new VaultException(buildExceptionMessage(response));
@@ -244,7 +254,8 @@ public class VaultSysTemplate implements VaultSysOperations {
private static class GetMounts implements SessionCallback> {
- private static final ParameterizedTypeReference MOUNT_TYPE_REF = new ParameterizedTypeReference() {};
+ private static final ParameterizedTypeReference MOUNT_TYPE_REF = new ParameterizedTypeReference() {
+ };
private final String path;
@@ -255,8 +266,9 @@ public class VaultSysTemplate implements VaultSysOperations {
@Override
public Map doWithVault(VaultOperations.VaultSession session) {
- VaultResponseEntity response = session.exchange(path, HttpMethod.GET, null, MOUNT_TYPE_REF,
- Collections. emptyMap());
+ VaultResponseEntity response = session.exchange(path,
+ HttpMethod.GET, null, MOUNT_TYPE_REF,
+ Collections.emptyMap());
if (response.isSuccessful() && response.hasBody()) {
@@ -272,7 +284,8 @@ public class VaultSysTemplate implements VaultSysOperations {
throw new VaultException(buildExceptionMessage(response));
}
- private static class VaultMountsResponse extends VaultResponseSupport> {
+ private static class VaultMountsResponse extends
+ VaultResponseSupport> {
private Map topLevelMounts = new HashMap();
@@ -304,22 +317,26 @@ public class VaultSysTemplate implements VaultSysOperations {
}
- private static class Health implements VaultAccessor.RestTemplateCallback {
+ private static class Health implements
+ VaultAccessor.RestTemplateCallback {
@Override
public VaultHealth doWithRestTemplate(URI uri, RestTemplate restTemplate) {
try {
- ResponseEntity healthResponse = restTemplate.exchange(uri, HttpMethod.GET, null,
- VaultHealthImpl.class);
+ ResponseEntity healthResponse = restTemplate.exchange(
+ uri, HttpMethod.GET, null, VaultHealthImpl.class);
return healthResponse.getBody();
- } catch (HttpStatusCodeException responseError) {
+ }
+ catch (HttpStatusCodeException responseError) {
try {
ObjectMapper mapper = new ObjectMapper();
- return mapper.readValue(responseError.getResponseBodyAsString(), VaultHealthImpl.class);
- } catch (Exception jsonError) {
+ return mapper.readValue(responseError.getResponseBodyAsString(),
+ VaultHealthImpl.class);
+ }
+ catch (Exception jsonError) {
throw responseError;
}
}
@@ -331,7 +348,8 @@ public class VaultSysTemplate implements VaultSysOperations {
private List