Shrink code in the ConnectionHandlers

This commit is contained in:
Andrin Fassbind 2022-04-15 16:25:45 +02:00 committed by Leonardo Brandenberger
parent 46b0e4386a
commit 5022974427
3 changed files with 105 additions and 145 deletions

View File

@ -13,20 +13,19 @@ import java.net.SocketException;
import java.util.Scanner; import java.util.Scanner;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import static ch.zhaw.pm2.multichat.protocol.ConnectionHandler.State.*; import static ch.zhaw.pm2.multichat.protocol.ConnectionHandler.State.*;
public class ClientConnectionHandler extends ConnectionHandler implements Runnable { public class ClientConnectionHandler extends ConnectionHandler implements Runnable {
private final Pattern messagePattern = Pattern.compile("^(?:@(\\S*))?\\s*(.*)$"); private final Pattern messagePattern = Pattern.compile( "^(?:@(\\S*))?\\s*(.*)$" );
private SimpleStringProperty userName; private SimpleStringProperty userName;
private final SimpleObjectProperty<State> state; private SimpleObjectProperty<State> state;
private final ClientMessageList messages; private ClientMessageList messages;
private final SimpleStringProperty serverAddress; private SimpleStringProperty serverAddress;
private final SimpleIntegerProperty serverPort; private SimpleIntegerProperty serverPort;
public ClientConnectionHandler(ClientMessageList messages) { public ClientConnectionHandler(ClientMessageList messages) {
super(); super();
this.messages = messages; this.messages = messages;
state = new SimpleObjectProperty<>(State.NEW); state = new SimpleObjectProperty<>(State.NEW);
@ -40,30 +39,24 @@ public class ClientConnectionHandler extends ConnectionHandler implements Runnab
this.serverAddress.set(serverAddress); this.serverAddress.set(serverAddress);
this.serverPort.set(serverPort); this.serverPort.set(serverPort);
setConnection(NetworkHandler.openConnection(serverAddress, serverPort)); setConnection(NetworkHandler.openConnection(serverAddress, serverPort));
this.userName = new SimpleStringProperty((userName == null || userName.isBlank()) ? USER_NONE : userName); this.userName = new SimpleStringProperty((userName == null || userName.isBlank())? USER_NONE : userName);
} }
public SimpleStringProperty getServerAddressProperty() { public SimpleStringProperty getServerAddressProperty() { return serverAddress; }
return serverAddress;
}
public SimpleIntegerProperty getServerPortProperty() { public SimpleIntegerProperty getServerPortProperty() { return serverPort; }
return serverPort;
}
public SimpleObjectProperty<State> getStateProperty() { public SimpleObjectProperty<State> getStateProperty() {
return this.state; return this.state;
} }
public SimpleStringProperty getUserNameProperty() { public SimpleStringProperty getUserNameProperty() { return userName; }
return userName;
}
public void setState(State newState) { public void setState (State newState) {
state.set(newState); state.set(newState);
} }
public void run() { public void run () {
startReceiving(); startReceiving();
} }
@ -84,9 +77,9 @@ public class ClientConnectionHandler extends ConnectionHandler implements Runnab
System.out.println("Connection terminated by remote"); System.out.println("Connection terminated by remote");
this.setState(DISCONNECTED); this.setState(DISCONNECTED);
System.err.println("Unregistered because connection terminated" + e.getMessage()); System.err.println("Unregistered because connection terminated" + e.getMessage());
} catch (IOException e) { } catch(IOException e) {
System.err.println("Communication error" + e); System.err.println("Communication error" + e);
} catch (ClassNotFoundException e) { } catch(ClassNotFoundException e) {
System.err.println("Received object of unknown type" + e.getMessage()); System.err.println("Received object of unknown type" + e.getMessage());
} }
System.out.println("Stopped Connection Handler"); System.out.println("Stopped Connection Handler");
@ -106,65 +99,48 @@ public class ClientConnectionHandler extends ConnectionHandler implements Runnab
private void processData(String data) { private void processData(String data) {
try { try {
// parse data content
Scanner scanner = new Scanner(data); Scanner scanner = new Scanner(data);
String sender = null; StringBuilder sender = new StringBuilder();
String reciever = null; StringBuilder reciever = new StringBuilder();
String type = null; StringBuilder type = new StringBuilder();
String payload = null; StringBuilder payload = new StringBuilder();
if (scanner.hasNextLine()) { super.processData(scanner,sender,reciever,type,payload);
sender = scanner.nextLine();
} else {
throw new ChatProtocolException("No Sender found");
}
if (scanner.hasNextLine()) {
reciever = scanner.nextLine();
} else {
throw new ChatProtocolException("No Reciever found");
}
if (scanner.hasNextLine()) {
type = scanner.nextLine();
} else {
throw new ChatProtocolException("No Type found");
}
if (scanner.hasNextLine()) {
payload = scanner.nextLine();
}
// dispatch operation based on type parameter // dispatch operation based on type parameter
if (type.equals(getDataTypeConnect())) { if (type.toString().equals(getDataTypeConnect())) {
System.err.println("Illegal connect request from server"); System.err.println("Illegal connect request from server");
} else if (type.equals(getDataTypeConfirm())) { } else if (type.toString().equals(getDataTypeConfirm())) {
if (state.get() == CONFIRM_CONNECT) { if (state.get() == CONFIRM_CONNECT) {
this.userName.set(reciever); this.userName.set(reciever.toString());
this.serverPort.set(getConnection().getRemotePort()); this.serverPort.set(getConnection().getRemotePort());
this.serverAddress.set(getConnection().getRemoteHost()); this.serverAddress.set(getConnection().getRemoteHost());
messages.addMessage(new Message(Message.MessageType.INFO, sender, reciever, payload)); messages.addMessage(new Message(Message.MessageType.INFO,sender.toString(),reciever.toString(),payload.toString()));
System.out.println("CONFIRM: " + payload); System.out.println("CONFIRM: " + payload);
this.setState(CONNECTED); this.setState(CONNECTED);
} else if (state.get() == CONFIRM_DISCONNECT) { } else if (state.get() == CONFIRM_DISCONNECT) {
messages.addMessage(new Message(Message.MessageType.INFO, sender, reciever, payload)); messages.addMessage(new Message(Message.MessageType.INFO,sender.toString(),reciever.toString(),payload.toString()));
System.out.println("CONFIRM: " + payload); System.out.println("CONFIRM: " + payload);
this.setState(DISCONNECTED); this.setState(DISCONNECTED);
} else { } else {
System.err.println("Got unexpected confirm message: " + payload); System.err.println("Got unexpected confirm message: " + payload);
} }
} else if (type.equals(getDataTypeDisconnect())) { } else if (type.toString().equals(getDataTypeDisconnect())) {
if (state.get() == DISCONNECTED) { if (state.get() == DISCONNECTED) {
System.out.println("DISCONNECT: Already in disconnected: " + payload); System.out.println("DISCONNECT: Already in disconnected: " + payload);
return; return;
} }
messages.addMessage(new Message(Message.MessageType.INFO, sender, reciever, payload)); messages.addMessage(new Message(Message.MessageType.INFO,sender.toString(),reciever.toString(),payload.toString()));
System.out.println("DISCONNECT: " + payload); System.out.println("DISCONNECT: " + payload);
this.setState(DISCONNECTED); this.setState(DISCONNECTED);
} else if (type.equals(getDataTypeMessage())) { } else if (type.toString().equals(getDataTypeMessage())) {
if (state.get() != CONNECTED) { if (state.get() != CONNECTED) {
System.out.println("MESSAGE: Illegal state " + state + " for message: " + payload); System.out.println("MESSAGE: Illegal state " + state + " for message: " + payload);
return; return;
} }
messages.addMessage(new Message(Message.MessageType.MESSAGE, sender, reciever, payload)); messages.addMessage(new Message(Message.MessageType.MESSAGE,sender.toString(),reciever.toString(),payload.toString()));
System.out.println("MESSAGE: From " + sender + " to " + reciever + ": " + payload); System.out.println("MESSAGE: From " + sender + " to " + reciever + ": "+ payload);
} else if (type.equals(getDataTypeError())) { } else if (type.toString().equals(getDataTypeError())) {
messages.addMessage(new Message(Message.MessageType.ERROR, sender, reciever, payload)); messages.addMessage(new Message(Message.MessageType.ERROR,sender.toString(),reciever.toString(),payload.toString()));
System.out.println("ERROR: " + payload); System.out.println("ERROR: " + payload);
} else { } else {
System.out.println("Unknown data type received: " + type); System.out.println("Unknown data type received: " + type);
@ -175,37 +151,16 @@ public class ClientConnectionHandler extends ConnectionHandler implements Runnab
} }
} }
private void sendData(String sender, String receiver, String type, String payload) {
if (getConnection().isAvailable()) {
new StringBuilder();
String data = new StringBuilder()
.append(sender + "\n")
.append(receiver + "\n")
.append(type + "\n")
.append(payload + "\n")
.toString();
try {
getConnection().send(data);
} catch (SocketException e) {
System.err.println("Connection closed: " + e.getMessage());
} catch (EOFException e) {
System.out.println("Connection terminated by remote");
} catch (IOException e) {
System.err.println("Communication error: " + e.getMessage());
}
}
}
public void connect() throws ChatProtocolException { public void connect() throws ChatProtocolException {
if (state.get() != NEW) throw new ChatProtocolException("Illegal state for connect: " + state); if (state.get() != NEW) throw new ChatProtocolException("Illegal state for connect: " + state);
this.sendData(userName.get(), USER_NONE, getDataTypeConnect(), null); this.sendData(userName.get(), USER_NONE, getDataTypeConnect(),null);
this.setState(CONFIRM_CONNECT); this.setState(CONFIRM_CONNECT);
} }
public void disconnect() throws ChatProtocolException { public void disconnect() throws ChatProtocolException {
if (state.get() != NEW && state.get() != CONNECTED) if (state.get() != NEW && state.get() != CONNECTED) throw new ChatProtocolException("Illegal state for disconnect: " + state);
throw new ChatProtocolException("Illegal state for disconnect: " + state); this.sendData(userName.get(), USER_NONE, getDataTypeDisconnect(),null);
this.sendData(userName.get(), USER_NONE, getDataTypeDisconnect(), null);
this.setState(CONFIRM_DISCONNECT); this.setState(CONFIRM_DISCONNECT);
} }
@ -216,15 +171,14 @@ public class ClientConnectionHandler extends ConnectionHandler implements Runnab
if (matcher.find()) { if (matcher.find()) {
String receiver = matcher.group(1); String receiver = matcher.group(1);
String message = matcher.group(2); String message = matcher.group(2);
if (message.length() < 1) { if(message.length() < 1){
return false; return false;
} }
if (receiver == null || receiver.isBlank()) receiver = ClientConnectionHandler.USER_ALL; if (receiver == null || receiver.isBlank()) receiver = ClientConnectionHandler.USER_ALL;
this.sendData(userName.get(), receiver, getDataTypeMessage(), message); this.sendData(userName.get(), receiver, getDataTypeMessage(),message);
return true; return true;
} else { } else {
return false; return false;
} }
} }
} }

