Move files in anticipation of move to modular system

This commit is contained in:
2016-07-03 12:28:35 +01:00
parent 72e82b41fe
commit 3cca0d9ba0
331 changed files with 5552 additions and 5587 deletions

View File

@@ -0,0 +1,7 @@
package base;
public interface Control {
public void start();
public void stop();
public void exit();
}

View File

@@ -0,0 +1,3 @@
package base;
public interface Duplex extends Forwarder, Sender {}

View File

@@ -0,0 +1,6 @@
package base;
public interface Forwarder extends Control {
public void register(Receiver receiver);
public void remove(Receiver receiver);
}

View File

@@ -0,0 +1,5 @@
package base;
public interface Receiver {
public void receive(byte[] buffer);
}

View File

@@ -0,0 +1,7 @@
package base;
import java.io.IOException;
public interface Sender extends Control {
public void send(byte[] buffer) throws IOException;
}

View File

@@ -0,0 +1,9 @@
package base.exception;
public class LoaderException extends Exception {
protected static final long serialVersionUID = 1L;
public LoaderException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,5 @@
package base.exception;
public class WorkerException extends Exception {
protected static final long serialVersionUID = 1L;
}

View File

@@ -0,0 +1,7 @@
package base.exception.worker;
import base.exception.WorkerException;
public class ActivateException extends WorkerException {
protected static final long serialVersionUID = 1L;
}

View File

@@ -0,0 +1,7 @@
package base.exception.worker;
import base.exception.WorkerException;
public class AlreadyActiveException extends WorkerException {
protected static final long serialVersionUID = 1L;
}

View File

@@ -0,0 +1,7 @@
package base.exception.worker;
import base.exception.WorkerException;
public class AlreadyRunningException extends WorkerException {
protected static final long serialVersionUID = 1L;
}

View File

@@ -0,0 +1,7 @@
package base.exception.worker;
import base.exception.WorkerException;
public class DeactivateException extends WorkerException {
protected static final long serialVersionUID = 1L;
}

View File

@@ -0,0 +1,7 @@
package base.exception.worker;
import base.exception.WorkerException;
public class NotActiveException extends WorkerException {
protected static final long serialVersionUID = 1L;
}

View File

@@ -0,0 +1,7 @@
package base.exception.worker;
import base.exception.WorkerException;
public class NotRunningException extends WorkerException {
protected static final long serialVersionUID = 1L;
}

View File

@@ -0,0 +1,7 @@
package base.exception.worker;
import base.exception.WorkerException;
public class StartException extends WorkerException {
protected static final long serialVersionUID = 1L;
}

View File

@@ -0,0 +1,146 @@
package base.loader;
import java.io.IOException;
import java.util.Properties;
import org.picocontainer.DefaultPicoContainer;
import org.picocontainer.MutablePicoContainer;
import org.picocontainer.Parameter;
import org.picocontainer.parameters.ConstantParameter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import base.Duplex;
import base.Forwarder;
import base.Sender;
import base.exception.LoaderException;
import base.server.datagram.UdpSender;
import base.server.forwarder.UdpDuplexClientForwarder;
import base.server.forwarder.UdpDuplexServerForwarder;
public class AbstractLoader<T> {
protected static final String PROPERTIES_FILE = "loader.properties";
protected static final Properties SERVER = null;
protected Logger logger = LoggerFactory.getLogger(AbstractLoader.class);
protected MutablePicoContainer pico;
public AbstractLoader() {
/* Initialise container */
pico = new DefaultPicoContainer();
}
public AbstractLoader(Properties properties) {
this();
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static <T> T getLoader() throws LoaderException {
return (T) new AbstractLoader(readProperties(PROPERTIES_FILE));
}
public static Properties readProperties(String propertiesFile) throws LoaderException {
/* Read properties file */
Properties properties = new Properties();
try {
properties.load(AbstractLoader.class.getClassLoader().getResourceAsStream(propertiesFile));
} catch (IOException e) {
throw new LoaderException("Faield to read properties file: " + PROPERTIES_FILE);
}
return properties;
}
protected Class<?> getSenderClass(String protocol, String implementation) throws LoaderException {
switch (protocol) {
case "tcp":
switch (implementation) {
case "channel":
return base.server.channel.TcpClient.class;
default:
case "socket":
return base.server.socket.TcpClient.class;
}
case "udp":
return UdpSender.class;
}
throw new LoaderException("Failed to determine <Sender>");
}
protected Class<?> getClientForwarderClass(String protocol, String implementation) throws LoaderException {
switch (protocol) {
case "tcp":
switch (implementation) {
case "channel":
return base.server.forwarder.TcpClientChannelForwarder.class;
default:
case "socket":
return base.server.forwarder.TcpClientSocketForwarder.class;
}
case "udp":
return UdpDuplexClientForwarder.class;
}
throw new LoaderException("Failed to determine <Forwarder>");
}
protected Class<?> getServerForwarderClass(String protocol, String implementation) throws LoaderException {
switch (protocol) {
case "tcp":
switch (implementation) {
case "channel":
return base.server.forwarder.TcpChannelServerForwarder.class;
default:
case "socket":
return base.server.forwarder.TcpSocketServerForwarder.class;
}
case "udp":
return UdpDuplexServerForwarder.class;
}
throw new LoaderException("Failed to determine <Forwarder>");
}
protected void addClientSender(String protocol, String implementation, String host, int port) throws LoaderException {
Class<?> senderClass = getSenderClass(protocol, implementation);
logger.debug("Adding " + senderClass);
pico.addComponent(Sender.class, senderClass, new Parameter[]{
new ConstantParameter(host),
new ConstantParameter(port)});
}
protected void addServerSender(String protocol, String implementation, int port) throws LoaderException {
Class<?> senderClass = getSenderClass(protocol, implementation);
logger.debug("Adding " + senderClass);
pico.addComponent(Sender.class, senderClass, new Parameter[]{
new ConstantParameter(port)});
}
protected void addClientForwarder(String protocol, String implementation, String host, int port) throws LoaderException {
Class<?> forwarderClass = getClientForwarderClass(protocol, implementation);
logger.debug("Adding " + forwarderClass);
pico.addComponent(Forwarder.class, forwarderClass, new Parameter[]{
new ConstantParameter(host),
new ConstantParameter(port)});
}
protected void addClientDuplex(String protocol, String implementation, String host, int port) throws LoaderException {
Class<?> duplexClass = getClientForwarderClass(protocol, implementation);
logger.debug("Adding " + duplexClass);
pico.addComponent(Duplex.class, duplexClass, new Parameter[]{
new ConstantParameter(host),
new ConstantParameter(port)});
}
protected void addServerForwarder(String protocol, String implementation, int port) throws LoaderException {
Class<?> forwarderClass = getServerForwarderClass(protocol, implementation);
logger.debug("Adding " + forwarderClass);
pico.addComponent(Forwarder.class, forwarderClass, new Parameter[]{
new ConstantParameter(port)});
}
protected void addServerDuplex(String protocol, String implementation, int port) throws LoaderException {
Class<?> duplexClass = getServerForwarderClass(protocol, implementation);
logger.debug("Adding " + duplexClass);
pico.addComponent(Duplex.class, duplexClass, new Parameter[]{
new ConstantParameter(port)});
}
}

View File

@@ -0,0 +1,137 @@
package base.server.channel;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;
import base.Sender;
import base.exception.worker.ActivateException;
import base.exception.worker.DeactivateException;
import base.work.Listen;
import base.work.Work;
import base.worker.Worker;
public class TcpClient extends Work implements Sender {
protected static final String HOST = "localhost";
protected static final int BUFFER_SIZE = 1024;
protected String host;
protected int port;
protected int bufferSize;
protected SocketChannel socketChannel;
protected Selector selector;
protected ArrayList<Listen<byte[]>> listenList = new ArrayList<Listen<byte[]>>();
public TcpClient(int port) {
this(HOST, port);
}
public TcpClient(String host, int port) {
this(host, port, BUFFER_SIZE);
}
public TcpClient(String host, int port, int bufferSize) {
this.host = host;
this.port = port;
this.bufferSize = bufferSize;
}
public void activate() throws ActivateException {
System.out.println("Client: Activate!");
try {
InetSocketAddress hostAddress = new InetSocketAddress(host, port);
socketChannel = SocketChannel.open(hostAddress);
socketChannel.configureBlocking(false);
while (!socketChannel.finishConnect()) {
sleep(Worker.SLEEP);
}
selector = Selector.open();
socketChannel.register(selector, SelectionKey.OP_READ);
synchronized (host) {
host.notifyAll();
}
} catch (Exception e) {
logger.error("", e);
throw new ActivateException();
}
super.activate();
}
public void deactivate() throws DeactivateException {
System.out.println("Client: Deactivate!");
try {
selector.close();
socketChannel.close();
} catch (IOException e) {
throw new DeactivateException();
}
}
public void stop() {
super.stop();
if (selector != null) {
selector.wakeup();
}
}
public final void work() {
try {
logger.debug("Client: Waiting for select... ");
logger.debug("Client: Number of selected keys: " + selector.select());
Set<SelectionKey> selectionKeySet = selector.selectedKeys();
Iterator<SelectionKey> selectionKeyIterator = selectionKeySet.iterator();
while (selectionKeyIterator.hasNext()) {
SelectionKey selectionKey = selectionKeyIterator.next();
if (selectionKey.isReadable()) {
ByteBuffer byteBuffer = ByteBuffer.allocate(bufferSize);
socketChannel.read(byteBuffer);
byte[] buffer = byteBuffer.array();
input(buffer);
} else if (selectionKey.isWritable()) {
byte[] buffer;
buffer = (byte[]) selectionKey.attachment();
ByteBuffer byteBuffer = ByteBuffer.wrap(buffer);
socketChannel.write(byteBuffer);
//selectionKey.cancel();
socketChannel.register(selector, SelectionKey.OP_READ);
}
selectionKeyIterator.remove();
}
} catch (Exception e) {
logger.error("", e);
}
}
protected void input(byte[] buffer) {}
public void send(byte[] buffer) throws IOException {
if (selector == null) {
try {
synchronized (host) {
host.wait();
}
} catch (InterruptedException e) {}
}
selector.wakeup();
socketChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, buffer);
}
public void close() throws IOException {
socketChannel.close();
}
/*public void register(Listen<byte[]> listen) {
listenList.add(listen);
}
public void remove(Listen<byte[]> listen) {
listenList.remove(listen);
}*/
}

View File

@@ -0,0 +1,158 @@
package base.server.channel;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.net.BindException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;
import base.Sender;
import base.exception.worker.ActivateException;
import base.exception.worker.DeactivateException;
import base.server.channel.TcpServerClient;
import base.work.Work;
public class TcpServer extends Work implements Sender {
protected static final Class<?> CLIENT_CLASS = TcpServerClient.class;
protected static final int BUFFER_SIZE = 1024;
protected int port;
protected int bufferSize;
protected Constructor<?> clientConstructor;
protected Selector selector;
protected ServerSocketChannel serverSocket;
protected ArrayList<TcpServerClient> clientList;
public TcpServer(int port) {
this(port, CLIENT_CLASS);
}
public TcpServer(int port, Class<?> clientClass) {
this(port, clientClass, BUFFER_SIZE);
}
public TcpServer(int port, Class<?> clientClass, int bufferSize) {
this.port = port;
this.bufferSize = bufferSize;
try {
// Allow dependency injection, constructor arguments
clientConstructor = Class.forName(clientClass.getName()).getConstructor(TcpServer.class, SocketChannel.class, Integer.class);
} catch (NoSuchMethodException | SecurityException | ClassNotFoundException e) {
logger.error("Failed to initialise client constructor", e);
}
clientList = new ArrayList<TcpServerClient>();
}
public void activate() throws ActivateException {
System.out.println("Server: Activate!");
try {
// Get selector
selector = Selector.open();
// Get server socket channel and register with selector
serverSocket = ServerSocketChannel.open();
InetSocketAddress hostAddress = new InetSocketAddress(port);
serverSocket.bind(hostAddress);
serverSocket.configureBlocking(false);
serverSocket.register(selector, SelectionKey.OP_ACCEPT);
synchronized (clientConstructor) {
clientConstructor.notifyAll();
}
return;
} catch (BindException e) {
logger.error("Address already in use", e);
} catch (IOException e) {
logger.error("", e);
}
throw new ActivateException();
}
public void deactivate() throws DeactivateException {
System.out.println("Server: Deactivate!");
try {
selector.close();
serverSocket.close();
} catch (IOException e) {
throw new DeactivateException();
} finally {
for (TcpServerClient client : clientList) {
client.stop();
}
}
}
public void stop() {
super.stop();
if (selector != null) {
selector.wakeup();
}
}
public void work() {
try {
System.out.println("Server: Waiting for select... ");
System.out.println("Server: Number of selected keys: " + selector.select());
Set<SelectionKey> selectionKeySet = selector.selectedKeys();
Iterator<SelectionKey> selectionKeyIterator = selectionKeySet.iterator();
while (selectionKeyIterator.hasNext()) {
SelectionKey selectionKey = selectionKeyIterator.next();
if (selectionKey.isAcceptable()) {
// Accept the new client connection
SocketChannel socketChannel = serverSocket.accept();
socketChannel.configureBlocking(false);
// Add the new connection to the selector
TcpServerClient client = (TcpServerClient) clientConstructor.newInstance(this, socketChannel, bufferSize);
clientList.add(client);
socketChannel.register(selector, SelectionKey.OP_READ, client);
//initClient(client);
System.out.println("Accepted new connection from client: " + socketChannel);
} else if (selectionKey.isReadable()) {
// Read the data from client
TcpServerClient serverClient = (TcpServerClient) selectionKey.attachment();
serverClient.readable();
} else if (selectionKey.isWritable()) {
// Write to client?
}
selectionKeyIterator.remove();
}
}/* catch (IOException e) {} catch (InstantiationException e) {
logger.error("", e);
} catch (IllegalAccessException e) {
logger.error("", e);
} catch (IllegalArgumentException e) {
logger.error("", e);
} catch (InvocationTargetException e) {
logger.error("", e);
} */catch (Exception e) {
e.printStackTrace();
}
}
protected void initClient(TcpServerClient client) {
try {
client.write(ByteBuffer.wrap(new String("Hi there!").getBytes()));
} catch (IOException e) {
logger.error("", e);
}
}
public void send(byte[] buffer) throws IOException {
logger.debug("Number of clients = " + clientList.size());
for (TcpServerClient client : clientList) {
// Should be dealt with in clients own thread
client.send(buffer);
}
}
public void input(TcpServerClient client, byte[] buffer) {}
}

View File

@@ -0,0 +1,54 @@
package base.server.channel;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import base.Sender;
import base.work.Listen;
public class TcpServerClient extends Listen<byte[]> implements Sender {
protected static final int BUFFER_SIZE = 1024;
protected TcpServer server;
protected SocketChannel socketChannel;
protected int bufferSize;
protected ByteBuffer byteBuffer;
public TcpServerClient(TcpServer server, SocketChannel socketChannel) {
this(server, socketChannel, BUFFER_SIZE);
}
public TcpServerClient(TcpServer server, SocketChannel socketChannel, Integer bufferSize) {
super();
this.server = server;
this.socketChannel = socketChannel;
this.bufferSize = bufferSize;
byteBuffer = ByteBuffer.allocate(bufferSize);
}
public void write(ByteBuffer byteBuffer) throws IOException {
socketChannel.write(byteBuffer);
}
public void readable() throws IOException {
int read;
while (( read = socketChannel.read(byteBuffer)) > 0) {
byteBuffer.flip();
byte[] buffer = byteBuffer.array();
input(buffer);
byteBuffer.clear();
}
if (read < 0) {
socketChannel.close();
}
}
public void input(byte[] buffer) {
server.input(this, buffer);
}
public void send(byte[] buffer) throws IOException {
write(ByteBuffer.wrap(buffer));
}
}

View File

@@ -0,0 +1,46 @@
package base.server.datagram;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.MulticastSocket;
import base.work.Work;
public abstract class AbstractUdpClient extends Work {
protected static final int BUFFER_SIZE = 2048;
protected int bufferSize;
protected MulticastSocket socket;
protected DatagramPacket datagramPacket;
public AbstractUdpClient() {}
public AbstractUdpClient(MulticastSocket socket) {
this(socket, BUFFER_SIZE);
}
public AbstractUdpClient(MulticastSocket socket, int bufferSize) {
this.socket = socket;
this.bufferSize = bufferSize;
byte[] buffer = new byte[bufferSize];
datagramPacket = new DatagramPacket(buffer, buffer.length);
}
public void work() {
try {
byte[] buffer = new byte[bufferSize];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
System.out.println("iets ontvangen!!!!!");
buffer = packet.getData();
input(buffer);
} catch (IOException e) {}
}
public void stop() {
socket.close();
super.stop();
}
protected abstract void input(byte[] buffer);
}

View File

@@ -0,0 +1,17 @@
package base.server.datagram;
import java.net.UnknownHostException;
public class UdpDuplexAutoClient extends UdpDuplexClient {
public UdpDuplexAutoClient(int bindPort, int sendPort) throws UnknownHostException {
super(HOST, bindPort, null, sendPort);
}
public UdpDuplexAutoClient(String bindHost, int bindPort, int sendPort) throws UnknownHostException {
super(bindHost, bindPort, null, sendPort);
}
public UdpDuplexAutoClient(String bindHost, int bindPort, int sendPort, int bufferSize) throws UnknownHostException {
super(bindHost, bindPort, null, sendPort, bufferSize);
}
}

View File

@@ -0,0 +1,51 @@
package base.server.datagram;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.UnknownHostException;
import base.Sender;
public class UdpDuplexClient extends UdpMulticastClient implements Sender {
protected int sendPort;
protected Sender sender;
public UdpDuplexClient(int bindPort, String sendHost, int sendPort) throws UnknownHostException {
this(HOST, bindPort, sendHost, sendPort);
}
public UdpDuplexClient(String bindHost, int bindPort, String sendHost, int sendPort) throws UnknownHostException {
this(bindHost, bindPort, sendHost, sendPort, BUFFER_SIZE);
}
public UdpDuplexClient(String bindHost, int bindPort, String sendHost, int sendPort, int bufferSize) throws UnknownHostException {
super(bindHost, bindPort, bufferSize);
this.sendPort = sendPort;
if (sendHost != null) {
sender = new UdpSender(sendHost, sendPort);
}
}
public void work() {
try {
byte[] buffer = new byte[bufferSize];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
buffer = packet.getData();
System.out.println("Receive from " + packet.getAddress().getHostAddress());
if (sender == null) {
String sendHost = packet.getAddress().getHostAddress();
sender = new UdpSender(sendHost, sendPort);
}
input(buffer);
} catch (IOException e) {}
}
public void send(byte[] buffer) throws IOException {
if (sender != null) {
sender.send(buffer);
}
}
public void input(byte[] buffer) {}
}

View File

@@ -0,0 +1,19 @@
package base.server.datagram;
import java.net.MulticastSocket;
import base.work.Listen;
public class UdpDuplexHelper extends AbstractUdpClient {
protected Listen<byte[]> listen;
public UdpDuplexHelper(Listen<byte[]> listen, MulticastSocket socket) {
super(socket);
this.listen = listen;
}
public void input(byte[] buffer) {
System.out.println("jajajaja");
listen.add(buffer);
}
}

View File

@@ -0,0 +1,59 @@
package base.server.datagram;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import base.exception.worker.ActivateException;
import base.exception.worker.DeactivateException;
public class UdpDuplexServer extends UdpMulticastServer {
protected int bindPort;
protected UdpDuplexHelper helper;
public UdpDuplexServer(int sendPort, int bindPort) {
super(sendPort);
this.bindPort = bindPort;
}
public void activate() throws ActivateException {
try {
socket = new MulticastSocket(bindPort);
synchronized (this) {
notifyAll();
}
helper = new UdpDuplexHelper(this, socket);
helper.start();
} catch (IOException e) {
throw new ActivateException();
}
super.activate();
}
public void deactivate() throws DeactivateException {
helper.stop();
super.deactivate();
}
public void send(byte[] buffer) throws IOException {
if (socket == null) {
synchronized (this) {
try {
wait();
} catch (InterruptedException e) {
return;
}
}
}
try {
InetAddress group = InetAddress.getByName(host);
System.out.println("Send to " + host + " " + port);
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, group, port);
socket.send(packet);
}
catch (IOException e) {
logger.error("", e);
}
}
}

