Commit c6323e97 authored by AnimeGitB's avatar AnimeGitB Committed by Luke H-W
Browse files

Funnel all gson calls into helper functions

Add deprecated getGsonFactory for plugin compat until 3.0
parent 76fcbb47
......@@ -3,7 +3,6 @@ package emu.grasscutter;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import emu.grasscutter.auth.AuthenticationSystem;
import emu.grasscutter.auth.DefaultAuthentication;
......@@ -56,7 +55,6 @@ public final class Grasscutter {
private static Language language;
private static final Gson gson = new GsonBuilder().setPrettyPrinting().create();
public static final File configFile = new File("./config.json");
private static int day; // Current day of week.
......@@ -203,8 +201,8 @@ public final class Grasscutter {
}
// If the file already exists, we attempt to load it.
try (FileReader file = new FileReader(configFile)) {
config = gson.fromJson(file, ConfigContainer.class);
try {
config = Utils.loadJsonToClass(configFile.getPath(), ConfigContainer.class);
} catch (Exception exception) {
getLogger().error("There was an error while trying to load the configuration from config.json. Please make sure that there are no syntax errors. If you want to start with a default configuration, delete your existing config.json.");
System.exit(1);
......@@ -220,7 +218,7 @@ public final class Grasscutter {
if (config == null) config = new ConfigContainer();
try (FileWriter file = new FileWriter(configFile)) {
file.write(gson.toJson(config));
file.write(Utils.jsonEncode(config));
} catch (IOException ignored) {
Grasscutter.getLogger().error("Unable to write to config file.");
} catch (Exception e) {
......@@ -272,8 +270,9 @@ public final class Grasscutter {
return consoleLineReader;
}
@Deprecated(forRemoval = true)
public static Gson getGsonFactory() {
return gson;
return Utils.getGsonFactory();
}
public static HttpServer getHttpServer() {
......
......@@ -4,10 +4,9 @@ import com.google.gson.JsonObject;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.Grasscutter.ServerDebugMode;
import emu.grasscutter.Grasscutter.ServerRunMode;
import emu.grasscutter.utils.Utils;
import java.nio.charset.StandardCharsets;
import java.util.Set;
import java.io.FileReader;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Locale;
......@@ -27,8 +26,7 @@ public class ConfigContainer {
*/
public static void updateConfig() {
try { // Check if the server is using a legacy config.
JsonObject configObject = Grasscutter.getGsonFactory()
.fromJson(new FileReader(Grasscutter.configFile, StandardCharsets.UTF_8), JsonObject.class);
JsonObject configObject = Utils.loadJsonToClass(Grasscutter.configFile.getPath(), JsonObject.class);
if (!configObject.has("version")) {
Grasscutter.getLogger().info("Updating legacy ..");
Grasscutter.saveConfig(null);
......
......@@ -15,6 +15,7 @@ import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
public class DataLoader {
......@@ -69,6 +70,24 @@ public class DataLoader {
return null;
}
public static <T> T loadClass(String resourcePath, Class<T> classType) throws IOException {
try (InputStreamReader reader = loadReader(resourcePath)) {
return Utils.loadJsonToClass(reader, classType);
}
}
public static <T> List<T> loadList(String resourcePath, Class<T> classType) throws IOException {
try (InputStreamReader reader = loadReader(resourcePath)) {
return Utils.loadJsonToList(reader, classType);
}
}
public static <T1,T2> Map<T1,T2> loadMap(String resourcePath, Class<T1> keyType, Class<T2> valueType) throws IOException {
try (InputStreamReader reader = loadReader(resourcePath)) {
return Utils.loadJsonToMap(reader, keyType, valueType);
}
}
public static void checkAllFiles() {
try {
List<Path> filenames = FileUtils.getPathsFromResource("/defaults/data/");
......
......@@ -2,7 +2,6 @@ package emu.grasscutter.data;
import com.google.gson.JsonElement;
import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.data.binout.*;
import emu.grasscutter.data.binout.AbilityModifier.AbilityConfigData;
......@@ -21,7 +20,6 @@ import lombok.SneakyThrows;
import org.reflections.Reflections;
import java.io.*;
import java.lang.reflect.Type;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
......@@ -29,6 +27,7 @@ import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static emu.grasscutter.config.Configuration.DATA;
import static emu.grasscutter.config.Configuration.RESOURCE;
import static emu.grasscutter.utils.Language.translate;
......@@ -119,17 +118,15 @@ public class ResourceLoader {
}
@SuppressWarnings({"rawtypes", "unchecked"})
protected static void loadFromResource(Class<?> c, String fileName, Int2ObjectMap map) throws Exception {
try (FileReader fileReader = new FileReader(RESOURCE("ExcelBinOutput/" + fileName))) {
List list = Grasscutter.getGsonFactory().fromJson(fileReader, TypeToken.getParameterized(Collection.class, c).getType());
protected static <T> void loadFromResource(Class<T> c, String fileName, Int2ObjectMap map) throws Exception {
List<T> list = Utils.loadJsonToList(RESOURCE("ExcelBinOutput/" + fileName), c);
for (Object o : list) {
for (T o : list) {
GameResource res = (GameResource) o;
res.onLoad();
map.put(res.getId(), res);
}
}
}
private static void loadScenePoints() {
Pattern pattern = Pattern.compile("(?<=scene)(.*?)(?=_point.json)");
......@@ -140,7 +137,6 @@ public class ResourceLoader {
return;
}
List<ScenePointEntry> scenePointList = new ArrayList<>();
for (File file : Objects.requireNonNull(folder.listFiles())) {
ScenePointConfig config;
Integer sceneId;
......@@ -152,8 +148,8 @@ public class ResourceLoader {
continue;
}
try (FileReader fileReader = new FileReader(file)) {
config = Grasscutter.getGsonFactory().fromJson(fileReader, ScenePointConfig.class);
try {
config = Utils.loadJsonToClass(file.getPath(), ScenePointConfig.class);
} catch (Exception e) {
e.printStackTrace();
continue;
......@@ -163,22 +159,20 @@ public class ResourceLoader {
continue;
}
List<Integer> scenePoints = new ArrayList<>();
for (Map.Entry<String, JsonElement> entry : config.points.entrySet()) {
PointData pointData = Grasscutter.getGsonFactory().fromJson(entry.getValue(), PointData.class);
pointData.setId(Integer.parseInt(entry.getKey()));
int id = Integer.parseInt(entry.getKey());
String name = sceneId + "_" + entry.getKey();
PointData pointData = Utils.jsonDecode(entry.getValue(), PointData.class);
pointData.setId(id);
ScenePointEntry sl = new ScenePointEntry(sceneId + "_" + entry.getKey(), pointData);
scenePointList.add(sl);
GameData.getScenePointIdList().add(pointData.getId());
GameData.getScenePointIdList().add(id);
GameData.getScenePointEntries().put(name, new ScenePointEntry(name, pointData));
scenePoints.add(id);
pointData.updateDailyDungeon();
}
GameData.getScenePointsPerScene().put(sceneId, new ArrayList<>());
for (ScenePointEntry entry : scenePointList) {
GameData.getScenePointEntries().put(entry.getName(), entry);
GameData.getScenePointsPerScene().get(sceneId).add(entry.getPointData().getId());
}
GameData.getScenePointsPerScene().put(sceneId, scenePoints);
}
}
......@@ -186,15 +180,15 @@ public class ResourceLoader {
List<AbilityEmbryoEntry> embryoList = null;
// Read from cached file if exists
try (InputStream embryoCache = DataLoader.load("AbilityEmbryos.json", false)) {
embryoList = Grasscutter.getGsonFactory().fromJson(new InputStreamReader(embryoCache), TypeToken.getParameterized(Collection.class, AbilityEmbryoEntry.class).getType());
try {
embryoList = Utils.loadJsonToList(DATA("AbilityEmbryos.json"), AbilityEmbryoEntry.class);
} catch (Exception ignored) {}
if (embryoList == null) {
// Load from BinOutput
Pattern pattern = Pattern.compile("(?<=ConfigAvatar_)(.*?)(?=.json)");
embryoList = new LinkedList<>();
embryoList = new ArrayList<>();
File folder = new File(Utils.toFilePath(RESOURCE("BinOutput/Avatar/")));
File[] files = folder.listFiles();
if (files == null) {
......@@ -213,8 +207,8 @@ public class ResourceLoader {
continue;
}
try (FileReader fileReader = new FileReader(file)) {
config = Grasscutter.getGsonFactory().fromJson(fileReader, AvatarConfig.class);
try {
config = Utils.loadJsonToClass(file.getPath(), AvatarConfig.class);
} catch (Exception e) {
e.printStackTrace();
continue;
......@@ -229,16 +223,12 @@ public class ResourceLoader {
embryoList.add(al);
}
File playerElementsFile = new File(Utils.toFilePath(RESOURCE("BinOutput/AbilityGroup/AbilityGroup_Other_PlayerElementAbility.json")));
if (playerElementsFile.exists()) {
try (FileReader fileReader = new FileReader(playerElementsFile)) {
GameDepot.setPlayerAbilities(Grasscutter.getGsonFactory().fromJson(fileReader, new TypeToken<Map<String, AvatarConfig>>(){}.getType()));
try {
GameDepot.setPlayerAbilities(Utils.loadJsonToMap(RESOURCE("BinOutput/AbilityGroup/AbilityGroup_Other_PlayerElementAbility.json"), String.class, AvatarConfig.class));
} catch (Exception e) {
e.printStackTrace();
}
}
}
if (embryoList == null || embryoList.isEmpty()) {
Grasscutter.getLogger().error("No embryos loaded!");
......@@ -262,8 +252,8 @@ public class ResourceLoader {
for (File file : files) {
List<AbilityConfigData> abilityConfigList;
try (FileReader fileReader = new FileReader(file)) {
abilityConfigList = Grasscutter.getGsonFactory().fromJson(fileReader, TypeToken.getParameterized(Collection.class, AbilityConfigData.class).getType());
try {
abilityConfigList = Utils.loadJsonToList(file.getPath(), AbilityConfigData.class);
} catch (Exception e) {
e.printStackTrace();
continue;
......@@ -320,11 +310,8 @@ public class ResourceLoader {
for (String name : spawnDataNames) {
// Load spawn entries from file
try (InputStreamReader reader = DataLoader.loadReader(name)) {
Type type = TypeToken.getParameterized(Collection.class, SpawnGroupEntry.class).getType();
List<SpawnGroupEntry> list = Grasscutter.getGsonFactory().fromJson(reader, type);
// Add spawns to group if it already exists in our spawn group map
spawnEntryMap.addAll(list);
spawnEntryMap.addAll(Utils.loadJsonToList(reader, SpawnGroupEntry.class));
} catch (Exception ignored) {}
}
......@@ -354,13 +341,12 @@ public class ResourceLoader {
// Read from cached file if exists
List<OpenConfigEntry> list = null;
try (InputStream openConfigCache = DataLoader.load("OpenConfig.json", false)) {
list = Grasscutter.getGsonFactory().fromJson(new InputStreamReader(openConfigCache), TypeToken.getParameterized(Collection.class, SpawnGroupEntry.class).getType());
try {
list = Utils.loadJsonToList(DATA("OpenConfig.json"), OpenConfigEntry.class);
} catch (Exception ignored) {}
if (list == null) {
Map<String, OpenConfigEntry> map = new TreeMap<>();
java.lang.reflect.Type type = new TypeToken<Map<String, OpenConfigData[]>>() {}.getType();
String[] folderNames = {"BinOutput/Talent/EquipTalents/", "BinOutput/Talent/AvatarTalents/"};
for (String name : folderNames) {
......@@ -374,11 +360,10 @@ public class ResourceLoader {
if (!file.getName().endsWith(".json")) {
continue;
}
Map<String, OpenConfigData[]> config;
try (FileReader fileReader = new FileReader(file)) {
config = Grasscutter.getGsonFactory().fromJson(fileReader, type);
try {
config = Utils.loadJsonToMap(file.getPath(), String.class, OpenConfigData[].class);
} catch (Exception e) {
e.printStackTrace();
continue;
......@@ -414,8 +399,8 @@ public class ResourceLoader {
for (File file : folder.listFiles()) {
MainQuestData mainQuest = null;
try (FileReader fileReader = new FileReader(file)) {
mainQuest = Grasscutter.getGsonFactory().fromJson(fileReader, MainQuestData.class);
try {
mainQuest = Utils.loadJsonToClass(file.getPath(), MainQuestData.class);
} catch (Exception e) {
e.printStackTrace();
continue;
......@@ -424,16 +409,14 @@ public class ResourceLoader {
GameData.getMainQuestDataMap().put(mainQuest.getId(), mainQuest);
}
try (Reader reader = new FileReader(RESOURCE("QuestEncryptionKeys.json"))) {
List<QuestEncryptionKey> keys = Grasscutter.getGsonFactory().fromJson(
reader,
TypeToken.getParameterized(List.class, QuestEncryptionKey.class).getType());
try {
List<QuestEncryptionKey> keys = DataLoader.loadList("QuestEncryptionKeys.json", QuestEncryptionKey.class);
Int2ObjectMap<QuestEncryptionKey> questEncryptionMap = GameData.getMainQuestEncryptionMap();
keys.forEach(key -> questEncryptionMap.put(key.getMainQuestId(), key));
Grasscutter.getLogger().debug("Loaded {} quest keys.", questEncryptionMap.size());
} catch (FileNotFoundException ignored) {
Grasscutter.getLogger().error("Unable to load quest keys - ./resources/QuestEncryptionKeys.json not found.");
} catch (FileNotFoundException | NullPointerException ignored) {
Grasscutter.getLogger().warn("Unable to load quest keys - ./resources/QuestEncryptionKeys.json not found.");
} catch (Exception e) {
Grasscutter.getLogger().error("Unable to load quest keys.", e);
}
......@@ -450,8 +433,8 @@ public class ResourceLoader {
for (File file : folder.listFiles()) {
ScriptSceneData sceneData;
try (FileReader fileReader = new FileReader(file)) {
sceneData = Grasscutter.getGsonFactory().fromJson(fileReader, ScriptSceneData.class);
try {
sceneData = Utils.loadJsonToClass(file.getPath(), ScriptSceneData.class);
} catch (Exception e) {
e.printStackTrace();
continue;
......@@ -464,42 +447,40 @@ public class ResourceLoader {
}
@SneakyThrows
private static void loadHomeworldDefaultSaveData(){
var folder = Files.list(Path.of(RESOURCE("BinOutput/HomeworldDefaultSave"))).toList();
private static void loadHomeworldDefaultSaveData() {
var pattern = Pattern.compile("scene(.*)_home_config.json");
for (var file : folder) {
var matcher = pattern.matcher(file.getFileName().toString());
Files.list(Path.of(RESOURCE("BinOutput/HomeworldDefaultSave"))).forEach(file -> {
String filename = file.getFileName().toString();
var matcher = pattern.matcher(filename);
if (!matcher.find()) {
continue;
}
var sceneId = matcher.group(1);
var data = Grasscutter.getGsonFactory().fromJson(Files.readString(file), HomeworldDefaultSaveData.class);
GameData.getHomeworldDefaultSaveData().put(Integer.parseInt(sceneId), data);
return;
}
try {
var sceneId = Integer.parseInt(matcher.group(1));
var data = Utils.loadJsonToClass(filename, HomeworldDefaultSaveData.class);
GameData.getHomeworldDefaultSaveData().put(sceneId, data);
} catch (Exception ignored) {}
});
Grasscutter.getLogger().debug("Loaded " + GameData.getHomeworldDefaultSaveData().size() + " HomeworldDefaultSaveDatas.");
}
@SneakyThrows
private static void loadNpcBornData() {
var folder = Files.list(Path.of(RESOURCE("BinOutput/Scene/SceneNpcBorn"))).toList();
for (var file : folder) {
Files.list(Path.of(RESOURCE("BinOutput/Scene/SceneNpcBorn"))).forEach(file -> {
if (file.toFile().isDirectory()) {
continue;
return;
}
var data = Grasscutter.getGsonFactory().fromJson(Files.readString(file), SceneNpcBornData.class);
try {
var data = Utils.loadJsonToClass(file.getFileName().toString(), SceneNpcBornData.class);
if (data.getBornPosList() == null || data.getBornPosList().size() == 0) {
continue;
return;
}
data.setIndex(SceneIndexManager.buildIndex(3, data.getBornPosList(), item -> item.getPos().toPoint()));
GameData.getSceneNpcBornData().put(data.getSceneId(), data);
}
} catch (Exception ignored) {}
});
Grasscutter.getLogger().debug("Loaded " + GameData.getSceneNpcBornData().size() + " SceneNpcBornDatas.");
}
......
package emu.grasscutter.game.activity;
import com.esotericsoftware.reflectasm.ConstructorAccess;
import com.google.gson.reflect.TypeToken;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.data.DataLoader;
import emu.grasscutter.data.GameData;
......@@ -14,9 +13,6 @@ import emu.grasscutter.server.packet.send.PacketActivityScheduleInfoNotify;
import lombok.Getter;
import org.reflections.Reflections;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
......@@ -45,13 +41,8 @@ public class ActivityManager extends BasePlayerManager {
activityWatcherTypeMap.put(typeName.value(), ConstructorAccess.get(item));
});
try (Reader reader = DataLoader.loadReader("ActivityConfig.json")) {
List<ActivityConfigItem> activities = Grasscutter.getGsonFactory().fromJson(
reader,
TypeToken.getParameterized(List.class, ActivityConfigItem.class).getType());
activities.forEach(item -> {
try {
DataLoader.loadList("ActivityConfig.json", ActivityConfigItem.class).forEach(item -> {
var activityData = GameData.getActivityDataMap().get(item.getActivityId());
if (activityData == null) {
Grasscutter.getLogger().warn("activity {} not exist.", item.getActivityId());
......
......@@ -13,6 +13,7 @@ import emu.grasscutter.game.player.Player;
import emu.grasscutter.game.props.ActionReason;
import emu.grasscutter.net.proto.ActivityWatcherInfoOuterClass;
import emu.grasscutter.server.packet.send.PacketActivityUpdateWatcherNotify;
import emu.grasscutter.utils.Utils;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Data;
......@@ -68,7 +69,7 @@ public class PlayerActivityData {
}
public void setDetail(Object detail){
this.detail = Grasscutter.getGsonFactory().toJson(detail);
this.detail = Utils.jsonEncode(detail);
}
public void takeWatcherReward(int watcherId) {
......
......@@ -8,6 +8,7 @@ import emu.grasscutter.game.props.ActivityType;
import emu.grasscutter.net.proto.ActivityInfoOuterClass;
import emu.grasscutter.net.proto.MusicBriefInfoOuterClass;
import emu.grasscutter.net.proto.MusicGameActivityDetailInfoOuterClass;
import emu.grasscutter.utils.Utils;
import java.util.stream.Collectors;
......@@ -47,8 +48,7 @@ public class MusicGameActivityHandler extends ActivityHandler {
playerActivityData.save();
}
return Grasscutter.getGsonFactory().fromJson(playerActivityData.getDetail(),
MusicGamePlayerData.class);
return Utils.jsonDecode(playerActivityData.getDetail(), MusicGamePlayerData.class);
}
public boolean setMusicGameRecord(PlayerActivityData playerActivityData, MusicGamePlayerData.MusicGameRecord newRecord) {
......
......@@ -6,8 +6,6 @@ import emu.grasscutter.data.GameData;
import emu.grasscutter.data.common.ItemParamData;
import emu.grasscutter.data.excels.CombineData;
import emu.grasscutter.game.inventory.GameItem;
import emu.grasscutter.game.inventory.Inventory;
import emu.grasscutter.game.inventory.ItemType;
import emu.grasscutter.game.player.Player;
import emu.grasscutter.game.props.ActionReason;
import emu.grasscutter.game.props.ItemUseOp;
......@@ -19,18 +17,12 @@ import emu.grasscutter.server.packet.send.PacketCombineFormulaDataNotify;
import emu.grasscutter.server.packet.send.PacketCombineRsp;
import emu.grasscutter.server.packet.send.PacketReliquaryDecomposeRsp;
import emu.grasscutter.utils.Utils;
import it.unimi.dsi.fastutil.Pair;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import com.google.gson.reflect.TypeToken;
public class CombineManger extends BaseGameSystem {
private final static Int2ObjectMap<List<Integer>> reliquaryDecomposeData = new Int2ObjectOpenHashMap<>();
......@@ -40,13 +32,10 @@ public class CombineManger extends BaseGameSystem {
public static void initialize() {
// Read the data we need for strongbox.
try (Reader fileReader = DataLoader.loadReader("ReliquaryDecompose.json")) {
List<ReliquaryDecomposeEntry> decomposeEntries = Grasscutter.getGsonFactory().fromJson(fileReader, TypeToken.getParameterized(Collection.class, ReliquaryDecomposeEntry.class).getType());
for (ReliquaryDecomposeEntry entry : decomposeEntries) {
try {
DataLoader.loadList("ReliquaryDecompose.json", ReliquaryDecomposeEntry.class).forEach(entry -> {
reliquaryDecomposeData.put(entry.getConfigId(), entry.getItems());
}
});
Grasscutter.getLogger().debug("Loaded {} reliquary decompose entries.", reliquaryDecomposeData.size());
}
catch (Exception ex) {
......
package emu.grasscutter.game.drop;
import com.google.gson.reflect.TypeToken;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.data.DataLoader;
import emu.grasscutter.data.GameData;
......@@ -19,9 +18,6 @@ import emu.grasscutter.utils.Utils;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Collection;
import java.util.List;
public class DropSystem extends BaseGameSystem {
......@@ -38,9 +34,9 @@ public class DropSystem extends BaseGameSystem {
}
public synchronized void load() {
try (Reader fileReader = DataLoader.loadReader("Drop.json")) {
getDropData().clear();
List<DropInfo> banners = Grasscutter.getGsonFactory().fromJson(fileReader, TypeToken.getParameterized(Collection.class, DropInfo.class).getType());
try {
List<DropInfo> banners = DataLoader.loadList("Drop.json", DropInfo.class);
if (banners.size() > 0) {
for (DropInfo di : banners) {
getDropData().put(di.getMonsterId(), di.getDropDataList());
......
......@@ -24,16 +24,11 @@ import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import it.unimi.dsi.fastutil.ints.IntSet;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import com.google.gson.reflect.TypeToken;
public class DungeonChallenge extends WorldChallenge {
/**
......@@ -46,13 +41,10 @@ public class DungeonChallenge extends WorldChallenge {
public static void initialize() {
// Read the data we need for dungeon rewards drops.
try (Reader fileReader = DataLoader.loadReader("DungeonDrop.json")) {
List<DungeonDrop> dungeonDropList = Grasscutter.getGsonFactory().fromJson(fileReader, TypeToken.getParameterized(Collection.class, DungeonDrop.class).getType());
for (DungeonDrop entry : dungeonDropList) {
try {
DataLoader.loadList("DungeonDrop.json", DungeonDrop.class).forEach(entry -> {
dungeonDropData.put(entry.getDungeonId(), entry.getDrops());
}
});
Grasscutter.getLogger().debug("Loaded {} dungeon drop data entries.", dungeonDropData.size());
}
catch (Exception ex) {
......
package emu.grasscutter.game.expedition;
import com.google.gson.reflect.TypeToken;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.data.DataLoader;
import emu.grasscutter.server.game.BaseGameSystem;
......@@ -8,12 +7,6 @@ import emu.grasscutter.server.game.GameServer;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import static emu.grasscutter.config.Configuration.*;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Collection;
import java.util.List;
public class ExpeditionSystem extends BaseGameSystem {
......@@ -30,9 +23,9 @@ public class ExpeditionSystem extends BaseGameSystem {
}
public synchronized void load() {
try (Reader fileReader = DataLoader.loadReader("ExpeditionReward.json")) {
getExpeditionRewardDataList().clear();
List<ExpeditionRewardInfo> banners = Grasscutter.getGsonFactory().fromJson(fileReader, TypeToken.getParameterized(Collection.class, ExpeditionRewardInfo.class).getType());
try {
List<ExpeditionRewardInfo> banners = DataLoader.loadList("ExpeditionReward.json", ExpeditionRewardInfo.class);
if (banners.size() > 0) {
for (ExpeditionRewardInfo di : banners) {
getExpeditionRewardDataList().put(di.getExpId(), di.getExpeditionRewardDataList());
......
......@@ -3,18 +3,11 @@ package emu.grasscutter.game.gacha;
import static emu.grasscutter.config.Configuration.*;
import java.io.File;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import com.google.gson.reflect.TypeToken;
import com.sun.nio.file.SensitivityWatchEventModifier;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.data.DataLoader;
......@@ -76,9 +69,9 @@ public class GachaSystem extends BaseGameSystem {
}
public synchronized void load() {
try (Reader fileReader = DataLoader.loadReader("Banners.json")) {
getGachaBanners().clear();
List<GachaBanner> banners = Grasscutter.getGsonFactory().fromJson(fileReader, TypeToken.getParameterized(Collection.class, GachaBanner.class).getType());
try {
List<GachaBanner> banners = DataLoader.loadList("Banners.json", GachaBanner.class);
if (banners.size() > 0) {
for (GachaBanner banner : banners) {
getGachaBanners().put(banner.getScheduleId(), banner);
......
......@@ -31,9 +31,6 @@ import emu.grasscutter.utils.Position;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
......@@ -42,7 +39,6 @@ import java.util.concurrent.ThreadLocalRandom;
import static emu.grasscutter.config.Configuration.GAME_OPTIONS;
import com.google.gson.reflect.TypeToken;
import com.google.protobuf.InvalidProtocolBufferException;
public class EnergyManager extends BasePlayerManager {
......@@ -60,12 +56,10 @@ public class EnergyManager extends BasePlayerManager {
public static void initialize() {
// Read the data we need for monster energy drops.
try (Reader fileReader = DataLoader.loadReader("EnergyDrop.json")) {
List<EnergyDropEntry> energyDropList = Grasscutter.getGsonFactory().fromJson(fileReader, TypeToken.getParameterized(Collection.class, EnergyDropEntry.class).getType());
for (EnergyDropEntry entry : energyDropList) {
try {
DataLoader.loadList("EnergyDrop.json", EnergyDropEntry.class).forEach(entry -> {
energyDropData.put(entry.getDropId(), entry.getDropList());
}
});
Grasscutter.getLogger().debug("Energy drop data successfully loaded.");
}
......@@ -74,12 +68,10 @@ public class EnergyManager extends BasePlayerManager {
}
// Read the data for particle generation from skills
try (Reader fileReader = new InputStreamReader(DataLoader.load("SkillParticleGeneration.json"))) {
List<SkillParticleGenerationEntry> skillParticleGenerationList = Grasscutter.getGsonFactory().fromJson(fileReader, TypeToken.getParameterized(Collection.class, SkillParticleGenerationEntry.class).getType());
for (SkillParticleGenerationEntry entry : skillParticleGenerationList) {
try {
DataLoader.loadList("SkillParticleGeneration.json", SkillParticleGenerationEntry.class).forEach(entry -> {
skillParticleGenerationData.put(entry.getAvatarId(), entry.getAmountList());
}
});
Grasscutter.getLogger().debug("Skill particle generation data successfully loaded.");
}
......
package emu.grasscutter.game.shop;
import com.google.gson.reflect.TypeToken;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.data.DataLoader;
import emu.grasscutter.data.GameData;
......@@ -14,11 +13,7 @@ import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import static emu.grasscutter.config.Configuration.*;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
......@@ -60,9 +55,9 @@ public class ShopSystem extends BaseGameSystem {
}
private void loadShop() {
try (Reader fileReader = DataLoader.loadReader("Shop.json")) {
getShopData().clear();
List<ShopTable> banners = Grasscutter.getGsonFactory().fromJson(fileReader, TypeToken.getParameterized(Collection.class, ShopTable.class).getType());
try {
List<ShopTable> banners = DataLoader.loadList("Shop.json", ShopTable.class);
if (banners.size() > 0) {
for (ShopTable shopTable : banners) {
for (ShopInfo cost : shopTable.getItems()) {
......@@ -104,9 +99,9 @@ public class ShopSystem extends BaseGameSystem {
}
private void loadShopChest() {
try (Reader fileReader = DataLoader.loadReader("ShopChest.json")) {
getShopChestData().clear();
List<ShopChestTable> shopChestTableList = Grasscutter.getGsonFactory().fromJson(fileReader, TypeToken.getParameterized(Collection.class, ShopChestTable.class).getType());
try {
List<ShopChestTable> shopChestTableList = DataLoader.loadList("ShopChest.json", ShopChestTable.class);
if (shopChestTableList.size() > 0) {
getShopChestData().addAll(shopChestTableList);
Grasscutter.getLogger().debug("ShopChest data successfully loaded.");
......@@ -119,9 +114,9 @@ public class ShopSystem extends BaseGameSystem {
}
private void loadShopChestBatchUse() {
try (Reader fileReader = DataLoader.loadReader("ShopChestBatchUse.json")) {
getShopChestBatchUseData().clear();
List<ShopChestBatchUseTable> shopChestBatchUseTableList = Grasscutter.getGsonFactory().fromJson(fileReader, TypeToken.getParameterized(Collection.class, ShopChestBatchUseTable.class).getType());
try {
List<ShopChestBatchUseTable> shopChestBatchUseTableList = DataLoader.loadList("ShopChestBatchUse.json", ShopChestBatchUseTable.class);
if (shopChestBatchUseTableList.size() > 0) {
getShopChestBatchUseData().addAll(shopChestBatchUseTableList);
Grasscutter.getLogger().debug("ShopChestBatchUse data successfully loaded.");
......
package emu.grasscutter.game.systems;
import com.google.gson.reflect.TypeToken;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.data.DataLoader;
import emu.grasscutter.game.player.Player;
......@@ -16,7 +15,6 @@ import lombok.Data;
import lombok.Getter;
import lombok.experimental.FieldDefaults;
import java.io.InputStreamReader;
import java.util.*;
@Getter
......@@ -30,9 +28,8 @@ public class AnnouncementSystem extends BaseGameSystem {
}
private int loadConfig() {
try (var fileReader = DataLoader.loadReader("Announcement.json")) {
List<AnnounceConfigItem> announceConfigItems = Grasscutter.getGsonFactory().fromJson(fileReader,
TypeToken.getParameterized(List.class, AnnounceConfigItem.class).getType());
try {
List<AnnounceConfigItem> announceConfigItems = DataLoader.loadList("Announcement.json", AnnounceConfigItem.class);
announceConfigItemMap.clear();
announceConfigItems.forEach(i -> announceConfigItemMap.put(i.getTemplateId(), i));
......
......@@ -7,11 +7,6 @@ import emu.grasscutter.data.excels.TowerScheduleData;
import emu.grasscutter.server.game.BaseGameSystem;
import emu.grasscutter.server.game.GameServer;
import static emu.grasscutter.config.Configuration.*;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
......@@ -25,8 +20,8 @@ public class TowerSystem extends BaseGameSystem {
private TowerScheduleConfig towerScheduleConfig;
public synchronized void load() {
try (Reader fileReader = DataLoader.loadReader("TowerSchedule.json")) {
towerScheduleConfig = Grasscutter.getGsonFactory().fromJson(fileReader, TowerScheduleConfig.class);
try {
towerScheduleConfig = DataLoader.loadClass("TowerSchedule.json", TowerScheduleConfig.class);
} catch (Exception e) {
Grasscutter.getLogger().error("Unable to load tower schedule config.", e);
}
......
package emu.grasscutter.game.world;
import com.google.gson.reflect.TypeToken;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.data.DataLoader;
import emu.grasscutter.data.GameData;
......@@ -17,9 +16,6 @@ import emu.grasscutter.scripts.data.SceneMonster;
import emu.grasscutter.server.game.BaseGameSystem;
import emu.grasscutter.server.game.GameServer;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
......@@ -42,15 +38,11 @@ public class WorldDataSystem extends BaseGameSystem {
// set the special chest first
chestInteractHandlerMap.put("SceneObj_Chest_Flora", new BossChestInteractHandler());
try (Reader reader = DataLoader.loadReader("ChestReward.json")) {
List<ChestReward> chestReward = Grasscutter.getGsonFactory().fromJson(
reader,
TypeToken.getParameterized(List.class, ChestReward.class).getType());
chestReward.forEach(reward ->
reward.getObjNames().forEach(
name -> chestInteractHandlerMap.putIfAbsent(name, new NormalChestInteractHandler(reward))));
try {
DataLoader.loadList("ChestReward.json", ChestReward.class)
.forEach(reward ->
reward.getObjNames().forEach(name ->
chestInteractHandlerMap.putIfAbsent(name, new NormalChestInteractHandler(reward))));
} catch (Exception e) {
Grasscutter.getLogger().error("Unable to load chest reward config.", e);
}
......
......@@ -12,6 +12,7 @@ import java.util.stream.Collectors;
import emu.grasscutter.GameConstants;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.utils.Utils;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
......@@ -59,7 +60,7 @@ public class PacketOpcodesUtils {
.filter(e -> e.getIntKey() > 0)
.collect(Collectors.toMap(Int2ObjectMap.Entry::getIntKey, Int2ObjectMap.Entry::getValue, (k, v) -> v, TreeMap::new));
// Write to file
writer.write(Grasscutter.getGsonFactory().toJson(packetIds));
writer.write(Utils.jsonEncode(packetIds));
Grasscutter.getLogger().info("Dumped packet ids.");
} catch (IOException e) {
e.printStackTrace();
......
......@@ -82,7 +82,7 @@ public final class PluginManager {
InputStreamReader fileReader = new InputStreamReader(configFile.openStream());
// Create a plugin config instance from the config file.
PluginConfig pluginConfig = Grasscutter.getGsonFactory().fromJson(fileReader, PluginConfig.class);
PluginConfig pluginConfig = Utils.loadJsonToClass(fileReader, PluginConfig.class);
// Check if the plugin config is valid.
if (!pluginConfig.validate()) {
Grasscutter.getLogger().warn("Plugin " + plugin.getName() + " has an invalid config file.");
......
......@@ -130,7 +130,7 @@ public final class Language {
languageCode = description.getLanguageCode();
try {
languageData = Grasscutter.getGsonFactory().fromJson(Utils.readFromInputStream(description.getLanguageFile()), JsonObject.class);
languageData = Utils.jsonDecode(Utils.readFromInputStream(description.getLanguageFile()), JsonObject.class);
} catch (Exception exception) {
Grasscutter.getLogger().warn("Failed to load language file: " + description.getLanguageCode(), exception);
}
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment