csep-2025/client/src/main/java/client/utils/ConfigService.java
2025-12-04 18:09:30 +01:00

80 lines
1.8 KiB
Java

package client.utils;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.nio.file.Path;
import java.io.File;
import java.io.IOException;
public class ConfigService {
private final Path configPath;
private final ObjectMapper mapper = new ObjectMapper();
private Config config;
/*
Constructor that takes the path to the config file as it's parameter
*/
public ConfigService(Path configPath){
this.configPath = configPath;
load();
}
/*
Load needs to be called to load any changes from the config file
to the config attribute of the configService class.
Takes no parameters
*/
private void load(){
File file = configPath.toFile(); //reads the config file as file
if (!file.exists()) { //if file doesn't exist then it creates a config object
config = new Config();
return;
}
try{
config = mapper.readValue(file, Config.class); //uses Jackson to map the file to the config attribute
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public Path getConfigPath() {
return configPath;
}
public ObjectMapper getMapper() {
return mapper;
}
public Config getConfig() {
return config;
}
public void setConfig(Config config) {
this.config = config;
}
/*
The save method saves any changes done to the file
from the config object
*/
public void save(){
try {
File file = configPath.toFile(); // file is the config file here
mapper.writeValue(file, config); // here we edit the value of the file using config
}
catch (Exception e){
throw new RuntimeException(e);
}
}
}