Compare commits

...

4 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
4 changed files with 159 additions and 74 deletions

View File

@ -4,6 +4,9 @@ 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;
@ -39,11 +42,14 @@ public class ChatWindowController {
public void initialize() {
serverAddressField.setText(NetworkHandler.DEFAULT_ADDRESS.getCanonicalHostName());
serverPortField.setText(String.valueOf(NetworkHandler.DEFAULT_PORT));
stateChanged(NEW);
}
this.messages = new ClientMessageList();
public void setMessages(ClientMessageList messages) {
this.messages = messages;
messages.getChangedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
setMessageField(messages.getMessages());
}
});
}
private void applicationClose() {
@ -52,7 +58,7 @@ public class ChatWindowController {
@FXML
private void toggleConnection () {
if (connectionHandler == null || connectionHandler.getState() != CONNECTED) {
if (connectionHandler == null || connectionHandler.getStateObjectProperty().get() != CONNECTED) {
connect();
} else {
disconnect();
@ -62,23 +68,22 @@ public class ChatWindowController {
private void connect() {
try {
messages.clear(); // clear message list
redrawMessageList();
startConnectionHandler();
connectionHandler.connect();
} catch(ChatProtocolException | IOException e) {
addError(e.getMessage());
messages.addMessage(null,null, e.getMessage(), Message.MessageType.ERROR);
}
}
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);
}
}
@ -87,31 +92,33 @@ public class ChatWindowController {
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);
}
}
//TODO: TEST
@FXML
private void applyFilter( ) {
this.redrawMessageList();
messages.getFilteredMessages(filterValue.getText().strip());
}
private void startConnectionHandler() throws IOException {
String userName = userNameField.getText();
String serverAddress = serverAddressField.getText();
int serverPort = Integer.parseInt(serverPortField.getText());
connectionHandler = new ClientConnectionHandler(
NetworkHandler.openConnection(serverAddress, serverPort), userName,
this);
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);
}
@ -138,6 +145,49 @@ public class ChatWindowController {
}
}
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
@ -165,21 +215,7 @@ public class ChatWindowController {
});
}
public void addMessage(String sender, String receiver, String message) {
messages.addMessage(new Message(Message.MessageType.MESSAGE, sender, receiver, message));
this.redrawMessageList();
}
public void addInfo(String message) {
messages.addMessage(new Message(Message.MessageType.INFO, null, null, message));
this.redrawMessageList();
}
public void addError(String message) {
messages.addMessage(new Message(Message.MessageType.ERROR, null, null, message));
this.redrawMessageList();
}
//TODO: MAKE ChangeListener
private void redrawMessageList() {
this.messageArea.clear();
Platform.runLater(() -> this.messageArea.setText(messages.getFilteredMessages(filterValue.getText().strip())));

View File

@ -2,6 +2,10 @@ package ch.zhaw.pm2.multichat.client;
import ch.zhaw.pm2.multichat.protocol.ChatProtocolException;
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;
import java.io.EOFException;
import java.io.IOException;
@ -11,10 +15,10 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static ch.zhaw.pm2.multichat.client.ClientConnectionHandler.State.*;
import static ch.zhaw.pm2.multichat.client.Message.MessageType.*;
public class ClientConnectionHandler implements Runnable {
private final NetworkHandler.NetworkConnection<String> connection;
private final ChatWindowController controller;
private NetworkHandler.NetworkConnection<String> connection;
// Data types used for the Chat Protocol
private static final String DATA_TYPE_CONNECT = "CONNECT";
@ -26,30 +30,44 @@ public class ClientConnectionHandler implements Runnable {
public static final String USER_NONE = "";
public static final String USER_ALL = "*";
private SimpleStringProperty userName;
private SimpleIntegerProperty serverPort;
private SimpleStringProperty serverAddress;
private ObjectProperty<State> stateObjectProperty;
private ClientMessageList messageList;
private final Pattern messagePattern = Pattern.compile( "^(?:@(\\w*))?\\s*(.*)$" );
private String userName = USER_NONE;
private State state = NEW;
enum State {
NEW, CONFIRM_CONNECT, CONNECTED, CONFIRM_DISCONNECT, DISCONNECTED;
}
public ClientConnectionHandler(NetworkHandler.NetworkConnection<String> connection,
String userName,
ChatWindowController controller) {
this.connection = connection;
this.userName = (userName == null || userName.isBlank())? USER_NONE : userName;
this.controller = controller;
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);
}
public State getState() {
return this.state;
public ObjectProperty<State> getStateObjectProperty() {
return stateObjectProperty;
}
public SimpleStringProperty getUserNameProperty() {
return userName;
}
public SimpleStringProperty getServerAddressProperty() {
return serverAddress;
}
public SimpleIntegerProperty getServerPortProperty() {
return serverPort;
}
public void setState (State newState) {
this.state = newState;
controller.stateChanged(newState);
this.stateObjectProperty.set(newState);
}
public void run () {
@ -93,6 +111,7 @@ public class ClientConnectionHandler implements Runnable {
System.out.println("Closed Connection Handler to Server");
}
private void processData(String data) {
try {
// parse data content
@ -123,45 +142,44 @@ public class ClientConnectionHandler implements Runnable {
if (type.equals(DATA_TYPE_CONNECT)) {
System.err.println("Illegal connect request from server");
} else if (type.equals(DATA_TYPE_CONFIRM)) {
if (state == CONFIRM_CONNECT) {
this.userName = reciever;
controller.setUserName(userName);
controller.setServerPort(connection.getRemotePort());
controller.setServerAddress(connection.getRemoteHost());
controller.addInfo(payload);
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 == CONFIRM_DISCONNECT) {
controller.addInfo(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);
}
} else if (type.equals(DATA_TYPE_DISCONNECT)) {
if (state == DISCONNECTED) {
if (stateObjectProperty.get() == DISCONNECTED) {
System.out.println("DISCONNECT: Already in disconnected: " + payload);
return;
}
controller.addInfo(payload);
messageList.addMessage(sender,reciever,payload,INFO);
System.out.println("DISCONNECT: " + payload);
this.setState(DISCONNECTED);
} else if (type.equals(DATA_TYPE_MESSAGE)) {
if (state != CONNECTED) {
System.out.println("MESSAGE: Illegal state " + state + " for message: " + payload);
if (stateObjectProperty.get() != CONNECTED) {
System.out.println("MESSAGE: Illegal state " + stateObjectProperty.get() + " for message: " + payload);
return;
}
controller.addMessage(sender, reciever, payload);
messageList.addMessage(sender,reciever,payload,MESSAGE);
System.out.println("MESSAGE: From " + sender + " to " + reciever + ": "+ payload);
} else if (type.equals(DATA_TYPE_ERROR)) {
controller.addError(payload);
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, DATA_TYPE_ERROR, e.getMessage());
sendData(USER_NONE, userName.get(), DATA_TYPE_ERROR, e.getMessage());
}
}
@ -187,19 +205,19 @@ public class ClientConnectionHandler implements Runnable {
}
public void connect() throws ChatProtocolException {
if (state != NEW) throw new ChatProtocolException("Illegal state for connect: " + state);
this.sendData(userName, USER_NONE, DATA_TYPE_CONNECT,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);
}
public void disconnect() throws ChatProtocolException {
if (state != NEW && state != CONNECTED) throw new ChatProtocolException("Illegal state for disconnect: " + state);
this.sendData(userName, USER_NONE, DATA_TYPE_DISCONNECT,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);
}
public boolean message(String messageString) throws ChatProtocolException {
if (state != 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()) {
@ -209,7 +227,7 @@ public class ClientConnectionHandler implements Runnable {
return false;
}
if (receiver == null || receiver.isBlank()) receiver = ClientConnectionHandler.USER_ALL;
this.sendData(userName, receiver, DATA_TYPE_MESSAGE,message);
this.sendData(userName.get(), receiver, DATA_TYPE_MESSAGE,message);
return true;
} else {
return false;

View File

@ -1,14 +1,34 @@
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;
import static ch.zhaw.pm2.multichat.client.ClientConnectionHandler.USER_NONE;
public class ClientMessageList {
private List<Message> messages = new ArrayList<>();
private List<Message> messages;
private SimpleBooleanProperty changed;
public ClientMessageList() {
messages = new ArrayList<>();
changed = new SimpleBooleanProperty(true);
}
public void addMessage(Message message) {
messages.add(message);
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());
}
public String getFilteredMessages(String filter) {
@ -28,8 +48,21 @@ public class ClientMessageList {
return result.toString();
}
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<>();
messages = new SimpleListProperty<>();
}
}

View File

@ -17,10 +17,8 @@ public class ClientUI extends Application {
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);
Pane rootPane = loader.load();
// fill in scene and stage setup
Scene scene = new Scene(rootPane);