View File

@@ -0,0 +1,42 @@
package base.server.datagram;
import java.io.IOException;
import java.net.InetAddress;
import java.net.MulticastSocket;
import base.exception.worker.ActivateException;
public class UdpMulticastClient extends AbstractUdpClient {
protected static final String HOST = "239.255.255.255";
protected String host;
protected int port;
public UdpMulticastClient(int port) {
this(HOST, port);
}
public UdpMulticastClient(String host, int port) {
this(host, port, BUFFER_SIZE);
}
public UdpMulticastClient(String host, int port, int bufferSize) {
this.host = host;
this.port = port;
this.bufferSize = BUFFER_SIZE;
System.out.println("Client bind: " + host + " " + port);
}
public void activate() throws ActivateException {
try {
socket = new MulticastSocket(port);
InetAddress group = InetAddress.getByName(host);
socket.joinGroup(group);
} catch (IOException e) {
logger.error("", e);
throw new ActivateException();
}
}
protected void input(byte[] buffer) {}
}

View File

@@ -0,0 +1,61 @@
package base.server.datagram;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import base.Sender;
import base.exception.worker.ActivateException;
import base.exception.worker.DeactivateException;
import base.work.Listen;
import base.worker.Worker;
public class UdpMulticastServer extends Listen<byte[]> implements Sender {
protected static final String HOST = "239.255.255.255";
protected static final int BUFFER_SIZE = 2048;
protected String host;
protected int port;
protected MulticastSocket socket;
public UdpMulticastServer(int port) {
this(HOST, port);
}
public UdpMulticastServer(String host, int port) {
super(Worker.Type.BACKGROUND);
this.host = host;
this.port = port;
System.out.println("Server send: " + host + " " + port);
}
public void activate() throws ActivateException {
try {
socket = new MulticastSocket();
} catch (IOException e) {
throw new ActivateException();
}
super.activate();
}
public void deactivate() throws DeactivateException {
socket.close();
super.deactivate();
}
public void input(byte[] buffer) {
try {
InetAddress group = InetAddress.getByName(host);
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, group, port);
socket.send(packet);
}
catch (IOException e) {
logger.error("", e);
}
}
public void send(byte[] buffer) throws IOException {
add(buffer);
}
}

