1
mirror of https://github.com/Shiewk/SModeration.git synced 2026-04-29 06:34:17 +02:00

Add gzip-compressed saving and loading system

This commit is contained in:
Shy
2024-06-09 10:55:32 +02:00
parent deee125e88
commit 9e59bae857
5 changed files with 137 additions and 15 deletions
@@ -1,17 +1,22 @@
package de.shiewk.smoderation.storage;
import de.shiewk.smoderation.SModeration;
import de.shiewk.smoderation.punishments.Punishment;
import net.kyori.adventure.text.logger.slf4j.ComponentLogger;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Predicate;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class PunishmentContainer {
@@ -68,4 +73,54 @@ public class PunishmentContainer {
public ArrayList<Punishment> copy() {
return new ArrayList<>(punishments);
}
public void load(File file){
final ComponentLogger logger = SModeration.LOGGER;
try {
logger.info("Loading from {}", file.getPath());
if (!file.isFile()){
logger.warn("The file does not exist.");
} else {
try (FileInputStream fin = new FileInputStream(file)){
GZIPInputStream gzin = new GZIPInputStream(fin);
while (gzin.available() > 0){
add(Punishment.load(gzin));
}
}
logger.info("Successfully loaded {} items.", punishments.size());
}
} catch (EOFException e) {
logger.error("The file was not correctly saved, {} items could be recovered!", this.punishments.size());
} catch (IOException e){
logger.error("An error occurred while loading: {}", e.toString());
for (StackTraceElement stackTraceElement : e.getStackTrace()) {
logger.error(stackTraceElement.toString());
}
}
}
public void save(File file) {
final ComponentLogger logger = SModeration.LOGGER;
try {
logger.info("Saving to {}", file.getPath());
if (!file.isFile()){
file.mkdirs();
file.delete();
file.createNewFile();
}
try (FileOutputStream outputStream = new FileOutputStream(file)) {
GZIPOutputStream gzout = new GZIPOutputStream(outputStream);
for (Punishment punishment : copy()) {
punishment.writeBytes(gzout);
}
gzout.close();
}
logger.info("Successfully saved.");
} catch (IOException e){
logger.error("An error occurred while saving: {}", e.toString());
for (StackTraceElement stackTraceElement : e.getStackTrace()) {
logger.error(stackTraceElement.toString());
}
}
}
}