webmarker-server/src/main/java/net/mindoverflow/webmarker/utils/config/ConfigManager.java

94 lines
2.7 KiB
Java

package net.mindoverflow.webmarker.utils.config;
import net.mindoverflow.webmarker.utils.messaging.MessageLevel;
import net.mindoverflow.webmarker.utils.messaging.Messenger;
import org.yaml.snakeyaml.Yaml;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
public class ConfigManager
{
private static final Messenger msg = new Messenger();
public static void checkFiles()
{
msg.send(MessageLevel.INFO, "Checking configuration files: ");
File configFile = FileType.CONFIG_YAML.file;
if(!configFile.exists())
{
try {
InputStream stream = ConfigManager.class.getResourceAsStream("/" + configFile.getName());
Files.copy(stream, Paths.get(configFile.getAbsolutePath()));
stream.close();
}
catch (IOException e)
{
msg.sendLine(MessageLevel.NONE, "FATAL");
e.printStackTrace();
msg.critical("Error creating missing file!");
System.exit(1);
}
}
msg.sendLine(MessageLevel.NONE, "OK");
}
public static void loadFiles()
{
msg.send(MessageLevel.INFO, "Loading configuration files: ");
try {
InputStream stream = new FileInputStream(FileType.CONFIG_YAML.file);
Yaml yaml = new Yaml();
FileType.CONFIG_YAML.yaml = yaml.load(stream);
} catch (FileNotFoundException e) {
e.printStackTrace();
msg.critical("Error loading config file!");
}
for(ConfigEntries entry : ConfigEntries.values())
{
String path = entry.getPath();
Object value = FileType.CONFIG_YAML.yaml.get(path);
entry.setValue(value);
}
msg.sendLine(MessageLevel.NONE, "OK");
for(ConfigEntries entry : ConfigEntries.values())
{
if(entry == ConfigEntries.JWT_SECRET) continue; // we don't want to log encryption secret key
msg.info(entry.name() + ": " + entry.getValue());
}
}
public static String getJarAbsolutePath()
{
Path currentPath = Paths.get("");
return currentPath.toAbsolutePath().toString();
}
public enum FileType
{
DATABASE_FILE(new File(getJarAbsolutePath() + File.separator + "database.sqlite"), null),
CONFIG_YAML(new File(getJarAbsolutePath() + File.separator + "config.yml"), new HashMap<>());
public File file;
public HashMap<String, Object> yaml;
FileType(File givenFile, HashMap<String, Object> yamlConfig)
{
file = givenFile;
yaml = yamlConfig;
}
}
}