Merge pull request #20 from informatik-ag-ngl/f/local_db

Added local database
This commit is contained in:
Kai S. K. Engelbart 2019-10-30 17:02:18 +01:00 committed by GitHub
commit 239d2bb029
8 changed files with 255 additions and 106 deletions

1
.gitignore vendored
View File

@ -1 +1,2 @@
/target/ /target/
/localDB/

View File

@ -1,12 +1,16 @@
package envoy.client; package envoy.client;
import java.io.Serializable;
import javax.swing.DefaultListModel; import javax.swing.DefaultListModel;
import envoy.schema.Message; import envoy.schema.Message;
import envoy.schema.User; import envoy.schema.User;
public class Chat { public class Chat implements Serializable {
private static final long serialVersionUID = -7751248474547242056L;
private User recipient; private User recipient;
private DefaultListModel<Message> model = new DefaultListModel<>(); private DefaultListModel<Message> model = new DefaultListModel<>();

View File

@ -1,88 +1,108 @@
package envoy.client; package envoy.client;
import java.util.Properties; import java.io.File;
import java.util.Properties;
/**
* Project: <strong>envoy-client</strong><br> /**
* File: <strong>Config.java</strong><br> * Project: <strong>envoy-client</strong><br>
* Created: <strong>12 Oct 2019</strong><br> * File: <strong>Config.java</strong><br>
* * Created: <strong>12 Oct 2019</strong><br>
* @author Kai S. K. Engelbart *
* @since Envoy v0.1-alpha * @author Kai S. K. Engelbart
*/ * @since Envoy v0.1-alpha
public class Config { */
public class Config {
private String server;
private int port; private String server;
private int port;
/** private File localDB;
* Defaults to the {@code server.properties} file for information.
* /**
* * Defaults to the {@code client.properties} file for information.
* @param properties - The two options for internet connection <strong> *
* server</strong> and <strong> port</strong> * @param properties a {@link Properties} object containing information about
* @since Envoy v0.1-alpha * the server and port, as well as the path to the local
*/ * database
public void load(Properties properties) { * @since Envoy v0.1-alpha
if (properties.containsKey("server")) server = properties.getProperty("server"); */
if (properties.containsKey("port")) port = Integer.parseInt(properties.getProperty("port")); public void load(Properties properties) {
} if (properties.containsKey("server")) server = properties.getProperty("server");
if (properties.containsKey("port")) port = Integer.parseInt(properties.getProperty("port"));
/** localDB = new File(properties.getProperty("localDB", ".\\localDB"));
* Sets the server and the port via command line properties --server/ -s and }
* --port/ -p.
* /**
* @param args {@code --server} or {@code -s} followed by the specified URL * Sets the server, port and localDB path via command line properties --server /
* and {@code --port} or {@code -p} followed by a 4-digit Integer * -s, --port / -p and --localDB / -db.
* @since Envoy v0.1-alpha *
*/ * @param args the command line arguments to parse
public void load(String[] args) { * @since Envoy v0.1-alpha
for (int i = 0; i < args.length; i++) */
switch (args[i]) { public void load(String[] args) {
case "--server": for (int i = 0; i < args.length; i++)
case "-s": switch (args[i]) {
server = args[++i]; case "--server":
break; case "-s":
case "--port": server = args[++i];
case "-p": break;
port = Integer.parseInt(args[++i]); case "--port":
break; case "-p":
} port = Integer.parseInt(args[++i]);
} break;
case "--localDB":
/** case "-db":
* @return true if server and port are known. localDB = new File(args[++i]);
* @since Envoy v0.1-alpha }
*/ }
public boolean isInitialized() { return server != null && !server.isEmpty() && port > 0; }
/**
/** * @return {@code true} if server, port and localDB directory are known.
* @return the URL of our website * @since Envoy v0.1-alpha
* @since Envoy v0.1-alpha */
*/ public boolean isInitialized() { return server != null && !server.isEmpty() && port > 0 && port < 65566 && localDB != null; }
public String getServer() { return server; }
/**
/** * @return the host name of the Envoy server
* Changes the default URL. * @since Envoy v0.1-alpha
* Exclusively meant for developing reasons. (localhost) */
* public String getServer() { return server; }
* @param server the URL where wish to host Envoy
* @since Envoy v0.1-alpha /**
*/ * Changes the default server host name.
public void setServer(String server) { this.server = server; } * Exclusively intended for development purposes.
*
/** * @param server the host name of the Envoy server
* @return the port at which Envoy is located in the Server * @since Envoy v0.1-alpha
* @since Envoy v0.1-alpha */
*/ public void setServer(String server) { this.server = server; }
public int getPort() { return port; }
/**
/** * @return the port at which the Envoy server is located on the host
* Changes the default port. * @since Envoy v0.1-alpha
* Exclusively meant for developing reasons. (localhost) */
* public int getPort() { return port; }
* @param port the port where we wish to connect to {@code Envoy}.
* @since Envoy v0.1-alpha /**
*/ * Changes the default port.
public void setPort(int port) { this.port = port; } * Exclusively intended for development purposes.
} *
* @param port the port where an Envoy server is located
* @since Envoy v0.1-alpha
*/
public void setPort(int port) { this.port = port; }
/**
* @return the local database specific to the client user
* @since Envoy v0.1-alpha
**/
public File getLocalDB() { return localDB; }
/**
* Changes the default local database.
* Exclusively intended for development purposes.
*
* @param the file containing the local database
* @since Envoy v0.1-alpha
**/
public void setLocalDB(File localDB) { this.localDB = localDB; }
}

View File

@ -0,0 +1,96 @@
package envoy.client;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
import envoy.exception.EnvoyException;
import envoy.schema.User;
/**
* Project: <strong>envoy-client</strong><br>
* File: <strong>LocalDB.java</strong><br>
* Created: <strong>27.10.2019</strong><br>
*
* @author Kai S. K. Engelbart
* @since Envoy v0.1-alpha
*/
public class LocalDB {
private File localDB;
private User sender;
private List<Chat> chats = new ArrayList<>();
/**
* Constructs an empty local database.
*
* @param sender the user that is logged in with this client
* @since Envoy v0.1-alpha
**/
public LocalDB(User sender) { this.sender = sender; }
/**
* Initializes the local database and fills it with values
* if the user has already sent or received messages.
*
* @param localDBDir the directory where we wish to save/load the database from.
* @throws EnvoyException if the directory selected is not an actual directory.
* @since Envoy v0.1-alpha
**/
public void initializeDBFile(File localDBDir) throws EnvoyException {
if (localDBDir.exists() && !localDBDir.isDirectory())
throw new EnvoyException(String.format("LocalDBDir '%s' is not a directory!", localDBDir.getAbsolutePath()));
localDB = new File(localDBDir, sender.getID() + ".db");
if (localDB.exists()) loadFromLocalDB();
}
/**
* Saves the database into a file for future use.
*
* @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();
System.err.println("unable to save the messages");
}
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(localDB))) {
out.writeObject(chats);
} catch (IOException ex) {
ex.printStackTrace();
System.err.println("unable to save the messages");
}
}
/**
* Loads all chats saved by Envoy for the client user.
*
* @throws EnvoyException if something fails while loading.
* @since Envoy v0.1-alpha
**/
@SuppressWarnings("unchecked")
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) {
throw new EnvoyException(e);
}
}
/**
* @return all saves {@link Chat} objects that list the client user as the
* sender
* @since Envoy v0.1-alpha
**/
public List<Chat> getChats() { return chats; }
}

View File

@ -6,8 +6,8 @@ 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.util.ArrayList; import java.awt.event.WindowAdapter;
import java.util.List; import java.awt.event.WindowEvent;
import javax.swing.DefaultListModel; import javax.swing.DefaultListModel;
import javax.swing.JButton; import javax.swing.JButton;
@ -25,6 +25,7 @@ import javax.swing.border.EmptyBorder;
import envoy.client.Chat; import envoy.client.Chat;
import envoy.client.Client; import envoy.client.Client;
import envoy.client.LocalDB;
import envoy.schema.Message; import envoy.schema.Message;
import envoy.schema.Messages; import envoy.schema.Messages;
import envoy.schema.User; import envoy.schema.User;
@ -46,20 +47,28 @@ public class ChatWindow extends JFrame {
private JPanel contentPane = new JPanel(); private JPanel contentPane = new JPanel();
private Client client; private Client client;
private LocalDB localDB;
private JList<User> userList = new JList<>(); private JList<User> userList = new JList<>();
private List<Chat> partnerChatList = new ArrayList<Chat>();
private Chat currentChat; private Chat currentChat;
public ChatWindow(Client client) { public ChatWindow(Client client, LocalDB localDB) {
this.client = client; this.client = client;
this.localDB = localDB;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 600, 800); setBounds(100, 100, 600, 800);
setTitle("Envoy"); setTitle("Envoy");
setLocationRelativeTo(null); setLocationRelativeTo(null);
// Save chats when window closes
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) { localDB.saveToLocalDB(); }
});
contentPane.setBackground(new Color(0, 0, 0)); contentPane.setBackground(new Color(0, 0, 0));
contentPane.setForeground(Color.white); contentPane.setForeground(Color.white);
contentPane.setBorder(new EmptyBorder(0, 5, 0, 0)); contentPane.setBorder(new EmptyBorder(0, 5, 0, 0));
@ -191,7 +200,7 @@ public class ChatWindow extends JFrame {
final User user = selectedUserList.getSelectedValue(); final User user = selectedUserList.getSelectedValue();
client.setRecipient(user); client.setRecipient(user);
currentChat = partnerChatList.stream().filter(chat -> chat.getRecipient().getID() == user.getID()).findFirst().get(); currentChat = localDB.getChats().stream().filter(chat -> chat.getRecipient().getID() == user.getID()).findFirst().get();
client.setRecipient(user); client.setRecipient(user);
@ -232,7 +241,13 @@ public class ChatWindow extends JFrame {
new Thread(() -> { new Thread(() -> {
Users users = client.getUsersListXml(); Users users = client.getUsersListXml();
DefaultListModel<User> userListModel = new DefaultListModel<>(); DefaultListModel<User> userListModel = new DefaultListModel<>();
users.getUser().forEach(user -> { userListModel.addElement(user); partnerChatList.add(new Chat(user)); }); users.getUser().forEach(user -> {
userListModel.addElement(user);
// Check if user exists in local DB
if (localDB.getChats().stream().filter(c -> c.getRecipient().getID() == user.getID()).count() == 0)
localDB.getChats().add(new Chat(user));
});
SwingUtilities.invokeLater(() -> userList.setModel(userListModel)); SwingUtilities.invokeLater(() -> userList.setModel(userListModel));
}).start(); }).start();
} }
@ -247,9 +262,9 @@ public class ChatWindow extends JFrame {
new Timer(timeout, (evt) -> { new Timer(timeout, (evt) -> {
Messages unreadMessages = client.getUnreadMessages(client.getSender().getID()); Messages unreadMessages = client.getUnreadMessages(client.getSender().getID());
for (int i = 0; i < unreadMessages.getMessage().size(); i++) for (int i = 0; i < unreadMessages.getMessage().size(); i++)
for (int j = 0; j < partnerChatList.size(); j++) for (int j = 0; j < localDB.getChats().size(); j++)
if (partnerChatList.get(j).getRecipient().getID() == unreadMessages.getMessage().get(i).getMetaData().getSender()) if (localDB.getChats().get(j).getRecipient().getID() == unreadMessages.getMessage().get(i).getMetaData().getSender())
partnerChatList.get(j).appendMessage(unreadMessages.getMessage().get(i)); localDB.getChats().get(j).appendMessage(unreadMessages.getMessage().get(i));
}).start(); }).start();
} }
} }

