reorganized code, added world share settings

This commit is contained in:
BuildTools 2016-10-29 03:02:27 -04:00
parent 9184da925b
commit db74430384
16 changed files with 595 additions and 457 deletions

View file

@ -1,6 +1,3 @@
main: iie.PerWorldInventoryPlugin main: main.MainPlugin
version: 1.0.0 version: 1.0.0
name: PerWorldInventoryPlugin name: PerWorldInventories
commands:
soundtest:
description: performs SoundTest

View file

@ -1,41 +0,0 @@
package iie;
import java.io.File;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
public class PerWorldInventoryPlugin extends JavaPlugin {
public void onEnable(){
PluginManager manager = getServer().getPluginManager();
manager.registerEvents(new WorldChangeListener(this), this);
PerWorldInventoryPlugin.getPlugin(this.getClass()).getServer().getListeningPluginChannels();
createConfig();
}
private void createConfig(){
try {
if (!getDataFolder().exists())
getDataFolder().mkdirs();
//CONFIG.YML
File file = new File(getDataFolder(), "config.yml");
if (!file.exists()){
getLogger().info("Config.yml not found, creating!");
saveDefaultConfig();
}else
getLogger().info("Config.yml found, loading!");
}catch (Exception e) {
e.printStackTrace();
}
}
}

View file

@ -1,24 +0,0 @@
package iie;
import org.bukkit.Location;
import org.bukkit.entity.Player;
public class PlayerData {
public static class Position {
public static String StringFromLocation(Player player){
Location location = player.getLocation();
return "x:" + location.getBlockX() + ",z:" + location.getBlockZ() + ",y:" + location.getBlockY();
}
public Location LocationFromString(String locationString){
return null;
}
}
}

View file

@ -1,80 +0,0 @@
package iie;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.apache.commons.codec.binary.Base64;
import org.bukkit.entity.Player;
import net.minecraft.server.v1_10_R1.IInventory;
import net.minecraft.server.v1_10_R1.ItemStack;
import net.minecraft.server.v1_10_R1.JsonList;
import net.minecraft.server.v1_10_R1.NBTCompressedStreamTools;
import net.minecraft.server.v1_10_R1.NBTTagCompound;
public class SerializerDebug {
public static String serializeItemStack(ItemStack itemStack, Player player){
player.sendMessage("serializeItemStack: called");
if (itemStack == null){ player.sendMessage("serializeItemStack: NULL itemStack"); return "null";}
player.sendMessage("serializeItemStack: nbt tag = " + itemStack.getTag().toString());
return itemStack.getTag().toString();
}
public static ItemStack deserializeItemStack(String itemStackString, Player player){
if (itemStackString.equals("null")){
player.sendMessage("deserializeItemStack: NULL itemStackString");
return null;
}
NBTTagCompound nbtTagCompound = (NBTTagCompound) JsonList.func_150315_a(itemStackString);;
player.sendMessage(nbtTagCompound.toString());
return ItemStack.createStack(nbtTagCompound);
}
public static String serializeInventory (IInventory invInventory, Player player){
player.sendMessage("serializeInventory: invInventory.getSize() = " + invInventory.getSize());
return IntStream.range(0, invInventory.getSize() - 1)
.mapToObj(s -> {
ItemStack i = invInventory.getItem(s);
player.sendMessage(Objects.isNull(i) ? "serializeInventory: NULL item" + s : "serializeInventory: item " + s + " found");
return Objects.isNull(i) ? null : s + "#" + serializeItemStack(i, player);
})
.filter(s -> s != null)
.collect(Collectors.joining(";"));
}
public static void setInventoryFromSerialized (IInventory invInventory, String invString, Player player){
if (invInventory == null){ player.sendMessage("setInventoryFromSerialized: invInventory NULL"); return;}
invInventory.l();
if (invString == null){ player.sendMessage("setInventoryFromSerialized: NULL invString"); return;}
if (invString.isEmpty()){ player.sendMessage("setInventoryFromSerialized: EMPTY invString"); return;}
if (!invString.contains(";")){ player.sendMessage("setInventoryFromSerialized: DOESN'T CONTAIN ';' "); return;}
Arrays.asList(invString.split(";"))
.stream()
.forEach(s -> {
String[] e = s.split("#");
invInventory.setItem(Integer.parseInt(e[0]), deserializeItemStack(e[1], player));
player.sendMessage("set item " + e[0] + " to inventory");
});
}
}

