Java Doc and CodeStyle improvements

This commit is contained in:
Leonardo Brandenberger 2022-04-15 17:09:15 +02:00
parent 77b3057911
commit 5f6266c017
6 changed files with 110 additions and 75 deletions

View File

@ -17,21 +17,31 @@ import java.io.IOException;
import static ch.zhaw.pm2.multichat.protocol.ConnectionHandler.State.*; import static ch.zhaw.pm2.multichat.protocol.ConnectionHandler.State.*;
public class ChatWindowController { public class ChatWindowController {
private ClientConnectionHandler connectionHandler; private ClientConnectionHandler connectionHandler;
private ClientMessageList messages; private ClientMessageList messages;
private final WindowCloseHandler windowCloseHandler = new WindowCloseHandler(); private final WindowCloseHandler windowCloseHandler = new WindowCloseHandler();
@FXML private Pane rootPane; @FXML
@FXML private TextField serverAddressField; private Pane rootPane;
@FXML private TextField serverPortField; @FXML
@FXML private TextField userNameField; private TextField serverAddressField;
@FXML private TextField messageField; @FXML
@FXML private TextArea messageArea; private TextField serverPortField;
@FXML private Button connectButton; @FXML
@FXML private Button sendButton; private TextField userNameField;
@FXML private TextField filterValue; @FXML
private TextField messageField;
@FXML
private TextArea messageArea;
@FXML
private Button connectButton;
@FXML
private Button sendButton;
@FXML
private TextField filterValue;
public void setMessages(ClientMessageList messages) { public void setMessages(ClientMessageList messages) {
@ -39,7 +49,7 @@ public class ChatWindowController {
messageListener(); messageListener();
} }
public void setConnectionHandler(ClientConnectionHandler connectionHandler){ public void setConnectionHandler(ClientConnectionHandler connectionHandler) {
this.connectionHandler = connectionHandler; this.connectionHandler = connectionHandler;
startConnectionHandlerListener(); startConnectionHandlerListener();
serverAddressField.setText(connectionHandler.getServerAddressProperty().get()); serverAddressField.setText(connectionHandler.getServerAddressProperty().get());
@ -51,7 +61,7 @@ public class ChatWindowController {
} }
@FXML @FXML
private void toggleConnection () { private void toggleConnection() {
if (connectionHandler == null || connectionHandler.getStateProperty().get() != CONNECTED) { if (connectionHandler == null || connectionHandler.getStateProperty().get() != CONNECTED) {
connect(); connect();
} else { } else {
@ -59,16 +69,20 @@ public class ChatWindowController {
} }
} }
private void connect() { private void connect() {
try { try {
messages.clear(); // clear message list messages.clear(); // clear message list
startConnectionHandler(); startConnectionHandler();
connectionHandler.connect(); connectionHandler.connect();
} catch(ChatProtocolException | IOException e) { } catch (ChatProtocolException | IOException e) {
addError(e.getMessage()); addError(e.getMessage());
} }
} }
/**
* Initiates disconnecting of the connectionHandler, also checks if connectionHandler is avaible.
*/
private void disconnect() { private void disconnect() {
if (connectionHandler == null) { if (connectionHandler == null) {
addError("No connection handler"); addError("No connection handler");
@ -81,6 +95,9 @@ public class ChatWindowController {
} }
} }
/**
*
*/
@FXML @FXML
private void message() { private void message() {
String messageString = messageField.getText().strip(); String messageString = messageField.getText().strip();
@ -98,13 +115,13 @@ public class ChatWindowController {
} }
@FXML @FXML
private void applyFilter( ) { private void applyFilter() {
Platform.runLater(() -> this.messageArea.setText(messages.getFilteredMessages(filterValue.getText().strip()))); Platform.runLater(() -> this.messageArea.setText(messages.getFilteredMessages(filterValue.getText().strip())));
} }
private void startConnectionHandler() throws IOException { private void startConnectionHandler() throws IOException {
String userName = userNameField.getText(); String userName = userNameField.getText();
if(!userName.contains(" ")) { if (!userName.contains(" ")) {
String serverAddress = serverAddressField.getText(); String serverAddress = serverAddressField.getText();
int serverPort = Integer.parseInt(serverPortField.getText()); int serverPort = Integer.parseInt(serverPortField.getText());
connectionHandler.initialize(serverAddress, serverPort, userName); connectionHandler.initialize(serverAddress, serverPort, userName);
@ -128,7 +145,7 @@ public class ChatWindowController {
connectButton.setText((newState == CONNECTED || newState == CONFIRM_DISCONNECT) ? "Disconnect" : "Connect"); connectButton.setText((newState == CONNECTED || newState == CONFIRM_DISCONNECT) ? "Disconnect" : "Connect");
} }
}); });
if(newState == DISCONNECTED){ if (newState == DISCONNECTED) {
connectionHandler.stopReceiving(); connectionHandler.stopReceiving();
} }
} }
@ -200,6 +217,7 @@ public class ChatWindowController {
}); });
} }
private void messageListener() { private void messageListener() {
messages.getChangedProperty().addListener(new ChangeListener<Boolean>() { messages.getChangedProperty().addListener(new ChangeListener<Boolean>() {
@Override @Override

View File

@ -13,17 +13,18 @@ import java.net.SocketException;
import java.util.Scanner; import java.util.Scanner;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import static ch.zhaw.pm2.multichat.protocol.ConnectionHandler.State.*; import static ch.zhaw.pm2.multichat.protocol.ConnectionHandler.State.*;
public class ClientConnectionHandler extends ConnectionHandler implements Runnable { public class ClientConnectionHandler extends ConnectionHandler implements Runnable {
private final Pattern messagePattern = Pattern.compile( "^(?:@(\\S*))?\\s*(.*)$" ); private final Pattern messagePattern = Pattern.compile("^(?:@(\\S*))?\\s*(.*)$");
private SimpleStringProperty userName; private SimpleStringProperty userName;
private SimpleObjectProperty<State> state; private final SimpleObjectProperty<State> state;
private ClientMessageList messages; private final ClientMessageList messages;
private SimpleStringProperty serverAddress; private final SimpleStringProperty serverAddress;
private SimpleIntegerProperty serverPort; private final SimpleIntegerProperty serverPort;
public ClientConnectionHandler(ClientMessageList messages) { public ClientConnectionHandler(ClientMessageList messages) {
super(); super();
@ -39,24 +40,30 @@ public class ClientConnectionHandler extends ConnectionHandler implements Runnab
this.serverAddress.set(serverAddress); this.serverAddress.set(serverAddress);
this.serverPort.set(serverPort); this.serverPort.set(serverPort);
setConnection(NetworkHandler.openConnection(serverAddress, serverPort)); setConnection(NetworkHandler.openConnection(serverAddress, serverPort));
this.userName = new SimpleStringProperty((userName == null || userName.isBlank())? USER_NONE : userName); this.userName = new SimpleStringProperty((userName == null || userName.isBlank()) ? USER_NONE : userName);
} }
public SimpleStringProperty getServerAddressProperty() { return serverAddress; } public SimpleStringProperty getServerAddressProperty() {
return serverAddress;
}
public SimpleIntegerProperty getServerPortProperty() { return serverPort; } public SimpleIntegerProperty getServerPortProperty() {
return serverPort;
}
public SimpleObjectProperty<State> getStateProperty() { public SimpleObjectProperty<State> getStateProperty() {
return this.state; return this.state;
} }
public SimpleStringProperty getUserNameProperty() { return userName; } public SimpleStringProperty getUserNameProperty() {
return userName;
}
public void setState (State newState) { public void setState(State newState) {
state.set(newState); state.set(newState);
} }
public void run () { public void run() {
startReceiving(); startReceiving();
} }
@ -77,9 +84,9 @@ public class ClientConnectionHandler extends ConnectionHandler implements Runnab
System.out.println("Connection terminated by remote"); System.out.println("Connection terminated by remote");
this.setState(DISCONNECTED); this.setState(DISCONNECTED);
System.err.println("Unregistered because connection terminated" + e.getMessage()); System.err.println("Unregistered because connection terminated" + e.getMessage());
} catch(IOException e) { } catch (IOException e) {
System.err.println("Communication error" + e); System.err.println("Communication error" + e);
} catch(ClassNotFoundException e) { } catch (ClassNotFoundException e) {
System.err.println("Received object of unknown type" + e.getMessage()); System.err.println("Received object of unknown type" + e.getMessage());
} }
System.out.println("Stopped Connection Handler"); System.out.println("Stopped Connection Handler");
@ -131,11 +138,11 @@ public class ClientConnectionHandler extends ConnectionHandler implements Runnab
this.userName.set(reciever); this.userName.set(reciever);
this.serverPort.set(getConnection().getRemotePort()); this.serverPort.set(getConnection().getRemotePort());
this.serverAddress.set(getConnection().getRemoteHost()); this.serverAddress.set(getConnection().getRemoteHost());
messages.addMessage(new Message(Message.MessageType.INFO,sender,reciever,payload)); messages.addMessage(new Message(Message.MessageType.INFO, sender, reciever, payload));
System.out.println("CONFIRM: " + payload); System.out.println("CONFIRM: " + payload);
this.setState(CONNECTED); this.setState(CONNECTED);
} else if (state.get() == CONFIRM_DISCONNECT) { } else if (state.get() == CONFIRM_DISCONNECT) {
messages.addMessage(new Message(Message.MessageType.INFO,sender,reciever,payload)); messages.addMessage(new Message(Message.MessageType.INFO, sender, reciever, payload));
System.out.println("CONFIRM: " + payload); System.out.println("CONFIRM: " + payload);
this.setState(DISCONNECTED); this.setState(DISCONNECTED);
} else { } else {
@ -146,7 +153,7 @@ public class ClientConnectionHandler extends ConnectionHandler implements Runnab
System.out.println("DISCONNECT: Already in disconnected: " + payload); System.out.println("DISCONNECT: Already in disconnected: " + payload);
return; return;
} }
messages.addMessage(new Message(Message.MessageType.INFO,sender,reciever,payload)); messages.addMessage(new Message(Message.MessageType.INFO, sender, reciever, payload));
System.out.println("DISCONNECT: " + payload); System.out.println("DISCONNECT: " + payload);
this.setState(DISCONNECTED); this.setState(DISCONNECTED);
} else if (type.equals(getDataTypeMessage())) { } else if (type.equals(getDataTypeMessage())) {
@ -154,10 +161,10 @@ public class ClientConnectionHandler extends ConnectionHandler implements Runnab
System.out.println("MESSAGE: Illegal state " + state + " for message: " + payload); System.out.println("MESSAGE: Illegal state " + state + " for message: " + payload);
return; return;
} }
messages.addMessage(new Message(Message.MessageType.MESSAGE,sender,reciever,payload)); messages.addMessage(new Message(Message.MessageType.MESSAGE, sender, reciever, payload));
System.out.println("MESSAGE: From " + sender + " to " + reciever + ": "+ payload); System.out.println("MESSAGE: From " + sender + " to " + reciever + ": " + payload);
} else if (type.equals(getDataTypeError())) { } else if (type.equals(getDataTypeError())) {
messages.addMessage(new Message(Message.MessageType.ERROR,sender,reciever,payload)); messages.addMessage(new Message(Message.MessageType.ERROR, sender, reciever, payload));
System.out.println("ERROR: " + payload); System.out.println("ERROR: " + payload);
} else { } else {
System.out.println("Unknown data type received: " + type); System.out.println("Unknown data type received: " + type);
@ -172,10 +179,10 @@ public class ClientConnectionHandler extends ConnectionHandler implements Runnab
if (getConnection().isAvailable()) { if (getConnection().isAvailable()) {
new StringBuilder(); new StringBuilder();
String data = new StringBuilder() String data = new StringBuilder()
.append(sender+"\n") .append(sender + "\n")
.append(receiver+"\n") .append(receiver + "\n")
.append(type+"\n") .append(type + "\n")
.append(payload+"\n") .append(payload + "\n")
.toString(); .toString();
try { try {
getConnection().send(data); getConnection().send(data);
@ -183,7 +190,7 @@ public class ClientConnectionHandler extends ConnectionHandler implements Runnab
System.err.println("Connection closed: " + e.getMessage()); System.err.println("Connection closed: " + e.getMessage());
} catch (EOFException e) { } catch (EOFException e) {
System.out.println("Connection terminated by remote"); System.out.println("Connection terminated by remote");
} catch(IOException e) { } catch (IOException e) {
System.err.println("Communication error: " + e.getMessage()); System.err.println("Communication error: " + e.getMessage());
} }
} }
@ -191,13 +198,14 @@ public class ClientConnectionHandler extends ConnectionHandler implements Runnab
public void connect() throws ChatProtocolException { public void connect() throws ChatProtocolException {
if (state.get() != NEW) throw new ChatProtocolException("Illegal state for connect: " + state); if (state.get() != NEW) throw new ChatProtocolException("Illegal state for connect: " + state);
this.sendData(userName.get(), USER_NONE, getDataTypeConnect(),null); this.sendData(userName.get(), USER_NONE, getDataTypeConnect(), null);
this.setState(CONFIRM_CONNECT); this.setState(CONFIRM_CONNECT);
} }
public void disconnect() throws ChatProtocolException { public void disconnect() throws ChatProtocolException {
if (state.get() != NEW && state.get() != CONNECTED) throw new ChatProtocolException("Illegal state for disconnect: " + state); if (state.get() != NEW && state.get() != CONNECTED)
this.sendData(userName.get(), USER_NONE, getDataTypeDisconnect(),null); throw new ChatProtocolException("Illegal state for disconnect: " + state);
this.sendData(userName.get(), USER_NONE, getDataTypeDisconnect(), null);
this.setState(CONFIRM_DISCONNECT); this.setState(CONFIRM_DISCONNECT);
} }
@ -208,11 +216,11 @@ public class ClientConnectionHandler extends ConnectionHandler implements Runnab
if (matcher.find()) { if (matcher.find()) {
String receiver = matcher.group(1); String receiver = matcher.group(1);
String message = matcher.group(2); String message = matcher.group(2);
if(message.length() < 1){ if (message.length() < 1) {
return false; return false;
} }
if (receiver == null || receiver.isBlank()) receiver = ClientConnectionHandler.USER_ALL; if (receiver == null || receiver.isBlank()) receiver = ClientConnectionHandler.USER_ALL;
this.sendData(userName.get(), receiver, getDataTypeMessage(),message); this.sendData(userName.get(), receiver, getDataTypeMessage(), message);
return true; return true;
} else { } else {
return false; return false;

View File

@ -7,7 +7,7 @@ import java.util.List;
public class ClientMessageList { public class ClientMessageList {
private List<Message> messages = new ArrayList<>(); private List<Message> messages = new ArrayList<>();
private SimpleBooleanProperty changed = new SimpleBooleanProperty(false); private final SimpleBooleanProperty changed = new SimpleBooleanProperty(false);
public void addMessage(Message message) { public void addMessage(Message message) {
messages.add(message); messages.add(message);
@ -17,14 +17,15 @@ public class ClientMessageList {
public String getFilteredMessages(String filter) { public String getFilteredMessages(String filter) {
StringBuilder result = new StringBuilder(); StringBuilder result = new StringBuilder();
boolean showAll = filter == null || filter.isBlank(); boolean showAll = filter == null || filter.isBlank();
for(Message message : messages) { for (Message message : messages) {
if(showAll || message.matchesFilter(filter)) if (showAll || message.matchesFilter(filter)) {
{
switch (message.getType()) { 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 ERROR -> result.append(String.format("[ERROR] %s\n", message.getText()));
case INFO -> result.append(String.format("[INFO] %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()));
} }
} }
} }
@ -36,6 +37,8 @@ public class ClientMessageList {
changed.set(!changed.get()); changed.set(!changed.get());
} }
public SimpleBooleanProperty getChangedProperty() { return changed; } public SimpleBooleanProperty getChangedProperty() {
return changed;
}
} }

View File

@ -7,8 +7,8 @@ import javafx.scene.layout.Pane;
import javafx.stage.Stage; import javafx.stage.Stage;
public class ClientUI extends Application { public class ClientUI extends Application {
private ClientMessageList clientMessageList = new ClientMessageList(); private final ClientMessageList clientMessageList = new ClientMessageList();
private ClientConnectionHandler connectionHandler = new ClientConnectionHandler(clientMessageList); private final ClientConnectionHandler connectionHandler = new ClientConnectionHandler(clientMessageList);
@Override @Override
public void start(Stage primaryStage) { public void start(Stage primaryStage) {
@ -34,7 +34,7 @@ public class ClientUI extends Application {
primaryStage.setTitle("Multichat Client"); primaryStage.setTitle("Multichat Client");
primaryStage.show(); primaryStage.show();
primaryStage.setMinWidth(primaryStage.getWidth()); //use automatically computed size as Minimum Size. primaryStage.setMinWidth(primaryStage.getWidth()); //use automatically computed size as Minimum Size.
} catch(Exception e) { } catch (Exception e) {
System.err.println("Error starting up UI" + e.getMessage()); System.err.println("Error starting up UI" + e.getMessage());
} }
} }

View File

@ -1,16 +1,17 @@
package ch.zhaw.pm2.multichat.client; 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 { public class Message {
private MessageType type; private final MessageType type;
private String sender; private final String sender;
private String receiver; private final String receiver;
private String text; private final String text;
/** /**
* Constructor of Message. Needs all Information about a Message to save them. * 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 reciever will be null)
* @param sender The User who has sent the message. * @param sender The User who has sent the message.
* @param receiver The User who should recieve the message. * @param receiver The User who should recieve the message.
@ -25,10 +26,11 @@ public class Message {
/** /**
* Checks if the Filter String is contained in one of the datafields sender, receiver or text * Checks if the Filter String is contained in one of the datafields sender, receiver or text
*
* @param filter The Filter String * @param filter The Filter String
* @return true if it the Filter String is contained in a datafield. * @return true if it the Filter String is contained in a datafield.
*/ */
public boolean matchesFilter(String filter){ public boolean matchesFilter(String filter) {
return (sender != null && sender.contains(filter)) || return (sender != null && sender.contains(filter)) ||
(receiver != null && receiver.contains(filter)) || (receiver != null && receiver.contains(filter)) ||
(text != null && text.contains(filter)); (text != null && text.contains(filter));
@ -63,7 +65,7 @@ public class Message {
} }
/** /**
* Enummeration of Message Types. * Enumeration of Message Types.
*/ */
public enum MessageType { public enum MessageType {
INFO, MESSAGE, ERROR; INFO, MESSAGE, ERROR;

View File

@ -19,6 +19,10 @@ public class Server {
// Connection registry // Connection registry
private Map<String,ServerConnectionHandler> connections = new HashMap<>(); private Map<String,ServerConnectionHandler> connections = new HashMap<>();
/**
*
* @param args
*/
public static void main(String[] args) { public static void main(String[] args) {
// Parse arguments for server port. // Parse arguments for server port.
try { try {