added Handout

This commit is contained in:
romanschenk37
2022-04-02 14:15:01 +02:00
parent 94c220fbb9
commit 0886f896b2
19 changed files with 1790 additions and 0 deletions
+64
View File
@@ -0,0 +1,64 @@
/*
* Gradle build configuration for specific lab module / exercise
*/
// enabled plugins
plugins {
// Support for Java
id 'java'
// Support for Java applications
id 'application'
// Support for JavaFX
id 'org.openjfx.javafxplugin' version '0.0.11'
}
// Project/Module information
description = 'Uebung Multichat Client Application'
group = 'ch.zhaw.pm2'
version = '2022.1'
// Dependency configuration
repositories {
mavenCentral()
}
dependencies {
// dependency to the protocol library
implementation project(':protocol')
// JUnit Jupiter dependencies
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.+'
testImplementation 'org.junit.jupiter:junit-jupiter-params:5.+'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.+'
}
// Configuration for Application plugin
application {
// Define the main class for the application.
mainClass = 'ch.zhaw.pm2.multichat.client.Client'
}
javafx {
version = '17.0.2'
modules = [ 'javafx.controls', 'javafx.fxml' ]
}
// Test task configuration
test {
// Use JUnit platform for unit tests
useJUnitPlatform()
}
// Java plugin configuration
java {
// By default the Java version of the gradle process is used as source/target version.
// This can be overridden, to ensure a specific version. Enable only if required.
sourceCompatibility = JavaVersion.VERSION_17 // ensure Java source code compatibility
// targetCompatibility = JavaVersion.VERSION_17 // version of the created byte-code
// Java compiler specific options
compileJava {
// source files should be UTF-8 encoded
options.encoding = 'UTF-8'
// for more options see https://docs.gradle.org/current/dsl/org.gradle.api.tasks.compile.CompileOptions.html
}
}
@@ -0,0 +1,218 @@
package ch.zhaw.pm2.multichat.client;
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.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
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.client.ClientConnectionHandler.State.*;
public class ChatWindowController {
private final Pattern messagePattern = Pattern.compile( "^(?:@(\\w*))?\\s*(.*)$" );
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
public void initialize() {
serverAddressField.setText(NetworkHandler.DEFAULT_ADDRESS.getCanonicalHostName());
serverPortField.setText(String.valueOf(NetworkHandler.DEFAULT_PORT));
stateChanged(NEW);
messages = new ClientMessageList(this);
}
private void applicationClose() {
connectionHandler.setState(DISCONNECTED);
}
@FXML
private void toggleConnection () {
if (connectionHandler == null || connectionHandler.getState() != CONNECTED) {
connect();
} else {
disconnect();
}
}
private void connect() {
try {
messages = new ClientMessageList(this); // clear message list
startConnectionHandler();
connectionHandler.connect();
} catch(ChatProtocolException | IOException e) {
writeError(e.getMessage());
}
}
private void disconnect() {
if (connectionHandler == null) {
writeError("No connection handler");
return;
}
try {
connectionHandler.disconnect();
} catch (ChatProtocolException e) {
writeError(e.getMessage());
}
}
@FXML
private void message() {
if (connectionHandler == null) {
writeError("No connection handler");
return;
}
String messageString = messageField.getText().strip();
Matcher matcher = messagePattern.matcher(messageString);
if (matcher.find()) {
String receiver = matcher.group(1);
String message = matcher.group(2);
if (receiver == null || receiver.isBlank()) receiver = ClientConnectionHandler.USER_ALL;
try {
connectionHandler.message(receiver, message);
} catch (ChatProtocolException e) {
writeError(e.getMessage());
}
} else {
writeError("Not a valid message format.");
}
}
@FXML
private void applyFilter( ) {
this.redrawMessageList();
}
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);
new Thread(connectionHandler).start();
// register window close handler
rootPane.getScene().getWindow().addEventHandler(WindowEvent.WINDOW_CLOSE_REQUEST, windowCloseHandler);
}
private void terminateConnectionHandler() {
// unregister window close handler
rootPane.getScene().getWindow().removeEventHandler(WindowEvent.WINDOW_CLOSE_REQUEST, windowCloseHandler);
if (connectionHandler != null) {
connectionHandler.stopReceiving();
connectionHandler = null;
}
}
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() {
connectButton.setText((newState == CONNECTED || newState == CONFIRM_DISCONNECT) ? "Disconnect" : "Connect");
}
});
if (newState == DISCONNECTED) {
terminateConnectionHandler();
}
}
public void setUserName(String userName) {
Platform.runLater(new Runnable() {
@Override
public void run() {
userNameField.setText(userName);
}
});
}
public void setServerAddress(String serverAddress) {
Platform.runLater(new Runnable() {
@Override
public void run() {
serverAddressField.setText(serverAddress);
}
});
}
public void setServerPort(int serverPort) {
Platform.runLater(new Runnable() {
@Override
public void run() {
serverPortField.setText(Integer.toString(serverPort));
}
});
}
public void addMessage(String sender, String receiver, String message) {
messages.addMessage(ClientMessageList.MessageType.MESSAGE, sender, receiver, message);
this.redrawMessageList();
}
public void addInfo(String message) {
messages.addMessage(ClientMessageList.MessageType.INFO, null, null, message);
this.redrawMessageList();
}
public void addError(String message) {
messages.addMessage(ClientMessageList.MessageType.ERROR, null, null, message);
this.redrawMessageList();
}
public void clearMessageArea() {
this.messageArea.clear();
}
private void redrawMessageList() {
Platform.runLater(() -> messages.writeFilteredMessages(filterValue.getText().strip()));
}
public void writeError(String message) {
this.messageArea.appendText(String.format("[ERROR] %s\n", message));
}
public void writeInfo(String message) {
this.messageArea.appendText(String.format("[INFO] %s\n", message));
}
public void writeMessage(String sender, String reciever, String message) {
this.messageArea.appendText(String.format("[%s -> %s] %s\n", sender, reciever, message));
}
class WindowCloseHandler implements EventHandler<WindowEvent> {
public void handle(WindowEvent event) {
applicationClose();
}
}
}
@@ -0,0 +1,14 @@
package ch.zhaw.pm2.multichat.client;
import javafx.application.Application;
public class Client {
public static void main(String[] args) {
// Start UI
System.out.println("Starting Client Application");
Application.launch(ClientUI.class, args);
System.out.println("Client Application ended");
}
}
@@ -0,0 +1,202 @@
package ch.zhaw.pm2.multichat.client;
import ch.zhaw.pm2.multichat.protocol.ChatProtocolException;
import ch.zhaw.pm2.multichat.protocol.NetworkHandler;
import java.io.EOFException;
import java.io.IOException;
import java.net.SocketException;
import java.util.Scanner;
import static ch.zhaw.pm2.multichat.client.ClientConnectionHandler.State.*;
public class ClientConnectionHandler implements Runnable {
private final NetworkHandler.NetworkConnection<String> connection;
private final ChatWindowController controller;
// 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 = "*";
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 State getState() {
return this.state;
}
public void setState (State newState) {
this.state = newState;
controller.stateChanged(newState);
}
public void run () {
startReceiving();
}
public void startReceiving() {
System.out.println("Starting Connection Handler");
try {
System.out.println("Start receiving data...");
while (connection.isAvailable()) {
String data = connection.receive();
processData(data);
}
System.out.println("Stopped recieving data");
} catch (SocketException e) {
System.out.println("Connection terminated locally");
this.setState(DISCONNECTED);
System.err.println("Unregistered because connection terminated" + e.getMessage());
} catch (EOFException e) {
System.out.println("Connection terminated by remote");
this.setState(DISCONNECTED);
System.err.println("Unregistered because connection terminated" + e.getMessage());
} catch(IOException e) {
System.err.println("Communication error" + e);
} catch(ClassNotFoundException e) {
System.err.println("Received object of unknown type" + e.getMessage());
}
System.out.println("Stopped Connection Handler");
}
public void stopReceiving() {
System.out.println("Closing Connection Handler to Server");
try {
System.out.println("Stop receiving data...");
connection.close();
System.out.println("Stopped receiving data.");
} catch (IOException e) {
System.err.println("Failed to close connection." + e.getMessage());
}
System.out.println("Closed Connection Handler to Server");
}
private void processData(String data) {
try {
// parse data content
Scanner scanner = new Scanner(data);
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.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);
System.out.println("CONFIRM: " + payload);
this.setState(CONNECTED);
} else if (state == CONFIRM_DISCONNECT) {
controller.addInfo(payload);
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) {
System.out.println("DISCONNECT: Already in disconnected: " + payload);
return;
}
controller.addInfo(payload);
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);
return;
}
controller.addMessage(sender, reciever, payload);
System.out.println("MESSAGE: From " + sender + " to " + reciever + ": "+ payload);
} else if (type.equals(DATA_TYPE_ERROR)) {
controller.addError(payload);
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());
}
}
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());
}
}
}
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);
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);
this.setState(CONFIRM_DISCONNECT);
}
public void message(String receiver, String message) throws ChatProtocolException {
if (state != CONNECTED) throw new ChatProtocolException("Illegal state for message: " + state);
this.sendData(userName, receiver, DATA_TYPE_MESSAGE,message);
}
}
@@ -0,0 +1,51 @@
package ch.zhaw.pm2.multichat.client;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class ClientMessageList {
private final List<MessageType> typeList = new ArrayList<>();
private final List<String> senderList = new ArrayList<>();
private final List<String> receiverList = new ArrayList<>();
private final List<String> messageList = new ArrayList<>();
private final ChatWindowController gui;
public ClientMessageList(ChatWindowController gui) {
this.gui = gui;
}
public void addMessage(MessageType type, String sender, String receiver, String message) {
typeList.add(type);
senderList.add(sender);
receiverList.add(receiver);
messageList.add(message);
}
public void writeFilteredMessages(String filter) {
boolean showAll = filter == null || filter.isBlank();
gui.clearMessageArea();
for(int i=0; i<senderList.size(); i++) {
String sender = Objects.requireNonNullElse(senderList.get(i),"");
String receiver = Objects.requireNonNullElse(receiverList.get(i),"");
String message = Objects.requireNonNull(messageList.get(i), "");
if(showAll ||
sender.contains(filter) ||
receiver.contains(filter) ||
message.contains(filter))
{
switch (typeList.get(i)) {
case MESSAGE: gui.writeMessage(senderList.get(i), receiverList.get(i), messageList.get(i)); break;
case ERROR: gui.writeError(messageList.get(i)); break;
case INFO: gui.writeInfo(messageList.get(i)); break;
default: gui.writeError("Unexpected message type: " + typeList.get(i));
}
}
}
}
public enum MessageType {
INFO, MESSAGE, ERROR;
}
}
@@ -0,0 +1,34 @@
package ch.zhaw.pm2.multichat.client;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
public class ClientUI extends Application {
@Override
public void start(Stage primaryStage) {
chatWindow(primaryStage);
}
private void chatWindow(Stage primaryStage) {
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("ChatWindow.fxml"));
Pane rootPane = loader.load();
// fill in scene and stage setup
Scene scene = new Scene(rootPane);
//scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
// configure and show stage
primaryStage.setScene(scene);
primaryStage.setMinWidth(420);
primaryStage.setMinHeight(250);
primaryStage.setTitle("Multichat Client");
primaryStage.show();
} catch(Exception e) {
System.err.println("Error starting up UI" + e.getMessage());
}
}
}
@@ -0,0 +1,77 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<BorderPane fx:id="rootPane" minWidth="-Infinity" prefHeight="500.0" prefWidth="420.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="ch.zhaw.pm2.multichat.client.ChatWindowController">
<top>
<VBox BorderPane.alignment="CENTER">
<children>
<MenuBar>
<menus>
<Menu mnemonicParsing="false" text="Filter">
<items>
<MenuItem mnemonicParsing="false" text="press Enter">
<graphic>
<TextField fx:id="filterValue" onAction="#applyFilter" />
</graphic>
</MenuItem>
</items>
</Menu>
</menus>
</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">
<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" />
<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">
<HBox.margin>
<Insets left="5.0" />
</HBox.margin>
</Button>
</children>
<BorderPane.margin>
<Insets />
</BorderPane.margin>
<padding>
<Insets bottom="5.0" left="5.0" right="5.0" top="5.0" />
</padding>
</HBox>
</children>
</VBox>
</top>
<bottom>
<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">
<HBox.margin>
<Insets left="5.0" />
</HBox.margin>
</Button>
</children>
<padding>
<Insets bottom="5.0" left="5.0" right="5.0" top="5.0" />
</padding>
</HBox>
</bottom>
<center>
<TextArea fx:id="messageArea" editable="false">
<BorderPane.margin>
<Insets left="5.0" right="5.0" />
</BorderPane.margin>
</TextArea>
</center>
</BorderPane>