From 749f0066218c785edb208881b2d746e49e97c986 Mon Sep 17 00:00:00 2001 From: "Kristian S. Stangeland" Date: Tue, 8 Jan 2013 03:33:24 +0100 Subject: [PATCH] Add the ability to serialize ItemStacks to strings. --- .../protocol/utility/StreamSerializer.java | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/ProtocolLib/src/main/java/com/comphenix/protocol/utility/StreamSerializer.java b/ProtocolLib/src/main/java/com/comphenix/protocol/utility/StreamSerializer.java index 2edbb3cf..5203a22d 100644 --- a/ProtocolLib/src/main/java/com/comphenix/protocol/utility/StreamSerializer.java +++ b/ProtocolLib/src/main/java/com/comphenix/protocol/utility/StreamSerializer.java @@ -1,9 +1,12 @@ package com.comphenix.protocol.utility; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Method; +import java.math.BigInteger; import org.bukkit.inventory.ItemStack; @@ -46,6 +49,24 @@ public class StreamSerializer { } } + /** + * Deserialize an item stack from a base-32 encoded string. + * @param input - base-32 encoded string. + * @return A deserialized item stack. + * @throws IOException If the operation failed due to reflection or corrupt data. + */ + public ItemStack deserializeItemStack(String input) throws IOException { + try { + BigInteger base32 = new BigInteger(input, 32); + ByteArrayInputStream inputStream = new ByteArrayInputStream(base32.toByteArray()); + + return deserializeItemStack(new DataInputStream(inputStream)); + + } catch (NumberFormatException e) { + throw new IOException("Input is not valid base 32.", e); + } + } + /** * Write or serialize an item stack to the given output stream. *

@@ -70,4 +91,20 @@ public class StreamSerializer { throw new IOException("Cannot write item stack " + stack, e); } } + + /** + * Serialize an item stack as a base-32 encoded string. + * @param stack - the item stack to serialize. + * @return A base-32 representation of the given item stack. + * @throws IOException If the operation fails due to reflection problems. + */ + public String serializeItemStack(ItemStack stack) throws IOException { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + DataOutputStream dataOutput = new DataOutputStream(outputStream); + + serializeItemStack(dataOutput, stack); + + // Serialize that array + return new BigInteger(1, outputStream.toByteArray()).toString(32); + } }