diff --git a/.gitignore b/.gitignore index b8f5ad3..b6d262c 100644 --- a/.gitignore +++ b/.gitignore @@ -38,4 +38,5 @@ build/ .DS_Store!/user.dat ### Bubbles ### -user.dat \ No newline at end of file +user.dat +messageLogs*.txt \ No newline at end of file diff --git a/saveMessage.txt b/saveMessage.txt index bc9d32d..6d04453 100644 --- a/saveMessage.txt +++ b/saveMessage.txt @@ -1,6 +1 @@ -Me: 1 -Me: 2 -Me: 3 -Me: 4 -Me: 5 -; +Me: 1Me: 2Me: 3Me: 4Me: 5;;; diff --git a/src/main/java/team/elrant/bubbles/gui/ChatViewApplication.java b/src/main/java/team/elrant/bubbles/gui/ChatViewApplication.java index 16bb676..1d5b629 100644 --- a/src/main/java/team/elrant/bubbles/gui/ChatViewApplication.java +++ b/src/main/java/team/elrant/bubbles/gui/ChatViewApplication.java @@ -8,11 +8,10 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.NotNull; -import org.jxmpp.jid.BareJid; +import org.jxmpp.jid.EntityBareJid; import org.jxmpp.jid.impl.JidCreate; import team.elrant.bubbles.xmpp.ConnectedUser; -import java.io.File; import java.util.Objects; /** @@ -55,21 +54,23 @@ public static void main(String[] args) { @Override public void start(@NotNull Stage stage) throws Exception { try { - @NotNull FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("views/ChatView.fxml")); + if (contactJid.isEmpty()) { + throw new IllegalArgumentException("Contact JID is empty."); + } + + logger.debug("Contact JID before parsing: {}", contactJid); + + EntityBareJid bareContactJid = JidCreate.entityBareFrom(contactJid); + + logger.debug("Parsed bare contact JID: {}", bareContactJid); + + FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("views/ChatView.fxml")); // Set custom controller factory - fxmlLoader.setControllerFactory(param -> { - try { - // Instantiate the controller with the required properties - BareJid bareContactJid = JidCreate.bareFrom(contactJid); - return new ChatViewController(connectedUser, bareContactJid); - } catch (Exception e) { - logger.error("Error creating ChatViewController: {}", e.getMessage()); - throw new RuntimeException(e); - } - }); + fxmlLoader.setControllerFactory(param -> new ChatViewController(connectedUser, bareContactJid)); + AnchorPane root = fxmlLoader.load(); - @NotNull Scene scene = new Scene(root, 800, 700); + Scene scene = new Scene(root, 800, 700); scene.getStylesheets().add(Objects.requireNonNull(getClass().getResource("styling/fluent-light.css")).toExternalForm()); stage.setTitle("Chat"); stage.setScene(scene); @@ -79,10 +80,9 @@ public void start(@NotNull Stage stage) throws Exception { stage.setOnCloseRequest(windowEvent -> { try { ChatViewController chatViewController = fxmlLoader.getController(); - chatViewController.saveMessage(); - } - catch (Exception e){ - logger.error("Error: {}",e.getMessage()); + chatViewController.saveToFile(); + } catch (Exception e) { + logger.error("Error: {}", e.getMessage()); } }); } catch (Exception e) { @@ -90,4 +90,5 @@ public void start(@NotNull Stage stage) throws Exception { throw e; } } -} \ No newline at end of file + +} diff --git a/src/main/java/team/elrant/bubbles/gui/ChatViewController.java b/src/main/java/team/elrant/bubbles/gui/ChatViewController.java index dfef953..638e6bb 100644 --- a/src/main/java/team/elrant/bubbles/gui/ChatViewController.java +++ b/src/main/java/team/elrant/bubbles/gui/ChatViewController.java @@ -1,21 +1,17 @@ package team.elrant.bubbles.gui; -import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextArea; import javafx.scene.input.KeyCode; -import javafx.scene.input.KeyEvent; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.NotNull; -import org.jxmpp.jid.BareJid; +import org.jxmpp.jid.EntityBareJid; import team.elrant.bubbles.xmpp.ConnectedUser; import java.io.*; -import java.security.Key; -import java.util.StringTokenizer; /** * The ChatViewController class controls the chat view functionality in the GUI. @@ -24,13 +20,17 @@ public class ChatViewController { private static final Logger logger = LogManager.getLogger(ChatViewController.class); private final @NotNull ConnectedUser connectedUser; - private final @NotNull BareJid bareContactJid; + private final @NotNull EntityBareJid bareContactJid; + @FXML private TextArea chatTextArea; + @FXML private TextArea messageTextArea; + @FXML private Button sendButton; + @FXML private Label failedSendMessageLabel; @@ -40,7 +40,7 @@ public class ChatViewController { * @param connectedUser The connected user instance. * @param bareContactJid The JID of the contact with whom the user is communicating. */ - public ChatViewController(@NotNull ConnectedUser connectedUser, @NotNull BareJid bareContactJid) { + public ChatViewController(@NotNull ConnectedUser connectedUser, @NotNull EntityBareJid bareContactJid) { this.connectedUser = connectedUser; this.bareContactJid = bareContactJid; } @@ -51,71 +51,79 @@ public ChatViewController(@NotNull ConnectedUser connectedUser, @NotNull BareJid */ @FXML protected void initialize() { - chatTextArea.setStyle("-fx-background-color: Black;"); - messageTextArea.setStyle("-fx-background-color: Black;"); - if(verifyFile() != 0){ + if (verifyFile() != 0) { readFromFile(); } connectedUser.addIncomingMessageListener(bareContactJid, this::updateChatDisplay); - messageTextArea.setOnKeyPressed(event ->{ - if(event.getCode() == KeyCode.ENTER) //when Enter is pressed, call sendMessage + messageTextArea.setOnKeyPressed(event -> { + if (event.getCode() == KeyCode.ENTER) sendMessage(); }); - sendButton.setOnKeyPressed(event -> sendMessage()); //call sendMessage when button is pressed - chatTextArea.setOnKeyPressed(event ->{ - if(event.getCode() == KeyCode.ENTER) //when Enter is pressed, call sendMessage + sendButton.setOnKeyPressed(event -> sendMessage()); + chatTextArea.setOnKeyPressed(event -> { + if (event.getCode() == KeyCode.ENTER) sendMessage(); }); messageTextArea.setWrapText(true); chatTextArea.setEditable(false); chatTextArea.setWrapText(true); - } - protected int verifyFile(){ - File file = new File("saveMessage.txt"); - return (int)file.length(); + /** + * Verifies if the message log file exists and returns its size. + * + * @return The size of the message log file, or 0 if the file does not exist. + */ + protected int verifyFile() { + File file = new File("messageLogs" + bareContactJid + ".txt"); + return (int) file.length(); } - protected void saveMessage(){ - try { - FileWriter f = new FileWriter("saveMessage.txt",false); - PrintWriter file = new PrintWriter(f); - file.println(chatTextArea.getText() + ";"); - f.flush(); - f.close(); - } - catch (IOException e){ - logger.error("Error To Save Message"); + /** + * Saves the current chat messages to a file. + */ + protected void saveToFile() { + try (PrintWriter file = new PrintWriter(new FileWriter("messageLogs" + bareContactJid + ".txt", false))) { + String[] lines = chatTextArea.getText().split("\\n"); + for (String line : lines) { + file.println(line); + } + } catch (IOException e) { + logger.error("Error saving messages: {}", e.getMessage()); } } - protected void readFromFile(){ //Read from file and add to chatAreaText - try { + + /** + * Reads chat messages from a file and appends them to the chat area. + */ + protected void readFromFile() { + try (BufferedReader file = new BufferedReader(new FileReader("messageLogs" + bareContactJid + ".txt"))) { String line; - FileReader f = new FileReader("saveMessage.txt"); - BufferedReader file = new BufferedReader(f); - StringTokenizer tokenizer; - String string = file.readLine(); - while (string != null){ - tokenizer = new StringTokenizer(string,";"); - line = "\n" + tokenizer.nextToken(); - chatTextArea.appendText(string); - string = file.readLine(); + while ((line = file.readLine()) != null) { + chatTextArea.appendText(line + "\n"); } - f.close(); - } - catch (IOException e){ - logger.error("Error To Read From File"); + } catch (IOException e) { + logger.error("Error reading from file: {}", e.getMessage()); } } + + /** + * Updates the chat display with the incoming message. + * + * @param message The incoming message to display. + */ + private void updateChatDisplay(@NotNull String message) { + chatTextArea.appendText("\n" + bareContactJid + ": " + message + "\n"); + } + /** * Sends a message to the contact and updates the chat display. */ @FXML protected void sendMessage() { try { - String message = messageTextArea.getText().trim(); // Trim to remove leading/trailing whitespace - if (!message.isEmpty()) { // Check if the message is not empty + String message = messageTextArea.getText().trim(); + if (!message.isEmpty()) { connectedUser.sendMessage(bareContactJid, message); chatTextArea.appendText("Me: " + message + "\n"); messageTextArea.clear(); @@ -127,13 +135,4 @@ protected void sendMessage() { logger.error("Error sending message: {}", e.getMessage()); } } - - /** - * Updates the chat display with the incoming message. - * - * @param message The incoming message to display. - */ - private void updateChatDisplay(@NotNull String message) { - chatTextArea.appendText("\n" + bareContactJid + ": " + message + "\n"); - } } diff --git a/src/main/java/team/elrant/bubbles/gui/LoginController.java b/src/main/java/team/elrant/bubbles/gui/LoginController.java index f144db8..050e92c 100644 --- a/src/main/java/team/elrant/bubbles/gui/LoginController.java +++ b/src/main/java/team/elrant/bubbles/gui/LoginController.java @@ -8,9 +8,6 @@ import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.Nullable; import team.elrant.bubbles.xmpp.ConnectedUser; -import team.elrant.bubbles.xmpp.User; - -import java.util.Set; public class LoginController { private static final Logger logger = LogManager.getLogger(LoginController.class); @@ -33,8 +30,10 @@ public class LoginController { private CheckBox seePasswordCheckbox; private @Nullable ConnectedUser connectedUser; - final String contact = "testuser"; - + /** + * Handles the submit button click event. + * Attempts to log in the user and open the main application view if successful. + */ @FXML protected void onSubmitButtonClick() { try { @@ -54,6 +53,10 @@ protected void onSubmitButtonClick() { } } + /** + * Handles the see password checkbox click event. + * Toggles the visibility of the password fields. + */ @FXML protected void onSeePasswordCheckBoxClick() { if (seePasswordCheckbox.isSelected()) { @@ -67,6 +70,10 @@ protected void onSeePasswordCheckBoxClick() { } } + /** + * Initializes the login view. + * Loads user information from file if available and sets event handlers. + */ @FXML public void initialize() { try { @@ -95,11 +102,17 @@ public void initialize() { }); } + /** + * Closes the login window. + */ private void closeLoginWindow() { Stage stage = (Stage) submitButton.getScene().getWindow(); stage.close(); } + /** + * Opens the main application view (SideView). + */ private void openSideView() { try { SideViewApplication sideViewApplication = new SideViewApplication(connectedUser); @@ -111,15 +124,4 @@ private void openSideView() { } } - - private void openChatWindow(User user) { - try { - if (connectedUser != null && connectedUser.isLoggedIn()) { - ChatViewApplication chatViewApplication = new ChatViewApplication(connectedUser, user.getUsername()); - chatViewApplication.start(new Stage()); - } - } catch (Exception e) { - logger.error("Error opening chat window: {}", e.getMessage()); - } - } } diff --git a/src/main/java/team/elrant/bubbles/gui/SideViewApplication.java b/src/main/java/team/elrant/bubbles/gui/SideViewApplication.java index ac26d37..3f4ed1f 100644 --- a/src/main/java/team/elrant/bubbles/gui/SideViewApplication.java +++ b/src/main/java/team/elrant/bubbles/gui/SideViewApplication.java @@ -12,41 +12,60 @@ import java.util.Objects; +/** + * The SideViewApplication class is responsible for launching the side view of the chat application GUI. + * It initializes the primary stage with the SideView.fxml layout and sets up the SideViewController. + */ public class SideViewApplication extends Application { private static final Logger logger = LogManager.getLogger(SideViewApplication.class); - private ConnectedUser connectedUser; + private final ConnectedUser connectedUser; + /** + * Constructs a SideViewApplication with the specified connected user. + * + * @param connectedUser The connected user object. + */ public SideViewApplication(ConnectedUser connectedUser) { this.connectedUser = connectedUser; } + /** + * The main method launches the JavaFX application. + * + * @param args The command-line arguments. + */ public static void main(String[] args) { launch(args); } /** - * The start method initializes the primary stage of the chat application. - * It loads the SideView.fxml layout and displays the stage. + * The start method initializes the primary stage of the side view application. + * It loads the SideView.fxml layout and sets up the SideViewController. * * @param stage The primary stage of the application. * @throws Exception If an error occurs during the initialization. */ @Override public void start(@NotNull Stage stage) throws Exception { - FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("views/SideView.fxml")); - AnchorPane root = fxmlLoader.load(); - - // Pass the connectedUser to the controller - SideViewController controller = fxmlLoader.getController(); - controller.setConnectedUser(connectedUser); - - Scene scene = new Scene(root, 320, 720); - scene.getStylesheets().add(Objects.requireNonNull(getClass().getResource("styling/fluent-light.css")).toExternalForm()); - stage.setTitle("Chat"); - stage.setScene(scene); - stage.centerOnScreen(); - stage.setResizable(false); - stage.show(); + try { + FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("views/SideView.fxml")); + AnchorPane root = fxmlLoader.load(); + + // Pass the connectedUser to the controller + SideViewController controller = fxmlLoader.getController(); + controller.setConnectedUser(connectedUser); + + Scene scene = new Scene(root, 320, 720); + scene.getStylesheets().add(Objects.requireNonNull(getClass().getResource("styling/fluent-light.css")).toExternalForm()); + stage.setTitle("Chat"); + stage.setScene(scene); + stage.centerOnScreen(); + stage.setResizable(false); + stage.show(); + } catch (Exception e) { + logger.error("Error starting SideViewApplication: {}", e.getMessage()); + throw e; + } } } diff --git a/src/main/java/team/elrant/bubbles/gui/SideViewController.java b/src/main/java/team/elrant/bubbles/gui/SideViewController.java index 299f124..b2a260e 100644 --- a/src/main/java/team/elrant/bubbles/gui/SideViewController.java +++ b/src/main/java/team/elrant/bubbles/gui/SideViewController.java @@ -2,11 +2,11 @@ import javafx.fxml.FXML; import javafx.scene.control.Label; -import javafx.scene.image.Image; -import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.Stage; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.jivesoftware.smack.roster.Roster; import org.jivesoftware.smack.roster.RosterEntry; import team.elrant.bubbles.xmpp.ConnectedUser; @@ -14,12 +14,9 @@ import java.util.Set; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - /** - * The SideViewController class controls the login functionality in the GUI. - * It handles ... + * The SideViewController class controls the user list functionality in the GUI. + * It handles displaying the list of online users and opening chat windows. */ public class SideViewController { private static final Logger logger = LogManager.getLogger(SideViewController.class); @@ -27,15 +24,23 @@ public class SideViewController { private VBox userList; private ConnectedUser connectedUser; - // Add setter for connectedUser + /** + * Sets the connected user for the side view controller. + * + * @param connectedUser The connected user to set. + */ public void setConnectedUser(ConnectedUser connectedUser) { this.connectedUser = connectedUser; } + /** + * Initializes the user list view. + * Populates the list with online users and adds event handlers to open chat windows. + */ @FXML public void initialize() { Roster roster = ConnectedUser.getRoster(); - Set rosterEntries = roster.getEntries(); + Set rosterEntries = roster.getEntries(); for (RosterEntry entry : rosterEntries) { String jid = entry.getJid().toString(); String[] parts = jid.split("@"); @@ -47,23 +52,24 @@ public void initialize() { // Create UI components HBox userItem = new HBox(); - // ImageView profilePic = new ImageView(new Image(user.getProfilePictureUrl())); - // profilePic.setFitHeight(50); - // profilePic.setFitWidth(50); Label userName = new Label(user.getUsername()); // Add event handler to open ChatPage - userName.setOnMouseClicked(event -> openChatPage(username)); + userName.setOnMouseClicked(event -> openChatPage(jid)); userItem.getChildren().addAll(userName); userList.getChildren().add(userItem); } } - // Method to open ChatPage - private void openChatPage(String username) { + /** + * Opens a chat window for the selected user. + * + * @param jid The JID of the user to open a chat window for. + */ + private void openChatPage(String jid) { try { - ChatViewApplication chatViewApplication = new ChatViewApplication(connectedUser, username); + ChatViewApplication chatViewApplication = new ChatViewApplication(connectedUser, jid); chatViewApplication.start(new Stage()); } catch (Exception e) { logger.error("Error opening chat window: {}", e.getMessage()); diff --git a/src/main/java/team/elrant/bubbles/xmpp/ChatListener.java b/src/main/java/team/elrant/bubbles/xmpp/ChatListener.java index 6b73825..c837e05 100644 --- a/src/main/java/team/elrant/bubbles/xmpp/ChatListener.java +++ b/src/main/java/team/elrant/bubbles/xmpp/ChatListener.java @@ -10,20 +10,32 @@ import java.util.function.Consumer; +/** + * The ChatListener class implements an incoming chat message listener. + * It is responsible for processing incoming chat messages and updating the chat display accordingly. + */ public class ChatListener implements IncomingChatMessageListener { private static final Logger logger = LogManager.getLogger(ChatListener.class); - public BareJid contactJid; - Consumer updateChatDisplay; + private final BareJid contactJid; + private final Consumer updateChatDisplay; - public ChatListener(BareJid contactJid, Consumer updateChatDisplay){ + /** + * Constructs a ChatListener with the specified contact JID and chat display updater. + * + * @param contactJid The JID of the contact with whom the chat is being conducted. + * @param updateChatDisplay A consumer function to update the chat display with incoming messages. + */ + public ChatListener(BareJid contactJid, Consumer updateChatDisplay) { this.contactJid = contactJid; this.updateChatDisplay = updateChatDisplay; } /** - * @param from The JID of the sender - * @param message The message contents - * @param chat The chat channel + * Processes incoming chat messages and updates the chat display if they are from the specified contact. + * + * @param from The JID of the sender. + * @param message The contents of the incoming message. + * @param chat The chat channel. */ @Override public void newIncomingMessage(EntityBareJid from, Message message, Chat chat) { diff --git a/src/main/java/team/elrant/bubbles/xmpp/ConnectedUser.java b/src/main/java/team/elrant/bubbles/xmpp/ConnectedUser.java index 83c2e94..935a68e 100644 --- a/src/main/java/team/elrant/bubbles/xmpp/ConnectedUser.java +++ b/src/main/java/team/elrant/bubbles/xmpp/ConnectedUser.java @@ -1,6 +1,5 @@ package team.elrant.bubbles.xmpp; -import javafx.fxml.FXML; import javafx.scene.control.PasswordField; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -12,12 +11,10 @@ import org.jivesoftware.smack.chat2.Chat; import org.jivesoftware.smack.chat2.ChatManager; import org.jivesoftware.smack.roster.Roster; -import org.jivesoftware.smack.roster.RosterEntry; import org.jivesoftware.smack.tcp.XMPPTCPConnection; import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration; import org.jxmpp.jid.BareJid; import org.jxmpp.jid.EntityBareJid; -import org.jxmpp.jid.impl.JidCreate; import java.io.*; import java.util.function.Consumer; @@ -28,8 +25,8 @@ */ public class ConnectedUser extends User { private static final Logger logger = LogManager.getLogger(ConnectedUser.class); - private final @Nullable String password; private static @Nullable Roster roster; + private final @NotNull String password; private @Nullable XMPPTCPConnection connection; private @Nullable ChatManager chatManager; @@ -50,14 +47,12 @@ public ConnectedUser(@NotNull String username, @NotNull String password, @NotNul * Load a new Connected user from a file. * * @param filename the filename - * * @throws IOException the io exception - * @throws ClassNotFoundException the class not found exception + * @throws ClassNotFoundException the class notfound exception */ public ConnectedUser(@NotNull String filename) throws IOException, ClassNotFoundException { super("uninit", "uninit"); //initialize after read file - try (FileInputStream fileIn = new FileInputStream(filename); - ObjectInputStream objectIn = new ObjectInputStream(fileIn)) { + try (FileInputStream fileIn = new FileInputStream(filename); ObjectInputStream objectIn = new ObjectInputStream(fileIn)) { ConnectedUser serializedUser = (ConnectedUser) objectIn.readObject(); logger.info("User information loaded from {}", filename); super.username = serializedUser.getUsername(); @@ -69,6 +64,20 @@ public ConnectedUser(@NotNull String filename) throws IOException, ClassNotFound } } + /** + * Retrieves the roster of the connected user. + * + * @return The roster of the connected user. + * @throws IllegalStateException if the roster is not initialized. + */ + public static @NotNull Roster getRoster() { + if (roster != null) { + return roster; + } else { + throw new IllegalStateException("Roster is not initialized."); + } + } + /** * Initializes the XMPP connection, logs in, sets up chat manager, and populates the roster. * After connecting, it sends a message to the test user. @@ -80,11 +89,7 @@ public ConnectedUser(@NotNull String filename) throws IOException, ClassNotFound * @throws IOException If an I/O error occurs. */ public void initializeConnection() throws SmackException, InterruptedException, XMPPException, IOException { - @NotNull XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder() - .setUsernameAndPassword(super.getUsername(), password) - .setXmppDomain(super.getServiceName()) - .setSecurityMode(ConnectionConfiguration.SecurityMode.required) - .build(); + @NotNull XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder().setUsernameAndPassword(super.getUsername(), password).setXmppDomain(super.getServiceName()).setSecurityMode(ConnectionConfiguration.SecurityMode.required).build(); connection = new XMPPTCPConnection(config); connection.connect(); @@ -96,41 +101,6 @@ public void initializeConnection() throws SmackException, InterruptedException, roster.reloadAndWait(); } - /** - * Adds a contact to the user's roster. - * - * @param contactJid The JID of the contact to add (user@service.name). - * @param nickname The user-defined nickname of the contact, defaults to the contact's username. - */ - public void addContact(@NotNull BareJid contactJid, @Nullable String nickname) { - try { - if (roster != null && !roster.contains(contactJid)) { - roster.createItemAndRequestSubscription(contactJid, nickname, null); - } - } catch (Exception e) { - logger.error("Error adding contact: {}", e.getMessage()); - } - } - - - /** - * Removes a contact from the user's roster. - * - * @param contactJid The JID of the contact to remove (user@service.name). - */ - public void removeContact(@NotNull String contactJid) { - try { - if (roster != null) { - RosterEntry entry = roster.getEntry(JidCreate.entityBareFrom(contactJid)); - if (entry != null) { - roster.removeEntry(entry); - } - } - } catch (Exception e) { - logger.error("Error removing contact: {}", e.getMessage()); - } - } - /** * Sends a message to a contact. * @@ -148,36 +118,19 @@ public void sendMessage(@NotNull BareJid contactJid, @NotNull String message) { } } - /** - * Accepts a subscription request from a contact. - * - * @param contactJid The JID of the contact to accept the subscription from (user@service.name). - * @param nickname The user-defined nickname of the contact, defaults to the contact's username. - */ - public void acceptSubscription(@NotNull BareJid contactJid, @Nullable String nickname) { - if (nickname == null || nickname.isEmpty()) { - nickname = contactJid.toString().split("@")[0]; - } - try { - if (roster != null) { - roster.createItemAndRequestSubscription(JidCreate.bareFrom(contactJid), nickname, null); - } - } catch (Exception e) { - logger.error("Error accepting subscription: {}", e.getMessage()); - } - } - /** * Saves the user information (excluding password) to a file. * - * @param filename The name of the file to save the user information to. + * @param filename The name of the file to save the user information to. + * @param savePassword Flag indicating whether to save the password in the file. */ public void saveUserToFile(@NotNull String filename, boolean savePassword) { File file = new File("user.dat"); - file.delete(); + if (file.delete()) { + logger.info("Old user information file deleted"); + } - try (@NotNull FileOutputStream fileOut = new FileOutputStream(filename); - @NotNull ObjectOutputStream objectOut = new ObjectOutputStream(fileOut)) { + try (@NotNull FileOutputStream fileOut = new FileOutputStream(filename); @NotNull ObjectOutputStream objectOut = new ObjectOutputStream(fileOut)) { if (savePassword) objectOut.writeObject(new ConnectedUser(this.getUsername(), this.getPassword(), this.getServiceName())); @@ -192,21 +145,7 @@ public void saveUserToFile(@NotNull String filename, boolean savePassword) { } } - /** - * Retrieves the roster of the connected user. - * - * @return The roster of the connected user. - * @throws IllegalStateException if the roster is not initialized. - */ - public static @NotNull Roster getRoster() { - if (roster != null) { - return roster; - } else { - throw new IllegalStateException("Roster is not initialized."); - } - } - - private String getPassword (){ + private @NotNull String getPassword() { return password; } @@ -216,7 +155,7 @@ private String getPassword (){ * * @param pwField the fxml password field */ - public void setPasswordField (PasswordField pwField) { + public void setPasswordField(PasswordField pwField) { pwField.setText(this.getPassword()); } @@ -226,10 +165,7 @@ public void setPasswordField (PasswordField pwField) { * @return true if the password in uninitialized, false if it isn't */ public boolean passwordUnInit() { - if (this.getPassword().equals("uninit")) - return true; - else - return false; + return this.getPassword().equals("uninit"); } /** @@ -245,17 +181,11 @@ public boolean isLoggedIn() { } } - /** - * Disconnects the user from the XMPP server. - */ - public void disconnect() { - if (connection != null) { - connection.disconnect(); - } - } - /** * Adds an incoming message listener to the chat manager. + * + * @param contactJid The JID of the contact for which to add the listener. + * @param updateChatDisplay The consumer to handle incoming messages. */ public void addIncomingMessageListener(BareJid contactJid, Consumer updateChatDisplay) { if (chatManager != null) { diff --git a/src/main/java/team/elrant/bubbles/xmpp/User.java b/src/main/java/team/elrant/bubbles/xmpp/User.java index 7b20388..2241793 100644 --- a/src/main/java/team/elrant/bubbles/xmpp/User.java +++ b/src/main/java/team/elrant/bubbles/xmpp/User.java @@ -24,7 +24,6 @@ public class User implements Serializable { * @param username The username of the user. * @param serviceName The service name of the XMPP server. */ - public User(@NotNull String username, @NotNull String serviceName) { this.username = username; this.serviceName = serviceName; @@ -38,8 +37,7 @@ public User(@NotNull String username, @NotNull String serviceName) { * @throws ClassNotFoundException If the class of a serialized object cannot be found. */ public User(@NotNull String filename) throws IOException, ClassNotFoundException { - try (FileInputStream fileIn = new FileInputStream(filename); - ObjectInputStream objectIn = new ObjectInputStream(fileIn)) { + try (FileInputStream fileIn = new FileInputStream(filename); ObjectInputStream objectIn = new ObjectInputStream(fileIn)) { User serializedUser = (User) objectIn.readObject(); logger.info("User information loaded from {}", filename); this.username = serializedUser.getUsername(); @@ -67,9 +65,4 @@ public User(@NotNull String filename) throws IOException, ClassNotFoundException public @NotNull String getServiceName() { return serviceName; } - - public String getProfilePictureUrl() { - // TODO Auto-generated method stub - throw new UnsupportedOperationException("Unimplemented method 'getProfilePictureUrl'"); - } }