View file

@ -1,170 +0,0 @@
package iie;
import com.google.common.collect.ForwardingMultimap;
import org.apache.commons.codec.binary.Base64;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.SkullMeta;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
public class SkullMaker {
private String owner;
private String url;
private int amount = 1;
private String name;
private List<String> lore = new ArrayList<>();
public SkullMaker withAmount(int amount) {
this.amount = amount;
return this;
}
public SkullMaker withName(String name) {
this.name = name;
return this;
}
public SkullMaker withLore(String line) {
lore.add(line);
return this;
}
public SkullMaker withLore(String... lines) {
lore.addAll(Arrays.asList(lines));
return this;
}
public SkullMaker withLore(List<String> lines) {
lore.addAll(lines);
return this;
}
public SkullMaker withOwner(String ownerName) {
this.owner = ownerName;
return this;
}
public SkullMaker withSkinUrl(String url) {
this.url = url;
return this;
}
public ItemStack build() {
ItemStack item = new ItemStack(Material.SKULL_ITEM, amount, (short) 3);
SkullMeta meta = (SkullMeta) item.getItemMeta();
if (owner != null) {
meta.setOwner(owner);
} else if (url != null) {
loadProfile(meta, url);
}
if (name != null) {
meta.setDisplayName(name);
}
if (!lore.isEmpty()) {
meta.setLore(lore);
}
item.setItemMeta(meta);
return item;
}
private void loadProfile(ItemMeta meta, String url) {
Class<?> profileClass = Reflection.getClass("com.mojang.authlib.GameProfile");
Constructor<?> profileConstructor = Reflection.getDeclaredConstructor(profileClass, UUID.class, String.class);
Object profile = Reflection.newInstance(profileConstructor, UUID.randomUUID(), null);
byte[] encodedData = Base64.encodeBase64(String.format("{textures:{SKIN:{url:\"%s\"}}}", url).getBytes());
Method getPropertiesMethod = Reflection.getDeclaredMethod(profileClass, "getProperties");
Object propertyMap = Reflection.invoke(getPropertiesMethod, profile);
Class<?> propertyClass = Reflection.getClass("com.mojang.authlib.properties.Property");
Reflection.invoke(
Reflection.getDeclaredMethod(
ForwardingMultimap.class, "put", Object.class, Object.class
),
propertyMap,
"textures",
Reflection.newInstance(Reflection.getDeclaredConstructor(propertyClass, String.class, String.class), "textures", new String(encodedData))
);
Reflection.setField("profile", meta, profile);
}
private static final class Reflection {
private static Class<?> getClass(String forName) {
try {
return Class.forName(forName);
} catch (ClassNotFoundException e) {
return null;
}
}
private static <T> Constructor<T> getDeclaredConstructor(Class<T> clazz, Class<?>... params) {
try {
return clazz.getDeclaredConstructor(params);
} catch (NoSuchMethodException e) {
return null;
}
}
private static <T> T newInstance(Constructor<T> constructor, Object... params) {
try {
return constructor.newInstance(params);
} catch (IllegalAccessException | InstantiationException | InvocationTargetException e) {
return null;
}
}
private static Method getDeclaredMethod(Class<?> clazz, String name, Class<?>... params) {
try {
return clazz.getDeclaredMethod(name, params);
} catch (NoSuchMethodException e) {
return null;
}
}
private static Object invoke(Method method, Object object, Object... params) {
method.setAccessible(true);
try {
return method.invoke(object, params);
} catch (InvocationTargetException | IllegalAccessException e) {
return null;
}
}
private static void setField(String name, Object instance, Object value) {
Field field = getDeclaredField(instance.getClass(), name);
field.setAccessible(true);
try {
field.set(instance, value);
} catch (IllegalAccessException ignored) {}
}
private static Field getDeclaredField(Class<?> clazz, String name) {
try {
return clazz.getDeclaredField(name);
} catch (NoSuchFieldException e) {
return null;
}
}
}
}

View file

