Skip to content

Instantly share code, notes, and snippets.

@nsivabalan
Created September 1, 2020 14:12
Show Gist options
  • Save nsivabalan/4214e13e2181aa143dbd664e1b7687ff to your computer and use it in GitHub Desktop.
Save nsivabalan/4214e13e2181aa143dbd664e1b7687ff to your computer and use it in GitHub Desktop.
public class OAuthCore {
private AccessTokenInfo accessTokenInfo;
private AtomicBoolean asyncRetrievalInProgress = new AtomicBoolean(false);
private AtomicBoolean logout = new AtomicBoolean(false);
private String getAccessToken(){
return this.accessTokenInfo.accessToken;
}
public void reset() {
// clear all tracking vars including logout.
}
// caller is expected to check if expired before calling this method, bcoz, this will take a
// lock and wait for any other threads that are executing.
public synchronized String retrieveAccessToken(){
if(!accessTokenInfo.isExpired()){ // do we need to check for log out here.
return accessTokenInfo.accessToken;
} else if(!logout.get()){
// fetch access token in blocking manner.
// after fetching if log out -> set log out.
// figure out how to convey the info to caller.
} else{
// already log out set. convey the info to caller.
}
}
public void mayBeRetrieveTokenIfExpiringWithinDeltaTime(){
if(asyncRetrievalInProgress.get()) {
return;
} else if(accessTokenInfo.isExpiringInDeltaTime(30000)) {
// retrieve token async via thread and update value of accessTokenInfo.
}
}
// within a thread.
// can async call result in log out ? can we override the existing token.
// if single thread pool, then don't need synchronous
private synchronized void retrieveTokenAsync(){
if(accessTokenInfo.isExpiringInDeltaTime(30000)) {
asyncRetrievalInProgress.set(true);
// fetch token and update.
asyncRetrievalInProgress.set(false);
}
}
class AccessTokenInfo {
String accessToken;
long expirationTimeMs;
AccessTokenInfo(String accessToken, long expirationTimeMs){
this.expirationTimeMs = expirationTimeMs;
this.accessToken = accessToken;
}
public boolean isExpired() {
return System.currentTimeMillis() > expirationTimeMs;
}
public boolean isExpiringInDeltaTime(long deltaTimeMs) {
return (expirationTimeMs - deltaTimeMs) <= System.currentTimeMillis();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment