Fixes a crash caused by StargateYamlConfiguration

This commit is contained in:
2023-04-20 16:02:57 +02:00
parent aa480faef2
commit 9d981f2cc6
7 changed files with 88 additions and 46 deletions

View File

@@ -207,7 +207,7 @@ public class Stargate extends JavaPlugin {
* @param message <p>A message describing what happened</p> * @param message <p>A message describing what happened</p>
*/ */
public static void debug(String route, String message) { public static void debug(String route, String message) {
if (stargateConfig == null || stargateConfig.isDebuggingEnabled()) { if (stargateConfig == null || !stargateConfig.isLoaded() || stargateConfig.isDebuggingEnabled()) {
logger.info("[Stargate::" + route + "] " + message); logger.info("[Stargate::" + route + "] " + message);
} else { } else {
logger.log(Level.FINEST, "[Stargate::" + route + "] " + message); logger.log(Level.FINEST, "[Stargate::" + route + "] " + message);
@@ -357,7 +357,7 @@ public class Stargate extends JavaPlugin {
super.reloadConfig(); super.reloadConfig();
this.configuration = new StargateYamlConfiguration(); this.configuration = new StargateYamlConfiguration();
try { try {
configuration.load(new File(getDataFolder(), configFileName)); this.configuration.load(new File(getDataFolder(), configFileName));
} catch (IOException | InvalidConfigurationException e) { } catch (IOException | InvalidConfigurationException e) {
e.printStackTrace(); e.printStackTrace();
} }
@@ -367,7 +367,7 @@ public class Stargate extends JavaPlugin {
public void saveConfig() { public void saveConfig() {
super.saveConfig(); super.saveConfig();
try { try {
configuration.save(new File(getDataFolder(), configFileName)); this.configuration.save(new File(getDataFolder(), configFileName));
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
@@ -387,13 +387,13 @@ public class Stargate extends JavaPlugin {
this.getConfig(); this.getConfig();
PluginDescriptionFile pluginDescriptionFile = this.getDescription(); PluginDescriptionFile pluginDescriptionFile = this.getDescription();
pluginManager = getServer().getPluginManager(); pluginManager = getServer().getPluginManager();
configuration = new StargateYamlConfiguration(); this.configuration = new StargateYamlConfiguration();
try { try {
configuration.load(new File(getDataFolder(), configFileName)); this.configuration.load(new File(getDataFolder(), configFileName));
} catch (IOException | InvalidConfigurationException e) { } catch (IOException | InvalidConfigurationException e) {
getLogger().log(Level.SEVERE, e.getMessage()); getLogger().log(Level.SEVERE, e.getMessage());
} }
configuration.options().copyDefaults(true); this.configuration.options().copyDefaults(true);
logger = Logger.getLogger("Minecraft"); logger = Logger.getLogger("Minecraft");
Server server = getServer(); Server server = getServer();

View File

@@ -14,6 +14,7 @@ import net.knarcraft.stargate.utility.PortalFileHelper;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.configuration.MemorySection;
import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.messaging.Messenger; import org.bukkit.plugin.messaging.Messenger;
@@ -48,6 +49,7 @@ public final class StargateConfig {
private String gateFolder; private String gateFolder;
private String portalFolder; private String portalFolder;
private String languageName = "en"; private String languageName = "en";
private boolean isLoaded = false;
private final Map<ConfigOption, Object> configOptions; private final Map<ConfigOption, Object> configOptions;
@@ -109,6 +111,17 @@ public final class StargateConfig {
DynmapManager.initialize(dynmapAPI); DynmapManager.initialize(dynmapAPI);
DynmapManager.addAllPortalMarkers(); DynmapManager.addAllPortalMarkers();
} }
this.isLoaded = true;
}
/**
* Gets whether this configuration has been fully loaded
*
* @return <p>True if fully loaded</p>
*/
public boolean isLoaded() {
return this.isLoaded;
} }
/** /**
@@ -365,10 +378,11 @@ public final class StargateConfig {
FileConfiguration newConfig = Stargate.getInstance().getConfiguration(); FileConfiguration newConfig = Stargate.getInstance().getConfiguration();
boolean isMigrating = false; boolean isMigrating = false;
if (newConfig.getString("lang") != null || newConfig.getString("economy.freeGatesGreen") != null || if (newConfig.getString("lang") != null || newConfig.getString("economy.taxAccount") == null) {
newConfig.getString("economy.taxAccount") == null) {
migrateConfig(newConfig); migrateConfig(newConfig);
isMigrating = true; isMigrating = true;
Stargate.getInstance().reloadConfig();
newConfig = Stargate.getInstance().getConfiguration();
} }
//Copy missing default values if any values are missing //Copy missing default values if any values are missing
@@ -409,6 +423,7 @@ public final class StargateConfig {
//If users have an outdated config, assume they also need to update their default gates //If users have an outdated config, assume they also need to update their default gates
if (isMigrating) { if (isMigrating) {
this.createMissingFolders();
GateHandler.writeDefaultGatesToFolder(gateFolder); GateHandler.writeDefaultGatesToFolder(gateFolder);
} }
@@ -486,6 +501,9 @@ public final class StargateConfig {
// Copy all keys to the new config // Copy all keys to the new config
for (String key : oldConfiguration.getKeys(true)) { for (String key : oldConfiguration.getKeys(true)) {
if (oldConfiguration.get(key) instanceof MemorySection) {
continue;
}
Stargate.debug("Stargate::migrateConfig", "Setting " + key + " to " + oldConfiguration.get(key)); Stargate.debug("Stargate::migrateConfig", "Setting " + key + " to " + oldConfiguration.get(key));
newConfiguration.set(key, oldConfiguration.get(key)); newConfiguration.set(key, oldConfiguration.get(key));
} }
@@ -527,12 +545,8 @@ public final class StargateConfig {
* Creates missing folders * Creates missing folders
*/ */
private void createMissingFolders() { private void createMissingFolders() {
File newPortalDir = new File(portalFolder); createMissingFolder(new File(gateFolder), "Unable to create gate directory");
if (!newPortalDir.exists()) { createMissingFolder(new File(portalFolder), "Unable to create portal directory");
if (!newPortalDir.mkdirs()) {
logger.severe("Unable to create portal directory");
}
}
File newFile = new File(portalFolder, Stargate.getInstance().getServer().getWorlds().get(0).getName() + File newFile = new File(portalFolder, Stargate.getInstance().getServer().getWorlds().get(0).getName() +
".db"); ".db");
if (!newFile.exists() && !newFile.getParentFile().exists()) { if (!newFile.exists() && !newFile.getParentFile().exists()) {
@@ -542,6 +556,20 @@ public final class StargateConfig {
} }
} }
/**
* Creates the given folder if it's missing
*
* @param folder <p>The folder to create</p>
* @param errorMessage <p>The error message to display if unable to create the folder</p>
*/
private void createMissingFolder(File folder, String errorMessage) {
if (!folder.exists()) {
if (!folder.mkdirs()) {
logger.severe(errorMessage);
}
}
}
/** /**
* Gets the folder all portals are stored in * Gets the folder all portals are stored in
* *

View File

@@ -313,14 +313,16 @@ public final class StargateGateConfig {
try { try {
PortalSignDrawer.setMainColor(ChatColor.of(mainSignColor.toUpperCase())); PortalSignDrawer.setMainColor(ChatColor.of(mainSignColor.toUpperCase()));
} catch (IllegalArgumentException | NullPointerException exception) { } catch (IllegalArgumentException | NullPointerException exception) {
Stargate.logWarning("You have specified an invalid main sign color in your config.yml. Defaulting to BLACK"); Stargate.logWarning("You have specified an invalid main sign color in your config.yml (" + mainSignColor +
"). Defaulting to BLACK");
PortalSignDrawer.setMainColor(ChatColor.BLACK); PortalSignDrawer.setMainColor(ChatColor.BLACK);
} }
try { try {
PortalSignDrawer.setHighlightColor(ChatColor.of(highlightSignColor.toUpperCase())); PortalSignDrawer.setHighlightColor(ChatColor.of(highlightSignColor.toUpperCase()));
} catch (IllegalArgumentException | NullPointerException exception) { } catch (IllegalArgumentException | NullPointerException exception) {
Stargate.logWarning("You have specified an invalid highlighting sign color in your config.yml. Defaulting to WHITE"); Stargate.logWarning("You have specified an invalid highlighting sign color in your config.yml (" +
highlightSignColor + "). Defaulting to WHITE");
PortalSignDrawer.setHighlightColor(ChatColor.WHITE); PortalSignDrawer.setHighlightColor(ChatColor.WHITE);
} }
} }

View File

@@ -16,6 +16,7 @@ import java.util.List;
*/ */
public class StargateYamlConfiguration extends YamlConfiguration { public class StargateYamlConfiguration extends YamlConfiguration {
public static final String START_OF_COMMENT_LINE = "[HASHTAG]";
static public final String END_OF_COMMENT = "_endOfComment_"; static public final String END_OF_COMMENT = "_endOfComment_";
static public final String START_OF_COMMENT = "comment_"; static public final String START_OF_COMMENT = "comment_";
@@ -51,7 +52,8 @@ public class StargateYamlConfiguration extends YamlConfiguration {
for (String line : configString.split("\n")) { for (String line : configString.split("\n")) {
if (line.trim().startsWith("#")) { if (line.trim().startsWith("#")) {
//Temporarily store the comment line //Temporarily store the comment line
currentComment.add(line.trim().replaceFirst("#", "")); currentComment.add(line.trim().replaceFirst(line.trim().startsWith("# ") ? "# " : "{2}#",
START_OF_COMMENT_LINE));
} else { } else {
//Write the full formatted comment to the StringBuilder //Write the full formatted comment to the StringBuilder
if (!currentComment.isEmpty()) { if (!currentComment.isEmpty()) {
@@ -119,6 +121,7 @@ public class StargateYamlConfiguration extends YamlConfiguration {
//Output the empty line as-is, as it's not part of a comment //Output the empty line as-is, as it's not part of a comment
finalText.append("\n"); finalText.append("\n");
} else if (isReadingCommentBlock) { } else if (isReadingCommentBlock) {
possibleComment = possibleComment.replace(START_OF_COMMENT_LINE, "");
//Output the comment with correct indentation //Output the comment with correct indentation
finalText.append(addIndentation(commentIndentation)).append("# ").append(possibleComment).append("\n"); finalText.append(addIndentation(commentIndentation)).append("# ").append(possibleComment).append("\n");
} else { } else {

View File

@@ -7,6 +7,7 @@ import org.bukkit.Material;
import org.bukkit.Tag; import org.bukkit.Tag;
import java.io.BufferedWriter; import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter; import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
@@ -290,7 +291,7 @@ public class Gate {
*/ */
public void save(String gateFolder) { public void save(String gateFolder) {
try { try {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(gateFolder + filename)); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(new File(gateFolder, filename)));
//Save main material names //Save main material names
writeConfig(bufferedWriter, "portal-open", portalOpenBlock.name()); writeConfig(bufferedWriter, "portal-open", portalOpenBlock.name());
@@ -311,6 +312,7 @@ public class Gate {
bufferedWriter.close(); bufferedWriter.close();
} catch (IOException ex) { } catch (IOException ex) {
Stargate.logSevere(String.format("Could not save Gate %s - %s", filename, ex.getMessage())); Stargate.logSevere(String.format("Could not save Gate %s - %s", filename, ex.getMessage()));
ex.printStackTrace();
} }
} }

View File

@@ -152,7 +152,7 @@ public class GateHandler {
} }
//Update gate file in case the format has changed between versions //Update gate file in case the format has changed between versions
gate.save(parentFolder + "/"); gate.save(parentFolder);
return gate; return gate;
} }

View File

@@ -108,6 +108,33 @@ gates:
# Or if using an easily destroyable open/closed material. # Or if using an easily destroyable open/closed material.
protectEntrance: false protectEntrance: false
cosmetic:
# Will the destination a networked portal last connected to be listed first in its scroll menu?
rememberDestination: false
# For networked gates, are destinations listed alphabetically instead of chronologically?
# (This applies to all non-fixed and non-random gates).
sortNetworkDestinations: false
# What color will StarGate use for the text on gate signs?
# Note that players can override this with DYE and/or GLOW_INK_SAC
mainSignColor: BLACK
# What color will StarGate use to accent the above text?
highlightSignColor: WHITE
# Text and highlight colors can be modified on a per-sign basis (below).
# Format: 'SIGN_TYPE:mainSignColor,highlightSignColor'
perSignColors:
- 'ACACIA:default,default'
- 'BIRCH:default,default'
- 'CRIMSON:inverted,inverted'
- 'DARK_OAK:inverted,inverted'
- 'JUNGLE:default,default'
- 'OAK:default,default'
- 'SPRUCE:inverted,inverted'
- 'WARPED:inverted,inverted'
# +----------------------------------------------------------------------------------------------+ # # +----------------------------------------------------------------------------------------------+ #
# | Economy | # # | Economy | #
# +----------------------------------------------------------------------------------------------+ # # +----------------------------------------------------------------------------------------------+ #
@@ -149,32 +176,12 @@ economy:
# https://hub.spigotmc.org/javadocs/spigot/org/bukkit/ChatColor.html # https://hub.spigotmc.org/javadocs/spigot/org/bukkit/ChatColor.html
freeGatesColor: DARK_GREEN freeGatesColor: DARK_GREEN
cosmetic: # Does your server have a tax account (closed economy)?
# Will the destination a networked portal last connected to be listed first in its scroll menu? # If so, please provide the name of your tax account (collected money will be sent to it).
rememberDestination: false # If not, leave this section blank (collected money will be deleted).
#
# For networked gates, are destinations listed alphabetically instead of chronologically? # Note that useCost money is excluded from this system when toOwner is true.
# (This applies to all non-fixed and non-random gates). taxAccount: ''
sortNetworkDestinations: false
# What color will StarGate use for the text on gate signs?
# Note that players can override this with DYE and/or GLOW_INK_SAC
mainSignColor: BLACK
# What color will StarGate use to accent the above text?
highlightSignColor: WHITE
# Text and highlight colors can be modified on a per-sign basis (below).
# Format: 'SIGN_TYPE:mainSignColor,highlightSignColor'
perSignColors:
- 'ACACIA:default,default'
- 'BIRCH:default,default'
- 'CRIMSON:inverted,inverted'
- 'DARK_OAK:inverted,inverted'
- 'JUNGLE:default,default'
- 'OAK:default,default'
- 'SPRUCE:inverted,inverted'
- 'WARPED:inverted,inverted'
# +----------------------------------------------------------------------------------------------+ # # +----------------------------------------------------------------------------------------------+ #
# | Technical | # # | Technical | #