diff --git a/.gitignore b/.gitignore index d77958c..a6f89c2 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1 @@ -/target/ -/localDB/ -/log/ -/themes.ser \ No newline at end of file +/target/ \ No newline at end of file diff --git a/src/main/java/envoy/client/Config.java b/src/main/java/envoy/client/Config.java index ca86a33..3e511f9 100644 --- a/src/main/java/envoy/client/Config.java +++ b/src/main/java/envoy/client/Config.java @@ -1,7 +1,10 @@ package envoy.client; import java.io.File; +import java.util.HashMap; +import java.util.Map; import java.util.Properties; +import java.util.logging.Level; import envoy.exception.EnvoyException; @@ -20,14 +23,19 @@ import envoy.exception.EnvoyException; */ public class Config { - private String server; - private int port; - private File localDB; - private int syncTimeout; + private Map> items = new HashMap<>(); private static Config config; - private Config() {} + private Config() { + items.put("server", new ConfigItem<>("server", "s", (input) -> input, null)); + items.put("port", new ConfigItem<>("port", "p", (input) -> Integer.parseInt(input), null)); + items.put("localDB", new ConfigItem<>("localDB", "db", (input) -> new File(input), new File("localDB"))); + items.put("syncTimeout", new ConfigItem<>("syncTimeout", "st", (input) -> Integer.parseInt(input), 1000)); + items.put("homeDirectory", new ConfigItem<>("homeDirectory", "h", (input) -> new File(input), new File(System.getProperty("user.home"), ".envoy"))); + items.put("fileLevelBarrier", new ConfigItem<>("fileLevelBarrier", "fb", (input) -> Level.parse(input), Level.CONFIG)); + items.put("consoleLevelBarrier", new ConfigItem<>("consoleLevelBarrier", "cb", (input) -> Level.parse(input), Level.FINEST)); + } /** * @return the singleton instance of the {@link Config} @@ -53,10 +61,7 @@ public class Config { try { Properties properties = new Properties(); properties.load(loader.getResourceAsStream("client.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")); - syncTimeout = Integer.parseInt(properties.getProperty("syncTimeout", "1000")); + items.forEach((name, item) -> { if (properties.containsKey(name)) item.parse(properties.getProperty(name)); }); } catch (Exception e) { throw new EnvoyException("Failed to load client.properties", e); } @@ -72,84 +77,69 @@ public class Config { */ public void load(String[] args) throws EnvoyException { for (int i = 0; i < args.length; i++) - switch (args[i]) { - case "--server": - case "-s": - server = args[++i]; - break; - case "--port": - case "-p": - port = Integer.parseInt(args[++i]); - break; - case "--localDB": - case "-db": - localDB = new File(args[++i]); - break; - default: - throw new EnvoyException("Unknown token " + args[i] + " found"); - } + for (ConfigItem item : items.values()) + if (args[i].startsWith("--")) { + if (args[i].length() == 2) throw new EnvoyException("Malformed command line argument at position " + i); + final String commandLong = args[i].substring(2); + if (item.getCommandLong().equals(commandLong)) { + item.parse(args[++i]); + break; + } + } else if (args[i].startsWith("-")) { + if (args[i].length() == 1) throw new EnvoyException("Malformed command line argument at position " + i); + final String commandShort = args[i].substring(1); + if (item.getCommandShort().equals(commandShort)) { + item.parse(args[++i]); + break; + } + } else throw new EnvoyException("Malformed command line argument at position " + i); } /** * @return {@code true} if server, port and localDB directory are known. * @since Envoy v0.1-alpha */ - public boolean isInitialized() { return server != null && !server.isEmpty() && port > 0 && port < 65566 && localDB != null; } + public boolean isInitialized() { return items.values().stream().noneMatch(item -> item.get() == null); } /** * @return the host name of the Envoy server * @since Envoy v0.1-alpha */ - public String getServer() { return server; } - - /** - * Changes the default server host name. - * Exclusively intended for development purposes. - * - * @param server the host name of the Envoy server - * @since Envoy v0.1-alpha - */ - public void setServer(String server) { this.server = server; } + public String getServer() { return (String) items.get("server").get(); } /** * @return the port at which the Envoy server is located on the host * @since Envoy v0.1-alpha */ - public int getPort() { return port; } - - /** - * Changes the default 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; } + public int getPort() { return (int) items.get("port").get(); } /** * @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 localDB the file containing the local database - * @since Envoy v0.1-alpha - **/ - public void setLocalDB(File localDB) { this.localDB = localDB; } + */ + public File getLocalDB() { return (File) items.get("localDB").get(); } /** * @return the current time (milliseconds) that is waited between Syncs * @since Envoy v0.1-alpha */ - public int getSyncTimeout() { return syncTimeout; } + public int getSyncTimeout() { return (int) items.get("syncTimeout").get(); } /** - * @param syncTimeout sets the time (milliseconds) during which Sync waits - * @since Envoy v0.1-alpha + * @return the directory in which all local files are saves + * @since Envoy v0.2-alpha */ - public void setSyncTimeout(int syncTimeout) { this.syncTimeout = syncTimeout; } + public File getHomeDirectory() { return (File) items.get("homeDirectory").get(); } + + /** + * @return the minimal {@link Level} to log inside the log file + * @since Envoy v0.2-alpha + */ + public Level getFileLevelBarrier() { return (Level) items.get("fileLevelBarrier").get(); } + + /** + * @return the minimal {@link Level} to log inside the console + * @since Envoy v0.2-alpha + */ + public Level getConsoleLevelBarrier() { return (Level) items.get("consoleLevelBarrier").get(); } } diff --git a/src/main/java/envoy/client/ConfigItem.java b/src/main/java/envoy/client/ConfigItem.java new file mode 100644 index 0000000..87e927b --- /dev/null +++ b/src/main/java/envoy/client/ConfigItem.java @@ -0,0 +1,64 @@ +package envoy.client; + +import java.util.function.Function; + +/** + * Contains a single {@link Config} value as well as the corresponding command + * line arguments and its default value.
+ *
+ * Project: envoy-clientChess
+ * File: ConfigItem.javaEvent.java
+ * Created: 21.12.2019
+ * + * @author Kai S. K. Engelbart + * @param the type of the config item's value + * @since Envoy v0.2-alpha + */ +public class ConfigItem { + + private String commandLong, commandShort; + private Function parseFunction; + private T value; + + /** + * Initializes a {@link ConfigItem} + * + * @param commandLong the long command line argument to set this value + * @param commandShort the short command line argument to set this value + * @param parseFunction the {@code Function} that parses the value + * from a string + * @param defaultValue the optional default value to set before parsing + * @since Envoy v0.2-alpha + */ + public ConfigItem(String commandLong, String commandShort, Function parseFunction, T defaultValue) { + this.commandLong = commandLong; + this.commandShort = commandShort; + this.parseFunction = parseFunction; + value = defaultValue; + } + + /** + * Parses this {@ConfigItem}'s value from a string + * @param input the string to parse from + * @since Envoy v0.2-alpha + */ + public void parse(String input) { value = parseFunction.apply(input); } + + /** + * @return The long command line argument to set the value of this {@link ConfigItem} + * @since Envoy v0.2-alpha + */ + public String getCommandLong() { return commandLong; } + + /** + * @return The short command line argument to set the value of this {@link ConfigItem} + * @since Envoy v0.2-alpha + */ + public String getCommandShort() { return commandShort; } + + /** + * @return the value of this {@link ConfigItem} + * @since Envoy v0.2-alpha + */ + public T get() { return value; } +} diff --git a/src/main/java/envoy/client/Settings.java b/src/main/java/envoy/client/Settings.java index d7e01de..6502049 100644 --- a/src/main/java/envoy/client/Settings.java +++ b/src/main/java/envoy/client/Settings.java @@ -37,7 +37,7 @@ public class Settings { /** * User-defined themes are stored inside this file. */ - private File themeFile = new File("themes.ser"); + private File themeFile = new File(Config.getInstance().getHomeDirectory(), "themes.ser"); /** * Singleton instance of this class. diff --git a/src/main/java/envoy/client/ui/Startup.java b/src/main/java/envoy/client/ui/Startup.java index df07361..21e4cf0 100644 --- a/src/main/java/envoy/client/ui/Startup.java +++ b/src/main/java/envoy/client/ui/Startup.java @@ -1,6 +1,7 @@ package envoy.client.ui; import java.awt.EventQueue; +import java.io.File; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; @@ -8,10 +9,7 @@ import java.util.logging.Logger; import javax.swing.JFrame; import javax.swing.JOptionPane; -import envoy.client.Client; -import envoy.client.Config; -import envoy.client.LocalDB; -import envoy.client.Settings; +import envoy.client.*; import envoy.client.util.EnvoyLog; import envoy.exception.EnvoyException; import envoy.schema.User; @@ -61,6 +59,10 @@ public class Startup { System.exit(1); e.printStackTrace(); } + + // Set new logger levels loaded from config + EnvoyLog.setFileLevelBarrier(config.getFileLevelBarrier()); + EnvoyLog.setConsoleLevelBarrier(config.getConsoleLevelBarrier()); // Ask the user for their user name String userName = JOptionPane.showInputDialog("Please enter your username"); @@ -72,7 +74,7 @@ public class Startup { // Initialize the local database LocalDB localDB; try { - localDB = new LocalDB(config.getLocalDB()); + localDB = new LocalDB(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()); diff --git a/src/main/java/envoy/client/util/EnvoyLog.java b/src/main/java/envoy/client/util/EnvoyLog.java index db4e03c..282e1b4 100644 --- a/src/main/java/envoy/client/util/EnvoyLog.java +++ b/src/main/java/envoy/client/util/EnvoyLog.java @@ -2,11 +2,9 @@ package envoy.client.util; import java.io.File; import java.io.IOException; -import java.util.logging.ConsoleHandler; -import java.util.logging.FileHandler; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.logging.SimpleFormatter; +import java.util.logging.*; + +import envoy.client.Config; /** * Project: envoy-client
@@ -14,57 +12,69 @@ import java.util.logging.SimpleFormatter; * Created: 14 Dec 2019
* * @author Leon Hofmeister + * @author Kai S. K. Engelbart * @since Envoy v0.2-alpha */ public class EnvoyLog { - private static Level fileLevelBarrier = Level.CONFIG; + private static FileHandler fileHandler; + private static ConsoleHandler consoleHandler; + + static { + File logFile = new File(Config.getInstance().getHomeDirectory(), "log/envoy_user.log"); + logFile.getParentFile().mkdirs(); + SimpleFormatter formatter = new SimpleFormatter(); + + try { + fileHandler = new FileHandler(logFile.getAbsolutePath()); + fileHandler.setLevel(Config.getInstance().getFileLevelBarrier()); + fileHandler.setFormatter(formatter); + } catch (SecurityException | IOException e) { + e.printStackTrace(); + } + consoleHandler = new ConsoleHandler(); + consoleHandler.setLevel(Config.getInstance().getConsoleLevelBarrier()); + consoleHandler.setFormatter(formatter); + } private EnvoyLog() {} /** * Creates a {@link Logger} with a specified name + * * @param name the name of the {@link Logger} to create * @return the created {@link Logger} + * @since Envoy v0.2-alpha */ public static Logger getLogger(String name) { // Get a logger with the specified name Logger logger = Logger.getLogger(name); - - final String logPath = "log/envoy_user.log"; - new File(logPath).getParentFile().mkdirs(); - - SimpleFormatter formatter = new SimpleFormatter(); - - try { - FileHandler fh = new FileHandler(logPath); - fh.setLevel(fileLevelBarrier); - fh.setFormatter(formatter); - logger.addHandler(fh); - } catch (SecurityException | IOException e) { - e.printStackTrace(); - } - - ConsoleHandler ch = new ConsoleHandler(); - ch.setLevel(Level.FINEST); - ch.setFormatter(formatter); - logger.addHandler(ch); - + + // Add handlers + if (fileHandler != null) logger.addHandler(fileHandler); + if (consoleHandler != null) logger.addHandler(consoleHandler); + return logger; } - - /** - * @return the fileLevelBarrier: The current barrier for writing logs to a file. - * @since Envoy v0.2-alpha - */ - public static Level getFileLevelBarrier() { return fileLevelBarrier; } /** - * @param fileLevelBarrier the severity below which logRecords will be written - * only to the console. At or above they'll also be + * @param fileLevelBarrier the severity below which logRecords will not be + * written to the log file. At or above they'll also be * logged in a file. Can be written either in Digits * from 0 - 1000 or with the according name of the level * @since Envoy v0.2-alpha */ - public static void setFileLevel(String fileLevelBarrier) { EnvoyLog.fileLevelBarrier = Level.parse(fileLevelBarrier); } + public static void setFileLevelBarrier(Level fileLevelBarrier) { if (fileHandler != null) fileHandler.setLevel(fileLevelBarrier); } + + /** + * @param consoleLevelBarrier the severity below which logRecords will not be + * written to the console. At or above they'll also + * be logged in a file. Can be written either in + * digits from 0 - 1000 or with the according name of + * the level + * @since Envoy v0.2-alpha + */ + public static void setConsoleLevelBarrier(Level consoleLevelBarrier) { + if (consoleHandler != null) consoleHandler.setLevel(consoleLevelBarrier); + } }