Improved logging and code readability

This commit is contained in:
delvh 2019-12-07 10:44:25 +01:00
parent 2a120411d2
commit c79500acde
8 changed files with 497 additions and 527 deletions

View File

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

View File

@ -114,7 +114,7 @@ public class Config {
* Changes the default local database.
* 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
**/
public void setLocalDB(File localDB) { this.localDB = localDB; }

View File

@ -80,19 +80,13 @@ public class LocalDB {
* @throws IOException if something went wrong during saving
* @since Envoy v0.1-alpha
*/
public void saveToLocalDB() {
try {
localDB.getParentFile().mkdirs();
localDB.createNewFile();
} catch (IOException e) {
e.printStackTrace();
logger.warning("unable to save the messages");
}
public void saveToLocalDB() throws IOException {
localDB.getParentFile().mkdirs();
localDB.createNewFile();
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(localDB))) {
out.writeObject(chats);
} catch (IOException ex) {
ex.printStackTrace();
logger.warning("unable to save the messages");
throw ex;
}
}
@ -116,7 +110,7 @@ public class LocalDB {
* Creates a {@link Message} object serializable to XML.
*
* @param textContent The content (text) of the message
* @param recipient The recipient of the message
* @param recipient The recipient of the message
* @return prepared {@link Message} object
* @since Envoy v0.1-alpha
*/
@ -144,7 +138,7 @@ public class LocalDB {
sync.getMessages().addAll(readMessages.getMessages());
readMessages.getMessages().clear();
logger.info(String.format("Filled sync with %d messages.", sync.getMessages().size()));
logger.finest(String.format("Filled sync with %d messages.", sync.getMessages().size()));
return sync;
}
@ -189,28 +183,20 @@ public class LocalDB {
if (returnSync.getMessages().get(i).getMetadata().getMessageId() != 0
&& returnSync.getMessages().get(i).getMetadata().getState() == MessageState.READ) {
// Update local Messages to state READ
logger.info("Message with ID: " + returnSync.getMessages().get(i).getMetadata().getMessageId()
logger.finest("Message with ID: " + returnSync.getMessages().get(i).getMetadata().getMessageId()
+ "was initialized to be set to READ in localDB.");
for (int j = 0; j < getChats().size(); j++) {
if (getChats().get(j)
.getRecipient()
.getID() == returnSync.getMessages().get(i).getMetadata().getRecipient()) {
logger.info("Chat with: " + getChats().get(j).getRecipient().getID() + "was selected.");
if (getChats().get(j).getRecipient().getID() == returnSync.getMessages().get(i).getMetadata().getRecipient()) {
logger.fine("Chat with: " + getChats().get(j).getRecipient().getID() + "was selected.");
for (int k = 0; k < getChats().get(j).getModel().getSize(); k++) {
if (getChats().get(j).getModel().get(k).getMetadata().getMessageId() == returnSync.getMessages()
.get(i)
.getMetadata()
.getMessageId()) {
logger.info("Message with ID: "
+ getChats().get(j).getModel().get(k).getMetadata().getMessageId()
+ "was selected.");
getChats().get(j)
.getModel()
.get(k)
.getMetadata()
.setState(returnSync.getMessages().get(i).getMetadata().getState());
logger.info("Message State is now: "
+ getChats().get(j).getModel().get(k).getMetadata().getState().toString());
logger
.finest("Message with ID: " + getChats().get(j).getModel().get(k).getMetadata().getMessageId() + "was selected.");
getChats().get(j).getModel().get(k).getMetadata().setState(returnSync.getMessages().get(i).getMetadata().getState());
logger.finest("Message State is now: " + getChats().get(j).getModel().get(k).getMetadata().getState().toString());
}
}
}
@ -237,7 +223,6 @@ public class LocalDB {
* Adds the unread messages returned from the server in the latest sync to the
* right chats in the LocalDB.
*
* @param localDB
* @since Envoy v0.1-alpha
*/
public void addUnreadMessagesToLocalDB() {
@ -255,7 +240,7 @@ public class LocalDB {
* <br>
* Adds these messages to the {@code readMessages} {@link Sync} object.
*
* @param currentChat
* @param currentChat the {@link Chat} that was just opened
* @since Envoy v0.1-alpha
*/
public void setMessagesToRead(Chat currentChat) {

View File

@ -10,6 +10,8 @@ import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
@ -73,7 +75,14 @@ public class ChatWindow extends JFrame {
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) { localDB.saveToLocalDB(); }
public void windowClosing(WindowEvent evt) {
try {
localDB.saveToLocalDB();
} catch (IOException e1) {
e1.printStackTrace();
logger.log(Level.WARNING, "Unable to save the messages", e1);
}
}
});
contentPane.setBackground(new Color(0, 0, 0));
@ -126,8 +135,8 @@ public class ChatWindow extends JFrame {
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER && ((SettingsScreen.enterToSend && e.getModifiersEx() == 0)
|| (e.getModifiersEx() == KeyEvent.CTRL_DOWN_MASK))) {
if (e.getKeyCode() == KeyEvent.VK_ENTER
&& ((SettingsScreen.enterToSend && e.getModifiersEx() == 0) || (e.getModifiersEx() == KeyEvent.CTRL_DOWN_MASK))) {
postMessage(messageList);
}
@ -189,7 +198,7 @@ public class ChatWindow extends JFrame {
SettingsScreen.open(localDB.getUser().getName());
} catch (Exception e) {
SettingsScreen.open();
logger.warning("An error occured while opening the settings screen: " + e);
logger.log(Level.WARNING, "An error occured while opening the settings screen", e);
e.printStackTrace();
}
});
@ -219,11 +228,7 @@ public class ChatWindow extends JFrame {
final User user = selectedUserList.getSelectedValue();
client.setRecipient(user);
currentChat = localDB.getChats()
.stream()
.filter(chat -> chat.getRecipient().getID() == user.getID())
.findFirst()
.get();
currentChat = localDB.getChats().stream().filter(chat -> chat.getRecipient().getID() == user.getID()).findFirst().get();
// Set all unread messages in the chat to read
readCurrentChat();
@ -262,10 +267,7 @@ public class ChatWindow extends JFrame {
private void postMessage(JList<Message> messageList) {
if (!client.hasRecipient()) {
JOptionPane.showMessageDialog(this,
"Please select a recipient!",
"Cannot send message",
JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(this, "Please select a recipient!", "Cannot send message", JOptionPane.INFORMATION_MESSAGE);
}
if (!messageEnterTextArea.getText().isEmpty()) try {
@ -321,8 +323,7 @@ public class ChatWindow extends JFrame {
new Thread(() -> {
// Synchronize
localDB.applySync(
client.sendSync(client.getSender().getID(), localDB.fillSync(client.getSender().getID())));
localDB.applySync(client.sendSync(client.getSender().getID(), localDB.fillSync(client.getSender().getID())));
// Process unread messages
localDB.addUnreadMessagesToLocalDB();
@ -332,8 +333,7 @@ public class ChatWindow extends JFrame {
readCurrentChat();
// Update UI
SwingUtilities
.invokeLater(() -> { updateUserStates(); contentPane.revalidate(); contentPane.repaint(); });
SwingUtilities.invokeLater(() -> { updateUserStates(); contentPane.revalidate(); contentPane.repaint(); });
}).start();
}).start();
}

View File

@ -26,8 +26,7 @@ public class MessageListRenderer extends JLabel implements ListCellRenderer<Mess
private static final long serialVersionUID = 5164417379767181198L;
@Override
public Component getListCellRendererComponent(JList<? extends Message> list, Message value, int index,
boolean isSelected, boolean cellHasFocus) {
public Component getListCellRendererComponent(JList<? extends Message> list, Message value, int index, boolean isSelected, boolean cellHasFocus) {
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
@ -39,16 +38,12 @@ public class MessageListRenderer extends JLabel implements ListCellRenderer<Mess
setOpaque(true);
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 ? ""
: 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("<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.
*
* @param username The name of the User
* @param Email The Email that is associated with that Account
* @since Envoy v0.1-alpha
*/
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.
*
* @param Username The name of the User
* @param Email The Email that is associated with that Account
* @since Envoy v0.1-alpha
*/
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; }
/**
* @param enterToSend <br>
* toggles whether a message should be sent via
* <br>
* buttonpress "enter" or "ctrl"+"enter"
* @param enterForSend <br>
* toggles whether a message should be sent via
* <br>
* buttonpress "enter" or "ctrl"+"enter"
* @since Envoy v0.1-alpha
*/
public static void setEnterToSend(boolean enterForSend) { enterToSend = enterForSend; }

View File

@ -26,7 +26,7 @@ import envoy.exception.EnvoyException;
*/
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) {
logger.setLevel(Level.ALL);
@ -44,30 +44,29 @@ public class Startup {
}
// Override configuration values with command line arguments
if (args.length > 0)
config.load(args);
if (args.length > 0) config.load(args);
if (!config.isInitialized()) {
logger.warning("Server or port are not defined. Exiting...");
JOptionPane.showMessageDialog(null, "Error loading configuration values.", "Configuration error",
JOptionPane.ERROR_MESSAGE);
logger.severe("Server or port are not defined. Exiting...");
JOptionPane.showMessageDialog(null, "Error loading configuration values.", "Configuration error", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
String userName = JOptionPane.showInputDialog("Please enter your username");
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);
}
Client client = new Client(config, userName);
LocalDB localDB = new LocalDB(client.getSender());
Client client = new Client(config, userName);
LocalDB localDB = new LocalDB(client.getSender());
try {
localDB.initializeDBFile(config.getLocalDB());
} catch (EnvoyException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null,
"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(() -> {

View File

@ -24,9 +24,9 @@ public class UserListRenderer extends JLabel implements ListCellRenderer<User> {
private static final long serialVersionUID = 5164417379767181198L;
@SuppressWarnings("incomplete-switch")
@Override
public Component getListCellRendererComponent(JList<? extends User> list, User value, int index, boolean isSelected,
boolean cellHasFocus) {
public Component getListCellRendererComponent(JList<? extends User> list, User value, int index, boolean isSelected, boolean cellHasFocus) {
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
@ -38,28 +38,19 @@ public class UserListRenderer extends JLabel implements ListCellRenderer<User> {
// Enable background rendering
setOpaque(true);
final String name = value.getName();
final UserStatus status = value.getStatus();
switch (status) {
case ONLINE:
setText(String.format(
"<html><p style=\"color:#03fc20\"><b><small>%s</b></small><br><p style=\"color:white\">%s</html>",
status,
name));
setText(String
.format("<html><p style=\"color:#03fc20\"><b><small>%s</b></small><br><p style=\"color:white\">%s</html>", status, name));
break;
case OFFLINE:
setText(String.format(
"<html><p style=\"color:#fc0303\"><b><small>%s</b></small><br><p style=\"color:white\">%s</html>",
status,
name));
setText(String
.format("<html><p style=\"color:#fc0303\"><b><small>%s</b></small><br><p style=\"color:white\">%s</html>", status, name));
break;
}
return this;
}
}