use of org.wso2.carbon.apimgt.gateway.utils.redis.RedisCacheUtils in project carbon-apimgt by wso2.
the class OAuthTokenGenerator method generateToken.
/**
* Method to check for and refresh expired/generate new access tokens
*
* @param oAuthEndpoint OAuthEndpoint object for token endpoint properties
* @param latch CountDownLatch for blocking call when OAuth API is invoked
* @return TokenResponse object
* @throws APISecurityException In the event of errors when generating new token
*/
public static TokenResponse generateToken(OAuthEndpoint oAuthEndpoint, CountDownLatch latch) throws APISecurityException {
try {
TokenResponse tokenResponse = null;
if (ServiceReferenceHolder.getInstance().isRedisEnabled()) {
Object previousResponseObject = new RedisCacheUtils(ServiceReferenceHolder.getInstance().getRedisPool()).getObject(oAuthEndpoint.getId(), TokenResponse.class);
if (previousResponseObject != null) {
tokenResponse = (TokenResponse) previousResponseObject;
}
} else {
tokenResponse = TokenCache.getInstance().getTokenMap().get(oAuthEndpoint.getId());
}
if (tokenResponse != null) {
long validTill = tokenResponse.getValidTill();
long currentTimeInSeconds = System.currentTimeMillis() / 1000;
long timeDifference = validTill - currentTimeInSeconds;
if (timeDifference <= 1) {
if (tokenResponse.getRefreshToken() != null) {
tokenResponse = addTokenToCache(oAuthEndpoint, tokenResponse.getRefreshToken());
} else {
tokenResponse = addTokenToCache(oAuthEndpoint, null);
}
}
} else {
tokenResponse = addTokenToCache(oAuthEndpoint, null);
}
return tokenResponse;
} catch (IOException e) {
log.error("Error while generating OAuth Token" + getEndpointId(oAuthEndpoint));
throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE, e);
} catch (APIManagementException e) {
log.error("Could not retrieve OAuth Token" + getEndpointId(oAuthEndpoint));
throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR, "Error while retrieving OAuth token", e);
} catch (ParseException e) {
log.error("Could not retrieve OAuth Token" + getEndpointId(oAuthEndpoint));
throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR, "Error while parsing OAuth Token endpoint response", e);
} finally {
if (latch != null) {
latch.countDown();
}
}
}
Aggregations