Merge pull request #65 from informatik-ag-ngl/f/config

Added logger level and home folder configuration
This commit is contained in:
Kai S. K. Engelbart 2019-12-21 12:48:43 +01:00 committed by GitHub
commit 732c8d1d20
6 changed files with 169 additions and 106 deletions

3
.gitignore vendored
View File

@ -1,4 +1 @@
/target/ /target/
/localDB/
/log/
/themes.ser

View File

@ -1,7 +1,10 @@
package envoy.client; package envoy.client;
import java.io.File; import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties; import java.util.Properties;
import java.util.logging.Level;
import envoy.exception.EnvoyException; import envoy.exception.EnvoyException;
@ -20,14 +23,19 @@ import envoy.exception.EnvoyException;
*/ */
public class Config { public class Config {
private String server; private Map<String, ConfigItem<?>> items = new HashMap<>();
private int port;
private File localDB;
private int syncTimeout;
private static Config config; 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} * @return the singleton instance of the {@link Config}
@ -53,10 +61,7 @@ public class Config {
try { try {
Properties properties = new Properties(); Properties properties = new Properties();
properties.load(loader.getResourceAsStream("client.properties")); properties.load(loader.getResourceAsStream("client.properties"));
if (properties.containsKey("server")) server = properties.getProperty("server"); items.forEach((name, item) -> { if (properties.containsKey(name)) item.parse(properties.getProperty(name)); });
if (properties.containsKey("port")) port = Integer.parseInt(properties.getProperty("port"));
localDB = new File(properties.getProperty("localDB", ".\\localDB"));
syncTimeout = Integer.parseInt(properties.getProperty("syncTimeout", "1000"));
} catch (Exception e) { } catch (Exception e) {
throw new EnvoyException("Failed to load client.properties", e); throw new EnvoyException("Failed to load client.properties", e);
} }
@ -72,84 +77,69 @@ public class Config {
*/ */
public void load(String[] args) throws EnvoyException { public void load(String[] args) throws EnvoyException {
for (int i = 0; i < args.length; i++) for (int i = 0; i < args.length; i++)
switch (args[i]) { for (ConfigItem<?> item : items.values())
case "--server": if (args[i].startsWith("--")) {
case "-s": if (args[i].length() == 2) throw new EnvoyException("Malformed command line argument at position " + i);
server = args[++i]; final String commandLong = args[i].substring(2);
break; if (item.getCommandLong().equals(commandLong)) {
case "--port": item.parse(args[++i]);
case "-p": break;
port = Integer.parseInt(args[++i]); }
break; } else if (args[i].startsWith("-")) {
case "--localDB": if (args[i].length() == 1) throw new EnvoyException("Malformed command line argument at position " + i);
case "-db": final String commandShort = args[i].substring(1);
localDB = new File(args[++i]); if (item.getCommandShort().equals(commandShort)) {
break; item.parse(args[++i]);
default: break;
throw new EnvoyException("Unknown token " + args[i] + " found"); }
} } else throw new EnvoyException("Malformed command line argument at position " + i);
} }
/** /**
* @return {@code true} if server, port and localDB directory are known. * @return {@code true} if server, port and localDB directory are known.
* @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 boolean isInitialized() { return items.values().stream().noneMatch(item -> item.get() == null); }
/** /**
* @return the host name of the Envoy server * @return the host name of the Envoy server
* @since Envoy v0.1-alpha * @since Envoy v0.1-alpha
*/ */
public String getServer() { return server; } public String getServer() { return (String) items.get("server").get(); }
/**
* 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; }
/** /**
* @return the port at which the Envoy server is located on the host * @return the port at which the Envoy server is located on the host
* @since Envoy v0.1-alpha * @since Envoy v0.1-alpha
*/ */
public int getPort() { return port; } public int getPort() { return (int) items.get("port").get(); }
/**
* 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; }
/** /**
* @return the local database specific to the client user * @return the local database specific to the client user
* @since Envoy v0.1-alpha * @since Envoy v0.1-alpha
**/ */
public File getLocalDB() { return localDB; } public File getLocalDB() { return (File) items.get("localDB").get(); }
/**
* 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; }
/** /**
* @return the current time (milliseconds) that is waited between Syncs * @return the current time (milliseconds) that is waited between Syncs
* @since Envoy v0.1-alpha * @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 * @return the directory in which all local files are saves
* @since Envoy v0.1-alpha * @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(); }
} }

View File

@ -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.<br>
* <br>
* Project: <strong>envoy-clientChess</strong><br>
* File: <strong>ConfigItem.javaEvent.java</strong><br>
* Created: <strong>21.12.2019</strong><br>
*
* @author Kai S. K. Engelbart
* @param <T> the type of the config item's value
* @since Envoy v0.2-alpha
*/
public class ConfigItem<T> {
private String commandLong, commandShort;
private Function<String, T> 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<String, T>} 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<String, T> 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; }
}

View File

@ -37,7 +37,7 @@ public class Settings {
/** /**
* User-defined themes are stored inside this file. * 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. * Singleton instance of this class.

View File

@ -1,6 +1,7 @@
package envoy.client.ui; package envoy.client.ui;
import java.awt.EventQueue; import java.awt.EventQueue;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
@ -8,10 +9,7 @@ import java.util.logging.Logger;
import javax.swing.JFrame; import javax.swing.JFrame;
import javax.swing.JOptionPane; import javax.swing.JOptionPane;
import envoy.client.Client; import envoy.client.*;
import envoy.client.Config;
import envoy.client.LocalDB;
import envoy.client.Settings;
import envoy.client.util.EnvoyLog; import envoy.client.util.EnvoyLog;
import envoy.exception.EnvoyException; import envoy.exception.EnvoyException;
import envoy.schema.User; import envoy.schema.User;
@ -62,6 +60,10 @@ public class Startup {
e.printStackTrace(); e.printStackTrace();
} }
// Set new logger levels loaded from config
EnvoyLog.setFileLevelBarrier(config.getFileLevelBarrier());
EnvoyLog.setConsoleLevelBarrier(config.getConsoleLevelBarrier());
// Ask the user for their user name // Ask the user for their user name
String userName = JOptionPane.showInputDialog("Please enter your username"); String userName = JOptionPane.showInputDialog("Please enter your username");
if (userName == null || userName.isEmpty()) { if (userName == null || userName.isEmpty()) {
@ -72,7 +74,7 @@ public class Startup {
// Initialize the local database // Initialize the local database
LocalDB localDB; LocalDB localDB;
try { try {
localDB = new LocalDB(config.getLocalDB()); localDB = new LocalDB(new File(config.getHomeDirectory(), config.getLocalDB().getPath()));
} catch (IOException e3) { } catch (IOException e3) {
logger.log(Level.SEVERE, "Could not initialize local database", e3); logger.log(Level.SEVERE, "Could not initialize local database", e3);
JOptionPane.showMessageDialog(null, "Could not initialize local database!\n" + e3.toString()); JOptionPane.showMessageDialog(null, "Could not initialize local database!\n" + e3.toString());

View File

@ -2,11 +2,9 @@ package envoy.client.util;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.logging.ConsoleHandler; import java.util.logging.*;
import java.util.logging.FileHandler;
import java.util.logging.Level; import envoy.client.Config;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
/** /**
* Project: <strong>envoy-client</strong><br> * Project: <strong>envoy-client</strong><br>
@ -14,57 +12,69 @@ import java.util.logging.SimpleFormatter;
* Created: <strong>14 Dec 2019</strong><br> * Created: <strong>14 Dec 2019</strong><br>
* *
* @author Leon Hofmeister * @author Leon Hofmeister
* @author Kai S. K. Engelbart
* @since Envoy v0.2-alpha * @since Envoy v0.2-alpha
*/ */
public class EnvoyLog { 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() {} private EnvoyLog() {}
/** /**
* Creates a {@link Logger} with a specified name * Creates a {@link Logger} with a specified name
*
* @param name the name of the {@link Logger} to create * @param name the name of the {@link Logger} to create
* @return the created {@link Logger} * @return the created {@link Logger}
* @since Envoy v0.2-alpha
*/ */
public static Logger getLogger(String name) { public static Logger getLogger(String name) {
// Get a logger with the specified name // Get a logger with the specified name
Logger logger = Logger.getLogger(name); Logger logger = Logger.getLogger(name);
final String logPath = "log/envoy_user.log"; // Add handlers
new File(logPath).getParentFile().mkdirs(); if (fileHandler != null) logger.addHandler(fileHandler);
if (consoleHandler != null) logger.addHandler(consoleHandler);
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);
return logger; return logger;
} }
/** /**
* @return the fileLevelBarrier: The current barrier for writing logs to a file. * @param fileLevelBarrier the severity below which logRecords will not be
* @since Envoy v0.2-alpha * written to the log file. At or above they'll also be
*/
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
* logged in a file. Can be written either in Digits * logged in a file. Can be written either in Digits
* from 0 - 1000 or with the according name of the level * from 0 - 1000 or with the according name of the level
* @since Envoy v0.2-alpha * @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);
}
} }