84 lines
3.1 KiB
Java
84 lines
3.1 KiB
Java
package com.alttd.cometskyblock.configuration;
|
|
|
|
import org.jetbrains.annotations.NotNull;
|
|
import org.spongepowered.configurate.CommentedConfigurationNode;
|
|
import org.spongepowered.configurate.ConfigurateException;
|
|
import org.spongepowered.configurate.yaml.NodeStyle;
|
|
import org.spongepowered.configurate.yaml.YamlConfigurationLoader;
|
|
|
|
import java.nio.file.Path;
|
|
import java.util.concurrent.CompletableFuture;
|
|
import java.util.concurrent.atomic.AtomicReference;
|
|
import org.slf4j.Logger;
|
|
|
|
public class ConfigurationContainer<C extends Configuration> {
|
|
private final AtomicReference<C> config;
|
|
private final YamlConfigurationLoader loader;
|
|
private final CommentedConfigurationNode node;
|
|
private final Class<C> clazz;
|
|
private final Logger logger;
|
|
|
|
private ConfigurationContainer(final C config, final Class<C> clazz, final YamlConfigurationLoader loader, final CommentedConfigurationNode node, final Logger logger) {
|
|
this.config = new AtomicReference<>(config);
|
|
this.loader = loader;
|
|
this.node = node;
|
|
this.clazz = clazz;
|
|
this.logger = logger;
|
|
}
|
|
|
|
public CompletableFuture<Boolean> reload() {
|
|
return CompletableFuture.supplyAsync(() -> {
|
|
try {
|
|
final CommentedConfigurationNode node = loader.load();
|
|
C newConfig = node.get(clazz);
|
|
node.set(clazz, newConfig);
|
|
loader.save(node);
|
|
config.set(newConfig);
|
|
return true;
|
|
} catch (ConfigurateException exception) {
|
|
logger.error("Could not reload {} configuration file", clazz.getSimpleName(), exception);
|
|
return false;
|
|
}
|
|
});
|
|
}
|
|
|
|
public CompletableFuture<Boolean> save() {
|
|
return CompletableFuture.supplyAsync(() -> {
|
|
try {
|
|
node.set(clazz, get());
|
|
loader.save(node);
|
|
return true;
|
|
} catch (ConfigurateException exception) {
|
|
logger.error("Could not reload {} configuration file", clazz.getSimpleName(), exception);
|
|
return false;
|
|
}
|
|
});
|
|
}
|
|
|
|
public @NotNull C get() {
|
|
return this.config.get();
|
|
}
|
|
|
|
public static <C extends Configuration> ConfigurationContainer<C> load(final Logger logger, final Path path, final Class<C> clazz, final String file) {
|
|
final YamlConfigurationLoader loader = YamlConfigurationLoader.builder()
|
|
.defaultOptions(options -> options
|
|
.shouldCopyDefaults(true)
|
|
.header("")
|
|
)
|
|
.path(path.resolve(file + ".yml"))
|
|
.nodeStyle(NodeStyle.BLOCK)
|
|
.build();
|
|
try {
|
|
final CommentedConfigurationNode node = loader.load();
|
|
final C config = node.get(clazz);
|
|
node.set(clazz, config);
|
|
loader.save(node);
|
|
return new ConfigurationContainer<>(config, clazz, loader, node, logger);
|
|
} catch (ConfigurateException exception){
|
|
logger.error("Could not load {} configuration file", clazz.getSimpleName(), exception);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
}
|