View File

@@ -0,0 +1,56 @@
package base.server.datagram;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import base.Sender;
public class UdpSender implements Sender {
protected static final String HOST = "localhost";
protected Logger logger = LoggerFactory.getLogger(getClass());
protected DatagramSocket datagramSocket;
protected InetAddress inetAddress;
protected int port;
public UdpSender(int port) throws UnknownHostException {
this(HOST, port);
}
public UdpSender(String host, int port) throws UnknownHostException {
System.out.println("Sender use: " + host + " " + port);
inetAddress = InetAddress.getByName(host);
this.port = port;
try {
datagramSocket = new DatagramSocket();
} catch (SocketException e) {
logger.error("Failed to create socket", e);
}
}
public void start() {}
public void stop() {
datagramSocket.close();
}
public void exit() {
stop();
}
public void send(byte[] buffer) {
try {
DatagramPacket datagramPacket = new DatagramPacket(buffer, buffer.length, inetAddress, port);
datagramSocket.send(datagramPacket);
} catch (IOException e) {
logger.error("Failed to send buffer", e);
}
}
}

View File

@@ -0,0 +1,64 @@
package base.server.datagram;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import base.exception.worker.ActivateException;
import base.work.Work;
public class UdpServer extends Work {
protected static final int BUFFER_SIZE = 1024;
protected static final int TIMEOUT = 1000;
protected int port;
protected int bufferSize;
protected DatagramSocket diagramSocket;
public UdpServer(int port) {
this(port, BUFFER_SIZE);
}
public UdpServer(int port, int bufferSize) {
super();
this.port = port;
this.bufferSize = bufferSize;
}
public void activate() throws ActivateException {
try {
logger.debug("Starting datagram socket on port " + port);
diagramSocket = new DatagramSocket(port);
diagramSocket.setSoTimeout(TIMEOUT);
super.activate();
} catch (SocketException e) {
logger.error("Failed to initialize socket", e);
throw new ActivateException();
}
}
public void stop() {
super.stop();
if (diagramSocket != null) {
diagramSocket.close();
}
}
public void work() {
byte[] buffer = new byte[bufferSize];
DatagramPacket datagramPacket = new DatagramPacket(buffer, buffer.length);
try {
diagramSocket.receive(datagramPacket);
} catch (SocketException e) {
stop();
} catch (IOException e) {
logger.error("Failed to receive packet", e);
stop();
return;
}
input(buffer);
}
protected void input(byte[] buffer) {}
}

View File

@@ -0,0 +1,31 @@
package base.server.forwarder;
import java.util.ArrayList;
import base.Duplex;
import base.Receiver;
import base.server.channel.TcpServer;
import base.server.channel.TcpServerClient;
public class TcpChannelServerForwarder extends TcpServer implements Duplex {
protected ArrayList<Receiver> receiverList;
public TcpChannelServerForwarder(int port) {
super(port);
receiverList = new ArrayList<Receiver>();
}
public void register(Receiver receiver) {
receiverList.add(receiver);
}
public void remove(Receiver receiver) {
receiverList.remove(receiver);
}
public void input(TcpServerClient client, byte[] buffer) {
for (Receiver receiver: receiverList) {
receiver.receive(buffer);
}
}
}

View File

