Improved Config machanism with ConfigItems

Added logger levels and home directory to Config
This commit is contained in:
Kai S. K. Engelbart 2019-12-21 11:35:01 +01:00
parent a8406cb033
commit 8b6e501c2e
4 changed files with 94 additions and 77 deletions

View File

@ -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<String, ConfigItem<?>> 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"))));
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,57 @@ 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
*/
public void setSyncTimeout(int syncTimeout) { this.syncTimeout = syncTimeout; }
public File getHomeDirectory() { return (File) items.get("homeDirectory").get(); }
public Level getFileLevelBarrier() { return (Level) items.get("fileLevelBarrier").get(); }
public Level getConsoleLevelBarrier() { return (Level) items.get("consoleLevelBarrier").get(); }
}

View File

@ -0,0 +1,32 @@
package envoy.client;
import java.util.function.Function;
/**
* 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
*/
public class ConfigItem<T> {
private String commandLong, commandShort;
private Function<String, T> parseFunction;
private T value;
public ConfigItem(String commandLong, String commandShort, Function<String, T> parseFunction, T defaultValue) {
this.commandLong = commandLong;
this.commandShort = commandShort;
this.parseFunction = parseFunction;
value = defaultValue;
}
public void parse(String input) { value = parseFunction.apply(input); }
public String getCommandLong() { return commandLong; }
public String getCommandShort() { return commandShort; }
public T get() { return value; }
}

View File

@ -61,6 +61,9 @@ public class Startup {
System.exit(1);
e.printStackTrace();
}
EnvoyLog.setFileLevelBarrier(Config.getInstance().getFileLevelBarrier());
EnvoyLog.setConsoleLevelBarrier(Config.getInstance().getConsoleLevelBarrier());
// Ask the user for their user name
String userName = JOptionPane.showInputDialog("Please enter your username");

View File

@ -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: <strong>envoy-client</strong><br>
@ -14,28 +12,30 @@ import java.util.logging.SimpleFormatter;
* Created: <strong>14 Dec 2019</strong><br>
*
* @author Leon Hofmeister
* @author Kai S. K. Engelbart
* @since Envoy v0.2-alpha
*/
public class EnvoyLog {
private static Level fileLevelBarrier = Level.CONFIG;
private static Level fileLevelBarrier = Config.getInstance().getFileLevelBarrier(), consoleLevelBarrier = Config.getInstance().getConsoleLevelBarrier();
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}
*/
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();
SimpleFormatter formatter = new SimpleFormatter();
try {
FileHandler fh = new FileHandler(logPath);
fh.setLevel(fileLevelBarrier);
@ -44,15 +44,15 @@ public class EnvoyLog {
} catch (SecurityException | IOException e) {
e.printStackTrace();
}
ConsoleHandler ch = new ConsoleHandler();
ch.setLevel(Level.FINEST);
ch.setLevel(consoleLevelBarrier);
ch.setFormatter(formatter);
logger.addHandler(ch);
return logger;
}
/**
* @return the fileLevelBarrier: The current barrier for writing logs to a file.
* @since Envoy v0.2-alpha
@ -66,5 +66,9 @@ public class EnvoyLog {
* 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) { EnvoyLog.fileLevelBarrier = fileLevelBarrier; }
public static Level getConsoleLevelBarrier() { return consoleLevelBarrier; }
public static void setConsoleLevelBarrier(Level consoleLevelBarrier) { EnvoyLog.consoleLevelBarrier = consoleLevelBarrier; }
}