@ -1,91 +0,0 @@
package iie;
import java.util.UUID;
import org.bukkit.World;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.craftbukkit.v1_10_R1.inventory.CraftInventory;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerChangedWorldEvent;
import net.minecraft.server.v1_10_R1.IInventory;
public class WorldChangeListener implements Listener {
PerWorldInventoryPlugin plugin;
public WorldChangeListener(PerWorldInventoryPlugin plugin){
this.plugin = plugin;
}
@EventHandler(priority = EventPriority.MONITOR)
public void onWorldChangeListener(PlayerChangedWorldEvent event){
Player player = event.getPlayer();
UUID uuid = player.getUniqueId();
String playerPath = ".players.(" + player.getName() + ")" + uuid.toString() + ".";
World worldTo = player.getWorld();
World worldFrom = event.getFrom();
String worldToName = worldTo.getName();
String worldFromName = worldFrom.getName();
String pathTo = worldToName + playerPath;
String pathFrom = worldFromName + playerPath;
FileConfiguration config = plugin.getConfig();
//----------------------------------------------------------------------instantiations
//----------------------------------------------------------------------INVENTORY
final IInventory inventory = ((CraftInventory)player.getInventory()).getInventory();
config.set(pathFrom + "inventory", SerializerDebug.serializeInventory(inventory, player));
plugin.saveConfig();
SerializerDebug.setInventoryFromSerialized(inventory, (String) config.get(pathTo + "inventory"), player);
//player.getInventory().clear();
//player.getInventory().setContents(
// SerializerDebug.InventoryFromString(invString, invInventory.getType())
// .getContents()
// );
//----------------------------------------------------------------------ENDERCHEST
final IInventory enderchest = ((CraftInventory)player.getEnderChest()).getInventory();
config.set(pathFrom + "enderchest", SerializerDebug.serializeInventory(enderchest, player));
plugin.saveConfig();
SerializerDebug.setInventoryFromSerialized(enderchest, (String) config.get(pathTo + "enderchest"), player);
//player.getEnderChest().clear();
//player.getEnderChest().setContents(
// SerializerDebug.InventoryFromString(invString, invInventory.getType())
// .getContents()
// );
//----------------------------------------------------------------------PLAYER DATA
config.set(pathFrom + "status", PlayerData.Position.StringFromLocation(player));
plugin.saveConfig();
}
}

View file

@ -1,25 +0,0 @@
package iie;
import net.minecraft.server.v1_10_R1.IInventory;
public class test {
public static IInventory invInventory (){
IInventory invInventory = null;
try{
invInventory = IInventory.class.newInstance();
}catch (IllegalAccessException | InstantiationException e) {
e.printStackTrace();
}
return invInventory;
}
public void method(){
final IInventory invInventory = invInventory();
Serializer.setInventoryFromSerialized(invInventory, "string");
}
public void method2(){
method();
}
}

59
src/main/MainPlugin.java Normal file
View file

@ -0,0 +1,59 @@
package main;
import org.bukkit.plugin.java.JavaPlugin;
public class MainPlugin extends JavaPlugin {
public void onEnable(){
//getServer().getPluginManager().registerEvents(new WorldLoadListener(this), this);
getServer().getPluginManager().registerEvents(new WorldChangeListener(this), this);
MainPlugin.getPlugin(this.getClass()).getServer().getListeningPluginChannels();
saveDefaultConfig();
WorldChangeManager.init(this);
//BukkitTask task = new initWorldSettings().runTaskLater(this, 20);
}
}
/*
public void initWorldSettings(){
Bukkit.getServer().getWorlds()
.stream()
.forEach(s -> {
FileConfiguration config = getConfig();
String name = s.getName();
if (config.get(name + ".settings.shareinvgroup") == null)
config.set(name + ".settings.shareinvgroup", name);
if (config.get(name + ".settings.sharedatagroup") == null)
config.set(name + ".settings.sharedatagroup", name);
});
saveConfig();
}
}
private void createConfig(){
try {
if (!getDataFolder().exists())
getDataFolder().mkdirs();
File file = new File(getDataFolder(), "config.yml");
if (!file.exists()){
getLogger().info("Config.yml not found, creating!");
saveDefaultConfig();
}else
getLogger().info("Config.yml found, loading!");
}catch (Exception e) {
e.printStackTrace();
}
}
*/

View file