@@ -0,0 +1,31 @@
package base.server.forwarder;
import java.util.ArrayList;
import base.Duplex;
import base.Receiver;
import base.server.socket.TcpClient;
import base.server.socket.TcpServerClient;
public class TcpClientChannelForwarder extends TcpClient implements Duplex {
protected ArrayList<Receiver> receiverList;
public TcpClientChannelForwarder(String host, int port) {
super(host, port);
receiverList = new ArrayList<Receiver>();
}
public void register(Receiver receiver) {
receiverList.add(receiver);
}
public void remove(Receiver receiver) {
receiverList.remove(receiver);
}
public void input(TcpServerClient client, byte[] buffer) {
for (Receiver receiver: receiverList) {
receiver.receive(buffer);
}
}
}

View File

@@ -0,0 +1,31 @@
package base.server.forwarder;
import java.util.ArrayList;
import base.Duplex;
import base.Receiver;
import base.server.channel.TcpClient;
import base.server.channel.TcpServerClient;
public class TcpClientSocketForwarder extends TcpClient implements Duplex {
protected ArrayList<Receiver> receiverList;
public TcpClientSocketForwarder(String host, int port) {
super(host, port);
receiverList = new ArrayList<Receiver>();
}
public void register(Receiver receiver) {
receiverList.add(receiver);
}
public void remove(Receiver receiver) {
receiverList.remove(receiver);
}
public void input(TcpServerClient client, byte[] buffer) {
for (Receiver receiver: receiverList) {
receiver.receive(buffer);
}
}
}

View File

@@ -0,0 +1,31 @@
package base.server.forwarder;
import java.util.ArrayList;
import base.Duplex;
import base.Receiver;
import base.server.socket.TcpServer;
import base.server.socket.TcpServerClient;
public class TcpSocketServerForwarder extends TcpServer implements Duplex {
protected ArrayList<Receiver> receiverList;
public TcpSocketServerForwarder(int port) {
super(port);
receiverList = new ArrayList<Receiver>();
}
public void register(Receiver receiver) {
receiverList.add(receiver);
}
public void remove(Receiver receiver) {
receiverList.remove(receiver);
}
public void input(TcpServerClient client, byte[] buffer) {
for (Receiver receiver: receiverList) {
receiver.receive(buffer);
}
}
}

View File

@@ -0,0 +1,31 @@
package base.server.forwarder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import base.Duplex;
import base.Receiver;
import base.server.datagram.UdpDuplexClient;
public class UdpDuplexClientForwarder extends UdpDuplexClient implements Duplex {
protected ArrayList<Receiver> receiverList;
public UdpDuplexClientForwarder(String bindHost, int bindPort, String sendHost, int sendPort) throws UnknownHostException {
super(bindHost, bindPort, sendHost, sendPort);
receiverList = new ArrayList<Receiver>();
}
public void register(Receiver receiver) {
receiverList.add(receiver);
}
public void remove(Receiver receiver) {
receiverList.remove(receiver);
}
public void input(byte[] buffer) {
for (Receiver receiver: receiverList) {
receiver.receive(buffer);
}
}
}

View File

@@ -0,0 +1,30 @@
package base.server.forwarder;
import java.util.ArrayList;
import base.Duplex;
import base.Receiver;
import base.server.datagram.UdpDuplexServer;
public class UdpDuplexServerForwarder extends UdpDuplexServer implements Duplex {
protected ArrayList<Receiver> receiverList;
public UdpDuplexServerForwarder(int port, int listenPort) {
super(port, listenPort);
receiverList = new ArrayList<Receiver>();
}
public void register(Receiver receiver) {
receiverList.add(receiver);
}
public void remove(Receiver receiver) {
receiverList.remove(receiver);
}
public void input(byte[] buffer) {
for (Receiver receiver: receiverList) {
receiver.receive(buffer);
}
}
}

View File

@@ -0,0 +1,30 @@
package base.server.forwarder;
import java.util.ArrayList;
import base.Forwarder;
import base.Receiver;
import base.server.datagram.UdpServer;
public class UdpServerForwarder extends UdpServer implements Forwarder {
protected ArrayList<Receiver> receiverList;
public UdpServerForwarder(int port) {
super(port);
receiverList = new ArrayList<Receiver>();
}
public void register(Receiver receiver) {
receiverList.add(receiver);
}
public void remove(Receiver receiver) {
receiverList.remove(receiver);
}
public void input(byte[] buffer) {
for (Receiver receiver: receiverList) {
receiver.receive(buffer);
}
}
}

View File

@@ -0,0 +1,33 @@
package base.server.receiver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import base.Control;
import base.Forwarder;
import base.Receiver;
public abstract class AbstractReceiver implements Receiver, Control {
protected Logger logger = LoggerFactory.getLogger(getClass());
protected Forwarder forwarder;
public AbstractReceiver(Forwarder forwarder) {
this.forwarder = forwarder;
forwarder.register(this);
}
public void start() {
forwarder.start();
}
public void stop() {
forwarder.stop();
}
public void exit() {
forwarder.exit();
}
abstract public void receive(byte[] buffer);
}

View File

@@ -0,0 +1,72 @@
package base.server.socket;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import base.Sender;
import base.exception.worker.DeactivateException;
import base.work.Work;
public abstract class AbstractTcpClient extends Work implements Sender {
protected static final int BUFFER_SIZE = 1024;
protected Object object = new Object();
protected int bufferSize;
protected Socket socket;
protected InputStream inputStream;
protected OutputStream outputStream;
public AbstractTcpClient(Integer bufferSize) {
this.bufferSize = bufferSize;
}
public boolean active() {
return super.active() && socket.isConnected();
}
public void deactivate() throws DeactivateException {
super.deactivate();
try {
inputStream.close();
outputStream.close();
socket.close();
} catch (IOException e) {
logger.error("", e);
}
}
public void exit() {
super.exit();
try {
socket.close();
} catch (IOException e) {
logger.error("", e);
}
}
public void work() {
byte[] buffer = new byte[bufferSize];
try {
while (inputStream.read(buffer) > 0) {
input(buffer);
}
} catch (IOException e) {
stop();
}
}
protected abstract void input(byte[] buffer);
public void send(byte[] buffer) throws IOException {
if (outputStream == null) {
try {
synchronized (object) {
object.wait();
}
} catch (InterruptedException e) {}
}
outputStream.write(buffer);
}
}

View File

@@ -0,0 +1,49 @@
package base.server.socket;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import base.Sender;
import base.exception.worker.ActivateException;
public class TcpClient extends AbstractTcpClient implements Sender {
protected static final String HOST = "localhost";
protected String host;
protected int port;
public TcpClient(int port) {
this(HOST, port);
}
public TcpClient(String host, int port) {
this(host, port, BUFFER_SIZE);
}
public TcpClient(String host, int port, int bufferSize) {
super(bufferSize);
this.host = host;
this.port = port;
}
public void activate() throws ActivateException {
try {
socket = new Socket(host, port);
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
synchronized (object) {
object.notifyAll();
}
} catch (UnknownHostException e) {
logger.error("", e);
throw new ActivateException();
} catch (IOException e) {
logger.error("", e);
throw new ActivateException();
}
super.activate();
}
protected void input(byte[] buffer) {}
}

View File

@@ -0,0 +1,86 @@
package base.server.socket;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import base.Sender;
import base.exception.worker.ActivateException;
import base.exception.worker.DeactivateException;
import base.work.Work;
public class TcpServer extends Work implements Sender {
protected static final Class<?> CLIENT_CLASS = TcpServerClient.class;
protected int port;
protected ServerSocket serverSocket;
protected Constructor<?> clientConstructor;
protected ArrayList<TcpServerClient> clientList;
public TcpServer(int port) {
this(port, CLIENT_CLASS);
}
public TcpServer(int port, Class<?> clientClass) {
this.port = port;
try {
clientConstructor = Class.forName(clientClass.getName()).getConstructor(TcpServer.class, Socket.class);
} catch (NoSuchMethodException | SecurityException | ClassNotFoundException e) {
logger.error("Failed to initialise client constructor");
}
clientList = new ArrayList<TcpServerClient>();
}
public void activate() throws ActivateException {
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
logger.error("", e);
throw new ActivateException();
}
}
public void deactivate() throws DeactivateException {
for (TcpServerClient client : clientList) {
client.stop();
}
}
public void exit() {
super.exit();
try {
serverSocket.close();
for (TcpServerClient client : clientList) {
client.exit();
}
} catch (IOException e) {
logger.error("", e);
}
}
public void work() {
try {
Socket socket = serverSocket.accept();
TcpServerClient client = (TcpServerClient) clientConstructor.newInstance(this, socket);
clientList.add(client);
client.start();
System.out.println("Accepted new connection from client: " + socket);
} catch (IOException e) {
stop();
} catch (Exception e) {
logger.error("", e);
}
}
public void send(byte[] buffer) throws IOException {
logger.debug("Number of clients = " + clientList.size());
for (TcpServerClient client : clientList) {
// Should be dealt with in clients own thread?
client.send(buffer);
}
}
public void input(TcpServerClient client, byte[] buffer) {}
}

