-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathTokenManager.java
More file actions
62 lines (51 loc) · 1.79 KB
/
TokenManager.java
File metadata and controls
62 lines (51 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.amadeus.client;
import com.amadeus.Configuration;
import com.amadeus.Constants;
import com.amadeus.HTTPClient;
import com.amadeus.Params;
import com.amadeus.Response;
import com.amadeus.exceptions.ResponseException;
import com.google.gson.JsonObject;
import lombok.Getter;
/**
* Handles token-related functionality, including fetching and refreshing tokens.
*/
public class TokenManager {
private static final long TOKEN_BUFFER = 10000L;
private static final long MILLISECONDS_IN_SECOND = 1000L;
private final HTTPClient client;
@Getter
private String tokenValue = null;
private long expiresAt;
public TokenManager(HTTPClient client) {
this.client = client;
}
public void lazyUpdateAccessToken() throws ResponseException {
if (isTokenExpiredOrNull()) {
updateAccessToken();
}
}
private boolean isTokenExpiredOrNull() {
return isTokenNull() || isTokenExpired();
}
private boolean isTokenNull() {
return tokenValue == null;
}
private boolean isTokenExpired() {
return (System.currentTimeMillis() + TOKEN_BUFFER) > expiresAt;
}
private void updateAccessToken() throws ResponseException {
Configuration config = client.getConfiguration();
Params requestParams = AuthUtils.createAuthRequestParams(config);
Response response = AuthUtils.executeUnauthenticatedRequest(client, requestParams);
storeAccessTokenDetails(response.getResult());
}
private void storeAccessTokenDetails(JsonObject result) {
this.tokenValue = result.get(Constants.ACCESS_TOKEN).getAsString();
int expiresIn = result.get(Constants.EXPIRES_IN).getAsInt();
this.expiresAt = calculateExpiryTime(expiresIn);
}
private long calculateExpiryTime(int expiresIn) {
return System.currentTimeMillis() + expiresIn * MILLISECONDS_IN_SECOND;
}
}