/** * Creates a {@link Credential} objects with the given {@link TokensAndUrlAuthData} which supports * refreshing tokens. */ public Credential createCredential(TokensAndUrlAuthData authData) { return new Credential.Builder(BearerToken.authorizationHeaderAccessMethod()) .setTransport(httpTransport) .setJsonFactory(jsonFactory) .setClientAuthentication( new ClientParametersAuthentication(appCredentials.getKey(), appCredentials.getSecret())) .setTokenServerEncodedUrl(authData.getTokenServerEncodedUrl()) .build() .setAccessToken(authData.getAccessToken()) .setRefreshToken(authData.getRefreshToken()) .setExpiresInSeconds(EXPIRE_TIME_IN_SECONDS); } }
@Override public GoogleCredential setExpiresInSeconds(Long expiresIn) { return (GoogleCredential) super.setExpiresInSeconds(expiresIn); }
@Test public void testRefreshCredential_refresh() throws Exception { credential.setAccessToken(ACCESS_TOKEN); credential.setRefreshToken(REFRESH_TOKEN); credential.setExpiresInSeconds(REFRESH_WINDOW_SECS - 10L); Mockito.doReturn(true).when(oAuth2Helper).callRefreshToken(credential); oAuth2Helper.refreshCredential(credential); verify(oAuth2Helper).callRefreshToken(credential); }
@Test public void testRefreshCredential_refreshFailedNoException() throws Exception { credential.setAccessToken(ACCESS_TOKEN); credential.setRefreshToken(REFRESH_TOKEN); credential.setExpiresInSeconds(REFRESH_WINDOW_SECS - 10L); Mockito.doReturn(false).when(oAuth2Helper).callRefreshToken(credential); oAuth2Helper.refreshCredential(credential); }
@Test public void testRefreshCredential_refreshFailedException() throws Exception { credential.setAccessToken(ACCESS_TOKEN); credential.setRefreshToken(REFRESH_TOKEN); credential.setExpiresInSeconds(REFRESH_WINDOW_SECS - 10L); Mockito.doThrow(new IOException("Failed")).when(oAuth2Helper).callRefreshToken(credential); thrown.expect(IOException.class); oAuth2Helper.refreshCredential(credential); } }
@Test public void testRefreshCredential_noRefreshToken() throws Exception { credential.setAccessToken(ACCESS_TOKEN); credential.setRefreshToken(null); credential.setExpiresInSeconds(null); assertSame(credential, oAuth2Helper.refreshCredential(credential)); }
@Test public void testRefreshCredential_notSoonEnough() throws Exception { credential.setAccessToken(ACCESS_TOKEN); credential.setRefreshToken(REFRESH_TOKEN); credential.setExpiresInSeconds(REFRESH_WINDOW_SECS * 2L); assertSame(credential, oAuth2Helper.refreshCredential(credential)); }
credential.setExpiresInSeconds(1000L);