View File

@ -8,6 +8,8 @@ import javax.swing.JOptionPane;
import envoy.client.Client; import envoy.client.Client;
import envoy.client.Config; import envoy.client.Config;
import envoy.client.LocalDB;
import envoy.exception.EnvoyException;
/** /**
* Starts the Envoy client and prompts the user to enter their name. * Starts the Envoy client and prompts the user to enter their name.
@ -30,7 +32,7 @@ public class Startup {
ClassLoader loader = Thread.currentThread().getContextClassLoader(); ClassLoader loader = Thread.currentThread().getContextClassLoader();
try { try {
Properties configProperties = new Properties(); Properties configProperties = new Properties();
configProperties.load(loader.getResourceAsStream("server.properties")); configProperties.load(loader.getResourceAsStream("client.properties"));
config.load(configProperties); config.load(configProperties);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
@ -47,11 +49,21 @@ public class Startup {
System.err.println("User name is not set or empty. Exiting..."); System.err.println("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());
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);
}
EventQueue.invokeLater(() -> { EventQueue.invokeLater(() -> {
try { try {
ChatWindow frame = new ChatWindow(client); ChatWindow frame = new ChatWindow(client, localDB);
frame.setVisible(true); frame.setVisible(true);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();

View File

@ -0,0 +1,3 @@
server=http://kske.feste-ip.net
port=43315
localDB=.\\localDB

View File

@ -1,2 +0,0 @@
server=http://kske.feste-ip.net
port=43315