From 7dc5f0151ba5ad1b62cde26e155dab80ffc27e7d Mon Sep 17 00:00:00 2001 From: mlus-Asuka <1319237806@qq.com> Date: Fri, 9 Dec 2022 22:47:56 +0800 Subject: [PATCH] fix bug --- .../vip/fubuki/playersync/PlayerSync.java | 7 +++-- .../fubuki/playersync/config/JdbcConfig.java | 2 +- .../fubuki/playersync/sync/ModsSupport.java | 21 +++++++------ .../fubuki/playersync/sync/VanillaSync.java | 29 ++++++++++-------- .../vip/fubuki/playersync/util/JDBCsetUp.java | 30 ++++++++++++++----- 5 files changed, 54 insertions(+), 35 deletions(-) diff --git a/src/main/java/vip/fubuki/playersync/PlayerSync.java b/src/main/java/vip/fubuki/playersync/PlayerSync.java index dad4565..b7d3b16 100644 --- a/src/main/java/vip/fubuki/playersync/PlayerSync.java +++ b/src/main/java/vip/fubuki/playersync/PlayerSync.java @@ -13,6 +13,7 @@ import net.minecraftforge.event.server.ServerStartingEvent; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import org.slf4j.Logger; import vip.fubuki.playersync.config.JdbcConfig; +import vip.fubuki.playersync.sync.VanillaSync; import vip.fubuki.playersync.util.JDBCsetUp; import java.sql.SQLException; @@ -21,21 +22,21 @@ import java.sql.SQLException; public class PlayerSync { public static final String MODID = "playersync"; - private static final Logger LOGGER = LogUtils.getLogger(); + public static final Logger LOGGER = LogUtils.getLogger(); public PlayerSync() { IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus(); ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, JdbcConfig.COMMON_CONFIG); modEventBus.addListener(this::commonSetup); MinecraftForge.EVENT_BUS.register(this); + MinecraftForge.EVENT_BUS.register(new VanillaSync()); } private void commonSetup(final FMLCommonSetupEvent event) {} @SubscribeEvent public void onServerStarting(ServerStartingEvent event) throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException { - JDBCsetUp.executeUpdate("CREATE DATABASE IF NOT EXISTS "+JdbcConfig.DATABASE_NAME.get()); - JDBCsetUp.executeUpdate("USE "+JdbcConfig.DATABASE_NAME.get()); + JDBCsetUp.executeUpdate("CREATE DATABASE IF NOT EXISTS "+JdbcConfig.DATABASE_NAME.get(),true); JDBCsetUp.executeUpdate("CREATE TABLE IF NOT EXISTS player_data (uuid CHAR(36) NOT NULL,inventory BLOB,armor BLOB,advancements BLOB,enderchest BLOB,effects BLOB,xp int,food_level int,score int,health int,online boolean, PRIMARY KEY (uuid))"); if(ModList.get().isLoaded("curios")) { JDBCsetUp.executeUpdate("CREATE TABLE IF NOT EXISTS curios (uuid CHAR(36) NOT NULL,curios_item BLOB, PRIMARY KEY (uuid))"); diff --git a/src/main/java/vip/fubuki/playersync/config/JdbcConfig.java b/src/main/java/vip/fubuki/playersync/config/JdbcConfig.java index 732903b..c68382f 100644 --- a/src/main/java/vip/fubuki/playersync/config/JdbcConfig.java +++ b/src/main/java/vip/fubuki/playersync/config/JdbcConfig.java @@ -25,7 +25,7 @@ public class JdbcConfig { HOST=COMMON_BUILDER.comment("The host of the database").define("host", "localhost"); DATABASE_NAME= COMMON_BUILDER.comment("Database name").define("database_name", "playersync"); PORT = COMMON_BUILDER.comment("database port").defineInRange("db_port", 3306, 0, 65535); - USE_SSL = COMMON_BUILDER.comment("Use SSL").define("whether use ssl", false); + USE_SSL = COMMON_BUILDER.comment("whether use SSL").define("use_ssl", false); USERNAME = COMMON_BUILDER.comment("username").define("user_name", "root"); PASSWORD = COMMON_BUILDER.comment("password").define("password", "password"); SYNC_WORLD = COMMON_BUILDER.comment("The worlds that will be synchronized.If running in server it is supposed to have only one").define("sync_world", new ArrayList()); diff --git a/src/main/java/vip/fubuki/playersync/sync/ModsSupport.java b/src/main/java/vip/fubuki/playersync/sync/ModsSupport.java index dcb036e..fea94a3 100644 --- a/src/main/java/vip/fubuki/playersync/sync/ModsSupport.java +++ b/src/main/java/vip/fubuki/playersync/sync/ModsSupport.java @@ -5,8 +5,6 @@ import net.minecraft.nbt.NbtUtils; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.event.entity.player.PlayerEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.ModList; import net.minecraftforge.items.IItemHandlerModifiable; import vip.fubuki.playersync.util.JDBCsetUp; @@ -19,26 +17,28 @@ import java.util.Map; @SuppressWarnings({"InstantiationOfUtilityClass", "AccessStaticViaInstance"}) public class ModsSupport { - @SubscribeEvent - public void onPlayerJoin(PlayerEvent.PlayerLoggedInEvent event) throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException { + + public void onPlayerJoin(Player player) throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException { if (ModList.get().isLoaded("curios")) { //TODO curios support top.theillusivec4.curios.api.CuriosApi CuriosApi = new top.theillusivec4.curios.api.CuriosApi(); - LazyOptional itemHandler = CuriosApi.getCuriosHelper().getEquippedCurios(event.getEntity()); - ResultSet resultSet = JDBCsetUp.executeQuery("SELECT curios_item FROM curios WHERE uuid = '"+event.getEntity().getUUID()+"'"); + LazyOptional itemHandler = CuriosApi.getCuriosHelper().getEquippedCurios(player); + ResultSet resultSet = JDBCsetUp.executeQuery("SELECT curios_item FROM curios WHERE uuid = '"+player.getUUID()+"'"); if(resultSet.next()) { - Map curios = LocalJsonUtil.StringToEntryMap(resultSet.getString("curios")); + Map curios = LocalJsonUtil.StringToEntryMap(resultSet.getString("curios_item")); itemHandler.ifPresent(handler -> { for (int i = 0; i < handler.getSlots(); i++) { try { + if(curios.get(i)==null) continue; handler.setStackInSlot(i, ItemStack.of(NbtUtils.snbtToStructure(curios.get(i).replace("|", ",")))); } catch (CommandSyntaxException e) { throw new RuntimeException(e); } } }); + resultSet.close(); }else{ - StoreCurios(event.getEntity(),true); + StoreCurios(player,true); } } if(ModList.get().isLoaded("sophisticatedbackpacks")) { @@ -46,10 +46,9 @@ public class ModsSupport { } } - @SubscribeEvent - public void onPlayerLeave(PlayerEvent.PlayerLoggedOutEvent event) throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException { + public void onPlayerLeave(Player player) throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException { if (ModList.get().isLoaded("curios")) { - StoreCurios(event.getEntity(), false); + StoreCurios(player, false); } if(ModList.get().isLoaded("sophisticatedbackpacks")) { //TODO sophisticatedbackpacks support diff --git a/src/main/java/vip/fubuki/playersync/sync/VanillaSync.java b/src/main/java/vip/fubuki/playersync/sync/VanillaSync.java index 3b7cc1a..b4385c2 100644 --- a/src/main/java/vip/fubuki/playersync/sync/VanillaSync.java +++ b/src/main/java/vip/fubuki/playersync/sync/VanillaSync.java @@ -68,16 +68,13 @@ public class VanillaSync { serverPlayer.getEnderChestInventory().setItem(entry.getKey(),Deserialize(entry)); } //Effects - if(!resultSet.getString("effects").equals("{}")) { - Map effects = LocalJsonUtil.StringToEntryMap(resultSet.getString("effects")); - for (Map.Entry entry : effects.entrySet()) { - CompoundTag effectTag = NbtUtils.snbtToStructure(entry.getValue().replace("|", ",")); - MobEffectInstance mobEffectInstance = MobEffectInstance.load(effectTag); - assert mobEffectInstance != null; - serverPlayer.addEffect(mobEffectInstance); - } - }else{ - serverPlayer.removeAllEffects(); + serverPlayer.removeAllEffects(); + Map effects = LocalJsonUtil.StringToEntryMap(resultSet.getString("effects")); + for (Map.Entry entry : effects.entrySet()) { + CompoundTag effectTag = NbtUtils.snbtToStructure(entry.getValue().replace("|", ",")); + MobEffectInstance mobEffectInstance = MobEffectInstance.load(effectTag); + assert mobEffectInstance != null; + serverPlayer.addEffect(mobEffectInstance); } //Advancements File gameDir = Minecraft.getInstance().gameDirectory; @@ -91,13 +88,17 @@ public class VanillaSync { }else{ File[] files= ScanAdvancementsFile(player_uuid, gameDir); for (File file : files) { - if(!file.exists()) continue; + if(file==null) continue; byte [] bytes=resultSet.getString("advancements").getBytes(); Files.write(file.toPath(),bytes); } } } + //Mod support + ModsSupport modsSupport = new ModsSupport(); + modsSupport.onPlayerJoin(serverPlayer); } + resultSet.close(); } private static ItemStack Deserialize(Map.Entry entry) throws CommandSyntaxException { @@ -110,6 +111,9 @@ public class VanillaSync { String player_uuid = event.getEntity().getUUID().toString(); JDBCsetUp.executeUpdate("UPDATE player_data SET online=false WHERE uuid='"+player_uuid+"'"); Store(event.getEntity(),false,Dist.CLIENT.isDedicatedServer()); + //Mod support + ModsSupport modsSupport = new ModsSupport(); + modsSupport.onPlayerLeave(event.getEntity()); } public void Store(Player player, boolean init,boolean isServer) throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException, IOException { @@ -157,6 +161,7 @@ public class VanillaSync { //Get LastModified long latestModifiedDate = 0; for (File file : files) { + if(file==null) continue; if (file.lastModified() > latestModifiedDate) { latestModifiedDate = file.lastModified(); advancements = file; @@ -171,7 +176,7 @@ public class VanillaSync { //SQL Operation if(init){ - JDBCsetUp.executeUpdate("INSERT INTO player_data (uuid,armor,inventory,enderchest,advancements,effects,xp,food_level,health,score,online) VALUES ('"+player_uuid+"','"+equipment+"','"+inventoryMap+"','"+ender_chest+"','"+advancements+"','"+effects+"','"+XP+"','"+food_level+"','"+health+"','"+score+"',online=true)"); + JDBCsetUp.executeUpdate("INSERT INTO player_data (uuid,armor,inventory,enderchest,advancements,effects,xp,food_level,health,score,online) VALUES ('"+player_uuid+"','"+equipment+"','"+inventoryMap+"','"+ender_chest+"','"+advancements+"','"+effectMap+"','"+XP+"','"+food_level+"','"+health+"','"+score+"',online=true)"); }else JDBCsetUp.executeUpdate("UPDATE player_data SET inventory = '"+inventoryMap+"',armor='"+equipment+"' ,xp='"+XP+"',effects='"+effectMap+"',enderchest='"+ender_chest+"',score='"+score+"',food_level='"+food_level+"',health='"+health+"',advancements='"+json+"' WHERE uuid = '"+player_uuid+"'"); } diff --git a/src/main/java/vip/fubuki/playersync/util/JDBCsetUp.java b/src/main/java/vip/fubuki/playersync/util/JDBCsetUp.java index 94036b0..bcd5e1e 100644 --- a/src/main/java/vip/fubuki/playersync/util/JDBCsetUp.java +++ b/src/main/java/vip/fubuki/playersync/util/JDBCsetUp.java @@ -6,28 +6,42 @@ import java.sql.*; import java.util.Properties; + public class JDBCsetUp { - private static final String url="jdbc:mysql://"+JdbcConfig.HOST.get()+":"+JdbcConfig.PORT.get()+"?useUnicode=true&characterEncoding=utf-8&useSSL="+JdbcConfig.USE_SSL.get()+"&serverTimezone=UTC&allowPublicKeyRetrieval=true"; - public static Connection getConnection() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException { - Class clazz = Class.forName("com.mysql.cj.jdbc.Driver"); + @SuppressWarnings("deprecation") + public static Connection getConnection(boolean init) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException { + Class clazz = Class.forName("com.mysql.cj.jdbc.Driver"); Driver driver = (Driver) clazz.newInstance(); Properties properties = new Properties(); properties.setProperty("user",JdbcConfig.USERNAME.get()); properties.setProperty("password",JdbcConfig.PASSWORD.get()); + String url; + if(init) { + url="jdbc:mysql://"+JdbcConfig.HOST.get()+":"+JdbcConfig.PORT.get()+"?useUnicode=true&characterEncoding=utf-8&useSSL="+JdbcConfig.USE_SSL.get()+"&serverTimezone=UTC&allowPublicKeyRetrieval=true"; + }else{ + url="jdbc:mysql://"+JdbcConfig.HOST.get()+":"+JdbcConfig.PORT.get()+"/"+JdbcConfig.DATABASE_NAME.get()+"?useUnicode=true&characterEncoding=utf-8&useSSL="+JdbcConfig.USE_SSL.get()+"&serverTimezone=UTC&allowPublicKeyRetrieval=true"; + } return driver.connect(url,properties); } public static ResultSet executeQuery(String sql) throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException { - Statement statement= getConnection().createStatement(); - statement.executeUpdate("USE "+JdbcConfig.DATABASE_NAME.get()); - return statement.executeQuery(sql); + Statement statement= getConnection(false).createStatement(); + ResultSet resultSet = statement.executeQuery(sql); + return resultSet; } public static void executeUpdate(String sql) throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException { - Statement statement= getConnection().createStatement(); - statement.executeUpdate("USE "+JdbcConfig.DATABASE_NAME.get()); + Statement statement= getConnection(false).createStatement(); statement.executeUpdate(sql); + statement.close(); + } + + public static void executeUpdate(String sql,boolean init) throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException { + Statement statement= getConnection(init).createStatement(); + if(!init) statement.executeUpdate("USE "+JdbcConfig.DATABASE_NAME.get()); + statement.executeUpdate(sql); + statement.close(); } }