void messageReceived(T message);
+
+ /**
+ * Gets the protocol associated with this session.
+ *
+ * @return the protocol
+ */
+ public Protocol getProtocol();
+
+ /**
+ * Sends a message across the network.
+ *
+ * @param message The message.
+ */
+ public void send(Message message);
+
+ /**
+ * Sends any amount of messages to the client.
+ *
+ * @param messages the messages to send to the client
+ */
+ public void sendAll(Message... messages);
+
+ /**
+ * Closes the session.
+ *
+ */
+ public void disconnect();
+
+ /**
+ * Called after the Session has been disconnected, right before the Session is invalidated.
+ *
+ */
+ public void onDisconnect();
+
+ /**
+ * Returns the address of this session.
+ *
+ * @return The remote address.
+ */
+ public InetSocketAddress getAddress();
+
+ /**
+ * Gets the id for this session
+ *
+ * @return session id
+ */
+ public String getSessionId();
+
+ /**
+ * Validates that {@code c} is the channel of the session. The channel of a session never changes.
+ *
+ * @param c the channel to check
+ * @throws IllegalStateException if {@code c} is not the channel of the session
+ */
+ public void validate(Channel c) throws IllegalStateException;
+
+ /**
+ * True if this session is open and connected. If the session is closed, errors will be thrown if messages are attempted to be sent.
+ *
+ * @return is active
+ */
+ public boolean isActive();
+
+ public interface UncaughtExceptionHandler {
+ /**
+ * Called when an exception occurs during session handling
+ *
+ * @param message the message handler threw an exception on
+ * @param handle handler that threw the an exception handling the message
+ * @param ex the exception
+ */
+ public void uncaughtException(Message message, MessageHandler> handle, Exception ex);
+ }
+
+ /**
+ * Gets the uncaught exception handler.
+ *
+ * Note: the default exception handler is the {@link DefaultUncaughtExceptionHandler}.
+ *
+ * @return exception handler
+ */
+ public UncaughtExceptionHandler getUncaughtExceptionHandler();
+
+ /**
+ * Sets the uncaught exception handler to be used for this session. Null values are not permitted.
+ *
+ * Note: to reset the default exception handler, use the{@link DefaultUncaughtExceptionHandler}.
+ */
+ public void setUncaughtExceptionHandler(UncaughtExceptionHandler handler);
+
+ public static final class DefaultUncaughtExceptionHandler implements UncaughtExceptionHandler {
+ private final Session session;
+
+ public DefaultUncaughtExceptionHandler(Session session) {
+ this.session = session;
+ }
+
+ @Override
+ public void uncaughtException(Message message, MessageHandler> handle, Exception ex) {
+ session.getProtocol().getLogger().log(Level.ERROR, "Message handler for " + message.getClass().getSimpleName() + " threw exception", ex);
+ //session.disconnect("Message handler exception for " + message.getClass().getSimpleName());
+ session.disconnect();
+ }
+ }
+}
diff --git a/src/test/java/com/flowpowered/networking/ByteBufferChannelProcessorTest.java b/src/test/java/com/flowpowered/networking/ByteBufferChannelProcessorTest.java
new file mode 100644
index 0000000..0e4941e
--- /dev/null
+++ b/src/test/java/com/flowpowered/networking/ByteBufferChannelProcessorTest.java
@@ -0,0 +1,109 @@
+/*
+ * This file is part of Flow Networking, licensed under the MIT License (MIT).
+ *
+ * Copyright (c) 2013 Spout LLC
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.flowpowered.networking;
+
+import java.util.Random;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.Unpooled;
+import io.netty.channel.ChannelHandlerContext;
+
+import org.junit.Test;
+import static org.junit.Assert.assertTrue;
+
+import com.flowpowered.networking.fake.ChannelHandlerContextFaker;
+import com.flowpowered.networking.process.ByteBufferChannelProcessor;
+
+public class ByteBufferChannelProcessorTest {
+ private final int LENGTH = 65536;
+ Thread mainThread;
+
+ @Test
+ public void randomPassthrough() {
+
+ mainThread = Thread.currentThread();
+
+ ByteBuf buffer = Unpooled.buffer(2048);
+
+ ChannelHandlerContext ctx = ChannelHandlerContextFaker.setup();
+
+ ByteBufferChannelProcessor processor = new ByteBufferChannelProcessor(256);
+
+ byte[] input = new byte[LENGTH];
+ byte[] output = new byte[LENGTH];
+
+ Random r = new Random();
+
+ for (int i = 0; i < input.length; i++) {
+ input[i] = (byte) (r.nextInt());
+ }
+
+ int writePointer = 0;
+ int readPointer = 0;
+
+ int pass = 0;
+
+ while (writePointer < LENGTH && (pass++) < 512) {
+
+ int toWrite = r.nextInt(512);
+
+ if (r.nextInt(10) == 0) {
+ // simulate "large" packets
+ toWrite *= 10;
+ }
+
+ if (toWrite > buffer.writableBytes()) {
+ toWrite = buffer.writableBytes();
+ }
+ if (toWrite > LENGTH - writePointer) {
+ toWrite = LENGTH - writePointer;
+ }
+
+ //System.out.println("Writing block of size " + toWrite);
+
+ buffer.writeBytes(input, writePointer, toWrite);
+ writePointer += toWrite;
+
+ ByteBuf buf = Unpooled.buffer();
+ ByteBuf outputBuffer = processor.process(ctx, buffer, buf);
+
+ buffer.discardReadBytes();
+
+ while (outputBuffer.isReadable()) {
+ int toRead = r.nextInt(768);
+ if (toRead > outputBuffer.readableBytes()) {
+ toRead = outputBuffer.readableBytes();
+ }
+ //System.out.println("ToRead: " + toRead + " of " + outputBuffer.readableBytes());
+ outputBuffer.readBytes(output, readPointer, toRead);
+ readPointer += toRead;
+ outputBuffer.discardReadBytes();
+ }
+ }
+
+ for (int i = 0; i < input.length; i++) {
+ assertTrue("Mismatch at position " + i, input[i] == output[i]);
+ }
+ }
+}
diff --git a/src/test/java/com/flowpowered/networking/PreprocessReplayingDecoderTest.java b/src/test/java/com/flowpowered/networking/PreprocessReplayingDecoderTest.java
new file mode 100644
index 0000000..dc47b42
--- /dev/null
+++ b/src/test/java/com/flowpowered/networking/PreprocessReplayingDecoderTest.java
@@ -0,0 +1,184 @@
+/*
+ * This file is part of Flow Networking, licensed under the MIT License (MIT).
+ *
+ * Copyright (c) 2013 Spout LLC
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.flowpowered.networking;
+
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Random;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.Unpooled;
+import io.netty.channel.ChannelHandlerContext;
+import java.util.Arrays;
+
+import org.junit.Test;
+import static org.junit.Assert.assertTrue;
+
+import com.flowpowered.networking.fake.ChannelHandlerContextFaker;
+import com.flowpowered.networking.fake.FakeChannelHandlerContext;
+import com.flowpowered.networking.process.CommonChannelProcessor;
+import com.flowpowered.networking.process.PreprocessReplayingDecoder;
+
+public class PreprocessReplayingDecoderTest {
+ private final int LENGTH = 65536;
+ private final int BREAK = 17652;
+
+ @Test
+ public void test() throws Exception {
+ // Preprocessor basically is split into two parts
+ // Part 1 is just a direct copy
+ // Part 2 negates all bytes before copying
+ Preprocessor p = new Preprocessor(512, BREAK, LENGTH);
+
+ // Set up a fake ChannelHandlerContext
+ FakeChannelHandlerContext fake = ChannelHandlerContextFaker.setup();
+ fake.setList(new LinkedList());
+
+ Random r = new Random();
+
+ // Get some random bytes for data
+ byte[] input = new byte[LENGTH];
+ r.nextBytes(input);
+
+ for (int i = 0; i < input.length;) {
+ // Simulate real data read
+ int burstSize = r.nextInt(512);
+ // With a 1/10 chance of having an extra-large burst
+ if (r.nextInt(10) == 0) {
+ burstSize *= 10;
+ }
+
+ // Final burst needs to be clamped
+ if (i + burstSize > input.length) {
+ burstSize = input.length - i;
+ }
+
+ // Write info to a new ByteBuf
+ final ByteBuf buf = Unpooled.buffer(burstSize);
+ buf.writeBytes(input, i, burstSize);
+ i += burstSize;
+
+ // Fake a read
+ p.channelRead(fake, buf);
+ }
+
+ // Get the output data and combine into one array
+ List outputList = fake.getList();
+ byte[] output = new byte[LENGTH];
+ int i = 0;
+ for (byte[] array : outputList) {
+ for (int j = 0; j < array.length; j++) {
+ output[i++] = array[j];
+ }
+ }
+
+ for (i = 0; i < input.length; i++) {
+ byte expected = i < BREAK ? input[i] : (byte) ~input[i];
+ if (output[i] != expected) {
+ for (int j = i - 10; j <= i + 10; j++) {
+ //System.out.println(j + ") " + Integer.toBinaryString(input[j] & 0xFF) + " " + Integer.toBinaryString(output[j] & 0xFF));
+ }
+ }
+
+ if (i < BREAK) {
+ assertTrue("Input/Output mismatch at position " + i, output[i] == input[i]);
+ } else {
+ assertTrue("Input/Output mismatch at position " + i + ", after the processor change", output[i] == (byte) ~input[i]);
+ }
+ }
+ }
+
+ private static class Preprocessor extends PreprocessReplayingDecoder {
+ private final int breakPoint;
+ private final int length;
+ private int position = 0;
+ private boolean breakOccured;
+ private Random r = new Random();
+
+ public Preprocessor(int capacity, int breakPoint, int length) {
+ super(capacity);
+ this.breakPoint = breakPoint;
+ this.length = length;
+ }
+
+ @Override
+ public Object decodeProcessed(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
+ int packetSize = r.nextInt(128) + 1;
+ if (r.nextInt(10) == 0) {
+ packetSize *= 20;
+ }
+
+ if (position + packetSize > breakPoint && !breakOccured) {
+ packetSize = breakPoint - position;
+ }
+ if (position + packetSize > length) {
+ packetSize = length - position;
+ }
+
+ if (packetSize == 0) {
+ return null;
+ }
+
+ byte[] buf = new byte[packetSize];
+
+ buffer.readBytes(buf);
+
+ position += packetSize;
+
+ if (position == breakPoint) {
+ this.setProcessor(new NegatingProcessor(512));
+ breakOccured = true;
+ }
+
+ return buf;
+ }
+ }
+
+ private static class NegatingProcessor extends CommonChannelProcessor {
+ byte[] buffer = new byte[65536];
+ int readPointer = 0;
+ int writePointer = 0;
+ int mask = 0xFFFF;
+
+ public NegatingProcessor(int capacity) {
+ super(capacity);
+ }
+
+ @Override
+ protected void write(byte[] buf, int length) {
+ for (int i = 0; i < length; i++) {
+ buffer[(writePointer++) & mask] = (byte) ~buf[i];
+ }
+ }
+
+ @Override
+ protected int read(byte[] buf) {
+ int i;
+ for (i = 0; i < buf.length && readPointer < writePointer; i++) {
+ buf[i] = buffer[(readPointer++) & mask];
+ }
+ return i;
+ }
+ }
+}
diff --git a/src/test/java/com/flowpowered/networking/fake/ChannelHandlerContextFaker.java b/src/test/java/com/flowpowered/networking/fake/ChannelHandlerContextFaker.java
new file mode 100644
index 0000000..9025ec0
--- /dev/null
+++ b/src/test/java/com/flowpowered/networking/fake/ChannelHandlerContextFaker.java
@@ -0,0 +1,71 @@
+/*
+ * This file is part of Flow Networking, licensed under the MIT License (MIT).
+ *
+ * Copyright (c) 2013 Spout LLC
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.flowpowered.networking.fake;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.ByteBufAllocator;
+import io.netty.buffer.Unpooled;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelConfig;
+
+import org.mockito.Mockito;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+
+public class ChannelHandlerContextFaker {
+ private static FakeChannelHandlerContext context = null;
+ private static Channel channel = null;
+ private static ChannelConfig config = null;
+ private static ByteBufAllocator alloc = null;
+
+ public static FakeChannelHandlerContext setup() {
+ if (context == null) {
+ alloc();
+ context = Mockito.mock(FakeChannelHandlerContext.class, Mockito.CALLS_REAL_METHODS);
+ channel = Mockito.mock(Channel.class);
+ config = Mockito.mock(ChannelConfig.class);
+ Mockito.doReturn(channel).when(context).channel();
+ Mockito.when(channel.config()).thenReturn(config);
+ Mockito.when(config.getAllocator()).thenReturn(alloc);
+ Answer answer = new Answer() {
+ @Override
+ public ByteBuf answer(InvocationOnMock invocation) throws Throwable {
+ ByteBuf buffer = Unpooled.buffer();
+ buffer.retain();
+ return buffer;
+ }
+ };
+ Mockito.when(alloc.buffer()).thenAnswer(answer);
+ Mockito.when(alloc.buffer(Mockito.anyInt())).thenAnswer(answer);
+ }
+ return context;
+ }
+
+ public static ByteBufAllocator alloc() {
+ if (alloc == null) {
+ alloc = Mockito.mock(ByteBufAllocator.class);
+ }
+ return alloc;
+ }
+}
diff --git a/src/test/java/com/flowpowered/networking/fake/FakeChannelHandlerContext.java b/src/test/java/com/flowpowered/networking/fake/FakeChannelHandlerContext.java
new file mode 100644
index 0000000..6db892e
--- /dev/null
+++ b/src/test/java/com/flowpowered/networking/fake/FakeChannelHandlerContext.java
@@ -0,0 +1,65 @@
+/*
+ * This file is part of Flow Networking, licensed under the MIT License (MIT).
+ *
+ * Copyright (c) 2013 Spout LLC
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.flowpowered.networking.fake;
+
+import io.netty.buffer.ByteBufAllocator;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelHandlerContext;
+
+import java.util.List;
+
+public abstract class FakeChannelHandlerContext implements ChannelHandlerContext {
+ private List list;
+ boolean first;
+
+ public void setList(List list) {
+ this.list = list;
+ }
+
+ public List getList() {
+ return list;
+ }
+
+ @Override
+ public ChannelHandlerContext fireChannelRead(Object msg) {
+ if (list != null && msg instanceof byte[]) {
+ list.add((byte[]) msg);
+ }
+ return this;
+ }
+
+ @Override
+ public abstract Channel channel();
+
+ @Override
+ public boolean isRemoved() {
+ return false;
+ }
+
+ @Override
+ public ByteBufAllocator alloc() {
+ return ChannelHandlerContextFaker.alloc();
+ }
+}
+