Apply spring-javaformat and checkstyle

This commit adds the spring-javaformat code formatter and checkstyle
rules to the project to make code formatting and style more consistent
with other Spring projects.
This commit is contained in:
Scott Frederick
2020-05-19 15:32:17 -05:00
parent 175e851cb7
commit efbedf845f
209 changed files with 4381 additions and 4518 deletions

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -26,6 +26,7 @@ buildscript {
classpath 'io.spring.gradle:spring-io-plugin:0.0.8.RELEASE'
classpath 'org.asciidoctor:asciidoctor-gradle-plugin:1.5.12'
classpath 'io.spring.nohttp:nohttp-gradle:0.0.1.RELEASE'
classpath 'io.spring.javaformat:spring-javaformat-gradle-plugin:0.0.22'
}
}
@@ -50,12 +51,6 @@ ext {
] as String[]
}
apply plugin: 'io.spring.nohttp'
checkstyle {
toolVersion = 8.16
}
allprojects {
apply plugin: 'java'
apply plugin: 'maven'
@@ -68,6 +63,15 @@ allprojects {
apply plugin: "io.spring.dependency-management"
apply plugin: 'org.asciidoctor.gradle.asciidoctor'
apply plugin: 'io.spring.nohttp'
apply plugin: 'io.spring.javaformat'
apply plugin: 'checkstyle'
checkstyle {
toolVersion = 8.29
configDir = new File("${rootProject.projectDir}/src/checkstyle")
}
group = 'org.springframework.credhub'
asciidoctor {
@@ -133,6 +137,8 @@ subprojects {
}
dependencies {
checkstyle("io.spring.javaformat:spring-javaformat-checkstyle:0.0.22")
testCompile("junit:junit:$junitVersion")
testCompile("org.mockito:mockito-core:$mockitoVersion")
}

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
apply plugin: 'maven'
install {

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
rootProject.name = 'spring-credhub'
include ':spring-credhub-core'

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2017-2018 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,38 +18,41 @@ package org.springframework.credhub.configuration;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import io.netty.channel.ChannelOption;
import io.netty.handler.ssl.ClientAuth;
import io.netty.handler.ssl.IdentityCipherSuiteFilter;
import io.netty.handler.ssl.JdkSslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.SslProvider;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import reactor.netty.http.client.HttpClient;
import org.springframework.credhub.support.ClientOptions;
import org.springframework.http.client.reactive.ClientHttpConnector;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import reactor.netty.http.client.HttpClient;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
/**
* Factory for {@link ClientHttpConnector} that supports {@link ReactorClientHttpConnector}.
* Factory for {@link ClientHttpConnector} that supports
* {@link ReactorClientHttpConnector}.
*
* @author Mark Paluch
* @author Scott Frederick
*/
public class ClientHttpConnectorFactory {
public final class ClientHttpConnectorFactory {
private static final Log logger = LogFactory.getLog(ClientHttpConnectorFactory.class);
private static final SslCertificateUtils sslCertificateUtils = new SslCertificateUtils();
private ClientHttpConnectorFactory() {
}
/**
* Create a {@link ClientHttpConnector} for the given {@link ClientOptions}.
*
* @param options must not be {@literal null}
* @return a new {@link ClientHttpConnector}.
*/
@@ -57,29 +60,28 @@ public class ClientHttpConnectorFactory {
HttpClient httpClient = HttpClient.create();
if (usingCustomCerts(options)) {
TrustManagerFactory trustManagerFactory =
sslCertificateUtils.createTrustManagerFactory(options.getCaCertFiles());
TrustManagerFactory trustManagerFactory = sslCertificateUtils
.createTrustManagerFactory(options.getCaCertFiles());
httpClient = httpClient.secure(sslContextSpec -> sslContextSpec
.sslContext(SslContextBuilder.forClient()
.sslProvider(SslProvider.JDK)
.trustManager(trustManagerFactory)));
} else {
httpClient = httpClient.secure(sslContextSpec -> {
httpClient = httpClient.secure((sslContextSpec) -> sslContextSpec.sslContext(
SslContextBuilder.forClient().sslProvider(SslProvider.JDK).trustManager(trustManagerFactory)));
}
else {
httpClient = httpClient.secure((sslContextSpec) -> {
try {
sslContextSpec
.sslContext(new JdkSslContext(SSLContext.getDefault(), true, null,
IdentityCipherSuiteFilter.INSTANCE, null, ClientAuth.REQUIRE, null, false));
} catch (NoSuchAlgorithmException e) {
logger.error("Error configuring HTTP connections", e);
throw new RuntimeException("Error configuring HTTP connections", e);
sslContextSpec.sslContext(new JdkSslContext(SSLContext.getDefault(), true, null,
IdentityCipherSuiteFilter.INSTANCE, null, ClientAuth.REQUIRE, null, false));
}
catch (NoSuchAlgorithmException ex) {
logger.error("Error configuring HTTP connections", ex);
throw new RuntimeException("Error configuring HTTP connections", ex);
}
});
}
if (options.getConnectionTimeout() != null) {
httpClient = httpClient.tcpConfiguration(tcpClient ->
tcpClient.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
httpClient = httpClient
.tcpConfiguration((tcpClient) -> tcpClient.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
Math.toIntExact(options.getConnectionTimeout().toMillis())));
}
@@ -89,4 +91,5 @@ public class ClientHttpConnectorFactory {
private static boolean usingCustomCerts(ClientOptions options) {
return options.getCaCertFiles() != null;
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -56,26 +56,26 @@ import org.springframework.util.ClassUtils;
* @author Mark Paluch
* @author Scott Frederick
*/
public class ClientHttpRequestFactoryFactory {
public final class ClientHttpRequestFactoryFactory {
private static final Log logger = LogFactory.getLog(ClientHttpRequestFactoryFactory.class);
private static final SslCertificateUtils sslCertificateUtils = new SslCertificateUtils();
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 OKHTTP3_PRESENT = ClassUtils.isPresent(
"okhttp3.OkHttpClient",
private static final boolean OKHTTP3_PRESENT = ClassUtils.isPresent("okhttp3.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());
private ClientHttpRequestFactoryFactory() {
}
/**
* Create a {@link ClientHttpRequestFactory} for the given {@link ClientOptions}.
*
* @param options must not be {@literal null}
* @return a new {@link ClientHttpRequestFactory}. Lifecycle beans must be initialized
* after obtaining.
@@ -99,24 +99,30 @@ public class ClientHttpRequestFactoryFactory {
logger.info("Using Netty for HTTP connections");
return Netty.usingNetty(options);
}
} catch (GeneralSecurityException | IOException e) {
logger.warn("Error configuring HTTP connections", e);
}
catch (GeneralSecurityException | IOException ex) {
logger.warn("Error configuring HTTP connections", ex);
}
logger.info("Defaulting to java.net.HttpUrlConnection for HTTP connections");
return HttpURLConnection.usingJdk(options);
}
private static boolean usingCustomCerts(ClientOptions options) {
return options.getCaCertFiles() != null;
}
/**
* {@link ClientHttpRequestFactory} using {@link java.net.HttpURLConnection}.
*/
static class HttpURLConnection {
static ClientHttpRequestFactory usingJdk(ClientOptions options) {
if (usingCustomCerts(options)) {
logger.warn("Trust material will not be configured when using " +
"java.net.HttpUrlConnection. Use an alternate HTTP Client " +
"(Apache HttpComponents HttpClient, OkHttp3, or Netty) when " +
"configuring CA certificates.");
logger.warn("Trust material will not be configured when using "
+ "java.net.HttpUrlConnection. Use an alternate HTTP Client "
+ "(Apache HttpComponents HttpClient, OkHttp3, or Netty) when "
+ "configuring CA certificates.");
}
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
@@ -130,6 +136,7 @@ public class ClientHttpRequestFactoryFactory {
return factory;
}
}
/**
@@ -139,27 +146,22 @@ public class ClientHttpRequestFactoryFactory {
* @author Scott Frederick
*/
static class HttpComponents {
static ClientHttpRequestFactory usingHttpComponents(ClientOptions options)
throws GeneralSecurityException {
static ClientHttpRequestFactory usingHttpComponents(ClientOptions options) throws GeneralSecurityException {
HttpClientBuilder httpClientBuilder = HttpClients.custom();
if (usingCustomCerts(options)) {
SSLContext sslContext = sslCertificateUtils.getSSLContext(options.getCaCertFiles());
SSLConnectionSocketFactory sslSocketFactory =
new SSLConnectionSocketFactory(sslContext);
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);
httpClientBuilder
.setSSLSocketFactory(sslSocketFactory)
.setSSLContext(sslContext);
} else {
httpClientBuilder
.setSSLContext(SSLContext.getDefault())
.useSystemProperties();
httpClientBuilder.setSSLSocketFactory(sslSocketFactory).setSSLContext(sslContext);
}
else {
httpClientBuilder.setSSLContext(SSLContext.getDefault()).useSystemProperties();
}
RequestConfig.Builder requestConfigBuilder = RequestConfig.custom()
.setAuthenticationEnabled(true);
RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setAuthenticationEnabled(true);
if (options.getConnectionTimeout() != null) {
requestConfigBuilder.setConnectTimeout(options.getConnectionTimeoutMillis());
@@ -172,6 +174,7 @@ public class ClientHttpRequestFactoryFactory {
return new HttpComponentsClientHttpRequestFactory(httpClientBuilder.build());
}
}
/**
@@ -181,19 +184,19 @@ public class ClientHttpRequestFactoryFactory {
* @author Scott Frederick
*/
static class OkHttp3 {
static ClientHttpRequestFactory usingOkHttp3(ClientOptions options)
throws GeneralSecurityException {
static ClientHttpRequestFactory usingOkHttp3(ClientOptions options) throws GeneralSecurityException {
Builder builder = new Builder();
if (usingCustomCerts(options)) {
SSLSocketFactory socketFactory =
sslCertificateUtils.getSSLContext(options.getCaCertFiles()).getSocketFactory();
X509TrustManager trustManager =
sslCertificateUtils.createTrustManager(options.getCaCertFiles());
SSLSocketFactory socketFactory = sslCertificateUtils.getSSLContext(options.getCaCertFiles())
.getSocketFactory();
X509TrustManager trustManager = sslCertificateUtils.createTrustManager(options.getCaCertFiles());
builder.sslSocketFactory(socketFactory, trustManager);
} else {
}
else {
SSLSocketFactory socketFactory = SSLContext.getDefault().getSocketFactory();
X509TrustManager trustManager = sslCertificateUtils.getDefaultX509TrustManager();
@@ -221,8 +224,7 @@ public class ClientHttpRequestFactoryFactory {
static class Netty {
@SuppressWarnings("deprecation")
static ClientHttpRequestFactory usingNetty(ClientOptions options)
throws IOException, GeneralSecurityException {
static ClientHttpRequestFactory usingNetty(ClientOptions options) throws IOException, GeneralSecurityException {
final Netty4ClientHttpRequestFactory requestFactory = new Netty4ClientHttpRequestFactory();
@@ -234,17 +236,15 @@ public class ClientHttpRequestFactoryFactory {
}
if (usingCustomCerts(options)) {
TrustManagerFactory trustManagerFactory =
sslCertificateUtils.createTrustManagerFactory(options.getCaCertFiles());
TrustManagerFactory trustManagerFactory = sslCertificateUtils
.createTrustManagerFactory(options.getCaCertFiles());
SslContext sslContext = SslContextBuilder
.forClient()
.sslProvider(SslProvider.JDK)
.trustManager(trustManagerFactory)
.build();
SslContext sslContext = SslContextBuilder.forClient().sslProvider(SslProvider.JDK)
.trustManager(trustManagerFactory).build();
requestFactory.setSslContext(sslContext);
} else {
}
else {
SslContext sslContext = new JdkSslContext(SSLContext.getDefault(), true, null,
IdentityCipherSuiteFilter.INSTANCE, null, ClientAuth.REQUIRE, null, false);
@@ -256,7 +256,4 @@ public class ClientHttpRequestFactoryFactory {
}
private static boolean usingCustomCerts(ClientOptions options) {
return options.getCaCertFiles() != null;
}
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -41,77 +41,68 @@ public class CredHubTemplateFactory {
/**
* Create a {@link CredHubTemplate} for interaction with a CredHub server.
*
* @param credHubProperties connection properties
* @param clientOptions connection options
* @param clientOptions connection options
* @return a {@code CredHubTemplate}
*/
public CredHubTemplate credHubTemplate(CredHubProperties credHubProperties,
ClientOptions clientOptions) {
public CredHubTemplate credHubTemplate(CredHubProperties credHubProperties, ClientOptions clientOptions) {
return new CredHubTemplate(credHubProperties, clientHttpRequestFactory(clientOptions));
}
/**
* Create a {@link CredHubTemplate} for interaction with a CredHub server
* using OAuth2 for authentication.
*
* @param credHubProperties connection properties
* @param clientOptions connection options
* Create a {@link CredHubTemplate} for interaction with a CredHub server using OAuth2
* for authentication.
* @param credHubProperties connection properties
* @param clientOptions connection options
* @param clientRegistrationRepository a repository of OAuth2 client registrations
* @param authorizedClientRepository a repository of authorized OAuth2 clients
* @param authorizedClientRepository a repository of authorized OAuth2 clients
* @return a {@code CredHubTemplate}
*/
public CredHubTemplate credHubTemplate(CredHubProperties credHubProperties,
ClientOptions clientOptions,
ClientRegistrationRepository clientRegistrationRepository,
OAuth2AuthorizedClientRepository authorizedClientRepository) {
public CredHubTemplate credHubTemplate(CredHubProperties credHubProperties, ClientOptions clientOptions,
ClientRegistrationRepository clientRegistrationRepository,
OAuth2AuthorizedClientRepository authorizedClientRepository) {
return new CredHubTemplate(credHubProperties, clientHttpRequestFactory(clientOptions),
clientRegistrationRepository, authorizedClientRepository);
}
/**
* Create a {@link CredHubTemplate} for interaction with a CredHub server
* using OAuth2 for authentication.
*
* @param credHubProperties connection properties
* @param clientOptions connection options
* Create a {@link CredHubTemplate} for interaction with a CredHub server using OAuth2
* for authentication.
* @param credHubProperties connection properties
* @param clientOptions connection options
* @param clientRegistrationRepository a repository of OAuth2 client registrations
* @param clientManager an OAuth2 authorization client manager
* @param clientManager an OAuth2 authorization client manager
* @return a {@code CredHubTemplate}
*/
public CredHubOperations credHubTemplate(CredHubProperties credHubProperties, ClientOptions clientOptions,
ClientRegistrationRepository clientRegistrationRepository,
OAuth2AuthorizedClientManager clientManager) {
ClientRegistrationRepository clientRegistrationRepository, OAuth2AuthorizedClientManager clientManager) {
return new CredHubTemplate(credHubProperties, clientHttpRequestFactory(clientOptions),
clientRegistrationRepository, clientManager);
}
/**
* Create a {@link ReactiveCredHubTemplate} for interaction with a CredHub server.
*
* @param credHubProperties connection properties
* @param clientOptions connection options
* @param clientOptions connection options
* @return a {@code ReactiveCredHubTemplate}
*/
public ReactiveCredHubTemplate reactiveCredHubTemplate(CredHubProperties credHubProperties,
ClientOptions clientOptions) {
ClientOptions clientOptions) {
return new ReactiveCredHubTemplate(credHubProperties, clientHttpConnector(clientOptions));
}
/**
* Create a {@link ReactiveCredHubTemplate} for interaction with a CredHub server
* using OAuth2 for authentication.
*
* @param credHubProperties connection properties
* @param clientOptions connection options
* @param credHubProperties connection properties
* @param clientOptions connection options
* @param clientRegistrationRepository a repository of OAuth2 client registrations
* @param authorizedClientRepository a repository of OAuth2 client authorizations
* @param authorizedClientRepository a repository of OAuth2 client authorizations
* @return a {@code ReactiveCredHubTemplate}
*/
public ReactiveCredHubOperations reactiveCredHubTemplate(CredHubProperties credHubProperties,
ClientOptions clientOptions,
ReactiveClientRegistrationRepository clientRegistrationRepository,
ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {
ClientOptions clientOptions, ReactiveClientRegistrationRepository clientRegistrationRepository,
ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {
return new ReactiveCredHubTemplate(credHubProperties, clientHttpConnector(clientOptions),
clientRegistrationRepository, authorizedClientRepository);
}
@@ -119,21 +110,18 @@ public class CredHubTemplateFactory {
/**
* Create a {@link ReactiveCredHubTemplate} for interaction with a CredHub server
* using OAuth2 for authentication.
*
* @param credHubProperties connection properties
* @param clientOptions connection options
* @param clientManager an OAuth2 authorization client manager
* @param clientOptions connection options
* @param clientManager an OAuth2 authorization client manager
* @return a {@code ReactiveCredHubTemplate}
*/
public ReactiveCredHubOperations reactiveCredHubTemplate(CredHubProperties credHubProperties,
ClientOptions clientOptions,
ReactiveOAuth2AuthorizedClientManager clientManager) {
ClientOptions clientOptions, ReactiveOAuth2AuthorizedClientManager clientManager) {
return new ReactiveCredHubTemplate(credHubProperties, clientHttpConnector(clientOptions), clientManager);
}
/**
* Create a {@link ClientHttpRequestFactory}.
*
* @param clientOptions options for creating the client connection
* @return the {@link ClientHttpRequestFactory} instance.
*/
@@ -143,11 +131,11 @@ public class CredHubTemplateFactory {
/**
* Create a {@link ClientHttpRequestFactory}.
*
* @param clientOptions options for creating the client connection
* @return the {@link ClientHttpRequestFactory} instance.
*/
private ClientHttpConnector clientHttpConnector(ClientOptions clientOptions) {
return ClientHttpConnectorFactory.create(clientOptions);
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,10 +16,6 @@
package org.springframework.credhub.configuration;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
@@ -36,16 +32,22 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
/**
* Utility methods for building custom trust material for HTTP connections.
*
* @author Scott Frederick
*/
class SslCertificateUtils {
X509TrustManager getDefaultX509TrustManager() {
try {
TrustManagerFactory trustManagerFactory =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
TrustManagerFactory trustManagerFactory = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init((KeyStore) null);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
@@ -56,11 +58,12 @@ class SslCertificateUtils {
}
}
throw new IllegalStateException("Unable to setup SSL; no X509TrustManager found in: " +
Arrays.toString(trustManagers));
} catch (GeneralSecurityException e) {
throw new IllegalStateException("Unable to setup SSL; error getting a X509TrustManager: " +
e.getMessage(), e);
throw new IllegalStateException(
"Unable to setup SSL; no X509TrustManager found in: " + Arrays.toString(trustManagers));
}
catch (GeneralSecurityException ex) {
throw new IllegalStateException("Unable to setup SSL; error getting a X509TrustManager: " + ex.getMessage(),
ex);
}
}
@@ -72,8 +75,9 @@ class SslCertificateUtils {
sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
return sslContext;
} catch (GeneralSecurityException e) {
throw new IllegalStateException("Error creating SSLContext: " + e.getMessage(), e);
}
catch (GeneralSecurityException ex) {
throw new IllegalStateException("Error creating SSLContext: " + ex.getMessage(), ex);
}
}
@@ -86,18 +90,17 @@ class SslCertificateUtils {
trustManagerFactory.init(trustStore);
return trustManagerFactory;
} catch (GeneralSecurityException e) {
throw new IllegalStateException("Error creating KeyManagerFactory: " + e.getMessage(), e);
}
catch (GeneralSecurityException ex) {
throw new IllegalStateException("Error creating KeyManagerFactory: " + ex.getMessage(), ex);
}
}
X509TrustManager createTrustManager(String[] caCertFiles) {
TrustManager[] trustManagers = createTrustManagerFactory(caCertFiles)
.getTrustManagers();
TrustManager[] trustManagers = createTrustManagerFactory(caCertFiles).getTrustManagers();
if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
throw new IllegalStateException("Unexpected default trust managers: "
+ Arrays.toString(trustManagers));
throw new IllegalStateException("Unexpected default trust managers: " + Arrays.toString(trustManagers));
}
return (X509TrustManager) trustManagers[0];
@@ -112,8 +115,9 @@ class SslCertificateUtils {
addCertsToCertificateStore(keyStore, certificates);
return keyStore;
} catch (GeneralSecurityException | IOException e) {
throw new IllegalStateException("Error creating new truststore: " + e.getMessage(), e);
}
catch (GeneralSecurityException | IOException ex) {
throw new IllegalStateException("Error creating new truststore: " + ex.getMessage(), ex);
}
}
@@ -130,8 +134,9 @@ class SslCertificateUtils {
try {
FileInputStream fileStream = new FileInputStream(new File(fileName));
return new BufferedInputStream(fileStream);
} catch (FileNotFoundException e) {
throw new IllegalArgumentException("Certificate file not found: " + fileName, e);
}
catch (FileNotFoundException ex) {
throw new IllegalArgumentException("Certificate file not found: " + fileName, ex);
}
}
@@ -144,12 +149,14 @@ class SslCertificateUtils {
do {
certs.add((X509Certificate) certificateFactory.generateCertificate(inputStream));
} while (inputStream.available() > minCertLength);
}
while (inputStream.available() > minCertLength);
return certs;
} catch (CertificateException | IOException e) {
throw new IllegalStateException("Error reading certificate from file "
+ fileName + ": " + e.getMessage(), e);
}
catch (CertificateException | IOException ex) {
throw new IllegalStateException("Error reading certificate from file " + fileName + ": " + ex.getMessage(),
ex);
}
}
@@ -159,8 +166,10 @@ class SslCertificateUtils {
String alias = cert.getSubjectX500Principal().getName();
keyStore.setCertificateEntry(alias, cert);
}
} catch (KeyStoreException e) {
throw new IllegalStateException("Error creating new certificate store: " + e.getMessage(), e);
}
catch (KeyStoreException ex) {
throw new IllegalStateException("Error creating new certificate store: " + ex.getMessage(), ex);
}
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -17,4 +17,4 @@
/**
* Spring configuration support for Spring CredHub.
*/
package org.springframework.credhub.configuration;
package org.springframework.credhub.configuration;

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -25,9 +25,9 @@ import org.springframework.web.client.HttpStatusCodeException;
* @author Scott Frederick
*/
public class CredHubException extends HttpStatusCodeException {
/**
* Create a new exception with the provided root cause.
*
* @param e an {@link HttpStatusCodeException} caught while attempting to communicate
* with CredHub
*/
@@ -37,11 +37,11 @@ public class CredHubException extends HttpStatusCodeException {
/**
* Create a new exception with the provided error status code.
*
* @param statusCode an {@link HttpStatus} indicating an error while attempting to
* communicate with CredHub
*/
public CredHubException(HttpStatus statusCode) {
super(statusCode);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,6 +16,9 @@
package org.springframework.credhub.core;
import java.io.IOException;
import java.util.Collections;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
@@ -28,20 +31,20 @@ import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import java.io.IOException;
import java.util.Collections;
/**
* A request interceptor that sets OAuth2 bearer authentication headers to all CredHub requests.
* A request interceptor that sets OAuth2 bearer authentication headers to all CredHub
* requests.
*
* @author Scott Frederick
*/
class CredHubOAuth2RequestInterceptor implements ClientHttpRequestInterceptor {
private final ClientRegistration clientRegistration;
private final OAuth2AuthorizedClientManager clientManager;
CredHubOAuth2RequestInterceptor(ClientRegistration clientRegistration,
OAuth2AuthorizedClientManager clientManager) {
OAuth2AuthorizedClientManager clientManager) {
this.clientRegistration = clientRegistration;
this.clientManager = clientManager;
}
@@ -52,8 +55,8 @@ class CredHubOAuth2RequestInterceptor implements ClientHttpRequestInterceptor {
* {@inheritDoc}
*/
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
ClientHttpRequestExecution execution) throws IOException {
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
throws IOException {
HttpRequestWrapper requestWrapper = new HttpRequestWrapper(request);
HttpHeaders headers = requestWrapper.getHeaders();
@@ -64,13 +67,13 @@ class CredHubOAuth2RequestInterceptor implements ClientHttpRequestInterceptor {
private OAuth2AuthorizedClient authorizeClient() {
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(clientRegistration.getRegistrationId())
.principal(new OAuth2ClientCredentialsGrantAuthenticationToken(clientRegistration))
.build();
return clientManager.authorize(authorizeRequest);
.withClientRegistrationId(this.clientRegistration.getRegistrationId())
.principal(new OAuth2ClientCredentialsGrantAuthenticationToken(this.clientRegistration)).build();
return this.clientManager.authorize(authorizeRequest);
}
private static class OAuth2ClientCredentialsGrantAuthenticationToken extends AbstractAuthenticationToken {
private final ClientRegistration clientRegistration;
OAuth2ClientCredentialsGrantAuthenticationToken(ClientRegistration clientRegistration) {
@@ -87,5 +90,7 @@ class CredHubOAuth2RequestInterceptor implements ClientHttpRequestInterceptor {
public Object getPrincipal() {
return this.clientRegistration.getClientId();
}
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -30,55 +30,50 @@ import org.springframework.web.client.RestTemplate;
* @author Scott Frederick
*/
public interface CredHubOperations {
/**
* Get the operations for saving, retrieving, and deleting credentials.
*
* @return the credentials operations
*/
CredHubCredentialOperations credentials();
/**
* Get the operations for adding, retrieving, and deleting credential permissions.
*
* @return the permissions operations
*/
CredHubPermissionOperations permissions();
/**
* Get the operations for adding, retrieving, and deleting credential permissions.
*
* @return the permissions operations
*/
CredHubPermissionV2Operations permissionsV2();
/**
* Get the operations for retrieving, regenerating, and updating certificates.
*
* @return the certificates operations
*/
CredHubCertificateOperations certificates();
/**
* Get the operations for interpolating service binding credentials.
*
* @return the interpolation operations
*/
CredHubInterpolationOperations interpolation();
/**
* Get the operations for retrieving CredHub server information.
*
* @return the info operations
*/
CredHubInfoOperations info();
/**
* Allow interaction with the configured {@link RestTemplate} not provided
* by other methods.
*
* Allow interaction with the configured {@link RestTemplate} not provided by other
* methods.
* @param callback wrapper for the callback method
* @param <T> the credential implementation type
* @return the return value from the callback method
*/
<T> T doWithRest(RestOperationsCallback<T> callback);
}

View File

@@ -1,19 +1,17 @@
/*
* Copyright 2016-2020 the original author or authors.
*
* * Copyright 2013-2017 the original author or authors.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * https://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.credhub.core;
@@ -25,7 +23,9 @@ package org.springframework.credhub.core;
* @author Daniel Lavoie
*/
public class CredHubProperties {
private String url;
private OAuth2 oauth2;
/**
@@ -37,17 +37,15 @@ public class CredHubProperties {
/**
* Get the base URI for the CredHub server (scheme, host, and port). This value will
* be prepended to all requests to CredHub.
*
* @return the base URI
*/
public String getUrl() {
return url;
return this.url;
}
/**
* Set the base URI for the CredHub server (scheme, host, and port). This value will
* be prepended to all requests to CredHub.
*
* @param url the base URI for the CredHub server
*/
public void setUrl(String url) {
@@ -56,16 +54,14 @@ public class CredHubProperties {
/**
* Get the OAuth2 properties.
*
* @return the OAuth2 properties.
*/
public OAuth2 getOauth2() {
return oauth2;
return this.oauth2;
}
/**
* Set the OAuth2 properties.
*
* @param oauth2 the OAuth2 properties
*/
public void setOauth2(OAuth2 oauth2) {
@@ -76,6 +72,7 @@ public class CredHubProperties {
* Properties containing OAuth2 credentials for CredHub connectivity.
*/
public static class OAuth2 {
private String registrationId;
/**
@@ -86,20 +83,20 @@ public class CredHubProperties {
/**
* Get the OAuth2 client registration ID used to authenticate with CredHub.
*
* @return the OAuth2 registration ID
*/
public String getRegistrationId() {
return registrationId;
return this.registrationId;
}
/**
* Set the OAuth2 client registration ID used to authentiate with CredHub.
*
* @param registrationId the OAuth2 client registration ID
*/
public void setRegistrationId(String registrationId) {
this.registrationId = registrationId;
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,10 +16,9 @@
package org.springframework.credhub.core;
import static java.util.Collections.singletonList;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import org.springframework.credhub.support.utils.JsonUtils;
import org.springframework.http.HttpHeaders;
@@ -50,24 +49,26 @@ import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.DefaultUriBuilderFactory;
/**
* Factory for creating a {@link RestTemplate} configured for communication with
* a CredHub server.
* Factory for creating a {@link RestTemplate} configured for communication with a CredHub
* server.
*
* @author Scott Frederick
* @author Daniel Lavoie
*/
class CredHubRestTemplateFactory {
final class CredHubRestTemplateFactory {
private CredHubRestTemplateFactory() {
}
/**
* Create a {@link RestTemplate} configured for communication with a CredHub server.
*
* @param properties CredHub connection properties
* @param properties the CredHub connection properties
* @param clientHttpRequestFactory the {@link ClientHttpRequestFactory} to use when
* creating new connections
* creating new connections
* @return a configured {@link RestTemplate}
*/
static RestTemplate createRestTemplate(CredHubProperties properties,
ClientHttpRequestFactory clientHttpRequestFactory) {
ClientHttpRequestFactory clientHttpRequestFactory) {
RestTemplate restTemplate = new RestTemplate();
configureRestTemplate(restTemplate, properties.getUrl(), clientHttpRequestFactory);
@@ -77,18 +78,17 @@ class CredHubRestTemplateFactory {
/**
* Create a {@link RestTemplate} configured for communication with a CredHub server.
*
* @param properties CredHub connection properties
* @param clientHttpRequestFactory the {@link ClientHttpRequestFactory} to use when
* creating new connections
* @param properties the CredHub connection properties
* @param clientHttpRequestFactory the {@link ClientHttpRequestFactory} to use when
* creating new connections
* @param clientRegistrationRepository a repository of OAuth2 client registrations
* @param authorizedClientRepository a repository of authorized OAuth2 clients
* @param authorizedClientRepository a repository of authorized OAuth2 clients
* @return a configured {@link RestTemplate}
*/
static RestTemplate createRestTemplate(CredHubProperties properties,
ClientHttpRequestFactory clientHttpRequestFactory,
ClientRegistrationRepository clientRegistrationRepository,
OAuth2AuthorizedClientRepository authorizedClientRepository) {
ClientHttpRequestFactory clientHttpRequestFactory,
ClientRegistrationRepository clientRegistrationRepository,
OAuth2AuthorizedClientRepository authorizedClientRepository) {
RestTemplate restTemplate = new RestTemplate();
configureRestTemplate(restTemplate, properties.getUrl(), clientHttpRequestFactory);
@@ -100,18 +100,16 @@ class CredHubRestTemplateFactory {
/**
* Create a {@link RestTemplate} configured for communication with a CredHub server.
*
* @param properties CredHub connection properties
* @param clientHttpRequestFactory the {@link ClientHttpRequestFactory} to use when
* creating new connections
* @param properties the CredHub connection properties
* @param clientHttpRequestFactory the {@link ClientHttpRequestFactory} to use when
* creating new connections
* @param clientRegistrationRepository a repository of OAuth2 client registrations
* @param clientManager an OAuth2 authorization client manager
* @param clientManager an OAuth2 authorization client manager
* @return a configured {@link RestTemplate}
*/
public static RestTemplate createRestTemplate(CredHubProperties properties,
ClientHttpRequestFactory clientHttpRequestFactory,
ClientRegistrationRepository clientRegistrationRepository,
OAuth2AuthorizedClientManager clientManager) {
static RestTemplate createRestTemplate(CredHubProperties properties,
ClientHttpRequestFactory clientHttpRequestFactory,
ClientRegistrationRepository clientRegistrationRepository, OAuth2AuthorizedClientManager clientManager) {
RestTemplate restTemplate = new RestTemplate();
configureRestTemplate(restTemplate, properties.getUrl(), clientHttpRequestFactory);
@@ -123,49 +121,42 @@ class CredHubRestTemplateFactory {
/**
* Configure a {@link RestTemplate} for communication with a CredHub server.
*
* @param restTemplate an existing {@link RestTemplate} to configure
* @param baseUri the base URI for the CredHub server
* @param restTemplate an existing {@link RestTemplate} to configure
* @param baseUri the base URI for the CredHub server
* @param clientHttpRequestFactory the {@link ClientHttpRequestFactory} to use when
* creating new connections
* creating new connections
*/
private static void configureRestTemplate(RestTemplate restTemplate, String baseUri,
ClientHttpRequestFactory clientHttpRequestFactory) {
ClientHttpRequestFactory clientHttpRequestFactory) {
restTemplate.setRequestFactory(clientHttpRequestFactory);
restTemplate.setUriTemplateHandler(new DefaultUriBuilderFactory(baseUri));
restTemplate.getInterceptors().add(new CredHubRequestInterceptor());
restTemplate.setMessageConverters(Arrays.asList(
new ByteArrayHttpMessageConverter(),
new StringHttpMessageConverter(),
new MappingJackson2HttpMessageConverter(JsonUtils.buildObjectMapper())));
restTemplate.setMessageConverters(
Arrays.asList(new ByteArrayHttpMessageConverter(), new StringHttpMessageConverter(),
new MappingJackson2HttpMessageConverter(JsonUtils.buildObjectMapper())));
}
/**
* Configure OAuth2 features of a {@link RestTemplate}.
*
* @param restTemplate an existing {@link RestTemplate} to configure
* @param clientId the OAuth2 client ID for authentication
* @param restTemplate an existing {@link RestTemplate} to configure
* @param clientId the OAuth2 client ID for authentication
* @param clientRegistrationRepository a repository of OAuth2 client registrations
* @param clientManager an OAuth2 authorization client manager
* @param clientManager an OAuth2 authorization client manager
*/
private static void configureOAuth2(RestTemplate restTemplate,
String clientId,
ClientRegistrationRepository clientRegistrationRepository,
OAuth2AuthorizedClientManager clientManager) {
private static void configureOAuth2(RestTemplate restTemplate, String clientId,
ClientRegistrationRepository clientRegistrationRepository, OAuth2AuthorizedClientManager clientManager) {
ClientRegistration clientRegistration = getClientRegistration(clientRegistrationRepository, clientId);
restTemplate.getInterceptors()
.add(new CredHubOAuth2RequestInterceptor(clientRegistration, clientManager));
restTemplate.getInterceptors().add(new CredHubOAuth2RequestInterceptor(clientRegistration, clientManager));
}
private static ClientRegistration getClientRegistration(ClientRegistrationRepository clientRegistrationRepository,
String clientId) {
ClientRegistration clientRegistration = clientRegistrationRepository
.findByRegistrationId(clientId);
String clientId) {
ClientRegistration clientRegistration = clientRegistrationRepository.findByRegistrationId(clientId);
if (clientRegistration == null) {
throw new IllegalStateException("The CredHub OAuth2 client registration ID '" + clientId +
"' is not a valid Spring Security OAuth2 client registration");
throw new IllegalStateException("The CredHub OAuth2 client registration ID '" + clientId
+ "' is not a valid Spring Security OAuth2 client registration");
}
return clientRegistration;
@@ -176,16 +167,13 @@ class CredHubRestTemplateFactory {
OAuth2AuthorizedClientRepository authorizedClientRepository,
ClientHttpRequestFactory clientHttpRequestFactory) {
OAuth2AuthorizedClientProvider authorizedClientProvider =
OAuth2AuthorizedClientProviderBuilder.builder()
.authorizationCode()
.clientCredentials(b ->
b.accessTokenResponseClient(buildTokenResponseClient(clientHttpRequestFactory)))
.build();
OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
.authorizationCode().clientCredentials(
(b) -> b.accessTokenResponseClient(buildTokenResponseClient(clientHttpRequestFactory)))
.build();
DefaultOAuth2AuthorizedClientManager authorizedClientManager =
new DefaultOAuth2AuthorizedClientManager(
clientRegistrationRepository, authorizedClientRepository);
DefaultOAuth2AuthorizedClientManager authorizedClientManager = new DefaultOAuth2AuthorizedClientManager(
clientRegistrationRepository, authorizedClientRepository);
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
return authorizedClientManager;
@@ -193,16 +181,14 @@ class CredHubRestTemplateFactory {
private static OAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> buildTokenResponseClient(
ClientHttpRequestFactory clientHttpRequestFactory) {
DefaultClientCredentialsTokenResponseClient tokenResponseClient =
new DefaultClientCredentialsTokenResponseClient();
DefaultClientCredentialsTokenResponseClient tokenResponseClient = new DefaultClientCredentialsTokenResponseClient();
tokenResponseClient.setRestOperations(createTokenServerRestTemplate(clientHttpRequestFactory));
return tokenResponseClient;
}
private static RestTemplate createTokenServerRestTemplate(ClientHttpRequestFactory clientHttpRequestFactory) {
RestTemplate restOperations = new RestTemplate(Arrays.asList(
new FormHttpMessageConverter(),
new OAuth2AccessTokenResponseHttpMessageConverter()));
RestTemplate restOperations = new RestTemplate(
Arrays.asList(new FormHttpMessageConverter(), new OAuth2AccessTokenResponseHttpMessageConverter()));
restOperations.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
restOperations.setRequestFactory(clientHttpRequestFactory);
return restOperations;
@@ -212,16 +198,19 @@ class CredHubRestTemplateFactory {
* A request interceptor that sets headers common to all CredHub requests.
*/
private static class CredHubRequestInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
ClientHttpRequestExecution execution) throws IOException {
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
throws IOException {
HttpRequestWrapper requestWrapper = new HttpRequestWrapper(request);
HttpHeaders headers = requestWrapper.getHeaders();
headers.setAccept(singletonList(MediaType.APPLICATION_JSON));
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);
return execution.execute(requestWrapper, body);
}
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -42,13 +42,14 @@ import org.springframework.web.client.RestTemplate;
* @author Scott Frederick
*/
public class CredHubTemplate implements CredHubOperations {
private final RestTemplate restTemplate;
private final boolean usingOAuth2;
/**
* Create a new {@link CredHubTemplate} using the provided {@link RestTemplate}.
* Intended for internal testing only.
*
* @param restTemplate the {@link RestTemplate} to use for interactions with CredHub
*/
public CredHubTemplate(RestTemplate restTemplate) {
@@ -61,68 +62,61 @@ public class CredHubTemplate implements CredHubOperations {
/**
* Create a new {@link CredHubTemplate} using the provided connection properties and
* {@link ClientHttpRequestFactory}.
*
* @param properties CredHub connection properties; must not be {@literal null}
* @param properties the CredHub connection properties; must not be {@literal null}
* @param clientHttpRequestFactory the {@link ClientHttpRequestFactory} to use when
* creating new connections
* creating new connections
*/
public CredHubTemplate(CredHubProperties properties, ClientHttpRequestFactory clientHttpRequestFactory) {
Assert.notNull(properties, "properties must not be null");
Assert.notNull(clientHttpRequestFactory, "clientHttpRequestFactory must not be null");
this.restTemplate = CredHubRestTemplateFactory.createRestTemplate(properties,
clientHttpRequestFactory);
this.restTemplate = CredHubRestTemplateFactory.createRestTemplate(properties, clientHttpRequestFactory);
this.usingOAuth2 = false;
}
/**
* Create a new {@link CredHubTemplate} using the provided connection properties,
* {@link ClientHttpRequestFactory}, and OAuth2 support.
*
* @param properties CredHub connection properties; must not be {@literal null}
* @param clientHttpRequestFactory the {@link ClientHttpRequestFactory} to use when
* creating new connections
* @param properties the CredHub connection properties; must not be {@literal null}
* @param clientHttpRequestFactory the {@link ClientHttpRequestFactory} to use when
* creating new connections
* @param clientRegistrationRepository a repository of OAuth2 client registrations
* @param authorizedClientRepository a repository of authorized OAuth2 clients
* @param authorizedClientRepository a repository of authorized OAuth2 clients
*/
public CredHubTemplate(CredHubProperties properties,
ClientHttpRequestFactory clientHttpRequestFactory,
ClientRegistrationRepository clientRegistrationRepository,
OAuth2AuthorizedClientRepository authorizedClientRepository) {
public CredHubTemplate(CredHubProperties properties, ClientHttpRequestFactory clientHttpRequestFactory,
ClientRegistrationRepository clientRegistrationRepository,
OAuth2AuthorizedClientRepository authorizedClientRepository) {
Assert.notNull(properties, "properties must not be null");
Assert.notNull(clientHttpRequestFactory, "clientHttpRequestFactory must not be null");
Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository must not be null");
this.restTemplate = CredHubRestTemplateFactory.createRestTemplate(properties,
clientHttpRequestFactory, clientRegistrationRepository, authorizedClientRepository);
this.restTemplate = CredHubRestTemplateFactory.createRestTemplate(properties, clientHttpRequestFactory,
clientRegistrationRepository, authorizedClientRepository);
this.usingOAuth2 = true;
}
/**
* Create a new {@link CredHubTemplate} using the provided connection properties,
* {@link ClientHttpRequestFactory}, and OAuth2 support.
*
* @param properties CredHub connection properties; must not be {@literal null}
* @param clientHttpRequestFactory the {@link ClientHttpRequestFactory} to use when
* creating new connections
* @param properties the CredHub connection properties; must not be {@literal null}
* @param clientHttpRequestFactory the {@link ClientHttpRequestFactory} to use when
* creating new connections
* @param clientRegistrationRepository a repository of OAuth2 client registrations
* @param clientManager an OAuth2 authorization client manager
* @param clientManager an OAuth2 authorization client manager
*/
public CredHubTemplate(CredHubProperties properties, ClientHttpRequestFactory clientHttpRequestFactory,
ClientRegistrationRepository clientRegistrationRepository,
OAuth2AuthorizedClientManager clientManager) {
ClientRegistrationRepository clientRegistrationRepository, OAuth2AuthorizedClientManager clientManager) {
Assert.notNull(properties, "properties must not be null");
Assert.notNull(clientHttpRequestFactory, "clientHttpRequestFactory must not be null");
Assert.notNull(clientManager, "clientManager must not be null");
this.restTemplate = CredHubRestTemplateFactory.createRestTemplate(properties,
clientHttpRequestFactory, clientRegistrationRepository, clientManager);
this.restTemplate = CredHubRestTemplateFactory.createRestTemplate(properties, clientHttpRequestFactory,
clientRegistrationRepository, clientManager);
this.usingOAuth2 = true;
}
/**
* Get the operations for saving, retrieving, and deleting credentials.
*
* @return the credentials operations
*/
@Override
@@ -131,8 +125,8 @@ public class CredHubTemplate implements CredHubOperations {
}
/**
* Get the operations for adding, retrieving, and deleting permissions from a credential.
*
* Get the operations for adding, retrieving, and deleting permissions from a
* credential.
* @return the permissions operations
*/
@Override
@@ -141,8 +135,8 @@ public class CredHubTemplate implements CredHubOperations {
}
/**
* Get the operations for adding, retrieving, and deleting permissions from a credential.
*
* Get the operations for adding, retrieving, and deleting permissions from a
* credential.
* @return the permissions operations
*/
@Override
@@ -152,7 +146,6 @@ public class CredHubTemplate implements CredHubOperations {
/**
* Get the operations for retrieving, regenerating, and updating certificates.
*
* @return the certificates operations
*/
@Override
@@ -162,7 +155,6 @@ public class CredHubTemplate implements CredHubOperations {
/**
* Get the operations for interpolating service binding credentials.
*
* @return the interpolation operations
*/
@Override
@@ -172,7 +164,6 @@ public class CredHubTemplate implements CredHubOperations {
/**
* Get the operations for retrieving CredHub server information.
*
* @return the info operations
*/
@Override
@@ -181,9 +172,8 @@ public class CredHubTemplate implements CredHubOperations {
}
/**
* Allow interaction with the configured {@link RestTemplate} not provided
* by other methods.
*
* Allow interaction with the configured {@link RestTemplate} not provided by other
* methods.
* @param callback wrapper for the callback method
* @param <T> the credential implementation type
* @return the return value from the callback method
@@ -193,14 +183,15 @@ public class CredHubTemplate implements CredHubOperations {
Assert.notNull(callback, "callback must not be null");
try {
return callback.doWithRestOperations(restTemplate);
return callback.doWithRestOperations(this.restTemplate);
}
catch (HttpStatusCodeException e) {
throw new CredHubException(e);
catch (HttpStatusCodeException ex) {
throw new CredHubException(ex);
}
}
public boolean isUsingOAuth2() {
return this.usingOAuth2;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,6 +17,7 @@
package org.springframework.credhub.core;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.credhub.support.utils.JsonUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
@@ -36,90 +37,78 @@ import org.springframework.web.reactive.function.client.ExchangeStrategies;
import org.springframework.web.reactive.function.client.WebClient;
/**
* Factory for creating a {@link WebClient} configured for communication with
* a CredHub server.
* Factory for creating a {@link WebClient} configured for communication with a CredHub
* server.
*
* @author Mark Paluch
* @author Scott Frederick
*/
class CredHubWebClientFactory {
/**
* Create a {@link WebClient} configured for communication with a CredHub server.
*
* @param properties CredHub connection properties
* @param clientHttpConnector the {@link ClientHttpConnector} to use when
* creating new connections
* @return a configured {@link WebClient}
*/
static WebClient createWebClient(CredHubProperties properties,
ClientHttpConnector clientHttpConnector) {
return buildWebClient(properties.getUrl(), clientHttpConnector)
.build();
final class CredHubWebClientFactory {
private CredHubWebClientFactory() {
}
/**
* Create a {@link WebClient} configured for communication with a CredHub server.
*
* @param properties CredHub connection properties
* @param clientHttpConnector the {@link ClientHttpConnector} to use when
* creating new connections
* @param properties the CredHub connection properties
* @param clientHttpConnector the {@link ClientHttpConnector} to use when creating new
* connections
* @return a configured {@link WebClient}
*/
static WebClient createWebClient(CredHubProperties properties, ClientHttpConnector clientHttpConnector) {
return buildWebClient(properties.getUrl(), clientHttpConnector).build();
}
/**
* Create a {@link WebClient} configured for communication with a CredHub server.
* @param properties the CredHub connection properties
* @param clientHttpConnector the {@link ClientHttpConnector} to use when creating new
* connections
* @param clientRegistrationRepository a repository of OAuth2 client registrations
* @param authorizedClientRepository a repository of OAuth2 authorized clients
* @param authorizedClientRepository a repository of OAuth2 authorized clients
* @return a configured {@link WebClient}
*/
static WebClient createWebClient(CredHubProperties properties, ClientHttpConnector clientHttpConnector,
ReactiveClientRegistrationRepository clientRegistrationRepository,
ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {
ReactiveOAuth2AuthorizedClientProvider clientProvider =
buildClientProvider(clientHttpConnector);
ReactiveClientRegistrationRepository clientRegistrationRepository,
ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {
ReactiveOAuth2AuthorizedClientProvider clientProvider = buildClientProvider(clientHttpConnector);
DefaultReactiveOAuth2AuthorizedClientManager defaultClientManager =
buildClientManager(clientRegistrationRepository, authorizedClientRepository, clientProvider);
DefaultReactiveOAuth2AuthorizedClientManager defaultClientManager = buildClientManager(
clientRegistrationRepository, authorizedClientRepository, clientProvider);
return createWebClient(properties, clientHttpConnector, defaultClientManager);
}
/**
* Create a {@link WebClient} configured for communication with a CredHub server.
*
* @param properties CredHub connection properties
* @param clientHttpConnector the {@link ClientHttpConnector} to use when
* creating new connections
* @param clientManager OAuth2 client manager to use to authenticate a client
* @param properties the CredHub connection properties
* @param clientHttpConnector the {@link ClientHttpConnector} to use when creating new
* connections
* @param clientManager an OAuth2 client manager to use to authenticate a client
* @return a configured {@link WebClient}
*/
static WebClient createWebClient(CredHubProperties properties,
ClientHttpConnector clientHttpConnector,
ReactiveOAuth2AuthorizedClientManager clientManager) {
static WebClient createWebClient(CredHubProperties properties, ClientHttpConnector clientHttpConnector,
ReactiveOAuth2AuthorizedClientManager clientManager) {
ServerOAuth2AuthorizedClientExchangeFilterFunction oauth =
new ServerOAuth2AuthorizedClientExchangeFilterFunction(clientManager);
ServerOAuth2AuthorizedClientExchangeFilterFunction oauth = new ServerOAuth2AuthorizedClientExchangeFilterFunction(
clientManager);
return buildWebClient(properties.getUrl(), clientHttpConnector)
.filter(oauth)
.defaultRequest(requestHeadersSpec ->
requestHeadersSpec.attributes(
ServerOAuth2AuthorizedClientExchangeFilterFunction
.clientRegistrationId(properties.getOauth2().getRegistrationId())))
return buildWebClient(properties.getUrl(), clientHttpConnector).filter(oauth).defaultRequest(
(requestHeadersSpec) -> requestHeadersSpec.attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction
.clientRegistrationId(properties.getOauth2().getRegistrationId())))
.build();
}
private static ReactiveOAuth2AuthorizedClientProvider buildClientProvider(
ClientHttpConnector clientHttpConnector) {
return ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
.authorizationCode()
.clientCredentials(b ->
b.accessTokenResponseClient(buildTokenResponseClient(clientHttpConnector)))
private static ReactiveOAuth2AuthorizedClientProvider buildClientProvider(ClientHttpConnector clientHttpConnector) {
return ReactiveOAuth2AuthorizedClientProviderBuilder.builder().authorizationCode()
.clientCredentials((b) -> b.accessTokenResponseClient(buildTokenResponseClient(clientHttpConnector)))
.build();
}
private static WebClientReactiveClientCredentialsTokenResponseClient buildTokenResponseClient(
ClientHttpConnector clientHttpConnector) {
WebClientReactiveClientCredentialsTokenResponseClient tokenResponseClient =
new WebClientReactiveClientCredentialsTokenResponseClient();
tokenResponseClient.setWebClient(WebClient.builder()
.clientConnector(clientHttpConnector)
.build());
WebClientReactiveClientCredentialsTokenResponseClient tokenResponseClient = new WebClientReactiveClientCredentialsTokenResponseClient();
tokenResponseClient.setWebClient(WebClient.builder().clientConnector(clientHttpConnector).build());
return tokenResponseClient;
}
@@ -127,28 +116,25 @@ class CredHubWebClientFactory {
ReactiveClientRegistrationRepository clientRegistrationRepository,
ServerOAuth2AuthorizedClientRepository authorizedClientRepository,
ReactiveOAuth2AuthorizedClientProvider clientProvider) {
DefaultReactiveOAuth2AuthorizedClientManager clientManager =
new DefaultReactiveOAuth2AuthorizedClientManager(clientRegistrationRepository,
authorizedClientRepository);
DefaultReactiveOAuth2AuthorizedClientManager clientManager = new DefaultReactiveOAuth2AuthorizedClientManager(
clientRegistrationRepository, authorizedClientRepository);
clientManager.setAuthorizedClientProvider(clientProvider);
return clientManager;
}
private static WebClient.Builder buildWebClient(String baseUri, ClientHttpConnector clientHttpConnector) {
ExchangeStrategies strategies = ExchangeStrategies.builder()
.codecs(configurer -> {
ObjectMapper mapper = JsonUtils.buildObjectMapper();
ExchangeStrategies strategies = ExchangeStrategies.builder().codecs((configurer) -> {
ObjectMapper mapper = JsonUtils.buildObjectMapper();
CodecConfigurer.DefaultCodecs dc = configurer.defaultCodecs();
dc.jackson2JsonDecoder(new Jackson2JsonDecoder(mapper));
dc.jackson2JsonEncoder(new Jackson2JsonEncoder(mapper));
}).build();
CodecConfigurer.DefaultCodecs dc = configurer.defaultCodecs();
dc.jackson2JsonDecoder(new Jackson2JsonDecoder(mapper));
dc.jackson2JsonEncoder(new Jackson2JsonEncoder(mapper));
}).build();
return WebClient.builder()
.clientConnector(clientHttpConnector)
.baseUrl(baseUri)
return WebClient.builder().clientConnector(clientHttpConnector).baseUrl(baseUri)
.defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.exchangeStrategies(strategies);
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,18 +16,22 @@
package org.springframework.credhub.core;
import reactor.core.publisher.Mono;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
public class ExceptionUtils {
public final class ExceptionUtils {
private ExceptionUtils() {
}
/**
* Helper method to throw an appropriate exception if a request to CredHub
* returns with an error code.
*
* Helper method to throw an appropriate exception if a request to CredHub returns
* with an error code.
* @param response a {@link ResponseEntity} returned from {@link RestTemplate}
*/
public static void throwExceptionOnError(ResponseEntity<?> response) {
@@ -37,13 +41,13 @@ public class ExceptionUtils {
}
/**
* Helper method to return an appropriate error if a request to CredHub
* returns with an error code.
*
* @return the generated error
* Helper method to return an appropriate error if a request to CredHub returns with
* an error code.
* @param response a {@link ClientResponse} returned from {@link WebClient}
* @return the generated error
*/
public static Mono<Throwable> buildError(ClientResponse response) {
return Mono.error(new CredHubException(response.statusCode()));
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,7 +16,10 @@
package org.springframework.credhub.core;
import java.util.function.Function;
import org.reactivestreams.Publisher;
import org.springframework.credhub.core.certificate.ReactiveCredHubCertificateOperations;
import org.springframework.credhub.core.credential.ReactiveCredHubCredentialOperations;
import org.springframework.credhub.core.info.ReactiveCredHubInfoOperations;
@@ -25,64 +28,57 @@ import org.springframework.credhub.core.permission.ReactiveCredHubPermissionOper
import org.springframework.credhub.core.permissionV2.ReactiveCredHubPermissionV2Operations;
import org.springframework.web.reactive.function.client.WebClient;
import java.util.function.Function;
/**
* Specifies the main interaction with CredHub.
*
* @author Scott Frederick
*/
public interface ReactiveCredHubOperations {
/**
* Get the operations for saving, retrieving, and deleting credentials.
*
* @return the credentials operations
*/
ReactiveCredHubCredentialOperations credentials();
/**
* Get the operations for adding, retrieving, and deleting credential permissions.
*
* @return the permissions operations
*/
ReactiveCredHubPermissionOperations permissions();
/**
* Get the operations for adding, retrieving, and deleting credential permissions.
*
* @return the permissions operations
*/
ReactiveCredHubPermissionV2Operations permissionsV2();
/**
* Get the operations for retrieving, regenerating, and updating certificates.
*
* @return the certificates operations
*/
ReactiveCredHubCertificateOperations certificates();
/**
* Get the operations for interpolating service binding credentials.
*
* @return the interpolation operations
*/
ReactiveCredHubInterpolationOperations interpolation();
/**
* Get the operations for retrieving CredHub server information.
*
* @return the info operations
*/
ReactiveCredHubInfoOperations info();
/**
* Allow interaction with the configured {@link WebClient} not provided
* by other methods.
*
* Allow interaction with the configured {@link WebClient} not provided by other
* methods.
* @param callback wrapper for the callback method
* @param <V> the publisher type
* @param <T> the credential implementation type
* @return the return value from the callback method
*/
<V, T extends Publisher<V>> T doWithWebClient(Function<WebClient, ? extends T> callback);
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,7 +16,10 @@
package org.springframework.credhub.core;
import java.util.function.Function;
import org.reactivestreams.Publisher;
import org.springframework.credhub.core.certificate.ReactiveCredHubCertificateOperations;
import org.springframework.credhub.core.certificate.ReactiveCredHubCertificateTemplate;
import org.springframework.credhub.core.credential.ReactiveCredHubCredentialOperations;
@@ -38,21 +41,20 @@ import org.springframework.util.Assert;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.reactive.function.client.WebClient;
import java.util.function.Function;
/**
* Implements the main interaction with CredHub.
*
* @author Scott Frederick
*/
public class ReactiveCredHubTemplate implements ReactiveCredHubOperations {
private final WebClient webClient;
private final boolean usingOAuth2;
/**
* Create a new {@link ReactiveCredHubTemplate} using the provided {@link WebClient}.
* Intended for internal testing only.
*
* @param webClient the {@link WebClient} to use for interactions with CredHub
*/
public ReactiveCredHubTemplate(WebClient webClient) {
@@ -65,10 +67,9 @@ public class ReactiveCredHubTemplate implements ReactiveCredHubOperations {
/**
* Create a new {@link ReactiveCredHubTemplate} using the provided base URI and
* {@link ClientHttpRequestFactory}.
*
* @param credHubProperties connection properties for the CredHub server
* @param clientHttpConnector the {@link ClientHttpConnector} to use when
* creating new connections
* @param clientHttpConnector the {@link ClientHttpConnector} to use when creating new
* connections
*/
public ReactiveCredHubTemplate(CredHubProperties credHubProperties, ClientHttpConnector clientHttpConnector) {
Assert.notNull(credHubProperties, "credHubProperties must not be null");
@@ -81,16 +82,15 @@ public class ReactiveCredHubTemplate implements ReactiveCredHubOperations {
/**
* Create a new {@link ReactiveCredHubTemplate} using the provided base URI and
* {@link ClientHttpRequestFactory}.
*
* @param credHubProperties connection properties for the CredHub server
* @param clientHttpConnector the {@link ClientHttpConnector} to use when
* creating new connections
* @param clientHttpConnector the {@link ClientHttpConnector} to use when creating new
* connections
* @param clientRegistrationRepository a repository of OAuth2 client registrations
* @param authorizedClientRepository a repository of authorized OAuth2 clients
*/
public ReactiveCredHubTemplate(CredHubProperties credHubProperties, ClientHttpConnector clientHttpConnector,
ReactiveClientRegistrationRepository clientRegistrationRepository,
ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {
ReactiveClientRegistrationRepository clientRegistrationRepository,
ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {
Assert.notNull(credHubProperties, "credHubProperties must not be null");
Assert.notNull(clientHttpConnector, "clientHttpConnector must not be null");
Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository must not be null");
@@ -104,14 +104,13 @@ public class ReactiveCredHubTemplate implements ReactiveCredHubOperations {
/**
* Create a new {@link ReactiveCredHubTemplate} using the provided base URI and
* {@link ClientHttpRequestFactory}.
*
* @param credHubProperties connection properties for the CredHub server
* @param clientHttpConnector the {@link ClientHttpConnector} to use when
* creating new connections
* @param clientManager an OAuth2 authorization client manager
* @param credHubProperties connection properties for the CredHub server
* @param clientHttpConnector the {@link ClientHttpConnector} to use when creating new
* connections
* @param clientManager an OAuth2 authorization client manager
*/
public ReactiveCredHubTemplate(CredHubProperties credHubProperties, ClientHttpConnector clientHttpConnector,
ReactiveOAuth2AuthorizedClientManager clientManager) {
ReactiveOAuth2AuthorizedClientManager clientManager) {
Assert.notNull(credHubProperties, "credHubProperties must not be null");
Assert.notNull(clientHttpConnector, "clientHttpConnector must not be null");
Assert.notNull(clientManager, "clientManager must not be null");
@@ -122,7 +121,6 @@ public class ReactiveCredHubTemplate implements ReactiveCredHubOperations {
/**
* Get the operations for saving, retrieving, and deleting credentials.
*
* @return the credentials operations
*/
@Override
@@ -131,8 +129,8 @@ public class ReactiveCredHubTemplate implements ReactiveCredHubOperations {
}
/**
* Get the operations for adding, retrieving, and deleting permissions from a credential.
*
* Get the operations for adding, retrieving, and deleting permissions from a
* credential.
* @return the permissions operations
*/
@Override
@@ -141,8 +139,8 @@ public class ReactiveCredHubTemplate implements ReactiveCredHubOperations {
}
/**
* Get the operations for adding, retrieving, and deleting permissions from a credential.
*
* Get the operations for adding, retrieving, and deleting permissions from a
* credential.
* @return the permissions operations
*/
@Override
@@ -152,7 +150,6 @@ public class ReactiveCredHubTemplate implements ReactiveCredHubOperations {
/**
* Get the operations for retrieving, regenerating, and updating certificates.
*
* @return the certificates operations
*/
@Override
@@ -162,7 +159,6 @@ public class ReactiveCredHubTemplate implements ReactiveCredHubOperations {
/**
* Get the operations for interpolating service binding credentials.
*
* @return the interpolation operations
*/
@Override
@@ -172,7 +168,6 @@ public class ReactiveCredHubTemplate implements ReactiveCredHubOperations {
/**
* Get the operations for retrieving CredHub server information.
*
* @return the info operations
*/
@Override
@@ -181,9 +176,8 @@ public class ReactiveCredHubTemplate implements ReactiveCredHubOperations {
}
/**
* Allow interaction with the configured {@link WebClient} not provided
* by other methods.
*
* Allow interaction with the configured {@link WebClient} not provided by other
* methods.
* @param callback wrapper for the callback method
* @param <T> the credential implementation type
* @return the return value from the callback method
@@ -193,14 +187,15 @@ public class ReactiveCredHubTemplate implements ReactiveCredHubOperations {
Assert.notNull(callback, "callback must not be null");
try {
return callback.apply(webClient);
return callback.apply(this.webClient);
}
catch (HttpStatusCodeException e) {
throw new CredHubException(e);
catch (HttpStatusCodeException ex) {
throw new CredHubException(ex);
}
}
public boolean isUsingOAuth2() {
return this.usingOAuth2;
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -21,6 +21,7 @@ import org.springframework.web.client.RestOperations;
/**
* A callback for executing arbitrary operations on {@link RestOperations}.
*
* @param <T> the type of CredHub credential
* @author Mark Paluch
*/
public interface RestOperationsCallback<T> {
@@ -28,9 +29,9 @@ public interface RestOperationsCallback<T> {
/**
* Callback method providing a {@link RestOperations} that is configured to interact
* with the CredHub server.
*
* @param restOperations restOperations to use, must not be {@literal null}.
* @return a result object or null if none.
*/
T doWithRestOperations(RestOperations restOperations);
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,11 +16,11 @@
package org.springframework.credhub.core.certificate;
import org.springframework.credhub.support.certificate.CertificateSummary;
import java.util.List;
import org.springframework.credhub.support.CredentialName;
import org.springframework.credhub.support.certificate.CertificateCredentialDetails;
import java.util.List;
import org.springframework.credhub.support.certificate.CertificateSummary;
/**
* Specifies the interactions with CredHub to retrieve, regenerate, and update
@@ -29,51 +29,50 @@ import java.util.List;
* @author Scott Frederick
*/
public interface CredHubCertificateOperations {
/**
* Retrieve all certificates from CredHub.
*
* @return a collection of certificates
*/
List<CertificateSummary> getAll();
/**
* Retrieve a certificate using its name.
*
* @param name the name of the certificate credential; must not be {@literal null}
* @return the details of the retrieved certificate credential
*/
CertificateSummary getByName(final CredentialName name);
CertificateSummary getByName(CredentialName name);
/**
* Regenerate a certificate.
*
* @param id the CredHub-generated ID of the certificate credential; must not be {@literal null}
* and must be an ID returned by {@link #getAll()}
* or {@link #getByName(CredentialName)}
* @param id the CredHub-generated ID of the certificate credential; must not be
* {@literal null} and must be an ID returned by {@link #getAll()} or
* {@link #getByName(CredentialName)}
* @param setAsTransitional {@code true} to mark the certificate version transitional;
* {@code false} otherwise
* {@code false} otherwise
* @return the details of the certificate credential
*/
CertificateCredentialDetails regenerate(final String id, final boolean setAsTransitional);
CertificateCredentialDetails regenerate(String id, boolean setAsTransitional);
/**
* Regenerate all certificates in CredHub that were signed by the specified certificate.
*
* @param certificateName the name of the signing certificate credential; must not be {@literal null}
* Regenerate all certificates in CredHub that were signed by the specified
* certificate.
* @param certificateName the name of the signing certificate credential; must not be
* {@literal null}
* @return the names of all regenerated certificate credentials
*/
List<CredentialName> regenerate(CredentialName certificateName);
/**
* Make the specified version of a certificate the {@literal transitional} version.
*
* @param id the CredHub-generated ID of the certificate credential; must not be {@literal null}
* and must be an ID returned by {@link #getAll()}
* or {@link #getByName(CredentialName)}
* @param versionId the CredHub-generated ID of the version of the certificate credential that should be
* marked {@literal transitional}, or {@literal null} to indicate that no version
* is {@literal transitional}
* @param id the CredHub-generated ID of the certificate credential; must not be
* {@literal null} and must be an ID returned by {@link #getAll()} or
* {@link #getByName(CredentialName)}
* @param versionId the CredHub-generated ID of the version of the certificate
* credential that should be marked {@literal transitional}, or {@literal null} to
* indicate that no version is {@literal transitional}
* @return the details of the certificate credential, including all versions
*/
List<CertificateCredentialDetails> updateTransitionalVersion(final String id, final String versionId);
List<CertificateCredentialDetails> updateTransitionalVersion(String id, String versionId);
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,46 +16,54 @@
package org.springframework.credhub.core.certificate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.credhub.core.CredHubOperations;
import org.springframework.credhub.core.ExceptionUtils;
import org.springframework.credhub.support.certificate.CertificateSummary;
import org.springframework.credhub.support.certificate.CertificateSummaryData;
import org.springframework.credhub.support.CredentialName;
import org.springframework.credhub.support.certificate.CertificateCredentialDetails;
import org.springframework.credhub.support.certificate.CertificateSummary;
import org.springframework.credhub.support.certificate.CertificateSummaryData;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Implements the interactions with CredHub to retrieve, regenerate, and update
* certificates.
*
* @author Scott Frederick
* @author Scott Frederick
*/
public class CredHubCertificateTemplate implements CredHubCertificateOperations {
static final String BASE_URL_PATH = "/api/v1/certificates";
static final String NAME_URL_QUERY = BASE_URL_PATH + "?name={name}";
static final String REGENERATE_URL_PATH = BASE_URL_PATH + "/{id}/regenerate";
static final String UPDATE_TRANSITIONAL_URL_PATH = BASE_URL_PATH + "/{id}/update_transitional_version";
static final String BULK_REGENERATE_URL_PATH = "/api/v1/bulk-regenerate";
static final String TRANSITIONAL_REQUEST_FIELD = "set_as_transitional";
static final String VERSION_REQUEST_FIELD = "version";
static final String SIGNED_BY_REQUEST_FIELD = "signed_by";
static final String REGENERATED_CREDENTIALS_RESPONSE_FIELD = "regenerated_credentials";
private CredHubOperations credHubOperations;
private final CredHubOperations credHubOperations;
/**
* Create a new {@link CredHubCertificateTemplate}.
*
* @param credHubOperations the {@link CredHubOperations} to use for interactions with CredHub
* @param credHubOperations the {@link CredHubOperations} to use for interactions with
* CredHub
*/
public CredHubCertificateTemplate(CredHubOperations credHubOperations) {
this.credHubOperations = credHubOperations;
@@ -63,9 +71,9 @@ public class CredHubCertificateTemplate implements CredHubCertificateOperations
@Override
public List<CertificateSummary> getAll() {
return credHubOperations.doWithRest(restOperations -> {
ResponseEntity<CertificateSummaryData> response = restOperations
.getForEntity(BASE_URL_PATH, CertificateSummaryData.class);
return this.credHubOperations.doWithRest((restOperations) -> {
ResponseEntity<CertificateSummaryData> response = restOperations.getForEntity(BASE_URL_PATH,
CertificateSummaryData.class);
ExceptionUtils.throwExceptionOnError(response);
@@ -77,9 +85,9 @@ public class CredHubCertificateTemplate implements CredHubCertificateOperations
public CertificateSummary getByName(final CredentialName name) {
Assert.notNull(name, "certificate name must not be null");
return credHubOperations.doWithRest(restOperations -> {
ResponseEntity<CertificateSummaryData> response = restOperations
.getForEntity(NAME_URL_QUERY, CertificateSummaryData.class, name.getName());
return this.credHubOperations.doWithRest((restOperations) -> {
ResponseEntity<CertificateSummaryData> response = restOperations.getForEntity(NAME_URL_QUERY,
CertificateSummaryData.class, name.getName());
ExceptionUtils.throwExceptionOnError(response);
@@ -91,16 +99,15 @@ public class CredHubCertificateTemplate implements CredHubCertificateOperations
public CertificateCredentialDetails regenerate(final String id, final boolean setAsTransitional) {
Assert.notNull(id, "credential ID must not be null");
final ParameterizedTypeReference<CertificateCredentialDetails> ref =
new ParameterizedTypeReference<CertificateCredentialDetails>() {};
final ParameterizedTypeReference<CertificateCredentialDetails> ref = new ParameterizedTypeReference<CertificateCredentialDetails>() {
};
return credHubOperations.doWithRest(restOperations -> {
return this.credHubOperations.doWithRest((restOperations) -> {
Map<String, Boolean> request = new HashMap<>(1);
request.put(TRANSITIONAL_REQUEST_FIELD, setAsTransitional);
ResponseEntity<CertificateCredentialDetails> response =
restOperations.exchange(REGENERATE_URL_PATH, HttpMethod.POST,
new HttpEntity<Object>(request), ref, id);
ResponseEntity<CertificateCredentialDetails> response = restOperations.exchange(REGENERATE_URL_PATH,
HttpMethod.POST, new HttpEntity<Object>(request), ref, id);
ExceptionUtils.throwExceptionOnError(response);
@@ -112,16 +119,15 @@ public class CredHubCertificateTemplate implements CredHubCertificateOperations
public List<CredentialName> regenerate(final CredentialName certificateName) {
Assert.notNull(certificateName, "certificate name must not be null");
final ParameterizedTypeReference<Map<String, List<CredentialName>>> ref =
new ParameterizedTypeReference<Map<String, List<CredentialName>>>() {};
final ParameterizedTypeReference<Map<String, List<CredentialName>>> ref = new ParameterizedTypeReference<Map<String, List<CredentialName>>>() {
};
return credHubOperations.doWithRest(restOperations -> {
return this.credHubOperations.doWithRest((restOperations) -> {
Map<String, Object> request = new HashMap<>(1);
request.put(SIGNED_BY_REQUEST_FIELD, certificateName.getName());
ResponseEntity<Map<String, List<CredentialName>>> response =
restOperations.exchange(BULK_REGENERATE_URL_PATH, HttpMethod.POST,
new HttpEntity<>(request), ref);
ResponseEntity<Map<String, List<CredentialName>>> response = restOperations
.exchange(BULK_REGENERATE_URL_PATH, HttpMethod.POST, new HttpEntity<>(request), ref);
ExceptionUtils.throwExceptionOnError(response);
@@ -129,24 +135,23 @@ public class CredHubCertificateTemplate implements CredHubCertificateOperations
});
}
public List<CertificateCredentialDetails> updateTransitionalVersion(final String id,
final String versionId) {
public List<CertificateCredentialDetails> updateTransitionalVersion(final String id, final String versionId) {
Assert.notNull(id, "credential ID must not be null");
final ParameterizedTypeReference<List<CertificateCredentialDetails>> ref =
new ParameterizedTypeReference<List<CertificateCredentialDetails>>() {};
final ParameterizedTypeReference<List<CertificateCredentialDetails>> ref = new ParameterizedTypeReference<List<CertificateCredentialDetails>>() {
};
return credHubOperations.doWithRest(restOperations -> {
return this.credHubOperations.doWithRest((restOperations) -> {
Map<String, String> request = new HashMap<>(1);
request.put(VERSION_REQUEST_FIELD, versionId);
ResponseEntity<List<CertificateCredentialDetails>> response =
restOperations.exchange(UPDATE_TRANSITIONAL_URL_PATH, HttpMethod.PUT,
new HttpEntity<Object>(request), ref, id);
ResponseEntity<List<CertificateCredentialDetails>> response = restOperations
.exchange(UPDATE_TRANSITIONAL_URL_PATH, HttpMethod.PUT, new HttpEntity<Object>(request), ref, id);
ExceptionUtils.throwExceptionOnError(response);
return response.getBody();
});
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,11 +16,12 @@
package org.springframework.credhub.core.certificate;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.springframework.credhub.support.CredentialName;
import org.springframework.credhub.support.certificate.CertificateCredentialDetails;
import org.springframework.credhub.support.certificate.CertificateSummary;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/**
* Specifies the interactions with CredHub to retrieve, regenerate, and update
@@ -29,51 +30,50 @@ import reactor.core.publisher.Mono;
* @author Scott Frederick
*/
public interface ReactiveCredHubCertificateOperations {
/**
* Retrieve all certificates from CredHub.
*
* @return a collection of certificates
*/
Flux<CertificateSummary> getAll();
/**
* Retrieve a certificate using its name.
*
* @param name the name of the certificate credential; must not be {@literal null}
* @return the details of the retrieved certificate credential
*/
Mono<CertificateSummary> getByName(final CredentialName name);
Mono<CertificateSummary> getByName(CredentialName name);
/**
* Regenerate a certificate.
*
* @param id the CredHub-generated ID of the certificate credential; must not be {@literal null}
* and must be an ID returned by {@link #getAll()}
* or {@link #getByName(CredentialName)}
* @param id the CredHub-generated ID of the certificate credential; must not be
* {@literal null} and must be an ID returned by {@link #getAll()} or
* {@link #getByName(CredentialName)}
* @param setAsTransitional {@code true} to mark the certificate version transitional;
* {@code false} otherwise
* {@code false} otherwise
* @return the details of the certificate credential
*/
Mono<CertificateCredentialDetails> regenerate(final String id, final boolean setAsTransitional);
Mono<CertificateCredentialDetails> regenerate(String id, boolean setAsTransitional);
/**
* Regenerate all certificates in CredHub that were signed by the specified certificate.
*
* @param certificateName the name of the signing certificate credential; must not be {@literal null}
* Regenerate all certificates in CredHub that were signed by the specified
* certificate.
* @param certificateName the name of the signing certificate credential; must not be
* {@literal null}
* @return the names of all regenerated certificate credentials
*/
Flux<CredentialName> regenerate(CredentialName certificateName);
/**
* Make the specified version of a certificate the {@literal transitional} version.
*
* @param id the CredHub-generated ID of the certificate credential; must not be {@literal null}
* and must be an ID returned by {@link #getAll()}
* or {@link #getByName(CredentialName)}
* @param versionId the CredHub-generated ID of the version of the certificate credential that should be
* marked {@literal transitional}, or {@literal null} to indicate that no version
* is {@literal transitional}
* @param id the CredHub-generated ID of the certificate credential; must not be
* {@literal null} and must be an ID returned by {@link #getAll()} or
* {@link #getByName(CredentialName)}
* @param versionId the CredHub-generated ID of the version of the certificate
* credential that should be marked {@literal transitional}, or {@literal null} to
* indicate that no version is {@literal transitional}
* @return the details of the certificate credential, including all versions
*/
Flux<CertificateCredentialDetails> updateTransitionalVersion(final String id, final String versionId);
Flux<CertificateCredentialDetails> updateTransitionalVersion(String id, String versionId);
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,6 +16,13 @@
package org.springframework.credhub.core.certificate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.credhub.core.ExceptionUtils;
import org.springframework.credhub.core.ReactiveCredHubOperations;
@@ -25,37 +32,39 @@ import org.springframework.credhub.support.certificate.CertificateSummary;
import org.springframework.credhub.support.certificate.CertificateSummaryData;
import org.springframework.http.HttpStatus;
import org.springframework.util.Assert;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Implements the interactions with CredHub to retrieve, regenerate, and update
* certificates.
*
* @author Scott Frederick
* @author Scott Frederick
*/
public class ReactiveCredHubCertificateTemplate implements ReactiveCredHubCertificateOperations {
private static final String BASE_URL_PATH = "/api/v1/certificates";
private static final String NAME_URL_QUERY = BASE_URL_PATH + "?name={name}";
private static final String REGENERATE_URL_PATH = BASE_URL_PATH + "/{id}/regenerate";
private static final String UPDATE_TRANSITIONAL_URL_PATH = BASE_URL_PATH + "/{id}/update_transitional_version";
private static final String BULK_REGENERATE_URL_PATH = "/api/v1/bulk-regenerate";
private static final String TRANSITIONAL_REQUEST_FIELD = "set_as_transitional";
private static final String VERSION_REQUEST_FIELD = "version";
private static final String SIGNED_BY_REQUEST_FIELD = "signed_by";
private static final String REGENERATED_CREDENTIALS_RESPONSE_FIELD = "regenerated_credentials";
private ReactiveCredHubOperations credHubOperations;
private final ReactiveCredHubOperations credHubOperations;
/**
* Create a new {@link ReactiveCredHubCertificateTemplate}.
*
* @param credHubOperations the {@link ReactiveCredHubOperations} to use for interactions with CredHub
* @param credHubOperations the {@link ReactiveCredHubOperations} to use for
* interactions with CredHub
*/
public ReactiveCredHubCertificateTemplate(ReactiveCredHubOperations credHubOperations) {
this.credHubOperations = credHubOperations;
@@ -63,81 +72,61 @@ public class ReactiveCredHubCertificateTemplate implements ReactiveCredHubCertif
@Override
public Flux<CertificateSummary> getAll() {
return credHubOperations.doWithWebClient(webClient -> webClient
.get()
.uri(BASE_URL_PATH)
.retrieve()
.onStatus(HttpStatus::isError, ExceptionUtils::buildError)
.bodyToMono(CertificateSummaryData.class)
.flatMapMany(data -> Flux.fromIterable(data.getCertificates())));
return this.credHubOperations.doWithWebClient((webClient) -> webClient.get().uri(BASE_URL_PATH).retrieve()
.onStatus(HttpStatus::isError, ExceptionUtils::buildError).bodyToMono(CertificateSummaryData.class)
.flatMapMany((data) -> Flux.fromIterable(data.getCertificates())));
}
@Override
public Mono<CertificateSummary> getByName(final CredentialName name) {
Assert.notNull(name, "certificate name must not be null");
return credHubOperations.doWithWebClient(webClient -> webClient
.get()
.uri(NAME_URL_QUERY, name.getName())
.retrieve()
.onStatus(HttpStatus::isError, ExceptionUtils::buildError)
return this.credHubOperations.doWithWebClient((webClient) -> webClient.get().uri(NAME_URL_QUERY, name.getName())
.retrieve().onStatus(HttpStatus::isError, ExceptionUtils::buildError)
.bodyToMono(CertificateSummaryData.class)
.flatMapMany(data -> Flux.fromIterable(data.getCertificates())))
.single();
.flatMapMany((data) -> Flux.fromIterable(data.getCertificates()))).single();
}
@Override
public Mono<CertificateCredentialDetails> regenerate(final String id, final boolean setAsTransitional) {
Assert.notNull(id, "credential ID must not be null");
final ParameterizedTypeReference<CertificateCredentialDetails> ref =
new ParameterizedTypeReference<CertificateCredentialDetails>() {};
final ParameterizedTypeReference<CertificateCredentialDetails> ref = new ParameterizedTypeReference<CertificateCredentialDetails>() {
};
Map<String, Boolean> request = new HashMap<>(1);
request.put(TRANSITIONAL_REQUEST_FIELD, setAsTransitional);
return credHubOperations.doWithWebClient(webClient -> webClient
.post()
.uri(REGENERATE_URL_PATH, id)
.bodyValue(request)
.retrieve()
.onStatus(HttpStatus::isError, ExceptionUtils::buildError)
.bodyToMono(ref));
return this.credHubOperations
.doWithWebClient((webClient) -> webClient.post().uri(REGENERATE_URL_PATH, id).bodyValue(request)
.retrieve().onStatus(HttpStatus::isError, ExceptionUtils::buildError).bodyToMono(ref));
}
@Override
public Flux<CredentialName> regenerate(final CredentialName certificateName) {
Assert.notNull(certificateName, "certificate name must not be null");
final ParameterizedTypeReference<Map<String, List<CredentialName>>> ref =
new ParameterizedTypeReference<Map<String, List<CredentialName>>>() {};
final ParameterizedTypeReference<Map<String, List<CredentialName>>> ref = new ParameterizedTypeReference<Map<String, List<CredentialName>>>() {
};
Map<String, Object> request = new HashMap<>(1);
request.put(SIGNED_BY_REQUEST_FIELD, certificateName.getName());
return credHubOperations.doWithWebClient(webClient -> webClient
.post()
.uri(BULK_REGENERATE_URL_PATH)
.bodyValue(request)
.retrieve()
.onStatus(HttpStatus::isError, ExceptionUtils::buildError)
.bodyToFlux(ref)
.flatMap(body -> Flux.fromIterable(body.get(REGENERATED_CREDENTIALS_RESPONSE_FIELD))));
return this.credHubOperations.doWithWebClient((webClient) -> webClient.post().uri(BULK_REGENERATE_URL_PATH)
.bodyValue(request).retrieve().onStatus(HttpStatus::isError, ExceptionUtils::buildError).bodyToFlux(ref)
.flatMap((body) -> Flux.fromIterable(body.get(REGENERATED_CREDENTIALS_RESPONSE_FIELD))));
}
public Flux<CertificateCredentialDetails> updateTransitionalVersion(final String id,
final String versionId) {
public Flux<CertificateCredentialDetails> updateTransitionalVersion(final String id, final String versionId) {
Assert.notNull(id, "credential ID must not be null");
Map<String, String> request = new HashMap<>(1);
request.put(VERSION_REQUEST_FIELD, versionId);
return credHubOperations.doWithWebClient(webClient -> webClient
.put()
.uri(UPDATE_TRANSITIONAL_URL_PATH, id)
.bodyValue(request)
.retrieve()
.onStatus(HttpStatus::isError, ExceptionUtils::buildError)
.bodyToFlux(CertificateCredentialDetails.class));
return this.credHubOperations
.doWithWebClient((webClient) -> webClient.put().uri(UPDATE_TRANSITIONAL_URL_PATH, id).bodyValue(request)
.retrieve().onStatus(HttpStatus::isError, ExceptionUtils::buildError)
.bodyToFlux(CertificateCredentialDetails.class));
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -17,4 +17,4 @@
/**
* Core API abstractions for certificate operations.
*/
package org.springframework.credhub.core.certificate;
package org.springframework.credhub.core.certificate;

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,6 +16,8 @@
package org.springframework.credhub.core.credential;
import java.util.List;
import org.springframework.credhub.support.CredentialDetails;
import org.springframework.credhub.support.CredentialName;
import org.springframework.credhub.support.CredentialPath;
@@ -23,114 +25,105 @@ import org.springframework.credhub.support.CredentialRequest;
import org.springframework.credhub.support.CredentialSummary;
import org.springframework.credhub.support.ParametersRequest;
import java.util.List;
/**
* Specifies the interactions with CredHub to save, generate, retrieve,
* and delete credentials.
* Specifies the interactions with CredHub to save, generate, retrieve, and delete
* credentials.
*
* @author Scott Frederick
*/
public interface CredHubCredentialOperations {
/**
* Write a new credential to CredHub, or overwrite an existing credential with a new
* value.
*
* @param credentialRequest the credential to write to CredHub; must not be {@literal null}
* @param credentialRequest the credential to write to CredHub; must not be
* {@literal null}
* @param <T> the credential implementation type
* @return the details of the written credential
*/
<T> CredentialDetails<T> write(final CredentialRequest<T> credentialRequest);
<T> CredentialDetails<T> write(CredentialRequest<T> credentialRequest);
/**
* Generate a new credential in CredHub, or overwrite an existing credential with a new
* generated value.
*
* @param parametersRequest the parameters of the new credential to generate in CredHub;
* must not be {@literal null}
* Generate a new credential in CredHub, or overwrite an existing credential with a
* new generated value.
* @param parametersRequest the parameters of the new credential to generate in
* CredHub; must not be {@literal null}
* @param <T> the credential implementation type
* @param <P> the credential parameter implementation type
* @return the details of the generated credential
*/
<T, P> CredentialDetails<T> generate(final ParametersRequest<P> parametersRequest);
<T, P> CredentialDetails<T> generate(ParametersRequest<P> parametersRequest);
/**
* Regenerate a credential in CredHub. Only credentials that were previously generated can be
* re-generated.
*
* Regenerate a credential in CredHub. Only credentials that were previously generated
* can be re-generated.
* @param <T> the credential implementation type
* @param name the name of the credential; must not be {@literal null}
* @param credentialType the type of the credential to be regenerated; must not be {@literal null}
* @param credentialType the type of the credential to be regenerated; must not be
* {@literal null}
* @return the details of the regenerated credential
*/
<T> CredentialDetails<T> regenerate(final CredentialName name, Class<T> credentialType);
<T> CredentialDetails<T> regenerate(CredentialName name, Class<T> credentialType);
/**
* Retrieve a credential using its ID, as returned in a write request.
*
* @param id the ID of the credential; must not be {@literal null}
* @param credentialType the type of the credential to be retrieved; must not be {@literal null}
* @param credentialType the type of the credential to be retrieved; must not be
* {@literal null}
* @param <T> the credential implementation type
* @return the details of the retrieved credential
*/
<T> CredentialDetails<T> getById(final String id, final Class<T> credentialType);
<T> CredentialDetails<T> getById(String id, Class<T> credentialType);
/**
* Retrieve a credential using its name, as passed to a write request.
* Only the current credential value will be returned.
*
* Retrieve a credential using its name, as passed to a write request. Only the
* current credential value will be returned.
* @param name the name of the credential; must not be {@literal null}
* @param credentialType the type of credential expected to be returned
* @param <T> the credential implementation type
* @return the details of the retrieved credential
*/
<T> CredentialDetails<T> getByName(final CredentialName name, final Class<T> credentialType);
<T> CredentialDetails<T> getByName(CredentialName name, Class<T> credentialType);
/**
* Retrieve a credential using its name, as passed to a write request.
* A collection of all stored values for the named credential will be returned,
* including historical values.
*
* Retrieve a credential using its name, as passed to a write request. A collection of
* all stored values for the named credential will be returned, including historical
* values.
* @param name the name of the credential; must not be {@literal null}
* @param credentialType the type of credential expected to be returned
* @param <T> the credential implementation type
* @return the details of the retrieved credential, including history
*/
<T> List<CredentialDetails<T>> getByNameWithHistory(final CredentialName name, final Class<T> credentialType);
<T> List<CredentialDetails<T>> getByNameWithHistory(CredentialName name, Class<T> credentialType);
/**
* Retrieve a credential using its name, as passed to a write request.
* A collection of stored values for the named credential will be returned,
* with the specified number of historical values.
*
* Retrieve a credential using its name, as passed to a write request. A collection of
* stored values for the named credential will be returned, with the specified number
* of historical values.
* @param name the name of the credential; must not be {@literal null}
* @param versions the number of historical versions to retrieve
* @param credentialType the type of credential expected to be returned
* @param <T> the credential implementation type
* @return the details of the retrieved credential, including history
*/
<T> List<CredentialDetails<T>> getByNameWithHistory(final CredentialName name, int versions,
final Class<T> credentialType);
<T> List<CredentialDetails<T>> getByNameWithHistory(CredentialName name, int versions, Class<T> credentialType);
/**
* Find a credential using a full or partial name.
*
* @param name the name of the credential; must not be {@literal null}
* @return a summary of the credential search results
*/
List<CredentialSummary> findByName(final CredentialName name);
List<CredentialSummary> findByName(CredentialName name);
/**
* Find a credential using a path.
*
* @param path the path to the credential; must not be {@literal null}
* @return a summary of the credential search results
*/
List<CredentialSummary> findByPath(final String path);
List<CredentialSummary> findByPath(String path);
/**
* Retrieve a collection of all paths that contain credentials.
*
* @return a collection of paths
* @deprecated as of CredHub 2.0 this operation is not supported
*/
@@ -138,8 +131,8 @@ public interface CredHubCredentialOperations {
/**
* Delete a credential by its full name.
*
* @param name the name of the credential; must not be {@literal null}
*/
void deleteByName(final CredentialName name);
void deleteByName(CredentialName name);
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,6 +16,10 @@
package org.springframework.credhub.core.credential;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.credhub.core.CredHubOperations;
import org.springframework.credhub.core.ExceptionUtils;
@@ -33,35 +37,39 @@ import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Implements the interactions with CredHub to save, retrieve,
* and delete credentials.
* Implements the interactions with CredHub to save, retrieve, and delete credentials.
*
* @author Scott Frederick
* @author Scott Frederick
*/
public class CredHubCredentialTemplate implements CredHubCredentialOperations {
static final String BASE_URL_PATH = "/api/v1/data";
static final String ID_URL_PATH = BASE_URL_PATH + "/{id}";
static final String NAME_URL_QUERY = BASE_URL_PATH + "?name={name}";
static final String NAME_URL_QUERY_CURRENT = NAME_URL_QUERY + "&current=true";
static final String NAME_URL_QUERY_VERSIONS = NAME_URL_QUERY + "&versions={versions}";
static final String NAME_LIKE_URL_QUERY = BASE_URL_PATH + "?name-like={name}";
static final String PATH_URL_QUERY = BASE_URL_PATH + "?path={path}";
static final String SHOW_ALL_URL_QUERY = BASE_URL_PATH + "?paths=true";
static final String REGENERATE_URL_PATH = "/api/v1/regenerate";
static final String NAME_REQUEST_FIELD = "name";
private CredHubOperations credHubOperations;
private final CredHubOperations credHubOperations;
/**
* Create a new {@link CredHubCredentialTemplate}.
*
* @param credHubOperations the {@link CredHubOperations} to use for interactions with CredHub
* @param credHubOperations the {@link CredHubOperations} to use for interactions with
* CredHub
*/
public CredHubCredentialTemplate(CredHubOperations credHubOperations) {
this.credHubOperations = credHubOperations;
@@ -71,13 +79,12 @@ public class CredHubCredentialTemplate implements CredHubCredentialOperations {
public <T> CredentialDetails<T> write(final CredentialRequest<T> credentialRequest) {
Assert.notNull(credentialRequest, "credentialRequest must not be null");
final ParameterizedTypeReference<CredentialDetails<T>> ref =
new ParameterizedTypeReference<CredentialDetails<T>>() {};
final ParameterizedTypeReference<CredentialDetails<T>> ref = new ParameterizedTypeReference<CredentialDetails<T>>() {
};
return credHubOperations.doWithRest(restOperations -> {
ResponseEntity<CredentialDetails<T>> response =
restOperations.exchange(BASE_URL_PATH, HttpMethod.PUT,
new HttpEntity<>(credentialRequest), ref);
return this.credHubOperations.doWithRest((restOperations) -> {
ResponseEntity<CredentialDetails<T>> response = restOperations.exchange(BASE_URL_PATH, HttpMethod.PUT,
new HttpEntity<>(credentialRequest), ref);
ExceptionUtils.throwExceptionOnError(response);
@@ -89,13 +96,12 @@ public class CredHubCredentialTemplate implements CredHubCredentialOperations {
public <T, P> CredentialDetails<T> generate(final ParametersRequest<P> parametersRequest) {
Assert.notNull(parametersRequest, "parametersRequest must not be null");
final ParameterizedTypeReference<CredentialDetails<T>> ref =
new ParameterizedTypeReference<CredentialDetails<T>>() {};
final ParameterizedTypeReference<CredentialDetails<T>> ref = new ParameterizedTypeReference<CredentialDetails<T>>() {
};
return credHubOperations.doWithRest(restOperations -> {
ResponseEntity<CredentialDetails<T>> response =
restOperations.exchange(BASE_URL_PATH, HttpMethod.POST,
new HttpEntity<>(parametersRequest), ref);
return this.credHubOperations.doWithRest((restOperations) -> {
ResponseEntity<CredentialDetails<T>> response = restOperations.exchange(BASE_URL_PATH, HttpMethod.POST,
new HttpEntity<>(parametersRequest), ref);
ExceptionUtils.throwExceptionOnError(response);
@@ -108,16 +114,15 @@ public class CredHubCredentialTemplate implements CredHubCredentialOperations {
Assert.notNull(name, "credential name must not be null");
Assert.notNull(credentialType, "credential type must not be null");
final ParameterizedTypeReference<CredentialDetails<T>> ref =
new ParameterizedTypeReference<CredentialDetails<T>>() {};
final ParameterizedTypeReference<CredentialDetails<T>> ref = new ParameterizedTypeReference<CredentialDetails<T>>() {
};
return credHubOperations.doWithRest(restOperations -> {
return this.credHubOperations.doWithRest((restOperations) -> {
Map<String, Object> request = new HashMap<>(1);
request.put(NAME_REQUEST_FIELD, name.getName());
ResponseEntity<CredentialDetails<T>> response =
restOperations.exchange(REGENERATE_URL_PATH, HttpMethod.POST,
new HttpEntity<>(request), ref);
ResponseEntity<CredentialDetails<T>> response = restOperations.exchange(REGENERATE_URL_PATH,
HttpMethod.POST, new HttpEntity<>(request), ref);
ExceptionUtils.throwExceptionOnError(response);
@@ -130,12 +135,12 @@ public class CredHubCredentialTemplate implements CredHubCredentialOperations {
Assert.notNull(id, "credential id must not be null");
Assert.notNull(credentialType, "credential type must not be null");
final ParameterizedTypeReference<CredentialDetails<T>> ref =
new ParameterizedTypeReference<CredentialDetails<T>>() {};
final ParameterizedTypeReference<CredentialDetails<T>> ref = new ParameterizedTypeReference<CredentialDetails<T>>() {
};
return credHubOperations.doWithRest(restOperations -> {
ResponseEntity<CredentialDetails<T>> response =
restOperations.exchange(ID_URL_PATH, HttpMethod.GET, null, ref, id);
return this.credHubOperations.doWithRest((restOperations) -> {
ResponseEntity<CredentialDetails<T>> response = restOperations.exchange(ID_URL_PATH, HttpMethod.GET, null,
ref, id);
ExceptionUtils.throwExceptionOnError(response);
@@ -148,13 +153,12 @@ public class CredHubCredentialTemplate implements CredHubCredentialOperations {
Assert.notNull(name, "credential name must not be null");
Assert.notNull(credentialType, "credential type must not be null");
final ParameterizedTypeReference<CredentialDetailsData<T>> ref =
new ParameterizedTypeReference<CredentialDetailsData<T>>() {};
final ParameterizedTypeReference<CredentialDetailsData<T>> ref = new ParameterizedTypeReference<CredentialDetailsData<T>>() {
};
return credHubOperations.doWithRest(restOperations -> {
ResponseEntity<CredentialDetailsData<T>> response =
restOperations.exchange(NAME_URL_QUERY_CURRENT, HttpMethod.GET,
null, ref, name.getName());
return this.credHubOperations.doWithRest((restOperations) -> {
ResponseEntity<CredentialDetailsData<T>> response = restOperations.exchange(NAME_URL_QUERY_CURRENT,
HttpMethod.GET, null, ref, name.getName());
ExceptionUtils.throwExceptionOnError(response);
@@ -163,16 +167,17 @@ public class CredHubCredentialTemplate implements CredHubCredentialOperations {
}
@Override
public <T> List<CredentialDetails<T>> getByNameWithHistory(final CredentialName name, final Class<T> credentialType) {
public <T> List<CredentialDetails<T>> getByNameWithHistory(final CredentialName name,
final Class<T> credentialType) {
Assert.notNull(name, "credential name must not be null");
Assert.notNull(credentialType, "credential type must not be null");
final ParameterizedTypeReference<CredentialDetailsData<T>> ref =
new ParameterizedTypeReference<CredentialDetailsData<T>>() {};
final ParameterizedTypeReference<CredentialDetailsData<T>> ref = new ParameterizedTypeReference<CredentialDetailsData<T>>() {
};
return credHubOperations.doWithRest(restOperations -> {
ResponseEntity<CredentialDetailsData<T>> response =
restOperations.exchange(NAME_URL_QUERY, HttpMethod.GET, null, ref, name.getName());
return this.credHubOperations.doWithRest((restOperations) -> {
ResponseEntity<CredentialDetailsData<T>> response = restOperations.exchange(NAME_URL_QUERY, HttpMethod.GET,
null, ref, name.getName());
ExceptionUtils.throwExceptionOnError(response);
@@ -182,17 +187,16 @@ public class CredHubCredentialTemplate implements CredHubCredentialOperations {
@Override
public <T> List<CredentialDetails<T>> getByNameWithHistory(final CredentialName name, final int versions,
final Class<T> credentialType) {
final Class<T> credentialType) {
Assert.notNull(name, "credential name must not be null");
Assert.notNull(credentialType, "credential type must not be null");
final ParameterizedTypeReference<CredentialDetailsData<T>> ref =
new ParameterizedTypeReference<CredentialDetailsData<T>>() {};
final ParameterizedTypeReference<CredentialDetailsData<T>> ref = new ParameterizedTypeReference<CredentialDetailsData<T>>() {
};
return credHubOperations.doWithRest(restOperations -> {
ResponseEntity<CredentialDetailsData<T>> response =
restOperations.exchange(NAME_URL_QUERY_VERSIONS, HttpMethod.GET, null, ref,
name.getName(), versions);
return this.credHubOperations.doWithRest((restOperations) -> {
ResponseEntity<CredentialDetailsData<T>> response = restOperations.exchange(NAME_URL_QUERY_VERSIONS,
HttpMethod.GET, null, ref, name.getName(), versions);
ExceptionUtils.throwExceptionOnError(response);
@@ -204,10 +208,9 @@ public class CredHubCredentialTemplate implements CredHubCredentialOperations {
public List<CredentialSummary> findByName(final CredentialName name) {
Assert.notNull(name, "credential name must not be null");
return credHubOperations.doWithRest(restOperations -> {
ResponseEntity<CredentialSummaryData> response = restOperations
.getForEntity(NAME_LIKE_URL_QUERY,
CredentialSummaryData.class, name.getName());
return this.credHubOperations.doWithRest((restOperations) -> {
ResponseEntity<CredentialSummaryData> response = restOperations.getForEntity(NAME_LIKE_URL_QUERY,
CredentialSummaryData.class, name.getName());
ExceptionUtils.throwExceptionOnError(response);
@@ -219,10 +222,9 @@ public class CredHubCredentialTemplate implements CredHubCredentialOperations {
public List<CredentialSummary> findByPath(final String path) {
Assert.notNull(path, "credential path must not be null");
return credHubOperations.doWithRest(restOperations -> {
ResponseEntity<CredentialSummaryData> response = restOperations
.getForEntity(PATH_URL_QUERY, CredentialSummaryData.class,
path);
return this.credHubOperations.doWithRest((restOperations) -> {
ResponseEntity<CredentialSummaryData> response = restOperations.getForEntity(PATH_URL_QUERY,
CredentialSummaryData.class, path);
ExceptionUtils.throwExceptionOnError(response);
@@ -233,9 +235,9 @@ public class CredHubCredentialTemplate implements CredHubCredentialOperations {
@Override
@Deprecated
public List<CredentialPath> getAllPaths() {
return credHubOperations.doWithRest(restOperations -> {
ResponseEntity<CredentialPathData> response = restOperations
.getForEntity(SHOW_ALL_URL_QUERY, CredentialPathData.class);
return this.credHubOperations.doWithRest((restOperations) -> {
ResponseEntity<CredentialPathData> response = restOperations.getForEntity(SHOW_ALL_URL_QUERY,
CredentialPathData.class);
ExceptionUtils.throwExceptionOnError(response);
@@ -247,9 +249,10 @@ public class CredHubCredentialTemplate implements CredHubCredentialOperations {
public void deleteByName(final CredentialName name) {
Assert.notNull(name, "credential name must not be null");
credHubOperations.doWithRest(restOperations -> {
this.credHubOperations.doWithRest((restOperations) -> {
restOperations.delete(NAME_URL_QUERY, name.getName());
return null;
});
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,124 +16,119 @@
package org.springframework.credhub.core.credential;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.springframework.credhub.support.CredentialDetails;
import org.springframework.credhub.support.CredentialName;
import org.springframework.credhub.support.CredentialRequest;
import org.springframework.credhub.support.CredentialSummary;
import org.springframework.credhub.support.ParametersRequest;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/**
* Specifies the interactions with CredHub to save, generate, retrieve,
* and delete credentials.
* Specifies the interactions with CredHub to save, generate, retrieve, and delete
* credentials.
*
* @author Scott Frederick
*/
public interface ReactiveCredHubCredentialOperations {
/**
* Write a new credential to CredHub, or overwrite an existing credential with a new
* value.
*
* @param credentialRequest the credential to write to CredHub; must not be {@literal null}
* @param credentialRequest the credential to write to CredHub; must not be
* {@literal null}
* @param <T> the credential implementation type
* @return the details of the written credential
*/
<T> Mono<CredentialDetails<T>> write(final CredentialRequest<T> credentialRequest);
<T> Mono<CredentialDetails<T>> write(CredentialRequest<T> credentialRequest);
/**
* Generate a new credential in CredHub, or overwrite an existing credential with a new
* generated value.
*
* @param parametersRequest the parameters of the new credential to generate in CredHub;
* must not be {@literal null}
* @param credentialType the type of the credential to be regenerated; must not be {@literal null}
* Generate a new credential in CredHub, or overwrite an existing credential with a
* new generated value.
* @param parametersRequest the parameters of the new credential to generate in
* CredHub; must not be {@literal null}
* @param credentialType the type of the credential to be regenerated; must not be
* {@literal null}
* @param <T> the credential implementation type
* @param <P> the credential parameter implementation type
* @return the details of the generated credential
*/
<T, P> Mono<CredentialDetails<T>> generate(final ParametersRequest<P> parametersRequest,
Class<T> credentialType);
<T, P> Mono<CredentialDetails<T>> generate(ParametersRequest<P> parametersRequest, Class<T> credentialType);
/**
* Regenerate a credential in CredHub. Only credentials that were previously generated can be
* re-generated.
*
* Regenerate a credential in CredHub. Only credentials that were previously generated
* can be re-generated.
* @param name the name of the credential; must not be {@literal null}
* @param credentialType the type of the credential to be regenerated; must not be {@literal null}
* @param credentialType the type of the credential to be regenerated; must not be
* {@literal null}
* @param <T> the credential implementation type
* @return the details of the regenerated credential
*/
<T> Mono<CredentialDetails<T>> regenerate(final CredentialName name, Class<T> credentialType);
<T> Mono<CredentialDetails<T>> regenerate(CredentialName name, Class<T> credentialType);
/**
* Retrieve a credential using its ID, as returned in a write request.
*
* @param id the ID of the credential; must not be {@literal null}
* @param credentialType the type of the credential to be retrieved; must not be {@literal null}
* @param credentialType the type of the credential to be retrieved; must not be
* {@literal null}
* @param <T> the credential implementation type
* @return the details of the retrieved credential
*/
<T> Mono<CredentialDetails<T>> getById(final String id, final Class<T> credentialType);
<T> Mono<CredentialDetails<T>> getById(String id, Class<T> credentialType);
/**
* Retrieve a credential using its name, as passed to a write request.
* Only the current credential value will be returned.
*
* Retrieve a credential using its name, as passed to a write request. Only the
* current credential value will be returned.
* @param name the name of the credential; must not be {@literal null}
* @param credentialType the type of credential expected to be returned
* @param <T> the credential implementation type
* @return the details of the retrieved credential
*/
<T> Mono<CredentialDetails<T>> getByName(final CredentialName name, final Class<T> credentialType);
<T> Mono<CredentialDetails<T>> getByName(CredentialName name, Class<T> credentialType);
/**
* Retrieve a credential using its name, as passed to a write request.
* A collection of all stored values for the named credential will be returned,
* including historical values.
*
* Retrieve a credential using its name, as passed to a write request. A collection of
* all stored values for the named credential will be returned, including historical
* values.
* @param name the name of the credential; must not be {@literal null}
* @param credentialType the type of credential expected to be returned
* @param <T> the credential implementation type
* @return the details of the retrieved credential, including history
*/
<T> Flux<CredentialDetails<T>> getByNameWithHistory(final CredentialName name, final Class<T> credentialType);
<T> Flux<CredentialDetails<T>> getByNameWithHistory(CredentialName name, Class<T> credentialType);
/**
* Retrieve a credential using its name, as passed to a write request.
* A collection of stored values for the named credential will be returned,
* with the specified number of historical values.
*
* Retrieve a credential using its name, as passed to a write request. A collection of
* stored values for the named credential will be returned, with the specified number
* of historical values.
* @param name the name of the credential; must not be {@literal null}
* @param versions the number of historical versions to retrieve
* @param credentialType the type of credential expected to be returned
* @param <T> the credential implementation type
* @return the details of the retrieved credential, including history
*/
<T> Flux<CredentialDetails<T>> getByNameWithHistory(final CredentialName name, int versions,
final Class<T> credentialType);
<T> Flux<CredentialDetails<T>> getByNameWithHistory(CredentialName name, int versions, Class<T> credentialType);
/**
* Find a credential using a full or partial name.
*
* @param name the name of the credential; must not be {@literal null}
* @return a summary of the credential search results
*/
Flux<CredentialSummary> findByName(final CredentialName name);
Flux<CredentialSummary> findByName(CredentialName name);
/**
* Find a credential using a path.
*
* @param path the path to the credential; must not be {@literal null}
* @return a summary of the credential search results
*/
Flux<CredentialSummary> findByPath(final String path);
Flux<CredentialSummary> findByPath(String path);
/**
* Delete a credential by its full name.
*
* @param name the name of the credential; must not be {@literal null}
* @return an empty {@code Mono}
*/
Mono<Void> deleteByName(final CredentialName name);
Mono<Void> deleteByName(CredentialName name);
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,6 +16,12 @@
package org.springframework.credhub.core.credential;
import java.util.HashMap;
import java.util.Map;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.credhub.core.ExceptionUtils;
import org.springframework.credhub.core.ReactiveCredHubOperations;
@@ -28,36 +34,38 @@ import org.springframework.credhub.support.CredentialSummaryData;
import org.springframework.credhub.support.ParametersRequest;
import org.springframework.http.HttpStatus;
import org.springframework.util.Assert;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.HashMap;
import java.util.Map;
/**
* Implements the interactions with CredHub to save, retrieve,
* and delete credentials.
* Implements the interactions with CredHub to save, retrieve, and delete credentials.
*
* @author Scott Frederick
* @author Scott Frederick
*/
public class ReactiveCredHubCredentialTemplate implements ReactiveCredHubCredentialOperations {
private static final String BASE_URL_PATH = "/api/v1/data";
private static final String ID_URL_PATH = BASE_URL_PATH + "/{id}";
private static final String NAME_URL_QUERY = BASE_URL_PATH + "?name={name}";
private static final String NAME_URL_QUERY_CURRENT = NAME_URL_QUERY + "&current=true";
private static final String NAME_URL_QUERY_VERSIONS = NAME_URL_QUERY + "&versions={versions}";
private static final String NAME_LIKE_URL_QUERY = BASE_URL_PATH + "?name-like={name}";
private static final String PATH_URL_QUERY = BASE_URL_PATH + "?path={path}";
private static final String REGENERATE_URL_PATH = "/api/v1/regenerate";
private static final String NAME_REQUEST_FIELD = "name";
private ReactiveCredHubOperations credHubOperations;
private final ReactiveCredHubOperations credHubOperations;
/**
* Create a new {@link ReactiveCredHubCredentialTemplate}.
*
* @param credHubOperations the {@link ReactiveCredHubOperations} to use for interactions with CredHub
* @param credHubOperations the {@link ReactiveCredHubOperations} to use for
* interactions with CredHub
*/
public ReactiveCredHubCredentialTemplate(ReactiveCredHubOperations credHubOperations) {
this.credHubOperations = credHubOperations;
@@ -67,33 +75,25 @@ public class ReactiveCredHubCredentialTemplate implements ReactiveCredHubCredent
public <T> Mono<CredentialDetails<T>> write(final CredentialRequest<T> credentialRequest) {
Assert.notNull(credentialRequest, "credentialRequest must not be null");
final ParameterizedTypeReference<CredentialDetails<T>> ref =
new ParameterizedTypeReference<CredentialDetails<T>>() {};
final ParameterizedTypeReference<CredentialDetails<T>> ref = new ParameterizedTypeReference<CredentialDetails<T>>() {
};
return credHubOperations.doWithWebClient(webClient -> webClient
.put()
.uri(BASE_URL_PATH)
.bodyValue(credentialRequest)
.retrieve()
.onStatus(HttpStatus::isError, ExceptionUtils::buildError)
.bodyToMono(ref));
return this.credHubOperations
.doWithWebClient((webClient) -> webClient.put().uri(BASE_URL_PATH).bodyValue(credentialRequest)
.retrieve().onStatus(HttpStatus::isError, ExceptionUtils::buildError).bodyToMono(ref));
}
@Override
public <T, P> Mono<CredentialDetails<T>> generate(final ParametersRequest<P> parametersRequest,
Class<T> credentialType) {
Class<T> credentialType) {
Assert.notNull(parametersRequest, "parametersRequest must not be null");
final ParameterizedTypeReference<CredentialDetails<T>> ref =
new ParameterizedTypeReference<CredentialDetails<T>>() {};
final ParameterizedTypeReference<CredentialDetails<T>> ref = new ParameterizedTypeReference<CredentialDetails<T>>() {
};
return credHubOperations.doWithWebClient(webClient -> webClient
.post()
.uri(BASE_URL_PATH)
.bodyValue(parametersRequest)
.retrieve()
.onStatus(HttpStatus::isError, ExceptionUtils::buildError)
.bodyToMono(ref));
return this.credHubOperations
.doWithWebClient((webClient) -> webClient.post().uri(BASE_URL_PATH).bodyValue(parametersRequest)
.retrieve().onStatus(HttpStatus::isError, ExceptionUtils::buildError).bodyToMono(ref));
}
@Override
@@ -101,19 +101,15 @@ public class ReactiveCredHubCredentialTemplate implements ReactiveCredHubCredent
Assert.notNull(name, "credential name must not be null");
Assert.notNull(credentialType, "credential type must not be null");
final ParameterizedTypeReference<CredentialDetails<T>> ref =
new ParameterizedTypeReference<CredentialDetails<T>>() {};
final ParameterizedTypeReference<CredentialDetails<T>> ref = new ParameterizedTypeReference<CredentialDetails<T>>() {
};
Map<String, Object> request = new HashMap<>(1);
request.put(NAME_REQUEST_FIELD, name.getName());
return credHubOperations.doWithWebClient(webClient -> webClient
.post()
.uri(REGENERATE_URL_PATH)
.bodyValue(request)
.retrieve()
.onStatus(HttpStatus::isError, ExceptionUtils::buildError)
.bodyToMono(ref));
return this.credHubOperations
.doWithWebClient((webClient) -> webClient.post().uri(REGENERATE_URL_PATH).bodyValue(request).retrieve()
.onStatus(HttpStatus::isError, ExceptionUtils::buildError).bodyToMono(ref));
}
@Override
@@ -121,15 +117,11 @@ public class ReactiveCredHubCredentialTemplate implements ReactiveCredHubCredent
Assert.notNull(id, "credential id must not be null");
Assert.notNull(credentialType, "credential type must not be null");
final ParameterizedTypeReference<CredentialDetails<T>> ref =
new ParameterizedTypeReference<CredentialDetails<T>>() {};
final ParameterizedTypeReference<CredentialDetails<T>> ref = new ParameterizedTypeReference<CredentialDetails<T>>() {
};
return credHubOperations.doWithWebClient(webClient -> webClient
.get()
.uri(ID_URL_PATH, id)
.retrieve()
.onStatus(HttpStatus::isError, ExceptionUtils::buildError)
.bodyToMono(ref));
return this.credHubOperations.doWithWebClient((webClient) -> webClient.get().uri(ID_URL_PATH, id).retrieve()
.onStatus(HttpStatus::isError, ExceptionUtils::buildError).bodyToMono(ref));
}
@Override
@@ -137,88 +129,71 @@ public class ReactiveCredHubCredentialTemplate implements ReactiveCredHubCredent
Assert.notNull(name, "credential name must not be null");
Assert.notNull(credentialType, "credential type must not be null");
final ParameterizedTypeReference<CredentialDetailsData<T>> ref =
new ParameterizedTypeReference<CredentialDetailsData<T>>() {};
final ParameterizedTypeReference<CredentialDetailsData<T>> ref = new ParameterizedTypeReference<CredentialDetailsData<T>>() {
};
return credHubOperations.doWithWebClient(webClient -> webClient
.get()
.uri(NAME_URL_QUERY_CURRENT, name.getName())
.retrieve()
.onStatus(HttpStatus::isError, ExceptionUtils::buildError)
.bodyToMono(ref)
.map(body -> body.getData().get(0)));
return this.credHubOperations
.doWithWebClient((webClient) -> webClient.get().uri(NAME_URL_QUERY_CURRENT, name.getName()).retrieve()
.onStatus(HttpStatus::isError, ExceptionUtils::buildError).bodyToMono(ref)
.map((body) -> body.getData().get(0)));
}
@Override
public <T> Flux<CredentialDetails<T>> getByNameWithHistory(final CredentialName name, final Class<T> credentialType) {
public <T> Flux<CredentialDetails<T>> getByNameWithHistory(final CredentialName name,
final Class<T> credentialType) {
Assert.notNull(name, "credential name must not be null");
Assert.notNull(credentialType, "credential type must not be null");
final ParameterizedTypeReference<CredentialDetailsData<T>> ref =
new ParameterizedTypeReference<CredentialDetailsData<T>>() {};
final ParameterizedTypeReference<CredentialDetailsData<T>> ref = new ParameterizedTypeReference<CredentialDetailsData<T>>() {
};
return credHubOperations.doWithWebClient(webClient -> webClient
.get()
.uri(NAME_URL_QUERY, name.getName())
.retrieve()
.onStatus(HttpStatus::isError, ExceptionUtils::buildError)
.bodyToFlux(ref)
.flatMap(body -> Flux.fromIterable(body.getData())));
return this.credHubOperations.doWithWebClient((webClient) -> webClient.get().uri(NAME_URL_QUERY, name.getName())
.retrieve().onStatus(HttpStatus::isError, ExceptionUtils::buildError).bodyToFlux(ref)
.flatMap((body) -> Flux.fromIterable(body.getData())));
}
@Override
public <T> Flux<CredentialDetails<T>> getByNameWithHistory(final CredentialName name, final int versions,
final Class<T> credentialType) {
final Class<T> credentialType) {
Assert.notNull(name, "credential name must not be null");
Assert.notNull(credentialType, "credential type must not be null");
final ParameterizedTypeReference<CredentialDetailsData<T>> ref =
new ParameterizedTypeReference<CredentialDetailsData<T>>() {};
final ParameterizedTypeReference<CredentialDetailsData<T>> ref = new ParameterizedTypeReference<CredentialDetailsData<T>>() {
};
return credHubOperations.doWithWebClient(webClient -> webClient
.get()
.uri(NAME_URL_QUERY_VERSIONS, name.getName(), versions)
.retrieve()
.onStatus(HttpStatus::isError, ExceptionUtils::buildError)
.bodyToFlux(ref)
.flatMap(body -> Flux.fromIterable(body.getData())));
return this.credHubOperations
.doWithWebClient((webClient) -> webClient.get().uri(NAME_URL_QUERY_VERSIONS, name.getName(), versions)
.retrieve().onStatus(HttpStatus::isError, ExceptionUtils::buildError).bodyToFlux(ref)
.flatMap((body) -> Flux.fromIterable(body.getData())));
}
@Override
public Flux<CredentialSummary> findByName(final CredentialName name) {
Assert.notNull(name, "credential name must not be null");
return credHubOperations.doWithWebClient(webClient -> webClient
.get()
.uri(NAME_LIKE_URL_QUERY, name.getName())
.retrieve()
.onStatus(HttpStatus::isError, ExceptionUtils::buildError)
.bodyToMono(CredentialSummaryData.class)
.flatMapMany(data -> Flux.fromIterable(data.getCredentials())));
return this.credHubOperations.doWithWebClient((webClient) -> webClient.get()
.uri(NAME_LIKE_URL_QUERY, name.getName()).retrieve()
.onStatus(HttpStatus::isError, ExceptionUtils::buildError).bodyToMono(CredentialSummaryData.class)
.flatMapMany((data) -> Flux.fromIterable(data.getCredentials())));
}
@Override
public Flux<CredentialSummary> findByPath(final String path) {
Assert.notNull(path, "credential path must not be null");
return credHubOperations.doWithWebClient(webClient -> webClient
.get()
.uri(PATH_URL_QUERY, path)
.retrieve()
.onStatus(HttpStatus::isError, ExceptionUtils::buildError)
return this.credHubOperations.doWithWebClient((webClient) -> webClient.get().uri(PATH_URL_QUERY, path)
.retrieve().onStatus(HttpStatus::isError, ExceptionUtils::buildError)
.bodyToMono(CredentialSummaryData.class)
.flatMapMany(data -> Flux.fromIterable(data.getCredentials())));
.flatMapMany((data) -> Flux.fromIterable(data.getCredentials())));
}
@Override
public Mono<Void> deleteByName(final CredentialName name) {
Assert.notNull(name, "credential name must not be null");
return credHubOperations.doWithWebClient(webClient -> webClient
.delete()
.uri(NAME_URL_QUERY, name.getName())
.retrieve()
.onStatus(HttpStatus::isError, ExceptionUtils::buildError)
.bodyToMono(Void.class));
return this.credHubOperations
.doWithWebClient((webClient) -> webClient.delete().uri(NAME_URL_QUERY, name.getName()).retrieve()
.onStatus(HttpStatus::isError, ExceptionUtils::buildError).bodyToMono(Void.class));
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -17,4 +17,4 @@
/**
* Core API abstractions for credential operations.
*/
package org.springframework.credhub.core.credential;
package org.springframework.credhub.core.credential;

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -27,7 +27,6 @@ public interface CredHubInfoOperations {
/**
* Retrieve the version information from the CredHub server.
*
* @return the server version information
*/
VersionInfo version();

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -24,17 +24,18 @@ import org.springframework.http.ResponseEntity;
/**
* Implements the interaction with CredHub retrieve server information.
*
* @author Scott Frederick
* @author Scott Frederick
*/
public class CredHubInfoTemplate implements CredHubInfoOperations {
static final String VERSION_URL_PATH = "/version";
private CredHubOperations credHubOperations;
private final CredHubOperations credHubOperations;
/**
* Create a new {@link CredHubInfoTemplate}.
*
* @param credHubOperations the {@link CredHubOperations} to use for interactions with CredHub
* @param credHubOperations the {@link CredHubOperations} to use for interactions with
* CredHub
*/
public CredHubInfoTemplate(CredHubOperations credHubOperations) {
this.credHubOperations = credHubOperations;
@@ -42,18 +43,17 @@ public class CredHubInfoTemplate implements CredHubInfoOperations {
/**
* Retrieve the version information from the CredHub server.
*
* @return the server version information
*/
@Override
public VersionInfo version() {
return credHubOperations.doWithRest(restOperations -> {
ResponseEntity<VersionInfo> response = restOperations
.getForEntity(VERSION_URL_PATH, VersionInfo.class);
return this.credHubOperations.doWithRest((restOperations) -> {
ResponseEntity<VersionInfo> response = restOperations.getForEntity(VERSION_URL_PATH, VersionInfo.class);
ExceptionUtils.throwExceptionOnError(response);
return response.getBody();
});
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,9 +16,10 @@
package org.springframework.credhub.core.info;
import org.springframework.credhub.support.info.VersionInfo;
import reactor.core.publisher.Mono;
import org.springframework.credhub.support.info.VersionInfo;
/**
* Specifies the interactions with CredHub for retrieving server information.
*
@@ -28,7 +29,6 @@ public interface ReactiveCredHubInfoOperations {
/**
* Retrieve the version information from the CredHub server.
*
* @return the server version information
*/
Mono<VersionInfo> version();

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,26 +16,28 @@
package org.springframework.credhub.core.info;
import reactor.core.publisher.Mono;
import org.springframework.credhub.core.ExceptionUtils;
import org.springframework.credhub.core.ReactiveCredHubOperations;
import org.springframework.credhub.support.info.VersionInfo;
import org.springframework.http.HttpStatus;
import reactor.core.publisher.Mono;
/**
* Implements the interaction with CredHub retrieve server information.
*
* @author Scott Frederick
* @author Scott Frederick
*/
public class ReactiveCredHubInfoTemplate implements ReactiveCredHubInfoOperations {
private static final String VERSION_URL_PATH = "/version";
private ReactiveCredHubOperations credHubOperations;
private final ReactiveCredHubOperations credHubOperations;
/**
* Create a new {@link ReactiveCredHubInfoTemplate}.
*
* @param credHubOperations the {@link ReactiveCredHubOperations} to use for interactions with CredHub
* @param credHubOperations the {@link ReactiveCredHubOperations} to use for
* interactions with CredHub
*/
public ReactiveCredHubInfoTemplate(ReactiveCredHubOperations credHubOperations) {
this.credHubOperations = credHubOperations;
@@ -43,16 +45,12 @@ public class ReactiveCredHubInfoTemplate implements ReactiveCredHubInfoOperation
/**
* Retrieve the version information from the CredHub server.
*
* @return the server version information
*/
@Override
public Mono<VersionInfo> version() {
return credHubOperations.doWithWebClient(webClient -> webClient
.get()
.uri(VERSION_URL_PATH)
.retrieve()
.onStatus(HttpStatus::isError, ExceptionUtils::buildError)
.bodyToMono(VersionInfo.class));
return this.credHubOperations.doWithWebClient((webClient) -> webClient.get().uri(VERSION_URL_PATH).retrieve()
.onStatus(HttpStatus::isError, ExceptionUtils::buildError).bodyToMono(VersionInfo.class));
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -17,4 +17,4 @@
/**
* Core API abstractions for informational operations.
*/
package org.springframework.credhub.core.info;
package org.springframework.credhub.core.info;

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -24,6 +24,7 @@ import org.springframework.credhub.support.ServicesData;
* @author Scott Frederick
*/
public interface CredHubInterpolationOperations {
/**
* Search the provided data structure of bound service credentials, looking for
* references to CredHub credentials. Any CredHub credentials found in the data
@@ -31,9 +32,9 @@ public interface CredHubInterpolationOperations {
*
* Example:
*
* A JSON data structure parsed from a {@literal VCAP_SERVICES} environment
* variable might look like this if the service broker that provided the binding
* is integrated with CredHub:
* A JSON data structure parsed from a {@literal VCAP_SERVICES} environment variable
* might look like this if the service broker that provided the binding is integrated
* with CredHub:
*
* <pre>
* {@code
@@ -77,12 +78,12 @@ public interface CredHubInterpolationOperations {
* }
* }
* </pre>
*
* @param serviceData a data structure of bound service credentials, as would be
* parsed from the {@literal VCAP_SERVICES} environment variable provided to
* applications running on Cloud Foundry
* @return the serviceData structure with CredHub references replaced by stored
* credential values
*/
ServicesData interpolateServiceData(final ServicesData serviceData);
ServicesData interpolateServiceData(ServicesData serviceData);
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -25,19 +25,21 @@ import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
/**
* Implements the main interaction with CredHub to interpolate service binding credentials.
* Implements the main interaction with CredHub to interpolate service binding
* credentials.
*
* @author Scott Frederick
* @author Scott Frederick
*/
public class CredHubInterpolationTemplate implements CredHubInterpolationOperations {
static final String INTERPOLATE_URL_PATH = "/api/v1/interpolate";
private CredHubOperations credHubOperations;
private final CredHubOperations credHubOperations;
/**
* Create a new {@link CredHubInterpolationTemplate}.
*
* @param credHubOperations the {@link CredHubOperations} to use for interactions with CredHub
* @param credHubOperations the {@link CredHubOperations} to use for interactions with
* CredHub
*/
public CredHubInterpolationTemplate(CredHubOperations credHubOperations) {
this.credHubOperations = credHubOperations;
@@ -47,14 +49,14 @@ public class CredHubInterpolationTemplate implements CredHubInterpolationOperati
public ServicesData interpolateServiceData(final ServicesData serviceData) {
Assert.notNull(serviceData, "serviceData must not be null");
return credHubOperations.doWithRest(restOperations -> {
ResponseEntity<ServicesData> response = restOperations
.exchange(INTERPOLATE_URL_PATH, HttpMethod.POST,
new HttpEntity<>(serviceData), ServicesData.class);
return this.credHubOperations.doWithRest((restOperations) -> {
ResponseEntity<ServicesData> response = restOperations.exchange(INTERPOLATE_URL_PATH, HttpMethod.POST,
new HttpEntity<>(serviceData), ServicesData.class);
ExceptionUtils.throwExceptionOnError(response);
return response.getBody();
});
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,15 +16,17 @@
package org.springframework.credhub.core.interpolation;
import org.springframework.credhub.support.ServicesData;
import reactor.core.publisher.Mono;
import org.springframework.credhub.support.ServicesData;
/**
* Specifies the interactions with CredHub to interpolate service binding credentials.
*
* @author Scott Frederick
*/
public interface ReactiveCredHubInterpolationOperations {
/**
* Search the provided data structure of bound service credentials, looking for
* references to CredHub credentials. Any CredHub credentials found in the data
@@ -32,9 +34,9 @@ public interface ReactiveCredHubInterpolationOperations {
*
* Example:
*
* A JSON data structure parsed from a {@literal VCAP_SERVICES} environment
* variable might look like this if the service broker that provided the binding
* is integrated with CredHub:
* A JSON data structure parsed from a {@literal VCAP_SERVICES} environment variable
* might look like this if the service broker that provided the binding is integrated
* with CredHub:
*
* <pre>
* {@code
@@ -78,12 +80,12 @@ public interface ReactiveCredHubInterpolationOperations {
* }
* }
* </pre>
*
* @param serviceData a data structure of bound service credentials, as would be
* parsed from the {@literal VCAP_SERVICES} environment variable provided to
* applications running on Cloud Foundry
* @return the serviceData structure with CredHub references replaced by stored
* credential values
*/
Mono<ServicesData> interpolateServiceData(final ServicesData serviceData);
Mono<ServicesData> interpolateServiceData(ServicesData serviceData);
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,28 +16,31 @@
package org.springframework.credhub.core.interpolation;
import reactor.core.publisher.Mono;
import org.springframework.credhub.core.CredHubOperations;
import org.springframework.credhub.core.ExceptionUtils;
import org.springframework.credhub.core.ReactiveCredHubOperations;
import org.springframework.credhub.support.ServicesData;
import org.springframework.http.HttpStatus;
import org.springframework.util.Assert;
import reactor.core.publisher.Mono;
/**
* Implements the main interaction with CredHub to interpolate service binding credentials.
* Implements the main interaction with CredHub to interpolate service binding
* credentials.
*
* @author Scott Frederick
* @author Scott Frederick
*/
public class ReactiveCredHubInterpolationTemplate implements ReactiveCredHubInterpolationOperations {
private static final String INTERPOLATE_URL_PATH = "/api/v1/interpolate";
private ReactiveCredHubOperations credHubOperations;
private final ReactiveCredHubOperations credHubOperations;
/**
* Create a new {@link ReactiveCredHubInterpolationTemplate}.
*
* @param credHubOperations the {@link CredHubOperations} to use for interactions with CredHub
* @param credHubOperations the {@link CredHubOperations} to use for interactions with
* CredHub
*/
public ReactiveCredHubInterpolationTemplate(ReactiveCredHubOperations credHubOperations) {
this.credHubOperations = credHubOperations;
@@ -47,12 +50,9 @@ public class ReactiveCredHubInterpolationTemplate implements ReactiveCredHubInte
public Mono<ServicesData> interpolateServiceData(final ServicesData serviceData) {
Assert.notNull(serviceData, "serviceData must not be null");
return credHubOperations.doWithWebClient(webClient -> webClient
.post()
.uri(INTERPOLATE_URL_PATH)
.bodyValue(serviceData)
.retrieve()
.onStatus(HttpStatus::isError, ExceptionUtils::buildError)
.bodyToMono(ServicesData.class));
return this.credHubOperations.doWithWebClient(
(webClient) -> webClient.post().uri(INTERPOLATE_URL_PATH).bodyValue(serviceData).retrieve()
.onStatus(HttpStatus::isError, ExceptionUtils::buildError).bodyToMono(ServicesData.class));
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -17,4 +17,4 @@
/**
* Core API abstractions for interpolation operations.
*/
package org.springframework.credhub.core.interpolation;
package org.springframework.credhub.core.interpolation;

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -17,4 +17,4 @@
/**
* Core API abstractions for Spring CredHub.
*/
package org.springframework.credhub.core;
package org.springframework.credhub.core;

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,39 +16,38 @@
package org.springframework.credhub.core.permission;
import java.util.List;
import org.springframework.credhub.support.CredentialName;
import org.springframework.credhub.support.permissions.Actor;
import org.springframework.credhub.support.permissions.Permission;
import java.util.List;
/**
* Specifies the interactions with CredHub to add, retrieve, and delete permissions.
*
* @author Scott Frederick
*/
public interface CredHubPermissionOperations {
/**
* Get the permissions associated with a credential.
*
* @param name the name of the credential; must not be {@literal null}
* @return the collection of permissions associated with the credential
*/
List<Permission> getPermissions(final CredentialName name);
List<Permission> getPermissions(CredentialName name);
/**
* Add permissions to an existing credential.
*
* @param name the name of the credential; must not be {@literal null}
* @param permissions a collection of permissions to add
*/
void addPermissions(final CredentialName name, final Permission... permissions);
void addPermissions(CredentialName name, Permission... permissions);
/**
* Delete a permission associated with a credential.
*
* @param name the name of the credential; must not be {@literal null}
* @param actor the actor of the permission; must not be {@literal null}
*/
void deletePermission(final CredentialName name, final Actor actor);
void deletePermission(CredentialName name, Actor actor);
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,6 +16,8 @@
package org.springframework.credhub.core.permission;
import java.util.List;
import org.springframework.credhub.core.CredHubOperations;
import org.springframework.credhub.support.CredentialName;
import org.springframework.credhub.support.CredentialPermissions;
@@ -26,25 +28,25 @@ import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import java.util.List;
/**
* Implements the main interaction with CredHub to add, retrieve,
* and delete permissions.
* Implements the main interaction with CredHub to add, retrieve, and delete permissions.
*
* @author Scott Frederick
* @author Scott Frederick
*/
public class CredHubPermissionTemplate implements CredHubPermissionOperations {
static final String PERMISSIONS_URL_PATH = "/api/v1/permissions";
static final String PERMISSIONS_URL_QUERY = PERMISSIONS_URL_PATH + "?credential_name={name}";
static final String PERMISSIONS_ACTOR_URL_QUERY = PERMISSIONS_URL_QUERY + "&actor={actor}";
private CredHubOperations credHubOperations;
private final CredHubOperations credHubOperations;
/**
* Create a new {@link CredHubPermissionTemplate}.
*
* @param credHubOperations the {@link CredHubOperations} to use for interactions with CredHub
* @param credHubOperations the {@link CredHubOperations} to use for interactions with
* CredHub
*/
public CredHubPermissionTemplate(CredHubOperations credHubOperations) {
this.credHubOperations = credHubOperations;
@@ -54,24 +56,21 @@ public class CredHubPermissionTemplate implements CredHubPermissionOperations {
public List<Permission> getPermissions(final CredentialName name) {
Assert.notNull(name, "credential name must not be null");
return credHubOperations.doWithRest(restOperations -> {
ResponseEntity<CredentialPermissions> response =
restOperations.getForEntity(PERMISSIONS_URL_QUERY,
CredentialPermissions.class, name.getName());
return this.credHubOperations.doWithRest((restOperations) -> {
ResponseEntity<CredentialPermissions> response = restOperations.getForEntity(PERMISSIONS_URL_QUERY,
CredentialPermissions.class, name.getName());
return response.getBody().getPermissions();
});
}
@Override
public void addPermissions(final CredentialName name,
final Permission... permissions) {
public void addPermissions(final CredentialName name, final Permission... permissions) {
Assert.notNull(name, "credential name must not be null");
final CredentialPermissions credentialPermissions = new CredentialPermissions(name, permissions);
credHubOperations.doWithRest(restOperations -> {
restOperations.exchange(PERMISSIONS_URL_PATH, HttpMethod.POST,
new HttpEntity<>(credentialPermissions),
this.credHubOperations.doWithRest((restOperations) -> {
restOperations.exchange(PERMISSIONS_URL_PATH, HttpMethod.POST, new HttpEntity<>(credentialPermissions),
CredentialPermissions.class);
return null;
});
@@ -82,9 +81,10 @@ public class CredHubPermissionTemplate implements CredHubPermissionOperations {
Assert.notNull(name, "credential name must not be null");
Assert.notNull(actor, "actor must not be null");
credHubOperations.doWithRest(restOperations -> {
this.credHubOperations.doWithRest((restOperations) -> {
restOperations.delete(PERMISSIONS_ACTOR_URL_QUERY, name.getName(), actor.getIdentity());
return null;
});
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,11 +16,12 @@
package org.springframework.credhub.core.permission;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.springframework.credhub.support.CredentialName;
import org.springframework.credhub.support.permissions.Actor;
import org.springframework.credhub.support.permissions.Permission;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/**
* Specifies the interactions with CredHub to add, retrieve, and delete permissions.
@@ -28,29 +29,28 @@ import reactor.core.publisher.Mono;
* @author Scott Frederick
*/
public interface ReactiveCredHubPermissionOperations {
/**
* Get the permissions associated with a credential.
*
* @param name the name of the credential; must not be {@literal null}
* @return the collection of permissions associated with the credential
*/
Flux<Permission> getPermissions(final CredentialName name);
Flux<Permission> getPermissions(CredentialName name);
/**
* Add permissions to an existing credential.
*
* @param name the name of the credential; must not be {@literal null}
* @param permissions a collection of permissions to add
* @return an empty {@code Mono}
*/
Mono<Void> addPermissions(final CredentialName name, final Permission... permissions);
Mono<Void> addPermissions(CredentialName name, Permission... permissions);
/**
* Delete a permission associated with a credential.
*
* @param name the name of the credential; must not be {@literal null}
* @param actor the actor of the permission; must not be {@literal null}
* @return an empty {@code Mono}
*/
Mono<Void> deletePermission(final CredentialName name, final Actor actor);
Mono<Void> deletePermission(CredentialName name, Actor actor);
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,6 +16,9 @@
package org.springframework.credhub.core.permission;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.springframework.credhub.core.ExceptionUtils;
import org.springframework.credhub.core.ReactiveCredHubOperations;
import org.springframework.credhub.support.CredentialName;
@@ -24,26 +27,26 @@ import org.springframework.credhub.support.permissions.Actor;
import org.springframework.credhub.support.permissions.Permission;
import org.springframework.http.HttpStatus;
import org.springframework.util.Assert;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/**
* Implements the main interaction with CredHub to add, retrieve,
* and delete permissions.
* Implements the main interaction with CredHub to add, retrieve, and delete permissions.
*
* @author Scott Frederick
*/
public class ReactiveCredHubPermissionTemplate implements ReactiveCredHubPermissionOperations {
private static final String PERMISSIONS_URL_PATH = "/api/v1/permissions";
private static final String PERMISSIONS_URL_QUERY = PERMISSIONS_URL_PATH + "?credential_name={name}";
private static final String PERMISSIONS_ACTOR_URL_QUERY = PERMISSIONS_URL_QUERY + "&actor={actor}";
private ReactiveCredHubOperations credHubOperations;
private final ReactiveCredHubOperations credHubOperations;
/**
* Create a new {@link ReactiveCredHubPermissionTemplate}.
*
* @param credHubOperations the {@link ReactiveCredHubOperations} to use for interactions with CredHub
* @param credHubOperations the {@link ReactiveCredHubOperations} to use for
* interactions with CredHub
*/
public ReactiveCredHubPermissionTemplate(ReactiveCredHubOperations credHubOperations) {
this.credHubOperations = credHubOperations;
@@ -53,29 +56,21 @@ public class ReactiveCredHubPermissionTemplate implements ReactiveCredHubPermiss
public Flux<Permission> getPermissions(final CredentialName name) {
Assert.notNull(name, "credential name must not be null");
return credHubOperations.doWithWebClient(webClient -> webClient
.get()
.uri(PERMISSIONS_URL_QUERY, name.getName())
.retrieve()
.onStatus(HttpStatus::isError, ExceptionUtils::buildError)
.bodyToMono(CredentialPermissions.class)
.flatMapMany(data -> Flux.fromIterable(data.getPermissions())));
return this.credHubOperations.doWithWebClient((webClient) -> webClient.get()
.uri(PERMISSIONS_URL_QUERY, name.getName()).retrieve()
.onStatus(HttpStatus::isError, ExceptionUtils::buildError).bodyToMono(CredentialPermissions.class)
.flatMapMany((data) -> Flux.fromIterable(data.getPermissions())));
}
@Override
public Mono<Void> addPermissions(final CredentialName name,
final Permission... permissions) {
public Mono<Void> addPermissions(final CredentialName name, final Permission... permissions) {
Assert.notNull(name, "credential name must not be null");
final CredentialPermissions credentialPermissions = new CredentialPermissions(name, permissions);
return credHubOperations.doWithWebClient(webClient -> webClient
.post()
.uri(PERMISSIONS_URL_PATH)
.bodyValue(credentialPermissions)
.retrieve()
.onStatus(HttpStatus::isError, ExceptionUtils::buildError)
.bodyToMono(Void.class));
return this.credHubOperations.doWithWebClient(
(webClient) -> webClient.post().uri(PERMISSIONS_URL_PATH).bodyValue(credentialPermissions).retrieve()
.onStatus(HttpStatus::isError, ExceptionUtils::buildError).bodyToMono(Void.class));
}
@Override
@@ -83,11 +78,9 @@ public class ReactiveCredHubPermissionTemplate implements ReactiveCredHubPermiss
Assert.notNull(name, "credential name must not be null");
Assert.notNull(actor, "actor must not be null");
return credHubOperations.doWithWebClient(webClient -> webClient
.delete()
.uri(PERMISSIONS_ACTOR_URL_QUERY, name.getName(), actor.getIdentity())
.retrieve()
.onStatus(HttpStatus::isError, ExceptionUtils::buildError)
.bodyToMono(Void.class));
return this.credHubOperations.doWithWebClient(
(webClient) -> webClient.delete().uri(PERMISSIONS_ACTOR_URL_QUERY, name.getName(), actor.getIdentity())
.retrieve().onStatus(HttpStatus::isError, ExceptionUtils::buildError).bodyToMono(Void.class));
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -17,4 +17,4 @@
/**
* Core API abstractions for permission operations.
*/
package org.springframework.credhub.core.permission;
package org.springframework.credhub.core.permission;

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -28,47 +28,44 @@ import org.springframework.credhub.support.permissions.Permission;
* @author Alberto C. Ríos
*/
public interface CredHubPermissionV2Operations {
/**
* Get a permission.
*
* @param id the CredHub-assigned ID of the permission; must not be {@literal null}
* @return the details if the specified permission
*/
CredentialPermission getPermissions(final String id);
CredentialPermission getPermissions(String id);
/**
* Get a permission by path and actor.
* @since API 2.1
*
* @param path the path of the credentials; must not be {@literal null}
* @param actor the actor of the credentials; must not be {@literal null}
* @return the details if the specified permission
* @since API 2.1
*/
CredentialPermission getPermissionsByPathAndActor(final CredentialName path, final Actor actor);
CredentialPermission getPermissionsByPathAndActor(CredentialName path, Actor actor);
/**
* Add permissions to an credential path.
*
* @param path the path of the credentials; must not be {@literal null}
* @param permission a permission to add
* @return the details if the added permission
*/
CredentialPermission addPermissions(final CredentialName path, final Permission permission);
CredentialPermission addPermissions(CredentialName path, Permission permission);
/**
* Add permissions to an existing credential.
*
* @param id the CredHub-assigned ID of the permission; must not be {@literal null}
* @param path the path of the credentials; must not be {@literal null}
* @param permission a permission to add
* @return the details if the added permission
*/
CredentialPermission updatePermissions(final String id, final CredentialName path, final Permission permission);
CredentialPermission updatePermissions(String id, CredentialName path, Permission permission);
/**
* Delete a permission.
*
* @param id the CredHub-assigned ID of the permission; must not be {@literal null}
*/
void deletePermission(final String id);
void deletePermission(String id);
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -27,23 +27,25 @@ import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
/**
* Implements the main interaction with CredHub to add, retrieve,
* and delete permissions.
* Implements the main interaction with CredHub to add, retrieve, and delete permissions.
*
* @author Scott Frederick
* @author Scott Frederick
* @author Alberto C. Ríos
*/
public class CredHubPermissionV2Template implements CredHubPermissionV2Operations {
static final String PERMISSIONS_URL_PATH = "/api/v2/permissions";
static final String PERMISSIONS_ID_URL_PATH = PERMISSIONS_URL_PATH + "/{id}";
static final String PERMISSIONS_PATH_ACTOR_URL_QUERY = PERMISSIONS_URL_PATH + "?path={path}&actor={actor}";
private CredHubOperations credHubOperations;
private final CredHubOperations credHubOperations;
/**
* Create a new {@link CredHubPermissionV2Template}.
*
* @param credHubOperations the {@link CredHubOperations} to use for interactions with CredHub
* @param credHubOperations the {@link CredHubOperations} to use for interactions with
* CredHub
*/
public CredHubPermissionV2Template(CredHubOperations credHubOperations) {
this.credHubOperations = credHubOperations;
@@ -53,10 +55,9 @@ public class CredHubPermissionV2Template implements CredHubPermissionV2Operation
public CredentialPermission getPermissions(final String id) {
Assert.notNull(id, "credential ID must not be null");
return credHubOperations.doWithRest(restOperations -> {
ResponseEntity<CredentialPermission> response =
restOperations.getForEntity(PERMISSIONS_ID_URL_PATH,
CredentialPermission.class, id);
return this.credHubOperations.doWithRest((restOperations) -> {
ResponseEntity<CredentialPermission> response = restOperations.getForEntity(PERMISSIONS_ID_URL_PATH,
CredentialPermission.class, id);
return response.getBody();
});
}
@@ -66,45 +67,39 @@ public class CredHubPermissionV2Template implements CredHubPermissionV2Operation
Assert.notNull(path, "credential path must not be null");
Assert.notNull(actor, "credential actor must not be null");
return credHubOperations.doWithRest(restOperations -> {
ResponseEntity<CredentialPermission> response =
restOperations.getForEntity(PERMISSIONS_PATH_ACTOR_URL_QUERY,
CredentialPermission.class, path.getName(), actor.getIdentity());
return this.credHubOperations.doWithRest((restOperations) -> {
ResponseEntity<CredentialPermission> response = restOperations.getForEntity(
PERMISSIONS_PATH_ACTOR_URL_QUERY, CredentialPermission.class, path.getName(), actor.getIdentity());
return response.getBody();
});
}
@Override
public CredentialPermission addPermissions(final CredentialName path,
final Permission permission) {
public CredentialPermission addPermissions(final CredentialName path, final Permission permission) {
Assert.notNull(path, "credential path must not be null");
Assert.notNull(permission, "credential permission must not be null");
final CredentialPermission credentialPermission = new CredentialPermission(path, permission);
return credHubOperations.doWithRest(restOperations -> {
ResponseEntity<CredentialPermission> response =
restOperations.exchange(PERMISSIONS_URL_PATH, HttpMethod.POST,
new HttpEntity<>(credentialPermission),
CredentialPermission.class);
return this.credHubOperations.doWithRest((restOperations) -> {
ResponseEntity<CredentialPermission> response = restOperations.exchange(PERMISSIONS_URL_PATH,
HttpMethod.POST, new HttpEntity<>(credentialPermission), CredentialPermission.class);
return response.getBody();
});
}
@Override
public CredentialPermission updatePermissions(final String id, final CredentialName path,
final Permission permission) {
final Permission permission) {
Assert.notNull(id, "credential ID must not be null");
Assert.notNull(path, "credential path must not be null");
Assert.notNull(permission, "credential permission must not be null");
final CredentialPermission credentialPermission = new CredentialPermission(path, permission);
return credHubOperations.doWithRest(restOperations -> {
ResponseEntity<CredentialPermission> response =
restOperations.exchange(PERMISSIONS_ID_URL_PATH, HttpMethod.PUT,
new HttpEntity<>(credentialPermission),
CredentialPermission.class, id);
return this.credHubOperations.doWithRest((restOperations) -> {
ResponseEntity<CredentialPermission> response = restOperations.exchange(PERMISSIONS_ID_URL_PATH,
HttpMethod.PUT, new HttpEntity<>(credentialPermission), CredentialPermission.class, id);
return response.getBody();
});
}
@@ -113,9 +108,10 @@ public class CredHubPermissionV2Template implements CredHubPermissionV2Operation
public void deletePermission(final String id) {
Assert.notNull(id, "credential ID must not be null");
credHubOperations.doWithRest(restOperations -> {
this.credHubOperations.doWithRest((restOperations) -> {
restOperations.delete(PERMISSIONS_ID_URL_PATH, id);
return null;
});
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,11 +16,12 @@
package org.springframework.credhub.core.permissionV2;
import reactor.core.publisher.Mono;
import org.springframework.credhub.support.CredentialName;
import org.springframework.credhub.support.CredentialPermission;
import org.springframework.credhub.support.permissions.Actor;
import org.springframework.credhub.support.permissions.Permission;
import reactor.core.publisher.Mono;
/**
* Specifies the interactions with CredHub to add, retrieve, and delete permissions.
@@ -29,48 +30,45 @@ import reactor.core.publisher.Mono;
* @author Alberto C. Ríos
*/
public interface ReactiveCredHubPermissionV2Operations {
/**
* Get a permission.
*
* @param id the CredHub-assigned ID of the permission; must not be {@literal null}
* @return the details if the specified permission
*/
Mono<CredentialPermission> getPermissions(final String id);
Mono<CredentialPermission> getPermissions(String id);
/**
* Get a permission by path and actor.
* @since API 2.1
*
* @param path the path of the credentials; must not be {@literal null}
* @param actor the actor of the credentials; must not be {@literal null}
* @return the details if the specified permission
* @since API 2.1
*/
Mono<CredentialPermission> getPermissionsByPathAndActor(final CredentialName path, final Actor actor);
Mono<CredentialPermission> getPermissionsByPathAndActor(CredentialName path, Actor actor);
/**
* Add permissions to an credential path.
*
* @param path the path of the credentials; must not be {@literal null}
* @param permission a permission to add
* @return the details if the added permission
*/
Mono<CredentialPermission> addPermissions(final CredentialName path, final Permission permission);
Mono<CredentialPermission> addPermissions(CredentialName path, Permission permission);
/**
* Add permissions to an existing credential.
*
* @param id the CredHub-assigned ID of the permission; must not be {@literal null}
* @param path the path of the credentials; must not be {@literal null}
* @param permission a permission to add
* @return the details if the added permission
*/
Mono<CredentialPermission> updatePermissions(final String id, final CredentialName path, final Permission permission);
Mono<CredentialPermission> updatePermissions(String id, CredentialName path, Permission permission);
/**
* Delete a permission.
*
* @param id the CredHub-assigned ID of the permission; must not be {@literal null}
* @return an empty {@code Mono}
*/
Mono<Void> deletePermission(final String id);
Mono<Void> deletePermission(String id);
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -28,23 +28,25 @@ import org.springframework.http.HttpStatus;
import org.springframework.util.Assert;
/**
* Implements the main interaction with CredHub to add, retrieve,
* and delete permissions.
* Implements the main interaction with CredHub to add, retrieve, and delete permissions.
*
* @author Scott Frederick
* @author Alberto C. Ríos
*/
public class ReactiveCredHubPermissionV2Template implements ReactiveCredHubPermissionV2Operations {
private static final String PERMISSIONS_URL_PATH = "/api/v2/permissions";
private static final String PERMISSIONS_ID_URL_PATH = PERMISSIONS_URL_PATH + "/{id}";
static final String PERMISSIONS_PATH_ACTOR_URL_QUERY = PERMISSIONS_URL_PATH + "?path={path}&actor={actor}";
private ReactiveCredHubOperations credHubOperations;
private final ReactiveCredHubOperations credHubOperations;
/**
* Create a new {@link ReactiveCredHubPermissionV2Template}.
*
* @param credHubOperations the {@link ReactiveCredHubOperations} to use for interactions with CredHub
* @param credHubOperations the {@link ReactiveCredHubOperations} to use for
* interactions with CredHub
*/
public ReactiveCredHubPermissionV2Template(ReactiveCredHubOperations credHubOperations) {
this.credHubOperations = credHubOperations;
@@ -54,27 +56,19 @@ public class ReactiveCredHubPermissionV2Template implements ReactiveCredHubPermi
public Mono<CredentialPermission> getPermissions(final String id) {
Assert.notNull(id, "credential ID must not be null");
return credHubOperations.doWithWebClient(webClient -> webClient
.get()
.uri(PERMISSIONS_ID_URL_PATH, id)
.retrieve()
.bodyToMono(CredentialPermission.class));
return this.credHubOperations.doWithWebClient((webClient) -> webClient.get().uri(PERMISSIONS_ID_URL_PATH, id)
.retrieve().bodyToMono(CredentialPermission.class));
}
@Override
public Mono<CredentialPermission> addPermissions(final CredentialName path,
final Permission permission) {
public Mono<CredentialPermission> addPermissions(final CredentialName path, final Permission permission) {
Assert.notNull(path, "credential path must not be null");
Assert.notNull(permission, "credential permission must not be null");
final CredentialPermission credentialPermission = new CredentialPermission(path, permission);
return credHubOperations.doWithWebClient(webClient -> webClient
.post()
.uri(PERMISSIONS_URL_PATH)
.bodyValue(credentialPermission)
.retrieve()
.onStatus(HttpStatus::isError, ExceptionUtils::buildError)
return this.credHubOperations.doWithWebClient((webClient) -> webClient.post().uri(PERMISSIONS_URL_PATH)
.bodyValue(credentialPermission).retrieve().onStatus(HttpStatus::isError, ExceptionUtils::buildError)
.bodyToMono(CredentialPermission.class));
}
@@ -83,29 +77,22 @@ public class ReactiveCredHubPermissionV2Template implements ReactiveCredHubPermi
Assert.notNull(path, "credential path must not be null");
Assert.notNull(actor, "credential actor must not be null");
return credHubOperations.doWithWebClient(webClient -> webClient
.get()
.uri(PERMISSIONS_PATH_ACTOR_URL_QUERY, path.getName(), actor.getIdentity())
.retrieve()
.onStatus(HttpStatus::isError, ExceptionUtils::buildError)
.bodyToMono(CredentialPermission.class));
return this.credHubOperations.doWithWebClient((webClient) -> webClient.get()
.uri(PERMISSIONS_PATH_ACTOR_URL_QUERY, path.getName(), actor.getIdentity()).retrieve()
.onStatus(HttpStatus::isError, ExceptionUtils::buildError).bodyToMono(CredentialPermission.class));
}
@Override
public Mono<CredentialPermission> updatePermissions(final String id, final CredentialName path,
final Permission permission) {
final Permission permission) {
Assert.notNull(id, "credential ID must not be null");
Assert.notNull(path, "credential path must not be null");
Assert.notNull(permission, "credential permission must not be null");
final CredentialPermission credentialPermission = new CredentialPermission(path, permission);
return credHubOperations.doWithWebClient(webClient -> webClient
.put()
.uri(PERMISSIONS_ID_URL_PATH, id)
.bodyValue(credentialPermission)
.retrieve()
.onStatus(HttpStatus::isError, ExceptionUtils::buildError)
return this.credHubOperations.doWithWebClient((webClient) -> webClient.put().uri(PERMISSIONS_ID_URL_PATH, id)
.bodyValue(credentialPermission).retrieve().onStatus(HttpStatus::isError, ExceptionUtils::buildError)
.bodyToMono(CredentialPermission.class));
}
@@ -113,11 +100,8 @@ public class ReactiveCredHubPermissionV2Template implements ReactiveCredHubPermi
public Mono<Void> deletePermission(final String id) {
Assert.notNull(id, "credential ID must not be null");
return credHubOperations.doWithWebClient(webClient -> webClient
.delete()
.uri(PERMISSIONS_ID_URL_PATH, id)
.retrieve()
.onStatus(HttpStatus::isError, ExceptionUtils::buildError)
.bodyToMono(Void.class));
return this.credHubOperations.doWithWebClient((webClient) -> webClient.delete().uri(PERMISSIONS_ID_URL_PATH, id)
.retrieve().onStatus(HttpStatus::isError, ExceptionUtils::buildError).bodyToMono(Void.class));
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -17,4 +17,4 @@
/**
* Core API abstractions for permission operations.
*/
package org.springframework.credhub.core.permissionV2;
package org.springframework.credhub.core.permissionV2;

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -17,4 +17,4 @@
/**
* Spring abstractions for interacting with Cloud Foundry CredHub.
*/
package org.springframework.credhub;
package org.springframework.credhub;

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -26,6 +26,7 @@ import java.util.concurrent.TimeUnit;
* @author Scott Frederick
*/
public class ClientOptions {
private Duration connectionTimeout;
private Duration readTimeout;
@@ -43,12 +44,11 @@ public class ClientOptions {
/**
* Create a {@link ClientOptions} with the provided values.
*
* @param connectionTimeout connection timeout in {@link TimeUnit#MILLISECONDS}, must
* be greater {@literal 0}
* @param readTimeout read timeout in {@link TimeUnit#MILLISECONDS}, must be greater
* {@literal 0}
* @param caCertFiles one or more CA certificate files to use when connecting
* @param connectionTimeout connection timeout in {@link TimeUnit#MILLISECONDS}, must
* be greater {@literal 0}
* @param readTimeout read timeout in {@link TimeUnit#MILLISECONDS}, must be greater
* {@literal 0}
* @param caCertFiles one or more CA certificate files to use when connecting
*/
public ClientOptions(Duration connectionTimeout, Duration readTimeout, String[] caCertFiles) {
this.connectionTimeout = connectionTimeout;
@@ -58,7 +58,6 @@ public class ClientOptions {
/**
* Get the connection timeout in {@link TimeUnit#MILLISECONDS}.
*
* @return the connection timeout; can be {@literal null if not explicitly set}
*/
public Duration getConnectionTimeout() {
@@ -67,11 +66,10 @@ public class ClientOptions {
/**
* Get the connection timeout in {@link TimeUnit#MILLISECONDS}.
*
* @return the connection timeout; can be {@literal null if not explicitly set}
*/
public Integer getConnectionTimeoutMillis() {
return this.connectionTimeout == null ? null : Math.toIntExact(this.connectionTimeout.toMillis());
return (this.connectionTimeout == null) ? null : Math.toIntExact(this.connectionTimeout.toMillis());
}
public void setConnectionTimeout(Duration connectionTimeout) {
@@ -80,7 +78,6 @@ public class ClientOptions {
/**
* Get the read timeout in {@link TimeUnit#MILLISECONDS}.
*
* @return the read timeout; can be {@literal null if not explicitly set}
*/
public Duration getReadTimeout() {
@@ -89,11 +86,10 @@ public class ClientOptions {
/**
* Get the read timeout in {@link TimeUnit#MILLISECONDS}.
*
* @return the read timeout; can be {@literal null if not explicitly set}
*/
public Integer getReadTimeoutMillis() {
return this.readTimeout == null ? null : Math.toIntExact(this.readTimeout.toMillis());
return (this.readTimeout == null) ? null : Math.toIntExact(this.readTimeout.toMillis());
}
public void setReadTimeout(Duration readTimeout) {
@@ -101,10 +97,11 @@ public class ClientOptions {
}
public String[] getCaCertFiles() {
return caCertFiles;
return this.caCertFiles;
}
public void setCaCertFiles(String[] caCertFiles) {
this.caCertFiles = caCertFiles;
}
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,39 +16,46 @@
package org.springframework.credhub.support;
import com.fasterxml.jackson.annotation.JsonInclude;
import org.springframework.credhub.core.permission.CredHubPermissionOperations;
import org.springframework.credhub.support.permissions.Permission;
import org.springframework.util.Assert;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonInclude;
import org.springframework.credhub.core.permission.CredHubPermissionOperations;
import org.springframework.credhub.support.permissions.Permission;
import org.springframework.util.Assert;
/**
* Fields common to all types of CredHub requests.
*
* @param <T> the type of CredHub credential
* @author Scott Frederick
*/
@SuppressWarnings("WeakerAccess")
public class CredHubRequest<T> {
protected Boolean overwrite;
protected WriteMode mode;
protected CredentialName name;
protected CredentialType credentialType;
protected List<Permission> additionalPermissions;
protected T details;
public CredHubRequest() {
additionalPermissions = new ArrayList<>();
this.additionalPermissions = new ArrayList<>();
}
/**
* Get the value of the {@literal boolean} flag indicating whether the CredHub
* should create a new credential or update an existing credential.
*
* Get the value of the {@literal boolean} flag indicating whether the CredHub should
* create a new credential or update an existing credential.
* @return the {@literal boolean} overwrite value
* @deprecated as of CredHub 1.6, use {@link #mode}
*/
@@ -62,7 +69,6 @@ public class CredHubRequest<T> {
/**
* Get the value of the write mode indicator.
*
* @return the write mode
*/
public WriteMode getMode() {
@@ -75,12 +81,11 @@ public class CredHubRequest<T> {
/**
* Get the {@link CredentialName} of the credential.
*
* @return the name of the credential
*/
@JsonInclude
public String getName() {
return name == null ? null : name.getName();
return (this.name == null) ? null : this.name.getName();
}
void setName(CredentialName name) {
@@ -89,11 +94,10 @@ public class CredHubRequest<T> {
/**
* Get the {@link CredentialType} of the credential.
*
* @return the type of the credential
* @return the type of the credential
*/
public String getType() {
return credentialType.getValueType();
return this.credentialType.getValueType();
}
void setType(CredentialType credentialType) {
@@ -106,52 +110,70 @@ public class CredHubRequest<T> {
/**
* Get the set of {@link Permission} to assign to the credential.
*
* @return the set of {@link Permission}
*/
public List<Permission> getAdditionalPermissions() {
return this.additionalPermissions;
}
@Override
public String toString() {
return "CredHubRequest{" +
"overwrite=" + overwrite +
", name=" + name +
", credentialType=" + credentialType +
", additionalPermissions=" + additionalPermissions +
", details=" + details +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof CredHubRequest)) return false;
if (this == o) {
return true;
}
if (!(o instanceof CredHubRequest)) {
return false;
}
CredHubRequest that = (CredHubRequest) o;
if (overwrite != that.overwrite) return false;
if (name != null ? !name.equals(that.name) : that.name != null) return false;
if (credentialType != that.credentialType) return false;
if (additionalPermissions != null ?
!additionalPermissions.equals(that.additionalPermissions) : that.additionalPermissions == null) return false;
if (details != null ? !details.equals(that.details) : that.details != null) return false;
if (mode != null ? !mode.equals(that.mode) : that.mode != null) return false;
if (this.overwrite != that.overwrite) {
return false;
}
if ((this.name != null) ? !this.name.equals(that.name) : (that.name != null)) {
return false;
}
if (this.credentialType != that.credentialType) {
return false;
}
if ((this.additionalPermissions != null) ? !this.additionalPermissions.equals(that.additionalPermissions)
: (that.additionalPermissions == null)) {
return false;
}
if ((this.details != null) ? !this.details.equals(that.details) : (that.details != null)) {
return false;
}
if ((this.mode != null) ? !this.mode.equals(that.mode) : (that.mode != null)) {
return false;
}
return true;
}
@Override
public int hashCode() {
return Objects.hash(overwrite, name, credentialType, additionalPermissions, details, mode);
return Objects.hash(this.overwrite, this.name, this.credentialType, this.additionalPermissions, this.details,
this.mode);
}
@Override
public String toString() {
return "CredHubRequest{" + "overwrite=" + this.overwrite + ", name=" + this.name + ", credentialType="
+ this.credentialType + ", additionalPermissions=" + this.additionalPermissions + ", details="
+ this.details + '}';
}
/**
* A builder that provides a fluent API for constructing {@link CredHubRequest}s.
*
* @param <T> the type of CredHub credential
* @param <R> the type of the concrete {@link CredHubRequest}
* @param <B> the type of the concrete builder
*/
protected static abstract class CredHubRequestBuilder<T, R extends CredHubRequest<T>, B extends CredHubRequestBuilder<T, R, B>> {
protected abstract static class CredHubRequestBuilder<T, R extends CredHubRequest<T>, B extends CredHubRequestBuilder<T, R, B>> {
private final B thisObj;
protected final R targetObj;
/**
@@ -164,111 +186,104 @@ public class CredHubRequest<T> {
/**
* Provide the concrete object to build.
*
* @return the target object
*/
protected abstract R createTarget();
/**
* Provide the concrete builder.
*
* @return the builder
*/
protected abstract B createBuilder();
/**
* Set the {@link CredentialName} for the credential.
*
* @param name the credential name; must not be {@literal null}
* @return the builder
*/
public B name(CredentialName name) {
Assert.notNull(name, "name must not be null");
targetObj.setName(name);
return thisObj;
this.targetObj.setName(name);
return this.thisObj;
}
/**
* Sets a {@literal boolean} value indicating whether CredHub should create a new
* credential or update and existing credential.
*
* @param overwrite {@literal false} to create a new credential, or
* {@literal true} to update and existing credential
* @return the builder
* @deprecated as of CredHub 1.6, use {@link #mode(WriteMode)}
*/
public B overwrite(boolean overwrite) {
targetObj.setOverwrite(overwrite);
return thisObj;
this.targetObj.setOverwrite(overwrite);
return this.thisObj;
}
/**
* Sets a value indicating the action CredHub should take when a credential being written
* or generated already exists.
*
* As of CredHub 2.0, this value must not be set on write requests (write requests always
* overwrite the credential that already exists) but may be set on generate requests.
* Sets a value indicating the action CredHub should take when a credential being
* written or generated already exists.
*
* As of CredHub 2.0, this value must not be set on write requests (write requests
* always overwrite the credential that already exists) but may be set on generate
* requests.
* @param mode the {@link WriteMode} to use when a credential exists
* @return the builder
*/
public B mode(WriteMode mode) {
targetObj.setMode(mode);
return thisObj;
this.targetObj.setMode(mode);
return this.thisObj;
}
/**
* Add an {@link Permission} to the permissions that will be assigned to the
* credential.
*
* @param permission a {@link Permission} to assign to the credential
* @return the builder
* @deprecated as of CredHub 2.0, use {@link CredHubPermissionOperations} to assign
* permissions to a credential after it is created
* @deprecated as of CredHub 2.0, use {@link CredHubPermissionOperations} to
* assign permissions to a credential after it is created
*/
public B permission(Permission permission) {
targetObj.getAdditionalPermissions().add(permission);
return thisObj;
this.targetObj.getAdditionalPermissions().add(permission);
return this.thisObj;
}
/**
* Add a collection of {@link Permission}s to the controls that will be
* assigned to the credential.
*
* @param permissions a collection of {@link Permission}s to
* assign to the credential
* Add a collection of {@link Permission}s to the controls that will be assigned
* to the credential.
* @param permissions a collection of {@link Permission}s to assign to the
* credential
* @return the builder
* @deprecated as of CredHub 2.0, use {@link CredHubPermissionOperations} to assign
* permissions to a credential after it is created
* @deprecated as of CredHub 2.0, use {@link CredHubPermissionOperations} to
* assign permissions to a credential after it is created
*/
public B permissions(Collection<? extends Permission> permissions) {
targetObj.getAdditionalPermissions().addAll(permissions);
return thisObj;
this.targetObj.getAdditionalPermissions().addAll(permissions);
return this.thisObj;
}
/**
* Add a collection of {@link Permission}s to the controls that will be
* assigned to the credential.
*
* @param permissions a collection of {@link Permission}s to
* assign to the credential
* Add a collection of {@link Permission}s to the controls that will be assigned
* to the credential.
* @param permissions a collection of {@link Permission}s to assign to the
* credential
* @return the builder
* @deprecated as of CredHub 2.0, use {@link CredHubPermissionOperations} to assign
* permissions to a credential after it is created
* @deprecated as of CredHub 2.0, use {@link CredHubPermissionOperations} to
* assign permissions to a credential after it is created
*/
public B permissions(Permission... permissions) {
targetObj.getAdditionalPermissions().addAll(Arrays.asList(permissions));
return thisObj;
this.targetObj.getAdditionalPermissions().addAll(Arrays.asList(permissions));
return this.thisObj;
}
/**
* Create a {@link CredHubRequest} from the provided values.
*
* @return a {@link CredHubRequest}
*/
public R build() {
return targetObj;
return this.targetObj;
}
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,23 +16,25 @@
package org.springframework.credhub.support;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import java.util.Objects;
/**
* The details of a credential that has been written to CredHub.
*
* Clients don't typically instantiate objects of this type, but will receive them in response
* to write and retrieve requests. The {@literal id} and {@literal name} fields
* Clients don't typically instantiate objects of this type, but will receive them in
* response to write and retrieve requests. The {@literal id} and {@literal name} fields
* can be used in subsequent requests.
*
* @param <T> the type of CredHub credential
* @author Scott Frederick
*/
public class CredentialDetails<T> extends CredentialSummary {
private final String id;
@JsonProperty("type")
private final CredentialType credentialType;
@@ -52,12 +54,10 @@ public class CredentialDetails<T> extends CredentialSummary {
* Create a {@link CredentialDetails} from the provided parameters. Intended for
* internal use. Clients will get {@link CredentialDetails} objects populated from
* CredHub responses.
*
* @param id the CredHub-generated unique ID of the credential
* @param name the client-provided name of the credential
* @param credentialType the {@link CredentialType} of the credential
* @param value the client-provided value for the credential
* created
* @param value the client-provided value for the credential created
*/
public CredentialDetails(String id, CredentialName name, CredentialType credentialType, T value) {
super(name);
@@ -68,7 +68,6 @@ public class CredentialDetails<T> extends CredentialSummary {
/**
* Get the the CredHub-generated unique ID of the credential.
*
* @return the credential ID
*/
public String getId() {
@@ -77,7 +76,6 @@ public class CredentialDetails<T> extends CredentialSummary {
/**
* Get the client-provided {@link CredentialType} of the credential.
*
* @return the credential type
*/
public CredentialType getCredentialType() {
@@ -86,7 +84,6 @@ public class CredentialDetails<T> extends CredentialSummary {
/**
* Get the client-provided value for the credential.
*
* @return the credential value
*/
public T getValue() {
@@ -95,35 +92,37 @@ public class CredentialDetails<T> extends CredentialSummary {
@Override
public boolean equals(Object o) {
if (this == o)
if (this == o) {
return true;
if (!(o instanceof CredentialDetails))
}
if (!(o instanceof CredentialDetails)) {
return false;
}
CredentialDetails that = (CredentialDetails) o;
if (id != null ? !id.equals(that.id) : that.id != null)
if ((this.id != null) ? !this.id.equals(that.id) : (that.id != null)) {
return false;
if (credentialType != that.credentialType)
}
if (this.credentialType != that.credentialType) {
return false;
if (value != null ? !value.equals(that.value) : that.value != null)
}
if ((this.value != null) ? !this.value.equals(that.value) : (that.value != null)) {
return false;
}
return true;
}
@Override
public int hashCode() {
return Objects.hash(id, name, credentialType, value, versionCreatedAt);
return Objects.hash(this.id, this.name, this.credentialType, this.value, this.versionCreatedAt);
}
@Override
public String toString() {
return "CredentialDetails{"
+ "id='" + id + '\''
+ ", name=" + name
+ ", credentialType=" + credentialType
+ ", value=" + value
+ ", versionCreatedAt='" + versionCreatedAt + '\'' +
'}';
return "CredentialDetails{" + "id='" + this.id + '\'' + ", name=" + this.name + ", credentialType="
+ this.credentialType + ", value=" + this.value + ", versionCreatedAt='" + this.versionCreatedAt + '\''
+ '}';
}
}

View File

@@ -1,6 +1,5 @@
/*
*
* Copyright 2013-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,7 +12,6 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.springframework.credhub.support;
@@ -23,13 +21,14 @@ import java.util.List;
import java.util.Objects;
/**
* A collection of {@link CredentialDetails}. Clients don't typically instantiate
* objects of this type, but will receive them in response to write and retrieve
* requests.
* A collection of {@link CredentialDetails}. Clients don't typically instantiate objects
* of this type, but will receive them in response to write and retrieve requests.
*
* @param <T> the type of CredHub credential
* @author Scott Frederick
*/
public class CredentialDetailsData<T> {
private final List<CredentialDetails<T>> data;
/**
@@ -40,10 +39,9 @@ public class CredentialDetailsData<T> {
}
/**
* Create a {@link CredentialDetailsData} from the provided parameters. Intended for internal
* use. Clients will get {@link CredentialDetailsData} objects populated from
* Create a {@link CredentialDetailsData} from the provided parameters. Intended for
* internal use. Clients will get {@link CredentialDetailsData} objects populated from
* CredHub responses.
*
* @param data a collection of {@link CredentialDetails}
*/
@SafeVarargs
@@ -53,7 +51,6 @@ public class CredentialDetailsData<T> {
/**
* Get the collection of {@link CredentialDetails}.
*
* @return the collection of {@link CredentialDetails}
*/
public List<CredentialDetails<T>> getData() {
@@ -62,27 +59,29 @@ public class CredentialDetailsData<T> {
@Override
public boolean equals(Object o) {
if (this == o)
if (this == o) {
return true;
if (!(o instanceof CredentialDetailsData))
}
if (!(o instanceof CredentialDetailsData)) {
return false;
if (!super.equals(o))
}
if (!super.equals(o)) {
return false;
}
CredentialDetailsData that = (CredentialDetailsData) o;
return data != null ? data.equals(that.data) : that.data == null;
return (this.data != null) ? this.data.equals(that.data) : (that.data == null);
}
@Override
public int hashCode() {
return Objects.hashCode(data);
return Objects.hashCode(this.data);
}
@Override
public String toString() {
return "CredentialDetailData{"
+ "data=" + data
+ '}';
return "CredentialDetailData{" + "data=" + this.data + '}';
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -32,13 +32,13 @@ import org.springframework.util.StringUtils;
* @author Scott Frederick
*/
public class CredentialName {
@JsonIgnore
final String[] segments;
/**
* Create a name from the provided value. The name must consist of segments
* separated by the "/" character.
*
* Create a name from the provided value. The name must consist of segments separated
* by the "/" character.
* @param name the credential name; must not be {@literal null}
*/
CredentialName(String name) {
@@ -51,14 +51,14 @@ public class CredentialName {
if (split[0].length() == 0) {
// name contains a leading "/"
this.segments = Arrays.copyOfRange(split, 1, split.length);
} else {
}
else {
this.segments = split;
}
}
/**
* Create a name from the provided segments.
*
* @param segments the list of name segments; must not be {@literal null}
*/
CredentialName(String... segments) {
@@ -68,39 +68,40 @@ public class CredentialName {
/**
* Builds a name from the provided segments.
*
* @return the credential name
*/
@JsonInclude
public String getName() {
if (segments.length == 1) {
return segments[0];
} else {
return "/" + StringUtils.arrayToDelimitedString(segments, "/");
if (this.segments.length == 1) {
return this.segments[0];
}
else {
return "/" + StringUtils.arrayToDelimitedString(this.segments, "/");
}
}
@Override
public boolean equals(Object o) {
if (this == o)
if (this == o) {
return true;
if (!(o instanceof CredentialName))
}
if (!(o instanceof CredentialName)) {
return false;
}
CredentialName that = (CredentialName) o;
return Arrays.equals(segments, that.segments);
return Arrays.equals(this.segments, that.segments);
}
@Override
public int hashCode() {
return Objects.hashCode(segments);
return Objects.hashCode(this.segments);
}
@Override
public String toString() {
return "CredentialName{" +
getName() +
'}';
return "CredentialName{" + getName() + '}';
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -25,6 +25,7 @@ import java.util.Objects;
* @author Scott Frederick
*/
public class CredentialPath {
private final String path;
/**
@@ -36,10 +37,9 @@ public class CredentialPath {
}
/**
* Create a {@link CredentialPath} from the provided parameters. Intended for
* internal use. Clients will get {@link CredentialPath} objects populated from
* CredHub responses.
*
* Create a {@link CredentialPath} from the provided parameters. Intended for internal
* use. Clients will get {@link CredentialPath} objects populated from CredHub
* responses.
* @param path the name of the credential
*/
public CredentialPath(String path) {
@@ -48,7 +48,6 @@ public class CredentialPath {
/**
* Get the path to the credential.
*
* @return the credential path
*/
public String getPath() {
@@ -57,25 +56,26 @@ public class CredentialPath {
@Override
public boolean equals(Object o) {
if (this == o)
if (this == o) {
return true;
if (!(o instanceof CredentialPath))
}
if (!(o instanceof CredentialPath)) {
return false;
}
CredentialPath that = (CredentialPath) o;
return (path != null ? !path.equals(that.path) : that.path != null);
return ((this.path != null) ? !this.path.equals(that.path) : (that.path != null));
}
@Override
public int hashCode() {
return Objects.hashCode(path);
return Objects.hashCode(this.path);
}
@Override
public String toString() {
return "CredentialPath{"
+ "path=" + path
+ '}';
return "CredentialPath{" + "path=" + this.path + '}';
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -21,12 +21,13 @@ import java.util.List;
import java.util.Objects;
/**
* A collection of {@link CredentialPath}s. Clients don't typically instantiate
* objects of this type, but will receive them in response to requests.
* A collection of {@link CredentialPath}s. Clients don't typically instantiate objects of
* this type, but will receive them in response to requests.
*
* @author Scott Frederick
*/
public class CredentialPathData {
private final List<CredentialPath> paths;
/**
@@ -38,10 +39,9 @@ public class CredentialPathData {
}
/**
* Create a {@link CredentialPathData} from the provided parameters. Intended for internal
* use. Clients will get {@link CredentialPathData} objects populated from
* Create a {@link CredentialPathData} from the provided parameters. Intended for
* internal use. Clients will get {@link CredentialPathData} objects populated from
* CredHub responses.
*
* @param paths a collection of {@link CredentialPath}s
*/
public CredentialPathData(CredentialPath... paths) {
@@ -50,7 +50,6 @@ public class CredentialPathData {
/**
* Get the collection of {@link CredentialPath}s.
*
* @return the collection of {@link CredentialPath}s
*/
public List<CredentialPath> getPaths() {
@@ -59,28 +58,29 @@ public class CredentialPathData {
@Override
public boolean equals(Object o) {
if (this == o)
if (this == o) {
return true;
if (!(o instanceof CredentialPathData))
}
if (!(o instanceof CredentialPathData)) {
return false;
if (!super.equals(o))
}
if (!super.equals(o)) {
return false;
}
CredentialPathData that = (CredentialPathData) o;
return paths != null ? paths.equals(that.paths)
: that.paths == null;
return (this.paths != null) ? this.paths.equals(that.paths) : (that.paths == null);
}
@Override
public int hashCode() {
return Objects.hashCode(paths);
return Objects.hashCode(this.paths);
}
@Override
public String toString() {
return "CredentialPathData{"
+ "paths=" + paths
+ '}';
return "CredentialPathData{" + "paths=" + this.paths + '}';
}
}

View File

@@ -1,6 +1,5 @@
/*
*
* Copyright 2013-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -11,29 +10,30 @@
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permission and
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.springframework.credhub.support;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
import org.springframework.credhub.support.permissions.Permission;
import java.util.Objects;
import org.springframework.credhub.support.permissions.Permission;
/**
* A {@link Permission} associated with a credential. Clients don't typically instantiate
* objects of this type, but will receive them in response to write and retrieve
* requests.
* objects of this type, but will receive them in response to write and retrieve requests.
*
* @author Scott Frederick
*/
public class CredentialPermission {
@JsonProperty("uuid")
private final String uuid;
private final CredentialName path;
@JsonUnwrapped
@@ -50,10 +50,9 @@ public class CredentialPermission {
}
/**
* Create a {@link CredentialPermission} from the provided parameters. Intended for internal
* use. Clients will get {@link CredentialPermission} objects populated from
* Create a {@link CredentialPermission} from the provided parameters. Intended for
* internal use. Clients will get {@link CredentialPermission} objects populated from
* CredHub responses.
*
* @param path the path of the credential(s) that the permission will apply to
* @param permission a collection of {@link Permission}s
*/
@@ -65,7 +64,6 @@ public class CredentialPermission {
/**
* Get the CredHub-assigned ID of the permission.
*
* @return the permission ID
*/
public String getId() {
@@ -74,7 +72,6 @@ public class CredentialPermission {
/**
* Get the name of the credential that the permission apply to.
*
* @return the credential name
*/
public String getPath() {
@@ -83,38 +80,41 @@ public class CredentialPermission {
/**
* Get the collection of {@link Permission}s.
*
* @return the collection of {@link Permission}s
*/
public Permission getPermission() {
return this.permission;
}
@Override
public String toString() {
return "CredentialPermissions{"
+ "uuid=" + uuid
+ ", path=" + path
+ ", permission=" + permission
+ '}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof CredentialPermission)) return false;
if (this == o) {
return true;
}
if (!(o instanceof CredentialPermission)) {
return false;
}
CredentialPermission that = (CredentialPermission) o;
if (uuid != null ? !uuid.equals(that.uuid) : that.uuid != null)
if ((this.uuid != null) ? !this.uuid.equals(that.uuid) : (that.uuid != null)) {
return false;
if (path != null ? !path.equals(that.path) : that.path != null)
}
if ((this.path != null) ? !this.path.equals(that.path) : (that.path != null)) {
return false;
return permission != null ? permission.equals(that.permission) : that.permission == null;
}
return (this.permission != null) ? this.permission.equals(that.permission) : (that.permission == null);
}
@Override
public int hashCode() {
return Objects.hash(uuid, path, permission);
return Objects.hash(this.uuid, this.path, this.permission);
}
@Override
public String toString() {
return "CredentialPermissions{" + "uuid=" + this.uuid + ", path=" + this.path + ", permission="
+ this.permission + '}';
}
}

View File

@@ -1,6 +1,5 @@
/*
*
* Copyright 2013-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,26 +12,27 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.springframework.credhub.support;
import org.springframework.credhub.support.permissions.Permission;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import org.springframework.credhub.support.permissions.Permission;
/**
* A collection of {@link Permission}s associated with a credential. Clients don't
* typically instantiate objects of this type, but will receive them in response
* to write and retrieve requests.
* typically instantiate objects of this type, but will receive them in response to write
* and retrieve requests.
*
* @author Scott Frederick
*/
public class CredentialPermissions {
private final CredentialName credentialName;
private final List<Permission> permissions;
/**
@@ -45,10 +45,9 @@ public class CredentialPermissions {
}
/**
* Create a {@link CredentialPermissions} from the provided parameters. Intended for internal
* use. Clients will get {@link CredentialPermissions} objects populated from
* Create a {@link CredentialPermissions} from the provided parameters. Intended for
* internal use. Clients will get {@link CredentialPermissions} objects populated from
* CredHub responses.
*
* @param credentialName the name of the credential that the permissions will apply to
* @param permissions a collection of {@link Permission}s
*/
@@ -59,7 +58,6 @@ public class CredentialPermissions {
/**
* Get the name of the credential that the permissions apply to.
*
* @return the credential name
*/
public String getCredentialName() {
@@ -68,35 +66,39 @@ public class CredentialPermissions {
/**
* Get the collection of {@link Permission}s.
*
* @return the collection of {@link Permission}s
*/
public List<Permission> getPermissions() {
return this.permissions;
}
@Override
public String toString() {
return "CredentialPermissions{"
+ "credentialName=" + credentialName
+ ", permissions=" + permissions
+ '}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof CredentialPermissions)) return false;
if (this == o) {
return true;
}
if (!(o instanceof CredentialPermissions)) {
return false;
}
CredentialPermissions that = (CredentialPermissions) o;
if (credentialName != null ? !credentialName.equals(that.credentialName) : that.credentialName != null)
if ((this.credentialName != null) ? !this.credentialName.equals(that.credentialName)
: (that.credentialName != null)) {
return false;
return permissions != null ? permissions.equals(that.permissions) : that.permissions == null;
}
return (this.permissions != null) ? this.permissions.equals(that.permissions) : (that.permissions == null);
}
@Override
public int hashCode() {
return Objects.hash(credentialName, permissions);
return Objects.hash(this.credentialName, this.permissions);
}
@Override
public String toString() {
return "CredentialPermissions{" + "credentialName=" + this.credentialName + ", permissions=" + this.permissions
+ '}';
}
}

View File

@@ -1,6 +1,5 @@
/*
*
* Copyright 2013-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,7 +12,6 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.springframework.credhub.support;
@@ -21,12 +19,13 @@ package org.springframework.credhub.support;
/**
* The details of a request to write a new or update an existing credential in CredHub.
*
* @param <T> the type of CredHub credential
* @author Scott Frederick
*/
public class CredentialRequest<T> extends CredHubRequest<T> {
/**
* Initialize a {@link CredentialRequest}.
*
* @param type the credential implementation type
*/
protected CredentialRequest(CredentialType type) {
@@ -36,7 +35,6 @@ public class CredentialRequest<T> extends CredHubRequest<T> {
/**
* Get the value of the credential.
*
* @return the value of the credential
*/
public T getValue() {
@@ -46,4 +44,5 @@ public class CredentialRequest<T> extends CredHubRequest<T> {
protected void setValue(T value) {
this.details = value;
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -27,7 +27,9 @@ import java.util.Objects;
* @author Scott Frederick
*/
public class CredentialSummary {
protected final CredentialName name;
protected final Date versionCreatedAt;
/**
@@ -42,7 +44,6 @@ public class CredentialSummary {
* Create a {@link CredentialSummary} from the provided parameters. Intended for
* internal use. Clients will get {@link CredentialSummary} objects populated from
* CredHub responses.
*
* @param name the name of the credential
*/
public CredentialSummary(CredentialName name) {
@@ -52,7 +53,6 @@ public class CredentialSummary {
/**
* Get the client-provided name of the credential.
*
* @return the credential name
*/
public CredentialName getName() {
@@ -60,8 +60,8 @@ public class CredentialSummary {
}
/**
* Get the CredHub-generated {@link Date} when this version of the credential was created.
*
* Get the CredHub-generated {@link Date} when this version of the credential was
* created.
* @return the credential version creation {@link Date}
*/
public Date getVersionCreatedAt() {
@@ -70,29 +70,30 @@ public class CredentialSummary {
@Override
public boolean equals(Object o) {
if (this == o)
if (this == o) {
return true;
if (!(o instanceof CredentialSummary))
}
if (!(o instanceof CredentialSummary)) {
return false;
}
CredentialSummary that = (CredentialSummary) o;
if (name != null ? !name.equals(that.name) : that.name != null)
if ((this.name != null) ? !this.name.equals(that.name) : (that.name != null)) {
return false;
return versionCreatedAt != null ? versionCreatedAt.equals(that.versionCreatedAt)
: that.versionCreatedAt == null;
}
return (this.versionCreatedAt != null) ? this.versionCreatedAt.equals(that.versionCreatedAt)
: (that.versionCreatedAt == null);
}
@Override
public int hashCode() {
return Objects.hash(name, versionCreatedAt);
return Objects.hash(this.name, this.versionCreatedAt);
}
@Override
public String toString() {
return "CredentialSummary{"
+ "name=" + name
+ ", versionCreatedAt='" + versionCreatedAt + '\''
+ '}';
return "CredentialSummary{" + "name=" + this.name + ", versionCreatedAt='" + this.versionCreatedAt + '\'' + '}';
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -21,13 +21,13 @@ import java.util.List;
import java.util.Objects;
/**
* A collection of {@link CredentialSummary}s. Clients don't typically instantiate
* objects of this type, but will receive them in response to write and retrieve
* requests.
* A collection of {@link CredentialSummary}s. Clients don't typically instantiate objects
* of this type, but will receive them in response to write and retrieve requests.
*
* @author Scott Frederick
*/
public class CredentialSummaryData {
private final List<CredentialSummary> credentials;
/**
@@ -39,10 +39,9 @@ public class CredentialSummaryData {
}
/**
* Create a {@link CredentialSummaryData} from the provided parameters. Intended for internal
* use. Clients will get {@link CredentialSummaryData} objects populated from
* Create a {@link CredentialSummaryData} from the provided parameters. Intended for
* internal use. Clients will get {@link CredentialSummaryData} objects populated from
* CredHub responses.
*
* @param credentials a collection of {@link CredentialSummary}s
*/
public CredentialSummaryData(CredentialSummary... credentials) {
@@ -51,7 +50,6 @@ public class CredentialSummaryData {
/**
* Get the collection of {@link CredentialSummary}s.
*
* @return the collection of {@link CredentialSummary}s
*/
public List<CredentialSummary> getCredentials() {
@@ -60,28 +58,29 @@ public class CredentialSummaryData {
@Override
public boolean equals(Object o) {
if (this == o)
if (this == o) {
return true;
if (!(o instanceof CredentialSummaryData))
}
if (!(o instanceof CredentialSummaryData)) {
return false;
if (!super.equals(o))
}
if (!super.equals(o)) {
return false;
}
CredentialSummaryData that = (CredentialSummaryData) o;
return credentials != null ? credentials.equals(that.credentials)
: that.credentials == null;
return (this.credentials != null) ? this.credentials.equals(that.credentials) : (that.credentials == null);
}
@Override
public int hashCode() {
return Objects.hashCode(credentials);
return Objects.hashCode(this.credentials);
}
@Override
public String toString() {
return "CredentialSummaryData{"
+ "credentials=" + credentials
+ '}';
return "CredentialSummaryData{" + "credentials=" + this.credentials + '}';
}
}

View File

@@ -1,6 +1,5 @@
/*
*
* Copyright 2013-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,7 +12,6 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.springframework.credhub.support;
@@ -28,8 +26,11 @@ import org.springframework.credhub.support.value.ValueCredential;
/**
* The types of credentials that can be written to CredHub.
*
* @author Scott Frederick
*/
public enum CredentialType {
/**
* Indicates a credential of type {@link PasswordCredential}.
*/
@@ -66,6 +67,7 @@ public enum CredentialType {
JSON("json", JsonCredential.class);
private final String valueType;
private final Class<?> modelClass;
CredentialType(String valueType, Class<?> modelClass) {
@@ -75,26 +77,26 @@ public enum CredentialType {
/**
* Get the type value that will be used in requests to CredHub.
*
* @return the type value
*/
public String getValueType() {
return valueType;
return this.valueType;
}
/**
* Get the class that models requests of the credential type.
*
* @return the credential model class
*/
public Class<?> getModelClass() {
return modelClass;
return this.modelClass;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return valueType;
return this.valueType;
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -19,8 +19,20 @@ package org.springframework.credhub.support;
import com.fasterxml.jackson.annotation.JsonCreator;
public enum KeyLength {
/**
* 2048 bit key.
*/
LENGTH_2048(2048),
/**
* 3072 bit key.
*/
LENGTH_3072(3072),
/**
* 4096 bit key.
*/
LENGTH_4096(4096);
private final int length;
@@ -30,12 +42,11 @@ public enum KeyLength {
}
public int getLength() {
return length;
return this.length;
}
/**
* Convert an integer value to its enum value.
*
* @param length the integer value to convert to enum value
* @return the enum value
*/
@@ -48,4 +59,5 @@ public enum KeyLength {
}
return null;
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -24,26 +24,28 @@ import org.springframework.util.Assert;
* @author Scott Frederick
*/
public class KeyPairCredential {
private final String publicKey;
private final String privateKey;
/**
* Create an empty {@link KeyPairCredential}. Intended to be used internally for deserialization of responses.
* Create an empty {@link KeyPairCredential}. Intended to be used internally for
* deserialization of responses.
*/
protected KeyPairCredential() {
publicKey = null;
privateKey = null;
this.publicKey = null;
this.privateKey = null;
}
/**
* Create a {@link KeyPairCredential} from the provided parameters. Intended for internal use.
*
* Create a {@link KeyPairCredential} from the provided parameters. Intended for
* internal use.
* @param publicKey the public key
* @param privateKey the private key
*/
protected KeyPairCredential(String publicKey, String privateKey) {
Assert.isTrue(publicKey != null || privateKey != null,
"one of publicKey or privateKey must not be null");
Assert.isTrue(publicKey != null || privateKey != null, "one of publicKey or privateKey must not be null");
this.publicKey = publicKey;
this.privateKey = privateKey;
@@ -51,19 +53,18 @@ public class KeyPairCredential {
/**
* Get the value of the public key.
*
* @return the public key
*/
public String getPublicKey() {
return publicKey;
return this.publicKey;
}
/**
* Get the value of the private key.
*
* @return the private key
*/
public String getPrivateKey() {
return privateKey;
return this.privateKey;
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -22,6 +22,7 @@ package org.springframework.credhub.support;
* @author Scott Frederick
*/
public class KeyParameters {
protected final KeyLength keyLength;
/**
@@ -33,7 +34,6 @@ public class KeyParameters {
/**
* Create a {@link KeyParameters} with the specified key length.
*
* @param keyLength the length of the key to generate
*/
protected KeyParameters(KeyLength keyLength) {
@@ -42,10 +42,10 @@ public class KeyParameters {
/**
* Get the value of the key length parameter.
*
* @return the value of the parameter; will be {@literal null} if not explicitly set
*/
public Integer getKeyLength() {
return keyLength == null ? null : keyLength.getLength();
return (this.keyLength == null) ? null : this.keyLength.getLength();
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -19,21 +19,21 @@ package org.springframework.credhub.support;
/**
* The details of a request to generate a credential in CredHub.
*
* @param <T> the type of CredHub credential
* @author Scott Frederick
*/
public class ParametersRequest<T> extends CredHubRequest<T> {
/**
* Initialize a {@link ParametersRequest}.
*
* @param type the type of credential this request supports
*/
protected ParametersRequest(CredentialType type) {
credentialType = type;
this.credentialType = type;
}
/**
* Get the parameters of the credential.
*
* @return the parameters of the credential
*/
public T getParameters() {
@@ -43,4 +43,5 @@ public class ParametersRequest<T> extends CredHubRequest<T> {
protected void setParameters(T parameters) {
this.details = parameters;
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,16 +16,15 @@
package org.springframework.credhub.support;
import org.springframework.util.Assert;
import java.util.Arrays;
import org.springframework.util.Assert;
/**
* The client-provided name of a credential that stores service instance binding
* credentials. Service instance binding credential names consist of four segments:
* service broker name, service offering name, service binding GUID, and credential
* name. When these values are combined the full name of the credential will be of
* the form
* service broker name, service offering name, service binding GUID, and credential name.
* When these values are combined the full name of the credential will be of the form
* {@literal /c/service-broker-name/service-offering-name/binding-GUID/credential-name}.
*
* Objects of this type are created by clients and included as part of requests.
@@ -33,25 +32,24 @@ import java.util.Arrays;
* @author Scott Frederick
*/
public class ServiceInstanceCredentialName extends CredentialName {
/**
* Create a {@link ServiceInstanceCredentialName} from the required name fields.
* Intended for internal use in tests. Clients should use
* {@link #builder()} to construct instances of this class.
*
* Intended for internal use in tests. Clients should use {@link #builder()} to
* construct instances of this class.
* @param serviceBrokerName the human-readable name of the service broker
* @param serviceOfferingName the human-readable name of the service offering
* @param serviceBindingId the GUID of the service binding
* @param credentialName the name of the binding credential
*/
ServiceInstanceCredentialName(String serviceBrokerName, String serviceOfferingName,
String serviceBindingId, String credentialName) {
ServiceInstanceCredentialName(String serviceBrokerName, String serviceOfferingName, String serviceBindingId,
String credentialName) {
super("c", serviceBrokerName, serviceOfferingName, serviceBindingId, credentialName);
}
/**
* Create a builder that provides a fluent API for providing the values required
* to construct a {@link ServiceInstanceCredentialName}.
*
* Create a builder that provides a fluent API for providing the values required to
* construct a {@link ServiceInstanceCredentialName}.
* @return the builder
*/
public static ServiceInstanceCredentialNameBuilder builder() {
@@ -60,9 +58,7 @@ public class ServiceInstanceCredentialName extends CredentialName {
@Override
public String toString() {
return "ServiceInstanceCredentialName{"
+ "segments=" + Arrays.toString(segments)
+ "}";
return "ServiceInstanceCredentialName{" + "segments=" + Arrays.toString(this.segments) + "}";
}
/**
@@ -70,22 +66,25 @@ public class ServiceInstanceCredentialName extends CredentialName {
* {@link ServiceInstanceCredentialName} instances.
*/
public static class ServiceInstanceCredentialNameBuilder {
private String serviceBrokerName;
private String serviceOfferingName;
private String serviceBindingId;
private String credentialName;
/**
* Create a {@link ServiceInstanceCredentialNameBuilder}
* Create a {@link ServiceInstanceCredentialNameBuilder}.
*/
ServiceInstanceCredentialNameBuilder() {
}
/**
* Set the service broker name segment of the credential name. This is typically
* a human-readable name and should be unique among all service brokers in
* Cloud Foundry.
*
* Set the service broker name segment of the credential name. This is typically a
* human-readable name and should be unique among all service brokers in Cloud
* Foundry.
* @param serviceBrokerName the service broker name; must not be {@literal null}
* @return the builder
*/
@@ -98,8 +97,8 @@ public class ServiceInstanceCredentialName extends CredentialName {
/**
* Set the service offering name segment of the credential name. This is typically
* a human-readable name and should be unique within the service broker.
*
* @param serviceOfferingName the service offering name; must not be {@literal null}
* @param serviceOfferingName the service offering name; must not be
* {@literal null}
* @return the builder
*/
public ServiceInstanceCredentialNameBuilder serviceOfferingName(String serviceOfferingName) {
@@ -112,7 +111,6 @@ public class ServiceInstanceCredentialName extends CredentialName {
* Set the service binding ID segment of the credential name. This value is
* generated by Cloud Foundry when a service instance is bound to an application
* and is in the form of a GUID.
*
* @param serviceBindingId the service binding ID; must not be {@literal null}
* @return the builder
*/
@@ -124,7 +122,6 @@ public class ServiceInstanceCredentialName extends CredentialName {
/**
* Set the credential name segment of the full credential name.
*
* @param credentialName the credential name; must not be {@literal null}
* @return the builder
*/
@@ -136,12 +133,13 @@ public class ServiceInstanceCredentialName extends CredentialName {
/**
* Create a {@link ServiceInstanceCredentialName} from the provided values.
*
* @return a {@link ServiceInstanceCredentialName}
*/
public ServiceInstanceCredentialName build() {
return new ServiceInstanceCredentialName(serviceBrokerName,
serviceOfferingName, serviceBindingId, credentialName);
return new ServiceInstanceCredentialName(this.serviceBrokerName, this.serviceOfferingName,
this.serviceBindingId, this.credentialName);
}
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -21,10 +21,11 @@ import java.util.List;
import java.util.Map;
/**
* Service data parsed from the {@literal VCAP_SERVICES} environment variable provided to applications
* running on Cloud Foundry.
* Service data parsed from the {@literal VCAP_SERVICES} environment variable provided to
* applications running on Cloud Foundry.
*
* If the {@literal VCAP_SERVICES} environment variable for an application contains the following:
* If the {@literal VCAP_SERVICES} environment variable for an application contains the
* following:
*
* <pre>
* {@code
@@ -57,19 +58,22 @@ import java.util.Map;
* }
* </pre>
*
* Then the {@link ServicesData} data structure would hold the equivalent of this JSON structure parsed
* to a {@literal Map}.
* Then the {@link ServicesData} data structure would hold the equivalent of this JSON
* structure parsed to a {@literal Map}.
*
* @author Scott Frederick
*/
public class ServicesData extends HashMap<String, List<Map<String, Object>>> {
public ServicesData() {
}
/**
* Initialize with the provided {@link HashMap}.
*
* @param data a {@literal HashMap} to initialize this data structure from
*/
public ServicesData(HashMap<String, List<Map<String, Object>>> data) {
super(data);
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -28,9 +28,9 @@ import java.util.Arrays;
* @author Scott Frederick
*/
public class SimpleCredentialName extends CredentialName {
/**
* Create a {@link SimpleCredentialName} from the provided segments.
*
* @param segments the credential name segments; must not be {@literal null} and must
* contain at least one segment
*/
@@ -40,8 +40,7 @@ public class SimpleCredentialName extends CredentialName {
@Override
public String toString() {
return "SimpleCredentialName{"
+ "segments=" + Arrays.toString(segments)
+ "}";
return "SimpleCredentialName{" + "segments=" + Arrays.toString(segments) + "}";
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,21 +16,21 @@
package org.springframework.credhub.support;
import org.springframework.util.Assert;
import java.util.Objects;
import org.springframework.util.Assert;
/**
* A base type for a credential that contains a single string value.
*
* @author Scott Frederick
*/
public class StringCredential {
protected final String value;
/**
* Create a credential containing the specified value.
*
* @param value the credential value
*/
protected StringCredential(String value) {
@@ -40,23 +40,30 @@ public class StringCredential {
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof StringCredential)) return false;
if (this == o) {
return true;
}
if (!(o instanceof StringCredential)) {
return false;
}
StringCredential that = (StringCredential) o;
if (value != null ? !value.equals(that.value) : that.value != null) return false;
if ((this.value != null) ? !this.value.equals(that.value) : (that.value != null)) {
return false;
}
return true;
}
@Override
public int hashCode() {
return Objects.hashCode(value);
return Objects.hashCode(this.value);
}
@Override
public String toString() {
return value;
return this.value;
}
}

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.credhub.support;
/**
@@ -8,22 +24,23 @@ package org.springframework.credhub.support;
* @author Scott Frederick
*/
public enum WriteMode {
/**
* Indicates that CredHub should not replace the value of a credential
* if the credential exists
* Indicates that CredHub should not replace the value of a credential if the
* credential exists.
*/
NO_OVERWRITE("no-overwrite"),
/**
* Indicates that CredHub should replace any existing credential
* value with a new value
* Indicates that CredHub should replace any existing credential value with a new
* value.
*/
OVERWRITE("overwrite"),
/**
* Indicates that CredHub should replace any existing credential
* value with a new value only if generation parameters are different
* from the original generation parameters
* Indicates that CredHub should replace any existing credential value with a new
* value only if generation parameters are different from the original generation
* parameters.
*/
CONVERGE("converge");
@@ -34,18 +51,19 @@ public enum WriteMode {
}
/**
* Get the {@code mode} value as a {@code String}
*
* Get the {@code mode} value as a {@code String}.
* @return the mode value
*/
public String getMode() {
return mode;
return this.mode;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return mode;
return this.mode;
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -21,36 +21,39 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.util.Assert;
/**
* A certificate credential consists of a certificate, a certificate authority, and a private key. At least
* one of these three values must be provided.
* A certificate credential consists of a certificate, a certificate authority, and a
* private key. At least one of these three values must be provided.
*
* @author Scott Frederick
* @author Scott Frederick
*/
public class CertificateCredential {
private final String certificate;
@JsonProperty("ca")
private final String certificateAuthority;
private final String privateKey;
/**
* Create an empty {@link CertificateCredential}. Intended to be used internally for deserialization of responses.
* Create an empty {@link CertificateCredential}. Intended to be used internally for
* deserialization of responses.
*/
private CertificateCredential() {
certificate = null;
certificateAuthority = null;
privateKey = null;
this.certificate = null;
this.certificateAuthority = null;
this.privateKey = null;
}
/**
* Create an {@link CertificateCredential} from the provided public and private key. At least one of the key
* values must not be {@literal null}.
*
* @param certificate the certificate value; may be {@literal null} if one of the other parameters
* is not {@literal null}
* @param certificateAuthority the certificate authority value; may be {@literal null} if one of
* the other parameters is not {@literal null}
* @param privateKey the private key; may be {@literal null} if one of the other parameters is
* not {@literal null}
* Create an {@link CertificateCredential} from the provided public and private key.
* At least one of the key values must not be {@literal null}.
* @param certificate the certificate value; may be {@literal null} if one of the
* other parameters is not {@literal null}
* @param certificateAuthority the certificate authority value; may be {@literal null}
* if one of the other parameters is not {@literal null}
* @param privateKey the private key; may be {@literal null} if one of the other
* parameters is not {@literal null}
*/
public CertificateCredential(String certificate, String certificateAuthority, String privateKey) {
Assert.isTrue(certificate != null || certificateAuthority != null || privateKey != null,
@@ -60,31 +63,28 @@ public class CertificateCredential {
this.privateKey = privateKey;
}
/**
* Get the certificate value.
*
* @return the certificate
*/
public String getCertificate() {
return certificate;
return this.certificate;
}
/**
* Get the certificate authority value.
*
* @return the certificate authority
*/
public String getCertificateAuthority() {
return certificateAuthority;
return this.certificateAuthority;
}
/**
* Get the private key value.
*
* @return the private key
*/
public String getPrivateKey() {
return privateKey;
return this.privateKey;
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -21,16 +21,17 @@ import org.springframework.credhub.support.CredentialName;
import org.springframework.credhub.support.CredentialType;
/**
* The details of a certificate credential that has been written to CredHub. This is a specialization
* of {@link CredentialDetails} that adds certificate-specific fields.
* The details of a certificate credential that has been written to CredHub. This is a
* specialization of {@link CredentialDetails} that adds certificate-specific fields.
*
* Clients don't typically instantiate objects of this type, but will receive them in response
* to credential operation requests. The {@literal id} and {@literal name} fields
* Clients don't typically instantiate objects of this type, but will receive them in
* response to credential operation requests. The {@literal id} and {@literal name} fields
* can be used in subsequent requests.
*
* @author Scott Frederick
*/
public class CertificateCredentialDetails extends CredentialDetails<CertificateCredential> {
private final boolean transitional;
/**
@@ -43,29 +44,29 @@ public class CertificateCredentialDetails extends CredentialDetails<CertificateC
}
/**
* Create a {@link CertificateCredentialDetails} from the provided parameters. Intended for
* internal use. Clients will get {@link CertificateCredentialDetails} objects populated from
* CredHub responses.
*
* Create a {@link CertificateCredentialDetails} from the provided parameters.
* Intended for internal use. Clients will get {@link CertificateCredentialDetails}
* objects populated from CredHub responses.
* @param id the CredHub-generated unique ID of the credential
* @param name the client-provided name of the credential
* @param credentialType the {@link CredentialType} of the credential
* @param transitional a flag indicating whether the certificate will be used for signing
* @param transitional a flag indicating whether the certificate will be used for
* signing
* @param value the client-provided value for the credential
*/
public CertificateCredentialDetails(String id, CredentialName name, CredentialType credentialType,
boolean transitional, CertificateCredential value) {
boolean transitional, CertificateCredential value) {
super(id, name, credentialType, value);
this.transitional = transitional;
}
/**
* Get the value of the flag indicating whether the certificate is currently being used for signing
* or if it is being staged.
*
* Get the value of the flag indicating whether the certificate is currently being
* used for signing or if it is being staged.
* @return the transitional flag
*/
public boolean isTransitional() {
return transitional;
return this.transitional;
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -17,27 +17,27 @@
package org.springframework.credhub.support.certificate;
import org.springframework.credhub.support.CredentialRequest;
import org.springframework.credhub.support.CredentialType;
import org.springframework.util.Assert;
import static org.springframework.credhub.support.CredentialType.CERTIFICATE;
/**
* The details of a request to write a new or update an existing {@link CertificateCredential} in CredHub.
* The details of a request to write a new or update an existing
* {@link CertificateCredential} in CredHub.
*
* @author Scott Frederick
*/
public class CertificateCredentialRequest extends CredentialRequest<CertificateCredential> {
/**
* Initialize a {@link CredentialRequest}.
*/
CertificateCredentialRequest() {
super(CERTIFICATE);
super(CredentialType.CERTIFICATE);
}
/**
* Create a builder that provides a fluent API for providing the values required
* to construct a {@link CertificateCredentialRequest}.
*
* Create a builder that provides a fluent API for providing the values required to
* construct a {@link CertificateCredentialRequest}.
* @return a builder
*/
public static CertificateCredentialRequestBuilder builder() {
@@ -45,10 +45,12 @@ public class CertificateCredentialRequest extends CredentialRequest<CertificateC
}
/**
* A builder that provides a fluent API for constructing {@link CertificateCredentialRequest}s.
* A builder that provides a fluent API for constructing
* {@link CertificateCredentialRequest}s.
*/
public static class CertificateCredentialRequestBuilder
extends CredHubRequestBuilder<CertificateCredential, CertificateCredentialRequest, CertificateCredentialRequestBuilder> {
public static class CertificateCredentialRequestBuilder extends
CredHubRequestBuilder<CertificateCredential, CertificateCredentialRequest, CertificateCredentialRequestBuilder> {
@Override
protected CertificateCredentialRequest createTarget() {
return new CertificateCredentialRequest();
@@ -61,7 +63,6 @@ public class CertificateCredentialRequest extends CredentialRequest<CertificateC
/**
* Set the value of a certificate credential.
*
* @param value the credential value; must not be {@literal null}
* @return the builder
*/
@@ -70,5 +71,7 @@ public class CertificateCredentialRequest extends CredentialRequest<CertificateC
targetObj.setValue(value);
return this;
}
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -26,23 +26,37 @@ import org.springframework.util.Assert;
*
* @author Scott Frederick
*/
public class CertificateParameters extends KeyParameters {
private String commonName;
private String[] alternativeNames;
private String organization;
private String organizationUnit;
private String locality;
private String state;
private String country;
private String certificateAuthorityCredential;
private Boolean certificateAuthority;
private Boolean selfSign;
private Integer duration;
private KeyUsage[] keyUsage;
private ExtendedKeyUsage[] extendedKeyUsage;
public final class CertificateParameters extends KeyParameters {
private final String commonName;
private final String[] alternativeNames;
private final String organization;
private final String organizationUnit;
private final String locality;
private final String state;
private final String country;
private final String certificateAuthorityCredential;
private final Boolean certificateAuthority;
private final Boolean selfSign;
private final Integer duration;
private final KeyUsage[] keyUsage;
private final ExtendedKeyUsage[] extendedKeyUsage;
/**
* Create a {@link CertificateParameters} using defaults for all parameter values. Intended for internal use.
* Create a {@link CertificateParameters} using defaults for all parameter values.
* Intended for internal use.
*/
@SuppressWarnings("unused")
private CertificateParameters() {
@@ -62,13 +76,27 @@ public class CertificateParameters extends KeyParameters {
}
/**
* Create a {@link CertificateParameters} using the specified parameter values. Intended for internal use.
* Create a {@link CertificateParameters} using the specified parameter values.
* Intended for internal use.
* @param keyLength the parameter value; must not be {@literal null}
* @param commonName the parameter value; must not be {@literal null}
* @param alternativeNames the parameter value; must not be {@literal null}
* @param organization the parameter value; must not be {@literal null}
* @param organizationUnit the parameter value; must not be {@literal null}
* @param locality the parameter value; must not be {@literal null}
* @param state the parameter value; must not be {@literal null}
* @param country the parameter value; must not be {@literal null}
* @param duration the parameter value
* @param certificateAuthorityCredential the parameter value; must not be
* @param certificateAuthority the parameter value
* @param selfSign the parameter value
* @param keyUsage one or more parameter values
* @param extendedKeyUsage one or more parameter values
*/
private CertificateParameters(KeyLength keyLength, String commonName, String[] alternativeNames, String organization,
String organizationUnit, String locality, String state, String country,
Integer duration, String certificateAuthorityCredential,
Boolean certificateAuthority, Boolean selfSign,
KeyUsage[] keyUsage, ExtendedKeyUsage[] extendedKeyUsage) {
private CertificateParameters(KeyLength keyLength, String commonName, String[] alternativeNames,
String organization, String organizationUnit, String locality, String state, String country,
Integer duration, String certificateAuthorityCredential, Boolean certificateAuthority, Boolean selfSign,
KeyUsage[] keyUsage, ExtendedKeyUsage[] extendedKeyUsage) {
super(keyLength);
this.commonName = commonName;
this.alternativeNames = alternativeNames;
@@ -86,126 +114,125 @@ public class CertificateParameters extends KeyParameters {
}
/**
* Get the value of the common name parameter that will be used when generating the certificate.
*
* Get the value of the common name parameter that will be used when generating the
* certificate.
* @return the value of the parameter; will be {@literal null} if not explicitly set
*/
public String getCommonName() {
return commonName;
return this.commonName;
}
/**
* Get the value of the alternative names parameter that will be used when generating the certificate.
*
* Get the value of the alternative names parameter that will be used when generating
* the certificate.
* @return the value of the parameter; will be {@literal null} if not explicitly set
*/
public String[] getAlternativeNames() {
return alternativeNames;
return this.alternativeNames;
}
/**
* Get the value of the organization parameter that will be used when generating the certificate.
*
* Get the value of the organization parameter that will be used when generating the
* certificate.
* @return the value of the parameter; will be {@literal null} if not explicitly set
*/
public String getOrganization() {
return organization;
return this.organization;
}
/**
* Get the value of the organization unit parameter that will be used when generating the certificate.
*
* Get the value of the organization unit parameter that will be used when generating
* the certificate.
* @return the value of the parameter; will be {@literal null} if not explicitly set
*/
public String getOrganizationUnit() {
return organizationUnit;
return this.organizationUnit;
}
/**
* Get the value of the locality parameter that will be used when generating the certificate.
*
* Get the value of the locality parameter that will be used when generating the
* certificate.
* @return the value of the parameter; will be {@literal null} if not explicitly set
*/
public String getLocality() {
return locality;
return this.locality;
}
/**
* Get the value of the state parameter that will be used when generating the certificate.
*
* Get the value of the state parameter that will be used when generating the
* certificate.
* @return the value of the parameter; will be {@literal null} if not explicitly set
*/
public String getState() {
return state;
return this.state;
}
/**
* Get the value of the country parameter that will be used when generating the certificate.
*
* Get the value of the country parameter that will be used when generating the
* certificate.
* @return the value of the parameter; will be {@literal null} if not explicitly set
*/
public String getCountry() {
return country;
return this.country;
}
/**
* Get the value of the certificate authority parameter that will be used when generating the certificate.
*
* Get the value of the certificate authority parameter that will be used when
* generating the certificate.
* @return the value of the parameter; will be {@literal null} if not explicitly set
*/
public String getCa() {
return certificateAuthorityCredential;
return this.certificateAuthorityCredential;
}
/**
* Get the value of the flag that indicates whether the generated certificate is a certificate authority.
*
* Get the value of the flag that indicates whether the generated certificate is a
* certificate authority.
* @return the value of the parameter; will be {@literal null} if not explicitly set
*/
public Boolean getIsCa() {
return certificateAuthority;
return this.certificateAuthority;
}
/**
* Get the value of the flag that indicates whether the generated certificate is self-signed.
*
* Get the value of the flag that indicates whether the generated certificate is
* self-signed.
* @return the value of the parameter; will be {@literal null} if not explicitly set
*/
public Boolean getSelfSign() {
return selfSign;
return this.selfSign;
}
/**
* Get the value of the duration (in days) parameter that will be used when generating the certificate.
*
* Get the value of the duration (in days) parameter that will be used when generating
* the certificate.
* @return the value of the parameter; will be {@literal null} if not explicitly set
*/
public Integer getDuration() {
return duration;
return this.duration;
}
/**
* Get the value of the key usage extensions that will be used when generating the certificate.
*
* Get the value of the key usage extensions that will be used when generating the
* certificate.
* @return the value of the parameter; will be {@literal null} if not explicitly set
*/
public KeyUsage[] getKeyUsage() {
return keyUsage;
return this.keyUsage;
}
/**
* Get the value of the extended key usage extensions that will be used when generating the certificate.
*
* Get the value of the extended key usage extensions that will be used when
* generating the certificate.
* @return the value of the parameter; will be {@literal null} if not explicitly set
*/
public ExtendedKeyUsage[] getExtendedKeyUsage() {
return extendedKeyUsage;
return this.extendedKeyUsage;
}
/**
* Create a builder that provides a fluent API for providing the values required
* to construct a {@link CertificateParameters}.
*
* Create a builder that provides a fluent API for providing the values required to
* construct a {@link CertificateParameters}.
* @return a builder
*/
public static CertificateParametersBuilder builder() {
@@ -213,27 +240,41 @@ public class CertificateParameters extends KeyParameters {
}
/**
* A builder that provides a fluent API for constructing {@link CertificateParametersBuilder}s.
* A builder that provides a fluent API for constructing
* {@link CertificateParametersBuilder}s.
*/
public static class CertificateParametersBuilder {
private KeyLength keyLength;
private String commonName;
private String[] alternativeNames;
private String organization;
private String organizationUnit;
private String locality;
private String state;
private String country;
private Integer duration;
private String certificateAuthorityCredential;
private Boolean certificateAuthority;
private Boolean selfSign;
private KeyUsage[] keyUsage;
private ExtendedKeyUsage[] extendedKeyUsage;
/**
* Set the length of the key for the generated certificate.
*
* @param keyLength the parameter value; must not be {@literal null}
* @return the builder
*/
@@ -245,7 +286,6 @@ public class CertificateParameters extends KeyParameters {
/**
* Set the Common Name (CN) field to be used for the generated certificate.
*
* @param commonName the parameter value; must not be {@literal null}
* @return the builder
*/
@@ -257,7 +297,6 @@ public class CertificateParameters extends KeyParameters {
/**
* Set the Alternative Names (SAN) field to be used for the generated certificate.
*
* @param alternativeNames the parameter value; must not be {@literal null}
* @return the builder
*/
@@ -269,7 +308,6 @@ public class CertificateParameters extends KeyParameters {
/**
* Set the Organization (O) field to be used for the generated certificate.
*
* @param organization the parameter value; must not be {@literal null}
* @return the builder
*/
@@ -281,7 +319,6 @@ public class CertificateParameters extends KeyParameters {
/**
* Set the Organization Unit (OU) field to be used for the generated certificate.
*
* @param organizationUnit the parameter value; must not be {@literal null}
* @return the builder
*/
@@ -293,7 +330,6 @@ public class CertificateParameters extends KeyParameters {
/**
* Set the Locality (L) field to be used for the generated certificate.
*
* @param locality the parameter value; must not be {@literal null}
* @return the builder
*/
@@ -305,7 +341,6 @@ public class CertificateParameters extends KeyParameters {
/**
* Set the State (S) field to be used for the generated certificate.
*
* @param state the parameter value; must not be {@literal null}
* @return the builder
*/
@@ -317,7 +352,6 @@ public class CertificateParameters extends KeyParameters {
/**
* Set the Country (C) field to be used for the generated certificate.
*
* @param country the parameter value; must not be {@literal null}
* @return the builder
*/
@@ -329,7 +363,6 @@ public class CertificateParameters extends KeyParameters {
/**
* Set the duration in days that the generated certificate should be valid.
*
* @param duration the parameter value
* @return the builder
*/
@@ -339,9 +372,10 @@ public class CertificateParameters extends KeyParameters {
}
/**
* Set the name of a certificate authority credential in CredHub to sign the generated certificate with.
*
* @param certificateAuthorityCredential the parameter value; must not be {@literal null}
* Set the name of a certificate authority credential in CredHub to sign the
* generated certificate with.
* @param certificateAuthorityCredential the parameter value; must not be
* {@literal null}
* @return the builder
*/
public CertificateParametersBuilder certificateAuthorityCredential(String certificateAuthorityCredential) {
@@ -351,12 +385,14 @@ public class CertificateParameters extends KeyParameters {
}
/**
* Set the name of a certificate authority credential in CredHub to sign the generated certificate with.
*
* @param certificateAuthorityCredential the parameter value; must not be {@literal null}
* Set the name of a certificate authority credential in CredHub to sign the
* generated certificate with.
* @param certificateAuthorityCredential the parameter value; must not be
* {@literal null}
* @return the builder
*/
public CertificateParametersBuilder certificateAuthorityCredential(CredentialName certificateAuthorityCredential) {
public CertificateParametersBuilder certificateAuthorityCredential(
CredentialName certificateAuthorityCredential) {
Assert.notNull(certificateAuthorityCredential, "certificateAuthorityCredential must not be null");
this.certificateAuthorityCredential = certificateAuthorityCredential.getName();
return this;
@@ -365,7 +401,6 @@ public class CertificateParameters extends KeyParameters {
/**
* Set the value of the flag that indicates whether the generated certificate is a
* certificate authority.
*
* @param certificateAuthority the parameter value
* @return the builder
*/
@@ -375,9 +410,8 @@ public class CertificateParameters extends KeyParameters {
}
/**
* Set the value of the flag that indicates whether the generated certificate should be
* self-signed.
*
* Set the value of the flag that indicates whether the generated certificate
* should be self-signed.
* @param selfSign the parameter value
* @return the builder
*/
@@ -388,7 +422,6 @@ public class CertificateParameters extends KeyParameters {
/**
* Set the value of the key usage extensions for the generated certificate.
*
* @param keyUsage one or more parameter values
* @return the builder
*/
@@ -398,8 +431,8 @@ public class CertificateParameters extends KeyParameters {
}
/**
* Set the value of the extended key usage extensions for the generated certificate.
*
* Set the value of the extended key usage extensions for the generated
* certificate.
* @param extendedKeyUsage one or more parameter values
* @return the builder
*/
@@ -410,18 +443,21 @@ public class CertificateParameters extends KeyParameters {
/**
* Create a {@link CertificateParameters} from the provided values.
*
* @return the created {@link CertificateParameters}
*/
public CertificateParameters build() {
Assert.isTrue(commonName != null || organization != null || organizationUnit != null ||
locality != null || state != null || country != null,
Assert.isTrue(
this.commonName != null || this.organization != null || this.organizationUnit != null
|| this.locality != null || this.state != null || this.country != null,
"at least one subject parameter must be specified");
Assert.isTrue(certificateAuthorityCredential != null || certificateAuthority != null || selfSign != null,
"at least one signing parameter must be specified");
return new CertificateParameters(keyLength, commonName, alternativeNames, organization, organizationUnit,
locality, state, country, duration, certificateAuthorityCredential, certificateAuthority, selfSign,
keyUsage, extendedKeyUsage);
Assert.isTrue(this.certificateAuthorityCredential != null || this.certificateAuthority != null
|| this.selfSign != null, "at least one signing parameter must be specified");
return new CertificateParameters(this.keyLength, this.commonName, this.alternativeNames, this.organization,
this.organizationUnit, this.locality, this.state, this.country, this.duration,
this.certificateAuthorityCredential, this.certificateAuthority, this.selfSign, this.keyUsage,
this.extendedKeyUsage);
}
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,28 +16,27 @@
package org.springframework.credhub.support.certificate;
import org.springframework.credhub.support.CredentialType;
import org.springframework.credhub.support.ParametersRequest;
import org.springframework.util.Assert;
import static org.springframework.credhub.support.CredentialType.CERTIFICATE;
/**
* The details of a request to generate a new {@link CertificateCredential} in CredHub.
*
* @author Scott Frederick
*/
public class CertificateParametersRequest extends ParametersRequest<CertificateParameters> {
/**
* Create a {@link CertificateParametersRequest}.
*/
CertificateParametersRequest() {
super(CERTIFICATE);
super(CredentialType.CERTIFICATE);
}
/**
* Create a builder that provides a fluent API for providing the values required
* to construct a {@link CertificateParametersRequest}.
*
* Create a builder that provides a fluent API for providing the values required to
* construct a {@link CertificateParametersRequest}.
* @return a builder
*/
public static CertificateParametersRequestBuilder builder() {
@@ -45,10 +44,12 @@ public class CertificateParametersRequest extends ParametersRequest<CertificateP
}
/**
* A builder that provides a fluent API for constructing {@link CertificateParametersRequest}s.
* A builder that provides a fluent API for constructing
* {@link CertificateParametersRequest}s.
*/
public static class CertificateParametersRequestBuilder
extends CredHubRequestBuilder<CertificateParameters, CertificateParametersRequest, CertificateParametersRequestBuilder> {
public static class CertificateParametersRequestBuilder extends
CredHubRequestBuilder<CertificateParameters, CertificateParametersRequest, CertificateParametersRequestBuilder> {
@Override
protected CertificateParametersRequest createTarget() {
return new CertificateParametersRequest();
@@ -61,14 +62,15 @@ public class CertificateParametersRequest extends ParametersRequest<CertificateP
/**
* Set the parameters for generation of a password credential.
*
* @param parameters the generation parameters; must not be {@literal null}
* @return the builder
*/
public CertificateParametersRequestBuilder parameters(CertificateParameters parameters) {
Assert.notNull(parameters, "parameters must not be null");
targetObj.setParameters(parameters);
this.targetObj.setParameters(parameters);
return this;
}
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -26,21 +26,21 @@ import java.util.Objects;
* @author Scott Frederick
*/
public class CertificateSummary {
private final String id;
private final String name;
@SuppressWarnings("unused")
private CertificateSummary() {
id = null;
name = null;
this.id = null;
this.name = null;
}
/**
* Create a {@link CertificateSummary} from the provided parameters. Intended for
* internal use. Clients will get {@link CertificateSummary} objects populated from
* CredHub responses.
*
* @param id the ID of the certificate credential
* @param name the name of the certificate credential
*/
@@ -51,20 +51,18 @@ public class CertificateSummary {
/**
* Get the CredHub-generated ID of the certificate credential.
*
* @return the credential ID
*/
public String getId() {
return id;
return this.id;
}
/**
* Get the client-provided name of the certificate credential.
*
* @return the credential name
*/
public String getName() {
return name;
return this.name;
}
@Override
@@ -76,20 +74,17 @@ public class CertificateSummary {
return false;
}
CertificateSummary that = (CertificateSummary) o;
return Objects.equals(id, that.id) &&
Objects.equals(name, that.name);
return Objects.equals(this.id, that.id) && Objects.equals(this.name, that.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
return Objects.hash(this.id, this.name);
}
@Override
public String toString() {
return "CertificateSummary{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
'}';
return "CertificateSummary{" + "id='" + this.id + '\'' + ", name='" + this.name + '\'' + '}';
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -27,6 +27,7 @@ import java.util.Objects;
* @author Scott Frederick
*/
public class CertificateSummaryData {
private List<CertificateSummary> certificates;
/**
@@ -37,10 +38,9 @@ public class CertificateSummaryData {
}
/**
* Create a {@link CertificateSummaryData} from the provided parameters. Intended for internal
* use. Clients will get {@link CertificateSummaryData} objects populated from
* CredHub responses.
*
* Create a {@link CertificateSummaryData} from the provided parameters. Intended for
* internal use. Clients will get {@link CertificateSummaryData} objects populated
* from CredHub responses.
* @param certificates a collection of {@link CertificateSummary}s
*/
public CertificateSummaryData(CertificateSummary... certificates) {
@@ -49,7 +49,6 @@ public class CertificateSummaryData {
/**
* Get the collection of {@link CertificateSummary}s.
*
* @return the collection of {@link CertificateSummary}s
*/
public List<CertificateSummary> getCertificates() {
@@ -58,28 +57,29 @@ public class CertificateSummaryData {
@Override
public boolean equals(Object o) {
if (this == o)
if (this == o) {
return true;
if (!(o instanceof CertificateSummaryData))
}
if (!(o instanceof CertificateSummaryData)) {
return false;
if (!super.equals(o))
}
if (!super.equals(o)) {
return false;
}
CertificateSummaryData that = (CertificateSummaryData) o;
return certificates != null ? certificates.equals(that.certificates)
: that.certificates == null;
return (this.certificates != null) ? this.certificates.equals(that.certificates) : (that.certificates == null);
}
@Override
public int hashCode() {
return Objects.hashCode(certificates);
return Objects.hashCode(this.certificates);
}
@Override
public String toString() {
return "CertificateSummaryData{"
+ "certificates=" + certificates
+ '}';
return "CertificateSummaryData{" + "certificates=" + this.certificates + '}';
}
}

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.credhub.support.certificate;
/**
@@ -7,10 +23,30 @@ package org.springframework.credhub.support.certificate;
* @author Scott Frederick
*/
public enum ExtendedKeyUsage {
/**
* Client authentication.
*/
CLIENT_AUTH("client_auth"),
/**
* Server authentication.
*/
SERVER_AUTH("server_auth"),
/**
* Code signing.
*/
CODE_SIGNING("code_signing"),
/**
* Email protection.
*/
EMAIL_PROTECTION("email_protection"),
/**
* Time stamping.
*/
TIMESTAMPING("timestamping");
private final String value;
@@ -20,18 +56,19 @@ public enum ExtendedKeyUsage {
}
/**
* Get the value as a {@code String}
*
* Get the value as a {@code String}.
* @return the mode value
*/
public String getValue() {
return value;
return this.value;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return value;
return this.value;
}
}

View File

@@ -1,22 +1,73 @@
/*
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.credhub.support.certificate;
/**
* The types of key usage extensions that can be assigned to a generated
* certificate.
* The types of key usage extensions that can be assigned to a generated certificate.
*
* @author Scott Frederick
*/
public enum KeyUsage {
/**
* Digital signature key.
*/
DIGITAL_SIGNATURE("digital_signature"),
/**
* Non-repudiation key.
*/
NON_REPUDIATION("non_repudiation"),
/**
* Key encipherment key.
*/
KEY_ENCIPHERMENT("key_encipherment"),
/**
* Data encipherment key.
*/
DATA_ENCIPHERMENT("data_encipherment"),
/**
* Key agreement key.
*/
KEY_AGREEMENT("key_agreement"),
/**
* Key certificate signing key.
*/
KEY_CERT_SIGN("key_cert_sign"),
/**
* CRL signing key.
*/
CRL_SIGN("crl_sign"),
/**
* Encipher only key.
*/
ENCIPHER_ONLY("encipher_only"),
/**
* Decipher only key.
*/
DECIPHER_ONLY("decipher_only");
private final String value;
KeyUsage(String value) {
@@ -24,18 +75,19 @@ public enum KeyUsage {
}
/**
* Get the value as a {@code String}
*
* Get the value as a {@code String}.
* @return the mode value
*/
public String getValue() {
return value;
return this.value;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return value;
return this.value;
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -17,4 +17,4 @@
/**
* Java representations of CredHub certificate credentials.
*/
package org.springframework.credhub.support.certificate;
package org.springframework.credhub.support.certificate;

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -22,6 +22,7 @@ package org.springframework.credhub.support.info;
* @author Scott Frederick
*/
public class VersionInfo {
private final String version;
@SuppressWarnings("unused")
@@ -30,10 +31,9 @@ public class VersionInfo {
}
/**
* Create a new {@literal VersionInfo} containing the specified version string. Intended for
* internal use. Clients will get {@literal VersionInfo} objects populated from
* CredHub responses.
*
* Create a new {@literal VersionInfo} containing the specified version string.
* Intended for internal use. Clients will get {@literal VersionInfo} objects
* populated from CredHub responses.
* @param version a version string
*/
public VersionInfo(String version) {
@@ -42,7 +42,6 @@ public class VersionInfo {
/**
* Get the value of the version string returned from the CredHub server.
*
* @return the version string
*/
public String getVersion() {
@@ -51,8 +50,8 @@ public class VersionInfo {
/**
* Determine if the CredHub server implements the v1 API.
*
* @return {@code true} if the server implements the CredHub v1 API; {@code false} otherwise
* @return {@code true} if the server implements the CredHub v1 API; {@code false}
* otherwise
*/
public boolean isVersion1() {
return this.version.startsWith("1.");
@@ -60,8 +59,8 @@ public class VersionInfo {
/**
* Determine if the CredHub server implements the v2 API.
*
* @return {@code true} if the server implements the CredHub v2 API; {@code false} otherwise
* @return {@code true} if the server implements the CredHub v2 API; {@code false}
* otherwise
*/
public boolean isVersion2() {
return this.version.startsWith("2.");
@@ -69,8 +68,8 @@ public class VersionInfo {
/**
* Determine if the CredHub server implements the v2.0 API.
*
* @return {@code true} if the server implements the CredHub v2.0 API; {@code false} otherwise
* @return {@code true} if the server implements the CredHub v2.0 API; {@code false}
* otherwise
*/
public boolean isVersion2_0() {
return this.version.startsWith("2.0");
@@ -78,10 +77,11 @@ public class VersionInfo {
/**
* Determine if the CredHub server implements the v2.1 API.
*
* @return {@code true} if the server implements the CredHub v2.1 API; {@code false} otherwise
* @return {@code true} if the server implements the CredHub v2.1 API; {@code false}
* otherwise
*/
public boolean isVersion2_1() {
return this.version.startsWith("2.1");
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -17,4 +17,4 @@
/**
* Java representations of CredHub server information.
*/
package org.springframework.credhub.support.info;
package org.springframework.credhub.support.info;

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -20,13 +20,16 @@ import java.util.HashMap;
import java.util.Map;
/**
* A JSON credential consists of one or more fields in a JSON document. The JSON document is represented as a
* {@literal Map} object, which will be converted to a JSON document before sending to CredHub.
* A JSON credential consists of one or more fields in a JSON document. The JSON document
* is represented as a {@literal Map} object, which will be converted to a JSON document
* before sending to CredHub.
*
* @author Scott Frederick
*/
public class JsonCredential extends HashMap<String, Object> {
/**
* Create a {@code JsonCredential}.
* @see HashMap#HashMap()
*/
public JsonCredential() {
@@ -34,30 +37,32 @@ public class JsonCredential extends HashMap<String, Object> {
}
/**
* Create a {@code JsonCredential} with the specified initial capacity.
* @param initialCapacity the initial capacity
* @see HashMap#HashMap(int)
*
* @param initialCapacity the initial capacity
*/
public JsonCredential(int initialCapacity) {
super(initialCapacity);
}
/**
* @see HashMap#HashMap(int, float)
*
* Create a {@code JsonCredential} with the specified initial capacity and load
* factor.
* @param initialCapacity the initial capacity
* @param loadFactor the load factor
* @param loadFactor the load factor
* @see HashMap#HashMap(int, float)
*/
public JsonCredential(int initialCapacity, float loadFactor) {
super(initialCapacity, loadFactor);
}
/**
* @see HashMap#HashMap(Map)
*
* Create a {@code JsonCredential} from the provided Map.
* @param m the map whose mappings are to be placed in this map
* @see HashMap#HashMap(Map)
*/
public JsonCredential(Map<? extends String, ?> m) {
super(m);
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,30 +16,30 @@
package org.springframework.credhub.support.json;
import org.springframework.credhub.support.CredentialRequest;
import org.springframework.util.Assert;
import java.util.Map;
import static org.springframework.credhub.support.CredentialType.JSON;
import org.springframework.credhub.support.CredentialRequest;
import org.springframework.credhub.support.CredentialType;
import org.springframework.util.Assert;
/**
* The details of a request to write a new or update an existing {@link JsonCredential} in CredHub.
* The details of a request to write a new or update an existing {@link JsonCredential} in
* CredHub.
*
* @author Scott Frederick
*/
public class JsonCredentialRequest extends CredentialRequest<JsonCredential> {
/**
* Initialize a {@link CredentialRequest}.
*/
JsonCredentialRequest() {
super(JSON);
super(CredentialType.JSON);
}
/**
* Create a builder that provides a fluent API for providing the values required
* to construct a {@link JsonCredentialRequest}.
*
* Create a builder that provides a fluent API for providing the values required to
* construct a {@link JsonCredentialRequest}.
* @return a builder
*/
public static JsonCredentialRequestBuilder builder() {
@@ -47,10 +47,11 @@ public class JsonCredentialRequest extends CredentialRequest<JsonCredential> {
}
/**
* A builder that provides a fluent API for constructing {@link JsonCredentialRequest}s.
* A builder that provides a fluent API for constructing
* {@link JsonCredentialRequest}s.
*/
public static class JsonCredentialRequestBuilder extends
CredHubRequestBuilder<JsonCredential, JsonCredentialRequest, JsonCredentialRequestBuilder> {
public static class JsonCredentialRequestBuilder
extends CredHubRequestBuilder<JsonCredential, JsonCredentialRequest, JsonCredentialRequestBuilder> {
@Override
protected JsonCredentialRequest createTarget() {
@@ -64,7 +65,6 @@ public class JsonCredentialRequest extends CredentialRequest<JsonCredential> {
/**
* Set the value of a JSON credential.
*
* @param value the credential value; must not be {@literal null}
* @return the builder
*/
@@ -78,6 +78,7 @@ public class JsonCredentialRequest extends CredentialRequest<JsonCredential> {
value(new JsonCredential(value));
return this;
}
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -17,4 +17,4 @@
/**
* Java representations of CredHub JSON credentials.
*/
package org.springframework.credhub.support.json;
package org.springframework.credhub.support.json;

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -17,4 +17,4 @@
/**
* Java representations of CredHub requests and responses.
*/
package org.springframework.credhub.support;
package org.springframework.credhub.support;

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -18,6 +18,7 @@ package org.springframework.credhub.support.password;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import org.springframework.credhub.support.StringCredential;
/**
@@ -26,9 +27,9 @@ import org.springframework.credhub.support.StringCredential;
* @author Scott Frederick
*/
public class PasswordCredential extends StringCredential {
/**
* Create a {@link PasswordCredential} containing the specified password value.
*
* @param value the password; must not be {@literal null}
*/
@JsonCreator
@@ -38,11 +39,11 @@ public class PasswordCredential extends StringCredential {
/**
* Get the password value.
*
* @return the password value
*/
@JsonValue
public String getPassword() {
return value;
return this.value;
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -17,27 +17,27 @@
package org.springframework.credhub.support.password;
import org.springframework.credhub.support.CredentialRequest;
import org.springframework.credhub.support.CredentialType;
import org.springframework.util.Assert;
import static org.springframework.credhub.support.CredentialType.PASSWORD;
/**
* The details of a request to write a new or update an existing {@link PasswordCredential} in CredHub.
* The details of a request to write a new or update an existing
* {@link PasswordCredential} in CredHub.
*
* @author Scott Frederick
*/
public class PasswordCredentialRequest extends CredentialRequest<PasswordCredential> {
/**
* Initialize a {@link CredentialRequest}.
*/
PasswordCredentialRequest() {
super(PASSWORD);
super(CredentialType.PASSWORD);
}
/**
* Create a builder that provides a fluent API for providing the values required
* to construct a {@link PasswordCredentialRequest}.
*
* Create a builder that provides a fluent API for providing the values required to
* construct a {@link PasswordCredentialRequest}.
* @return a builder
*/
public static PasswordCredentialRequestBuilder builder() {
@@ -45,10 +45,12 @@ public class PasswordCredentialRequest extends CredentialRequest<PasswordCredent
}
/**
* A builder that provides a fluent API for constructing {@link PasswordCredentialRequest}s.
* A builder that provides a fluent API for constructing
* {@link PasswordCredentialRequest}s.
*/
public static class PasswordCredentialRequestBuilder
extends CredHubRequestBuilder<PasswordCredential, PasswordCredentialRequest, PasswordCredentialRequestBuilder> {
public static class PasswordCredentialRequestBuilder extends
CredHubRequestBuilder<PasswordCredential, PasswordCredentialRequest, PasswordCredentialRequestBuilder> {
@Override
protected PasswordCredentialRequest createTarget() {
return new PasswordCredentialRequest();
@@ -61,19 +63,17 @@ public class PasswordCredentialRequest extends CredentialRequest<PasswordCredent
/**
* Set the value of a password credential.
*
* @param value the credential value; must not be {@literal null}
* @return the builder
*/
public PasswordCredentialRequestBuilder value(PasswordCredential value) {
Assert.notNull(value, "value must not be null");
targetObj.setValue(value);
this.targetObj.setValue(value);
return this;
}
/**
* Set the value of a password credential.
*
* Set the value of a password credential.
* @param value the credential value; must not be {@literal null}
* @return the builder
*/
@@ -81,6 +81,7 @@ public class PasswordCredentialRequest extends CredentialRequest<PasswordCredent
value(new PasswordCredential(value));
return this;
}
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -17,40 +17,48 @@
package org.springframework.credhub.support.password;
/**
* Parameters for generating a new password credential. All parameters are optional; if not specified,
* CredHub-provided defaults will be used.
* Parameters for generating a new password credential. All parameters are optional; if
* not specified, CredHub-provided defaults will be used.
*
* @author Scott Frederick
*/
public class PasswordParameters {
private final Integer length;
private final Boolean excludeUpper;
private final Boolean excludeLower;
private final Boolean excludeNumber;
private final Boolean includeSpecial;
/**
* Create a {@link PasswordParameters} using defaults for all parameter values.
*/
public PasswordParameters() {
length = null;
excludeUpper = null;
excludeLower = null;
excludeNumber = null;
includeSpecial = null;
this.length = null;
this.excludeUpper = null;
this.excludeLower = null;
this.excludeNumber = null;
this.includeSpecial = null;
}
/**
* Create a {@link PasswordParameters} using the specified values.
*
* @param length length of generated password value
* @param excludeUpper {@literal true} to exclude upper case alpha characters from generated credential value
* @param excludeLower {@literal true} to exclude lower case alpha characters from generated credential value
* @param excludeNumber {@literal true} to exclude numeric characters from generated credential value
* @param includeSpecial {@literal true} to include non-alphanumeric characters in generated credential value
* @param excludeUpper {@literal true} to exclude upper case alpha characters from
* generated credential value
* @param excludeLower {@literal true} to exclude lower case alpha characters from
* generated credential value
* @param excludeNumber {@literal true} to exclude numeric characters from generated
* credential value
* @param includeSpecial {@literal true} to include non-alphanumeric characters in
* generated credential value
*/
public PasswordParameters(int length, boolean excludeUpper, boolean excludeLower,
boolean excludeNumber, boolean includeSpecial) {
public PasswordParameters(int length, boolean excludeUpper, boolean excludeLower, boolean excludeNumber,
boolean includeSpecial) {
this.length = length;
this.excludeUpper = excludeUpper;
this.excludeLower = excludeLower;
@@ -60,53 +68,47 @@ public class PasswordParameters {
/**
* Get the value of the length parameter.
*
* @return the value of the parameter; will be {@literal null} if not explicitly set
*/
public Integer getLength() {
return length;
return this.length;
}
/**
* Get the value of the exclude upper case characters parameter.
*
* @return the value of the parameter; will be {@literal null} if not explicitly set
*/
public Boolean getExcludeUpper() {
return excludeUpper;
return this.excludeUpper;
}
/**
* Get the value of the exclude lower case characters parameter.
*
* @return the value of the parameter; will be {@literal null} if not explicitly set
*/
public Boolean getExcludeLower() {
return excludeLower;
return this.excludeLower;
}
/**
* Get the value of the exclude numeric characters parameter.
*
* @return the value of the parameter; will be {@literal null} if not explicitly set
*/
public Boolean getExcludeNumber() {
return excludeNumber;
return this.excludeNumber;
}
/**
* Get the value of the include non-alphanumeric characters parameter.
*
* @return the value of the parameter; will be {@literal null} if not explicitly set
*/
public Boolean getIncludeSpecial() {
return includeSpecial;
return this.includeSpecial;
}
/**
* Create a builder that provides a fluent API for providing the values required
* to construct a {@link PasswordParameters}.
*
* Create a builder that provides a fluent API for providing the values required to
* construct a {@link PasswordParameters}.
* @return a builder
*/
public static PasswordParametersBuilder builder() {
@@ -114,18 +116,23 @@ public class PasswordParameters {
}
/**
* A builder that provides a fluent API for constructing {@link PasswordParametersBuilder}s.
* A builder that provides a fluent API for constructing
* {@link PasswordParametersBuilder}s.
*/
public static class PasswordParametersBuilder {
private Integer length = null;
private Boolean excludeUpper = null;
private Boolean excludeLower = null;
private Boolean excludeNumber = null;
private Boolean includeSpecial = null;
/**
* Set the value of the password length parameter.
*
* @param length the parameter value
* @return the builder
*/
@@ -136,8 +143,8 @@ public class PasswordParameters {
/**
* Set the value of the exclude upper case characters parameter.
*
* @param exclude {@literal true} to exclude upper case alpha characters from generated credential value
* @param exclude {@literal true} to exclude upper case alpha characters from
* generated credential value
* @return the builder
*/
public PasswordParametersBuilder excludeUpper(boolean exclude) {
@@ -147,8 +154,8 @@ public class PasswordParameters {
/**
* Set the value of the exclude lower case characters parameter.
*
* @param exclude {@literal true} to exclude lower case alpha characters from generated credential value
* @param exclude {@literal true} to exclude lower case alpha characters from
* generated credential value
* @return the builder
*/
public PasswordParametersBuilder excludeLower(boolean exclude) {
@@ -158,8 +165,8 @@ public class PasswordParameters {
/**
* Set the value of the exclude numeric characters parameter.
*
* @param exclude {@literal true} to exclude numeric characters from generated credential value
* @param exclude {@literal true} to exclude numeric characters from generated
* credential value
* @return the builder
*/
public PasswordParametersBuilder excludeNumber(boolean exclude) {
@@ -169,8 +176,8 @@ public class PasswordParameters {
/**
* Set the value of the include special characters parameter.
*
* @param include {@literal true} to include non-alphanumeric characters in generated credential value
* @param include {@literal true} to include non-alphanumeric characters in
* generated credential value
* @return the builder
*/
public PasswordParametersBuilder includeSpecial(boolean include) {
@@ -180,11 +187,13 @@ public class PasswordParameters {
/**
* Create a {@link PasswordParameters} from the provided values.
*
* @return the created {@link PasswordParameters}
*/
public PasswordParameters build() {
return new PasswordParameters(length, excludeUpper, excludeLower, excludeNumber, includeSpecial);
return new PasswordParameters(this.length, this.excludeUpper, this.excludeLower, this.excludeNumber,
this.includeSpecial);
}
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,28 +16,27 @@
package org.springframework.credhub.support.password;
import org.springframework.credhub.support.CredentialType;
import org.springframework.credhub.support.ParametersRequest;
import org.springframework.util.Assert;
import static org.springframework.credhub.support.CredentialType.PASSWORD;
/**
* The details of a request to generate a new {@link PasswordCredential} in CredHub.
*
* @author Scott Frederick
*/
public class PasswordParametersRequest extends ParametersRequest<PasswordParameters> {
/**
* Create a {@link PasswordParametersRequest}.
*/
PasswordParametersRequest() {
super(PASSWORD);
super(CredentialType.PASSWORD);
}
/**
* Create a builder that provides a fluent API for providing the values required
* to construct a {@link PasswordParametersRequest}.
*
* Create a builder that provides a fluent API for providing the values required to
* construct a {@link PasswordParametersRequest}.
* @return a builder
*/
public static PasswordParametersRequestBuilder builder() {
@@ -45,10 +44,12 @@ public class PasswordParametersRequest extends ParametersRequest<PasswordParamet
}
/**
* A builder that provides a fluent API for constructing {@link PasswordParametersRequest}s.
* A builder that provides a fluent API for constructing
* {@link PasswordParametersRequest}s.
*/
public static class PasswordParametersRequestBuilder
extends CredHubRequestBuilder<PasswordParameters, PasswordParametersRequest, PasswordParametersRequestBuilder> {
public static class PasswordParametersRequestBuilder extends
CredHubRequestBuilder<PasswordParameters, PasswordParametersRequest, PasswordParametersRequestBuilder> {
@Override
protected PasswordParametersRequest createTarget() {
return new PasswordParametersRequest();
@@ -61,14 +62,15 @@ public class PasswordParametersRequest extends ParametersRequest<PasswordParamet
/**
* Set the parameters for generation of a password credential.
*
* @param parameters the generation parameters; must not be {@literal null}
* @return the builder
*/
public PasswordParametersRequestBuilder parameters(PasswordParameters parameters) {
Assert.notNull(parameters, "parameters must not be null");
targetObj.setParameters(parameters);
this.targetObj.setParameters(parameters);
return this;
}
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -17,4 +17,4 @@
/**
* Java representations of CredHub password credentials.
*/
package org.springframework.credhub.support.password;
package org.springframework.credhub.support.password;

View File

@@ -1,6 +1,5 @@
/*
*
* Copyright 2013-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,33 +12,30 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.springframework.credhub.support.permissions;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import org.springframework.util.Assert;
import java.util.Objects;
import static org.springframework.credhub.support.permissions.ActorType.APP;
import static org.springframework.credhub.support.permissions.ActorType.OAUTH_CLIENT;
import static org.springframework.credhub.support.permissions.ActorType.USER;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import org.springframework.util.Assert;
/**
* Identifies an entity that is authorized to perform operations on a CredHub credential.
*
* @author Scott Frederick
*/
public class Actor {
public final class Actor {
private final ActorType authType;
private final String primaryIdentifier;
/**
* Create a new {@literal Actor}.
*
* @param actorType the type of the authorized entity
* @param primaryIdentifier the unique identifier of the authorized entity
*/
@@ -51,31 +47,28 @@ public class Actor {
/**
* Create an application identifier. An application is identified by a GUID generated
* by Cloud Foundry when the application is created.
*
* @param appId the Cloud Foundry application GUID
* @return the created {@literal Actor}
*/
public static Actor app(String appId) {
Assert.notNull(appId, "appId must not be null");
return new Actor(APP, appId);
return new Actor(ActorType.APP, appId);
}
/**
* Create a user identifier. A user is identified by a GUID generated by UAA when
* a user account is created.
*
* Create a user identifier. A user is identified by a GUID generated by UAA when a
* user account is created.
* @param userId the UAA user GUID
* @return the created {@literal Actor}
*/
public static Actor user(String userId) {
Assert.notNull(userId, "userId must not be null");
return new Actor(USER, userId);
return new Actor(ActorType.USER, userId);
}
/**
* Create a user identifier. A user is identified by a GUID generated by UAA when
* a user account is created and the ID of the identity zone the user was created in.
*
* Create a user identifier. A user is identified by a GUID generated by UAA when a
* user account is created and the ID of the identity zone the user was created in.
* @param zoneId the UAA identity zone ID
* @param userId the UAA user GUID
* @return the created {@literal Actor}
@@ -83,24 +76,23 @@ public class Actor {
public static Actor user(String zoneId, String userId) {
Assert.notNull(zoneId, "zoneId must not be null");
Assert.notNull(userId, "userId must not be null");
return new Actor(USER, zoneId + "/" + userId);
return new Actor(ActorType.USER, zoneId + "/" + userId);
}
/**
* Create an OAuth2 client identifier. A client identified by user-provided identifier.
*
* Create an OAuth2 client identifier. A client identified by user-provided
* identifier.
* @param clientId the UAA client ID
* @return the created {@literal Actor}
*/
public static Actor client(String clientId) {
Assert.notNull(clientId, "clientId must not be null");
return new Actor(OAUTH_CLIENT, clientId);
return new Actor(ActorType.OAUTH_CLIENT, clientId);
}
/**
* Create an OAuth2 client identifier. A client identified by user-provided identifier
* and the ID of the identity zone the client was created in.
*
* @param zoneId the UAA identity zone ID
* @param clientId the UAA client ID
* @return the created {@literal Actor}
@@ -108,35 +100,33 @@ public class Actor {
public static Actor client(String zoneId, String clientId) {
Assert.notNull(zoneId, "zoneId must not be null");
Assert.notNull(clientId, "clientId must not be null");
return new Actor(OAUTH_CLIENT, zoneId + "/" + clientId);
return new Actor(ActorType.OAUTH_CLIENT, zoneId + "/" + clientId);
}
/**
* Get the type of the authorized entity.
*
* @return the entity type
*/
public ActorType getAuthType() {
return authType;
return this.authType;
}
/**
* Get the identity of the authorized entity.
*
* @return the identifier
*/
public String getPrimaryIdentifier() {
return primaryIdentifier;
return this.primaryIdentifier;
}
/**
* Get the full identifier for the authorized entity, which is a combination of the type and identity.
*
* Get the full identifier for the authorized entity, which is a combination of the
* type and identity.
* @return the full identifier
*/
@JsonValue
public String getIdentity() {
return authType.getType() + ":" + primaryIdentifier;
return this.authType.getType() + ":" + this.primaryIdentifier;
}
@JsonCreator
@@ -149,27 +139,31 @@ public class Actor {
return null;
}
@Override
public String toString() {
return "Actor{" +
"authType=" + authType +
", primaryIdentifier='" + primaryIdentifier + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Actor)) return false;
if (this == o) {
return true;
}
if (!(o instanceof Actor)) {
return false;
}
Actor actor = (Actor) o;
if (authType != actor.authType) return false;
return primaryIdentifier.equals(actor.primaryIdentifier);
if (this.authType != actor.authType) {
return false;
}
return this.primaryIdentifier.equals(actor.primaryIdentifier);
}
@Override
public int hashCode() {
return Objects.hash(authType, primaryIdentifier);
return Objects.hash(this.authType, this.primaryIdentifier);
}
@Override
public String toString() {
return "Actor{" + "authType=" + this.authType + ", primaryIdentifier='" + this.primaryIdentifier + '\'' + '}';
}
}

View File

@@ -1,6 +1,5 @@
/*
*
* Copyright 2013-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,29 +12,30 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.springframework.credhub.support.permissions;
/**
* The types of entities that can be authorized to perform operations on CredHub credentials.
* The types of entities that can be authorized to perform operations on CredHub
* credentials.
*
* @author Scott Frederick
*/
public enum ActorType {
/**
* A Cloud Foundry application entity
* A Cloud Foundry application entity.
*/
APP("mtls-app"),
/**
* A UAA user entity, as can be used with a password grant
* A UAA user entity, as can be used with a password grant.
*/
USER("uaa-user"),
/**
* A UAA client entity, as can be used with a client credentials grant
* A UAA client entity, as can be used with a client credentials grant.
*/
OAUTH_CLIENT("uaa-client");
@@ -47,17 +47,18 @@ public enum ActorType {
/**
* Get the entity type.
*
* @return the entity type
*/
public String getType() {
return type;
return this.type;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return type;
return this.type;
}
}

View File

@@ -1,6 +1,5 @@
/*
*
* Copyright 2013-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,7 +12,6 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.springframework.credhub.support.permissions;
@@ -21,9 +19,10 @@ package org.springframework.credhub.support.permissions;
/**
* The set of operations that are allowed on a credential.
*
* @author Scott Frederick
* @author Scott Frederick
*/
public enum Operation {
/**
* Allows the value of a credential to be read.
*/
@@ -57,17 +56,18 @@ public enum Operation {
/**
* Get the value of the operation.
*
* @return the value of the operation.
*/
public String operation() {
return operation;
return this.operation;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return operation;
return this.operation;
}
}

View File

@@ -1,6 +1,5 @@
/*
*
* Copyright 2013-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,32 +12,33 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.springframework.credhub.support.permissions;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.credhub.support.CredentialRequest;
import org.springframework.util.Assert;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.credhub.support.CredentialRequest;
import org.springframework.util.Assert;
/**
* Permissions applied to a credential in CredHub. If provided when a
* credential is written, these values will control what actors can access update
* or retrieve the credential.
* Permissions applied to a credential in CredHub. If provided when a credential is
* written, these values will control what actors can access update or retrieve the
* credential.
*
* Objects of this type are constructed by the application and passed
* as part of a {@link CredentialRequest}.
* Objects of this type are constructed by the application and passed as part of a
* {@link CredentialRequest}.
*
* @author Scott Frederick
*/
public class Permission {
public final class Permission {
private final Actor actor;
@JsonProperty
@@ -54,9 +54,8 @@ public class Permission {
}
/**
* Create a set of permissions. Intended to be used internally.
* Clients should use {@link #builder()} to construct instances of this class.
*
* Create a set of permissions. Intended to be used internally. Clients should use
* {@link #builder()} to construct instances of this class.
* @param actor the ID of the entity that will be allowed to access the credential
* @param operations the operations that the actor will be allowed to perform on the
* credential
@@ -68,7 +67,6 @@ public class Permission {
/**
* Get the ID of the entity that will be allowed to access the credential.
*
* @return the ID
*/
public Actor getActor() {
@@ -76,38 +74,35 @@ public class Permission {
}
/**
* Get the set of operations that the actor will be allowed to perform on
* the credential.
*
* Get the set of operations that the actor will be allowed to perform on the
* credential.
* @return the operations
*/
public List<Operation> getOperations() {
return operations;
return this.operations;
}
/**
* Get the set of operations that the actor will be allowed to perform on
* the credential.
*
* Get the set of operations that the actor will be allowed to perform on the
* credential.
* @return the operations
*/
@JsonGetter("operations")
private List<String> getOperationsAsString() {
if (operations == null) {
if (this.operations == null) {
return null;
}
List<String> operationValues = new ArrayList<>(operations.size());
for (Operation operation : operations) {
List<String> operationValues = new ArrayList<>(this.operations.size());
for (Operation operation : this.operations) {
operationValues.add(operation.operation());
}
return operationValues;
}
/**
* Create a builder that provides a fluent API for providing the values required
* to construct a {@link Permission}.
*
* Create a builder that provides a fluent API for providing the values required to
* construct a {@link Permission}.
* @return a builder
*/
public static CredentialPermissionBuilder builder() {
@@ -116,38 +111,38 @@ public class Permission {
@Override
public boolean equals(Object o) {
if (this == o)
if (this == o) {
return true;
if (!(o instanceof Permission))
}
if (!(o instanceof Permission)) {
return false;
}
Permission that = (Permission) o;
if (actor != null ? !actor.equals(that.actor) : that.actor != null)
if ((this.actor != null) ? !this.actor.equals(that.actor) : (that.actor != null)) {
return false;
return operations != null ? operations.equals(that.operations)
: that.operations == null;
}
return (this.operations != null) ? this.operations.equals(that.operations) : (that.operations == null);
}
@Override
public int hashCode() {
return Objects.hash(actor, operations);
return Objects.hash(this.actor, this.operations);
}
@Override
public String toString() {
return "CredentialPermission{"
+ "actor='" + actor + '\''
+ ", operations=" + operations
+ '}';
return "CredentialPermission{" + "actor='" + this.actor + '\'' + ", operations=" + this.operations + '}';
}
/**
* A builder that provides a fluent API for constructing {@link Permission}
* instances.
* A builder that provides a fluent API for constructing {@link Permission} instances.
*/
public static class CredentialPermissionBuilder {
private Actor actor;
private ArrayList<Operation> operations;
CredentialPermissionBuilder() {
@@ -156,35 +151,32 @@ public class Permission {
/**
* Set the ID of an application that will be assigned permissions on a credential.
* This will often be a Cloud Foundry application GUID.
*
* @param appId application ID; must not be {@literal null}
* @return the builder
*/
public CredentialPermissionBuilder app(String appId) {
Assert.notNull(appId, "appId must not be null");
Assert.isNull(actor, "only one actor can be specified");
Assert.isNull(this.actor, "only one actor can be specified");
this.actor = Actor.app(appId);
return this;
}
/**
* Set the ID of a user that will be assigned permissions on a credential.
* This is typically a GUID generated by UAA when a user account is created.
*
* Set the ID of a user that will be assigned permissions on a credential. This is
* typically a GUID generated by UAA when a user account is created.
* @param userId user ID; must not be {@literal null}
* @return the builder
*/
public CredentialPermissionBuilder user(String userId) {
Assert.notNull(userId, "userId must not be null");
Assert.isNull(actor, "only one actor can be specified");
Assert.isNull(this.actor, "only one actor can be specified");
this.actor = Actor.user(userId);
return this;
}
/**
* Set the ID of a user that will be assigned permissions on a credential.
* This is typically a GUID generated by UAA when a user account is created.
*
* Set the ID of a user that will be assigned permissions on a credential. This is
* typically a GUID generated by UAA when a user account is created.
* @param zoneId zone ID; must not be {@literal null}
* @param userId user ID; must not be {@literal null}
* @return the builder
@@ -192,44 +184,43 @@ public class Permission {
public CredentialPermissionBuilder user(String zoneId, String userId) {
Assert.notNull(zoneId, "zoneId must not be null");
Assert.notNull(userId, "userId must not be null");
Assert.isNull(actor, "only one actor can be specified");
Assert.isNull(this.actor, "only one actor can be specified");
this.actor = Actor.user(zoneId, userId);
return this;
}
/**
* Set the ID of an OAuth2 client that will be assigned permissions on a credential.
*
* @param clientId OAuth2 client ID; must not be {@literal null}
* Set the ID of an OAuth2 client that will be assigned permissions on a
* credential.
* @param clientId an OAuth2 client ID; must not be {@literal null}
* @return the builder
*/
public CredentialPermissionBuilder client(String clientId) {
Assert.notNull(clientId, "clientId must not be null");
Assert.isNull(actor, "only one actor can be specified");
Assert.isNull(this.actor, "only one actor can be specified");
this.actor = Actor.client(clientId);
return this;
}
/**
* Set the ID of an OAuth2 client that will be assigned permissions on a credential.
*
* Set the ID of an OAuth2 client that will be assigned permissions on a
* credential.
* @param zoneId zone ID; must not be {@literal null}
* @param clientId OAuth2 client ID; must not be {@literal null}
* @param clientId an OAuth2 client ID; must not be {@literal null}
* @return the builder
*/
public CredentialPermissionBuilder client(String zoneId, String clientId) {
Assert.notNull(zoneId, "zoneId must not be null");
Assert.notNull(clientId, "clientId must not be null");
Assert.isNull(actor, "only one actor can be specified");
Assert.isNull(this.actor, "only one actor can be specified");
this.actor = Actor.client(zoneId, clientId);
return this;
}
/**
* Set an {@link Operation} that the actor will be allowed to perform on
* the credential. Multiple operations can be provided with consecutive calls to
* this method.
*
* Set an {@link Operation} that the actor will be allowed to perform on the
* credential. Multiple operations can be provided with consecutive calls to this
* method.
* @param operation the {@link Operation}
* @return the builder
*/
@@ -242,7 +233,6 @@ public class Permission {
/**
* Specify a set of {@link Operation}s that the actor will be allowed to perform
* on the credential.
*
* @param operations the {@link Operation}s
* @return the builder
*/
@@ -253,28 +243,31 @@ public class Permission {
}
private void initOperations() {
if (this.operations == null) this.operations = new ArrayList<>();
if (this.operations == null) {
this.operations = new ArrayList<>();
}
}
/**
* Construct a {@link Permission} with the provided values.
*
* @return a {@link Permission}
*/
public Permission build() {
List<Operation> operations;
switch (this.operations == null ? 0 : this.operations.size()) {
case 0:
operations = java.util.Collections.emptyList();
break;
case 1:
operations = java.util.Collections.singletonList(this.operations.get(0));
break;
default:
operations = java.util.Collections.unmodifiableList(new ArrayList<>(this.operations));
switch ((this.operations == null) ? 0 : this.operations.size()) {
case 0:
operations = java.util.Collections.emptyList();
break;
case 1:
operations = java.util.Collections.singletonList(this.operations.get(0));
break;
default:
operations = java.util.Collections.unmodifiableList(new ArrayList<>(this.operations));
}
return new Permission(actor, operations);
return new Permission(this.actor, operations);
}
}
}

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -17,4 +17,4 @@
/**
* Java representations of CredHub JSON credential permissions.
*/
package org.springframework.credhub.support.permissions;
package org.springframework.credhub.support.permissions;

Some files were not shown because too many files have changed in this diff Show More