Merge pull request #47 from PM2-IT21bWIN-ruiz-mach-krea/Java_Doc_and_Formatting

Java doc and formatting
This commit is contained in:
Roman Schenk authored and GitHub Enterprise committed 2022-04-16 20:06:03 +02:00
commit b67b9c84aa
11 files changed
+390 -162

No files matched your search

+1 -1
View File
@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- Do not edit this file with editors other than diagrams.net -->
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="2601px" height="2210px" viewBox="-0.5 -0.5 2601 2210" content="&lt;mxfile host=&quot;Electron&quot; modified=&quot;2022-04-16T17:20:57.099Z&quot; agent=&quot;5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) draw.io/17.2.1 Chrome/96.0.4664.174 Electron/16.1.0 Safari/537.36&quot; etag=&quot;NvST5MnDjkijMmkzUQJS&quot; version=&quot;17.2.1&quot; type=&quot;device&quot;&gt;&lt;diagram id=&quot;E9rHy_gAgqXRi0qXOPk2&quot; name=&quot;Seite-1&quot;&gt;7Z1Zc+O2soB/jas8D54SSVHLoy3biU/NVraTk3maoiVa5okk+lL0eJRff7GSINBcJZCUgqrUxARXoT8Aje5G48yZrX/9FnmvL5/Dhb86sweLX2fO9Zlt29PRCP0Pl+xoiTVxh7RkGQULVpYWPAT/+KxwwErfgoW/zVwYh+EqDl6zhfNws/HncabMi6LwPXvZc7jKvvXVW/pKwcPcW6ml/w0W8QsrHfGfgU/87gfLF/5qazSlZ9Yev5r9lO2LtwjfhSLn5syZRWEY07/Wv2b+Clcfrxh6323O2eTLIn8TV7nh7jH68c/v76Off15c34fuX8PfFv+5YE/56a3e2C8+s0cr9Lyr7au3wV8d71hdjP7vDX/q1TxchdGZc4lORssn7xy9Ff03Q/+Cf33AfzpXpPI38cWztw5WO3r7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B8IghLAjr6xRC0d6UDyHfKcggeLwI2gWxet0imO83UmfLhsAjJrAgNK9bAgUNoZTAy8j3AABZseGvx/wVhPh1y18lxwqzYV+9xXEo+1WSQsNfj/mb9HQmIoYaFq+aM/AdK3zOoK8zkErOEhqp9ic/b7S/4wNQTKLYKwCLE56BSJmFGfstzKjDTcHWo4XcaF6YMaq8LUqwQTWOGPjHN9uiHFeXVbDhRLddViUXhvf6ukKg4NZOnLiGvuOib9rXAbOS4yIOl8uVn4ZUGfqOir5hQfa+TukTI3tLjSUGuuOCbthTC924ko/C7H93rNyJC1Z6xV0lz4Th7li5m/Z0gjGus9TDQHdU0LniDgK9gq6SGwLPand0UfM5udTQd1T0FSQQ7pa+Sn4IRN06wGvtlLVCphc8Lg4L9prqlsPK27xvY8zhi7dZ+ovzB3xAbtr47+TA8HhMPI4GfZ2CVPZzbP34DxYoKiYZ4cGjhsej4tHu69SkckI0xOODuIpDhDKzvMOQeVRkiku+e0Vm5cxoCZl4Xcc53208XephgDwqIAsSenQKpPhdlVP15SfjM/nuTpni8aCnE6JJcV6xLMV3m+fw3KB45CiKm8T3CsV8d4yK4k0UhZFh8dhZdHs6D5rku2gkFucr34s+p6uXjKXyuAic9HS+I35X0QY2i8h7F9OSG/yOCb+J1dfZTfFu8DQzLEmBbEbikwDR6esEpdxjw0A0s5NT4FBcLt4rDss9NYzD2raewDe2nlNCuGCrLine truncated
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="2601px" height="2210px" viewBox="-0.5 -0.5 2601 2210" content="&lt;mxfile host=&quot;Electron&quot; modified=&quot;2022-04-16T17:45:06.713Z&quot; agent=&quot;5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) draw.io/17.2.1 Chrome/96.0.4664.174 Electron/16.1.0 Safari/537.36&quot; etag=&quot;k5Q521hm3mURMrUdJZdW&quot; version=&quot;17.2.1&quot; type=&quot;device&quot;&gt;&lt;diagram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0UhZFh8dhZdHs6D5rku2gkFucr34s+p6uXjKXyuAic9HS+I35X0QY2i8h7F9OSG/yOCb+J1dfZTfFu8DQzLEmBbEbikwDR6esEpdxjw0A0s5NT4FBcLt4rDss9NYzD2raewDe2nlNCuGCrLine truncated

