Simplify MojangUtils

Signed-off-by: TheMode <themode@outlook.fr>
This commit is contained in:
TheMode 2021-11-07 14:46:26 +01:00
parent a29cac471b
commit e5ad5609cf

View File

@ -17,55 +17,35 @@ import java.util.concurrent.TimeUnit;
* Utils class using mojang API.
*/
public final class MojangUtils {
private static final Cache<String, JsonObject> UUID_CACHE = Caffeine.newBuilder()
.expireAfterWrite(30, TimeUnit.SECONDS)
.softValues()
.build();
private static final Cache<String, JsonObject> USERNAME_CACHE = Caffeine.newBuilder()
private static final String FROM_UUID_URL = "https://sessionserver.mojang.com/session/minecraft/profile/%s?unsigned=false";
private static final String FROM_USERNAME_URL = "https://api.mojang.com/users/profiles/minecraft/%s";
private static final Cache<String, JsonObject> URL_CACHE = Caffeine.newBuilder()
.expireAfterWrite(30, TimeUnit.SECONDS)
.softValues()
.build();
@Blocking
public static @Nullable JsonObject fromUuid(@NotNull String uuid) {
// Check cache
{
final JsonObject jsonObject = UUID_CACHE.getIfPresent(uuid);
if (jsonObject != null) {
return jsonObject;
}
}
// Retrieve from the rate-limited Mojang API
final String url = "https://sessionserver.mojang.com/session/minecraft/profile/" + uuid + "?unsigned=false";
return retrieve(url, uuid, UUID_CACHE);
final String url = String.format(FROM_UUID_URL, uuid);
return retrieve(url, uuid);
}
@Blocking
public static @Nullable JsonObject fromUsername(@NotNull String username) {
// Check cache
{
final JsonObject jsonObject = USERNAME_CACHE.getIfPresent(username);
if (jsonObject != null) {
return jsonObject;
}
}
// Retrieve from the rate-limited Mojang API
final String url = "https://api.mojang.com/users/profiles/minecraft/" + username;
return retrieve(url, username, USERNAME_CACHE);
final String url = String.format(FROM_USERNAME_URL, username);
return retrieve(url, username);
}
@Nullable
private static JsonObject retrieve(@NotNull String url, @NotNull String key,
@NotNull Cache<String, JsonObject> cache) {
try {
final String response = URLUtils.getText(url);
final JsonObject jsonObject = JsonParser.parseString(response).getAsJsonObject();
cache.put(key, jsonObject);
return jsonObject;
} catch (IOException e) {
MinecraftServer.getExceptionManager().handleException(e);
return null;
}
private static @Nullable JsonObject retrieve(@NotNull String url, @NotNull String key) {
return URL_CACHE.get(key, s -> {
try {
// Retrieve from the rate-limited Mojang API
final String response = URLUtils.getText(url);
return JsonParser.parseString(response).getAsJsonObject();
} catch (IOException e) {
MinecraftServer.getExceptionManager().handleException(e);
throw new RuntimeException(e);
}
});
}
}