View File

@@ -0,0 +1,37 @@
package base.server.socket;
import java.io.IOException;
import java.net.Socket;
import base.exception.worker.ActivateException;
public class TcpServerClient extends AbstractTcpClient {
private TcpServer server;
public TcpServerClient(TcpServer server, Socket socket) {
this(server, socket, BUFFER_SIZE);
}
public TcpServerClient(TcpServer server, Socket socket, Integer bufferSize) {
super(bufferSize);
this.server = server;
this.socket = socket;
}
public void activate() throws ActivateException {
try {
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
synchronized (object) {
object.notifyAll();
}
} catch (IOException e) {
logger.error("", e);
throw new ActivateException();
}
}
public void input(byte[] buffer) {
server.input(this, buffer);
}
}

View File

@@ -0,0 +1,40 @@
package base.util;
import java.util.concurrent.CopyOnWriteArrayList;
public class ArrayCycle<E> extends CopyOnWriteArrayList<E> {
protected static final long serialVersionUID = 1L;
protected int index = 0;
@SuppressWarnings("unchecked")
public ArrayCycle(E... elementArray) {
if (elementArray != null) {
for (E element : elementArray) {
add(element);
}
}
}
public E current() {
return this.get(index);
}
public synchronized E previous() {
if (--index < 0) {
index = Math.max(0, size() - 1);
}
return get(index);
}
public synchronized E next() {
if (++index >= size()) {
index = 0;
}
return size() == 0 ? null : get(index);
}
public E reset() {
return get(index = 0);
}
}

View File

@@ -0,0 +1,41 @@
package base.util;
public class Buffer {
protected byte[] elements;
protected int capacity;
protected int index;
protected int size;
public Buffer(int capacity) {
this.elements = new byte[capacity];
this.capacity = capacity;
index = 0;
size = 0;
}
public synchronized void add(byte... elements) {
for (byte element : elements) {
this.elements[index++ % capacity] = element;
if (size < capacity) {
++size;
}
}
}
public synchronized void write(byte[] elements, int offset, int length) {
for (int i = offset; i < length; ++i) {
this.elements[index++ % capacity] = elements[i];
if (size < capacity) {
++size;
}
}
}
public synchronized byte[] get() {
byte[] elements = new byte[size];
for (int i = 0; i < size; i++) {
elements[i] = this.elements[(index + i) % size];
}
return elements;
}
}

View File

@@ -0,0 +1,6 @@
package base.util;
public interface Bufferable {
public void load();
public void unload();
}

View File

@@ -0,0 +1,74 @@
package base.util;
public class BufferedArrayCycle<E extends Bufferable> extends ArrayCycle<E> {
protected static final long serialVersionUID = 1L;
protected ArrayCycle<? extends Bufferable> buffer;
protected int before;
protected int after;
protected int indexFirst;
protected int indexLast;
//protected int indexBuffer;
//protected Bufferable[] bufferableArray;
@SuppressWarnings("unchecked")
public BufferedArrayCycle(int before, int after) {
this.before = before;
this.after = after;
indexFirst = 0;
indexLast = 0;
//bufferableArray = new Bufferable[before + after + 1];
//buffer = new ArrayCycle<Bufferable>();
}
public E previous() {
get(indexFirst).unload();
indexFirst = previous(indexFirst);
indexLast = previous(indexLast);
get(indexLast).load();
// eerste before weg
// eerste after wordt huidig
// voeg laatste after toe
return current();
}
public E next() {
// eerste before weg
// eerste after wordt huidig
// voeg laatste after toe
return size() == 0 ? null : get(index);
}
protected int previous(int index) {
if (--index < 0) {
index = Math.max(0, size() - 1);
}
return index;
}
protected int next(int index) {
System.out.println(index);
if (++index >= size()) {
index = 0;
}
return index;
}
public static void main(String[] args) {
BufferedArrayCycle<Dummy> bac = new BufferedArrayCycle<Dummy>(2, 3);
for (int i = 1; i <= 10; ++i) {
bac.add(new Dummy(i));
}
bac.remove(0);
System.out.println(bac.get(2).id);
}
}

View File

@@ -0,0 +1,18 @@
package base.util;
public class Dummy implements Bufferable {
public int id;
public Dummy(int id) {
this.id = id;
}
public void load() {
System.out.println("Dummy #" + id + ": load()");
}
public void unload() {
System.out.println("Dummy #" + id + ": load()");
}
}

View File

@@ -0,0 +1,96 @@
package base.work;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import base.exception.worker.ActivateException;
import base.worker.BackgroundListener;
import base.worker.ForegroundListener;
import base.worker.Worker;
import base.worker.pool.Listener;
import base.worker.pool.ListenerPool;
import base.worker.pool.PooledListener;
public abstract class Listen<E> extends Work implements Listener<E> {
protected static final Worker.Type WORKER_TYPE = Worker.Type.DIRECT;
protected Listener<E> listener;
protected Worker.Type workerType;
public Queue<E> queue;
public Listen() {
this(WORKER_TYPE);
}
protected Listen(Worker.Type workerType) {
queue = new ConcurrentLinkedQueue<E>();
this.workerType = workerType;
switch (workerType) {
case DIRECT:
return;
case FOREGROUND:
listener = new ForegroundListener<E>(this);
break;
default:
listener = new BackgroundListener<E>(this);
break;
}
}
protected Listen(Worker worker) {
this.worker = worker;
queue = new ConcurrentLinkedQueue<E>();
}
protected Listen(ListenerPool<E> listenerPool) {
listener = new PooledListener<E>(this);
listenerPool.add((PooledListener<E>) listener);
queue = new ConcurrentLinkedQueue<E>();
}
public synchronized void add(E element) {
if (workerType.equals(Worker.Type.DIRECT)) {
input(element);
} else {
queue.add(element);
listener.add(element);
}
}
public void start() {
if (workerType.equals(Worker.Type.DIRECT)) {
try {
activate();
} catch (ActivateException e) {
logger.error("Failed to start directly", e);
}
} else {
super.start();
}
}
public void stop() {
super.stop();
synchronized (this) {
notifyAll();
}
}
public void work() {
while (!queue.isEmpty()) {
logger.debug("Listen: work() > input");
input(queue.poll());
}
synchronized (this) {
logger.debug("Listen: work() > wait");
try {
wait();
} catch (InterruptedException e) {}
logger.debug("Listen: work() > notified");
}
}
public void input(E element) {
System.err.println(element);
}
}

View File

@@ -0,0 +1,32 @@
package base.work;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import base.worker.Worker;
public class ReflectiveListen extends Listen<Object> {
public ReflectiveListen() {
super();
}
public ReflectiveListen(Worker.Type workerType) {
super(workerType);
}
public void input(Object object) {
Class<?> clazz = object.getClass();
MethodType methodType = MethodType.methodType(void.class, clazz);
MethodHandles.Lookup lookup = MethodHandles.lookup();
MethodHandle methodHandle;
try {
methodHandle = lookup.findVirtual(getClass(), "input", methodType);
methodHandle.invoke(this, object);
} catch (Exception e) {
logger.error("", e);
} catch (Throwable e) {
logger.error("", e);
}
}
}

View File

@@ -0,0 +1,73 @@
package base.work;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import base.Control;
import base.exception.worker.ActivateException;
import base.exception.worker.DeactivateException;
import base.worker.DirectWorker;
import base.worker.ThreadWorker;
import base.worker.Worker;
import base.worker.pool.PooledWorker;
import base.worker.pool.WorkerPool;
public abstract class Work implements Control {
protected static final Worker.Type WORKER_TYPE = Worker.Type.BACKGROUND;
protected Logger logger = LoggerFactory.getLogger(getClass());
protected Worker worker;
protected Work() {
this(WORKER_TYPE);
}
protected Work(Worker.Type workerType) {
switch (workerType) {
case FOREGROUND:
worker = new DirectWorker(this);
break;
default:
worker = new ThreadWorker(this);
break;
}
}
protected Work(Worker worker) {
this.worker = worker;
}
protected Work(WorkerPool workerPool) {
worker = new PooledWorker(this);
workerPool.add((PooledWorker) worker);
}
protected void sleep(int time) {
worker.sleep(time);
}
public void start() {
logger.trace("Work: start()");
worker.start();
}
public void stop() {
logger.trace("Work: stop()");
worker.stop();
}
public boolean active() {
logger.trace("Work: active()");
return worker.active();
}
public void exit() {
logger.debug("Work: exit()");
worker.exit();
}
public void activate() throws ActivateException {}
public void deactivate() throws DeactivateException {}
public abstract void work();
}