@ -1,4 +1,4 @@
package iie; package main;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@ -273,7 +273,7 @@ public class SerializerOld {
if (texture != null) if (texture != null)
serializedItemStack += ":texture@" + texture; serializedItemStack += ":texture@" + texture;
((Player) invInventory.getHolder()).sendMessage( ((Player) invInventory.getHolder()).sendMessage(
Serializer.serializeItemStack( Serializers.serializeItemStack(
((CraftInventory) invInventory).getInventory().getContents()[i] ((CraftInventory) invInventory).getInventory().getContents()[i]
) )
); );

126
src/main/Serializers.java Normal file
View file

@ -0,0 +1,126 @@
package main;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.apache.commons.codec.binary.Base64;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.craftbukkit.v1_10_R1.entity.CraftPlayer;
import org.bukkit.entity.Player;
import net.minecraft.server.v1_10_R1.EntityPlayer;
import net.minecraft.server.v1_10_R1.IInventory;
import net.minecraft.server.v1_10_R1.ItemStack;
import net.minecraft.server.v1_10_R1.NBTCompressedStreamTools;
import net.minecraft.server.v1_10_R1.NBTTagCompound;
import net.minecraft.server.v1_10_R1.PlayerList;
public class Serializers {
//----------------------------------------------------------------------( INVENTORY )
//SERIALIZE ITEMSTACK
public static String serializeItemStack(ItemStack itemStack){
NBTTagCompound tag = itemStack.save(new NBTTagCompound());
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try { NBTCompressedStreamTools.a(tag, outputStream); }
catch (IOException e) { e.printStackTrace(); }
return Base64.encodeBase64String(outputStream.toByteArray());
}
//DESERIALIZE ITEMSTACK
public static ItemStack deserializeItemStack(String itemStackString){
NBTTagCompound nbtTagCompound = null;
ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64.decodeBase64(itemStackString));
try {nbtTagCompound = NBTCompressedStreamTools.a(inputStream);}
catch (IOException e) {e.printStackTrace();}
return ItemStack.createStack(nbtTagCompound);
}
//SERIALIZE INVENTORY
public static String serializeInventory (IInventory invInventory){
return IntStream.range(0, invInventory.getSize())
.mapToObj(s -> {
ItemStack i = invInventory.getItem(s);
return Objects.isNull(i) ? null : s + "#" + serializeItemStack(i);
})
.filter(s -> s != null)
.collect(Collectors.joining(";"));
}
//SET INVENTORY FROM SERIALIZED
public static void setInventoryFromSerialized (IInventory invInventory, String invString){
invInventory.l();
if (invString != null && !invString.isEmpty())
Arrays.asList(invString.split(";"))
.parallelStream()
.forEach(s -> {
String[] e = s.split("#");
invInventory.setItem(Integer.parseInt(e[0]), deserializeItemStack(e[1]));
});
}
//----------------------------------------------------------------------( LOCATION )
//SERIALIZE LOCATION
public static String serializeLocation(Location location){
return
"x:" + location.getBlockX() +
",z:" + location.getBlockZ() +
",y:" + location.getBlockY() +
",p:" + location.getPitch() +
",y:" + location.getYaw();
}
//DESERIALIZE LOCATION
public static Location deserializeLocation(World world, String locationString){
String[] s = locationString.split(",");
return new Location(
world,
Double.valueOf(s[0].split(":")[1]),
Double.valueOf(s[1].split(":")[1]),
Double.valueOf(s[2].split(":")[1]),
Float.valueOf(s[3].split(":")[1]),
Float.valueOf(s[4].split(":")[1])
);
}
//----------------------------------------------------------------------( PLAYERDATA )
//SERIALIZE PLAYERDATA
public static String serializePlayerData(Player player){
StringBuilder result = new StringBuilder();
result.append("health:" + player.getHealth() + ";");
result.append("food:" + player.getFoodLevel() + ";");
result.append("exhaustion: " + player.getExhaustion() + ";");
result.append("exp:" + player.getExp() + ";");
result.append("air:" + player.getRemainingAir() + ";");
result.append("fireticks:" + player.getFireTicks() + ";");
return result.toString();
}
}

View file

@ -0,0 +1,39 @@
package main;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerChangedWorldEvent;
public class WorldChangeListener implements Listener {
private static MainPlugin plugin;
private static FileConfiguration config;
public WorldChangeListener(MainPlugin plugin){
WorldChangeListener.plugin = plugin;
WorldChangeListener.config = plugin.getConfig();
}
@EventHandler(priority = EventPriority.MONITOR)
public void onWorldChangeListener(PlayerChangedWorldEvent event){
Player player = event.getPlayer();
String worldTo = player.getWorld().getName();
String worldFrom = event.getFrom().getName();
initWorldSettings(worldTo);
initWorldSettings(worldFrom);
WorldChangeManager.update(player,worldTo, worldFrom);
}
public static void initWorldSettings(String world){
if (config.get(world + ".settings.shareinvgroup") == null)
config.set(world + ".settings.shareinvgroup", world);
if (config.get(world + ".settings.sharedatagroup") == null)
config.set(world + ".settings.sharedatagroup", world);
plugin.saveConfig();
}
}

