Started moving Startup contents into the new Startup class

This commit is contained in:
Kai S. K. Engelbart 2020-03-27 21:14:49 +01:00
parent 3a9fa365b4
commit 31b032eb08
4 changed files with 140 additions and 118 deletions

View File

@ -1,26 +1,14 @@
package envoy.client; package envoy.client;
import java.awt.EventQueue; import java.awt.EventQueue;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import javax.swing.JFrame; import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import envoy.client.data.*; import envoy.client.data.Settings;
import envoy.client.net.Client;
import envoy.client.net.WriteProxy;
import envoy.client.ui.StatusTrayIcon; import envoy.client.ui.StatusTrayIcon;
import envoy.client.ui.container.ChatWindow; import envoy.client.ui.container.ChatWindow;
import envoy.client.ui.container.LoginDialog;
import envoy.data.Config; import envoy.data.Config;
import envoy.data.Message;
import envoy.data.User.UserStatus;
import envoy.exception.EnvoyException; import envoy.exception.EnvoyException;
import envoy.util.EnvoyLog; import envoy.util.EnvoyLog;
@ -38,10 +26,9 @@ import envoy.util.EnvoyLog;
*/ */
public class Startup { public class Startup {
private static ChatWindow chatWindow;
private static final Logger logger = EnvoyLog.getLogger(Startup.class); private static final Logger logger = EnvoyLog.getLogger(Startup.class);
// TODO: Update Javadoc
/** /**
* Loads the application by first loading the configuration, then acquiring a * Loads the application by first loading the configuration, then acquiring a
* user name and connecting to the server. If the server cannot be reached, * user name and connecting to the server. If the server cannot be reached,
@ -54,86 +41,6 @@ public class Startup {
* @since Envoy Client v0.1-alpha * @since Envoy Client v0.1-alpha
*/ */
public static void main(String[] args) { public static void main(String[] args) {
ClientConfig config = ClientConfig.getInstance();
SwingUtilities.invokeLater(() -> chatWindow = new ChatWindow());
try {
// Load the configuration from client.properties first
Properties properties = new Properties();
properties.load(Startup.class.getClassLoader().getResourceAsStream("client.properties"));
config.load(properties);
// Override configuration values with command line arguments
if (args.length > 0) config.load(args);
// Check if all mandatory configuration values have been initialized
if (!config.isInitialized()) throw new EnvoyException("Configuration is not fully initialized");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error loading configuration values:\n" + e, "Configuration error", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
System.exit(1);
}
// Setup logger for the envoy package
EnvoyLog.initialize(config);
EnvoyLog.attach("envoy");
EnvoyLog.setFileLevelBarrier(config.getFileLevelBarrier());
EnvoyLog.setConsoleLevelBarrier(config.getConsoleLevelBarrier());
// 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, "Local database error", JOptionPane.ERROR_MESSAGE);
System.exit(1);
return;
}
// Initialize client and unread message cache
Client client = new Client();
Cache<Message> cache = new Cache<>();
// Try to connect to the server
new LoginDialog(client, localDB, cache);
SwingUtilities.invokeLater(() -> chatWindow.setVisible(true));
// Set client user in local database
localDB.setUser(client.getSender());
// Initialize chats in local database
try {
localDB.initializeUserStorage();
localDB.loadUserData();
} 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 will not be stored locally.",
"Local DB error",
JOptionPane.WARNING_MESSAGE);
}
// Initialize write proxy
final WriteProxy writeProxy = client.createWriteProxy(localDB);
if (client.isOnline()) {
// Save all users to the local database and flush cache
localDB.setUsers(client.getUsers());
writeProxy.flushCache();
} else
// Set all contacts to offline mode
localDB.getUsers().values().stream().filter(u -> u != localDB.getUser()).forEach(u -> u.setStatus(UserStatus.OFFLINE));
// Display ChatWindow and StatusTrayIcon // Display ChatWindow and StatusTrayIcon
EventQueue.invokeLater(() -> { EventQueue.invokeLater(() -> {
try { try {
@ -160,18 +67,5 @@ public class Startup {
} }
}); });
// 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);
}
}));
} }
} }

View File

@ -3,6 +3,7 @@
<?import javafx.scene.control.Button?> <?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?> <?import javafx.scene.control.Label?>
<?import javafx.scene.control.ListView?> <?import javafx.scene.control.ListView?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.layout.ColumnConstraints?> <?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?> <?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.RowConstraints?> <?import javafx.scene.layout.RowConstraints?>
@ -18,10 +19,11 @@
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" /> <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
</rowConstraints> </rowConstraints>
<children> <children>
<ListView id="userList" prefHeight="211.0" prefWidth="300.0" GridPane.rowIndex="2" /> <ListView id="userList" prefHeight="211.0" prefWidth="300.0" GridPane.rowIndex="1" />
<Label text="Label" /> <Label text="Label" />
<Button id="settingsButton" mnemonicParsing="false" text="Settings" GridPane.columnIndex="1" /> <Button id="settingsButton" mnemonicParsing="false" text="Settings" GridPane.columnIndex="1" />
<ListView id="messageList" prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="1" GridPane.rowIndex="1" /> <ListView id="messageList" prefHeight="257.0" prefWidth="300.0" GridPane.columnIndex="1" GridPane.rowIndex="1" />
<Button id="postButton" mnemonicParsing="false" text="Post" GridPane.columnIndex="1" GridPane.rowIndex="2" /> <Button id="postButton" mnemonicParsing="false" text="Post" GridPane.columnIndex="1" GridPane.rowIndex="2" />
<TextArea prefHeight="200.0" prefWidth="200.0" GridPane.rowIndex="2" />
</children> </children>
</GridPane> </GridPane>

