diff --git a/build.gradle b/build.gradle index a949760..1e8b3e3 100644 --- a/build.gradle +++ b/build.gradle @@ -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") } diff --git a/publish-maven.gradle b/publish-maven.gradle index b475464..8b8ecd0 100644 --- a/publish-maven.gradle +++ b/publish-maven.gradle @@ -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 { diff --git a/settings.gradle b/settings.gradle index 231900c..74450a5 100644 --- a/settings.gradle +++ b/settings.gradle @@ -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' diff --git a/spring-credhub-core/build.gradle b/spring-credhub-core/build.gradle index 0774d1e..7eaaa65 100644 --- a/spring-credhub-core/build.gradle +++ b/spring-credhub-core/build.gradle @@ -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, diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/configuration/ClientHttpConnectorFactory.java b/spring-credhub-core/src/main/java/org/springframework/credhub/configuration/ClientHttpConnectorFactory.java index 9bda3e7..542e0ae 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/configuration/ClientHttpConnectorFactory.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/configuration/ClientHttpConnectorFactory.java @@ -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; } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/configuration/ClientHttpRequestFactoryFactory.java b/spring-credhub-core/src/main/java/org/springframework/credhub/configuration/ClientHttpRequestFactoryFactory.java index 67a5e87..f5668ed 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/configuration/ClientHttpRequestFactoryFactory.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/configuration/ClientHttpRequestFactoryFactory.java @@ -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; - } -} \ No newline at end of file +} diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/configuration/CredHubTemplateFactory.java b/spring-credhub-core/src/main/java/org/springframework/credhub/configuration/CredHubTemplateFactory.java index 4ee0d2d..f450248 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/configuration/CredHubTemplateFactory.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/configuration/CredHubTemplateFactory.java @@ -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); } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/configuration/SslCertificateUtils.java b/spring-credhub-core/src/main/java/org/springframework/credhub/configuration/SslCertificateUtils.java index a56e34f..1ad212c 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/configuration/SslCertificateUtils.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/configuration/SslCertificateUtils.java @@ -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); } } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/configuration/package-info.java b/spring-credhub-core/src/main/java/org/springframework/credhub/configuration/package-info.java index 20a8231..60ee1b2 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/configuration/package-info.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/configuration/package-info.java @@ -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; \ No newline at end of file +package org.springframework.credhub.configuration; diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/CredHubException.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/CredHubException.java index 4bdb9b9..2697f69 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/CredHubException.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/CredHubException.java @@ -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); } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/CredHubOAuth2RequestInterceptor.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/CredHubOAuth2RequestInterceptor.java index 560c587..e7d700c 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/CredHubOAuth2RequestInterceptor.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/CredHubOAuth2RequestInterceptor.java @@ -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(); } + } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/CredHubOperations.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/CredHubOperations.java index c5d9f4c..2db4d65 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/CredHubOperations.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/CredHubOperations.java @@ -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 the credential implementation type * @return the return value from the callback method */ T doWithRest(RestOperationsCallback callback); + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/CredHubProperties.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/CredHubProperties.java index 4e0cd51..7b9e3b7 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/CredHubProperties.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/CredHubProperties.java @@ -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; } + } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/CredHubRestTemplateFactory.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/CredHubRestTemplateFactory.java index affd543..b218d7e 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/CredHubRestTemplateFactory.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/CredHubRestTemplateFactory.java @@ -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 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); } + } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/CredHubTemplate.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/CredHubTemplate.java index 47f7527..1f74e00 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/CredHubTemplate.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/CredHubTemplate.java @@ -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 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; } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/CredHubWebClientFactory.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/CredHubWebClientFactory.java index 7f4a875..79806d3 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/CredHubWebClientFactory.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/CredHubWebClientFactory.java @@ -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); } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/ExceptionUtils.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/ExceptionUtils.java index 24632ff..c050670 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/ExceptionUtils.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/ExceptionUtils.java @@ -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 buildError(ClientResponse response) { return Mono.error(new CredHubException(response.statusCode())); } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/ReactiveCredHubOperations.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/ReactiveCredHubOperations.java index da493db..11235dc 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/ReactiveCredHubOperations.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/ReactiveCredHubOperations.java @@ -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 the publisher type * @param the credential implementation type * @return the return value from the callback method */ > T doWithWebClient(Function callback); + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/ReactiveCredHubTemplate.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/ReactiveCredHubTemplate.java index 0c397fa..b8000d8 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/ReactiveCredHubTemplate.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/ReactiveCredHubTemplate.java @@ -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 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; } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/RestOperationsCallback.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/RestOperationsCallback.java index fe39ccf..c71c23b 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/RestOperationsCallback.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/RestOperationsCallback.java @@ -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 the type of CredHub credential * @author Mark Paluch */ public interface RestOperationsCallback { @@ -28,9 +29,9 @@ public interface RestOperationsCallback { /** * 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); -} \ No newline at end of file + +} diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/certificate/CredHubCertificateOperations.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/certificate/CredHubCertificateOperations.java index aecc918..38cd885 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/certificate/CredHubCertificateOperations.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/certificate/CredHubCertificateOperations.java @@ -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 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 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 updateTransitionalVersion(final String id, final String versionId); + List updateTransitionalVersion(String id, String versionId); + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/certificate/CredHubCertificateTemplate.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/certificate/CredHubCertificateTemplate.java index 38f5231..dd77c52 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/certificate/CredHubCertificateTemplate.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/certificate/CredHubCertificateTemplate.java @@ -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 getAll() { - return credHubOperations.doWithRest(restOperations -> { - ResponseEntity response = restOperations - .getForEntity(BASE_URL_PATH, CertificateSummaryData.class); + return this.credHubOperations.doWithRest((restOperations) -> { + ResponseEntity 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 response = restOperations - .getForEntity(NAME_URL_QUERY, CertificateSummaryData.class, name.getName()); + return this.credHubOperations.doWithRest((restOperations) -> { + ResponseEntity 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 ref = - new ParameterizedTypeReference() {}; + final ParameterizedTypeReference ref = new ParameterizedTypeReference() { + }; - return credHubOperations.doWithRest(restOperations -> { + return this.credHubOperations.doWithRest((restOperations) -> { Map request = new HashMap<>(1); request.put(TRANSITIONAL_REQUEST_FIELD, setAsTransitional); - ResponseEntity response = - restOperations.exchange(REGENERATE_URL_PATH, HttpMethod.POST, - new HttpEntity(request), ref, id); + ResponseEntity response = restOperations.exchange(REGENERATE_URL_PATH, + HttpMethod.POST, new HttpEntity(request), ref, id); ExceptionUtils.throwExceptionOnError(response); @@ -112,16 +119,15 @@ public class CredHubCertificateTemplate implements CredHubCertificateOperations public List regenerate(final CredentialName certificateName) { Assert.notNull(certificateName, "certificate name must not be null"); - final ParameterizedTypeReference>> ref = - new ParameterizedTypeReference>>() {}; + final ParameterizedTypeReference>> ref = new ParameterizedTypeReference>>() { + }; - return credHubOperations.doWithRest(restOperations -> { + return this.credHubOperations.doWithRest((restOperations) -> { Map request = new HashMap<>(1); request.put(SIGNED_BY_REQUEST_FIELD, certificateName.getName()); - ResponseEntity>> response = - restOperations.exchange(BULK_REGENERATE_URL_PATH, HttpMethod.POST, - new HttpEntity<>(request), ref); + ResponseEntity>> 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 updateTransitionalVersion(final String id, - final String versionId) { + public List updateTransitionalVersion(final String id, final String versionId) { Assert.notNull(id, "credential ID must not be null"); - final ParameterizedTypeReference> ref = - new ParameterizedTypeReference>() {}; + final ParameterizedTypeReference> ref = new ParameterizedTypeReference>() { + }; - return credHubOperations.doWithRest(restOperations -> { + return this.credHubOperations.doWithRest((restOperations) -> { Map request = new HashMap<>(1); request.put(VERSION_REQUEST_FIELD, versionId); - ResponseEntity> response = - restOperations.exchange(UPDATE_TRANSITIONAL_URL_PATH, HttpMethod.PUT, - new HttpEntity(request), ref, id); + ResponseEntity> response = restOperations + .exchange(UPDATE_TRANSITIONAL_URL_PATH, HttpMethod.PUT, new HttpEntity(request), ref, id); ExceptionUtils.throwExceptionOnError(response); return response.getBody(); }); } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/certificate/ReactiveCredHubCertificateOperations.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/certificate/ReactiveCredHubCertificateOperations.java index d0ddd10..3668f5a 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/certificate/ReactiveCredHubCertificateOperations.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/certificate/ReactiveCredHubCertificateOperations.java @@ -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 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 getByName(final CredentialName name); + Mono 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 regenerate(final String id, final boolean setAsTransitional); + Mono 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 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 updateTransitionalVersion(final String id, final String versionId); + Flux updateTransitionalVersion(String id, String versionId); + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/certificate/ReactiveCredHubCertificateTemplate.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/certificate/ReactiveCredHubCertificateTemplate.java index 947de47..3bdb30a 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/certificate/ReactiveCredHubCertificateTemplate.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/certificate/ReactiveCredHubCertificateTemplate.java @@ -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 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 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 regenerate(final String id, final boolean setAsTransitional) { Assert.notNull(id, "credential ID must not be null"); - final ParameterizedTypeReference ref = - new ParameterizedTypeReference() {}; + final ParameterizedTypeReference ref = new ParameterizedTypeReference() { + }; Map 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 regenerate(final CredentialName certificateName) { Assert.notNull(certificateName, "certificate name must not be null"); - final ParameterizedTypeReference>> ref = - new ParameterizedTypeReference>>() {}; + final ParameterizedTypeReference>> ref = new ParameterizedTypeReference>>() { + }; Map 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 updateTransitionalVersion(final String id, - final String versionId) { + public Flux updateTransitionalVersion(final String id, final String versionId) { Assert.notNull(id, "credential ID must not be null"); Map 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)); } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/certificate/package-info.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/certificate/package-info.java index f83d0f7..303a4c3 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/certificate/package-info.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/certificate/package-info.java @@ -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; \ No newline at end of file +package org.springframework.credhub.core.certificate; diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/credential/CredHubCredentialOperations.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/credential/CredHubCredentialOperations.java index 100854e..8a5eccf 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/credential/CredHubCredentialOperations.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/credential/CredHubCredentialOperations.java @@ -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 the credential implementation type * @return the details of the written credential */ - CredentialDetails write(final CredentialRequest credentialRequest); + CredentialDetails write(CredentialRequest 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 the credential implementation type * @param

the credential parameter implementation type * @return the details of the generated credential */ - CredentialDetails generate(final ParametersRequest

parametersRequest); + CredentialDetails generate(ParametersRequest

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 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 */ - CredentialDetails regenerate(final CredentialName name, Class credentialType); + CredentialDetails regenerate(CredentialName name, Class 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 the credential implementation type * @return the details of the retrieved credential */ - CredentialDetails getById(final String id, final Class credentialType); + CredentialDetails getById(String id, Class 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 the credential implementation type * @return the details of the retrieved credential */ - CredentialDetails getByName(final CredentialName name, final Class credentialType); + CredentialDetails getByName(CredentialName name, Class 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 the credential implementation type * @return the details of the retrieved credential, including history */ - List> getByNameWithHistory(final CredentialName name, final Class credentialType); + List> getByNameWithHistory(CredentialName name, Class 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 the credential implementation type * @return the details of the retrieved credential, including history */ - List> getByNameWithHistory(final CredentialName name, int versions, - final Class credentialType); + List> getByNameWithHistory(CredentialName name, int versions, Class 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 findByName(final CredentialName name); + List 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 findByPath(final String path); + List 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); + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/credential/CredHubCredentialTemplate.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/credential/CredHubCredentialTemplate.java index 68a8acd..bf29544 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/credential/CredHubCredentialTemplate.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/credential/CredHubCredentialTemplate.java @@ -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 + "¤t=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 CredentialDetails write(final CredentialRequest credentialRequest) { Assert.notNull(credentialRequest, "credentialRequest must not be null"); - final ParameterizedTypeReference> ref = - new ParameterizedTypeReference>() {}; + final ParameterizedTypeReference> ref = new ParameterizedTypeReference>() { + }; - return credHubOperations.doWithRest(restOperations -> { - ResponseEntity> response = - restOperations.exchange(BASE_URL_PATH, HttpMethod.PUT, - new HttpEntity<>(credentialRequest), ref); + return this.credHubOperations.doWithRest((restOperations) -> { + ResponseEntity> 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 CredentialDetails generate(final ParametersRequest

parametersRequest) { Assert.notNull(parametersRequest, "parametersRequest must not be null"); - final ParameterizedTypeReference> ref = - new ParameterizedTypeReference>() {}; + final ParameterizedTypeReference> ref = new ParameterizedTypeReference>() { + }; - return credHubOperations.doWithRest(restOperations -> { - ResponseEntity> response = - restOperations.exchange(BASE_URL_PATH, HttpMethod.POST, - new HttpEntity<>(parametersRequest), ref); + return this.credHubOperations.doWithRest((restOperations) -> { + ResponseEntity> 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> ref = - new ParameterizedTypeReference>() {}; + final ParameterizedTypeReference> ref = new ParameterizedTypeReference>() { + }; - return credHubOperations.doWithRest(restOperations -> { + return this.credHubOperations.doWithRest((restOperations) -> { Map request = new HashMap<>(1); request.put(NAME_REQUEST_FIELD, name.getName()); - ResponseEntity> response = - restOperations.exchange(REGENERATE_URL_PATH, HttpMethod.POST, - new HttpEntity<>(request), ref); + ResponseEntity> 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> ref = - new ParameterizedTypeReference>() {}; + final ParameterizedTypeReference> ref = new ParameterizedTypeReference>() { + }; - return credHubOperations.doWithRest(restOperations -> { - ResponseEntity> response = - restOperations.exchange(ID_URL_PATH, HttpMethod.GET, null, ref, id); + return this.credHubOperations.doWithRest((restOperations) -> { + ResponseEntity> 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> ref = - new ParameterizedTypeReference>() {}; + final ParameterizedTypeReference> ref = new ParameterizedTypeReference>() { + }; - return credHubOperations.doWithRest(restOperations -> { - ResponseEntity> response = - restOperations.exchange(NAME_URL_QUERY_CURRENT, HttpMethod.GET, - null, ref, name.getName()); + return this.credHubOperations.doWithRest((restOperations) -> { + ResponseEntity> 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 List> getByNameWithHistory(final CredentialName name, final Class credentialType) { + public List> getByNameWithHistory(final CredentialName name, + final Class credentialType) { Assert.notNull(name, "credential name must not be null"); Assert.notNull(credentialType, "credential type must not be null"); - final ParameterizedTypeReference> ref = - new ParameterizedTypeReference>() {}; + final ParameterizedTypeReference> ref = new ParameterizedTypeReference>() { + }; - return credHubOperations.doWithRest(restOperations -> { - ResponseEntity> response = - restOperations.exchange(NAME_URL_QUERY, HttpMethod.GET, null, ref, name.getName()); + return this.credHubOperations.doWithRest((restOperations) -> { + ResponseEntity> 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 List> getByNameWithHistory(final CredentialName name, final int versions, - final Class credentialType) { + final Class credentialType) { Assert.notNull(name, "credential name must not be null"); Assert.notNull(credentialType, "credential type must not be null"); - final ParameterizedTypeReference> ref = - new ParameterizedTypeReference>() {}; + final ParameterizedTypeReference> ref = new ParameterizedTypeReference>() { + }; - return credHubOperations.doWithRest(restOperations -> { - ResponseEntity> response = - restOperations.exchange(NAME_URL_QUERY_VERSIONS, HttpMethod.GET, null, ref, - name.getName(), versions); + return this.credHubOperations.doWithRest((restOperations) -> { + ResponseEntity> 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 findByName(final CredentialName name) { Assert.notNull(name, "credential name must not be null"); - return credHubOperations.doWithRest(restOperations -> { - ResponseEntity response = restOperations - .getForEntity(NAME_LIKE_URL_QUERY, - CredentialSummaryData.class, name.getName()); + return this.credHubOperations.doWithRest((restOperations) -> { + ResponseEntity 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 findByPath(final String path) { Assert.notNull(path, "credential path must not be null"); - return credHubOperations.doWithRest(restOperations -> { - ResponseEntity response = restOperations - .getForEntity(PATH_URL_QUERY, CredentialSummaryData.class, - path); + return this.credHubOperations.doWithRest((restOperations) -> { + ResponseEntity 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 getAllPaths() { - return credHubOperations.doWithRest(restOperations -> { - ResponseEntity response = restOperations - .getForEntity(SHOW_ALL_URL_QUERY, CredentialPathData.class); + return this.credHubOperations.doWithRest((restOperations) -> { + ResponseEntity 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; }); } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/credential/ReactiveCredHubCredentialOperations.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/credential/ReactiveCredHubCredentialOperations.java index 7555967..122633b 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/credential/ReactiveCredHubCredentialOperations.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/credential/ReactiveCredHubCredentialOperations.java @@ -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 the credential implementation type * @return the details of the written credential */ - Mono> write(final CredentialRequest credentialRequest); + Mono> write(CredentialRequest 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 the credential implementation type * @param

the credential parameter implementation type * @return the details of the generated credential */ - Mono> generate(final ParametersRequest

parametersRequest, - Class credentialType); + Mono> generate(ParametersRequest

parametersRequest, Class 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 the credential implementation type * @return the details of the regenerated credential */ - Mono> regenerate(final CredentialName name, Class credentialType); + Mono> regenerate(CredentialName name, Class 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 the credential implementation type * @return the details of the retrieved credential */ - Mono> getById(final String id, final Class credentialType); + Mono> getById(String id, Class 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 the credential implementation type * @return the details of the retrieved credential */ - Mono> getByName(final CredentialName name, final Class credentialType); + Mono> getByName(CredentialName name, Class 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 the credential implementation type * @return the details of the retrieved credential, including history */ - Flux> getByNameWithHistory(final CredentialName name, final Class credentialType); + Flux> getByNameWithHistory(CredentialName name, Class 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 the credential implementation type * @return the details of the retrieved credential, including history */ - Flux> getByNameWithHistory(final CredentialName name, int versions, - final Class credentialType); + Flux> getByNameWithHistory(CredentialName name, int versions, Class 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 findByName(final CredentialName name); + Flux 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 findByPath(final String path); + Flux 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 deleteByName(final CredentialName name); + Mono deleteByName(CredentialName name); + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/credential/ReactiveCredHubCredentialTemplate.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/credential/ReactiveCredHubCredentialTemplate.java index 2a85003..69a33a0 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/credential/ReactiveCredHubCredentialTemplate.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/credential/ReactiveCredHubCredentialTemplate.java @@ -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 + "¤t=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 Mono> write(final CredentialRequest credentialRequest) { Assert.notNull(credentialRequest, "credentialRequest must not be null"); - final ParameterizedTypeReference> ref = - new ParameterizedTypeReference>() {}; + final ParameterizedTypeReference> ref = new ParameterizedTypeReference>() { + }; - 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 Mono> generate(final ParametersRequest

parametersRequest, - Class credentialType) { + Class credentialType) { Assert.notNull(parametersRequest, "parametersRequest must not be null"); - final ParameterizedTypeReference> ref = - new ParameterizedTypeReference>() {}; + final ParameterizedTypeReference> ref = new ParameterizedTypeReference>() { + }; - 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> ref = - new ParameterizedTypeReference>() {}; + final ParameterizedTypeReference> ref = new ParameterizedTypeReference>() { + }; Map 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> ref = - new ParameterizedTypeReference>() {}; + final ParameterizedTypeReference> ref = new ParameterizedTypeReference>() { + }; - 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> ref = - new ParameterizedTypeReference>() {}; + final ParameterizedTypeReference> ref = new ParameterizedTypeReference>() { + }; - 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 Flux> getByNameWithHistory(final CredentialName name, final Class credentialType) { + public Flux> getByNameWithHistory(final CredentialName name, + final Class credentialType) { Assert.notNull(name, "credential name must not be null"); Assert.notNull(credentialType, "credential type must not be null"); - final ParameterizedTypeReference> ref = - new ParameterizedTypeReference>() {}; + final ParameterizedTypeReference> ref = new ParameterizedTypeReference>() { + }; - 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 Flux> getByNameWithHistory(final CredentialName name, final int versions, - final Class credentialType) { + final Class credentialType) { Assert.notNull(name, "credential name must not be null"); Assert.notNull(credentialType, "credential type must not be null"); - final ParameterizedTypeReference> ref = - new ParameterizedTypeReference>() {}; + final ParameterizedTypeReference> ref = new ParameterizedTypeReference>() { + }; - 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 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 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 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)); } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/credential/package-info.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/credential/package-info.java index ebb550b..9310d52 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/credential/package-info.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/credential/package-info.java @@ -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; \ No newline at end of file +package org.springframework.credhub.core.credential; diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/info/CredHubInfoOperations.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/info/CredHubInfoOperations.java index 50d1cee..70f83c2 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/info/CredHubInfoOperations.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/info/CredHubInfoOperations.java @@ -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(); diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/info/CredHubInfoTemplate.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/info/CredHubInfoTemplate.java index 46cb4da..c953a66 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/info/CredHubInfoTemplate.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/info/CredHubInfoTemplate.java @@ -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 response = restOperations - .getForEntity(VERSION_URL_PATH, VersionInfo.class); + return this.credHubOperations.doWithRest((restOperations) -> { + ResponseEntity response = restOperations.getForEntity(VERSION_URL_PATH, VersionInfo.class); ExceptionUtils.throwExceptionOnError(response); return response.getBody(); }); } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/info/ReactiveCredHubInfoOperations.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/info/ReactiveCredHubInfoOperations.java index 8e55ba2..8121661 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/info/ReactiveCredHubInfoOperations.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/info/ReactiveCredHubInfoOperations.java @@ -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 version(); diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/info/ReactiveCredHubInfoTemplate.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/info/ReactiveCredHubInfoTemplate.java index 7cca2d5..b385267 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/info/ReactiveCredHubInfoTemplate.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/info/ReactiveCredHubInfoTemplate.java @@ -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 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)); } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/info/package-info.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/info/package-info.java index e6e64a6..5cd90c3 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/info/package-info.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/info/package-info.java @@ -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; \ No newline at end of file +package org.springframework.credhub.core.info; diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/interpolation/CredHubInterpolationOperations.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/interpolation/CredHubInterpolationOperations.java index 4ead97f..508a326 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/interpolation/CredHubInterpolationOperations.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/interpolation/CredHubInterpolationOperations.java @@ -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: * *

 	 * {@code
@@ -77,12 +78,12 @@ public interface CredHubInterpolationOperations {
 	 * }
 	 * }
 	 * 
- * * @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); + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/interpolation/CredHubInterpolationTemplate.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/interpolation/CredHubInterpolationTemplate.java index cb46b4e..157d561 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/interpolation/CredHubInterpolationTemplate.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/interpolation/CredHubInterpolationTemplate.java @@ -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 response = restOperations - .exchange(INTERPOLATE_URL_PATH, HttpMethod.POST, - new HttpEntity<>(serviceData), ServicesData.class); + return this.credHubOperations.doWithRest((restOperations) -> { + ResponseEntity response = restOperations.exchange(INTERPOLATE_URL_PATH, HttpMethod.POST, + new HttpEntity<>(serviceData), ServicesData.class); ExceptionUtils.throwExceptionOnError(response); return response.getBody(); }); } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/interpolation/ReactiveCredHubInterpolationOperations.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/interpolation/ReactiveCredHubInterpolationOperations.java index 174c5a4..f3db1e7 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/interpolation/ReactiveCredHubInterpolationOperations.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/interpolation/ReactiveCredHubInterpolationOperations.java @@ -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: * *
 	 * {@code
@@ -78,12 +80,12 @@ public interface ReactiveCredHubInterpolationOperations {
 	 * }
 	 * }
 	 * 
- * * @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 interpolateServiceData(final ServicesData serviceData); + Mono interpolateServiceData(ServicesData serviceData); + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/interpolation/ReactiveCredHubInterpolationTemplate.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/interpolation/ReactiveCredHubInterpolationTemplate.java index 3bf50c6..64e058a 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/interpolation/ReactiveCredHubInterpolationTemplate.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/interpolation/ReactiveCredHubInterpolationTemplate.java @@ -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 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)); } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/interpolation/package-info.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/interpolation/package-info.java index 2c373de..53e87e0 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/interpolation/package-info.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/interpolation/package-info.java @@ -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; \ No newline at end of file +package org.springframework.credhub.core.interpolation; diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/package-info.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/package-info.java index 065ce18..9054dfa 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/package-info.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/package-info.java @@ -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; \ No newline at end of file +package org.springframework.credhub.core; diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/permission/CredHubPermissionOperations.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/permission/CredHubPermissionOperations.java index be11230..07d500a 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/permission/CredHubPermissionOperations.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/permission/CredHubPermissionOperations.java @@ -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 getPermissions(final CredentialName name); + List 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); + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/permission/CredHubPermissionTemplate.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/permission/CredHubPermissionTemplate.java index 92d4f51..6966659 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/permission/CredHubPermissionTemplate.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/permission/CredHubPermissionTemplate.java @@ -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 getPermissions(final CredentialName name) { Assert.notNull(name, "credential name must not be null"); - return credHubOperations.doWithRest(restOperations -> { - ResponseEntity response = - restOperations.getForEntity(PERMISSIONS_URL_QUERY, - CredentialPermissions.class, name.getName()); + return this.credHubOperations.doWithRest((restOperations) -> { + ResponseEntity 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; }); } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/permission/ReactiveCredHubPermissionOperations.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/permission/ReactiveCredHubPermissionOperations.java index 1ada75d..9c8aed8 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/permission/ReactiveCredHubPermissionOperations.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/permission/ReactiveCredHubPermissionOperations.java @@ -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 getPermissions(final CredentialName name); + Flux 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 addPermissions(final CredentialName name, final Permission... permissions); + Mono 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 deletePermission(final CredentialName name, final Actor actor); + Mono deletePermission(CredentialName name, Actor actor); + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/permission/ReactiveCredHubPermissionTemplate.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/permission/ReactiveCredHubPermissionTemplate.java index 20c6b4f..5b8c034 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/permission/ReactiveCredHubPermissionTemplate.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/permission/ReactiveCredHubPermissionTemplate.java @@ -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 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 addPermissions(final CredentialName name, - final Permission... permissions) { + public Mono 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)); } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/permission/package-info.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/permission/package-info.java index 2f7cbca..61ff3b9 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/permission/package-info.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/permission/package-info.java @@ -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; \ No newline at end of file +package org.springframework.credhub.core.permission; diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/permissionV2/CredHubPermissionV2Operations.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/permissionV2/CredHubPermissionV2Operations.java index 7828336..6eecd10 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/permissionV2/CredHubPermissionV2Operations.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/permissionV2/CredHubPermissionV2Operations.java @@ -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); + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/permissionV2/CredHubPermissionV2Template.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/permissionV2/CredHubPermissionV2Template.java index 220d4c4..b47d27e 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/permissionV2/CredHubPermissionV2Template.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/permissionV2/CredHubPermissionV2Template.java @@ -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 response = - restOperations.getForEntity(PERMISSIONS_ID_URL_PATH, - CredentialPermission.class, id); + return this.credHubOperations.doWithRest((restOperations) -> { + ResponseEntity 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 response = - restOperations.getForEntity(PERMISSIONS_PATH_ACTOR_URL_QUERY, - CredentialPermission.class, path.getName(), actor.getIdentity()); + return this.credHubOperations.doWithRest((restOperations) -> { + ResponseEntity 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 response = - restOperations.exchange(PERMISSIONS_URL_PATH, HttpMethod.POST, - new HttpEntity<>(credentialPermission), - CredentialPermission.class); + return this.credHubOperations.doWithRest((restOperations) -> { + ResponseEntity 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 response = - restOperations.exchange(PERMISSIONS_ID_URL_PATH, HttpMethod.PUT, - new HttpEntity<>(credentialPermission), - CredentialPermission.class, id); + return this.credHubOperations.doWithRest((restOperations) -> { + ResponseEntity 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; }); } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/permissionV2/ReactiveCredHubPermissionV2Operations.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/permissionV2/ReactiveCredHubPermissionV2Operations.java index e3a44f0..1d0d4c4 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/permissionV2/ReactiveCredHubPermissionV2Operations.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/permissionV2/ReactiveCredHubPermissionV2Operations.java @@ -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 getPermissions(final String id); + Mono 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 getPermissionsByPathAndActor(final CredentialName path, final Actor actor); + Mono 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 addPermissions(final CredentialName path, final Permission permission); + Mono 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 updatePermissions(final String id, final CredentialName path, final Permission permission); + Mono 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 deletePermission(final String id); + Mono deletePermission(String id); + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/permissionV2/ReactiveCredHubPermissionV2Template.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/permissionV2/ReactiveCredHubPermissionV2Template.java index 422d79e..e3fc41b 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/permissionV2/ReactiveCredHubPermissionV2Template.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/permissionV2/ReactiveCredHubPermissionV2Template.java @@ -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 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 addPermissions(final CredentialName path, - final Permission permission) { + public Mono 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 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 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)); } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/core/permissionV2/package-info.java b/spring-credhub-core/src/main/java/org/springframework/credhub/core/permissionV2/package-info.java index 7e87c51..54e93d9 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/core/permissionV2/package-info.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/core/permissionV2/package-info.java @@ -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; \ No newline at end of file +package org.springframework.credhub.core.permissionV2; diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/package-info.java b/spring-credhub-core/src/main/java/org/springframework/credhub/package-info.java index fdadc70..223f1b4 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/package-info.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/package-info.java @@ -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; \ No newline at end of file +package org.springframework.credhub; diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/ClientOptions.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/ClientOptions.java index 15f3af9..ddacfe2 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/ClientOptions.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/ClientOptions.java @@ -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; } -} \ No newline at end of file + +} diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredHubRequest.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredHubRequest.java index 0f08e6e..aa26c1d 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredHubRequest.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredHubRequest.java @@ -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 the type of CredHub credential * @author Scott Frederick */ @SuppressWarnings("WeakerAccess") public class CredHubRequest { + protected Boolean overwrite; + protected WriteMode mode; + protected CredentialName name; + protected CredentialType credentialType; + protected List 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 { /** * Get the value of the write mode indicator. - * * @return the write mode */ public WriteMode getMode() { @@ -75,12 +81,11 @@ public class CredHubRequest { /** * 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 { /** * 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 { /** * Get the set of {@link Permission} to assign to the credential. - * * @return the set of {@link Permission} */ public List 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 the type of CredHub credential + * @param the type of the concrete {@link CredHubRequest} + * @param the type of the concrete builder */ - protected static abstract class CredHubRequestBuilder, B extends CredHubRequestBuilder> { + protected abstract static class CredHubRequestBuilder, B extends CredHubRequestBuilder> { + private final B thisObj; + protected final R targetObj; /** @@ -164,111 +186,104 @@ public class CredHubRequest { /** * 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 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; } + } } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialDetails.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialDetails.java index 86d0e23..2f191a4 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialDetails.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialDetails.java @@ -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 the type of CredHub credential * @author Scott Frederick */ public class CredentialDetails extends CredentialSummary { + private final String id; - + @JsonProperty("type") private final CredentialType credentialType; @@ -52,12 +54,10 @@ public class CredentialDetails 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 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 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 extends CredentialSummary { /** * Get the client-provided value for the credential. - * * @return the credential value */ public T getValue() { @@ -95,35 +92,37 @@ public class CredentialDetails 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 + '\'' + + '}'; } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialDetailsData.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialDetailsData.java index 1ed2ebd..60c619d 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialDetailsData.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialDetailsData.java @@ -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 the type of CredHub credential * @author Scott Frederick */ public class CredentialDetailsData { + private final List> data; /** @@ -40,10 +39,9 @@ public class CredentialDetailsData { } /** - * 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 { /** * Get the collection of {@link CredentialDetails}. - * * @return the collection of {@link CredentialDetails} */ public List> getData() { @@ -62,27 +59,29 @@ public class CredentialDetailsData { @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 + '}'; } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialName.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialName.java index 1862e17..6da64df 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialName.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialName.java @@ -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() + '}'; } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialPath.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialPath.java index 47f732a..47f80c1 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialPath.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialPath.java @@ -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 + '}'; } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialPathData.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialPathData.java index cc4d621..e4f6d08 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialPathData.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialPathData.java @@ -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 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 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 + '}'; } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialPermission.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialPermission.java index 6804555..ba7a8b3 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialPermission.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialPermission.java @@ -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 + '}'; + } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialPermissions.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialPermissions.java index 3030c7e..4c7a71f 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialPermissions.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialPermissions.java @@ -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 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 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 + + '}'; + } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialRequest.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialRequest.java index b1ed3dd..56ebd1f 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialRequest.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialRequest.java @@ -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 the type of CredHub credential * @author Scott Frederick */ public class CredentialRequest extends CredHubRequest { + /** * Initialize a {@link CredentialRequest}. - * * @param type the credential implementation type */ protected CredentialRequest(CredentialType type) { @@ -36,7 +35,6 @@ public class CredentialRequest extends CredHubRequest { /** * Get the value of the credential. - * * @return the value of the credential */ public T getValue() { @@ -46,4 +44,5 @@ public class CredentialRequest extends CredHubRequest { protected void setValue(T value) { this.details = value; } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialSummary.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialSummary.java index dc26de1..4372237 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialSummary.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialSummary.java @@ -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 + '\'' + '}'; } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialSummaryData.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialSummaryData.java index 675ef08..b52b930 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialSummaryData.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialSummaryData.java @@ -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 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 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 + '}'; } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialType.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialType.java index 126edb6..2919256 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialType.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/CredentialType.java @@ -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; } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/KeyLength.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/KeyLength.java index e253b65..9ef360f 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/KeyLength.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/KeyLength.java @@ -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; } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/KeyPairCredential.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/KeyPairCredential.java index fcf2f61..7960844 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/KeyPairCredential.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/KeyPairCredential.java @@ -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; } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/KeyParameters.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/KeyParameters.java index 2dfea6e..42027d6 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/KeyParameters.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/KeyParameters.java @@ -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(); } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/ParametersRequest.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/ParametersRequest.java index d675a8e..c376450 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/ParametersRequest.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/ParametersRequest.java @@ -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 the type of CredHub credential * @author Scott Frederick */ public class ParametersRequest extends CredHubRequest { + /** * 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 extends CredHubRequest { protected void setParameters(T parameters) { this.details = parameters; } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/ServiceInstanceCredentialName.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/ServiceInstanceCredentialName.java index ca68538..e7e3153 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/ServiceInstanceCredentialName.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/ServiceInstanceCredentialName.java @@ -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); } + } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/ServicesData.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/ServicesData.java index 3bb0d0f..b88e965 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/ServicesData.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/ServicesData.java @@ -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: * *
  * {@code
@@ -57,19 +58,22 @@ import java.util.Map;
  * }
  * 
* - * 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>> { + public ServicesData() { } /** * Initialize with the provided {@link HashMap}. - * * @param data a {@literal HashMap} to initialize this data structure from */ public ServicesData(HashMap>> data) { super(data); } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/SimpleCredentialName.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/SimpleCredentialName.java index ba8c9b9..2302d2a 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/SimpleCredentialName.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/SimpleCredentialName.java @@ -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) + "}"; } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/StringCredential.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/StringCredential.java index 5efc380..f63e4f1 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/StringCredential.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/StringCredential.java @@ -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; } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/WriteMode.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/WriteMode.java index a87c457..2eed7a4 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/WriteMode.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/WriteMode.java @@ -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; } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/certificate/CertificateCredential.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/certificate/CertificateCredential.java index 1f14e06..cd8f77e 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/certificate/CertificateCredential.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/certificate/CertificateCredential.java @@ -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; } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/certificate/CertificateCredentialDetails.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/certificate/CertificateCredentialDetails.java index a89e2b4..de5df6d 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/certificate/CertificateCredentialDetails.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/certificate/CertificateCredentialDetails.java @@ -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 { + private final boolean transitional; /** @@ -43,29 +44,29 @@ public class CertificateCredentialDetails extends CredentialDetails { + /** * 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 { + public static class CertificateCredentialRequestBuilder extends + CredHubRequestBuilder { + @Override protected CertificateCredentialRequest createTarget() { return new CertificateCredentialRequest(); @@ -61,7 +63,6 @@ public class CertificateCredentialRequest extends CredentialRequest { + /** * 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 { + public static class CertificateParametersRequestBuilder extends + CredHubRequestBuilder { + @Override protected CertificateParametersRequest createTarget() { return new CertificateParametersRequest(); @@ -61,14 +62,15 @@ public class CertificateParametersRequest extends ParametersRequest 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 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 + '}'; } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/certificate/ExtendedKeyUsage.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/certificate/ExtendedKeyUsage.java index c45e38b..c187d6c 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/certificate/ExtendedKeyUsage.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/certificate/ExtendedKeyUsage.java @@ -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; } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/certificate/KeyUsage.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/certificate/KeyUsage.java index 73bd7b8..25b1f3a 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/certificate/KeyUsage.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/certificate/KeyUsage.java @@ -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; } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/certificate/package-info.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/certificate/package-info.java index 099d9fd..b77ae4d 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/certificate/package-info.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/certificate/package-info.java @@ -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; \ No newline at end of file +package org.springframework.credhub.support.certificate; diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/info/VersionInfo.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/info/VersionInfo.java index a57fbba..d98d47d 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/info/VersionInfo.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/info/VersionInfo.java @@ -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"); } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/info/package-info.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/info/package-info.java index 45d8d2f..4f148c5 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/info/package-info.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/info/package-info.java @@ -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; \ No newline at end of file +package org.springframework.credhub.support.info; diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/json/JsonCredential.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/json/JsonCredential.java index f7e2990..b70b99f 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/json/JsonCredential.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/json/JsonCredential.java @@ -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 { + /** + * Create a {@code JsonCredential}. * @see HashMap#HashMap() */ public JsonCredential() { @@ -34,30 +37,32 @@ public class JsonCredential extends HashMap { } /** + * 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 m) { super(m); } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/json/JsonCredentialRequest.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/json/JsonCredentialRequest.java index 3e7976d..f0c8f77 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/json/JsonCredentialRequest.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/json/JsonCredentialRequest.java @@ -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 { + /** * 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 { } /** - * 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 { + public static class JsonCredentialRequestBuilder + extends CredHubRequestBuilder { @Override protected JsonCredentialRequest createTarget() { @@ -64,7 +65,6 @@ public class JsonCredentialRequest extends CredentialRequest { /** * 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 { value(new JsonCredential(value)); return this; } + } } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/json/package-info.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/json/package-info.java index 608dae1..5e04020 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/json/package-info.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/json/package-info.java @@ -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; \ No newline at end of file +package org.springframework.credhub.support.json; diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/package-info.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/package-info.java index 7f458bc..7f3ea6f 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/package-info.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/package-info.java @@ -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; \ No newline at end of file +package org.springframework.credhub.support; diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/password/PasswordCredential.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/password/PasswordCredential.java index 67cbef2..41574c4 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/password/PasswordCredential.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/password/PasswordCredential.java @@ -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; } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/password/PasswordCredentialRequest.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/password/PasswordCredentialRequest.java index ca1c657..fec0577 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/password/PasswordCredentialRequest.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/password/PasswordCredentialRequest.java @@ -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 { + /** * 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 { + public static class PasswordCredentialRequestBuilder extends + CredHubRequestBuilder { + @Override protected PasswordCredentialRequest createTarget() { return new PasswordCredentialRequest(); @@ -61,19 +63,17 @@ public class PasswordCredentialRequest extends CredentialRequest { + /** * 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 { + public static class PasswordParametersRequestBuilder extends + CredHubRequestBuilder { + @Override protected PasswordParametersRequest createTarget() { return new PasswordParametersRequest(); @@ -61,14 +62,15 @@ public class PasswordParametersRequest extends ParametersRequest 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 getOperationsAsString() { - if (operations == null) { + if (this.operations == null) { return null; } - - List operationValues = new ArrayList<>(operations.size()); - for (Operation operation : operations) { + + List 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 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 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); } + } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/permissions/package-info.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/permissions/package-info.java index 50bdafd..2b0e4f4 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/permissions/package-info.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/permissions/package-info.java @@ -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; \ No newline at end of file +package org.springframework.credhub.support.permissions; diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/rsa/RsaCredential.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/rsa/RsaCredential.java index 71fae86..900565f 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/rsa/RsaCredential.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/rsa/RsaCredential.java @@ -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,26 +19,31 @@ package org.springframework.credhub.support.rsa; import org.springframework.credhub.support.KeyPairCredential; /** - * An RSA credential consists of a public and/or private key. At least one of these key values must be provided. + * An RSA credential consists of a public and/or private key. At least one of these key + * values must be provided. * - * @author Scott Frederick + * @author Scott Frederick */ public class RsaCredential extends KeyPairCredential { + /** - * Create an empty {@link RsaCredential}. Intended to be used internally for deserialization of responses. + * Create an empty {@link RsaCredential}. Intended to be used internally for + * deserialization of responses. */ private RsaCredential() { super(); } /** - * Create an {@link RsaCredential} from the provided public and private key. At least one of the key - * values must not be {@literal null}. - * - * @param publicKey the public key; may be {@literal null} only if {@literal privateKey} is not null - * @param privateKey the private key; may be {@literal null} only if {@literal publicKey} is not null + * Create an {@link RsaCredential} from the provided public and private key. At least + * one of the key values must not be {@literal null}. + * @param publicKey the public key; may be {@literal null} only if + * {@literal privateKey} is not null + * @param privateKey the private key; may be {@literal null} only if + * {@literal publicKey} is not null */ public RsaCredential(String publicKey, String privateKey) { super(publicKey, privateKey); } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/rsa/RsaCredentialRequest.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/rsa/RsaCredentialRequest.java index 34902ab..cee4595 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/rsa/RsaCredentialRequest.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/rsa/RsaCredentialRequest.java @@ -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.rsa; import org.springframework.credhub.support.CredentialRequest; +import org.springframework.credhub.support.CredentialType; import org.springframework.util.Assert; -import static org.springframework.credhub.support.CredentialType.RSA; - /** - * The details of a request to write a new or update an existing {@link RsaCredential} in CredHub. + * The details of a request to write a new or update an existing {@link RsaCredential} in + * CredHub. * * @author Scott Frederick */ public class RsaCredentialRequest extends CredentialRequest { + /** * Initialize a {@link CredentialRequest}. */ RsaCredentialRequest() { - super(RSA); + super(CredentialType.RSA); } /** - * Create a builder that provides a fluent API for providing the values required - * to construct a {@link RsaCredentialRequest}. - * + * Create a builder that provides a fluent API for providing the values required to + * construct a {@link RsaCredentialRequest}. * @return a builder */ public static RsaCredentialRequestBuilder builder() { @@ -45,10 +45,12 @@ public class RsaCredentialRequest extends CredentialRequest { } /** - * A builder that provides a fluent API for constructing {@link RsaCredentialRequest}s. + * A builder that provides a fluent API for constructing + * {@link RsaCredentialRequest}s. */ public static class RsaCredentialRequestBuilder extends CredHubRequestBuilder { + @Override protected RsaCredentialRequest createTarget() { return new RsaCredentialRequest(); @@ -61,14 +63,15 @@ public class RsaCredentialRequest extends CredentialRequest { /** * Set the value of an RSA credential. - * * @param value the credential value; must not be {@literal null} * @return the builder */ public RsaCredentialRequestBuilder value(RsaCredential value) { Assert.notNull(value, "value must not be null"); - targetObj.setValue(value); + this.targetObj.setValue(value); return this; } + } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/rsa/RsaParameters.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/rsa/RsaParameters.java index f7b1111..ca452e2 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/rsa/RsaParameters.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/rsa/RsaParameters.java @@ -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 org.springframework.credhub.support.KeyParameters; import org.springframework.util.Assert; /** - * Parameters for generating a new RSA credential. All parameters are optional; if not specified, - * CredHub-provided defaults will be used. + * Parameters for generating a new RSA credential. All parameters are optional; if not + * specified, CredHub-provided defaults will be used. * * @author Scott Frederick */ public class RsaParameters extends KeyParameters { + /** * Create a {@link RsaParameters} using defaults for all parameter values. */ @@ -36,11 +37,11 @@ public class RsaParameters extends KeyParameters { /** * Create a {@link RsaParameters} using the specified values. - * * @param keyLength length of generated RSA key; must not be {@literal null} */ public RsaParameters(KeyLength keyLength) { super(keyLength); Assert.notNull(keyLength, "keyLength must not be null"); } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/rsa/RsaParametersRequest.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/rsa/RsaParametersRequest.java index 625d458..b8e5dd3 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/rsa/RsaParametersRequest.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/rsa/RsaParametersRequest.java @@ -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.rsa; +import org.springframework.credhub.support.CredentialType; import org.springframework.credhub.support.ParametersRequest; import org.springframework.util.Assert; -import static org.springframework.credhub.support.CredentialType.RSA; - /** * The details of a request to generate a new {@link RsaCredential} in CredHub. * * @author Scott Frederick */ public class RsaParametersRequest extends ParametersRequest { + /** * Create a {@link RsaParametersRequest}. */ RsaParametersRequest() { - super(RSA); + super(CredentialType.RSA); } /** - * Create a builder that provides a fluent API for providing the values required - * to construct a {@link RsaParametersRequest}. - * + * Create a builder that provides a fluent API for providing the values required to + * construct a {@link RsaParametersRequest}. * @return a builder */ public static RsaParametersRequestBuilder builder() { @@ -45,10 +44,12 @@ public class RsaParametersRequest extends ParametersRequest { } /** - * A builder that provides a fluent API for constructing {@link RsaParametersRequest}s. + * A builder that provides a fluent API for constructing + * {@link RsaParametersRequest}s. */ public static class RsaParametersRequestBuilder extends CredHubRequestBuilder { + @Override protected RsaParametersRequest createTarget() { return new RsaParametersRequest(); @@ -61,14 +62,15 @@ public class RsaParametersRequest extends ParametersRequest { /** * Set the parameters for generation of an RSA credential. - * * @param parameters the generation parameters; must not be {@literal null} * @return the builder */ public RsaParametersRequestBuilder parameters(RsaParameters parameters) { Assert.notNull(parameters, "parameters must not be null"); - targetObj.setParameters(parameters); + this.targetObj.setParameters(parameters); return this; } + } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/rsa/package-info.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/rsa/package-info.java index ca546c0..1dc4ff0 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/rsa/package-info.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/rsa/package-info.java @@ -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 RSA credentials. */ -package org.springframework.credhub.support.rsa; \ No newline at end of file +package org.springframework.credhub.support.rsa; diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/ssh/SshCredential.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/ssh/SshCredential.java index 142fb3e..c19b3b2 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/ssh/SshCredential.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/ssh/SshCredential.java @@ -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,40 +19,45 @@ package org.springframework.credhub.support.ssh; import org.springframework.credhub.support.KeyPairCredential; /** - * An SSH credential consists of a public and/or private key. At least one of these key values must be provided. + * An SSH credential consists of a public and/or private key. At least one of these key + * values must be provided. * * @author Scott Frederick */ public class SshCredential extends KeyPairCredential { + private final String publicKeyFingerprint; /** - * Create an empty {@link SshCredential}. Intended to be used internally for deserialization of responses. + * Create an empty {@link SshCredential}. Intended to be used internally for + * deserialization of responses. */ private SshCredential() { super(); - publicKeyFingerprint = null; + this.publicKeyFingerprint = null; } /** - * Create an {@link SshCredential} from the provided public and private key. At least one of the key - * values must not be {@literal null}. - * - * @param publicKey the public key; may be {@literal null} only if {@literal privateKey} is not null - * @param privateKey the private key; may be {@literal null} only if {@literal publicKey} is not null + * Create an {@link SshCredential} from the provided public and private key. At least + * one of the key values must not be {@literal null}. + * @param publicKey the public key; may be {@literal null} only if + * {@literal privateKey} is not null + * @param privateKey the private key; may be {@literal null} only if + * {@literal publicKey} is not null */ public SshCredential(String publicKey, String privateKey) { super(publicKey, privateKey); - publicKeyFingerprint = null; + this.publicKeyFingerprint = null; } /** - * Get the fingerprint of the public key associated with the credential. This value can not be provided - * when creating an {@code SshCredential}, but may be provided by CredHub when retrieving one. - * + * Get the fingerprint of the public key associated with the credential. This value + * can not be provided when creating an {@code SshCredential}, but may be provided by + * CredHub when retrieving one. * @return the public key fingerprint value */ public String getPublicKeyFingerprint() { - return publicKeyFingerprint; + return this.publicKeyFingerprint; } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/ssh/SshCredentialRequest.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/ssh/SshCredentialRequest.java index eb4cfa5..89df741 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/ssh/SshCredentialRequest.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/ssh/SshCredentialRequest.java @@ -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.ssh; import org.springframework.credhub.support.CredentialRequest; +import org.springframework.credhub.support.CredentialType; import org.springframework.util.Assert; -import static org.springframework.credhub.support.CredentialType.SSH; - /** - * The details of a request to write a new or update an existing {@link SshCredential} in CredHub. + * The details of a request to write a new or update an existing {@link SshCredential} in + * CredHub. * * @author Scott Frederick */ public class SshCredentialRequest extends CredentialRequest { + /** * Initialize a {@link CredentialRequest}. */ SshCredentialRequest() { - super(SSH); + super(CredentialType.SSH); } /** - * Create a builder that provides a fluent API for providing the values required - * to construct a {@link SshCredentialRequest}. - * + * Create a builder that provides a fluent API for providing the values required to + * construct a {@link SshCredentialRequest}. * @return a builder */ public static SshCredentialRequestBuilder builder() { @@ -45,10 +45,12 @@ public class SshCredentialRequest extends CredentialRequest { } /** - * A builder that provides a fluent API for constructing {@link SshCredentialRequest}s. + * A builder that provides a fluent API for constructing + * {@link SshCredentialRequest}s. */ public static class SshCredentialRequestBuilder extends CredHubRequestBuilder { + @Override protected SshCredentialRequest createTarget() { return new SshCredentialRequest(); @@ -61,14 +63,15 @@ public class SshCredentialRequest extends CredentialRequest { /** * Set the value of an SSH credential. - * * @param value the credential value; must not be {@literal null} * @return the builder */ public SshCredentialRequestBuilder value(SshCredential value) { Assert.notNull(value, "value must not be null"); - targetObj.setValue(value); + this.targetObj.setValue(value); return this; } + } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/ssh/SshParameters.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/ssh/SshParameters.java index ed04171..3e4bcd2 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/ssh/SshParameters.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/ssh/SshParameters.java @@ -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 org.springframework.credhub.support.KeyParameters; import org.springframework.util.Assert; /** - * Parameters for generating a new SSH credential. All parameters are optional; if not specified, - * CredHub-provided defaults will be used. + * Parameters for generating a new SSH credential. All parameters are optional; if not + * specified, CredHub-provided defaults will be used. * * @author Scott Frederick */ public class SshParameters extends KeyParameters { + private final String sshComment; /** @@ -34,12 +35,11 @@ public class SshParameters extends KeyParameters { */ private SshParameters() { super(); - sshComment = null; + this.sshComment = null; } /** * Create a {@link SshParameters} using the specified values. - * * @param sshComment comment for the generated SSH key; must not be {@literal null} */ public SshParameters(String sshComment) { @@ -50,7 +50,6 @@ public class SshParameters extends KeyParameters { /** * Create a {@link SshParameters} using the specified values. - * * @param keyLength length of generated SSH key; must not be {@literal null} */ public SshParameters(KeyLength keyLength) { @@ -61,7 +60,6 @@ public class SshParameters extends KeyParameters { /** * Create a {@link SshParameters} using the specified values. - * * @param keyLength length of generated SSH key; must not be {@literal null} * @param sshComment comment for the generated SSH key; must not be {@literal null} */ @@ -74,10 +72,10 @@ public class SshParameters extends KeyParameters { /** * Get the value of the ssh comment parameter. - * * @return the value of the parameter; will be {@literal null} if not explicitly set */ public String getSshComment() { - return sshComment; + return this.sshComment; } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/ssh/SshParametersRequest.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/ssh/SshParametersRequest.java index 24aaa77..3699d19 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/ssh/SshParametersRequest.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/ssh/SshParametersRequest.java @@ -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.ssh; +import org.springframework.credhub.support.CredentialType; import org.springframework.credhub.support.ParametersRequest; import org.springframework.util.Assert; -import static org.springframework.credhub.support.CredentialType.SSH; - /** * The details of a request to generate a new {@link SshCredential} in CredHub. * * @author Scott Frederick */ public class SshParametersRequest extends ParametersRequest { + /** * Create a {@link SshParametersRequest}. */ SshParametersRequest() { - super(SSH); + super(CredentialType.SSH); } /** - * Create a builder that provides a fluent API for providing the values required - * to construct a {@link SshParametersRequest}. - * + * Create a builder that provides a fluent API for providing the values required to + * construct a {@link SshParametersRequest}. * @return a builder */ public static SshParametersRequestBuilder builder() { @@ -45,10 +44,12 @@ public class SshParametersRequest extends ParametersRequest { } /** - * A builder that provides a fluent API for constructing {@link SshParametersRequest}s. + * A builder that provides a fluent API for constructing + * {@link SshParametersRequest}s. */ public static class SshParametersRequestBuilder extends CredHubRequestBuilder { + @Override protected SshParametersRequest createTarget() { return new SshParametersRequest(); @@ -61,14 +62,15 @@ public class SshParametersRequest extends ParametersRequest { /** * Set the parameters for generation of an SSH credential. - * * @param parameters the generation parameters; must not be {@literal null} * @return the builder */ public SshParametersRequestBuilder parameters(SshParameters parameters) { Assert.notNull(parameters, "parameters must not be null"); - targetObj.setParameters(parameters); + this.targetObj.setParameters(parameters); return this; } + } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/ssh/package-info.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/ssh/package-info.java index 32d5533..62e5fc2 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/ssh/package-info.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/ssh/package-info.java @@ -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 SSH credentials. */ -package org.springframework.credhub.support.ssh; \ No newline at end of file +package org.springframework.credhub.support.ssh; diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/user/UserCredential.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/user/UserCredential.java index f93b914..33e2f77 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/user/UserCredential.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/user/UserCredential.java @@ -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,28 +19,31 @@ package org.springframework.credhub.support.user; import org.springframework.util.Assert; /** - * A user credential consists of an optional username and a password. When retrieved, a user credential - * will contain a hash of the password. + * A user credential consists of an optional username and a password. When retrieved, a + * user credential will contain a hash of the password. * * @author Scott Frederick */ public class UserCredential { + private final String username; + private final String password; + private final String passwordHash; /** - * Create an empty {@link UserCredential}. Intended to be used internally for deserialization of responses. + * Create an empty {@link UserCredential}. Intended to be used internally for + * deserialization of responses. */ private UserCredential() { - username = null; - password = null; - passwordHash = null; + this.username = null; + this.password = null; + this.passwordHash = null; } /** * Create a {@link UserCredential} with the specified values. - * * @param username the name of the user; must not be {@literal null} * @param password the password of the user; must not be {@literal null} */ @@ -54,7 +57,6 @@ public class UserCredential { /** * Create a {@link UserCredential} with the specified password value. - * * @param password the password of the user; must not be {@literal null} */ public UserCredential(String password) { @@ -66,28 +68,26 @@ public class UserCredential { /** * Get the user name. - * * @return the user name */ public String getUsername() { - return username; + return this.username; } /** * Get the user password. - * * @return the user password */ public String getPassword() { - return password; + return this.password; } - + /** * Get the SHA-512 hash of the user password. - * * @return the hash of the user password */ public String getPasswordHash() { - return passwordHash; + return this.passwordHash; } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/user/UserCredentialRequest.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/user/UserCredentialRequest.java index 52b7145..badceaa 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/user/UserCredentialRequest.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/user/UserCredentialRequest.java @@ -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.user; import org.springframework.credhub.support.CredentialRequest; +import org.springframework.credhub.support.CredentialType; import org.springframework.util.Assert; -import static org.springframework.credhub.support.CredentialType.USER; - /** - * The details of a request to write a new or update an existing {@link UserCredential} in CredHub. + * The details of a request to write a new or update an existing {@link UserCredential} in + * CredHub. * * @author Scott Frederick */ public class UserCredentialRequest extends CredentialRequest { + /** * Initialize a {@link CredentialRequest}. */ UserCredentialRequest() { - super(USER); + super(CredentialType.USER); } /** - * Create a builder that provides a fluent API for providing the values required - * to construct a {@link UserCredentialRequest}. - * + * Create a builder that provides a fluent API for providing the values required to + * construct a {@link UserCredentialRequest}. * @return a builder */ public static UserCredentialRequestBuilder builder() { @@ -45,10 +45,12 @@ public class UserCredentialRequest extends CredentialRequest { } /** - * A builder that provides a fluent API for constructing {@link UserCredentialRequest}s. + * A builder that provides a fluent API for constructing + * {@link UserCredentialRequest}s. */ public static class UserCredentialRequestBuilder extends CredHubRequestBuilder { + @Override protected UserCredentialRequest createTarget() { return new UserCredentialRequest(); @@ -61,14 +63,15 @@ public class UserCredentialRequest extends CredentialRequest { /** * Set the value of a user credential. - * * @param value the credential value; must not be {@literal null} * @return the builder */ public UserCredentialRequestBuilder value(UserCredential value) { Assert.notNull(value, "value must not be null"); - targetObj.setValue(value); + this.targetObj.setValue(value); return this; } + } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/user/UserParametersRequest.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/user/UserParametersRequest.java index fed542b..d254c49 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/user/UserParametersRequest.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/user/UserParametersRequest.java @@ -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,29 @@ package org.springframework.credhub.support.user; +import org.springframework.credhub.support.CredentialType; import org.springframework.credhub.support.ParametersRequest; import org.springframework.credhub.support.password.PasswordParameters; import org.springframework.util.Assert; -import static org.springframework.credhub.support.CredentialType.USER; - /** * The details of a request to generate a new {@link UserCredential} in CredHub. * * @author Scott Frederick */ public class UserParametersRequest extends ParametersRequest { + private UserValue value; /** * Create a {@link UserParametersRequest}. */ UserParametersRequest() { - super(USER); + super(CredentialType.USER); } /** * Set the value of the username parameter. - * * @param username the username */ void setValue(String username) { @@ -48,17 +47,15 @@ public class UserParametersRequest extends ParametersRequest /** * Get the value of the username parameter. - * * @return the value of the parameter */ public UserValue getValue() { - return value; + return this.value; } /** - * Create a builder that provides a fluent API for providing the values required - * to construct a {@link UserParametersRequest}. - * + * Create a builder that provides a fluent API for providing the values required to + * construct a {@link UserParametersRequest}. * @return a builder */ public static UserParametersRequestBuilder builder() { @@ -66,10 +63,12 @@ public class UserParametersRequest extends ParametersRequest } /** - * A builder that provides a fluent API for constructing {@link UserParametersRequest}s. + * A builder that provides a fluent API for constructing + * {@link UserParametersRequest}s. */ public static class UserParametersRequestBuilder extends CredHubRequestBuilder { + @Override protected UserParametersRequest createTarget() { return new UserParametersRequest(); @@ -82,33 +81,34 @@ public class UserParametersRequest extends ParametersRequest /** * Set the parameters for generation of the password for a user credential. - * - * @param parameters the password generation parameters; must not be {@literal null} + * @param parameters the password generation parameters; must not be + * {@literal null} * @return the builder */ public UserParametersRequestBuilder parameters(PasswordParameters parameters) { Assert.notNull(parameters, "parameters must not be null"); - targetObj.setParameters(parameters); + this.targetObj.setParameters(parameters); return this; } /** * Set the username for the generated user. - * * @param username the username; must not be {@literal null} * @return the builder */ public UserParametersRequestBuilder username(String username) { Assert.notNull(username, "username must not be null"); - targetObj.setValue(username); + this.targetObj.setValue(username); return this; } + } /** * Holds the value of the username parameter. */ - private static class UserValue { + public static class UserValue { + private String username; UserValue(String username) { @@ -116,7 +116,9 @@ public class UserParametersRequest extends ParametersRequest } public String getUsername() { - return username; + return this.username; } + } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/user/package-info.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/user/package-info.java index c3d8b5b..94cb04e 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/user/package-info.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/user/package-info.java @@ -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 user credentials. */ -package org.springframework.credhub.support.user; \ No newline at end of file +package org.springframework.credhub.support.user; diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/utils/JsonUtils.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/utils/JsonUtils.java index 1cff5dc..ed537f8 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/utils/JsonUtils.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/utils/JsonUtils.java @@ -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.support.utils; +import java.util.ArrayList; +import java.util.List; + import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; @@ -23,21 +26,22 @@ import com.fasterxml.jackson.databind.PropertyNamingStrategy; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.jsontype.NamedType; import com.fasterxml.jackson.databind.util.StdDateFormat; -import org.springframework.credhub.support.CredentialType; -import java.util.ArrayList; -import java.util.List; +import org.springframework.credhub.support.CredentialType; /** * Utility methods for configuring JSON serialization and deserialization. * * @author Scott Frederick */ -public class JsonUtils { +public final class JsonUtils { + + private JsonUtils() { + } + /** - * Create and configure the {@link ObjectMapper} used for serializing and deserializing - * JSON requests and responses. - * + * Create and configure the {@link ObjectMapper} used for serializing and + * deserializing JSON requests and responses. * @return a configured {@link ObjectMapper} */ public static ObjectMapper buildObjectMapper() { @@ -55,9 +59,8 @@ public class JsonUtils { } /** - * Configure type mapping for the {@literal value} field in the {@literal CredentialDetails} - * object. - * + * Configure type mapping for the {@literal value} field in the + * {@literal CredentialDetails} object. * @param objectMapper the {@link ObjectMapper} to configure */ private static void configureCredentialDetailTypeMapping(ObjectMapper objectMapper) { @@ -70,6 +73,7 @@ public class JsonUtils { } private static void registerSubtypes(ObjectMapper objectMapper, List subtypes) { - objectMapper.registerSubtypes(subtypes.toArray(new NamedType[]{})); + objectMapper.registerSubtypes(subtypes.toArray(new NamedType[] {})); } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/utils/package-info.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/utils/package-info.java index 947edae..e16b0bf 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/utils/package-info.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/utils/package-info.java @@ -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 @@ /** * Internal CredHub utility classes. */ -package org.springframework.credhub.support.utils; \ No newline at end of file +package org.springframework.credhub.support.utils; diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/value/ValueCredential.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/value/ValueCredential.java index 6292f3e..1e5d726 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/value/ValueCredential.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/value/ValueCredential.java @@ -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,6 +17,7 @@ package org.springframework.credhub.support.value; import com.fasterxml.jackson.annotation.JsonValue; + import org.springframework.credhub.support.StringCredential; /** @@ -25,9 +26,9 @@ import org.springframework.credhub.support.StringCredential; * @author Scott Frederick */ public class ValueCredential extends StringCredential { + /** * Create a {@link ValueCredential} containing the specified string value. - * * @param value the value */ public ValueCredential(String value) { @@ -36,11 +37,11 @@ public class ValueCredential extends StringCredential { /** * Get the credential value. - * * @return the credential value */ @JsonValue public String getValue() { - return value; + return this.value; } + } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/value/ValueCredentialRequest.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/value/ValueCredentialRequest.java index 466d16d..4b54ec6 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/value/ValueCredentialRequest.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/value/ValueCredentialRequest.java @@ -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.value; import org.springframework.credhub.support.CredentialRequest; +import org.springframework.credhub.support.CredentialType; import org.springframework.util.Assert; -import static org.springframework.credhub.support.CredentialType.VALUE; - /** - * The details of a request to write a new or update an existing value credential in CredHub. + * The details of a request to write a new or update an existing value credential in + * CredHub. * * @author Scott Frederick */ public class ValueCredentialRequest extends CredentialRequest { + /** * Initialize a {@link CredentialRequest}. */ ValueCredentialRequest() { - super(VALUE); + super(CredentialType.VALUE); } /** - * Create a builder that provides a fluent API for providing the values required - * to construct a {@link ValueCredentialRequest}. - * + * Create a builder that provides a fluent API for providing the values required to + * construct a {@link ValueCredentialRequest}. * @return a builder */ public static ValueCredentialRequestBuilder builder() { @@ -45,10 +45,12 @@ public class ValueCredentialRequest extends CredentialRequest { } /** - * A builder that provides a fluent API for constructing {@link ValueCredentialRequest}s. + * A builder that provides a fluent API for constructing + * {@link ValueCredentialRequest}s. */ public static class ValueCredentialRequestBuilder extends CredHubRequestBuilder { + @Override protected ValueCredentialRequest createTarget() { return new ValueCredentialRequest(); @@ -61,19 +63,17 @@ public class ValueCredentialRequest extends CredentialRequest { /** * Set the value of a {@literal value} credential. - * * @param value the credential value; must not be {@literal null} * @return the builder */ public ValueCredentialRequestBuilder value(ValueCredential value) { Assert.notNull(value, "value must not be null"); - targetObj.setValue(value); + this.targetObj.setValue(value); return this; } /** - * Set the value of a {@literal value} credential. - * + * Set the value of a {@literal value} credential. * @param value the credential value; must not be {@literal null} * @return the builder */ @@ -81,6 +81,7 @@ public class ValueCredentialRequest extends CredentialRequest { value(new ValueCredential(value)); return this; } + } } diff --git a/spring-credhub-core/src/main/java/org/springframework/credhub/support/value/package-info.java b/spring-credhub-core/src/main/java/org/springframework/credhub/support/value/package-info.java index f338286..d624959 100644 --- a/spring-credhub-core/src/main/java/org/springframework/credhub/support/value/package-info.java +++ b/spring-credhub-core/src/main/java/org/springframework/credhub/support/value/package-info.java @@ -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 value credentials. */ -package org.springframework.credhub.support.value; \ No newline at end of file +package org.springframework.credhub.support.value; diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/configuration/ClientHttpConnectorFactoryTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/configuration/ClientHttpConnectorFactoryTests.java index e435ab1..59ec3f0 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/configuration/ClientHttpConnectorFactoryTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/configuration/ClientHttpConnectorFactoryTests.java @@ -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,16 +17,19 @@ package org.springframework.credhub.configuration; import org.junit.Test; + import org.springframework.credhub.support.ClientOptions; import org.springframework.http.client.reactive.ClientHttpConnector; import static org.assertj.core.api.Assertions.assertThat; public class ClientHttpConnectorFactoryTests { + @Test public void nettyClientIsCreated() { ClientHttpConnector clientHttpConnector = ClientHttpConnectorFactory.create(new ClientOptions()); assertThat(clientHttpConnector).isNotNull(); } -} \ No newline at end of file + +} diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/configuration/ClientHttpRequestFactoryFactoryTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/configuration/ClientHttpRequestFactoryFactoryTests.java index 491e600..083f9ac 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/configuration/ClientHttpRequestFactoryFactoryTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/configuration/ClientHttpRequestFactoryFactoryTests.java @@ -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,10 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.junit.Test; import org.springframework.beans.factory.DisposableBean; +import org.springframework.credhub.configuration.ClientHttpRequestFactoryFactory.HttpComponents; +import org.springframework.credhub.configuration.ClientHttpRequestFactoryFactory.HttpURLConnection; +import org.springframework.credhub.configuration.ClientHttpRequestFactoryFactory.Netty; +import org.springframework.credhub.configuration.ClientHttpRequestFactoryFactory.OkHttp3; import org.springframework.credhub.support.ClientOptions; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; @@ -29,22 +33,19 @@ import org.springframework.http.client.OkHttp3ClientHttpRequestFactory; import org.springframework.http.client.SimpleClientHttpRequestFactory; import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.credhub.configuration.ClientHttpRequestFactoryFactory.HttpComponents.usingHttpComponents; -import static org.springframework.credhub.configuration.ClientHttpRequestFactoryFactory.HttpURLConnection.usingJdk; -import static org.springframework.credhub.configuration.ClientHttpRequestFactoryFactory.Netty.usingNetty; -import static org.springframework.credhub.configuration.ClientHttpRequestFactoryFactory.OkHttp3.usingOkHttp3; public class ClientHttpRequestFactoryFactoryTests { + @Test public void jdkDefaultClientCreated() { - ClientHttpRequestFactory factory = usingJdk(new ClientOptions()); + ClientHttpRequestFactory factory = HttpURLConnection.usingJdk(new ClientOptions()); assertThat(factory).isInstanceOf(SimpleClientHttpRequestFactory.class); } @Test public void httpComponentsClientCreated() throws Exception { - ClientHttpRequestFactory factory = usingHttpComponents(new ClientOptions()); + ClientHttpRequestFactory factory = HttpComponents.usingHttpComponents(new ClientOptions()); assertThat(factory).isInstanceOf(HttpComponentsClientHttpRequestFactory.class); @@ -57,7 +58,7 @@ public class ClientHttpRequestFactoryFactoryTests { @Test public void okHttp3ClientCreated() throws Exception { - ClientHttpRequestFactory factory = usingOkHttp3(new ClientOptions()); + ClientHttpRequestFactory factory = OkHttp3.usingOkHttp3(new ClientOptions()); assertThat(factory).isInstanceOf(OkHttp3ClientHttpRequestFactory.class); @@ -67,10 +68,11 @@ public class ClientHttpRequestFactoryFactoryTests { @Test @SuppressWarnings("deprecation") public void nettyClientCreated() throws Exception { - ClientHttpRequestFactory factory = usingNetty(new ClientOptions()); + ClientHttpRequestFactory factory = Netty.usingNetty(new ClientOptions()); assertThat(factory).isInstanceOf(Netty4ClientHttpRequestFactory.class); ((DisposableBean) factory).destroy(); } -} \ No newline at end of file + +} diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/core/CredHubRestTemplateFactoryUnitTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/core/CredHubRestTemplateFactoryUnitTests.java index 20a3fbd..30a36c7 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/core/CredHubRestTemplateFactoryUnitTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/core/CredHubRestTemplateFactoryUnitTests.java @@ -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; @@ -30,6 +28,7 @@ import static org.assertj.core.api.Assertions.assertThat; @RunWith(MockitoJUnitRunner.class) public class CredHubRestTemplateFactoryUnitTests { + @Mock private ClientHttpRequestFactory clientHttpRequestFactory; @@ -37,9 +36,10 @@ public class CredHubRestTemplateFactoryUnitTests { public void restTemplateIsCreated() { CredHubProperties properties = new CredHubProperties(); properties.setUrl("https://credhub.cf.example.com:8844"); - RestTemplate restTemplate = CredHubRestTemplateFactory - .createRestTemplate(properties, clientHttpRequestFactory); + RestTemplate restTemplate = CredHubRestTemplateFactory.createRestTemplate(properties, + this.clientHttpRequestFactory); assertThat(restTemplate).isNotNull(); } -} \ No newline at end of file + +} diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/core/CredHubWebClientFactoryTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/core/CredHubWebClientFactoryTests.java index 25f650c..fae9085 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/core/CredHubWebClientFactoryTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/core/CredHubWebClientFactoryTests.java @@ -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. @@ -20,6 +20,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; + import org.springframework.http.client.reactive.ClientHttpConnector; import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository; import org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository; @@ -29,6 +30,7 @@ import static org.assertj.core.api.Assertions.assertThat; @RunWith(MockitoJUnitRunner.class) public class CredHubWebClientFactoryTests { + @Mock private ClientHttpConnector clientHttpConnector; @@ -40,10 +42,10 @@ public class CredHubWebClientFactoryTests { @Test public void webClientIsCreated() { - WebClient webClient = CredHubWebClientFactory - .createWebClient(new CredHubProperties(), clientHttpConnector, - clientRegistrationRepository, authorizedClientRepository); + WebClient webClient = CredHubWebClientFactory.createWebClient(new CredHubProperties(), this.clientHttpConnector, + this.clientRegistrationRepository, this.authorizedClientRepository); assertThat(webClient).isNotNull(); } -} \ No newline at end of file + +} diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/core/certificate/CredHubCertificateTemplateUnitTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/core/certificate/CredHubCertificateTemplateUnitTests.java index fd9efb5..34eb8c8 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/core/certificate/CredHubCertificateTemplateUnitTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/core/certificate/CredHubCertificateTemplateUnitTests.java @@ -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,49 +16,41 @@ package org.springframework.credhub.core.certificate; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.core.ParameterizedTypeReference; -import org.springframework.credhub.core.CredHubTemplate; -import org.springframework.credhub.support.CredentialName; -import org.springframework.credhub.support.certificate.CertificateSummary; -import org.springframework.credhub.support.certificate.CertificateSummaryData; -import org.springframework.credhub.support.CredentialType; -import org.springframework.credhub.support.SimpleCredentialName; -import org.springframework.credhub.support.certificate.CertificateCredential; -import org.springframework.credhub.support.certificate.CertificateCredentialDetails; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpMethod; -import org.springframework.http.ResponseEntity; -import org.springframework.web.client.RestTemplate; - import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.credhub.core.CredHubTemplate; +import org.springframework.credhub.support.CredentialName; +import org.springframework.credhub.support.CredentialType; +import org.springframework.credhub.support.SimpleCredentialName; +import org.springframework.credhub.support.certificate.CertificateCredential; +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.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.when; -import static org.springframework.credhub.core.certificate.CredHubCertificateTemplate.BASE_URL_PATH; -import static org.springframework.credhub.core.certificate.CredHubCertificateTemplate.BULK_REGENERATE_URL_PATH; -import static org.springframework.credhub.core.certificate.CredHubCertificateTemplate.NAME_URL_QUERY; -import static org.springframework.credhub.core.certificate.CredHubCertificateTemplate.REGENERATED_CREDENTIALS_RESPONSE_FIELD; -import static org.springframework.credhub.core.certificate.CredHubCertificateTemplate.REGENERATE_URL_PATH; -import static org.springframework.credhub.core.certificate.CredHubCertificateTemplate.SIGNED_BY_REQUEST_FIELD; -import static org.springframework.credhub.core.certificate.CredHubCertificateTemplate.TRANSITIONAL_REQUEST_FIELD; -import static org.springframework.credhub.core.certificate.CredHubCertificateTemplate.UPDATE_TRANSITIONAL_URL_PATH; -import static org.springframework.credhub.core.certificate.CredHubCertificateTemplate.VERSION_REQUEST_FIELD; -import static org.springframework.http.HttpMethod.POST; -import static org.springframework.http.HttpStatus.OK; +import static org.mockito.BDDMockito.given; @RunWith(MockitoJUnitRunner.class) public class CredHubCertificateTemplateUnitTests { + private static final SimpleCredentialName NAME = new SimpleCredentialName("example", "certificate"); @Mock @@ -68,21 +60,18 @@ public class CredHubCertificateTemplateUnitTests { @Before public void setUp() { - credHubTemplate = new CredHubTemplate(restTemplate).certificates(); + this.credHubTemplate = new CredHubTemplate(this.restTemplate).certificates(); } @Test public void getAll() { - CertificateSummaryData expectedCertificates = new CertificateSummaryData( - new CertificateSummary("id1", "name1"), - new CertificateSummary("id2", "name2"), - new CertificateSummary("id3", "name3") - ); + CertificateSummaryData expectedCertificates = new CertificateSummaryData(new CertificateSummary("id1", "name1"), + new CertificateSummary("id2", "name2"), new CertificateSummary("id3", "name3")); - when(restTemplate.getForEntity(BASE_URL_PATH, CertificateSummaryData.class)) - .thenReturn(new ResponseEntity<>(expectedCertificates, OK)); + given(this.restTemplate.getForEntity(CredHubCertificateTemplate.BASE_URL_PATH, CertificateSummaryData.class)) + .willReturn(new ResponseEntity<>(expectedCertificates, HttpStatus.OK)); - List response = credHubTemplate.getAll(); + List response = this.credHubTemplate.getAll(); assertThat(response).isNotNull(); assertThat(response.size()).isEqualTo(expectedCertificates.getCertificates().size()); @@ -92,13 +81,12 @@ public class CredHubCertificateTemplateUnitTests { @Test public void getByName() { CertificateSummaryData expectedCertificates = new CertificateSummaryData( - new CertificateSummary("id1", "name1") - ); + new CertificateSummary("id1", "name1")); - when(restTemplate.getForEntity(NAME_URL_QUERY, CertificateSummaryData.class, NAME.getName())) - .thenReturn(new ResponseEntity<>(expectedCertificates, OK)); + given(this.restTemplate.getForEntity(CredHubCertificateTemplate.NAME_URL_QUERY, CertificateSummaryData.class, + NAME.getName())).willReturn(new ResponseEntity<>(expectedCertificates, HttpStatus.OK)); - CertificateSummary response = credHubTemplate.getByName(NAME); + CertificateSummary response = this.credHubTemplate.getByName(NAME); assertThat(response).isNotNull(); assertThat(response.getId()).isEqualTo("id1"); @@ -108,18 +96,17 @@ public class CredHubCertificateTemplateUnitTests { @Test @SuppressWarnings("unchecked") public void regenerate() { - CertificateCredentialDetails expectedCertificate = - new CertificateCredentialDetails("id", NAME, CredentialType.CERTIFICATE, true, - new CertificateCredential("cert", "authority", "key")); + CertificateCredentialDetails expectedCertificate = new CertificateCredentialDetails("id", NAME, + CredentialType.CERTIFICATE, true, new CertificateCredential("cert", "authority", "key")); Map request = new HashMap<>(); - request.put(TRANSITIONAL_REQUEST_FIELD, true); + request.put(CredHubCertificateTemplate.TRANSITIONAL_REQUEST_FIELD, true); - when(restTemplate.exchange(eq(REGENERATE_URL_PATH), eq(HttpMethod.POST), + given(this.restTemplate.exchange(eq(CredHubCertificateTemplate.REGENERATE_URL_PATH), eq(HttpMethod.POST), eq(new HttpEntity<>(request)), isA(ParameterizedTypeReference.class), eq("id"))) - .thenReturn(new ResponseEntity<>(expectedCertificate, OK)); + .willReturn(new ResponseEntity<>(expectedCertificate, HttpStatus.OK)); - CertificateCredentialDetails response = credHubTemplate.regenerate("id", true); + CertificateCredentialDetails response = this.credHubTemplate.regenerate("id", true); assertThat(response).isNotNull(); assertThat(response.getId()).isEqualTo("id"); @@ -133,24 +120,26 @@ public class CredHubCertificateTemplateUnitTests { @Test @SuppressWarnings("unchecked") public void bulkRegenerate() { - Map> expectedResponse = - Collections.singletonMap(REGENERATED_CREDENTIALS_RESPONSE_FIELD, - Arrays.asList( - new SimpleCredentialName("example-certificate1"), - new SimpleCredentialName("example-certificate2"))); + Map> expectedResponse = Collections.singletonMap( + CredHubCertificateTemplate.REGENERATED_CREDENTIALS_RESPONSE_FIELD, + Arrays.asList(new SimpleCredentialName("example-certificate1"), + new SimpleCredentialName("example-certificate2"))); - Map request = new HashMap() {{ - put(SIGNED_BY_REQUEST_FIELD, NAME.getName()); - }}; + Map request = new HashMap() { + { + put(CredHubCertificateTemplate.SIGNED_BY_REQUEST_FIELD, NAME.getName()); + } + }; - when(restTemplate.exchange(eq(BULK_REGENERATE_URL_PATH), eq(POST), + given(this.restTemplate.exchange(eq(CredHubCertificateTemplate.BULK_REGENERATE_URL_PATH), eq(HttpMethod.POST), eq(new HttpEntity<>(request)), isA(ParameterizedTypeReference.class))) - .thenReturn(new ResponseEntity<>(expectedResponse, OK)); + .willReturn(new ResponseEntity<>(expectedResponse, HttpStatus.OK)); - List response = credHubTemplate.regenerate(NAME); + List response = this.credHubTemplate.regenerate(NAME); assertThat(response).isNotNull(); - assertThat(response).isEqualTo(expectedResponse.get(REGENERATED_CREDENTIALS_RESPONSE_FIELD)); + assertThat(response) + .isEqualTo(expectedResponse.get(CredHubCertificateTemplate.REGENERATED_CREDENTIALS_RESPONSE_FIELD)); } @Test @@ -160,18 +149,16 @@ public class CredHubCertificateTemplateUnitTests { new CertificateCredentialDetails("id1", NAME, CredentialType.CERTIFICATE, false, new CertificateCredential("cert1", "authority1", "key1")), new CertificateCredentialDetails("id2", NAME, CredentialType.CERTIFICATE, true, - new CertificateCredential("cert2", "authority2", "key2")) - ); + new CertificateCredential("cert2", "authority2", "key2"))); Map request = new HashMap<>(); - request.put(VERSION_REQUEST_FIELD, "id2"); + request.put(CredHubCertificateTemplate.VERSION_REQUEST_FIELD, "id2"); - when(restTemplate.exchange(eq(UPDATE_TRANSITIONAL_URL_PATH), eq(HttpMethod.PUT), - eq(new HttpEntity<>(request)), isA(ParameterizedTypeReference.class), eq("id1"))) - .thenReturn(new ResponseEntity<>(expectedCertificates, OK)); + given(this.restTemplate.exchange(eq(CredHubCertificateTemplate.UPDATE_TRANSITIONAL_URL_PATH), + eq(HttpMethod.PUT), eq(new HttpEntity<>(request)), isA(ParameterizedTypeReference.class), eq("id1"))) + .willReturn(new ResponseEntity<>(expectedCertificates, HttpStatus.OK)); - List response = - credHubTemplate.updateTransitionalVersion("id1", "id2"); + List response = this.credHubTemplate.updateTransitionalVersion("id1", "id2"); assertThat(response).hasSize(2); assertThat(response).extracting("id").contains("id1", "id2"); @@ -182,4 +169,5 @@ public class CredHubCertificateTemplateUnitTests { assertThat(response).extracting("value.certificateAuthority").contains("authority1", "authority2"); assertThat(response).extracting("value.privateKey").contains("key1", "key2"); } -} \ No newline at end of file + +} diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubCredentialTemplateSummaryUnitTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubCredentialTemplateSummaryUnitTests.java index ebde2bb..0eda1f0 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubCredentialTemplateSummaryUnitTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubCredentialTemplateSummaryUnitTests.java @@ -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,75 +27,71 @@ import org.junit.runner.RunWith; import org.springframework.credhub.core.CredHubException; import org.springframework.credhub.support.CredentialSummary; import org.springframework.credhub.support.CredentialSummaryData; +import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; -import static org.mockito.Mockito.when; -import static org.springframework.credhub.core.credential.CredHubCredentialTemplate.NAME_LIKE_URL_QUERY; -import static org.springframework.credhub.core.credential.CredHubCredentialTemplate.PATH_URL_QUERY; -import static org.springframework.http.HttpStatus.OK; -import static org.springframework.http.HttpStatus.UNAUTHORIZED; +import static org.mockito.BDDMockito.given; @RunWith(Theories.class) public class CredHubCredentialTemplateSummaryUnitTests extends CredHubCredentialTemplateUnitTestsBase { - @DataPoint("responses") - public static ResponseEntity successfulResponse = - ResponseEntity - .ok() - .body(new CredentialSummaryData(new CredentialSummary(NAME))); @DataPoint("responses") - public static ResponseEntity httpErrorResponse = - ResponseEntity - .status(UNAUTHORIZED) - .body(new CredentialSummaryData()); + public static ResponseEntity successfulResponse = ResponseEntity.ok() + .body(new CredentialSummaryData(new CredentialSummary(NAME))); + + @DataPoint("responses") + public static ResponseEntity httpErrorResponse = ResponseEntity + .status(HttpStatus.UNAUTHORIZED).body(new CredentialSummaryData()); @Theory - public void findByName(@FromDataPoints("responses") - ResponseEntity expectedResponse) { - when(restTemplate.getForEntity(NAME_LIKE_URL_QUERY, CredentialSummaryData.class, NAME.getName())) - .thenReturn(expectedResponse); + public void findByName(@FromDataPoints("responses") ResponseEntity expectedResponse) { + given(this.restTemplate.getForEntity(CredHubCredentialTemplate.NAME_LIKE_URL_QUERY, CredentialSummaryData.class, + NAME.getName())).willReturn(expectedResponse); - if (!expectedResponse.getStatusCode().equals(OK)) { + if (!expectedResponse.getStatusCode().equals(HttpStatus.OK)) { try { - credHubTemplate.findByName(NAME); + this.credHubTemplate.findByName(NAME); fail("Exception should have been thrown"); - } catch (CredHubException e) { - assertThat(e.getMessage()).contains(expectedResponse.getStatusCode().toString()); } - } else { - List response = credHubTemplate.findByName(NAME); + catch (CredHubException ex) { + assertThat(ex.getMessage()).contains(expectedResponse.getStatusCode().toString()); + } + } + else { + List response = this.credHubTemplate.findByName(NAME); assertResponseContainsExpectedCredentials(expectedResponse, response); } } @Theory - public void findByPath(@FromDataPoints("responses") - ResponseEntity expectedResponse) { - when(restTemplate.getForEntity(PATH_URL_QUERY, CredentialSummaryData.class, NAME.getName())) - .thenReturn(expectedResponse); + public void findByPath(@FromDataPoints("responses") ResponseEntity expectedResponse) { + given(this.restTemplate.getForEntity(CredHubCredentialTemplate.PATH_URL_QUERY, CredentialSummaryData.class, + NAME.getName())).willReturn(expectedResponse); - if (!expectedResponse.getStatusCode().equals(OK)) { + if (!expectedResponse.getStatusCode().equals(HttpStatus.OK)) { try { - credHubTemplate.findByPath(NAME.getName()); + this.credHubTemplate.findByPath(NAME.getName()); fail("Exception should have been thrown"); - } catch (CredHubException e) { - assertThat(e.getMessage()).contains(expectedResponse.getStatusCode().toString()); } - } else { - List response = credHubTemplate.findByPath(NAME.getName()); + catch (CredHubException ex) { + assertThat(ex.getMessage()).contains(expectedResponse.getStatusCode().toString()); + } + } + else { + List response = this.credHubTemplate.findByPath(NAME.getName()); assertResponseContainsExpectedCredentials(expectedResponse, response); } } - private void assertResponseContainsExpectedCredentials( - ResponseEntity expectedResponse, + private void assertResponseContainsExpectedCredentials(ResponseEntity expectedResponse, List response) { assertThat(response).isNotNull(); assertThat(response.size()).isEqualTo(expectedResponse.getBody().getCredentials().size()); assertThat(response).contains(expectedResponse.getBody().getCredentials().get(0)); } -} \ No newline at end of file + +} diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubCredentialTemplateUnitTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubCredentialTemplateUnitTests.java index 52d6915..a879167 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubCredentialTemplateUnitTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubCredentialTemplateUnitTests.java @@ -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,32 +16,33 @@ package org.springframework.credhub.core.credential; +import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; + import org.springframework.credhub.support.CredentialPath; import org.springframework.credhub.support.CredentialPathData; +import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import java.util.List; - import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static org.springframework.credhub.core.credential.CredHubCredentialTemplate.NAME_URL_QUERY; -import static org.springframework.credhub.core.credential.CredHubCredentialTemplate.SHOW_ALL_URL_QUERY; -import static org.springframework.http.HttpStatus.OK; @RunWith(MockitoJUnitRunner.class) public class CredHubCredentialTemplateUnitTests extends CredHubCredentialTemplateUnitTestsBase { + @Test @SuppressWarnings("deprecation") public void getAllPaths() { - when(restTemplate.getForEntity(SHOW_ALL_URL_QUERY, CredentialPathData.class)) - .thenReturn(new ResponseEntity<>(new CredentialPathData(new CredentialPath("/path1"), new CredentialPath("/path2")), OK)); + given(this.restTemplate.getForEntity(CredHubCredentialTemplate.SHOW_ALL_URL_QUERY, CredentialPathData.class)) + .willReturn(new ResponseEntity<>( + new CredentialPathData(new CredentialPath("/path1"), new CredentialPath("/path2")), + HttpStatus.OK)); - List paths = credHubTemplate.getAllPaths(); + List paths = this.credHubTemplate.getAllPaths(); assertThat(paths.size()).isEqualTo(2); assertThat(paths).extracting("path").contains("/path1", "/path2"); @@ -49,8 +50,9 @@ public class CredHubCredentialTemplateUnitTests extends CredHubCredentialTemplat @Test public void deleteByName() { - credHubTemplate.deleteByName(NAME); + this.credHubTemplate.deleteByName(NAME); - verify(restTemplate).delete(NAME_URL_QUERY, NAME.getName()); + verify(this.restTemplate).delete(CredHubCredentialTemplate.NAME_URL_QUERY, NAME.getName()); } -} \ No newline at end of file + +} diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubCredentialTemplateUnitTestsBase.java b/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubCredentialTemplateUnitTestsBase.java index 02ace70..44a7e85 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubCredentialTemplateUnitTestsBase.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubCredentialTemplateUnitTestsBase.java @@ -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,6 +28,7 @@ import org.springframework.credhub.support.SimpleCredentialName; import org.springframework.web.client.RestTemplate; public abstract class CredHubCredentialTemplateUnitTestsBase { + protected static final SimpleCredentialName NAME = new SimpleCredentialName("example", "credential"); @Rule @@ -40,6 +41,7 @@ public abstract class CredHubCredentialTemplateUnitTestsBase { @Before public void setUpCredHubTemplateUnitTests() { - credHubTemplate = new CredHubTemplate(restTemplate).credentials(); + this.credHubTemplate = new CredHubTemplate(this.restTemplate).credentials(); } + } diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubTemplateDetailCertificateUnitTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubTemplateDetailCertificateUnitTests.java index 9297690..24cb497 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubTemplateDetailCertificateUnitTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubTemplateDetailCertificateUnitTests.java @@ -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, @@ -38,12 +38,12 @@ import org.springframework.http.ResponseEntity; @RunWith(Theories.class) public class CredHubTemplateDetailCertificateUnitTests extends CredHubTemplateDetailUnitTestsBase { - private static final CertificateCredential CREDENTIAL = - new CertificateCredential("certificate", "authority", "private-key"); - private static final CertificateParameters PARAMETERS = CertificateParameters.builder() - .commonName("common") - .certificateAuthorityCredential("credential") - .build(); + + private static final CertificateCredential CREDENTIAL = new CertificateCredential("certificate", "authority", + "private-key"); + + private static final CertificateParameters PARAMETERS = CertificateParameters.builder().commonName("common") + .certificateAuthorityCredential("credential").build(); @DataPoints("detail-responses") public static List>> buildDetailResponses() { @@ -57,18 +57,12 @@ public class CredHubTemplateDetailCertificateUnitTests @Override public CredentialRequest getWriteRequest() { - return CertificateCredentialRequest.builder() - .name(NAME) - .value(CREDENTIAL) - .build(); + return CertificateCredentialRequest.builder().name(NAME).value(CREDENTIAL).build(); } @Override public ParametersRequest getGenerateRequest() { - return CertificateParametersRequest.builder() - .name(NAME) - .parameters(PARAMETERS) - .build(); + return CertificateParametersRequest.builder().name(NAME).parameters(PARAMETERS).build(); } @Override @@ -77,44 +71,45 @@ public class CredHubTemplateDetailCertificateUnitTests } @Theory - public void write(@FromDataPoints("detail-responses") - ResponseEntity> expectedResponse) { + public void write( + @FromDataPoints("detail-responses") ResponseEntity> expectedResponse) { verifyWrite(expectedResponse); } @Theory - public void generate(@FromDataPoints("detail-responses") - ResponseEntity> expectedResponse) { + public void generate( + @FromDataPoints("detail-responses") ResponseEntity> expectedResponse) { verifyGenerate(expectedResponse); } @Theory - public void regenerate(@FromDataPoints("detail-responses") - ResponseEntity> expectedResponse) { + public void regenerate( + @FromDataPoints("detail-responses") ResponseEntity> expectedResponse) { verifyRegenerate(expectedResponse); } @Theory - public void getById(@FromDataPoints("detail-responses") - ResponseEntity> expectedResponse) { + public void getById( + @FromDataPoints("detail-responses") ResponseEntity> expectedResponse) { verifyGetById(expectedResponse); } @Theory - public void getByName(@FromDataPoints("data-responses") - ResponseEntity> expectedResponse) { + public void getByName( + @FromDataPoints("data-responses") ResponseEntity> expectedResponse) { verifyGetByName(expectedResponse); } @Theory - public void getByNameWithHistory(@FromDataPoints("data-responses") - ResponseEntity> expectedResponse) { + public void getByNameWithHistory( + @FromDataPoints("data-responses") ResponseEntity> expectedResponse) { verifyGetByNameWithHistory(expectedResponse); } @Theory - public void getByNameWithVersions(@FromDataPoints("data-responses") - ResponseEntity> expectedResponse) { + public void getByNameWithVersions( + @FromDataPoints("data-responses") ResponseEntity> expectedResponse) { verifyGetByNameWithVersions(expectedResponse); } -} \ No newline at end of file + +} diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubTemplateDetailJsonUnitTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubTemplateDetailJsonUnitTests.java index abf7486..cab3d57 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubTemplateDetailJsonUnitTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubTemplateDetailJsonUnitTests.java @@ -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, @@ -33,8 +33,8 @@ import org.springframework.credhub.support.json.JsonCredentialRequest; import org.springframework.http.ResponseEntity; @RunWith(Theories.class) -public class CredHubTemplateDetailJsonUnitTests - extends CredHubTemplateDetailUnitTestsBase { +public class CredHubTemplateDetailJsonUnitTests extends CredHubTemplateDetailUnitTestsBase { + private static final JsonCredential CREDENTIAL = new JsonCredential() { { put("data", "value"); @@ -54,10 +54,7 @@ public class CredHubTemplateDetailJsonUnitTests @Override public CredentialRequest getWriteRequest() { - return JsonCredentialRequest.builder() - .name(NAME) - .value(CREDENTIAL) - .build(); + return JsonCredentialRequest.builder().name(NAME).value(CREDENTIAL).build(); } @Override @@ -66,32 +63,33 @@ public class CredHubTemplateDetailJsonUnitTests } @Theory - public void write(@FromDataPoints("detail-responses") - ResponseEntity> expectedResponse) { + public void write( + @FromDataPoints("detail-responses") ResponseEntity> expectedResponse) { verifyWrite(expectedResponse); } @Theory - public void getById(@FromDataPoints("detail-responses") - ResponseEntity> expectedResponse) { + public void getById( + @FromDataPoints("detail-responses") ResponseEntity> expectedResponse) { verifyGetById(expectedResponse); } @Theory - public void getByName(@FromDataPoints("data-responses") - ResponseEntity> expectedResponse) { + public void getByName( + @FromDataPoints("data-responses") ResponseEntity> expectedResponse) { verifyGetByName(expectedResponse); } @Theory - public void getByNameWithHistory(@FromDataPoints("data-responses") - ResponseEntity> expectedResponse) { + public void getByNameWithHistory( + @FromDataPoints("data-responses") ResponseEntity> expectedResponse) { verifyGetByNameWithHistory(expectedResponse); } @Theory - public void getByNameWithVersions(@FromDataPoints("data-responses") - ResponseEntity> expectedResponse) { + public void getByNameWithVersions( + @FromDataPoints("data-responses") ResponseEntity> expectedResponse) { verifyGetByNameWithVersions(expectedResponse); } -} \ No newline at end of file + +} diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubTemplateDetailPasswordUnitTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubTemplateDetailPasswordUnitTests.java index bdb7d37..fc22f47 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubTemplateDetailPasswordUnitTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubTemplateDetailPasswordUnitTests.java @@ -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, @@ -38,7 +38,9 @@ import org.springframework.http.ResponseEntity; @RunWith(Theories.class) public class CredHubTemplateDetailPasswordUnitTests extends CredHubTemplateDetailUnitTestsBase { + private static final PasswordCredential CREDENTIAL = new PasswordCredential("secret"); + private static final PasswordParameters PARAMETERS = new PasswordParameters(); @DataPoints("detail-responses") @@ -53,18 +55,12 @@ public class CredHubTemplateDetailPasswordUnitTests @Override public CredentialRequest getWriteRequest() { - return PasswordCredentialRequest.builder() - .name(NAME) - .value(CREDENTIAL) - .build(); + return PasswordCredentialRequest.builder().name(NAME).value(CREDENTIAL).build(); } @Override protected ParametersRequest getGenerateRequest() { - return PasswordParametersRequest.builder() - .name(NAME) - .parameters(PARAMETERS) - .build(); + return PasswordParametersRequest.builder().name(NAME).parameters(PARAMETERS).build(); } @Override @@ -73,44 +69,45 @@ public class CredHubTemplateDetailPasswordUnitTests } @Theory - public void write(@FromDataPoints("detail-responses") - ResponseEntity> expectedResponse) { + public void write( + @FromDataPoints("detail-responses") ResponseEntity> expectedResponse) { verifyWrite(expectedResponse); } @Theory - public void generate(@FromDataPoints("detail-responses") - ResponseEntity> expectedResponse) { + public void generate( + @FromDataPoints("detail-responses") ResponseEntity> expectedResponse) { verifyGenerate(expectedResponse); } @Theory - public void regenerate(@FromDataPoints("detail-responses") - ResponseEntity> expectedResponse) { + public void regenerate( + @FromDataPoints("detail-responses") ResponseEntity> expectedResponse) { verifyRegenerate(expectedResponse); } @Theory - public void getById(@FromDataPoints("detail-responses") - ResponseEntity> expectedResponse) { + public void getById( + @FromDataPoints("detail-responses") ResponseEntity> expectedResponse) { verifyGetById(expectedResponse); } @Theory - public void getByName(@FromDataPoints("data-responses") - ResponseEntity> expectedResponse) { + public void getByName( + @FromDataPoints("data-responses") ResponseEntity> expectedResponse) { verifyGetByName(expectedResponse); } @Theory - public void getByNameWithHistory(@FromDataPoints("data-responses") - ResponseEntity> expectedResponse) { + public void getByNameWithHistory( + @FromDataPoints("data-responses") ResponseEntity> expectedResponse) { verifyGetByNameWithHistory(expectedResponse); } @Theory - public void getByNameWithVersions(@FromDataPoints("data-responses") - ResponseEntity> expectedResponse) { + public void getByNameWithVersions( + @FromDataPoints("data-responses") ResponseEntity> expectedResponse) { verifyGetByNameWithVersions(expectedResponse); } -} \ No newline at end of file + +} diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubTemplateDetailRsaUnitTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubTemplateDetailRsaUnitTests.java index 09b93e2..8652729 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubTemplateDetailRsaUnitTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubTemplateDetailRsaUnitTests.java @@ -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, @@ -39,7 +39,9 @@ import org.springframework.http.ResponseEntity; @RunWith(Theories.class) public class CredHubTemplateDetailRsaUnitTests extends CredHubTemplateDetailUnitTestsBase { + private static final RsaCredential CREDENTIAL = new RsaCredential("public-key", "private-key"); + private static final RsaParameters PARAMETERS = new RsaParameters(KeyLength.LENGTH_4096); @DataPoints("detail-responses") @@ -54,18 +56,12 @@ public class CredHubTemplateDetailRsaUnitTests @Override public CredentialRequest getWriteRequest() { - return RsaCredentialRequest.builder() - .name(NAME) - .value(CREDENTIAL) - .build(); + return RsaCredentialRequest.builder().name(NAME).value(CREDENTIAL).build(); } @Override public ParametersRequest getGenerateRequest() { - return RsaParametersRequest.builder() - .name(NAME) - .parameters(PARAMETERS) - .build(); + return RsaParametersRequest.builder().name(NAME).parameters(PARAMETERS).build(); } @Override @@ -74,44 +70,45 @@ public class CredHubTemplateDetailRsaUnitTests } @Theory - public void write(@FromDataPoints("detail-responses") - ResponseEntity> expectedResponse) { + public void write( + @FromDataPoints("detail-responses") ResponseEntity> expectedResponse) { verifyWrite(expectedResponse); } @Theory - public void generate(@FromDataPoints("detail-responses") - ResponseEntity> expectedResponse) { + public void generate( + @FromDataPoints("detail-responses") ResponseEntity> expectedResponse) { verifyGenerate(expectedResponse); } @Theory - public void regenerate(@FromDataPoints("detail-responses") - ResponseEntity> expectedResponse) { + public void regenerate( + @FromDataPoints("detail-responses") ResponseEntity> expectedResponse) { verifyRegenerate(expectedResponse); } @Theory - public void getById(@FromDataPoints("detail-responses") - ResponseEntity> expectedResponse) { + public void getById( + @FromDataPoints("detail-responses") ResponseEntity> expectedResponse) { verifyGetById(expectedResponse); } @Theory - public void getByName(@FromDataPoints("data-responses") - ResponseEntity> expectedResponse) { + public void getByName( + @FromDataPoints("data-responses") ResponseEntity> expectedResponse) { verifyGetByName(expectedResponse); } @Theory - public void getByNameWithHistory(@FromDataPoints("data-responses") - ResponseEntity> expectedResponse) { + public void getByNameWithHistory( + @FromDataPoints("data-responses") ResponseEntity> expectedResponse) { verifyGetByNameWithHistory(expectedResponse); } @Theory - public void getByNameWithVersions(@FromDataPoints("data-responses") - ResponseEntity> expectedResponse) { + public void getByNameWithVersions( + @FromDataPoints("data-responses") ResponseEntity> expectedResponse) { verifyGetByNameWithVersions(expectedResponse); } -} \ No newline at end of file + +} diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubTemplateDetailSshUnitTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubTemplateDetailSshUnitTests.java index 34232e8..43d59b1 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubTemplateDetailSshUnitTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubTemplateDetailSshUnitTests.java @@ -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, @@ -39,7 +39,9 @@ import org.springframework.http.ResponseEntity; @RunWith(Theories.class) public class CredHubTemplateDetailSshUnitTests extends CredHubTemplateDetailUnitTestsBase { + private static final SshCredential CREDENTIAL = new SshCredential("public-key", "private-key"); + private static final SshParameters PARAMETERS = new SshParameters(KeyLength.LENGTH_2048, "comment"); @DataPoints("detail-responses") @@ -54,18 +56,12 @@ public class CredHubTemplateDetailSshUnitTests @Override public CredentialRequest getWriteRequest() { - return SshCredentialRequest.builder() - .name(NAME) - .value(CREDENTIAL) - .build(); + return SshCredentialRequest.builder().name(NAME).value(CREDENTIAL).build(); } @Override public ParametersRequest getGenerateRequest() { - return SshParametersRequest.builder() - .name(NAME) - .parameters(PARAMETERS) - .build(); + return SshParametersRequest.builder().name(NAME).parameters(PARAMETERS).build(); } @Override @@ -74,44 +70,45 @@ public class CredHubTemplateDetailSshUnitTests } @Theory - public void write(@FromDataPoints("detail-responses") - ResponseEntity> expectedResponse) { + public void write( + @FromDataPoints("detail-responses") ResponseEntity> expectedResponse) { verifyWrite(expectedResponse); } @Theory - public void generate(@FromDataPoints("detail-responses") - ResponseEntity> expectedResponse) { + public void generate( + @FromDataPoints("detail-responses") ResponseEntity> expectedResponse) { verifyGenerate(expectedResponse); } @Theory - public void regenerate(@FromDataPoints("detail-responses") - ResponseEntity> expectedResponse) { + public void regenerate( + @FromDataPoints("detail-responses") ResponseEntity> expectedResponse) { verifyRegenerate(expectedResponse); } @Theory - public void getById(@FromDataPoints("detail-responses") - ResponseEntity> expectedResponse) { + public void getById( + @FromDataPoints("detail-responses") ResponseEntity> expectedResponse) { verifyGetById(expectedResponse); } @Theory - public void getByName(@FromDataPoints("data-responses") - ResponseEntity> expectedResponse) { + public void getByName( + @FromDataPoints("data-responses") ResponseEntity> expectedResponse) { verifyGetByName(expectedResponse); } @Theory - public void getByNameWithHistory(@FromDataPoints("data-responses") - ResponseEntity> expectedResponse) { + public void getByNameWithHistory( + @FromDataPoints("data-responses") ResponseEntity> expectedResponse) { verifyGetByNameWithHistory(expectedResponse); } @Theory - public void getByNameWithVersions(@FromDataPoints("data-responses") - ResponseEntity> expectedResponse) { + public void getByNameWithVersions( + @FromDataPoints("data-responses") ResponseEntity> expectedResponse) { verifyGetByNameWithVersions(expectedResponse); } -} \ No newline at end of file + +} diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubTemplateDetailUnitTestsBase.java b/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubTemplateDetailUnitTestsBase.java index d44b45d..ab05b05 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubTemplateDetailUnitTestsBase.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubTemplateDetailUnitTestsBase.java @@ -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, @@ -29,6 +29,7 @@ import org.springframework.credhub.support.CredentialRequest; import org.springframework.credhub.support.CredentialType; import org.springframework.credhub.support.ParametersRequest; import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -37,25 +38,15 @@ import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.ArgumentMatchers.isNull; -import static org.mockito.Mockito.when; -import static org.springframework.credhub.core.credential.CredHubCredentialTemplate.BASE_URL_PATH; -import static org.springframework.credhub.core.credential.CredHubCredentialTemplate.ID_URL_PATH; -import static org.springframework.credhub.core.credential.CredHubCredentialTemplate.NAME_REQUEST_FIELD; -import static org.springframework.credhub.core.credential.CredHubCredentialTemplate.NAME_URL_QUERY; -import static org.springframework.credhub.core.credential.CredHubCredentialTemplate.NAME_URL_QUERY_CURRENT; -import static org.springframework.credhub.core.credential.CredHubCredentialTemplate.NAME_URL_QUERY_VERSIONS; -import static org.springframework.credhub.core.credential.CredHubCredentialTemplate.REGENERATE_URL_PATH; -import static org.springframework.http.HttpMethod.GET; -import static org.springframework.http.HttpMethod.POST; -import static org.springframework.http.HttpMethod.PUT; -import static org.springframework.http.HttpStatus.OK; -import static org.springframework.http.HttpStatus.UNAUTHORIZED; +import static org.mockito.BDDMockito.given; @SuppressWarnings("unchecked") public abstract class CredHubTemplateDetailUnitTestsBase extends CredHubCredentialTemplateUnitTestsBase { + private static final String CREDENTIAL_ID = "1111-1111-1111-1111"; protected abstract Class getType(); + protected abstract CredentialRequest getWriteRequest(); protected ParametersRequest

getGenerateRequest() { @@ -63,46 +54,34 @@ public abstract class CredHubTemplateDetailUnitTestsBase extends CredHubCr } static List>> buildDetailResponses(CredentialType type, T credential) { - return Arrays.asList( - ResponseEntity - .ok() - .body(new CredentialDetails<>(CREDENTIAL_ID, NAME, type, credential)), - ResponseEntity - .status(UNAUTHORIZED) - .body(new CredentialDetails<>()) - ); + return Arrays.asList(ResponseEntity.ok().body(new CredentialDetails<>(CREDENTIAL_ID, NAME, type, credential)), + ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(new CredentialDetails<>())); } static List>> buildDataResponses(CredentialType type, T credential) { return Arrays.asList( - ResponseEntity - .ok() - .body(new CredentialDetailsData<>( - new CredentialDetails<>(CREDENTIAL_ID, NAME, type, credential))), - ResponseEntity - .status(UNAUTHORIZED) - .body(new CredentialDetailsData<>()) - ); + ResponseEntity.ok().body( + new CredentialDetailsData<>(new CredentialDetails<>(CREDENTIAL_ID, NAME, type, credential))), + ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(new CredentialDetailsData<>())); } void verifyWrite(ResponseEntity> expectedResponse) { CredentialRequest request = getWriteRequest(); - when(restTemplate.exchange(eq(BASE_URL_PATH), eq(PUT), - eq(new HttpEntity<>(request)), isA(ParameterizedTypeReference.class))) - .thenReturn(expectedResponse); + given(this.restTemplate.exchange(eq(CredHubCredentialTemplate.BASE_URL_PATH), eq(HttpMethod.PUT), + eq(new HttpEntity<>(request)), isA(ParameterizedTypeReference.class))).willReturn(expectedResponse); if (!expectedResponse.getStatusCode().equals(HttpStatus.OK)) { try { - credHubTemplate.write(request); + this.credHubTemplate.write(request); fail("Exception should have been thrown"); } - catch (CredHubException e) { - assertThat(e.getMessage()).contains(expectedResponse.getStatusCode().toString()); + catch (CredHubException ex) { + assertThat(ex.getMessage()).contains(expectedResponse.getStatusCode().toString()); } } else { - CredentialDetails response = credHubTemplate.write(request); + CredentialDetails response = this.credHubTemplate.write(request); assertDetailsResponseContainsExpectedCredential(expectedResponse, response); } @@ -111,46 +90,46 @@ public abstract class CredHubTemplateDetailUnitTestsBase extends CredHubCr void verifyGenerate(ResponseEntity> expectedResponse) { ParametersRequest

request = getGenerateRequest(); - when(restTemplate.exchange(eq(BASE_URL_PATH), eq(POST), - eq(new HttpEntity<>(request)), isA(ParameterizedTypeReference.class))) - .thenReturn(expectedResponse); + given(this.restTemplate.exchange(eq(CredHubCredentialTemplate.BASE_URL_PATH), eq(HttpMethod.POST), + eq(new HttpEntity<>(request)), isA(ParameterizedTypeReference.class))).willReturn(expectedResponse); if (!expectedResponse.getStatusCode().equals(HttpStatus.OK)) { try { - credHubTemplate.generate(request); + this.credHubTemplate.generate(request); fail("Exception should have been thrown"); } - catch (CredHubException e) { - assertThat(e.getMessage()).contains(expectedResponse.getStatusCode().toString()); + catch (CredHubException ex) { + assertThat(ex.getMessage()).contains(expectedResponse.getStatusCode().toString()); } } else { - CredentialDetails response = credHubTemplate.generate(request); + CredentialDetails response = this.credHubTemplate.generate(request); assertDetailsResponseContainsExpectedCredential(expectedResponse, response); } } void verifyRegenerate(ResponseEntity> expectedResponse) { - Map request = new HashMap() {{ - put(NAME_REQUEST_FIELD, NAME.getName()); - }}; + Map request = new HashMap() { + { + put(CredHubCredentialTemplate.NAME_REQUEST_FIELD, NAME.getName()); + } + }; - when(restTemplate.exchange(eq(REGENERATE_URL_PATH), eq(POST), - eq(new HttpEntity<>(request)), isA(ParameterizedTypeReference.class))) - .thenReturn(expectedResponse); + given(this.restTemplate.exchange(eq(CredHubCredentialTemplate.REGENERATE_URL_PATH), eq(HttpMethod.POST), + eq(new HttpEntity<>(request)), isA(ParameterizedTypeReference.class))).willReturn(expectedResponse); if (!expectedResponse.getStatusCode().equals(HttpStatus.OK)) { try { - credHubTemplate.regenerate(NAME, getType()); + this.credHubTemplate.regenerate(NAME, getType()); fail("Exception should have been thrown"); } - catch (CredHubException e) { - assertThat(e.getMessage()).contains(expectedResponse.getStatusCode().toString()); + catch (CredHubException ex) { + assertThat(ex.getMessage()).contains(expectedResponse.getStatusCode().toString()); } } else { - CredentialDetails response = credHubTemplate.regenerate(NAME, getType()); + CredentialDetails response = this.credHubTemplate.regenerate(NAME, getType()); assertDetailsResponseContainsExpectedCredential(expectedResponse, response); } @@ -158,22 +137,21 @@ public abstract class CredHubTemplateDetailUnitTestsBase extends CredHubCr @SuppressWarnings("deprecation") void verifyGetById(ResponseEntity> expectedResponse) { - when(restTemplate.exchange(eq(ID_URL_PATH), eq(GET), isNull(HttpEntity.class), - isA(ParameterizedTypeReference.class), eq(CREDENTIAL_ID))) - .thenReturn(expectedResponse); + given(this.restTemplate.exchange(eq(CredHubCredentialTemplate.ID_URL_PATH), eq(HttpMethod.GET), + isNull(HttpEntity.class), isA(ParameterizedTypeReference.class), eq(CREDENTIAL_ID))) + .willReturn(expectedResponse); if (!expectedResponse.getStatusCode().equals(HttpStatus.OK)) { try { - credHubTemplate.getById(CREDENTIAL_ID, String.class); + this.credHubTemplate.getById(CREDENTIAL_ID, String.class); fail("Exception should have been thrown"); } - catch (CredHubException e) { - assertThat(e.getMessage()).contains(expectedResponse.getStatusCode().toString()); + catch (CredHubException ex) { + assertThat(ex.getMessage()).contains(expectedResponse.getStatusCode().toString()); } } else { - CredentialDetails response = - credHubTemplate.getById(CREDENTIAL_ID, getType()); + CredentialDetails response = this.credHubTemplate.getById(CREDENTIAL_ID, getType()); assertDetailsResponseContainsExpectedCredential(expectedResponse, response); } @@ -181,21 +159,21 @@ public abstract class CredHubTemplateDetailUnitTestsBase extends CredHubCr @SuppressWarnings("deprecation") void verifyGetByName(ResponseEntity> expectedResponse) { - when(restTemplate.exchange(eq(NAME_URL_QUERY_CURRENT), eq(GET), isNull(HttpEntity.class), - isA(ParameterizedTypeReference.class), eq(NAME.getName()))) - .thenReturn(expectedResponse); + given(this.restTemplate.exchange(eq(CredHubCredentialTemplate.NAME_URL_QUERY_CURRENT), eq(HttpMethod.GET), + isNull(HttpEntity.class), isA(ParameterizedTypeReference.class), eq(NAME.getName()))) + .willReturn(expectedResponse); - if (!expectedResponse.getStatusCode().equals(OK)) { + if (!expectedResponse.getStatusCode().equals(HttpStatus.OK)) { try { - credHubTemplate.getByName(NAME, String.class); + this.credHubTemplate.getByName(NAME, String.class); fail("Exception should have been thrown"); } - catch (CredHubException e) { - assertThat(e.getMessage()).contains(expectedResponse.getStatusCode().toString()); + catch (CredHubException ex) { + assertThat(ex.getMessage()).contains(expectedResponse.getStatusCode().toString()); } } else { - CredentialDetails response = credHubTemplate.getByName(NAME, getType()); + CredentialDetails response = this.credHubTemplate.getByName(NAME, getType()); assertDataResponseContainsExpectedCredential(expectedResponse, response); } @@ -203,21 +181,21 @@ public abstract class CredHubTemplateDetailUnitTestsBase extends CredHubCr @SuppressWarnings("deprecation") void verifyGetByNameWithHistory(ResponseEntity> expectedResponse) { - when(restTemplate.exchange(eq(NAME_URL_QUERY), eq(GET), isNull(HttpEntity.class), - isA(ParameterizedTypeReference.class), eq(NAME.getName()))) - .thenReturn(expectedResponse); + given(this.restTemplate.exchange(eq(CredHubCredentialTemplate.NAME_URL_QUERY), eq(HttpMethod.GET), + isNull(HttpEntity.class), isA(ParameterizedTypeReference.class), eq(NAME.getName()))) + .willReturn(expectedResponse); - if (!expectedResponse.getStatusCode().equals(OK)) { + if (!expectedResponse.getStatusCode().equals(HttpStatus.OK)) { try { - credHubTemplate.getByNameWithHistory(NAME, String.class); + this.credHubTemplate.getByNameWithHistory(NAME, String.class); fail("Exception should have been thrown"); } - catch (CredHubException e) { - assertThat(e.getMessage()).contains(expectedResponse.getStatusCode().toString()); + catch (CredHubException ex) { + assertThat(ex.getMessage()).contains(expectedResponse.getStatusCode().toString()); } } else { - List> response = credHubTemplate.getByNameWithHistory(NAME, getType()); + List> response = this.credHubTemplate.getByNameWithHistory(NAME, getType()); assertDataResponseContainsExpectedCredentials(expectedResponse, response); } @@ -225,45 +203,43 @@ public abstract class CredHubTemplateDetailUnitTestsBase extends CredHubCr @SuppressWarnings("deprecation") void verifyGetByNameWithVersions(ResponseEntity> expectedResponse) { - when(restTemplate.exchange(eq(NAME_URL_QUERY_VERSIONS), eq(GET), isNull(HttpEntity.class), - isA(ParameterizedTypeReference.class), eq(NAME.getName()), eq(5))) - .thenReturn(expectedResponse); + given(this.restTemplate.exchange(eq(CredHubCredentialTemplate.NAME_URL_QUERY_VERSIONS), eq(HttpMethod.GET), + isNull(HttpEntity.class), isA(ParameterizedTypeReference.class), eq(NAME.getName()), eq(5))) + .willReturn(expectedResponse); - if (!expectedResponse.getStatusCode().equals(OK)) { + if (!expectedResponse.getStatusCode().equals(HttpStatus.OK)) { try { - credHubTemplate.getByNameWithHistory(NAME, 5, String.class); + this.credHubTemplate.getByNameWithHistory(NAME, 5, String.class); fail("Exception should have been thrown"); } - catch (CredHubException e) { - assertThat(e.getMessage()).contains(expectedResponse.getStatusCode().toString()); + catch (CredHubException ex) { + assertThat(ex.getMessage()).contains(expectedResponse.getStatusCode().toString()); } } else { - List> response = credHubTemplate.getByNameWithHistory(NAME, 5, getType()); + List> response = this.credHubTemplate.getByNameWithHistory(NAME, 5, getType()); assertDataResponseContainsExpectedCredentials(expectedResponse, response); } } private void assertDataResponseContainsExpectedCredentials( - ResponseEntity> expectedResponse, - List> response) { + ResponseEntity> expectedResponse, List> response) { assertThat(response).isNotNull(); assertThat(response).hasSize(expectedResponse.getBody().getData().size()); assertThat(response).contains(expectedResponse.getBody().getData().get(0)); } - private void assertDataResponseContainsExpectedCredential( - ResponseEntity> expectedResponse, + private void assertDataResponseContainsExpectedCredential(ResponseEntity> expectedResponse, CredentialDetails response) { assertThat(response).isNotNull(); assertThat(response).isEqualTo(expectedResponse.getBody().getData().get(0)); } - private void assertDetailsResponseContainsExpectedCredential( - ResponseEntity> expectedResponse, + private void assertDetailsResponseContainsExpectedCredential(ResponseEntity> expectedResponse, CredentialDetails response) { assertThat(response).isNotNull(); assertThat(response).isEqualTo(expectedResponse.getBody()); } -} \ No newline at end of file + +} diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubTemplateDetailUserUnitTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubTemplateDetailUserUnitTests.java index ec36183..65bb42f 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubTemplateDetailUserUnitTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubTemplateDetailUserUnitTests.java @@ -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, @@ -33,8 +33,8 @@ import org.springframework.credhub.support.user.UserCredentialRequest; import org.springframework.http.ResponseEntity; @RunWith(Theories.class) -public class CredHubTemplateDetailUserUnitTests - extends CredHubTemplateDetailUnitTestsBase { +public class CredHubTemplateDetailUserUnitTests extends CredHubTemplateDetailUnitTestsBase { + private static final UserCredential CREDENTIAL = new UserCredential("myname", "secret"); @DataPoints("detail-responses") @@ -49,10 +49,7 @@ public class CredHubTemplateDetailUserUnitTests @Override public CredentialRequest getWriteRequest() { - return UserCredentialRequest.builder() - .name(NAME) - .value(CREDENTIAL) - .build(); + return UserCredentialRequest.builder().name(NAME).value(CREDENTIAL).build(); } @Override @@ -61,32 +58,33 @@ public class CredHubTemplateDetailUserUnitTests } @Theory - public void write(@FromDataPoints("detail-responses") - ResponseEntity> expectedResponse) { + public void write( + @FromDataPoints("detail-responses") ResponseEntity> expectedResponse) { verifyWrite(expectedResponse); } @Theory - public void getById(@FromDataPoints("detail-responses") - ResponseEntity> expectedResponse) { + public void getById( + @FromDataPoints("detail-responses") ResponseEntity> expectedResponse) { verifyGetById(expectedResponse); } @Theory - public void getByName(@FromDataPoints("data-responses") - ResponseEntity> expectedResponse) { + public void getByName( + @FromDataPoints("data-responses") ResponseEntity> expectedResponse) { verifyGetByName(expectedResponse); } @Theory - public void getByNameWithHistory(@FromDataPoints("data-responses") - ResponseEntity> expectedResponse) { + public void getByNameWithHistory( + @FromDataPoints("data-responses") ResponseEntity> expectedResponse) { verifyGetByNameWithHistory(expectedResponse); } @Theory - public void getByNameWithVersions(@FromDataPoints("data-responses") - ResponseEntity> expectedResponse) { + public void getByNameWithVersions( + @FromDataPoints("data-responses") ResponseEntity> expectedResponse) { verifyGetByNameWithVersions(expectedResponse); } -} \ No newline at end of file + +} diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubTemplateDetailValueUnitTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubTemplateDetailValueUnitTests.java index e111905..5d839e4 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubTemplateDetailValueUnitTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/core/credential/CredHubTemplateDetailValueUnitTests.java @@ -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, @@ -33,10 +33,9 @@ import org.springframework.credhub.support.value.ValueCredentialRequest; import org.springframework.http.ResponseEntity; @RunWith(Theories.class) -public class CredHubTemplateDetailValueUnitTests - extends CredHubTemplateDetailUnitTestsBase { - private static final ValueCredential CREDENTIAL = new ValueCredential("secret"); +public class CredHubTemplateDetailValueUnitTests extends CredHubTemplateDetailUnitTestsBase { + private static final ValueCredential CREDENTIAL = new ValueCredential("secret"); @DataPoints("detail-responses") public static List>> buildDetailResponses() { @@ -50,10 +49,7 @@ public class CredHubTemplateDetailValueUnitTests @Override public CredentialRequest getWriteRequest() { - return ValueCredentialRequest.builder() - .name(NAME) - .value(CREDENTIAL) - .build(); + return ValueCredentialRequest.builder().name(NAME).value(CREDENTIAL).build(); } @Override @@ -62,32 +58,33 @@ public class CredHubTemplateDetailValueUnitTests } @Theory - public void write(@FromDataPoints("detail-responses") - ResponseEntity> expectedResponse) { + public void write( + @FromDataPoints("detail-responses") ResponseEntity> expectedResponse) { verifyWrite(expectedResponse); } @Theory - public void getById(@FromDataPoints("detail-responses") - ResponseEntity> expectedResponse) { + public void getById( + @FromDataPoints("detail-responses") ResponseEntity> expectedResponse) { verifyGetById(expectedResponse); } @Theory - public void getByName(@FromDataPoints("data-responses") - ResponseEntity> expectedResponse) { + public void getByName( + @FromDataPoints("data-responses") ResponseEntity> expectedResponse) { verifyGetByName(expectedResponse); } @Theory - public void getByNameWithHistory(@FromDataPoints("data-responses") - ResponseEntity> expectedResponse) { + public void getByNameWithHistory( + @FromDataPoints("data-responses") ResponseEntity> expectedResponse) { verifyGetByNameWithHistory(expectedResponse); } @Theory - public void getByNameWithVersions(@FromDataPoints("data-responses") - ResponseEntity> expectedResponse) { + public void getByNameWithVersions( + @FromDataPoints("data-responses") ResponseEntity> expectedResponse) { verifyGetByNameWithVersions(expectedResponse); } -} \ No newline at end of file + +} diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/core/info/CredHubInfoTemplateUnitTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/core/info/CredHubInfoTemplateUnitTests.java index ac7c8a7..a8e0b66 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/core/info/CredHubInfoTemplateUnitTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/core/info/CredHubInfoTemplateUnitTests.java @@ -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,18 +25,19 @@ import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.MockitoRule; import org.mockito.quality.Strictness; + import org.springframework.credhub.core.CredHubTemplate; import org.springframework.credhub.support.info.VersionInfo; +import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; -import static org.springframework.credhub.core.info.CredHubInfoTemplate.VERSION_URL_PATH; -import static org.springframework.http.HttpStatus.OK; +import static org.mockito.BDDMockito.given; @RunWith(MockitoJUnitRunner.class) public class CredHubInfoTemplateUnitTests { + @Rule public MockitoRule mockitoRule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS); @@ -47,17 +48,17 @@ public class CredHubInfoTemplateUnitTests { @Before public void setUp() { - credHubTemplate = new CredHubTemplate(restTemplate).info(); + this.credHubTemplate = new CredHubTemplate(this.restTemplate).info(); } @Test public void getVersion() { - when(restTemplate.getForEntity(VERSION_URL_PATH, VersionInfo.class)) - .thenReturn(new ResponseEntity<>(new VersionInfo("2.0.0"), OK)); + given(this.restTemplate.getForEntity(CredHubInfoTemplate.VERSION_URL_PATH, VersionInfo.class)) + .willReturn(new ResponseEntity<>(new VersionInfo("2.0.0"), HttpStatus.OK)); - VersionInfo response = credHubTemplate.version(); + VersionInfo response = this.credHubTemplate.version(); assertThat(response.getVersion()).isEqualTo("2.0.0"); } -} \ No newline at end of file +} diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/core/interpolation/CredHubInterpolationTemplateUnitTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/core/interpolation/CredHubInterpolationTemplateUnitTests.java index 56b7e2b..b1000a2 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/core/interpolation/CredHubInterpolationTemplateUnitTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/core/interpolation/CredHubInterpolationTemplateUnitTests.java @@ -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.interpolation; +import java.io.IOException; + import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Before; import org.junit.Rule; @@ -26,24 +28,23 @@ import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.MockitoRule; import org.mockito.quality.Strictness; + import org.springframework.credhub.core.CredHubTemplate; import org.springframework.credhub.support.ServiceInstanceCredentialName; import org.springframework.credhub.support.ServicesData; import org.springframework.credhub.support.utils.JsonUtils; import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; -import java.io.IOException; - import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; -import static org.springframework.credhub.core.interpolation.CredHubInterpolationTemplate.INTERPOLATE_URL_PATH; -import static org.springframework.http.HttpMethod.POST; -import static org.springframework.http.HttpStatus.OK; +import static org.mockito.BDDMockito.given; @RunWith(MockitoJUnitRunner.class) public class CredHubInterpolationTemplateUnitTests { + @Rule public MockitoRule mockitoRule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS); @@ -54,32 +55,30 @@ public class CredHubInterpolationTemplateUnitTests { @Before public void setUp() { - credHubTemplate = new CredHubTemplate(restTemplate).interpolation(); + this.credHubTemplate = new CredHubTemplate(this.restTemplate).interpolation(); } @Test public void interpolateServiceData() throws IOException { ServiceInstanceCredentialName credentialName = ServiceInstanceCredentialName.builder() - .serviceBrokerName("service-broker") - .serviceOfferingName("service-offering") - .serviceBindingId("1111-1111-1111-111") - .credentialName("credential_json") - .build(); + .serviceBrokerName("service-broker").serviceOfferingName("service-offering") + .serviceBindingId("1111-1111-1111-111").credentialName("credential_json").build(); ServicesData vcapServices = buildVcapServices(credentialName.getName()); ServicesData expectedResponse = new ServicesData(); - when(restTemplate.exchange(INTERPOLATE_URL_PATH, POST, + given(this.restTemplate.exchange(CredHubInterpolationTemplate.INTERPOLATE_URL_PATH, HttpMethod.POST, new HttpEntity<>(vcapServices), ServicesData.class)) - .thenReturn(new ResponseEntity<>(expectedResponse, OK)); + .willReturn(new ResponseEntity<>(expectedResponse, HttpStatus.OK)); - ServicesData response = credHubTemplate.interpolateServiceData(vcapServices); + ServicesData response = this.credHubTemplate.interpolateServiceData(vcapServices); assertThat(response).isEqualTo(expectedResponse); } private ServicesData buildVcapServices(String credHubReferenceName) throws IOException { + // @formatter:off String vcapServices = "{" + " \"service-offering\": [" + " {" + @@ -96,9 +95,10 @@ public class CredHubInterpolationTemplateUnitTests { " }" + " ]" + "}"; + // @formatter:on ObjectMapper mapper = JsonUtils.buildObjectMapper(); return mapper.readValue(vcapServices, ServicesData.class); } -} \ No newline at end of file +} diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/core/permission/CredHubPermissionTemplateUnitTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/core/permission/CredHubPermissionTemplateUnitTests.java index fc2ad49..e79c8ba 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/core/permission/CredHubPermissionTemplateUnitTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/core/permission/CredHubPermissionTemplateUnitTests.java @@ -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,35 +16,34 @@ package org.springframework.credhub.core.permission; +import java.util.List; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; + import org.springframework.credhub.core.CredHubTemplate; import org.springframework.credhub.support.CredentialPermissions; import org.springframework.credhub.support.SimpleCredentialName; import org.springframework.credhub.support.permissions.Actor; import org.springframework.credhub.support.permissions.ActorType; -import org.springframework.credhub.support.permissions.Permission; import org.springframework.credhub.support.permissions.Operation; +import org.springframework.credhub.support.permissions.Permission; import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; -import java.util.List; - import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static org.springframework.credhub.core.permission.CredHubPermissionTemplate.PERMISSIONS_ACTOR_URL_QUERY; -import static org.springframework.credhub.core.permission.CredHubPermissionTemplate.PERMISSIONS_URL_PATH; -import static org.springframework.credhub.core.permission.CredHubPermissionTemplate.PERMISSIONS_URL_QUERY; -import static org.springframework.http.HttpMethod.POST; -import static org.springframework.http.HttpStatus.OK; @RunWith(MockitoJUnitRunner.class) public class CredHubPermissionTemplateUnitTests { + private static final SimpleCredentialName NAME = new SimpleCredentialName("example", "credential"); @Mock @@ -54,30 +53,21 @@ public class CredHubPermissionTemplateUnitTests { @Before public void setUp() { - credHubTemplate = new CredHubTemplate(restTemplate).permissions(); + this.credHubTemplate = new CredHubTemplate(this.restTemplate).permissions(); } @Test public void getPermissions() { - CredentialPermissions expectedResponse = new CredentialPermissions( - NAME, - Permission.builder() - .app("app-id") - .operation(Operation.READ) - .operation(Operation.WRITE) - .build(), - Permission.builder() - .user("zone1", "user-id") - .operations(Operation.READ_ACL) - .operations(Operation.WRITE_ACL) - .operation(Operation.DELETE) - .build() - ); + CredentialPermissions expectedResponse = new CredentialPermissions(NAME, + Permission.builder().app("app-id").operation(Operation.READ).operation(Operation.WRITE).build(), + Permission.builder().user("zone1", "user-id").operations(Operation.READ_ACL) + .operations(Operation.WRITE_ACL).operation(Operation.DELETE).build()); - when(restTemplate.getForEntity(PERMISSIONS_URL_QUERY, CredentialPermissions.class, NAME.getName())) - .thenReturn(new ResponseEntity<>(expectedResponse, OK)); + given(this.restTemplate.getForEntity(CredHubPermissionTemplate.PERMISSIONS_URL_QUERY, + CredentialPermissions.class, NAME.getName())) + .willReturn(new ResponseEntity<>(expectedResponse, HttpStatus.OK)); - List response = credHubTemplate.getPermissions(NAME); + List response = this.credHubTemplate.getPermissions(NAME); assertThat(response).isNotNull(); assertThat(response).hasSize(expectedResponse.getPermissions().size()); @@ -86,30 +76,25 @@ public class CredHubPermissionTemplateUnitTests { @Test public void addPermissions() { - Permission permission1 = Permission.builder() - .app("app-id") - .operation(Operation.READ) - .operation(Operation.WRITE) - .build(); - - Permission permission2 = Permission.builder() - .user("zone1", "user-id") - .operations(Operation.READ_ACL) - .operations(Operation.WRITE_ACL) - .operation(Operation.DELETE) + Permission permission1 = Permission.builder().app("app-id").operation(Operation.READ).operation(Operation.WRITE) .build(); - credHubTemplate.addPermissions(NAME, permission1, permission2); + Permission permission2 = Permission.builder().user("zone1", "user-id").operations(Operation.READ_ACL) + .operations(Operation.WRITE_ACL).operation(Operation.DELETE).build(); - verify(restTemplate).exchange(PERMISSIONS_URL_PATH, POST, + this.credHubTemplate.addPermissions(NAME, permission1, permission2); + + verify(this.restTemplate).exchange(CredHubPermissionTemplate.PERMISSIONS_URL_PATH, HttpMethod.POST, new HttpEntity<>(new CredentialPermissions(NAME, permission1, permission2)), CredentialPermissions.class); } @Test public void deletePermission() { - credHubTemplate.deletePermission(NAME, Actor.app("appid1")); + this.credHubTemplate.deletePermission(NAME, Actor.app("appid1")); - verify(restTemplate).delete(PERMISSIONS_ACTOR_URL_QUERY, NAME.getName(), ActorType.APP + ":appid1"); + verify(this.restTemplate).delete(CredHubPermissionTemplate.PERMISSIONS_ACTOR_URL_QUERY, NAME.getName(), + ActorType.APP + ":appid1"); } -} \ No newline at end of file + +} diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/core/permissionV2/CredHubPermissionV2TemplateUnitTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/core/permissionV2/CredHubPermissionV2TemplateUnitTests.java index 9387d75..1e62944 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/core/permissionV2/CredHubPermissionV2TemplateUnitTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/core/permissionV2/CredHubPermissionV2TemplateUnitTests.java @@ -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,28 +26,23 @@ import org.springframework.credhub.core.CredHubTemplate; import org.springframework.credhub.support.CredentialPermission; import org.springframework.credhub.support.SimpleCredentialName; import org.springframework.credhub.support.permissions.Actor; +import org.springframework.credhub.support.permissions.ActorType; import org.springframework.credhub.support.permissions.Operation; import org.springframework.credhub.support.permissions.Permission; import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static org.springframework.credhub.core.permissionV2.CredHubPermissionV2Template.PERMISSIONS_PATH_ACTOR_URL_QUERY; -import static org.springframework.credhub.core.permissionV2.CredHubPermissionV2Template.PERMISSIONS_ID_URL_PATH; -import static org.springframework.credhub.core.permissionV2.CredHubPermissionV2Template.PERMISSIONS_URL_PATH; -import static org.springframework.credhub.support.permissions.ActorType.APP; -import static org.springframework.credhub.support.permissions.ActorType.OAUTH_CLIENT; -import static org.springframework.http.HttpMethod.POST; -import static org.springframework.http.HttpMethod.PUT; -import static org.springframework.http.HttpStatus.OK; @RunWith(MockitoJUnitRunner.class) public class CredHubPermissionV2TemplateUnitTests { - private static final SimpleCredentialName PATH = - new SimpleCredentialName("example", "credential", "*"); + + private static final SimpleCredentialName PATH = new SimpleCredentialName("example", "credential", "*"); @Mock private RestTemplate restTemplate; @@ -56,29 +51,25 @@ public class CredHubPermissionV2TemplateUnitTests { @Before public void setUp() { - credHubTemplate = new CredHubTemplate(restTemplate).permissionsV2(); + this.credHubTemplate = new CredHubTemplate(this.restTemplate).permissionsV2(); } @Test public void getPermissions() { String permissionId = "uuid"; - CredentialPermission expectedResponse = new CredentialPermission( - PATH, - Permission.builder() - .app("app-id") - .operation(Operation.READ) - .operation(Operation.WRITE) - .build()); + CredentialPermission expectedResponse = new CredentialPermission(PATH, + Permission.builder().app("app-id").operation(Operation.READ).operation(Operation.WRITE).build()); - when(restTemplate.getForEntity(PERMISSIONS_ID_URL_PATH, CredentialPermission.class, permissionId)) - .thenReturn(new ResponseEntity<>(expectedResponse, OK)); + given(this.restTemplate.getForEntity(CredHubPermissionV2Template.PERMISSIONS_ID_URL_PATH, + CredentialPermission.class, permissionId)) + .willReturn(new ResponseEntity<>(expectedResponse, HttpStatus.OK)); - CredentialPermission response = credHubTemplate.getPermissions(permissionId); + CredentialPermission response = this.credHubTemplate.getPermissions(permissionId); assertThat(response).isNotNull(); assertThat(response.getPath()).isEqualTo(PATH.getName()); - assertThat(response.getPermission().getActor().getAuthType()).isEqualTo(APP); + assertThat(response.getPermission().getActor().getAuthType()).isEqualTo(ActorType.APP); assertThat(response.getPermission().getOperations()).contains(Operation.READ, Operation.WRITE); } @@ -86,46 +77,39 @@ public class CredHubPermissionV2TemplateUnitTests { public void getPermissionsByPathAndActor() { String clientId = "client-id"; - CredentialPermission expectedResponse = new CredentialPermission( - PATH, - Permission.builder() - .operation(Operation.READ) - .operation(Operation.WRITE) - .client(clientId) - .build()); + CredentialPermission expectedResponse = new CredentialPermission(PATH, + Permission.builder().operation(Operation.READ).operation(Operation.WRITE).client(clientId).build()); - String actor = OAUTH_CLIENT + ":" + clientId; - when(restTemplate.getForEntity(PERMISSIONS_PATH_ACTOR_URL_QUERY, CredentialPermission.class, PATH.getName(), actor)) - .thenReturn(new ResponseEntity<>(expectedResponse, OK)); + String actor = ActorType.OAUTH_CLIENT + ":" + clientId; + given(this.restTemplate.getForEntity(CredHubPermissionV2Template.PERMISSIONS_PATH_ACTOR_URL_QUERY, + CredentialPermission.class, PATH.getName(), actor)) + .willReturn(new ResponseEntity<>(expectedResponse, HttpStatus.OK)); - CredentialPermission response = credHubTemplate.getPermissionsByPathAndActor(PATH, Actor.client(clientId)); + CredentialPermission response = this.credHubTemplate.getPermissionsByPathAndActor(PATH, Actor.client(clientId)); assertThat(response).isNotNull(); assertThat(response.getPath()).isEqualTo(PATH.getName()); - assertThat(response.getPermission().getActor().getAuthType()).isEqualTo(OAUTH_CLIENT); + assertThat(response.getPermission().getActor().getAuthType()).isEqualTo(ActorType.OAUTH_CLIENT); assertThat(response.getPermission().getActor().getPrimaryIdentifier()).isEqualTo(clientId); assertThat(response.getPermission().getOperations()).contains(Operation.READ, Operation.WRITE); } @Test public void addPermissions() { - Permission permission = Permission.builder() - .app("app-id") - .operation(Operation.READ) - .operation(Operation.WRITE) + Permission permission = Permission.builder().app("app-id").operation(Operation.READ).operation(Operation.WRITE) .build(); CredentialPermission expectedResponse = new CredentialPermission(PATH, permission); - when(restTemplate.exchange(PERMISSIONS_URL_PATH, POST, new HttpEntity<>(expectedResponse), - CredentialPermission.class)) - .thenReturn(new ResponseEntity<>(expectedResponse, OK)); + given(this.restTemplate.exchange(CredHubPermissionV2Template.PERMISSIONS_URL_PATH, HttpMethod.POST, + new HttpEntity<>(expectedResponse), CredentialPermission.class)) + .willReturn(new ResponseEntity<>(expectedResponse, HttpStatus.OK)); - CredentialPermission response = credHubTemplate.addPermissions(PATH, permission); + CredentialPermission response = this.credHubTemplate.addPermissions(PATH, permission); assertThat(response).isNotNull(); assertThat(response.getPath()).isEqualTo(PATH.getName()); - assertThat(response.getPermission().getActor().getAuthType()).isEqualTo(APP); + assertThat(response.getPermission().getActor().getAuthType()).isEqualTo(ActorType.APP); assertThat(response.getPermission().getOperations()).contains(Operation.READ, Operation.WRITE); } @@ -133,30 +117,28 @@ public class CredHubPermissionV2TemplateUnitTests { public void updatePermissions() { String permissionId = "uuid"; - Permission permission = Permission.builder() - .app("app-id") - .operation(Operation.READ) - .operation(Operation.WRITE) + Permission permission = Permission.builder().app("app-id").operation(Operation.READ).operation(Operation.WRITE) .build(); CredentialPermission expectedResponse = new CredentialPermission(PATH, permission); - when(restTemplate.exchange(PERMISSIONS_ID_URL_PATH, PUT, new HttpEntity<>(expectedResponse), - CredentialPermission.class, permissionId)) - .thenReturn(new ResponseEntity<>(expectedResponse, OK)); + given(this.restTemplate.exchange(CredHubPermissionV2Template.PERMISSIONS_ID_URL_PATH, HttpMethod.PUT, + new HttpEntity<>(expectedResponse), CredentialPermission.class, permissionId)) + .willReturn(new ResponseEntity<>(expectedResponse, HttpStatus.OK)); - CredentialPermission response = credHubTemplate.updatePermissions(permissionId, PATH, permission); + CredentialPermission response = this.credHubTemplate.updatePermissions(permissionId, PATH, permission); assertThat(response).isNotNull(); assertThat(response.getPath()).isEqualTo(PATH.getName()); - assertThat(response.getPermission().getActor().getAuthType()).isEqualTo(APP); + assertThat(response.getPermission().getActor().getAuthType()).isEqualTo(ActorType.APP); assertThat(response.getPermission().getOperations()).contains(Operation.READ, Operation.WRITE); } @Test public void deletePermission() { - credHubTemplate.deletePermission("uuid"); + this.credHubTemplate.deletePermission("uuid"); - verify(restTemplate).delete(PERMISSIONS_ID_URL_PATH, "uuid"); + verify(this.restTemplate).delete(CredHubPermissionV2Template.PERMISSIONS_ID_URL_PATH, "uuid"); } + } diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/support/CertificateSummaryDataTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/support/CertificateSummaryDataTests.java index 77efe84..af3775d 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/support/CertificateSummaryDataTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/support/CertificateSummaryDataTests.java @@ -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,13 +17,16 @@ package org.springframework.credhub.support; import org.junit.Test; + import org.springframework.credhub.support.certificate.CertificateSummaryData; import static org.assertj.core.api.Assertions.assertThat; public class CertificateSummaryDataTests extends JsonParsingUnitTestsBase { + @Test public void deserializeWithCertificates() { + // @formatter:off String json = "{\n" + " \"certificates\": [\n" + " {\n" + @@ -36,24 +39,24 @@ public class CertificateSummaryDataTests extends JsonParsingUnitTestsBase { " }\n" + " ]\n" + "}"; + // @formatter:on CertificateSummaryData certificates = parseResponse(json, CertificateSummaryData.class); assertThat(certificates.getCertificates().size()).isEqualTo(2); - assertThat(certificates.getCertificates()).extracting("id") - .contains("2993f622-cb1e-4e00-a267-4b23c273bf3d", "b40d3d3b-2cf5-4a73-babd-9dceefa9b0db"); - assertThat(certificates.getCertificates()).extracting("name") - .contains("/example-certificate-1", "/example-certificate-2"); + assertThat(certificates.getCertificates()).extracting("id").contains("2993f622-cb1e-4e00-a267-4b23c273bf3d", + "b40d3d3b-2cf5-4a73-babd-9dceefa9b0db"); + assertThat(certificates.getCertificates()).extracting("name").contains("/example-certificate-1", + "/example-certificate-2"); } @Test public void deserializeWithNoCertificates() { - String json = "{\n" + - " \"certificates\": []\n" + - "}"; + String json = "{\n" + " \"certificates\": []\n" + "}"; CertificateSummaryData certificates = parseResponse(json, CertificateSummaryData.class); assertThat(certificates.getCertificates().size()).isEqualTo(0); } -} \ No newline at end of file + +} diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/support/CredHubRequestUnitTestsBase.java b/spring-credhub-core/src/test/java/org/springframework/credhub/support/CredHubRequestUnitTestsBase.java index 78f6756..8daed6c 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/support/CredHubRequestUnitTestsBase.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/support/CredHubRequestUnitTestsBase.java @@ -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,97 +21,75 @@ import org.junit.Test; import org.springframework.credhub.support.CredHubRequest.CredHubRequestBuilder; import org.springframework.credhub.support.permissions.Actor; +import org.springframework.credhub.support.permissions.Operation; import org.springframework.credhub.support.permissions.Permission; -import static org.springframework.credhub.support.JsonPathAssert.assertThat; - -import static org.springframework.credhub.support.permissions.Operation.READ; -import static org.springframework.credhub.support.permissions.Operation.READ_ACL; -import static org.springframework.credhub.support.permissions.Operation.WRITE; -import static org.springframework.credhub.support.permissions.Operation.WRITE_ACL; - public abstract class CredHubRequestUnitTestsBase { + protected CredHubRequestBuilder requestBuilder; @Test @SuppressWarnings("deprecation") public void serializationWithOnePermission() { - requestBuilder - .permission(Permission.builder() - .app("app-id") - .operation(READ) - .build()); + this.requestBuilder.permission(Permission.builder().app("app-id").operation(Operation.READ).build()); - DocumentContext json = JsonTestUtils.toJsonPath(requestBuilder.build()); + DocumentContext json = JsonTestUtils.toJsonPath(this.requestBuilder.build()); - assertThat(json).hasPath("$.additional_permissions[0].actor") + JsonPathAssert.assertThat(json).hasPath("$.additional_permissions[0].actor") .isEqualTo(Actor.app("app-id").getIdentity()); - assertThat(json).hasPath("$.additional_permissions[0].operations[0]") - .isEqualTo("read"); + JsonPathAssert.assertThat(json).hasPath("$.additional_permissions[0].operations[0]").isEqualTo("read"); } @Test - @SuppressWarnings({"deprecation"}) + @SuppressWarnings({ "deprecation" }) public void serializationWithThreePermissions() { - requestBuilder - .permission(Permission.builder() - .app("app-id") - .operation(READ).operation(WRITE) - .build()) - .permission(Permission.builder() - .user("zone1", "user-id") - .operations(READ_ACL, WRITE_ACL) - .build()) - .permission(Permission.builder() - .client("client-id") - .operations(READ, WRITE, READ_ACL, WRITE_ACL) - .build()); + this.requestBuilder + .permission( + Permission.builder().app("app-id").operation(Operation.READ).operation(Operation.WRITE).build()) + .permission(Permission.builder().user("zone1", "user-id") + .operations(Operation.READ_ACL, Operation.WRITE_ACL).build()) + .permission(Permission.builder().client("client-id") + .operations(Operation.READ, Operation.WRITE, Operation.READ_ACL, Operation.WRITE_ACL).build()); - DocumentContext json = JsonTestUtils.toJsonPath(requestBuilder.build()); + DocumentContext json = JsonTestUtils.toJsonPath(this.requestBuilder.build()); - assertThat(json).hasPath("$.additional_permissions[0].actor") + JsonPathAssert.assertThat(json).hasPath("$.additional_permissions[0].actor") .isEqualTo(Actor.app("app-id").getIdentity()); - assertThat(json).hasPath("$.additional_permissions[0].operations[0]") - .isEqualTo("read"); - assertThat(json).hasPath("$.additional_permissions[0].operations[1]") - .isEqualTo("write"); + JsonPathAssert.assertThat(json).hasPath("$.additional_permissions[0].operations[0]").isEqualTo("read"); + JsonPathAssert.assertThat(json).hasPath("$.additional_permissions[0].operations[1]").isEqualTo("write"); - assertThat(json).hasPath("$.additional_permissions[1].actor") + JsonPathAssert.assertThat(json).hasPath("$.additional_permissions[1].actor") .isEqualTo(Actor.user("zone1", "user-id").getIdentity()); - assertThat(json).hasPath("$.additional_permissions[1].operations[0]") - .isEqualTo("read_acl"); - assertThat(json).hasPath("$.additional_permissions[1].operations[1]") - .isEqualTo("write_acl"); + JsonPathAssert.assertThat(json).hasPath("$.additional_permissions[1].operations[0]").isEqualTo("read_acl"); + JsonPathAssert.assertThat(json).hasPath("$.additional_permissions[1].operations[1]").isEqualTo("write_acl"); - assertThat(json).hasPath("$.additional_permissions[2].actor") + JsonPathAssert.assertThat(json).hasPath("$.additional_permissions[2].actor") .isEqualTo(Actor.client("client-id").getIdentity()); - assertThat(json).hasPath("$.additional_permissions[2].operations[0]") - .isEqualTo("read"); - assertThat(json).hasPath("$.additional_permissions[2].operations[1]") - .isEqualTo("write"); - assertThat(json).hasPath("$.additional_permissions[2].operations[2]") - .isEqualTo("read_acl"); - assertThat(json).hasPath("$.additional_permissions[2].operations[3]") - .isEqualTo("write_acl"); + JsonPathAssert.assertThat(json).hasPath("$.additional_permissions[2].operations[0]").isEqualTo("read"); + JsonPathAssert.assertThat(json).hasPath("$.additional_permissions[2].operations[1]").isEqualTo("write"); + JsonPathAssert.assertThat(json).hasPath("$.additional_permissions[2].operations[2]").isEqualTo("read_acl"); + JsonPathAssert.assertThat(json).hasPath("$.additional_permissions[2].operations[3]").isEqualTo("write_acl"); } protected DocumentContext toJsonPath(CredHubRequestBuilder requestBuilder) { return JsonTestUtils.toJsonPath(requestBuilder.build()); } - protected void assertCommonRequestFields(DocumentContext json, Boolean overwrite, WriteMode writeMode, - String name, String type) { + protected void assertCommonRequestFields(DocumentContext json, Boolean overwrite, WriteMode writeMode, String name, + String type) { if (overwrite == null) { - assertThat(json).hasNoPath("$.overwrite"); - } else { - assertThat(json).hasPath("$.overwrite").isEqualTo(overwrite); + JsonPathAssert.assertThat(json).hasNoPath("$.overwrite"); } - assertThat(json).hasPath("$.mode").isEqualTo(writeMode.getMode()); - assertThat(json).hasPath("$.name").isEqualTo(name); - assertThat(json).hasPath("$.type").isEqualTo(type); + else { + JsonPathAssert.assertThat(json).hasPath("$.overwrite").isEqualTo(overwrite); + } + JsonPathAssert.assertThat(json).hasPath("$.mode").isEqualTo(writeMode.getMode()); + JsonPathAssert.assertThat(json).hasPath("$.name").isEqualTo(name); + JsonPathAssert.assertThat(json).hasPath("$.type").isEqualTo(type); } protected void assertNoPermissions(DocumentContext json) { - assertThat(json).hasNoPath("$.additional_permissions"); + JsonPathAssert.assertThat(json).hasNoPath("$.additional_permissions"); } + } diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/support/CredentialPathDataTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/support/CredentialPathDataTests.java index fb02d67..570c417 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/support/CredentialPathDataTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/support/CredentialPathDataTests.java @@ -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; import org.junit.Test; @@ -5,8 +21,10 @@ import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class CredentialPathDataTests extends JsonParsingUnitTestsBase { + @Test public void deserializeWithPaths() { + // @formatter:off String json = "{\n" + " \"paths\": [\n" + " {\n" + @@ -26,22 +44,22 @@ public class CredentialPathDataTests extends JsonParsingUnitTestsBase { " }\n" + " ]\n" + "}"; + // @formatter:on CredentialPathData paths = parseResponse(json, CredentialPathData.class); assertThat(paths.getPaths().size()).isEqualTo(5); - assertThat(paths.getPaths()).extracting("path") - .contains("/", "/director-name/", "/director-name/deploy1/", "/director-name/deploy2/", "/director2/"); + assertThat(paths.getPaths()).extracting("path").contains("/", "/director-name/", "/director-name/deploy1/", + "/director-name/deploy2/", "/director2/"); } @Test public void deserializeWithNoPaths() { - String json = "{\n" + - " \"paths\": []" + - "}"; + String json = "{\n" + " \"paths\": []" + "}"; CredentialPathData paths = parseResponse(json, CredentialPathData.class); assertThat(paths.getPaths().size()).isEqualTo(0); } -} \ No newline at end of file + +} diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/support/CredentialSummaryDataUnitTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/support/CredentialSummaryDataUnitTests.java index 7289b3d..700db9e 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/support/CredentialSummaryDataUnitTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/support/CredentialSummaryDataUnitTests.java @@ -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, @@ -23,8 +23,10 @@ import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class CredentialSummaryDataUnitTests extends JsonParsingUnitTestsBase { + @Test public void deserializationWithCredentials() { + // @formatter:off String json = "{\n" + " \"credentials\": [\n" + " {\n" + @@ -41,6 +43,7 @@ public class CredentialSummaryDataUnitTests extends JsonParsingUnitTestsBase { " }\n" + " ]\n" + "}"; + // @formatter:on CredentialSummaryData response = parseResponse(json, CredentialSummaryData.class); @@ -48,12 +51,9 @@ public class CredentialSummaryDataUnitTests extends JsonParsingUnitTestsBase { List credentials = response.getCredentials(); - assertThat(credentials.get(0).getName().getName()) - .isEqualTo("/deploy123/example1"); - assertThat(credentials.get(1).getName().getName()) - .isEqualTo("/deploy123/example2"); - assertThat(credentials.get(2).getName().getName()) - .isEqualTo("/deploy123/example3"); + assertThat(credentials.get(0).getName().getName()).isEqualTo("/deploy123/example1"); + assertThat(credentials.get(1).getName().getName()).isEqualTo("/deploy123/example2"); + assertThat(credentials.get(2).getName().getName()).isEqualTo("/deploy123/example3"); for (CredentialSummary credential : credentials) { assertThat(credential.getVersionCreatedAt()).isEqualTo(testDate); @@ -62,14 +62,12 @@ public class CredentialSummaryDataUnitTests extends JsonParsingUnitTestsBase { @Test public void deserializationWithEmptyCredentials() { - String json = "{\n" + - " \"credentials\": [\n" + - " ]\n" + - "}"; + String json = "{\n" + " \"credentials\": [\n" + " ]\n" + "}"; CredentialSummaryData response = parseResponse(json, CredentialSummaryData.class); assertThat(response.getCredentials()).isNotNull(); assertThat(response.getCredentials()).hasSize(0); } + } diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/support/JsonParsingUnitTestsBase.java b/spring-credhub-core/src/test/java/org/springframework/credhub/support/JsonParsingUnitTestsBase.java index 051936a..f8a71ee 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/support/JsonParsingUnitTestsBase.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/support/JsonParsingUnitTestsBase.java @@ -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,29 +24,34 @@ import org.junit.Before; import static org.assertj.core.api.Assertions.assertThat; public abstract class JsonParsingUnitTestsBase { + static final String TEST_DATE_STRING = "2017-01-31T11:22:33Z"; - private final String CREDENTIAL_DETAIL_TEMPLATE = "{" + + // @formatter:off + private static final String CREDENTIAL_DETAIL_TEMPLATE = "{" + " \"version_created_at\": \"" + TEST_DATE_STRING + "\"," + " \"id\": \"80cbb13f-7562-4e72-92de-f3ccf69eaa59\"," + " \"name\": \"/service-broker-name/service-instance-name/binding-id/credentials-json\"," + " %s" + "}"; + // @formatter:on - private final String CREDENTIAL_DETAILS_DATA_TEMPLATE = "{" + + // @formatter:off + private static final String CREDENTIAL_DETAILS_DATA_TEMPLATE = "{" + " \"data\": [" + CREDENTIAL_DETAIL_TEMPLATE + " ]" + "}"; + // @formatter:on Date testDate; @Before public void setUpJsonParsing() throws Exception { - testDate = new StdDateFormat().parse(TEST_DATE_STRING); + this.testDate = new StdDateFormat().parse(TEST_DATE_STRING); } - protected T parseResponse(String json, Class type) { + protected T parseResponse(String json, Class type) { return JsonTestUtils.fromJson(json, type); } @@ -71,9 +76,10 @@ public abstract class JsonParsingUnitTestsBase { } protected void assertCommonDetails(CredentialDetails data) { - assertThat(data.getVersionCreatedAt()).isEqualTo(testDate); + assertThat(data.getVersionCreatedAt()).isEqualTo(this.testDate); assertThat(data.getId()).isEqualTo("80cbb13f-7562-4e72-92de-f3ccf69eaa59"); - assertThat(data.getName().getName()).isEqualTo( - "/service-broker-name/service-instance-name/binding-id/credentials-json"); + assertThat(data.getName().getName()) + .isEqualTo("/service-broker-name/service-instance-name/binding-id/credentials-json"); } + } diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/support/JsonPathAssert.java b/spring-credhub-core/src/test/java/org/springframework/credhub/support/JsonPathAssert.java index 2809495..8cb947c 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/support/JsonPathAssert.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/support/JsonPathAssert.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-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. * 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.assertj.core.api.AbstractObjectAssert; import org.assertj.core.api.Assertions; public class JsonPathAssert extends AbstractAssert { + public JsonPathAssert(DocumentContext actual) { super(actual, JsonPathAssert.class); } @@ -34,20 +35,23 @@ public class JsonPathAssert extends AbstractAssert hasPath(String path) { try { - return Assertions.assertThat(actual.read(path, Object.class)); - } catch (PathNotFoundException e) { - failWithMessage("The JSON " + actual.jsonString() + " does not contain the path '" + path + "'"); + return Assertions.assertThat(this.actual.read(path, Object.class)); + } + catch (PathNotFoundException ex) { + failWithMessage("The JSON " + this.actual.jsonString() + " does not contain the path '" + path + "'"); return null; } } + } diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/support/JsonTestUtils.java b/spring-credhub-core/src/test/java/org/springframework/credhub/support/JsonTestUtils.java index fdb3a4c..cd6c3e2 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/support/JsonTestUtils.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/support/JsonTestUtils.java @@ -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.support; +import java.io.IOException; + import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.jayway.jsonpath.Configuration; @@ -23,13 +25,13 @@ import com.jayway.jsonpath.DocumentContext; import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.spi.json.JacksonJsonProvider; import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider; -import org.springframework.credhub.support.utils.JsonUtils; -import java.io.IOException; +import org.springframework.credhub.support.utils.JsonUtils; import static org.assertj.core.api.Assertions.fail; public final class JsonTestUtils { + private JsonTestUtils() { } @@ -37,9 +39,10 @@ public final class JsonTestUtils { try { ObjectMapper mapper = JsonUtils.buildObjectMapper(); return mapper.writeValueAsString(object); - } catch (JsonProcessingException e) { - fail("Error creating JSON string from object: " + e); - throw new IllegalStateException(e); + } + catch (JsonProcessingException ex) { + fail("Error creating JSON string from object: " + ex); + throw new IllegalStateException(ex); } } @@ -47,18 +50,18 @@ public final class JsonTestUtils { try { ObjectMapper mapper = JsonUtils.buildObjectMapper(); return mapper.readValue(json, type); - } catch (IOException e) { - fail("Error parsing JSON string to object: " + e); - throw new IllegalStateException(e); + } + catch (IOException ex) { + fail("Error parsing JSON string to object: " + ex); + throw new IllegalStateException(ex); } } public static DocumentContext toJsonPath(Object object) { - Configuration configuration = Configuration.builder() - .jsonProvider(new JacksonJsonProvider()) - .mappingProvider(new JacksonMappingProvider()) - .build(); + Configuration configuration = Configuration.builder().jsonProvider(new JacksonJsonProvider()) + .mappingProvider(new JacksonMappingProvider()).build(); return JsonPath.parse(toJson(object), configuration); } + } diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/support/ServiceInstanceCredentialNameUnitTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/support/ServiceInstanceCredentialNameUnitTests.java index a5d36a6..1204707 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/support/ServiceInstanceCredentialNameUnitTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/support/ServiceInstanceCredentialNameUnitTests.java @@ -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,11 +21,13 @@ import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class ServiceInstanceCredentialNameUnitTests { + @Test public void simpleNameIsConstructed() { - CredentialName credentialName = - new ServiceInstanceCredentialName("broker-name", "service-name", "binding-id", "credential-name"); + CredentialName credentialName = new ServiceInstanceCredentialName("broker-name", "service-name", "binding-id", + "credential-name"); assertThat(credentialName.getName()).isEqualTo("/c/broker-name/service-name/binding-id/credential-name"); } -} \ No newline at end of file + +} diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/support/SimpleCredentialNameUnitTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/support/SimpleCredentialNameUnitTests.java index e3a1b73..caf18d5 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/support/SimpleCredentialNameUnitTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/support/SimpleCredentialNameUnitTests.java @@ -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.support; @@ -23,13 +21,14 @@ import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class SimpleCredentialNameUnitTests { + @Test public void singleElementNameIsConstructed() { CredentialName credentialName = new SimpleCredentialName("credential-name"); assertThat(credentialName.getName()).isEqualTo("credential-name"); } - + @Test public void singleElementNameWithLeadingSlashIsParsed() { CredentialName credentialName = new CredentialName("/credential-name"); @@ -46,12 +45,11 @@ public class SimpleCredentialNameUnitTests { @Test public void simpleNameIsConstructed() { - CredentialName credentialName = - new SimpleCredentialName("myorg", "example", "credential-name"); + CredentialName credentialName = new SimpleCredentialName("myorg", "example", "credential-name"); assertThat(credentialName.getName()).isEqualTo("/myorg/example/credential-name"); } - + @Test public void simpleNameIsParsed() { CredentialName credentialName = new CredentialName("/myorg/example/credential-name"); @@ -65,4 +63,5 @@ public class SimpleCredentialNameUnitTests { assertThat(credentialName.getName()).isEqualTo("/myorg/example/credential-name"); } -} \ No newline at end of file + +} diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/support/certificate/CertificateCredentialDetailsUnitTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/support/certificate/CertificateCredentialDetailsUnitTests.java index e2de0d5..c6c75bb 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/support/certificate/CertificateCredentialDetailsUnitTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/support/certificate/CertificateCredentialDetailsUnitTests.java @@ -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,8 @@ import org.springframework.credhub.support.JsonParsingUnitTestsBase; import static org.assertj.core.api.Assertions.assertThat; public class CertificateCredentialDetailsUnitTests extends JsonParsingUnitTestsBase { + + // @formatter:off private static final String CERT_CREDENTIALS = " \"type\": \"certificate\"," + " \"value\": {" + @@ -33,6 +35,7 @@ public class CertificateCredentialDetailsUnitTests extends JsonParsingUnitTestsB " \"ca\": \"authority\"," + " \"private_key\": \"private-key\"" + " }"; + // @formatter:on @Test public void deserializeDetailsWithAllValues() { @@ -43,11 +46,13 @@ public class CertificateCredentialDetailsUnitTests extends JsonParsingUnitTestsB @Test public void deserializeDetailsCertOnly() { + // @formatter:off final String credentials = " \"type\": \"certificate\"," + " \"value\": {" + " \"certificate\": \"cert\"" + " }"; + // @formatter:on CredentialDetails data = parseDetails(credentials); assertDetails(data, "cert", null, null); @@ -55,12 +60,14 @@ public class CertificateCredentialDetailsUnitTests extends JsonParsingUnitTestsB @Test public void deserializeDetailsWithNoCert() { + // @formatter:off final String credentials = " \"type\": \"certificate\"," + " \"value\": {" + " \"ca\": \"authority\"," + " \"private_key\": \"private-key\"" + " }"; + // @formatter:on CredentialDetails data = parseDetails(credentials); assertDetails(data, null, "authority", "private-key"); @@ -77,13 +84,14 @@ public class CertificateCredentialDetailsUnitTests extends JsonParsingUnitTestsB assertDetails(data, "cert", "authority", "private-key"); } - private void assertDetails(CredentialDetails data, - String certificate, String ca, String privateKey) { + private void assertDetails(CredentialDetails data, String certificate, String ca, + String privateKey) { assertCommonDetails(data); - + assertThat(data.getCredentialType()).isEqualTo(CredentialType.CERTIFICATE); assertThat(data.getValue().getCertificate()).isEqualTo(certificate); assertThat(data.getValue().getCertificateAuthority()).isEqualTo(ca); assertThat(data.getValue().getPrivateKey()).isEqualTo(privateKey); } + } diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/support/certificate/CertificateCredentialRequestUnitTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/support/certificate/CertificateCredentialRequestUnitTests.java index b993333..2d68ec3 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/support/certificate/CertificateCredentialRequestUnitTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/support/certificate/CertificateCredentialRequestUnitTests.java @@ -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,12 @@ import org.junit.Before; import org.junit.Test; import org.springframework.credhub.support.CredHubRequestUnitTestsBase; +import org.springframework.credhub.support.JsonPathAssert; import org.springframework.credhub.support.SimpleCredentialName; import org.springframework.credhub.support.WriteMode; -import static org.springframework.credhub.support.JsonPathAssert.assertThat; - public class CertificateCredentialRequestUnitTests extends CredHubRequestUnitTestsBase { + @Before public void setUp() { buildRequest(new CertificateCredential("cert", "ca", "private-key")); @@ -34,12 +34,12 @@ public class CertificateCredentialRequestUnitTests extends CredHubRequestUnitTes @Test public void serializeWithAllValues() { - DocumentContext json = toJsonPath(requestBuilder); + DocumentContext json = toJsonPath(this.requestBuilder); assertCommonRequestFields(json, true, WriteMode.OVERWRITE, "/example/credential", "certificate"); - assertThat(json).hasPath("$.value.certificate").isEqualTo("cert"); - assertThat(json).hasPath("$.value.ca").isEqualTo("ca"); - assertThat(json).hasPath("$.value.private_key").isEqualTo("private-key"); + JsonPathAssert.assertThat(json).hasPath("$.value.certificate").isEqualTo("cert"); + JsonPathAssert.assertThat(json).hasPath("$.value.ca").isEqualTo("ca"); + JsonPathAssert.assertThat(json).hasPath("$.value.private_key").isEqualTo("private-key"); assertNoPermissions(json); } @@ -48,12 +48,11 @@ public class CertificateCredentialRequestUnitTests extends CredHubRequestUnitTes public void serializeWithCertOnly() { buildRequest(new CertificateCredential("cert", null, null)); - DocumentContext json = toJsonPath(requestBuilder); + DocumentContext json = toJsonPath(this.requestBuilder); assertCommonRequestFields(json, true, WriteMode.OVERWRITE, "/example/credential", "certificate"); - assertThat(json).hasPath("$.value.certificate").isEqualTo("cert"); - assertThat(json).hasNoPath("$.value.ca") - .hasNoPath("$.value.private_key"); + JsonPathAssert.assertThat(json).hasPath("$.value.certificate").isEqualTo("cert"); + JsonPathAssert.assertThat(json).hasNoPath("$.value.ca").hasNoPath("$.value.private_key"); assertNoPermissions(json); } @@ -62,12 +61,12 @@ public class CertificateCredentialRequestUnitTests extends CredHubRequestUnitTes public void serializeWithNoCert() { buildRequest(new CertificateCredential(null, "ca", "private-key")); - DocumentContext json = toJsonPath(requestBuilder); + DocumentContext json = toJsonPath(this.requestBuilder); assertCommonRequestFields(json, true, WriteMode.OVERWRITE, "/example/credential", "certificate"); - assertThat(json).hasNoPath("$.value.certificate"); - assertThat(json).hasPath("$.value.ca").isEqualTo("ca"); - assertThat(json).hasPath("$.value.private_key").isEqualTo("private-key"); + JsonPathAssert.assertThat(json).hasNoPath("$.value.certificate"); + JsonPathAssert.assertThat(json).hasPath("$.value.ca").isEqualTo("ca"); + JsonPathAssert.assertThat(json).hasPath("$.value.private_key").isEqualTo("private-key"); assertNoPermissions(json); } @@ -76,16 +75,14 @@ public class CertificateCredentialRequestUnitTests extends CredHubRequestUnitTes public void serializeWithNoValues() { buildRequest(new CertificateCredential(null, null, null)); - toJsonPath(requestBuilder); + toJsonPath(this.requestBuilder); } @SuppressWarnings("deprecation") private void buildRequest(CertificateCredential value) { - requestBuilder = CertificateCredentialRequest.builder() - .name(new SimpleCredentialName("example", "credential")) - .overwrite(true) - .mode(WriteMode.OVERWRITE) + this.requestBuilder = CertificateCredentialRequest.builder() + .name(new SimpleCredentialName("example", "credential")).overwrite(true).mode(WriteMode.OVERWRITE) .value(value); } -} \ No newline at end of file +} diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/support/certificate/CertificateParametersRequestUnitTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/support/certificate/CertificateParametersRequestUnitTests.java index 27c3a0a..026df98 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/support/certificate/CertificateParametersRequestUnitTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/support/certificate/CertificateParametersRequestUnitTests.java @@ -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,38 +21,27 @@ import org.junit.Before; import org.junit.Test; import org.springframework.credhub.support.CredHubRequestUnitTestsBase; +import org.springframework.credhub.support.JsonPathAssert; import org.springframework.credhub.support.KeyLength; import org.springframework.credhub.support.SimpleCredentialName; import org.springframework.credhub.support.WriteMode; -import static org.springframework.credhub.support.JsonPathAssert.assertThat; - @SuppressWarnings("deprecation") public class CertificateParametersRequestUnitTests extends CredHubRequestUnitTestsBase { + @Before public void setUp() { - requestBuilder = CertificateParametersRequest.builder(); + this.requestBuilder = CertificateParametersRequest.builder(); } @Test public void serializeWithParameters() { - requestBuilder = CertificateParametersRequest.builder() - .name(new SimpleCredentialName("example", "credential")) - .overwrite(true) - .mode(WriteMode.OVERWRITE) - .parameters(CertificateParameters.builder() - .keyLength(KeyLength.LENGTH_2048) - .commonName("common") - .alternateNames("alt1", "alt2") - .organization("org") - .organizationUnit("dev") - .locality("city") - .state("state") - .country("country") - .duration(1234) - .certificateAuthorityCredential("credential") - .certificateAuthority(true) - .selfSign(false) + this.requestBuilder = CertificateParametersRequest.builder() + .name(new SimpleCredentialName("example", "credential")).overwrite(true).mode(WriteMode.OVERWRITE) + .parameters(CertificateParameters.builder().keyLength(KeyLength.LENGTH_2048).commonName("common") + .alternateNames("alt1", "alt2").organization("org").organizationUnit("dev").locality("city") + .state("state").country("country").duration(1234).certificateAuthorityCredential("credential") + .certificateAuthority(true).selfSign(false) .keyUsage(KeyUsage.CRL_SIGN, KeyUsage.DATA_ENCIPHERMENT, KeyUsage.DECIPHER_ONLY, KeyUsage.DIGITAL_SIGNATURE, KeyUsage.ENCIPHER_ONLY, KeyUsage.KEY_AGREEMENT, KeyUsage.KEY_CERT_SIGN, KeyUsage.KEY_ENCIPHERMENT, KeyUsage.NON_REPUDIATION) @@ -61,76 +50,83 @@ public class CertificateParametersRequestUnitTests extends CredHubRequestUnitTes ExtendedKeyUsage.TIMESTAMPING) .build()); - DocumentContext json = toJsonPath(requestBuilder); + DocumentContext json = toJsonPath(this.requestBuilder); assertCommonRequestFields(json, true, WriteMode.OVERWRITE, "/example/credential", "certificate"); - assertThat(json).hasPath("$.parameters.key_length").isEqualTo(2048); - assertThat(json).hasPath("$.parameters.common_name").isEqualTo("common"); - assertThat(json).hasPath("$.parameters.alternative_names[0]").isEqualTo("alt1"); - assertThat(json).hasPath("$.parameters.alternative_names[1]").isEqualTo("alt2"); - assertThat(json).hasPath("$.parameters.organization").isEqualTo("org"); - assertThat(json).hasPath("$.parameters.organization_unit").isEqualTo("dev"); - assertThat(json).hasPath("$.parameters.locality").isEqualTo("city"); - assertThat(json).hasPath("$.parameters.state").isEqualTo("state"); - assertThat(json).hasPath("$.parameters.country").isEqualTo("country"); - assertThat(json).hasPath("$.parameters.duration").isEqualTo(1234); - assertThat(json).hasPath("$.parameters.ca").isEqualTo("credential"); - assertThat(json).hasPath("$.parameters.is_ca").isEqualTo(true); - assertThat(json).hasPath("$.parameters.self_sign").isEqualTo(false); - assertThat(json).hasPath("$.parameters.key_usage[0]").isEqualTo(KeyUsage.CRL_SIGN.getValue()); - assertThat(json).hasPath("$.parameters.key_usage[1]").isEqualTo(KeyUsage.DATA_ENCIPHERMENT.getValue()); - assertThat(json).hasPath("$.parameters.key_usage[2]").isEqualTo(KeyUsage.DECIPHER_ONLY.getValue()); - assertThat(json).hasPath("$.parameters.key_usage[3]").isEqualTo(KeyUsage.DIGITAL_SIGNATURE.getValue()); - assertThat(json).hasPath("$.parameters.key_usage[4]").isEqualTo(KeyUsage.ENCIPHER_ONLY.getValue()); - assertThat(json).hasPath("$.parameters.key_usage[5]").isEqualTo(KeyUsage.KEY_AGREEMENT.getValue()); - assertThat(json).hasPath("$.parameters.key_usage[6]").isEqualTo(KeyUsage.KEY_CERT_SIGN.getValue()); - assertThat(json).hasPath("$.parameters.key_usage[7]").isEqualTo(KeyUsage.KEY_ENCIPHERMENT.getValue()); - assertThat(json).hasPath("$.parameters.key_usage[8]").isEqualTo(KeyUsage.NON_REPUDIATION.getValue()); - assertThat(json).hasPath("$.parameters.extended_key_usage[0]").isEqualTo(ExtendedKeyUsage.CLIENT_AUTH.getValue()); - assertThat(json).hasPath("$.parameters.extended_key_usage[1]").isEqualTo(ExtendedKeyUsage.CODE_SIGNING.getValue()); - assertThat(json).hasPath("$.parameters.extended_key_usage[2]").isEqualTo(ExtendedKeyUsage.EMAIL_PROTECTION.getValue()); - assertThat(json).hasPath("$.parameters.extended_key_usage[3]").isEqualTo(ExtendedKeyUsage.SERVER_AUTH.getValue()); - assertThat(json).hasPath("$.parameters.extended_key_usage[4]").isEqualTo(ExtendedKeyUsage.TIMESTAMPING.getValue()); + JsonPathAssert.assertThat(json).hasPath("$.parameters.key_length").isEqualTo(2048); + JsonPathAssert.assertThat(json).hasPath("$.parameters.common_name").isEqualTo("common"); + JsonPathAssert.assertThat(json).hasPath("$.parameters.alternative_names[0]").isEqualTo("alt1"); + JsonPathAssert.assertThat(json).hasPath("$.parameters.alternative_names[1]").isEqualTo("alt2"); + JsonPathAssert.assertThat(json).hasPath("$.parameters.organization").isEqualTo("org"); + JsonPathAssert.assertThat(json).hasPath("$.parameters.organization_unit").isEqualTo("dev"); + JsonPathAssert.assertThat(json).hasPath("$.parameters.locality").isEqualTo("city"); + JsonPathAssert.assertThat(json).hasPath("$.parameters.state").isEqualTo("state"); + JsonPathAssert.assertThat(json).hasPath("$.parameters.country").isEqualTo("country"); + JsonPathAssert.assertThat(json).hasPath("$.parameters.duration").isEqualTo(1234); + JsonPathAssert.assertThat(json).hasPath("$.parameters.ca").isEqualTo("credential"); + JsonPathAssert.assertThat(json).hasPath("$.parameters.is_ca").isEqualTo(true); + JsonPathAssert.assertThat(json).hasPath("$.parameters.self_sign").isEqualTo(false); + JsonPathAssert.assertThat(json).hasPath("$.parameters.key_usage[0]").isEqualTo(KeyUsage.CRL_SIGN.getValue()); + JsonPathAssert.assertThat(json).hasPath("$.parameters.key_usage[1]") + .isEqualTo(KeyUsage.DATA_ENCIPHERMENT.getValue()); + JsonPathAssert.assertThat(json).hasPath("$.parameters.key_usage[2]") + .isEqualTo(KeyUsage.DECIPHER_ONLY.getValue()); + JsonPathAssert.assertThat(json).hasPath("$.parameters.key_usage[3]") + .isEqualTo(KeyUsage.DIGITAL_SIGNATURE.getValue()); + JsonPathAssert.assertThat(json).hasPath("$.parameters.key_usage[4]") + .isEqualTo(KeyUsage.ENCIPHER_ONLY.getValue()); + JsonPathAssert.assertThat(json).hasPath("$.parameters.key_usage[5]") + .isEqualTo(KeyUsage.KEY_AGREEMENT.getValue()); + JsonPathAssert.assertThat(json).hasPath("$.parameters.key_usage[6]") + .isEqualTo(KeyUsage.KEY_CERT_SIGN.getValue()); + JsonPathAssert.assertThat(json).hasPath("$.parameters.key_usage[7]") + .isEqualTo(KeyUsage.KEY_ENCIPHERMENT.getValue()); + JsonPathAssert.assertThat(json).hasPath("$.parameters.key_usage[8]") + .isEqualTo(KeyUsage.NON_REPUDIATION.getValue()); + JsonPathAssert.assertThat(json).hasPath("$.parameters.extended_key_usage[0]") + .isEqualTo(ExtendedKeyUsage.CLIENT_AUTH.getValue()); + JsonPathAssert.assertThat(json).hasPath("$.parameters.extended_key_usage[1]") + .isEqualTo(ExtendedKeyUsage.CODE_SIGNING.getValue()); + JsonPathAssert.assertThat(json).hasPath("$.parameters.extended_key_usage[2]") + .isEqualTo(ExtendedKeyUsage.EMAIL_PROTECTION.getValue()); + JsonPathAssert.assertThat(json).hasPath("$.parameters.extended_key_usage[3]") + .isEqualTo(ExtendedKeyUsage.SERVER_AUTH.getValue()); + JsonPathAssert.assertThat(json).hasPath("$.parameters.extended_key_usage[4]") + .isEqualTo(ExtendedKeyUsage.TIMESTAMPING.getValue()); } @Test public void serializeWithMinimalParameters() { - requestBuilder = CertificateParametersRequest.builder() - .name(new SimpleCredentialName("example", "credential")) - .overwrite(true) - .mode(WriteMode.NO_OVERWRITE) - .parameters(CertificateParameters.builder() - .commonName("common") - .certificateAuthorityCredential("credential") - .build()); + this.requestBuilder = CertificateParametersRequest.builder() + .name(new SimpleCredentialName("example", "credential")).overwrite(true).mode(WriteMode.NO_OVERWRITE) + .parameters(CertificateParameters.builder().commonName("common") + .certificateAuthorityCredential("credential").build()); - DocumentContext json = toJsonPath(requestBuilder); + DocumentContext json = toJsonPath(this.requestBuilder); assertCommonRequestFields(json, true, WriteMode.NO_OVERWRITE, "/example/credential", "certificate"); - assertThat(json).hasNoPath("$.parameters.key_length"); - assertThat(json).hasPath("$.parameters.common_name").isEqualTo("common"); - assertThat(json).hasPath("$.parameters.ca").isEqualTo("credential"); - assertThat(json).hasNoPath("$.parameters.alternative_names"); - assertThat(json).hasNoPath("$.parameters.organization"); - assertThat(json).hasNoPath("$.parameters.organization_unit"); - assertThat(json).hasNoPath("$.parameters.locality"); - assertThat(json).hasNoPath("$.parameters.state"); - assertThat(json).hasNoPath("$.parameters.country"); - assertThat(json).hasNoPath("$.parameters.duration"); - assertThat(json).hasNoPath("$.parameters.is_ca"); - assertThat(json).hasNoPath("$.parameters.self_sign"); - assertThat(json).hasNoPath("$.parameters.key_usage"); - assertThat(json).hasNoPath("$.parameters.extended_key_usage"); + JsonPathAssert.assertThat(json).hasNoPath("$.parameters.key_length"); + JsonPathAssert.assertThat(json).hasPath("$.parameters.common_name").isEqualTo("common"); + JsonPathAssert.assertThat(json).hasPath("$.parameters.ca").isEqualTo("credential"); + JsonPathAssert.assertThat(json).hasNoPath("$.parameters.alternative_names"); + JsonPathAssert.assertThat(json).hasNoPath("$.parameters.organization"); + JsonPathAssert.assertThat(json).hasNoPath("$.parameters.organization_unit"); + JsonPathAssert.assertThat(json).hasNoPath("$.parameters.locality"); + JsonPathAssert.assertThat(json).hasNoPath("$.parameters.state"); + JsonPathAssert.assertThat(json).hasNoPath("$.parameters.country"); + JsonPathAssert.assertThat(json).hasNoPath("$.parameters.duration"); + JsonPathAssert.assertThat(json).hasNoPath("$.parameters.is_ca"); + JsonPathAssert.assertThat(json).hasNoPath("$.parameters.self_sign"); + JsonPathAssert.assertThat(json).hasNoPath("$.parameters.key_usage"); + JsonPathAssert.assertThat(json).hasNoPath("$.parameters.extended_key_usage"); } @Test public void serializeWithNoParameters() { - requestBuilder = CertificateParametersRequest.builder() - .name(new SimpleCredentialName("example", "credential")) - .overwrite(true) - .mode(WriteMode.CONVERGE); + this.requestBuilder = CertificateParametersRequest.builder() + .name(new SimpleCredentialName("example", "credential")).overwrite(true).mode(WriteMode.CONVERGE); - DocumentContext json = toJsonPath(requestBuilder); + DocumentContext json = toJsonPath(this.requestBuilder); assertCommonRequestFields(json, true, WriteMode.CONVERGE, "/example/credential", "certificate"); assertParametersNotSet(json); @@ -138,21 +134,19 @@ public class CertificateParametersRequestUnitTests extends CredHubRequestUnitTes @Test(expected = IllegalArgumentException.class) public void serializeWithEmptyParameters() { - requestBuilder = CertificateParametersRequest.builder() - .name(new SimpleCredentialName("example", "credential")) - .overwrite(true) - .parameters(CertificateParameters.builder() - .keyLength(KeyLength.LENGTH_2048) - .build()); + this.requestBuilder = CertificateParametersRequest.builder() + .name(new SimpleCredentialName("example", "credential")).overwrite(true) + .parameters(CertificateParameters.builder().keyLength(KeyLength.LENGTH_2048).build()); - toJsonPath(requestBuilder); + toJsonPath(this.requestBuilder); } private void assertParametersNotSet(DocumentContext json) { - assertThat(json).hasNoPath("$.parameters.key_length"); - assertThat(json).hasNoPath("$.parameters.exclude_lower"); - assertThat(json).hasNoPath("$.parameters.exclude_upper"); - assertThat(json).hasNoPath("$.parameters.exclude_number"); - assertThat(json).hasNoPath("$.parameters.include_special"); + JsonPathAssert.assertThat(json).hasNoPath("$.parameters.key_length"); + JsonPathAssert.assertThat(json).hasNoPath("$.parameters.exclude_lower"); + JsonPathAssert.assertThat(json).hasNoPath("$.parameters.exclude_upper"); + JsonPathAssert.assertThat(json).hasNoPath("$.parameters.exclude_number"); + JsonPathAssert.assertThat(json).hasNoPath("$.parameters.include_special"); } -} \ No newline at end of file + +} diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/support/info/VersionInfoTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/support/info/VersionInfoTests.java index ce686fd..37d6266 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/support/info/VersionInfoTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/support/info/VersionInfoTests.java @@ -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,16 +17,16 @@ package org.springframework.credhub.support.info; import org.junit.Test; + import org.springframework.credhub.support.JsonParsingUnitTestsBase; import static org.assertj.core.api.Assertions.assertThat; public class VersionInfoTests extends JsonParsingUnitTestsBase { + @Test public void deserializeWithV1() { - String json = "{\n" + - " \"version\": \"1.9.0\"\n" + - "}"; + String json = "{\n" + " \"version\": \"1.9.0\"\n" + "}"; VersionInfo versionInfo = parseResponse(json, VersionInfo.class); @@ -39,9 +39,7 @@ public class VersionInfoTests extends JsonParsingUnitTestsBase { @Test public void deserializeWithV2_0() { - String json = "{\n" + - " \"version\": \"2.0.2\"\n" + - "}"; + String json = "{\n" + " \"version\": \"2.0.2\"\n" + "}"; VersionInfo versionInfo = parseResponse(json, VersionInfo.class); @@ -54,9 +52,7 @@ public class VersionInfoTests extends JsonParsingUnitTestsBase { @Test public void deserializeWithV2_1() { - String json = "{\n" + - " \"version\": \"2.1.2\"\n" + - "}"; + String json = "{\n" + " \"version\": \"2.1.2\"\n" + "}"; VersionInfo versionInfo = parseResponse(json, VersionInfo.class); @@ -66,4 +62,5 @@ public class VersionInfoTests extends JsonParsingUnitTestsBase { assertThat(versionInfo.isVersion2_0()).isFalse(); assertThat(versionInfo.isVersion2_1()).isTrue(); } -} \ No newline at end of file + +} diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/support/json/JsonCredentialDetailsUnitTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/support/json/JsonCredentialDetailsUnitTests.java index 4fb971e..38bbc3a 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/support/json/JsonCredentialDetailsUnitTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/support/json/JsonCredentialDetailsUnitTests.java @@ -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,8 @@ import org.springframework.credhub.support.JsonParsingUnitTestsBase; import static org.assertj.core.api.Assertions.assertThat; public class JsonCredentialDetailsUnitTests extends JsonParsingUnitTestsBase { + + // @formatter:off private static final String JSON_CREDENTIALS = " \"type\": \"json\"," + " \"value\": {" + @@ -33,6 +35,7 @@ public class JsonCredentialDetailsUnitTests extends JsonParsingUnitTestsBase { " \"client_secret\": \"test-secret\"," + " \"uri\": \"https://example.com\"" + " }"; + // @formatter:on @Test public void deserializeDetails() { @@ -55,8 +58,8 @@ public class JsonCredentialDetailsUnitTests extends JsonParsingUnitTestsBase { assertThat(data.getCredentialType()).isEqualTo(CredentialType.JSON); JsonCredential valueMap = data.getValue(); - assertThat(valueMap).containsEntry("client_id", "test-id") - .containsEntry("client_secret", "test-secret") + assertThat(valueMap).containsEntry("client_id", "test-id").containsEntry("client_secret", "test-secret") .containsEntry("uri", "https://example.com"); } + } diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/support/json/JsonCredentialRequestUnitTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/support/json/JsonCredentialRequestUnitTests.java index 86bed74..49e42d6 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/support/json/JsonCredentialRequestUnitTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/support/json/JsonCredentialRequestUnitTests.java @@ -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,34 +21,32 @@ import org.junit.Before; import org.junit.Test; import org.springframework.credhub.support.CredHubRequestUnitTestsBase; +import org.springframework.credhub.support.JsonPathAssert; import org.springframework.credhub.support.SimpleCredentialName; import org.springframework.credhub.support.WriteMode; -import static org.springframework.credhub.support.JsonPathAssert.assertThat; - public class JsonCredentialRequestUnitTests extends CredHubRequestUnitTestsBase { @Before public void setUp() { - requestBuilder = JsonCredentialRequest.builder() - .name(new SimpleCredentialName("example", "credential")) + this.requestBuilder = JsonCredentialRequest.builder().name(new SimpleCredentialName("example", "credential")) .value(new JsonCredential() { { put("data", "value"); put("test", true); } - }) - .mode(WriteMode.OVERWRITE); + }).mode(WriteMode.OVERWRITE); } @Test public void serializeWithJsonValue() { - DocumentContext json = toJsonPath(requestBuilder); + DocumentContext json = toJsonPath(this.requestBuilder); assertCommonRequestFields(json, null, WriteMode.OVERWRITE, "/example/credential", "json"); - assertThat(json).hasPath("$.value.data").isEqualTo("value"); - assertThat(json).hasPath("$.value.test").isEqualTo(true); + JsonPathAssert.assertThat(json).hasPath("$.value.data").isEqualTo("value"); + JsonPathAssert.assertThat(json).hasPath("$.value.test").isEqualTo(true); assertNoPermissions(json); } -} \ No newline at end of file + +} diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/support/password/PasswordCredentialDetailsUnitTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/support/password/PasswordCredentialDetailsUnitTests.java index 4ca4063..253872a 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/support/password/PasswordCredentialDetailsUnitTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/support/password/PasswordCredentialDetailsUnitTests.java @@ -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,22 +26,19 @@ import org.springframework.credhub.support.JsonParsingUnitTestsBase; import static org.assertj.core.api.Assertions.assertThat; public class PasswordCredentialDetailsUnitTests extends JsonParsingUnitTestsBase { - private static final String PASSWORD_CREDENTIALS = - " \"type\": \"password\"," + - " \"value\": \"secret\""; + + private static final String PASSWORD_CREDENTIALS = " \"type\": \"password\"," + " \"value\": \"secret\""; @Test public void deserializeDetails() { - CredentialDetails data = - parseDetails(PASSWORD_CREDENTIALS); + CredentialDetails data = parseDetails(PASSWORD_CREDENTIALS); assertDetails(data); } @Test public void deserializeDetailsData() { - CredentialDetailsData response = - parseDetailsData(PASSWORD_CREDENTIALS); + CredentialDetailsData response = parseDetailsData(PASSWORD_CREDENTIALS); assertThat(response.getData()).hasSize(1); @@ -52,8 +49,9 @@ public class PasswordCredentialDetailsUnitTests extends JsonParsingUnitTestsBase private void assertDetails(CredentialDetails data) { assertCommonDetails(data); - + assertThat(data.getCredentialType()).isEqualTo(CredentialType.PASSWORD); assertThat(data.getValue().getPassword()).isEqualTo("secret"); } + } diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/support/password/PasswordCredentialRequestUnitTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/support/password/PasswordCredentialRequestUnitTests.java index 7ab4d9b..8db6c6f 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/support/password/PasswordCredentialRequestUnitTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/support/password/PasswordCredentialRequestUnitTests.java @@ -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,46 +21,42 @@ import org.junit.Before; import org.junit.Test; import org.springframework.credhub.support.CredHubRequestUnitTestsBase; +import org.springframework.credhub.support.JsonPathAssert; import org.springframework.credhub.support.SimpleCredentialName; import org.springframework.credhub.support.WriteMode; -import static org.springframework.credhub.support.JsonPathAssert.assertThat; - @SuppressWarnings("deprecation") public class PasswordCredentialRequestUnitTests extends CredHubRequestUnitTestsBase { @Before public void setUp() { - requestBuilder = PasswordCredentialRequest.builder() - .name(new SimpleCredentialName("example", "credential")) - .overwrite(true) - .mode(WriteMode.OVERWRITE) + this.requestBuilder = PasswordCredentialRequest.builder() + .name(new SimpleCredentialName("example", "credential")).overwrite(true).mode(WriteMode.OVERWRITE) .value(new PasswordCredential("secret")); } @Test public void serializeWithPasswordValue() { - DocumentContext json = toJsonPath(requestBuilder); + DocumentContext json = toJsonPath(this.requestBuilder); assertCommonRequestFields(json, true, WriteMode.OVERWRITE, "/example/credential", "password"); - assertThat(json).hasPath("$.value").isEqualTo("secret"); + JsonPathAssert.assertThat(json).hasPath("$.value").isEqualTo("secret"); assertNoPermissions(json); } @Test public void serializeWithStringValue() { - requestBuilder = PasswordCredentialRequest.builder() - .name(new SimpleCredentialName("example", "credential")) - .overwrite(true) - .mode(WriteMode.OVERWRITE) + this.requestBuilder = PasswordCredentialRequest.builder() + .name(new SimpleCredentialName("example", "credential")).overwrite(true).mode(WriteMode.OVERWRITE) .value("secret"); - DocumentContext json = toJsonPath(requestBuilder); + DocumentContext json = toJsonPath(this.requestBuilder); assertCommonRequestFields(json, true, WriteMode.OVERWRITE, "/example/credential", "password"); - assertThat(json).hasPath("$.value").isEqualTo("secret"); + JsonPathAssert.assertThat(json).hasPath("$.value").isEqualTo("secret"); assertNoPermissions(json); } -} \ No newline at end of file + +} diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/support/password/PasswordParametersRequestUnitTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/support/password/PasswordParametersRequestUnitTests.java index 656aa04..9f6deb1 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/support/password/PasswordParametersRequestUnitTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/support/password/PasswordParametersRequestUnitTests.java @@ -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,51 +21,42 @@ import org.junit.Before; import org.junit.Test; import org.springframework.credhub.support.CredHubRequestUnitTestsBase; +import org.springframework.credhub.support.JsonPathAssert; import org.springframework.credhub.support.SimpleCredentialName; import org.springframework.credhub.support.WriteMode; -import static org.springframework.credhub.support.JsonPathAssert.assertThat; - @SuppressWarnings("deprecation") public class PasswordParametersRequestUnitTests extends CredHubRequestUnitTestsBase { + @Before public void setUp() { - requestBuilder = PasswordParametersRequest.builder(); + this.requestBuilder = PasswordParametersRequest.builder(); } @Test public void serializeWithParameters() { - requestBuilder = PasswordParametersRequest.builder() - .name(new SimpleCredentialName("example", "credential")) - .overwrite(true) - .mode(WriteMode.OVERWRITE) - .parameters(PasswordParameters.builder() - .length(20) - .excludeLower(true) - .excludeUpper(false) - .excludeNumber(true) - .includeSpecial(false) - .build()); + this.requestBuilder = PasswordParametersRequest.builder() + .name(new SimpleCredentialName("example", "credential")).overwrite(true).mode(WriteMode.OVERWRITE) + .parameters(PasswordParameters.builder().length(20).excludeLower(true).excludeUpper(false) + .excludeNumber(true).includeSpecial(false).build()); - DocumentContext json = toJsonPath(requestBuilder); + DocumentContext json = toJsonPath(this.requestBuilder); assertCommonRequestFields(json, true, WriteMode.OVERWRITE, "/example/credential", "password"); - assertThat(json).hasPath("$.parameters.length").isEqualTo(20); - assertThat(json).hasPath("$.parameters.exclude_lower").isEqualTo(true); - assertThat(json).hasPath("$.parameters.exclude_upper").isEqualTo(false); - assertThat(json).hasPath("$.parameters.exclude_number").isEqualTo(true); - assertThat(json).hasPath("$.parameters.include_special").isEqualTo(false); + JsonPathAssert.assertThat(json).hasPath("$.parameters.length").isEqualTo(20); + JsonPathAssert.assertThat(json).hasPath("$.parameters.exclude_lower").isEqualTo(true); + JsonPathAssert.assertThat(json).hasPath("$.parameters.exclude_upper").isEqualTo(false); + JsonPathAssert.assertThat(json).hasPath("$.parameters.exclude_number").isEqualTo(true); + JsonPathAssert.assertThat(json).hasPath("$.parameters.include_special").isEqualTo(false); } @Test public void serializeWithEmptyParameters() { - requestBuilder = PasswordParametersRequest.builder() - .name(new SimpleCredentialName("example", "credential")) - .overwrite(true) - .mode(WriteMode.CONVERGE) + this.requestBuilder = PasswordParametersRequest.builder() + .name(new SimpleCredentialName("example", "credential")).overwrite(true).mode(WriteMode.CONVERGE) .parameters(new PasswordParameters()); - DocumentContext json = toJsonPath(requestBuilder); + DocumentContext json = toJsonPath(this.requestBuilder); assertCommonRequestFields(json, true, WriteMode.CONVERGE, "/example/credential", "password"); assertParametersNotSet(json); @@ -73,22 +64,21 @@ public class PasswordParametersRequestUnitTests extends CredHubRequestUnitTestsB @Test public void serializeWithNoParameters() { - requestBuilder = PasswordParametersRequest.builder() - .name(new SimpleCredentialName("example", "credential")) - .overwrite(true) - .mode(WriteMode.NO_OVERWRITE); + this.requestBuilder = PasswordParametersRequest.builder() + .name(new SimpleCredentialName("example", "credential")).overwrite(true).mode(WriteMode.NO_OVERWRITE); - DocumentContext json = toJsonPath(requestBuilder); + DocumentContext json = toJsonPath(this.requestBuilder); assertCommonRequestFields(json, true, WriteMode.NO_OVERWRITE, "/example/credential", "password"); assertParametersNotSet(json); } private void assertParametersNotSet(DocumentContext json) { - assertThat(json).hasNoPath("$.parameters.length"); - assertThat(json).hasNoPath("$.parameters.exclude_lower"); - assertThat(json).hasNoPath("$.parameters.exclude_upper"); - assertThat(json).hasNoPath("$.parameters.exclude_number"); - assertThat(json).hasNoPath("$.parameters.include_special"); + JsonPathAssert.assertThat(json).hasNoPath("$.parameters.length"); + JsonPathAssert.assertThat(json).hasNoPath("$.parameters.exclude_lower"); + JsonPathAssert.assertThat(json).hasNoPath("$.parameters.exclude_upper"); + JsonPathAssert.assertThat(json).hasNoPath("$.parameters.exclude_number"); + JsonPathAssert.assertThat(json).hasNoPath("$.parameters.include_special"); } -} \ No newline at end of file + +} diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/support/permissions/CredentialPermissionUnitTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/support/permissions/CredentialPermissionUnitTests.java index e2b32a3..1a3cd1a 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/support/permissions/CredentialPermissionUnitTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/support/permissions/CredentialPermissionUnitTests.java @@ -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,35 @@ * 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 java.util.List; + import com.jayway.jsonpath.DocumentContext; import org.junit.Test; + import org.springframework.credhub.support.CredentialPermission; import org.springframework.credhub.support.JsonParsingUnitTestsBase; +import org.springframework.credhub.support.JsonPathAssert; import org.springframework.credhub.support.JsonTestUtils; import org.springframework.credhub.support.SimpleCredentialName; -import java.util.List; - import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.credhub.support.JsonPathAssert.assertThat; public class CredentialPermissionUnitTests extends JsonParsingUnitTestsBase { + @Test public void deserializePermission() { + // @formatter:off String json = "{" + "\"uuid\": \"uuid\",\n" + "\"path\": \"/example-directory/example-specific-credential\",\n" + "\"actor\": \"uaa-user:106f52e2-5d01-4675-8d7a-c05ff9a2c081\",\n" + "\"operations\": [\"read\",\"write\"]" + "}"; + // @formatter:on CredentialPermission credentialPermission = parsePermission(json); @@ -58,22 +60,20 @@ public class CredentialPermissionUnitTests extends JsonParsingUnitTestsBase { @Test public void serializePermission() { - CredentialPermission permission = - new CredentialPermission(new SimpleCredentialName("example", "credential", "*"), - Permission.builder() - .app("appid1") - .operations(Operation.READ, Operation.WRITE) - .build()); + CredentialPermission permission = new CredentialPermission( + new SimpleCredentialName("example", "credential", "*"), + Permission.builder().app("appid1").operations(Operation.READ, Operation.WRITE).build()); DocumentContext json = JsonTestUtils.toJsonPath(permission); - assertThat(json).hasPath("$.path").isEqualTo("/example/credential/*"); - assertThat(json).hasPath("$.actor").isEqualTo(Actor.app("appid1").getIdentity()); - assertThat(json).hasPath("$.operations[0]").isEqualTo("read"); - assertThat(json).hasPath("$.operations[1]").isEqualTo("write"); + JsonPathAssert.assertThat(json).hasPath("$.path").isEqualTo("/example/credential/*"); + JsonPathAssert.assertThat(json).hasPath("$.actor").isEqualTo(Actor.app("appid1").getIdentity()); + JsonPathAssert.assertThat(json).hasPath("$.operations[0]").isEqualTo("read"); + JsonPathAssert.assertThat(json).hasPath("$.operations[1]").isEqualTo("write"); } private CredentialPermission parsePermission(String json) { return JsonTestUtils.fromJson(json, CredentialPermission.class); } + } diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/support/permissions/CredentialPermissionsUnitTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/support/permissions/CredentialPermissionsUnitTests.java index 454e388..3c6f888 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/support/permissions/CredentialPermissionsUnitTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/support/permissions/CredentialPermissionsUnitTests.java @@ -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; @@ -25,17 +23,17 @@ import org.junit.Test; import org.springframework.credhub.support.CredentialPermissions; import org.springframework.credhub.support.JsonParsingUnitTestsBase; +import org.springframework.credhub.support.JsonPathAssert; import org.springframework.credhub.support.JsonTestUtils; import org.springframework.credhub.support.SimpleCredentialName; import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.credhub.support.JsonPathAssert.assertThat; -import static org.springframework.credhub.support.permissions.ActorType.APP; -import static org.springframework.credhub.support.permissions.ActorType.USER; public class CredentialPermissionsUnitTests extends JsonParsingUnitTestsBase { + @Test public void deserializePermissions() { + // @formatter:off String json = "{\"credential_name\": \"/c/example\"," + "\"permissions\": [" + " {" + @@ -55,6 +53,7 @@ public class CredentialPermissionsUnitTests extends JsonParsingUnitTestsBase { " ]" + " }" + " ]}"; + // @formatter:on CredentialPermissions permissions = parsePermissions(json); @@ -62,16 +61,16 @@ public class CredentialPermissionsUnitTests extends JsonParsingUnitTestsBase { assertThat(permissions.getPermissions().size()).isEqualTo(2); Permission permission = permissions.getPermissions().get(0); - assertThat(permission.getActor().getAuthType()).isEqualTo(APP); + assertThat(permission.getActor().getAuthType()).isEqualTo(ActorType.APP); assertThat(permission.getActor().getPrimaryIdentifier()).isEqualTo("appid1"); List operations = permission.getOperations(); assertThat(operations.size()).isEqualTo(5); - assertThat(operations).contains(Operation.READ, Operation.WRITE, Operation.DELETE, - Operation.READ_ACL, Operation.WRITE_ACL); + assertThat(operations).contains(Operation.READ, Operation.WRITE, Operation.DELETE, Operation.READ_ACL, + Operation.WRITE_ACL); permission = permissions.getPermissions().get(1); - assertThat(permission.getActor().getAuthType()).isEqualTo(USER); + assertThat(permission.getActor().getAuthType()).isEqualTo(ActorType.USER); assertThat(permission.getActor().getPrimaryIdentifier()).isEqualTo("zone1/userid"); operations = permission.getOperations(); @@ -90,22 +89,20 @@ public class CredentialPermissionsUnitTests extends JsonParsingUnitTestsBase { @Test public void serialize() { - CredentialPermissions permissions = - new CredentialPermissions(new SimpleCredentialName("example", "credentialName"), - Permission.builder() - .app("appid1") - .operations(Operation.READ, Operation.WRITE) - .build()); + CredentialPermissions permissions = new CredentialPermissions( + new SimpleCredentialName("example", "credentialName"), + Permission.builder().app("appid1").operations(Operation.READ, Operation.WRITE).build()); DocumentContext json = JsonTestUtils.toJsonPath(permissions); - assertThat(json).hasPath("$.credential_name").isEqualTo("/example/credentialName"); - assertThat(json).hasPath("$.permissions[0].actor").isEqualTo(Actor.app("appid1").getIdentity()); - assertThat(json).hasPath("$.permissions[0].operations[0]").isEqualTo("read"); - assertThat(json).hasPath("$.permissions[0].operations[1]").isEqualTo("write"); + JsonPathAssert.assertThat(json).hasPath("$.credential_name").isEqualTo("/example/credentialName"); + JsonPathAssert.assertThat(json).hasPath("$.permissions[0].actor").isEqualTo(Actor.app("appid1").getIdentity()); + JsonPathAssert.assertThat(json).hasPath("$.permissions[0].operations[0]").isEqualTo("read"); + JsonPathAssert.assertThat(json).hasPath("$.permissions[0].operations[1]").isEqualTo("write"); } private CredentialPermissions parsePermissions(String json) { return JsonTestUtils.fromJson(json, CredentialPermissions.class); } + } diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/support/rsa/RsaCredentialDetailsUnitTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/support/rsa/RsaCredentialDetailsUnitTests.java index ec95891..8f52a8f 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/support/rsa/RsaCredentialDetailsUnitTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/support/rsa/RsaCredentialDetailsUnitTests.java @@ -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,12 +26,15 @@ import org.springframework.credhub.support.JsonParsingUnitTestsBase; import static org.assertj.core.api.Assertions.assertThat; public class RsaCredentialDetailsUnitTests extends JsonParsingUnitTestsBase { + + // @formatter:off private static final String RSA_CREDENTIALS = " \"type\": \"rsa\"," + " \"value\": {" + " \"private_key\": \"private-key\"," + " \"public_key\": \"public-key\"" + " }"; + // @formatter:on @Test public void deserializeDetailsWithPublicAndPrivateKeys() { @@ -42,11 +45,13 @@ public class RsaCredentialDetailsUnitTests extends JsonParsingUnitTestsBase { @Test public void deserializeDetailsWithPublicKey() { + // @formatter:off final String credentials = " \"type\": \"rsa\"," + - " \"value\": {" + - " \"public_key\": \"public-key\"" + - " }"; + " \"value\": {" + + " \"public_key\": \"public-key\"" + + " }"; + // @formatter:on CredentialDetails data = parseDetails(credentials); assertDetails(data, "public-key", null); @@ -54,11 +59,13 @@ public class RsaCredentialDetailsUnitTests extends JsonParsingUnitTestsBase { @Test public void deserializeDetailsWithPrivateKey() { + // @formatter:off final String credentials = " \"type\": \"rsa\"," + - " \"value\": {" + - " \"private_key\": \"private-key\"" + - " }"; + " \"value\": {" + + " \"private_key\": \"private-key\"" + + " }"; + // @formatter:on CredentialDetails data = parseDetails(credentials); assertDetails(data, null, "private-key"); @@ -77,9 +84,10 @@ public class RsaCredentialDetailsUnitTests extends JsonParsingUnitTestsBase { private void assertDetails(CredentialDetails data, String publicKey, String privateKey) { assertCommonDetails(data); - + assertThat(data.getCredentialType()).isEqualTo(CredentialType.RSA); assertThat(data.getValue().getPublicKey()).isEqualTo(publicKey); assertThat(data.getValue().getPrivateKey()).isEqualTo(privateKey); } + } diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/support/rsa/RsaCredentialRequestUnitTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/support/rsa/RsaCredentialRequestUnitTests.java index b6c018e..1cf8fee 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/support/rsa/RsaCredentialRequestUnitTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/support/rsa/RsaCredentialRequestUnitTests.java @@ -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,12 @@ import org.junit.Before; import org.junit.Test; import org.springframework.credhub.support.CredHubRequestUnitTestsBase; +import org.springframework.credhub.support.JsonPathAssert; import org.springframework.credhub.support.SimpleCredentialName; import org.springframework.credhub.support.WriteMode; -import static org.springframework.credhub.support.JsonPathAssert.assertThat; - public class RsaCredentialRequestUnitTests extends CredHubRequestUnitTestsBase { + @Before public void setUp() { buildRequest(new RsaCredential("public-key", "private-key")); @@ -34,11 +34,11 @@ public class RsaCredentialRequestUnitTests extends CredHubRequestUnitTestsBase { @Test public void serializeWithPublicAndPrivateKey() { - DocumentContext json = toJsonPath(requestBuilder); + DocumentContext json = toJsonPath(this.requestBuilder); assertCommonRequestFields(json, true, WriteMode.OVERWRITE, "/example/credential", "rsa"); - assertThat(json).hasPath("$.value.public_key").isEqualTo("public-key"); - assertThat(json).hasPath("$.value.private_key").isEqualTo("private-key"); + JsonPathAssert.assertThat(json).hasPath("$.value.public_key").isEqualTo("public-key"); + JsonPathAssert.assertThat(json).hasPath("$.value.private_key").isEqualTo("private-key"); assertNoPermissions(json); } @@ -47,12 +47,12 @@ public class RsaCredentialRequestUnitTests extends CredHubRequestUnitTestsBase { public void serializeWithPublicKey() { buildRequest(new RsaCredential("public-key", null)); - DocumentContext json = toJsonPath(requestBuilder); + DocumentContext json = toJsonPath(this.requestBuilder); assertCommonRequestFields(json, true, WriteMode.OVERWRITE, "/example/credential", "rsa"); - assertThat(json).hasPath("$.value.public_key").isEqualTo("public-key"); - assertThat(json).hasNoPath("$.value.private_key"); + JsonPathAssert.assertThat(json).hasPath("$.value.public_key").isEqualTo("public-key"); + JsonPathAssert.assertThat(json).hasNoPath("$.value.private_key"); assertNoPermissions(json); } @@ -61,11 +61,11 @@ public class RsaCredentialRequestUnitTests extends CredHubRequestUnitTestsBase { public void serializeWithPrivateKey() { buildRequest(new RsaCredential(null, "private-key")); - DocumentContext json = toJsonPath(requestBuilder); + DocumentContext json = toJsonPath(this.requestBuilder); assertCommonRequestFields(json, true, WriteMode.OVERWRITE, "/example/credential", "rsa"); - assertThat(json).hasNoPath("$.value.public_key"); - assertThat(json).hasPath("$.value.private_key").isEqualTo("private-key"); + JsonPathAssert.assertThat(json).hasNoPath("$.value.public_key"); + JsonPathAssert.assertThat(json).hasPath("$.value.private_key").isEqualTo("private-key"); assertNoPermissions(json); } @@ -74,15 +74,13 @@ public class RsaCredentialRequestUnitTests extends CredHubRequestUnitTestsBase { public void serializeWithNeitherKey() { buildRequest(new RsaCredential(null, null)); - toJsonPath(requestBuilder); + toJsonPath(this.requestBuilder); } @SuppressWarnings("deprecation") private void buildRequest(RsaCredential value) { - requestBuilder = RsaCredentialRequest.builder() - .name(new SimpleCredentialName("example", "credential")) - .overwrite(true) - .mode(WriteMode.OVERWRITE) - .value(value); + this.requestBuilder = RsaCredentialRequest.builder().name(new SimpleCredentialName("example", "credential")) + .overwrite(true).mode(WriteMode.OVERWRITE).value(value); } -} \ No newline at end of file + +} diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/support/rsa/RsaParametersRequestUnitTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/support/rsa/RsaParametersRequestUnitTests.java index cc0215a..140c5b0 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/support/rsa/RsaParametersRequestUnitTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/support/rsa/RsaParametersRequestUnitTests.java @@ -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,43 +21,39 @@ import org.junit.Before; import org.junit.Test; import org.springframework.credhub.support.CredHubRequestUnitTestsBase; +import org.springframework.credhub.support.JsonPathAssert; import org.springframework.credhub.support.KeyLength; import org.springframework.credhub.support.SimpleCredentialName; import org.springframework.credhub.support.WriteMode; -import static org.springframework.credhub.support.JsonPathAssert.assertThat; - @SuppressWarnings("deprecation") public class RsaParametersRequestUnitTests extends CredHubRequestUnitTestsBase { + @Before public void setUp() { - requestBuilder = RsaParametersRequest.builder(); + this.requestBuilder = RsaParametersRequest.builder(); } @Test public void serializeWithParameters() { - requestBuilder = RsaParametersRequest.builder() - .name(new SimpleCredentialName("example", "credential")) - .overwrite(true) - .mode(WriteMode.OVERWRITE) - .parameters(new RsaParameters(KeyLength.LENGTH_4096)); + this.requestBuilder = RsaParametersRequest.builder().name(new SimpleCredentialName("example", "credential")) + .overwrite(true).mode(WriteMode.OVERWRITE).parameters(new RsaParameters(KeyLength.LENGTH_4096)); - DocumentContext json = toJsonPath(requestBuilder); + DocumentContext json = toJsonPath(this.requestBuilder); assertCommonRequestFields(json, true, WriteMode.OVERWRITE, "/example/credential", "rsa"); - assertThat(json).hasPath("$.parameters.key_length").isEqualTo(4096); + JsonPathAssert.assertThat(json).hasPath("$.parameters.key_length").isEqualTo(4096); } @Test public void serializeWithNoParameters() { - requestBuilder = RsaParametersRequest.builder() - .name(new SimpleCredentialName("example", "credential")) - .overwrite(true) - .mode(WriteMode.OVERWRITE); + this.requestBuilder = RsaParametersRequest.builder().name(new SimpleCredentialName("example", "credential")) + .overwrite(true).mode(WriteMode.OVERWRITE); - DocumentContext json = toJsonPath(requestBuilder); + DocumentContext json = toJsonPath(this.requestBuilder); assertCommonRequestFields(json, true, WriteMode.OVERWRITE, "/example/credential", "rsa"); - assertThat(json).hasNoPath("$.parameters.key_length"); + JsonPathAssert.assertThat(json).hasNoPath("$.parameters.key_length"); } -} \ No newline at end of file + +} diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/support/ssh/SshCredentialDetailsUnitTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/support/ssh/SshCredentialDetailsUnitTests.java index 5e70798..76e24b0 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/support/ssh/SshCredentialDetailsUnitTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/support/ssh/SshCredentialDetailsUnitTests.java @@ -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,13 +26,16 @@ import org.springframework.credhub.support.JsonParsingUnitTestsBase; import static org.assertj.core.api.Assertions.assertThat; public class SshCredentialDetailsUnitTests extends JsonParsingUnitTestsBase { + + // @formatter:off private static final String SSH_CREDENTIALS = " \"type\": \"ssh\"," + " \"value\": {" + - " \"private_key\": \"private-key\"," + - " \"public_key\": \"public-key\"," + - " \"public_key_fingerprint\": \"fingerprint\"" + + " \"private_key\": \"private-key\"," + + " \"public_key\": \"public-key\"," + + " \"public_key_fingerprint\": \"fingerprint\"" + " }"; + // @formatter:on @Test public void deserializeDetailsWithPublicAndPrivateKeys() { @@ -43,11 +46,13 @@ public class SshCredentialDetailsUnitTests extends JsonParsingUnitTestsBase { @Test public void deserializeDetailsWithPublicKey() { + // @formatter:off final String credentials = " \"type\": \"ssh\"," + - " \"value\": {" + - " \"public_key\": \"public-key\"" + - " }"; + " \"value\": {" + + " \"public_key\": \"public-key\"" + + " }"; + // @formatter:on CredentialDetails data = parseDetails(credentials); assertDetails(data, "public-key", null, null); @@ -55,11 +60,13 @@ public class SshCredentialDetailsUnitTests extends JsonParsingUnitTestsBase { @Test public void deserializeDetailsWithPrivateKey() { + // @formatter:off final String credentials = " \"type\": \"ssh\"," + - " \"value\": {" + - " \"private_key\": \"private-key\"" + - " }"; + " \"value\": {" + + " \"private_key\": \"private-key\"" + + " }"; + // @formatter:on CredentialDetails data = parseDetails(credentials); assertDetails(data, null, "private-key", null); @@ -76,13 +83,14 @@ public class SshCredentialDetailsUnitTests extends JsonParsingUnitTestsBase { assertDetails(data, "public-key", "private-key", "fingerprint"); } - private void assertDetails(CredentialDetails data, - String publicKey, String privateKey, String publicKeyFingerprint) { + private void assertDetails(CredentialDetails data, String publicKey, String privateKey, + String publicKeyFingerprint) { assertCommonDetails(data); - + assertThat(data.getCredentialType()).isEqualTo(CredentialType.SSH); assertThat(data.getValue().getPublicKey()).isEqualTo(publicKey); assertThat(data.getValue().getPrivateKey()).isEqualTo(privateKey); assertThat(data.getValue().getPublicKeyFingerprint()).isEqualTo(publicKeyFingerprint); } + } diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/support/ssh/SshCredentialRequestUnitTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/support/ssh/SshCredentialRequestUnitTests.java index d04ff35..6427ffe 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/support/ssh/SshCredentialRequestUnitTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/support/ssh/SshCredentialRequestUnitTests.java @@ -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,12 @@ import org.junit.Before; import org.junit.Test; import org.springframework.credhub.support.CredHubRequestUnitTestsBase; +import org.springframework.credhub.support.JsonPathAssert; import org.springframework.credhub.support.SimpleCredentialName; import org.springframework.credhub.support.WriteMode; -import static org.springframework.credhub.support.JsonPathAssert.assertThat; - public class SshCredentialRequestUnitTests extends CredHubRequestUnitTestsBase { + @Before public void setUp() { buildRequest(new SshCredential("public-key", "private-key")); @@ -34,11 +34,11 @@ public class SshCredentialRequestUnitTests extends CredHubRequestUnitTestsBase { @Test public void serializeWithPublicAndPrivateKey() { - DocumentContext json = toJsonPath(requestBuilder); + DocumentContext json = toJsonPath(this.requestBuilder); assertCommonRequestFields(json, true, WriteMode.OVERWRITE, "/example/credential", "ssh"); - assertThat(json).hasPath("$.value.public_key").isEqualTo("public-key"); - assertThat(json).hasPath("$.value.private_key").isEqualTo("private-key"); + JsonPathAssert.assertThat(json).hasPath("$.value.public_key").isEqualTo("public-key"); + JsonPathAssert.assertThat(json).hasPath("$.value.private_key").isEqualTo("private-key"); assertNoPermissions(json); } @@ -47,11 +47,11 @@ public class SshCredentialRequestUnitTests extends CredHubRequestUnitTestsBase { public void serializeWithPublicKey() { buildRequest(new SshCredential("public-key", null)); - DocumentContext json = toJsonPath(requestBuilder); + DocumentContext json = toJsonPath(this.requestBuilder); assertCommonRequestFields(json, true, WriteMode.OVERWRITE, "/example/credential", "ssh"); - assertThat(json).hasPath("$.value.public_key").isEqualTo("public-key"); - assertThat(json).hasNoPath("$.value.private_key"); + JsonPathAssert.assertThat(json).hasPath("$.value.public_key").isEqualTo("public-key"); + JsonPathAssert.assertThat(json).hasNoPath("$.value.private_key"); assertNoPermissions(json); } @@ -60,11 +60,11 @@ public class SshCredentialRequestUnitTests extends CredHubRequestUnitTestsBase { public void serializeWithPrivateKey() { buildRequest(new SshCredential(null, "private-key")); - DocumentContext json = toJsonPath(requestBuilder); + DocumentContext json = toJsonPath(this.requestBuilder); assertCommonRequestFields(json, true, WriteMode.OVERWRITE, "/example/credential", "ssh"); - assertThat(json).hasNoPath("$.value.public_key"); - assertThat(json).hasPath("$.value.private_key").isEqualTo("private-key"); + JsonPathAssert.assertThat(json).hasNoPath("$.value.public_key"); + JsonPathAssert.assertThat(json).hasPath("$.value.private_key").isEqualTo("private-key"); assertNoPermissions(json); } @@ -73,15 +73,13 @@ public class SshCredentialRequestUnitTests extends CredHubRequestUnitTestsBase { public void serializeWithNeitherKey() { buildRequest(new SshCredential(null, null)); - toJsonPath(requestBuilder); + toJsonPath(this.requestBuilder); } @SuppressWarnings("deprecation") private void buildRequest(SshCredential value) { - requestBuilder = SshCredentialRequest.builder() - .name(new SimpleCredentialName("example", "credential")) - .overwrite(true) - .mode(WriteMode.OVERWRITE) - .value(value); + this.requestBuilder = SshCredentialRequest.builder().name(new SimpleCredentialName("example", "credential")) + .overwrite(true).mode(WriteMode.OVERWRITE).value(value); } -} \ No newline at end of file + +} diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/support/ssh/SshParametersRequestUnitTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/support/ssh/SshParametersRequestUnitTests.java index c64b9a7..1614f82 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/support/ssh/SshParametersRequestUnitTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/support/ssh/SshParametersRequestUnitTests.java @@ -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,75 +21,66 @@ import org.junit.Before; import org.junit.Test; import org.springframework.credhub.support.CredHubRequestUnitTestsBase; +import org.springframework.credhub.support.JsonPathAssert; import org.springframework.credhub.support.KeyLength; import org.springframework.credhub.support.SimpleCredentialName; import org.springframework.credhub.support.WriteMode; -import static org.springframework.credhub.support.JsonPathAssert.assertThat; - @SuppressWarnings("deprecation") public class SshParametersRequestUnitTests extends CredHubRequestUnitTestsBase { + @Before public void setUp() { - requestBuilder = SshParametersRequest.builder(); + this.requestBuilder = SshParametersRequest.builder(); } @Test public void serializeWithParameters() { - requestBuilder = SshParametersRequest.builder() - .name(new SimpleCredentialName("example", "credential")) - .overwrite(true) - .mode(WriteMode.OVERWRITE) + this.requestBuilder = SshParametersRequest.builder().name(new SimpleCredentialName("example", "credential")) + .overwrite(true).mode(WriteMode.OVERWRITE) .parameters(new SshParameters(KeyLength.LENGTH_2048, "ssh comment")); - DocumentContext json = toJsonPath(requestBuilder); + DocumentContext json = toJsonPath(this.requestBuilder); assertCommonRequestFields(json, true, WriteMode.OVERWRITE, "/example/credential", "ssh"); - assertThat(json).hasPath("$.parameters.key_length").isEqualTo(2048); - assertThat(json).hasPath("$.parameters.ssh_comment").isEqualTo("ssh comment"); + JsonPathAssert.assertThat(json).hasPath("$.parameters.key_length").isEqualTo(2048); + JsonPathAssert.assertThat(json).hasPath("$.parameters.ssh_comment").isEqualTo("ssh comment"); } @Test public void serializeWithLengthParameter() { - requestBuilder = SshParametersRequest.builder() - .name(new SimpleCredentialName("example", "credential")) - .overwrite(true) - .mode(WriteMode.NO_OVERWRITE) - .parameters(new SshParameters(KeyLength.LENGTH_2048)); + this.requestBuilder = SshParametersRequest.builder().name(new SimpleCredentialName("example", "credential")) + .overwrite(true).mode(WriteMode.NO_OVERWRITE).parameters(new SshParameters(KeyLength.LENGTH_2048)); - DocumentContext json = toJsonPath(requestBuilder); + DocumentContext json = toJsonPath(this.requestBuilder); assertCommonRequestFields(json, true, WriteMode.NO_OVERWRITE, "/example/credential", "ssh"); - assertThat(json).hasPath("$.parameters.key_length").isEqualTo(2048); - assertThat(json).hasNoPath("$.parameters.ssh_comment"); + JsonPathAssert.assertThat(json).hasPath("$.parameters.key_length").isEqualTo(2048); + JsonPathAssert.assertThat(json).hasNoPath("$.parameters.ssh_comment"); } @Test public void serializeWithCommentParameter() { - requestBuilder = SshParametersRequest.builder() - .name(new SimpleCredentialName("example", "credential")) - .overwrite(true) - .mode(WriteMode.CONVERGE) - .parameters(new SshParameters("ssh comment")); + this.requestBuilder = SshParametersRequest.builder().name(new SimpleCredentialName("example", "credential")) + .overwrite(true).mode(WriteMode.CONVERGE).parameters(new SshParameters("ssh comment")); - DocumentContext json = toJsonPath(requestBuilder); + DocumentContext json = toJsonPath(this.requestBuilder); assertCommonRequestFields(json, true, WriteMode.CONVERGE, "/example/credential", "ssh"); - assertThat(json).hasNoPath("$.parameters.key_length"); - assertThat(json).hasPath("$.parameters.ssh_comment").isEqualTo("ssh comment"); + JsonPathAssert.assertThat(json).hasNoPath("$.parameters.key_length"); + JsonPathAssert.assertThat(json).hasPath("$.parameters.ssh_comment").isEqualTo("ssh comment"); } @Test public void serializeWithNoParameters() { - requestBuilder = SshParametersRequest.builder() - .name(new SimpleCredentialName("example", "credential")) - .overwrite(true) - .mode(WriteMode.OVERWRITE); + this.requestBuilder = SshParametersRequest.builder().name(new SimpleCredentialName("example", "credential")) + .overwrite(true).mode(WriteMode.OVERWRITE); - DocumentContext json = toJsonPath(requestBuilder); + DocumentContext json = toJsonPath(this.requestBuilder); assertCommonRequestFields(json, true, WriteMode.OVERWRITE, "/example/credential", "ssh"); - assertThat(json).hasNoPath("$.parameters.key_length"); - assertThat(json).hasNoPath("$.parameters.ssh_comment"); + JsonPathAssert.assertThat(json).hasNoPath("$.parameters.key_length"); + JsonPathAssert.assertThat(json).hasNoPath("$.parameters.ssh_comment"); } -} \ No newline at end of file + +} diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/support/user/UserCredentialDetailsUnitTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/support/user/UserCredentialDetailsUnitTests.java index 2bed495..7c81451 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/support/user/UserCredentialDetailsUnitTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/support/user/UserCredentialDetailsUnitTests.java @@ -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,13 +26,16 @@ import org.springframework.credhub.support.JsonParsingUnitTestsBase; import static org.assertj.core.api.Assertions.assertThat; public class UserCredentialDetailsUnitTests extends JsonParsingUnitTestsBase { + + // @formatter:off private static final String USER_CREDENTIALS = " \"type\": \"user\"," + " \"value\": {" + - " \"username\": \"myname\"," + - " \"password\": \"secret\"," + - " \"password_hash\": \"secret-hash\"" + + " \"username\": \"myname\"," + + " \"password\": \"secret\"," + + " \"password_hash\": \"secret-hash\"" + " }"; + // @formatter:on @Test public void deserializeDetails() { @@ -54,10 +57,11 @@ public class UserCredentialDetailsUnitTests extends JsonParsingUnitTestsBase { private void assertDetails(CredentialDetails data) { assertCommonDetails(data); - + assertThat(data.getCredentialType()).isEqualTo(CredentialType.USER); assertThat(data.getValue().getUsername()).isEqualTo("myname"); assertThat(data.getValue().getPassword()).isEqualTo("secret"); assertThat(data.getValue().getPasswordHash()).isEqualTo("secret-hash"); } + } diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/support/user/UserCredentialRequestUnitTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/support/user/UserCredentialRequestUnitTests.java index 1a2861b..f3c320f 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/support/user/UserCredentialRequestUnitTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/support/user/UserCredentialRequestUnitTests.java @@ -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,31 +21,28 @@ import org.junit.Before; import org.junit.Test; import org.springframework.credhub.support.CredHubRequestUnitTestsBase; +import org.springframework.credhub.support.JsonPathAssert; import org.springframework.credhub.support.SimpleCredentialName; import org.springframework.credhub.support.WriteMode; import org.springframework.credhub.support.user.UserCredentialRequest.UserCredentialRequestBuilder; -import static org.springframework.credhub.support.JsonPathAssert.assertThat; - @SuppressWarnings("deprecation") public class UserCredentialRequestUnitTests extends CredHubRequestUnitTestsBase { + @Before public void setUp() { - requestBuilder = UserCredentialRequest.builder() - .name(new SimpleCredentialName("example", "credential")) - .overwrite(true) - .mode(WriteMode.OVERWRITE) - .value(new UserCredential("myname", "secret")); + this.requestBuilder = UserCredentialRequest.builder().name(new SimpleCredentialName("example", "credential")) + .overwrite(true).mode(WriteMode.OVERWRITE).value(new UserCredential("myname", "secret")); } @Test public void serializeWithUsernameAndPassword() { - DocumentContext json = toJsonPath(requestBuilder); + DocumentContext json = toJsonPath(this.requestBuilder); assertCommonRequestFields(json, true, WriteMode.OVERWRITE, "/example/credential", "user"); - assertThat(json).hasPath("$.value.username").isEqualTo("myname"); - assertThat(json).hasPath("$.value.password").isEqualTo("secret"); - assertThat(json).hasNoPath("$.value.password_hash"); + JsonPathAssert.assertThat(json).hasPath("$.value.username").isEqualTo("myname"); + JsonPathAssert.assertThat(json).hasPath("$.value.password").isEqualTo("secret"); + JsonPathAssert.assertThat(json).hasNoPath("$.value.password_hash"); assertNoPermissions(json); } @@ -53,18 +50,17 @@ public class UserCredentialRequestUnitTests extends CredHubRequestUnitTestsBase @Test public void serializeWithPassword() { UserCredentialRequestBuilder builder = UserCredentialRequest.builder() - .name(new SimpleCredentialName("example", "credential")) - .overwrite(true) - .mode(WriteMode.OVERWRITE) + .name(new SimpleCredentialName("example", "credential")).overwrite(true).mode(WriteMode.OVERWRITE) .value(new UserCredential("secret")); DocumentContext json = toJsonPath(builder); assertCommonRequestFields(json, true, WriteMode.OVERWRITE, "/example/credential", "user"); - assertThat(json).hasNoPath("$.value.username"); - assertThat(json).hasPath("$.value.password").isEqualTo("secret"); - assertThat(json).hasNoPath("$.value.password_hash"); + JsonPathAssert.assertThat(json).hasNoPath("$.value.username"); + JsonPathAssert.assertThat(json).hasPath("$.value.password").isEqualTo("secret"); + JsonPathAssert.assertThat(json).hasNoPath("$.value.password_hash"); assertNoPermissions(json); } -} \ No newline at end of file + +} diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/support/user/UserParametersRequestUnitTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/support/user/UserParametersRequestUnitTests.java index ce08216..b7b71bf 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/support/user/UserParametersRequestUnitTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/support/user/UserParametersRequestUnitTests.java @@ -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,54 +21,43 @@ import org.junit.Before; import org.junit.Test; import org.springframework.credhub.support.CredHubRequestUnitTestsBase; +import org.springframework.credhub.support.JsonPathAssert; import org.springframework.credhub.support.SimpleCredentialName; import org.springframework.credhub.support.WriteMode; import org.springframework.credhub.support.password.PasswordParameters; -import static org.springframework.credhub.support.JsonPathAssert.assertThat; - @SuppressWarnings("deprecation") public class UserParametersRequestUnitTests extends CredHubRequestUnitTestsBase { + @Before public void setUp() { - requestBuilder = UserParametersRequest.builder(); + this.requestBuilder = UserParametersRequest.builder(); } @Test public void serializeWithParameters() { - requestBuilder = UserParametersRequest.builder() - .name(new SimpleCredentialName("example", "credential")) - .overwrite(true) - .mode(WriteMode.OVERWRITE) - .username("user") - .parameters(PasswordParameters.builder() - .length(20) - .excludeLower(true) - .excludeUpper(false) - .excludeNumber(true) - .includeSpecial(false) - .build()); + this.requestBuilder = UserParametersRequest.builder().name(new SimpleCredentialName("example", "credential")) + .overwrite(true).mode(WriteMode.OVERWRITE).username("user") + .parameters(PasswordParameters.builder().length(20).excludeLower(true).excludeUpper(false) + .excludeNumber(true).includeSpecial(false).build()); - DocumentContext json = toJsonPath(requestBuilder); + DocumentContext json = toJsonPath(this.requestBuilder); assertCommonRequestFields(json, true, WriteMode.OVERWRITE, "/example/credential", "user"); - assertThat(json).hasPath("$.value.username").isEqualTo("user"); - assertThat(json).hasPath("$.parameters.length").isEqualTo(20); - assertThat(json).hasPath("$.parameters.exclude_lower").isEqualTo(true); - assertThat(json).hasPath("$.parameters.exclude_upper").isEqualTo(false); - assertThat(json).hasPath("$.parameters.exclude_number").isEqualTo(true); - assertThat(json).hasPath("$.parameters.include_special").isEqualTo(false); + JsonPathAssert.assertThat(json).hasPath("$.value.username").isEqualTo("user"); + JsonPathAssert.assertThat(json).hasPath("$.parameters.length").isEqualTo(20); + JsonPathAssert.assertThat(json).hasPath("$.parameters.exclude_lower").isEqualTo(true); + JsonPathAssert.assertThat(json).hasPath("$.parameters.exclude_upper").isEqualTo(false); + JsonPathAssert.assertThat(json).hasPath("$.parameters.exclude_number").isEqualTo(true); + JsonPathAssert.assertThat(json).hasPath("$.parameters.include_special").isEqualTo(false); } @Test public void serializeWithEmptyParameters() { - requestBuilder = UserParametersRequest.builder() - .name(new SimpleCredentialName("example", "credential")) - .overwrite(true) - .mode(WriteMode.NO_OVERWRITE) - .parameters(new PasswordParameters()); + this.requestBuilder = UserParametersRequest.builder().name(new SimpleCredentialName("example", "credential")) + .overwrite(true).mode(WriteMode.NO_OVERWRITE).parameters(new PasswordParameters()); - DocumentContext json = toJsonPath(requestBuilder); + DocumentContext json = toJsonPath(this.requestBuilder); assertCommonRequestFields(json, true, WriteMode.NO_OVERWRITE, "/example/credential", "user"); assertParametersNotSet(json); @@ -76,23 +65,22 @@ public class UserParametersRequestUnitTests extends CredHubRequestUnitTestsBase @Test public void serializeWithNoParameters() { - requestBuilder = UserParametersRequest.builder() - .name(new SimpleCredentialName("example", "credential")) - .overwrite(true) - .mode(WriteMode.CONVERGE); + this.requestBuilder = UserParametersRequest.builder().name(new SimpleCredentialName("example", "credential")) + .overwrite(true).mode(WriteMode.CONVERGE); - DocumentContext json = toJsonPath(requestBuilder); + DocumentContext json = toJsonPath(this.requestBuilder); assertCommonRequestFields(json, true, WriteMode.CONVERGE, "/example/credential", "user"); assertParametersNotSet(json); } private void assertParametersNotSet(DocumentContext json) { - assertThat(json).hasNoPath("$.value.username"); - assertThat(json).hasNoPath("$.parameters.length"); - assertThat(json).hasNoPath("$.parameters.exclude_lower"); - assertThat(json).hasNoPath("$.parameters.exclude_upper"); - assertThat(json).hasNoPath("$.parameters.exclude_number"); - assertThat(json).hasNoPath("$.parameters.include_special"); + JsonPathAssert.assertThat(json).hasNoPath("$.value.username"); + JsonPathAssert.assertThat(json).hasNoPath("$.parameters.length"); + JsonPathAssert.assertThat(json).hasNoPath("$.parameters.exclude_lower"); + JsonPathAssert.assertThat(json).hasNoPath("$.parameters.exclude_upper"); + JsonPathAssert.assertThat(json).hasNoPath("$.parameters.exclude_number"); + JsonPathAssert.assertThat(json).hasNoPath("$.parameters.include_special"); } -} \ No newline at end of file + +} diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/support/value/ValueCredentialDetailsUnitTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/support/value/ValueCredentialDetailsUnitTests.java index a6e2053..f4473e3 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/support/value/ValueCredentialDetailsUnitTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/support/value/ValueCredentialDetailsUnitTests.java @@ -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,22 +26,23 @@ import org.springframework.credhub.support.JsonParsingUnitTestsBase; import static org.assertj.core.api.Assertions.assertThat; public class ValueCredentialDetailsUnitTests extends JsonParsingUnitTestsBase { + + // @formatter:off private static final String VALUE_CREDENTIALS = " \"type\": \"value\"," + " \"value\": \"somevalue\""; + // @formatter:on @Test public void deserializeDetails() { - CredentialDetails data = - parseDetails(VALUE_CREDENTIALS); + CredentialDetails data = parseDetails(VALUE_CREDENTIALS); assertDetails(data); } @Test public void deserializeDetailsData() { - CredentialDetailsData response = - parseDetailsData(VALUE_CREDENTIALS); + CredentialDetailsData response = parseDetailsData(VALUE_CREDENTIALS); assertThat(response.getData()).hasSize(1); @@ -52,8 +53,9 @@ public class ValueCredentialDetailsUnitTests extends JsonParsingUnitTestsBase { private void assertDetails(CredentialDetails data) { assertCommonDetails(data); - + assertThat(data.getCredentialType()).isEqualTo(CredentialType.VALUE); assertThat(data.getValue().getValue()).isEqualTo("somevalue"); } + } diff --git a/spring-credhub-core/src/test/java/org/springframework/credhub/support/value/ValueCredentialRequestUnitTests.java b/spring-credhub-core/src/test/java/org/springframework/credhub/support/value/ValueCredentialRequestUnitTests.java index 704392e..6f17a5d 100644 --- a/spring-credhub-core/src/test/java/org/springframework/credhub/support/value/ValueCredentialRequestUnitTests.java +++ b/spring-credhub-core/src/test/java/org/springframework/credhub/support/value/ValueCredentialRequestUnitTests.java @@ -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,29 +21,26 @@ import org.junit.Before; import org.junit.Test; import org.springframework.credhub.support.CredHubRequestUnitTestsBase; +import org.springframework.credhub.support.JsonPathAssert; import org.springframework.credhub.support.SimpleCredentialName; -import static org.springframework.credhub.support.JsonPathAssert.assertThat; - public class ValueCredentialRequestUnitTests extends CredHubRequestUnitTestsBase { @Before @SuppressWarnings("deprecation") public void setUp() { - requestBuilder = ValueCredentialRequest.builder() - .name(new SimpleCredentialName("example", "credential")) - .overwrite(true) - .value(new ValueCredential("somevalue")); + this.requestBuilder = ValueCredentialRequest.builder().name(new SimpleCredentialName("example", "credential")) + .overwrite(true).value(new ValueCredential("somevalue")); } @Test public void serializeWithValue() { - DocumentContext json = toJsonPath(requestBuilder); + DocumentContext json = toJsonPath(this.requestBuilder); - assertThat(json).hasPath("$.overwrite").isEqualTo(true); - assertThat(json).hasPath("$.name").isEqualTo("/example/credential"); - assertThat(json).hasPath("$.type").isEqualTo("value"); - assertThat(json).hasPath("$.value").isEqualTo("somevalue"); + JsonPathAssert.assertThat(json).hasPath("$.overwrite").isEqualTo(true); + JsonPathAssert.assertThat(json).hasPath("$.name").isEqualTo("/example/credential"); + JsonPathAssert.assertThat(json).hasPath("$.type").isEqualTo("value"); + JsonPathAssert.assertThat(json).hasPath("$.value").isEqualTo("somevalue"); assertNoPermissions(json); } @@ -51,18 +48,17 @@ public class ValueCredentialRequestUnitTests extends CredHubRequestUnitTestsBase @Test @SuppressWarnings("deprecation") public void serializeWithStringValue() { - requestBuilder = ValueCredentialRequest.builder() - .name(new SimpleCredentialName("example", "credential")) - .overwrite(true) - .value("somevalue"); + this.requestBuilder = ValueCredentialRequest.builder().name(new SimpleCredentialName("example", "credential")) + .overwrite(true).value("somevalue"); - DocumentContext json = toJsonPath(requestBuilder); + DocumentContext json = toJsonPath(this.requestBuilder); - assertThat(json).hasPath("$.overwrite").isEqualTo(true); - assertThat(json).hasPath("$.name").isEqualTo("/example/credential"); - assertThat(json).hasPath("$.type").isEqualTo("value"); - assertThat(json).hasPath("$.value").isEqualTo("somevalue"); + JsonPathAssert.assertThat(json).hasPath("$.overwrite").isEqualTo(true); + JsonPathAssert.assertThat(json).hasPath("$.name").isEqualTo("/example/credential"); + JsonPathAssert.assertThat(json).hasPath("$.type").isEqualTo("value"); + JsonPathAssert.assertThat(json).hasPath("$.value").isEqualTo("somevalue"); assertNoPermissions(json); } -} \ No newline at end of file + +} diff --git a/spring-credhub-demo/build.gradle b/spring-credhub-demo/build.gradle index 4281385..989110b 100644 --- a/spring-credhub-demo/build.gradle +++ b/spring-credhub-demo/build.gradle @@ -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, diff --git a/spring-credhub-demo/settings.gradle b/spring-credhub-demo/settings.gradle index e69de29..995478f 100644 --- a/spring-credhub-demo/settings.gradle +++ b/spring-credhub-demo/settings.gradle @@ -0,0 +1,16 @@ +/* + * 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. + */ + diff --git a/spring-credhub-demo/src/main/java/org/springframework/credhub/demo/Application.java b/spring-credhub-demo/src/main/java/org/springframework/credhub/demo/Application.java index cb1b225..caa4d8b 100644 --- a/spring-credhub-demo/src/main/java/org/springframework/credhub/demo/Application.java +++ b/spring-credhub-demo/src/main/java/org/springframework/credhub/demo/Application.java @@ -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, diff --git a/spring-credhub-demo/src/main/java/org/springframework/credhub/demo/CredHubDemoController.java b/spring-credhub-demo/src/main/java/org/springframework/credhub/demo/CredHubDemoController.java index a4ed98a..5b2f679 100644 --- a/spring-credhub-demo/src/main/java/org/springframework/credhub/demo/CredHubDemoController.java +++ b/spring-credhub-demo/src/main/java/org/springframework/credhub/demo/CredHubDemoController.java @@ -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, diff --git a/spring-credhub-docs/build.gradle b/spring-credhub-docs/build.gradle index 0b537d9..06bee00 100644 --- a/spring-credhub-docs/build.gradle +++ b/spring-credhub-docs/build.gradle @@ -1,11 +1,11 @@ /* - * Copyright 2016-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. * 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, diff --git a/spring-credhub-docs/src/test/java/com/example/credhub/CredHubService.java b/spring-credhub-docs/src/test/java/com/example/credhub/CredHubService.java index cd2f475..7aebf26 100644 --- a/spring-credhub-docs/src/test/java/com/example/credhub/CredHubService.java +++ b/spring-credhub-docs/src/test/java/com/example/credhub/CredHubService.java @@ -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 com.example.credhub; import org.springframework.credhub.core.CredHubOperations; @@ -10,37 +26,32 @@ import org.springframework.stereotype.Component; @Component public class CredHubService { + private final CredHubOperations credHubOperations; + private final SimpleCredentialName credentialName; public CredHubService(CredHubOperations credHubOperations) { this.credHubOperations = credHubOperations; - credentialName = new SimpleCredentialName("example", "password"); + this.credentialName = new SimpleCredentialName("example", "password"); } public String generatePassword() { - PasswordParameters parameters = PasswordParameters.builder() - .length(12) - .excludeLower(false) - .excludeUpper(false) - .excludeNumber(false) - .includeSpecial(true) - .build(); - - CredentialDetails password = credHubOperations.credentials() - .generate(PasswordParametersRequest.builder() - .name(credentialName) - .parameters(parameters) - .build()); + PasswordParameters parameters = PasswordParameters.builder().length(12).excludeLower(false).excludeUpper(false) + .excludeNumber(false).includeSpecial(true).build(); + + CredentialDetails password = this.credHubOperations.credentials() + .generate(PasswordParametersRequest.builder().name(this.credentialName).parameters(parameters).build()); return password.getValue().getPassword(); } public String getPassword() { - CredentialDetails password = credHubOperations.credentials() - .getByName(credentialName, PasswordCredential.class); + CredentialDetails password = this.credHubOperations.credentials() + .getByName(this.credentialName, PasswordCredential.class); return password.getValue().getPassword(); } + } diff --git a/spring-credhub-docs/src/test/java/com/example/credhub/ReactiveCredHubService.java b/spring-credhub-docs/src/test/java/com/example/credhub/ReactiveCredHubService.java index f60d3a1..6280a57 100644 --- a/spring-credhub-docs/src/test/java/com/example/credhub/ReactiveCredHubService.java +++ b/spring-credhub-docs/src/test/java/com/example/credhub/ReactiveCredHubService.java @@ -1,45 +1,56 @@ +/* + * 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 com.example.credhub; +import reactor.core.publisher.Mono; + import org.springframework.credhub.core.ReactiveCredHubOperations; import org.springframework.credhub.support.SimpleCredentialName; import org.springframework.credhub.support.password.PasswordCredential; import org.springframework.credhub.support.password.PasswordParameters; import org.springframework.credhub.support.password.PasswordParametersRequest; import org.springframework.stereotype.Component; -import reactor.core.publisher.Mono; @Component public class ReactiveCredHubService { + private final ReactiveCredHubOperations credHubOperations; + private final SimpleCredentialName credentialName; public ReactiveCredHubService(ReactiveCredHubOperations credHubOperations) { this.credHubOperations = credHubOperations; - credentialName = new SimpleCredentialName("example", "password"); + this.credentialName = new SimpleCredentialName("example", "password"); } public Mono generatePassword() { - PasswordParameters parameters = PasswordParameters.builder() - .length(12) - .excludeLower(false) - .excludeUpper(false) - .excludeNumber(false) - .includeSpecial(true) - .build(); + PasswordParameters parameters = PasswordParameters.builder().length(12).excludeLower(false).excludeUpper(false) + .excludeNumber(false).includeSpecial(true).build(); - return credHubOperations.credentials() - .generate(PasswordParametersRequest.builder() - .name(credentialName) - .parameters(parameters) - .build(), + return this.credHubOperations.credentials() + .generate(PasswordParametersRequest.builder().name(this.credentialName).parameters(parameters).build(), PasswordCredential.class) - .map(password -> password.getValue().getPassword()); + .map((password) -> password.getValue().getPassword()); } public Mono getPassword() { - return credHubOperations.credentials() - .getByName(credentialName, PasswordCredential.class) - .map(password -> password.getValue().getPassword()); + return this.credHubOperations.credentials().getByName(this.credentialName, PasswordCredential.class) + .map((password) -> password.getValue().getPassword()); } + } diff --git a/spring-credhub-integration-tests/build.gradle b/spring-credhub-integration-tests/build.gradle index f07e87a..5c5ea6a 100644 --- a/spring-credhub-integration-tests/build.gradle +++ b/spring-credhub-integration-tests/build.gradle @@ -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, diff --git a/spring-credhub-integration-tests/src/test/java/org/springframework/credhub/integration/CertificateIntegrationTests.java b/spring-credhub-integration-tests/src/test/java/org/springframework/credhub/integration/CertificateIntegrationTests.java index 1c3f22d..511a65a 100644 --- a/spring-credhub-integration-tests/src/test/java/org/springframework/credhub/integration/CertificateIntegrationTests.java +++ b/spring-credhub-integration-tests/src/test/java/org/springframework/credhub/integration/CertificateIntegrationTests.java @@ -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,40 +16,43 @@ package org.springframework.credhub.integration; +import java.util.List; + import org.junit.After; import org.junit.Before; import org.junit.Test; + import org.springframework.credhub.core.certificate.CredHubCertificateOperations; import org.springframework.credhub.core.credential.CredHubCredentialOperations; -import org.springframework.credhub.support.CredentialName; -import org.springframework.credhub.support.certificate.CertificateSummary; import org.springframework.credhub.support.CredentialDetails; +import org.springframework.credhub.support.CredentialName; import org.springframework.credhub.support.CredentialType; import org.springframework.credhub.support.SimpleCredentialName; import org.springframework.credhub.support.certificate.CertificateCredential; import org.springframework.credhub.support.certificate.CertificateCredentialDetails; import org.springframework.credhub.support.certificate.CertificateParameters; import org.springframework.credhub.support.certificate.CertificateParametersRequest; - - -import java.util.List; +import org.springframework.credhub.support.certificate.CertificateSummary; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assume.assumeTrue; public class CertificateIntegrationTests extends CredHubIntegrationTests { - private static final SimpleCredentialName TEST_CERT_NAME = - new SimpleCredentialName("spring-credhub", "integration-test", "test-certificate"); - private static final SimpleCredentialName ROOT_CERT_NAME = - new SimpleCredentialName("spring-credhub", "integration-test", "root-certificate"); + + private static final SimpleCredentialName TEST_CERT_NAME = new SimpleCredentialName("spring-credhub", + "integration-test", "test-certificate"); + + private static final SimpleCredentialName ROOT_CERT_NAME = new SimpleCredentialName("spring-credhub", + "integration-test", "root-certificate"); private CredHubCredentialOperations credentials; + private CredHubCertificateOperations certificates; @Before public void setUp() { - credentials = operations.credentials(); - certificates = operations.certificates(); + this.credentials = this.operations.credentials(); + this.certificates = this.operations.certificates(); deleteCredentialIfExists(TEST_CERT_NAME); deleteCredentialIfExists(ROOT_CERT_NAME); @@ -65,14 +68,9 @@ public class CertificateIntegrationTests extends CredHubIntegrationTests { public void generateCertificate() { assumeTrue(serverApiIsV2()); - CredentialDetails certificate = - credentials.generate(CertificateParametersRequest.builder() - .name(TEST_CERT_NAME) - .parameters(CertificateParameters.builder() - .commonName("example.com") - .selfSign(true) - .build()) - .build()); + CredentialDetails certificate = this.credentials.generate(CertificateParametersRequest + .builder().name(TEST_CERT_NAME) + .parameters(CertificateParameters.builder().commonName("example.com").selfSign(true).build()).build()); assertThat(certificate.getName().getName()).isEqualTo(TEST_CERT_NAME.getName()); assertThat(certificate.getCredentialType()).isEqualTo(CredentialType.CERTIFICATE); assertThat(certificate.getId()).isNotNull(); @@ -80,11 +78,11 @@ public class CertificateIntegrationTests extends CredHubIntegrationTests { assertThat(certificate.getValue().getCertificateAuthority()).isNotNull(); assertThat(certificate.getValue().getPrivateKey()).isNotNull(); - CertificateSummary byName = certificates.getByName(TEST_CERT_NAME); + CertificateSummary byName = this.certificates.getByName(TEST_CERT_NAME); assertThat(byName.getName()).isEqualTo(TEST_CERT_NAME.getName()); assertThat(byName.getId()).isNotNull(); - List allCertificates = certificates.getAll(); + List allCertificates = this.certificates.getAll(); assertThat(allCertificates.size()).isGreaterThan(0); assertThat(allCertificates).extracting("name").contains(TEST_CERT_NAME.getName()); } @@ -93,75 +91,61 @@ public class CertificateIntegrationTests extends CredHubIntegrationTests { public void regenerateCertificate() { assumeTrue(serverApiIsV2()); - CredentialDetails certificate = - credentials.generate(CertificateParametersRequest.builder() - .name(TEST_CERT_NAME) - .parameters(CertificateParameters.builder() - .commonName("example.com") - .selfSign(true) - .build()) - .build()); + CredentialDetails certificate = this.credentials.generate(CertificateParametersRequest + .builder().name(TEST_CERT_NAME) + .parameters(CertificateParameters.builder().commonName("example.com").selfSign(true).build()).build()); assertThat(certificate.getName().getName()).isEqualTo(TEST_CERT_NAME.getName()); - CertificateSummary byName = certificates.getByName(TEST_CERT_NAME); + CertificateSummary byName = this.certificates.getByName(TEST_CERT_NAME); - CertificateCredentialDetails regenerated = certificates.regenerate(byName.getId(), true); + CertificateCredentialDetails regenerated = this.certificates.regenerate(byName.getId(), true); assertThat(regenerated.getName().getName()).isEqualTo(TEST_CERT_NAME.getName()); assertThat(regenerated.isTransitional()).isTrue(); - assertThat(regenerated.getValue().getCertificate()) - .isNotEqualTo(certificate.getValue().getCertificate()); + assertThat(regenerated.getValue().getCertificate()).isNotEqualTo(certificate.getValue().getCertificate()); assertThat(regenerated.getValue().getCertificateAuthority()) .isNotEqualTo(certificate.getValue().getCertificateAuthority()); - assertThat(regenerated.getValue().getPrivateKey()) - .isNotEqualTo(certificate.getValue().getPrivateKey()); + assertThat(regenerated.getValue().getPrivateKey()).isNotEqualTo(certificate.getValue().getPrivateKey()); } @Test public void rotateCertificate() { assumeTrue(serverApiIsV2()); - CredentialDetails certificate = - credentials.generate(CertificateParametersRequest.builder() - .name(TEST_CERT_NAME) - .parameters(CertificateParameters.builder() - .commonName("example.com") - .selfSign(true) - .build()) - .build()); + CredentialDetails certificate = this.credentials.generate(CertificateParametersRequest + .builder().name(TEST_CERT_NAME) + .parameters(CertificateParameters.builder().commonName("example.com").selfSign(true).build()).build()); assertThat(certificate.getName().getName()).isEqualTo(TEST_CERT_NAME.getName()); String credentialVersion0Id = certificate.getId(); - List> allVersions = - credentials.getByNameWithHistory(TEST_CERT_NAME, CertificateCredential.class); + List> allVersions = this.credentials + .getByNameWithHistory(TEST_CERT_NAME, CertificateCredential.class); assertThat(allVersions).hasSize(1); assertThat(allVersions.get(0).getId()).isEqualTo(credentialVersion0Id); - CertificateSummary byName = certificates.getByName(TEST_CERT_NAME); + CertificateSummary byName = this.certificates.getByName(TEST_CERT_NAME); String certificateId = byName.getId(); - CertificateCredentialDetails regenerated = certificates.regenerate(certificateId, true); + CertificateCredentialDetails regenerated = this.certificates.regenerate(certificateId, true); assertThat(regenerated.getName().getName()).isEqualTo(TEST_CERT_NAME.getName()); - assertThat(regenerated.getValue().getCertificate()) - .isNotEqualTo(certificate.getValue().getCertificate()); + assertThat(regenerated.getValue().getCertificate()).isNotEqualTo(certificate.getValue().getCertificate()); assertThat(regenerated.getValue().getCertificateAuthority()) .isNotEqualTo(certificate.getValue().getCertificateAuthority()); - assertThat(regenerated.getValue().getPrivateKey()) - .isNotEqualTo(certificate.getValue().getPrivateKey()); + assertThat(regenerated.getValue().getPrivateKey()).isNotEqualTo(certificate.getValue().getPrivateKey()); String credentialVersion1Id = regenerated.getId(); - allVersions = credentials.getByNameWithHistory(TEST_CERT_NAME, CertificateCredential.class); + allVersions = this.credentials.getByNameWithHistory(TEST_CERT_NAME, CertificateCredential.class); assertThat(allVersions).hasSize(2); assertThat(allVersions).extracting("id").contains(credentialVersion1Id, credentialVersion0Id); - List updatedCertificate = - certificates.updateTransitionalVersion(certificateId, credentialVersion0Id); + List updatedCertificate = this.certificates + .updateTransitionalVersion(certificateId, credentialVersion0Id); assertThat(updatedCertificate).hasSize(2); assertThat(updatedCertificate).extracting("id").contains(credentialVersion1Id, credentialVersion0Id); assertThat(updatedCertificate).extracting("transitional").contains(false, true); - updatedCertificate = certificates.updateTransitionalVersion(certificateId, null); + updatedCertificate = this.certificates.updateTransitionalVersion(certificateId, null); assertThat(updatedCertificate).hasSize(1); assertThat(updatedCertificate).extracting("id").contains(credentialVersion1Id); assertThat(updatedCertificate).extracting("transitional").contains(false); @@ -169,34 +153,29 @@ public class CertificateIntegrationTests extends CredHubIntegrationTests { @Test public void bulkRegenerateCertificates() { - CredentialDetails rootCertificate = - credentials.generate(CertificateParametersRequest.builder() - .name(ROOT_CERT_NAME) - .parameters(CertificateParameters.builder() - .commonName("example.com") - .certificateAuthority(true) - .selfSign(true) - .build()) - .build()); + CredentialDetails rootCertificate = this.credentials + .generate( + CertificateParametersRequest + .builder().name(ROOT_CERT_NAME).parameters(CertificateParameters.builder() + .commonName("example.com").certificateAuthority(true).selfSign(true).build()) + .build()); - CredentialDetails signedCertificate = - credentials.generate(CertificateParametersRequest.builder() - .name(TEST_CERT_NAME) - .parameters(CertificateParameters.builder() - .commonName("example.com") - .certificateAuthorityCredential(ROOT_CERT_NAME) - .build()) + CredentialDetails signedCertificate = this.credentials + .generate(CertificateParametersRequest + .builder().name(TEST_CERT_NAME).parameters(CertificateParameters.builder() + .commonName("example.com").certificateAuthorityCredential(ROOT_CERT_NAME).build()) .build()); assertThat(signedCertificate.getValue().getCertificateAuthority()) .isEqualTo(rootCertificate.getValue().getCertificate()); - List> allVersions = - credentials.getByNameWithHistory(TEST_CERT_NAME, CertificateCredential.class); + List> allVersions = this.credentials + .getByNameWithHistory(TEST_CERT_NAME, CertificateCredential.class); assertThat(allVersions).hasSize(1); assertThat(allVersions.get(0).getId()).isEqualTo(signedCertificate.getId()); - List regeneratedNames = certificates.regenerate(ROOT_CERT_NAME); + List regeneratedNames = this.certificates.regenerate(ROOT_CERT_NAME); assertThat(regeneratedNames).hasSize(1); assertThat(regeneratedNames).contains(TEST_CERT_NAME); } + } diff --git a/spring-credhub-integration-tests/src/test/java/org/springframework/credhub/integration/CredHubIntegrationTests.java b/spring-credhub-integration-tests/src/test/java/org/springframework/credhub/integration/CredHubIntegrationTests.java index 85c7df2..447c094 100644 --- a/spring-credhub-integration-tests/src/test/java/org/springframework/credhub/integration/CredHubIntegrationTests.java +++ b/spring-credhub-integration-tests/src/test/java/org/springframework/credhub/integration/CredHubIntegrationTests.java @@ -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. @@ -17,6 +17,7 @@ package org.springframework.credhub.integration; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.credhub.core.CredHubException; @@ -26,7 +27,7 @@ import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) -@SpringBootTest(classes = {TestApplication.class}) +@SpringBootTest(classes = { TestApplication.class }) @ActiveProfiles("test") public abstract class CredHubIntegrationTests { @@ -34,18 +35,20 @@ public abstract class CredHubIntegrationTests { protected CredHubOperations operations; boolean serverApiIsV1() { - return operations.info().version().isVersion1(); + return this.operations.info().version().isVersion1(); } boolean serverApiIsV2() { - return operations.info().version().isVersion2(); + return this.operations.info().version().isVersion2(); } void deleteCredentialIfExists(CredentialName credentialName) { try { - operations.credentials().deleteByName(credentialName); - } catch (CredHubException e) { + this.operations.credentials().deleteByName(credentialName); + } + catch (CredHubException ex) { // ignore failing deletes on cleanup } } + } diff --git a/spring-credhub-integration-tests/src/test/java/org/springframework/credhub/integration/CredentialIntegrationTests.java b/spring-credhub-integration-tests/src/test/java/org/springframework/credhub/integration/CredentialIntegrationTests.java index 6462d60..640f91c 100644 --- a/spring-credhub-integration-tests/src/test/java/org/springframework/credhub/integration/CredentialIntegrationTests.java +++ b/spring-credhub-integration-tests/src/test/java/org/springframework/credhub/integration/CredentialIntegrationTests.java @@ -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,12 @@ package org.springframework.credhub.integration; +import java.util.List; + import org.junit.After; import org.junit.Before; import org.junit.Test; + import org.springframework.credhub.core.credential.CredHubCredentialOperations; import org.springframework.credhub.support.CredentialDetails; import org.springframework.credhub.support.CredentialSummary; @@ -31,14 +34,14 @@ import org.springframework.credhub.support.user.UserParametersRequest; import org.springframework.credhub.support.value.ValueCredential; import org.springframework.credhub.support.value.ValueCredentialRequest; -import java.util.List; - import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assume.assumeTrue; public class CredentialIntegrationTests extends CredHubIntegrationTests { - private static final SimpleCredentialName CREDENTIAL_NAME = - new SimpleCredentialName("spring-credhub", "integration-test", "test-credential"); + + private static final SimpleCredentialName CREDENTIAL_NAME = new SimpleCredentialName("spring-credhub", + "integration-test", "test-credential"); + private static final String CREDENTIAL_VALUE = "test-value"; private CredHubCredentialOperations credentials; @@ -47,14 +50,10 @@ public class CredentialIntegrationTests extends CredHubIntegrationTests { @Before public void setUp() { - credentials = operations.credentials(); + this.credentials = this.operations.credentials(); - passwordParameters = PasswordParameters.builder() - .length(12) - .excludeLower(false) - .excludeUpper(false) - .excludeNumber(false) - .includeSpecial(true); + this.passwordParameters = PasswordParameters.builder().length(12).excludeLower(false).excludeUpper(false) + .excludeNumber(false).includeSpecial(true); deleteCredentialIfExists(CREDENTIAL_NAME); } @@ -63,36 +62,34 @@ public class CredentialIntegrationTests extends CredHubIntegrationTests { public void tearDown() { deleteCredentialIfExists(CREDENTIAL_NAME); - List afterDelete = credentials.findByName(CREDENTIAL_NAME); + List afterDelete = this.credentials.findByName(CREDENTIAL_NAME); assertThat(afterDelete).hasSize(0); } @Test public void writeCredential() { - CredentialDetails written = credentials.write(ValueCredentialRequest.builder() - .name(CREDENTIAL_NAME) - .value(CREDENTIAL_VALUE) - .build()); + CredentialDetails written = this.credentials + .write(ValueCredentialRequest.builder().name(CREDENTIAL_NAME).value(CREDENTIAL_VALUE).build()); assertThat(written.getName().getName()).isEqualTo(CREDENTIAL_NAME.getName()); assertThat(written.getValue().getValue()).isEqualTo(CREDENTIAL_VALUE); assertThat(written.getCredentialType()).isEqualTo(CredentialType.VALUE); assertThat(written.getId()).isNotNull(); - CredentialDetails byId = credentials.getById(written.getId(), ValueCredential.class); + CredentialDetails byId = this.credentials.getById(written.getId(), ValueCredential.class); assertThat(byId.getName().getName()).isEqualTo(CREDENTIAL_NAME.getName()); assertThat(byId.getValue().getValue()).isEqualTo(CREDENTIAL_VALUE); assertThat(byId.getCredentialType()).isEqualTo(CredentialType.VALUE); - CredentialDetails byName = credentials.getByName(CREDENTIAL_NAME, ValueCredential.class); + CredentialDetails byName = this.credentials.getByName(CREDENTIAL_NAME, ValueCredential.class); assertThat(byName.getName().getName()).isEqualTo(CREDENTIAL_NAME.getName()); assertThat(byName.getValue().getValue()).isEqualTo(CREDENTIAL_VALUE); assertThat(byName.getCredentialType()).isEqualTo(CredentialType.VALUE); - List foundByName = credentials.findByName(new SimpleCredentialName("/test")); + List foundByName = this.credentials.findByName(new SimpleCredentialName("/test")); assertThat(foundByName).hasSize(1); assertThat(foundByName).extracting("name").extracting("name").containsExactly(CREDENTIAL_NAME.getName()); - List foundByPath = credentials.findByPath("/spring-credhub/integration-test"); + List foundByPath = this.credentials.findByPath("/spring-credhub/integration-test"); assertThat(foundByPath).hasSize(1); assertThat(foundByPath).extracting("name").extracting("name").containsExactly(CREDENTIAL_NAME.getName()); } @@ -101,19 +98,15 @@ public class CredentialIntegrationTests extends CredHubIntegrationTests { public void overwriteCredentialV2() { assumeTrue(serverApiIsV2()); - CredentialDetails written = credentials.write(ValueCredentialRequest.builder() - .name(CREDENTIAL_NAME) - .value(CREDENTIAL_VALUE) - .build()); + CredentialDetails written = this.credentials + .write(ValueCredentialRequest.builder().name(CREDENTIAL_NAME).value(CREDENTIAL_VALUE).build()); assertThat(written.getName().getName()).isEqualTo(CREDENTIAL_NAME.getName()); assertThat(written.getValue().getValue()).isEqualTo(CREDENTIAL_VALUE); assertThat(written.getCredentialType()).isEqualTo(CredentialType.VALUE); assertThat(written.getId()).isNotNull(); - CredentialDetails overwritten = credentials.write(ValueCredentialRequest.builder() - .name(CREDENTIAL_NAME) - .value("new-value") - .build()); + CredentialDetails overwritten = this.credentials + .write(ValueCredentialRequest.builder().name(CREDENTIAL_NAME).value("new-value").build()); assertThat(overwritten.getName().getName()).isEqualTo(CREDENTIAL_NAME.getName()); assertThat(overwritten.getValue().getValue()).isEqualTo("new-value"); @@ -124,28 +117,20 @@ public class CredentialIntegrationTests extends CredHubIntegrationTests { public void overwriteCredentialV1() { assumeTrue(serverApiIsV1()); - CredentialDetails written = credentials.write(ValueCredentialRequest.builder() - .name(CREDENTIAL_NAME) - .value(CREDENTIAL_VALUE) - .build()); + CredentialDetails written = this.credentials + .write(ValueCredentialRequest.builder().name(CREDENTIAL_NAME).value(CREDENTIAL_VALUE).build()); assertThat(written.getName().getName()).isEqualTo(CREDENTIAL_NAME.getName()); assertThat(written.getValue().getValue()).isEqualTo(CREDENTIAL_VALUE); assertThat(written.getCredentialType()).isEqualTo(CredentialType.VALUE); assertThat(written.getId()).isNotNull(); - CredentialDetails overwritten = credentials.write(ValueCredentialRequest.builder() - .name(CREDENTIAL_NAME) - .value("new-value") - .mode(WriteMode.NO_OVERWRITE) - .build()); + CredentialDetails overwritten = this.credentials.write(ValueCredentialRequest.builder() + .name(CREDENTIAL_NAME).value("new-value").mode(WriteMode.NO_OVERWRITE).build()); assertThat(overwritten.getName().getName()).isEqualTo(CREDENTIAL_NAME.getName()); assertThat(overwritten.getValue().getValue()).isEqualTo(CREDENTIAL_VALUE); - overwritten = credentials.write(ValueCredentialRequest.builder() - .name(CREDENTIAL_NAME) - .value("new-value") - .mode(WriteMode.OVERWRITE) - .build()); + overwritten = this.credentials.write(ValueCredentialRequest.builder().name(CREDENTIAL_NAME).value("new-value") + .mode(WriteMode.OVERWRITE).build()); assertThat(overwritten.getName().getName()).isEqualTo(CREDENTIAL_NAME.getName()); assertThat(overwritten.getValue().getValue()).isEqualTo("new-value"); @@ -153,15 +138,15 @@ public class CredentialIntegrationTests extends CredHubIntegrationTests { } private void verifyHistory() { - List> history = - credentials.getByNameWithHistory(CREDENTIAL_NAME, ValueCredential.class); + List> history = this.credentials.getByNameWithHistory(CREDENTIAL_NAME, + ValueCredential.class); assertThat(history).hasSize(2); assertThat(history.get(0).getName()).isEqualTo(CREDENTIAL_NAME); assertThat(history.get(0).getValue().getValue()).isEqualTo("new-value"); assertThat(history.get(1).getName()).isEqualTo(CREDENTIAL_NAME); assertThat(history.get(1).getValue().getValue()).isEqualTo(CREDENTIAL_VALUE); - history = credentials.getByNameWithHistory(CREDENTIAL_NAME, 2, ValueCredential.class); + history = this.credentials.getByNameWithHistory(CREDENTIAL_NAME, 2, ValueCredential.class); assertThat(history).hasSize(2); assertThat(history.get(0).getName()).isEqualTo(CREDENTIAL_NAME); assertThat(history.get(0).getValue().getValue()).isEqualTo("new-value"); @@ -171,21 +156,19 @@ public class CredentialIntegrationTests extends CredHubIntegrationTests { @Test public void generateCredential() { - CredentialDetails generated = credentials.generate(UserParametersRequest.builder() - .name(CREDENTIAL_NAME) - .username("test-user") - .parameters(passwordParameters.build()) - .build()); + CredentialDetails generated = this.credentials.generate(UserParametersRequest.builder() + .name(CREDENTIAL_NAME).username("test-user").parameters(this.passwordParameters.build()).build()); assertThat(generated.getName().getName()).isEqualTo(CREDENTIAL_NAME.getName()); assertThat(generated.getCredentialType()).isEqualTo(CredentialType.USER); assertThat(generated.getValue().getUsername()).isEqualTo("test-user"); assertThat(generated.getValue().getPassword()).matches("^[a-zA-Z0-9\\p{Punct}]{12}$"); assertThat(generated.getValue().getPasswordHash()).isNotNull(); - CredentialDetails retrieved = credentials.getById(generated.getId(), UserCredential.class); + CredentialDetails retrieved = this.credentials.getById(generated.getId(), UserCredential.class); assertThat(retrieved.getName().getName()).isEqualTo(CREDENTIAL_NAME.getName()); - CredentialDetails regenerated = credentials.regenerate(CREDENTIAL_NAME, UserCredential.class); + CredentialDetails regenerated = this.credentials.regenerate(CREDENTIAL_NAME, + UserCredential.class); assertThat(regenerated.getName().getName()).isEqualTo(CREDENTIAL_NAME.getName()); assertThat(regenerated.getValue().getUsername()).isEqualTo("test-user"); assertThat(regenerated.getValue().getPassword()).matches("^[a-zA-Z0-9\\p{Punct}]{12}$"); @@ -195,22 +178,16 @@ public class CredentialIntegrationTests extends CredHubIntegrationTests { @Test public void generateNoOverwriteCredential() { - CredentialDetails generated = credentials.generate(UserParametersRequest.builder() - .name(CREDENTIAL_NAME) - .username("test-user") - .parameters(passwordParameters.build()) - .build()); + CredentialDetails generated = this.credentials.generate(UserParametersRequest.builder() + .name(CREDENTIAL_NAME).username("test-user").parameters(this.passwordParameters.build()).build()); assertThat(generated.getName().getName()).isEqualTo(CREDENTIAL_NAME.getName()); assertThat(generated.getValue().getUsername()).isEqualTo("test-user"); assertThat(generated.getValue().getPassword()).matches("^[a-zA-Z0-9\\p{Punct}]{12}$"); assertThat(generated.getValue().getPasswordHash()).isNotNull(); - CredentialDetails noOverwrite = credentials.generate(UserParametersRequest.builder() - .name(CREDENTIAL_NAME) - .mode(WriteMode.NO_OVERWRITE) - .username("test-user") - .parameters(passwordParameters.build()) - .build()); + CredentialDetails noOverwrite = this.credentials + .generate(UserParametersRequest.builder().name(CREDENTIAL_NAME).mode(WriteMode.NO_OVERWRITE) + .username("test-user").parameters(this.passwordParameters.build()).build()); assertThat(noOverwrite.getValue().getUsername()).isEqualTo("test-user"); assertThat(noOverwrite.getValue().getPassword()).isEqualTo(generated.getValue().getPassword()); assertThat(noOverwrite.getValue().getPasswordHash()).isEqualTo(generated.getValue().getPasswordHash()); @@ -218,22 +195,16 @@ public class CredentialIntegrationTests extends CredHubIntegrationTests { @Test public void generateOverwriteCredential() { - CredentialDetails generated = credentials.generate(UserParametersRequest.builder() - .name(CREDENTIAL_NAME) - .username("test-user") - .parameters(passwordParameters.build()) - .build()); + CredentialDetails generated = this.credentials.generate(UserParametersRequest.builder() + .name(CREDENTIAL_NAME).username("test-user").parameters(this.passwordParameters.build()).build()); assertThat(generated.getName().getName()).isEqualTo(CREDENTIAL_NAME.getName()); assertThat(generated.getValue().getUsername()).isEqualTo("test-user"); assertThat(generated.getValue().getPassword()).matches("^[a-zA-Z0-9\\p{Punct}]{12}$"); assertThat(generated.getValue().getPasswordHash()).isNotNull(); - CredentialDetails overwrite = credentials.generate(UserParametersRequest.builder() - .name(CREDENTIAL_NAME) - .mode(WriteMode.OVERWRITE) - .username("test-user") - .parameters(passwordParameters.build()) - .build()); + CredentialDetails overwrite = this.credentials + .generate(UserParametersRequest.builder().name(CREDENTIAL_NAME).mode(WriteMode.OVERWRITE) + .username("test-user").parameters(this.passwordParameters.build()).build()); assertThat(overwrite.getValue().getUsername()).isEqualTo("test-user"); assertThat(overwrite.getValue().getPassword()).isNotEqualTo(generated.getValue().getPassword()); assertThat(overwrite.getValue().getPasswordHash()).isNotEqualTo(generated.getValue().getPasswordHash()); @@ -241,41 +212,30 @@ public class CredentialIntegrationTests extends CredHubIntegrationTests { @Test public void generateConvergeCredential() { - CredentialDetails generated = credentials.generate(UserParametersRequest.builder() - .name(CREDENTIAL_NAME) - .username("test-user") - .parameters(passwordParameters.build()) - .build()); + CredentialDetails generated = this.credentials.generate(UserParametersRequest.builder() + .name(CREDENTIAL_NAME).username("test-user").parameters(this.passwordParameters.build()).build()); assertThat(generated.getName().getName()).isEqualTo(CREDENTIAL_NAME.getName()); assertThat(generated.getValue().getUsername()).isEqualTo("test-user"); assertThat(generated.getValue().getPassword()).matches("^[a-zA-Z0-9\\p{Punct}]{12}$"); assertThat(generated.getValue().getPasswordHash()).isNotNull(); - CredentialDetails convergeWithoutChanges = credentials.generate(UserParametersRequest.builder() - .name(CREDENTIAL_NAME) - .mode(WriteMode.CONVERGE) - .username("test-user") - .parameters(passwordParameters.build()) - .build()); + CredentialDetails convergeWithoutChanges = this.credentials + .generate(UserParametersRequest.builder().name(CREDENTIAL_NAME).mode(WriteMode.CONVERGE) + .username("test-user").parameters(this.passwordParameters.build()).build()); assertThat(convergeWithoutChanges.getValue().getUsername()).isEqualTo("test-user"); - assertThat(convergeWithoutChanges.getValue().getPassword()) - .isEqualTo(generated.getValue().getPassword()); + assertThat(convergeWithoutChanges.getValue().getPassword()).isEqualTo(generated.getValue().getPassword()); assertThat(convergeWithoutChanges.getValue().getPasswordHash()) .isEqualTo(generated.getValue().getPasswordHash()); - passwordParameters.includeSpecial(false); + this.passwordParameters.includeSpecial(false); - CredentialDetails convergeWithChanges = - credentials.generate(UserParametersRequest.builder() - .name(CREDENTIAL_NAME) - .mode(WriteMode.CONVERGE) - .username("test-user") - .parameters(passwordParameters.build()) - .build()); + CredentialDetails convergeWithChanges = this.credentials + .generate(UserParametersRequest.builder().name(CREDENTIAL_NAME).mode(WriteMode.CONVERGE) + .username("test-user").parameters(this.passwordParameters.build()).build()); assertThat(convergeWithChanges.getValue().getUsername()).isEqualTo("test-user"); - assertThat(convergeWithChanges.getValue().getPassword()) - .isNotEqualTo(generated.getValue().getPassword()); + assertThat(convergeWithChanges.getValue().getPassword()).isNotEqualTo(generated.getValue().getPassword()); assertThat(convergeWithChanges.getValue().getPasswordHash()) .isNotEqualTo(generated.getValue().getPasswordHash()); } + } diff --git a/spring-credhub-integration-tests/src/test/java/org/springframework/credhub/integration/InfoIntegrationTests.java b/spring-credhub-integration-tests/src/test/java/org/springframework/credhub/integration/InfoIntegrationTests.java index 89ec2ef..7f49603 100644 --- a/spring-credhub-integration-tests/src/test/java/org/springframework/credhub/integration/InfoIntegrationTests.java +++ b/spring-credhub-integration-tests/src/test/java/org/springframework/credhub/integration/InfoIntegrationTests.java @@ -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,23 +18,26 @@ package org.springframework.credhub.integration; import org.junit.Before; import org.junit.Test; + import org.springframework.credhub.core.info.CredHubInfoOperations; import org.springframework.credhub.support.info.VersionInfo; import static org.assertj.core.api.Assertions.assertThat; public class InfoIntegrationTests extends CredHubIntegrationTests { + private CredHubInfoOperations info; @Before public void setUp() { - info = operations.info(); + this.info = this.operations.info(); } - + @Test public void getInfo() { - VersionInfo version = info.version(); + VersionInfo version = this.info.version(); assertThat(version.getVersion()).isNotNull(); } + } diff --git a/spring-credhub-integration-tests/src/test/java/org/springframework/credhub/integration/InterpolationIntegrationTests.java b/spring-credhub-integration-tests/src/test/java/org/springframework/credhub/integration/InterpolationIntegrationTests.java index 28f3a75..3f75eb4 100644 --- a/spring-credhub-integration-tests/src/test/java/org/springframework/credhub/integration/InterpolationIntegrationTests.java +++ b/spring-credhub-integration-tests/src/test/java/org/springframework/credhub/integration/InterpolationIntegrationTests.java @@ -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,15 @@ package org.springframework.credhub.integration; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.After; import org.junit.Before; import org.junit.Test; + import org.springframework.credhub.core.credential.CredHubCredentialOperations; import org.springframework.credhub.core.interpolation.CredHubInterpolationOperations; import org.springframework.credhub.support.CredentialDetails; @@ -30,23 +35,21 @@ import org.springframework.credhub.support.json.JsonCredential; import org.springframework.credhub.support.json.JsonCredentialRequest; import org.springframework.credhub.support.utils.JsonUtils; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - import static org.assertj.core.api.Assertions.assertThat; public class InterpolationIntegrationTests extends CredHubIntegrationTests { - private static final SimpleCredentialName CREDENTIAL_NAME = - new SimpleCredentialName("spring-credhub", "integration-test", "interpolation-credential"); + + private static final SimpleCredentialName CREDENTIAL_NAME = new SimpleCredentialName("spring-credhub", + "integration-test", "interpolation-credential"); private CredHubInterpolationOperations interpolation; + private CredHubCredentialOperations credentials; @Before public void setUp() { - this.interpolation = operations.interpolation(); - this.credentials = operations.credentials(); + this.interpolation = this.operations.interpolation(); + this.credentials = this.operations.credentials(); } @After @@ -57,36 +60,35 @@ public class InterpolationIntegrationTests extends CredHubIntegrationTests { @Test @SuppressWarnings("unchecked") public void interpolate() throws IOException { - Map json = new HashMap() {{ - put("url", "https://example.com"); - put("username", "user"); - put("password", "secret"); - }}; + Map json = new HashMap() { + { + put("url", "https://example.com"); + put("username", "user"); + put("password", "secret"); + } + }; - CredentialDetails written = credentials.write(JsonCredentialRequest.builder() - .name(CREDENTIAL_NAME) - .value(json) - .build()); + CredentialDetails written = this.credentials + .write(JsonCredentialRequest.builder().name(CREDENTIAL_NAME).value(json).build()); assertThat(written.getName().getName()).isEqualTo(CREDENTIAL_NAME.getName()); assertThat(written.getValue()).isEqualTo(json); assertThat(written.getCredentialType()).isEqualTo(CredentialType.JSON); assertThat(written.getId()).isNotNull(); - ServicesData servicesData = - interpolation.interpolateServiceData(buildVcapServices(CREDENTIAL_NAME.getName())); + ServicesData servicesData = this.interpolation + .interpolateServiceData(buildVcapServices(CREDENTIAL_NAME.getName())); assertThat(servicesData).containsKey("service-offering"); assertThat(servicesData.get("service-offering")).hasSize(1); assertThat(servicesData.get("service-offering").get(0)).containsKey("credentials"); - Map credentials = - (Map) servicesData.get("service-offering").get(0).get("credentials"); - assertThat(credentials) - .containsEntry("url", "https://example.com") - .containsEntry("username", "user") + Map credentials = (Map) servicesData.get("service-offering").get(0) + .get("credentials"); + assertThat(credentials).containsEntry("url", "https://example.com").containsEntry("username", "user") .containsEntry("password", "secret"); } private ServicesData buildVcapServices(String credHubReferenceName) throws IOException { + // @formatter:off String vcapServices = "{" + " \"service-offering\": [" + " {" + @@ -103,8 +105,10 @@ public class InterpolationIntegrationTests extends CredHubIntegrationTests { " }" + " ]" + "}"; + // @formatter:on ObjectMapper mapper = JsonUtils.buildObjectMapper(); return mapper.readValue(vcapServices, ServicesData.class); } + } diff --git a/spring-credhub-integration-tests/src/test/java/org/springframework/credhub/integration/PermissionIntegrationTests.java b/spring-credhub-integration-tests/src/test/java/org/springframework/credhub/integration/PermissionIntegrationTests.java index 9c0d49e..979ce0f 100644 --- a/spring-credhub-integration-tests/src/test/java/org/springframework/credhub/integration/PermissionIntegrationTests.java +++ b/spring-credhub-integration-tests/src/test/java/org/springframework/credhub/integration/PermissionIntegrationTests.java @@ -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,35 +16,39 @@ package org.springframework.credhub.integration; +import java.util.List; + import org.junit.After; import org.junit.Before; import org.junit.Test; + import org.springframework.credhub.core.credential.CredHubCredentialOperations; import org.springframework.credhub.core.permission.CredHubPermissionOperations; import org.springframework.credhub.support.SimpleCredentialName; import org.springframework.credhub.support.permissions.Actor; -import org.springframework.credhub.support.permissions.Permission; import org.springframework.credhub.support.permissions.Operation; +import org.springframework.credhub.support.permissions.Permission; import org.springframework.credhub.support.value.ValueCredentialRequest; -import java.util.List; - import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assume.assumeTrue; public class PermissionIntegrationTests extends CredHubIntegrationTests { - private static final SimpleCredentialName CREDENTIAL_NAME = - new SimpleCredentialName("spring-credhub", "integration-test", "test-permissions-credential"); + + private static final SimpleCredentialName CREDENTIAL_NAME = new SimpleCredentialName("spring-credhub", + "integration-test", "test-permissions-credential"); + private static final String CREDENTIAL_VALUE = "test-value"; private CredHubCredentialOperations credentials; + private CredHubPermissionOperations permissions; @Before public void setUp() { - credentials = operations.credentials(); - permissions = operations.permissions(); - + this.credentials = this.operations.credentials(); + this.permissions = this.operations.permissions(); + deleteCredentialIfExists(CREDENTIAL_NAME); } @@ -57,40 +61,27 @@ public class PermissionIntegrationTests extends CredHubIntegrationTests { public void managePermissionsServerV1() { assumeTrue(serverApiIsV1()); - credentials.write(ValueCredentialRequest.builder() - .name(CREDENTIAL_NAME) - .value(CREDENTIAL_VALUE) - .build()); + this.credentials.write(ValueCredentialRequest.builder().name(CREDENTIAL_NAME).value(CREDENTIAL_VALUE).build()); - Permission appPermission = Permission.builder() - .app("app1") - .operation(Operation.READ) - .build(); - Permission userPermission = Permission.builder() - .user("user1") - .operations(Operation.READ, Operation.WRITE, Operation.DELETE) - .build(); - Permission clientPermission = Permission.builder() - .client("client1") - .operations(Operation.READ_ACL, Operation.WRITE_ACL) - .build(); + Permission appPermission = Permission.builder().app("app1").operation(Operation.READ).build(); + Permission userPermission = Permission.builder().user("user1") + .operations(Operation.READ, Operation.WRITE, Operation.DELETE).build(); + Permission clientPermission = Permission.builder().client("client1") + .operations(Operation.READ_ACL, Operation.WRITE_ACL).build(); - permissions.addPermissions(CREDENTIAL_NAME, - appPermission, - userPermission, - clientPermission); + this.permissions.addPermissions(CREDENTIAL_NAME, appPermission, userPermission, clientPermission); - List retrievedPermissions = permissions.getPermissions(CREDENTIAL_NAME); + List retrievedPermissions = this.permissions.getPermissions(CREDENTIAL_NAME); // CredHub 1.x will automatically add a permission for the authenticated user; assertThat(retrievedPermissions.size()).isEqualTo(4); assertThat(retrievedPermissions).contains(appPermission, userPermission, clientPermission); - permissions.deletePermission(CREDENTIAL_NAME, Actor.app("app1")); - permissions.deletePermission(CREDENTIAL_NAME, Actor.user("user1")); - permissions.deletePermission(CREDENTIAL_NAME, Actor.client("client1")); + this.permissions.deletePermission(CREDENTIAL_NAME, Actor.app("app1")); + this.permissions.deletePermission(CREDENTIAL_NAME, Actor.user("user1")); + this.permissions.deletePermission(CREDENTIAL_NAME, Actor.client("client1")); - List afterDelete = permissions.getPermissions(CREDENTIAL_NAME); + List afterDelete = this.permissions.getPermissions(CREDENTIAL_NAME); assertThat(afterDelete.size()).isEqualTo(1); } @@ -98,39 +89,27 @@ public class PermissionIntegrationTests extends CredHubIntegrationTests { public void managePermissionsServerV2() { assumeTrue(serverApiIsV2()); - credentials.write(ValueCredentialRequest.builder() - .name(CREDENTIAL_NAME) - .value(CREDENTIAL_VALUE) - .build()); + this.credentials.write(ValueCredentialRequest.builder().name(CREDENTIAL_NAME).value(CREDENTIAL_VALUE).build()); - Permission appPermission = Permission.builder() - .app("app1") - .operation(Operation.READ) - .build(); - Permission userPermission = Permission.builder() - .user("user1") - .operations(Operation.READ, Operation.WRITE, Operation.DELETE) - .build(); - Permission clientPermission = Permission.builder() - .client("client1") - .operations(Operation.READ_ACL, Operation.WRITE_ACL) - .build(); + Permission appPermission = Permission.builder().app("app1").operation(Operation.READ).build(); + Permission userPermission = Permission.builder().user("user1") + .operations(Operation.READ, Operation.WRITE, Operation.DELETE).build(); + Permission clientPermission = Permission.builder().client("client1") + .operations(Operation.READ_ACL, Operation.WRITE_ACL).build(); - permissions.addPermissions(CREDENTIAL_NAME, - appPermission, - userPermission, - clientPermission); + this.permissions.addPermissions(CREDENTIAL_NAME, appPermission, userPermission, clientPermission); - List retrievedPermissions = permissions.getPermissions(CREDENTIAL_NAME); + List retrievedPermissions = this.permissions.getPermissions(CREDENTIAL_NAME); assertThat(retrievedPermissions.size()).isEqualTo(3); assertThat(retrievedPermissions).contains(appPermission, userPermission, clientPermission); - permissions.deletePermission(CREDENTIAL_NAME, Actor.app("app1")); - permissions.deletePermission(CREDENTIAL_NAME, Actor.user("user1")); - permissions.deletePermission(CREDENTIAL_NAME, Actor.client("client1")); + this.permissions.deletePermission(CREDENTIAL_NAME, Actor.app("app1")); + this.permissions.deletePermission(CREDENTIAL_NAME, Actor.user("user1")); + this.permissions.deletePermission(CREDENTIAL_NAME, Actor.client("client1")); - List afterDelete = permissions.getPermissions(CREDENTIAL_NAME); + List afterDelete = this.permissions.getPermissions(CREDENTIAL_NAME); assertThat(afterDelete.size()).isEqualTo(0); } + } diff --git a/spring-credhub-integration-tests/src/test/java/org/springframework/credhub/integration/PermissionV2IntegrationTests.java b/spring-credhub-integration-tests/src/test/java/org/springframework/credhub/integration/PermissionV2IntegrationTests.java index b5b12a9..530984c 100644 --- a/spring-credhub-integration-tests/src/test/java/org/springframework/credhub/integration/PermissionV2IntegrationTests.java +++ b/spring-credhub-integration-tests/src/test/java/org/springframework/credhub/integration/PermissionV2IntegrationTests.java @@ -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,12 @@ package org.springframework.credhub.integration; +import java.util.List; + import org.junit.After; import org.junit.Before; import org.junit.Test; + import org.springframework.credhub.core.credential.CredHubCredentialOperations; import org.springframework.credhub.core.permissionV2.CredHubPermissionV2Operations; import org.springframework.credhub.support.CredentialPermission; @@ -29,25 +32,25 @@ import org.springframework.credhub.support.permissions.Operation; import org.springframework.credhub.support.permissions.Permission; import org.springframework.credhub.support.value.ValueCredentialRequest; -import java.util.List; - import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assume.assumeTrue; -import static org.springframework.credhub.support.permissions.ActorType.OAUTH_CLIENT; public class PermissionV2IntegrationTests extends CredHubIntegrationTests { - private static final SimpleCredentialName CREDENTIAL_NAME = - new SimpleCredentialName("spring-credhub", "integration-test", "test-permissionsV2-credential"); + + private static final SimpleCredentialName CREDENTIAL_NAME = new SimpleCredentialName("spring-credhub", + "integration-test", "test-permissionsV2-credential"); + private static final String CREDENTIAL_VALUE = "test-value"; private CredHubCredentialOperations credentials; + private CredHubPermissionV2Operations permissions; @Before public void setUp() { - credentials = operations.credentials(); - permissions = operations.permissionsV2(); - + this.credentials = this.operations.credentials(); + this.permissions = this.operations.permissionsV2(); + deleteCredentialIfExists(CREDENTIAL_NAME); } @@ -60,77 +63,61 @@ public class PermissionV2IntegrationTests extends CredHubIntegrationTests { public void managePermissions() { assumeTrue(serverApiIsV2()); - credentials.write(ValueCredentialRequest.builder() - .name(CREDENTIAL_NAME) - .value(CREDENTIAL_VALUE) - .build()); + this.credentials.write(ValueCredentialRequest.builder().name(CREDENTIAL_NAME).value(CREDENTIAL_VALUE).build()); - Permission clientPermission = Permission.builder() - .client("client1") - .operations(Operation.READ, Operation.WRITE, Operation.DELETE) - .build(); + Permission clientPermission = Permission.builder().client("client1") + .operations(Operation.READ, Operation.WRITE, Operation.DELETE).build(); - CredentialPermission added = permissions.addPermissions(CREDENTIAL_NAME, clientPermission); + CredentialPermission added = this.permissions.addPermissions(CREDENTIAL_NAME, clientPermission); assertThat(added.getId()).isNotNull(); assertThat(added.getPath()).isEqualTo(CREDENTIAL_NAME.getName()); - assertPermissions(added, OAUTH_CLIENT, "client1", - Operation.READ, Operation.WRITE, Operation.DELETE); + assertPermissions(added, ActorType.OAUTH_CLIENT, "client1", Operation.READ, Operation.WRITE, Operation.DELETE); String permissionId = added.getId(); - CredentialPermission retrieved = permissions.getPermissions(permissionId); + CredentialPermission retrieved = this.permissions.getPermissions(permissionId); assertThat(retrieved.getId()).isEqualTo(permissionId); assertThat(retrieved.getPath()).isEqualTo(CREDENTIAL_NAME.getName()); - assertPermissions(retrieved, OAUTH_CLIENT, "client1", - Operation.READ, Operation.WRITE, Operation.DELETE); + assertPermissions(retrieved, ActorType.OAUTH_CLIENT, "client1", Operation.READ, Operation.WRITE, + Operation.DELETE); - permissions.deletePermission(permissionId); + this.permissions.deletePermission(permissionId); } @Test public void updatePermissions() { assumeTrue(serverApiIsV2()); - credentials.write(ValueCredentialRequest.builder() - .name(CREDENTIAL_NAME) - .value(CREDENTIAL_VALUE) - .build()); + this.credentials.write(ValueCredentialRequest.builder().name(CREDENTIAL_NAME).value(CREDENTIAL_VALUE).build()); - Permission clientPermission = Permission.builder() - .client("client1") - .operations(Operation.READ, Operation.WRITE, Operation.DELETE) - .build(); + Permission clientPermission = Permission.builder().client("client1") + .operations(Operation.READ, Operation.WRITE, Operation.DELETE).build(); - CredentialPermission added = permissions.addPermissions(CREDENTIAL_NAME, clientPermission); + CredentialPermission added = this.permissions.addPermissions(CREDENTIAL_NAME, clientPermission); assertThat(added.getId()).isNotNull(); assertThat(added.getPath()).isEqualTo(CREDENTIAL_NAME.getName()); - assertPermissions(added, OAUTH_CLIENT, "client1", - Operation.READ, Operation.WRITE, Operation.DELETE); + assertPermissions(added, ActorType.OAUTH_CLIENT, "client1", Operation.READ, Operation.WRITE, Operation.DELETE); String permissionId = added.getId(); - Permission newPermission = Permission.builder() - .client("client1") - .operations(Operation.READ_ACL, Operation.WRITE_ACL) - .build(); + Permission newPermission = Permission.builder().client("client1") + .operations(Operation.READ_ACL, Operation.WRITE_ACL).build(); - CredentialPermission updated = permissions.updatePermissions(permissionId, CREDENTIAL_NAME, newPermission); + CredentialPermission updated = this.permissions.updatePermissions(permissionId, CREDENTIAL_NAME, newPermission); assertThat(updated.getId()).isEqualTo(permissionId); assertThat(updated.getPath()).isEqualTo(CREDENTIAL_NAME.getName()); - assertPermissions(updated, OAUTH_CLIENT, "client1", - Operation.READ_ACL, Operation.WRITE_ACL); + assertPermissions(updated, ActorType.OAUTH_CLIENT, "client1", Operation.READ_ACL, Operation.WRITE_ACL); - CredentialPermission retrieved = permissions.getPermissions(permissionId); + CredentialPermission retrieved = this.permissions.getPermissions(permissionId); assertThat(retrieved.getId()).isEqualTo(permissionId); assertThat(retrieved.getPath()).isEqualTo(CREDENTIAL_NAME.getName()); - assertPermissions(retrieved, OAUTH_CLIENT, "client1", - Operation.READ_ACL, Operation.WRITE_ACL); + assertPermissions(retrieved, ActorType.OAUTH_CLIENT, "client1", Operation.READ_ACL, Operation.WRITE_ACL); - permissions.deletePermission(permissionId); + this.permissions.deletePermission(permissionId); } - private void assertPermissions(CredentialPermission credentialPermission, - ActorType actorType, String actorId, Operation... operations) { + private void assertPermissions(CredentialPermission credentialPermission, ActorType actorType, String actorId, + Operation... operations) { Actor actor = credentialPermission.getPermission().getActor(); assertThat(actor.getAuthType()).isEqualTo(actorType); assertThat(actor.getPrimaryIdentifier()).isEqualTo(actorId); @@ -138,4 +125,5 @@ public class PermissionV2IntegrationTests extends CredHubIntegrationTests { List ops = credentialPermission.getPermission().getOperations(); assertThat(ops).containsExactlyInAnyOrder(operations); } + } diff --git a/spring-credhub-integration-tests/src/test/java/org/springframework/credhub/integration/TestApplication.java b/spring-credhub-integration-tests/src/test/java/org/springframework/credhub/integration/TestApplication.java index dd6c76f..1a8757b 100644 --- a/spring-credhub-integration-tests/src/test/java/org/springframework/credhub/integration/TestApplication.java +++ b/spring-credhub-integration-tests/src/test/java/org/springframework/credhub/integration/TestApplication.java @@ -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. @@ -20,8 +20,10 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication -public class TestApplication { +public class TestApplication { + public static void main(String[] args) { SpringApplication.run(TestApplication.class, args); } + } diff --git a/spring-credhub-reactive-integration-tests/build.gradle b/spring-credhub-reactive-integration-tests/build.gradle index 2abe932..b87289b 100644 --- a/spring-credhub-reactive-integration-tests/build.gradle +++ b/spring-credhub-reactive-integration-tests/build.gradle @@ -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, diff --git a/spring-credhub-reactive-integration-tests/src/test/java/org/springframework/credhub/integration/ReactiveCertificateIntegrationTests.java b/spring-credhub-reactive-integration-tests/src/test/java/org/springframework/credhub/integration/ReactiveCertificateIntegrationTests.java index dcc74aa..01300c2 100644 --- a/spring-credhub-reactive-integration-tests/src/test/java/org/springframework/credhub/integration/ReactiveCertificateIntegrationTests.java +++ b/spring-credhub-reactive-integration-tests/src/test/java/org/springframework/credhub/integration/ReactiveCertificateIntegrationTests.java @@ -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,13 @@ package org.springframework.credhub.integration; +import java.util.concurrent.atomic.AtomicReference; + import org.junit.After; import org.junit.Before; import org.junit.Test; +import reactor.test.StepVerifier; + import org.springframework.credhub.core.certificate.ReactiveCredHubCertificateOperations; import org.springframework.credhub.core.credential.ReactiveCredHubCredentialOperations; import org.springframework.credhub.support.CredentialType; @@ -26,26 +30,26 @@ import org.springframework.credhub.support.SimpleCredentialName; import org.springframework.credhub.support.certificate.CertificateCredential; import org.springframework.credhub.support.certificate.CertificateParameters; import org.springframework.credhub.support.certificate.CertificateParametersRequest; -import reactor.test.StepVerifier; - -import java.util.concurrent.atomic.AtomicReference; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assume.assumeTrue; public class ReactiveCertificateIntegrationTests extends ReactiveCredHubIntegrationTests { - private static final SimpleCredentialName TEST_CERT_NAME = - new SimpleCredentialName("spring-credhub", "integration-test", "test-certificate"); - private static final SimpleCredentialName ROOT_CERT_NAME = - new SimpleCredentialName("spring-credhub", "integration-test", "root-certificate"); + + private static final SimpleCredentialName TEST_CERT_NAME = new SimpleCredentialName("spring-credhub", + "integration-test", "test-certificate"); + + private static final SimpleCredentialName ROOT_CERT_NAME = new SimpleCredentialName("spring-credhub", + "integration-test", "root-certificate"); private ReactiveCredHubCredentialOperations credentials; + private ReactiveCredHubCertificateOperations certificates; @Before public void setUp() { - credentials = operations.credentials(); - certificates = operations.certificates(); + this.credentials = this.operations.credentials(); + this.certificates = this.operations.certificates(); deleteCredentialIfExists(TEST_CERT_NAME); deleteCredentialIfExists(ROOT_CERT_NAME); @@ -61,35 +65,25 @@ public class ReactiveCertificateIntegrationTests extends ReactiveCredHubIntegrat public void generateCertificate() { assumeTrue(serverApiIsV2()); - StepVerifier.create(credentials.generate(CertificateParametersRequest.builder() - .name(TEST_CERT_NAME) - .parameters(CertificateParameters.builder() - .commonName("example.com") - .selfSign(true) - .build()) - .build(), - CertificateCredential.class)) - .assertNext(response -> { + StepVerifier.create(this.credentials.generate(CertificateParametersRequest.builder().name(TEST_CERT_NAME) + .parameters(CertificateParameters.builder().commonName("example.com").selfSign(true).build()).build(), + CertificateCredential.class)).assertNext((response) -> { assertThat(response.getName().getName()).isEqualTo(TEST_CERT_NAME.getName()); assertThat(response.getCredentialType()).isEqualTo(CredentialType.CERTIFICATE); assertThat(response.getId()).isNotNull(); assertThat(response.getValue().getCertificate()).isNotNull(); assertThat(response.getValue().getCertificateAuthority()).isNotNull(); assertThat(response.getValue().getPrivateKey()).isNotNull(); - }) - .verifyComplete(); + }).verifyComplete(); - StepVerifier.create(certificates.getByName(TEST_CERT_NAME)) - .assertNext(response -> { - assertThat(response.getName()).isEqualTo(TEST_CERT_NAME.getName()); - assertThat(response.getId()).isNotNull(); - }) - .verifyComplete(); + StepVerifier.create(this.certificates.getByName(TEST_CERT_NAME)).assertNext((response) -> { + assertThat(response.getName()).isEqualTo(TEST_CERT_NAME.getName()); + assertThat(response.getId()).isNotNull(); + }).verifyComplete(); - StepVerifier.create(certificates.getAll()) - .assertNext(response -> assertThat(response.getName()).isEqualTo(TEST_CERT_NAME.getName())) - .thenCancel() - .verify(); + StepVerifier.create(this.certificates.getAll()) + .assertNext((response) -> assertThat(response.getName()).isEqualTo(TEST_CERT_NAME.getName())) + .thenCancel().verify(); } @Test @@ -99,42 +93,29 @@ public class ReactiveCertificateIntegrationTests extends ReactiveCredHubIntegrat AtomicReference certificate = new AtomicReference<>(); AtomicReference certificateId = new AtomicReference<>(); - StepVerifier.create(credentials.generate(CertificateParametersRequest.builder() - .name(TEST_CERT_NAME) - .parameters(CertificateParameters.builder() - .commonName("example.com") - .selfSign(true) - .build()) - .build(), - CertificateCredential.class)) - .assertNext(response -> { + StepVerifier.create(this.credentials.generate(CertificateParametersRequest.builder().name(TEST_CERT_NAME) + .parameters(CertificateParameters.builder().commonName("example.com").selfSign(true).build()).build(), + CertificateCredential.class)).assertNext((response) -> { assertThat(response.getName().getName()).isEqualTo(TEST_CERT_NAME.getName()); certificate.set(response.getValue()); - }) - .verifyComplete(); + }).verifyComplete(); - StepVerifier.create(certificates.getByName(TEST_CERT_NAME)) - .assertNext(response -> { - assertThat(response.getName()).isEqualTo(TEST_CERT_NAME.getName()); - assertThat(response.getId()).isNotNull(); + StepVerifier.create(this.certificates.getByName(TEST_CERT_NAME)).assertNext((response) -> { + assertThat(response.getName()).isEqualTo(TEST_CERT_NAME.getName()); + assertThat(response.getId()).isNotNull(); - certificateId.set(response.getId()); - }) - .verifyComplete(); + certificateId.set(response.getId()); + }).verifyComplete(); - StepVerifier.create(certificates.regenerate(certificateId.get(), true)) - .assertNext(response -> { - assertThat(response.getName().getName()).isEqualTo(TEST_CERT_NAME.getName()); - assertThat(response.isTransitional()).isTrue(); - assertThat(response.getValue().getCertificate()) - .isNotEqualTo(certificate.get().getCertificate()); - assertThat(response.getValue().getCertificateAuthority()) - .isNotEqualTo(certificate.get().getCertificateAuthority()); - assertThat(response.getValue().getPrivateKey()) - .isNotEqualTo(certificate.get().getPrivateKey()); - }) - .verifyComplete(); + StepVerifier.create(this.certificates.regenerate(certificateId.get(), true)).assertNext((response) -> { + assertThat(response.getName().getName()).isEqualTo(TEST_CERT_NAME.getName()); + assertThat(response.isTransitional()).isTrue(); + assertThat(response.getValue().getCertificate()).isNotEqualTo(certificate.get().getCertificate()); + assertThat(response.getValue().getCertificateAuthority()) + .isNotEqualTo(certificate.get().getCertificateAuthority()); + assertThat(response.getValue().getPrivateKey()).isNotEqualTo(certificate.get().getPrivateKey()); + }).verifyComplete(); } @Test @@ -146,70 +127,56 @@ public class ReactiveCertificateIntegrationTests extends ReactiveCredHubIntegrat AtomicReference credentialVersion1Id = new AtomicReference<>(); AtomicReference certificateId = new AtomicReference<>(); - StepVerifier.create(credentials.generate(CertificateParametersRequest.builder() - .name(TEST_CERT_NAME) - .parameters(CertificateParameters.builder() - .commonName("example.com") - .selfSign(true) - .build()) - .build(), CertificateCredential.class)) - .assertNext(response -> { + StepVerifier.create(this.credentials.generate(CertificateParametersRequest.builder().name(TEST_CERT_NAME) + .parameters(CertificateParameters.builder().commonName("example.com").selfSign(true).build()).build(), + CertificateCredential.class)).assertNext((response) -> { assertThat(response.getName().getName()).isEqualTo(TEST_CERT_NAME.getName()); certificate.set(response.getValue()); credentialVersion0Id.set(response.getId()); - }) + }).verifyComplete(); + + StepVerifier.create(this.credentials.getByNameWithHistory(TEST_CERT_NAME, CertificateCredential.class)) + .assertNext((response) -> assertThat(response.getId()).isEqualTo(credentialVersion0Id.get())) .verifyComplete(); - StepVerifier.create(credentials.getByNameWithHistory(TEST_CERT_NAME, CertificateCredential.class)) - .assertNext(response -> assertThat(response.getId()).isEqualTo(credentialVersion0Id.get())) + StepVerifier.create(this.certificates.getByName(TEST_CERT_NAME)).assertNext((response) -> { + assertThat(response.getName()).isEqualTo(TEST_CERT_NAME.getName()); + assertThat(response.getId()).isNotNull(); + + certificateId.set(response.getId()); + }).verifyComplete(); + + StepVerifier.create(this.certificates.regenerate(certificateId.get(), true)).assertNext((response) -> { + assertThat(response.getName().getName()).isEqualTo(TEST_CERT_NAME.getName()); + assertThat(response.getValue().getCertificate()).isNotEqualTo(certificate.get().getCertificate()); + assertThat(response.getValue().getCertificateAuthority()) + .isNotEqualTo(certificate.get().getCertificateAuthority()); + assertThat(response.getValue().getPrivateKey()).isNotEqualTo(certificate.get().getPrivateKey()); + + credentialVersion1Id.set(response.getId()); + }).verifyComplete(); + + StepVerifier.create(this.credentials.getByNameWithHistory(TEST_CERT_NAME, CertificateCredential.class)) + .assertNext((response) -> assertThat(response.getId()).isEqualTo(credentialVersion1Id.get())) + .assertNext((response) -> assertThat(response.getId()).isEqualTo(credentialVersion0Id.get())) .verifyComplete(); - StepVerifier.create(certificates.getByName(TEST_CERT_NAME)) - .assertNext(response -> { - assertThat(response.getName()).isEqualTo(TEST_CERT_NAME.getName()); - assertThat(response.getId()).isNotNull(); - - certificateId.set(response.getId()); - }) - .verifyComplete(); - - StepVerifier.create(certificates.regenerate(certificateId.get(), true)) - .assertNext(response -> { - assertThat(response.getName().getName()).isEqualTo(TEST_CERT_NAME.getName()); - assertThat(response.getValue().getCertificate()) - .isNotEqualTo(certificate.get().getCertificate()); - assertThat(response.getValue().getCertificateAuthority()) - .isNotEqualTo(certificate.get().getCertificateAuthority()); - assertThat(response.getValue().getPrivateKey()) - .isNotEqualTo(certificate.get().getPrivateKey()); - - credentialVersion1Id.set(response.getId()); - }) - .verifyComplete(); - - StepVerifier.create(credentials.getByNameWithHistory(TEST_CERT_NAME, CertificateCredential.class)) - .assertNext(response -> assertThat(response.getId()).isEqualTo(credentialVersion1Id.get())) - .assertNext(response -> assertThat(response.getId()).isEqualTo(credentialVersion0Id.get())) - .verifyComplete(); - - StepVerifier.create(certificates.updateTransitionalVersion(certificateId.get(), credentialVersion0Id.get())) - .assertNext(response -> { + StepVerifier + .create(this.certificates.updateTransitionalVersion(certificateId.get(), credentialVersion0Id.get())) + .assertNext((response) -> { assertThat(response.getId()).isEqualTo(credentialVersion1Id.get()); assertThat(response.isTransitional()).isFalse(); - }) - .assertNext(response -> { + }).assertNext((response) -> { assertThat(response.getId()).isEqualTo(credentialVersion0Id.get()); assertThat(response.isTransitional()).isTrue(); - }) - .verifyComplete(); + }).verifyComplete(); - StepVerifier.create(certificates.updateTransitionalVersion(certificateId.get(), null)) - .assertNext(response -> { + StepVerifier.create(this.certificates.updateTransitionalVersion(certificateId.get(), null)) + .assertNext((response) -> { assertThat(response.getId()).isEqualTo(credentialVersion1Id.get()); assertThat(response.isTransitional()).isFalse(); - }) - .verifyComplete(); + }).verifyComplete(); } @Test @@ -217,44 +184,37 @@ public class ReactiveCertificateIntegrationTests extends ReactiveCredHubIntegrat AtomicReference rootCertificate = new AtomicReference<>(); AtomicReference signedCertificateId = new AtomicReference<>(); - StepVerifier.create(credentials.generate(CertificateParametersRequest.builder() - .name(ROOT_CERT_NAME) - .parameters(CertificateParameters.builder() - .commonName("example.com") - .certificateAuthority(true) - .selfSign(true) - .build()) - .build(), - CertificateCredential.class)) - .assertNext(response -> { + StepVerifier + .create(this.credentials.generate( + CertificateParametersRequest.builder().name(ROOT_CERT_NAME) + .parameters(CertificateParameters.builder().commonName("example.com") + .certificateAuthority(true).selfSign(true).build()) + .build(), + CertificateCredential.class)) + .assertNext((response) -> { assertThat(response.getName().getName()).isEqualTo(ROOT_CERT_NAME.getName()); rootCertificate.set(response.getValue()); - }) - .verifyComplete(); + }).verifyComplete(); - StepVerifier.create(credentials.generate(CertificateParametersRequest.builder() - .name(TEST_CERT_NAME) - .parameters(CertificateParameters.builder() - .commonName("example.com") - .certificateAuthorityCredential(ROOT_CERT_NAME) - .build()) + StepVerifier.create(this.credentials.generate( + CertificateParametersRequest.builder().name(TEST_CERT_NAME) + .parameters(CertificateParameters.builder().commonName("example.com") + .certificateAuthorityCredential(ROOT_CERT_NAME).build()) .build(), - CertificateCredential.class)) - .assertNext(response -> { + CertificateCredential.class)).assertNext((response) -> { assertThat(response.getValue().getCertificateAuthority()) .isEqualTo(rootCertificate.get().getCertificate()); signedCertificateId.set(response.getId()); - }) + }).verifyComplete(); + + StepVerifier.create(this.credentials.getByNameWithHistory(TEST_CERT_NAME, CertificateCredential.class)) + .assertNext((response) -> assertThat(response.getId()).isEqualTo(signedCertificateId.get())) .verifyComplete(); - StepVerifier.create(credentials.getByNameWithHistory(TEST_CERT_NAME, CertificateCredential.class)) - .assertNext(response -> assertThat(response.getId()).isEqualTo(signedCertificateId.get())) - .verifyComplete(); - - StepVerifier.create(certificates.regenerate(ROOT_CERT_NAME)) - .assertNext(response -> assertThat(response).isEqualTo(TEST_CERT_NAME)) - .verifyComplete(); + StepVerifier.create(this.certificates.regenerate(ROOT_CERT_NAME)) + .assertNext((response) -> assertThat(response).isEqualTo(TEST_CERT_NAME)).verifyComplete(); } + } diff --git a/spring-credhub-reactive-integration-tests/src/test/java/org/springframework/credhub/integration/ReactiveCredHubIntegrationTests.java b/spring-credhub-reactive-integration-tests/src/test/java/org/springframework/credhub/integration/ReactiveCredHubIntegrationTests.java index 8e1a6f4..8a81e40 100644 --- a/spring-credhub-reactive-integration-tests/src/test/java/org/springframework/credhub/integration/ReactiveCredHubIntegrationTests.java +++ b/spring-credhub-reactive-integration-tests/src/test/java/org/springframework/credhub/integration/ReactiveCredHubIntegrationTests.java @@ -1,11 +1,11 @@ /* - * 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. * 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,6 +17,8 @@ package org.springframework.credhub.integration; import org.junit.runner.RunWith; +import reactor.core.publisher.Mono; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.credhub.core.ReactiveCredHubOperations; @@ -24,10 +26,9 @@ import org.springframework.credhub.support.CredentialName; import org.springframework.credhub.support.info.VersionInfo; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; -import reactor.core.publisher.Mono; @RunWith(SpringRunner.class) -@SpringBootTest(classes = {TestApplication.class}) +@SpringBootTest(classes = { TestApplication.class }) @ActiveProfiles("test") public abstract class ReactiveCredHubIntegrationTests { @@ -43,12 +44,11 @@ public abstract class ReactiveCredHubIntegrationTests { } private VersionInfo getVersion() { - return operations.info().version().single().block(); + return this.operations.info().version().single().block(); } void deleteCredentialIfExists(CredentialName credentialName) { - operations.credentials().deleteByName(credentialName) - .onErrorResume(e -> Mono.empty()) - .block(); + this.operations.credentials().deleteByName(credentialName).onErrorResume((e) -> Mono.empty()).block(); } + } diff --git a/spring-credhub-reactive-integration-tests/src/test/java/org/springframework/credhub/integration/ReactiveCredentialIntegrationTests.java b/spring-credhub-reactive-integration-tests/src/test/java/org/springframework/credhub/integration/ReactiveCredentialIntegrationTests.java index 50d86d9..16955d0 100644 --- a/spring-credhub-reactive-integration-tests/src/test/java/org/springframework/credhub/integration/ReactiveCredentialIntegrationTests.java +++ b/spring-credhub-reactive-integration-tests/src/test/java/org/springframework/credhub/integration/ReactiveCredentialIntegrationTests.java @@ -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,13 @@ package org.springframework.credhub.integration; +import java.util.concurrent.atomic.AtomicReference; + import org.junit.After; import org.junit.Before; import org.junit.Test; +import reactor.test.StepVerifier; + import org.springframework.credhub.core.credential.ReactiveCredHubCredentialOperations; import org.springframework.credhub.support.CredentialDetails; import org.springframework.credhub.support.CredentialType; @@ -29,16 +33,15 @@ import org.springframework.credhub.support.user.UserCredential; import org.springframework.credhub.support.user.UserParametersRequest; import org.springframework.credhub.support.value.ValueCredential; import org.springframework.credhub.support.value.ValueCredentialRequest; -import reactor.test.StepVerifier; - -import java.util.concurrent.atomic.AtomicReference; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assume.assumeTrue; public class ReactiveCredentialIntegrationTests extends ReactiveCredHubIntegrationTests { - private static final SimpleCredentialName CREDENTIAL_NAME = - new SimpleCredentialName("spring-credhub", "integration-test", "test-credential"); + + private static final SimpleCredentialName CREDENTIAL_NAME = new SimpleCredentialName("spring-credhub", + "integration-test", "test-credential"); + private static final String CREDENTIAL_VALUE = "test-value"; private ReactiveCredHubCredentialOperations credentials; @@ -47,14 +50,10 @@ public class ReactiveCredentialIntegrationTests extends ReactiveCredHubIntegrati @Before public void setUp() { - credentials = operations.credentials(); + this.credentials = this.operations.credentials(); - passwordParameters = PasswordParameters.builder() - .length(12) - .excludeLower(false) - .excludeUpper(false) - .excludeNumber(false) - .includeSpecial(true); + this.passwordParameters = PasswordParameters.builder().length(12).excludeLower(false).excludeUpper(false) + .excludeNumber(false).includeSpecial(true); deleteCredentialIfExists(CREDENTIAL_NAME); } @@ -63,56 +62,47 @@ public class ReactiveCredentialIntegrationTests extends ReactiveCredHubIntegrati public void tearDown() { deleteCredentialIfExists(CREDENTIAL_NAME); - StepVerifier.create(credentials.findByName(CREDENTIAL_NAME)) - .expectComplete() - .verify(); + StepVerifier.create(this.credentials.findByName(CREDENTIAL_NAME)).expectComplete().verify(); } @Test public void writeCredential() { AtomicReference> written = new AtomicReference<>(); - StepVerifier.create(credentials.write(ValueCredentialRequest.builder() - .name(CREDENTIAL_NAME) - .value(CREDENTIAL_VALUE) - .build())) - .assertNext(response -> { + StepVerifier + .create(this.credentials + .write(ValueCredentialRequest.builder().name(CREDENTIAL_NAME).value(CREDENTIAL_VALUE).build())) + .assertNext((response) -> { assertThat(response.getName().getName()).isEqualTo(CREDENTIAL_NAME.getName()); assertThat(response.getValue().getValue()).isEqualTo(CREDENTIAL_VALUE); assertThat(response.getCredentialType()).isEqualTo(CredentialType.VALUE); assertThat(response.getId()).isNotNull(); written.set(response); - }) - .verifyComplete(); + }).verifyComplete(); - StepVerifier.create(credentials.getById(written.get().getId(), ValueCredential.class)) - .assertNext(response -> { + StepVerifier.create(this.credentials.getById(written.get().getId(), ValueCredential.class)) + .assertNext((response) -> { assertThat(response.getName().getName()).isEqualTo(CREDENTIAL_NAME.getName()); assertThat(response.getValue().getValue()).isEqualTo(CREDENTIAL_VALUE); assertThat(response.getCredentialType()).isEqualTo(CredentialType.VALUE); - }) - .verifyComplete(); + }).verifyComplete(); - StepVerifier.create(credentials.getByName(CREDENTIAL_NAME, ValueCredential.class)) - .assertNext(response -> { + StepVerifier.create(this.credentials.getByName(CREDENTIAL_NAME, ValueCredential.class)) + .assertNext((response) -> { assertThat(response.getName().getName()).isEqualTo(CREDENTIAL_NAME.getName()); assertThat(response.getValue().getValue()).isEqualTo(CREDENTIAL_VALUE); assertThat(response.getCredentialType()).isEqualTo(CredentialType.VALUE); - }) - .verifyComplete(); + }).verifyComplete(); - StepVerifier.create(credentials.findByName(new SimpleCredentialName("/test"))) - .assertNext(response -> assertThat(response) - .extracting("name").extracting("name") + StepVerifier.create(this.credentials.findByName(new SimpleCredentialName("/test"))) + .assertNext((response) -> assertThat(response).extracting("name").extracting("name") .containsExactly(CREDENTIAL_NAME.getName())) .verifyComplete(); - StepVerifier.create(credentials.findByPath("/spring-credhub/integration-test")) - .assertNext(response -> - assertThat(response) - .extracting("name").extracting("name") - .containsExactly(CREDENTIAL_NAME.getName())) + StepVerifier.create(this.credentials.findByPath("/spring-credhub/integration-test")) + .assertNext((response) -> assertThat(response).extracting("name").extracting("name") + .containsExactly(CREDENTIAL_NAME.getName())) .verifyComplete(); } @@ -120,27 +110,23 @@ public class ReactiveCredentialIntegrationTests extends ReactiveCredHubIntegrati public void overwriteCredentialV2() { assumeTrue(serverApiIsV2()); - StepVerifier.create(credentials.write(ValueCredentialRequest.builder() - .name(CREDENTIAL_NAME) - .value(CREDENTIAL_VALUE) - .build())) - .assertNext(response -> { + StepVerifier + .create(this.credentials + .write(ValueCredentialRequest.builder().name(CREDENTIAL_NAME).value(CREDENTIAL_VALUE).build())) + .assertNext((response) -> { assertThat(response.getName().getName()).isEqualTo(CREDENTIAL_NAME.getName()); assertThat(response.getValue().getValue()).isEqualTo(CREDENTIAL_VALUE); assertThat(response.getCredentialType()).isEqualTo(CredentialType.VALUE); assertThat(response.getId()).isNotNull(); - }) - .verifyComplete(); + }).verifyComplete(); - StepVerifier.create(credentials.write(ValueCredentialRequest.builder() - .name(CREDENTIAL_NAME) - .value("new-value") - .build())) - .assertNext(response -> { + StepVerifier + .create(this.credentials + .write(ValueCredentialRequest.builder().name(CREDENTIAL_NAME).value("new-value").build())) + .assertNext((response) -> { assertThat(response.getName().getName()).isEqualTo(CREDENTIAL_NAME.getName()); assertThat(response.getValue().getValue()).isEqualTo("new-value"); - }) - .verifyComplete(); + }).verifyComplete(); verifyHistory(); } @@ -149,80 +135,62 @@ public class ReactiveCredentialIntegrationTests extends ReactiveCredHubIntegrati public void overwriteCredentialV1() { assumeTrue(serverApiIsV1()); - StepVerifier.create(credentials.write(ValueCredentialRequest.builder() - .name(CREDENTIAL_NAME) - .value(CREDENTIAL_VALUE) - .build())) - .assertNext(response -> { + StepVerifier + .create(this.credentials + .write(ValueCredentialRequest.builder().name(CREDENTIAL_NAME).value(CREDENTIAL_VALUE).build())) + .assertNext((response) -> { assertThat(response.getName().getName()).isEqualTo(CREDENTIAL_NAME.getName()); assertThat(response.getValue().getValue()).isEqualTo(CREDENTIAL_VALUE); assertThat(response.getCredentialType()).isEqualTo(CredentialType.VALUE); assertThat(response.getId()).isNotNull(); }).verifyComplete(); - StepVerifier.create(credentials.write(ValueCredentialRequest.builder() - .name(CREDENTIAL_NAME) - .value("new-value") - .mode(WriteMode.NO_OVERWRITE) - .build())) - .assertNext(response -> { + StepVerifier.create(this.credentials.write(ValueCredentialRequest.builder().name(CREDENTIAL_NAME) + .value("new-value").mode(WriteMode.NO_OVERWRITE).build())).assertNext((response) -> { assertThat(response.getName().getName()).isEqualTo(CREDENTIAL_NAME.getName()); assertThat(response.getValue().getValue()).isEqualTo(CREDENTIAL_VALUE); - }) - .verifyComplete(); + }).verifyComplete(); - StepVerifier.create(credentials.write(ValueCredentialRequest.builder() - .name(CREDENTIAL_NAME) - .value("new-value") - .mode(WriteMode.OVERWRITE) - .build())) - .assertNext(response -> { + StepVerifier.create(this.credentials.write(ValueCredentialRequest.builder().name(CREDENTIAL_NAME) + .value("new-value").mode(WriteMode.OVERWRITE).build())).assertNext((response) -> { assertThat(response.getName().getName()).isEqualTo(CREDENTIAL_NAME.getName()); assertThat(response.getValue().getValue()).isEqualTo("new-value"); - }) - .verifyComplete(); + }).verifyComplete(); verifyHistory(); } private void verifyHistory() { - StepVerifier.create(credentials.getByNameWithHistory(CREDENTIAL_NAME, ValueCredential.class)) - .assertNext(response -> { + StepVerifier.create(this.credentials.getByNameWithHistory(CREDENTIAL_NAME, ValueCredential.class)) + .assertNext((response) -> { assertThat(response.getName().getName()).isEqualTo(CREDENTIAL_NAME.getName()); assertThat(response.getValue().getValue()).isEqualTo("new-value"); assertThat(response.getCredentialType()).isEqualTo(CredentialType.VALUE); - }) - .assertNext(response -> { + }).assertNext((response) -> { assertThat(response.getName().getName()).isEqualTo(CREDENTIAL_NAME.getName()); assertThat(response.getValue().getValue()).isEqualTo(CREDENTIAL_VALUE); assertThat(response.getCredentialType()).isEqualTo(CredentialType.VALUE); - }) - .verifyComplete(); + }).verifyComplete(); - StepVerifier.create(credentials.getByNameWithHistory(CREDENTIAL_NAME, 2, ValueCredential.class)) - .assertNext(response -> { + StepVerifier.create(this.credentials.getByNameWithHistory(CREDENTIAL_NAME, 2, ValueCredential.class)) + .assertNext((response) -> { assertThat(response.getName().getName()).isEqualTo(CREDENTIAL_NAME.getName()); assertThat(response.getValue().getValue()).isEqualTo("new-value"); assertThat(response.getCredentialType()).isEqualTo(CredentialType.VALUE); - }) - .assertNext(response -> { + }).assertNext((response) -> { assertThat(response.getName().getName()).isEqualTo(CREDENTIAL_NAME.getName()); assertThat(response.getValue().getValue()).isEqualTo(CREDENTIAL_VALUE); assertThat(response.getCredentialType()).isEqualTo(CredentialType.VALUE); - }) - .verifyComplete(); + }).verifyComplete(); } @Test public void generateCredential() { AtomicReference> generated = new AtomicReference<>(); - StepVerifier.create(credentials.generate(UserParametersRequest.builder() - .name(CREDENTIAL_NAME) - .username("test-user") - .parameters(passwordParameters.build()) - .build(), UserCredential.class)) - .assertNext(response -> { + StepVerifier.create(this.credentials.generate(UserParametersRequest.builder().name(CREDENTIAL_NAME) + .username("test-user").parameters(this.passwordParameters.build()).build(), UserCredential.class)) + .assertNext((response) -> { assertThat(response.getName().getName()).isEqualTo(CREDENTIAL_NAME.getName()); assertThat(response.getCredentialType()).isEqualTo(CredentialType.USER); assertThat(response.getValue().getUsername()).isEqualTo("test-user"); @@ -230,15 +198,14 @@ public class ReactiveCredentialIntegrationTests extends ReactiveCredHubIntegrati assertThat(response.getValue().getPasswordHash()).isNotNull(); generated.set(response); - }) + }).verifyComplete(); + + StepVerifier.create(this.credentials.getById(generated.get().getId(), UserCredential.class)) + .assertNext((response) -> assertThat(response.getName().getName()).isEqualTo(CREDENTIAL_NAME.getName())) .verifyComplete(); - StepVerifier.create(credentials.getById(generated.get().getId(), UserCredential.class)) - .assertNext(response -> assertThat(response.getName().getName()).isEqualTo(CREDENTIAL_NAME.getName())) - .verifyComplete(); - - StepVerifier.create(credentials.regenerate(CREDENTIAL_NAME, UserCredential.class)) - .assertNext(response -> { + StepVerifier.create(this.credentials.regenerate(CREDENTIAL_NAME, UserCredential.class)) + .assertNext((response) -> { assertThat(response.getName().getName()).isEqualTo(CREDENTIAL_NAME.getName()); assertThat(response.getValue().getUsername()).isEqualTo("test-user"); assertThat(response.getValue().getPassword()).matches("^[a-zA-Z0-9\\p{Punct}]{12}$"); @@ -246,72 +213,63 @@ public class ReactiveCredentialIntegrationTests extends ReactiveCredHubIntegrati .isNotEqualTo(generated.get().getValue().getPassword()); assertThat(response.getValue().getPasswordHash()) .isNotEqualTo(generated.get().getValue().getPasswordHash()); - }) - .verifyComplete(); + }).verifyComplete(); } @Test public void generateNoOverwriteCredential() { AtomicReference> generated = new AtomicReference<>(); - StepVerifier.create(credentials.generate(UserParametersRequest.builder() - .name(CREDENTIAL_NAME) - .username("test-user") - .parameters(passwordParameters.build()) - .build(), UserCredential.class)) - .assertNext(response -> { + StepVerifier.create(this.credentials.generate(UserParametersRequest.builder().name(CREDENTIAL_NAME) + .username("test-user").parameters(this.passwordParameters.build()).build(), UserCredential.class)) + .assertNext((response) -> { assertThat(response.getName().getName()).isEqualTo(CREDENTIAL_NAME.getName()); assertThat(response.getValue().getUsername()).isEqualTo("test-user"); assertThat(response.getValue().getPassword()).matches("^[a-zA-Z0-9\\p{Punct}]{12}$"); assertThat(response.getValue().getPasswordHash()).isNotNull(); generated.set(response); - }) - .verifyComplete(); + }).verifyComplete(); - StepVerifier.create(credentials.generate(UserParametersRequest.builder() - .name(CREDENTIAL_NAME) - .mode(WriteMode.NO_OVERWRITE) - .username("test-user") - .parameters(passwordParameters.build()) - .build(), UserCredential.class)) - .assertNext(response -> { + StepVerifier + .create(this.credentials.generate( + UserParametersRequest.builder().name(CREDENTIAL_NAME).mode(WriteMode.NO_OVERWRITE) + .username("test-user").parameters(this.passwordParameters.build()).build(), + UserCredential.class)) + .assertNext((response) -> { assertThat(response.getValue().getUsername()).isEqualTo("test-user"); assertThat(response.getValue().getPassword()).isEqualTo(generated.get().getValue().getPassword()); - assertThat(response.getValue().getPasswordHash()).isEqualTo(generated.get().getValue().getPasswordHash()); - }) - .verifyComplete(); + assertThat(response.getValue().getPasswordHash()) + .isEqualTo(generated.get().getValue().getPasswordHash()); + }).verifyComplete(); } @Test public void generateOverwriteCredential() { AtomicReference> generated = new AtomicReference<>(); - StepVerifier.create(credentials.generate(UserParametersRequest.builder() - .name(CREDENTIAL_NAME) - .username("test-user") - .parameters(passwordParameters.build()) - .build(), UserCredential.class)) - .assertNext(response -> { + StepVerifier.create(this.credentials.generate(UserParametersRequest.builder().name(CREDENTIAL_NAME) + .username("test-user").parameters(this.passwordParameters.build()).build(), UserCredential.class)) + .assertNext((response) -> { assertThat(response.getName().getName()).isEqualTo(CREDENTIAL_NAME.getName()); assertThat(response.getValue().getUsername()).isEqualTo("test-user"); assertThat(response.getValue().getPassword()).matches("^[a-zA-Z0-9\\p{Punct}]{12}$"); assertThat(response.getValue().getPasswordHash()).isNotNull(); generated.set(response); - }) - .verifyComplete(); + }).verifyComplete(); - StepVerifier.create(credentials.generate(UserParametersRequest.builder() - .name(CREDENTIAL_NAME) - .mode(WriteMode.OVERWRITE) - .username("test-user") - .parameters(passwordParameters.build()) - .build(), UserCredential.class)) - .assertNext(response -> { + StepVerifier + .create(this.credentials.generate( + UserParametersRequest.builder().name(CREDENTIAL_NAME).mode(WriteMode.OVERWRITE) + .username("test-user").parameters(this.passwordParameters.build()).build(), + UserCredential.class)) + .assertNext((response) -> { assertThat(response.getValue().getUsername()).isEqualTo("test-user"); - assertThat(response.getValue().getPassword()).isNotEqualTo(generated.get().getValue().getPassword()); - assertThat(response.getValue().getPasswordHash()).isNotEqualTo(generated.get().getValue().getPasswordHash()); + assertThat(response.getValue().getPassword()) + .isNotEqualTo(generated.get().getValue().getPassword()); + assertThat(response.getValue().getPasswordHash()) + .isNotEqualTo(generated.get().getValue().getPasswordHash()); }).verifyComplete(); } @@ -319,51 +277,43 @@ public class ReactiveCredentialIntegrationTests extends ReactiveCredHubIntegrati public void generateConvergeCredential() { AtomicReference> generated = new AtomicReference<>(); - StepVerifier.create(credentials.generate(UserParametersRequest.builder() - .name(CREDENTIAL_NAME) - .username("test-user") - .parameters(passwordParameters.build()) - .build(), UserCredential.class)) - .assertNext(response -> { + StepVerifier.create(this.credentials.generate(UserParametersRequest.builder().name(CREDENTIAL_NAME) + .username("test-user").parameters(this.passwordParameters.build()).build(), UserCredential.class)) + .assertNext((response) -> { assertThat(response.getName().getName()).isEqualTo(CREDENTIAL_NAME.getName()); assertThat(response.getValue().getUsername()).isEqualTo("test-user"); assertThat(response.getValue().getPassword()).matches("^[a-zA-Z0-9\\p{Punct}]{12}$"); assertThat(response.getValue().getPasswordHash()).isNotNull(); generated.set(response); - }) - .verifyComplete(); + }).verifyComplete(); - StepVerifier.create(credentials.generate(UserParametersRequest.builder() - .name(CREDENTIAL_NAME) - .mode(WriteMode.CONVERGE) - .username("test-user") - .parameters(passwordParameters.build()) - .build(), UserCredential.class)) - .assertNext(response -> { + StepVerifier + .create(this.credentials.generate( + UserParametersRequest.builder().name(CREDENTIAL_NAME).mode(WriteMode.CONVERGE) + .username("test-user").parameters(this.passwordParameters.build()).build(), + UserCredential.class)) + .assertNext((response) -> { assertThat(response.getValue().getUsername()).isEqualTo("test-user"); - assertThat(response.getValue().getPassword()) - .isEqualTo(generated.get().getValue().getPassword()); + assertThat(response.getValue().getPassword()).isEqualTo(generated.get().getValue().getPassword()); assertThat(response.getValue().getPasswordHash()) .isEqualTo(generated.get().getValue().getPasswordHash()); - }) - .verifyComplete(); + }).verifyComplete(); - passwordParameters.includeSpecial(false); + this.passwordParameters.includeSpecial(false); - StepVerifier.create(credentials.generate(UserParametersRequest.builder() - .name(CREDENTIAL_NAME) - .mode(WriteMode.CONVERGE) - .username("test-user") - .parameters(passwordParameters.build()) - .build(), UserCredential.class)) - .assertNext(response -> { + StepVerifier + .create(this.credentials.generate( + UserParametersRequest.builder().name(CREDENTIAL_NAME).mode(WriteMode.CONVERGE) + .username("test-user").parameters(this.passwordParameters.build()).build(), + UserCredential.class)) + .assertNext((response) -> { assertThat(response.getValue().getUsername()).isEqualTo("test-user"); assertThat(response.getValue().getPassword()) .isNotEqualTo(generated.get().getValue().getPassword()); assertThat(response.getValue().getPasswordHash()) .isNotEqualTo(generated.get().getValue().getPasswordHash()); - }) - .verifyComplete(); + }).verifyComplete(); } + } diff --git a/spring-credhub-reactive-integration-tests/src/test/java/org/springframework/credhub/integration/ReactiveInfoIntegrationTests.java b/spring-credhub-reactive-integration-tests/src/test/java/org/springframework/credhub/integration/ReactiveInfoIntegrationTests.java index 97e30b3..a61b2fb 100644 --- a/spring-credhub-reactive-integration-tests/src/test/java/org/springframework/credhub/integration/ReactiveInfoIntegrationTests.java +++ b/spring-credhub-reactive-integration-tests/src/test/java/org/springframework/credhub/integration/ReactiveInfoIntegrationTests.java @@ -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,23 +18,25 @@ package org.springframework.credhub.integration; import org.junit.Before; import org.junit.Test; -import org.springframework.credhub.core.info.ReactiveCredHubInfoOperations; import reactor.test.StepVerifier; +import org.springframework.credhub.core.info.ReactiveCredHubInfoOperations; + import static org.assertj.core.api.Assertions.assertThat; public class ReactiveInfoIntegrationTests extends ReactiveCredHubIntegrationTests { + private ReactiveCredHubInfoOperations info; @Before public void setUp() { - info = operations.info(); + this.info = this.operations.info(); } @Test public void getInfo() { - StepVerifier.create(info.version()) - .assertNext(response -> assertThat(response.getVersion()).isNotNull()) + StepVerifier.create(this.info.version()).assertNext((response) -> assertThat(response.getVersion()).isNotNull()) .verifyComplete(); } + } diff --git a/spring-credhub-reactive-integration-tests/src/test/java/org/springframework/credhub/integration/ReactiveInterpolationIntegrationTests.java b/spring-credhub-reactive-integration-tests/src/test/java/org/springframework/credhub/integration/ReactiveInterpolationIntegrationTests.java index 43b60b3..89423c2 100644 --- a/spring-credhub-reactive-integration-tests/src/test/java/org/springframework/credhub/integration/ReactiveInterpolationIntegrationTests.java +++ b/spring-credhub-reactive-integration-tests/src/test/java/org/springframework/credhub/integration/ReactiveInterpolationIntegrationTests.java @@ -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,16 @@ package org.springframework.credhub.integration; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.After; import org.junit.Before; import org.junit.Test; +import reactor.test.StepVerifier; + import org.springframework.credhub.core.credential.ReactiveCredHubCredentialOperations; import org.springframework.credhub.core.interpolation.ReactiveCredHubInterpolationOperations; import org.springframework.credhub.support.CredentialType; @@ -27,25 +33,22 @@ import org.springframework.credhub.support.ServicesData; import org.springframework.credhub.support.SimpleCredentialName; import org.springframework.credhub.support.json.JsonCredentialRequest; import org.springframework.credhub.support.utils.JsonUtils; -import reactor.test.StepVerifier; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; public class ReactiveInterpolationIntegrationTests extends ReactiveCredHubIntegrationTests { - private static final SimpleCredentialName CREDENTIAL_NAME = - new SimpleCredentialName("spring-credhub", "integration-test", "interpolation-credential"); + + private static final SimpleCredentialName CREDENTIAL_NAME = new SimpleCredentialName("spring-credhub", + "integration-test", "interpolation-credential"); private ReactiveCredHubInterpolationOperations interpolation; + private ReactiveCredHubCredentialOperations credentials; @Before public void setUp() { - this.interpolation = operations.interpolation(); - this.credentials = operations.credentials(); + this.interpolation = this.operations.interpolation(); + this.credentials = this.operations.credentials(); } @After @@ -56,41 +59,39 @@ public class ReactiveInterpolationIntegrationTests extends ReactiveCredHubIntegr @Test @SuppressWarnings("unchecked") public void interpolate() throws IOException { - Map json = new HashMap() {{ - put("url", "https://example.com"); - put("username", "user"); - put("password", "secret"); - }}; + Map json = new HashMap() { + { + put("url", "https://example.com"); + put("username", "user"); + put("password", "secret"); + } + }; - StepVerifier.create(credentials.write(JsonCredentialRequest.builder() - .name(CREDENTIAL_NAME) - .value(json) - .build())) - .assertNext(response -> { + StepVerifier + .create(this.credentials + .write(JsonCredentialRequest.builder().name(CREDENTIAL_NAME).value(json).build())) + .assertNext((response) -> { assertThat(response.getName().getName()).isEqualTo(CREDENTIAL_NAME.getName()); assertThat(response.getValue()).isEqualTo(json); assertThat(response.getCredentialType()).isEqualTo(CredentialType.JSON); assertThat(response.getId()).isNotNull(); - }) - .verifyComplete(); + }).verifyComplete(); - StepVerifier.create(interpolation.interpolateServiceData(buildVcapServices(CREDENTIAL_NAME.getName()))) - .assertNext(servicesData -> { + StepVerifier.create(this.interpolation.interpolateServiceData(buildVcapServices(CREDENTIAL_NAME.getName()))) + .assertNext((servicesData) -> { assertThat(servicesData).containsKey("service-offering"); assertThat(servicesData.get("service-offering")).hasSize(1); assertThat(servicesData.get("service-offering").get(0)).containsKey("credentials"); - Map credentials = - (Map) servicesData.get("service-offering").get(0).get("credentials"); - assertThat(credentials) - .containsEntry("url", "https://example.com") - .containsEntry("username", "user") - .containsEntry("password", "secret"); - }) - .verifyComplete(); + Map credentials = (Map) servicesData.get("service-offering").get(0) + .get("credentials"); + assertThat(credentials).containsEntry("url", "https://example.com") + .containsEntry("username", "user").containsEntry("password", "secret"); + }).verifyComplete(); } private ServicesData buildVcapServices(String credHubReferenceName) throws IOException { + // @formatter:off String vcapServices = "{" + " \"service-offering\": [" + " {" + @@ -107,8 +108,10 @@ public class ReactiveInterpolationIntegrationTests extends ReactiveCredHubIntegr " }" + " ]" + "}"; + // @formatter:on ObjectMapper mapper = JsonUtils.buildObjectMapper(); return mapper.readValue(vcapServices, ServicesData.class); } + } diff --git a/spring-credhub-reactive-integration-tests/src/test/java/org/springframework/credhub/integration/ReactivePermissionIntegrationTests.java b/spring-credhub-reactive-integration-tests/src/test/java/org/springframework/credhub/integration/ReactivePermissionIntegrationTests.java index 878adad..64a87e9 100644 --- a/spring-credhub-reactive-integration-tests/src/test/java/org/springframework/credhub/integration/ReactivePermissionIntegrationTests.java +++ b/spring-credhub-reactive-integration-tests/src/test/java/org/springframework/credhub/integration/ReactivePermissionIntegrationTests.java @@ -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,6 +19,9 @@ package org.springframework.credhub.integration; import org.junit.After; import org.junit.Before; import org.junit.Test; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + import org.springframework.credhub.core.credential.ReactiveCredHubCredentialOperations; import org.springframework.credhub.core.permission.ReactiveCredHubPermissionOperations; import org.springframework.credhub.support.SimpleCredentialName; @@ -27,24 +30,25 @@ import org.springframework.credhub.support.permissions.ActorType; import org.springframework.credhub.support.permissions.Operation; import org.springframework.credhub.support.permissions.Permission; import org.springframework.credhub.support.value.ValueCredentialRequest; -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assume.assumeTrue; public class ReactivePermissionIntegrationTests extends ReactiveCredHubIntegrationTests { - private static final SimpleCredentialName CREDENTIAL_NAME = - new SimpleCredentialName("spring-credhub", "integration-test", "test-permissions-credential"); + + private static final SimpleCredentialName CREDENTIAL_NAME = new SimpleCredentialName("spring-credhub", + "integration-test", "test-permissions-credential"); + private static final String CREDENTIAL_VALUE = "test-value"; private ReactiveCredHubCredentialOperations credentials; + private ReactiveCredHubPermissionOperations permissions; @Before public void setUp() { - credentials = operations.credentials(); - permissions = operations.permissions(); + this.credentials = this.operations.credentials(); + this.permissions = this.operations.permissions(); deleteCredentialIfExists(CREDENTIAL_NAME); deletePermissionsIfExist(); @@ -60,47 +64,36 @@ public class ReactivePermissionIntegrationTests extends ReactiveCredHubIntegrati public void managePermissionsServerV1() { assumeTrue(serverApiIsV1()); - StepVerifier.create(credentials.write(ValueCredentialRequest.builder() - .name(CREDENTIAL_NAME) - .value(CREDENTIAL_VALUE) - .build())) - .assertNext(response -> { + StepVerifier + .create(this.credentials + .write(ValueCredentialRequest.builder().name(CREDENTIAL_NAME).value(CREDENTIAL_VALUE).build())) + .assertNext((response) -> { assertThat(response.getName()).isEqualTo(CREDENTIAL_NAME); assertThat(response.getId()).isNotNull(); - }) - .verifyComplete(); + }).verifyComplete(); - Permission appPermission = Permission.builder() - .app("app1") - .operation(Operation.READ) - .build(); - Permission userPermission = Permission.builder() - .user("user1") - .operations(Operation.READ, Operation.WRITE, Operation.DELETE) - .build(); - Permission clientPermission = Permission.builder() - .client("client1") - .operations(Operation.READ_ACL, Operation.WRITE_ACL) - .build(); + Permission appPermission = Permission.builder().app("app1").operation(Operation.READ).build(); + Permission userPermission = Permission.builder().user("user1") + .operations(Operation.READ, Operation.WRITE, Operation.DELETE).build(); + Permission clientPermission = Permission.builder().client("client1") + .operations(Operation.READ_ACL, Operation.WRITE_ACL).build(); - StepVerifier.create(permissions.addPermissions(CREDENTIAL_NAME, - appPermission, - userPermission, - clientPermission)) - .expectComplete() - .verify(); + StepVerifier.create( + this.permissions.addPermissions(CREDENTIAL_NAME, appPermission, userPermission, clientPermission)) + .expectComplete().verify(); - StepVerifier.create(permissions.getPermissions(CREDENTIAL_NAME)) - .assertNext(response -> assertThat(response.getActor().getAuthType()).isEqualTo(ActorType.OAUTH_CLIENT)) - .assertNext(response -> assertThat(response).isEqualTo(appPermission)) - .assertNext(response -> assertThat(response).isEqualTo(userPermission)) - .assertNext(response -> assertThat(response).isEqualTo(clientPermission)) - .verifyComplete(); + StepVerifier.create(this.permissions.getPermissions(CREDENTIAL_NAME)) + .assertNext( + (response) -> assertThat(response.getActor().getAuthType()).isEqualTo(ActorType.OAUTH_CLIENT)) + .assertNext((response) -> assertThat(response).isEqualTo(appPermission)) + .assertNext((response) -> assertThat(response).isEqualTo(userPermission)) + .assertNext((response) -> assertThat(response).isEqualTo(clientPermission)).verifyComplete(); deletePermissionsIfExist(); - StepVerifier.create(permissions.getPermissions(CREDENTIAL_NAME)) - .assertNext(response -> assertThat(response.getActor().getAuthType()).isEqualTo(ActorType.OAUTH_CLIENT)) + StepVerifier.create(this.permissions.getPermissions(CREDENTIAL_NAME)) + .assertNext( + (response) -> assertThat(response.getActor().getAuthType()).isEqualTo(ActorType.OAUTH_CLIENT)) .verifyComplete(); } @@ -108,58 +101,41 @@ public class ReactivePermissionIntegrationTests extends ReactiveCredHubIntegrati public void managePermissionsServerV2() { assumeTrue(serverApiIsV2()); - StepVerifier.create(credentials.write(ValueCredentialRequest.builder() - .name(CREDENTIAL_NAME) - .value(CREDENTIAL_VALUE) - .build())) - .assertNext(response -> { + StepVerifier + .create(this.credentials + .write(ValueCredentialRequest.builder().name(CREDENTIAL_NAME).value(CREDENTIAL_VALUE).build())) + .assertNext((response) -> { assertThat(response.getName()).isEqualTo(CREDENTIAL_NAME); assertThat(response.getId()).isNotNull(); - }) - .verifyComplete(); + }).verifyComplete(); - Permission appPermission = Permission.builder() - .app("app1") - .operation(Operation.READ) - .build(); - Permission userPermission = Permission.builder() - .user("user1") - .operations(Operation.READ, Operation.WRITE, Operation.DELETE) - .build(); - Permission clientPermission = Permission.builder() - .client("client1") - .operations(Operation.READ_ACL, Operation.WRITE_ACL) - .build(); + Permission appPermission = Permission.builder().app("app1").operation(Operation.READ).build(); + Permission userPermission = Permission.builder().user("user1") + .operations(Operation.READ, Operation.WRITE, Operation.DELETE).build(); + Permission clientPermission = Permission.builder().client("client1") + .operations(Operation.READ_ACL, Operation.WRITE_ACL).build(); - StepVerifier.create(permissions.addPermissions(CREDENTIAL_NAME, - appPermission, - userPermission, - clientPermission)) - .expectComplete() - .verify(); + StepVerifier.create( + this.permissions.addPermissions(CREDENTIAL_NAME, appPermission, userPermission, clientPermission)) + .expectComplete().verify(); - StepVerifier.create(permissions.getPermissions(CREDENTIAL_NAME)) - .assertNext(response -> assertThat(response).isEqualTo(appPermission)) - .assertNext(response -> assertThat(response).isEqualTo(userPermission)) - .assertNext(response -> assertThat(response).isEqualTo(clientPermission)) - .verifyComplete(); + StepVerifier.create(this.permissions.getPermissions(CREDENTIAL_NAME)) + .assertNext((response) -> assertThat(response).isEqualTo(appPermission)) + .assertNext((response) -> assertThat(response).isEqualTo(userPermission)) + .assertNext((response) -> assertThat(response).isEqualTo(clientPermission)).verifyComplete(); deletePermissionsIfExist(); - StepVerifier.create(permissions.getPermissions(CREDENTIAL_NAME)) - .expectComplete() - .verify(); + StepVerifier.create(this.permissions.getPermissions(CREDENTIAL_NAME)).expectComplete().verify(); } private void deletePermissionsIfExist() { - permissions.deletePermission(CREDENTIAL_NAME, Actor.app("app1")) - .onErrorResume(e -> Mono.empty()) + this.permissions.deletePermission(CREDENTIAL_NAME, Actor.app("app1")).onErrorResume((e) -> Mono.empty()) .block(); - permissions.deletePermission(CREDENTIAL_NAME, Actor.user("user1")) - .onErrorResume(e -> Mono.empty()) + this.permissions.deletePermission(CREDENTIAL_NAME, Actor.user("user1")).onErrorResume((e) -> Mono.empty()) .block(); - permissions.deletePermission(CREDENTIAL_NAME, Actor.client("client1")) - .onErrorResume(e -> Mono.empty()) + this.permissions.deletePermission(CREDENTIAL_NAME, Actor.client("client1")).onErrorResume((e) -> Mono.empty()) .block(); } + } diff --git a/spring-credhub-reactive-integration-tests/src/test/java/org/springframework/credhub/integration/ReactivePermissionV2IntegrationTests.java b/spring-credhub-reactive-integration-tests/src/test/java/org/springframework/credhub/integration/ReactivePermissionV2IntegrationTests.java index 9d976b5..e9556ba 100644 --- a/spring-credhub-reactive-integration-tests/src/test/java/org/springframework/credhub/integration/ReactivePermissionV2IntegrationTests.java +++ b/spring-credhub-reactive-integration-tests/src/test/java/org/springframework/credhub/integration/ReactivePermissionV2IntegrationTests.java @@ -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,14 @@ package org.springframework.credhub.integration; +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; + import org.junit.After; import org.junit.Before; import org.junit.Test; +import reactor.test.StepVerifier; + import org.springframework.credhub.core.credential.ReactiveCredHubCredentialOperations; import org.springframework.credhub.core.permissionV2.ReactiveCredHubPermissionV2Operations; import org.springframework.credhub.support.CredentialPermission; @@ -28,27 +33,25 @@ import org.springframework.credhub.support.permissions.ActorType; import org.springframework.credhub.support.permissions.Operation; import org.springframework.credhub.support.permissions.Permission; import org.springframework.credhub.support.value.ValueCredentialRequest; -import reactor.test.StepVerifier; - -import java.util.List; -import java.util.concurrent.atomic.AtomicReference; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assume.assumeTrue; -import static org.springframework.credhub.support.permissions.ActorType.OAUTH_CLIENT; public class ReactivePermissionV2IntegrationTests extends ReactiveCredHubIntegrationTests { - private static final SimpleCredentialName CREDENTIAL_NAME = - new SimpleCredentialName("spring-credhub", "integration-test", "test-permissionsV2-credential"); + + private static final SimpleCredentialName CREDENTIAL_NAME = new SimpleCredentialName("spring-credhub", + "integration-test", "test-permissionsV2-credential"); + private static final String CREDENTIAL_VALUE = "test-value"; private ReactiveCredHubCredentialOperations credentials; + private ReactiveCredHubPermissionV2Operations permissions; @Before public void setUp() { - credentials = operations.credentials(); - permissions = operations.permissionsV2(); + this.credentials = this.operations.credentials(); + this.permissions = this.operations.permissionsV2(); deleteCredentialIfExists(CREDENTIAL_NAME); } @@ -64,44 +67,35 @@ public class ReactivePermissionV2IntegrationTests extends ReactiveCredHubIntegra AtomicReference permissionId = new AtomicReference<>(); - StepVerifier.create(credentials.write(ValueCredentialRequest.builder() - .name(CREDENTIAL_NAME) - .value(CREDENTIAL_VALUE) - .build())) - .assertNext(response -> { + StepVerifier + .create(this.credentials + .write(ValueCredentialRequest.builder().name(CREDENTIAL_NAME).value(CREDENTIAL_VALUE).build())) + .assertNext((response) -> { assertThat(response.getName()).isEqualTo(CREDENTIAL_NAME); assertThat(response.getId()).isNotNull(); - }) - .verifyComplete(); + }).verifyComplete(); - Permission clientPermission = Permission.builder() - .client("client1") - .operations(Operation.READ, Operation.WRITE, Operation.DELETE) - .build(); + Permission clientPermission = Permission.builder().client("client1") + .operations(Operation.READ, Operation.WRITE, Operation.DELETE).build(); - StepVerifier.create(permissions.addPermissions(CREDENTIAL_NAME, clientPermission)) - .assertNext(response -> { + StepVerifier.create(this.permissions.addPermissions(CREDENTIAL_NAME, clientPermission)) + .assertNext((response) -> { assertThat(response.getId()).isNotNull(); assertThat(response.getPath()).isEqualTo(CREDENTIAL_NAME.getName()); - assertPermissions(response, OAUTH_CLIENT, "client1", - Operation.READ, Operation.WRITE, Operation.DELETE); + assertPermissions(response, ActorType.OAUTH_CLIENT, "client1", Operation.READ, Operation.WRITE, + Operation.DELETE); permissionId.set(response.getId()); - }) - .verifyComplete(); + }).verifyComplete(); - StepVerifier.create(permissions.getPermissions(permissionId.get())) - .assertNext(response -> { - assertThat(response.getId()).isEqualTo(permissionId.get()); - assertThat(response.getPath()).isEqualTo(CREDENTIAL_NAME.getName()); - assertPermissions(response, OAUTH_CLIENT, "client1", - Operation.READ, Operation.WRITE, Operation.DELETE); - }) - .verifyComplete(); + StepVerifier.create(this.permissions.getPermissions(permissionId.get())).assertNext((response) -> { + assertThat(response.getId()).isEqualTo(permissionId.get()); + assertThat(response.getPath()).isEqualTo(CREDENTIAL_NAME.getName()); + assertPermissions(response, ActorType.OAUTH_CLIENT, "client1", Operation.READ, Operation.WRITE, + Operation.DELETE); + }).verifyComplete(); - StepVerifier.create(permissions.deletePermission(permissionId.get())) - .expectComplete() - .verify(); + StepVerifier.create(this.permissions.deletePermission(permissionId.get())).expectComplete().verify(); } @Test @@ -110,62 +104,49 @@ public class ReactivePermissionV2IntegrationTests extends ReactiveCredHubIntegra AtomicReference permissionId = new AtomicReference<>(); - StepVerifier.create(credentials.write(ValueCredentialRequest.builder() - .name(CREDENTIAL_NAME) - .value(CREDENTIAL_VALUE) - .build())) - .assertNext(response -> { + StepVerifier + .create(this.credentials + .write(ValueCredentialRequest.builder().name(CREDENTIAL_NAME).value(CREDENTIAL_VALUE).build())) + .assertNext((response) -> { assertThat(response.getName()).isEqualTo(CREDENTIAL_NAME); assertThat(response.getId()).isNotNull(); - }) - .verifyComplete(); + }).verifyComplete(); - Permission clientPermission = Permission.builder() - .client("client1") - .operations(Operation.READ, Operation.WRITE, Operation.DELETE) - .build(); + Permission clientPermission = Permission.builder().client("client1") + .operations(Operation.READ, Operation.WRITE, Operation.DELETE).build(); - StepVerifier.create(permissions.addPermissions(CREDENTIAL_NAME, clientPermission)) - .assertNext(response -> { + StepVerifier.create(this.permissions.addPermissions(CREDENTIAL_NAME, clientPermission)) + .assertNext((response) -> { assertThat(response.getId()).isNotNull(); assertThat(response.getPath()).isEqualTo(CREDENTIAL_NAME.getName()); - assertPermissions(response, OAUTH_CLIENT, "client1", - Operation.READ, Operation.WRITE, Operation.DELETE); + assertPermissions(response, ActorType.OAUTH_CLIENT, "client1", Operation.READ, Operation.WRITE, + Operation.DELETE); permissionId.set(response.getId()); - }) - .verifyComplete(); + }).verifyComplete(); - Permission newPermission = Permission.builder() - .client("client1") - .operations(Operation.READ_ACL, Operation.WRITE_ACL) - .build(); + Permission newPermission = Permission.builder().client("client1") + .operations(Operation.READ_ACL, Operation.WRITE_ACL).build(); - StepVerifier.create(permissions.updatePermissions(permissionId.get(), CREDENTIAL_NAME, newPermission)) - .assertNext(response -> { + StepVerifier.create(this.permissions.updatePermissions(permissionId.get(), CREDENTIAL_NAME, newPermission)) + .assertNext((response) -> { assertThat(response.getId()).isEqualTo(permissionId.get()); assertThat(response.getPath()).isEqualTo(CREDENTIAL_NAME.getName()); - assertPermissions(response, OAUTH_CLIENT, "client1", - Operation.READ_ACL, Operation.WRITE_ACL); - }) - .verifyComplete(); + assertPermissions(response, ActorType.OAUTH_CLIENT, "client1", Operation.READ_ACL, + Operation.WRITE_ACL); + }).verifyComplete(); - StepVerifier.create(permissions.getPermissions(permissionId.get())) - .assertNext(response -> { - assertThat(response.getId()).isEqualTo(permissionId.get()); - assertThat(response.getPath()).isEqualTo(CREDENTIAL_NAME.getName()); - assertPermissions(response, OAUTH_CLIENT, "client1", - Operation.READ_ACL, Operation.WRITE_ACL); - }) - .verifyComplete(); + StepVerifier.create(this.permissions.getPermissions(permissionId.get())).assertNext((response) -> { + assertThat(response.getId()).isEqualTo(permissionId.get()); + assertThat(response.getPath()).isEqualTo(CREDENTIAL_NAME.getName()); + assertPermissions(response, ActorType.OAUTH_CLIENT, "client1", Operation.READ_ACL, Operation.WRITE_ACL); + }).verifyComplete(); - StepVerifier.create(permissions.deletePermission(permissionId.get())) - .expectComplete() - .verify(); + StepVerifier.create(this.permissions.deletePermission(permissionId.get())).expectComplete().verify(); } - private void assertPermissions(CredentialPermission credentialPermission, - ActorType actorType, String actorId, Operation... operations) { + private void assertPermissions(CredentialPermission credentialPermission, ActorType actorType, String actorId, + Operation... operations) { Actor actor = credentialPermission.getPermission().getActor(); assertThat(actor.getAuthType()).isEqualTo(actorType); assertThat(actor.getPrimaryIdentifier()).isEqualTo(actorId); @@ -173,4 +154,5 @@ public class ReactivePermissionV2IntegrationTests extends ReactiveCredHubIntegra List ops = credentialPermission.getPermission().getOperations(); assertThat(ops).containsExactlyInAnyOrder(operations); } + } diff --git a/spring-credhub-reactive-integration-tests/src/test/java/org/springframework/credhub/integration/TestApplication.java b/spring-credhub-reactive-integration-tests/src/test/java/org/springframework/credhub/integration/TestApplication.java index 7e5c130..eb06ca4 100644 --- a/spring-credhub-reactive-integration-tests/src/test/java/org/springframework/credhub/integration/TestApplication.java +++ b/spring-credhub-reactive-integration-tests/src/test/java/org/springframework/credhub/integration/TestApplication.java @@ -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. @@ -27,21 +27,24 @@ import org.springframework.security.oauth2.client.registration.ReactiveClientReg @SpringBootApplication public class TestApplication { + public static void main(String[] args) { SpringApplication.run(TestApplication.class, args); } @Configuration(proxyBeanMethods = false) static class ClientManagerConfiguration { + @Bean AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager reactiveClientManager( ReactiveClientRegistrationRepository clientRegistrationRepository, ReactiveOAuth2AuthorizedClientService authorizedClientService) { - AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager clientManager = - new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager( - clientRegistrationRepository, authorizedClientService); + AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager clientManager = new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager( + clientRegistrationRepository, authorizedClientService); clientManager.setAuthorizedClientProvider(new ClientCredentialsReactiveOAuth2AuthorizedClientProvider()); return clientManager; } + } + } diff --git a/spring-credhub-starter/build.gradle b/spring-credhub-starter/build.gradle index 41dea6f..80414c8 100644 --- a/spring-credhub-starter/build.gradle +++ b/spring-credhub-starter/build.gradle @@ -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, diff --git a/spring-credhub-starter/src/main/java/org/springframework/credhub/autoconfig/CredHubAutoConfiguration.java b/spring-credhub-starter/src/main/java/org/springframework/credhub/autoconfig/CredHubAutoConfiguration.java index 9c7b15e..d53d4a8 100644 --- a/spring-credhub-starter/src/main/java/org/springframework/credhub/autoconfig/CredHubAutoConfiguration.java +++ b/spring-credhub-starter/src/main/java/org/springframework/credhub/autoconfig/CredHubAutoConfiguration.java @@ -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,21 +28,21 @@ import org.springframework.credhub.support.ClientOptions; /** * {@link EnableAutoConfiguration Auto-configuration} for Spring CredHub support beans. - * + * * @author Scott Frederick * @author Daniel Lavoie */ @Configuration(proxyBeanMethods = false) @EnableConfigurationProperties public class CredHubAutoConfiguration { + /** * Create a {@link CredHubProperties} bean and populate it from properties. - * * @return a {@link CredHubProperties} bean */ @Bean @ConditionalOnMissingBean - @ConditionalOnProperty(value = "spring.credhub.url") + @ConditionalOnProperty("spring.credhub.url") @ConfigurationProperties(prefix = "spring.credhub") public CredHubProperties credHubProperties() { return new CredHubProperties(); @@ -50,14 +50,14 @@ public class CredHubAutoConfiguration { /** * Create a {@link ClientOptions} bean and populate it from properties. - * * @return a {@link ClientOptions} bean */ @Bean @ConditionalOnMissingBean - @ConditionalOnProperty(value = "spring.credhub.url") + @ConditionalOnProperty("spring.credhub.url") @ConfigurationProperties(prefix = "spring.credhub") public ClientOptions clientOptions() { return new ClientOptions(); } + } diff --git a/spring-credhub-starter/src/main/java/org/springframework/credhub/autoconfig/CredHubOAuth2AutoConfiguration.java b/spring-credhub-starter/src/main/java/org/springframework/credhub/autoconfig/CredHubOAuth2AutoConfiguration.java index f144651..9f80f8e 100644 --- a/spring-credhub-starter/src/main/java/org/springframework/credhub/autoconfig/CredHubOAuth2AutoConfiguration.java +++ b/spring-credhub-starter/src/main/java/org/springframework/credhub/autoconfig/CredHubOAuth2AutoConfiguration.java @@ -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.autoconfig; +import java.util.ArrayList; +import java.util.List; + import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; @@ -41,17 +44,15 @@ import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepo import org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository; import org.springframework.security.oauth2.client.web.server.UnAuthenticatedServerOAuth2AuthorizedClientRepository; -import java.util.ArrayList; -import java.util.List; - /** - * {@link EnableAutoConfiguration Auto-configuration} for Spring CredHub OAuth2 support beans. + * {@link EnableAutoConfiguration Auto-configuration} for Spring CredHub OAuth2 support + * beans. * * @author Scott Frederick */ @Configuration(proxyBeanMethods = false) @EnableConfigurationProperties(OAuth2ClientProperties.class) -@AutoConfigureAfter({OAuth2ClientAutoConfiguration.class, ReactiveOAuth2ClientAutoConfiguration.class}) +@AutoConfigureAfter({ OAuth2ClientAutoConfiguration.class, ReactiveOAuth2ClientAutoConfiguration.class }) @ConditionalOnClass(name = "org.springframework.security.oauth2.client.registration.ClientRegistration") @ConditionalOnProperty("spring.credhub.oauth2.registration-id") @Conditional(ClientsConfiguredCondition.class) @@ -66,7 +67,6 @@ public class CredHubOAuth2AutoConfiguration { /** * Create a {@code ClientRegistrationRepository} bean for use with an OAuth2-enabled * {@code CredHubTemplate}. - * * @return the {@code ClientRegistrationRepository} */ @Bean @@ -74,15 +74,13 @@ public class CredHubOAuth2AutoConfiguration { @ConditionalOnClass(name = "javax.servlet.http.HttpServletRequest") public ClientRegistrationRepository credHubClientRegistrationRepository() { List registrations = new ArrayList<>( - OAuth2ClientPropertiesRegistrationAdapter - .getClientRegistrations(this.properties).values()); + OAuth2ClientPropertiesRegistrationAdapter.getClientRegistrations(this.properties).values()); return new InMemoryClientRegistrationRepository(registrations); } /** - * Create an {@code OAuth2AuthorizedClientRepository} bean for use with an OAuth2-enabled - * {@code CredHubTemplate}. - * + * Create an {@code OAuth2AuthorizedClientRepository} bean for use with an + * OAuth2-enabled {@code CredHubTemplate}. * @param clientRegistrationRepository a {@code ClientRegistrationRepository} * @return the {@code OAuth2AuthorizedClientRepository} */ @@ -92,14 +90,13 @@ public class CredHubOAuth2AutoConfiguration { public OAuth2AuthorizedClientRepository credHubAuthorizedClientRepository( ClientRegistrationRepository clientRegistrationRepository) { return new AuthenticatedPrincipalOAuth2AuthorizedClientRepository( - new InMemoryOAuth2AuthorizedClientService(clientRegistrationRepository)); + new InMemoryOAuth2AuthorizedClientService(clientRegistrationRepository)); } /** - * Create a {@code ReactiveClientRegistrationRepository} bean for use with an OAuth2-enabled - * {@code ReactiveCredHubTemplate}, in case + * Create a {@code ReactiveClientRegistrationRepository} bean for use with an + * OAuth2-enabled {@code ReactiveCredHubTemplate}, in case * {@link ReactiveOAuth2ClientAutoConfiguration} doesn't configure one. - * * @return the {@code ReactiveClientRegistrationRepository} */ @Bean @@ -107,16 +104,14 @@ public class CredHubOAuth2AutoConfiguration { @ConditionalOnClass(name = "org.springframework.web.reactive.function.client.WebClient") public ReactiveClientRegistrationRepository credHubReactiveClientRegistrationRepository() { List registrations = new ArrayList<>( - OAuth2ClientPropertiesRegistrationAdapter - .getClientRegistrations(this.properties).values()); + OAuth2ClientPropertiesRegistrationAdapter.getClientRegistrations(this.properties).values()); return new InMemoryReactiveClientRegistrationRepository(registrations); } /** - * Create a {@code ServerOAuth2AuthorizedClientRepository} bean for use with an OAuth2-enabled - * {@code ReactiveCredHubTemplate}, to override the default provided by + * Create a {@code ServerOAuth2AuthorizedClientRepository} bean for use with an + * OAuth2-enabled {@code ReactiveCredHubTemplate}, to override the default provided by * {@link ReactiveOAuth2ClientAutoConfiguration}. - * * @return the {@code ServerOAuth2AuthorizedClientRepository} */ @Bean @@ -125,4 +120,5 @@ public class CredHubOAuth2AutoConfiguration { public ServerOAuth2AuthorizedClientRepository credHubReactiveAuthorizedClientRepository() { return new UnAuthenticatedServerOAuth2AuthorizedClientRepository(); } -} \ No newline at end of file + +} diff --git a/spring-credhub-starter/src/main/java/org/springframework/credhub/autoconfig/CredHubTemplateAutoConfiguration.java b/spring-credhub-starter/src/main/java/org/springframework/credhub/autoconfig/CredHubTemplateAutoConfiguration.java index 82f3bf8..0f9b1aa 100644 --- a/spring-credhub-starter/src/main/java/org/springframework/credhub/autoconfig/CredHubTemplateAutoConfiguration.java +++ b/spring-credhub-starter/src/main/java/org/springframework/credhub/autoconfig/CredHubTemplateAutoConfiguration.java @@ -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,12 +32,10 @@ import org.springframework.credhub.core.CredHubTemplate; * @author Scott Frederick */ @Configuration(proxyBeanMethods = false) -@AutoConfigureAfter({CredHubAutoConfiguration.class, - CredHubOAuth2AutoConfiguration.class, - OAuth2ClientAutoConfiguration.class, - ReactiveOAuth2ClientAutoConfiguration.class}) +@AutoConfigureAfter({ CredHubAutoConfiguration.class, CredHubOAuth2AutoConfiguration.class, + OAuth2ClientAutoConfiguration.class, ReactiveOAuth2ClientAutoConfiguration.class }) @ConditionalOnBean(CredHubProperties.class) -@Import({CredHubTemplateConfiguration.class, ReactiveCredHubTemplateConfiguration.class}) +@Import({ CredHubTemplateConfiguration.class, ReactiveCredHubTemplateConfiguration.class }) public class CredHubTemplateAutoConfiguration { } diff --git a/spring-credhub-starter/src/main/java/org/springframework/credhub/autoconfig/CredHubTemplateConfiguration.java b/spring-credhub-starter/src/main/java/org/springframework/credhub/autoconfig/CredHubTemplateConfiguration.java index c6f4ebe..d6c1936 100644 --- a/spring-credhub-starter/src/main/java/org/springframework/credhub/autoconfig/CredHubTemplateConfiguration.java +++ b/spring-credhub-starter/src/main/java/org/springframework/credhub/autoconfig/CredHubTemplateConfiguration.java @@ -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,30 +41,30 @@ import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepo * @author Daniel Lavoie * @author Scott Frederick */ -@Import({CredHubTemplateBaseConfiguration.class, - CredHubTemplateOAuth2Configuration.class, - CredHubTemplateOAuth2ClientConfiguration.class}) +@Import({ CredHubTemplateBaseConfiguration.class, CredHubTemplateOAuth2Configuration.class, + CredHubTemplateOAuth2ClientConfiguration.class }) public class CredHubTemplateConfiguration { @Configuration(proxyBeanMethods = false) @ConditionalOnClass(name = "javax.servlet.http.HttpServletRequest") - @ConditionalOnProperty(prefix = "spring.credhub.oauth2", name = "registration-id", - havingValue = "false", matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.credhub.oauth2", name = "registration-id", havingValue = "false", + matchIfMissing = true) static class CredHubTemplateBaseConfiguration { + /** * Create the {@link CredHubTemplate} that the application will use to interact * with CredHub. - * * @param credHubProperties {@link CredHubProperties} for CredHub - * @param clientOptions client connection options + * @param clientOptions client connection options * @return the {@link CredHubOperations} bean */ @Bean @ConditionalOnMissingBean - public CredHubOperations credHubTemplate(CredHubProperties credHubProperties, ClientOptions clientOptions) { + CredHubOperations credHubTemplate(CredHubProperties credHubProperties, ClientOptions clientOptions) { return new CredHubTemplateFactory().credHubTemplate(credHubProperties, clientOptions); } + } @Configuration(proxyBeanMethods = false) @@ -72,26 +72,26 @@ public class CredHubTemplateConfiguration { @ConditionalOnProperty(prefix = "spring.credhub.oauth2", name = "registration-id") @ConditionalOnMissingBean(OAuth2AuthorizedClientManager.class) static class CredHubTemplateOAuth2Configuration { + /** * Create the {@link CredHubTemplate} that the application will use to interact * with CredHub. - * - * @param credHubProperties {@link CredHubProperties} for CredHub - * @param clientOptions client connection options + * @param credHubProperties {@link CredHubProperties} for CredHub + * @param clientOptions client 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 the {@link CredHubOperations} bean */ @Bean @ConditionalOnMissingBean - public CredHubOperations credHubTemplate( - CredHubProperties credHubProperties, ClientOptions clientOptions, + CredHubOperations credHubTemplate(CredHubProperties credHubProperties, ClientOptions clientOptions, ClientRegistrationRepository clientRegistrationRepository, OAuth2AuthorizedClientRepository authorizedClientRepository) { return new CredHubTemplateFactory().credHubTemplate(credHubProperties, clientOptions, clientRegistrationRepository, authorizedClientRepository); } + } @Configuration(proxyBeanMethods = false) @@ -99,26 +99,26 @@ public class CredHubTemplateConfiguration { @ConditionalOnProperty(prefix = "spring.credhub.oauth2", name = "registration-id") @ConditionalOnBean(OAuth2AuthorizedClientManager.class) static class CredHubTemplateOAuth2ClientConfiguration { + /** * Create the {@link CredHubTemplate} that the application will use to interact * with CredHub. - * - * @param credHubProperties {@link CredHubProperties} for CredHub - * @param clientOptions client connection options + * @param credHubProperties {@link CredHubProperties} for CredHub + * @param clientOptions client 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 the {@link CredHubTemplate} bean */ @Bean @ConditionalOnMissingBean - public CredHubOperations credHubTemplate( - CredHubProperties credHubProperties, ClientOptions clientOptions, + CredHubOperations credHubTemplate(CredHubProperties credHubProperties, ClientOptions clientOptions, ClientRegistrationRepository clientRegistrationRepository, OAuth2AuthorizedClientManager clientManager) { return new CredHubTemplateFactory().credHubTemplate(credHubProperties, clientOptions, clientRegistrationRepository, clientManager); } + } } diff --git a/spring-credhub-starter/src/main/java/org/springframework/credhub/autoconfig/ReactiveCredHubTemplateConfiguration.java b/spring-credhub-starter/src/main/java/org/springframework/credhub/autoconfig/ReactiveCredHubTemplateConfiguration.java index f5ca152..9c05a8e 100644 --- a/spring-credhub-starter/src/main/java/org/springframework/credhub/autoconfig/ReactiveCredHubTemplateConfiguration.java +++ b/spring-credhub-starter/src/main/java/org/springframework/credhub/autoconfig/ReactiveCredHubTemplateConfiguration.java @@ -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,57 +41,58 @@ import org.springframework.security.oauth2.client.web.server.ServerOAuth2Authori * * @author Scott Frederick */ -@Import({ReactiveCredHubTemplateBaseConfiguration.class, - ReactiveCredHubTemplateOAuth2Configuration.class, - ReactiveCredHubTemplateOAuth2ClientConfiguration.class}) +@Import({ ReactiveCredHubTemplateBaseConfiguration.class, ReactiveCredHubTemplateOAuth2Configuration.class, + ReactiveCredHubTemplateOAuth2ClientConfiguration.class }) public class ReactiveCredHubTemplateConfiguration { @Configuration(proxyBeanMethods = false) @ConditionalOnClass(name = "org.springframework.web.reactive.function.client.WebClient") - @ConditionalOnProperty(prefix = "spring.credhub.oauth2", name = "registration-id", havingValue = "false", matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.credhub.oauth2", name = "registration-id", havingValue = "false", + matchIfMissing = true) static class ReactiveCredHubTemplateBaseConfiguration { + /** - * Create the {@link ReactiveCredHubTemplate} that the application will use to interact - * with CredHub. - * + * Create the {@link ReactiveCredHubTemplate} that the application will use to + * interact with CredHub. * @param credHubProperties {@link CredHubProperties} for CredHub - * @param clientOptions client connection options + * @param clientOptions client connection options * @return the {@link CredHubTemplate} bean */ @Bean @ConditionalOnMissingBean - public ReactiveCredHubOperations reactiveCredHubTemplate(CredHubProperties credHubProperties, - ClientOptions clientOptions) { + ReactiveCredHubOperations reactiveCredHubTemplate(CredHubProperties credHubProperties, + ClientOptions clientOptions) { return new CredHubTemplateFactory().reactiveCredHubTemplate(credHubProperties, clientOptions); } + } @Configuration(proxyBeanMethods = false) - @ConditionalOnClass(name = {"org.springframework.web.reactive.function.client.WebClient"}) + @ConditionalOnClass(name = { "org.springframework.web.reactive.function.client.WebClient" }) @ConditionalOnProperty(prefix = "spring.credhub.oauth2", name = "registration-id") @ConditionalOnMissingBean(ReactiveOAuth2AuthorizedClientManager.class) static class ReactiveCredHubTemplateOAuth2Configuration { + /** - * Create the {@link ReactiveCredHubTemplate} that the application will use to interact - * with CredHub. - * - * @param credHubProperties {@link CredHubProperties} for CredHub - * @param clientOptions client connection options + * Create the {@link ReactiveCredHubTemplate} that the application will use to + * interact with CredHub. + * @param credHubProperties {@link CredHubProperties} for CredHub + * @param clientOptions client connection options * @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 the {@link CredHubTemplate} bean */ @Bean @ConditionalOnMissingBean - public ReactiveCredHubOperations reactiveCredHubTemplate( - CredHubProperties credHubProperties, ClientOptions clientOptions, - ReactiveClientRegistrationRepository clientRegistrationRepository, + ReactiveCredHubOperations reactiveCredHubTemplate(CredHubProperties credHubProperties, + ClientOptions clientOptions, ReactiveClientRegistrationRepository clientRegistrationRepository, ServerOAuth2AuthorizedClientRepository authorizedClientRepository) { return new CredHubTemplateFactory().reactiveCredHubTemplate(credHubProperties, clientOptions, clientRegistrationRepository, authorizedClientRepository); } + } @Configuration(proxyBeanMethods = false) @@ -99,24 +100,24 @@ public class ReactiveCredHubTemplateConfiguration { @ConditionalOnProperty(prefix = "spring.credhub.oauth2", name = "registration-id") @ConditionalOnBean(ReactiveOAuth2AuthorizedClientManager.class) static class ReactiveCredHubTemplateOAuth2ClientConfiguration { + /** - * Create the {@link ReactiveCredHubTemplate} that the application will use to interact - * with CredHub. - * + * Create the {@link ReactiveCredHubTemplate} that the application will use to + * interact with CredHub. * @param credHubProperties {@link CredHubProperties} for CredHub - * @param clientOptions client connection options - * @param clientManager an OAuth2 authorization client manager + * @param clientOptions client connection options + * @param clientManager an OAuth2 authorization client manager * @return the {@link CredHubTemplate} bean */ @Bean @ConditionalOnMissingBean - public ReactiveCredHubOperations reactiveCredHubTemplate( - CredHubProperties credHubProperties, ClientOptions clientOptions, - ReactiveOAuth2AuthorizedClientManager clientManager) { + ReactiveCredHubOperations reactiveCredHubTemplate(CredHubProperties credHubProperties, + ClientOptions clientOptions, ReactiveOAuth2AuthorizedClientManager clientManager) { return new CredHubTemplateFactory().reactiveCredHubTemplate(credHubProperties, clientOptions, clientManager); } + } } diff --git a/spring-credhub-starter/src/main/java/org/springframework/credhub/autoconfig/package-info.java b/spring-credhub-starter/src/main/java/org/springframework/credhub/autoconfig/package-info.java index 70ae29e..fb17f87 100644 --- a/spring-credhub-starter/src/main/java/org/springframework/credhub/autoconfig/package-info.java +++ b/spring-credhub-starter/src/main/java/org/springframework/credhub/autoconfig/package-info.java @@ -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 auto configuration support for Spring CredHub. */ -package org.springframework.credhub.autoconfig; \ No newline at end of file +package org.springframework.credhub.autoconfig; diff --git a/spring-credhub-starter/src/main/java/org/springframework/credhub/diagnostics/ClientNotConfiguredFailureAnalyzer.java b/spring-credhub-starter/src/main/java/org/springframework/credhub/diagnostics/ClientNotConfiguredFailureAnalyzer.java index 27b2631..af2b9a0 100644 --- a/spring-credhub-starter/src/main/java/org/springframework/credhub/diagnostics/ClientNotConfiguredFailureAnalyzer.java +++ b/spring-credhub-starter/src/main/java/org/springframework/credhub/diagnostics/ClientNotConfiguredFailureAnalyzer.java @@ -5,7 +5,7 @@ * 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,8 +25,8 @@ import org.springframework.boot.diagnostics.FailureAnalysis; import org.springframework.boot.diagnostics.FailureAnalyzer; /** - * A {@link FailureAnalyzer} that detects the condition when Spring CredHub has been configured - * with an OAuth2 client but beans required for this configuration are missing. + * A {@link FailureAnalyzer} that detects the condition when Spring CredHub has been + * configured with an OAuth2 client but beans required for this configuration are missing. * * @author Scott Frederick */ @@ -48,23 +48,24 @@ class ClientNotConfiguredFailureAnalyzer extends AbstractFailureAnalyzer notFoundBean) { - return notFoundBean != null && (notFoundBean.getName().contains("ClientRegistrationRepository") || - notFoundBean.getName().contains("OAuth2AuthorizedClientRepository")); + return notFoundBean != null && (notFoundBean.getName().contains("ClientRegistrationRepository") + || notFoundBean.getName().contains("OAuth2AuthorizedClientRepository")); } private String getDescription() { - return "A CredHub OAuth2 client registration is configured " + - "but Spring Security is not available or the Spring Security OAuth2 " + - "client registration not configured correctly."; + return "A CredHub OAuth2 client registration is configured " + + "but Spring Security is not available or the Spring Security OAuth2 " + + "client registration not configured correctly."; } private String getAction() { - return "Add Spring Security to the application classpath and configure properties for the " + - "OAuth2 client registration under 'spring.security.oauth2.client.registration'."; + return "Add Spring Security to the application classpath and configure properties for the " + + "OAuth2 client registration under 'spring.security.oauth2.client.registration'."; } @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = beanFactory; } + } diff --git a/spring-credhub-starter/src/test/java/org/springframework/credhub/autoconfig/CredHubAutoConfigurationTests.java b/spring-credhub-starter/src/test/java/org/springframework/credhub/autoconfig/CredHubAutoConfigurationTests.java index a4e031e..48d9e03 100644 --- a/spring-credhub-starter/src/test/java/org/springframework/credhub/autoconfig/CredHubAutoConfigurationTests.java +++ b/spring-credhub-starter/src/test/java/org/springframework/credhub/autoconfig/CredHubAutoConfigurationTests.java @@ -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.autoconfig; +import java.time.Duration; + import org.junit.Test; + import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.context.properties.ConfigurationProperties; @@ -30,54 +33,36 @@ import org.springframework.credhub.support.ClientOptions; import org.springframework.http.client.reactive.ClientHttpConnector; import org.springframework.web.reactive.function.client.WebClient; -import java.time.Duration; - import static org.assertj.core.api.Assertions.assertThat; public class CredHubAutoConfigurationTests { private final ApplicationContextRunner context = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of( - CredHubAutoConfiguration.class - )); + .withConfiguration(AutoConfigurations.of(CredHubAutoConfiguration.class)); @Test public void autoConfiguredWithDefaultProperties() { - context - .withPropertyValues( - "spring.credhub.url=https://localhost", - "spring.credhub.oauth2.registration-id=test-client", - "spring.credhub.connection-timeout=30", - "spring.credhub.read-timeout=60", - "debug=true" - ) - .run(this::assertPropertiesConfigured); + this.context.withPropertyValues("spring.credhub.url=https://localhost", + "spring.credhub.oauth2.registration-id=test-client", "spring.credhub.connection-timeout=30", + "spring.credhub.read-timeout=60", "debug=true").run(this::assertPropertiesConfigured); } @Test public void autoConfiguredWithCustomProperties() { - context - .withConfiguration(AutoConfigurations.of(CustomPropertiesConfiguration.class)) - .withPropertyValues( - "my.custom.credhub.url=https://localhost", + this.context.withConfiguration(AutoConfigurations.of(CustomPropertiesConfiguration.class)) + .withPropertyValues("my.custom.credhub.url=https://localhost", "my.custom.credhub.oauth2.registration-id=test-client", - "my.custom.credhub.connection-timeout=30", - "my.custom.credhub.read-timeout=60" - ) + "my.custom.credhub.connection-timeout=30", "my.custom.credhub.read-timeout=60") .run(this::assertPropertiesConfigured); } @Test public void webClientConnectorNotConfigured() { - context - .withClassLoader(new FilteredClassLoader(WebClient.class)) - .withPropertyValues( - "spring.credhub.url=https://localhost", - "spring.credhub.oauth2.registration-id=test-client", - "spring.credhub.connection-timeout=30", - "spring.credhub.read-timeout=60" - ) - .run(context -> assertThat(context).doesNotHaveBean(ClientHttpConnector.class)); + this.context.withClassLoader(new FilteredClassLoader(WebClient.class)) + .withPropertyValues("spring.credhub.url=https://localhost", + "spring.credhub.oauth2.registration-id=test-client", "spring.credhub.connection-timeout=30", + "spring.credhub.read-timeout=60") + .run((context) -> assertThat(context).doesNotHaveBean(ClientHttpConnector.class)); } private void assertPropertiesConfigured(AssertableApplicationContext context) { @@ -95,6 +80,7 @@ public class CredHubAutoConfigurationTests { @Configuration @AutoConfigureBefore(CredHubAutoConfiguration.class) public static class CustomPropertiesConfiguration { + @Bean @ConfigurationProperties(prefix = "my.custom.credhub") public CredHubProperties credHubProperties() { @@ -106,5 +92,7 @@ public class CredHubAutoConfigurationTests { public ClientOptions clientOptions() { return new ClientOptions(); } + } + } diff --git a/spring-credhub-starter/src/test/java/org/springframework/credhub/autoconfig/CredHubOAuth2AutoConfigurationTests.java b/spring-credhub-starter/src/test/java/org/springframework/credhub/autoconfig/CredHubOAuth2AutoConfigurationTests.java index c5ba74d..c168069 100644 --- a/spring-credhub-starter/src/test/java/org/springframework/credhub/autoconfig/CredHubOAuth2AutoConfigurationTests.java +++ b/spring-credhub-starter/src/test/java/org/springframework/credhub/autoconfig/CredHubOAuth2AutoConfigurationTests.java @@ -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,6 +17,7 @@ package org.springframework.credhub.autoconfig; import org.junit.Test; + import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.FilteredClassLoader; import org.springframework.boot.test.context.assertj.ApplicationContextAssertProvider; @@ -31,45 +32,31 @@ import static org.assertj.core.api.Assertions.assertThat; public class CredHubOAuth2AutoConfigurationTests { - private final Class[] configurations = { - CredHubAutoConfiguration.class, - CredHubOAuth2AutoConfiguration.class - }; + private final Class[] configurations = { CredHubAutoConfiguration.class, CredHubOAuth2AutoConfiguration.class }; - private final String[] oAuth2ClientProperties = { - "spring.credhub.oauth2.registration-id=test-client", + private final String[] oAuth2ClientProperties = { "spring.credhub.oauth2.registration-id=test-client", "spring.security.oauth2.client.registration.credhub-client.provider=uaa", "spring.security.oauth2.client.registration.credhub-client.client-id=test-client", "spring.security.oauth2.client.registration.credhub-client.client-secret=test-secret", "spring.security.oauth2.client.registration.credhub-client.authorization-grant-type=client_credentials", - "spring.security.oauth2.client.provider.uaa.token-uri=https://example.com/uaa/oauth/token" - }; + "spring.security.oauth2.client.provider.uaa.token-uri=https://example.com/uaa/oauth/token" }; - private final ApplicationContextRunner context = new ApplicationContextRunner() - .withPropertyValues( - "debug=true" - ) - .withConfiguration(AutoConfigurations.of( - configurations - )); + private final ApplicationContextRunner context = new ApplicationContextRunner().withPropertyValues("debug=true") + .withConfiguration(AutoConfigurations.of(this.configurations)); @Test public void oauth2ContextConfigured() { - context - .withPropertyValues(oAuth2ClientProperties) - .run(context -> { - assertServletOAuth2ContextConfigured(context); - assertReactiveOAuth2ContextConfigured(context); - }); + this.context.withPropertyValues(this.oAuth2ClientProperties).run((context) -> { + assertServletOAuth2ContextConfigured(context); + assertReactiveOAuth2ContextConfigured(context); + }); } @Test public void oauth2ContextConfiguredWithoutWebClient() { - context - .withClassLoader(new FilteredClassLoader(WebClient.class)) - .withPropertyValues(oAuth2ClientProperties) - .run(context -> { + this.context.withClassLoader(new FilteredClassLoader(WebClient.class)) + .withPropertyValues(this.oAuth2ClientProperties).run((context) -> { assertServletOAuth2ContextConfigured(context); assertReactiveOAuth2ContextNotConfigured(context); }); @@ -77,10 +64,8 @@ public class CredHubOAuth2AutoConfigurationTests { @Test public void oauth2ContextConfiguredWithWebApp() { - new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(configurations)) - .withPropertyValues(oAuth2ClientProperties) - .run(context -> { + new WebApplicationContextRunner().withConfiguration(AutoConfigurations.of(this.configurations)) + .withPropertyValues(this.oAuth2ClientProperties).run((context) -> { assertServletOAuth2ContextConfigured(context); assertReactiveOAuth2ContextConfigured(context); }); @@ -88,10 +73,8 @@ public class CredHubOAuth2AutoConfigurationTests { @Test public void oauth2ContextConfiguredWithReactiveWebApp() { - new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(configurations)) - .withPropertyValues(oAuth2ClientProperties) - .run(context -> { + new ReactiveWebApplicationContextRunner().withConfiguration(AutoConfigurations.of(this.configurations)) + .withPropertyValues(this.oAuth2ClientProperties).run((context) -> { assertServletOAuth2ContextConfigured(context); assertReactiveOAuth2ContextConfigured(context); }); @@ -99,11 +82,9 @@ public class CredHubOAuth2AutoConfigurationTests { @Test public void oauth2ContextConfiguredWithReactiveWebAppNoServlet() { - new ReactiveWebApplicationContextRunner() - .withClassLoader(new FilteredClassLoader("javax.servlet")) - .withConfiguration(AutoConfigurations.of(configurations)) - .withPropertyValues(oAuth2ClientProperties) - .run(context -> { + new ReactiveWebApplicationContextRunner().withClassLoader(new FilteredClassLoader("javax.servlet")) + .withConfiguration(AutoConfigurations.of(this.configurations)) + .withPropertyValues(this.oAuth2ClientProperties).run((context) -> { assertServletOAuth2ContextNotConfigured(context); assertReactiveOAuth2ContextConfigured(context); }); @@ -111,14 +92,12 @@ public class CredHubOAuth2AutoConfigurationTests { @Test public void oauth2ContextNotConfiguredWithoutProperties() { - context - .run(this::assertOAuth2ContextNotConfigured); + this.context.run(this::assertOAuth2ContextNotConfigured); } @Test public void oauth2ContextNotConfiguredWithoutSpringSecurity() { - context - .withClassLoader(new FilteredClassLoader(ClientRegistration.class)) + this.context.withClassLoader(new FilteredClassLoader(ClientRegistration.class)) .run(this::assertOAuth2ContextNotConfigured); } @@ -156,4 +135,5 @@ public class CredHubOAuth2AutoConfigurationTests { assertServletOAuth2ContextNotConfigured(context); assertReactiveOAuth2ContextNotConfigured(context); } + } diff --git a/spring-credhub-starter/src/test/java/org/springframework/credhub/autoconfig/CredHubTemplateAutoConfigurationTests.java b/spring-credhub-starter/src/test/java/org/springframework/credhub/autoconfig/CredHubTemplateAutoConfigurationTests.java index a2b1690..1d4ecc8 100644 --- a/spring-credhub-starter/src/test/java/org/springframework/credhub/autoconfig/CredHubTemplateAutoConfigurationTests.java +++ b/spring-credhub-starter/src/test/java/org/springframework/credhub/autoconfig/CredHubTemplateAutoConfigurationTests.java @@ -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, @@ -54,32 +54,25 @@ import static org.assertj.core.api.Assertions.assertThat; public class CredHubTemplateAutoConfigurationTests { - private static final FilteredClassLoader SPRING_SECURITY_FILTERED_CLASS_LOADER = - new FilteredClassLoader("org.springframework.security.oauth2.client"); + private static final FilteredClassLoader SPRING_SECURITY_FILTERED_CLASS_LOADER = new FilteredClassLoader( + "org.springframework.security.oauth2.client"); - private static final FilteredClassLoader SERVLET_AND_SECURITY_FILTERED_CLASS_LOADER = - new FilteredClassLoader("javax.servlet.http.HttpServletRequest", - "org.springframework.security.oauth2.client"); + private static final FilteredClassLoader SERVLET_AND_SECURITY_FILTERED_CLASS_LOADER = new FilteredClassLoader( + "javax.servlet.http.HttpServletRequest", "org.springframework.security.oauth2.client"); - private static final FilteredClassLoader WEB_CLIENT_AND_SECURITY_FILTERED_CLASS_LOADER = - new FilteredClassLoader("org.springframework.web.reactive.function.client", - "org.springframework.security.oauth2.client"); + private static final FilteredClassLoader WEB_CLIENT_AND_SECURITY_FILTERED_CLASS_LOADER = new FilteredClassLoader( + "org.springframework.web.reactive.function.client", "org.springframework.security.oauth2.client"); private final ApplicationContextRunner context = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of( - ReactiveOAuth2ClientAutoConfiguration.class, - CredHubAutoConfiguration.class, - CredHubOAuth2AutoConfiguration.class, - CredHubTemplateAutoConfiguration.class - )) + .withConfiguration( + AutoConfigurations.of(ReactiveOAuth2ClientAutoConfiguration.class, CredHubAutoConfiguration.class, + CredHubOAuth2AutoConfiguration.class, CredHubTemplateAutoConfiguration.class)) .withInitializer(new ConditionEvaluationReportLoggingListener(LogLevel.INFO)); @Test public void credHubTemplatesConfigured() { - context - .withPropertyValues("spring.credhub.url=https://localhost") - .withClassLoader(SPRING_SECURITY_FILTERED_CLASS_LOADER) - .run(context -> { + this.context.withPropertyValues("spring.credhub.url=https://localhost") + .withClassLoader(SPRING_SECURITY_FILTERED_CLASS_LOADER).run((context) -> { assertThat(context).hasSingleBean(CredHubTemplate.class); CredHubTemplate credHubTemplate = context.getBean(CredHubTemplate.class); assertThat(credHubTemplate.isUsingOAuth2()).isFalse(); @@ -92,25 +85,21 @@ public class CredHubTemplateAutoConfigurationTests { @Test public void credHubTemplatesConfiguredWithSpringSecurityWithoutClientId() { - context - .withPropertyValues("spring.credhub.url=https://localhost") - .run(context -> { - assertThat(context).hasSingleBean(CredHubTemplate.class); - CredHubTemplate credHubTemplate = context.getBean(CredHubTemplate.class); - assertThat(credHubTemplate.isUsingOAuth2()).isFalse(); + this.context.withPropertyValues("spring.credhub.url=https://localhost").run((context) -> { + assertThat(context).hasSingleBean(CredHubTemplate.class); + CredHubTemplate credHubTemplate = context.getBean(CredHubTemplate.class); + assertThat(credHubTemplate.isUsingOAuth2()).isFalse(); - assertThat(context).hasSingleBean(ReactiveCredHubTemplate.class); - ReactiveCredHubTemplate reactiveCredHubTemplate = context.getBean(ReactiveCredHubTemplate.class); - assertThat(reactiveCredHubTemplate.isUsingOAuth2()).isFalse(); - }); + assertThat(context).hasSingleBean(ReactiveCredHubTemplate.class); + ReactiveCredHubTemplate reactiveCredHubTemplate = context.getBean(ReactiveCredHubTemplate.class); + assertThat(reactiveCredHubTemplate.isUsingOAuth2()).isFalse(); + }); } @Test public void reactiveCredHubTemplateNotConfiguredWithoutWebClient() { - context - .withPropertyValues("spring.credhub.url=https://localhost") - .withClassLoader(new FilteredClassLoader(WebClient.class)) - .run(context -> { + this.context.withPropertyValues("spring.credhub.url=https://localhost") + .withClassLoader(new FilteredClassLoader(WebClient.class)).run((context) -> { assertThat(context).hasSingleBean(CredHubTemplate.class); CredHubTemplate credHubTemplate = context.getBean(CredHubTemplate.class); assertThat(credHubTemplate.isUsingOAuth2()).isFalse(); @@ -121,18 +110,15 @@ public class CredHubTemplateAutoConfigurationTests { @Test public void credHubTemplatesConfiguredWithOAuth2() { - context - .withPropertyValues( - "spring.credhub.url=https://localhost", - "spring.credhub.oauth2.registration-id=credhub-client", + this.context.withPropertyValues("spring.credhub.url=https://localhost", + "spring.credhub.oauth2.registration-id=credhub-client", - "spring.security.oauth2.client.registration.credhub-client.provider=uaa", - "spring.security.oauth2.client.registration.credhub-client.client-id=test-client", - "spring.security.oauth2.client.registration.credhub-client.client-secret=test-secret", - "spring.security.oauth2.client.registration.credhub-client.authorization-grant-type=client_credentials", - "spring.security.oauth2.client.provider.uaa.token-uri=https://example.com/uaa/oauth/token" - ) - .run(context -> { + "spring.security.oauth2.client.registration.credhub-client.provider=uaa", + "spring.security.oauth2.client.registration.credhub-client.client-id=test-client", + "spring.security.oauth2.client.registration.credhub-client.client-secret=test-secret", + "spring.security.oauth2.client.registration.credhub-client.authorization-grant-type=client_credentials", + "spring.security.oauth2.client.provider.uaa.token-uri=https://example.com/uaa/oauth/token") + .run((context) -> { assertThat(context).hasSingleBean(CredHubTemplate.class); assertThat(context).hasSingleBean(ClientRegistrationRepository.class); assertThat(context).hasSingleBean(OAuth2AuthorizedClientRepository.class); @@ -151,19 +137,15 @@ public class CredHubTemplateAutoConfigurationTests { @Test public void credHubTemplatesConfiguredWithOAuth2AndCustomClientManager() { - context - .withPropertyValues( - "spring.credhub.url=https://localhost", - "spring.credhub.oauth2.registration-id=credhub-client", + this.context.withPropertyValues("spring.credhub.url=https://localhost", + "spring.credhub.oauth2.registration-id=credhub-client", - "spring.security.oauth2.client.registration.credhub-client.provider=uaa", - "spring.security.oauth2.client.registration.credhub-client.client-id=test-client", - "spring.security.oauth2.client.registration.credhub-client.client-secret=test-secret", - "spring.security.oauth2.client.registration.credhub-client.authorization-grant-type=client_credentials", - "spring.security.oauth2.client.provider.uaa.token-uri=https://example.com/uaa/oauth/token" - ) - .withUserConfiguration(ClientManagerConfiguration.class) - .run(context -> { + "spring.security.oauth2.client.registration.credhub-client.provider=uaa", + "spring.security.oauth2.client.registration.credhub-client.client-id=test-client", + "spring.security.oauth2.client.registration.credhub-client.client-secret=test-secret", + "spring.security.oauth2.client.registration.credhub-client.authorization-grant-type=client_credentials", + "spring.security.oauth2.client.provider.uaa.token-uri=https://example.com/uaa/oauth/token") + .withUserConfiguration(ClientManagerConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(CredHubTemplate.class); assertThat(context).hasSingleBean(ClientRegistrationRepository.class); assertThat(context).hasSingleBean(OAuth2AuthorizedClientRepository.class); @@ -174,7 +156,8 @@ public class CredHubTemplateAutoConfigurationTests { assertThat(context).hasSingleBean(ReactiveCredHubTemplate.class); assertThat(context).hasSingleBean(ReactiveClientRegistrationRepository.class); assertThat(context).hasSingleBean(ServerOAuth2AuthorizedClientRepository.class); - assertThat(context).hasSingleBean(AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager.class); + assertThat(context) + .hasSingleBean(AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager.class); ReactiveCredHubTemplate reactiveCredHubTemplate = context.getBean(ReactiveCredHubTemplate.class); assertThat(reactiveCredHubTemplate.isUsingOAuth2()).isTrue(); }); @@ -182,112 +165,94 @@ public class CredHubTemplateAutoConfigurationTests { @Test public void credHubTemplatesNotConfiguredWithInvalidClientRegistration() { - context - .withPropertyValues( - "spring.credhub.url=https://localhost", - "spring.credhub.oauth2.registration-id=invalid-client", + this.context.withPropertyValues("spring.credhub.url=https://localhost", + "spring.credhub.oauth2.registration-id=invalid-client", - "spring.security.oauth2.client.registration.credhub-client.provider=uaa", - "spring.security.oauth2.client.registration.credhub-client.client-id=test-client", - "spring.security.oauth2.client.registration.credhub-client.client-secret=test-secret", - "spring.security.oauth2.client.registration.credhub-client.authorization-grant-type=client_credentials", - "spring.security.oauth2.client.provider.uaa.token-uri=https://example.com/uaa/oauth/token" - ) - .run(context -> assertThat(context) - .getFailure() - .hasMessageContaining("The CredHub OAuth2 client registration ID 'invalid-client' is not a valid")); + "spring.security.oauth2.client.registration.credhub-client.provider=uaa", + "spring.security.oauth2.client.registration.credhub-client.client-id=test-client", + "spring.security.oauth2.client.registration.credhub-client.client-secret=test-secret", + "spring.security.oauth2.client.registration.credhub-client.authorization-grant-type=client_credentials", + "spring.security.oauth2.client.provider.uaa.token-uri=https://example.com/uaa/oauth/token") + .run((context) -> assertThat(context).getFailure().hasMessageContaining( + "The CredHub OAuth2 client registration ID 'invalid-client' is not a valid")); } @Test public void credHubTemplateNotConfiguredWithMissingClientRegistration() { - context - .withClassLoader(WEB_CLIENT_AND_SECURITY_FILTERED_CLASS_LOADER) - .withPropertyValues( - "spring.credhub.url=https://localhost", - "spring.credhub.oauth2.registration-id=credhub-client" - ) - .run(context -> assertThat(context) - .getFailure() + this.context.withClassLoader(WEB_CLIENT_AND_SECURITY_FILTERED_CLASS_LOADER) + .withPropertyValues("spring.credhub.url=https://localhost", + "spring.credhub.oauth2.registration-id=credhub-client") + .run((context) -> assertThat(context).getFailure() .hasMessageMatching(noSuchBeanExceptionMessage("ClientRegistrationRepository"))); } @Test public void reactiveCredHubTemplateNotConfiguredWithMissingClientRegistration() { - context - .withClassLoader(SERVLET_AND_SECURITY_FILTERED_CLASS_LOADER) - .withPropertyValues( - "spring.credhub.url=https://localhost", - "spring.credhub.oauth2.registration-id=credhub-client" - ) - .run(context -> assertThat(context) - .getFailure() + this.context.withClassLoader(SERVLET_AND_SECURITY_FILTERED_CLASS_LOADER) + .withPropertyValues("spring.credhub.url=https://localhost", + "spring.credhub.oauth2.registration-id=credhub-client") + .run((context) -> assertThat(context).getFailure() .hasMessageMatching(noSuchBeanExceptionMessage("ReactiveClientRegistrationRepository"))); } @Test public void credHubTemplateNotConfiguredWithOAuth2ButMissingSpringSecurity() { - context - .withClassLoader(WEB_CLIENT_AND_SECURITY_FILTERED_CLASS_LOADER) - .withPropertyValues( - "spring.credhub.url=https://localhost", - "spring.credhub.oauth2.registration-id=credhub-client", + this.context.withClassLoader(WEB_CLIENT_AND_SECURITY_FILTERED_CLASS_LOADER).withPropertyValues( + "spring.credhub.url=https://localhost", "spring.credhub.oauth2.registration-id=credhub-client", - "spring.security.oauth2.client.registration.credhub-client.provider=uaa", - "spring.security.oauth2.client.registration.credhub-client.client-id=test-client", - "spring.security.oauth2.client.registration.credhub-client.client-secret=test-secret", - "spring.security.oauth2.client.registration.credhub-client.authorization-grant-type=client_credentials", - "spring.security.oauth2.client.provider.uaa.token-uri=https://example.com/uaa/oauth/token" - ) - .run(context -> assertThat(context).hasFailed()); + "spring.security.oauth2.client.registration.credhub-client.provider=uaa", + "spring.security.oauth2.client.registration.credhub-client.client-id=test-client", + "spring.security.oauth2.client.registration.credhub-client.client-secret=test-secret", + "spring.security.oauth2.client.registration.credhub-client.authorization-grant-type=client_credentials", + "spring.security.oauth2.client.provider.uaa.token-uri=https://example.com/uaa/oauth/token") + .run((context) -> assertThat(context).hasFailed()); } @Test public void reactiveCredHubTemplateNotConfiguredWithOAuth2ButMissingSpringSecurity() { - context - .withClassLoader(SERVLET_AND_SECURITY_FILTERED_CLASS_LOADER) - .withPropertyValues( - "spring.credhub.url=https://localhost", - "spring.credhub.oauth2.registration-id=credhub-client", + this.context.withClassLoader(SERVLET_AND_SECURITY_FILTERED_CLASS_LOADER).withPropertyValues( + "spring.credhub.url=https://localhost", "spring.credhub.oauth2.registration-id=credhub-client", - "spring.security.oauth2.client.registration.credhub-client.provider=uaa", - "spring.security.oauth2.client.registration.credhub-client.client-id=test-client", - "spring.security.oauth2.client.registration.credhub-client.client-secret=test-secret", - "spring.security.oauth2.client.registration.credhub-client.authorization-grant-type=client_credentials", - "spring.security.oauth2.client.provider.uaa.token-uri=https://example.com/uaa/oauth/token" - ) - .run(context -> assertThat(context).hasFailed()); - } - - @Configuration(proxyBeanMethods = false) - static class ClientManagerConfiguration { - @Bean - AuthorizedClientServiceOAuth2AuthorizedClientManager clientManager(OAuth2ClientProperties properties) { - List registrations = new ArrayList<>( - OAuth2ClientPropertiesRegistrationAdapter - .getClientRegistrations(properties).values()); - ClientRegistrationRepository clientRegistrationRepository = - new InMemoryClientRegistrationRepository(registrations); - OAuth2AuthorizedClientService authorizedClientService = - new InMemoryOAuth2AuthorizedClientService(clientRegistrationRepository); - return new AuthorizedClientServiceOAuth2AuthorizedClientManager( - clientRegistrationRepository, authorizedClientService); - } - - @Bean - AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager reactiveClientManager(OAuth2ClientProperties properties) { - List registrations = new ArrayList<>( - OAuth2ClientPropertiesRegistrationAdapter - .getClientRegistrations(properties).values()); - ReactiveClientRegistrationRepository clientRegistrationRepository = - new InMemoryReactiveClientRegistrationRepository(registrations); - ReactiveOAuth2AuthorizedClientService authorizedClientService = - new InMemoryReactiveOAuth2AuthorizedClientService(clientRegistrationRepository); - return new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager( - clientRegistrationRepository, authorizedClientService); - } + "spring.security.oauth2.client.registration.credhub-client.provider=uaa", + "spring.security.oauth2.client.registration.credhub-client.client-id=test-client", + "spring.security.oauth2.client.registration.credhub-client.client-secret=test-secret", + "spring.security.oauth2.client.registration.credhub-client.authorization-grant-type=client_credentials", + "spring.security.oauth2.client.provider.uaa.token-uri=https://example.com/uaa/oauth/token") + .run((context) -> assertThat(context).hasFailed()); } private String noSuchBeanExceptionMessage(final String className) { return ".*No qualifying bean of type '.*" + className + "' available.*"; } + + @Configuration(proxyBeanMethods = false) + static class ClientManagerConfiguration { + + @Bean + AuthorizedClientServiceOAuth2AuthorizedClientManager clientManager(OAuth2ClientProperties properties) { + List registrations = new ArrayList<>( + OAuth2ClientPropertiesRegistrationAdapter.getClientRegistrations(properties).values()); + ClientRegistrationRepository clientRegistrationRepository = new InMemoryClientRegistrationRepository( + registrations); + OAuth2AuthorizedClientService authorizedClientService = new InMemoryOAuth2AuthorizedClientService( + clientRegistrationRepository); + return new AuthorizedClientServiceOAuth2AuthorizedClientManager(clientRegistrationRepository, + authorizedClientService); + } + + @Bean + AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager reactiveClientManager( + OAuth2ClientProperties properties) { + List registrations = new ArrayList<>( + OAuth2ClientPropertiesRegistrationAdapter.getClientRegistrations(properties).values()); + ReactiveClientRegistrationRepository clientRegistrationRepository = new InMemoryReactiveClientRegistrationRepository( + registrations); + ReactiveOAuth2AuthorizedClientService authorizedClientService = new InMemoryReactiveOAuth2AuthorizedClientService( + clientRegistrationRepository); + return new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager(clientRegistrationRepository, + authorizedClientService); + } + + } + } diff --git a/src/checkstyle/checkstyle-suppressions.xml b/src/checkstyle/checkstyle-suppressions.xml new file mode 100644 index 0000000..c5848ef --- /dev/null +++ b/src/checkstyle/checkstyle-suppressions.xml @@ -0,0 +1,22 @@ + + + + + + diff --git a/src/checkstyle/checkstyle.xml b/src/checkstyle/checkstyle.xml new file mode 100644 index 0000000..ecd190f --- /dev/null +++ b/src/checkstyle/checkstyle.xml @@ -0,0 +1,26 @@ + + + + + + + + + + \ No newline at end of file diff --git a/src/nohttp/checkstyle.xml b/src/nohttp/checkstyle.xml new file mode 100644 index 0000000..3529c84 --- /dev/null +++ b/src/nohttp/checkstyle.xml @@ -0,0 +1,23 @@ + + + + + + + + \ No newline at end of file