View file

@ -0,0 +1,156 @@
package main;
import java.util.Arrays;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.craftbukkit.v1_10_R1.inventory.CraftInventory;
import org.bukkit.entity.Player;
import net.minecraft.server.v1_10_R1.IInventory;
public class WorldChangeManager {
private static MainPlugin plugin;
private static FileConfiguration config;
public static void init(MainPlugin plugin){ //onEnable()
WorldChangeManager.plugin = plugin;
WorldChangeManager.config = plugin.getConfig();
}
//EVALUATE SHARE SETTINGS
public static boolean[] compare (String worldTo, String worldFrom) {
boolean[] result = new boolean[] {false,false};
String[][] params =
(String[][]) Arrays.asList
(new String[] {
(String) config.get(worldTo + ".settings.shareinvgroup"),
(String) config.get(worldFrom + ".settings.shareinvgroup"),
(String) config.get(worldTo + ".settings.sharedatagroup"),
(String) config.get(worldFrom + ".settings.sharedatagroup")
})
.stream()
.map(s -> (String[]) s
.trim()
.replaceAll("( )", "")
.toLowerCase()
.split("\\*"))
.toArray(String[][]::new);
/* Each world has two sharing settings: for inventory sharing,
* and for playerdata sharing. Each setting has two parameters:
* the sharegroup flag, which labels a group of sharing worlds,
* and an optional suffix, *in or *out, specifying that the world
* shares with its group in only one traffic direction
*/
if (params[0][0].equals(params[1][0])//inv
&& (
(
params[0].length > 1 ? params[0][1].equals("in") : true
&& params[1].length > 1 ? params[1][1].equals("out") : true
)
|| (
params[1].length > 1 ? params[1][1].equals("out") : true
&& params[0].length > 1 ? params[1][1].equals("in") : true
)
)
)
result[0] = true;
if (params[2][0].equals(params[3][0])//data
&& (
(
params[2].length > 1 ? params[2][1].equals("in") : true
&& params[3].length > 1 ? params[3][1].equals("out") : true
)
|| (
params[3].length > 1 ? params[3][1].equals("out") : true
&& params[2].length > 1 ? params[3][1].equals("in") : true
)
)
)
result[1] = true;
return result;
}
//VALUES USED BY THE UPDATE METHODS
public static class Values {
public String uuid;
public String worldTo;
public String worldFrom;
public String pTo;
public String pFrom;
public boolean shareinv;
public boolean sharedata;
public Values (Player player, String worldTo, String worldFrom){
this.uuid = player.getUniqueId().toString();
this.worldTo = worldTo;
this.worldFrom = worldFrom;
this.pTo = worldTo + ".players." + uuid;
this.pFrom = worldFrom + ".players." + uuid;
boolean[] compare = compare(worldTo,worldFrom);
this.shareinv = compare[0];
this.sharedata = compare[1];
}
}
//MAIN UPDATE METHOD
public static void update(Player player, String worldTo, String worldFrom){
final Values values = new Values(player, worldTo, worldFrom);
updateLocation(values, player);
updateInventories(values, player);
//updatePlayerData(values, player);
}
//UPDATE LOCATION
public static void updateLocation(Values values, Player player){
config.set(
values.pFrom + ".location",
serializers.location.serialize(player.getLocation())
);
plugin.saveConfig();
/* players are not automatically moved to their stored location,
* this is done only on request, in a dedicated teleport method
*/
}
//UPDATE INVENTORIES
public static void updateInventories(Values values, Player player){
IInventory inventory = ((CraftInventory) player.getInventory()).getInventory();
config.set(values.pFrom + ".inventory", serializers.inventory.serialize(inventory));
plugin.saveConfig();
if (!values.shareinv)
serializers.inventory.setFromSerialized(
inventory, (String) config.get(values.pTo + ".inventory")
);
IInventory enderchest = ((CraftInventory) player.getEnderChest()).getInventory();
config.set(values.pFrom + ".enderchest", serializers.inventory.serialize(enderchest));
plugin.saveConfig();
if (!values.sharedata)
serializers.inventory.setFromSerialized(
enderchest, (String) config.get(values.pTo + ".enderchest")
);
}
//UPDATE PLAYERDATA
public static void updatePlayerData(Values values, Player player){
config.set(values.pFrom + ".playerdata", serializers.playerdata.serialize(player));
plugin.saveConfig();
if (!values.sharedata)
;
}
}

