Skip to content

Instantly share code, notes, and snippets.

@gigaherz
Created May 2, 2016 10:52
Show Gist options
  • Save gigaherz/a5c5e717890d1e67799fac4f9fe50cda to your computer and use it in GitHub Desktop.
Save gigaherz/a5c5e717890d1e67799fac4f9fe50cda to your computer and use it in GitHub Desktop.
package gigaherz.enderthing.client;
import com.google.common.collect.Maps;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class PlayerNameCache
{
private static class PlayerNameRequest
{
public boolean complete;
public String lastKnownName;
public long lastKnownDate;
public long lastQueryDate;
public String getLastKnownName()
{
if(!complete)
return null;
return lastKnownName;
}
public boolean isOld()
{
return (System.currentTimeMillis() - lastQueryDate) > (24L * 3600L * 1000L);
}
}
private static Map<UUID, PlayerNameRequest> cache = Maps.newHashMap();
public static String queryNameFromUUID(UUID uuid)
{
PlayerNameRequest req = cache.get(uuid);
if(req == null || req.isOld())
{
req = startNameRequest(uuid);
}
return req.getLastKnownName();
}
static ExecutorService executor = Executors.newCachedThreadPool();
private static PlayerNameRequest startNameRequest(UUID uuid)
{
PlayerNameRequest req = new PlayerNameRequest();
cache.put(uuid, req);
executor.execute(() -> {
try
{
URL url = new URL("https://api.mojang.com/user/profiles/" + uuid.toString().replace("-","") + "/names");
JsonReader input = new JsonReader(new InputStreamReader(url.openStream()));
String lastKnownName = null;
long lastKnownDate = -1;
input.beginArray();
while (input.hasNext())
{
if (input.peek() != JsonToken.BEGIN_OBJECT)
{
continue;
}
String name = null;
long changeDate = 0;
input.beginObject();
while (input.hasNext())
{
String id = input.nextName();
if (id.equals("name"))
{
name = input.nextString();
}
else if(id.equals("changedToAt"))
{
changeDate = input.nextLong();
}
}
input.endObject();
if(changeDate > lastKnownDate)
{
lastKnownDate = changeDate;
lastKnownName = name;
}
}
input.endArray();
input.close();
req.lastKnownName = lastKnownName;
req.lastKnownDate = lastKnownDate;
req.complete = true;
}
catch (MalformedURLException e)
{
req.complete = true;
}
catch (IOException e)
{
e.printStackTrace();
}
});
return req;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment