Compare commits

..
Author SHA1 Message Date
Andrin Fassbind ad13445978 Start refactoring ClientConnectionHandler.java
ERROR UnsupportedOperationException in ClientMessageList
2022-04-12 21:11:35 +02:00
Andrin Fassbind 88d4493cfb Merge branch 'main' into State_Sync
# Conflicts:
#	client/src/main/java/ch/zhaw/pm2/multichat/client/ChatWindowController.java
#	client/src/main/java/ch/zhaw/pm2/multichat/client/ClientConnectionHandler.java
#	client/src/main/java/ch/zhaw/pm2/multichat/client/ClientMessageList.java
2022-04-12 19:29:11 +02:00
Andrin Fassbind f2fb32bbd4 Start refactoring ClientConnectionHandler.java 2022-04-12 19:22:13 +02:00
Andrin Fassbind f2945b3075 Make State SimpleObjectProperty in ClientConnectionHandler.java
Add changelistener to stateproperty in ChatWindowController.java

fixes Issue #21
2022-04-12 17:44:49 +02:00
11 changed files with 509 additions and 905 deletions
File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 133 KiB

@@ -1,10 +1,12 @@
package ch.zhaw.pm2.multichat.client;
import ch.zhaw.pm2.multichat.protocol.ConnectionHandler.State;
import ch.zhaw.pm2.multichat.client.ClientConnectionHandler.State;
import ch.zhaw.pm2.multichat.protocol.ChatProtocolException;
import ch.zhaw.pm2.multichat.protocol.NetworkHandler;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ListChangeListener;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
@@ -14,188 +16,178 @@ import javafx.scene.layout.Pane;
import javafx.stage.WindowEvent;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static ch.zhaw.pm2.multichat.protocol.ConnectionHandler.State.*;
import static ch.zhaw.pm2.multichat.client.ClientConnectionHandler.State.*;
/**
* Class Representing the Controller Element of the Window, also Contains the Elements that contacts the View Elements via
* Listeners and Observable Objects.
* To Contact the Model Elements needed it also holds references to message and the Connectionhandler.
*/
public class ChatWindowController {
private ClientConnectionHandler connectionHandler;
private ClientMessageList messages;
private final WindowCloseHandler windowCloseHandler = new WindowCloseHandler();
@FXML
private Pane rootPane;
@FXML
private TextField serverAddressField;
@FXML
private TextField serverPortField;
@FXML
private TextField userNameField;
@FXML
private TextField messageField;
@FXML
private TextArea messageArea;
@FXML
private Button connectButton;
@FXML
private TextField filterValue;
@FXML
private Button sendButton;
@FXML private Pane rootPane;
@FXML private TextField serverAddressField;
@FXML private TextField serverPortField;
@FXML private TextField userNameField;
@FXML private TextField messageField;
@FXML private TextArea messageArea;
@FXML private Button connectButton;
@FXML private Button sendButton;
@FXML private TextField filterValue;
/**
* Takes a message object and stores it used as Model and also starts message Listener via messageListener method.
*
* @param messages Object that will be set for use as Model
*/
public void setMessages(ClientMessageList messages) {
this.messages = messages;
messageListener();
@FXML
public void initialize() {
serverAddressField.setText(NetworkHandler.DEFAULT_ADDRESS.getCanonicalHostName());
serverPortField.setText(String.valueOf(NetworkHandler.DEFAULT_PORT));
this.messages = new ClientMessageList();
messages.getChangedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
setMessageField(messages.getMessages());
}
});
}
/**
* Takes a Connection handler object and stores it used as Model and also starts a Listener for it.
*
* @param connectionHandler that will be set and used as Model.
*/
public void setConnectionHandler(ClientConnectionHandler connectionHandler) {
this.connectionHandler = connectionHandler;
startConnectionHandlerListener();
serverAddressField.setText(connectionHandler.getServerAddressProperty().get());
serverPortField.setText(String.valueOf(connectionHandler.getServerPortProperty().get()));
refreshConnectionState(connectionHandler.getStateProperty().get());
}
/**
* Method which closes the Application via use of the disconnect Method.
*/
private void applicationClose() {
disconnect();
connectionHandler.setState(DISCONNECTED);
}
/**
* Method that handles the Connect Button and Initiates connect when connectionHandler is not Connected or
* a disconnect when it is connected.
*/
@FXML
private void toggleConnection () {
if (connectionHandler == null || connectionHandler.getStateProperty().get() != CONNECTED) {
if (connectionHandler == null || connectionHandler.getStateObjectProperty().get() != CONNECTED) {
connect();
} else {
disconnect();
}
}
/**
* Initiates a connection by starting Connection Handler and telling, the Handler to start a connection.
*/
private void connect() {
try {
messages.clear(); // clear message list
startConnectionHandler();
connectionHandler.connect();
} catch(ChatProtocolException | IOException e) {
addError("Error while starting Connection Handler and connect" + e);
messages.addMessage(null,null, e.getMessage(), Message.MessageType.ERROR);
}
}
/**
* Initiates disconnecting of the connectionHandler, also checks if connectionHandler is available.
*/
private void disconnect() {
if (connectionHandler == null) {
addError("No connection handler");
messages.addMessage(null,null,"No connection handler", Message.MessageType.ERROR);
return;
}
try {
connectionHandler.disconnect();
} catch (ChatProtocolException e) {
addError(e.getMessage());
messages.addMessage(null,null, e.getMessage(), Message.MessageType.ERROR);
}
}
/**
* Method which is used when the send button is pressed and handing over a message to the Connection Handler
*/
@FXML
private void message() {
String messageString = messageField.getText().strip();
try {
if (connectionHandler == null) {
addError("No connection handler");
messages.addMessage(null,null,"No connection handler", Message.MessageType.ERROR);
} else if (!connectionHandler.message(messageString)) {
addError("Not a valid message format.");
messages.addMessage(null,null,"Not a valid message format.", Message.MessageType.ERROR);
} else {
messageField.clear();
}
} catch (ChatProtocolException e) {
addError(e.getMessage());
messages.addMessage(null,null, e.getMessage(), Message.MessageType.ERROR);
}
}
/**
* Method which is used when a Filter is applied
* Setting the Text in the message area after sending it through the filter.
*/
//TODO: TEST
@FXML
private void applyFilter( ) {
Platform.runLater(() -> this.messageArea.setText(messages.getFilteredMessages(filterValue.getText().strip())));
messages.getFilteredMessages(filterValue.getText().strip());
}
/**
* Starts the ConnectionHandler setting the username and Checking if the name follows the valid format of no spaces.
*
* @throws IOException for error that may occur during initialization of connectionHandler.
*/
private void startConnectionHandler() throws IOException {
String userName = userNameField.getText();
if (!userName.contains(" ")) {
String serverAddress = serverAddressField.getText();
int serverPort = Integer.parseInt(serverPortField.getText());
connectionHandler.initialize(serverAddress, serverPort, userName);
connectionHandler = new ClientConnectionHandler(messages,serverAddress,serverPort,userName);
new Thread(connectionHandler).start();
//register changelistener
startChangeListener();
// register window close handler
rootPane.getScene().getWindow().addEventHandler(WindowEvent.WINDOW_CLOSE_REQUEST, windowCloseHandler);
} else {
addError("It is not allowed to have spaces in username!");
}
private void terminateConnectionHandler() {
// unregister window close handler
rootPane.getScene().getWindow().removeEventHandler(WindowEvent.WINDOW_CLOSE_REQUEST, windowCloseHandler);
if (connectionHandler != null) {
connectionHandler.stopReceiving();
connectionHandler = null;
}
}
/**
* Sets the state shown according to the state the method receives, if state indicates disconnected it will also inform the
* Connection Handler and tell it to stop Receiving more messages.
*
* @param newState is the state that it should be set to.
*/
public void refreshConnectionState(State newState) {
public void stateChanged(State newState) {
// update UI (need to be run in UI thread: see Platform.runLater())
Platform.runLater(new Runnable() {
@Override
public void run() {
if(newState == CONNECTED || newState == CONFIRM_DISCONNECT){
connectButton.setText("Disconnect");
messageField.setDisable(false);
sendButton.setDisable(false);
} else {
connectButton.setText("Connect");
messageField.setDisable(true);
sendButton.setDisable(true);
}
connectButton.setText((newState == CONNECTED || newState == CONFIRM_DISCONNECT) ? "Disconnect" : "Connect");
}
});
if (newState == DISCONNECTED) {
connectionHandler.stopReceiving();
terminateConnectionHandler();
}
}
/**
* Sets displayed username according to the String provided.
*
* @param userName provided String that is set as name.
*/
private void startChangeListener() {
//Listener for State
connectionHandler.getStateObjectProperty().addListener(new ChangeListener<State>() {
@Override
public void changed(ObservableValue<? extends State> observable, State oldValue, State newValue) {
stateChanged(newValue);
}
});
//Listener for Username
connectionHandler.getUserNameProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
setUserName(newValue);
}
});
//Listener for Address
connectionHandler.getServerAddressProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
setServerAddress(newValue);
}
});
//Listener for Port
connectionHandler.getServerPortProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
setServerPort(newValue.intValue());
}
});
}
public void setMessageField(String message) {
Platform.runLater(new Runnable() {
@Override
public void run() {
messageField.setText(message);
}
});
}
public void setUserName(String userName) {
Platform.runLater(new Runnable() {
@Override
@@ -205,11 +197,6 @@ public class ChatWindowController {
});
}
/**
* Sets displayed Server Address.
*
* @param serverAddress provided String that is set as server address.
*/
public void setServerAddress(String serverAddress) {
Platform.runLater(new Runnable() {
@Override
@@ -219,11 +206,6 @@ public class ChatWindowController {
});
}
/**
* Sets displayed Server port.
*
* @param serverPort provided String that is set as server port.
*/
public void setServerPort(int serverPort) {
Platform.runLater(new Runnable() {
@Override
@@ -233,72 +215,17 @@ public class ChatWindowController {
});
}
/**
* Method which adds an incoming String as an Error Message.
*
* @param message String to be added as Error
*/
public void addError(String message) {
messages.addMessage(new Message(Message.MessageType.ERROR, null, null, message));
//TODO: MAKE ChangeListener
private void redrawMessageList() {
this.messageArea.clear();
Platform.runLater(() -> this.messageArea.setText(messages.getFilteredMessages(filterValue.getText().strip())));
}
/**
* Nested Class in charge of Closing the window
*/
class WindowCloseHandler implements EventHandler<WindowEvent> {
/**
*
* @param event the event which occurred when Windows is closed
*/
public void handle(WindowEvent event) {
applicationClose();
}
}
/**
* Starts several new Listener for Connection Handler changes by using several observable properties.
*/
public void startConnectionHandlerListener() {
connectionHandler.getStateProperty().addListener(new ChangeListener<State>() {
@Override
public void changed(ObservableValue<? extends State> observable, State oldValue, State newValue) {
refreshConnectionState(newValue);
}
});
connectionHandler.getUserNameProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
setUserName(newValue);
}
});
connectionHandler.getServerAddressProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
setServerAddress(newValue);
}
});
connectionHandler.getServerPortProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
setServerPort(newValue.intValue());
}
});
}
/**
* Starts a new Listener for messages by using the observable Boolean.
*/
private void messageListener() {
messages.getChangedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
Platform.runLater(() -> messageArea.setText(messages.getFilteredMessages(filterValue.getText().strip())));
}
});
}
}
@@ -2,16 +2,8 @@ package ch.zhaw.pm2.multichat.client;
import javafx.application.Application;
/**
* Client Main Class in charge of starting the UI only contains main method.
*/
public class Client {
/**
* Main method which launches the Client UI
*
* @param args no arguments needed
*/
public static void main(String[] args) {
// Start UI
System.out.println("Starting Client Application");
@@ -1,8 +1,8 @@
package ch.zhaw.pm2.multichat.client;
import ch.zhaw.pm2.multichat.protocol.ChatProtocolException;
import ch.zhaw.pm2.multichat.protocol.ConnectionHandler;
import ch.zhaw.pm2.multichat.protocol.NetworkHandler;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
@@ -14,118 +14,75 @@ import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static ch.zhaw.pm2.multichat.protocol.ConnectionHandler.State.*;
import static ch.zhaw.pm2.multichat.client.ClientConnectionHandler.State.*;
import static ch.zhaw.pm2.multichat.client.Message.MessageType.*;
/**
* Client Connection Handler Class is used for the connection of the Client to a server
* it is used part as a Model storing properties like userName, state, serverAddress and Port.
* Also holds methods to
*/
public class ClientConnectionHandler extends ConnectionHandler implements Runnable {
public class ClientConnectionHandler implements Runnable {
private NetworkHandler.NetworkConnection<String> connection;
private final Pattern messagePattern = Pattern.compile("^(?:@(\\S*))?\\s*(.*)$");
// 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 final SimpleStringProperty userName;
private final SimpleObjectProperty<State> state;
private final ClientMessageList messages;
private final SimpleStringProperty serverAddress;
private final SimpleIntegerProperty serverPort;
public static final String USER_NONE = "";
public static final String USER_ALL = "*";
/**
* Constructor initializes ConnectionHandler by Setting default values for the fields and stores the given messages itself.
*
* @param messages
*/
public ClientConnectionHandler(ClientMessageList messages) {
super();
this.messages = messages;
state = new SimpleObjectProperty<>(State.NEW);
serverAddress = new SimpleStringProperty(NetworkHandler.DEFAULT_ADDRESS.getCanonicalHostName());
serverPort = new SimpleIntegerProperty(NetworkHandler.DEFAULT_PORT);
this.userName = new SimpleStringProperty(null);
private SimpleStringProperty userName;
private SimpleIntegerProperty serverPort;
private SimpleStringProperty serverAddress;
private ObjectProperty<State> stateObjectProperty;
private ClientMessageList messageList;
private final Pattern messagePattern = Pattern.compile( "^(?:@(\\w*))?\\s*(.*)$" );
enum State {
NEW, CONFIRM_CONNECT, CONNECTED, CONFIRM_DISCONNECT, DISCONNECTED;
}
/**
* Called to initialize the ClientConnectionHandler when trying to start a connection
*
* @param serverAddress to connect to
* @param serverPort to connect to
* @param userName to connect as
* @throws IOException if connection to Server not possible
*/
public void initialize(String serverAddress, int serverPort, String userName) throws IOException {
state.set(NEW);
this.serverAddress.set(serverAddress);
this.serverPort.set(serverPort);
setConnection(NetworkHandler.openConnection(serverAddress, serverPort));
this.userName.set((userName == null || userName.isBlank()) ? USER_NONE : userName);
public ClientConnectionHandler(ClientMessageList messageList,String serverAddress,int serverPort,String userName) throws IOException {
this.stateObjectProperty = new SimpleObjectProperty<>(NEW);
this.userName = new SimpleStringProperty((userName == null || userName.isBlank())? USER_NONE : userName);
this.serverPort = new SimpleIntegerProperty();
this.serverAddress = new SimpleStringProperty();
this.messageList = messageList;
this.connection = NetworkHandler.openConnection(serverAddress,serverPort);
}
/**
* Observable getter Method for the stored serverAddress
*
* @return the stored serverAddress
*/
public SimpleStringProperty getServerAddressProperty() {
return serverAddress;
public ObjectProperty<State> getStateObjectProperty() {
return stateObjectProperty;
}
/**
* Observable getter Method for the stored serverPort
*
* @return the stored serverPort
*/
public SimpleIntegerProperty getServerPortProperty() {
return serverPort;
}
/**
* Observable getter Method for the stored state
*
* @return the stored state
*/
public SimpleObjectProperty<State> getStateProperty() {
return this.state;
}
/**
* Observable getter Method for the stored userName
*
* @return the stored userName
*/
public SimpleStringProperty getUserNameProperty() {
return userName;
}
/**
* Method which sets a new State.
*
* @param newState the state that will be set
*/
public SimpleStringProperty getServerAddressProperty() {
return serverAddress;
}
public SimpleIntegerProperty getServerPortProperty() {
return serverPort;
}
public void setState (State newState) {
state.set(newState);
this.stateObjectProperty.set(newState);
}
/**
* Standard run method which will directly start the startReceiving method.
*/
public void run () {
startReceiving();
}
/**
* Method that is started by the run method, starts a connection handler.
* Figures out if connection is available if not determines the error cause and gives an error accordingly.
*/
private void startReceiving() {
public void startReceiving() {
System.out.println("Starting Connection Handler");
try {
System.out.println("Start receiving data...");
while (getConnection().isAvailable()) {
String data = getConnection().receive();
while (connection.isAvailable()) {
String data = connection.receive();
processData(data);
}
System.out.println("Stopped receiving data");
System.out.println("Stopped recieving data");
} catch (SocketException e) {
System.out.println("Connection terminated locally");
this.setState(DISCONNECTED);
@@ -142,14 +99,11 @@ public class ClientConnectionHandler extends ConnectionHandler implements Runnab
System.out.println("Stopped Connection Handler");
}
/**
* Method which is used to stop receiving data, gets the current connection and closes it.
*/
public void stopReceiving() {
System.out.println("Closing Connection Handler to Server");
try {
System.out.println("Stop receiving data...");
getConnection().close();
connection.close();
System.out.println("Stopped receiving data.");
} catch (IOException e) {
System.err.println("Failed to close connection." + e.getMessage());
@@ -157,134 +111,113 @@ public class ClientConnectionHandler extends ConnectionHandler implements Runnab
System.out.println("Closed Connection Handler to Server");
}
/**
* Method which processes data and determines its type then uses the corresponding method to process it.
*
* @param data that is received in a form of a String and then used depending on its determined cause.
*/
private void processData(String data) {
try {
// parse data content
Scanner scanner = new Scanner(data);
StringBuilder sender = new StringBuilder();
StringBuilder receiver = new StringBuilder();
StringBuilder type = new StringBuilder();
StringBuilder payload = new StringBuilder();
super.processData(scanner, sender, receiver, type, payload);
// dispatch operation based on type parameter
if (type.toString().equals(getDataTypeConnect())) {
System.err.println("Illegal connect request from server");
} else if (type.toString().equals(getDataTypeConfirm())) {
caseConfirm(sender.toString(), receiver.toString(), payload.toString());
} else if (type.toString().equals(getDataTypeDisconnect())) {
caseDisconnect(sender.toString(), receiver.toString(), payload.toString());
} else if (type.toString().equals(getDataTypeMessage())) {
caseMessage(sender.toString(), receiver.toString(), payload.toString());
} else if (type.toString().equals(getDataTypeError())) {
caseError(sender.toString(), receiver.toString(), payload.toString());
String sender = null;
String reciever = null;
String type = null;
String payload = null;
if (scanner.hasNextLine()) {
sender = scanner.nextLine();
} else {
System.out.println("Unknown data type received: " + type);
throw new ChatProtocolException("No Sender found");
}
} catch (ChatProtocolException e) {
System.err.println("Error while processing data: " + e.getMessage());
sendData(USER_NONE, userName.get(), getDataTypeError(), e.getMessage());
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");
}
private void caseConfirm(String sender, String receiver, String payload) {
if (state.get() == CONFIRM_CONNECT) {
this.userName.set(receiver);
this.serverPort.set(getConnection().getRemotePort());
this.serverAddress.set(getConnection().getRemoteHost());
messages.addMessage(new Message(Message.MessageType.INFO, sender, receiver, payload));
if (scanner.hasNextLine()) {
payload = scanner.nextLine();
}
// dispatch operation based on type parameter
if (type.equals(DATA_TYPE_CONNECT)) {
System.err.println("Illegal connect request from server");
} else if (type.equals(DATA_TYPE_CONFIRM)) {
if (stateObjectProperty.get() == CONFIRM_CONNECT) {
this.userName.set(reciever);
this.serverAddress.set(connection.getRemoteHost());
this.serverPort.set(connection.getRemotePort());
messageList.addMessage(sender,reciever,payload,INFO);
System.out.println("CONFIRM: " + payload);
this.setState(CONNECTED);
} else if (state.get() == CONFIRM_DISCONNECT) {
messages.addMessage(new Message(Message.MessageType.INFO, sender, receiver, payload));
} else if (stateObjectProperty.get() == CONFIRM_DISCONNECT) {
messageList.addMessage(sender,reciever,payload,INFO);
System.out.println("CONFIRM: " + payload);
this.setState(DISCONNECTED);
} else {
System.err.println("Got unexpected confirm message: " + payload);
}
}
/**
* Initiates the disconnect sequence and sends the message with all its info.
*
* @param sender the sender name of the message
* @param receiver the receiver name of the message
* @param payload the added payload that corresponds to the message
*/
private void caseDisconnect(String sender, String receiver, String payload) {
if (state.get() == DISCONNECTED) {
} else if (type.equals(DATA_TYPE_DISCONNECT)) {
if (stateObjectProperty.get() == DISCONNECTED) {
System.out.println("DISCONNECT: Already in disconnected: " + payload);
return;
}
messages.addMessage(new Message(Message.MessageType.INFO, sender, receiver, payload));
messageList.addMessage(sender,reciever,payload,INFO);
System.out.println("DISCONNECT: " + payload);
this.setState(DISCONNECTED);
}
/**
* Initiates the procedure to send a new message and sends one as such.
*
* @param sender the sender name of the message
* @param receiver the receiver name of the message
* @param payload the added payload that corresponds to the message
*/
private void caseMessage(String sender, String receiver, String payload) {
if (state.get() != CONNECTED) {
System.out.println("MESSAGE: Illegal state " + state + " for message: " + payload);
} else if (type.equals(DATA_TYPE_MESSAGE)) {
if (stateObjectProperty.get() != CONNECTED) {
System.out.println("MESSAGE: Illegal state " + stateObjectProperty.get() + " for message: " + payload);
return;
}
messages.addMessage(new Message(Message.MessageType.MESSAGE, sender, receiver, payload));
System.out.println("MESSAGE: From " + sender + " to " + receiver + ": " + payload);
}
/**
* Stores the message as an error message and displays it as such as well.
*
* @param sender the sender name of the message
* @param receiver the receiver name of the message
* @param payload the added payload that corresponds to the message
*/
private void caseError(String sender, String receiver, String payload) {
messages.addMessage(new Message(Message.MessageType.ERROR, sender, receiver, payload));
messageList.addMessage(sender,reciever,payload,MESSAGE);
System.out.println("MESSAGE: From " + sender + " to " + reciever + ": "+ payload);
} else if (type.equals(DATA_TYPE_ERROR)) {
messageList.addMessage(sender,reciever,payload,ERROR);
System.out.println("ERROR: " + payload);
} else {
System.out.println("Unknown data type received: " + type);
}
} catch (ChatProtocolException e) {
System.err.println("Error while processing data: " + e.getMessage());
sendData(USER_NONE, userName.get(), DATA_TYPE_ERROR, e.getMessage());
}
}
public 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 {
connection.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());
}
}
}
/**
* Send connect attempt to Server
*
* @throws ChatProtocolException Error that is thrown if the state is not set to NEW
*/
public void connect() throws ChatProtocolException {
if (state.get() != NEW) throw new ChatProtocolException("Illegal state for connect: " + state);
this.sendData(userName.get(), USER_NONE, getDataTypeConnect(), null);
if (stateObjectProperty.get() != NEW) throw new ChatProtocolException("Illegal state for connect: " + stateObjectProperty.get());
this.sendData(userName.get(), USER_NONE, DATA_TYPE_CONNECT,null);
this.setState(CONFIRM_CONNECT);
}
/**
* Send Disconnect attempt to server
*
* @throws ChatProtocolException Error tha si thrown if state is invalid
*/
public void disconnect() throws ChatProtocolException {
if (state.get() != NEW && state.get() != CONNECTED)
throw new ChatProtocolException("Illegal state for disconnect: " + state);
this.sendData(userName.get(), USER_NONE, getDataTypeDisconnect(), null);
if (stateObjectProperty.get() != NEW && stateObjectProperty.get() != CONNECTED) throw new ChatProtocolException("Illegal state for disconnect: " + stateObjectProperty.get());
this.sendData(userName.get(), USER_NONE, DATA_TYPE_DISCONNECT,null);
this.setState(CONFIRM_DISCONNECT);
}
/**
* Sends message to Server
*
* @param messageString The message the user wants to send
* @return true if message is valid else false
* @throws ChatProtocolException if illegal connection state
*/
public boolean message(String messageString) throws ChatProtocolException {
if (state.get() != CONNECTED) throw new ChatProtocolException("Illegal state for message: " + state);
if (stateObjectProperty.get() != CONNECTED) throw new ChatProtocolException("Illegal state for message: " + stateObjectProperty.get());
Matcher matcher = messagePattern.matcher(messageString);
if (matcher.find()) {
@@ -294,10 +227,11 @@ public class ClientConnectionHandler extends ConnectionHandler implements Runnab
return false;
}
if (receiver == null || receiver.isBlank()) receiver = ClientConnectionHandler.USER_ALL;
this.sendData(userName.get(), receiver, getDataTypeMessage(), message);
this.sendData(userName.get(), receiver, DATA_TYPE_MESSAGE,message);
return true;
} else {
return false;
}
}
}
@@ -1,67 +1,68 @@
package ch.zhaw.pm2.multichat.client;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import java.util.ArrayList;
import java.util.List;
/**
* Class that is used to store the messages in an ArrayList
* And also as a Model that informs the controller via Listeners that can be initialized
*/
public class ClientMessageList {
private List<Message> messages = new ArrayList<>();
private final SimpleBooleanProperty changed = new SimpleBooleanProperty(false);
import static ch.zhaw.pm2.multichat.client.ClientConnectionHandler.USER_NONE;
/**
* Adds a new message to ArrayList and also informs Listener.
* @param message that should be added
*/
public void addMessage(Message message) {
messages.add(message);
public class ClientMessageList {
private List<Message> messages;
private SimpleBooleanProperty changed;
public ClientMessageList() {
messages = new ArrayList<>();
changed = new SimpleBooleanProperty(true);
}
public SimpleBooleanProperty getChangedProperty() {
return changed;
}
public void addMessage(String sender, String receiver, String message, Message.MessageType type) {
if(sender == null) {
sender = USER_NONE;
}
messages.add(new Message(type, sender, receiver, message));
changed.set(!changed.get());
}
/**
* Applies a given filter over all messages and returns the result as a new String.
* Method is also in charge of applying the correct prefix to the message according to its type.
*
* @param filter is the applied filter on all the messages that are stored.
* @return String that matches the given filter.
*/
public String getFilteredMessages(String filter) {
StringBuilder result = new StringBuilder();
boolean showAll = filter == null || filter.isBlank();
for(Message message : messages) {
if (showAll || message.matchesFilter(filter)) {
if(showAll || message.matchesFilter(filter))
{
switch (message.getType()) {
case MESSAGE ->
result.append(String.format("[%s -> %s] %s\n", message.getSender(), message.getReceiver(), message.getText()));
case MESSAGE -> result.append(String.format("[%s -> %s] %s\n", message.getSender(), message.getReceiver(), message.getText()));
case ERROR -> result.append(String.format("[ERROR] %s\n", message.getText()));
case INFO -> result.append(String.format("[INFO] %s\n", message.getText()));
default ->
result.append(String.format("[ERROR] %s\n", "Unexpected message type: " + message.getType()));
default -> result.append(String.format("[ERROR] %s\n", "Unexpected message type: " + message.getType()));
}
}
}
return result.toString();
}
/**
* Overwrites the Arraylist of messages, clearing it, also informs all Listeners.
*/
public String getMessages() {
StringBuilder result = new StringBuilder();
for(Message message : messages) {
switch (message.getType()) {
case MESSAGE -> result.append(String.format("[%s -> %s] %s\n", message.getSender(), message.getReceiver(), message.getText()));
case ERROR -> result.append(String.format("[ERROR] %s\n", message.getText()));
case INFO -> result.append(String.format("[INFO] %s\n", message.getText()));
default -> result.append(String.format("[ERROR] %s\n", "Unexpected message type: " + message.getType()));
}
}
return result.toString();
}
public void clear() {
messages = new ArrayList<>();
changed.set(!changed.get());
}
/**
* Getter Method to check the current value of SimpleBooleanProperty changed.
*
* @return the current value of changed
*/
public SimpleBooleanProperty getChangedProperty() {
return changed;
messages = new SimpleListProperty<>();
}
}
@@ -6,40 +6,19 @@ import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
/**
* Class in charge of initializing and loading elements needed for the GUI.
* Also Launching the chat window with pre-given parameters
*/
public class ClientUI extends Application {
private final ClientMessageList clientMessageList = new ClientMessageList();
private final ClientConnectionHandler connectionHandler = new ClientConnectionHandler(clientMessageList);
private ClientMessageList clientMessageList = new ClientMessageList();
/**
* Start method will only run the chatWindow method.
*
* @param primaryStage the primary stage for this application, onto which
* the application scene can be set.
* Applications may create other stages, if needed, but they will not be
* primary stages.
*/
@Override
public void start(Stage primaryStage) {
chatWindow(primaryStage);
}
/**
* Method is in charge of loading the FXML file and then initializing the controllers and setting some parameters for the stage.
*
* @param primaryStage of the Application onto which the Scene is set.
*/
private void chatWindow(Stage primaryStage) {
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("ChatWindow.fxml"));
Pane rootPane = loader.load();
ChatWindowController chatWindowController = loader.getController();
chatWindowController.setMessages(clientMessageList);
chatWindowController.setConnectionHandler(connectionHandler);
Pane rootPane = loader.load();
// fill in scene and stage setup
Scene scene = new Scene(rootPane);
@@ -1,20 +1,19 @@
package ch.zhaw.pm2.multichat.client;
/**
* A Message object represents one Message of a client. Can be stored in ClientMessageList.
A Message object represents one Message of a client. Can be stored in ClientMessageList.
*/
public class Message {
private final MessageType type;
private final String sender;
private final String receiver;
private final String text;
private MessageType type;
private String sender;
private String receiver;
private String text;
/**
* Constructor of Message. Needs all Information about a Message to save them.
*
* @param type Message (if it's a message typed by a user), Error or Information (if it is generated automatically, in this case sender and receiver will be null)
* @param type Message (if it's a message typed by a user), Error or Information (if it is generated automatically, in this case sender and reciever will be null)
* @param sender The User who has sent the message.
* @param receiver The User who should receive the message.
* @param receiver The User who should recieve the message.
* @param text The Text of the message.
*/
public Message(MessageType type, String sender, String receiver, String text) {
@@ -26,9 +25,8 @@ public class Message {
/**
* Checks if the Filter String is contained in one of the datafields sender, receiver or text
*
* @param filter The Filter String
* @return true if it is the Filter String is contained in a data field.
* @return true if it the Filter String is contained in a datafield.
*/
public boolean matchesFilter(String filter){
return (sender != null && sender.contains(filter)) ||
@@ -51,7 +49,7 @@ public class Message {
}
/**
* @return The Receiver who receives the Message.
* @return The Reciever who recieves the Message.
*/
public String getReceiver() {
return receiver;
@@ -65,7 +63,7 @@ public class Message {
}
/**
* Enumeration of Message Types.
* Enummeration of Message Types.
*/
public enum MessageType {
INFO, MESSAGE, ERROR;
@@ -12,9 +12,7 @@
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>
<BorderPane xmlns:fx="http://javafx.com/fxml/1" fx:id="rootPane" minWidth="-Infinity" prefHeight="500.0"
prefWidth="420.0" xmlns="http://javafx.com/javafx/18"
fx:controller="ch.zhaw.pm2.multichat.client.ChatWindowController">
<BorderPane fx:id="rootPane" minWidth="-Infinity" prefHeight="500.0" prefWidth="420.0" xmlns="http://javafx.com/javafx/18" xmlns:fx="http://javafx.com/fxml/1" fx:controller="ch.zhaw.pm2.multichat.client.ChatWindowController">
<top>
<VBox BorderPane.alignment="CENTER">
<children>
@@ -33,25 +31,20 @@
</MenuBar>
<HBox fillHeight="false" spacing="5.0">
<children>
<TextField fx:id="userNameField" alignment="CENTER_RIGHT" maxWidth="1.7976931348623157E308"
minWidth="110.0" promptText="Username" HBox.hgrow="SOMETIMES"/>
<Label alignment="CENTER" contentDisplay="CENTER" text="\@" textAlignment="CENTER"
textOverrun="CLIP" HBox.hgrow="NEVER">
<TextField fx:id="userNameField" alignment="CENTER_RIGHT" maxWidth="1.7976931348623157E308" minWidth="110.0" promptText="Username" HBox.hgrow="SOMETIMES" />
<Label alignment="CENTER" contentDisplay="CENTER" text="\@" textAlignment="CENTER" textOverrun="CLIP" HBox.hgrow="NEVER">
<HBox.margin>
<Insets bottom="5.0" top="5.0" />
</HBox.margin>
</Label>
<TextField fx:id="serverAddressField" alignment="CENTER_RIGHT" minWidth="110.0"
promptText="Host" HBox.hgrow="SOMETIMES"/>
<TextField fx:id="serverAddressField" alignment="CENTER_RIGHT" minWidth="110.0" promptText="Host" HBox.hgrow="SOMETIMES" />
<Label text=":" HBox.hgrow="NEVER">
<HBox.margin>
<Insets bottom="5.0" top="5.0" />
</HBox.margin>
</Label>
<TextField fx:id="serverPortField" minWidth="-Infinity" prefWidth="60.0" promptText="Port"
HBox.hgrow="NEVER"/>
<Button fx:id="connectButton" maxWidth="-Infinity" minWidth="-Infinity" mnemonicParsing="false"
onAction="#toggleConnection" prefWidth="80.0" text="Connect" HBox.hgrow="NEVER">
<TextField fx:id="serverPortField" minWidth="-Infinity" prefWidth="60.0" promptText="Port" HBox.hgrow="NEVER" />
<Button fx:id="connectButton" maxWidth="-Infinity" minWidth="-Infinity" mnemonicParsing="false" onAction="#toggleConnection" prefWidth="80.0" text="Connect" HBox.hgrow="NEVER">
<HBox.margin>
<Insets left="5.0" />
</HBox.margin>
@@ -71,8 +64,7 @@
<HBox spacing="5.0">
<children>
<TextField fx:id="messageField" onAction="#message" HBox.hgrow="ALWAYS" />
<Button fx:id="sendButton" alignment="CENTER" maxWidth="-Infinity" minWidth="-Infinity"
mnemonicParsing="false" onAction="#message" prefWidth="50.0" text="Send" textAlignment="CENTER">
<Button fx:id="sendButton" alignment="CENTER" maxWidth="-Infinity" minWidth="-Infinity" mnemonicParsing="false" onAction="#message" prefWidth="50.0" text="Send" textAlignment="CENTER">
<HBox.margin>
<Insets left="5.0" />
</HBox.margin>
@@ -1,142 +0,0 @@
package ch.zhaw.pm2.multichat.protocol;
import java.io.EOFException;
import java.io.IOException;
import java.net.SocketException;
import java.util.Scanner;
/**
* This abstract class is the superclass for ClientConnectionHandler and ServerConnectionHandler
* It offers the DATA_TYPE Strings and a {@link State} enum for all valid connection states.
* Shared methods are implemented in this class as well {@link ConnectionHandler#sendData(String, String, String, String)} {@link ConnectionHandler#processData(Scanner, StringBuilder, StringBuilder, StringBuilder, StringBuilder)}
*/
public abstract class ConnectionHandler {
private NetworkHandler.NetworkConnection<String> connection;
// 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";
public static final String USER_NONE = "";
public static final String USER_ALL = "*";
// State of the connection
public enum State {
NEW, CONFIRM_CONNECT, CONNECTED, CONFIRM_DISCONNECT, DISCONNECTED, ERROR;
}
/**
* @return {@link ConnectionHandler#DATA_TYPE_CONNECT}
*/
public static String getDataTypeConnect() {
return DATA_TYPE_CONNECT;
}
/**
* @return {@link ConnectionHandler#DATA_TYPE_CONFIRM}
*/
public static String getDataTypeConfirm() {
return DATA_TYPE_CONFIRM;
}
/**
* @return {@link ConnectionHandler#DATA_TYPE_DISCONNECT}
*/
public static String getDataTypeDisconnect() {
return DATA_TYPE_DISCONNECT;
}
/**
* @return {@link ConnectionHandler#DATA_TYPE_MESSAGE
*/
public static String getDataTypeMessage() {
return DATA_TYPE_MESSAGE;
}
/**
* @return {@link ConnectionHandler#DATA_TYPE_ERROR}
*/
public static String getDataTypeError() {
return DATA_TYPE_ERROR;
}
/**
* @return {@link NetworkHandler.NetworkConnection}
*/
public NetworkHandler.NetworkConnection<String> getConnection() {
return connection;
}
/**
* This method sets the NetworkConnection used for the server <-> client connection
*
* @param connection NetworkConnection used for the server <-> client connection
*/
protected void setConnection(NetworkHandler.NetworkConnection<String> connection) {
this.connection = connection;
}
/**
* This method reads the data when a ConnectionHandler receives it. It tries to read out the sender, receiver, type and payload.
* If the data does not contain the expected number of lines, it throws a {@link ChatProtocolException}
*
* @param scanner to read data
* @param sender of the data
* @param receiver for the data
* @param type of data
* @param payload the data sent
* @throws ChatProtocolException if the data does not contain the expected number of lines
*/
protected void processData(Scanner scanner, StringBuilder sender, StringBuilder receiver, StringBuilder type, StringBuilder payload) throws ChatProtocolException {
// parse data content
if (scanner.hasNextLine()) {
sender.append(scanner.nextLine());
} else if (scanner.hasNextLine()) {
receiver.append(scanner.nextLine());
} else {
throw new ChatProtocolException("No Sender found");
}
if (scanner.hasNextLine()) {
receiver.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());
}
}
/**
* This method gets called to send data via the socket defined in the {@link NetworkHandler.NetworkConnection}
*
* @param sender of the data
* @param receiver of the data
* @param type of the data
* @param payload of the data
*/
protected void sendData(String sender, String receiver, String type, String payload) {
if (connection.isAvailable()) {
String data = sender + "\n" +
receiver + "\n" +
type + "\n" +
payload + "\n";
try {
connection.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());
}
}
}
}
@@ -8,38 +8,14 @@ import java.util.HashMap;
import java.util.Map;
/**
* This Class represents a Server. The user can start the programm with the port number as a argument.
* If no argument has been set the {@link NetworkHandler#DEFAULT_PORT} is used as port number.
* After initialising the server:
* 1. Starts a Socketserver using the logic given in {@link NetworkHandler.NetworkServer#createServer()}
* 2. The server starts to listen for incoming connection using the Logic given in {@link NetworkHandler.NetworkServer#waitForConnection()}
* 3. New connections will be attached to a Connection handler: {@link ServerConnectionHandler} and placed in a Map containing all active connections {@link Server#connections}
*/
public class Server {
// Server connection
private final NetworkHandler.NetworkServer<String> networkServer;
private NetworkHandler.NetworkServer<String> networkServer;
// Connection registry
private final Map<String, ServerConnectionHandler> connections = new HashMap<>();
private Map<String,ServerConnectionHandler> connections = new HashMap<>();
/**
* The Constructor to create a new instance.
*
* @param serverPort to listen for incoming connections.
* @throws IOException thrown if an I/O error occurs when opening the socket.
*/
public Server(int serverPort) throws IOException {
// Open server connection
System.out.println("Create server connection");
networkServer = NetworkHandler.createServer(serverPort);
System.out.println("Listening on " + networkServer.getHostAddress() + ":" + networkServer.getHostPort());
}
/**
* @param args
*/
public static void main(String[] args) {
// Parse arguments for server port.
try {
@@ -78,10 +54,13 @@ public class Server {
}
}
/**
* With this methode the instance waits for incoming connections. If a client tries to connect to the server.
* The connection will be registered in the connection registry if successful.
*/
public Server(int serverPort) throws IOException {
// Open server connection
System.out.println("Create server connection");
networkServer = NetworkHandler.createServer(serverPort);
System.out.println("Listening on " + networkServer.getHostAddress() + ":" + networkServer.getHostPort());
}
private void start() {
System.out.println("Server started.");
try {
@@ -89,19 +68,22 @@ public class Server {
NetworkHandler.NetworkConnection<String> connection = networkServer.waitForConnection();
ServerConnectionHandler connectionHandler = new ServerConnectionHandler(connection, connections);
new Thread(connectionHandler).start();
System.out.println(String.format("Connected new Client %s with IP:Port <%s:%d>",
connectionHandler.getUserName(),
connection.getRemoteHost(),
connection.getRemotePort()
));
}
} catch(SocketException e) {
System.out.println("Server connection terminated");
} catch (IOException e) {
}
catch (IOException e) {
System.err.println("Communication error " + e);
}
// close server
System.out.println("Server Stopped.");
}
/**
* This method will stop the serversocket.
*/
public void terminate() {
try {
System.out.println("Close server port.");
@@ -1,93 +1,68 @@
package ch.zhaw.pm2.multichat.server;
import ch.zhaw.pm2.multichat.protocol.ChatProtocolException;
import ch.zhaw.pm2.multichat.protocol.ConnectionHandler;
import static ch.zhaw.pm2.multichat.protocol.ConnectionHandler.State.*;
import ch.zhaw.pm2.multichat.protocol.NetworkHandler;
import java.io.EOFException;
import java.io.IOException;
import java.net.SocketException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;
import static ch.zhaw.pm2.multichat.server.ServerConnectionHandler.State.*;
/**
* This class represents the connection between the server and a client and offers the serverside logic.
* The ServerConnectionHandler receives data send from the client as well as sends data to the client.
* <p>
* The ServeConnectionHandler offers following functionality:
* <p>
* Evaluating connection attempts from a client by:
* 1. Checks if Username is valid (Not used)
* 2. Saves Username in {@link ServerConnectionHandler#userName}
* 3. Saves the connection in the {@link ServerConnectionHandler#connectionRegistry}
* <p>
* Processes disconnections from a client by:
* 1. Removing the connection from the {@link ServerConnectionHandler#connectionRegistry}
* 2. Terminates the socket by calling {@link NetworkHandler.NetworkConnection#close()}
* <p>
* Process Messages send from a client by:
* 1. Evaluating the receiver by differentiating between broadcast or unicast.
* 2. Sending the message accordingly.
* <p>
* To use this class, start a new instance and start it in a thread.
* To constructor needs following parameter:
* 1. {@link ch.zhaw.pm2.multichat.protocol.NetworkHandler.NetworkConnection} representing the socket connection between server and client
* 2. {@link Map<String,ServerConnectionHandler>} registry to check for all active connections
* 3. {@link ReentrantLock @link Condition} to lock server thread to evaluate connection.
*/
public class ServerConnectionHandler extends ConnectionHandler implements Runnable {
public class ServerConnectionHandler 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 String userName = "Anonymous-"+connectionId;
private State state = NEW;
/**
* Called when runnable gets started in a thread.
*/
@Override
public void run() {
startReceiving();
}
/**
* Constructor to initialize the connection
*
* @param connection representing the socket connection between server and client
* @param registry map containing all active connections between server and clients
enum State {
NEW, CONNECTED, DISCONNECTED;
}
*/
public ServerConnectionHandler(NetworkHandler.NetworkConnection<String> connection,
Map<String,ServerConnectionHandler> registry) {
super();
setConnection(connection);
Objects.requireNonNull(connection, "Connection must not be null");
Objects.requireNonNull(registry, "Registry must not be null");
this.connection = connection;
this.connectionRegistry = registry;
}
/**
* These methods runs in a while-loop as long as the socket between server and client is available
* and the connection State is not ERROR.
*/
private void startReceiving() {
System.out.println("Starting Connection Handler for new User");
public String getUserName() {
return this.userName;
}
public void startReceiving() {
System.out.println("Starting Connection Handler for " + userName);
try {
System.out.println("Start receiving data...");
while (getConnection().isAvailable() && !(state == ERROR)) {
String data = getConnection().receive();
while (connection.isAvailable()) {
String data = connection.receive();
processData(data);
}
System.out.println("Stopped receiving data");
System.out.println("Stopped recieving data");
} catch (SocketException e) {
System.out.println("Connection terminated locally");
connectionRegistry.remove(userName);
@@ -101,60 +76,84 @@ public class ServerConnectionHandler extends ConnectionHandler implements Runnab
} catch(ClassNotFoundException e) {
System.err.println("Received object of unknown type: " + e.getMessage());
}
if (state == ERROR) {
System.out.println("Stopping Connection Handler for Rejected Client");
} else {
System.out.println("Stopping Connection Handler for " + userName);
}
}
/**
* This method will call {@link NetworkHandler.NetworkConnection#close()} to close the Socket.
*/
private void stopReceiving() {
public void stopReceiving() {
System.out.println("Closing Connection Handler for " + userName);
try {
System.out.println("Stop receiving data...");
getConnection().close();
connection.close();
System.out.println("Stopped receiving data.");
} catch (IOException e) {
System.err.println("Failed to close connection." + e.getMessage());
System.err.println("Failed to close connection." + e);
}
System.out.println("Closed Connection Handler for " + userName);
}
/**
* This method gets called when socket receives data. The method checks for the data type and reacts accordingly
* If data type:
* 1. Connect => checks if username is valid. if valid sends response to client with confirmation.
* If username not valid quits connection by changing status to ERROR.
* 2. Confirm => Server should not receive this kind of message. STDOUT informs about it.
* 3. Disconnect => Disconnects connection by removing connection from registry and calling method to terminate socket.
* 4. Message => Checks if broadcast or unicast. Sends data accordingly
* 5. Error => STDERR message
*
* @param data received by the server
*/
private void processData(String data) {
try {
// parse data content
Scanner scanner = new Scanner(data);
StringBuilder sender = new StringBuilder();
StringBuilder receiver = new StringBuilder();
StringBuilder type = new StringBuilder();
StringBuilder payload = new StringBuilder();
super.processData(scanner, sender, receiver, type, payload);
String sender = null;
String reciever = null;
String type = null;
String payload = null;
if (scanner.hasNextLine()) {
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
if (type.toString().equals(getDataTypeConnect())) {
caseConnect(sender.toString());
} else if (type.toString().equals(getDataTypeConfirm())) {
if (type.equals(DATA_TYPE_CONNECT)) {
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))
throw new ChatProtocolException("User name already taken: " + sender);
this.userName = sender;
connectionRegistry.put(userName, this);
sendData(USER_NONE, userName, DATA_TYPE_CONFIRM, "Registration successfull for " + userName);
this.state = CONNECTED;
} else if (type.equals(DATA_TYPE_CONFIRM)) {
System.out.println("Not expecting to receive a CONFIRM request from client");
} else if (type.toString().equals(getDataTypeDisconnect())) {
caseDisconnect();
} else if (type.toString().equals(getDataTypeMessage())) {
caseMessage(sender.toString(), receiver.toString(), type.toString(), payload.toString());
} else if (type.toString().equals(getDataTypeError())) {
} else if (type.equals(DATA_TYPE_DISCONNECT)) {
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);
this.state = DISCONNECTED;
this.stopReceiving();
} else if (type.equals(DATA_TYPE_MESSAGE)) {
if (state != CONNECTED) throw new ChatProtocolException("Illegal state for message request: " + state);
if (USER_ALL.equals(reciever)) {
for (ServerConnectionHandler handler : connectionRegistry.values()) {
handler.sendData(sender, reciever, type, payload);
}
} else {
ServerConnectionHandler handler = connectionRegistry.get(reciever);
if (handler != null) {
handler.sendData(sender, reciever, type, payload);
} else {
this.sendData(USER_NONE, userName, DATA_TYPE_ERROR, "Unknown User: " + reciever);
}
}
} else if (type.equals(DATA_TYPE_ERROR)) {
System.err.println("Received error from client (" + sender + "): " + payload);
} else {
System.err.println("Unknown data type received: " + type);
@@ -162,81 +161,27 @@ public class ServerConnectionHandler extends ConnectionHandler implements Runnab
}
} catch(ChatProtocolException e) {
System.out.println("Error while processing data" + e.getMessage());
sendData(USER_NONE, userName, getDataTypeError(), e.getMessage());
sendData(USER_NONE, userName, DATA_TYPE_ERROR, e.getMessage());
}
}
/**
* This method is called by method {@link ServerConnectionHandler#processData(String)}
* Checks if username is valid. if valid sends response to client with confirmation.
*
* @param sender of the payload
* @throws ChatProtocolException if username not valid
*/
private void caseConnect(String sender) throws ChatProtocolException {
if (this.state != NEW) throw new ChatProtocolException("Illegal state for connect request: " + state);
if (sender.isBlank()) sender = this.userName;
//if username not valid
if (connectionRegistry.containsKey(sender)) {
state = ERROR;
System.out.println(String.format("Connecting failed for new Client with IP:Port <%s:%d>.\nReason: Name already taken.",
getConnection().getRemoteHost(),
getConnection().getRemotePort()));
throw new ChatProtocolException("User name already taken: " + sender);
}
//if username valid
this.userName = sender;
connectionRegistry.put(userName, this);
sendData(USER_NONE, userName, getDataTypeConfirm(), "Registration successful for " + userName);
this.state = CONNECTED;
System.out.println(String.format("Connected new Client %s with IP:Port <%s:%d>",
userName,
getConnection().getRemoteHost(),
getConnection().getRemotePort()));
}
/**
* This method is called by method {@link ServerConnectionHandler#processData(String)}
* Disconnects connection by removing connection from registry and calling method {@link ServerConnectionHandler#stopReceiving()} to terminate socket.
*
* @throws ChatProtocolException if state already DISCONNECTED.
*/
private void caseDisconnect() throws ChatProtocolException {
if (state == DISCONNECTED)
throw new ChatProtocolException("Illegal state for disconnect request: " + state);
if (state == CONNECTED) {
connectionRegistry.remove(this.userName);
}
sendData(USER_NONE, userName, getDataTypeConfirm(), "Confirm disconnect of " + userName);
this.state = DISCONNECTED;
this.stopReceiving();
}
/**
* This method is called by method {@link ServerConnectionHandler#processData(String)}
* Checks if broadcast or unicast. Sends data accordingly
*
* @param sender who sent data
* @param receiver to receive data
* @param type of message
* @param payload data to transmit
* @throws ChatProtocolException if state not equal to CONNECT
*/
private void caseMessage(String sender, String receiver, String type, String payload) throws ChatProtocolException {
if (state != CONNECTED) throw new ChatProtocolException("Illegal state for message request: " + state);
if (USER_ALL.equals(receiver)) {
for (ServerConnectionHandler handler : connectionRegistry.values()) {
handler.sendData(sender, receiver, type, payload);
}
} else {
ServerConnectionHandler handler = connectionRegistry.get(receiver);
if (handler != null) {
handler.sendData(sender, receiver, type, payload);
if (!receiver.equals(sender)) {
sendData(sender, receiver, type, payload); //send message to sender if it's a direct message and sender is not receiver.
}
} else {
this.sendData(USER_NONE, userName, getDataTypeError(), "Unknown User: " + receiver);
public 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 {
connection.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());
}
}
}