Create ConnectionHandlerClass

Remove Codeduplication
This commit is contained in:
Andrin Fassbind
2022-04-14 21:11:58 +02:00
parent af46e499ff
commit 5e6e9d5817
4 changed files with 94 additions and 73 deletions
@@ -1,6 +1,7 @@
package ch.zhaw.pm2.multichat.server;
import ch.zhaw.pm2.multichat.protocol.ChatProtocolException;
import ch.zhaw.pm2.multichat.protocol.ConnectionHandler;
import ch.zhaw.pm2.multichat.protocol.NetworkHandler;
import java.io.EOFException;
@@ -16,22 +17,11 @@ import java.util.concurrent.locks.ReentrantLock;
import static ch.zhaw.pm2.multichat.server.ServerConnectionHandler.State.*;
public class ServerConnectionHandler implements Runnable{
public class ServerConnectionHandler extends ConnectionHandler implements Runnable{
private static final AtomicInteger connectionCounter = new AtomicInteger(0);
private final int connectionId = connectionCounter.incrementAndGet();
private final NetworkHandler.NetworkConnection<String> connection;
private final Map<String,ServerConnectionHandler> connectionRegistry;
// Data types used for the Chat Protocol
private static final String DATA_TYPE_CONNECT = "CONNECT";
private static final String DATA_TYPE_CONFIRM = "CONFIRM";
private static final String DATA_TYPE_DISCONNECT = "DISCONNECT";
private static final String DATA_TYPE_MESSAGE = "MESSAGE";
private static final String DATA_TYPE_ERROR = "ERROR";
private static final String USER_NONE = "";
private static final String USER_ALL = "*";
private ReentrantLock mutex;
private Condition nameComplete;
@@ -50,9 +40,9 @@ public class ServerConnectionHandler implements Runnable{
public ServerConnectionHandler(NetworkHandler.NetworkConnection<String> connection,
Map<String,ServerConnectionHandler> registry, ReentrantLock mutex, Condition nameComplete) {
super(connection);
Objects.requireNonNull(connection, "Connection must not be null");
Objects.requireNonNull(registry, "Registry must not be null");
this.connection = connection;
this.connectionRegistry = registry;
this.mutex = mutex;
this.nameComplete = nameComplete;
@@ -62,12 +52,12 @@ public class ServerConnectionHandler implements Runnable{
return this.userName;
}
public void startReceiving() {
private void startReceiving() {
System.out.println("Starting Connection Handler for new User");
try {
System.out.println("Start receiving data...");
while (connection.isAvailable()) {
String data = connection.receive();
while (getConnection().isAvailable()) {
String data = getConnection().receive();
processData(data);
}
System.out.println("Stopped recieving data");
@@ -88,11 +78,11 @@ public class ServerConnectionHandler implements Runnable{
}
public void stopReceiving() {
private void stopReceiving() {
System.out.println("Closing Connection Handler for " + userName);
try {
System.out.println("Stop receiving data...");
connection.close();
getConnection().close();
System.out.println("Stopped receiving data.");
} catch (IOException e) {
System.err.println("Failed to close connection." + e);
@@ -128,7 +118,7 @@ public class ServerConnectionHandler implements Runnable{
}
// dispatch operation based on type parameter
if (type.equals(DATA_TYPE_CONNECT)) {
if (type.equals(getDataTypeConnect())) {
if (this.state != NEW) throw new ChatProtocolException("Illegal state for connect request: " + state);
if (sender == null || sender.isBlank()) sender = this.userName;
if (connectionRegistry.containsKey(sender))
@@ -142,20 +132,20 @@ public class ServerConnectionHandler implements Runnable{
mutex.unlock();
}
connectionRegistry.put(userName, this);
sendData(USER_NONE, userName, DATA_TYPE_CONFIRM, "Registration successfull for " + userName);
sendData(USER_NONE, userName, getDataTypeConfirm(), "Registration successfull for " + userName);
this.state = CONNECTED;
} else if (type.equals(DATA_TYPE_CONFIRM)) {
} else if (type.equals(getDataTypeConfirm())) {
System.out.println("Not expecting to receive a CONFIRM request from client");
} else if (type.equals(DATA_TYPE_DISCONNECT)) {
} else if (type.equals(getDataTypeDisconnect())) {
if (state == DISCONNECTED)
throw new ChatProtocolException("Illegal state for disconnect request: " + state);
if (state == CONNECTED) {
connectionRegistry.remove(this.userName);
}
sendData(USER_NONE, userName, DATA_TYPE_CONFIRM, "Confirm disconnect of " + userName);
sendData(USER_NONE, userName, getDataTypeConfirm(), "Confirm disconnect of " + userName);
this.state = DISCONNECTED;
this.stopReceiving();
} else if (type.equals(DATA_TYPE_MESSAGE)) {
} else if (type.equals(getDataTypeMessage())) {
if (state != CONNECTED) throw new ChatProtocolException("Illegal state for message request: " + state);
if (USER_ALL.equals(reciever)) {
for (ServerConnectionHandler handler : connectionRegistry.values()) {
@@ -169,10 +159,10 @@ public class ServerConnectionHandler implements Runnable{
sendData(sender, reciever, type, payload); //send message to sender if it's a direct message and sender is not receiver.
}
} else {
this.sendData(USER_NONE, userName, DATA_TYPE_ERROR, "Unknown User: " + reciever);
this.sendData(USER_NONE, userName, getDataTypeError(), "Unknown User: " + reciever);
}
}
} else if (type.equals(DATA_TYPE_ERROR)) {
} else if (type.equals(getDataTypeError())) {
System.err.println("Received error from client (" + sender + "): " + payload);
} else {
System.err.println("Unknown data type received: " + type);
@@ -180,12 +170,12 @@ public class ServerConnectionHandler implements Runnable{
}
} catch(ChatProtocolException e) {
System.out.println("Error while processing data" + e.getMessage());
sendData(USER_NONE, userName, DATA_TYPE_ERROR, e.getMessage());
sendData(USER_NONE, userName, getDataTypeError(), e.getMessage());
}
}
public void sendData(String sender, String receiver, String type, String payload) {
if (connection.isAvailable()) {
private void sendData(String sender, String receiver, String type, String payload) {
if (getConnection().isAvailable()) {
new StringBuilder();
String data = new StringBuilder()
.append(sender+"\n")
@@ -194,7 +184,7 @@ public class ServerConnectionHandler implements Runnable{
.append(payload+"\n")
.toString();
try {
connection.send(data);
getConnection().send(data);
} catch (SocketException e) {
System.out.println("Connection closed: " + e.getMessage());
} catch (EOFException e) {