diff --git a/.gitignore b/.gitignore index 8baaf9fc42..f55b43e3fb 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,8 @@ +*/bin/* +*.*~ +.classpath +.settings +.project /.gradle/ /.nb-gradle/private/ /.nb-gradle/profiles/private/ diff --git a/jme3-core/src/main/resources/com/jme3/system/version.properties b/jme3-core/src/main/resources/com/jme3/system/version.properties index 98168a14e1..68fd913612 100644 --- a/jme3-core/src/main/resources/com/jme3/system/version.properties +++ b/jme3-core/src/main/resources/com/jme3/system/version.properties @@ -1,11 +1,12 @@ # THIS IS AN AUTO-GENERATED FILE.. # DO NOT MODIFY! -build.date=1900-01-01 -git.revision=0 -git.branch=unknown -git.hash= -git.hash.short= -git.tag= -name.full=jMonkeyEngine 3.1.0-UNKNOWN +build.date=2016-03-30 +git.revision=5488 +git.branch=addDefaultServerTests +git.hash=d489ecc91ff05cc4b9b4bbb0c5540fc02ecd0832 +git.hash.short=d489ecc +git.tag=null +name.full=jMonkeyEngine 3.1-addDefaultServerTests-5488 +version.full=3.1-addDefaultServerTests-5488 version.number=3.1.0 version.tag=SNAPSHOT \ No newline at end of file diff --git a/jme3-examples/src/main/java/jme3test/network/TestChatClient.java b/jme3-examples/src/main/java/jme3test/network/TestChatClient.java index 2e8ecbfafc..ba788e067e 100644 --- a/jme3-examples/src/main/java/jme3test/network/TestChatClient.java +++ b/jme3-examples/src/main/java/jme3test/network/TestChatClient.java @@ -31,10 +31,11 @@ */ package jme3test.network; +import com.jme3.network.AbstractMessage; import com.jme3.network.Client; import com.jme3.network.ClientStateListener; import com.jme3.network.ErrorListener; -import com.jme3.network.Message; +//import com.jme3.network.Message; import com.jme3.network.MessageListener; import com.jme3.network.Network; import java.awt.Component; @@ -45,6 +46,7 @@ import java.util.logging.Logger; import javax.swing.*; import jme3test.network.TestChatServer.ChatMessage; +import jme3test.network.TestChatServer.CommandMessage; /** * A simple test chat server. When SM implements a set @@ -159,7 +161,7 @@ public void run() { private class ChatHandler implements MessageListener { @Override - public void messageReceived(Client source, Message m) { + public void messageReceived(Client source, AbstractMessage m) { ChatMessage chat = (ChatMessage) m; System.out.println("Received:" + chat); @@ -227,10 +229,18 @@ public void actionPerformed(ActionEvent evt) { String name = nameField.getText(); String message = messageField.getText(); - ChatMessage chat = new ChatMessage(name, message); - chat.setReliable(reliable); - System.out.println("Sending:" + chat); - client.send(chat); + if(message.startsWith("/")) { + CommandMessage command = new CommandMessage(name, message); + command.setReliable(reliable); + System.out.println("Sending:" + command); + client.send(command); + } + else { + ChatMessage chat = new ChatMessage(name, message); + chat.setReliable(reliable); + System.out.println("Sending:" + chat); + client.send(chat); + } } } } diff --git a/jme3-examples/src/main/java/jme3test/network/TestChatServer.java b/jme3-examples/src/main/java/jme3test/network/TestChatServer.java index 8bdb740b99..1a5a97fbdf 100644 --- a/jme3-examples/src/main/java/jme3test/network/TestChatServer.java +++ b/jme3-examples/src/main/java/jme3test/network/TestChatServer.java @@ -35,7 +35,6 @@ import java.util.logging.Logger; import com.jme3.network.*; -import com.jme3.network.serializing.Serializable; import com.jme3.network.serializing.Serializer; import java.io.IOException; @@ -70,6 +69,7 @@ public TestChatServer() throws IOException { ChatHandler handler = new ChatHandler(); server.addMessageListener(handler, ChatMessage.class); + server.addMessageListener(new CommandHandler(), CommandMessage.class); server.addConnectionListener(new ChatConnectionListener()); } @@ -124,7 +124,8 @@ protected void runCommand( HostedConnection conn, String user, String command ) public static void initializeClasses() { // Doing it here means that the client code only needs to // call our initialize. - Serializer.registerClass(ChatMessage.class); +// Serializer.registerClass(ChatMessage.class); +// Serializer.registerClass(CommandMessage.class); } public static void main(String... args) throws Exception { @@ -160,7 +161,7 @@ public ChatHandler() { } @Override - public void messageReceived(HostedConnection source, Message m) { + public void messageReceived(HostedConnection source, AbstractMessage m) { if (m instanceof ChatMessage) { // Keep track of the name just in case we // want to know it for some other reason later and it's @@ -168,12 +169,6 @@ public void messageReceived(HostedConnection source, Message m) { ChatMessage cm = (ChatMessage)m; source.setAttribute("name", cm.getName()); - // Check for a / command - if( cm.message.startsWith("/") ) { - runCommand(source, cm.name, cm.message); - return; - } - System.out.println("Broadcasting:" + m + " reliable:" + m.isReliable()); // Just rebroadcast... the reliable flag will stay the @@ -184,6 +179,27 @@ public void messageReceived(HostedConnection source, Message m) { } } } + + private class CommandHandler implements MessageListener { + + public CommandHandler() { + } + + @Override + public void messageReceived(HostedConnection source, AbstractMessage m) { + if (m instanceof CommandMessage) { + // Keep track of the name just in case we + // want to know it for some other reason later and it's + // a good example of session data + CommandMessage cm = (CommandMessage)m; + source.setAttribute("name", cm.getName()); + + runCommand(source, cm.name, cm.command); + } else { + System.err.println("Received odd message:" + m); + } + } + } private class ChatConnectionListener implements ConnectionListener { @@ -199,7 +215,6 @@ public void connectionRemoved(Server server, HostedConnection conn) { } - @Serializable public static class ChatMessage extends AbstractMessage { private String name; @@ -234,4 +249,39 @@ public String toString() { return name + ":" + message; } } + + public static class CommandMessage extends AbstractMessage { + + private String name; + private String command; + + public CommandMessage() { + } + + public CommandMessage(String name, String message) { + setName(name); + setMessage(message); + } + + public void setName(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setMessage(String s) { + this.command = s; + } + + public String getMessage() { + return command; + } + + @Override + public String toString() { + return name + ":" + command; + } + } } diff --git a/jme3-examples/src/main/java/jme3test/network/TestLatency.java b/jme3-examples/src/main/java/jme3test/network/TestLatency.java index 6f49a003b9..07ee6e8ee1 100644 --- a/jme3-examples/src/main/java/jme3test/network/TestLatency.java +++ b/jme3-examples/src/main/java/jme3test/network/TestLatency.java @@ -33,7 +33,6 @@ package jme3test.network; import com.jme3.network.*; -import com.jme3.network.serializing.Serializable; import com.jme3.network.serializing.Serializer; import java.io.IOException; @@ -51,7 +50,6 @@ private static long getTime(){ return System.currentTimeMillis() - startTime; } - @Serializable public static class TimestampMessage extends AbstractMessage { long timeSent = 0; @@ -70,7 +68,7 @@ public TimestampMessage(long timeSent, long timeReceived){ } public static void main(String[] args) throws IOException, InterruptedException{ - Serializer.registerClass(TimestampMessage.class); +// Serializer.registerClass(TimestampMessage.class); Server server = Network.createServer(5110); server.start(); @@ -79,7 +77,7 @@ public static void main(String[] args) throws IOException, InterruptedException{ client.start(); client.addMessageListener(new MessageListener(){ - public void messageReceived(Client source, Message m) { + public void messageReceived(Client source, AbstractMessage m) { TimestampMessage timeMsg = (TimestampMessage) m; long curTime = getTime(); @@ -103,7 +101,7 @@ public void messageReceived(Client source, Message m) { }, TimestampMessage.class); server.addMessageListener(new MessageListener(){ - public void messageReceived(HostedConnection source, Message m) { + public void messageReceived(HostedConnection source, AbstractMessage m) { TimestampMessage timeMsg = (TimestampMessage) m; TimestampMessage outMsg = new TimestampMessage(timeMsg.timeSent, getTime()); source.send(outMsg); diff --git a/jme3-examples/src/main/java/jme3test/network/TestMessages.java b/jme3-examples/src/main/java/jme3test/network/TestMessages.java index 361f097ecd..f1be82bfd1 100644 --- a/jme3-examples/src/main/java/jme3test/network/TestMessages.java +++ b/jme3-examples/src/main/java/jme3test/network/TestMessages.java @@ -33,22 +33,19 @@ package jme3test.network; import com.jme3.network.*; -import com.jme3.network.serializing.Serializable; import com.jme3.network.serializing.Serializer; import java.io.IOException; public class TestMessages { - @Serializable public static class PingMessage extends AbstractMessage { } - @Serializable public static class PongMessage extends AbstractMessage { } private static class ServerPingResponder implements MessageListener { - public void messageReceived(HostedConnection source, com.jme3.network.Message message) { + public void messageReceived(HostedConnection source, AbstractMessage message) { if (message instanceof PingMessage){ System.out.println("Server: Received ping message!"); source.send(new PongMessage()); @@ -57,7 +54,7 @@ public void messageReceived(HostedConnection source, com.jme3.network.Message me } private static class ClientPingResponder implements MessageListener { - public void messageReceived(Client source, com.jme3.network.Message message) { + public void messageReceived(Client source, AbstractMessage message) { if (message instanceof PongMessage){ System.out.println("Client: Received pong message!"); } @@ -65,8 +62,8 @@ public void messageReceived(Client source, com.jme3.network.Message message) { } public static void main(String[] args) throws IOException, InterruptedException{ - Serializer.registerClass(PingMessage.class); - Serializer.registerClass(PongMessage.class); +// Serializer.registerClass(PingMessage.class); +// Serializer.registerClass(PongMessage.class); Server server = Network.createServer(5110); server.start(); diff --git a/jme3-examples/src/main/java/jme3test/network/TestRemoteCall.java b/jme3-examples/src/main/java/jme3test/network/TestRemoteCall.java index 4335bb3253..087b4cc6a8 100644 --- a/jme3-examples/src/main/java/jme3test/network/TestRemoteCall.java +++ b/jme3-examples/src/main/java/jme3test/network/TestRemoteCall.java @@ -39,7 +39,7 @@ import com.jme3.network.Server; import com.jme3.network.rmi.ObjectStore; import com.jme3.network.serializing.Serializer; -import com.jme3.network.serializing.serializers.SavableSerializer; +//import com.jme3.network.serializing.serializers.SavableSerializer; import com.jme3.scene.Spatial; import java.io.IOException; import java.util.concurrent.Callable; @@ -102,7 +102,7 @@ public void simpleInitApp() { } public static void main(String[] args) throws IOException, InterruptedException{ - Serializer.registerClass(Savable.class, new SavableSerializer()); +// Serializer.registerClass(Savable.class, new SavableSerializer()); createServer(); diff --git a/jme3-examples/src/main/java/jme3test/network/TestSerialization.java b/jme3-examples/src/main/java/jme3test/network/TestSerialization.java index cbdeb6697c..4a64f4d32b 100644 --- a/jme3-examples/src/main/java/jme3test/network/TestSerialization.java +++ b/jme3-examples/src/main/java/jme3test/network/TestSerialization.java @@ -33,14 +33,12 @@ package jme3test.network; import com.jme3.network.*; -import com.jme3.network.serializing.Serializable; import com.jme3.network.serializing.Serializer; import java.io.IOException; import java.util.*; public class TestSerialization implements MessageListener { - @Serializable public static class SomeObject { private int val; @@ -68,7 +66,6 @@ public enum Status { Low; } - @Serializable public static class TestSerializationMessage extends AbstractMessage { boolean z; @@ -121,7 +118,7 @@ public TestSerializationMessage(boolean initIt){ } } - public void messageReceived(HostedConnection source, Message m) { + public void messageReceived(HostedConnection source, AbstractMessage m) { TestSerializationMessage cm = (TestSerializationMessage) m; System.out.println(cm.z); System.out.println(cm.b); @@ -140,8 +137,8 @@ public void messageReceived(HostedConnection source, Message m) { } public static void main(String[] args) throws IOException, InterruptedException{ - Serializer.registerClass(SomeObject.class); - Serializer.registerClass(TestSerializationMessage.class); +// Serializer.registerClass(SomeObject.class); +// Serializer.registerClass(TestSerializationMessage.class); Server server = Network.createServer( 5110 ); server.start(); diff --git a/jme3-examples/src/main/java/jme3test/network/TestThroughput.java b/jme3-examples/src/main/java/jme3test/network/TestThroughput.java index c261ec0b9e..37d02df98b 100644 --- a/jme3-examples/src/main/java/jme3test/network/TestThroughput.java +++ b/jme3-examples/src/main/java/jme3test/network/TestThroughput.java @@ -31,88 +31,418 @@ */ package jme3test.network; +import com.jme3.math.Matrix3f; +import com.jme3.math.Vector3f; import com.jme3.network.*; -import com.jme3.network.serializing.Serializable; +import com.jme3.network.kernel.KernelException; import com.jme3.network.serializing.Serializer; + +import java.awt.Label; import java.io.IOException; +import java.io.Serializable; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.Random; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; -public class TestThroughput implements MessageListener { //extends MessageAdapter { +@SuppressWarnings("serial") +public class TestThroughput implements Serializable { - private static long lastTime = -1; - private static long counter = 0; - private static long total = 0; + private static AtomicInteger counter = new AtomicInteger(0); + private static AtomicInteger serverCounter = new AtomicInteger(0); // Change this flag to test UDP instead of TCP private static boolean testReliable = false; - private boolean isOnServer; - - public TestThroughput(boolean isOnServer) { - this.isOnServer = isOnServer; - } + private static int n; // Number of different test messages + private static int ms; // Number of milliseconds to run + private static Random rand = new Random(); - @Serializable - public static class TestMessage extends AbstractMessage { - - public TestMessage() { - setReliable(testReliable); + private static Server server; + private static Client client; + + private static Class[] messageClasses = new Class[] { + EmptyTestMessage.class, + SimpleTestMessage.class, + PhysicsTestMessage.class, + HugeTestMessage.class + }; + private static Class[] dataClasses = new Class[] { + Vector3f.class, + Matrix3f.class, + HugeTestMessage.HugeTestSubMessage.class, + ArrayList.class, + HashMap.class, + Date.class + }; + + public static class TestThroughputListener implements MessageListener { + private boolean isOnServer; + + public TestThroughputListener(boolean isOnServer) { + this.isOnServer = isOnServer; } - } - - @Override - public void messageReceived(MessageConnection source, Message msg) { - - if (!isOnServer) { - // It's local to the client so we got it back - counter++; - total++; - long time = System.currentTimeMillis(); -//System.out.println( "total:" + total + " counter:" + counter + " lastTime:" + lastTime + " time:" + time ); - if (lastTime < 0) { - lastTime = time; - } else if (time - lastTime > 1000) { - long delta = time - lastTime; - double scale = delta / 1000.0; - double pps = counter / scale; - System.out.println("messages per second:" + pps + " total messages:" + total); - counter = 0; - lastTime = time; - } - } else { - if (source == null) { - System.out.println("Received a message from a not fully connected source, msg:" + msg); + + @Override + public void messageReceived(MessageConnection source, AbstractMessage msg) { + if (!isOnServer) { + counter.incrementAndGet(); } else { -//System.out.println( "sending:" + msg + " back to client:" + source ); - // The 'reliable' flag is transient and the server doesn't - // (yet) reset this value for us. - ((com.jme3.network.Message) msg).setReliable(testReliable); - source.send(msg); + if (source == null) { + System.out.println("Received a message from a not fully connected source, msg:" + msg); + } else { + try { + msg.setReliable(testReliable); + source.send(msg); + serverCounter.incrementAndGet(); + } catch (KernelException e) { + // This happens when there are still messages in the pipeline from a closed client + // Just discard the message + } + } } } } + public static void main(String[] args) throws IOException, InterruptedException { - - Serializer.registerClass(TestMessage.class); - - // Use this to test the client/server name version check - //Server server = Network.createServer( "bad name", 42, 5110, 5110 ); - Server server = Network.createServer(5110, 5110); + for(int i = 0; i < messageClasses.length; i++) { + Serializer.registerClass(messageClasses[i]); + } + for(int i = 0; i < dataClasses.length; i++) { + Serializer.registerClass(dataClasses[i]); + } + + server = Network.createServer(5110, 5110); server.start(); - Client client = Network.connectToServer("localhost", 5110); + client = Network.connectToServer("localhost", 5110); client.start(); - client.addMessageListener(new TestThroughput(false), TestMessage.class); - server.addMessageListener(new TestThroughput(true), TestMessage.class); + client.addMessageListener(new TestThroughputListener(false), messageClasses); + server.addMessageListener(new TestThroughputListener(true), messageClasses); + + Thread.sleep(100); + n = 1000; + ms = 10 * 1000; + + System.out.println("Running tests for " + messageClasses.length + " types of messages with " + (ms/1000) + " seconds"); + System.out.println(); + + // Because the tests keep influencing other tests, just run one at a time.. + testEmpty(); +// testSimple(); +// testPhysics(); +// testHuge(); + + System.exit(0); + } + + private static void runThroughputTest(AbstractMessage... messages) { + counter.set(0); + serverCounter.set(0); + + long start = System.currentTimeMillis(); + int i = 0; + while((System.currentTimeMillis() - start) < ms) { + client.send(messages[i % messages.length]); + i++; + } + + System.out.println("Sent " + i + " messages in " + (ms/1000) + " seconds."); + System.out.println("Of these, " + serverCounter.get() + " were recieved by the server and " + + counter.get() + " by the client."); + try{ + Thread.sleep(1000); + System.out.println("A second later, " + serverCounter.get() + " were recieved by the server and " + + counter.get() + " by the client."); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + private static void runSerializationTest(AbstractMessage message) { + ByteBuffer buffer = ByteBuffer.allocate(32767 + 2); + try { + Serializer.writeObject(buffer, message); + } catch (IOException e) { + System.err.println("Serialization failed!"); + e.printStackTrace(); + } + System.out.println("Serialization size is " + buffer.position()); + } + + private static void testEmpty() { + System.out.println("Running EmptyTestMessage tests"); + + EmptyTestMessage message = new EmptyTestMessage(); + + runSerializationTest(message); + runThroughputTest(message); + + System.out.println(); + } - Thread.sleep(1); + private static void testSimple() { + System.out.println("Running SimpleTestMessage tests"); + + SimpleTestMessage[] messages = new SimpleTestMessage[n]; + for(int i = 0; i < n; i++) { + messages[i] = new SimpleTestMessage(UUID.randomUUID().toString()); + } + + runSerializationTest(messages[0]); + runThroughputTest(messages); + + System.out.println(); + } - TestMessage test = new TestMessage(); -// for( int i = 0; i < 10; i++ ) { - while (true) { -//System.out.println( "sending." ); - client.send(test); + private static void testPhysics() { + System.out.println("Running PhysicsTestMessage tests"); + + PhysicsTestMessage[] messages = new PhysicsTestMessage[n]; + for(int i = 0; i < n; i++) { + messages[i] = PhysicsTestMessage.constructRandom(); + } + + runSerializationTest(PhysicsTestMessage.constructExample()); + runThroughputTest(messages); + + System.out.println(); + } + + private static void testHuge() { + System.out.println("Running HugeTestMessage tests"); + + HugeTestMessage[] messages = new HugeTestMessage[n]; + + for(int i = 0; i < n; i++) { + messages[i] = HugeTestMessage.constructRandom(); + } + + runSerializationTest(HugeTestMessage.constructExample()); + runThroughputTest(messages); + + System.out.println(); + } + + + private static Vector3f randomVector(float scale) { + return new Vector3f(rand.nextFloat() * scale, + rand.nextFloat() * scale, + rand.nextFloat() * scale); + } + + private static Matrix3f randomMatrix(float scale) { + return new Matrix3f(rand.nextFloat() * scale, rand.nextFloat() * scale, rand.nextFloat() * scale, + rand.nextFloat() * scale, rand.nextFloat() * scale, rand.nextFloat() * scale, + rand.nextFloat() * scale, rand.nextFloat() * scale, rand.nextFloat() * scale); + } + + public static class EmptyTestMessage extends AbstractMessage implements Serializable { + public EmptyTestMessage() { + setReliable(testReliable); + } + + public static EmptyTestMessage constructRandom() { + return new EmptyTestMessage(); + } + + public static EmptyTestMessage constructExample() { + return new EmptyTestMessage(); } + } + + public static class SimpleTestMessage extends AbstractMessage implements Serializable { + public String message; - //Thread.sleep(5000); + public SimpleTestMessage() { + // Required by Kryo. Could use constructRandom. + } + + public SimpleTestMessage(String message) { + setReliable(testReliable); + + this.message = message; + } + + public static SimpleTestMessage constructRandom() { + return new SimpleTestMessage(UUID.randomUUID().toString()); + } + + public static SimpleTestMessage constructExample() { + return new SimpleTestMessage("c0dc2435-dc88-496d-9b4a-ef2ef1e537c9"); + } + } + + public static class PhysicsTestMessage extends AbstractMessage implements Serializable { + public Vector3f vec1; + public Vector3f vec2; + public Vector3f vec3; + public Vector3f vec4; + public Vector3f vec5; + public Matrix3f mat1; + public Matrix3f mat2; + + public PhysicsTestMessage() { + // Required by Kryo. Could use constructRandom. + } + + public PhysicsTestMessage( + Vector3f vec1, Vector3f vec2, Vector3f vec3, Vector3f vec4, Vector3f vec5, + Matrix3f mat1, Matrix3f mat2) { + setReliable(testReliable); + + this.vec1 = vec1; + this.vec2 = vec2; + this.vec3 = vec3; + this.vec4 = vec4; + this.vec5 = vec5; + this.mat1 = mat1; + this.mat2 = mat2; + } + + public static PhysicsTestMessage constructRandom() { + Vector3f vec1 = randomVector(1); + Vector3f vec2 = randomVector(0.01f); + Vector3f vec3 = randomVector(5); + Vector3f vec4 = randomVector(1000); + Vector3f vec5 = randomVector((int) Float.MAX_VALUE); + Matrix3f mat1 = randomMatrix(1); + Matrix3f mat2 = randomMatrix((int) Float.MAX_VALUE); + return new PhysicsTestMessage(vec1, vec2, vec3, vec4, vec5, mat1, mat2); + } + + public static PhysicsTestMessage constructExample() { + Vector3f vec1 = new Vector3f(0.433166980743408203125f,0.82575452327728271484375f,0.955823123455047607421875f); + Vector3f vec2 = new Vector3f(0.009725025855004787445068359375f,0.0054381941445171833038330078125f,0.00021268546697683632373809814453125f); + Vector3f vec3 = new Vector3f(2.938496112823486328125f,4.7902927398681640625f,1.794808864593505859375f); + Vector3f vec4 = new Vector3f(328.64569091796875f,990.1982421875f,775.70758056640625f); + Vector3f vec5 = new Vector3f(1186151296f,850664832f,1532781312f); + Matrix3f mat1 = new Matrix3f(0.9948008060455322265625f,0.499847590923309326171875f,0.045433461666107177734375f, + 0.288867175579071044921875f,0.8376448154449462890625f,0.264260709285736083984375f, + 0.730224311351776123046875f,0.4005107879638671875f,0.97741806507110595703125f); + Matrix3f mat2 = new Matrix3f(1221519616f,1262525056f,1983939200f, + 556515072f,1268844544f,1640567936f, + 20781696f,1712417920f,1353835648f); + return new PhysicsTestMessage(vec1, vec2, vec3, vec4, vec5, mat1, mat2); + } + } + + public static class HugeTestMessage extends AbstractMessage implements Serializable { + + public static class HugeTestSubMessage extends PhysicsTestMessage implements Serializable { + public Vector3f vec6; + public Matrix3f mat3; + + public HugeTestSubMessage(Vector3f vec1, Vector3f vec2, Vector3f vec3, + Vector3f vec4, Vector3f vec5, Vector3f vec6, + Matrix3f mat1, Matrix3f mat2, Matrix3f mat3) { + super(vec1, vec2, vec3, vec4, vec5, mat1, mat2); + this.vec6 = vec6; + this.mat3 = mat3; + } + + public HugeTestSubMessage() { + // Required by Kryo. Could use constructRandom. + } + + public static HugeTestSubMessage constructRandom() { + return new HugeTestSubMessage( + randomVector(1), randomVector(0.5f), randomVector(24), + randomVector(1000), randomVector(0.0001f), randomVector(Float.MAX_VALUE), + randomMatrix(1), randomMatrix(0.2f), randomMatrix(1000)); + } + + public static HugeTestSubMessage constructExample() { + Vector3f vec1 = new Vector3f(0.734558284282684326171875f,0.1037347316741943359375f,0.9635913372039794921875f); + Vector3f vec2 = new Vector3f(0.2863779366016387939453125f,0.1739477217197418212890625f,0.121182739734649658203125f); + Vector3f vec3 = new Vector3f(23.9283580780029296875f,1.685794830322265625f,4.0823535919189453125f); + Vector3f vec4 = new Vector3f(571.7216796875f,493.94287109375f,21.1187591552734375f); + Vector3f vec5 = new Vector3f(0.00004635152072296477854251861572265625f,0.0000645517720840871334075927734375f,0.0000068765875766985118389129638671875f); + Vector3f vec6 = new Vector3f(7894541938613643216668711816955691008f,133026838198553518533820343453506076672f,250347972238109762423186708926434377728f); + Matrix3f mat1 = new Matrix3f(0.5152451992034912109375f,0.554454267024993896484375f,0.301480352878570556640625f, + 0.585283696651458740234375f,0.126667499542236328125f,0.00066840648651123046875f, + 0.629179894924163818359375f,0.099936783313751220703125f,0.1898162364959716796875f); + Matrix3f mat2 = new Matrix3f(0.13529066741466522216796875f,0.06602752208709716796875f,0.17806760966777801513671875f, + 0.0544088147580623626708984375f,0.12109376490116119384765625f,0.19446246325969696044921875f, + 0.108363606035709381103515625f,0.16804240643978118896484375f,0.13968805968761444091796875f); + Matrix3f mat3 = new Matrix3f(122.839752197265625f,210.7856903076171875f,347.761627197265625f, + 175.275390625f,127.128662109375f,401.360382080078125f, + 428.85064697265625f,857.57647705078125f,433.4407958984375f); + return new HugeTestSubMessage(vec1, vec2, vec3, vec4, vec5, vec6, mat1, mat2, mat3); + } + } + + public HugeTestSubMessage submsg; + public ArrayList> list; + public Date date; + + public HugeTestMessage() { + // Required by Kryo. Could use constructRandom. + } + + public HugeTestMessage(HugeTestSubMessage submsg, ArrayList> list, Date date) { + setReliable(testReliable); + + this.submsg = submsg; + this.list = list; + this.date = date; + } + + public static HugeTestMessage constructRandom() { + HugeTestSubMessage submsg = HugeTestSubMessage.constructRandom(); + + ArrayList> list = new ArrayList>(); + while(rand.nextFloat() < 0.9f) { + HashMap map = new HashMap(); + while(rand.nextFloat() < 0.7f) { + int ints = rand.nextInt(10); + Integer[] arr = new Integer[ints]; + for(int i = 0; i < ints; i++) { + arr[i] = rand.nextInt(); + } + map.put(UUID.randomUUID().toString(), arr); + } + list.add(map); + } + + Date date = new Date(); + + return new HugeTestMessage(submsg, list, date); + } + + public static HugeTestMessage constructExample() { + HugeTestSubMessage submsg = HugeTestSubMessage.constructExample(); + + ArrayList> list = new ArrayList>(); + HashMap map1 = new HashMap(); + map1.put("b1a6403e-1b60-48dc-849c-12eb8ad27d06", new Integer[] {1859738404, 1694268120, -1129680451, -1224667903, -661151019, -2096401476, -1501844014, 1839364723}); + map1.put("6303d3a8-7506-4a4e-8f13-9e4cd6c7fbcb", new Integer[] {-1856653715, 476417908, -716406513, 1513345772, 1471991271}); + map1.put("90ab696b-1448-4cd0-a8a0-0558f58e8097", new Integer[] {-735676597, -1073278648, -1076764924}); + map1.put("55d2d19f-f1cd-4d82-b1f2-0f5f262c2719", new Integer[] {706411505, 73831233, -356557658, -1101021211}); + list.add(map1); + + HashMap map2 = new HashMap(); + map2.put("fbe8aca5-425b-4c1b-81fe-e2b45a883751", new Integer[] {-1986031668, -216366978, 2143748480}); + map2.put("37b45cd6-aa30-4144-ab24-a2296324f0d7", new Integer[] {1840420678, -148582777}); + map2.put("ef12c9ac-bf53-4054-977e-45a22997210d", new Integer[] {313946288, -2100994421}); + list.add(map2); + + HashMap map3 = new HashMap(); + map3.put("9f9f7b7a-40bd-4fbc-96a5-0555a320d2da", new Integer[]{}); + map3.put("234b3e08-8d6d-4861-b86c-b05769be3fcc", new Integer[] {162012643}); + list.add(map3); + + HashMap map4 = new HashMap(); + map4.put("a27b0043-5358-4a60-9e37-1ad743687cac", new Integer[] {-1108614336, 1077521187, -1551597258, -167932021, -668704169, -1738237249, 1133662364, 1717389473}); + list.add(map4); + + Date date = new Date(1459681195625l); + + return new HugeTestMessage(submsg, list, date); + } } } diff --git a/jme3-networking/build.gradle b/jme3-networking/build.gradle index 0a77d7d720..844cd3d207 100644 --- a/jme3-networking/build.gradle +++ b/jme3-networking/build.gradle @@ -4,4 +4,8 @@ if (!hasProperty('mainClass')) { dependencies { compile project(':jme3-core') + compile 'org.mockito:mockito-all:1.10.19' + compile 'junit:junit:4.12' + compile 'com.esotericsoftware:kryo:3.0.3' + compile 'de.ruedigermoeller:fst:2.45' } diff --git a/jme3-networking/src/main/java/com/jme3/network/AbstractMessage.java b/jme3-networking/src/main/java/com/jme3/network/AbstractMessage.java index 5a13a68239..8fc50593d7 100644 --- a/jme3-networking/src/main/java/com/jme3/network/AbstractMessage.java +++ b/jme3-networking/src/main/java/com/jme3/network/AbstractMessage.java @@ -31,16 +31,14 @@ */ package com.jme3.network; -import com.jme3.network.serializing.Serializable; - /** * Interface implemented by all network messages. * * @version $Revision$ * @author Paul Speed */ -@Serializable() -public abstract class AbstractMessage implements Message + +public abstract class AbstractMessage implements java.io.Serializable { private transient boolean reliable = true; @@ -57,7 +55,7 @@ protected AbstractMessage( boolean reliable ) * Sets this message to 'reliable' or not and returns this * message. */ - public Message setReliable(boolean f) + public AbstractMessage setReliable(boolean f) { this.reliable = f; return this; diff --git a/jme3-networking/src/main/java/com/jme3/network/Client.java b/jme3-networking/src/main/java/com/jme3/network/Client.java index 3ef9134dfe..c88ffacb3c 100644 --- a/jme3-networking/src/main/java/com/jme3/network/Client.java +++ b/jme3-networking/src/main/java/com/jme3/network/Client.java @@ -90,13 +90,13 @@ public interface Client extends MessageConnection /** * Sends a message to the server. */ - public void send( Message message ); + public void send( AbstractMessage message ); /** * Sends a message to the other end of the connection using * the specified alternate channel. */ - public void send( int channel, Message message ); + public void send( int channel, AbstractMessage message ); /** * Closes this connection to the server. diff --git a/jme3-networking/src/main/java/com/jme3/network/Message.java b/jme3-networking/src/main/java/com/jme3/network/Message.java deleted file mode 100644 index 9586b039e5..0000000000 --- a/jme3-networking/src/main/java/com/jme3/network/Message.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2009-2012 jMonkeyEngine - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of 'jMonkeyEngine' nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package com.jme3.network; - -import com.jme3.network.serializing.Serializable; - -/** - * Interface implemented by all network messages. - * - * @version $Revision$ - * @author Paul Speed - */ -@Serializable() -public interface Message -{ - /** - * Sets this message to 'reliable' or not and returns this - * message. - */ - public Message setReliable(boolean f); - - /** - * Indicates which way an outgoing message should be sent - * or which way an incoming message was sent. - */ - public boolean isReliable(); -} diff --git a/jme3-networking/src/main/java/com/jme3/network/MessageConnection.java b/jme3-networking/src/main/java/com/jme3/network/MessageConnection.java index 0938e1e452..eb7034f289 100644 --- a/jme3-networking/src/main/java/com/jme3/network/MessageConnection.java +++ b/jme3-networking/src/main/java/com/jme3/network/MessageConnection.java @@ -70,12 +70,12 @@ public interface MessageConnection /** * Sends a message to the other end of the connection. */ - public void send( Message message ); + public void send( AbstractMessage message ); /** * Sends a message to the other end of the connection using * the specified alternate channel. */ - public void send( int channel, Message message ); + public void send( int channel, AbstractMessage message ); } diff --git a/jme3-networking/src/main/java/com/jme3/network/MessageListener.java b/jme3-networking/src/main/java/com/jme3/network/MessageListener.java index 68c708b160..353c3727a1 100644 --- a/jme3-networking/src/main/java/com/jme3/network/MessageListener.java +++ b/jme3-networking/src/main/java/com/jme3/network/MessageListener.java @@ -49,5 +49,5 @@ */ public interface MessageListener { - public void messageReceived( S source, Message m ); + public void messageReceived( S source, AbstractMessage m ); } diff --git a/jme3-networking/src/main/java/com/jme3/network/Server.java b/jme3-networking/src/main/java/com/jme3/network/Server.java index a52cb33bfc..d996f2d0f7 100644 --- a/jme3-networking/src/main/java/com/jme3/network/Server.java +++ b/jme3-networking/src/main/java/com/jme3/network/Server.java @@ -65,7 +65,7 @@ public interface Server /** * Sends the specified message to all connected clients. */ - public void broadcast( Message message ); + public void broadcast( AbstractMessage message ); /** * Sends the specified message to all connected clients that match @@ -81,7 +81,7 @@ public interface Server * server.broadcast( Filters.notEqualTo( source ), message ); * */ - public void broadcast( Filter filter, Message message ); + public void broadcast( Filter filter, AbstractMessage message ); /** * Sends the specified message over the specified alternate channel to all connected @@ -97,7 +97,7 @@ public interface Server * server.broadcast( Filters.notEqualTo( source ), message ); * */ - public void broadcast( int channel, Filter filter, Message message ); + public void broadcast( int channel, Filter filter, AbstractMessage message ); /** * Start the server so that it will began accepting new connections diff --git a/jme3-networking/src/main/java/com/jme3/network/base/ConnectorAdapter.java b/jme3-networking/src/main/java/com/jme3/network/base/ConnectorAdapter.java index 6f4935f8fb..b23c2f7fbd 100644 --- a/jme3-networking/src/main/java/com/jme3/network/base/ConnectorAdapter.java +++ b/jme3-networking/src/main/java/com/jme3/network/base/ConnectorAdapter.java @@ -31,8 +31,9 @@ */ package com.jme3.network.base; +import com.jme3.network.AbstractMessage; import com.jme3.network.ErrorListener; -import com.jme3.network.Message; +//import com.jme3.network.Message; import com.jme3.network.MessageListener; import com.jme3.network.kernel.Connector; import com.jme3.network.kernel.ConnectorException; @@ -127,7 +128,7 @@ public void close() } } - protected void dispatch( Message m ) + protected void dispatch( AbstractMessage m ) { dispatcher.messageReceived( null, m ); } @@ -168,7 +169,7 @@ public void run() protocol.addBuffer( buffer ); - Message m = null; + AbstractMessage m = null; while( (m = protocol.getMessage()) != null ) { m.setReliable( reliable ); dispatch( m ); diff --git a/jme3-networking/src/main/java/com/jme3/network/base/DefaultClient.java b/jme3-networking/src/main/java/com/jme3/network/base/DefaultClient.java index 94a951e520..993fb0990c 100644 --- a/jme3-networking/src/main/java/com/jme3/network/base/DefaultClient.java +++ b/jme3-networking/src/main/java/com/jme3/network/base/DefaultClient.java @@ -38,7 +38,7 @@ import com.jme3.network.message.ClientRegistrationMessage; import com.jme3.network.message.DisconnectMessage; import com.jme3.network.service.ClientServiceManager; -import com.jme3.network.service.serializer.ClientSerializerRegistrationsService; +//import com.jme3.network.service.serializer.ClientSerializerRegistrationsService; import java.io.IOException; import java.nio.ByteBuffer; import java.util.*; @@ -101,7 +101,7 @@ public DefaultClient( String gameName, int version, Connector reliable, Connecto protected void addStandardServices() { log.fine("Adding standard services..."); - services.addService(new ClientSerializerRegistrationsService()); +// services.addService(new ClientSerializerRegistrationsService()); } protected void setPrimaryConnectors( Connector reliable, Connector fast, ConnectorFactory connectorFactory ) @@ -229,7 +229,7 @@ public ClientServiceManager getServices() } @Override - public void send( Message message ) + public void send( AbstractMessage message ) { if( log.isLoggable(Level.FINER) ) { log.log(Level.FINER, "send({0})", message); @@ -242,7 +242,7 @@ public void send( Message message ) } @Override - public void send( int channel, Message message ) + public void send( int channel, AbstractMessage message ) { if( log.isLoggable(Level.FINER) ) { log.log(Level.FINER, "send({0}, {1})", new Object[]{channel, message}); @@ -262,7 +262,7 @@ public void send( int channel, Message message ) send(channel + CH_FIRST, message, true); } - protected void send( int channel, Message message, boolean waitForConnected ) + protected void send( int channel, AbstractMessage message, boolean waitForConnected ) { checkRunning(); @@ -387,7 +387,7 @@ protected void fireConnected() { for( ClientStateListener l : stateListeners ) { l.clientConnected( this ); - } + } } protected void startServices() @@ -449,7 +449,7 @@ protected void configureChannels( long tempId, int[] ports ) { } } - protected void dispatch( Message m ) + protected void dispatch( AbstractMessage m ) { if( log.isLoggable(Level.FINER) ) { log.log(Level.FINER, "{0} received:{1}", new Object[]{this, m}); @@ -503,7 +503,7 @@ protected void dispatch( Message m ) protected class Redispatch implements MessageListener, ErrorListener { @Override - public void messageReceived( Object source, Message m ) + public void messageReceived( Object source, AbstractMessage m ) { dispatch( m ); } diff --git a/jme3-networking/src/main/java/com/jme3/network/base/DefaultServer.java b/jme3-networking/src/main/java/com/jme3/network/base/DefaultServer.java index eceaf6d730..a407263058 100644 --- a/jme3-networking/src/main/java/com/jme3/network/base/DefaultServer.java +++ b/jme3-networking/src/main/java/com/jme3/network/base/DefaultServer.java @@ -223,13 +223,13 @@ public void close() } @Override - public void broadcast( Message message ) + public void broadcast( AbstractMessage message ) { broadcast( null, message ); } @Override - public void broadcast( Filter filter, Message message ) + public void broadcast( Filter filter, AbstractMessage message ) { if( log.isLoggable(Level.FINER) ) { log.log(Level.FINER, "broadcast({0}, {1})", new Object[]{filter, message}); @@ -252,7 +252,7 @@ public void broadcast( Filter filter, Message message } @Override - public void broadcast( int channel, Filter filter, Message message ) + public void broadcast( int channel, Filter filter, AbstractMessage message ) { if( log.isLoggable(Level.FINER) ) { log.log(Level.FINER, "broadcast({0}, {1}. {2})", new Object[]{channel, filter, message}); @@ -324,7 +324,7 @@ public void removeMessageListener( MessageListener lis messageListeners.removeMessageListener( listener, classes ); } - protected void dispatch( HostedConnection source, Message m ) + protected void dispatch( HostedConnection source, AbstractMessage m ) { if( log.isLoggable(Level.FINER) ) { log.log(Level.FINER, "{0} received:{1}", new Object[]{source, m}); @@ -574,7 +574,7 @@ public String getAddress() } @Override - public void send( Message message ) + public void send( AbstractMessage message ) { if( log.isLoggable(Level.FINER) ) { log.log(Level.FINER, "send({0})", message); @@ -588,7 +588,7 @@ public void send( Message message ) } @Override - public void send( int channel, Message message ) + public void send( int channel, AbstractMessage message ) { if( log.isLoggable(Level.FINER) ) { log.log(Level.FINER, "send({0}, {1})", new Object[]{channel, message}); @@ -669,7 +669,7 @@ public String toString() protected class Redispatch implements MessageListener { @Override - public void messageReceived( HostedConnection source, Message m ) + public void messageReceived( HostedConnection source, AbstractMessage m ) { dispatch( source, m ); } diff --git a/jme3-networking/src/main/java/com/jme3/network/base/KernelAdapter.java b/jme3-networking/src/main/java/com/jme3/network/base/KernelAdapter.java index 6d6fcef7b4..f12d75df53 100644 --- a/jme3-networking/src/main/java/com/jme3/network/base/KernelAdapter.java +++ b/jme3-networking/src/main/java/com/jme3/network/base/KernelAdapter.java @@ -31,15 +31,18 @@ */ package com.jme3.network.base; +import com.jme3.network.AbstractMessage; import com.jme3.network.Filter; import com.jme3.network.HostedConnection; -import com.jme3.network.Message; +//import com.jme3.network.Message; import com.jme3.network.MessageListener; +import com.jme3.network.Server; import com.jme3.network.kernel.Endpoint; import com.jme3.network.kernel.EndpointEvent; import com.jme3.network.kernel.Envelope; import com.jme3.network.kernel.Kernel; import com.jme3.network.message.ClientRegistrationMessage; + import java.nio.ByteBuffer; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -164,7 +167,7 @@ protected void connectionClosed( Endpoint p ) * per-connection locking but it couldn't possibly guard against * out of order Envelope processing.

