AccessTokenProvider { protected synchronized CompletableFuture<AccessToken> obtainAccessToken() { CompletableFuture<AccessToken> result = tokenFuture; if (tokenFuture == null) { LOG.debug("Obtaining a new access token for SW360."); tokenFuture = result = getAuthClient().getOAuth2AccessToken() .thenApply(AccessToken::new); tokenFuture.whenComplete(this::handleTokenResult); } return result; } AccessTokenProvider(SW360AuthenticationClient authClient); SW360AuthenticationClient getAuthClient(); CompletableFuture<T> doWithToken(Function<? super AccessToken, ? extends CompletableFuture<T>> func);  }
@Test public void testAccessTokenCanBeObtained() { CompletableFuture<String> tokenFuture = CompletableFuture.completedFuture(TOKEN); expectTokenRequest(tokenFuture); AccessToken accessToken = tokenProvider.obtainAccessToken().join(); assertThat(accessToken.getToken()).isEqualTo(TOKEN); }
@Test public void testAccessTokenIsCached() { CompletableFuture<String> tokenFuture = CompletableFuture.completedFuture(TOKEN); expectTokenRequest(tokenFuture); AccessToken accessToken1 = tokenProvider.obtainAccessToken().join(); AccessToken accessToken2 = tokenProvider.obtainAccessToken().join(); assertThat(accessToken2).isSameAs(accessToken1); verify(authClient).getOAuth2AccessToken(); }
@Test public void testFailedResultIsNotCached() { CompletableFuture<String> tokenFutureFailed = new CompletableFuture<>(); tokenFutureFailed.completeExceptionally(new IOException("no token")); CompletableFuture<String> tokenFutureSuccess = CompletableFuture.completedFuture(TOKEN); expectTokenRequest(tokenFutureFailed, tokenFutureSuccess); tokenProvider.obtainAccessToken(); AccessToken accessToken = tokenProvider.obtainAccessToken().join(); assertThat(accessToken.getToken()).isEqualTo(TOKEN); }