diff --git a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/session/MemorySessionStorage.java b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/session/MemorySessionStorage.java index 10d7a976..620b0faa 100644 --- a/LaunchServer/src/main/java/pro/gravit/launchserver/auth/session/MemorySessionStorage.java +++ b/LaunchServer/src/main/java/pro/gravit/launchserver/auth/session/MemorySessionStorage.java @@ -1,8 +1,18 @@ package pro.gravit.launchserver.auth.session; +import pro.gravit.launcher.Launcher; import pro.gravit.launcher.NeedGarbageCollection; +import pro.gravit.launchserver.LaunchServer; import pro.gravit.launchserver.manangers.SessionManager; +import pro.gravit.utils.helper.IOHelper; +import pro.gravit.utils.helper.LogHelper; +import java.io.IOException; +import java.io.Reader; +import java.io.Writer; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Stream; @@ -11,6 +21,17 @@ public class MemorySessionStorage extends SessionStorage implements NeedGarbageC private transient final Map clientSet = new ConcurrentHashMap<>(128); private transient final Map> uuidIndex = new ConcurrentHashMap<>(32); + public boolean autoDump = false; + public String dumpFile = "sessions.json"; + + @Override + public void init(LaunchServer server) { + super.init(server); + if(autoDump) { + loadSessionsData(); + garbageCollection(); + } + } @Override public byte[] getSessionData(UUID session) { @@ -69,6 +90,32 @@ public boolean deleteSessionsByUserUUID(UUID userUUID) { public void clear() { clientSet.clear(); uuidIndex.clear(); + if(autoDump) { + garbageCollection(); + dumpSessionsData(); + } + } + + public void dumpSessionsData() { + DumpedData dumpedData = new DumpedData(clientSet, uuidIndex); + Path path = Paths.get(dumpFile); + try(Writer writer = IOHelper.newWriter(path)) { + Launcher.gsonManager.gson.toJson(dumpedData, writer); + } catch (IOException e) { + LogHelper.error(e); + } + } + + public void loadSessionsData() { + Path path = Paths.get(dumpFile); + if(!Files.exists(path)) return; + try(Reader reader = IOHelper.newReader(path)) { + DumpedData data = Launcher.gsonManager.gson.fromJson(reader, DumpedData.class); + clientSet.putAll(data.clientSet); + uuidIndex.putAll(data.uuidIndex); + } catch (IOException e) { + LogHelper.error(e); + } } @Override @@ -125,4 +172,14 @@ public Entry(byte[] data, UUID sessionUuid) { this.timestamp = System.currentTimeMillis(); } } + + private static class DumpedData { + private transient final Map clientSet; + private transient final Map> uuidIndex; + + private DumpedData(Map clientSet, Map> uuidIndex) { + this.clientSet = clientSet; + this.uuidIndex = uuidIndex; + } + } }