View file

@ -0,0 +1,126 @@
package serializers;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.apache.commons.codec.binary.Base64;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.craftbukkit.v1_10_R1.entity.CraftPlayer;
import org.bukkit.entity.Player;
import net.minecraft.server.v1_10_R1.EntityPlayer;
import net.minecraft.server.v1_10_R1.IInventory;
import net.minecraft.server.v1_10_R1.ItemStack;
import net.minecraft.server.v1_10_R1.NBTCompressedStreamTools;
import net.minecraft.server.v1_10_R1.NBTTagCompound;
import net.minecraft.server.v1_10_R1.PlayerList;
public class Serializers {
//----------------------------------------------------------------------( INVENTORY )
//SERIALIZE ITEMSTACK
public static String serializeItemStack(ItemStack itemStack){
NBTTagCompound tag = itemStack.save(new NBTTagCompound());
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try { NBTCompressedStreamTools.a(tag, outputStream); }
catch (IOException e) { e.printStackTrace(); }
return Base64.encodeBase64String(outputStream.toByteArray());
}
//DESERIALIZE ITEMSTACK
public static ItemStack deserializeItemStack(String itemStackString){
NBTTagCompound nbtTagCompound = null;
ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64.decodeBase64(itemStackString));
try {nbtTagCompound = NBTCompressedStreamTools.a(inputStream);}
catch (IOException e) {e.printStackTrace();}
return ItemStack.createStack(nbtTagCompound);
}
//SERIALIZE INVENTORY
public static String serializeInventory (IInventory invInventory){
return IntStream.range(0, invInventory.getSize())
.mapToObj(s -> {
ItemStack i = invInventory.getItem(s);
return Objects.isNull(i) ? null : s + "#" + serializeItemStack(i);
})
.filter(s -> s != null)
.collect(Collectors.joining(";"));
}
//SET INVENTORY FROM SERIALIZED
public static void setInventoryFromSerialized (IInventory invInventory, String invString){
invInventory.l();
if (invString != null && !invString.isEmpty())
Arrays.asList(invString.split(";"))
.parallelStream()
.forEach(s -> {
String[] e = s.split("#");
invInventory.setItem(Integer.parseInt(e[0]), deserializeItemStack(e[1]));
});
}
//----------------------------------------------------------------------( LOCATION )
//SERIALIZE LOCATION
public static String serializeLocation(Location location){
return
"x:" + location.getBlockX() +
",z:" + location.getBlockZ() +
",y:" + location.getBlockY() +
",p:" + location.getPitch() +
",y:" + location.getYaw();
}
//DESERIALIZE LOCATION
public static Location deserializeLocation(World world, String locationString){
String[] s = locationString.split(",");
return new Location(
world,
Double.valueOf(s[0].split(":")[1]),
Double.valueOf(s[1].split(":")[1]),
Double.valueOf(s[2].split(":")[1]),
Float.valueOf(s[3].split(":")[1]),
Float.valueOf(s[4].split(":")[1])
);
}
//----------------------------------------------------------------------( PLAYERDATA )
//SERIALIZE PLAYERDATA
public static String serializePlayerData(Player player){
StringBuilder result = new StringBuilder();
result.append("health:" + player.getHealth() + ";");
result.append("food:" + player.getFoodLevel() + ";");
result.append("exhaustion: " + player.getExhaustion() + ";");
result.append("exp:" + player.getExp() + ";");
result.append("air:" + player.getRemainingAir() + ";");
result.append("fireticks:" + player.getFireTicks() + ";");
return result.toString();
}
}

View file

