package net.frozenorb.apiv3.models; import lombok.Getter; import lombok.Setter; import net.frozenorb.apiv3.APIv3; import net.frozenorb.apiv3.serialization.ExcludeFromReplies; import org.mongodb.morphia.annotations.Entity; import org.mongodb.morphia.annotations.Id; import org.mongodb.morphia.annotations.Indexed; import java.util.*; import java.util.concurrent.TimeUnit; @Entity(value = "servers", noClassnameStored = true) public final class Server { private static Map serverCache = null; private static List serverCacheAlt = null; private static long serverCacheUpdated = 0; @Getter @Id private String id; @Getter private String displayName; @Getter @ExcludeFromReplies String apiKey; @Getter @Indexed private String serverGroup; @Getter private String serverIp; @Getter @Setter private Date lastUpdatedAt; @Getter @Setter private double lastTps; @Getter @Setter @ExcludeFromReplies private Set players; public static Server byId(String id) { updateCacheIfNeeded(); return serverCache.get(id); } public static List values() { updateCacheIfNeeded(); return serverCacheAlt; } public Server() {} // For Morphia public Server(String id, String displayName, String apiKey, ServerGroup serverGroup, String serverIp) { this.id = id; this.displayName = displayName; this.apiKey = apiKey; this.serverGroup = serverGroup.getId(); this.serverIp = serverIp; this.lastUpdatedAt = new Date(); this.lastTps = 0; this.players = new HashSet<>(); } public void delete() { APIv3.getDatastore().delete(this); } private static void updateCacheIfNeeded() { if (serverCache == null || (System.currentTimeMillis() - serverCacheUpdated) > TimeUnit.MINUTES.toMillis(1)) { Map working = new HashMap<>(); List workingAlt = new ArrayList<>(); for (Server server : APIv3.getDatastore().createQuery(Server.class).asList()) { working.put(server.getId(), server); workingAlt.add(server); } serverCache = working; serverCacheAlt = workingAlt; serverCacheUpdated = System.currentTimeMillis(); } } }