Before

Width:  |  Height:  |  Size: 133 KiB

After

Width:  |  Height:  |  Size: 133 KiB

@@ -17,28 +17,51 @@ import java.io.IOException;
import static ch.zhaw.pm2.multichat.protocol.ConnectionHandler.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 Button sendButton;
@FXML private TextField filterValue;
@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;
/**
* 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();
}
/**
* 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();
@@ -46,10 +69,17 @@ public class ChatWindowController {
serverPortField.setText(String.valueOf(connectionHandler.getServerPortProperty().get()));
}
/**
* Method which closes the Application via use of the disconnect Method.
*/
private void applicationClose() {
disconnect();
}
/**
* 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) {
@@ -59,16 +89,22 @@ public class ChatWindowController {
}
}
/**
* 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(e.getMessage());
addError("Error while starting Connection Handler and connect" + e);
}
}
/**
* Initiates disconnecting of the connectionHandler, also checks if connectionHandler is available.
*/
private void disconnect() {
if (connectionHandler == null) {
addError("No connection handler");
@@ -81,6 +117,9 @@ public class ChatWindowController {
}
}
/**
* 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();
@@ -97,11 +136,20 @@ public class ChatWindowController {
}
}
/**
* Method which is used when a Filter is applied
* Setting the Text in the message area after sending it through the filter.
*/
@FXML
private void applyFilter() {
Platform.runLater(() -> this.messageArea.setText(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(" ")) {
@@ -110,16 +158,18 @@ public class ChatWindowController {
connectionHandler.initialize(serverAddress, serverPort, userName);
new Thread(connectionHandler).start();
//register Listener
//startConnectionHandlerListener();
// register window close handler
rootPane.getScene().getWindow().addEventHandler(WindowEvent.WINDOW_CLOSE_REQUEST, windowCloseHandler);
} else {
addError("It is not allowed to have spaces in username!");
}
}
/**
* 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 stateChanged(State newState) {
// update UI (need to be run in UI thread: see Platform.runLater())
Platform.runLater(new Runnable() {
@@ -133,6 +183,11 @@ public class ChatWindowController {
}
}
/**
* Sets displayed username according to the String provided.
*
* @param userName provided String that is set as name.
*/
public void setUserName(String userName) {
Platform.runLater(new Runnable() {
@Override
@@ -142,6 +197,11 @@ 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
@@ -151,6 +211,11 @@ 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
@@ -160,16 +225,32 @@ 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));
}
/**
* 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
@@ -200,6 +281,9 @@ public class ChatWindowController {
});
}
/**
* Starts a new Listener for messages by using the observable Boolean.
*/
private void messageListener() {
messages.getChangedProperty().addListener(new ChangeListener<Boolean>() {
@Override
@@ -2,8 +2,16 @@ 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");
@@ -13,18 +13,29 @@ import java.net.SocketException;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static ch.zhaw.pm2.multichat.protocol.ConnectionHandler.State.*;
/**
* 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 {
private final Pattern messagePattern = Pattern.compile("^(?:@(\\S*))?\\s*(.*)$");
private SimpleStringProperty userName;
private SimpleObjectProperty<State> state;
private ClientMessageList messages;
private SimpleStringProperty serverAddress;
private SimpleIntegerProperty serverPort;
private final SimpleStringProperty userName;
private final SimpleObjectProperty<State> state;
private final ClientMessageList messages;
private final SimpleStringProperty serverAddress;
private final SimpleIntegerProperty serverPort;
/**
* 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;
@@ -34,6 +45,14 @@ public class ClientConnectionHandler extends ConnectionHandler implements Runnab
this.userName = new SimpleStringProperty(null);
}
/**
* 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);
@@ -42,24 +61,62 @@ public class ClientConnectionHandler extends ConnectionHandler implements Runnab
this.userName.set((userName == null || userName.isBlank()) ? USER_NONE : userName);
}
public SimpleStringProperty getServerAddressProperty() { return serverAddress; }
/**
* Observable getter Method for the stored serverAddress
*
* @return the stored serverAddress
*/
public SimpleStringProperty getServerAddressProperty() {
return serverAddress;
}
public SimpleIntegerProperty getServerPortProperty() { return serverPort; }
/**
* 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;
}
public SimpleStringProperty getUserNameProperty() { return userName; }
/**
* 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 void setState(State newState) {
state.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() {
System.out.println("Starting Connection Handler");
try {
@@ -68,7 +125,7 @@ public class ClientConnectionHandler extends ConnectionHandler implements Runnab
String data = getConnection().receive();
processData(data);
}
System.out.println("Stopped recieving data");
System.out.println("Stopped receiving data");
} catch (SocketException e) {
System.out.println("Connection terminated locally");
this.setState(DISCONNECTED);
@@ -85,6 +142,9 @@ 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 {
@@ -97,26 +157,31 @@ 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 {
Scanner scanner = new Scanner(data);
StringBuilder sender = new StringBuilder();
StringBuilder reciever = new StringBuilder();
StringBuilder receiver = new StringBuilder();
StringBuilder type = new StringBuilder();
StringBuilder payload = new StringBuilder();
super.processData(scanner,sender,reciever,type,payload);
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(), reciever.toString(), payload.toString());
caseConfirm(sender.toString(), receiver.toString(), payload.toString());
} else if (type.toString().equals(getDataTypeDisconnect())) {
caseDisconnect(sender.toString(),reciever.toString(),payload.toString());
caseDisconnect(sender.toString(), receiver.toString(), payload.toString());
} else if (type.toString().equals(getDataTypeMessage())) {
caseMessage(sender.toString(),reciever.toString(),payload.toString());
caseMessage(sender.toString(), receiver.toString(), payload.toString());
} else if (type.toString().equals(getDataTypeError())) {
caseError(sender.toString(), reciever.toString(), payload.toString());
caseError(sender.toString(), receiver.toString(), payload.toString());
} else {
System.out.println("Unknown data type received: " + type);
}
@@ -126,16 +191,16 @@ public class ClientConnectionHandler extends ConnectionHandler implements Runnab
}
}
private void caseConfirm(String sender, String reciever, String payload) {
private void caseConfirm(String sender, String receiver, String payload) {
if (state.get() == CONFIRM_CONNECT) {
this.userName.set(reciever);
this.userName.set(receiver);
this.serverPort.set(getConnection().getRemotePort());
this.serverAddress.set(getConnection().getRemoteHost());
messages.addMessage(new Message(Message.MessageType.INFO,sender,reciever,payload));
messages.addMessage(new Message(Message.MessageType.INFO, sender, receiver, payload));
System.out.println("CONFIRM: " + payload);
this.setState(CONNECTED);
} else if (state.get() == CONFIRM_DISCONNECT) {
messages.addMessage(new Message(Message.MessageType.INFO,sender,reciever,payload));
messages.addMessage(new Message(Message.MessageType.INFO, sender, receiver, payload));
System.out.println("CONFIRM: " + payload);
this.setState(DISCONNECTED);
} else {
@@ -143,42 +208,81 @@ public class ClientConnectionHandler extends ConnectionHandler implements Runnab
}
}
private void caseDisconnect(String sender, String reciever, String 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) {
System.out.println("DISCONNECT: Already in disconnected: " + payload);
return;
}
messages.addMessage(new Message(Message.MessageType.INFO,sender,reciever,payload));
messages.addMessage(new Message(Message.MessageType.INFO, sender, receiver, payload));
System.out.println("DISCONNECT: " + payload);
this.setState(DISCONNECTED);
}
private void caseMessage(String sender, String reciever, String payload) {
/**
* 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);
return;
}
messages.addMessage(new Message(Message.MessageType.MESSAGE,sender,reciever,payload));
System.out.println("MESSAGE: From " + sender + " to " + reciever + ": "+ payload);
messages.addMessage(new Message(Message.MessageType.MESSAGE, sender, receiver, payload));
System.out.println("MESSAGE: From " + sender + " to " + receiver + ": " + payload);
}
private void caseError(String sender, String reciever, String payload) {
messages.addMessage(new Message(Message.MessageType.ERROR,sender,reciever,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));
System.out.println("ERROR: " + payload);
}
/**
* 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);
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);
if (state.get() != NEW && state.get() != CONNECTED)
throw new ChatProtocolException("Illegal state for disconnect: " + state);
this.sendData(userName.get(), USER_NONE, getDataTypeDisconnect(), 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);
@@ -5,37 +5,63 @@ import javafx.beans.property.SimpleBooleanProperty;
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 SimpleBooleanProperty changed = new SimpleBooleanProperty(false);
private final SimpleBooleanProperty changed = new SimpleBooleanProperty(false);
/**
* Adds a new message to ArrayList and also informs Listener.
* @param message that should be added
*/
public void addMessage(Message message) {
messages.add(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 void clear() {
messages = new ArrayList<>();
changed.set(!changed.get());
}
public SimpleBooleanProperty getChangedProperty() { return changed; }
/**
* Getter Method to check the current value of SimpleBooleanProperty changed.
*
* @return the current value of changed
*/
public SimpleBooleanProperty getChangedProperty() {
return changed;
}
}
@@ -6,15 +6,32 @@ 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 ClientMessageList clientMessageList = new ClientMessageList();
private ClientConnectionHandler connectionHandler = new ClientConnectionHandler(clientMessageList);
private final ClientMessageList clientMessageList = new ClientMessageList();
private final ClientConnectionHandler connectionHandler = new ClientConnectionHandler(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"));
@@ -1,19 +1,20 @@
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 MessageType type;
private String sender;
private String receiver;
private String text;
private final MessageType type;
private final String sender;
private final String receiver;
private final 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 reciever 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 receiver will be null)
* @param sender The User who has sent the message.
* @param receiver The User who should recieve the message.
* @param receiver The User who should receive the message.
* @param text The Text of the message.
*/
public Message(MessageType type, String sender, String receiver, String text) {
@@ -25,8 +26,9 @@ public class Message {
/**
* Checks if the Filter String is contained in one of the data fields sender, receiver or text
*
* @param filter The Filter String
* @return true if it the Filter String is contained in a datafield.
* @return true if it is the Filter String is contained in a data field.
*/
public boolean matchesFilter(String filter) {
return (sender != null && sender.contains(filter)) ||
@@ -49,7 +51,7 @@ public class Message {
}
/**
* @return The Reciever who recieves the Message.
* @return The Receiver who receives the Message.
*/
public String getReceiver() {
return receiver;
@@ -63,7 +65,7 @@ public class Message {
}
/**
* Enummeration of Message Types.
* Enumeration of Message Types.
*/
public enum MessageType {
INFO, MESSAGE, ERROR;
@@ -12,7 +12,9 @@
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>
<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">
<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">
<top>
<VBox BorderPane.alignment="CENTER">
<children>
@@ -31,20 +33,25 @@
</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>
@@ -64,7 +71,8 @@
<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>
@@ -29,7 +29,6 @@ public abstract class ConnectionHandler {
}
/**
*
* @return {@link ConnectionHandler#DATA_TYPE_CONNECT}
*/
public static String getDataTypeConnect() {
@@ -37,7 +36,6 @@ public abstract class ConnectionHandler {
}
/**
*
* @return {@link ConnectionHandler#DATA_TYPE_CONFIRM}
*/
public static String getDataTypeConfirm() {
@@ -45,7 +43,6 @@ public abstract class ConnectionHandler {
}
/**
*
* @return {@link ConnectionHandler#DATA_TYPE_DISCONNECT}
*/
public static String getDataTypeDisconnect() {
@@ -53,7 +50,6 @@ public abstract class ConnectionHandler {
}
/**
*
* @return {@link ConnectionHandler#DATA_TYPE_MESSAGE
*/
public static String getDataTypeMessage() {
@@ -61,7 +57,6 @@ public abstract class ConnectionHandler {
}
/**
*
* @return {@link ConnectionHandler#DATA_TYPE_ERROR}
*/
public static String getDataTypeError() {
@@ -69,7 +64,6 @@ public abstract class ConnectionHandler {
}
/**
*
* @return {@link NetworkHandler.NetworkConnection}
*/
public NetworkHandler.NetworkConnection<String> getConnection() {
@@ -78,6 +72,7 @@ public abstract class ConnectionHandler {
/**
* 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) {
@@ -85,24 +80,27 @@ public abstract class ConnectionHandler {
}
/**
* This method reads the data when a ConnectionHandler recieves it. It tries to read out the sender, reciever, type and payload.
* 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 reciever for 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 reciever, StringBuilder type, StringBuilder payload) throws ChatProtocolException {
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()) {
reciever.append(scanner.nextLine());
receiver.append(scanner.nextLine());
} else {
throw new ChatProtocolException("No Reciever found");
}
@@ -118,6 +116,7 @@ public abstract class ConnectionHandler {
/**
* 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
@@ -125,13 +124,10 @@ public abstract class ConnectionHandler {
*/
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();
String data = sender + "\n" +
receiver + "\n" +
type + "\n" +
payload + "\n";
try {
connection.send(data);
} catch (SocketException e) {
@@ -1,14 +1,12 @@
package ch.zhaw.pm2.multichat.server;
import ch.zhaw.pm2.multichat.protocol.ConnectionHandler;
import ch.zhaw.pm2.multichat.protocol.NetworkHandler;
import java.io.IOException;
import java.net.SocketException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* This Class represents a Server. The user can start the programm with the port number as a argument.
@@ -16,17 +14,32 @@ import java.util.concurrent.locks.ReentrantLock;
* 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 conections will be atached to a Connectionhandler: {@link ServerConnectionHandler} and placed in a Map containing all active connections {@link Server#connections}
*
* 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 NetworkHandler.NetworkServer<String> networkServer;
private final NetworkHandler.NetworkServer<String> networkServer;
// Connection registry
private Map<String,ServerConnectionHandler> connections = new HashMap<>();
private final 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 {
@@ -65,30 +78,16 @@ public class Server {
}
}
/**
* 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());
}
/**
* 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.
*/
private void start() {
ReentrantLock mutex = new ReentrantLock();
Condition nameComplete = mutex.newCondition();
System.out.println("Server started.");
try {
while (true) {
NetworkHandler.NetworkConnection<String> connection = networkServer.waitForConnection();
ServerConnectionHandler connectionHandler = new ServerConnectionHandler(connection, connections, mutex, nameComplete);
ServerConnectionHandler connectionHandler = new ServerConnectionHandler(connection, connections);
new Thread(connectionHandler).start();
}
} catch (SocketException e) {
@@ -2,7 +2,9 @@ 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;
@@ -12,44 +14,39 @@ import java.util.Map;
import java.util.Objects;
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* 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()}
*
* Processes Messages send from a client by:
* 1. Evaluating the reciever by differentiating between broadcast or unicast.
* <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 {
private static final AtomicInteger connectionCounter = new AtomicInteger(0);
private final int connectionId = connectionCounter.incrementAndGet();
private final Map<String, ServerConnectionHandler> connectionRegistry;
private ReentrantLock mutex;
private Condition nameComplete;
private String userName = "Anonymous-" + connectionId;
private State state = NEW;
@@ -62,41 +59,24 @@ public class ServerConnectionHandler extends ConnectionHandler implements Runnab
}
/**
* Constructor to intitialize the connection
* @param connection representing the socket connection between server and clinet
* 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
* @param mutex to lock thread
* @param nameComplete condition to call threads
*/
public ServerConnectionHandler(NetworkHandler.NetworkConnection<String> connection,
Map<String,ServerConnectionHandler> registry, ReentrantLock mutex, Condition nameComplete) {
Map<String, ServerConnectionHandler> registry) {
super();
setConnection(connection);
Objects.requireNonNull(connection, "Connection must not be null");
Objects.requireNonNull(registry, "Registry must not be null");
this.connectionRegistry = registry;
this.mutex = mutex;
this.nameComplete = nameComplete;
}
/**
*
* @return the username of the connected client
*/
public String getUserName() {
return this.userName;
}
/**
*
* @return state of the connection. Poosible states are see {@link ch.zhaw.pm2.multichat.protocol.ConnectionHandler.State}
*/
public State getState() {
return state;
}
/**
* This methods runs in a whileloop as long as the socket between server and client is available
* 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() {
@@ -107,7 +87,7 @@ public class ServerConnectionHandler extends ConnectionHandler implements Runnab
String data = getConnection().receive();
processData(data);
}
System.out.println("Stopped recieving data");
System.out.println("Stopped receiving data");
} catch (SocketException e) {
System.out.println("Connection terminated locally");
connectionRegistry.remove(userName);
@@ -145,24 +125,25 @@ public class ServerConnectionHandler extends ConnectionHandler implements Runnab
}
/**
* This method gets called when socket recieves data. The method checks for the data type and reacts accordingly
* 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 recieve this kind of message. STDOUT informs about it.
* 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 recieved by the server
*
* @param data received by the server
*/
private void processData(String data) {
try {
Scanner scanner = new Scanner(data);
StringBuilder sender = new StringBuilder();
StringBuilder reciever = new StringBuilder();
StringBuilder receiver = new StringBuilder();
StringBuilder type = new StringBuilder();
StringBuilder payload = new StringBuilder();
super.processData(scanner,sender,reciever,type,payload);
super.processData(scanner, sender, receiver, type, payload);
// dispatch operation based on type parameter
if (type.toString().equals(getDataTypeConnect())) {
@@ -172,7 +153,7 @@ public class ServerConnectionHandler extends ConnectionHandler implements Runnab
} else if (type.toString().equals(getDataTypeDisconnect())) {
caseDisconnect();
} else if (type.toString().equals(getDataTypeMessage())) {
caseMessage(sender.toString(), reciever.toString(), type.toString(), payload.toString());
caseMessage(sender.toString(), receiver.toString(), type.toString(), payload.toString());
} else if (type.toString().equals(getDataTypeError())) {
System.err.println("Received error from client (" + sender + "): " + payload);
} else {
@@ -188,6 +169,7 @@ public class ServerConnectionHandler extends ConnectionHandler implements Runnab
/**
* 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
*/
@@ -205,7 +187,7 @@ public class ServerConnectionHandler extends ConnectionHandler implements Runnab
//if username valid
this.userName = sender;
connectionRegistry.put(userName, this);
sendData(USER_NONE, userName, getDataTypeConfirm(), "Registration successfull for " + userName);
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,
@@ -216,7 +198,8 @@ public class ServerConnectionHandler extends ConnectionHandler implements Runnab
/**
* 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 allready DISCONNECTED.
*
* @throws ChatProtocolException if state already DISCONNECTED.
*/
private void caseDisconnect() throws ChatProtocolException {
if (state == DISCONNECTED)
@@ -232,27 +215,28 @@ public class ServerConnectionHandler extends ConnectionHandler implements Runnab
/**
* This method is called by method {@link ServerConnectionHandler#processData(String)}
* Checks if broadcast or unicast. Sends data accordingly
*
* @param sender who sent data
* @param reciever to recieve 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 reciever, String type, String payload) throws ChatProtocolException{
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(reciever)) {
if (USER_ALL.equals(receiver)) {
for (ServerConnectionHandler handler : connectionRegistry.values()) {
handler.sendData(sender, reciever, type, payload);
handler.sendData(sender, receiver, type, payload);
}
} else {
ServerConnectionHandler handler = connectionRegistry.get(reciever);
ServerConnectionHandler handler = connectionRegistry.get(receiver);
if (handler != null) {
handler.sendData(sender, reciever, type, payload);
if(!reciever.equals(sender)){
sendData(sender, reciever, type, payload); //send message to sender if it's a direct message and sender is not receiver.
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: " + reciever);
this.sendData(USER_NONE, userName, getDataTypeError(), "Unknown User: " + receiver);
}
}
}