View File

@@ -0,0 +1,21 @@
package base.worker;
import base.work.Listen;
import base.worker.pool.Listener;
public class BackgroundListener<E> extends ThreadWorker implements Listener<E> {
protected Listen<E> listen;
public BackgroundListener(Listen<E> listen) {
this(listen, true);
}
public BackgroundListener(Listen<E> listen, boolean thread) {
super(listen, thread);
this.listen = listen;
}
public void add(E element) {
listen.notify();
}
}

View File

@@ -0,0 +1,14 @@
package base.worker;
import base.work.Work;
public class DirectIntervalWorker extends ThreadIntervalWorker {
public DirectIntervalWorker(Work work, int interval) {
super(work, false);
this.interval = interval;
}
public DirectIntervalWorker(IntervalWork intervalWork) {
super(intervalWork);
}
}

View File

@@ -0,0 +1,9 @@
package base.worker;
import base.work.Work;
public class DirectWorker extends ThreadWorker {
public DirectWorker(Work work) {
super(work, false);
}
}

View File

@@ -0,0 +1,10 @@
package base.worker;
import base.work.Listen;
import base.worker.pool.Listener;
public class ForegroundListener<E> extends BackgroundListener<E> implements Listener<E> {
public ForegroundListener(Listen<E> listen) {
super(listen, false);
}
}

View File

@@ -0,0 +1,37 @@
package base.worker;
import base.work.Work;
public abstract class IntervalWork extends Work {
protected IntervalWork() {
this(WORKER_TYPE);
}
protected IntervalWork(int interval) {
this(WORKER_TYPE, interval);
}
protected IntervalWork(Worker.Type workerType) {
switch (workerType) {
case FOREGROUND:
worker = new DirectIntervalWorker(this);
break;
default:
case BACKGROUND:
worker = new ThreadIntervalWorker(this);
break;
}
}
protected IntervalWork(Worker.Type workerType, int interval) {
switch (workerType) {
case FOREGROUND:
worker = new DirectIntervalWorker(this, interval);
break;
default:
case BACKGROUND:
worker = new ThreadIntervalWorker(this, interval);
break;
}
}
}

View File

@@ -0,0 +1,61 @@
package base.worker;
import java.util.Timer;
import java.util.TimerTask;
import base.work.Work;
public class ThreadIntervalWorker extends ThreadWorker {
protected static final int INTERVAL = 500;
protected int interval;
public ThreadIntervalWorker(Work work) {
super(work);
interval = INTERVAL;
}
public ThreadIntervalWorker(Work work, boolean thread) {
super(work, thread);
interval = INTERVAL;
}
public ThreadIntervalWorker(Work work, int interval) {
super(work);
this.interval = interval;
}
protected Timer timer;
public synchronized void start(boolean thread) {
if (!active) {
activate = true;
timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
Worker worker = ThreadIntervalWorker.this;
worker.runActivate();
worker.runDeactivate();
worker.runWork();
}}, 0, interval);
active = true;
}
if (!thread) {
try {
synchronized (this) {
wait();
}
} catch (InterruptedException e) {
logger.info("", e);
}
}
}
public synchronized void stop() {
if (active) {
timer.cancel();
deactivate = true;
run();
notifyAll();
}
}
}

View File

@@ -0,0 +1,45 @@
package base.worker;
import base.work.Work;
public class ThreadWorker extends Worker implements Runnable {
protected static final boolean THREAD = true;
protected boolean thread = true;
public ThreadWorker(Work work, boolean thread) {
this(work);
this.thread = thread;
}
public ThreadWorker(Work work) {
super(work);
}
public synchronized void start(boolean thread) {
if (!active) {
activate = true;
}
if (!run) {
run = true;
if (thread) {
logger.debug("Start thread");
new Thread(this, work.getClass().getName()).start();
} else {
logger.debug("Run directly");
run();
}
} else {
notifyAll();
}
}
public synchronized void start() {
start(thread);
}
public void exit() {
run = false;
work.stop();
}
}

View File

@@ -0,0 +1,114 @@
package base.worker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import base.exception.worker.ActivateException;
import base.exception.worker.DeactivateException;
import base.work.Work;
public abstract class Worker {
public enum Type {
DIRECT, FOREGROUND, BACKGROUND, POOLED
}
public static final int SLEEP = 100;
protected Logger logger;
protected boolean run = false;
protected boolean active = false;
protected boolean activate = false;
protected boolean deactivate = false;
protected Work work;
public Worker(Work work) {
this.work = work;
logger = LoggerFactory.getLogger(work.getClass());
}
public boolean active() {
logger.trace("Worker: active()");
return deactivate || active;
}
public final void run() {
logger.debug("Worker: run()");
while (run || deactivate) {
runActivate();
runDeactivate();
runWork();
}
}
public void runActivate() {
if (activate && !active) {
logger.trace("Worker: runActivate()");
try {
work.activate();
active = true;
} catch (ActivateException e) {
logger.error("", e);
} finally {
activate = false;
}
}
}
public void runDeactivate() {
if (deactivate && active) {
logger.trace("Worker: runDeactivate()");
try {
work.deactivate();
} catch (DeactivateException e) {
logger.error("", e);
} finally {
deactivate = false;
active = false;
}
}
}
public void runWork() {
if (active) {
logger.trace("Worker: runWork() > work");
work.work();
} else if (run) {
try {
logger.trace("Worker: runWork() > wait");
synchronized (this) {
wait();
}
} catch (InterruptedException e) {
logger.info("", e);
}
}
}
public void sleep() {
sleep(SLEEP);
}
public void sleep(int time) {
try {
if (time > 0) {
Thread.sleep(time);
}
} catch (InterruptedException e) {
logger.info("", e);
}
}
public abstract void start();
public void stop() {
logger.trace("Worker: stop()");
if (active && !activate) {
deactivate = true;
}
activate = false;
}
abstract public void exit();
}

View File

@@ -0,0 +1,5 @@
package base.worker.pool;
public interface Listener<E> {
public void add(E element);
}

View File

@@ -0,0 +1,38 @@
package base.worker.pool;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
public class ListenerPool<E> {
protected int poolSize;
protected BlockingQueue<Wrapper<E>> queue;
protected ExecutorService executorService;
public ListenerPool(int poolSize) {
this.poolSize = poolSize;
queue = new LinkedBlockingQueue<Wrapper<E>>();
executorService = Executors.newFixedThreadPool(poolSize);
}
public PooledListener<E> add(PooledListener<E> listener) {
listener.setPoolQueue(queue);
return listener;
}
public void start() {
for (int i = 0; i < poolSize; ++i) {
Runnable runnable = new ListenerPoolRunnable<E>(queue, i);
executorService.execute(runnable);
}
}
public void await() {
try {
executorService.awaitTermination(0, TimeUnit.SECONDS);
} catch (InterruptedException e) {}
}
}

View File

@@ -0,0 +1,24 @@
package base.worker.pool;
import java.util.concurrent.BlockingQueue;
class ListenerPoolRunnable<E> implements Runnable {
protected BlockingQueue<Wrapper<E>> queue;
protected int id;
public ListenerPoolRunnable(BlockingQueue<Wrapper<E>> queue, int id) {
this.queue = queue;
this.id = id;
}
public void run() {
try {
while (true) {
System.out.println("Thread #" + id + " waiting...");
Wrapper<E> wrapper = queue.take();
wrapper.deliver();
Thread.sleep((int) (Math.random() * 1000));
}
} catch (InterruptedException e) {}
}
}

View File

@@ -0,0 +1,28 @@
package base.worker.pool;
import java.util.concurrent.BlockingQueue;
import base.work.Listen;
public class PooledListener<E> extends PooledWorker implements Listener<E> {
protected BlockingQueue<Wrapper<E>> poolQueue;
protected Listen<E> listen;
public PooledListener(Listen<E> listen) {
super(listen);
this.listen = listen;
}
public void setPoolQueue(BlockingQueue<Wrapper<E>> poolQueue) {
this.poolQueue = poolQueue;
}
public synchronized void add(E element) {
Wrapper<E> wrapper = new Wrapper<E>(this, element);
poolQueue.add(wrapper);
}
void input(E element) {
listen.input(element);
}
}

View File

