WIP cleanup/fix unit tests

This commit is contained in:
nathan 2015-07-17 02:46:00 +02:00
parent 8a26f3021e
commit a35935ff85
19 changed files with 1488 additions and 1139 deletions

View File

@ -1,15 +1,6 @@
package dorkbox.network; package dorkbox.network;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.LoggerContext;
@ -21,8 +12,21 @@ import dorkbox.network.connection.EndPoint;
import dorkbox.network.util.entropy.Entropy; import dorkbox.network.util.entropy.Entropy;
import dorkbox.network.util.entropy.SimpleEntropy; import dorkbox.network.util.entropy.SimpleEntropy;
import dorkbox.network.util.exceptions.InitializationException; import dorkbox.network.util.exceptions.InitializationException;
import org.slf4j.LoggerFactory;
public abstract class BaseTest { import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import static org.junit.Assert.fail;
public abstract
class BaseTest {
public static final String host = "localhost";
public static final int tcpPort = 54558;
public static final int udpPort = 54779;
public static final int udtPort = 54580;
static { static {
// we want our entropy generation to be simple (ie, no user interaction to generate) // we want our entropy generation to be simple (ie, no user interaction to generate)
@ -33,16 +37,12 @@ public abstract class BaseTest {
} }
} }
static public String host = "localhost";
static public int tcpPort = 54558;
static public int udpPort = 54779;
static public int udtPort = 54580;
private ArrayList<EndPoint> endPoints = new ArrayList<EndPoint>();
private volatile Timer timer;
boolean fail_check; boolean fail_check;
private final ArrayList<EndPoint> endPoints = new ArrayList<EndPoint>();
private volatile Timer timer;
public BaseTest () { public
BaseTest() {
System.out.println("---- " + getClass().getSimpleName()); System.out.println("---- " + getClass().getSimpleName());
// assume SLF4J is bound to logback in the current environment // assume SLF4J is bound to logback in the current environment
@ -90,39 +90,35 @@ public abstract class BaseTest {
rootLogger.addAppender(consoleAppender); rootLogger.addAppender(consoleAppender);
} }
public void addEndPoint(final EndPoint endPoint) { public
void addEndPoint(final EndPoint endPoint) {
this.endPoints.add(endPoint); this.endPoints.add(endPoint);
} }
public void stopEndPoints() { public
void stopEndPoints() {
stopEndPoints(0); stopEndPoints(0);
} }
public void stopEndPoints(int stopAfterMillis) { public
if (stopAfterMillis > 0) { void stopEndPoints(int stopAfterMillis) {
if (stopAfterMillis <= 0) {
stopAfterMillis = 1;
}
if (this.timer == null) { if (this.timer == null) {
this.timer = new Timer("UnitTest timeout timer"); this.timer = new Timer("UnitTest timeout timer");
} }
// don't automatically timeout when we are testing. // We have to ALWAYS run this in a new timer, BECAUSE if stopEndPoints() is called from a client/server thread, it will DEADLOCK
this.timer.schedule(new TimerTask() { this.timer.schedule(new TimerTask() {
@Override @Override
public void run () { public
synchronized (BaseTest.this.endPoints) { void run() {
for (EndPoint endPoint : BaseTest.this.endPoints) {
endPoint.stop();
}
BaseTest.this.endPoints.clear();
}
BaseTest.this.timer.cancel();
BaseTest.this.timer.purge();
BaseTest.this.timer = null;
}
}, stopAfterMillis);
} else {
synchronized (BaseTest.this.endPoints) { synchronized (BaseTest.this.endPoints) {
for (EndPoint endPoint : BaseTest.this.endPoints) { for (EndPoint endPoint : BaseTest.this.endPoints) {
endPoint.stop(); endPoint.stop();
endPoint.waitForShutdown();
} }
BaseTest.this.endPoints.clear(); BaseTest.this.endPoints.clear();
} }
@ -132,9 +128,11 @@ public abstract class BaseTest {
BaseTest.this.timer = null; BaseTest.this.timer = null;
} }
} }
}, stopAfterMillis);
} }
public void waitForThreads(int stopAfterSecondsOrMillis) { public
void waitForThreads(int stopAfterSecondsOrMillis) {
if (stopAfterSecondsOrMillis < 1000) { if (stopAfterSecondsOrMillis < 1000) {
stopAfterSecondsOrMillis *= 1000; stopAfterSecondsOrMillis *= 1000;
} }
@ -142,11 +140,13 @@ public abstract class BaseTest {
waitForThreads0(stopAfterSecondsOrMillis); waitForThreads0(stopAfterSecondsOrMillis);
} }
public void waitForThreads() { public
void waitForThreads() {
waitForThreads0(0); waitForThreads0(0);
} }
private void waitForThreads0(int stopAfterMillis) { private
void waitForThreads0(int stopAfterMillis) {
this.fail_check = false; this.fail_check = false;
TimerTask failTask = null; TimerTask failTask = null;
@ -156,7 +156,8 @@ public abstract class BaseTest {
failTask = new TimerTask() { failTask = new TimerTask() {
@Override @Override
public void run () { public
void run() {
BaseTest.this.fail_check = true; BaseTest.this.fail_check = true;
} }
}; };
@ -185,7 +186,7 @@ public abstract class BaseTest {
// Give sockets a chance to close before starting the next test. // Give sockets a chance to close before starting the next test.
try { try {
Thread.sleep(1000); Thread.sleep(100);
} catch (InterruptedException ignored) { } catch (InterruptedException ignored) {
} }
} }

View File

@ -2,17 +2,20 @@
package dorkbox.network; package dorkbox.network;
import static org.junit.Assert.fail;
import java.util.Arrays;
import dorkbox.network.PingPongTest.TYPE; import dorkbox.network.PingPongTest.TYPE;
import dorkbox.network.connection.Connection; import dorkbox.network.connection.Connection;
import dorkbox.network.connection.Listener; import dorkbox.network.connection.Listener;
import dorkbox.network.connection.idle.IdleBridge; import dorkbox.network.connection.idle.IdleBridge;
import dorkbox.network.util.SerializationManager; import dorkbox.network.util.ConnectionSerializationManager;
import dorkbox.network.util.KryoConnectionSerializationManager;
import dorkbox.network.util.exceptions.InitializationException; import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException; import dorkbox.network.util.exceptions.SecurityException;
import org.junit.Test;
import java.io.IOException;
import java.util.Arrays;
import static org.junit.Assert.fail;
public class ChunkedDataTest extends BaseTest { public class ChunkedDataTest extends BaseTest {
private volatile boolean success = false; private volatile boolean success = false;
@ -24,7 +27,8 @@ public class ChunkedDataTest extends BaseTest {
} }
// have to test sending objects // have to test sending objects
public void ObjectSender() throws InitializationException, SecurityException { @Test
public void ObjectSender() throws InitializationException, SecurityException, IOException {
final Data mainData = new Data(); final Data mainData = new Data();
populateData(mainData); populateData(mainData);
@ -33,6 +37,9 @@ public class ChunkedDataTest extends BaseTest {
ConnectionOptions connectionOptions = new ConnectionOptions(); ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort; connectionOptions.tcpPort = tcpPort;
connectionOptions.host = host; connectionOptions.host = host;
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT();
register(connectionOptions.serializationManager);
sendObject(mainData, connectionOptions, ConnectionType.TCP); sendObject(mainData, connectionOptions, ConnectionType.TCP);
@ -41,7 +48,10 @@ public class ChunkedDataTest extends BaseTest {
connectionOptions.tcpPort = tcpPort; connectionOptions.tcpPort = tcpPort;
connectionOptions.udpPort = udpPort; connectionOptions.udpPort = udpPort;
connectionOptions.host = host; connectionOptions.host = host;
sendObject(mainData, connectionOptions, ConnectionType.TCP); connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT();
register(connectionOptions.serializationManager);
sendObject(mainData, connectionOptions, ConnectionType.UDP);
System.err.println("-- UDT"); System.err.println("-- UDT");
@ -49,15 +59,19 @@ public class ChunkedDataTest extends BaseTest {
connectionOptions.tcpPort = tcpPort; connectionOptions.tcpPort = tcpPort;
connectionOptions.udtPort = udtPort; connectionOptions.udtPort = udtPort;
connectionOptions.host = host; connectionOptions.host = host;
sendObject(mainData, connectionOptions, ConnectionType.TCP); connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT();
register(connectionOptions.serializationManager);
sendObject(mainData, connectionOptions, ConnectionType.UDT);
} }
private void sendObject(final Data mainData, ConnectionOptions connectionOptions, final ConnectionType type) throws InitializationException, SecurityException { private void sendObject(final Data mainData, ConnectionOptions connectionOptions, final ConnectionType type)
throws InitializationException, SecurityException, IOException {
Server server = new Server(connectionOptions); Server server = new Server(connectionOptions);
server.disableRemoteKeyValidation(); server.disableRemoteKeyValidation();
register(server.getSerialization());
addEndPoint(server); addEndPoint(server);
server.setIdleTimeout(100); server.setIdleTimeout(100);
server.bind(false); server.bind(false);
@ -82,7 +96,6 @@ public class ChunkedDataTest extends BaseTest {
Client client = new Client(connectionOptions); Client client = new Client(connectionOptions);
client.disableRemoteKeyValidation(); client.disableRemoteKeyValidation();
register(client.getSerialization());
addEndPoint(client); addEndPoint(client);
client.listeners().add(new Listener<Data>() { client.listeners().add(new Listener<Data>() {
@Override @Override
@ -133,7 +146,7 @@ public class ChunkedDataTest extends BaseTest {
data.Booleans = new Boolean[] {true, false}; data.Booleans = new Boolean[] {true, false};
} }
private void register (SerializationManager kryoMT) { private void register (ConnectionSerializationManager kryoMT) {
kryoMT.register(int[].class); kryoMT.register(int[].class);
kryoMT.register(short[].class); kryoMT.register(short[].class);
kryoMT.register(float[].class); kryoMT.register(float[].class);

View File

@ -1,58 +1,66 @@
package dorkbox.network; package dorkbox.network;
import static org.junit.Assert.fail;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.Test;
import dorkbox.network.connection.Connection; import dorkbox.network.connection.Connection;
import dorkbox.network.connection.Listener; import dorkbox.network.connection.Listener;
import dorkbox.network.util.SerializationManager; import dorkbox.network.util.ConnectionSerializationManager;
import dorkbox.network.util.KryoConnectionSerializationManager;
import dorkbox.network.util.exceptions.InitializationException; import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException; import dorkbox.network.util.exceptions.SecurityException;
import org.junit.Test;
public class ClientSendTest extends BaseTest { import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.junit.Assert.fail;
public
class ClientSendTest extends BaseTest {
private AtomicBoolean checkPassed = new AtomicBoolean(false); private AtomicBoolean checkPassed = new AtomicBoolean(false);
@Test @Test
public void sendDataFromClientClass () throws InitializationException, SecurityException { public
void sendDataFromClientClass() throws InitializationException, SecurityException, IOException {
ConnectionOptions connectionOptions = new ConnectionOptions(); ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort; connectionOptions.tcpPort = tcpPort;
connectionOptions.host = host; connectionOptions.host = host;
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT();
register(connectionOptions.serializationManager);
Server server = new Server(connectionOptions); Server server = new Server(connectionOptions);
server.disableRemoteKeyValidation(); server.disableRemoteKeyValidation();
addEndPoint(server); addEndPoint(server);
server.bind(false); server.bind(false);
register(server.getSerialization());
server.listeners().add(new Listener<AMessage>() { server.listeners()
.add(new Listener<AMessage>() {
@Override @Override
public void received (Connection connection, AMessage object) { public
void received(Connection connection, AMessage object) {
System.err.println("Server received message from client. Bouncing back."); System.err.println("Server received message from client. Bouncing back.");
connection.send().TCP(object); connection.send()
.TCP(object);
} }
}); });
Client client = new Client(connectionOptions); Client client = new Client(connectionOptions);
client.disableRemoteKeyValidation(); client.disableRemoteKeyValidation();
addEndPoint(client); addEndPoint(client);
register(client.getSerialization());
client.connect(5000); client.connect(5000);
client.listeners().add(new Listener<AMessage>() { client.listeners()
.add(new Listener<AMessage>() {
@Override @Override
public void received (Connection connection, AMessage object) { public
void received(Connection connection, AMessage object) {
ClientSendTest.this.checkPassed.set(true); ClientSendTest.this.checkPassed.set(true);
stopEndPoints(); stopEndPoints();
} }
}); });
client.send().TCP(new AMessage()); client.send()
.TCP(new AMessage());
waitForThreads(); waitForThreads();
@ -61,12 +69,15 @@ public class ClientSendTest extends BaseTest {
} }
} }
private void register (SerializationManager kryoMT) { private static
void register(ConnectionSerializationManager kryoMT) {
kryoMT.register(AMessage.class); kryoMT.register(AMessage.class);
} }
public static class AMessage { public static
public AMessage () { class AMessage {
public
AMessage() {
} }
} }
} }

View File

@ -1,161 +1,187 @@
package dorkbox.network; package dorkbox.network;
import dorkbox.network.connection.Connection;
import dorkbox.network.connection.EndPoint;
import dorkbox.network.connection.Listener;
import dorkbox.network.util.ConnectionSerializationManager;
import dorkbox.network.util.KryoConnectionSerializationManager;
import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException;
import org.junit.Test;
import java.io.IOException;
import java.util.Timer; import java.util.Timer;
import java.util.TimerTask; import java.util.TimerTask;
import org.junit.Test; public
class ConnectionTest extends BaseTest {
import dorkbox.network.connection.Connection;
import dorkbox.network.connection.Listener;
import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException;
public class ConnectionTest extends BaseTest {
@Test @Test
public void connectLocal() throws InitializationException, SecurityException { public
void connectLocal() throws InitializationException, SecurityException, IOException {
System.out.println("---- " + "Local"); System.out.println("---- " + "Local");
startServer(null);
startClient(null); ConnectionOptions connectionOptions = new ConnectionOptions(EndPoint.LOCAL_CHANNEL);
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT();
register(connectionOptions.serializationManager);
startServer(connectionOptions);
startClient(connectionOptions);
waitForThreads(10); waitForThreads(10);
} }
@Test @Test
public void connectTcp() throws InitializationException, SecurityException { public
void connectTcp() throws InitializationException, SecurityException, IOException {
System.out.println("---- " + "TCP"); System.out.println("---- " + "TCP");
ConnectionOptions connectionOptions = new ConnectionOptions(); ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort; connectionOptions.tcpPort = tcpPort;
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT();
register(connectionOptions.serializationManager);
Server server = startServer(connectionOptions); startServer(connectionOptions);
connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort;
connectionOptions.host = host; connectionOptions.host = host;
startClient(connectionOptions); startClient(connectionOptions);
server.waitForStop(true);
waitForThreads(10); waitForThreads(10);
} }
@Test @Test
public void connectTcpUdp() throws InitializationException, SecurityException { public
void connectTcpUdp() throws InitializationException, SecurityException, IOException {
System.out.println("---- " + "TCP UDP"); System.out.println("---- " + "TCP UDP");
ConnectionOptions connectionOptions = new ConnectionOptions(); ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort; connectionOptions.tcpPort = tcpPort;
connectionOptions.udpPort = udpPort; connectionOptions.udpPort = udpPort;
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT();
register(connectionOptions.serializationManager);
Server server = startServer(connectionOptions); startServer(connectionOptions);
connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort;
connectionOptions.udpPort = udpPort;
connectionOptions.host = host; connectionOptions.host = host;
startClient(connectionOptions); startClient(connectionOptions);
server.waitForStop(true);
waitForThreads(10); waitForThreads(10);
} }
@Test @Test
public void connectTcpUdt() throws InitializationException, SecurityException { public
void connectTcpUdt() throws InitializationException, SecurityException, IOException {
System.out.println("---- " + "TCP UDT"); System.out.println("---- " + "TCP UDT");
ConnectionOptions connectionOptions = new ConnectionOptions(); ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort; connectionOptions.tcpPort = tcpPort;
connectionOptions.udtPort = udtPort; connectionOptions.udtPort = udtPort;
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT();
register(connectionOptions.serializationManager);
Server server = startServer(connectionOptions); startServer(connectionOptions);
connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort;
connectionOptions.udtPort = udtPort;
connectionOptions.host = host; connectionOptions.host = host;
startClient(connectionOptions); startClient(connectionOptions);
server.waitForStop(true);
waitForThreads(10); waitForThreads(10);
} }
@Test @Test
public void connectTcpUdpUdt() throws InitializationException, SecurityException { public
void connectTcpUdpUdt() throws InitializationException, SecurityException, IOException {
System.out.println("---- " + "TCP UDP UDT"); System.out.println("---- " + "TCP UDP UDT");
ConnectionOptions connectionOptions = new ConnectionOptions(); ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort; connectionOptions.tcpPort = tcpPort;
connectionOptions.udpPort = udpPort; connectionOptions.udpPort = udpPort;
connectionOptions.udtPort = udtPort; connectionOptions.udtPort = udtPort;
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT();
register(connectionOptions.serializationManager);
Server server = startServer(connectionOptions); startServer(connectionOptions);
connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort;
connectionOptions.udpPort = udpPort;
connectionOptions.udtPort = udtPort;
connectionOptions.host = host; connectionOptions.host = host;
startClient(connectionOptions); startClient(connectionOptions);
server.waitForStop(true);
waitForThreads(10); waitForThreads(10);
} }
private Server startServer(ConnectionOptions connectionOptions) throws InitializationException, SecurityException { private
Server server; Server startServer(ConnectionOptions connectionOptions) throws InitializationException, SecurityException, IOException {
if (connectionOptions != null) { Server server = new Server(connectionOptions);
server = new Server(connectionOptions);
} else {
server = new Server();
}
server.disableRemoteKeyValidation(); server.disableRemoteKeyValidation();
addEndPoint(server); addEndPoint(server);
server.bind(false); server.bind(false);
server.listeners().add(new Listener<Object>() { server.listeners()
.add(new Listener<Object>() {
Timer timer = new Timer(); Timer timer = new Timer();
@Override @Override
public void connected (final Connection connection) { public
void connected(final Connection connection) {
this.timer.schedule(new TimerTask() { this.timer.schedule(new TimerTask() {
@Override @Override
public void run () { public
void run() {
System.out.println("Disconnecting after 1 second."); System.out.println("Disconnecting after 1 second.");
connection.close(); connection.close();
} }
}, 1000); }, 1000);
} }
@Override
public void received(Connection connection, Object message) {
System.err.println("Received message from client: " + message.getClass().getSimpleName());
}
}); });
return server; return server;
} }
private Client startClient(ConnectionOptions connectionOptions) throws InitializationException, SecurityException { private
Client startClient(ConnectionOptions connectionOptions) throws InitializationException, SecurityException, IOException {
Client client; Client client;
if (connectionOptions != null) { if (connectionOptions != null) {
client = new Client(connectionOptions); client = new Client(connectionOptions);
} else { }
else {
client = new Client(); client = new Client();
} }
client.disableRemoteKeyValidation(); client.disableRemoteKeyValidation();
addEndPoint(client); addEndPoint(client);
client.listeners().add(new Listener<Object>() { client.listeners()
.add(new Listener<Object>() {
@Override @Override
public void disconnected(Connection connection) { public
void disconnected(Connection connection) {
stopEndPoints(); stopEndPoints();
} }
}); });
client.connect(5000); client.connect(5000);
client.send()
.TCP(new BMessage())
.flush();
return client; return client;
} }
private
void register(ConnectionSerializationManager kryoMT) {
kryoMT.register(BMessage.class);
}
public static
class BMessage {
public
BMessage() {
}
}
} }

View File

@ -1,21 +1,23 @@
package dorkbox.network; package dorkbox.network;
import static org.junit.Assert.fail;
import org.junit.Test;
import dorkbox.network.connection.Connection; import dorkbox.network.connection.Connection;
import dorkbox.network.connection.Listener; import dorkbox.network.connection.Listener;
import dorkbox.network.util.exceptions.InitializationException; import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException; import dorkbox.network.util.exceptions.SecurityException;
import org.junit.Test;
public class DiscoverHostTest extends BaseTest { import java.io.IOException;
import static org.junit.Assert.fail;
public
class DiscoverHostTest extends BaseTest {
volatile boolean connected = false; volatile boolean connected = false;
@Test @Test
public void broadcast () throws InitializationException, SecurityException { public
void broadcast() throws InitializationException, SecurityException, IOException {
ConnectionOptions connectionOptions = new ConnectionOptions(); ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort; connectionOptions.tcpPort = tcpPort;
@ -39,9 +41,11 @@ public class DiscoverHostTest extends BaseTest {
Client client = new Client(connectionOptions); Client client = new Client(connectionOptions);
client.disableRemoteKeyValidation(); client.disableRemoteKeyValidation();
addEndPoint(client); addEndPoint(client);
client.listeners().add(new Listener<Object>() { client.listeners()
.add(new Listener<Object>() {
@Override @Override
public void connected(Connection connection) { public
void connected(Connection connection) {
DiscoverHostTest.this.connected = true; DiscoverHostTest.this.connected = true;
stopEndPoints(); stopEndPoints();
} }

View File

@ -1,28 +1,30 @@
package dorkbox.network; package dorkbox.network;
import static org.junit.Assert.fail;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Arrays;
import org.junit.Test;
import dorkbox.network.PingPongTest.TYPE; import dorkbox.network.PingPongTest.TYPE;
import dorkbox.network.connection.Connection; import dorkbox.network.connection.Connection;
import dorkbox.network.connection.Listener; import dorkbox.network.connection.Listener;
import dorkbox.network.connection.idle.IdleBridge; import dorkbox.network.connection.idle.IdleBridge;
import dorkbox.network.connection.idle.InputStreamSender; import dorkbox.network.connection.idle.InputStreamSender;
import dorkbox.network.util.SerializationManager; import dorkbox.network.util.ConnectionSerializationManager;
import dorkbox.network.util.KryoConnectionSerializationManager;
import dorkbox.network.util.exceptions.InitializationException; import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException; import dorkbox.network.util.exceptions.SecurityException;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import static org.junit.Assert.fail;
@SuppressWarnings({"rawtypes"}) @SuppressWarnings({"rawtypes"})
public class IdleTest extends BaseTest { public
class IdleTest extends BaseTest {
private volatile boolean success = false; private volatile boolean success = false;
enum ConnectionType { enum ConnectionType {
TCP, TCP,
UDP, UDP,
@ -30,13 +32,15 @@ public class IdleTest extends BaseTest {
} }
@Test @Test
public void InputStreamSender() throws InitializationException, SecurityException { public
void InputStreamSender() throws InitializationException, SecurityException, IOException {
final int largeDataSize = 12345; final int largeDataSize = 12345;
System.err.println("-- TCP"); System.err.println("-- TCP");
ConnectionOptions connectionOptions = new ConnectionOptions(); ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort; connectionOptions.tcpPort = tcpPort;
connectionOptions.host = host; connectionOptions.host = host;
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT(false, false);
streamSpecificType(largeDataSize, connectionOptions, ConnectionType.TCP); streamSpecificType(largeDataSize, connectionOptions, ConnectionType.TCP);
@ -45,6 +49,7 @@ public class IdleTest extends BaseTest {
connectionOptions.tcpPort = tcpPort; connectionOptions.tcpPort = tcpPort;
connectionOptions.udpPort = udpPort; connectionOptions.udpPort = udpPort;
connectionOptions.host = host; connectionOptions.host = host;
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT(false, false);
streamSpecificType(largeDataSize, connectionOptions, ConnectionType.UDP); streamSpecificType(largeDataSize, connectionOptions, ConnectionType.UDP);
@ -53,6 +58,7 @@ public class IdleTest extends BaseTest {
connectionOptions.tcpPort = tcpPort; connectionOptions.tcpPort = tcpPort;
connectionOptions.udtPort = udtPort; connectionOptions.udtPort = udtPort;
connectionOptions.host = host; connectionOptions.host = host;
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT(false, false);
streamSpecificType(largeDataSize, connectionOptions, ConnectionType.UDT); streamSpecificType(largeDataSize, connectionOptions, ConnectionType.UDT);
} }
@ -60,7 +66,8 @@ public class IdleTest extends BaseTest {
// have to test sending objects // have to test sending objects
@Test @Test
public void ObjectSender() throws InitializationException, SecurityException { public
void ObjectSender() throws InitializationException, SecurityException, IOException {
final Data mainData = new Data(); final Data mainData = new Data();
populateData(mainData); populateData(mainData);
@ -69,6 +76,8 @@ public class IdleTest extends BaseTest {
ConnectionOptions connectionOptions = new ConnectionOptions(); ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort; connectionOptions.tcpPort = tcpPort;
connectionOptions.host = host; connectionOptions.host = host;
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT();
register(connectionOptions.serializationManager);
sendObject(mainData, connectionOptions, ConnectionType.TCP); sendObject(mainData, connectionOptions, ConnectionType.TCP);
@ -77,6 +86,8 @@ public class IdleTest extends BaseTest {
connectionOptions.tcpPort = tcpPort; connectionOptions.tcpPort = tcpPort;
connectionOptions.udpPort = udpPort; connectionOptions.udpPort = udpPort;
connectionOptions.host = host; connectionOptions.host = host;
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT();
register(connectionOptions.serializationManager);
sendObject(mainData, connectionOptions, ConnectionType.TCP); sendObject(mainData, connectionOptions, ConnectionType.TCP);
@ -85,28 +96,39 @@ public class IdleTest extends BaseTest {
connectionOptions.tcpPort = tcpPort; connectionOptions.tcpPort = tcpPort;
connectionOptions.udtPort = udtPort; connectionOptions.udtPort = udtPort;
connectionOptions.host = host; connectionOptions.host = host;
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT();
register(connectionOptions.serializationManager);
sendObject(mainData, connectionOptions, ConnectionType.TCP); sendObject(mainData, connectionOptions, ConnectionType.TCP);
} }
private void sendObject(final Data mainData, ConnectionOptions connectionOptions, final ConnectionType type) throws InitializationException, SecurityException { private
void sendObject(final Data mainData, ConnectionOptions connectionOptions, final ConnectionType type)
throws InitializationException, SecurityException, IOException {
Server server = new Server(connectionOptions); Server server = new Server(connectionOptions);
server.disableRemoteKeyValidation(); server.disableRemoteKeyValidation();
register(server.getSerialization());
addEndPoint(server); addEndPoint(server);
server.setIdleTimeout(100); server.setIdleTimeout(100);
server.bind(false); server.bind(false);
server.listeners().add(new Listener<Data>() { server.listeners()
.add(new Listener<Data>() {
@Override @Override
public void connected (Connection connection) { public
void connected(Connection connection) {
IdleBridge sendOnIdle = connection.sendOnIdle(mainData); IdleBridge sendOnIdle = connection.sendOnIdle(mainData);
switch (type) { switch (type) {
case TCP: sendOnIdle.TCP(); break; case TCP:
case UDP: sendOnIdle.UDP(); break; sendOnIdle.TCP();
case UDT: sendOnIdle.UDT(); break; break;
case UDP:
sendOnIdle.UDP();
break;
case UDT:
sendOnIdle.UDT();
break;
} }
} }
}); });
@ -115,11 +137,12 @@ public class IdleTest extends BaseTest {
Client client = new Client(connectionOptions); Client client = new Client(connectionOptions);
client.disableRemoteKeyValidation(); client.disableRemoteKeyValidation();
register(client.getSerialization());
addEndPoint(client); addEndPoint(client);
client.listeners().add(new Listener<Data>() { client.listeners()
.add(new Listener<Data>() {
@Override @Override
public void received(Connection connection, Data object) { public
void received(Connection connection, Data object) {
if (mainData.equals(object)) { if (mainData.equals(object)) {
IdleTest.this.success = true; IdleTest.this.success = true;
} }
@ -139,16 +162,19 @@ public class IdleTest extends BaseTest {
private void streamSpecificType(final int largeDataSize, ConnectionOptions connectionOptions, final ConnectionType type) throws InitializationException, SecurityException { private
void streamSpecificType(final int largeDataSize, ConnectionOptions connectionOptions, final ConnectionType type)
throws InitializationException, SecurityException, IOException {
Server server = new Server(connectionOptions); Server server = new Server(connectionOptions);
server.disableRemoteKeyValidation(); server.disableRemoteKeyValidation();
server.getSerialization().setRegistrationRequired(false);
addEndPoint(server); addEndPoint(server);
server.setIdleTimeout(100); server.setIdleTimeout(100);
server.bind(false); server.bind(false);
server.listeners().add(new Listener<byte[]>() { server.listeners()
.add(new Listener<byte[]>() {
@Override @Override
public void connected (Connection connection) { public
void connected(Connection connection) {
ByteArrayOutputStream output = new ByteArrayOutputStream(largeDataSize); ByteArrayOutputStream output = new ByteArrayOutputStream(largeDataSize);
for (int i = 0; i < largeDataSize; i++) { for (int i = 0; i < largeDataSize; i++) {
output.write(i); output.write(i);
@ -159,22 +185,30 @@ public class IdleTest extends BaseTest {
// Send data in 512 byte chunks. // Send data in 512 byte chunks.
IdleBridge sendOnIdle = connection.sendOnIdle(new InputStreamSender(input, 512) { IdleBridge sendOnIdle = connection.sendOnIdle(new InputStreamSender(input, 512) {
@Override @Override
protected void start () { protected
void start() {
// Normally would send an object so the receiving side knows how to handle the chunks we are about to send. // Normally would send an object so the receiving side knows how to handle the chunks we are about to send.
System.err.println("starting"); System.err.println("starting");
} }
@Override @Override
protected byte[] onNext (byte[] bytes) { protected
byte[] onNext(byte[] bytes) {
//System.out.println("sending " + bytes.length); //System.out.println("sending " + bytes.length);
return bytes; // Normally would wrap the byte[] with an object so the receiving side knows how to handle it. return bytes; // Normally would wrap the byte[] with an object so the receiving side knows how to handle it.
} }
}); });
switch (type) { switch (type) {
case TCP: sendOnIdle.TCP(); break; case TCP:
case UDP: sendOnIdle.UDP(); break; sendOnIdle.TCP();
case UDT: sendOnIdle.UDT(); break; break;
case UDP:
sendOnIdle.UDP();
break;
case UDT:
sendOnIdle.UDT();
break;
} }
} }
}); });
@ -183,13 +217,14 @@ public class IdleTest extends BaseTest {
Client client = new Client(connectionOptions); Client client = new Client(connectionOptions);
client.disableRemoteKeyValidation(); client.disableRemoteKeyValidation();
client.getSerialization().setRegistrationRequired(false);
addEndPoint(client); addEndPoint(client);
client.listeners().add(new Listener<byte[]>() { client.listeners()
.add(new Listener<byte[]>() {
int total; int total;
@Override @Override
public void received (Connection connection, byte[] object) { public
void received(Connection connection, byte[] object) {
int length = object.length; int length = object.length;
//System.err.println("received " + length); //System.err.println("received " + length);
this.total += length; this.total += length;
@ -210,7 +245,8 @@ public class IdleTest extends BaseTest {
} }
private void populateData(Data data) { private
void populateData(Data data) {
StringBuilder buffer = new StringBuilder(); StringBuilder buffer = new StringBuilder();
for (int i = 0; i < 3000; i++) { for (int i = 0; i < 3000; i++) {
buffer.append('a'); buffer.append('a');
@ -230,7 +266,8 @@ public class IdleTest extends BaseTest {
data.booleans = new boolean[] {true, false}; data.booleans = new boolean[] {true, false};
data.Ints = new Integer[] {-1234567, 1234567, -1, 0, 1, Integer.MAX_VALUE, Integer.MIN_VALUE}; data.Ints = new Integer[] {-1234567, 1234567, -1, 0, 1, Integer.MAX_VALUE, Integer.MIN_VALUE};
data.Shorts = new Short[] {-12345, 12345, -1, 0, 1, Short.MAX_VALUE, Short.MIN_VALUE}; data.Shorts = new Short[] {-12345, 12345, -1, 0, 1, Short.MAX_VALUE, Short.MIN_VALUE};
data.Floats = new Float[] {0f, -0f, 1f, -1f, 123456f, -123456f, 0.1f, 0.2f, -0.3f, (float)Math.PI, Float.MAX_VALUE, Float.MIN_VALUE}; data.Floats = new Float[] {0f, -0f, 1f, -1f, 123456f, -123456f, 0.1f, 0.2f, -0.3f, (float) Math.PI, Float.MAX_VALUE,
Float.MIN_VALUE};
data.Doubles = new Double[] {0d, -0d, 1d, -1d, 123456d, -123456d, 0.1d, 0.2d, -0.3d, Math.PI, Double.MAX_VALUE, Double.MIN_VALUE}; data.Doubles = new Double[] {0d, -0d, 1d, -1d, 123456d, -123456d, 0.1d, 0.2d, -0.3d, Math.PI, Double.MAX_VALUE, Double.MIN_VALUE};
data.Longs = new Long[] {0l, -0l, 1l, -1l, 123456l, -123456l, 99999999999l, -99999999999l, Long.MAX_VALUE, Long.MIN_VALUE}; data.Longs = new Long[] {0l, -0l, 1l, -1l, 123456l, -123456l, 99999999999l, -99999999999l, Long.MAX_VALUE, Long.MIN_VALUE};
data.Bytes = new Byte[] {-123, 123, -1, 0, 1, Byte.MAX_VALUE, Byte.MIN_VALUE}; data.Bytes = new Byte[] {-123, 123, -1, 0, 1, Byte.MAX_VALUE, Byte.MIN_VALUE};
@ -238,7 +275,8 @@ public class IdleTest extends BaseTest {
data.Booleans = new Boolean[] {true, false}; data.Booleans = new Boolean[] {true, false};
} }
private void register (SerializationManager kryoMT) { private
void register(ConnectionSerializationManager kryoMT) {
kryoMT.register(int[].class); kryoMT.register(int[].class);
kryoMT.register(short[].class); kryoMT.register(short[].class);
kryoMT.register(float[].class); kryoMT.register(float[].class);
@ -260,7 +298,8 @@ public class IdleTest extends BaseTest {
kryoMT.register(TYPE.class); kryoMT.register(TYPE.class);
} }
static public class Data { static public
class Data {
public String string; public String string;
public String[] strings; public String[] strings;
public int[] ints; public int[] ints;
@ -282,7 +321,8 @@ public class IdleTest extends BaseTest {
@Override @Override
public int hashCode() { public
int hashCode() {
final int prime = 31; final int prime = 31;
int result = 1; int result = 1;
result = prime * result + Arrays.hashCode(this.Booleans); result = prime * result + Arrays.hashCode(this.Booleans);
@ -307,7 +347,8 @@ public class IdleTest extends BaseTest {
} }
@Override @Override
public boolean equals(Object obj) { public
boolean equals(Object obj) {
if (this == obj) { if (this == obj) {
return true; return true;
} }
@ -370,7 +411,8 @@ public class IdleTest extends BaseTest {
if (other.string != null) { if (other.string != null) {
return false; return false;
} }
} else if (!this.string.equals(other.string)) { }
else if (!this.string.equals(other.string)) {
return false; return false;
} }
if (!Arrays.equals(this.strings, other.strings)) { if (!Arrays.equals(this.strings, other.strings)) {
@ -380,7 +422,8 @@ public class IdleTest extends BaseTest {
} }
@Override @Override
public String toString () { public
String toString() {
return "Data"; return "Data";
} }
} }

View File

@ -2,18 +2,19 @@
package dorkbox.network; package dorkbox.network;
import static org.junit.Assert.fail; import dorkbox.network.connection.Connection;
import dorkbox.network.connection.Listener;
import dorkbox.network.util.ConnectionSerializationManager;
import dorkbox.network.util.KryoConnectionSerializationManager;
import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException;
import org.junit.Test;
import java.io.IOException;
import java.security.SecureRandom; import java.security.SecureRandom;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test; import static org.junit.Assert.fail;
import dorkbox.network.connection.Connection;
import dorkbox.network.connection.Listener;
import dorkbox.network.util.SerializationManager;
import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException;
public class LargeBufferTest extends BaseTest { public class LargeBufferTest extends BaseTest {
private static final int OBJ_SIZE = 1024 * 10; private static final int OBJ_SIZE = 1024 * 10;
@ -23,19 +24,20 @@ public class LargeBufferTest extends BaseTest {
private volatile int clientCheck = -1; private volatile int clientCheck = -1;
@Test @Test
public void manyLargeMessages () throws InitializationException, SecurityException { public void manyLargeMessages () throws InitializationException, SecurityException, IOException {
final int messageCount = 1024; final int messageCount = 1024;
ConnectionOptions connectionOptions = new ConnectionOptions(); ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort; connectionOptions.tcpPort = tcpPort;
connectionOptions.udpPort = udpPort; connectionOptions.udpPort = udpPort;
connectionOptions.host = host; connectionOptions.host = host;
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT();
register(connectionOptions.serializationManager);
Server server = new Server(connectionOptions); Server server = new Server(connectionOptions);
server.disableRemoteKeyValidation(); server.disableRemoteKeyValidation();
addEndPoint(server); addEndPoint(server);
server.bind(false); server.bind(false);
register(server.getSerialization());
server.listeners().add(new Listener<LargeMessage>() { server.listeners().add(new Listener<LargeMessage>() {
AtomicInteger received = new AtomicInteger(); AtomicInteger received = new AtomicInteger();
@ -60,7 +62,6 @@ public class LargeBufferTest extends BaseTest {
Client client = new Client(connectionOptions); Client client = new Client(connectionOptions);
client.disableRemoteKeyValidation(); client.disableRemoteKeyValidation();
addEndPoint(client); addEndPoint(client);
register(client.getSerialization());
client.connect(5000); client.connect(5000);
client.listeners().add(new Listener<LargeMessage>() { client.listeners().add(new Listener<LargeMessage>() {
@ -105,7 +106,7 @@ public class LargeBufferTest extends BaseTest {
} }
} }
private void register (SerializationManager kryoMT) { private void register (ConnectionSerializationManager kryoMT) {
kryoMT.register(byte[].class); kryoMT.register(byte[].class);
kryoMT.register(LargeMessage.class); kryoMT.register(LargeMessage.class);
} }

View File

@ -1,24 +1,19 @@
package dorkbox.network; package dorkbox.network;
import static org.junit.Assert.assertEquals; import dorkbox.network.connection.*;
import static org.junit.Assert.assertTrue; import dorkbox.network.util.exceptions.InitializationException;
import static org.junit.Assert.fail; import dorkbox.network.util.exceptions.SecurityException;
import org.junit.Test;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test; import static org.junit.Assert.*;
import dorkbox.network.connection.Connection; public
import dorkbox.network.connection.ConnectionImpl; class ListenerTest extends BaseTest {
import dorkbox.network.connection.Listener;
import dorkbox.network.connection.ListenerRaw;
import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException;
public class ListenerTest extends BaseTest {
private final String origString = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; // lots of a's to encourage compression private final String origString = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; // lots of a's to encourage compression
private final int limit = 20; private final int limit = 20;
@ -31,24 +26,30 @@ public class ListenerTest extends BaseTest {
AtomicBoolean superClass2WorkedOK = new AtomicBoolean(false); AtomicBoolean superClass2WorkedOK = new AtomicBoolean(false);
AtomicBoolean disconnectWorkedOK = new AtomicBoolean(false); AtomicBoolean disconnectWorkedOK = new AtomicBoolean(false);
// quick and dirty test to also test connection sub-classing // quick and dirty test to also test connection sub-classing
class TestConnectionA extends ConnectionImpl { class TestConnectionA extends ConnectionImpl {
public TestConnectionA(String name) { public
super(name); TestConnectionA(Class<? extends EndPoint> type) {
super(type);
} }
public void check() { public
void check() {
ListenerTest.this.subClassWorkedOK.set(true); ListenerTest.this.subClassWorkedOK.set(true);
} }
} }
class TestConnectionB extends TestConnectionA { class TestConnectionB extends TestConnectionA {
public TestConnectionB(String name) { public
super(name); TestConnectionB(Class<? extends EndPoint> type) {
super(type);
} }
@Override @Override
public void check() { public
void check() {
ListenerTest.this.subClassWorkedOK.set(true); ListenerTest.this.subClassWorkedOK.set(true);
} }
} }
@ -57,15 +58,17 @@ public class ListenerTest extends BaseTest {
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
@Test @Test
public void listener() throws SecurityException, InitializationException { public
void listener() throws SecurityException, InitializationException, IOException {
ConnectionOptions connectionOptions = new ConnectionOptions(); ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort; connectionOptions.tcpPort = tcpPort;
connectionOptions.host = host; connectionOptions.host = host;
Server server = new Server(connectionOptions) { Server server = new Server(connectionOptions) {
@Override @Override
public TestConnectionA newConnection(String name) { public
return new TestConnectionA(name); TestConnectionA newConnection(Class<? extends EndPoint> type) {
return new TestConnectionA(type);
} }
}; };
@ -73,27 +76,34 @@ public class ListenerTest extends BaseTest {
addEndPoint(server); addEndPoint(server);
server.bind(false); server.bind(false);
server.listeners().add(new ListenerRaw<TestConnectionA, String>() { server.listeners()
.add(new ListenerRaw<TestConnectionA, String>() {
@Override @Override
public void received (TestConnectionA connection, String string) { public
void received(TestConnectionA connection, String string) {
connection.check(); connection.check();
// System.err.println("default check"); // System.err.println("default check");
connection.send().TCP(string); connection.send()
.TCP(string);
} }
}); });
server.listeners().add(new Listener<String>() { server.listeners()
.add(new Listener<String>() {
@Override @Override
public void received (Connection connection, String string) { public
void received(Connection connection, String string) {
// System.err.println("subclass check"); // System.err.println("subclass check");
ListenerTest.this.subClassWorkedOK2.set(true); ListenerTest.this.subClassWorkedOK2.set(true);
} }
}); });
// should be able to happen! // should be able to happen!
server.listeners().add(new Listener() { server.listeners()
.add(new Listener() {
@Override @Override
public void received(Connection connection, Object string) { public
void received(Connection connection, Object string) {
// System.err.println("generic class check"); // System.err.println("generic class check");
ListenerTest.this.superClassWorkedOK.set(true); ListenerTest.this.superClassWorkedOK.set(true);
} }
@ -101,17 +111,21 @@ public class ListenerTest extends BaseTest {
// should be able to happen! // should be able to happen!
server.listeners().add(new ListenerRaw() { server.listeners()
.add(new ListenerRaw() {
@Override @Override
public void received(Connection connection, Object string) { public
void received(Connection connection, Object string) {
// System.err.println("generic class check"); // System.err.println("generic class check");
ListenerTest.this.superClass2WorkedOK.set(true); ListenerTest.this.superClass2WorkedOK.set(true);
} }
}); });
server.listeners().add(new Listener() { server.listeners()
.add(new Listener() {
@Override @Override
public void disconnected(Connection connection) { public
void disconnected(Connection connection) {
// System.err.println("disconnect check"); // System.err.println("disconnect check");
ListenerTest.this.disconnectWorkedOK.set(true); ListenerTest.this.disconnectWorkedOK.set(true);
} }
@ -119,12 +133,15 @@ public class ListenerTest extends BaseTest {
// should not let this happen! // should not let this happen!
try { try {
server.listeners().add(new ListenerRaw<TestConnectionB, String>() { server.listeners()
.add(new ListenerRaw<TestConnectionB, String>() {
@Override @Override
public void received (TestConnectionB connection, String string) { public
void received(TestConnectionB connection, String string) {
connection.check(); connection.check();
System.err.println(string); System.err.println(string);
connection.send().TCP(string); connection.send()
.TCP(string);
} }
}); });
this.fail = "Should not be able to ADD listeners that are NOT the basetype or the interface"; this.fail = "Should not be able to ADD listeners that are NOT the basetype or the interface";
@ -139,18 +156,24 @@ public class ListenerTest extends BaseTest {
client.disableRemoteKeyValidation(); client.disableRemoteKeyValidation();
addEndPoint(client); addEndPoint(client);
client.listeners().add(new Listener<String>() { client.listeners()
.add(new Listener<String>() {
@Override @Override
public void connected (Connection connection) { public
connection.send().TCP(ListenerTest.this.origString); // 20 a's void connected(Connection connection) {
connection.send()
.TCP(ListenerTest.this.origString); // 20 a's
} }
@Override @Override
public void received (Connection connection, String string) { public
void received(Connection connection, String string) {
if (ListenerTest.this.count.get() < ListenerTest.this.limit) { if (ListenerTest.this.count.get() < ListenerTest.this.limit) {
ListenerTest.this.count.getAndIncrement(); ListenerTest.this.count.getAndIncrement();
connection.send().TCP(string); connection.send()
} else { .TCP(string);
}
else {
if (!ListenerTest.this.origString.equals(string)) { if (!ListenerTest.this.origString.equals(string)) {
ListenerTest.this.fail = "original string not equal to the string received"; ListenerTest.this.fail = "original string not equal to the string received";
} }

View File

@ -1,38 +1,42 @@
package dorkbox.network; package dorkbox.network;
import static org.junit.Assert.fail;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import dorkbox.network.connection.Connection; import dorkbox.network.connection.Connection;
import dorkbox.network.connection.Listener; import dorkbox.network.connection.Listener;
import dorkbox.network.util.KryoConnectionSerializationManager;
import dorkbox.network.util.exceptions.InitializationException; import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException; import dorkbox.network.util.exceptions.SecurityException;
import org.junit.Test;
public class MultipleServerTest extends BaseTest { import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.fail;
public
class MultipleServerTest extends BaseTest {
AtomicInteger received = new AtomicInteger(); AtomicInteger received = new AtomicInteger();
@Test @Test
public void multipleServers() throws InitializationException, SecurityException { public
void multipleServers() throws InitializationException, SecurityException, IOException {
ConnectionOptions connectionOptions1 = new ConnectionOptions(); ConnectionOptions connectionOptions1 = new ConnectionOptions();
connectionOptions1.tcpPort = tcpPort; connectionOptions1.tcpPort = tcpPort;
connectionOptions1.udpPort = udpPort; connectionOptions1.udpPort = udpPort;
connectionOptions1.localChannelName = "chan1"; connectionOptions1.localChannelName = "chan1";
connectionOptions1.serializationManager = KryoConnectionSerializationManager.DEFAULT();
connectionOptions1.serializationManager.register(String[].class);
Server server1 = new Server(connectionOptions1); Server server1 = new Server(connectionOptions1);
server1.disableRemoteKeyValidation(); server1.disableRemoteKeyValidation();
server1.getSerialization().register(String[].class);
addEndPoint(server1); addEndPoint(server1);
server1.bind(false); server1.bind(false);
server1.listeners().add(new Listener<String>() { server1.listeners()
.add(new Listener<String>() {
@Override @Override
public void received (Connection connection, String object) { public
void received(Connection connection, String object) {
if (!object.equals("client1")) { if (!object.equals("client1")) {
fail(); fail();
} }
@ -46,16 +50,19 @@ public class MultipleServerTest extends BaseTest {
connectionOptions2.tcpPort = tcpPort + 1; connectionOptions2.tcpPort = tcpPort + 1;
connectionOptions2.udpPort = udpPort + 1; connectionOptions2.udpPort = udpPort + 1;
connectionOptions2.localChannelName = "chan2"; connectionOptions2.localChannelName = "chan2";
connectionOptions2.serializationManager = KryoConnectionSerializationManager.DEFAULT();
connectionOptions2.serializationManager.register(String[].class);
Server server2 = new Server(connectionOptions2); Server server2 = new Server(connectionOptions2);
server2.disableRemoteKeyValidation(); server2.disableRemoteKeyValidation();
server2.getSerialization().register(String[].class);
addEndPoint(server2); addEndPoint(server2);
server2.bind(false); server2.bind(false);
server2.listeners().add(new Listener<String>() { server2.listeners()
.add(new Listener<String>() {
@Override @Override
public void received (Connection connection, String object) { public
void received(Connection connection, String object) {
if (!object.equals("client2")) { if (!object.equals("client2")) {
fail(); fail();
} }
@ -72,12 +79,14 @@ public class MultipleServerTest extends BaseTest {
Client client1 = new Client(connectionOptions1); Client client1 = new Client(connectionOptions1);
client1.disableRemoteKeyValidation(); client1.disableRemoteKeyValidation();
client1.getSerialization().register(String[].class);
addEndPoint(client1); addEndPoint(client1);
client1.listeners().add(new Listener<String>() { client1.listeners()
.add(new Listener<String>() {
@Override @Override
public void connected (Connection connection) { public
connection.send().TCP("client1"); void connected(Connection connection) {
connection.send()
.TCP("client1");
} }
}); });
client1.connect(5000); client1.connect(5000);
@ -88,12 +97,14 @@ public class MultipleServerTest extends BaseTest {
Client client2 = new Client(connectionOptions2); Client client2 = new Client(connectionOptions2);
client2.disableRemoteKeyValidation(); client2.disableRemoteKeyValidation();
client2.getSerialization().register(String[].class);
addEndPoint(client2); addEndPoint(client2);
client2.listeners().add(new Listener<String>() { client2.listeners()
.add(new Listener<String>() {
@Override @Override
public void connected (Connection connection) { public
connection.send().TCP("client2"); void connected(Connection connection) {
connection.send()
.TCP("client2");
} }
}); });
client2.connect(5000); client2.connect(5000);

View File

@ -1,23 +1,24 @@
package dorkbox.network; package dorkbox.network;
import static org.junit.Assert.assertEquals; import dorkbox.network.connection.Connection;
import dorkbox.network.connection.Listener;
import dorkbox.network.util.KryoConnectionSerializationManager;
import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException;
import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test; import static org.junit.Assert.assertEquals;
import dorkbox.network.connection.Connection; public
import dorkbox.network.connection.Listener; class MultipleThreadTest extends BaseTest {
import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException;
public class MultipleThreadTest extends BaseTest {
AtomicInteger sent = new AtomicInteger(0); AtomicInteger sent = new AtomicInteger(0);
AtomicInteger totalClientCounter = new AtomicInteger(1); AtomicInteger totalClientCounter = new AtomicInteger(1);
AtomicInteger receivedServer = new AtomicInteger(1); AtomicInteger receivedServer = new AtomicInteger(1);
@ -29,26 +30,32 @@ public class MultipleThreadTest extends BaseTest {
private final int threadCount = 15; private final int threadCount = 15;
private final int clientCount = 13; private final int clientCount = 13;
private List<Client> clients = new ArrayList<Client>(this.clientCount); private final List<Client> clients = new ArrayList<Client>(this.clientCount);
@Test @Test
public void multipleThreads () throws InitializationException, SecurityException { public
void multipleThreads() throws InitializationException, SecurityException, IOException {
final KryoConnectionSerializationManager serializationManager = KryoConnectionSerializationManager.DEFAULT(false, true);
serializationManager.register(String[].class);
serializationManager.register(DataClass.class);
ConnectionOptions connectionOptions = new ConnectionOptions(); ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort; connectionOptions.tcpPort = tcpPort;
connectionOptions.host = host; connectionOptions.host = host;
connectionOptions.serializationManager = serializationManager;
final Server server = new Server(connectionOptions); final Server server = new Server(connectionOptions);
server.disableRemoteKeyValidation(); server.disableRemoteKeyValidation();
server.getSerialization().register(String[].class);
server.getSerialization().register(DataClass.class);
addEndPoint(server); addEndPoint(server);
server.bind(false); server.bind(false);
server.listeners().add(new Listener<DataClass>() { server.listeners()
.add(new Listener<DataClass>() {
@Override @Override
public void connected(final Connection connection) { public
void connected(final Connection connection) {
System.err.println("Client connected to server."); System.err.println("Client connected to server.");
// kickoff however many threads we need, and send data to the client. // kickoff however many threads we need, and send data to the client.
@ -56,12 +63,17 @@ public class MultipleThreadTest extends BaseTest {
final int index = i; final int index = i;
new Thread() { new Thread() {
@Override @Override
public void run () { public
void run() {
for (int i = 1; i <= MultipleThreadTest.this.messageCount; i++) { for (int i = 1; i <= MultipleThreadTest.this.messageCount; i++) {
int incrementAndGet = MultipleThreadTest.this.sent.getAndIncrement(); int incrementAndGet = MultipleThreadTest.this.sent.getAndIncrement();
DataClass dataClass = new DataClass("Server -> client. Thread #" + index + " message# " + incrementAndGet, incrementAndGet); DataClass dataClass = new DataClass(
"Server -> client. Thread #" + index + " message# " + incrementAndGet,
incrementAndGet);
MultipleThreadTest.this.sentStringsToClientDebug.put(incrementAndGet, dataClass); MultipleThreadTest.this.sentStringsToClientDebug.put(incrementAndGet, dataClass);
connection.send().TCP(dataClass).flush(); connection.send()
.TCP(dataClass)
.flush();
} }
} }
}.start(); }.start();
@ -70,7 +82,8 @@ public class MultipleThreadTest extends BaseTest {
@Override @Override
public void received (Connection connection, DataClass object) { public
void received(Connection connection, DataClass object) {
int incrementAndGet = MultipleThreadTest.this.receivedServer.getAndIncrement(); int incrementAndGet = MultipleThreadTest.this.receivedServer.getAndIncrement();
@ -94,28 +107,33 @@ public class MultipleThreadTest extends BaseTest {
client.disableRemoteKeyValidation(); client.disableRemoteKeyValidation();
this.clients.add(client); this.clients.add(client);
client.getSerialization().register(String[].class);
client.getSerialization().register(DataClass.class);
addEndPoint(client); addEndPoint(client);
client.listeners().add(new Listener<DataClass>() { client.listeners()
.add(new Listener<DataClass>() {
AtomicInteger received = new AtomicInteger(1); AtomicInteger received = new AtomicInteger(1);
@Override @Override
public void connected(Connection connection) { public
void connected(Connection connection) {
System.err.println("Client #" + index + " connected."); System.err.println("Client #" + index + " connected.");
} }
@Override @Override
public void received (Connection connection, DataClass object) { public
void received(Connection connection, DataClass object) {
int clientLocalCounter = this.received.getAndIncrement(); int clientLocalCounter = this.received.getAndIncrement();
MultipleThreadTest.this.sentStringsToClientDebug.remove(object.index); MultipleThreadTest.this.sentStringsToClientDebug.remove(object.index);
// we finished!! // we finished!!
if (clientLocalCounter == MultipleThreadTest.this.messageCount * MultipleThreadTest.this.threadCount) { if (clientLocalCounter == MultipleThreadTest.this.messageCount * MultipleThreadTest.this.threadCount) {
System.err.println("Client #" + index + " received " + clientLocalCounter + " (" + MultipleThreadTest.this.totalClientCounter.getAndIncrement() + ") Sending back " + MultipleThreadTest.this.messageCount + " messages."); System.err.println("Client #" + index + " received " + clientLocalCounter + " (" +
MultipleThreadTest.this.totalClientCounter.getAndIncrement() + ") Sending back " +
MultipleThreadTest.this.messageCount + " messages.");
// now spam back messages! // now spam back messages!
for (int i = 0; i < MultipleThreadTest.this.messageCount; i++) { for (int i = 0; i < MultipleThreadTest.this.messageCount; i++) {
connection.send().TCP(new DataClass("Client #" + index + " -> Server message " + i, index)); connection.send()
.TCP(new DataClass("Client #" + index + " -> Server message " + i, index));
} }
} }
} }
@ -127,7 +145,8 @@ public class MultipleThreadTest extends BaseTest {
// the ONLY way to safely work in the server is with LISTENERS. Everything else can FAIL, because of it's async. nature. // the ONLY way to safely work in the server is with LISTENERS. Everything else can FAIL, because of it's async. nature.
// our clients should receive messageCount * threadCount * clientCount TOTAL messages // our clients should receive messageCount * threadCount * clientCount TOTAL messages
System.err.println("SEND COUNTS: " + this.threadCount * this.clientCount * this.messageCount + " and then " + this.messageCount * this.clientCount + " total messages"); System.err.println("SEND COUNTS: " + this.threadCount * this.clientCount * this.messageCount + " and then " +
this.messageCount * this.clientCount + " total messages");
synchronized (this.lock) { synchronized (this.lock) {
try { try {
@ -148,14 +167,17 @@ public class MultipleThreadTest extends BaseTest {
assertEquals(this.messageCount * this.clientCount, this.receivedServer.get() - 1); // offset by 1 since we start at 1. assertEquals(this.messageCount * this.clientCount, this.receivedServer.get() - 1); // offset by 1 since we start at 1.
} }
public static class DataClass { public static
class DataClass {
public String data; public String data;
public Integer index; public Integer index;
public DataClass() { public
DataClass() {
} }
public DataClass(String data, Integer index) { public
DataClass(String data, Integer index) {
this.data = data; this.data = data;
this.index = index; this.index = index;
} }

View File

@ -1,25 +1,25 @@
package dorkbox.network; package dorkbox.network;
import static org.junit.Assert.fail; import dorkbox.network.connection.Connection;
import dorkbox.network.connection.Listener;
import dorkbox.network.util.ConnectionSerializationManager;
import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException;
import org.junit.Test;
import java.io.IOException;
import java.util.Arrays; import java.util.Arrays;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test; import static org.junit.Assert.fail;
import dorkbox.network.connection.Connection;
import dorkbox.network.connection.Listener;
import dorkbox.network.util.SerializationManager;
import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException;
public class PingPongLocalTest extends BaseTest { public class PingPongLocalTest extends BaseTest {
private volatile String fail; private volatile String fail;
int tries = 10000; int tries = 10000;
@Test @Test
public void pingPongLocal() throws InitializationException, SecurityException { public void pingPongLocal() throws InitializationException, SecurityException, IOException {
this.fail = "Data not received."; this.fail = "Data not received.";
final Data dataLOCAL = new Data(); final Data dataLOCAL = new Data();
@ -126,7 +126,7 @@ public class PingPongLocalTest extends BaseTest {
data.Booleans = new Boolean[] {true,false}; data.Booleans = new Boolean[] {true,false};
} }
private void register(SerializationManager kryoMT) { private void register(ConnectionSerializationManager kryoMT) {
kryoMT.register(int[].class); kryoMT.register(int[].class);
kryoMT.register(short[].class); kryoMT.register(short[].class);
kryoMT.register(float[].class); kryoMT.register(float[].class);

View File

@ -1,33 +1,36 @@
package dorkbox.network; package dorkbox.network;
import static org.junit.Assert.fail;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import dorkbox.network.connection.Connection; import dorkbox.network.connection.Connection;
import dorkbox.network.connection.EndPoint; import dorkbox.network.connection.EndPoint;
import dorkbox.network.connection.Listener; import dorkbox.network.connection.Listener;
import dorkbox.network.util.SerializationManager; import dorkbox.network.util.ConnectionSerializationManager;
import dorkbox.network.util.KryoConnectionSerializationManager;
import dorkbox.network.util.exceptions.InitializationException; import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException; import dorkbox.network.util.exceptions.SecurityException;
import org.junit.Test;
public class PingPongTest extends BaseTest { import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.fail;
public
class PingPongTest extends BaseTest {
private volatile String fail; private volatile String fail;
int tries = 1000; int tries = 1000;
enum TYPE { enum TYPE {
TCP, UDP, UDT TCP, UDP, UDT
} }
@Test @Test
public void pingPong () throws InitializationException, SecurityException { public
void pingPong() throws InitializationException, SecurityException, IOException {
// UDP data is kinda big. Make sure it fits into one packet. // UDP data is kinda big. Make sure it fits into one packet.
int origSize = EndPoint.udpMaxSize; int origSize = EndPoint.udpMaxSize;
EndPoint.udpMaxSize = 2048; EndPoint.udpMaxSize = 2048;
@ -39,6 +42,8 @@ public class PingPongTest extends BaseTest {
connectionOptions.udpPort = udpPort; connectionOptions.udpPort = udpPort;
connectionOptions.udtPort = udtPort; connectionOptions.udtPort = udtPort;
connectionOptions.host = host; connectionOptions.host = host;
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT();
register(connectionOptions.serializationManager);
final Data dataTCP = new Data(); final Data dataTCP = new Data();
populateData(dataTCP, TYPE.TCP); populateData(dataTCP, TYPE.TCP);
@ -50,36 +55,41 @@ public class PingPongTest extends BaseTest {
Server server = new Server(connectionOptions); Server server = new Server(connectionOptions);
server.disableRemoteKeyValidation(); server.disableRemoteKeyValidation();
addEndPoint(server); addEndPoint(server);
register(server.getSerialization());
server.bind(false); server.bind(false);
server.listeners().add(new Listener<Data>() { server.listeners()
.add(new Listener<Data>() {
@Override @Override
public void error(Connection connection, Throwable throwable) { public
void error(Connection connection, Throwable throwable) {
PingPongTest.this.fail = "Error during processing. " + throwable; PingPongTest.this.fail = "Error during processing. " + throwable;
} }
@Override @Override
public void received (Connection connection, Data data) { public
void received(Connection connection, Data data) {
if (data.type == TYPE.TCP) { if (data.type == TYPE.TCP) {
if (!data.equals(dataTCP)) { if (!data.equals(dataTCP)) {
PingPongTest.this.fail = "TCP data is not equal on server."; PingPongTest.this.fail = "TCP data is not equal on server.";
throw new RuntimeException("Fail! " + PingPongTest.this.fail); throw new RuntimeException("Fail! " + PingPongTest.this.fail);
} }
connection.send().TCP(data); connection.send()
.TCP(data);
} }
else if (data.type == TYPE.UDP) { else if (data.type == TYPE.UDP) {
if (!data.equals(dataUDP)) { if (!data.equals(dataUDP)) {
PingPongTest.this.fail = "UDP data is not equal on server."; PingPongTest.this.fail = "UDP data is not equal on server.";
throw new RuntimeException("Fail! " + PingPongTest.this.fail); throw new RuntimeException("Fail! " + PingPongTest.this.fail);
} }
connection.send().UDP(data); connection.send()
.UDP(data);
} }
else if (data.type == TYPE.UDT) { else if (data.type == TYPE.UDT) {
if (!data.equals(dataUDT)) { if (!data.equals(dataUDT)) {
PingPongTest.this.fail = "UDT data is not equal on server."; PingPongTest.this.fail = "UDT data is not equal on server.";
throw new RuntimeException("Fail! " + PingPongTest.this.fail); throw new RuntimeException("Fail! " + PingPongTest.this.fail);
} }
connection.send().UDT(data); connection.send()
.UDT(data);
} }
else { else {
PingPongTest.this.fail = "Unknown data type on server."; PingPongTest.this.fail = "Unknown data type on server.";
@ -93,8 +103,8 @@ public class PingPongTest extends BaseTest {
Client client = new Client(connectionOptions); Client client = new Client(connectionOptions);
client.disableRemoteKeyValidation(); client.disableRemoteKeyValidation();
addEndPoint(client); addEndPoint(client);
register(client.getSerialization()); client.listeners()
client.listeners().add(new Listener<Data>() { .add(new Listener<Data>() {
AtomicInteger checkTCP = new AtomicInteger(0); AtomicInteger checkTCP = new AtomicInteger(0);
AtomicInteger checkUDP = new AtomicInteger(0); AtomicInteger checkUDP = new AtomicInteger(0);
AtomicInteger checkUDT = new AtomicInteger(0); AtomicInteger checkUDT = new AtomicInteger(0);
@ -103,55 +113,70 @@ public class PingPongTest extends BaseTest {
AtomicBoolean doneUDT = new AtomicBoolean(false); AtomicBoolean doneUDT = new AtomicBoolean(false);
@Override @Override
public void connected (Connection connection) { public
void connected(Connection connection) {
PingPongTest.this.fail = null; PingPongTest.this.fail = null;
connection.send().TCP(dataTCP); connection.send()
connection.send().UDP(dataUDP); // UDP ping pong stops if a UDP packet is lost. .TCP(dataTCP);
connection.send().UDT(dataUDT); connection.send()
.UDP(dataUDP); // UDP ping pong stops if a UDP packet is lost.
connection.send()
.UDT(dataUDT);
} }
@Override @Override
public void error(Connection connection, Throwable throwable) { public
void error(Connection connection, Throwable throwable) {
PingPongTest.this.fail = "Error during processing. " + throwable; PingPongTest.this.fail = "Error during processing. " + throwable;
throwable.printStackTrace(); throwable.printStackTrace();
} }
@Override @Override
public void received (Connection connection, Data data) { public
void received(Connection connection, Data data) {
if (data.type == TYPE.TCP) { if (data.type == TYPE.TCP) {
if (!data.equals(dataTCP)) { if (!data.equals(dataTCP)) {
PingPongTest.this.fail = "TCP data is not equal on client."; PingPongTest.this.fail = "TCP data is not equal on client.";
throw new RuntimeException("Fail! " + PingPongTest.this.fail); throw new RuntimeException("Fail! " + PingPongTest.this.fail);
} }
if (this.checkTCP.getAndIncrement() <= PingPongTest.this.tries) { if (this.checkTCP.getAndIncrement() <= PingPongTest.this.tries) {
connection.send().TCP(data); connection.send()
} else { .TCP(data);
}
else {
System.err.println("TCP done."); System.err.println("TCP done.");
this.doneTCP.set(true); this.doneTCP.set(true);
} }
} else if (data.type == TYPE.UDP) { }
else if (data.type == TYPE.UDP) {
if (!data.equals(dataUDP)) { if (!data.equals(dataUDP)) {
PingPongTest.this.fail = "UDP data is not equal on client."; PingPongTest.this.fail = "UDP data is not equal on client.";
throw new RuntimeException("Fail! " + PingPongTest.this.fail); throw new RuntimeException("Fail! " + PingPongTest.this.fail);
} }
if (this.checkUDP.getAndIncrement() <= PingPongTest.this.tries) { if (this.checkUDP.getAndIncrement() <= PingPongTest.this.tries) {
connection.send().UDP(data); connection.send()
} else { .UDP(data);
}
else {
System.err.println("UDP done."); System.err.println("UDP done.");
this.doneUDP.set(true); this.doneUDP.set(true);
} }
} else if (data.type == TYPE.UDT) { }
else if (data.type == TYPE.UDT) {
if (!data.equals(dataUDT)) { if (!data.equals(dataUDT)) {
PingPongTest.this.fail = "UDT data is not equal on client."; PingPongTest.this.fail = "UDT data is not equal on client.";
throw new RuntimeException("Fail! " + PingPongTest.this.fail); throw new RuntimeException("Fail! " + PingPongTest.this.fail);
} }
if (this.checkUDT.getAndIncrement() <= PingPongTest.this.tries) { if (this.checkUDT.getAndIncrement() <= PingPongTest.this.tries) {
connection.send().UDT(data); connection.send()
} else { .UDT(data);
}
else {
System.err.println("UDT done."); System.err.println("UDT done.");
this.doneUDT.set(true); this.doneUDT.set(true);
} }
} else { }
else {
PingPongTest.this.fail = "Unknown data type on client."; PingPongTest.this.fail = "Unknown data type on client.";
throw new RuntimeException("Fail! " + PingPongTest.this.fail); throw new RuntimeException("Fail! " + PingPongTest.this.fail);
} }
@ -174,7 +199,8 @@ public class PingPongTest extends BaseTest {
EndPoint.udpMaxSize = origSize; EndPoint.udpMaxSize = origSize;
} }
private void populateData (Data data, TYPE type) { private
void populateData(Data data, TYPE type) {
data.type = type; data.type = type;
StringBuilder buffer = new StringBuilder(); StringBuilder buffer = new StringBuilder();
@ -196,7 +222,8 @@ public class PingPongTest extends BaseTest {
data.booleans = new boolean[] {true, false}; data.booleans = new boolean[] {true, false};
data.Ints = new Integer[] {-1234567, 1234567, -1, 0, 1, Integer.MAX_VALUE, Integer.MIN_VALUE}; data.Ints = new Integer[] {-1234567, 1234567, -1, 0, 1, Integer.MAX_VALUE, Integer.MIN_VALUE};
data.Shorts = new Short[] {-12345, 12345, -1, 0, 1, Short.MAX_VALUE, Short.MIN_VALUE}; data.Shorts = new Short[] {-12345, 12345, -1, 0, 1, Short.MAX_VALUE, Short.MIN_VALUE};
data.Floats = new Float[] {0f, -0f, 1f, -1f, 123456f, -123456f, 0.1f, 0.2f, -0.3f, (float)Math.PI, Float.MAX_VALUE, Float.MIN_VALUE}; data.Floats = new Float[] {0f, -0f, 1f, -1f, 123456f, -123456f, 0.1f, 0.2f, -0.3f, (float) Math.PI, Float.MAX_VALUE,
Float.MIN_VALUE};
data.Doubles = new Double[] {0d, -0d, 1d, -1d, 123456d, -123456d, 0.1d, 0.2d, -0.3d, Math.PI, Double.MAX_VALUE, Double.MIN_VALUE}; data.Doubles = new Double[] {0d, -0d, 1d, -1d, 123456d, -123456d, 0.1d, 0.2d, -0.3d, Math.PI, Double.MAX_VALUE, Double.MIN_VALUE};
data.Longs = new Long[] {0l, -0l, 1l, -1l, 123456l, -123456l, 99999999999l, -99999999999l, Long.MAX_VALUE, Long.MIN_VALUE}; data.Longs = new Long[] {0l, -0l, 1l, -1l, 123456l, -123456l, 99999999999l, -99999999999l, Long.MAX_VALUE, Long.MIN_VALUE};
data.Bytes = new Byte[] {-123, 123, -1, 0, 1, Byte.MAX_VALUE, Byte.MIN_VALUE}; data.Bytes = new Byte[] {-123, 123, -1, 0, 1, Byte.MAX_VALUE, Byte.MIN_VALUE};
@ -204,7 +231,8 @@ public class PingPongTest extends BaseTest {
data.Booleans = new Boolean[] {true, false}; data.Booleans = new Boolean[] {true, false};
} }
private void register (SerializationManager kryoMT) { private
void register(ConnectionSerializationManager kryoMT) {
kryoMT.register(int[].class); kryoMT.register(int[].class);
kryoMT.register(short[].class); kryoMT.register(short[].class);
kryoMT.register(float[].class); kryoMT.register(float[].class);
@ -226,7 +254,8 @@ public class PingPongTest extends BaseTest {
kryoMT.register(TYPE.class); kryoMT.register(TYPE.class);
} }
static public class Data { static public
class Data {
public TYPE type; public TYPE type;
public String string; public String string;
public String[] strings; public String[] strings;
@ -249,7 +278,8 @@ public class PingPongTest extends BaseTest {
@Override @Override
public int hashCode() { public
int hashCode() {
final int prime = 31; final int prime = 31;
int result = 1; int result = 1;
result = prime * result + Arrays.hashCode(this.Booleans); result = prime * result + Arrays.hashCode(this.Booleans);
@ -275,7 +305,8 @@ public class PingPongTest extends BaseTest {
} }
@Override @Override
public boolean equals(Object obj) { public
boolean equals(Object obj) {
if (this == obj) { if (this == obj) {
return true; return true;
} }
@ -338,7 +369,8 @@ public class PingPongTest extends BaseTest {
if (other.string != null) { if (other.string != null) {
return false; return false;
} }
} else if (!this.string.equals(other.string)) { }
else if (!this.string.equals(other.string)) {
return false; return false;
} }
if (!Arrays.equals(this.strings, other.strings)) { if (!Arrays.equals(this.strings, other.strings)) {
@ -351,7 +383,8 @@ public class PingPongTest extends BaseTest {
} }
@Override @Override
public String toString () { public
String toString() {
return "Data"; return "Data";
} }
} }

View File

@ -1,25 +1,27 @@
package dorkbox.network; package dorkbox.network;
import static org.junit.Assert.fail;
import org.junit.Test;
import dorkbox.network.connection.Connection; import dorkbox.network.connection.Connection;
import dorkbox.network.connection.Ping; import dorkbox.network.connection.Ping;
import dorkbox.network.connection.PingListener; import dorkbox.network.connection.PingListener;
import dorkbox.network.util.exceptions.InitializationException; import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException; import dorkbox.network.util.exceptions.SecurityException;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.fail;
public class PingTest extends BaseTest { public
class PingTest extends BaseTest {
private volatile int response = -1; private volatile int response = -1;
// ping prefers the following order: UDP, UDT, TCP // ping prefers the following order: UDP, UDT, TCP
@Test @Test
public void pingTCP() throws InitializationException, SecurityException { public
void pingTCP() throws InitializationException, SecurityException, IOException {
this.response = -1; this.response = -1;
ConnectionOptions connectionOptions = new ConnectionOptions(); ConnectionOptions connectionOptions = new ConnectionOptions();
@ -41,7 +43,9 @@ public class PingTest extends BaseTest {
System.err.println("Testing TCP ping"); System.err.println("Testing TCP ping");
for (int i = 0; i < 10; i++) { for (int i = 0; i < 10; i++) {
this.response = client.send().ping().getResponse(); this.response = client.send()
.ping()
.getResponse();
System.err.println("Ping: " + this.response); System.err.println("Ping: " + this.response);
} }
@ -52,7 +56,8 @@ public class PingTest extends BaseTest {
} }
@Test @Test
public void pingTCP_testListeners1() throws InitializationException, SecurityException { public
void pingTCP_testListeners1() throws InitializationException, SecurityException, IOException {
this.response = -1; this.response = -1;
ConnectionOptions connectionOptions = new ConnectionOptions(); ConnectionOptions connectionOptions = new ConnectionOptions();
@ -78,12 +83,16 @@ public class PingTest extends BaseTest {
volatile int count = 0; volatile int count = 0;
@Override @Override
public void response(Connection connection, int pingResponseTime) { public
void response(Connection connection, int pingResponseTime) {
System.err.println("Ping: " + pingResponseTime); System.err.println("Ping: " + pingResponseTime);
if (this.count++ < 10) { if (this.count++ < 10) {
connection.send().ping().addListener(this); connection.send()
} else { .ping()
.addListener(this);
}
else {
PingTest.this.response = pingResponseTime; PingTest.this.response = pingResponseTime;
stopEndPoints(); stopEndPoints();
} }
@ -92,7 +101,8 @@ public class PingTest extends BaseTest {
// alternate way to register for the receipt of a one-off ping response // alternate way to register for the receipt of a one-off ping response
// doesn't matter how many times this is called. If there is a PING waiting, then it's overwritten // doesn't matter how many times this is called. If there is a PING waiting, then it's overwritten
Ping ping = client.send().ping(); Ping ping = client.send()
.ping();
ping.addListener(pingListener); ping.addListener(pingListener);
waitForThreads(); waitForThreads();
@ -103,7 +113,8 @@ public class PingTest extends BaseTest {
} }
@Test @Test
public void pingTCP_testListeners2() throws InitializationException, SecurityException { public
void pingTCP_testListeners2() throws InitializationException, SecurityException, IOException {
this.response = -1; this.response = -1;
ConnectionOptions connectionOptions = new ConnectionOptions(); ConnectionOptions connectionOptions = new ConnectionOptions();
@ -127,7 +138,8 @@ public class PingTest extends BaseTest {
final PingListener<Connection> pingListener = new PingListener<Connection>() { final PingListener<Connection> pingListener = new PingListener<Connection>() {
@Override @Override
public void response(Connection connection, int pingResponseTime) { public
void response(Connection connection, int pingResponseTime) {
System.err.println("Ping: " + pingResponseTime); System.err.println("Ping: " + pingResponseTime);
PingTest.this.response = pingResponseTime; PingTest.this.response = pingResponseTime;
stopEndPoints(); stopEndPoints();
@ -137,7 +149,8 @@ public class PingTest extends BaseTest {
// alternate way to register for the receipt of a one-off ping response // alternate way to register for the receipt of a one-off ping response
// doesn't matter how many times this is called. If there is a PING waiting, then it's overwritten // doesn't matter how many times this is called. If there is a PING waiting, then it's overwritten
Ping ping = client.send().ping(); Ping ping = client.send()
.ping();
ping.addListener(pingListener); ping.addListener(pingListener);
waitForThreads(); waitForThreads();
@ -149,7 +162,8 @@ public class PingTest extends BaseTest {
// ping prefers the following order: UDP, UDT, TCP // ping prefers the following order: UDP, UDT, TCP
@Test @Test
public void pingUDP() throws InitializationException, SecurityException { public
void pingUDP() throws InitializationException, SecurityException, IOException {
this.response = -1; this.response = -1;
ConnectionOptions connectionOptions = new ConnectionOptions(); ConnectionOptions connectionOptions = new ConnectionOptions();
@ -173,7 +187,9 @@ public class PingTest extends BaseTest {
System.err.println("Testing UDP ping"); System.err.println("Testing UDP ping");
for (int i = 0; i < 10; i++) { for (int i = 0; i < 10; i++) {
this.response = client.send().ping().getResponse(); this.response = client.send()
.ping()
.getResponse();
System.err.println("Ping: " + this.response); System.err.println("Ping: " + this.response);
} }
@ -187,7 +203,8 @@ public class PingTest extends BaseTest {
// ping prefers the following order: UDP, UDT, TCP // ping prefers the following order: UDP, UDT, TCP
@Test @Test
public void pingUDT() throws InitializationException, SecurityException { public
void pingUDT() throws InitializationException, SecurityException, IOException {
this.response = -1; this.response = -1;
ConnectionOptions connectionOptions = new ConnectionOptions(); ConnectionOptions connectionOptions = new ConnectionOptions();
@ -210,7 +227,9 @@ public class PingTest extends BaseTest {
System.err.println("Testing UDT ping"); System.err.println("Testing UDT ping");
for (int i = 0; i < 10; i++) { for (int i = 0; i < 10; i++) {
this.response = client.send().ping().getResponse(); this.response = client.send()
.ping()
.getResponse();
System.err.println("Ping: " + this.response); System.err.println("Ping: " + this.response);
} }

View File

@ -1,24 +1,25 @@
package dorkbox.network; package dorkbox.network;
import static org.junit.Assert.assertEquals;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import dorkbox.network.connection.Connection; import dorkbox.network.connection.Connection;
import dorkbox.network.connection.Listener; import dorkbox.network.connection.Listener;
import dorkbox.network.util.exceptions.InitializationException; import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException; import dorkbox.network.util.exceptions.SecurityException;
import org.junit.Test;
public class ReconnectTest extends BaseTest { import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals;
public
class ReconnectTest extends BaseTest {
@Test @Test
public void reconnect() throws InitializationException, SecurityException { public
void reconnect() throws InitializationException, SecurityException, IOException {
final Timer timer = new Timer(); final Timer timer = new Timer();
ConnectionOptions connectionOptions = new ConnectionOptions(); ConnectionOptions connectionOptions = new ConnectionOptions();
@ -30,12 +31,15 @@ public class ReconnectTest extends BaseTest {
server.disableRemoteKeyValidation(); server.disableRemoteKeyValidation();
addEndPoint(server); addEndPoint(server);
server.bind(false); server.bind(false);
server.listeners().add(new Listener<Object>() { server.listeners()
.add(new Listener<Object>() {
@Override @Override
public void connected(final Connection connection) { public
void connected(final Connection connection) {
timer.schedule(new TimerTask() { timer.schedule(new TimerTask() {
@Override @Override
public void run () { public
void run() {
System.out.println("Disconnecting after 2 seconds."); System.out.println("Disconnecting after 2 seconds.");
connection.close(); connection.close();
} }
@ -49,16 +53,19 @@ public class ReconnectTest extends BaseTest {
final Client client = new Client(connectionOptions); final Client client = new Client(connectionOptions);
client.disableRemoteKeyValidation(); client.disableRemoteKeyValidation();
addEndPoint(client); addEndPoint(client);
client.listeners().add(new Listener<Object>() { client.listeners()
.add(new Listener<Object>() {
@Override @Override
public void disconnected (Connection connection) { public
void disconnected(Connection connection) {
if (reconnectCount.getAndIncrement() == 2) { if (reconnectCount.getAndIncrement() == 2) {
stopEndPoints(); stopEndPoints();
return; return;
} }
new Thread() { new Thread() {
@Override @Override
public void run () { public
void run() {
System.out.println("Reconnecting: " + reconnectCount.get()); System.out.println("Reconnecting: " + reconnectCount.get());
client.reconnect(); client.reconnect();
} }

View File

@ -1,23 +1,27 @@
package dorkbox.network; package dorkbox.network;
import java.lang.reflect.Method; import dorkbox.network.connection.EndPoint;
import dorkbox.network.util.exceptions.SecurityException;
import dorkbox.network.util.store.SettingsStore;
import dorkbox.util.SerializationManager;
import dorkbox.util.storage.Storage;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters; import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters; import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.junit.Test; import org.junit.Test;
import dorkbox.network.util.exceptions.SecurityException; import java.io.IOException;
import dorkbox.network.util.store.SettingsStore; import java.lang.reflect.Method;
public class ReflectionSecurityTest extends BaseTest { public
class ReflectionSecurityTest extends BaseTest {
private static boolean RUN_TEST = false; private static boolean RUN_TEST = false;
@Test @Test
public void directInvocation() { public
void directInvocation() {
if (!RUN_TEST) { if (!RUN_TEST) {
System.out.println(" Not running test -- Skipping DirectInvocation test."); System.out.println(" Not running test -- Skipping DirectInvocation test.");
// since we exit the JVM on failure, we only run the test in special test-cases, not every time. // since we exit the JVM on failure, we only run the test in special test-cases, not every time.
@ -30,7 +34,8 @@ public class ReflectionSecurityTest extends BaseTest {
} }
@Test @Test
public void reflectionInvocationA() throws Exception { public
void reflectionInvocationA() throws Exception {
if (!RUN_TEST) { if (!RUN_TEST) {
// since we exit the JVM on failure, we only run the test in special test-cases, not every time. // since we exit the JVM on failure, we only run the test in special test-cases, not every time.
System.out.println(" Not running test -- Skipping ReflectionInvocationA test."); System.out.println(" Not running test -- Skipping ReflectionInvocationA test.");
@ -58,7 +63,8 @@ public class ReflectionSecurityTest extends BaseTest {
} }
@Test @Test
public void reflectionInvocationB() throws Exception { public
void reflectionInvocationB() throws Exception {
if (!RUN_TEST) { if (!RUN_TEST) {
// since we exit the JVM on failure, we only run the test in special test-cases, not every time. // since we exit the JVM on failure, we only run the test in special test-cases, not every time.
System.out.println(" Not running test -- Skipping ReflectionInvocationB test."); System.out.println(" Not running test -- Skipping ReflectionInvocationB test.");
@ -87,7 +93,8 @@ public class ReflectionSecurityTest extends BaseTest {
} }
@Test @Test
public void correctInvocation() throws SecurityException { public
void correctInvocation() throws SecurityException {
SettingsStore connectionStore = new ConnectionTestStore(); SettingsStore connectionStore = new ConnectionTestStore();
connectionStore.getPrivateKey(); connectionStore.getPrivateKey();
// if it's NOT successful, the JVM will shutdown! // if it's NOT successful, the JVM will shutdown!
@ -95,51 +102,68 @@ public class ReflectionSecurityTest extends BaseTest {
} }
public static class ConnectionTestStore extends SettingsStore { public static
class ConnectionTestStore extends SettingsStore {
@SuppressWarnings("unused") @SuppressWarnings("unused")
private static SettingsStore create() throws SecurityException { private static
SettingsStore create() throws SecurityException {
return new ConnectionTestStore(); return new ConnectionTestStore();
} }
@Override @Override
public ECPrivateKeyParameters getPrivateKey() throws SecurityException { public
void init(final Class<? extends EndPoint> type, final SerializationManager serializationManager, final Storage storage)
throws IOException {
}
@Override
public
ECPrivateKeyParameters getPrivateKey() throws SecurityException {
return null; return null;
} }
@Override @Override
public void savePrivateKey(ECPrivateKeyParameters serverPrivateKey) throws SecurityException { public
void savePrivateKey(ECPrivateKeyParameters serverPrivateKey) throws SecurityException {
} }
@Override @Override
public ECPublicKeyParameters getPublicKey() throws SecurityException { public
ECPublicKeyParameters getPublicKey() throws SecurityException {
return null; return null;
} }
@Override @Override
public void savePublicKey(ECPublicKeyParameters serverPublicKey) throws SecurityException { public
void savePublicKey(ECPublicKeyParameters serverPublicKey) throws SecurityException {
} }
@Override @Override
public byte[] getSalt() { public
byte[] getSalt() {
return null; return null;
} }
@Override @Override
public ECPublicKeyParameters getRegisteredServerKey(byte[] hostAddress) throws SecurityException { public
ECPublicKeyParameters getRegisteredServerKey(byte[] hostAddress) throws SecurityException {
return null; return null;
} }
@Override @Override
public void addRegisteredServerKey(byte[] hostAddress, ECPublicKeyParameters publicKey) throws SecurityException { public
void addRegisteredServerKey(byte[] hostAddress, ECPublicKeyParameters publicKey) throws SecurityException {
} }
@Override @Override
public boolean removeRegisteredServerKey(byte[] hostAddress) throws SecurityException { public
boolean removeRegisteredServerKey(byte[] hostAddress) throws SecurityException {
return true; return true;
} }
@Override @Override
public void shutdown() { public
void shutdown() {
} }
} }
} }

View File

@ -1,24 +1,25 @@
package dorkbox.network; package dorkbox.network;
import static org.junit.Assert.assertEquals;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import dorkbox.network.connection.Connection; import dorkbox.network.connection.Connection;
import dorkbox.network.connection.Listener; import dorkbox.network.connection.Listener;
import dorkbox.network.util.exceptions.InitializationException; import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException; import dorkbox.network.util.exceptions.SecurityException;
import org.junit.Test;
public class ReuseTest extends BaseTest { import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals;
public
class ReuseTest extends BaseTest {
AtomicInteger serverCount; AtomicInteger serverCount;
AtomicInteger clientCount; AtomicInteger clientCount;
@Test @Test
public void socketReuse() throws InitializationException, SecurityException { public
void socketReuse() throws InitializationException, SecurityException, IOException {
this.serverCount = new AtomicInteger(0); this.serverCount = new AtomicInteger(0);
this.clientCount = new AtomicInteger(0); this.clientCount = new AtomicInteger(0);
@ -30,15 +31,20 @@ public class ReuseTest extends BaseTest {
Server server = new Server(connectionOptions); Server server = new Server(connectionOptions);
server.disableRemoteKeyValidation(); server.disableRemoteKeyValidation();
addEndPoint(server); addEndPoint(server);
server.listeners().add(new Listener<String>() { server.listeners()
.add(new Listener<String>() {
@Override @Override
public void connected (Connection connection) { public
connection.send().TCP("-- TCP from server"); void connected(Connection connection) {
connection.send().UDP("-- UDP from server"); connection.send()
.TCP("-- TCP from server");
connection.send()
.UDP("-- UDP from server");
} }
@Override @Override
public void received (Connection connection, String object) { public
void received(Connection connection, String object) {
int incrementAndGet = ReuseTest.this.serverCount.incrementAndGet(); int incrementAndGet = ReuseTest.this.serverCount.incrementAndGet();
System.err.println("<S " + connection + "> " + incrementAndGet + " : " + object); System.err.println("<S " + connection + "> " + incrementAndGet + " : " + object);
} }
@ -49,15 +55,20 @@ public class ReuseTest extends BaseTest {
Client client = new Client(connectionOptions); Client client = new Client(connectionOptions);
client.disableRemoteKeyValidation(); client.disableRemoteKeyValidation();
addEndPoint(client); addEndPoint(client);
client.listeners().add(new Listener<String>() { client.listeners()
.add(new Listener<String>() {
@Override @Override
public void connected (Connection connection) { public
connection.send().TCP("-- TCP from client"); void connected(Connection connection) {
connection.send().UDP("-- UDP from client"); connection.send()
.TCP("-- TCP from client");
connection.send()
.UDP("-- UDP from client");
} }
@Override @Override
public void received (Connection connection, String object) { public
void received(Connection connection, String object) {
int incrementAndGet = ReuseTest.this.clientCount.incrementAndGet(); int incrementAndGet = ReuseTest.this.clientCount.incrementAndGet();
System.err.println("<C " + connection + "> " + incrementAndGet + " : " + object); System.err.println("<C " + connection + "> " + incrementAndGet + " : " + object);
} }
@ -87,21 +98,26 @@ public class ReuseTest extends BaseTest {
} }
@Test @Test
public void localReuse() throws InitializationException, SecurityException { public
void localReuse() throws InitializationException, SecurityException, IOException {
this.serverCount = new AtomicInteger(0); this.serverCount = new AtomicInteger(0);
this.clientCount = new AtomicInteger(0); this.clientCount = new AtomicInteger(0);
Server server = new Server(); Server server = new Server();
server.disableRemoteKeyValidation(); server.disableRemoteKeyValidation();
addEndPoint(server); addEndPoint(server);
server.listeners().add(new Listener<String>() { server.listeners()
.add(new Listener<String>() {
@Override @Override
public void connected (Connection connection) { public
connection.send().TCP("-- LOCAL from server"); void connected(Connection connection) {
connection.send()
.TCP("-- LOCAL from server");
} }
@Override @Override
public void received (Connection connection, String object) { public
void received(Connection connection, String object) {
int incrementAndGet = ReuseTest.this.serverCount.incrementAndGet(); int incrementAndGet = ReuseTest.this.serverCount.incrementAndGet();
System.err.println("<S " + connection + "> " + incrementAndGet + " : " + object); System.err.println("<S " + connection + "> " + incrementAndGet + " : " + object);
} }
@ -112,14 +128,18 @@ public class ReuseTest extends BaseTest {
Client client = new Client(); Client client = new Client();
client.disableRemoteKeyValidation(); client.disableRemoteKeyValidation();
addEndPoint(client); addEndPoint(client);
client.listeners().add(new Listener<String>() { client.listeners()
.add(new Listener<String>() {
@Override @Override
public void connected (Connection connection) { public
connection.send().TCP("-- LOCAL from client"); void connected(Connection connection) {
connection.send()
.TCP("-- LOCAL from client");
} }
@Override @Override
public void received (Connection connection, String object) { public
void received(Connection connection, String object) {
int incrementAndGet = ReuseTest.this.clientCount.incrementAndGet(); int incrementAndGet = ReuseTest.this.clientCount.incrementAndGet();
System.err.println("<C " + connection + "> " + incrementAndGet + " : " + object); System.err.println("<C " + connection + "> " + incrementAndGet + " : " + object);
} }

View File

@ -1,22 +1,23 @@
package dorkbox.network; package dorkbox.network;
import static org.junit.Assert.fail;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import dorkbox.network.connection.Connection; import dorkbox.network.connection.Connection;
import dorkbox.network.connection.EndPoint; import dorkbox.network.connection.EndPoint;
import dorkbox.network.connection.Listener; import dorkbox.network.connection.Listener;
import dorkbox.network.util.KryoConnectionSerializationManager;
import dorkbox.network.util.exceptions.InitializationException; import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException; import dorkbox.network.util.exceptions.SecurityException;
import org.junit.Test;
public class UnregisteredClassTest extends BaseTest { import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.fail;
public
class UnregisteredClassTest extends BaseTest {
private String fail; private String fail;
private int tries = 10000; private int tries = 10000;
@ -24,7 +25,8 @@ public class UnregisteredClassTest extends BaseTest {
private AtomicInteger receivedUDP = new AtomicInteger(); private AtomicInteger receivedUDP = new AtomicInteger();
@Test @Test
public void unregisteredClasses() throws InitializationException, SecurityException { public
void unregisteredClasses() throws InitializationException, SecurityException, IOException {
int origSize = EndPoint.udpMaxSize; int origSize = EndPoint.udpMaxSize;
EndPoint.udpMaxSize = 2048; EndPoint.udpMaxSize = 2048;
@ -32,6 +34,7 @@ public class UnregisteredClassTest extends BaseTest {
connectionOptions.tcpPort = tcpPort; connectionOptions.tcpPort = tcpPort;
connectionOptions.udpPort = udpPort; connectionOptions.udpPort = udpPort;
connectionOptions.host = host; connectionOptions.host = host;
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT(false, false);
System.err.println("Running test " + this.tries + " times, please wait for it to finish."); System.err.println("Running test " + this.tries + " times, please wait for it to finish.");
@ -42,30 +45,35 @@ public class UnregisteredClassTest extends BaseTest {
Server server = new Server(connectionOptions); Server server = new Server(connectionOptions);
server.disableRemoteKeyValidation(); server.disableRemoteKeyValidation();
server.getSerialization().setRegistrationRequired(false);
addEndPoint(server); addEndPoint(server);
server.bind(false); server.bind(false);
server.listeners().add(new Listener<Data>() { server.listeners()
.add(new Listener<Data>() {
@Override @Override
public void error(Connection connection, Throwable throwable) { public
void error(Connection connection, Throwable throwable) {
UnregisteredClassTest.this.fail = "Error during processing. " + throwable; UnregisteredClassTest.this.fail = "Error during processing. " + throwable;
} }
@Override @Override
public void received (Connection connection, Data data) { public
void received(Connection connection, Data data) {
if (data.isTCP) { if (data.isTCP) {
if (!data.equals(dataTCP)) { if (!data.equals(dataTCP)) {
UnregisteredClassTest.this.fail = "TCP data is not equal on server."; UnregisteredClassTest.this.fail = "TCP data is not equal on server.";
throw new RuntimeException("Fail! " + UnregisteredClassTest.this.fail); throw new RuntimeException("Fail! " + UnregisteredClassTest.this.fail);
} }
connection.send().TCP(data); connection.send()
.TCP(data);
UnregisteredClassTest.this.receivedTCP.incrementAndGet(); UnregisteredClassTest.this.receivedTCP.incrementAndGet();
} else { }
else {
if (!data.equals(dataUDP)) { if (!data.equals(dataUDP)) {
UnregisteredClassTest.this.fail = "UDP data is not equal on server."; UnregisteredClassTest.this.fail = "UDP data is not equal on server.";
throw new RuntimeException("Fail! " + UnregisteredClassTest.this.fail); throw new RuntimeException("Fail! " + UnregisteredClassTest.this.fail);
} }
connection.send().UDP(data); connection.send()
.UDP(data);
UnregisteredClassTest.this.receivedUDP.incrementAndGet(); UnregisteredClassTest.this.receivedUDP.incrementAndGet();
} }
} }
@ -75,50 +83,60 @@ public class UnregisteredClassTest extends BaseTest {
Client client = new Client(connectionOptions); Client client = new Client(connectionOptions);
client.disableRemoteKeyValidation(); client.disableRemoteKeyValidation();
client.getSerialization().setRegistrationRequired(false);
addEndPoint(client); addEndPoint(client);
client.listeners().add(new Listener<Data>() { client.listeners()
.add(new Listener<Data>() {
AtomicInteger checkTCP = new AtomicInteger(0); AtomicInteger checkTCP = new AtomicInteger(0);
AtomicInteger checkUDP = new AtomicInteger(0); AtomicInteger checkUDP = new AtomicInteger(0);
AtomicBoolean doneTCP = new AtomicBoolean(false); AtomicBoolean doneTCP = new AtomicBoolean(false);
AtomicBoolean doneUDP = new AtomicBoolean(false); AtomicBoolean doneUDP = new AtomicBoolean(false);
@Override @Override
public void connected (Connection connection) { public
void connected(Connection connection) {
UnregisteredClassTest.this.fail = null; UnregisteredClassTest.this.fail = null;
connection.send().TCP(dataTCP); connection.send()
connection.send().UDP(dataUDP); // UDP ping pong stops if a UDP packet is lost. .TCP(dataTCP);
connection.send()
.UDP(dataUDP); // UDP ping pong stops if a UDP packet is lost.
} }
@Override @Override
public void error(Connection connection, Throwable throwable) { public
void error(Connection connection, Throwable throwable) {
UnregisteredClassTest.this.fail = "Error during processing. " + throwable; UnregisteredClassTest.this.fail = "Error during processing. " + throwable;
System.err.println(UnregisteredClassTest.this.fail); System.err.println(UnregisteredClassTest.this.fail);
} }
@Override @Override
public void received (Connection connection, Data data) { public
void received(Connection connection, Data data) {
if (data.isTCP) { if (data.isTCP) {
if (!data.equals(dataTCP)) { if (!data.equals(dataTCP)) {
UnregisteredClassTest.this.fail = "TCP data is not equal on client."; UnregisteredClassTest.this.fail = "TCP data is not equal on client.";
throw new RuntimeException("Fail! " + UnregisteredClassTest.this.fail); throw new RuntimeException("Fail! " + UnregisteredClassTest.this.fail);
} }
if (this.checkTCP.getAndIncrement() <= UnregisteredClassTest.this.tries) { if (this.checkTCP.getAndIncrement() <= UnregisteredClassTest.this.tries) {
connection.send().TCP(data); connection.send()
.TCP(data);
UnregisteredClassTest.this.receivedTCP.incrementAndGet(); UnregisteredClassTest.this.receivedTCP.incrementAndGet();
} else { }
else {
System.err.println("TCP done."); System.err.println("TCP done.");
this.doneTCP.set(true); this.doneTCP.set(true);
} }
} else { }
else {
if (!data.equals(dataUDP)) { if (!data.equals(dataUDP)) {
UnregisteredClassTest.this.fail = "UDP data is not equal on client."; UnregisteredClassTest.this.fail = "UDP data is not equal on client.";
throw new RuntimeException("Fail! " + UnregisteredClassTest.this.fail); throw new RuntimeException("Fail! " + UnregisteredClassTest.this.fail);
} }
if (this.checkUDP.getAndIncrement() <= UnregisteredClassTest.this.tries) { if (this.checkUDP.getAndIncrement() <= UnregisteredClassTest.this.tries) {
connection.send().UDP(data); connection.send()
.UDP(data);
UnregisteredClassTest.this.receivedUDP.incrementAndGet(); UnregisteredClassTest.this.receivedUDP.incrementAndGet();
} else { }
else {
System.err.println("UDP done."); System.err.println("UDP done.");
this.doneUDP.set(true); this.doneUDP.set(true);
} }
@ -141,7 +159,8 @@ public class UnregisteredClassTest extends BaseTest {
EndPoint.udpMaxSize = origSize; EndPoint.udpMaxSize = origSize;
} }
private void populateData(Data data, boolean isTCP) { private
void populateData(Data data, boolean isTCP) {
data.isTCP = isTCP; data.isTCP = isTCP;
StringBuilder buffer = new StringBuilder(); StringBuilder buffer = new StringBuilder();
@ -153,8 +172,7 @@ public class UnregisteredClassTest extends BaseTest {
data.strings = new String[] {"ab012", "", null, "!@#$", "<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>"}; data.strings = new String[] {"ab012", "", null, "!@#$", "<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>"};
data.ints = new int[] {-1234567, 1234567, -1, 0, 1, Integer.MAX_VALUE, Integer.MIN_VALUE}; data.ints = new int[] {-1234567, 1234567, -1, 0, 1, Integer.MAX_VALUE, Integer.MIN_VALUE};
data.shorts = new short[] {-12345, 12345, -1, 0, 1, Short.MAX_VALUE, Short.MIN_VALUE}; data.shorts = new short[] {-12345, 12345, -1, 0, 1, Short.MAX_VALUE, Short.MIN_VALUE};
data.floats = new float[] {0, -0, 1, -1, 123456, -123456, 0.1f, 0.2f, -0.3f, (float)Math.PI, Float.MAX_VALUE, data.floats = new float[] {0, -0, 1, -1, 123456, -123456, 0.1f, 0.2f, -0.3f, (float) Math.PI, Float.MAX_VALUE, Float.MIN_VALUE};
Float.MIN_VALUE};
data.doubles = new double[] {0, -0, 1, -1, 123456, -123456, 0.1d, 0.2d, -0.3d, Math.PI, Double.MAX_VALUE, Double.MIN_VALUE}; data.doubles = new double[] {0, -0, 1, -1, 123456, -123456, 0.1d, 0.2d, -0.3d, Math.PI, Double.MAX_VALUE, Double.MIN_VALUE};
data.longs = new long[] {0, -0, 1, -1, 123456, -123456, 99999999999l, -99999999999l, Long.MAX_VALUE, Long.MIN_VALUE}; data.longs = new long[] {0, -0, 1, -1, 123456, -123456, 99999999999l, -99999999999l, Long.MAX_VALUE, Long.MIN_VALUE};
data.bytes = new byte[] {-123, 123, -1, 0, 1, Byte.MAX_VALUE, Byte.MIN_VALUE}; data.bytes = new byte[] {-123, 123, -1, 0, 1, Byte.MAX_VALUE, Byte.MIN_VALUE};
@ -164,15 +182,15 @@ public class UnregisteredClassTest extends BaseTest {
data.Shorts = new Short[] {-12345, 12345, -1, 0, 1, Short.MAX_VALUE, Short.MIN_VALUE}; data.Shorts = new Short[] {-12345, 12345, -1, 0, 1, Short.MAX_VALUE, Short.MIN_VALUE};
data.Floats = new Float[] {0f, -0f, 1f, -1f, 123456f, -123456f, 0.1f, 0.2f, -0.3f, (float) Math.PI, Float.MAX_VALUE, data.Floats = new Float[] {0f, -0f, 1f, -1f, 123456f, -123456f, 0.1f, 0.2f, -0.3f, (float) Math.PI, Float.MAX_VALUE,
Float.MIN_VALUE}; Float.MIN_VALUE};
data.Doubles = new Double[] {0d, -0d, 1d, -1d, 123456d, -123456d, 0.1d, 0.2d, -0.3d, Math.PI, Double.MAX_VALUE, data.Doubles = new Double[] {0d, -0d, 1d, -1d, 123456d, -123456d, 0.1d, 0.2d, -0.3d, Math.PI, Double.MAX_VALUE, Double.MIN_VALUE};
Double.MIN_VALUE};
data.Longs = new Long[] {0l, -0l, 1l, -1l, 123456l, -123456l, 99999999999l, -99999999999l, Long.MAX_VALUE, Long.MIN_VALUE}; data.Longs = new Long[] {0l, -0l, 1l, -1l, 123456l, -123456l, 99999999999l, -99999999999l, Long.MAX_VALUE, Long.MIN_VALUE};
data.Bytes = new Byte[] {-123, 123, -1, 0, 1, Byte.MAX_VALUE, Byte.MIN_VALUE}; data.Bytes = new Byte[] {-123, 123, -1, 0, 1, Byte.MAX_VALUE, Byte.MIN_VALUE};
data.Chars = new Character[] {32345, 12345, 0, 1, 63, Character.MAX_VALUE, Character.MIN_VALUE}; data.Chars = new Character[] {32345, 12345, 0, 1, 63, Character.MAX_VALUE, Character.MIN_VALUE};
data.Booleans = new Boolean[] {true, false}; data.Booleans = new Boolean[] {true, false};
} }
static public class Data { static public
class Data {
public String string; public String string;
public String[] strings; public String[] strings;
public int[] ints; public int[] ints;
@ -194,7 +212,8 @@ public class UnregisteredClassTest extends BaseTest {
public boolean isTCP; public boolean isTCP;
@Override @Override
public int hashCode () { public
int hashCode() {
final int prime = 31; final int prime = 31;
int result = 1; int result = 1;
result = prime * result + Arrays.hashCode(this.Booleans); result = prime * result + Arrays.hashCode(this.Booleans);
@ -220,7 +239,8 @@ public class UnregisteredClassTest extends BaseTest {
} }
@Override @Override
public boolean equals (Object obj) { public
boolean equals(Object obj) {
if (this == obj) { if (this == obj) {
return true; return true;
} }
@ -286,7 +306,8 @@ public class UnregisteredClassTest extends BaseTest {
if (other.string != null) { if (other.string != null) {
return false; return false;
} }
} else if (!this.string.equals(other.string)) { }
else if (!this.string.equals(other.string)) {
return false; return false;
} }
if (!Arrays.equals(this.strings, other.strings)) { if (!Arrays.equals(this.strings, other.strings)) {
@ -296,7 +317,8 @@ public class UnregisteredClassTest extends BaseTest {
} }
@Override @Override
public String toString () { public
String toString() {
return "Data"; return "Data";
} }
} }

View File

@ -1,10 +1,5 @@
package dorkbox.network.rmi; package dorkbox.network.rmi;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import dorkbox.network.BaseTest; import dorkbox.network.BaseTest;
import dorkbox.network.Client; import dorkbox.network.Client;
import dorkbox.network.ConnectionOptions; import dorkbox.network.ConnectionOptions;
@ -12,11 +7,17 @@ import dorkbox.network.Server;
import dorkbox.network.connection.Connection; import dorkbox.network.connection.Connection;
import dorkbox.network.connection.EndPoint; import dorkbox.network.connection.EndPoint;
import dorkbox.network.connection.Listener; import dorkbox.network.connection.Listener;
import dorkbox.network.util.SerializationManager; import dorkbox.network.util.ConnectionSerializationManager;
import dorkbox.network.util.exceptions.InitializationException; import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException; import dorkbox.network.util.exceptions.SecurityException;
import org.junit.Test;
public class RmiSendObjectTest extends BaseTest { import java.io.IOException;
import static org.junit.Assert.assertEquals;
public
class RmiSendObjectTest extends BaseTest {
private Rmi serverRMI; private Rmi serverRMI;
/** /**
@ -24,7 +25,8 @@ public class RmiSendObjectTest extends BaseTest {
* uses the first remote object to get the second remote object. * uses the first remote object to get the second remote object.
*/ */
@Test @Test
public void rmi() throws InitializationException, SecurityException { public
void rmi() throws InitializationException, SecurityException, IOException {
ConnectionOptions connectionOptions = new ConnectionOptions(); ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort; connectionOptions.tcpPort = tcpPort;
connectionOptions.host = host; connectionOptions.host = host;
@ -32,7 +34,7 @@ public class RmiSendObjectTest extends BaseTest {
Server server = new Server(connectionOptions); Server server = new Server(connectionOptions);
server.disableRemoteKeyValidation(); server.disableRemoteKeyValidation();
SerializationManager serverSerializationManager = server.getSerialization(); ConnectionSerializationManager serverSerializationManager = server.getSerialization();
register(server, serverSerializationManager); register(server, serverSerializationManager);
addEndPoint(server); addEndPoint(server);
server.bind(false); server.bind(false);
@ -40,7 +42,8 @@ public class RmiSendObjectTest extends BaseTest {
// After all common registrations, register OtherObjectImpl only on the server using the remote object interface ID. // After all common registrations, register OtherObjectImpl only on the server using the remote object interface ID.
// This causes OtherObjectImpl to be serialized as OtherObject. // This causes OtherObjectImpl to be serialized as OtherObject.
int otherObjectID = serverSerializationManager.getRegistration(OtherObject.class).getId(); int otherObjectID = serverSerializationManager.getRegistration(OtherObject.class)
.getId();
serverSerializationManager.register(OtherObjectImpl.class, new RemoteObjectSerializer<OtherObjectImpl>(server), otherObjectID); serverSerializationManager.register(OtherObjectImpl.class, new RemoteObjectSerializer<OtherObjectImpl>(server), otherObjectID);
@ -53,9 +56,11 @@ public class RmiSendObjectTest extends BaseTest {
this.serverRMI.register(42, serverTestObject); this.serverRMI.register(42, serverTestObject);
this.serverRMI.register(777, serverTestObject.getOtherObject()); this.serverRMI.register(777, serverTestObject.getOtherObject());
server.listeners().add(new Listener<OtherObjectImpl>() { server.listeners()
.add(new Listener<OtherObjectImpl>() {
@Override @Override
public void received (Connection connection, OtherObjectImpl object) { public
void received(Connection connection, OtherObjectImpl object) {
// The test is complete when the client sends the OtherObject instance. // The test is complete when the client sends the OtherObject instance.
if (object == serverTestObject.getOtherObject()) { if (object == serverTestObject.getOtherObject()) {
stopEndPoints(); stopEndPoints();
@ -70,12 +75,15 @@ public class RmiSendObjectTest extends BaseTest {
register(client, client.getSerialization()); register(client, client.getSerialization());
addEndPoint(client); addEndPoint(client);
client.listeners().add(new Listener<Object>() { client.listeners()
.add(new Listener<Object>() {
@Override @Override
public void connected(final Connection connection) { public
void connected(final Connection connection) {
new Thread(new Runnable() { new Thread(new Runnable() {
@Override @Override
public void run() { public
void run() {
TestObject test = connection.getRemoteObject(42, TestObject.class); TestObject test = connection.getRemoteObject(42, TestObject.class);
// Normal remote method call. // Normal remote method call.
assertEquals(43.21f, test.other(), .0001f); assertEquals(43.21f, test.other(), .0001f);
@ -88,7 +96,9 @@ public class RmiSendObjectTest extends BaseTest {
// When a remote proxy object is sent, the other side receives its actual remote object. // When a remote proxy object is sent, the other side receives its actual remote object.
// we have to manually flush, since we are in a separate thread that does not auto-flush. // we have to manually flush, since we are in a separate thread that does not auto-flush.
connection.send().TCP(otherObject).flush(); connection.send()
.TCP(otherObject)
.flush();
} }
}).start(); }).start();
} }
@ -99,40 +109,52 @@ public class RmiSendObjectTest extends BaseTest {
waitForThreads(20); waitForThreads(20);
} }
/** Registers the same classes in the same order on both the client and server. /**
* @param server */ * Registers the same classes in the same order on both the client and server.
static public void register(EndPoint endpoint, SerializationManager kryoMT) { */
public static
void register(EndPoint endpoint, ConnectionSerializationManager kryoMT) {
kryoMT.register(TestObject.class); kryoMT.register(TestObject.class);
kryoMT.register(OtherObject.class, new RemoteObjectSerializer<OtherObject>(endpoint)); kryoMT.register(OtherObject.class, new RemoteObjectSerializer<OtherObject>(endpoint));
} }
static public interface TestObject { public
public float other(); interface TestObject {
float other();
public OtherObject getOtherObject(); OtherObject getOtherObject();
} }
static public class TestObjectImpl implements TestObject {
public static
class TestObjectImpl implements TestObject {
public OtherObject otherObject; public OtherObject otherObject;
@Override @Override
public float other() { public
float other() {
return 43.21f; return 43.21f;
} }
@Override @Override
public OtherObject getOtherObject() { public
OtherObject getOtherObject() {
return this.otherObject; return this.otherObject;
} }
} }
static public interface OtherObject {
public float value (); public
interface OtherObject {
float value();
} }
static public class OtherObjectImpl implements OtherObject {
public static
class OtherObjectImpl implements OtherObject {
@Override @Override
public float value () { public
float value() {
return 12.34f; return 12.34f;
} }
} }

View File

@ -1,24 +1,26 @@
package dorkbox.network.rmi; package dorkbox.network.rmi;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Assert;
import org.junit.Test;
import dorkbox.network.BaseTest; import dorkbox.network.BaseTest;
import dorkbox.network.Client; import dorkbox.network.Client;
import dorkbox.network.ConnectionOptions; import dorkbox.network.ConnectionOptions;
import dorkbox.network.Server; import dorkbox.network.Server;
import dorkbox.network.connection.Connection; import dorkbox.network.connection.Connection;
import dorkbox.network.connection.Listener; import dorkbox.network.connection.Listener;
import dorkbox.network.util.SerializationManager; import dorkbox.network.util.ConnectionSerializationManager;
import dorkbox.network.util.KryoConnectionSerializationManager;
import dorkbox.network.util.exceptions.InitializationException; import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException; import dorkbox.network.util.exceptions.SecurityException;
import org.junit.Assert;
import org.junit.Test;
public class RmiTest extends BaseTest { import java.io.IOException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public
class RmiTest extends BaseTest {
private static final int CLIENT_ID = 4321; private static final int CLIENT_ID = 4321;
private static final int SERVER_ID = 1234; private static final int SERVER_ID = 1234;
@ -26,203 +28,12 @@ public class RmiTest extends BaseTest {
private static final int CLIENT_REMOTE_ID = 42; private static final int CLIENT_REMOTE_ID = 42;
private static final int SERVER_REMOTE_ID = 12; private static final int SERVER_REMOTE_ID = 12;
@Test private static
public void rmi() throws InitializationException, SecurityException { void runTest(final Connection connection, final int id, final int otherID) {
ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort;
connectionOptions.udpPort = udpPort;
connectionOptions.host = host;
connectionOptions.enableRmi = true;
final Server server = new Server(connectionOptions);
server.disableRemoteKeyValidation();
register(server.getSerialization());
addEndPoint(server);
server.bind(false);
// have to have this happen BEFORE any connections are made.
server.rmi().register(SERVER_REMOTE_ID, new TestObjectImpl(SERVER_ID));
server.listeners().add(new Listener<MessageWithTestObject>() {
@Override
public void received (Connection connection, MessageWithTestObject m) {
assertEquals(SERVER_ID, m.testObject.id());
System.err.println("Client Finished!");
// normally this is in the 'connected', but we do it here, so that it's more linear and easier to debug
runTest(connection, CLIENT_REMOTE_ID, CLIENT_ID);
}
});
// ----
final Client client = new Client(connectionOptions);
client.disableRemoteKeyValidation();
register(client.getSerialization());
addEndPoint(client);
// have to have this happen BEFORE any connections are made.
client.rmi().register(CLIENT_REMOTE_ID, new TestObjectImpl(CLIENT_ID));
client.listeners().add(new Listener<MessageWithTestObject>() {
@Override
public void connected (final Connection connection) {
RmiTest.runTest(connection, SERVER_REMOTE_ID, SERVER_ID);
}
@Override
public void received (Connection connection, MessageWithTestObject m) {
assertEquals(CLIENT_ID, m.testObject.id());
System.err.println("Server Finished!");
stopEndPoints(2000);
}
});
client.connect(5000);
waitForThreads(30);
}
@Test
public void rmiMany() throws InitializationException, SecurityException {
ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort;
connectionOptions.host = host;
connectionOptions.enableRmi = true;
final Server server = new Server(connectionOptions);
server.disableRemoteKeyValidation();
register(server.getSerialization());
addEndPoint(server);
server.bind(false);
// have to have this happen BEFORE any connections are made.
final TestObjectImpl serverTestObject = new TestObjectImpl(CLIENT_ID);
server.rmi().register(CLIENT_REMOTE_ID, serverTestObject);
server.listeners().add(new Listener<MessageWithTestObject>() {
@Override
public void received (Connection connection, MessageWithTestObject m) {
assertEquals(256 + 512 + 1024, serverTestObject.moos);
System.err.println("Client Finished!");
stopEndPoints(2000);
}
});
// ----
final Client client = new Client(connectionOptions);
client.disableRemoteKeyValidation();
register(client.getSerialization());
addEndPoint(client);
client.listeners().add(new Listener<MessageWithTestObject>() {
@Override
public void connected (final Connection connection) {
new Thread() { new Thread() {
@Override @Override
public void run() { public
TestObject test = connection.getRemoteObject(CLIENT_REMOTE_ID, TestObject.class); void run() {
for (int i = 0; i < 256; i++) {
assertEquals(CLIENT_ID, test.id());
}
for (int i = 0; i < 256; i++) {
test.moo();
}
for (int i = 0; i < 256; i++) {
test.moo("" + i);
}
for (int i = 0; i < 256; i++) {
test.moo("" + i, 0);
}
connection.send().TCP(new MessageWithTestObject()).flush();
}
}.start();
}
});
client.connect(5000);
waitForThreads(30);
}
@Test
public void rmiSlow() throws InitializationException, SecurityException {
ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort;
connectionOptions.host = host;
connectionOptions.enableRmi = true;
final Server server = new Server(connectionOptions);
server.disableRemoteKeyValidation();
register(server.getSerialization());
addEndPoint(server);
server.bind(false);
// have to have this happen BEFORE any connections are made.
final TestObjectImpl serverTestObject = new TestObjectImpl(CLIENT_ID);
server.rmi().register(CLIENT_REMOTE_ID, serverTestObject);
server.listeners().add(new Listener<MessageWithTestObject>() {
@Override
public void received (Connection connection, MessageWithTestObject m) {
System.err.println("Client Finished!");
stopEndPoints(2000);
}
});
// ----
final Client client = new Client(connectionOptions);
client.disableRemoteKeyValidation();
register(client.getSerialization());
addEndPoint(client);
client.listeners().add(new Listener<MessageWithTestObject>() {
@Override
public void connected(final Connection connection) {
new Thread() {
@Override
public void run() {
TestObject test = connection.getRemoteObject(CLIENT_REMOTE_ID, TestObject.class);
test.id();
// Timeout on purpose.
try {
((RemoteObject)test).setResponseTimeout(200);
test.slow();
Assert.fail();
} catch (TimeoutException ignored) {
}
try {
Thread.sleep(300);
} catch (InterruptedException ex) {
}
((RemoteObject)test).setResponseTimeout(3000);
connection.send().TCP(new MessageWithTestObject()).flush();
}
}.start();
}
});
client.connect(5000);
waitForThreads(30);
}
private static void runTest(final Connection connection, final int id, final int otherID) {
new Thread() {
@Override
public void run () {
System.err.println("Starting test for: " + id); System.err.println("Starting test for: " + id);
TestObject test = connection.getRemoteObject(id, TestObject.class); TestObject test = connection.getRemoteObject(id, TestObject.class);
@ -293,7 +104,8 @@ public class RmiTest extends BaseTest {
// Non-blocking call that errors out // Non-blocking call that errors out
remoteObject.setTransmitReturnValue(false); remoteObject.setTransmitReturnValue(false);
test.throwException(); test.throwException();
assertEquals(remoteObject.waitForLastResponse().getClass(), UnsupportedOperationException.class); assertEquals(remoteObject.waitForLastResponse()
.getClass(), UnsupportedOperationException.class);
// Call will time out if non-blocking isn't working properly // Call will time out if non-blocking isn't working properly
remoteObject.setTransmitExceptions(false); remoteObject.setTransmitExceptions(false);
@ -304,12 +116,15 @@ public class RmiTest extends BaseTest {
m.number = 678; m.number = 678;
m.text = "sometext"; m.text = "sometext";
m.testObject = connection.getRemoteObject(id, TestObject.class); m.testObject = connection.getRemoteObject(id, TestObject.class);
connection.send().TCP(m).flush(); connection.send()
.TCP(m)
.flush();
} }
}.start(); }.start();
} }
static public void register (SerializationManager kryoMT) { public static
void register(ConnectionSerializationManager kryoMT) {
kryoMT.register(Object.class); // Needed for Object#toString, hashCode, etc. kryoMT.register(Object.class); // Needed for Object#toString, hashCode, etc.
kryoMT.register(TestObject.class); kryoMT.register(TestObject.class);
kryoMT.register(MessageWithTestObject.class); kryoMT.register(MessageWithTestObject.class);
@ -317,51 +132,279 @@ public class RmiTest extends BaseTest {
kryoMT.register(StackTraceElement[].class); kryoMT.register(StackTraceElement[].class);
kryoMT.register(UnsupportedOperationException.class); kryoMT.register(UnsupportedOperationException.class);
kryoMT.setReferences(true); // Needed for UnsupportedOperationException, which has a circular reference in the cause field.
} }
public static interface TestObject { @Test
public void throwException(); public
void rmi() throws InitializationException, SecurityException, IOException {
ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort;
connectionOptions.udpPort = udpPort;
connectionOptions.host = host;
connectionOptions.enableRmi = true;
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT(true, true);
register(connectionOptions.serializationManager);
public void moo(); final Server server = new Server(connectionOptions);
server.disableRemoteKeyValidation();
addEndPoint(server);
server.bind(false);
public void moo(String value); // have to have this happen BEFORE any connections are made.
server.rmi()
.register(SERVER_REMOTE_ID, new TestObjectImpl(SERVER_ID));
public void moo(String value, long delay); server.listeners()
.add(new Listener<MessageWithTestObject>() {
@Override
public
void received(Connection connection, MessageWithTestObject m) {
assertEquals(SERVER_ID, m.testObject.id());
System.err.println("Client Finished!");
public int id(); // normally this is in the 'connected', but we do it here, so that it's more linear and easier to debug
runTest(connection, CLIENT_REMOTE_ID, CLIENT_ID);
}
});
public float slow ();
// ----
final Client client = new Client(connectionOptions);
client.disableRemoteKeyValidation();
addEndPoint(client);
// have to have this happen BEFORE any connections are made.
client.rmi()
.register(CLIENT_REMOTE_ID, new TestObjectImpl(CLIENT_ID));
client.listeners()
.add(new Listener<MessageWithTestObject>() {
@Override
public
void connected(final Connection connection) {
RmiTest.runTest(connection, SERVER_REMOTE_ID, SERVER_ID);
} }
public static class TestObjectImpl implements TestObject { @Override
public long value = System.currentTimeMillis(); public
void received(Connection connection, MessageWithTestObject m) {
assertEquals(CLIENT_ID, m.testObject.id());
System.err.println("Server Finished!");
stopEndPoints(2000);
}
});
client.connect(5000);
waitForThreads(30);
}
@Test
public
void rmiMany() throws InitializationException, SecurityException, IOException {
ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort;
connectionOptions.host = host;
connectionOptions.enableRmi = true;
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT(true, true);
register(connectionOptions.serializationManager);
final Server server = new Server(connectionOptions);
server.disableRemoteKeyValidation();
addEndPoint(server);
server.bind(false);
// have to have this happen BEFORE any connections are made.
final TestObjectImpl serverTestObject = new TestObjectImpl(CLIENT_ID);
server.rmi()
.register(CLIENT_REMOTE_ID, serverTestObject);
server.listeners()
.add(new Listener<MessageWithTestObject>() {
@Override
public
void received(Connection connection, MessageWithTestObject m) {
assertEquals(256 + 512 + 1024, serverTestObject.moos);
System.err.println("Client Finished!");
stopEndPoints(2000);
}
});
// ----
final Client client = new Client(connectionOptions);
client.disableRemoteKeyValidation();
addEndPoint(client);
client.listeners()
.add(new Listener<MessageWithTestObject>() {
@Override
public
void connected(final Connection connection) {
new Thread() {
@Override
public
void run() {
TestObject test = connection.getRemoteObject(CLIENT_REMOTE_ID, TestObject.class);
for (int i = 0; i < 256; i++) {
assertEquals(CLIENT_ID, test.id());
}
for (int i = 0; i < 256; i++) {
test.moo();
}
for (int i = 0; i < 256; i++) {
test.moo("" + i);
}
for (int i = 0; i < 256; i++) {
test.moo("" + i, 0);
}
connection.send()
.TCP(new MessageWithTestObject())
.flush();
}
}.start();
}
});
client.connect(5000);
waitForThreads(30);
}
@Test
public
void rmiSlow() throws InitializationException, SecurityException, IOException {
ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort;
connectionOptions.host = host;
connectionOptions.enableRmi = true;
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT(true, true);
register(connectionOptions.serializationManager);
final Server server = new Server(connectionOptions);
server.disableRemoteKeyValidation();
addEndPoint(server);
server.bind(false);
// have to have this happen BEFORE any connections are made.
final TestObjectImpl serverTestObject = new TestObjectImpl(CLIENT_ID);
server.rmi()
.register(CLIENT_REMOTE_ID, serverTestObject);
server.listeners()
.add(new Listener<MessageWithTestObject>() {
@Override
public
void received(Connection connection, MessageWithTestObject m) {
System.err.println("Client Finished!");
stopEndPoints(2000);
}
});
// ----
final Client client = new Client(connectionOptions);
client.disableRemoteKeyValidation();
addEndPoint(client);
client.listeners()
.add(new Listener<MessageWithTestObject>() {
@Override
public
void connected(final Connection connection) {
new Thread() {
@Override
public
void run() {
TestObject test = connection.getRemoteObject(CLIENT_REMOTE_ID, TestObject.class);
test.id();
// Timeout on purpose.
try {
((RemoteObject) test).setResponseTimeout(200);
test.slow();
Assert.fail();
} catch (TimeoutException ignored) {
}
try {
Thread.sleep(300);
} catch (InterruptedException ignored) {
}
((RemoteObject) test).setResponseTimeout(3000);
connection.send()
.TCP(new MessageWithTestObject())
.flush();
}
}.start();
}
});
client.connect(5000);
waitForThreads(30);
}
public
interface TestObject {
void throwException();
void moo();
void moo(String value);
void moo(String value, long delay);
int id();
float slow();
}
public static
class TestObjectImpl implements TestObject {
private final int id; private final int id;
public long value = System.currentTimeMillis();
public int moos; public int moos;
public TestObjectImpl(int id) { public
TestObjectImpl(int id) {
this.id = id; this.id = id;
} }
@Override @Override
public void throwException() { public
void throwException() {
throw new UnsupportedOperationException("Why would I do that?"); throw new UnsupportedOperationException("Why would I do that?");
} }
@Override @Override
public void moo() { public
void moo() {
this.moos++; this.moos++;
System.out.println("Moo!"); System.out.println("Moo!");
} }
@Override @Override
public void moo(String value) { public
void moo(String value) {
this.moos += 2; this.moos += 2;
System.out.println("Moo: " + value); System.out.println("Moo: " + value);
} }
@Override @Override
public void moo(String value, long delay) { public
void moo(String value, long delay) {
this.moos += 4; this.moos += 4;
System.out.println("Moo: " + value + " (" + delay + ")"); System.out.println("Moo: " + value + " (" + delay + ")");
try { try {
@ -372,21 +415,25 @@ public class RmiTest extends BaseTest {
} }
@Override @Override
public int id() { public
int id() {
return this.id; return this.id;
} }
@Override @Override
public float slow() { public
float slow() {
try { try {
Thread.sleep(300); Thread.sleep(300);
} catch (InterruptedException ex) { } catch (InterruptedException ignored) {
} }
return 666; return 666;
} }
} }
public static class MessageWithTestObject implements RmiMessages {
public static
class MessageWithTestObject implements RmiMessages {
public int number; public int number;
public String text; public String text;
public TestObject testObject; public TestObject testObject;