Expire auth token after 1 hour

This commit is contained in:
Reinhard Pointner 2016-04-17 22:21:14 +00:00
parent 7a823835fb
commit 23f2d4e609
2 changed files with 17 additions and 15 deletions

View File

@ -15,6 +15,7 @@ import java.net.URI;
import java.net.URL;
import java.nio.ByteBuffer;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
@ -79,18 +80,23 @@ public class TheTVDBClient2 extends AbstractEpisodeListProvider implements Artwo
}
private String token = null;
private Instant tokenExpireInstant = null;
private Duration tokenExpireDuration = Duration.ofHours(1);
private synchronized String getAuthorizationToken() {
// curl -v -X GET --header 'Accept: application/json' --header 'Authorization: Bearer TOKEN' 'https://api.thetvdb.com/languages'
if (token == null) {
try {
Object json = requestJson("login", singletonMap("apikey", apikey));
token = getString(json, "token");
} catch (Exception e) {
throw new IllegalStateException("Failed to retrieve authorization token: " + e.getMessage(), e);
private String getAuthorizationToken() {
synchronized (tokenExpireDuration) {
System.out.println("EXPIRE: " + tokenExpireInstant);
if (token == null || (tokenExpireInstant != null && Instant.now().isAfter(tokenExpireInstant))) {
try {
Object json = requestJson("login", singletonMap("apikey", apikey));
token = getString(json, "token");
tokenExpireInstant = Instant.now().plus(tokenExpireDuration);
} catch (Exception e) {
throw new IllegalStateException("Failed to retrieve authorization token: " + e.getMessage(), e);
}
}
return token;
}
return token;
}
protected String[] languages() throws Exception {

View File

@ -10,7 +10,7 @@ import org.junit.Test;
public class TheTVDBClient2Test {
TheTVDBClient2 thetvdb = new TheTVDBClient2("BA864DEE427E384A");
static TheTVDBClient2 thetvdb = new TheTVDBClient2("BA864DEE427E384A");
SearchResult buffy = new SearchResult(70327, "Buffy the Vampire Slayer");
SearchResult wonderfalls = new SearchResult(78845, "Wonderfalls");
@ -123,15 +123,11 @@ public class TheTVDBClient2Test {
@Test
public void getSeriesInfo() throws Exception {
TheTVDBSeriesInfo it = (TheTVDBSeriesInfo) thetvdb.getSeriesInfo(80348, Locale.ENGLISH);
SeriesInfo it = thetvdb.getSeriesInfo(80348, Locale.ENGLISH);
assertEquals(80348, it.getId(), 0);
assertEquals("TV-PG", it.getContentRating());
assertEquals("2007-09-24", it.getFirstAired().toString());
assertEquals("Action", it.getGenres().get(0));
assertEquals("tt0934814", it.getImdbId());
assertEquals("en", it.getLanguage());
assertEquals(987, it.getOverview().length());
assertEquals("45", it.getRuntime().toString());
assertEquals("Chuck", it.getName());
}