58 lines
1.9 KiB
Java
58 lines
1.9 KiB
Java
package io.kamax.mxisd.config;
|
|
|
|
import org.slf4j.Logger;
|
|
import org.slf4j.LoggerFactory;
|
|
import org.yaml.snakeyaml.Yaml;
|
|
import org.yaml.snakeyaml.constructor.Constructor;
|
|
import org.yaml.snakeyaml.LoaderOptions;
|
|
|
|
import java.io.FileInputStream;
|
|
import java.io.FileWriter;
|
|
import java.io.IOException;
|
|
import java.io.File;
|
|
import java.util.Optional;
|
|
|
|
public class YamlConfigLoader {
|
|
|
|
private static final Logger log = LoggerFactory.getLogger(YamlConfigLoader.class);
|
|
|
|
public static MxisdConfig loadFromFile(String path) throws IOException {
|
|
File file = new File(path); // Define the file from the path
|
|
Constructor constructor = new Constructor(MxisdConfig.class); // Ensure correct import
|
|
Yaml yaml = new Yaml(constructor); // No change needed here, this is correct
|
|
|
|
// Load from YAML
|
|
try (FileInputStream inputStream = new FileInputStream(file)) {
|
|
return yaml.loadAs(inputStream, MxisdConfig.class);
|
|
} catch (IOException e) {
|
|
// Handle exceptions
|
|
throw e;
|
|
}
|
|
}
|
|
|
|
public static Optional<MxisdConfig> tryLoadFromFile(String path) {
|
|
try {
|
|
return Optional.of(loadFromFile(path));
|
|
} catch (IOException e) {
|
|
log.warn("Unable to load configuration file from path {}: {}", path, e.getMessage());
|
|
return Optional.empty();
|
|
}
|
|
}
|
|
|
|
public static void dumpConfig(MxisdConfig cfg, String outputPath) throws IOException {
|
|
// Initialize LoaderOptions for dumping if needed
|
|
LoaderOptions loaderOptions = new LoaderOptions();
|
|
// Customize loaderOptions as necessary
|
|
|
|
Yaml yaml = new Yaml(loaderOptions);
|
|
|
|
try (FileWriter writer = new FileWriter(new File(outputPath))) {
|
|
yaml.dump(cfg, writer);
|
|
log.info("Configuration dumped successfully to {}", outputPath);
|
|
} catch (IOException e) {
|
|
log.error("Failed to dump YAML configuration to path: {}", outputPath, e);
|
|
throw e;
|
|
}
|
|
}
|
|
}
|