Load config.yaml using its own charset

Strings in the config are therefore respected by the configured charset
This commit is contained in:
P0nk
2021-09-08 20:01:43 +02:00
parent c841e9952b
commit 52551b2451
3 changed files with 37 additions and 11 deletions

View File

@@ -1,32 +1,58 @@
package config;
import com.esotericsoftware.yamlbeans.YamlReader;
import constants.string.CharsetConstants;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
public class YamlConfig {
public static final YamlConfig config = fromFile("config.yaml");
private static final String CONFIG_FILE_NAME = "config.yaml";
public static final YamlConfig config = loadConfig(CONFIG_FILE_NAME);
public List<WorldConfig> worlds;
public ServerConfig server;
public static YamlConfig fromFile(String filename) {
private static YamlConfig loadConfig(String fileName) {
try {
YamlReader reader = new YamlReader(new FileReader(filename));
YamlReader reader = new YamlReader(new FileReader(fileName, CharsetConstants.CHARSET));
YamlConfig config = reader.read(YamlConfig.class);
reader.close();
return config;
} catch (FileNotFoundException e) {
String message = "Could not read config file " + filename + ": " + e.getMessage();
throw new RuntimeException(message);
} catch (IOException e) {
String message = "Could not successfully parse config file " + filename + ": " + e.getMessage();
throw new RuntimeException(message);
throw new RuntimeException(getLoadConfigErrorMessage(e));
}
}
private static String getLoadConfigErrorMessage(IOException e) {
if (e instanceof FileNotFoundException) {
return "Could not read config file " + CONFIG_FILE_NAME + ": " + e.getMessage();
}
return "Could not successfully parse config file " + CONFIG_FILE_NAME + ": " + e.getMessage();
}
public static String loadCharset() {
try {
YamlReader reader = new YamlReader(new FileReader(CONFIG_FILE_NAME, StandardCharsets.US_ASCII));
reader.getConfig().readConfig.setIgnoreUnknownProperties(true);
StrippedYamlConfig charsetConfig = reader.read(StrippedYamlConfig.class);
reader.close();
return charsetConfig.server.CHARSET;
} catch (IOException e) {
throw new RuntimeException(getLoadConfigErrorMessage(e));
}
}
private static class StrippedYamlConfig {
public StrippedServerConfig server;
private static class StrippedServerConfig {
public String CHARSET;
}
}
}

View File

@@ -56,7 +56,7 @@ public class CharsetConstants {
}
private static Charset loadCharset() {
String configCharset = YamlConfig.config.server.CHARSET;
String configCharset = YamlConfig.loadCharset();
if (configCharset != null) {
Language language = Language.fromCharset(configCharset);
return Charset.forName(language.getCharset());