final String clientSecret = guestService.getApiKeyAttribute(apiKey,"google.client.secret");
final GoogleCredential.Builder builder = new GoogleCredential.Builder();
builder.setTransport(httpTransport);
builder.setJsonFactory(jsonFactory);
builder.setClientSecrets(clientId, clientSecret);
GoogleCredential credential = builder.build();
final Long tokenExpires = Long.valueOf(guestService.getApiKeyAttribute(apiKey, "tokenExpires"));
credential.setExpirationTimeMilliseconds(tokenExpires);
credential.setAccessToken(accessToken);
credential.setRefreshToken(refreshToken);
try {
if (tokenExpires<System.currentTimeMillis()) {
boolean tokenRefreshed = false;
// Don't worry about checking if we are running on a mirrored test instance.
// Refreshing tokens independently on both the main server and a mirrored instance
// seems to work just fine.
// Try to swap the expired access token for a fresh one.
tokenRefreshed = credential.refreshToken();
if(tokenRefreshed) {
Long newExpireTime = credential.getExpirationTimeMilliseconds();
logger.info("google calendar token has been refreshed, new expire time = " + newExpireTime);
// Update stored expire time
guestService.setApiKeyAttribute(apiKey, "accessToken", credential.getAccessToken());
guestService.setApiKeyAttribute(apiKey, "tokenExpires", newExpireTime.toString());
}
}
}
catch (TokenResponseException e) {