Updated config mechanism and added config for the server
Additionally fixed a small bug in EnvoyLog and envoy.server.Startup, fixed Receiver not stopping when the server was stopped and added access token authorization for the server config
This commit is contained in:
@ -1,8 +1,13 @@
|
||||
package envoy.data;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.*;
|
||||
import java.util.function.Function;
|
||||
import java.util.logging.Level;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import envoy.exception.EnvoyException;
|
||||
import envoy.util.EnvoyLog;
|
||||
|
||||
/**
|
||||
* Manages all application settings that are set during application startup by
|
||||
@ -21,13 +26,23 @@ public class Config {
|
||||
|
||||
protected Map<String, ConfigItem<?>> items = new HashMap<>();
|
||||
|
||||
private boolean modificationDisabled;
|
||||
|
||||
protected Config(String folderName) {
|
||||
final var rootDirectory = new File(System.getProperty("user.home"), folderName);
|
||||
put("homeDirectory", "home", File::new, true);
|
||||
((ConfigItem<File>) get("homeDirectory")).setValue(rootDirectory);
|
||||
put("fileLevelBarrier", "fb", Level::parse, true);
|
||||
put("consoleLevelBarrier", "cb", Level::parse, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses config items from a properties object.
|
||||
*
|
||||
* @param properties the properties object to parse
|
||||
* @since Envoy Common v0.1-beta
|
||||
*/
|
||||
public void load(Properties properties) {
|
||||
private void load(Properties properties) {
|
||||
items.entrySet()
|
||||
.stream()
|
||||
.filter(e -> properties.containsKey(e.getKey()))
|
||||
@ -38,43 +53,77 @@ public class Config {
|
||||
* Parses config items from an array of command line arguments.
|
||||
*
|
||||
* @param args the command line arguments to parse
|
||||
* @throws EnvoyException if the command line arguments contain an unknown token
|
||||
* @throws IllegalStateException if a malformed command line argument has been
|
||||
* supplied
|
||||
* @since Envoy Common v0.1-beta
|
||||
*/
|
||||
public void load(String[] args) throws EnvoyException {
|
||||
private void load(String[] args) {
|
||||
for (int i = 0; i < args.length; i++)
|
||||
for (ConfigItem<?> item : items.values())
|
||||
for (final ConfigItem<?> item : items.values())
|
||||
if (args[i].startsWith("--")) {
|
||||
if (args[i].length() == 2) throw new EnvoyException("Malformed command line argument at position " + i);
|
||||
if (args[i].length() == 2) throw new IllegalStateException("Malformed command line argument at position " + i + ": " + args[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);
|
||||
if (args[i].length() == 1) throw new IllegalStateException("Malformed command line argument at position " + i + ": " + args[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);
|
||||
} else throw new IllegalStateException("Malformed command line argument at position " + i + ": " + args[i]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes config items from a map.
|
||||
*
|
||||
* @param items the items to include in this config
|
||||
* Supplies default values from the given .properties file and
|
||||
* parses the configuration from an array of command line arguments.
|
||||
*
|
||||
* @param declaringClass the class calling this method
|
||||
* @param propertiesFilePath the path to where the .properties file can be found
|
||||
* - will be only the file name if it is located
|
||||
* directly inside the {@code src/main/resources}
|
||||
* folder
|
||||
* @param args the command line arguments to parse
|
||||
* @throws IllegalStateException if this method is getting called again or if a
|
||||
* malformed command line argument has been
|
||||
* supplied
|
||||
* @since Envoy Common v0.1-beta
|
||||
*/
|
||||
public void load(Map<String, ConfigItem<?>> items) { this.items.putAll(items); }
|
||||
public void loadAll(Class<?> declaringClass, String propertiesFilePath, String[] args) {
|
||||
if (modificationDisabled) throw new IllegalStateException("Cannot change config after isInitialized has been called");
|
||||
// Load the defaults from the given .properties file first
|
||||
final var properties = new Properties();
|
||||
try {
|
||||
properties.load(declaringClass.getClassLoader().getResourceAsStream(propertiesFilePath));
|
||||
} catch (final IOException e) {
|
||||
EnvoyLog.getLogger(Config.class).log(Level.SEVERE, "An error occurred when reading in the configuration: ", e);
|
||||
}
|
||||
load(properties);
|
||||
|
||||
// Override configuration values with command line arguments
|
||||
if (args.length > 0) load(args);
|
||||
|
||||
// Check if all mandatory configuration values have been initialized
|
||||
isInitialized();
|
||||
// Disable further editing of the config
|
||||
modificationDisabled = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return {@code true} if all mandatory config items are initialized
|
||||
* @throws IllegalStateException if a mandatory {@link ConfigItem} has not been
|
||||
* initialized
|
||||
* @since Envoy Common v0.1-beta
|
||||
*/
|
||||
public boolean isInitialized() {
|
||||
return items.values().stream().filter(ConfigItem::isMandatory).map(ConfigItem::get).noneMatch(Objects::isNull);
|
||||
private void isInitialized() {
|
||||
if (items.values().stream().filter(ConfigItem::isMandatory).map(ConfigItem::get).anyMatch(Objects::isNull))
|
||||
throw new IllegalStateException("config item(s) has/ have not been initialized:" + items.values()
|
||||
.stream()
|
||||
.filter(configItem -> configItem.isMandatory() && configItem.get() == null)
|
||||
.map(ConfigItem::getCommandLong)
|
||||
.collect(Collectors.toSet()));
|
||||
}
|
||||
|
||||
/**
|
||||
@ -83,4 +132,55 @@ public class Config {
|
||||
* @since Envoy Common v0.1-beta
|
||||
*/
|
||||
public ConfigItem<?> get(String name) { return items.get(name); }
|
||||
|
||||
/**
|
||||
* Shorthand for <br>
|
||||
* {@code items.put(commandName, new ConfigItem<>(commandName, commandShort, parseFunction, defaultValue, mandatory))}.
|
||||
*
|
||||
* @param <T> the type of the {@link ConfigItem}
|
||||
* @param commandName the key for this config item as well as its long name
|
||||
* @param commandShort the abbreviation of this config item
|
||||
* @param parseFunction the {@code Function<String, T>} that parses the value
|
||||
* from a string
|
||||
* @param mandatory indicated that this config item must be initialized with
|
||||
* a non-null value
|
||||
* @since Envoy Common v0.2-beta
|
||||
*/
|
||||
protected <T> void put(String commandName, String commandShort, Function<String, T> parseFunction, boolean mandatory) {
|
||||
items.put(commandName, new ConfigItem<>(commandName, commandShort, parseFunction, mandatory));
|
||||
}
|
||||
|
||||
/**
|
||||
* Shorthand for <br>
|
||||
* {@code put(commandName, commandShort, parseFunction, false)}.
|
||||
*
|
||||
* @param <T> the type of the {@link ConfigItem}
|
||||
* @param commandName the key for this config item as well as its long name
|
||||
* @param commandShort the abbreviation of this config item
|
||||
* @param parseFunction the {@code Function<String, T>} that parses the value
|
||||
* from a string
|
||||
* @since Envoy Common v0.2-beta
|
||||
*/
|
||||
protected <T> void put(String commandName, String commandShort, Function<String, T> parseFunction) {
|
||||
put(commandName, commandShort, parseFunction, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the directory in which all local files are saves
|
||||
* @since Envoy Client v0.2-beta
|
||||
*/
|
||||
public File getHomeDirectory() { return (File) items.get("homeDirectory").get(); }
|
||||
|
||||
/**
|
||||
* @return the minimal {@link Level} to log inside the log file
|
||||
* @since Envoy Client v0.2-beta
|
||||
*/
|
||||
public Level getFileLevelBarrier() { return (Level) items.get("fileLevelBarrier").get(); }
|
||||
|
||||
/**
|
||||
* @return the minimal {@link Level} to log inside the console
|
||||
* @since Envoy Client v0.2-beta
|
||||
*/
|
||||
public Level getConsoleLevelBarrier() { return (Level) items.get("consoleLevelBarrier").get(); }
|
||||
|
||||
}
|
||||
|
@ -29,17 +29,15 @@ public class ConfigItem<T> {
|
||||
* @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
|
||||
* @param mandatory indicated that this config item must be initialized with
|
||||
* a non-null value
|
||||
* @since Envoy Common v0.1-beta
|
||||
*/
|
||||
public ConfigItem(String commandLong, String commandShort, Function<String, T> parseFunction, T defaultValue, boolean mandatory) {
|
||||
public ConfigItem(String commandLong, String commandShort, Function<String, T> parseFunction, boolean mandatory) {
|
||||
this.commandLong = commandLong;
|
||||
this.commandShort = commandShort;
|
||||
this.parseFunction = parseFunction;
|
||||
this.mandatory = mandatory;
|
||||
value = defaultValue;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -52,7 +50,7 @@ public class ConfigItem<T> {
|
||||
* @since Envoy Common v0.1-beta
|
||||
*/
|
||||
public ConfigItem(String commandLong, String commandShort, Function<String, T> parseFunction) {
|
||||
this(commandLong, commandShort, parseFunction, null, false);
|
||||
this(commandLong, commandShort, parseFunction, false);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -83,6 +81,12 @@ public class ConfigItem<T> {
|
||||
*/
|
||||
public T get() { return value; }
|
||||
|
||||
/**
|
||||
* @param value the value to set
|
||||
* @since Envoy Common v0.2-beta
|
||||
*/
|
||||
protected void setValue(T value) { this.value = value; }
|
||||
|
||||
/**
|
||||
* @return {@code true} if this {@link ConfigItem} is mandatory for successful
|
||||
* application initialization
|
||||
|
@ -12,12 +12,9 @@ import envoy.data.Config;
|
||||
* Configures the {@link java.util.logging} API to output the log into the
|
||||
* console and a log file.
|
||||
* <p>
|
||||
* Call the {@link EnvoyLog#attach(String)} method to configure a part of the
|
||||
* logger hierarchy.
|
||||
* <p>
|
||||
* Project: <strong>envoy-client</strong><br>
|
||||
* File: <strong>EnvoyLogger.java</strong><br>
|
||||
* Created: <strong>14 Dec 2019</strong><br>
|
||||
* Created: <strong>14.12.2019</strong><br>
|
||||
*
|
||||
* @author Leon Hofmeister
|
||||
* @author Kai S. K. Engelbart
|
||||
@ -32,8 +29,7 @@ public class EnvoyLog {
|
||||
private EnvoyLog() {}
|
||||
|
||||
/**
|
||||
* Initializes logging. Call this method before calling the
|
||||
* {@link EnvoyLog#attach(String)} method.
|
||||
* Initializes logging.
|
||||
*
|
||||
* @param config the config providing the console and log file barriers
|
||||
* @since Envoy Common v0.1-beta
|
||||
@ -45,18 +41,19 @@ public class EnvoyLog {
|
||||
LogManager.getLogManager().reset();
|
||||
|
||||
// Configure log file
|
||||
final File logFile = new File((File) config.get("homeDirectory").get(),
|
||||
"log/envoy_user_" + DateTimeFormatter.ofPattern("yyyy-MM-dd--hh-mm-mm").format(LocalDateTime.now()) + ".log");
|
||||
final File logFile = new File(config.getHomeDirectory(),
|
||||
"log/" + DateTimeFormatter.ofPattern("yyyy-MM-dd--hh-mm").format(LocalDateTime.now()) + ".log");
|
||||
logFile.getParentFile().mkdirs();
|
||||
|
||||
// Configure formatting
|
||||
// Sample log entry: [2020-06-13 16:50:26] [INFORMATION] [envoy.client.ui.Startup] Closing connection...
|
||||
// Sample log entry: [2020-06-13 16:50:26] [INFORMATION]
|
||||
// [envoy.client.ui.Startup] Closing connection...
|
||||
System.setProperty("java.util.logging.SimpleFormatter.format", "[%1$tF %1$tT] [%4$-7s] [%3$s] %5$s %6$s%n");
|
||||
final SimpleFormatter formatter = new SimpleFormatter();
|
||||
|
||||
try {
|
||||
fileHandler = new FileHandler(logFile.getAbsolutePath());
|
||||
fileHandler.setLevel((Level) config.get("fileLevelBarrier").get());
|
||||
fileHandler.setLevel(config.getFileLevelBarrier());
|
||||
fileHandler.setFormatter(formatter);
|
||||
} catch (SecurityException | IOException e) {
|
||||
e.printStackTrace();
|
||||
@ -69,10 +66,11 @@ public class EnvoyLog {
|
||||
flush();
|
||||
}
|
||||
};
|
||||
consoleHandler.setLevel((Level) config.get("consoleLevelBarrier").get());
|
||||
consoleHandler.setLevel(config.getConsoleLevelBarrier());
|
||||
consoleHandler.setFormatter(formatter);
|
||||
|
||||
initialized = true;
|
||||
EnvoyLog.attach("envoy");
|
||||
}
|
||||
|
||||
/**
|
||||
@ -82,7 +80,7 @@ public class EnvoyLog {
|
||||
* @param path the path to the loggers to configure
|
||||
* @since Envoy Common v0.1-beta
|
||||
*/
|
||||
public static void attach(String path) {
|
||||
private static void attach(String path) {
|
||||
if (!initialized) throw new IllegalStateException("EnvoyLog is not initialized");
|
||||
|
||||
// Get root logger
|
||||
@ -105,22 +103,4 @@ public class EnvoyLog {
|
||||
* @since Envoy Common v0.1-beta
|
||||
*/
|
||||
public static Logger getLogger(Class<?> logClass) { return Logger.getLogger(logClass.getCanonicalName()); }
|
||||
|
||||
/**
|
||||
* Defines the logger level required for a record to be written to the log file.
|
||||
*
|
||||
* @param fileLevelBarrier the log file level
|
||||
* @since Envoy Common v0.1-beta
|
||||
*/
|
||||
public static void setFileLevelBarrier(Level fileLevelBarrier) { if (fileHandler != null) fileHandler.setLevel(fileLevelBarrier); }
|
||||
|
||||
/**
|
||||
* Defines the logger level required for a record to be written to the console.
|
||||
*
|
||||
* @param consoleLevelBarrier the console logger level
|
||||
* @since Envoy Common v0.1-beta
|
||||
*/
|
||||
public static void setConsoleLevelBarrier(Level consoleLevelBarrier) {
|
||||
if (consoleHandler != null) consoleHandler.setLevel(consoleLevelBarrier);
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user