@@ -0,0 +1,49 @@
package base.worker.pool;
import java.util.concurrent.BlockingQueue;
import base.work.Work;
import base.worker.Worker;
public class PooledWorker extends Worker {
protected BlockingQueue<Worker> activateQueue;
protected BlockingQueue<Worker> deactivateQueue;
public PooledWorker(Work work) {
super(work);
}
public void setActivateQueue(BlockingQueue<Worker> activateQueue) {
this.activateQueue = activateQueue;
}
public void setDeactivateQueue(BlockingQueue<Worker> deactivateQueue) {
this.deactivateQueue = deactivateQueue;
}
public void start() {
if (!active) {
activate = true;
}
if (!run) {
run = true;
}
try {
deactivateQueue.remove(this);
activateQueue.put(this);
} catch (InterruptedException e) {}
}
public void stop() {
System.out.println("stop!! " + active);
if (active) {
deactivate = true;
}
activateQueue.remove(this);
deactivateQueue.add(this);
}
public void exit() {
stop();
}
}

View File

@@ -0,0 +1,42 @@
package base.worker.pool;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import base.util.ArrayCycle;
import base.worker.Worker;
public class WorkerPool {
protected int poolSize;
protected BlockingQueue<Worker> activateQueue;
protected BlockingQueue<Worker> deactivateQueue;
protected ArrayCycle<Worker> workerCycle;
protected ExecutorService executorService;
public WorkerPool(int poolSize) {
this.poolSize = poolSize;
activateQueue = new LinkedBlockingQueue<Worker>();
deactivateQueue = new LinkedBlockingQueue<Worker>();
workerCycle = new ArrayCycle<Worker>();
executorService = Executors.newFixedThreadPool(poolSize);
}
public void start() {
for (int i = 0; i < poolSize; ++i) {
Runnable runnable = new WorkerPoolRunnable(activateQueue, deactivateQueue, workerCycle, i + 1);
executorService.execute(runnable);
}
}
public void stop() {
// Must be graceful
executorService.shutdownNow();
}
public void add(PooledWorker worker) {
worker.setActivateQueue(activateQueue);
worker.setDeactivateQueue(deactivateQueue);
}
}

View File

@@ -0,0 +1,41 @@
package base.worker.pool;
import java.util.concurrent.BlockingQueue;
import base.util.ArrayCycle;
import base.worker.Worker;
public class WorkerPoolRunnable implements Runnable {
protected BlockingQueue<Worker> activateQueue;
protected BlockingQueue<Worker> deactivateQueue;
protected ArrayCycle<Worker> workerCycle;
protected int id;
public WorkerPoolRunnable(BlockingQueue<Worker> activateQueue, BlockingQueue<Worker> deactivateQueue, ArrayCycle<Worker> workerCycle, int id) {
this.activateQueue = activateQueue;
this.deactivateQueue = deactivateQueue;
this.workerCycle = workerCycle;
this.id = id;
}
public void run() {
while (true) {
if (!deactivateQueue.isEmpty()) {
try {
Worker worker = deactivateQueue.take();
worker.runDeactivate();
workerCycle.remove(worker);
} catch (InterruptedException e) {}
} else if (!activateQueue.isEmpty() || workerCycle.isEmpty()) {
try {
Worker worker = activateQueue.take();
worker.runActivate();
workerCycle.add(worker);
} catch (InterruptedException e) {}
} else {
Worker worker = workerCycle.next();
worker.runWork();
}
}
}
}

View File

@@ -0,0 +1,16 @@
package base.worker.pool;
class Wrapper<E> {
protected PooledListener<E> listener;
protected E element;
public Wrapper(PooledListener<E> listener, E element) {
this.listener = listener;
this.element = element;
}
public void deliver() {
listener.input(element);
}
}

View File

@@ -0,0 +1,17 @@
package junit;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({
TestTcpSocketCommunication.class,
TestTcpChannelCommunication.class,
TestUdpUnicastCommunication.class,
TestUdpMulticastCommunication.class,
TestUdpDuplexCommunication.class
})
public class AllTests {}
// Should test start()/stop() of components, check implementation

View File

@@ -0,0 +1,94 @@
package junit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import base.server.channel.TcpClient;
import base.server.channel.TcpServer;
import base.server.channel.TcpServerClient;
public class TestTcpChannelCommunication {
protected TestTcpServer server;
protected TestTcpClient client;
@Before
public void setUp() throws Exception {
server = new TestTcpServer(1234);
server.start();
client = new TestTcpClient(1234);
client.start();
}
@After
public void tearDown() throws Exception {
client.exit();
server.exit();
// Should add blocking stop and exit to worker
while (client.active() || server.active()) {
Thread.sleep(100);
}
}
@Test
public void testSendClientToServer() throws Exception {
String message = "test";
client.send(message.getBytes());
synchronized (server) {
server.wait(2000);
}
byte[] buffer = server.buffer;
assertNotNull("Received input", buffer);
assertEquals("Message intact", message, new String(buffer).trim());
}
@Test
public void testSendServerToClient() throws Exception {
// If client can send, connection has been established
client.send("init".getBytes());
String message = "test";
server.send(message.getBytes());
synchronized (client) {
client.wait(2000);
}
byte[] buffer = client.buffer;
assertNotNull("Received input", buffer);
assertEquals("Message intact", message, new String(buffer).trim());
}
class TestTcpServer extends TcpServer {
public byte[] buffer;
public TestTcpServer(int port) {
super(port);
}
public void input(TcpServerClient client, byte[] buffer) {
this.buffer = buffer;
synchronized (this) {
notifyAll();
}
}
}
class TestTcpClient extends TcpClient {
public byte[] buffer;
public TestTcpClient(int port) {
super(port);
}
protected void input(byte[] buffer) {
this.buffer = buffer;
synchronized (this) {
notifyAll();
}
}
}
}

View File

@@ -0,0 +1,93 @@
package junit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import base.server.socket.TcpClient;
import base.server.socket.TcpServer;
import base.server.socket.TcpServerClient;
public class TestTcpSocketCommunication {
protected TestTcpServer server;
protected TestTcpClient client;
@Before
public void setUp() throws Exception {
server = new TestTcpServer(1234);
server.start();
client = new TestTcpClient(1234);
client.start();
}
@After
public void tearDown() throws Exception {
client.exit();
server.exit();
// Should add blocking stop and exit to worker
while (client.active() || server.active()) {
Thread.sleep(100);
}
}
@Test
public void testSendClientToServer() throws Exception {
String message = "test";
client.send(message.getBytes());
synchronized (server) {
server.wait(2000);
}
byte[] buffer = server.buffer;
assertNotNull("Received input", buffer);
assertEquals("Message intact", message, new String(buffer).trim());
}
@Test
public void testSendServerToClient() throws Exception {
// If client can send, connection has been established
client.send("init".getBytes());
String message = "test";
server.send(message.getBytes());
synchronized (client) {
client.wait(2000);
}
byte[] buffer = client.buffer;
assertNotNull("Received input", buffer);
assertEquals("Message intact", message, new String(buffer).trim());
}
class TestTcpServer extends TcpServer {
public byte[] buffer;
public TestTcpServer(int port) {
super(port);
}
public void input(TcpServerClient client, byte[] buffer) {
this.buffer = buffer;
synchronized (this) {
notifyAll();
}
}
}
class TestTcpClient extends TcpClient {
public byte[] buffer;
public TestTcpClient(int port) {
super(port);
}
protected void input(byte[] buffer) {
this.buffer = buffer;
synchronized (this) {
notifyAll();
}
}
}
}

View File

@@ -0,0 +1,96 @@
package junit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.net.UnknownHostException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import base.server.datagram.UdpDuplexAutoClient;
import base.server.datagram.UdpDuplexServer;
public class TestUdpDuplexCommunication {
protected TestUdpDuplexServer server;
protected TestUdpDuplexClient client;
@Before
public void setUp() throws Exception {
server = new TestUdpDuplexServer(1234, 1235);
server.start();
client = new TestUdpDuplexClient(1234, 1235);
client.start();
}
@After
public void tearDown() throws Exception {
client.exit();
server.exit();
// Should add blocking stop and exit to worker
while (client.active() || server.active()) {
Thread.sleep(1000);
}
}
@Test
public void testServerToClientCommunication() throws Exception {
String message = "test";
server.send(message.getBytes());
System.err.println("send");
synchronized (client) {
client.wait(2000);
}
byte[] buffer = client.buffer;
assertNotNull("Received input", buffer);
assertEquals("Message intact", message, new String(buffer).trim());
}
@Test
public void testClientToServerCommunication() throws Exception {
// Let client discover server address
testServerToClientCommunication();
String message = "test";
client.send(message.getBytes());
System.err.println("send");
synchronized (server) {
server.wait(2000);
}
byte[] buffer = server.buffer;
assertNotNull("Received input", buffer);
assertEquals("Message intact", message, new String(buffer).trim());
}
public class TestUdpDuplexServer extends UdpDuplexServer {
public byte[] buffer;
public TestUdpDuplexServer(int sendPort, int bindPort) {
super(sendPort, bindPort);
}
public void input(byte[] buffer) {
this.buffer = buffer;
synchronized (this) {
notifyAll();
}
}
}
class TestUdpDuplexClient extends UdpDuplexAutoClient {
public byte[] buffer;
public TestUdpDuplexClient(int bindPort, int sendPort) throws UnknownHostException {
super(bindPort, sendPort);
}
public void input(byte[] buffer) {
this.buffer = buffer;
synchronized (this) {
notifyAll();
}
}
}
}

