Merge pull request #37 from informatik-ag-ngl/f/logger

Improved logging and code readability
This commit is contained in:
delvh 2019-12-07 11:31:18 +01:00 committed by GitHub
commit 381bc6b334
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 774 additions and 787 deletions

View File

@ -36,14 +36,14 @@ public class Client {
this.config = config; this.config = config;
sender = getUser(username); sender = getUser(username);
logger.info("ID: " + sender.getID()); logger.info("ID: " + sender.getID());
} }
private <T, R> R post(String uri, T body, Class<R> responseBodyClass) { private <T, R> R post(String uri, T body, Class<R> responseBodyClass) {
javax.ws.rs.client.Client client = ClientBuilder.newClient(); javax.ws.rs.client.Client client = ClientBuilder.newClient();
WebTarget target = client.target(uri); WebTarget target = client.target(uri);
Response response = target.request().post(Entity.entity(body, "application/xml")); Response response = target.request().post(Entity.entity(body, "application/xml"));
R responseBody = response.readEntity(responseBodyClass); R responseBody = response.readEntity(responseBodyClass);
response.close(); response.close();
client.close(); client.close();
@ -133,7 +133,9 @@ public class Client {
* Updating UserStatus of all users in LocalDB. (Server sends all users with * Updating UserStatus of all users in LocalDB. (Server sends all users with
* their updated UserStatus to the client.) <br> * their updated UserStatus to the client.) <br>
* *
* @param userId * @param userId the id of the {@link Client} who sends the {@link Sync}
* @param sync the {@link Sync} to send
* @return a sync
* @since Envoy v0.1-alpha * @since Envoy v0.1-alpha
*/ */
public Sync sendSync(long userId, Sync sync) { public Sync sendSync(long userId, Sync sync) {
@ -168,16 +170,16 @@ public class Client {
public User getRecipient() { return recipient; } public User getRecipient() { return recipient; }
/** /**
* Sets the recipient. * Sets the recipient.
*
* @param recipient - the recipient to set * @param recipient - the recipient to set
* @since Envoy v0.1-alpha * @since Envoy v0.1-alpha
*/ */
public void setRecipient(User recipient) { this.recipient = recipient; } public void setRecipient(User recipient) { this.recipient = recipient; }
/** /**
* @return true, if a recipient is selected * @return true, if a recipient is selected
* @since Envoy v0.1-alpha * @since Envoy v0.1-alpha
*/ */
public boolean hasRecipient() { return recipient != null; } public boolean hasRecipient() { return recipient != null; }
} }

View File

@ -114,7 +114,7 @@ public class Config {
* Changes the default local database. * Changes the default local database.
* Exclusively intended for development purposes. * Exclusively intended for development purposes.
* *
* @param the file containing the local database * @param localDB the file containing the local database
* @since Envoy v0.1-alpha * @since Envoy v0.1-alpha
**/ **/
public void setLocalDB(File localDB) { this.localDB = localDB; } public void setLocalDB(File localDB) { this.localDB = localDB; }

View File

@ -1,300 +1,295 @@
package envoy.client; package envoy.client;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.ObjectInputStream; import java.io.ObjectInputStream;
import java.io.ObjectOutputStream; import java.io.ObjectOutputStream;
import java.time.Instant; import java.time.Instant;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.logging.Logger; import java.util.logging.Logger;
import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.DatatypeFactory;
import envoy.client.event.EventBus; import envoy.client.event.EventBus;
import envoy.client.event.MessageCreationEvent; import envoy.client.event.MessageCreationEvent;
import envoy.exception.EnvoyException; import envoy.exception.EnvoyException;
import envoy.schema.Message; import envoy.schema.Message;
import envoy.schema.Message.Metadata.MessageState; import envoy.schema.Message.Metadata.MessageState;
import envoy.schema.ObjectFactory; import envoy.schema.ObjectFactory;
import envoy.schema.Sync; import envoy.schema.Sync;
import envoy.schema.User; import envoy.schema.User;
/** /**
* Project: <strong>envoy-client</strong><br> * Project: <strong>envoy-client</strong><br>
* File: <strong>LocalDB.java</strong><br> * File: <strong>LocalDB.java</strong><br>
* Created: <strong>27.10.2019</strong><br> * Created: <strong>27.10.2019</strong><br>
* *
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
* @author Maximilian K&auml;fer * @author Maximilian K&auml;fer
* @since Envoy v0.1-alpha * @since Envoy v0.1-alpha
*/ */
public class LocalDB { public class LocalDB {
private File localDB; private File localDB;
private User sender; private User sender;
private List<Chat> chats = new ArrayList<>(); private List<Chat> chats = new ArrayList<>();
private ObjectFactory objectFactory = new ObjectFactory(); private ObjectFactory objectFactory = new ObjectFactory();
private DatatypeFactory datatypeFactory; private DatatypeFactory datatypeFactory;
private Sync unreadMessagesSync = objectFactory.createSync(); private Sync unreadMessagesSync = objectFactory.createSync();
private Sync sync = objectFactory.createSync(); private Sync sync = objectFactory.createSync();
private Sync readMessages = objectFactory.createSync(); private Sync readMessages = objectFactory.createSync();
private static final Logger logger = Logger.getLogger(LocalDB.class.getSimpleName()); private static final Logger logger = Logger.getLogger(LocalDB.class.getSimpleName());
/** /**
* Constructs an empty local database. * Constructs an empty local database.
* *
* @param sender the user that is logged in with this client * @param sender the user that is logged in with this client
* @since Envoy v0.1-alpha * @since Envoy v0.1-alpha
*/ */
public LocalDB(User sender) { public LocalDB(User sender) {
this.sender = sender; this.sender = sender;
try { try {
datatypeFactory = DatatypeFactory.newInstance(); datatypeFactory = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException e) { } catch (DatatypeConfigurationException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
/** /**
* Initializes the local database and fills it with values * Initializes the local database and fills it with values
* if the user has already sent or received messages. * if the user has already sent or received messages.
* *
* @param localDBDir the directory where we wish to save/load the database from. * @param localDBDir the directory where we wish to save/load the database from.
* @throws EnvoyException if the directory selected is not an actual directory. * @throws EnvoyException if the directory selected is not an actual directory.
* @since Envoy v0.1-alpha * @since Envoy v0.1-alpha
*/ */
public void initializeDBFile(File localDBDir) throws EnvoyException { public void initializeDBFile(File localDBDir) throws EnvoyException {
if (localDBDir.exists() && !localDBDir.isDirectory()) if (localDBDir.exists() && !localDBDir.isDirectory())
throw new EnvoyException(String.format("LocalDBDir '%s' is not a directory!", localDBDir.getAbsolutePath())); throw new EnvoyException(String.format("LocalDBDir '%s' is not a directory!", localDBDir.getAbsolutePath()));
localDB = new File(localDBDir, sender.getID() + ".db"); localDB = new File(localDBDir, sender.getID() + ".db");
if (localDB.exists()) loadFromLocalDB(); if (localDB.exists()) loadFromLocalDB();
} }
/** /**
* Saves the database into a file for future use. * Saves the database into a file for future use.
* *
* @throws IOException if something went wrong during saving * @throws IOException if something went wrong during saving
* @since Envoy v0.1-alpha * @since Envoy v0.1-alpha
*/ */
public void saveToLocalDB() { public void saveToLocalDB() throws IOException {
try { localDB.getParentFile().mkdirs();
localDB.getParentFile().mkdirs(); localDB.createNewFile();
localDB.createNewFile(); try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(localDB))) {
} catch (IOException e) { out.writeObject(chats);
e.printStackTrace(); } catch (IOException ex) {
logger.warning("unable to save the messages"); throw ex;
} }
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(localDB))) { }
out.writeObject(chats);
} catch (IOException ex) { /**
ex.printStackTrace(); * Loads all chats saved by Envoy for the client user.
logger.warning("unable to save the messages"); *
} * @throws EnvoyException if something fails while loading.
} * @since Envoy v0.1-alpha
*/
/** @SuppressWarnings("unchecked")
* Loads all chats saved by Envoy for the client user. private void loadFromLocalDB() throws EnvoyException {
* try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(localDB))) {
* @throws EnvoyException if something fails while loading. Object obj = in.readObject();
* @since Envoy v0.1-alpha if (obj instanceof ArrayList<?>) chats = (ArrayList<Chat>) obj;
*/ } catch (ClassNotFoundException | IOException e) {
@SuppressWarnings("unchecked") throw new EnvoyException(e);
private void loadFromLocalDB() throws EnvoyException { }
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(localDB))) { }
Object obj = in.readObject();
if (obj instanceof ArrayList<?>) chats = (ArrayList<Chat>) obj; /**
} catch (ClassNotFoundException | IOException e) { * Creates a {@link Message} object serializable to XML.
throw new EnvoyException(e); *
} * @param textContent The content (text) of the message
} * @param recipient The recipient of the message
* @return prepared {@link Message} object
/** * @since Envoy v0.1-alpha
* Creates a {@link Message} object serializable to XML. */
* public Message createMessage(String textContent, User recipient) {
* @param textContent The content (text) of the message Message.Metadata metaData = objectFactory.createMessageMetadata();
* @param recipient The recipient of the message metaData.setSender(sender.getID());
* @return prepared {@link Message} object metaData.setRecipient(recipient.getID());
* @since Envoy v0.1-alpha metaData.setState(MessageState.WAITING);
*/ metaData.setDate(datatypeFactory.newXMLGregorianCalendar(Instant.now().toString()));
public Message createMessage(String textContent, User recipient) {
Message.Metadata metaData = objectFactory.createMessageMetadata(); Message.Content content = objectFactory.createMessageContent();
metaData.setSender(sender.getID()); content.setType("text");
metaData.setRecipient(recipient.getID()); content.setText(textContent);
metaData.setState(MessageState.WAITING);
metaData.setDate(datatypeFactory.newXMLGregorianCalendar(Instant.now().toString())); Message message = objectFactory.createMessage();
message.setMetadata(metaData);
Message.Content content = objectFactory.createMessageContent(); message.getContent().add(content);
content.setType("text");
content.setText(textContent); return message;
}
Message message = objectFactory.createMessage();
message.setMetadata(metaData); /**
message.getContent().add(content); * Creates a {@link Sync} object filled with the changes that occurred to the
* local database since the last synchronization.
return message; *
} * @param userId the ID of the user that is synchronized by this client
* @return {@link Sync} object filled with the current changes
/** * @since Envoy v0.1-alpha
* Creates a {@link Sync} object filled with the changes that occurred to the */
* local database since the last synchronization. public Sync fillSync(long userId) {
* addWaitingMessagesToSync();
* @param userId the ID of the user that is synchronized by this client
* @return {@link Sync} object filled with the current changes sync.getMessages().addAll(readMessages.getMessages());
*/ readMessages.getMessages().clear();
public Sync fillSync(long userId) {
addWaitingMessagesToSync(); logger.finest(String.format("Filled sync with %d messages.", sync.getMessages().size()));
return sync;
sync.getMessages().addAll(readMessages.getMessages()); }
readMessages.getMessages().clear();
/**
logger.info(String.format("Filled sync with %d messages.", sync.getMessages().size())); * Applies the changes carried by a {@link Sync} object to the local database
return sync; *
} * @param returnSync the {@link Sync} object to apply
* @since Envoy v0.1-alpha
/** */
* Applies the changes carried by a {@link Sync} object to the local database public void applySync(Sync returnSync) {
* for (int i = 0; i < returnSync.getMessages().size(); i++) {
* @param returnSync the {@link Sync} object to apply
*/ // The message has an ID
public void applySync(Sync returnSync) { if (returnSync.getMessages().get(i).getMetadata().getMessageId() != 0) {
for (int i = 0; i < returnSync.getMessages().size(); i++) {
// Messages are processes differently corresponding to their state
// The message has an ID switch (returnSync.getMessages().get(i).getMetadata().getState()) {
if (returnSync.getMessages().get(i).getMetadata().getMessageId() != 0) { case SENT:
// Update previously waiting and now sent messages that were assigned an ID by
// Messages are processes differently corresponding to their state // the server
switch (returnSync.getMessages().get(i).getMetadata().getState()) { sync.getMessages().get(i).getMetadata().setMessageId(returnSync.getMessages().get(i).getMetadata().getMessageId());
case SENT: sync.getMessages().get(i).getMetadata().setState(returnSync.getMessages().get(i).getMetadata().getState());
// Update previously waiting and now sent messages that were assigned an ID by break;
// the server case RECEIVED:
sync.getMessages().get(i).getMetadata().setMessageId(returnSync.getMessages().get(i).getMetadata().getMessageId()); if (returnSync.getMessages().get(i).getMetadata().getSender() != 0) {
sync.getMessages().get(i).getMetadata().setState(returnSync.getMessages().get(i).getMetadata().getState()); // these are the unread Messages from the server
break; unreadMessagesSync.getMessages().add(returnSync.getMessages().get(i));
case RECEIVED:
if (returnSync.getMessages().get(i).getMetadata().getSender() != 0) { // Create and dispatch message creation event
// these are the unread Messages from the server EventBus.getInstance().dispatch(new MessageCreationEvent(returnSync.getMessages().get(i)));
unreadMessagesSync.getMessages().add(returnSync.getMessages().get(i)); } else {
// Update Messages in localDB to state RECEIVED
// Create and dispatch message creation event for (Chat chat : getChats())
EventBus.getInstance().dispatch(new MessageCreationEvent(returnSync.getMessages().get(i))); if (chat.getRecipient().getID() == returnSync.getMessages().get(i).getMetadata().getRecipient())
} else { for (int j = 0; j < chat.getModel().getSize(); j++)
// Update Messages in localDB to state RECEIVED if (chat.getModel().get(j).getMetadata().getMessageId() == returnSync.getMessages()
for (Chat chat : getChats()) .get(i)
if (chat.getRecipient().getID() == returnSync.getMessages().get(i).getMetadata().getRecipient()) .getMetadata()
for (int j = 0; j < chat.getModel().getSize(); j++) .getMessageId())
if (chat.getModel().get(j).getMetadata().getMessageId() == returnSync.getMessages() chat.getModel().get(j).getMetadata().setState(returnSync.getMessages().get(i).getMetadata().getState());
.get(i) }
.getMetadata() break;
.getMessageId()) case READ:
chat.getModel().get(j).getMetadata().setState(returnSync.getMessages().get(i).getMetadata().getState()); // Update local Messages to state READ
} logger.info("Message with ID: " + returnSync.getMessages().get(i).getMetadata().getMessageId()
break; + "was initialized to be set to READ in localDB.");
case READ: for (Chat chat : getChats())
// Update local Messages to state READ if (chat.getRecipient().getID() == returnSync.getMessages().get(i).getMetadata().getRecipient()) {
logger.info("Message with ID: " + returnSync.getMessages().get(i).getMetadata().getMessageId() logger.info("Chat with: " + chat.getRecipient().getID() + "was selected.");
+ "was initialized to be set to READ in localDB."); for (int k = 0; k < chat.getModel().getSize(); k++)
for (Chat chat : getChats()) if (chat.getModel().get(k).getMetadata().getMessageId() == returnSync.getMessages()
if (chat.getRecipient().getID() == returnSync.getMessages().get(i).getMetadata().getRecipient()) { .get(i)
logger.info("Chat with: " + chat.getRecipient().getID() + "was selected."); .getMetadata()
for (int k = 0; k < chat.getModel().getSize(); k++) .getMessageId()) {
if (chat.getModel().get(k).getMetadata().getMessageId() == returnSync.getMessages() logger.info("Message with ID: " + chat.getModel().get(k).getMetadata().getMessageId() + "was selected.");
.get(i) chat.getModel().get(k).getMetadata().setState(returnSync.getMessages().get(i).getMetadata().getState());
.getMetadata() logger.info("Message State is now: " + chat.getModel().get(k).getMetadata().getState());
.getMessageId()) { }
logger.info("Message with ID: " + chat.getModel().get(k).getMetadata().getMessageId() + "was selected."); }
chat.getModel().get(k).getMetadata().setState(returnSync.getMessages().get(i).getMetadata().getState()); break;
logger.info("Message State is now: " + chat.getModel().get(k).getMetadata().getState()); }
} }
} }
break;
} // Updating UserStatus of all users in LocalDB
} for (User user : returnSync.getUsers())
} for (Chat chat : getChats())
if (user.getID() == chat.getRecipient().getID()) {
// Updating UserStatus of all users in LocalDB chat.getRecipient().setStatus(user.getStatus());
for (User user : returnSync.getUsers()) logger.info(chat.getRecipient().getStatus().toString());
for (Chat chat : getChats()) }
if (user.getID() == chat.getRecipient().getID()) {
chat.getRecipient().setStatus(user.getStatus()); sync.getMessages().clear();
logger.info(chat.getRecipient().getStatus().toString()); sync.getUsers().clear();
} }
sync.getMessages().clear(); /**
sync.getUsers().clear(); * Adds the unread messages returned from the server in the latest sync to the
} * right chats in the LocalDB.
*
/** * @since Envoy v0.1-alpha
* Adds the unread messages returned from the server in the latest sync to the */
* right chats in the LocalDB. public void addUnreadMessagesToLocalDB() {
* for (Message message : unreadMessagesSync.getMessages())
* @param localDB for (Chat chat : getChats())
* @since Envoy v0.1-alpha if (message.getMetadata().getSender() == chat.getRecipient().getID()) {
*/ chat.appendMessage(message);
public void addUnreadMessagesToLocalDB() { break;
for (Message message : unreadMessagesSync.getMessages()) }
for (Chat chat : getChats()) }
if (message.getMetadata().getSender() == chat.getRecipient().getID()) {
chat.appendMessage(message); /**
break; * Changes all messages with state {@code RECEIVED} of a specific chat to state
} * {@code READ}.
} * <br>
* Adds these messages to the {@code readMessages} {@link Sync} object.
/** *
* Changes all messages with state {@code RECEIVED} of a specific chat to state * @param currentChat the {@link Chat} that was just opened
* {@code READ}. * @since Envoy v0.1-alpha
* <br> */
* Adds these messages to the {@code readMessages} {@link Sync} object. public void setMessagesToRead(Chat currentChat) {
* for (int i = currentChat.getModel().size() - 1; i >= 0; --i)
* @param currentChat if (currentChat.getModel().get(i).getMetadata().getRecipient() != currentChat.getRecipient().getID())
* @since Envoy v0.1-alpha if (currentChat.getModel().get(i).getMetadata().getState() == MessageState.RECEIVED) {
*/ currentChat.getModel().get(i).getMetadata().setState(MessageState.READ);
public void setMessagesToRead(Chat currentChat) { readMessages.getMessages().add(currentChat.getModel().get(i));
for (int i = currentChat.getModel().size() - 1; i >= 0; --i) } else break;
if (currentChat.getModel().get(i).getMetadata().getRecipient() != currentChat.getRecipient().getID()) }
if (currentChat.getModel().get(i).getMetadata().getState() == MessageState.RECEIVED) {
currentChat.getModel().get(i).getMetadata().setState(MessageState.READ); /**
readMessages.getMessages().add(currentChat.getModel().get(i)); * Adds all messages with state {@code WAITING} from the {@link LocalDB} to the
} else break; * {@link Sync} object.
} *
* @since Envoy v0.1-alpha
/** */
* Adds all messages with state {@code WAITING} from the {@link LocalDB} to the private void addWaitingMessagesToSync() {
* {@link Sync} object. for (Chat chat : getChats())
* for (int i = 0; i < chat.getModel().size(); i++)
* @since Envoy v0.1-alpha if (chat.getModel().get(i).getMetadata().getState() == MessageState.WAITING) {
*/ logger.info("Got Waiting Message");
private void addWaitingMessagesToSync() { sync.getMessages().add(chat.getModel().get(i));
for (Chat chat : getChats()) }
for (int i = 0; i < chat.getModel().size(); i++) }
if (chat.getModel().get(i).getMetadata().getState() == MessageState.WAITING) {
logger.info("Got Waiting Message"); /**
sync.getMessages().add(chat.getModel().get(i)); * Clears the {@code unreadMessagesSync} {@link Sync} object.
} *
} * @since Envoy v0.1-alpha
*/
/** public void clearUnreadMessagesSync() { unreadMessagesSync.getMessages().clear(); }
* Clears the {@code unreadMessagesSync} {@link Sync} object.
* /**
* @since Envoy v0.1-alpha * @return all saved {@link Chat} objects that list the client user as the
*/ * sender
public void clearUnreadMessagesSync() { unreadMessagesSync.getMessages().clear(); } * @since Envoy v0.1-alpha
**/
/** public List<Chat> getChats() { return chats; }
* @return all saved {@link Chat} objects that list the client user as the
* sender /**
* @since Envoy v0.1-alpha * @return the {@link User} who initialized the local database
**/ * @since Envoy v0.1-alpha
public List<Chat> getChats() { return chats; } */
public User getUser() { return sender; }
/** }
* @return the {@link User} who initialized the local database
* @since Envoy v0.1-alpha
*/
public User getUser() { return sender; }
}

View File

@ -1,342 +1,349 @@
package envoy.client.ui; package envoy.client.ui;
import java.awt.Color; import java.awt.Color;
import java.awt.ComponentOrientation; import java.awt.ComponentOrientation;
import java.awt.Font; import java.awt.Font;
import java.awt.GridBagConstraints; import java.awt.GridBagConstraints;
import java.awt.GridBagLayout; import java.awt.GridBagLayout;
import java.awt.Insets; import java.awt.Insets;
import java.awt.event.KeyAdapter; import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent; import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter; import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent; import java.awt.event.WindowEvent;
import java.util.logging.Logger; import java.io.IOException;
import java.util.logging.Level;
import javax.swing.DefaultListModel; import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame; import javax.swing.DefaultListModel;
import javax.swing.JList; import javax.swing.JButton;
import javax.swing.JOptionPane; import javax.swing.JFrame;
import javax.swing.JPanel; import javax.swing.JList;
import javax.swing.JScrollPane; import javax.swing.JOptionPane;
import javax.swing.JTextArea; import javax.swing.JPanel;
import javax.swing.JTextPane; import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel; import javax.swing.JTextArea;
import javax.swing.SwingUtilities; import javax.swing.JTextPane;
import javax.swing.Timer; import javax.swing.ListSelectionModel;
import javax.swing.border.EmptyBorder; import javax.swing.SwingUtilities;
import javax.swing.Timer;
import envoy.client.Chat; import javax.swing.border.EmptyBorder;
import envoy.client.Client;
import envoy.client.Config; import envoy.client.Chat;
import envoy.client.LocalDB; import envoy.client.Client;
import envoy.schema.Message; import envoy.client.Config;
import envoy.schema.Sync; import envoy.client.LocalDB;
import envoy.schema.User; import envoy.schema.Message;
import envoy.schema.Sync;
/** import envoy.schema.User;
* Project: <strong>envoy-client</strong><br>
* File: <strong>ChatWindow.java</strong><br> /**
* Created: <strong>28 Sep 2019</strong><br> * Project: <strong>envoy-client</strong><br>
* * File: <strong>ChatWindow.java</strong><br>
* @author Kai S. K. Engelbart * Created: <strong>28 Sep 2019</strong><br>
* @author Maximilian K&auml;fer *
* @author Leon Hofmeister * @author Kai S. K. Engelbart
* @since Envoy v0.1-alpha * @author Maximilian K&auml;fer
*/ * @author Leon Hofmeister
public class ChatWindow extends JFrame { * @since Envoy v0.1-alpha
*/
private static final long serialVersionUID = 6865098428255463649L; public class ChatWindow extends JFrame {
private JPanel contentPane = new JPanel(); private static final long serialVersionUID = 6865098428255463649L;
private Client client; private JPanel contentPane = new JPanel();
private LocalDB localDB;
private Client client;
private JList<User> userList = new JList<>(); private LocalDB localDB;
private Chat currentChat;
private JList<User> userList = new JList<>();
private JTextArea messageEnterTextArea; private Chat currentChat;
private static final Logger logger = Logger.getLogger(ChatWindow.class.getSimpleName()); private JTextArea messageEnterTextArea;
public ChatWindow(Client client, LocalDB localDB) { private static final Logger logger = Logger.getLogger(ChatWindow.class.getSimpleName());
this.client = client;
this.localDB = localDB; public ChatWindow(Client client, LocalDB localDB) {
this.client = client;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.localDB = localDB;
setBounds(100, 100, 600, 800);
setTitle("Envoy"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null); setBounds(100, 100, 600, 800);
setTitle("Envoy");
// Save chats when window closes setLocationRelativeTo(null);
addWindowListener(new WindowAdapter() {
// Save chats when window closes
@Override addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) { localDB.saveToLocalDB(); }
}); @Override
public void windowClosing(WindowEvent evt) {
contentPane.setBackground(new Color(0, 0, 0)); try {
contentPane.setForeground(Color.white); localDB.saveToLocalDB();
contentPane.setBorder(new EmptyBorder(0, 5, 0, 0)); } catch (IOException e1) {
setContentPane(contentPane); e1.printStackTrace();
GridBagLayout gbl_contentPane = new GridBagLayout(); logger.log(Level.WARNING, "Unable to save the messages", e1);
gbl_contentPane.columnWidths = new int[] { 1, 1, 1 }; }
gbl_contentPane.rowHeights = new int[] { 1, 1, 1 }; }
gbl_contentPane.columnWeights = new double[] { 0.3, 1.0, 0.1 }; });
gbl_contentPane.rowWeights = new double[] { 0.05, 1.0, 0.07 };
contentPane.setLayout(gbl_contentPane); contentPane.setBackground(new Color(0, 0, 0));
contentPane.setForeground(Color.white);
JList<Message> messageList = new JList<>(); contentPane.setBorder(new EmptyBorder(0, 5, 0, 0));
messageList.setCellRenderer(new MessageListRenderer()); setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
messageList.setFocusTraversalKeysEnabled(false); gbl_contentPane.columnWidths = new int[] { 1, 1, 1 };
messageList.setSelectionForeground(new Color(255, 255, 255)); gbl_contentPane.rowHeights = new int[] { 1, 1, 1 };
messageList.setSelectionBackground(new Color(102, 0, 153)); gbl_contentPane.columnWeights = new double[] { 0.3, 1.0, 0.1 };
messageList.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT); gbl_contentPane.rowWeights = new double[] { 0.05, 1.0, 0.07 };
messageList.setForeground(new Color(255, 255, 255)); contentPane.setLayout(gbl_contentPane);
messageList.setBackground(new Color(51, 51, 51));
JList<Message> messageList = new JList<>();
DefaultListModel<Message> messageListModel = new DefaultListModel<>(); messageList.setCellRenderer(new MessageListRenderer());
messageList.setModel(messageListModel);
messageList.setFont(new Font("Arial", Font.PLAIN, 17)); messageList.setFocusTraversalKeysEnabled(false);
messageList.setFixedCellHeight(60); messageList.setSelectionForeground(new Color(255, 255, 255));
messageList.setBorder(new EmptyBorder(5, 5, 5, 5)); messageList.setSelectionBackground(new Color(102, 0, 153));
messageList.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
JScrollPane scrollPane = new JScrollPane(); messageList.setForeground(new Color(255, 255, 255));
scrollPane.setForeground(new Color(0, 0, 0)); messageList.setBackground(new Color(51, 51, 51));
scrollPane.setBackground(new Color(51, 51, 51));
scrollPane.setViewportView(messageList); DefaultListModel<Message> messageListModel = new DefaultListModel<>();
scrollPane.setBorder(null); messageList.setModel(messageListModel);
messageList.setFont(new Font("Arial", Font.PLAIN, 17));
GridBagConstraints gbc_scrollPane = new GridBagConstraints(); messageList.setFixedCellHeight(60);
gbc_scrollPane.fill = GridBagConstraints.BOTH; messageList.setBorder(new EmptyBorder(5, 5, 5, 5));
gbc_scrollPane.gridwidth = 2;
gbc_scrollPane.gridx = 1; JScrollPane scrollPane = new JScrollPane();
gbc_scrollPane.gridy = 1; scrollPane.setForeground(new Color(0, 0, 0));
scrollPane.setBackground(new Color(51, 51, 51));
gbc_scrollPane.insets = new Insets(0, 10, 10, 10); scrollPane.setViewportView(messageList);
scrollPane.setBorder(null);
contentPane.add(scrollPane, gbc_scrollPane);
GridBagConstraints gbc_scrollPane = new GridBagConstraints();
// Message enter field gbc_scrollPane.fill = GridBagConstraints.BOTH;
messageEnterTextArea = new JTextArea(); gbc_scrollPane.gridwidth = 2;
messageEnterTextArea.addKeyListener(new KeyAdapter() { gbc_scrollPane.gridx = 1;
gbc_scrollPane.gridy = 1;
@Override
public void keyReleased(KeyEvent e) { gbc_scrollPane.insets = new Insets(0, 10, 10, 10);
if (e.getKeyCode() == KeyEvent.VK_ENTER
&& ((SettingsScreen.enterToSend && e.getModifiersEx() == 0) || (e.getModifiersEx() == KeyEvent.CTRL_DOWN_MASK))) { contentPane.add(scrollPane, gbc_scrollPane);
postMessage(messageList); // Message enter field
} messageEnterTextArea = new JTextArea();
} messageEnterTextArea.addKeyListener(new KeyAdapter() {
});
// Checks for changed Message @Override
messageEnterTextArea.setWrapStyleWord(true); public void keyReleased(KeyEvent e) {
messageEnterTextArea.setCaretColor(new Color(255, 255, 255)); if (e.getKeyCode() == KeyEvent.VK_ENTER
messageEnterTextArea.setForeground(new Color(255, 255, 255)); && ((SettingsScreen.enterToSend && e.getModifiersEx() == 0) || (e.getModifiersEx() == KeyEvent.CTRL_DOWN_MASK)))
messageEnterTextArea.setBackground(new Color(51, 51, 51)); postMessage(messageList);
messageEnterTextArea.setLineWrap(true); }
messageEnterTextArea.setBorder(null); });
messageEnterTextArea.setFont(new Font("Arial", Font.PLAIN, 17)); // Checks for changed Message
messageEnterTextArea.setBorder(new EmptyBorder(5, 5, 5, 5)); messageEnterTextArea.setWrapStyleWord(true);
messageEnterTextArea.setCaretColor(new Color(255, 255, 255));
GridBagConstraints gbc_messageEnterTextfield = new GridBagConstraints(); messageEnterTextArea.setForeground(new Color(255, 255, 255));
gbc_messageEnterTextfield.fill = GridBagConstraints.BOTH; messageEnterTextArea.setBackground(new Color(51, 51, 51));
gbc_messageEnterTextfield.gridx = 1; messageEnterTextArea.setLineWrap(true);
gbc_messageEnterTextfield.gridy = 2; messageEnterTextArea.setBorder(null);
messageEnterTextArea.setFont(new Font("Arial", Font.PLAIN, 17));
gbc_messageEnterTextfield.insets = new Insets(10, 10, 10, 10); messageEnterTextArea.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.add(messageEnterTextArea, gbc_messageEnterTextfield); GridBagConstraints gbc_messageEnterTextfield = new GridBagConstraints();
gbc_messageEnterTextfield.fill = GridBagConstraints.BOTH;
// Post Button gbc_messageEnterTextfield.gridx = 1;
JButton postButton = new JButton("Post"); gbc_messageEnterTextfield.gridy = 2;
postButton.setForeground(new Color(255, 255, 255));
postButton.setBackground(new Color(102, 51, 153)); gbc_messageEnterTextfield.insets = new Insets(10, 10, 10, 10);
postButton.setBorderPainted(false);
contentPane.add(messageEnterTextArea, gbc_messageEnterTextfield);
GridBagConstraints gbc_moveSelectionPostButton = new GridBagConstraints();
// Post Button
gbc_moveSelectionPostButton.fill = GridBagConstraints.BOTH; JButton postButton = new JButton("Post");
gbc_moveSelectionPostButton.gridx = 2; postButton.setForeground(new Color(255, 255, 255));
gbc_moveSelectionPostButton.gridy = 2; postButton.setBackground(new Color(102, 51, 153));
postButton.setBorderPainted(false);
gbc_moveSelectionPostButton.insets = new Insets(10, 10, 10, 10);
GridBagConstraints gbc_moveSelectionPostButton = new GridBagConstraints();
postButton.addActionListener((evt) -> { postMessage(messageList); });
contentPane.add(postButton, gbc_moveSelectionPostButton); gbc_moveSelectionPostButton.fill = GridBagConstraints.BOTH;
gbc_moveSelectionPostButton.gridx = 2;
// Settings Button gbc_moveSelectionPostButton.gridy = 2;
JButton settingsButton = new JButton("Settings");
settingsButton.setForeground(new Color(255, 255, 255)); gbc_moveSelectionPostButton.insets = new Insets(10, 10, 10, 10);
settingsButton.setBackground(new Color(102, 51, 153));
settingsButton.setBorderPainted(false); postButton.addActionListener((evt) -> { postMessage(messageList); });
contentPane.add(postButton, gbc_moveSelectionPostButton);
GridBagConstraints gbc_moveSelectionSettingsButton = new GridBagConstraints();
// Settings Button
gbc_moveSelectionSettingsButton.fill = GridBagConstraints.BOTH; JButton settingsButton = new JButton("Settings");
gbc_moveSelectionSettingsButton.gridx = 2; settingsButton.setForeground(new Color(255, 255, 255));
gbc_moveSelectionSettingsButton.gridy = 0; settingsButton.setBackground(new Color(102, 51, 153));
settingsButton.setBorderPainted(false);
gbc_moveSelectionSettingsButton.insets = new Insets(10, 10, 10, 10);
GridBagConstraints gbc_moveSelectionSettingsButton = new GridBagConstraints();
settingsButton.addActionListener((evt) -> {
try { gbc_moveSelectionSettingsButton.fill = GridBagConstraints.BOTH;
SettingsScreen.open(localDB.getUser().getName()); gbc_moveSelectionSettingsButton.gridx = 2;
} catch (Exception e) { gbc_moveSelectionSettingsButton.gridy = 0;
SettingsScreen.open();
logger.warning("An error occured while opening the settings screen: " + e); gbc_moveSelectionSettingsButton.insets = new Insets(10, 10, 10, 10);
e.printStackTrace();
} settingsButton.addActionListener((evt) -> {
}); try {
contentPane.add(settingsButton, gbc_moveSelectionSettingsButton); SettingsScreen.open(localDB.getUser().getName());
} catch (Exception e) {
// Partner name display SettingsScreen.open();
JTextPane textPane = new JTextPane(); logger.log(Level.WARNING, "An error occured while opening the settings screen", e);
textPane.setBackground(new Color(0, 0, 0)); e.printStackTrace();
textPane.setForeground(new Color(255, 255, 255)); }
});
textPane.setFont(new Font("Arial", Font.PLAIN, 20)); contentPane.add(settingsButton, gbc_moveSelectionSettingsButton);
GridBagConstraints gbc_partnerName = new GridBagConstraints(); // Partner name display
gbc_partnerName.fill = GridBagConstraints.HORIZONTAL; JTextPane textPane = new JTextPane();
gbc_partnerName.gridx = 1; textPane.setBackground(new Color(0, 0, 0));
gbc_partnerName.gridy = 0; textPane.setForeground(new Color(255, 255, 255));
gbc_partnerName.insets = new Insets(0, 10, 0, 10); textPane.setFont(new Font("Arial", Font.PLAIN, 20));
contentPane.add(textPane, gbc_partnerName);
GridBagConstraints gbc_partnerName = new GridBagConstraints();
userList.setCellRenderer(new UserListRenderer()); gbc_partnerName.fill = GridBagConstraints.HORIZONTAL;
userList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); gbc_partnerName.gridx = 1;
userList.addListSelectionListener((listSelectionEvent) -> { gbc_partnerName.gridy = 0;
if (!listSelectionEvent.getValueIsAdjusting()) {
@SuppressWarnings("unchecked") gbc_partnerName.insets = new Insets(0, 10, 0, 10);
final JList<User> selectedUserList = (JList<User>) listSelectionEvent.getSource(); contentPane.add(textPane, gbc_partnerName);
final User user = selectedUserList.getSelectedValue();
client.setRecipient(user); userList.setCellRenderer(new UserListRenderer());
userList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
currentChat = localDB.getChats().stream().filter(chat -> chat.getRecipient().getID() == user.getID()).findFirst().get(); userList.addListSelectionListener((listSelectionEvent) -> {
if (!listSelectionEvent.getValueIsAdjusting()) {
// Set all unread messages in the chat to read @SuppressWarnings("unchecked")
readCurrentChat(); final JList<User> selectedUserList = (JList<User>) listSelectionEvent.getSource();
final User user = selectedUserList.getSelectedValue();
client.setRecipient(user); client.setRecipient(user);
textPane.setText(currentChat.getRecipient().getName()); currentChat = localDB.getChats().stream().filter(chat -> chat.getRecipient().getID() == user.getID()).findFirst().get();
messageList.setModel(currentChat.getModel()); // Set all unread messages in the chat to read
contentPane.revalidate(); readCurrentChat();
}
}); client.setRecipient(user);
userList.setSelectionForeground(new Color(255, 255, 255)); textPane.setText(currentChat.getRecipient().getName());
userList.setSelectionBackground(new Color(102, 0, 153));
userList.setForeground(new Color(255, 255, 255)); messageList.setModel(currentChat.getModel());
userList.setBackground(new Color(51, 51, 51)); contentPane.revalidate();
userList.setFont(new Font("Arial", Font.PLAIN, 17)); }
userList.setBorder(new EmptyBorder(5, 5, 5, 5)); });
GridBagConstraints gbc_userList = new GridBagConstraints(); userList.setSelectionForeground(new Color(255, 255, 255));
gbc_userList.fill = GridBagConstraints.VERTICAL; userList.setSelectionBackground(new Color(102, 0, 153));
gbc_userList.gridx = 0; userList.setForeground(new Color(255, 255, 255));
gbc_userList.gridy = 1; userList.setBackground(new Color(51, 51, 51));
gbc_userList.anchor = GridBagConstraints.PAGE_START; userList.setFont(new Font("Arial", Font.PLAIN, 17));
gbc_userList.insets = new Insets(0, 0, 10, 0); userList.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.add(userList, gbc_userList); GridBagConstraints gbc_userList = new GridBagConstraints();
contentPane.revalidate(); gbc_userList.fill = GridBagConstraints.VERTICAL;
gbc_userList.gridx = 0;
loadUsersAndChats(); gbc_userList.gridy = 1;
startSyncThread(Config.getInstance().getSyncTimeout()); gbc_userList.anchor = GridBagConstraints.PAGE_START;
gbc_userList.insets = new Insets(0, 0, 10, 0);
contentPane.revalidate();
} contentPane.add(userList, gbc_userList);
contentPane.revalidate();
private void postMessage(JList<Message> messageList) {
if (!client.hasRecipient()) { loadUsersAndChats();
JOptionPane.showMessageDialog(this, "Please select a recipient!", "Cannot send message", JOptionPane.INFORMATION_MESSAGE); startSyncThread(Config.getInstance().getSyncTimeout());
return;
} contentPane.revalidate();
}
if (!messageEnterTextArea.getText().isEmpty()) try {
private void postMessage(JList<Message> messageList) {
// Create and send message object if (!client.hasRecipient()) {
final Message message = localDB.createMessage(messageEnterTextArea.getText(), currentChat.getRecipient()); JOptionPane.showMessageDialog(this, "Please select a recipient!", "Cannot send message", JOptionPane.INFORMATION_MESSAGE);
currentChat.appendMessage(message); return;
messageList.setModel(currentChat.getModel()); }
// Clear text field if (!messageEnterTextArea.getText().isEmpty()) try {
messageEnterTextArea.setText("");
contentPane.revalidate(); // Create and send message object
} catch (Exception e) { final Message message = localDB.createMessage(messageEnterTextArea.getText(), currentChat.getRecipient());
JOptionPane.showMessageDialog(this, currentChat.appendMessage(message);
"An exception occured while sending a message. See the log for more details.", messageList.setModel(currentChat.getModel());
"Exception occured",
JOptionPane.ERROR_MESSAGE); // Clear text field
e.printStackTrace(); messageEnterTextArea.setText("");
} contentPane.revalidate();
} } catch (Exception e) {
JOptionPane.showMessageDialog(this,
/** "An exception occured while sending a message. See the log for more details.",
* Initializes the elements of the user list by downloading them from the "Exception occured",
* server. JOptionPane.ERROR_MESSAGE);
* e.printStackTrace();
* @since Envoy v0.1-alpha }
*/ }
private void loadUsersAndChats() {
new Thread(() -> { /**
Sync users = client.getUsersListXml(); * Initializes the elements of the user list by downloading them from the
DefaultListModel<User> userListModel = new DefaultListModel<>(); * server.
users.getUsers().forEach(user -> { *
userListModel.addElement(user); * @since Envoy v0.1-alpha
*/
// Check if user exists in local DB private void loadUsersAndChats() {
if (localDB.getChats().stream().filter(c -> c.getRecipient().getID() == user.getID()).count() == 0) new Thread(() -> {
localDB.getChats().add(new Chat(user)); Sync users = client.getUsersListXml();
}); DefaultListModel<User> userListModel = new DefaultListModel<>();
SwingUtilities.invokeLater(() -> userList.setModel(userListModel)); users.getUsers().forEach(user -> {
}).start(); userListModel.addElement(user);
}
// Check if user exists in local DB
/** if (localDB.getChats().stream().filter(c -> c.getRecipient().getID() == user.getID()).count() == 0)
* Updates the data model and the UI repeatedly after a certain amount of localDB.getChats().add(new Chat(user));
* time. });
* SwingUtilities.invokeLater(() -> userList.setModel(userListModel));
* @param timeout the amount of time that passes between two requests sent to }).start();
* the server }
* @since Envoy v0.1-alpha
*/ /**
private void startSyncThread(int timeout) { * Updates the data model and the UI repeatedly after a certain amount of
new Timer(timeout, (evt) -> { * time.
new Thread(() -> { *
* @param timeout the amount of time that passes between two requests sent to
// Synchronize * the server
localDB.applySync(client.sendSync(client.getSender().getID(), localDB.fillSync(client.getSender().getID()))); * @since Envoy v0.1-alpha
*/
// Process unread messages private void startSyncThread(int timeout) {
localDB.addUnreadMessagesToLocalDB(); new Timer(timeout, (evt) -> {
localDB.clearUnreadMessagesSync(); new Thread(() -> {
// Mark unread messages as read when they are in the current chat // Synchronize
readCurrentChat(); localDB.applySync(client.sendSync(client.getSender().getID(), localDB.fillSync(client.getSender().getID())));
// Update UI // Process unread messages
SwingUtilities.invokeLater(() -> { updateUserStates(); contentPane.revalidate(); contentPane.repaint(); }); localDB.addUnreadMessagesToLocalDB();
}).start(); localDB.clearUnreadMessagesSync();
}).start();
} // Mark unread messages as read when they are in the current chat
readCurrentChat();
private void updateUserStates() {
for (int i = 0; i < userList.getModel().getSize(); i++) // Update UI
for (int j = 0; j < localDB.getChats().size(); j++) SwingUtilities.invokeLater(() -> { updateUserStates(); contentPane.revalidate(); contentPane.repaint(); });
if (userList.getModel().getElementAt(i).getID() == localDB.getChats().get(j).getRecipient().getID()) }).start();
userList.getModel().getElementAt(i).setStatus(localDB.getChats().get(j).getRecipient().getStatus()); }).start();
} }
/** private void updateUserStates() {
* Marks messages in the current chat as {@code READ}. for (int i = 0; i < userList.getModel().getSize(); i++)
*/ for (int j = 0; j < localDB.getChats().size(); j++)
private void readCurrentChat() { if (currentChat != null) { localDB.setMessagesToRead(currentChat); } } if (userList.getModel().getElementAt(i).getID() == localDB.getChats().get(j).getRecipient().getID())
} userList.getModel().getElementAt(i).setStatus(localDB.getChats().get(j).getRecipient().getStatus());
}
/**
* Marks messages in the current chat as {@code READ}.
*/
private void readCurrentChat() { if (currentChat != null) { localDB.setMessagesToRead(currentChat); } }
}

View File

@ -1,54 +1,49 @@
package envoy.client.ui; package envoy.client.ui;
import java.awt.Component; import java.awt.Component;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import javax.swing.JLabel; import javax.swing.JLabel;
import javax.swing.JList; import javax.swing.JList;
import javax.swing.ListCellRenderer; import javax.swing.ListCellRenderer;
import envoy.schema.Message; import envoy.schema.Message;
/** /**
* Defines how a message is displayed.<br> * Defines how a message is displayed.<br>
* <br> * <br>
* *
* Project: <strong>envoy-client</strong><br> * Project: <strong>envoy-client</strong><br>
* File: <strong>UserListRenderer.java</strong><br> * File: <strong>UserListRenderer.java</strong><br>
* Created: <strong>19 Oct 2019</strong><br> * Created: <strong>19 Oct 2019</strong><br>
* *
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
* @author Maximilian K&auml;fer * @author Maximilian K&auml;fer
* @since Envoy v0.1-alpha * @since Envoy v0.1-alpha
*/ */
public class MessageListRenderer extends JLabel implements ListCellRenderer<Message> { public class MessageListRenderer extends JLabel implements ListCellRenderer<Message> {
private static final long serialVersionUID = 5164417379767181198L; private static final long serialVersionUID = 5164417379767181198L;
@Override @Override
public Component getListCellRendererComponent(JList<? extends Message> list, Message value, int index, public Component getListCellRendererComponent(JList<? extends Message> list, Message value, int index, boolean isSelected, boolean cellHasFocus) {
boolean isSelected, boolean cellHasFocus) { if (isSelected) {
if (isSelected) { setBackground(list.getSelectionBackground());
setBackground(list.getSelectionBackground()); setForeground(list.getSelectionForeground());
setForeground(list.getSelectionForeground()); } else {
} else { setBackground(list.getBackground());
setBackground(list.getBackground()); setForeground(list.getForeground());
setForeground(list.getForeground()); }
}
setOpaque(true);
setOpaque(true);
final String text = value.getContent().get(0).getText();
final String text = value.getContent().get(0).getText(); final String state = value.getMetadata().getState().toString();
final String state = value.getMetadata().getState().toString(); final String date = value.getMetadata().getDate() == null ? ""
final String date = value.getMetadata().getDate() == null ? "" : new SimpleDateFormat("dd.MM.yyyy HH:mm ").format(value.getMetadata().getDate().toGregorianCalendar().getTime());
: new SimpleDateFormat("dd.MM.yyyy HH:mm ")
.format(value.getMetadata().getDate().toGregorianCalendar().getTime()); setText(String
.format("<html><p style=\"color:#d2d235\"><b><small>%s</b></small><br><p style=\"color:white\">%s :%s</html>", date, text, state));
setText(String.format( return this;
"<html><p style=\"color:#d2d235\"><b><small>%s</b></small><br><p style=\"color:white\">%s :%s</html>", }
date,
text,
state));
return this;
}
} }

View File

@ -41,7 +41,6 @@ public class SettingsScreen extends JDialog {
* It personalises the screen more. * It personalises the screen more.
* *
* @param username The name of the User * @param username The name of the User
* @param Email The Email that is associated with that Account
* @since Envoy v0.1-alpha * @since Envoy v0.1-alpha
*/ */
public static void open(String username) {// , String Email) {AUSKLAMMERN, WENN ANMELDUNG PER public static void open(String username) {// , String Email) {AUSKLAMMERN, WENN ANMELDUNG PER
@ -101,7 +100,6 @@ public class SettingsScreen extends JDialog {
* It personalises the screen more. * It personalises the screen more.
* *
* @param Username The name of the User * @param Username The name of the User
* @param Email The Email that is associated with that Account
* @since Envoy v0.1-alpha * @since Envoy v0.1-alpha
*/ */
public SettingsScreen(String Username) {// , String Email, String hashedPwd) {AUSKLAMMERN, WENN ANMELDUNG PER EMAIL public SettingsScreen(String Username) {// , String Email, String hashedPwd) {AUSKLAMMERN, WENN ANMELDUNG PER EMAIL
@ -145,10 +143,10 @@ public class SettingsScreen extends JDialog {
public static boolean isEnterToSend() { return enterToSend; } public static boolean isEnterToSend() { return enterToSend; }
/** /**
* @param enterToSend <br> * @param enterForSend <br>
* toggles whether a message should be sent via * toggles whether a message should be sent via
* <br> * <br>
* buttonpress "enter" or "ctrl"+"enter" * buttonpress "enter" or "ctrl"+"enter"
* @since Envoy v0.1-alpha * @since Envoy v0.1-alpha
*/ */
public static void setEnterToSend(boolean enterForSend) { enterToSend = enterForSend; } public static void setEnterToSend(boolean enterForSend) { enterToSend = enterForSend; }

View File

@ -26,11 +26,11 @@ import envoy.exception.EnvoyException;
*/ */
public class Startup { public class Startup {
private static final Logger logger = Logger.getLogger(Client.class.getSimpleName()); private static final Logger logger = Logger.getLogger(Startup.class.getSimpleName());
public static void main(String[] args) { public static void main(String[] args) {
logger.setLevel(Level.ALL); logger.setLevel(Level.ALL);
Config config = Config.getInstance(); Config config = Config.getInstance();
// Load the configuration from client.properties first // Load the configuration from client.properties first
@ -44,30 +44,29 @@ public class Startup {
} }
// Override configuration values with command line arguments // Override configuration values with command line arguments
if (args.length > 0) if (args.length > 0) config.load(args);
config.load(args);
if (!config.isInitialized()) { if (!config.isInitialized()) {
logger.warning("Server or port are not defined. Exiting..."); logger.severe("Server or port are not defined. Exiting...");
JOptionPane.showMessageDialog(null, "Error loading configuration values.", "Configuration error", JOptionPane.showMessageDialog(null, "Error loading configuration values.", "Configuration error", JOptionPane.ERROR_MESSAGE);
JOptionPane.ERROR_MESSAGE);
System.exit(1); System.exit(1);
} }
String userName = JOptionPane.showInputDialog("Please enter your username"); String userName = JOptionPane.showInputDialog("Please enter your username");
if (userName == null || userName.isEmpty()) { if (userName == null || userName.isEmpty()) {
logger.warning("User name is not set or empty. Exiting..."); logger.severe("User name is not set or empty. Exiting...");
System.exit(1); System.exit(1);
} }
Client client = new Client(config, userName); Client client = new Client(config, userName);
LocalDB localDB = new LocalDB(client.getSender()); LocalDB localDB = new LocalDB(client.getSender());
try { try {
localDB.initializeDBFile(config.getLocalDB()); localDB.initializeDBFile(config.getLocalDB());
} catch (EnvoyException e) { } catch (EnvoyException e) {
e.printStackTrace(); e.printStackTrace();
JOptionPane.showMessageDialog(null, JOptionPane.showMessageDialog(null,
"Error while loading local database: " + e.toString() + "\nChats will not be stored locally.", "Error while loading local database: " + e.toString() + "\nChats will not be stored locally.",
"Local DB error", JOptionPane.WARNING_MESSAGE); "Local DB error",
JOptionPane.WARNING_MESSAGE);
} }
EventQueue.invokeLater(() -> { EventQueue.invokeLater(() -> {

View File

@ -1,65 +1,56 @@
package envoy.client.ui; package envoy.client.ui;
import java.awt.Component; import java.awt.Component;
import javax.swing.JLabel; import javax.swing.JLabel;
import javax.swing.JList; import javax.swing.JList;
import javax.swing.ListCellRenderer; import javax.swing.ListCellRenderer;
import envoy.schema.User; import envoy.schema.User;
import envoy.schema.User.UserStatus; import envoy.schema.User.UserStatus;
/** /**
* Defines how the {@code UserList} is displayed. * Defines how the {@code UserList} is displayed.
* *
* Project: <strong>envoy-client</strong><br> * Project: <strong>envoy-client</strong><br>
* File: <strong>UserListRenderer.java</strong><br> * File: <strong>UserListRenderer.java</strong><br>
* Created: <strong>12 Oct 2019</strong><br> * Created: <strong>12 Oct 2019</strong><br>
* *
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
* @author Maximilian K&auml;fer * @author Maximilian K&auml;fer
* @since Envoy v0.1-alpha * @since Envoy v0.1-alpha
*/ */
public class UserListRenderer extends JLabel implements ListCellRenderer<User> { public class UserListRenderer extends JLabel implements ListCellRenderer<User> {
private static final long serialVersionUID = 5164417379767181198L; private static final long serialVersionUID = 5164417379767181198L;
@Override @SuppressWarnings("incomplete-switch")
public Component getListCellRendererComponent(JList<? extends User> list, User value, int index, boolean isSelected, @Override
boolean cellHasFocus) { public Component getListCellRendererComponent(JList<? extends User> list, User value, int index, boolean isSelected, boolean cellHasFocus) {
if (isSelected) { if (isSelected) {
setBackground(list.getSelectionBackground()); setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground()); setForeground(list.getSelectionForeground());
} else { } else {
setBackground(list.getBackground()); setBackground(list.getBackground());
setForeground(list.getForeground()); setForeground(list.getForeground());
} }
// Enable background rendering // Enable background rendering
setOpaque(true); setOpaque(true);
final String name = value.getName();
final String name = value.getName(); final UserStatus status = value.getStatus();
final UserStatus status = value.getStatus();
switch (status) {
switch (status) { case ONLINE:
case ONLINE: setText(String
setText(String.format( .format("<html><p style=\"color:#03fc20\"><b><small>%s</b></small><br><p style=\"color:white\">%s</html>", status, name));
"<html><p style=\"color:#03fc20\"><b><small>%s</b></small><br><p style=\"color:white\">%s</html>", break;
status, case OFFLINE:
name)); setText(String
break; .format("<html><p style=\"color:#fc0303\"><b><small>%s</b></small><br><p style=\"color:white\">%s</html>", status, name));
break;
case OFFLINE: }
setText(String.format( return this;
"<html><p style=\"color:#fc0303\"><b><small>%s</b></small><br><p style=\"color:white\">%s</html>", }
status,
name));
break;
}
return this;
}
} }