This repository has been archived on 2021-12-05. You can view files and clone it, but cannot push or open issues or pull requests.
envoy/src/main/java/envoy/client/ui/Startup.java

201 lines
6.5 KiB
Java

package envoy.client.ui;
import java.awt.EventQueue;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import envoy.client.Config;
import envoy.client.Settings;
import envoy.client.data.*;
import envoy.client.net.Client;
import envoy.client.net.WriteProxy;
import envoy.client.util.EnvoyLog;
import envoy.data.LoginCredentials;
import envoy.data.Message;
import envoy.data.User;
import envoy.exception.EnvoyException;
/**
* Starts the Envoy client and prompts the user to enter their name.<br>
* <br>
* Project: <strong>envoy-client</strong><br>
* File: <strong>Startup.java</strong><br>
* Created: <strong>12 Oct 2019</strong><br>
*
* @author Leon Hofmeister
* @author Maximilian K&auml;fer
* @author Kai S. K. Engelbart
* @since Envoy v0.1-alpha
*/
public class Startup {
private static ChatWindow chatWindow;
private static final Logger logger = EnvoyLog.getLogger(Startup.class.getSimpleName());
/**
* Loads the application by first loading the configuration, then acquiring a
* user name and connecting to the server. If the server cannot be reached,
* offline mode is entered if possible. After that, a {@link ChatWindow}
* instance is initialized and then displayed to the user. Upon application
* exit, settings and the local database are saved.
*
* @param args the command line arguments may contain configuration parameters
* and are parsed by the {@link Config} class
* @since Envoy v0.1-alpha
*/
public static void main(String[] args) {
Config config = Config.getInstance();
SwingUtilities.invokeLater(() -> chatWindow = new ChatWindow());
try {
// Load the configuration from client.properties first
config.load();
// Override configuration values with command line arguments
if (args.length > 0) config.load(args);
// Check if all configuration values have been initialized
if (!config.isInitialized()) throw new EnvoyException("Server or port are not defined");
} catch (Exception e) {
JOptionPane
.showMessageDialog(null, "Error loading configuration values:\n" + e.toString(), "Configuration error", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
System.exit(1);
}
// Set new logger levels loaded from config
EnvoyLog.setFileLevelBarrier(config.getFileLevelBarrier());
EnvoyLog.setConsoleLevelBarrier(config.getConsoleLevelBarrier());
// Ask the user for their user name and password
LoginCredentials credentials = new LoginDialog().getCredentials();
if (credentials == null) {
logger.info("The login process has been aborted by the user. Exiting...");
System.exit(0);
}
// Initialize the local database
LocalDb localDb;
if (config.isIgnoreLocalDB()) {
localDb = new TransientLocalDb();
JOptionPane.showMessageDialog(null,
"Ignoring local database.\nMessages will not be saved!",
"Local database warning",
JOptionPane.WARNING_MESSAGE);
} else try {
localDb = new PersistentLocalDb(new File(config.getHomeDirectory(), config.getLocalDB().getPath()));
} catch (IOException e3) {
logger.log(Level.SEVERE, "Could not initialize local database", e3);
JOptionPane
.showMessageDialog(null, "Could not initialize local database!\n" + e3.toString(), "Local database error", JOptionPane.ERROR_MESSAGE);
System.exit(1);
return;
}
SwingUtilities.invokeLater(() -> chatWindow.setVisible(true));
// Acquire the client user (with ID) either from the server or from the local
// database, which triggers offline mode
Client client = new Client();
Cache<Message> cache = null;
try {
// Try entering online mode first
localDb.loadIdGenerator();
cache = client.onlineInit(credentials, localDb);
} catch (Exception e1) {
logger.warning("Could not connect to server. Trying offline mode...");
e1.printStackTrace();
try {
// Try entering offline mode
localDb.loadUsers();
User clientUser = localDb.getUsers().get(credentials.getName());
if (clientUser == null) throw new EnvoyException("Could not enter offline mode: user name unknown");
client.setSender(clientUser);
JOptionPane.showMessageDialog(null,
"A connection to the server could not be established. Starting in offline mode.\n" + e1,
"Connection error",
JOptionPane.WARNING_MESSAGE);
} catch (Exception e2) {
JOptionPane.showMessageDialog(null, e2.toString(), "Client error", JOptionPane.ERROR_MESSAGE);
System.exit(1);
return;
}
}
// Set client user in local database
localDb.setUser(client.getSender());
// Initialize chats in local database
try {
localDb.initializeUserStorage();
localDb.loadChats();
} catch (FileNotFoundException e) {
// The local database file has not yet been created, probably first login
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null,
"Error while loading local database: " + e + "\nChats might not be stored locally.",
"Local DB error",
JOptionPane.WARNING_MESSAGE);
}
// Initialize write proxy
final WriteProxy writeProxy = client.createWriteProxy(localDb);
// Save all users to the local database and flush cache
if (client.isOnline()) {
localDb.setUsers(client.getUsers());
writeProxy.flushCache();
}
// Display ChatWindow and StatusTrayIcon
EventQueue.invokeLater(() -> {
try {
chatWindow.initContent(client, localDb, writeProxy);
try {
new StatusTrayIcon(chatWindow).show();
// If the tray icon is supported and corresponding settings is set, hide the
// chat window on close
Settings.getInstance()
.getItems()
.get("onCloseMode")
.setChangeHandler((onCloseMode) -> chatWindow
.setDefaultCloseOperation((Boolean) onCloseMode ? JFrame.HIDE_ON_CLOSE : JFrame.EXIT_ON_CLOSE));
} catch (EnvoyException e) {
logger.warning("The StatusTrayIcon is not supported on this platform!");
}
} catch (Exception e) {
e.printStackTrace();
}
});
// Relay unread messages from cache
if (cache != null) cache.relay();
// Save Settings and PersistentLocalDb on shutdown
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
logger.info("Closing connection...");
client.close();
logger.info("Saving local database and settings...");
localDb.save();
Settings.getInstance().save();
} catch (Exception e) {
logger.log(Level.SEVERE, "Unable to save local files", e);
}
}));
}
}