Skip to content

Commit

Permalink
Fix TieredCache so it also restores the deeper caches
Browse files Browse the repository at this point in the history
Add proxy capability to DataCall
Document that getCurrentGame returns null if not in-game
Add test for TieredCache and "not in-game"
  • Loading branch information
stelar7 committed Aug 8, 2017
1 parent 8c18886 commit 002017a
Show file tree
Hide file tree
Showing 8 changed files with 173 additions and 82 deletions.
37 changes: 29 additions & 8 deletions src/main/java/no/stelar7/api/l4j8/basic/cache/CacheProvider.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,15 @@ public abstract class CacheProvider
*/
public abstract void store(URLEndpoint type, Object obj);


/**
* Updates the TTL for this object
*
* @param type the endpoint to store the cache in
* @param obj the object to store
*/
public abstract void update(URLEndpoint type, Object obj);

/**
* Returns data from the cache if found, otherwise Optional.empty();
*
Expand All @@ -41,10 +50,12 @@ public abstract class CacheProvider
private ScheduledFuture<?> clearTask;
protected long timeToLive;

public long getTimeToLive()
{
return timeToLive;
}
/**
* Returns the time in seconds the items are alloweed to live in the cache
*
* @return long
*/
public abstract long getTimeToLive();

/**
* Returns the count of items in the cache
Expand Down Expand Up @@ -85,7 +96,11 @@ private EmptyProvider()
}

@Override
public void store(URLEndpoint clazz, Object obj) { /*void cache*/}
public void store(URLEndpoint clazz, Object obj) {/*void cache*/}

@Override
public void update(URLEndpoint type, Object obj)
{/*void cache*/}

@Override
public Optional<?> get(URLEndpoint type, Object... data)
Expand All @@ -95,12 +110,18 @@ public Optional<?> get(URLEndpoint type, Object... data)

@Override
public void clear(URLEndpoint type)
{/*void*/}
{/*void cache*/}

@Override
public void clearOldCache()
{/*void*/}

{/*void cache*/}

@Override
public long getTimeToLive()
{
return 0;
}

@Override
public long getSize()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,13 @@ public void store(URLEndpoint type, Object obj)
}
}


@Override
public void update(URLEndpoint type, Object obj)
{
store(type, obj);
}

@Override
public Optional<?> get(URLEndpoint type, Object... data)
{
Expand Down Expand Up @@ -86,6 +93,12 @@ public void clearOldCache()
clearOldCache(matches);
}

@Override
public long getTimeToLive()
{
return timeToLive;
}

@Override
public long getSize()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