View File

@ -1,5 +1,10 @@
package ch.zhaw.pm2.multichat.protocol; package ch.zhaw.pm2.multichat.protocol;
import java.io.EOFException;
import java.io.IOException;
import java.net.SocketException;
import java.util.Scanner;
public abstract class ConnectionHandler { public abstract class ConnectionHandler {
private NetworkHandler.NetworkConnection<String> connection; private NetworkHandler.NetworkConnection<String> connection;
@ -44,4 +49,47 @@ public abstract class ConnectionHandler {
protected void setConnection(NetworkHandler.NetworkConnection<String> connection) { protected void setConnection(NetworkHandler.NetworkConnection<String> connection) {
this.connection = connection; this.connection = connection;
} }
protected void processData(Scanner scanner, StringBuilder sender, StringBuilder reciever, StringBuilder type, StringBuilder payload) throws ChatProtocolException {
// parse data content
if (scanner.hasNextLine()) {
sender.append(scanner.nextLine());
} else {
throw new ChatProtocolException("No Sender found");
}
if (scanner.hasNextLine()) {
reciever.append(scanner.nextLine());
} else {
throw new ChatProtocolException("No Reciever found");
}
if (scanner.hasNextLine()) {
type.append(scanner.nextLine());
} else {
throw new ChatProtocolException("No Type found");
}
if (scanner.hasNextLine()) {
payload.append(scanner.nextLine());
}
}
protected void sendData(String sender, String receiver, String type, String payload) {
if (connection.isAvailable()) {
new StringBuilder();
String data = new StringBuilder()
.append(sender+"\n")
.append(receiver+"\n")
.append(type+"\n")
.append(payload+"\n")
.toString();
try {
getConnection().send(data);
} catch (SocketException e) {
System.err.println("Connection closed: " + e.getMessage());
} catch (EOFException e) {
System.out.println("Connection terminated by remote");
} catch(IOException e) {
System.err.println("Communication error: " + e.getMessage());
}
}
}
} }

View File

@ -8,7 +8,6 @@ import ch.zhaw.pm2.multichat.protocol.NetworkHandler;
import java.io.EOFException; import java.io.EOFException;
import java.io.IOException; import java.io.IOException;
import java.net.SocketException; import java.net.SocketException;
import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.Scanner; import java.util.Scanner;
@ -91,43 +90,25 @@ public class ServerConnectionHandler extends ConnectionHandler implements Runnab
getConnection().close(); getConnection().close();
System.out.println("Stopped receiving data."); System.out.println("Stopped receiving data.");
} catch (IOException e) { } catch (IOException e) {
System.err.println("Failed to close connection." + e); System.err.println("Failed to close connection." + e.getMessage());
} }
System.out.println("Closed Connection Handler for " + userName); System.out.println("Closed Connection Handler for " + userName);
} }
private void processData(String data) { private void processData(String data) {
try { try {
// parse data content
Scanner scanner = new Scanner(data); Scanner scanner = new Scanner(data);
String sender = null; StringBuilder sender = new StringBuilder();
String reciever = null; StringBuilder reciever = new StringBuilder();
String type = null; StringBuilder type = new StringBuilder();
String payload = null; StringBuilder payload = new StringBuilder();
if (scanner.hasNextLine()) { super.processData(scanner,sender,reciever,type,payload);
sender = scanner.nextLine();
} else {
throw new ChatProtocolException("No Sender found");
}
if (scanner.hasNextLine()) {
reciever = scanner.nextLine();
} else {
throw new ChatProtocolException("No Reciever found");
}
if (scanner.hasNextLine()) {
type = scanner.nextLine();
} else {
throw new ChatProtocolException("No Type found");
}
if (scanner.hasNextLine()) {
payload = scanner.nextLine();
}
// dispatch operation based on type parameter // dispatch operation based on type parameter
if (type.equals(getDataTypeConnect())) { if (type.toString().equals(getDataTypeConnect())) {
if (this.state != NEW) throw new ChatProtocolException("Illegal state for connect request: " + state); if (this.state != NEW) throw new ChatProtocolException("Illegal state for connect request: " + state);
if (sender == null || sender.isBlank()) sender = this.userName; if (sender.toString().isBlank()) sender.append(this.userName);
if (connectionRegistry.containsKey(sender)) { if (connectionRegistry.containsKey(sender.toString())) {
mutex.lock(); mutex.lock();
try { try {
state = ERROR; state = ERROR;
@ -140,7 +121,7 @@ public class ServerConnectionHandler extends ConnectionHandler implements Runnab
} }
mutex.lock(); mutex.lock();
try { try {
this.userName = sender; this.userName = sender.toString();
nameComplete.signal(); nameComplete.signal();
} }
finally { finally {
@ -149,9 +130,9 @@ public class ServerConnectionHandler extends ConnectionHandler implements Runnab
connectionRegistry.put(userName, this); connectionRegistry.put(userName, this);
sendData(USER_NONE, userName, getDataTypeConfirm(), "Registration successfull for " + userName); sendData(USER_NONE, userName, getDataTypeConfirm(), "Registration successfull for " + userName);
this.state = CONNECTED; this.state = CONNECTED;
} else if (type.equals(getDataTypeConfirm())) { } else if (type.toString().equals(getDataTypeConfirm())) {
System.out.println("Not expecting to receive a CONFIRM request from client"); System.out.println("Not expecting to receive a CONFIRM request from client");
} else if (type.equals(getDataTypeDisconnect())) { } else if (type.toString().equals(getDataTypeDisconnect())) {
if (state == DISCONNECTED) if (state == DISCONNECTED)
throw new ChatProtocolException("Illegal state for disconnect request: " + state); throw new ChatProtocolException("Illegal state for disconnect request: " + state);
if (state == CONNECTED) { if (state == CONNECTED) {
@ -160,24 +141,24 @@ public class ServerConnectionHandler extends ConnectionHandler implements Runnab
sendData(USER_NONE, userName, getDataTypeConfirm(), "Confirm disconnect of " + userName); sendData(USER_NONE, userName, getDataTypeConfirm(), "Confirm disconnect of " + userName);
this.state = DISCONNECTED; this.state = DISCONNECTED;
this.stopReceiving(); this.stopReceiving();
} else if (type.equals(getDataTypeMessage())) { } else if (type.toString().equals(getDataTypeMessage())) {
if (state != CONNECTED) throw new ChatProtocolException("Illegal state for message request: " + state); if (state != CONNECTED) throw new ChatProtocolException("Illegal state for message request: " + state);
if (USER_ALL.equals(reciever)) { if (USER_ALL.equals(reciever.toString())) {
for (ServerConnectionHandler handler : connectionRegistry.values()) { for (ServerConnectionHandler handler : connectionRegistry.values()) {
handler.sendData(sender, reciever, type, payload); handler.sendData(sender.toString(), reciever.toString(), type.toString(), payload.toString());
} }
} else { } else {
ServerConnectionHandler handler = connectionRegistry.get(reciever); ServerConnectionHandler handler = connectionRegistry.get(reciever.toString());
if (handler != null) { if (handler != null) {
handler.sendData(sender, reciever, type, payload); handler.sendData(sender.toString(), reciever.toString(), type.toString(), payload.toString());
if(!reciever.equals(sender)){ if(!reciever.toString().equals(sender.toString())){
sendData(sender, reciever, type, payload); //send message to sender if it's a direct message and sender is not receiver. sendData(sender.toString(), reciever.toString(), type.toString(), payload.toString()); //send message to sender if it's a direct message and sender is not receiver.
} }
} else { } else {
this.sendData(USER_NONE, userName, getDataTypeError(), "Unknown User: " + reciever); this.sendData(USER_NONE, userName, getDataTypeError(), "Unknown User: " + reciever);
} }
} }
} else if (type.equals(getDataTypeError())) { } else if (type.toString().equals(getDataTypeError())) {
System.err.println("Received error from client (" + sender + "): " + payload); System.err.println("Received error from client (" + sender + "): " + payload);
} else { } else {
System.err.println("Unknown data type received: " + type); System.err.println("Unknown data type received: " + type);
@ -188,27 +169,4 @@ public class ServerConnectionHandler extends ConnectionHandler implements Runnab
sendData(USER_NONE, userName, getDataTypeError(), e.getMessage()); sendData(USER_NONE, userName, getDataTypeError(), e.getMessage());
} }
} }
private void sendData(String sender, String receiver, String type, String payload) {
if (getConnection().isAvailable()) {
new StringBuilder();
String data = new StringBuilder()
.append(sender+"\n")
.append(receiver+"\n")
.append(type+"\n")
.append(payload+"\n")
.toString();
try {
getConnection().send(data);
} catch (SocketException e) {
System.out.println("Connection closed: " + e.getMessage());
} catch (EOFException e) {
System.out.println("Connection terminated by remote");
} catch(IOException e) {
System.out.println("Communication error: " + e.getMessage());
}
}
}
} }