*/ - protected void dispatch( Endpoint p, Message m ) + protected void dispatch( Endpoint p, AbstractMessage m ) { // Because this class is the only one with the information // to do it... we need to pull of the registration message @@ -180,7 +183,7 @@ protected void dispatch( Endpoint p, Message m ) if( reliable ) { // If it's a reliable connection then it's slightly more // concerning but this can happen all the time for a UDP endpoint. - log.log( Level.WARNING, "Recieved message from unconnected endpoint:" + p + " message:" + m ); + log.log( Level.WARNING, "Recieved message from unconnected endpoint: {0} message: {1}", new Object[] {p, m} ); } return; } @@ -229,13 +232,13 @@ protected void createAndDispatch( Envelope env ) for( int i = 0; i < len; i++ ) { sb.append( "[" + Integer.toHexString(data[i]) + "]" ); } - log.log( Level.FINE, "First 10 bytes of incomplete nessage:" + sb ); + log.log( Level.FINE, "First 10 bytes of incomplete nessage: {0}", sb ); throw new RuntimeException( "Envelope contained incomplete data:" + env ); } } // Should be complete... and maybe we should check but we don't - Message m = null; + AbstractMessage m = null; while( (m = protocol.getMessage()) != null ) { m.setReliable(reliable); dispatch( env.getSource(), m ); diff --git a/jme3-networking/src/main/java/com/jme3/network/base/MessageListenerRegistry.java b/jme3-networking/src/main/java/com/jme3/network/base/MessageListenerRegistry.java index 4a2e404917..bec0fb1d16 100644 --- a/jme3-networking/src/main/java/com/jme3/network/base/MessageListenerRegistry.java +++ b/jme3-networking/src/main/java/com/jme3/network/base/MessageListenerRegistry.java @@ -31,7 +31,8 @@ */ package com.jme3.network.base; -import com.jme3.network.Message; +import com.jme3.network.AbstractMessage; +//import com.jme3.network.Message; import com.jme3.network.MessageListener; import java.util.Collections; import java.util.List; @@ -61,7 +62,7 @@ public MessageListenerRegistry() } @Override - public void messageReceived( S source, Message m ) + public void messageReceived( S source, AbstractMessage m ) { boolean delivered = false; boolean trace = log.isLoggable(Level.FINER); diff --git a/jme3-networking/src/main/java/com/jme3/network/base/MessageProtocol.java b/jme3-networking/src/main/java/com/jme3/network/base/MessageProtocol.java index a9130f8386..43c79137e0 100644 --- a/jme3-networking/src/main/java/com/jme3/network/base/MessageProtocol.java +++ b/jme3-networking/src/main/java/com/jme3/network/base/MessageProtocol.java @@ -31,12 +31,14 @@ */ package com.jme3.network.base; -import com.jme3.network.Message; -import com.jme3.network.serializing.Serializer; import java.io.IOException; import java.nio.ByteBuffer; import java.util.LinkedList; +import com.jme3.network.AbstractMessage; +//import com.jme3.network.Message; +import com.jme3.network.serializing.Serializer; + /** * Consolidates the conversion of messages to/from byte buffers * and provides a rolling message buffer. ByteBuffers can be @@ -53,7 +55,7 @@ */ public class MessageProtocol { - private final LinkedList messages = new LinkedList(); + private final LinkedList messages = new LinkedList(); private ByteBuffer current; private int size; private Byte carry; @@ -63,14 +65,15 @@ public class MessageProtocol * and the (short length) + data protocol. If target is null * then a 32k byte buffer will be created and filled. */ - public static ByteBuffer messageToBuffer( Message message, ByteBuffer target ) + public static ByteBuffer messageToBuffer( AbstractMessage message, ByteBuffer target ) { // Could let the caller pass their own in ByteBuffer buffer = target == null ? ByteBuffer.allocate( 32767 + 2 ) : target; try { buffer.position( 2 ); - Serializer.writeClassAndObject( buffer, message ); + Serializer.writeObject(buffer, message); +// Serializer.writeClassAndObject( buffer, message ); buffer.flip(); short dataLength = (short)(buffer.remaining() - 2); buffer.putShort( dataLength ); @@ -78,6 +81,7 @@ public static ByteBuffer messageToBuffer( Message message, ByteBuffer target ) return buffer; } catch( IOException e ) { + e.printStackTrace(); throw new RuntimeException( "Error serializing message", e ); } } @@ -86,7 +90,7 @@ public static ByteBuffer messageToBuffer( Message message, ByteBuffer target ) * Retrieves and removes an extracted message from the accumulated buffer * or returns null if there are no more messages. */ - public Message getMessage() + public AbstractMessage getMessage() { if( messages.isEmpty() ) { return null; @@ -177,10 +181,16 @@ else if( buffer.remaining() < 2 ) { protected void createMessage( ByteBuffer buffer ) { try { - Object obj = Serializer.readClassAndObject( buffer ); - Message m = (Message)obj; +// FieldSerializer s = new FieldSerializer(); +// System.out.println(Arrays.toString(buffer.array())); + Object obj = Serializer.readObject(buffer, AbstractMessage.class); +// System.out.println(obj); + AbstractMessage m = (AbstractMessage) obj; + messages.add(m); } catch( IOException e ) { + System.err.println("Serialized object: " + buffer.toString()); + System.err.println("Serialized object: " + buffer.array().toString()); throw new RuntimeException( "Error deserializing object, class ID:" + buffer.getShort(0), e ); } } diff --git a/jme3-networking/src/main/java/com/jme3/network/message/ChannelInfoMessage.java b/jme3-networking/src/main/java/com/jme3/network/message/ChannelInfoMessage.java index cbf4355656..e1072ef265 100644 --- a/jme3-networking/src/main/java/com/jme3/network/message/ChannelInfoMessage.java +++ b/jme3-networking/src/main/java/com/jme3/network/message/ChannelInfoMessage.java @@ -32,7 +32,6 @@ package com.jme3.network.message; import com.jme3.network.AbstractMessage; -import com.jme3.network.serializing.Serializable; import java.util.Arrays; import java.util.List; @@ -41,7 +40,7 @@ * * @author Paul Speed */ -@Serializable() + public class ChannelInfoMessage extends AbstractMessage { private long id; private int[] ports; diff --git a/jme3-networking/src/main/java/com/jme3/network/message/ClientRegistrationMessage.java b/jme3-networking/src/main/java/com/jme3/network/message/ClientRegistrationMessage.java index d8c19a20c9..42e5b02ab7 100644 --- a/jme3-networking/src/main/java/com/jme3/network/message/ClientRegistrationMessage.java +++ b/jme3-networking/src/main/java/com/jme3/network/message/ClientRegistrationMessage.java @@ -33,7 +33,7 @@ import com.jme3.network.AbstractMessage; import com.jme3.network.serializing.*; -import com.jme3.network.serializing.serializers.StringSerializer; +//import com.jme3.network.serializing.serializers.StringSerializer; import java.io.IOException; import java.nio.ByteBuffer; @@ -46,14 +46,18 @@ * * @author Lars Wesselius, Paul Speed */ -@Serializable() -public class ClientRegistrationMessage extends AbstractMessage { + +public class ClientRegistrationMessage extends AbstractMessage implements java.io.Serializable { public static final short SERIALIZER_ID = -44; private long id; private String gameName; private int version; + + public ClientRegistrationMessage() { + + } public long getId() { return id; @@ -82,45 +86,4 @@ public int getVersion() { public String toString() { return getClass().getName() + "[id=" + id + ", gameName=" + gameName + ", version=" + version + "]"; } - - /** - * A message-specific serializer to avoid compatibility issues - * between versions. This serializer is registered to the specific - * SERIALIZER_ID which is compatible with previous versions of the - * SM serializer registrations... and now will be forever. - */ - public static class ClientRegistrationSerializer extends Serializer { - - public ClientRegistrationMessage readObject( ByteBuffer data, Class c ) throws IOException { - - // Read the null/non-null marker - if (data.get() == 0x0) - return null; - - ClientRegistrationMessage msg = new ClientRegistrationMessage(); - - msg.gameName = StringSerializer.readString(data); - msg.id = data.getLong(); - msg.version = data.getInt(); - - return msg; - } - - public void writeObject(ByteBuffer buffer, Object object) throws IOException { - - // Add the null/non-null marker - buffer.put( (byte)(object != null ? 0x1 : 0x0) ); - if (object == null) { - // Nothing left to do - return; - } - - ClientRegistrationMessage msg = (ClientRegistrationMessage)object; - StringSerializer.writeString( msg.gameName, buffer ); - - buffer.putLong(msg.id); - buffer.putInt(msg.version); - } - } - } diff --git a/jme3-networking/src/main/java/com/jme3/network/message/CompressedMessage.java b/jme3-networking/src/main/java/com/jme3/network/message/CompressedMessage.java index 40f20bf6ee..febf75a1dd 100644 --- a/jme3-networking/src/main/java/com/jme3/network/message/CompressedMessage.java +++ b/jme3-networking/src/main/java/com/jme3/network/message/CompressedMessage.java @@ -32,8 +32,6 @@ package com.jme3.network.message; import com.jme3.network.AbstractMessage; -import com.jme3.network.Message; -import com.jme3.network.serializing.Serializable; /** * CompressedMessage is a base class for all messages that @@ -41,21 +39,20 @@ * * @author Lars Wesselius */ -@Serializable() public class CompressedMessage extends AbstractMessage { - private Message message; + private AbstractMessage message; public CompressedMessage() { } - public CompressedMessage(Message msg) { + public CompressedMessage(AbstractMessage msg) { this.message = msg; } - public void setMessage(Message message) { + public void setMessage(AbstractMessage message) { this.message = message; } - public Message getMessage() { + public AbstractMessage getMessage() { return message; } } diff --git a/jme3-networking/src/main/java/com/jme3/network/message/DisconnectMessage.java b/jme3-networking/src/main/java/com/jme3/network/message/DisconnectMessage.java index d514232f43..31763b9370 100644 --- a/jme3-networking/src/main/java/com/jme3/network/message/DisconnectMessage.java +++ b/jme3-networking/src/main/java/com/jme3/network/message/DisconnectMessage.java @@ -33,7 +33,7 @@ import com.jme3.network.AbstractMessage; import com.jme3.network.serializing.*; -import com.jme3.network.serializing.serializers.StringSerializer; +//import com.jme3.network.serializing.serializers.StringSerializer; import java.io.IOException; import java.nio.ByteBuffer; @@ -42,7 +42,6 @@ * * @author Lars Wesselius, Paul Speed */ -@Serializable() public class DisconnectMessage extends AbstractMessage { public static final short SERIALIZER_ID = -42; @@ -83,7 +82,7 @@ public String toString() { */ public static class DisconnectSerializer extends Serializer { - public DisconnectMessage readObject( ByteBuffer data, Class c ) throws IOException { + public static DisconnectMessage readObject( ByteBuffer data, Class c ) throws IOException { // Read the null/non-null marker if (data.get() == 0x0) @@ -91,13 +90,13 @@ public DisconnectMessage readObject( ByteBuffer data, Class c ) throws IOExcepti DisconnectMessage msg = new DisconnectMessage(); - msg.reason = StringSerializer.readString(data); - msg.type = StringSerializer.readString(data); +// msg.reason = StringSerializer.readString(data); +// msg.type = StringSerializer.readString(data); return msg; } - public void writeObject(ByteBuffer buffer, Object object) throws IOException { + public static void writeObject(ByteBuffer buffer, Object object) throws IOException { // Add the null/non-null marker buffer.put( (byte)(object != null ? 0x1 : 0x0) ); @@ -107,8 +106,8 @@ public void writeObject(ByteBuffer buffer, Object object) throws IOException { } DisconnectMessage msg = (DisconnectMessage)object; - StringSerializer.writeString( msg.reason, buffer ); - StringSerializer.writeString( msg.type, buffer ); +// StringSerializer.writeString( msg.reason, buffer ); +// StringSerializer.writeString( msg.type, buffer ); } } } diff --git a/jme3-networking/src/main/java/com/jme3/network/message/GZIPCompressedMessage.java b/jme3-networking/src/main/java/com/jme3/network/message/GZIPCompressedMessage.java index a3065589a7..a50720b88a 100644 --- a/jme3-networking/src/main/java/com/jme3/network/message/GZIPCompressedMessage.java +++ b/jme3-networking/src/main/java/com/jme3/network/message/GZIPCompressedMessage.java @@ -31,8 +31,7 @@ */ package com.jme3.network.message; -import com.jme3.network.Message; -import com.jme3.network.serializing.Serializable; +import com.jme3.network.AbstractMessage; /** * GZIPCompressedMessage is the class that you need to use should you want to @@ -40,13 +39,12 @@ * * @author Lars Wesselius */ -@Serializable() public class GZIPCompressedMessage extends CompressedMessage { public GZIPCompressedMessage() { super(); } - public GZIPCompressedMessage(Message msg) { + public GZIPCompressedMessage(AbstractMessage msg) { super(msg); } } diff --git a/jme3-networking/src/main/java/com/jme3/network/message/SerializerRegistrationsMessage.java b/jme3-networking/src/main/java/com/jme3/network/message/SerializerRegistrationsMessage.java deleted file mode 100644 index d9b51d39aa..0000000000 --- a/jme3-networking/src/main/java/com/jme3/network/message/SerializerRegistrationsMessage.java +++ /dev/null @@ -1,210 +0,0 @@ -/* - * $Id: SerializerRegistrationsMessage.java 3829 2014-11-24 07:25:43Z pspeed $ - * - * Copyright (c) 2012, Paul Speed - * All rights reserved. - */ - -package com.jme3.network.message; - -import com.jme3.network.AbstractMessage; -import com.jme3.network.serializing.Serializable; -import com.jme3.network.serializing.Serializer; -import com.jme3.network.serializing.SerializerRegistration; -import com.jme3.network.serializing.serializers.FieldSerializer; -import java.util.*; -import java.util.jar.Attributes; -import java.util.logging.Level; -import java.util.logging.Logger; - - -/** - * Holds a compiled set of message registration information that - * can be sent over the wire. The received message can then be - * used to register all of the classes using the same IDs and - * same ordering, etc.. The intent is that the server compiles - * this message once it is sure that all serializable classes have - * been registered. It can then send this to each new client and - * they can use it to register all of the classes without requiring - * exactly reproducing the same calls that the server did to register - * messages. - * - *

Normally, JME recommends that apps have a common utility method - * that they call on both client and server. However, this makes - * pluggable services nearly impossible as some central class has to - * know about all registered serializers. This message implementation - * gets around by only requiring registration on the server.

- * - * @author Paul Speed - */ -@Serializable -public class SerializerRegistrationsMessage extends AbstractMessage { - - static final Logger log = Logger.getLogger(SerializerRegistrationsMessage.class.getName()); - - public static final Set ignore = new HashSet(); - static { - // We could build this automatically but then we - // risk making a client and server out of date simply because - // their JME versions are out of date. - ignore.add(Boolean.class); - ignore.add(Float.class); - ignore.add(Boolean.class); - ignore.add(Byte.class); - ignore.add(Character.class); - ignore.add(Short.class); - ignore.add(Integer.class); - ignore.add(Long.class); - ignore.add(Float.class); - ignore.add(Double.class); - ignore.add(String.class); - - ignore.add(DisconnectMessage.class); - ignore.add(ClientRegistrationMessage.class); - - ignore.add(Date.class); - ignore.add(AbstractCollection.class); - ignore.add(AbstractList.class); - ignore.add(AbstractSet.class); - ignore.add(ArrayList.class); - ignore.add(HashSet.class); - ignore.add(LinkedHashSet.class); - ignore.add(LinkedList.class); - ignore.add(TreeSet.class); - ignore.add(Vector.class); - ignore.add(AbstractMap.class); - ignore.add(Attributes.class); - ignore.add(HashMap.class); - ignore.add(Hashtable.class); - ignore.add(IdentityHashMap.class); - ignore.add(TreeMap.class); - ignore.add(WeakHashMap.class); - ignore.add(Enum.class); - - ignore.add(GZIPCompressedMessage.class); - ignore.add(ZIPCompressedMessage.class); - - ignore.add(ChannelInfoMessage.class); - - ignore.add(SerializerRegistrationsMessage.class); - ignore.add(SerializerRegistrationsMessage.Registration.class); - } - - public static SerializerRegistrationsMessage INSTANCE; - public static Registration[] compiled; - private static final Serializer fieldSerializer = new FieldSerializer(); - - private Registration[] registrations; - - public SerializerRegistrationsMessage() { - setReliable(true); - } - - public SerializerRegistrationsMessage( Registration... registrations ) { - setReliable(true); - this.registrations = registrations; - } - - public static void compile() { - - // Let's just see what they are here - List list = new ArrayList(); - for( SerializerRegistration reg : Serializer.getSerializerRegistrations() ) { - Class type = reg.getType(); - if( ignore.contains(type) ) - continue; - if( type.isPrimitive() ) - continue; - - list.add(new Registration(reg)); - } - - if( log.isLoggable(Level.FINE) ) { - log.log( Level.FINE, "Number of registered classes:{0}", list.size()); - for( Registration reg : list ) { - log.log( Level.FINE, " {0}", reg); - } - } - compiled = list.toArray(new Registration[list.size()]); - - INSTANCE = new SerializerRegistrationsMessage(compiled); - - Serializer.setReadOnly(true); - } - - public void registerAll() { - - // See if we will have problems because our registry is locked - if( Serializer.isReadOnly() ) { - // Check to see if maybe we are executing this from the - // same JVM that sent the message, ie: client and server are running on - // the same JVM - // There could be more advanced checks than this but for now we'll - // assume that if the registry was compiled here then it means - // we are also the server process. Note that this wouldn't hold true - // under complicated examples where there are clients of one server - // that also run their own servers but realistically they would have - // to disable the ServerSerializerRegistrationsServer anyway. - if( compiled != null ) { - log.log(Level.INFO, "Skipping registration as registry is locked, presumably by a local server process."); - return; - } - } - - log.log(Level.FINE, "Registering {0} classes...", registrations.length); - for( Registration reg : registrations ) { - log.log(Level.INFO, "Registering:{0}", reg); - reg.register(); - } - log.log(Level.FINE, "Done registering serializable classes."); - } - - @Serializable - public static final class Registration { - - private short id; - private String className; - private String serializerClassName; - - public Registration() { - } - - public Registration( SerializerRegistration reg ) { - - this.id = reg.getId(); - this.className = reg.getType().getName(); - if( reg.getSerializer().getClass() != FieldSerializer.class ) { - this.serializerClassName = reg.getSerializer().getClass().getName(); - } - } - - public void register() { - try { - Class type = Class.forName(className); - Serializer serializer; - if( serializerClassName == null ) { - serializer = fieldSerializer; - } else { - Class serializerType = Class.forName(serializerClassName); - serializer = (Serializer)serializerType.newInstance(); - } - SerializerRegistration result = Serializer.registerClassForId(id, type, serializer); - log.log(Level.FINE, " result:{0}", result); - } catch( ClassNotFoundException e ) { - throw new RuntimeException( "Class not found attempting to register:" + this, e ); - } catch( InstantiationException e ) { - throw new RuntimeException( "Error instantiating serializer registering:" + this, e ); - } catch( IllegalAccessException e ) { - throw new RuntimeException( "Error instantiating serializer registering:" + this, e ); - } - } - - @Override - public String toString() { - return "Registration[" + id + " = " + className + ", serializer=" + serializerClassName + "]"; - } - } -} - - - diff --git a/jme3-networking/src/main/java/com/jme3/network/message/ZIPCompressedMessage.java b/jme3-networking/src/main/java/com/jme3/network/message/ZIPCompressedMessage.java index c39e8b226f..39fe42e4b2 100644 --- a/jme3-networking/src/main/java/com/jme3/network/message/ZIPCompressedMessage.java +++ b/jme3-networking/src/main/java/com/jme3/network/message/ZIPCompressedMessage.java @@ -31,15 +31,14 @@ */ package com.jme3.network.message; -import com.jme3.network.Message; -import com.jme3.network.serializing.Serializable; +import com.jme3.network.AbstractMessage; +//import com.jme3.network.Message; /** * Compress a message using this ZIPCompressedMessage class * * @author Lars Wesselius */ -@Serializable() public class ZIPCompressedMessage extends CompressedMessage { private static int compressionLevel = 6; @@ -47,11 +46,11 @@ public ZIPCompressedMessage() { super(); } - public ZIPCompressedMessage(Message msg) { + public ZIPCompressedMessage(AbstractMessage msg) { super(msg); } - public ZIPCompressedMessage(Message msg, int level) { + public ZIPCompressedMessage(AbstractMessage msg, int level) { super(msg); setLevel(level); } diff --git a/jme3-networking/src/main/java/com/jme3/network/rmi/ObjectDef.java b/jme3-networking/src/main/java/com/jme3/network/rmi/ObjectDef.java index 64ffe3057c..dfa9fcdc97 100644 --- a/jme3-networking/src/main/java/com/jme3/network/rmi/ObjectDef.java +++ b/jme3-networking/src/main/java/com/jme3/network/rmi/ObjectDef.java @@ -32,10 +32,8 @@ package com.jme3.network.rmi; -import com.jme3.network.serializing.Serializable; import java.lang.reflect.Method; -@Serializable public class ObjectDef { /** diff --git a/jme3-networking/src/main/java/com/jme3/network/rmi/ObjectStore.java b/jme3-networking/src/main/java/com/jme3/network/rmi/ObjectStore.java index 05634b3ab2..fececb6215 100644 --- a/jme3-networking/src/main/java/com/jme3/network/rmi/ObjectStore.java +++ b/jme3-networking/src/main/java/com/jme3/network/rmi/ObjectStore.java @@ -87,7 +87,7 @@ public String toString(){ public class ServerEventHandler implements MessageListener, ConnectionListener { - public void messageReceived(HostedConnection source, Message m) { + public void messageReceived(HostedConnection source, AbstractMessage m) { onMessage(source, m); } @@ -103,7 +103,7 @@ public void connectionRemoved(Server server, HostedConnection conn) { public class ClientEventHandler implements MessageListener, ClientStateListener { - public void messageReceived(Object source, Message m) { + public void messageReceived(Object source, AbstractMessage m) { onMessage(null, m); } @@ -118,9 +118,9 @@ public void clientDisconnected(Client c, DisconnectInfo info) { static { Serializer s = new RmiSerializer(); - Serializer.registerClass(RemoteObjectDefMessage.class, s); - Serializer.registerClass(RemoteMethodCallMessage.class, s); - Serializer.registerClass(RemoteMethodReturnMessage.class, s); +// Serializer.registerClass(RemoteObjectDefMessage.class, s); +// Serializer.registerClass(RemoteMethodCallMessage.class, s); +// Serializer.registerClass(RemoteMethodReturnMessage.class, s); } public ObjectStore(Client client) { @@ -247,7 +247,7 @@ Object invokeRemoteMethod(RemoteObject remoteObj, Method method, Object[] args){ } } - private void onMessage(HostedConnection source, Message message) { + private void onMessage(HostedConnection source, AbstractMessage message) { // Might want to do more strict validation of the data // in the message to prevent crashes diff --git a/jme3-networking/src/main/java/com/jme3/network/rmi/RemoteMethodCallMessage.java b/jme3-networking/src/main/java/com/jme3/network/rmi/RemoteMethodCallMessage.java index 8c43c2842c..88ec6ed78b 100644 --- a/jme3-networking/src/main/java/com/jme3/network/rmi/RemoteMethodCallMessage.java +++ b/jme3-networking/src/main/java/com/jme3/network/rmi/RemoteMethodCallMessage.java @@ -32,14 +32,12 @@ package com.jme3.network.rmi; import com.jme3.network.AbstractMessage; -import com.jme3.network.serializing.Serializable; /** * Sent to a remote client to make a remote method invocation. * * @author Kirill Vainer */ -@Serializable public class RemoteMethodCallMessage extends AbstractMessage { public RemoteMethodCallMessage(){ diff --git a/jme3-networking/src/main/java/com/jme3/network/rmi/RemoteMethodReturnMessage.java b/jme3-networking/src/main/java/com/jme3/network/rmi/RemoteMethodReturnMessage.java index 31f2b396de..a15665a55d 100644 --- a/jme3-networking/src/main/java/com/jme3/network/rmi/RemoteMethodReturnMessage.java +++ b/jme3-networking/src/main/java/com/jme3/network/rmi/RemoteMethodReturnMessage.java @@ -32,7 +32,6 @@ package com.jme3.network.rmi; import com.jme3.network.AbstractMessage; -import com.jme3.network.serializing.Serializable; /** * Contains the return value for a remote method invocation, sent as a response @@ -40,7 +39,6 @@ * * @author Kirill Vainer. */ -@Serializable public class RemoteMethodReturnMessage extends AbstractMessage { public RemoteMethodReturnMessage(){ diff --git a/jme3-networking/src/main/java/com/jme3/network/rmi/RemoteObjectDefMessage.java b/jme3-networking/src/main/java/com/jme3/network/rmi/RemoteObjectDefMessage.java index a15ca5ccb6..34a68b6852 100644 --- a/jme3-networking/src/main/java/com/jme3/network/rmi/RemoteObjectDefMessage.java +++ b/jme3-networking/src/main/java/com/jme3/network/rmi/RemoteObjectDefMessage.java @@ -32,13 +32,11 @@ package com.jme3.network.rmi; import com.jme3.network.AbstractMessage; -import com.jme3.network.serializing.Serializable; /** * Sent to expose RMI interfaces on the local client to other clients. * @author Kirill Vainer */ -@Serializable public class RemoteObjectDefMessage extends AbstractMessage { public ObjectDef[] objects; diff --git a/jme3-networking/src/main/java/com/jme3/network/rmi/RmiSerializer.java b/jme3-networking/src/main/java/com/jme3/network/rmi/RmiSerializer.java index 8f55178d02..759414584f 100644 --- a/jme3-networking/src/main/java/com/jme3/network/rmi/RmiSerializer.java +++ b/jme3-networking/src/main/java/com/jme3/network/rmi/RmiSerializer.java @@ -32,7 +32,7 @@ package com.jme3.network.rmi; import com.jme3.network.serializing.Serializer; -import com.jme3.network.serializing.SerializerRegistration; +//import com.jme3.network.serializing.SerializerRegistration; import java.io.IOException; import java.lang.reflect.Method; import java.nio.ByteBuffer; @@ -50,9 +50,9 @@ public class RmiSerializer extends Serializer { private static final Logger logger = Logger.getLogger(RmiSerializer.class.getName()); // not good for multithread applications - private char[] chrBuf = new char[256]; + private static char[] chrBuf = new char[256]; - private void writeString(ByteBuffer buffer, String string) throws IOException{ + private static void writeString(ByteBuffer buffer, String string) throws IOException{ int length = string.length(); if (length > 255){ logger.log(Level.WARNING, "The string length exceeds the limit! {0} > 255", length); @@ -66,7 +66,7 @@ private void writeString(ByteBuffer buffer, String string) throws IOException{ } } - private String readString(ByteBuffer buffer){ + private static String readString(ByteBuffer buffer){ int length = buffer.get() & 0xff; for (int i = 0; i < length; i++){ chrBuf[i] = (char) (buffer.get() & 0xff); @@ -74,35 +74,36 @@ private String readString(ByteBuffer buffer){ return String.valueOf(chrBuf, 0, length); } - private void writeType(ByteBuffer buffer, Class clazz) throws IOException{ + private static void writeType(ByteBuffer buffer, Class clazz) throws IOException{ if (clazz == void.class){ buffer.putShort((short)0); } else { - SerializerRegistration reg = Serializer.getSerializerRegistration(clazz); - if (reg == null){ - logger.log(Level.WARNING, "Unknown class: {0}", clazz); - throw new IOException(); // prevents message from being serialized - } - buffer.putShort(reg.getId()); +// SerializerRegistration reg = Serializer.getSerializerRegistration(clazz); +// if (reg == null){ +// logger.log(Level.WARNING, "Unknown class: {0}", clazz); +// throw new IOException(); // prevents message from being serialized +// } +// buffer.putShort(reg.getId()); } } - private Class readType(ByteBuffer buffer) throws IOException{ - SerializerRegistration reg = Serializer.readClass(buffer); - if (reg == null){ - // either "void" or unknown val - short id = buffer.getShort(buffer.position()-2); - if (id == 0){ - return void.class; - } else{ - logger.log(Level.WARNING, "Undefined class ID: {0}", id); - throw new IOException(); // prevents message from being serialized - } - } - return reg.getType(); + private static Class readType(ByteBuffer buffer) throws IOException{ +// SerializerRegistration reg = Serializer.readClass(buffer); +// if (reg == null){ +// // either "void" or unknown val +// short id = buffer.getShort(buffer.position()-2); +// if (id == 0){ +// return void.class; +// } else{ +// logger.log(Level.WARNING, "Undefined class ID: {0}", id); +// throw new IOException(); // prevents message from being serialized +// } +// } +// return reg.getType(); + return Object.class; } - private void writeMethod(ByteBuffer buffer, Method method) throws IOException{ + private static void writeMethod(ByteBuffer buffer, Method method) throws IOException{ String name = method.getName(); Class[] paramTypes = method.getParameterTypes(); Class returnType = method.getReturnType(); @@ -114,7 +115,7 @@ private void writeMethod(ByteBuffer buffer, Method method) throws IOException{ writeType(buffer, paramType); } - private MethodDef readMethod(ByteBuffer buffer) throws IOException{ + private static MethodDef readMethod(ByteBuffer buffer) throws IOException{ String name = readString(buffer); Class retType = readType(buffer); @@ -131,7 +132,7 @@ private MethodDef readMethod(ByteBuffer buffer) throws IOException{ return def; } - private void writeObjectDef(ByteBuffer buffer, ObjectDef def) throws IOException{ + private static void writeObjectDef(ByteBuffer buffer, ObjectDef def) throws IOException{ buffer.putShort((short)def.objectId); writeString(buffer, def.objectName); Method[] methods = def.methods; @@ -141,7 +142,7 @@ private void writeObjectDef(ByteBuffer buffer, ObjectDef def) throws IOException } } - private ObjectDef readObjectDef(ByteBuffer buffer) throws IOException{ + private static ObjectDef readObjectDef(ByteBuffer buffer) throws IOException{ ObjectDef def = new ObjectDef(); def.objectId = buffer.getShort(); @@ -156,14 +157,14 @@ private ObjectDef readObjectDef(ByteBuffer buffer) throws IOException{ return def; } - private void writeObjectDefs(ByteBuffer buffer, RemoteObjectDefMessage defMsg) throws IOException{ + private static void writeObjectDefs(ByteBuffer buffer, RemoteObjectDefMessage defMsg) throws IOException{ ObjectDef[] defs = defMsg.objects; buffer.put( (byte) defs.length ); for (ObjectDef def : defs) writeObjectDef(buffer, def); } - private RemoteObjectDefMessage readObjectDefs(ByteBuffer buffer) throws IOException{ + private static RemoteObjectDefMessage readObjectDefs(ByteBuffer buffer) throws IOException{ RemoteObjectDefMessage defMsg = new RemoteObjectDefMessage(); int numObjs = buffer.get() & 0xff; ObjectDef[] defs = new ObjectDef[numObjs]; @@ -174,7 +175,7 @@ private RemoteObjectDefMessage readObjectDefs(ByteBuffer buffer) throws IOExcept return defMsg; } - private void writeMethodCall(ByteBuffer buffer, RemoteMethodCallMessage call) throws IOException{ + private static void writeMethodCall(ByteBuffer buffer, RemoteMethodCallMessage call) throws IOException{ buffer.putShort((short)call.objectId); buffer.putShort(call.methodId); buffer.putShort(call.invocationId); @@ -189,7 +190,7 @@ private void writeMethodCall(ByteBuffer buffer, RemoteMethodCallMessage call) th for (Object obj : call.args){ if (obj != null){ buffer.put((byte)0x01); - Serializer.writeClassAndObject(buffer, obj); +// Serializer.writeClassAndObject(buffer, obj); }else{ buffer.put((byte)0x00); } @@ -197,7 +198,7 @@ private void writeMethodCall(ByteBuffer buffer, RemoteMethodCallMessage call) th } } - private RemoteMethodCallMessage readMethodCall(ByteBuffer buffer) throws IOException{ + private static RemoteMethodCallMessage readMethodCall(ByteBuffer buffer) throws IOException{ RemoteMethodCallMessage call = new RemoteMethodCallMessage(); call.objectId = buffer.getShort(); call.methodId = buffer.getShort(); @@ -207,7 +208,7 @@ private RemoteMethodCallMessage readMethodCall(ByteBuffer buffer) throws IOExcep Object[] args = new Object[numArgs]; for (int i = 0; i < numArgs; i++){ if (buffer.get() == (byte)0x01){ - args[i] = Serializer.readClassAndObject(buffer); +// args[i] = Serializer.readClassAndObject(buffer); } } call.args = args; @@ -215,27 +216,26 @@ private RemoteMethodCallMessage readMethodCall(ByteBuffer buffer) throws IOExcep return call; } - private void writeMethodReturn(ByteBuffer buffer, RemoteMethodReturnMessage ret) throws IOException{ + private static void writeMethodReturn(ByteBuffer buffer, RemoteMethodReturnMessage ret) throws IOException{ buffer.putShort(ret.invocationID); if (ret.retVal != null){ buffer.put((byte)0x01); - Serializer.writeClassAndObject(buffer, ret.retVal); +// Serializer.writeClassAndObject(buffer, ret.retVal); }else{ buffer.put((byte)0x00); } } - private RemoteMethodReturnMessage readMethodReturn(ByteBuffer buffer) throws IOException{ + private static RemoteMethodReturnMessage readMethodReturn(ByteBuffer buffer) throws IOException{ RemoteMethodReturnMessage ret = new RemoteMethodReturnMessage(); ret.invocationID = buffer.getShort(); if (buffer.get() == (byte)0x01){ - ret.retVal = Serializer.readClassAndObject(buffer); +// ret.retVal = Serializer.readClassAndObject(buffer); } return ret; } - @Override - public T readObject(ByteBuffer data, Class c) throws IOException { + public static T readObject(ByteBuffer data, Class c) throws IOException { if (c == RemoteObjectDefMessage.class){ return (T) readObjectDefs(data); }else if (c == RemoteMethodCallMessage.class){ @@ -246,8 +246,7 @@ public T readObject(ByteBuffer data, Class c) throws IOException { return null; } - @Override - public void writeObject(ByteBuffer buffer, Object object) throws IOException { + public static void writeObject(ByteBuffer buffer, Object object) throws IOException { // int p = buffer.position(); if (object instanceof RemoteObjectDefMessage){ RemoteObjectDefMessage def = (RemoteObjectDefMessage) object; diff --git a/jme3-networking/src/main/java/com/jme3/network/serializing/Serializable.java b/jme3-networking/src/main/java/com/jme3/network/serializing/Serializable.java deleted file mode 100644 index 456a7f4320..0000000000 --- a/jme3-networking/src/main/java/com/jme3/network/serializing/Serializable.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2009-2012 jMonkeyEngine - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of 'jMonkeyEngine' nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package com.jme3.network.serializing; - -import com.jme3.network.serializing.serializers.FieldSerializer; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -/** - * Use this annotation when a class is going to be transferred - * over the network. - * - * @author Lars Wesselius - */ -@Retention(RetentionPolicy.RUNTIME) -public @interface Serializable { - Class serializer() default FieldSerializer.class; - short id() default 0; -} diff --git a/jme3-networking/src/main/java/com/jme3/network/serializing/Serializer.java b/jme3-networking/src/main/java/com/jme3/network/serializing/Serializer.java index ab1d05bc96..cd2896a8ff 100644 --- a/jme3-networking/src/main/java/com/jme3/network/serializing/Serializer.java +++ b/jme3-networking/src/main/java/com/jme3/network/serializing/Serializer.java @@ -31,22 +31,23 @@ */ package com.jme3.network.serializing; -import com.jme3.math.Vector3f; -import com.jme3.network.message.ChannelInfoMessage; -import com.jme3.network.message.ClientRegistrationMessage; -import com.jme3.network.message.DisconnectMessage; -import com.jme3.network.message.GZIPCompressedMessage; -import com.jme3.network.message.ZIPCompressedMessage; -import com.jme3.network.serializing.serializers.*; -import java.io.File; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.net.URL; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; import java.nio.ByteBuffer; -import java.util.*; -import java.util.jar.Attributes; -import java.util.logging.Level; -import java.util.logging.LogManager; -import java.util.logging.Logger; +import java.util.HashSet; +import java.util.Set; + +import org.nustaq.serialization.FSTConfiguration; + +import com.esotericsoftware.kryo.Kryo; +import com.esotericsoftware.kryo.io.Input; +import com.esotericsoftware.kryo.io.Output; +import com.jme3.network.AbstractMessage; +import com.jme3.network.message.ChannelInfoMessage; +import com.jme3.network.message.ClientRegistrationMessage; /** * The main serializer class, which will serialize objects such that @@ -55,420 +56,128 @@ * * @author Lars Wesselius */ -public abstract class Serializer { - protected static final Logger log = Logger.getLogger(Serializer.class.getName()); - - private static final SerializerRegistration NULL_CLASS = new SerializerRegistration( null, Void.class, (short)-1 ); - - private static final Map idRegistrations = new HashMap(); - private static final Map classRegistrations = new HashMap(); - private static final List registrations = new ArrayList(); - - private static final Serializer fieldSerializer = new FieldSerializer(); - private static final Serializer serializableSerializer = new SerializableSerializer(); - private static final Serializer arraySerializer = new ArraySerializer(); - - private static short nextAvailableId = -2; // historically the first ID was always -2 - - private static boolean strictRegistration = true; - - private static volatile boolean locked = false; +//@SuppressWarnings("all") +public class Serializer { + protected static final FSTConfiguration fstConf = FSTConfiguration.getDefaultConfiguration(); - - // Registers the classes we already have serializers for. - static { - - // Preregister some fixed serializers so that they don't move - // if the list below is modified. Automatic ID generation will - // skip these IDs. - registerClassForId( DisconnectMessage.SERIALIZER_ID, DisconnectMessage.class, - new DisconnectMessage.DisconnectSerializer() ); - registerClassForId( ClientRegistrationMessage.SERIALIZER_ID, ClientRegistrationMessage.class, - new ClientRegistrationMessage.ClientRegistrationSerializer() ); - + private static final ThreadLocal kryos = new ThreadLocal() { + protected Kryo initialValue() { + Kryo kryo = new Kryo(); + // Registration goes here. Removed because of difficulties of making this thread safe + return kryo; + }; + }; - registerClass(boolean.class, new BooleanSerializer()); - registerClass(byte.class, new ByteSerializer()); - registerClass(char.class, new CharSerializer()); - registerClass(short.class, new ShortSerializer()); - registerClass(int.class, new IntSerializer()); - registerClass(long.class, new LongSerializer()); - registerClass(float.class, new FloatSerializer()); - registerClass(double.class, new DoubleSerializer()); - - registerClass(Boolean.class, new BooleanSerializer()); - registerClass(Byte.class, new ByteSerializer()); - registerClass(Character.class, new CharSerializer()); - registerClass(Short.class, new ShortSerializer()); - registerClass(Integer.class, new IntSerializer()); - registerClass(Long.class, new LongSerializer()); - registerClass(Float.class, new FloatSerializer()); - registerClass(Double.class, new DoubleSerializer()); - registerClass(String.class, new StringSerializer()); - - registerClass(Vector3f.class, new Vector3Serializer()); - - registerClass(Date.class, new DateSerializer()); - - // all the Collection classes go here - registerClass(AbstractCollection.class, new CollectionSerializer()); - registerClass(AbstractList.class, new CollectionSerializer()); - registerClass(AbstractSet.class, new CollectionSerializer()); - registerClass(ArrayList.class, new CollectionSerializer()); - registerClass(HashSet.class, new CollectionSerializer()); - registerClass(LinkedHashSet.class, new CollectionSerializer()); - registerClass(LinkedList.class, new CollectionSerializer()); - registerClass(TreeSet.class, new CollectionSerializer()); - registerClass(Vector.class, new CollectionSerializer()); - - // All the Map classes go here - registerClass(AbstractMap.class, new MapSerializer()); - registerClass(Attributes.class, new MapSerializer()); - registerClass(HashMap.class, new MapSerializer()); - registerClass(Hashtable.class, new MapSerializer()); - registerClass(IdentityHashMap.class, new MapSerializer()); - registerClass(TreeMap.class, new MapSerializer()); - registerClass(WeakHashMap.class, new MapSerializer()); - - registerClass(Enum.class, new EnumSerializer()); - registerClass(GZIPCompressedMessage.class, new GZIPSerializer()); - registerClass(ZIPCompressedMessage.class, new ZIPSerializer()); - + static { + //com.esotericsoftware.minlog.Log.TRACE(); + + registerClass(AbstractMessage.class); + registerClass(ClientRegistrationMessage.class); registerClass(ChannelInfoMessage.class); } - /** - * When set to true, classes that do not have intrinsic IDs in their - * @Serializable will not be auto-registered during write. Defaults - * to true since this is almost never desired behavior with the way - * this code works. Set to false to get the old permissive behavior. - */ - public static void setStrictRegistration( boolean b ) { - strictRegistration = b; - } - - public static SerializerRegistration registerClass(Class cls) { - return registerClass(cls, true); - } - - public static void registerClasses(Class... classes) { - for( Class c : classes ) { - registerClass(c); - } + public static void registerClass(Class c) { + fstConf.registerClass(c); } - private static short nextId() { - - // If the ID we are about to return is already in use - // then skip it. - while (idRegistrations.containsKey(nextAvailableId) ) { - nextAvailableId--; - } - - // Return the available ID and post-decrement to get - // ready for next time. - return nextAvailableId--; - } - - /** - * Can put the registry in a read-only state such that additional attempts - * to register classes will fail. This can be used by servers to lock the - * registry to avoid accidentally registering classes after a full registry - * set has been compiled. - */ - public static void setReadOnly( boolean b ) { - locked = b; - } - - public static boolean isReadOnly() { - return locked; - } - - /** - * Directly registers a class for a specific ID. Generally, use the regular - * registerClass() method. This method is intended for framework code that might - * be maintaining specific ID maps across client and server. - */ - public static SerializerRegistration registerClassForId( short id, Class cls, Serializer serializer ) { - - if( locked ) { - throw new RuntimeException("Serializer registry locked trying to register class:" + cls); - } - - SerializerRegistration reg = new SerializerRegistration(serializer, cls, id); - - idRegistrations.put(id, reg); - classRegistrations.put(cls, reg); - - log.log( Level.FINE, "Registered class[" + id + "]:{0} to:" + serializer, cls ); - - serializer.initialize(cls); - - // Add the class after so that dependency order is preserved if the - // serializer registers its own classes. - registrations.add(reg); - - return reg; + public static T readObject(ByteBuffer data, Class c) throws IOException { + return readObject(data); } /** - * Registers the specified class. The failOnMiss flag controls whether or - * not this method returns null for failed registration or throws an exception. + * Uses Java serialization */ @SuppressWarnings("unchecked") - public static SerializerRegistration registerClass(Class cls, boolean failOnMiss) { - if (cls.isAnnotationPresent(Serializable.class)) { - Serializable serializable = (Serializable)cls.getAnnotation(Serializable.class); - - Class serializerClass = serializable.serializer(); - short classId = serializable.id(); - if (classId == 0) classId = nextId(); - - Serializer serializer = getSerializer(serializerClass, false); - - if (serializer == null) serializer = fieldSerializer; - - SerializerRegistration existingReg = getExactSerializerRegistration(cls); - - if (existingReg != null) classId = existingReg.getId(); - - SerializerRegistration reg = new SerializerRegistration(serializer, cls, classId); - - return registerClassForId( classId, cls, serializer ); - } - if (failOnMiss) { - throw new IllegalArgumentException( "Class is not marked @Serializable:" + cls ); - } - return null; + public static T readObjectFST(ByteBuffer data) throws IOException { + byte[] b = new byte[data.remaining()]; + data.get(b); + T object = (T) fstConf.asObject(b); + return object; } /** - * @deprecated This cannot be implemented in a reasonable way that works in - * all deployment methods. + * Uses Java serialization */ - @Deprecated - public static SerializerRegistration[] registerPackage(String pkgName) { - try { - ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - String path = pkgName.replace('.', '/'); - Enumeration resources = classLoader.getResources(path); - List dirs = new ArrayList(); - while (resources.hasMoreElements()) { - URL resource = resources.nextElement(); - dirs.add(new File(resource.getFile())); - } - ArrayList classes = new ArrayList(); - for (File directory : dirs) { - classes.addAll(findClasses(directory, pkgName)); - } - - SerializerRegistration[] registeredClasses = new SerializerRegistration[classes.size()]; - for (int i = 0; i != classes.size(); ++i) { - Class clz = classes.get(i); - registeredClasses[i] = registerClass(clz, false); - } - return registeredClasses; - } catch (Exception e) { - e.printStackTrace(); - } - return new SerializerRegistration[0]; - } - - private static List findClasses(File dir, String pkgName) throws ClassNotFoundException { - List classes = new ArrayList(); - if (!dir.exists()) { - return classes; - } - File[] files = dir.listFiles(); - for (File file : files) { - if (file.isDirectory()) { - assert !file.getName().contains("."); - classes.addAll(findClasses(file, pkgName + "." + file.getName())); - } else if (file.getName().endsWith(".class")) { - classes.add(Class.forName(pkgName + '.' + file.getName().substring(0, file.getName().length() - 6))); - } - } - return classes; - } - - public static SerializerRegistration registerClass(Class cls, Serializer serializer) { - SerializerRegistration existingReg = getExactSerializerRegistration(cls); - - short id; - if (existingReg != null) { - id = existingReg.getId(); - } else { - id = nextId(); - } - return registerClassForId( id, cls, serializer ); - } - - public static Serializer getExactSerializer(Class cls) { - return classRegistrations.get(cls).getSerializer(); - } - - public static Serializer getSerializer(Class cls) { - return getSerializer(cls, true); - } - - public static Serializer getSerializer(Class cls, boolean failOnMiss) { - return getSerializerRegistration(cls, failOnMiss).getSerializer(); - } - - public static Collection getSerializerRegistrations() { - return registrations; - } - - public static SerializerRegistration getExactSerializerRegistration(Class cls) { - return classRegistrations.get(cls); + @SuppressWarnings("unchecked") + public static T readObject(ByteBuffer data) throws IOException { + byte[] b = new byte[data.remaining()]; + data.get(b); + ByteArrayInputStream bytesIn = new ByteArrayInputStream(b); + ObjectInputStream ois = new ObjectInputStream(bytesIn); + T object; + try { + object = (T) ois.readObject(); + } catch (ClassNotFoundException e) { + throw new SerializerException( "Error reading object", e); + } + ois.close(); + return object; } - public static SerializerRegistration getSerializerRegistration(Class cls) { - return getSerializerRegistration(cls, strictRegistration); - } + /** + * Uses kryo serialization + * @param data + * @return + */ @SuppressWarnings("unchecked") - public static SerializerRegistration getSerializerRegistration(Class cls, boolean failOnMiss) { - SerializerRegistration reg = classRegistrations.get(cls); + public static T readObjectKryo(ByteBuffer data) throws IOException { + byte[] b = new byte[data.remaining()]; + data.get(b); - if (reg != null) return reg; - - for (Map.Entry entry : classRegistrations.entrySet()) { - if (entry.getKey().isAssignableFrom(Serializable.class)) continue; - if (entry.getKey().isAssignableFrom(cls)) return entry.getValue(); - } - - if (cls.isArray()) return registerClass(cls, arraySerializer); - - if (Serializable.class.isAssignableFrom(cls)) { - return getExactSerializerRegistration(java.io.Serializable.class); - } - - // See if the class could be safely auto-registered - if (cls.isAnnotationPresent(Serializable.class)) { - Serializable serializable = (Serializable)cls.getAnnotation(Serializable.class); - short classId = serializable.id(); - if( classId != 0 ) { - // No reason to fail because the ID is fixed - failOnMiss = false; - } - } + Input kryoInput = new Input(b); - if( failOnMiss ) { - throw new IllegalArgumentException( "Class has not been registered:" + cls ); - } - return registerClass(cls, fieldSerializer); - } - - - /////////////////////////////////////////////////////////////////////////////////// - - - /** - * Read the class from given buffer and return its SerializerRegistration. - * - * @param buffer The buffer to read from. - * @return The SerializerRegistration, or null if non-existent. - */ - public static SerializerRegistration readClass(ByteBuffer buffer) { - short classID = buffer.getShort(); - if (classID == -1) return NULL_CLASS; - return idRegistrations.get(classID); + Object object = kryos.get().readClassAndObject(kryoInput); + + kryoInput.close(); // kryo's input must be closed as well. + + return (T) object; } - + + /** - * Read the class and the object. - * - * @param buffer Buffer to read from. - * @return The Object that was read. - * @throws IOException If serialization failed. + * Uses Java serialization + * @param buffer + * @param object + * @throws IOException */ - @SuppressWarnings("unchecked") - public static Object readClassAndObject(ByteBuffer buffer) throws IOException { - SerializerRegistration reg = readClass(buffer); - if (reg == NULL_CLASS) return null; - if (reg == null) throw new SerializerException( "Class not found for buffer data." ); - return reg.getSerializer().readObject(buffer, reg.getType()); + public static void writeObjectFST(ByteBuffer buffer, Object object) throws IOException { + byte[] bytes = fstConf.asByteArray(object); + buffer.put(bytes); } - + /** - * Write a class and return its SerializerRegistration. - * - * @param buffer The buffer to write the given class to. - * @param type The class to write. - * @return The SerializerRegistration that's registered to the class. + * Uses Java serialization + * @param buffer + * @param object + * @throws IOException */ - public static SerializerRegistration writeClass(ByteBuffer buffer, Class type) throws IOException { - SerializerRegistration reg = getSerializerRegistration(type); - if (reg == null) { - throw new SerializerException( "Class not registered:" + type ); - } - - if( log.isLoggable(Level.FINER) ) { - log.log(Level.FINER, "writing class:{0} with ID:{1}", new Object[]{type, reg.getId()}); - } - buffer.putShort(reg.getId()); - return reg; + public static void writeObject(ByteBuffer buffer, Object object) throws IOException { + ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(bytesOut); + oos.writeObject(object); + oos.flush(); + byte[] bytes = bytesOut.toByteArray(); + bytesOut.close(); + oos.close(); + buffer.put(bytes); } - + /** - * Write the class and object. - * - * @param buffer The buffer to write to. - * @param object The object to write. - * @throws IOException If serializing fails. + * Uses Kryo serialization + * @param buffer + * @param object + * @throws IOException */ - public static void writeClassAndObject(ByteBuffer buffer, Object object) throws IOException { - if (object == null) { - buffer.putShort((short)-1); - return; - } - SerializerRegistration reg = writeClass(buffer, object.getClass()); + public static void writeObjectKryo(ByteBuffer buffer, Object object) throws IOException { + Output kryoOutput = new Output(buffer.array()); - // If the caller (or us) has registered a generic base class (like Enum) - // that is meant to steer automatic resolution for things like FieldSerializer - // that have final classes in fields... then there are cases where the exact - // type isn't known by the outer class. (Think of a message object - // that has an Object field but tries to send an Enum subclass in it.) - // In that case, the SerializerRegistration object we get back isn't - // really going to be capable of recreating the object on the other - // end because it won't know what class to use. This only comes up - // in writeclassAndObejct() because we just wrote an ID to a more generic - // class than will be readable on the other end. The check is simple, though. - if( reg.getType() != object.getClass() ) { - throw new IllegalArgumentException("Class has not been registered:" - + object.getClass() + " but resolved to generic serializer for:" + reg.getType()); - } + kryos.get().writeClassAndObject(kryoOutput, object); // oos.writeObject(object); - reg.getSerializer().writeObject(buffer, object); + buffer.put(kryoOutput.toBytes()); + kryoOutput.flush(); + kryoOutput.close(); // kryo output must be closed as well } - /** - * Read an object from the buffer, effectively deserializing it. - * - * @param data The buffer to read from. - * @param c The class of the object. - * @return The object read. - * @throws IOException If deserializing fails. - */ - public abstract T readObject(ByteBuffer data, Class c) throws IOException; - - /** - * Write an object to the buffer, effectively serializing it. - * - * @param buffer The buffer to write to. - * @param object The object to serialize. - * @throws IOException If serializing fails. - */ - public abstract void writeObject(ByteBuffer buffer, Object object) throws IOException; - - /** - * Registration for when a serializer may need to cache something. - * - * Override to use. - * - * @param clazz The class that has been registered to the serializer. - */ - public void initialize(Class clazz) { } } diff --git a/jme3-networking/src/main/java/com/jme3/network/serializing/SerializerRegistration.java b/jme3-networking/src/main/java/com/jme3/network/serializing/SerializerRegistration.java deleted file mode 100644 index 373d969eb5..0000000000 --- a/jme3-networking/src/main/java/com/jme3/network/serializing/SerializerRegistration.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (c) 2009-2012 jMonkeyEngine - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of 'jMonkeyEngine' nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package com.jme3.network.serializing; - -/** - * A SerializerRegistration represents a connection between a class, and - * its serializer. It also includes the class ID, as a short. - * - * @author Lars Wesselius - */ -public final class SerializerRegistration { - private Serializer serializer; - private short id; - private Class type; - - public SerializerRegistration(Serializer serializer, Class cls, short id) { - this.serializer = serializer; - type = cls; - this.id = id; - } - - /** - * Get the serializer. - * - * @return The serializer. - */ - public Serializer getSerializer() { - return serializer; - } - - /** - * Get the ID. - * - * @return The ID. - */ - public short getId() { - return id; - } - - /** - * Get the class type. - * - * @return The class type. - */ - public Class getType() { - return type; - } - - public String toString() { - return "SerializerRegistration[" + id + ", " + type + ", " + serializer + "]"; - } -} diff --git a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/ArraySerializer.java b/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/ArraySerializer.java deleted file mode 100644 index 564f4a06e3..0000000000 --- a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/ArraySerializer.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Copyright (c) 2009-2012 jMonkeyEngine, Java Game Networking - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of 'jMonkeyEngine' nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package com.jme3.network.serializing.serializers; - -import com.jme3.network.serializing.Serializer; -import java.io.IOException; -import java.lang.reflect.Array; -import java.lang.reflect.Modifier; -import java.nio.ByteBuffer; - -/** - * Array serializer - * - * @author Nathan Sweet - */ -@SuppressWarnings("unchecked") -public class ArraySerializer extends Serializer { - private int[] getDimensions (Object array) { - int depth = 0; - Class nextClass = array.getClass().getComponentType(); - while (nextClass != null) { - depth++; - nextClass = nextClass.getComponentType(); - } - int[] dimensions = new int[depth]; - dimensions[0] = Array.getLength(array); - if (depth > 1) collectDimensions(array, 1, dimensions); - return dimensions; - } - - private void collectDimensions (Object array, int dimension, int[] dimensions) { - boolean elementsAreArrays = dimension < dimensions.length - 1; - for (int i = 0, s = Array.getLength(array); i < s; i++) { - Object element = Array.get(array, i); - if (element == null) continue; - dimensions[dimension] = Math.max(dimensions[dimension], Array.getLength(element)); - if (elementsAreArrays) collectDimensions(element, dimension + 1, dimensions); - } - } - - public T readObject(ByteBuffer data, Class c) throws IOException { - byte dimensionCount = data.get(); - if (dimensionCount == 0) - return null; - - int[] dimensions = new int[dimensionCount]; - for (int i = 0; i < dimensionCount; i++) - dimensions[i] = data.getInt(); - - Serializer elementSerializer = null; - - Class elementClass = c; - while (elementClass.getComponentType() != null) - elementClass = elementClass.getComponentType(); - - if (Modifier.isFinal(elementClass.getModifiers())) elementSerializer = Serializer.getSerializer(elementClass); - // Create array and read in the data. - T array = (T)Array.newInstance(elementClass, dimensions); - readArray(elementSerializer, elementClass, data, array, 0, dimensions); - return array; - } - - public void writeObject(ByteBuffer buffer, Object object) throws IOException { - if (object == null){ - buffer.put((byte)0); - return; - } - - int[] dimensions = getDimensions(object); - buffer.put((byte)dimensions.length); - for (int dimension : dimensions) buffer.putInt(dimension); - Serializer elementSerializer = null; - - Class elementClass = object.getClass(); - while (elementClass.getComponentType() != null) { - elementClass = elementClass.getComponentType(); - } - - if (Modifier.isFinal(elementClass.getModifiers())) elementSerializer = Serializer.getSerializer(elementClass); - writeArray(elementSerializer, buffer, object, 0, dimensions.length); - } - - private void writeArray(Serializer elementSerializer, ByteBuffer buffer, Object array, int dimension, int dimensionCount) throws IOException { - int length = Array.getLength(array); - if (dimension > 0) { - buffer.putInt(length); - } - // Write array data. - boolean elementsAreArrays = dimension < dimensionCount - 1; - for (int i = 0; i < length; i++) { - Object element = Array.get(array, i); - if (elementsAreArrays) { - if (element != null) writeArray(elementSerializer, buffer, element, dimension + 1, dimensionCount); - } else if (elementSerializer != null) { - elementSerializer.writeObject(buffer, element); - } else { - // Each element could be a different type. Store the class with the object. - Serializer.writeClassAndObject(buffer, element); - } - } - } - - private void readArray (Serializer elementSerializer, Class elementClass, ByteBuffer buffer, Object array, int dimension, int[] dimensions) throws IOException { - boolean elementsAreArrays = dimension < dimensions.length - 1; - int length; - if (dimension == 0) { - length = dimensions[0]; - } else { - length = buffer.getInt(); - } - for (int i = 0; i < length; i++) { - if (elementsAreArrays) { - // Nested array. - Object element = Array.get(array, i); - if (element != null) readArray(elementSerializer, elementClass, buffer, element, dimension + 1, dimensions); - } else if (elementSerializer != null) { - // Use same converter (and class) for all elements. - Array.set(array, i, elementSerializer.readObject(buffer, elementClass)); - } else { - // Each element could be a different type. Look up the class with the object. - Array.set(array, i, Serializer.readClassAndObject(buffer)); - } - } - } -} diff --git a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/BooleanSerializer.java b/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/BooleanSerializer.java deleted file mode 100644 index 2bfb8e62b6..0000000000 --- a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/BooleanSerializer.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2009-2012 jMonkeyEngine - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of 'jMonkeyEngine' nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package com.jme3.network.serializing.serializers; - -import com.jme3.network.serializing.Serializer; -import java.io.IOException; -import java.nio.ByteBuffer; - -/** - * Boolean serializer. - * - * @author Lars Wesselius - */ -@SuppressWarnings("unchecked") -public class BooleanSerializer extends Serializer { - - public Boolean readObject(ByteBuffer data, Class c) throws IOException { - return data.get() == 1; - } - - public void writeObject(ByteBuffer buffer, Object object) throws IOException { - buffer.put(((Boolean)object) ? (byte)1 : (byte)0); - } -} diff --git a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/ByteSerializer.java b/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/ByteSerializer.java deleted file mode 100644 index 4e085bbe6a..0000000000 --- a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/ByteSerializer.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2009-2012 jMonkeyEngine - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of 'jMonkeyEngine' nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package com.jme3.network.serializing.serializers; - -import com.jme3.network.serializing.Serializer; -import java.io.IOException; -import java.nio.ByteBuffer; - -/** - * Byte serializer. - * - * @author Lars Wesselius - */ -@SuppressWarnings("unchecked") -public class ByteSerializer extends Serializer { - - public Byte readObject(ByteBuffer data, Class c) throws IOException { - return data.get(); - } - - public void writeObject(ByteBuffer buffer, Object object) throws IOException { - buffer.put((Byte)object); - } -} diff --git a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/CharSerializer.java b/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/CharSerializer.java deleted file mode 100644 index 274bc30db1..0000000000 --- a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/CharSerializer.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2009-2012 jMonkeyEngine - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of 'jMonkeyEngine' nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package com.jme3.network.serializing.serializers; - -import com.jme3.network.serializing.Serializer; -import java.io.IOException; -import java.nio.ByteBuffer; - -/** - * Char serializer. - * - * @author Lars Wesselius - */ -@SuppressWarnings("unchecked") -public class CharSerializer extends Serializer { - - public Character readObject(ByteBuffer data, Class c) throws IOException { - return data.getChar(); - } - - public void writeObject(ByteBuffer buffer, Object object) throws IOException { - buffer.putChar((Character)object); - } -} diff --git a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/CollectionSerializer.java b/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/CollectionSerializer.java deleted file mode 100644 index 960e8be10f..0000000000 --- a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/CollectionSerializer.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (c) 2009-2012 jMonkeyEngine - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of 'jMonkeyEngine' nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package com.jme3.network.serializing.serializers; - -import com.jme3.network.serializing.Serializer; -import com.jme3.network.serializing.SerializerRegistration; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.logging.Level; - -/** - * Serializes collections. - * - * @author Lars Wesselius - */ -public class CollectionSerializer extends Serializer { - - @SuppressWarnings("unchecked") - public T readObject(ByteBuffer data, Class c) throws IOException { - int length = data.getInt(); - - Collection collection; - try { - collection = (Collection)c.newInstance(); - } catch (Exception e) { - log.log(Level.FINE, "[Serializer][???] Could not determine collection type. Using ArrayList."); - collection = new ArrayList(length); - } - - if (length == 0) return (T)collection; - - if (data.get() == (byte)1) { - SerializerRegistration reg = Serializer.readClass(data); - Class clazz = reg.getType(); - Serializer serializer = reg.getSerializer(); - - for (int i = 0; i != length; ++i) { - collection.add(serializer.readObject(data, clazz)); - } - } else { - for (int i = 0; i != length; ++i) { - collection.add(Serializer.readClassAndObject(data)); - } - } - return (T)collection; - } - - public void writeObject(ByteBuffer buffer, Object object) throws IOException { - Collection collection = (Collection)object; - int length = collection.size(); - - buffer.putInt(length); - if (length == 0) return; - - Iterator it = collection.iterator(); - Class elementClass = it.next().getClass(); - while (it.hasNext()) { - Object obj = it.next(); - - if (obj.getClass() != elementClass) { - elementClass = null; - break; - } - } - - if (elementClass != null) { - buffer.put((byte)1); - Serializer.writeClass(buffer, elementClass); - Serializer serializer = Serializer.getSerializer(elementClass); - - for (Object elem : collection) { - serializer.writeObject(buffer, elem); - } - } else { - buffer.put((byte)0); - for (Object elem : collection) { - Serializer.writeClassAndObject(buffer, elem); - } - } - } -} diff --git a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/DateSerializer.java b/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/DateSerializer.java deleted file mode 100644 index 5bd8c465aa..0000000000 --- a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/DateSerializer.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2009-2012 jMonkeyEngine - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of 'jMonkeyEngine' nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package com.jme3.network.serializing.serializers; - -import com.jme3.network.serializing.Serializer; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.util.Date; - -/** - * Date serializer. - * - * @author Lars Wesselius - */ -@SuppressWarnings("unchecked") -public class DateSerializer extends Serializer { - - public Date readObject(ByteBuffer data, Class c) throws IOException { - return new Date(data.getLong()); - } - - public void writeObject(ByteBuffer buffer, Object object) throws IOException { - buffer.putLong(((Date)object).getTime()); - } -} diff --git a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/DoubleSerializer.java b/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/DoubleSerializer.java deleted file mode 100644 index cb7494d9e6..0000000000 --- a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/DoubleSerializer.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2009-2012 jMonkeyEngine - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of 'jMonkeyEngine' nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package com.jme3.network.serializing.serializers; - -import com.jme3.network.serializing.Serializer; -import java.io.IOException; -import java.nio.ByteBuffer; - -/** - * Double serializer. - * - * @author Lars Wesselius - */ -@SuppressWarnings("unchecked") -public class DoubleSerializer extends Serializer { - - public Double readObject(ByteBuffer data, Class c) throws IOException { - return data.getDouble(); - } - - public void writeObject(ByteBuffer buffer, Object object) throws IOException { - buffer.putDouble((Double)object); - } -} diff --git a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/EnumSerializer.java b/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/EnumSerializer.java deleted file mode 100644 index 3b89f7d5a8..0000000000 --- a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/EnumSerializer.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) 2009-2012 jMonkeyEngine - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of 'jMonkeyEngine' nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package com.jme3.network.serializing.serializers; - -import com.jme3.network.serializing.Serializer; -import com.jme3.network.serializing.SerializerException; -import java.io.IOException; -import java.nio.ByteBuffer; - -/** - * Enum serializer. - * - * @author Lars Wesselius - */ -public class EnumSerializer extends Serializer { - public T readObject(ByteBuffer data, Class c) throws IOException { - try { - int ordinal = data.getInt(); - - if (ordinal == -1) return null; - T[] enumConstants = c.getEnumConstants(); - if (enumConstants == null) { - throw new SerializerException("Class has no enum constants:" + c + " Ordinal:" + ordinal); - } - return enumConstants[ordinal]; - } catch (IndexOutOfBoundsException ex) { - return null; - } - } - - public void writeObject(ByteBuffer buffer, Object object) throws IOException { - if (object == null) { - buffer.putInt(-1); - } else { - buffer.putInt(((Enum)object).ordinal()); - } - } -} diff --git a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/FieldSerializer.java b/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/FieldSerializer.java deleted file mode 100644 index 0d410bb4dd..0000000000 --- a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/FieldSerializer.java +++ /dev/null @@ -1,218 +0,0 @@ -/* - * Copyright (c) 2009-2012 jMonkeyEngine, Java Game Networking - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of 'jMonkeyEngine' nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package com.jme3.network.serializing.serializers; - -import com.jme3.network.serializing.Serializer; -import com.jme3.network.serializing.SerializerException; -import java.io.IOException; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.nio.BufferOverflowException; -import java.nio.ByteBuffer; -import java.util.*; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * The field serializer is the default serializer used for custom class. - * - * @author Lars Wesselius, Nathan Sweet - */ -public class FieldSerializer extends Serializer { - - static final Logger log = Logger.getLogger(FieldSerializer.class.getName()); - - private static Map savedFields = new HashMap(); - private static Map savedCtors = new HashMap(); - - protected void checkClass(Class clazz) { - - // See if the class has a public no-arg constructor - try { - savedCtors.put(clazz, clazz.getConstructor()); - return; - } catch( NoSuchMethodException e ) { - //throw new RuntimeException( "Registration error: no-argument constructor not found on:" + clazz ); - } - - // See if it has a non-public no-arg constructor - try { - Constructor ctor = clazz.getDeclaredConstructor(); - - // Make sure we can call it later. - ctor.setAccessible(true); - - savedCtors.put(clazz, ctor); - return; - } catch( NoSuchMethodException e ) { - } - - throw new RuntimeException( "Registration error: no-argument constructor not found on:" + clazz ); - } - - public void initialize(Class clazz) { - - checkClass(clazz); - - List fields = new ArrayList(); - - Class processingClass = clazz; - while (processingClass != Object.class ) { - Collections.addAll(fields, processingClass.getDeclaredFields()); - processingClass = processingClass.getSuperclass(); - } - - List cachedFields = new ArrayList(fields.size()); - for (Field field : fields) { - int modifiers = field.getModifiers(); - if (Modifier.isTransient(modifiers)) continue; - if (Modifier.isFinal(modifiers)) continue; - if (Modifier.isStatic(modifiers)) continue; - if (field.isSynthetic()) continue; - field.setAccessible(true); - - SavedField cachedField = new SavedField(); - cachedField.field = field; - - if (Modifier.isFinal(field.getType().getModifiers())) { - // The type of this field is implicit in the outer class - // definition and because the type is final, it can confidently - // be determined on the other end. - // Note: passing false to this method has the side-effect that field.getType() - // will be registered as a real class that can then be read/written - // directly as any other registered class. It should be safe to take - // an ID like this because Serializer.initialize() is only called - // during registration... so this is like nested registration and - // doesn't have any ordering problems. - // ...well, as long as the order of fields is consistent from one - // end to the next. - cachedField.serializer = Serializer.getSerializer(field.getType(), false); - } - - cachedFields.add(cachedField); - } - - Collections.sort(cachedFields, new Comparator() { - public int compare (SavedField o1, SavedField o2) { - return o1.field.getName().compareTo(o2.field.getName()); - } - }); - savedFields.put(clazz, cachedFields.toArray(new SavedField[cachedFields.size()])); - - - } - - @SuppressWarnings("unchecked") - public T readObject(ByteBuffer data, Class c) throws IOException { - - // Read the null/non-null marker - if (data.get() == 0x0) - return null; - - SavedField[] fields = savedFields.get(c); - - T object; - try { - Constructor ctor = (Constructor)savedCtors.get(c); - object = ctor.newInstance(); - } catch (Exception e) { - throw new SerializerException( "Error creating object of type:" + c, e ); - } - - for (SavedField savedField : fields) { - Field field = savedField.field; - Serializer serializer = savedField.serializer; - if( log.isLoggable(Level.FINER) ) { - log.log(Level.FINER, "Reading field:{0} using serializer:{1}", new Object[]{field, serializer}); - } - Object value; - - if (serializer != null) { - value = serializer.readObject(data, field.getType()); - } else { - value = Serializer.readClassAndObject(data); - } - try { - field.set(object, value); - } catch (IllegalAccessException e) { - throw new SerializerException( "Error reading object", e); - } - } - return object; - } - - public void writeObject(ByteBuffer buffer, Object object) throws IOException { - - // Add the null/non-null marker - buffer.put( (byte)(object != null ? 0x1 : 0x0) ); - if (object == null) { - // Nothing left to do - return; - } - - SavedField[] fields = savedFields.get(object.getClass()); - if (fields == null) - throw new IOException("The " + object.getClass() + " is not registered" - + " in the serializer!"); - - for (SavedField savedField : fields) { - Object val = null; - try { - val = savedField.field.get(object); - } catch (IllegalAccessException e) { - throw new SerializerException("Unable to access field:" + savedField.field + " on:" + object, e); - } - Serializer serializer = savedField.serializer; - if( log.isLoggable(Level.FINER) ) { - log.log(Level.FINER, "Writing field:{0} using serializer:{1}", new Object[]{savedField.field, serializer}); - } - - try { - if (serializer != null) { - serializer.writeObject(buffer, val); - } else { - Serializer.writeClassAndObject(buffer, val); - } - } catch (BufferOverflowException boe) { - throw boe; - } catch (Exception e) { - throw new SerializerException( "Error writing object for field:" + savedField.field, e ); - } - } - } - - private final class SavedField { - public Field field; - public Serializer serializer; - } -} diff --git a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/FloatSerializer.java b/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/FloatSerializer.java deleted file mode 100644 index 519b43550f..0000000000 --- a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/FloatSerializer.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2009-2012 jMonkeyEngine - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of 'jMonkeyEngine' nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package com.jme3.network.serializing.serializers; - -import com.jme3.network.serializing.Serializer; -import java.io.IOException; -import java.nio.ByteBuffer; - -/** - * Float serializer. - * - * @author Lars Wesselius - */ -@SuppressWarnings("unchecked") -public class FloatSerializer extends Serializer { - - public Float readObject(ByteBuffer data, Class c) throws IOException { - return data.getFloat(); - } - - public void writeObject(ByteBuffer buffer, Object object) throws IOException { - buffer.putFloat((Float)object); - } -} diff --git a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/GZIPSerializer.java b/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/GZIPSerializer.java deleted file mode 100644 index 7579e84c57..0000000000 --- a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/GZIPSerializer.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (c) 2009-2012 jMonkeyEngine - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of 'jMonkeyEngine' nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package com.jme3.network.serializing.serializers; - -import com.jme3.network.Message; -import com.jme3.network.message.GZIPCompressedMessage; -import com.jme3.network.serializing.Serializer; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.util.zip.GZIPInputStream; -import java.util.zip.GZIPOutputStream; - -/** - * Serializes GZIP messages. - * - * @author Lars Wesselius - */ -public class GZIPSerializer extends Serializer { - - @SuppressWarnings("unchecked") - public T readObject(ByteBuffer data, Class c) throws IOException { - try - { - GZIPCompressedMessage result = new GZIPCompressedMessage(); - - byte[] byteArray = new byte[data.remaining()]; - - data.get(byteArray); - - GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(byteArray)); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - - byte[] tmp = new byte[9012]; - int read; - - while (in.available() > 0 && ((read = in.read(tmp)) > 0)) { - out.write(tmp, 0, read); - } - - result.setMessage((Message)Serializer.readClassAndObject(ByteBuffer.wrap(out.toByteArray()))); - return (T)result; - } - catch (Exception e) { - e.printStackTrace(); - throw new IOException(e.toString()); - } - } - - public void writeObject(ByteBuffer buffer, Object object) throws IOException { - if (!(object instanceof GZIPCompressedMessage)) return; - Message message = ((GZIPCompressedMessage)object).getMessage(); - - ByteBuffer tempBuffer = ByteBuffer.allocate(512000); - Serializer.writeClassAndObject(tempBuffer, message); - - ByteArrayOutputStream byteArrayOutput = new ByteArrayOutputStream(); - GZIPOutputStream gzipOutput = new GZIPOutputStream(byteArrayOutput); - - tempBuffer.flip(); - gzipOutput.write(tempBuffer.array(), 0, tempBuffer.limit()); - gzipOutput.flush(); - gzipOutput.finish(); - gzipOutput.close(); - - buffer.put(byteArrayOutput.toByteArray()); - } -} diff --git a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/IntSerializer.java b/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/IntSerializer.java deleted file mode 100644 index db8a4954cb..0000000000 --- a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/IntSerializer.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2009-2012 jMonkeyEngine - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of 'jMonkeyEngine' nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package com.jme3.network.serializing.serializers; - -import com.jme3.network.serializing.Serializer; -import java.io.IOException; -import java.nio.ByteBuffer; - -/** - * The Integer serializer serializes...integers. Big surprise. - * - * @author Lars Wesselius - */ -@SuppressWarnings("unchecked") -public class IntSerializer extends Serializer { - - public Integer readObject(ByteBuffer data, Class c) throws IOException { - return data.getInt(); - } - - public void writeObject(ByteBuffer buffer, Object object) throws IOException { - buffer.putInt((Integer)object); - } -} diff --git a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/LongSerializer.java b/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/LongSerializer.java deleted file mode 100644 index 28ebb28caf..0000000000 --- a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/LongSerializer.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2009-2012 jMonkeyEngine - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of 'jMonkeyEngine' nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package com.jme3.network.serializing.serializers; - -import com.jme3.network.serializing.Serializer; -import java.io.IOException; -import java.nio.ByteBuffer; - -/** - * The Long serializer. - * - * @author Lars Wesselius - */ -@SuppressWarnings("unchecked") -public class LongSerializer extends Serializer { - - public Long readObject(ByteBuffer data, Class c) throws IOException { - return data.getLong(); - } - - public void writeObject(ByteBuffer buffer, Object object) throws IOException { - buffer.putLong((Long)object); - } -} diff --git a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/MapSerializer.java b/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/MapSerializer.java deleted file mode 100644 index 4d41c57f0f..0000000000 --- a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/MapSerializer.java +++ /dev/null @@ -1,189 +0,0 @@ -/* - * Copyright (c) 2009-2012 jMonkeyEngine - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of 'jMonkeyEngine' nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package com.jme3.network.serializing.serializers; - -import com.jme3.network.serializing.Serializer; -import com.jme3.network.serializing.SerializerRegistration; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.logging.Level; - -public class MapSerializer extends Serializer { - - /* - - Structure: - - struct Map { - INT length - BYTE flags = { 0x01 = all keys have the same type, - 0x02 = all values have the same type } - if (flags has 0x01 set) - SHORT keyType - if (flags has 0x02 set) - SHORT valType - - struct MapEntry[length] entries { - if (flags does not have 0x01 set) - SHORT keyType - OBJECT key - - if (flags does not have 0x02 set) - SHORT valType - OBJECT value - } - } - - */ - - @SuppressWarnings("unchecked") - public T readObject(ByteBuffer data, Class c) throws IOException { - int length = data.getInt(); - - Map map; - try { - map = (Map)c.newInstance(); - } catch (Exception e) { - log.log(Level.WARNING, "[Serializer][???] Could not determine map type. Using HashMap."); - map = new HashMap(); - } - - if (length == 0) return (T)map; - - int flags = data.get() & 0xff; - boolean uniqueKeys = (flags & 0x01) == 0; - boolean uniqueVals = (flags & 0x02) == 0; - - Class keyClazz = null; - Class valClazz = null; - Serializer keySerial = null; - Serializer valSerial = null; - if (!uniqueKeys){ - SerializerRegistration reg = Serializer.readClass(data); - keyClazz = reg.getType(); - keySerial = reg.getSerializer(); - } - if (!uniqueVals){ - SerializerRegistration reg = Serializer.readClass(data); - valClazz = reg.getType(); - valSerial = reg.getSerializer(); - } - - for (int i = 0; i < length; i++){ - Object key; - Object value; - if (uniqueKeys){ - key = Serializer.readClassAndObject(data); - }else{ - key = keySerial.readObject(data, keyClazz); - } - if (uniqueVals){ - value = Serializer.readClassAndObject(data); - }else{ - value = valSerial.readObject(data, valClazz); - } - - map.put(key, value); - } - - return (T)map; - } - - @SuppressWarnings("unchecked") - public void writeObject(ByteBuffer buffer, Object object) throws IOException { - Map map = (Map)object; - int length = map.size(); - - buffer.putInt(length); - if (length == 0) return; - - - Set entries = map.entrySet(); - - Iterator it = entries.iterator(); - - Entry entry = it.next(); - Class keyClass = entry.getKey().getClass(); - Class valClass = entry.getValue().getClass(); - while (it.hasNext()) { - entry = it.next(); - - if (entry.getKey().getClass() != keyClass){ - keyClass = null; - if (valClass == null) - break; - } - if (entry.getValue().getClass() != valClass){ - valClass = null; - if (keyClass == null) - break; - } - } - - boolean uniqueKeys = keyClass == null; - boolean uniqueVals = valClass == null; - int flags = 0; - if (!uniqueKeys) flags |= 0x01; - if (!uniqueVals) flags |= 0x02; - buffer.put( (byte) flags ); - - Serializer keySerial = null, valSerial = null; - if (!uniqueKeys){ - Serializer.writeClass(buffer, keyClass); - keySerial = Serializer.getSerializer(keyClass); - } - if (!uniqueVals){ - Serializer.writeClass(buffer, valClass); - valSerial = Serializer.getSerializer(valClass); - } - - it = entries.iterator(); - while (it.hasNext()) { - entry = it.next(); - if (uniqueKeys){ - Serializer.writeClassAndObject(buffer, entry.getKey()); - }else{ - keySerial.writeObject(buffer, entry.getKey()); - } - if (uniqueVals){ - Serializer.writeClassAndObject(buffer, entry.getValue()); - }else{ - valSerial.writeObject(buffer, entry.getValue()); - } - } - } -} diff --git a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/SavableSerializer.java b/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/SavableSerializer.java deleted file mode 100644 index c91c8e4c5c..0000000000 --- a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/SavableSerializer.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright (c) 2009-2012 jMonkeyEngine - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of 'jMonkeyEngine' nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package com.jme3.network.serializing.serializers; - -import com.jme3.export.Savable; -import com.jme3.export.binary.BinaryExporter; -import com.jme3.export.binary.BinaryImporter; -import com.jme3.network.serializing.Serializer; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.ByteBuffer; - -public class SavableSerializer extends Serializer { - - private BinaryExporter exporter = new BinaryExporter(); - private BinaryImporter importer = new BinaryImporter(); - - private static class BufferOutputStream extends OutputStream { - - ByteBuffer output; - - public BufferOutputStream(ByteBuffer output){ - this.output = output; - } - - @Override - public void write(int b) throws IOException { - output.put( (byte) b ); - } - - @Override - public void write(byte[] b){ - output.put(b); - } - - @Override - public void write(byte[] b, int off, int len){ - output.put(b, off, len); - } - } - - private static class BufferInputStream extends InputStream { - - ByteBuffer input; - - public BufferInputStream(ByteBuffer input){ - this.input = input; - } - - @Override - public int read() throws IOException { - if (input.remaining() == 0) - return -1; - else - return input.get() & 0xff; - } - - @Override - public int read(byte[] b){ - return read(b, 0, b.length); - } - - @Override - public int read(byte[] b, int off, int len){ - int toRead = len > input.remaining() ? input.remaining() : len; - input.get(b, off, toRead); - return toRead; - } - - } - - @Override - @SuppressWarnings("unchecked") - public T readObject(ByteBuffer data, Class c) throws IOException { - BufferInputStream in = new BufferInputStream(data); - Savable s = importer.load(in); - in.close(); - return (T) s; - } - - @Override - public void writeObject(ByteBuffer buffer, Object object) throws IOException { - Savable s = (Savable) object; - BufferOutputStream out = new BufferOutputStream(buffer); - exporter.save(s, out); - out.close(); - } - -} diff --git a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/SerializableSerializer.java b/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/SerializableSerializer.java deleted file mode 100644 index 32eb2af2e1..0000000000 --- a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/SerializableSerializer.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) 2009-2012 jMonkeyEngine - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of 'jMonkeyEngine' nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package com.jme3.network.serializing.serializers; - -import com.jme3.network.serializing.Serializer; -import java.io.IOException; -import java.io.Serializable; -import java.nio.ByteBuffer; - -/** - * Serializes uses Java built-in method. - * - * TODO - * @author Lars Wesselius - */ -@SuppressWarnings("unchecked") -public class SerializableSerializer extends Serializer { - - public Serializable readObject(ByteBuffer data, Class c) throws IOException { - throw new UnsupportedOperationException( "Serializable serialization not supported." ); - } - - public void writeObject(ByteBuffer buffer, Object object) throws IOException { - throw new UnsupportedOperationException( "Serializable serialization not supported." ); - } -} diff --git a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/ShortSerializer.java b/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/ShortSerializer.java deleted file mode 100644 index 5131626667..0000000000 --- a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/ShortSerializer.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2009-2012 jMonkeyEngine - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of 'jMonkeyEngine' nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package com.jme3.network.serializing.serializers; - -import com.jme3.network.serializing.Serializer; -import java.io.IOException; -import java.nio.ByteBuffer; - -/** - * Short serializer. - * - * @author Lars Wesselius - */ -@SuppressWarnings("unchecked") -public class ShortSerializer extends Serializer { - public Short readObject(ByteBuffer data, Class c) throws IOException { - return data.getShort(); - } - - public void writeObject(ByteBuffer buffer, Object object) throws IOException { - buffer.putShort((Short)object); - } -} diff --git a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/StringSerializer.java b/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/StringSerializer.java deleted file mode 100644 index 3452bfa37d..0000000000 --- a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/StringSerializer.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (c) 2009-2012 jMonkeyEngine - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of 'jMonkeyEngine' nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package com.jme3.network.serializing.serializers; - -import com.jme3.network.serializing.Serializer; -import java.io.IOException; -import java.nio.BufferOverflowException; -import java.nio.ByteBuffer; - -/** - * String serializer. - * - * @author Lars Wesselius, Paul Speed - */ -@SuppressWarnings("unchecked") -public class StringSerializer extends Serializer { - - public static void writeString( String s, ByteBuffer buffer ) throws IOException { - if (s == null) { - // Write that it's 0. - buffer.put((byte)0); - return; - } - byte[] stringBytes = s.getBytes("UTF-8"); - int bufferLength = stringBytes.length; - - try { - if (bufferLength <= Byte.MAX_VALUE) { - buffer.put((byte)1); - buffer.put((byte)bufferLength); - } else if (bufferLength <= Short.MAX_VALUE) { - buffer.put((byte)2); - buffer.putShort((short)bufferLength); - } else { - buffer.put((byte)3); - buffer.putInt(bufferLength); - } - buffer.put(stringBytes); - } - catch (BufferOverflowException e) { - e.printStackTrace(); - } - } - - public static String readString( ByteBuffer data ) throws IOException { - int length = -1; - byte type = data.get(); - if (type == (byte)0) { - return null; - } else if (type == (byte)1) { - // Byte - length = data.get(); - } else if (type == (byte)2) { - // Short - length = data.getShort(); - } else if (type == (byte)3) { - // Int - length = data.getInt(); - } - if (length == -1) throw new IOException("Could not read String: Invalid length identifier."); - - byte[] buffer = new byte[length]; - data.get(buffer); - return new String(buffer, "UTF-8"); - } - - public String readObject(ByteBuffer data, Class c) throws IOException { - return readString(data); - } - - public void writeObject(ByteBuffer buffer, Object object) throws IOException { - String string = (String)object; - - writeString(string, buffer); - } -} diff --git a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/Vector3Serializer.java b/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/Vector3Serializer.java deleted file mode 100644 index 685dc5b9e5..0000000000 --- a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/Vector3Serializer.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2009-2012 jMonkeyEngine - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of 'jMonkeyEngine' nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package com.jme3.network.serializing.serializers; - -import com.jme3.math.Vector3f; -import com.jme3.network.serializing.Serializer; -import java.io.IOException; -import java.nio.ByteBuffer; - -/** - * @author Kirill Vainer - */ -@SuppressWarnings("unchecked") -public class Vector3Serializer extends Serializer { - - public Vector3f readObject(ByteBuffer data, Class c) throws IOException { - Vector3f vec3 = new Vector3f(); - vec3.x = data.getFloat(); - vec3.y = data.getFloat(); - vec3.z = data.getFloat(); - return vec3; - } - - public void writeObject(ByteBuffer buffer, Object object) throws IOException { - Vector3f vec3 = (Vector3f) object; - buffer.putFloat(vec3.x); - buffer.putFloat(vec3.y); - buffer.putFloat(vec3.z); - } -} diff --git a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/ZIPSerializer.java b/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/ZIPSerializer.java deleted file mode 100644 index ad7d7162d9..0000000000 --- a/jme3-networking/src/main/java/com/jme3/network/serializing/serializers/ZIPSerializer.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (c) 2009-2012 jMonkeyEngine - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of 'jMonkeyEngine' nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package com.jme3.network.serializing.serializers; - -import com.jme3.network.Message; -import com.jme3.network.message.ZIPCompressedMessage; -import com.jme3.network.serializing.Serializer; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; -import java.util.zip.ZipOutputStream; - -/** - * Serializes ZIP messages. - * - * @author Lars Wesselius - */ -public class ZIPSerializer extends Serializer { - - @SuppressWarnings("unchecked") - public T readObject(ByteBuffer data, Class c) throws IOException { - try - { - ZIPCompressedMessage result = new ZIPCompressedMessage(); - - byte[] byteArray = new byte[data.remaining()]; - - data.get(byteArray); - - ZipInputStream in = new ZipInputStream(new ByteArrayInputStream(byteArray)); - in.getNextEntry(); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - - byte[] tmp = new byte[9012]; - int read; - - while (in.available() > 0 && ((read = in.read(tmp)) > 0)) { - out.write(tmp, 0, read); - } - - in.closeEntry(); - out.flush(); - in.close(); - - result.setMessage((Message)Serializer.readClassAndObject(ByteBuffer.wrap(out.toByteArray()))); - return (T)result; - } - catch (Exception e) { - e.printStackTrace(); - throw new IOException(e.toString()); - } - } - - public void writeObject(ByteBuffer buffer, Object object) throws IOException { - if (!(object instanceof ZIPCompressedMessage)) return; - - ZIPCompressedMessage zipMessage = (ZIPCompressedMessage)object; - Message message = zipMessage.getMessage(); - ByteBuffer tempBuffer = ByteBuffer.allocate(512000); - Serializer.writeClassAndObject(tempBuffer, message); - - ByteArrayOutputStream byteArrayOutput = new ByteArrayOutputStream(); - ZipOutputStream zipOutput = new ZipOutputStream(byteArrayOutput); - zipOutput.setLevel(zipMessage.getLevel()); - - ZipEntry zipEntry = new ZipEntry("zip"); - - zipOutput.putNextEntry(zipEntry); - tempBuffer.flip(); - zipOutput.write(tempBuffer.array(), 0, tempBuffer.limit()); - zipOutput.flush(); - zipOutput.closeEntry(); - zipOutput.close(); - - buffer.put(byteArrayOutput.toByteArray()); - } -} diff --git a/jme3-networking/src/main/java/com/jme3/network/service/AbstractClientService.java b/jme3-networking/src/main/java/com/jme3/network/service/AbstractClientService.java index d1a848dac4..b08b4b9ce6 100644 --- a/jme3-networking/src/main/java/com/jme3/network/service/AbstractClientService.java +++ b/jme3-networking/src/main/java/com/jme3/network/service/AbstractClientService.java @@ -48,7 +48,8 @@ public abstract class AbstractClientService extends AbstractService { - - static final Logger log = Logger.getLogger(SerializerRegistrationsMessage.class.getName()); - - @Override - protected void onInitialize( ClientServiceManager serviceManager ) { - - // Make sure our message type is registered if it isn't already - if( Serializer.getExactSerializerRegistration(SerializerRegistrationsMessage.class) == null ) { - // This is the minimum we'd need just to be able to register - // the rest... otherwise we can't even receive this message. - Serializer.registerClass(SerializerRegistrationsMessage.class); - Serializer.registerClass(SerializerRegistrationsMessage.Registration.class); - } else { - log.log(Level.INFO, "Skipping registration of SerializerRegistrationsMessage."); - } - - // Add our listener for that message type - serviceManager.getClient().addMessageListener(this, SerializerRegistrationsMessage.class); - } - - @Override - public void messageReceived( Client source, Message m ) { - // We only wait for one kind of message... - SerializerRegistrationsMessage msg = (SerializerRegistrationsMessage)m; - msg.registerAll(); - } -} +//@com.jme3.network.serializing.Serializable +//public class ClientSerializerRegistrationsService extends AbstractClientService +// implements MessageListener, Serializable { +// +//// static final Logger log = Logger.getLogger(SerializerRegistrationsMessage.class.getName()); +// +// @Override +// protected void onInitialize( ClientServiceManager serviceManager ) { +// +// // Make sure our message type is registered if it isn't already +//// if( Serializer.getExactSerializerRegistration(SerializerRegistrationsMessage.class) == null ) { +// // This is the minimum we'd need just to be able to register +// // the rest... otherwise we can't even receive this message. +//// Serializer.registerClass(SerializerRegistrationsMessage.class); +//// Serializer.registerClass(SerializerRegistrationsMessage.Registration.class); +//// } else { +// log.log(Level.INFO, "Skipping registration of SerializerRegistrationsMessage."); +//// } +// +// // Add our listener for that message type +//// serviceManager.getClient().addMessageListener(this, SerializerRegistrationsMessage.class); +// } +// +// @Override +// public void messageReceived( Client source, AbstractMessage m ) { +// // We only wait for one kind of message... +// SerializerRegistrationsMessage msg = (SerializerRegistrationsMessage)m; +// msg.registerAll(); +// } +//} diff --git a/jme3-networking/src/main/java/com/jme3/network/service/serializer/ServerSerializerRegistrationsService.java b/jme3-networking/src/main/java/com/jme3/network/service/serializer/ServerSerializerRegistrationsService.java index 8af8395c38..00596c1887 100644 --- a/jme3-networking/src/main/java/com/jme3/network/service/serializer/ServerSerializerRegistrationsService.java +++ b/jme3-networking/src/main/java/com/jme3/network/service/serializer/ServerSerializerRegistrationsService.java @@ -34,7 +34,7 @@ import com.jme3.network.HostedConnection; import com.jme3.network.Server; -import com.jme3.network.message.SerializerRegistrationsMessage; +//import com.jme3.network.message.SerializerRegistrationsMessage; import com.jme3.network.serializing.Serializer; import com.jme3.network.service.AbstractHostedService; import com.jme3.network.service.HostedServiceManager; @@ -50,15 +50,20 @@ public class ServerSerializerRegistrationsService extends AbstractHostedService @Override protected void onInitialize( HostedServiceManager serviceManager ) { // Make sure our message type is registered - Serializer.registerClass(SerializerRegistrationsMessage.class); - Serializer.registerClass(SerializerRegistrationsMessage.Registration.class); +// Serializer.registerClass(SerializerRegistrationsMessage.class); +// Serializer.registerClass(SerializerRegistrationsMessage.Registration.class); } @Override public void start() { // Compile the registrations into a message we will // send to all connecting clients - SerializerRegistrationsMessage.compile(); +// SerializerRegistrationsMessage.compile(); + } + + @Override + public void stop() { +// Serializer.setReadOnly(false); } @Override @@ -67,6 +72,6 @@ public void connectionAdded(Server server, HostedConnection hc) { super.connectionAdded(server, hc); // Send the client the registration information - hc.send(SerializerRegistrationsMessage.INSTANCE); +// hc.send(SerializerRegistrationsMessage.INSTANCE); } } diff --git a/jme3-networking/src/main/java/com/jme3/network/util/AbstractMessageDelegator.java b/jme3-networking/src/main/java/com/jme3/network/util/AbstractMessageDelegator.java index a73496ea85..6a0c5908bf 100644 --- a/jme3-networking/src/main/java/com/jme3/network/util/AbstractMessageDelegator.java +++ b/jme3-networking/src/main/java/com/jme3/network/util/AbstractMessageDelegator.java @@ -32,7 +32,8 @@ package com.jme3.network.util; -import com.jme3.network.Message; +import com.jme3.network.AbstractMessage; +//import com.jme3.network.Message; import com.jme3.network.MessageConnection; import com.jme3.network.MessageListener; import java.lang.reflect.InvocationTargetException; @@ -116,7 +117,7 @@ protected boolean isValidMethod( Method m, Class messageType ) { } } - if( messageType == null && !Message.class.isAssignableFrom(parms[messageIndex]) ) { + if( messageType == null && !AbstractMessage.class.isAssignableFrom(parms[messageIndex]) ) { log.finest("Second paramter is not a Message or subclass."); return false; } @@ -280,7 +281,7 @@ protected Method getMethod( Class c ) { * on the delegate returned by getSourceDelegate(). */ @Override - public void messageReceived( S source, Message msg ) { + public void messageReceived( S source, AbstractMessage msg ) { if( msg == null ) { return; } diff --git a/jme3-networking/src/test/java/com/jme3/network/ComplexClass.java b/jme3-networking/src/test/java/com/jme3/network/ComplexClass.java new file mode 100644 index 0000000000..178085c851 --- /dev/null +++ b/jme3-networking/src/test/java/com/jme3/network/ComplexClass.java @@ -0,0 +1,29 @@ +package com.jme3.network; + + +public class ComplexClass implements java.io.Serializable { + public int a = 1; + public ComplexClass() {}; + public int method() { return 1; } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + a; + return result; + } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ComplexClass other = (ComplexClass) obj; + if (a != other.a) + return false; + return true; + } + +} \ No newline at end of file diff --git a/jme3-networking/src/test/java/com/jme3/network/ComplexSubClass.java b/jme3-networking/src/test/java/com/jme3/network/ComplexSubClass.java new file mode 100644 index 0000000000..2d806bfc22 --- /dev/null +++ b/jme3-networking/src/test/java/com/jme3/network/ComplexSubClass.java @@ -0,0 +1,30 @@ +package com.jme3.network; + + +public class ComplexSubClass extends ComplexClass implements java.io.Serializable { + public int a = 2; + public ComplexSubClass() {}; + public int method() { return 2; } + public int ownMethod() { return 1; } + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + a; + return result; + } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (!super.equals(obj)) + return false; + if (getClass() != obj.getClass()) + return false; + ComplexSubClass other = (ComplexSubClass) obj; + if (a != other.a) + return false; + return true; + } + +} \ No newline at end of file diff --git a/jme3-networking/src/test/java/com/jme3/network/DefaultServerTest.java b/jme3-networking/src/test/java/com/jme3/network/DefaultServerTest.java new file mode 100644 index 0000000000..378e454e45 --- /dev/null +++ b/jme3-networking/src/test/java/com/jme3/network/DefaultServerTest.java @@ -0,0 +1,112 @@ +package com.jme3.network; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + +import org.junit.Test; + +import com.jme3.network.kernel.tcp.SelectorKernel; +import com.jme3.network.base.DefaultServer; + +public class DefaultServerTest { + + @Test(expected=IllegalArgumentException.class) + public void createServerWithNoKernels() { + DefaultServer ds = new DefaultServer( "Test", 1, null, null ); + ds.close(); + } + + @Test(expected=IllegalStateException.class) + public void createServerWithAdditionalChannel() { + SelectorKernel reliable = mock(SelectorKernel.class); + DefaultServer ds = new DefaultServer( "Test", 1, reliable, null ); + ds.addChannel(2345); + ds.close(); + } + + @Test + public void createServer() { + SelectorKernel reliable = mock(SelectorKernel.class); + DefaultServer ds = new DefaultServer( "Test", 1, reliable, null ); + } + + @Test + public void createServerTwoChannels() { + SelectorKernel reliable = mock(SelectorKernel.class); + SelectorKernel fast = mock(SelectorKernel.class); + DefaultServer ds = new DefaultServer( "Test", 1, reliable, fast ); + } + + @Test + public void createServerTwoChannelsAddChannel() { + SelectorKernel reliable = mock(SelectorKernel.class); + SelectorKernel fast = mock(SelectorKernel.class); + DefaultServer ds = new DefaultServer( "Test", 1, reliable, fast ); + ds.addChannel(1234); + } + + @Test + public void createServerTwoChannelsAddManyChannels() { + SelectorKernel reliable = mock(SelectorKernel.class); + SelectorKernel fast = mock(SelectorKernel.class); + DefaultServer ds = new DefaultServer( "Test", 1, reliable, fast ); + for (int i = 1000; i < 10000; i++) + ds.addChannel(i); + } + + @Test(expected=IllegalArgumentException.class) + public void createServerTwoChannelsAddChannelIllegalPort() { + SelectorKernel reliable = mock(SelectorKernel.class); + SelectorKernel fast = mock(SelectorKernel.class); + DefaultServer ds = new DefaultServer( "Test", 1, reliable, fast ); + ds.addChannel(68000); + } + + @Test + public void createServerAndRun() { + SelectorKernel reliable = mock(SelectorKernel.class); + DefaultServer ds = new DefaultServer( "Test", 1, reliable, null ); + ds.start(); + ds.close(); + } + + @Test + public void testcreateServerAndRunIsRunning() { + SelectorKernel reliable = mock(SelectorKernel.class); + DefaultServer ds = new DefaultServer( "Test", 1, reliable, null ); + ds.start(); + assertTrue(ds.isRunning()); + ds.close(); + } + + @Test(expected=IllegalStateException.class) + public void createServerAndClose() { + SelectorKernel reliable = mock(SelectorKernel.class); + DefaultServer ds = new DefaultServer( "Test", 1, reliable, null ); + ds.close(); + } + + + + @Test + public void testBroadcastMessage() { + SelectorKernel reliable = mock(SelectorKernel.class); + DefaultServer ds = new DefaultServer( "Test", 1, reliable, null ); + ds.start(); + ds.broadcast(new AbstractMessage() { + private boolean reliable; + @Override + public AbstractMessage setReliable(boolean f) { + this.reliable = f; + return this; + } + + @Override + public boolean isReliable() { + return reliable; + } + }); + + ds.close(); + } +} diff --git a/jme3-networking/src/test/java/com/jme3/network/ThroughputTest.java b/jme3-networking/src/test/java/com/jme3/network/ThroughputTest.java new file mode 100644 index 0000000000..a238fd9786 --- /dev/null +++ b/jme3-networking/src/test/java/com/jme3/network/ThroughputTest.java @@ -0,0 +1,147 @@ +package com.jme3.network; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.ArrayList; + +import org.junit.Before; +import org.junit.Test; + +import com.jme3.network.kernel.KernelException; + +public class ThroughputTest { + + private long recvMsgs; + private long msgsToSend = 1000; + + @Before + public void setup() throws InterruptedException { + recvMsgs = 0; + Thread.sleep(500); + } + + @Test + public void testThroughputReliable() throws IOException, InterruptedException { + testThroughPut(msgsToSend); + assertEquals("must received as many messages as send ", msgsToSend, recvMsgs); + } + + public void testThroughPut(long numMsg) throws IOException, InterruptedException { +// Serializer.registerClass(TestMessage.class); +// Serializer.registerClass(ComplexClass.class); +// Serializer.registerClass(ComplexSubClass.class); + + Server server = null; + Client client = null; + TestThroughputC serverListener = null; + + boolean done = false; + + server = Network.createServer(5110, 5111); + + while(!done){ + try { + server.start(); + done = true; + } catch (KernelException e){ + Thread.sleep(100); + continue; + } finally { + Thread.sleep(100); + client = Network.connectToServer("localhost", 5110, 5111); + client.start(); + serverListener = new TestThroughputC(true); + } + } + + TestMessage test = new TestMessage();; + + client.addMessageListener(new TestThroughputC(false), TestMessage.class); + server.addMessageListener(serverListener, TestMessage.class); + + Thread.sleep(1); + + for( int i = 0; i < numMsg; i++ ) { + client.send(test); + Thread.sleep(0, 10); + } + + Thread.sleep(50); + + client.close(); + server.close(); + + serverListener = null; + client = null; + server = null; + System.gc(); + Thread.sleep(2000); + System.gc(); + } + + public static class TestMessage extends AbstractMessage implements java.io.Serializable { + + private String stringType = "nomnomnom"; + private int[] arrayType = {1,2,3,4,5,6}; + private String[] complexArrayType = {"hoi", "Doei!"}; + private String[] complexArrayUnicodeType = {"hoi", "Doeëi!"}; + private ArrayList complexArrayListType = new ArrayList<>(); + private ComplexSubClass A = new ComplexSubClass(); + + { + complexArrayListType.add("nomnomnomëëË"); + } + + public TestMessage() { + setReliable(true); + } + + public boolean testFields() { + int[] array = {1,2,3,4,5,6}; + String[] complexArray = {"hoi", "Doei!"}; + String[] complexUnicodeArray = {"hoi", "Doeëi!"}; + ArrayList arrayList = new ArrayList<>(); + arrayList.add("nomnomnomëëË"); + + assertEquals("nomnomnom" ,this.stringType); + assertArrayEquals(array, this.arrayType); + assertArrayEquals(complexArray, this.complexArrayType); + assertArrayEquals(complexUnicodeArray, this.complexArrayUnicodeType); + assertEquals(arrayList, this.complexArrayListType); + assertEquals(new ComplexSubClass(), this.A); + return true; + } + } + + class TestThroughputC implements MessageListener { //extends MessageAdapter { + + private boolean isOnServer; + + public TestThroughputC(boolean isOnServer) { + this.isOnServer = isOnServer; + } + + public boolean isOnServer() { return isOnServer; } + + @Override + public void messageReceived(MessageConnection source, AbstractMessage msg) { + + if (!isOnServer) { + recvMsgs++; + assertTrue(((TestMessage) msg).testFields()); + + } else { + if (source == null) { + System.out.println("Received a message from a not fully connected source, msg:" + msg); + } else { + source.send(msg); + } + } + } + + } + +} diff --git a/jme3-networking/src/test/java/com/jme3/network/serializing/SerializationIntegrationTest.java b/jme3-networking/src/test/java/com/jme3/network/serializing/SerializationIntegrationTest.java new file mode 100644 index 0000000000..5811f273fc --- /dev/null +++ b/jme3-networking/src/test/java/com/jme3/network/serializing/SerializationIntegrationTest.java @@ -0,0 +1,173 @@ +package com.jme3.network.serializing; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Test; + +import com.jme3.network.AbstractMessage; +import com.jme3.network.Client; +import com.jme3.network.HostedConnection; +//import com.jme3.network.Message; +import com.jme3.network.MessageListener; +import com.jme3.network.Network; +import com.jme3.network.Server; + +public class SerializationIntegrationTest { + + public class TestParameters implements java.io.Serializable { + public boolean z = true; + public byte b = -88; + public char c = 'Y'; + public short s = 9999; + public int i = 123; + public float f = -75.4e8f; + public long l = 9438345072805034L; + public double d = -854834.914703e88; + public int[] ia = new int[]{ 456, 678, 999 }; + + public List ls = new ArrayList(); + + public Map mp = new HashMap(); + + public Status status1 = Status.High; + public Status status2 = Status.Middle; + + public Date date = new Date(System.currentTimeMillis()); + + public TestParameters() { + ls.add("hello"); + ls.add(new SerializableObject(-22)); + mp.put("abc", new SerializableObject(555)); + } + } + + public static class SerializableObject implements java.io.Serializable { + + private int val; + + public SerializableObject() { + } + + public SerializableObject(int val) { + this.val = val; + } + + @Override + public String toString() { + return "SomeObject[val="+val+"]"; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + SerializableObject other = (SerializableObject) obj; + if (val != other.val) + return false; + return true; + } + } + + public enum Status { + High, + Middle, + Low; + } + + public static class TestSerializationMessage extends AbstractMessage implements java.io.Serializable { + + boolean z; + byte b; + char c; + short s; + int i; + float f; + long l; + double d; + int[] ia; + List ls; + Map mp; + Status status1; + Status status2; + Date date; + + public TestSerializationMessage() { + } + + public TestSerializationMessage(TestParameters p) { + super(true); // reliable + z = p.z; + b = p.b; + c = p.c; + s = p.s; + i = p.i; + f = p.f; + l = p.l; + d = p.d; + ia = p.ia; + ls = p.ls; + mp = p.mp; + status1 = p.status1; + status2 = p.status2; + date = p.date; + } + } + + public static class TestSerializationHandler implements MessageListener { + public TestSerializationMessage recievedMessage; + + public void messageReceived(HostedConnection source, AbstractMessage m) { + recievedMessage = (TestSerializationMessage) m; + } + } + + @Test + public void serializationTest() throws IOException, InterruptedException { +// Serializer.registerClass(SerializableObject.class); +// Serializer.registerClass(TestSerializationMessage.class); + + Server server = Network.createServer( 5110 ); + server.start(); + + Client client = Network.connectToServer( "localhost", 5110 ); + client.start(); + + TestParameters params = new TestParameters(); + TestSerializationMessage message = new TestSerializationMessage(params); + TestSerializationHandler handler = new TestSerializationHandler(); + + server.addMessageListener(handler, TestSerializationMessage.class); + client.send(message); + + Thread.sleep(100); + TestSerializationMessage recievedMessage = handler.recievedMessage; + + assertEquals(message.z, recievedMessage.z); + assertEquals(message.b, recievedMessage.b); + assertEquals(message.c, recievedMessage.c); + assertEquals(message.s, recievedMessage.s); + assertEquals(message.i, recievedMessage.i); + assertEquals(message.f, recievedMessage.f, Float.MIN_VALUE); + assertEquals(message.l, recievedMessage.l); + assertEquals(message.d, recievedMessage.d, Double.MIN_VALUE); + assertArrayEquals(message.ia, recievedMessage.ia); + assertEquals(message.ls, recievedMessage.ls); + assertEquals(message.mp, recievedMessage.mp); + assertEquals(message.status1, recievedMessage.status1); + assertEquals(message.status2, recievedMessage.status2); + assertEquals(message.date, recievedMessage.date); + } + +} diff --git a/jme3-networking/src/test/java/com/jme3/network/serializing/serializers/FieldSerializerTest.java b/jme3-networking/src/test/java/com/jme3/network/serializing/serializers/FieldSerializerTest.java new file mode 100644 index 0000000000..cc89461f29 --- /dev/null +++ b/jme3-networking/src/test/java/com/jme3/network/serializing/serializers/FieldSerializerTest.java @@ -0,0 +1,288 @@ +package com.jme3.network.serializing.serializers; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import org.junit.Test; + +import com.jme3.network.serializing.Serializer; + +public class FieldSerializerTest { + + public static class TestObject implements java.io.Serializable { + int val; + + public TestObject() { + } + + public TestObject(int val) { + this.val = val; + } + + @Override + public boolean equals(Object obj) { + return this.val == ((TestObject) obj).val; + } + } + + public static class TestObjectNoConstructor implements java.io.Serializable { + int val; + + public TestObjectNoConstructor(int val) { + this.val = val; + } + + @Override + public boolean equals(Object obj) { + return this.val == ((TestObjectNoConstructor) obj).val; + } + } + + public static class TestObjectPrivateConstructor implements java.io.Serializable { + int val; + + private TestObjectPrivateConstructor() { + } + + public TestObjectPrivateConstructor(int val) { + this.val = val; + } + + @Override + public boolean equals(Object obj) { + return this.val == ((TestObjectPrivateConstructor) obj).val; + } + } + + public static class TestObjectNoFields implements java.io.Serializable { + public TestObjectNoFields() { } + + @Override + public boolean equals(Object obj) { + return obj instanceof TestObjectNoFields; + } + } + + public static class TestObjectWithSuperclass extends TestObject implements java.io.Serializable { + String mes; + + public TestObjectWithSuperclass() { + } + + public TestObjectWithSuperclass(int val, String mes) { + this.val = val; + this.mes = mes; + } + + @Override + public boolean equals(Object obj) { + return this.val == ((TestObject) obj).val && + this.mes.equals(((TestObjectWithSuperclass) obj).mes); + } + } + + public static class TestObjectWithNestedCollections implements java.io.Serializable { + ArrayList> list; + + public TestObjectWithNestedCollections() { + } + + public TestObjectWithNestedCollections(ArrayList> list) { + this.list = list; + } + + @Override + public boolean equals(Object obj) { + ArrayList> otherList = ((TestObjectWithNestedCollections) obj).list; + if(list.size() != otherList.size()) return false; + + for(int i = 0; i < list.size(); i++) { + Map map = list.get(i); + Map otherMap = otherList.get(i); + + if(map == null) { + if(otherMap == null) continue; + else return false; + } + + if(map.size() != otherMap.size()) return false; + + Iterator it = map.keySet().iterator(); + while(it.hasNext()) { + String key = it.next(); + + Integer[] arr = map.get(key); + Integer[] otherArr = otherMap.get(key); + + if(!Arrays.equals(arr, otherArr)) return false; + } + + } + + return true; + } + } + + public static class TestObjectWithException implements java.io.Serializable { + RuntimeException exception; + + public TestObjectWithException() { + } + + public TestObjectWithException(RuntimeException exception) { + this.exception = exception; + } + + @Override + public boolean equals(Object obj) { + return exception.equals(((TestObjectWithException) obj).exception); + } + } + + @Test + public void serializationTestWithRegisterClass() throws IOException { + ByteBuffer buffer = ByteBuffer.allocate(1000); + TestObject obj = new TestObject(500); +// Serializer.registerClass(TestObject.class); + Serializer.writeObject(buffer, obj); + buffer.rewind(); + assertEquals(obj, Serializer.readObject(buffer)); + } + + @Test + public void serializationTestWithInitialize() throws IOException { + ByteBuffer buffer = ByteBuffer.allocate(1000); + ByteBuffer buffer2 = ByteBuffer.allocate(1000); + TestObject obj = new TestObject(1); + Serializer.writeObject(buffer, obj); + int bufferSize = buffer.position(); + buffer.rewind(); + assertEquals(obj, Serializer.readObject(buffer)); + + Serializer.writeObject(buffer2, obj); + int buffer2Size = buffer2.position(); + buffer2.rewind(); + assertEquals(obj, Serializer.readObject(buffer2)); + + System.out.println("serializationTestWithInitialize"); + System.out.println(buffer2Size - bufferSize); + System.out.println((double) bufferSize / buffer2Size); + } + + @Test + public void serializationTestWithPrivateConstructor() throws IOException { + ByteBuffer buffer = ByteBuffer.allocate(1000); + TestObjectPrivateConstructor obj = new TestObjectPrivateConstructor(240); + Serializer.writeObject(buffer, obj); + buffer.rewind(); + assertEquals(obj, Serializer.readObject(buffer)); + } + + @Test + public void serializationTestWithNoFields() throws IOException { + ByteBuffer buffer = ByteBuffer.allocate(1000); + TestObjectNoFields obj = new TestObjectNoFields(); + Serializer.writeObject(buffer, obj); + buffer.rewind(); + assertEquals(obj, Serializer.readObject(buffer)); + } + + @Test + public void serializationTestWithSuperclass() throws IOException { + ByteBuffer buffer = ByteBuffer.allocate(1000); + TestObjectWithSuperclass obj = new TestObjectWithSuperclass(24, "This is a message"); + + Serializer.writeObject(buffer, obj); + buffer.rewind(); + assertEquals(obj, Serializer.readObject(buffer)); + } + + @Test + public void serializationTestWithNestedCollectionsEmptyList() throws IOException { + ByteBuffer buffer = ByteBuffer.allocate(1000); + + ArrayList> list = new ArrayList>(); + TestObjectWithNestedCollections obj = new TestObjectWithNestedCollections(list); + Serializer.writeObject(buffer, obj); + buffer.rewind(); + assertEquals(obj, Serializer.readObject(buffer)); + } + + @Test + public void serializationTestWithNestedCollectionsEmptyMaps() throws IOException { + ByteBuffer buffer = ByteBuffer.allocate(1000); + ArrayList> list = new ArrayList>(); + list.add(new HashMap()); + list.add(null); + TestObjectWithNestedCollections obj = new TestObjectWithNestedCollections(list); + Serializer.writeObject(buffer, obj); + buffer.rewind(); + assertEquals(obj, Serializer.readObject(buffer)); + } + + @Test + public void serializationTestWithNestedCollectionsEmptyArrays() throws IOException { + ByteBuffer buffer = ByteBuffer.allocate(1000); + ArrayList> list = new ArrayList>(); + HashMap map = new HashMap(); + map.put("asdas", new Integer[0]); + map.put("", new Integer[]{}); + map.put(null, null); + list.add(map); + TestObjectWithNestedCollections obj = new TestObjectWithNestedCollections(list); + Serializer.writeObject(buffer, obj); + buffer.rewind(); + assertEquals(obj, Serializer.readObject(buffer)); + } + + @Test + public void serializationTestWithNestedCollectionsFull() throws IOException { + ByteBuffer buffer = ByteBuffer.allocate(1000); + ArrayList> list = new ArrayList>(); + + HashMap map = new HashMap(); + map.put("f34", new Integer[]{ 24, 8, -1 }); + map.put("aaa", null); + map.put(null, new Integer[]{ 0 }); + map.put("", new Integer[0]); + + HashMap map2 = new HashMap(); + map2.put("f34r3", new Integer[]{ 324234332 }); + + list.add(map); + list.add(map2); + list.add(new HashMap()); + list.add(null); + list.add(map); + + TestObjectWithNestedCollections obj = new TestObjectWithNestedCollections(list); + Serializer.writeObject(buffer, obj); + buffer.rewind(); + assertEquals(obj, Serializer.readObject(buffer)); + } + + // Doesn't work with Kryo! +// @Test +// public void serializationTestWithException() throws IOException { +// ByteBuffer buffer = ByteBuffer.allocate(1000); +// RuntimeException exception = new RuntimeException("Nothing happened!"); +// TestObjectWithException obj = new TestObjectWithException(exception); +// Serializer.writeObject(buffer, obj); +// buffer.rewind(); +// assertEquals(obj, Serializer.readObject(buffer)); +// } + +// @Test(expected=RuntimeException.class) +// public void checkClassTest() { +// Serializer.initialize(TestObjectNoConstructor.class); +// } +// + +} diff --git a/testresults.csv b/testresults.csv new file mode 100644 index 0000000000..4617bef5b4 --- /dev/null +++ b/testresults.csv @@ -0,0 +1,11 @@ +Serializing method,Reliable,Registration,Empty size,Empty sent,Empty received server,Empty received client,Empty received server+1,Empty received client+1,Simple size,Simple sent,Simple received server,Simple received client,Simple received server+1,Simple received client+1,Physics size,Physics sent,Physics received server,Physics received client,Physics received server+1,Physics received client+1,Huge size,Huge sent,Huge received server,Huge received client,Huge received server+1,Huge received client+1 +FST,FALSE,TRUE,3,594027,578034,578034,594027,594027,41,524630,508635,507742,524629,523736,149,506227,467462,464786,483456,480780,894,310436,119804,119097,147547,146801 +FST,TRUE,TRUE,3,641053,567789,560820,640279,619837,41,480181,457358,456744,480181,480181,149,459529,441253,441231,459529,459529,894,272114,111422,111422,135097,135097 +FST,FALSE,FALSE,52,542649,522684,517957,538680,533953,91,497530,475786,475405,491778,491400,200,523644,380468,378225,444881,442653,942,286728,118655,118162,145455,144961 +FST,TRUE,FALSE,52,480441,459042,458494,480441,480441,91,535569,516434,516129,535569,535569,200,410568,393098,393010,410568,410568,942,232388,92178,92177,114775,114775 +Kryo,FALSE,FALSE,51,538824,519253,517488,535246,533482,89,525301,504227,502752,520277,519499,192,472229,448378,447341,464371,463335,1044,323487,117176,116722,137844,137390 +Kryo,TRUE,FALSE,51,509626,487871,487560,509626,509626,89,554747,535450,535249,554747,554747,192,456303,438981,438944,456303,456303,1044,297441,113129,113129,133789,133788 +Java,FALSE,FALSE,116,566800,293375,292752,348894,348273,187,542524,225538,224428,274896,273784,552,600444,72768,71734,97019,95951,2119,102903,30329,30200,35840,35699 +Java,TRUE,FALSE,116,370948,352765,352734,370948,370948,187,1066106,184092,184070,220501,220492,552,596509,89077,89077,112112,112110,2119,99907,28100,28100,33159,33157 +jME,FALSE,TRUE,3,641103,625105,625105,641103,641103,41,573490,555243,554541,571234,570532,137,562337,536810,535389,551359,549940,818,284345,109578,109057,126706,126089 +jME,TRUE,TRUE,3,635733,562291,555737,635733,615680,41,553719,531007,530239,553719,553719,137,555038,536827,536739,555038,555038,818,293538,128359,128315,151681,151612 diff --git a/testresultsraw.txt b/testresultsraw.txt new file mode 100644 index 0000000000..7b2c4ac845 --- /dev/null +++ b/testresultsraw.txt @@ -0,0 +1,259 @@ +##### FST UNRELIABLE WITH REG ##### + +Running EmptyTestMessage tests +Serialization size is 3 +Sent 594027 messages in 10 seconds. +Of these, 578034 were recieved by the server and 578034 by the client. +A second later, 594027 were recieved by the server and 594027 by the client. + +Running SimpleTestMessage tests +Serialization size is 41 +Sent 524630 messages in 10 seconds. +Of these, 508635 were recieved by the server and 507742 by the client. +A second later, 524629 were recieved by the server and 523736 by the client. + +Running PhysicsTestMessage tests +Serialization size is 149 +Sent 506227 messages in 10 seconds. +Of these, 467462 were recieved by the server and 464786 by the client. +A second later, 483456 were recieved by the server and 480780 by the client. + +Running HugeTestMessage tests +Serialization size is 894 +Sent 310436 messages in 10 seconds. +Of these, 119804 were recieved by the server and 119097 by the client. +A second later, 147547 were recieved by the server and 146801 by the client. + +##### FST RELIABLE WITH REG ##### + +Running EmptyTestMessage tests +Serialization size is 3 +Sent 641053 messages in 10 seconds. +Of these, 567789 were recieved by the server and 560820 by the client. +A second later, 640279 were recieved by the server and 619837 by the client. + +Running SimpleTestMessage tests +Serialization size is 41 +Sent 480181 messages in 10 seconds. +Of these, 457358 were recieved by the server and 456744 by the client. +A second later, 480181 were recieved by the server and 480181 by the client. + +Running PhysicsTestMessage tests +Serialization size is 149 +Sent 459529 messages in 10 seconds. +Of these, 441253 were recieved by the server and 441231 by the client. +A second later, 459529 were recieved by the server and 459529 by the client. + +Running HugeTestMessage tests +Serialization size is 894 +Sent 272114 messages in 10 seconds. +Of these, 111422 were recieved by the server and 111422 by the client. +A second later, 135097 were recieved by the server and 135097 by the client. + +##### FST UNRELIABLE WITHOUT REG ##### + +Running EmptyTestMessage tests +Serialization size is 52 +Sent 542649 messages in 10 seconds. +Of these, 522684 were recieved by the server and 517957 by the client. +A second later, 538680 were recieved by the server and 533953 by the client. + +Running SimpleTestMessage tests +Serialization size is 91 +Sent 497530 messages in 10 seconds. +Of these, 475786 were recieved by the server and 475405 by the client. +A second later, 491778 were recieved by the server and 491400 by the client. + +Running PhysicsTestMessage tests +Serialization size is 200 +Sent 523644 messages in 10 seconds. +Of these, 380468 were recieved by the server and 378225 by the client. +A second later, 444881 were recieved by the server and 442653 by the client. + +Running HugeTestMessage tests +Serialization size is 942 +Sent 286728 messages in 10 seconds. +Of these, 118655 were recieved by the server and 118162 by the client. +A second later, 145455 were recieved by the server and 144961 by the client. + +##### FST RELIABLE WITHOUT REG ##### + +Running EmptyTestMessage tests +Serialization size is 52 +Sent 480441 messages in 10 seconds. +Of these, 459042 were recieved by the server and 458494 by the client. +A second later, 480441 were recieved by the server and 480441 by the client. + +Running SimpleTestMessage tests +Serialization size is 91 +Sent 535569 messages in 10 seconds. +Of these, 516434 were recieved by the server and 516129 by the client. +A second later, 535569 were recieved by the server and 535569 by the client. + +Running PhysicsTestMessage tests +Serialization size is 200 +Sent 410568 messages in 10 seconds. +Of these, 393098 were recieved by the server and 393010 by the client. +A second later, 410568 were recieved by the server and 410568 by the client. + +Running HugeTestMessage tests +Serialization size is 942 +Sent 232388 messages in 10 seconds. +Of these, 92178 were recieved by the server and 92177 by the client. +A second later, 114775 were recieved by the server and 114775 by the client. + +##### KRYO UNRELIABLE ##### + +Running EmptyTestMessage tests +Serialization size is 51 +Sent 538824 messages in 10 seconds. +Of these, 519253 were recieved by the server and 517488 by the client. +A second later, 535246 were recieved by the server and 533482 by the client. + +Running SimpleTestMessage tests +Serialization size is 89 +Sent 525301 messages in 10 seconds. +Of these, 504227 were recieved by the server and 502752 by the client. +A second later, 520277 were recieved by the server and 519499 by the client. + +Running PhysicsTestMessage tests +Serialization size is 192 +Sent 472229 messages in 10 seconds. +Of these, 448378 were recieved by the server and 447341 by the client. +A second later, 464371 were recieved by the server and 463335 by the client. + +Running HugeTestMessage tests +Serialization size is 1044 +Sent 323487 messages in 10 seconds. +Of these, 117176 were recieved by the server and 116722 by the client. +A second later, 137844 were recieved by the server and 137390 by the client. + +##### KRYO RELIABLE ##### + +Running EmptyTestMessage tests +Serialization size is 51 +Sent 509626 messages in 10 seconds. +Of these, 487871 were recieved by the server and 487560 by the client. +A second later, 509626 were recieved by the server and 509626 by the client. + +Running SimpleTestMessage tests +Serialization size is 89 +Sent 554747 messages in 10 seconds. +Of these, 535450 were recieved by the server and 535249 by the client. +A second later, 554747 were recieved by the server and 554747 by the client. + +Running PhysicsTestMessage tests +Serialization size is 192 +Sent 456303 messages in 10 seconds. +Of these, 438981 were recieved by the server and 438944 by the client. +A second later, 456303 were recieved by the server and 456303 by the client. + +Running HugeTestMessage tests +Serialization size is 1044 +Sent 297441 messages in 10 seconds. +Of these, 113129 were recieved by the server and 113129 by the client. +A second later, 133789 were recieved by the server and 133788 by the client. + +##### JAVA UNRELIABLE ##### + +Running EmptyTestMessage tests +Serialization size is 116 +Sent 566800 messages in 10 seconds. +Of these, 293375 were recieved by the server and 292752 by the client. +A second later, 348894 were recieved by the server and 348273 by the client. + +Running SimpleTestMessage tests +Serialization size is 187 +Sent 542524 messages in 10 seconds. +Of these, 225538 were recieved by the server and 224428 by the client. +A second later, 274896 were recieved by the server and 273784 by the client. + +Running PhysicsTestMessage tests +Serialization size is 552 +Sent 600444 messages in 10 seconds. +Of these, 72768 were recieved by the server and 71734 by the client. +A second later, 97019 were recieved by the server and 95951 by the client. + +Running HugeTestMessage tests +Serialization size is 2119 +Sent 102903 messages in 10 seconds. +Of these, 30329 were recieved by the server and 30200 by the client. +A second later, 35840 were recieved by the server and 35699 by the client. + +##### JAVA RELIABLE ##### + +Running EmptyTestMessage tests +Serialization size is 116 +Sent 370948 messages in 10 seconds. +Of these, 352765 were recieved by the server and 352734 by the client. +A second later, 370948 were recieved by the server and 370948 by the client. + +Running SimpleTestMessage tests +Serialization size is 187 +Sent 1066106 messages in 10 seconds. +Of these, 184092 were recieved by the server and 184070 by the client. +A second later, 220501 were recieved by the server and 220492 by the client. + +Running PhysicsTestMessage tests +Serialization size is 552 +Sent 596509 messages in 10 seconds. +Of these, 89077 were recieved by the server and 89077 by the client. +A second later, 112112 were recieved by the server and 112110 by the client. + +Running HugeTestMessage tests +Serialization size is 2119 +Sent 99907 messages in 10 seconds. +Of these, 28100 were recieved by the server and 28100 by the client. +A second later, 33159 were recieved by the server and 33157 by the client. + +##### JME UNRELIABLE ##### + +Running EmptyTestMessage tests +Serialization size is 3 +Sent 641103 messages in 10 seconds. +Of these, 625105 were recieved by the server and 625105 by the client. +A second later, 641103 were recieved by the server and 641103 by the client. + +Running SimpleTestMessage tests +Serialization size is 41 +Sent 573490 messages in 10 seconds. +Of these, 555243 were recieved by the server and 554541 by the client. +A second later, 571234 were recieved by the server and 570532 by the client. + +Running PhysicsTestMessage tests +Serialization size is 137 +Sent 562337 messages in 10 seconds. +Of these, 536810 were recieved by the server and 535389 by the client. +A second later, 551359 were recieved by the server and 549940 by the client. + +Running HugeTestMessage tests +Serialization size is 818 +Sent 284345 messages in 10 seconds. +Of these, 109578 were recieved by the server and 109057 by the client. +A second later, 126706 were recieved by the server and 126089 by the client. + +##### JME RELIABLE ##### + +Running EmptyTestMessage tests +Serialization size is 3 +Sent 635733 messages in 10 seconds. +Of these, 562291 were recieved by the server and 555737 by the client. +A second later, 635733 were recieved by the server and 615680 by the client. + +Running SimpleTestMessage tests +Serialization size is 41 +Sent 553719 messages in 10 seconds. +Of these, 531007 were recieved by the server and 530239 by the client. +A second later, 553719 were recieved by the server and 553719 by the client. + +Running PhysicsTestMessage tests +Serialization size is 137 +Sent 555038 messages in 10 seconds. +Of these, 536827 were recieved by the server and 536739 by the client. +A second later, 555038 were recieved by the server and 555038 by the client. + +Running HugeTestMessage tests +Serialization size is 818 +Sent 293538 messages in 10 seconds. +Of these, 128359 were recieved by the server and 128315 by the client. +A second later, 151681 were recieved by the server and 151612 by the client. \ No newline at end of file