public class TieredCacheProvider extends CacheProvider
{
List<CacheProvider> providers = new LinkedList<>();
private final List<CacheProvider> providers = new LinkedList<>();

public TieredCacheProvider(CacheProvider... provs)
{
Expand All @@ -15,9 +15,15 @@ public TieredCacheProvider(CacheProvider... provs)


@Override
public void store(URLEndpoint clazz, Object obj)
public void store(URLEndpoint type, Object obj)
{
providers.forEach(p -> p.store(clazz, obj));
providers.forEach(p -> p.store(type, obj));
}

@Override
public void update(URLEndpoint type, Object obj)
{
providers.forEach(p -> p.update(type, obj));
}

@Override
Expand All @@ -40,14 +46,24 @@ public Optional<?> get(URLEndpoint type, Object... data)

private void restoreCache(CacheProvider stoppingPoint, URLEndpoint type, Object obj)
{

boolean inTheFuture = false;

for (CacheProvider provider : providers)
{
if (provider.equals(stoppingPoint))
{
return;
inTheFuture = true;
}

provider.store(type, obj);

if (!inTheFuture)
{
provider.store(type, obj);
} else
{
provider.update(type, obj);
}
}
}

Expand All @@ -63,6 +79,12 @@ public void clearOldCache()
providers.forEach(CacheProvider::clearOldCache);
}

@Override
public long getTimeToLive()
{
return providers.stream().mapToLong(CacheProvider::getTimeToLive).sum();
}

@Override
public long getSize()
{
Expand Down
31 changes: 27 additions & 4 deletions src/main/java/no/stelar7/api/l4j8/basic/calling/DataCall.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,17 @@ public final class DataCall
private static final Map<Enum, Map<Enum, RateLimiter>> limiter = new HashMap<>();
private static final Map<Enum, Map<Enum, Map<Integer, Integer>>> callData = new HashMap<>();

private static APICredentials creds;
private static CacheProvider cache = CacheProvider.EmptyProvider.INSTANCE;
private static LogLevel logLevel = LogLevel.NONE;

private final Map<String, String> urlParams = new TreeMap<>();
private final Map<String, String> urlData = new TreeMap<>();
private final Map<String, String> urlHeaders = new TreeMap<>();

private Platform platform;
private URLEndpoint endpoint;

private static APICredentials creds;
private static CacheProvider cache = CacheProvider.EmptyProvider.INSTANCE;
private static LogLevel logLevel = LogLevel.NONE;
private static String urlProxy = Constants.REQUEST_URL;


public static Map<Enum, Map<Enum, RateLimiter>> getLimiter()
Expand Down Expand Up @@ -98,6 +99,24 @@ public static CacheProvider getCacheProvider()
return cache;
}

/**
* Takes in a proxy for the api.
* The URL should contain the parts:
* {platform}
* {game}
* {service}
* {version}
* {resource}
* <p>
* The default is https://{platform}.api.riotgames.com/{game}/{service}/{version}/{resource}
*
* @param proxy the url
*/
public static void setProxy(@Nullable String proxy)
{
urlProxy = proxy == null ? Constants.REQUEST_URL : proxy;
}

public static void setCacheProvider(@Nullable CacheProvider provider)
{
cache = provider == null ? CacheProvider.EmptyProvider.INSTANCE : provider;
Expand All @@ -108,4 +127,8 @@ public static void setCredentials(final APICredentials creds)
DataCall.creds = creds;
}

public String getProxy()
{
return urlProxy;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ public class DataCallBuilder
private static final BiFunction<String, String, String> MERGE = (o, n) -> o + "," + n;
private static final BiFunction<String, String, String> MERGE_AS_SET = (o, n) -> o + n;

private String BASE_URL = Constants.REQUEST_URL;
private String requestMethod = "GET";
private String postData = "";

Expand Down Expand Up @@ -64,30 +63,30 @@ public Object build(int... retrys)
System.err.println(response);
}

switch (response.getResponseCode())
try
{
case 200:
case 204:
switch (response.getResponseCode())
{
final Object returnType = this.dc.getEndpoint().getType();
Object dtoobj = Utils.getGson().fromJson(response.getResponseData(), (returnType instanceof Class<?>) ? (Class<?>) returnType : (Type) returnType);
case 200:
case 204:
{
final Object returnType = this.dc.getEndpoint().getType();
Object dtoobj = Utils.getGson().fromJson(response.getResponseData(), (returnType instanceof Class<?>) ? (Class<?>) returnType : (Type) returnType);

return process(dtoobj);
}

return process(dtoobj);
}

case 403:
{
throw new APIResponseException(APIHTTPErrorReason.ERROR_403, "Your Api key is invalid! If you just regenerated it, wait a few seconds, then try again. " + response.getResponseData());
}

case 404:
{
throw new APIResponseException(APIHTTPErrorReason.ERROR_400, "L4J8 error.. contact developer to get this fixed ..." + response.getResponseData());
}

case 429:
try
case 403:
{
throw new APIResponseException(APIHTTPErrorReason.ERROR_403, "Your Api key is invalid! If you just regenerated it, wait a few seconds, then try again. " + response.getResponseData());
}

case 404:
{
return null;
}

case 429:
if (response.getResponseData().startsWith(RateLimitType.LIMIT_UNDERLYING.getReason()) || response.getResponseData().startsWith(RateLimitType.LIMIT_SERVICE.getReason()))
{
int attempts = (retrys != null && retrys.length == 1) ? ++retrys[0] : 1;
Expand All @@ -109,30 +108,33 @@ public Object build(int... retrys)
}

return this.build();
} catch (InterruptedException e)

case 500:
case 502:
case 503:
case 504:
{
e.printStackTrace();
break;
int attempts = (retrys != null && retrys.length == 1) ? ++retrys[0] : 1;
System.err.format("Server error, waiting 1 second and retrying%n");
Thread.sleep(1000);

if (attempts > 3)
{
throw new APIResponseException(APIHTTPErrorReason.ERROR_500, response.getResponseData());
}

return this.build(attempts);
}

case 500:
case 502:
case 503:
case 504:
{
int attempts = (retrys != null && retrys.length == 1) ? ++retrys[0] : 1;
if (attempts > 3)

default:
{
throw new APIResponseException(APIHTTPErrorReason.ERROR_500, response.getResponseData());
break;
}

return this.build(attempts);
}

default:
{
break;
}
} catch (InterruptedException e)
{
e.printStackTrace();
}

System.err.println("Response Code:" + response.getResponseCode());
Expand Down Expand Up @@ -268,7 +270,6 @@ private DataCallResponse getResponse(final String url)

if (limitType == RateLimitType.LIMIT_METHOD)
{
// TODO
RateLimiter limter = DataCall.getLimiter().get(this.dc.getPlatform()).get(this.dc.getEndpoint());
limter.updateSleep(con.getHeaderField("Retry-After"));
limter.resetCalls();
Expand Down Expand Up @@ -328,15 +329,6 @@ private void saveHeaderRateLimit(String limitCount, Enum platform, Enum endpoint
DataCall.getCallData().put(platform, parent);

updateRatelimiter(platform, endpoint);

/*
private void saveHeaderRateLimit(String limitCount, Enum type)
{
Map<Integer, Integer> timeout = parseLimitFromHeader(limitCount);
DataCall.getCallData().put(type, timeout);
updateRatelimiter(type);
}
*/
}

private Map<Integer, Integer> parseLimitFromHeader(String headerValue)
Expand Down Expand Up @@ -382,7 +374,7 @@ public RateLimiter createLimiter(Enum key, String limitCount)
*/
private String getURL()
{
String[] url = {BASE_URL};
String[] url = {dc.getProxy()};
url[0] = url[0].replace(Constants.PLATFORM_PLACEHOLDER, dc.getPlatform().toString());
url[0] = url[0].replace(Constants.GAME_PLACEHOLDER, dc.getEndpoint().getGame());
url[0] = url[0].replace(Constants.SERVICE_PLACEHOLDER, dc.getEndpoint().getService());
Expand Down Expand Up @@ -511,7 +503,7 @@ public DataCallBuilder withURLParameter(final String key, final String value)

public DataCallBuilder withURL(String url)
{
this.BASE_URL = url;
dc.setProxy(url);
return this;
}

Expand Down
4 changes: 3 additions & 1 deletion src/main/java/no/stelar7/api/l4j8/impl/SpectatorAPI.java
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,12 @@ public List<SpectatorGameInfo> getFeaturedGames(Platform server)

/**
* The response object contains the CurrentGame of the summoner.
* <p>
* returns null if not in game
*
* @param server the region to execute against
* @param summonerId the summonerId
* @return Optional FeaturedGames
* @return SpectatorGameInfo
*/
public SpectatorGameInfo getCurrentGame(Platform server, long summonerId)
{
Expand Down
Loading

0 comments on commit 002017a

Please sign in to comment.