View File

@@ -0,0 +1,63 @@
package junit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import base.server.datagram.UdpMulticastClient;
import base.server.datagram.UdpMulticastServer;
public class TestUdpMulticastCommunication {
protected UdpMulticastServer server;
protected TestUdpMulticastClient client;
@Before
public void setUp() throws Exception {
server = new UdpMulticastServer(1234);
server.start();
client = new TestUdpMulticastClient(1234);
client.start();
}
@After
public void tearDown() throws Exception {
client.exit();
server.exit();
// Should add blocking stop and exit to worker
while (client.active() || server.active()) {
Thread.sleep(1000);
}
}
@Test
public void testServerToClientCommunication() throws Exception {
String message = "test";
server.send(message.getBytes());
System.err.println("send");
synchronized (client) {
client.wait(2000);
}
byte[] buffer = client.buffer;
assertNotNull("Received input", buffer);
assertEquals("Message intact", message, new String(buffer).trim());
}
class TestUdpMulticastClient extends UdpMulticastClient {
public byte[] buffer;
public TestUdpMulticastClient(int port) {
super(port);
}
public void input(byte[] buffer) {
this.buffer = buffer;
synchronized (this) {
notifyAll();
}
}
}
}

View File

@@ -0,0 +1,61 @@
package junit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import base.server.datagram.UdpSender;
import base.server.datagram.UdpServer;
public class TestUdpUnicastCommunication {
protected TestUdpServer server;
protected UdpSender sender;
@Before
public void setUp() throws Exception {
server = new TestUdpServer(1234);
server.start();
sender = new UdpSender(1234);
}
@After
public void tearDown() throws Exception {
server.exit();
// Should add blocking stop and exit to worker
while (server.active()) {
Thread.sleep(100);
}
}
@Test
public void testSendClientToServer() throws Exception {
String message = "test";
sender.send(message.getBytes());
synchronized (server) {
server.wait(2000);
}
byte[] buffer = server.buffer;
assertNotNull("Received input", buffer);
assertEquals("Message intact", message, new String(buffer).trim());
}
class TestUdpServer extends UdpServer {
public byte[] buffer;
public TestUdpServer(int port) {
super(port);
}
@Override
protected void input(byte[] buffer) {
this.buffer = buffer;
synchronized (this) {
notifyAll();
}
}
}
}

View File

@@ -0,0 +1,54 @@
package test;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
public class Test {
public static void main(String[] args) {
try {
new Test().start();
} catch (Throwable e) {
e.printStackTrace();
}
}
private void start() throws Throwable {
input((Object) new A());
input((Object) new B());
input((Object) new String[] {"a", "b"});
}
public void input(Object object) throws Throwable {
System.out.println("Object");
MethodType methodType = MethodType.methodType(void.class, object.getClass());
MethodHandles.Lookup lookup = MethodHandles.lookup();
MethodHandle methodHandle = lookup.findVirtual(getClass(), "input", methodType);
try {
methodHandle.invoke(this, object);
} catch (NoSuchMethodException e) {
e.printStackTrace();
System.exit(1);
}
}
public void input(A object) {
System.out.println("A");
}
public void input(B object) {
System.out.println("B");
}
public void input(String[] object) {
System.out.println("String[]");
}
public class A {
}
public class B {
}
}

View File

@@ -0,0 +1,15 @@
package worker;
import worker.dummy.DummyWork;
public class TestDirectWork {
public static void main(String[] args) {
DummyWork work = new DummyWork(1);
work.setWork(100);
work.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {}
}
}

View File

@@ -0,0 +1,18 @@
package worker;
import worker.dummy.DummyIntervalWork;
import base.work.Work;
public class TestIntervalWork {
public static void main(String[] args) {
Work work = new DummyIntervalWork(500);
for (int i = 0; i < 10; ++i) {
work.start();
System.out.println("--");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
work.stop();
}
}
}

View File

@@ -0,0 +1,19 @@
package worker;
import worker.dummy.DummyListen;
public class TestListen {
public static void main(String[] args) {
DummyListen<Integer> listen = new DummyListen<Integer>(0);
listen.start();
for (int i = 0; i < 10; ++i) {
listen.add(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
}
try {
Thread.sleep(10000);
} catch (InterruptedException e) {}
}
}

View File

@@ -0,0 +1,38 @@
package worker;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import worker.dummy.DummyListen;
import base.worker.pool.ListenerPool;
public class TestPooledListen {
protected int id;
public TestPooledListen(int id) {
this.id = id;
}
public void input(Integer element) {
System.out.println("#" + id + ": " + element);
}
public static void main(String[] args) {
ListenerPool<Integer> listenerPool = new ListenerPool<Integer>(5);
List<DummyListen<Integer>> listenList = new ArrayList<DummyListen<Integer>>();
for (int i = 0; i < 20; ++i) {
DummyListen<Integer> listen = new DummyListen<Integer>(listenerPool, i + 1);
listenList.add(listen);
}
listenerPool.start();
System.out.println("Starting to give out elements!");
for (int i = 0; i < 100; ++i) {
DummyListen<Integer> randomListen = listenList.get((new Random()).nextInt(listenList.size()));
randomListen.add(i);
}
//listenerPool.await();
}
}

View File

@@ -0,0 +1,45 @@
package worker;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import worker.dummy.DummyWork;
import base.work.Work;
import base.worker.pool.WorkerPool;
public class TestPooledWork {
public static void main(String[] args) {
WorkerPool workerPool = new WorkerPool(3);
List<DummyWork> workList = new ArrayList<DummyWork>();
for (int i = 0; i < 10; ++i) {
DummyWork work = new DummyWork(workerPool, i + 1);
workList.add(work);
}
workerPool.start();
System.out.println("Starting work!");
ArrayList<Work> activeWorkList = new ArrayList<Work>();
for (int i = 0; i < 8; ++i) {
DummyWork work = workList.get((new Random()).nextInt(workList.size()));
work.setWork(1000);
work.start();
activeWorkList.add(work);
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {}
int i = 0;
for (Work work : activeWorkList) {
if (++i > 5) {
break;
}
work.stop();
}
try {
Thread.sleep(100000);
} catch (InterruptedException e) {}
System.exit(0);
}
}

View File

@@ -0,0 +1,13 @@
package worker.dummy;
import base.worker.IntervalWork;
public class DummyIntervalWork extends IntervalWork {
public DummyIntervalWork(int interval) {
super(interval);
}
public void work() {
System.out.println(":-)");
}
}

View File

@@ -0,0 +1,26 @@
package worker.dummy;
import base.work.Listen;
import base.worker.pool.ListenerPool;
public class DummyListen<T> extends Listen<T> {
protected int id;
public DummyListen(ListenerPool<T> listenerPool, int id) {
super(listenerPool);
this.id = id;
}
public DummyListen(int id) {
super();
this.id = id;
}
public void input(Integer input) {
System.out.println("#" + id + ", input = " + input);
}
public void input(byte[] input) {
System.out.println("#" + id + ", input = " + new String(input).trim());
}
}

View File

@@ -0,0 +1,42 @@
package worker.dummy;
import base.exception.worker.ActivateException;
import base.exception.worker.DeactivateException;
import base.work.Work;
import base.worker.pool.WorkerPool;
public class DummyWork extends Work {
protected int id;
protected volatile int work;
public DummyWork(int id) {
super();
this.id = id;
}
public DummyWork(WorkerPool workerPool, int id) {
super(workerPool);
this.id = id;
}
public void setWork(int work) {
System.out.println("#" + id + ", set work @ " + work);
this.work = work;
}
public void work() {
System.out.println("#" + id + ", work = " + work);
if (--work < 1) {
stop();
}
sleep(300);
}
public void activate() throws ActivateException {
System.out.println("#" + id + ", activating...");
}
public void deactivate() throws DeactivateException {
System.out.println("#" + id + ", deactivating...");
}
}

View File

@@ -0,0 +1,4 @@
log4j.rootLogger=TRACE, CA
log4j.appender.CA=org.apache.log4j.ConsoleAppender
log4j.appender.CA.layout=org.apache.log4j.PatternLayout
log4j.appender.CA.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n