View File

@ -14,7 +14,7 @@ import javafx.fxml.FXML;
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
* @since Envoy Client v0.1-beta * @since Envoy Client v0.1-beta
*/ */
public class ChatSceneController { public final class ChatSceneController {
private static final Logger logger = EnvoyLog.getLogger(ChatSceneController.class); private static final Logger logger = EnvoyLog.getLogger(ChatSceneController.class);

View File

@ -1,5 +1,22 @@
package envoy.client.ui; package envoy.client.ui;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import envoy.client.data.*;
import envoy.client.net.Client;
import envoy.client.net.WriteProxy;
import envoy.client.ui.container.LoginDialog;
import envoy.data.Message;
import envoy.data.User.UserStatus;
import envoy.exception.EnvoyException;
import envoy.util.EnvoyLog;
import javafx.application.Application; import javafx.application.Application;
import javafx.fxml.FXMLLoader; import javafx.fxml.FXMLLoader;
import javafx.scene.Scene; import javafx.scene.Scene;
@ -17,19 +34,128 @@ import javafx.stage.Stage;
*/ */
public final class Startup extends Application { public final class Startup extends Application {
private LocalDB localDB;
private Client client;
private WriteProxy writeProxy;
private static final ClientConfig config = ClientConfig.getInstance();
private static final Logger logger = EnvoyLog.getLogger(Startup.class);
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public void start(Stage primaryStage) throws Exception { public void init() throws Exception {
try {
// Load the configuration from client.properties first
Properties properties = new Properties();
properties.load(Startup.class.getClassLoader().getResourceAsStream("client.properties"));
config.load(properties);
// Override configuration values with command line arguments
String[] args = (String[]) getParameters().getRaw().toArray();
if (args.length > 0) config.load(args);
// Check if all mandatory configuration values have been initialized
if (!config.isInitialized()) throw new EnvoyException("Configuration is not fully initialized");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error loading configuration values:\n" + e, "Configuration error", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
System.exit(1);
}
// Setup logger for the envoy package
EnvoyLog.initialize(config);
EnvoyLog.attach("envoy");
EnvoyLog.setFileLevelBarrier(config.getFileLevelBarrier());
EnvoyLog.setConsoleLevelBarrier(config.getConsoleLevelBarrier());
// Initialize the local database
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, "Local database error", JOptionPane.ERROR_MESSAGE);
System.exit(1);
return;
}
// Initialize client and unread message cache
Client client = new Client();
Cache<Message> cache = new Cache<>();
// Try to connect to the server
new LoginDialog(client, localDB, cache);
// Set client user in local database
localDB.setUser(client.getSender());
// Initialize chats in local database
try {
localDB.initializeUserStorage();
localDB.loadUserData();
} 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 will not be stored locally.",
"Local DB error",
JOptionPane.WARNING_MESSAGE);
}
// Initialize write proxy
writeProxy = client.createWriteProxy(localDB);
if (client.isOnline()) {
// Save all users to the local database and flush cache
localDB.setUsers(client.getUsers());
writeProxy.flushCache();
} else
// Set all contacts to offline mode
localDB.getUsers().values().stream().filter(u -> u != localDB.getUser()).forEach(u -> u.setStatus(UserStatus.OFFLINE));
}
/**
* {@inheritDoc}
*/
@Override
public void start(Stage stage) throws Exception {
// Prepare stage and load ChatScene
var loader = new FXMLLoader(getClass().getResource("ChatScene.fxml")); var loader = new FXMLLoader(getClass().getResource("ChatScene.fxml"));
var anchorPane = loader.<GridPane>load(); var anchorPane = loader.<GridPane>load();
var chatScene = new Scene(anchorPane); var chatScene = new Scene(anchorPane);
primaryStage.setTitle("Envoy"); stage.setTitle("Envoy");
primaryStage.getIcons().add(new Image(getClass().getResourceAsStream("/icons/envoy_logo.png"))); stage.getIcons().add(new Image(getClass().getResourceAsStream("/icons/envoy_logo.png")));
primaryStage.setScene(chatScene); stage.setScene(chatScene);
primaryStage.show(); stage.show();
}
/**
* {@inheritDoc}
*/
@Override
public void stop() throws Exception {
try {
// Save Settings and PersistentLocalDB on shutdown
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);
}
} }
public static void main(String[] args) { launch(args); } public static void main(String[] args) { launch(args); }