@ -1,4 +1,4 @@
package iie; package serializers;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
@ -15,30 +15,25 @@ import net.minecraft.server.v1_10_R1.ItemStack;
import net.minecraft.server.v1_10_R1.NBTCompressedStreamTools; import net.minecraft.server.v1_10_R1.NBTCompressedStreamTools;
import net.minecraft.server.v1_10_R1.NBTTagCompound; import net.minecraft.server.v1_10_R1.NBTTagCompound;
public class Serializer { public class inventory {
//SERIALIZE ITEMSTACK
public static String serializeItemStack(ItemStack itemStack){ public static String serializeItemStack(ItemStack itemStack){
NBTTagCompound tag = itemStack.save(new NBTTagCompound());
if (itemStack == null) return "null";
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try { NBTCompressedStreamTools.a(itemStack.getTag(), outputStream); } try { NBTCompressedStreamTools.a(tag, outputStream); }
catch (IOException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
return Base64.encodeBase64String(outputStream.toByteArray()); return Base64.encodeBase64String(outputStream.toByteArray());
} }
//DESERIALIZE ITEMSTACK
public static ItemStack deserializeItemStack(String itemStackString){ public static ItemStack deserializeItemStack(String itemStackString){
if (itemStackString.equals("null")) return null;
ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64.decodeBase64(itemStackString));
NBTTagCompound nbtTagCompound = null; NBTTagCompound nbtTagCompound = null;
ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64.decodeBase64(itemStackString));
try {nbtTagCompound = NBTCompressedStreamTools.a(inputStream);} try {nbtTagCompound = NBTCompressedStreamTools.a(inputStream);}
catch (IOException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}
@ -47,8 +42,8 @@ public class Serializer {
} }
//SERIALIZE INVENTORY
public static String serializeInventory (IInventory invInventory){ public static String serialize (IInventory invInventory){
return IntStream.range(0, invInventory.getSize()) return IntStream.range(0, invInventory.getSize())
.mapToObj(s -> { .mapToObj(s -> {
ItemStack i = invInventory.getItem(s); ItemStack i = invInventory.getItem(s);
@ -59,12 +54,12 @@ public class Serializer {
} }
//SET INVENTORY FROM SERIALIZED
public static void setInventoryFromSerialized (IInventory invInventory, String invString){ public static void setFromSerialized (IInventory invInventory, String invString){
invInventory.l(); invInventory.l();//clear inventory
if (invString != null) if (invString != null && !invString.isEmpty())
Arrays.asList(invString.split(";")) Arrays.asList(invString.split(";"))
.stream() .parallelStream()
.forEach(s -> { .forEach(s -> {
String[] e = s.split("#"); String[] e = s.split("#");
invInventory.setItem(Integer.parseInt(e[0]), deserializeItemStack(e[1])); invInventory.setItem(Integer.parseInt(e[0]), deserializeItemStack(e[1]));

View file

@ -0,0 +1,32 @@
package serializers;
import org.bukkit.Location;
import org.bukkit.World;
public class location {
//SERIALIZE LOCATION
public static String serialize(Location location){
return
location.getBlockX() + ","
+ location.getBlockZ() + ","
+ location.getBlockY() + ","
+ location.getPitch() + ","
+ location.getYaw();
}
//DESERIALIZE LOCATION
public static Location deserialize(World world, String locationString){
String[] s = locationString.split(",");
return new Location(
world,
Double.valueOf(s[0]),
Double.valueOf(s[1]),
Double.valueOf(s[2]),
Float.valueOf(s[3]),
Float.valueOf(s[4])
);
}
}

View file

@ -0,0 +1,39 @@
package serializers;
import java.util.Arrays;
import org.bukkit.entity.Player;
public class playerdata {
//SERIALIZE PLAYERDATA
public static String serialize(Player player){
StringBuilder result = new StringBuilder();
result.append("exp:" + player.getExp() + ",");
result.append("health:" + player.getHealth() + ",");
result.append("food:" + player.getFoodLevel() + ",");
result.append("saturation:" + player.getSaturation() + ",");
result.append("exhaustion:" + player.getExhaustion() + ",");
result.append("air:" + player.getRemainingAir() + ",");
result.append("walkspeed:" + player.getWalkSpeed() + ",");
result.append("fireticks:" + player.getFireTicks() + ",");
return result.toString();
}
//SET PLAYERDATA FROM SERIALIZED
public static void setFromSerialized(String dataString, Player player){
Double.valueOf(null);
Arrays.asList(dataString.split(","))
.parallelStream()
.forEach(s -> {
String[] e = s.split(":");
switch(e[0]){
case "health" :
player.setHealth(Double.valueOf(e[1]));
}
});
}
}