Updates KnarLib, uses improved formatting and removes redundant code

This commit is contained in:
2025-09-13 23:57:05 +02:00
parent d80907b5fb
commit fe8200813f
26 changed files with 207 additions and 609 deletions

View File

@@ -91,8 +91,8 @@ permissions), so you only need the most permissive one.
<details>
<summary>The full list of permission nodes may be found below: (Click to expand)</summary>
Note: `-` is used to show inheritance, such as `stargate.use` being a parent of `stargate.world`, `stargate.network`, and
`stargate.server`, thus giving all permissions of the indented items following the unindented node.
Note: `-` is used to show inheritance, such as `stargate.use` being a parent of `stargate.world`, `stargate.network`,
and `stargate.server`, thus giving all permissions of the indented items following the unindented node.
| Node | Description |
|-------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------|

View File

@@ -77,7 +77,7 @@
<dependency>
<groupId>net.knarcraft</groupId>
<artifactId>knarlib</artifactId>
<version>1.2.5</version>
<version>1.2.18</version>
<scope>compile</scope>
</dependency>
<dependency>

View File

@@ -1,14 +1,17 @@
package net.knarcraft.stargate;
import net.knarcraft.knarlib.formatting.StringFormatter;
import net.knarcraft.knarlib.formatting.Translator;
import net.knarcraft.knarlib.plugin.ConfigCommentPlugin;
import net.knarcraft.knarlib.util.ConfigHelper;
import net.knarcraft.knarlib.util.UpdateChecker;
import net.knarcraft.stargate.command.CommandStarGate;
import net.knarcraft.stargate.command.StarGateTabCompleter;
import net.knarcraft.stargate.config.EconomyConfig;
import net.knarcraft.stargate.config.Message;
import net.knarcraft.stargate.config.MessageSender;
import net.knarcraft.stargate.config.SGFormatBuilder;
import net.knarcraft.stargate.config.StargateConfig;
import net.knarcraft.stargate.config.StargateGateConfig;
import net.knarcraft.stargate.config.StargateYamlConfiguration;
import net.knarcraft.stargate.container.BlockChangeRequest;
import net.knarcraft.stargate.container.ChunkUnloadRequest;
import net.knarcraft.stargate.container.ControlBlockUpdateRequest;
@@ -29,20 +32,14 @@ import net.knarcraft.stargate.thread.ControlBlocksUpdateThread;
import net.knarcraft.stargate.thread.StarGateThread;
import net.knarcraft.stargate.utility.BStatsHelper;
import org.bukkit.Bukkit;
import org.bukkit.Server;
import org.bukkit.command.PluginCommand;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.java.JavaPluginLoader;
import org.bukkit.scheduler.BukkitScheduler;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
@@ -55,7 +52,7 @@ Copyright (C) 2011 Shaun (sturmeh)
Copyright (C) 2011 Dinnerbone
Copyright (C) 2011-2013 Steven "Drakia" Scott <Contact@TheDgtl.net>
Copyright (C) 2015-2020 Michael Smith (PseudoKnight)
Copyright (C) 2021-2022 Kristian Knarvik (EpicKnarvik97)
Copyright (C) 2021-2025 Kristian Knarvik (EpicKnarvik97)
The following license notice applies to all source and resource files in the Stargate project:
@@ -77,7 +74,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
* The main class of the Stargate plugin
*/
@SuppressWarnings("unused")
public class Stargate extends JavaPlugin {
public class Stargate extends ConfigCommentPlugin {
private static final String CONFIG_FILE_NAME = "config.yml";
private static final Queue<BlockChangeRequest> controlBlockUpdateRequestQueue = new LinkedList<>();
@@ -90,7 +87,6 @@ public class Stargate extends JavaPlugin {
private static PluginManager pluginManager;
private static StargateConfig stargateConfig;
private static String updateAvailable = null;
private FileConfiguration configuration;
/**
* Empty constructor necessary for Spigot
@@ -184,16 +180,6 @@ public class Stargate extends JavaPlugin {
return CONTROL_BLOCK_UPDATE_REQUEST_QUEUE;
}
/**
* Gets the sender for sending messages to players
*
* @return <p>The sender for sending messages to players</p>
*/
@NotNull
public static MessageSender getMessageSender() {
return stargateConfig.getMessageSender();
}
/**
* Gets the object containing gate configuration values
*
@@ -322,16 +308,6 @@ public class Stargate extends JavaPlugin {
return stargateConfig.getStargateGateConfig().getDefaultPortalNetwork();
}
/**
* Gets a translated string given its message key
*
* @param name <p>The name/key of the string to get</p>
* @return <p>The full translated string</p>
*/
public static @NotNull String getString(@NotNull Message name) {
return stargateConfig.getLanguageLoader().getString(name);
}
/**
* Gets a backup string given its message key
*
@@ -342,19 +318,6 @@ public class Stargate extends JavaPlugin {
return stargateConfig.getLanguageLoader().getBackupString(name);
}
/**
* Replaces a variable in a string
*
* @param input <p>The input containing the variables</p>
* @param search <p>The variable to replace</p>
* @param value <p>The replacement value</p>
* @return <p>The input string with the search replaced with value</p>
*/
@NotNull
public static String replacePlaceholders(@NotNull String input, @NotNull String search, @NotNull String value) {
return input.replace(search, value);
}
/**
* Gets this plugin's plugin manager
*
@@ -375,37 +338,6 @@ public class Stargate extends JavaPlugin {
return stargateConfig.getEconomyConfig();
}
/**
* Gets the raw configuration
*
* @return <p>The raw configuration</p>
*/
@NotNull
public FileConfiguration getConfiguration() {
return this.configuration;
}
@Override
public void reloadConfig() {
super.reloadConfig();
this.configuration = new StargateYamlConfiguration();
try {
this.configuration.load(new File(getDataFolder(), CONFIG_FILE_NAME));
} catch (IOException | InvalidConfigurationException exception) {
logSevere("Unable to load the configuration! Message: " + exception.getMessage());
}
}
@Override
public void saveConfig() {
super.saveConfig();
try {
this.configuration.save(new File(getDataFolder(), CONFIG_FILE_NAME));
} catch (IOException exception) {
logSevere("Unable to save the configuration! Message: " + exception.getMessage());
}
}
@Override
public void onDisable() {
PortalHandler.closeAllPortals();
@@ -420,19 +352,12 @@ public class Stargate extends JavaPlugin {
public void onEnable() {
Stargate.stargate = this;
Stargate.logger = getLogger();
this.saveDefaultConfig();
this.getConfig();
ConfigHelper.saveDefaults(this);
PluginDescriptionFile pluginDescriptionFile = this.getDescription();
pluginManager = getServer().getPluginManager();
this.configuration = new StargateYamlConfiguration();
try {
this.configuration.load(new File(getDataFolder(), CONFIG_FILE_NAME));
} catch (IOException | InvalidConfigurationException exception) {
getLogger().log(Level.SEVERE, exception.getMessage());
}
this.configuration.options().copyDefaults(true);
Server server = getServer();
// Set temporary string formatter before strings are loaded
SGFormatBuilder.setStringFormatter(new StringFormatter(this.getDescription().getName(), new Translator()));
try {
stargateConfig = new StargateConfig(logger);
@@ -456,7 +381,7 @@ public class Stargate extends JavaPlugin {
//Run necessary threads
runThreads();
this.registerCommands();
registerCommand("stargate", new CommandStarGate(this), new StarGateTabCompleter());
//Check for any available updates
UpdateChecker.checkForUpdate(this, "https://api.spigotmc.org/legacy/update.php?resource=109355",
@@ -493,17 +418,6 @@ public class Stargate extends JavaPlugin {
pluginManager.registerEvents(new EntitySpawnListener(), this);
}
/**
* Registers a command for this plugin
*/
private void registerCommands() {
PluginCommand stargateCommand = this.getCommand("stargate");
if (stargateCommand != null) {
stargateCommand.setExecutor(new CommandStarGate(this));
stargateCommand.setTabCompleter(new StarGateTabCompleter());
}
}
/**
* Gets the chunk unload queue containing chunks to unload
*

View File

@@ -6,6 +6,7 @@ import net.knarcraft.stargate.config.ConfigTag;
import net.knarcraft.stargate.config.DynmapManager;
import net.knarcraft.stargate.config.Message;
import net.knarcraft.stargate.config.OptionDataType;
import net.knarcraft.stargate.config.SGFormatBuilder;
import net.knarcraft.stargate.portal.Portal;
import net.knarcraft.stargate.portal.PortalRegistry;
import net.knarcraft.stargate.portal.PortalSignDrawer;
@@ -32,7 +33,7 @@ public class CommandConfig implements CommandExecutor {
@NotNull String[] args) {
if (commandSender instanceof Player player) {
if (!player.hasPermission("stargate.admin.config")) {
Stargate.getMessageSender().sendErrorMessage(commandSender, "Permission Denied");
new SGFormatBuilder("Permission Denied").error(commandSender);
return true;
}
}
@@ -69,7 +70,7 @@ public class CommandConfig implements CommandExecutor {
*/
private void updateConfigValue(@NotNull ConfigOption selectedOption, @NotNull CommandSender commandSender,
@NotNull String value) {
FileConfiguration configuration = Stargate.getInstance().getConfiguration();
FileConfiguration configuration = Stargate.getInstance().getConfig();
//Validate any sign colors
if (ConfigTag.COLOR.isTagged(selectedOption)) {
@@ -168,12 +169,11 @@ public class CommandConfig implements CommandExecutor {
*/
private void updateListConfigValue(@NotNull ConfigOption selectedOption, @NotNull CommandSender commandSender,
@NotNull String[] arguments) {
FileConfiguration configuration = Stargate.getInstance().getConfiguration();
FileConfiguration configuration = Stargate.getInstance().getConfig();
if (selectedOption == ConfigOption.PER_SIGN_COLORS) {
if (arguments.length < 4) {
Stargate.getMessageSender().sendErrorMessage(commandSender, "Usage: /sg config perSignColors " +
"<SIGN_TYPE> <MAIN_COLOR> <HIGHLIGHTING_COLOR>");
new SGFormatBuilder("Usage: /sg config perSignColors <SIGN_TYPE> <MAIN_COLOR> <HIGHLIGHTING_COLOR>").error(commandSender);
return;
}
@@ -200,7 +200,7 @@ public class CommandConfig implements CommandExecutor {
private String parsePerSignColorInput(@NotNull CommandSender commandSender, @NotNull String[] arguments) {
//Make sure the sign type is an actual sign
if (Material.matchMaterial(arguments[1] + "_SIGN") == null) {
Stargate.getMessageSender().sendErrorMessage(commandSender, "The given sign type is invalid");
new SGFormatBuilder("The given sign type is invalid").error(commandSender);
return null;
}
String colorString = arguments[1] + ":";
@@ -213,7 +213,7 @@ public class CommandConfig implements CommandExecutor {
if (validatePerSignColor(arguments[i + 2])) {
newColors[i] = arguments[i + 2];
} else {
Stargate.getMessageSender().sendErrorMessage(commandSender, errorMessage[i]);
new SGFormatBuilder(errorMessage[i]).error(commandSender);
return null;
}
}
@@ -265,7 +265,7 @@ public class CommandConfig implements CommandExecutor {
//Save the config file and reload if necessary
Stargate.getInstance().saveConfig();
Stargate.getMessageSender().sendSuccessMessage(commandSender, "Config updated");
new SGFormatBuilder("Config updated").success(commandSender);
//Reload whatever is necessary
reloadIfNecessary(commandSender, selectedOption);

View File

@@ -1,6 +1,7 @@
package net.knarcraft.stargate.command;
import net.knarcraft.stargate.Stargate;
import net.knarcraft.stargate.config.SGFormatBuilder;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
@@ -17,7 +18,7 @@ public class CommandReload implements CommandExecutor {
@NotNull String[] args) {
if (commandSender instanceof Player player) {
if (!player.hasPermission("stargate.admin.reload")) {
Stargate.getMessageSender().sendErrorMessage(commandSender, "Permission Denied");
new SGFormatBuilder("Permission Denied").error(commandSender);
return true;
}
}

View File

@@ -192,10 +192,10 @@ public final class EconomyConfig {
this.vault = vault;
return true;
} else {
Stargate.logInfo(Stargate.getString(Message.ECONOMY_LOAD_ERROR));
Stargate.logInfo(new SGFormatBuilder(Message.ECONOMY_LOAD_ERROR).toString());
}
} else {
Stargate.logInfo(Stargate.getString(Message.VAULT_LOAD_ERROR));
Stargate.logInfo(new SGFormatBuilder(Message.VAULT_LOAD_ERROR).toString());
}
configOptions.put(ConfigOption.USE_ECONOMY, false);
return false;

View File

@@ -113,10 +113,10 @@ public final class LanguageLoader {
private void updateLanguage(@NotNull String language) {
Map<Message, String> currentLanguageValues = load(language);
InputStream inputStream = getClass().getResourceAsStream("/lang/" + language + ".txt");
InputStream inputStream = FileHelper.getInputStreamForInternalFile("/lang/" + language + ".txt");
if (inputStream == null) {
Stargate.logInfo(String.format("The language %s is not available. Falling back to english, You can add a " +
"custom language by creating a new text file in the lang directory.", language));
Stargate.logInfo(String.format("Unable to find internal language file for %s. This will normally not " +
"cause any problems, except newly added translatable strings won't be automatically added", language));
Stargate.debug("LanguageLoader::updateLanguage", String.format("Unable to load /lang/%s.txt", language));
return;
}
@@ -209,6 +209,7 @@ public final class LanguageLoader {
* @param lang <p>The language to load</p>
* @return <p>A mapping between loaded string indexes and the strings to display</p>
*/
@Nullable
private Map<Message, String> load(@NotNull String lang) {
return load(lang, null);
}
@@ -220,6 +221,7 @@ public final class LanguageLoader {
* @param inputStream <p>An optional input stream to use. Defaults to using a file input stream</p>
* @return <p>A mapping between loaded string indexes and the strings to display</p>
*/
@Nullable
private Map<Message, String> load(@NotNull String lang, @Nullable InputStream inputStream) {
BufferedReader bufferedReader;
try {
@@ -257,6 +259,12 @@ public final class LanguageLoader {
}
}
/**
* Converts a map from string key to message into a map from message key to message
*
* @param configurationStrings <p>The map to convert</p>
* @return <p>The converted map</p>
*/
@NotNull
private Map<Message, String> fromStringMap(@NotNull Map<String, String> configurationStrings) {
Map<Message, String> output = new EnumMap<>(Message.class);

View File

@@ -1,62 +0,0 @@
package net.knarcraft.stargate.config;
import net.md_5.bungee.api.ChatColor;
import org.bukkit.command.CommandSender;
import org.jetbrains.annotations.NotNull;
/**
* The message sender is responsible sending messages to players with correct coloring and formatting
*/
public final class MessageSender {
private final LanguageLoader languageLoader;
/**
* Instantiates a new message sender
*
* @param languageLoader <p>The language loader to get translated strings from</p>
*/
public MessageSender(@NotNull LanguageLoader languageLoader) {
this.languageLoader = languageLoader;
}
/**
* Sends an error message to a player
*
* @param player <p>The player to send the message to</p>
* @param message <p>The message to send</p>
*/
public void sendErrorMessage(@NotNull CommandSender player, @NotNull String message) {
sendMessage(player, message, true);
}
/**
* Sends a success message to a player
*
* @param player <p>The player to send the message to</p>
* @param message <p>The message to send</p>
*/
public void sendSuccessMessage(@NotNull CommandSender player, @NotNull String message) {
sendMessage(player, message, false);
}
/**
* Sends a message to a player
*
* @param sender <p>The player to send the message to</p>
* @param message <p>The message to send</p>
* @param error <p>Whether the message sent is an error</p>
*/
private void sendMessage(@NotNull CommandSender sender, @NotNull String message, boolean error) {
if (message.isEmpty()) {
return;
}
message = ChatColor.translateAlternateColorCodes('&', message);
if (error) {
sender.sendMessage(ChatColor.RED + languageLoader.getString(Message.PREFIX) + ChatColor.WHITE + message);
} else {
sender.sendMessage(ChatColor.GREEN + languageLoader.getString(Message.PREFIX) + ChatColor.WHITE + message);
}
}
}

View File

@@ -0,0 +1,40 @@
package net.knarcraft.stargate.config;
import net.knarcraft.knarlib.formatting.FormatBuilder;
import net.knarcraft.stargate.Stargate;
import org.jetbrains.annotations.NotNull;
/**
* A customized format builder for automatic translation of Stargate messages
*/
public class SGFormatBuilder extends FormatBuilder {
/**
* Instantiates a new format builder
*/
public SGFormatBuilder() {
super();
}
/**
* Instantiates a new format builder
*
* <p>If the input is a list, it will be joined using the default delimiter: ",".</p>
*
* @param input <p>The input to use as the initial string of this format builder</p>
* @throws IllegalStateException <p>If the string formatter has not been set, and the input is a translatable message</p>
*/
public <K> SGFormatBuilder(@NotNull K input) throws IllegalStateException {
super(input);
}
@Override
@NotNull
protected <K> String asString(@NotNull K input, @NotNull String delimiter) {
if (input instanceof Message message) {
return Stargate.getStargateConfig().getLanguageLoader().getString(message);
}
return super.asString(input, delimiter);
}
}

View File

@@ -1,7 +1,9 @@
package net.knarcraft.stargate.config;
import net.knarcraft.knarlib.formatting.StringFormatter;
import net.knarcraft.knarlib.formatting.Translator;
import net.knarcraft.knarlib.property.ColorConversion;
import net.knarcraft.knarlib.util.FileHelper;
import net.knarcraft.knarlib.util.ConfigHelper;
import net.knarcraft.stargate.Stargate;
import net.knarcraft.stargate.container.BlockChangeRequest;
import net.knarcraft.stargate.listener.BungeeCordListener;
@@ -14,16 +16,12 @@ import net.knarcraft.stargate.utility.PortalFileHelper;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.MemorySection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.messaging.Messenger;
import org.dynmap.DynmapAPI;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
@@ -44,7 +42,6 @@ public final class StargateConfig {
private final HashSet<String> managedWorlds = new HashSet<>();
private StargateGateConfig stargateGateConfig;
private MessageSender messageSender;
private final LanguageLoader languageLoader;
private EconomyConfig economyConfig;
private final Logger logger;
@@ -100,7 +97,9 @@ public final class StargateConfig {
languageLoader.setChosenLanguage(languageName);
languageLoader.reload();
messageSender = new MessageSender(languageLoader);
// Update prefix of the format builder
SGFormatBuilder.setStringFormatter(getStringFormatter());
if (isDebuggingEnabled()) {
languageLoader.debug();
}
@@ -253,7 +252,10 @@ public final class StargateConfig {
//Reload portal markers
DynmapManager.addAllPortalMarkers();
messageSender.sendErrorMessage(sender, languageLoader.getString(Message.RELOADED));
// Update prefix of the format builder
SGFormatBuilder.setStringFormatter(getStringFormatter());
new SGFormatBuilder(Message.RELOADED).error(sender);
}
/**
@@ -398,14 +400,14 @@ public final class StargateConfig {
*/
public void loadConfig() {
Stargate.getInstance().reloadConfig();
FileConfiguration newConfig = Stargate.getInstance().getConfiguration();
FileConfiguration newConfig = Stargate.getInstance().getConfig();
boolean isMigrating = false;
if (newConfig.getString("lang") != null || newConfig.getString("economy.taxAccount") == null) {
migrateConfig(newConfig);
ConfigHelper.migrateConfig(Stargate.getInstance());
isMigrating = true;
Stargate.getInstance().reloadConfig();
newConfig = Stargate.getInstance().getConfiguration();
newConfig = Stargate.getInstance().getConfig();
}
//Copy missing default values if any values are missing
@@ -498,79 +500,6 @@ public final class StargateConfig {
Stargate.logInfo(String.format("Loaded %s gate layouts", GateHandler.getGateCount()));
}
/**
* Changes all configuration values from the old name to the new name
*
* @param currentConfiguration <p>The current config to back up</p>
*/
private void migrateConfig(@NotNull FileConfiguration currentConfiguration) {
String debugPath = "StargateConfig::migrateConfig";
//Save the old config just in case something goes wrong
try {
currentConfiguration.save(new File(dataFolderPath, "config.yml.old"));
} catch (IOException exception) {
Stargate.debug(debugPath, "Unable to save old backup and do migration");
return;
}
//Load old and new configuration
Stargate.getInstance().reloadConfig();
FileConfiguration oldConfiguration = Stargate.getInstance().getConfig();
InputStream configStream = FileHelper.getInputStreamForInternalFile("/config.yml");
if (configStream == null) {
Stargate.logSevere("Could not migrate the configuration, as the internal configuration could not be read!");
return;
}
YamlConfiguration newConfiguration = StargateYamlConfiguration.loadConfiguration(
FileHelper.getBufferedReaderFromInputStream(configStream));
//Read all available config migrations
Map<String, String> migrationFields;
try {
InputStream migrationStream = FileHelper.getInputStreamForInternalFile("/config-migrations.txt");
if (migrationStream == null) {
Stargate.logSevere("Could not migrate the configuration, as the internal migration paths could not be read!");
return;
}
migrationFields = FileHelper.readKeyValuePairs(FileHelper.getBufferedReaderFromInputStream(migrationStream),
"=", ColorConversion.NORMAL);
} catch (IOException exception) {
Stargate.debug(debugPath, "Unable to load config migration file");
return;
}
//Replace old config names with the new ones
for (String key : migrationFields.keySet()) {
if (oldConfiguration.contains(key)) {
String newPath = migrationFields.get(key);
Object oldValue = oldConfiguration.get(key);
if (!newPath.trim().isEmpty()) {
oldConfiguration.set(newPath, oldValue);
}
oldConfiguration.set(key, null);
}
}
// Copy all keys to the new config
for (String key : oldConfiguration.getKeys(true)) {
if (oldConfiguration.get(key) instanceof MemorySection) {
continue;
}
Stargate.debug(debugPath, "Setting " + key + " to " +
oldConfiguration.get(key));
newConfiguration.set(key, oldConfiguration.get(key));
}
try {
newConfiguration.save(new File(dataFolderPath, "config.yml"));
} catch (IOException exception) {
Stargate.debug(debugPath, "Unable to save migrated config");
}
Stargate.getInstance().reloadConfig();
}
/**
* Loads economy from Vault
*/
@@ -579,7 +508,7 @@ public final class StargateConfig {
if (economyConfig.setupEconomy(Stargate.getPluginManager()) && economyConfig.getEconomy() != null &&
economyConfig.getVault() != null) {
String vaultVersion = economyConfig.getVault().getDescription().getVersion();
Stargate.logInfo(Stargate.replacePlaceholders(Stargate.getString(Message.VAULT_LOADED), "%version%", vaultVersion));
Stargate.logInfo(new SGFormatBuilder(Message.VAULT_LOADED).replace("%version%", vaultVersion).toString());
}
}
@@ -642,16 +571,6 @@ public final class StargateConfig {
return gateFolder;
}
/**
* Gets the sender for sending messages to players
*
* @return <p>The sender for sending messages to players</p>
*/
@NotNull
public MessageSender getMessageSender() {
return messageSender;
}
/**
* Gets the language loader containing translated strings
*
@@ -662,4 +581,42 @@ public final class StargateConfig {
return languageLoader;
}
/**
* Gets the string formatter to use
*/
@NotNull
private StringFormatter getStringFormatter() {
// In order to allow automatic customization of prefix color, parse it properly
String rawPrefix = getLanguageLoader().getString(Message.PREFIX);
String colorPattern = "(?:[&§][a-fA-F0-9klmnor]|&?#[0-9a-fA-F]{6}|§x(?:§[a-fA-F0-9]){6})*";
Pattern pattern = Pattern.compile("(" + colorPattern + "\\[" + colorPattern + ")(\\w+)(" +
colorPattern + "]" + colorPattern + ")");
return getStringFormatter(rawPrefix, pattern);
}
/**
* Gets the string formatter to use
*
* @param rawPrefix <p>The formatter prefix to parse</p>
* @param pattern <p>The pattern to use for parsing</p>
*/
private static @NotNull StringFormatter getStringFormatter(String rawPrefix, Pattern pattern) {
String prefix = rawPrefix;
String namePrefix = "[";
String nameSuffix = "]";
Matcher matcher = pattern.matcher(rawPrefix);
if (matcher.find()) {
namePrefix = matcher.group(1).trim();
prefix = matcher.group(2).trim();
nameSuffix = matcher.group(3).trim();
}
StringFormatter stringFormatter = new StringFormatter(prefix, new Translator());
stringFormatter.setColorConversion(ColorConversion.RGB);
stringFormatter.setNamePrefix(namePrefix);
stringFormatter.setNameSuffix(nameSuffix);
return stringFormatter;
}
}

View File

@@ -1,227 +0,0 @@
package net.knarcraft.stargate.config;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* A YAML configuration which retains all comments
*
* <p>This configuration converts all comments to YAML values when loaded, which all start with comment_. When saved,
* those YAML values are converted to normal text comments. This ensures that the comments aren't removed by the
* YamlConfiguration during its parsing.</p>
*
* @author Kristian Knarvik
* @author Thorin
*/
public class StargateYamlConfiguration extends YamlConfiguration {
private static final String START_OF_COMMENT_LINE = "[HASHTAG]";
private static final String END_OF_COMMENT = "_endOfComment_";
private static final String START_OF_COMMENT = "comment_";
@Override
@NotNull
@SuppressWarnings("deprecation")
protected String buildHeader() {
return "";
}
@Override
@NotNull
public String saveToString() {
// Convert YAML comments to normal comments
return this.convertYAMLMappingsToComments(super.saveToString());
}
@Override
public void loadFromString(@NotNull String contents) throws InvalidConfigurationException {
// Convert normal comments to YAML comments to prevent them from disappearing
super.loadFromString(this.convertCommentsToYAMLMappings(contents));
}
/**
* Reads a file with comments, and recreates them into yaml mappings
*
* <p>A mapping follows this format: comment_{CommentNumber}: "The comment"
* This needs to be done as comments otherwise get removed using
* the {@link FileConfiguration#save(File)} method. The config
* needs to be saved if a config value has changed.</p>
*/
@NotNull
private String convertCommentsToYAMLMappings(@NotNull String configString) {
StringBuilder yamlBuilder = new StringBuilder();
List<String> currentComment = new ArrayList<>();
int commentId = 0;
int previousIndentation = 0;
for (String line : configString.split("\n")) {
String trimmed = line.trim();
if (trimmed.startsWith("#")) {
// Store the indentation of the block
if (currentComment.isEmpty()) {
previousIndentation = getIndentation(line);
}
//Temporarily store the comment line
addComment(currentComment, trimmed);
} else {
addYamlString(yamlBuilder, currentComment, line, previousIndentation, commentId);
commentId++;
previousIndentation = 0;
}
}
return yamlBuilder.toString();
}
/**
* Adds a YAML string to the given string builder
*
* @param yamlBuilder <p>The string builder used for building YAML</p>
* @param currentComment <p>The comment to add as a YAML string</p>
* @param line <p>The current line</p>
* @param previousIndentation <p>The indentation of the current block comment</p>
* @param commentId <p>The id of the comment</p>
*/
private void addYamlString(@NotNull StringBuilder yamlBuilder, @NotNull List<String> currentComment,
@NotNull String line, int previousIndentation, int commentId) {
String trimmed = line.trim();
//Write the full formatted comment to the StringBuilder
if (!currentComment.isEmpty()) {
int indentation = trimmed.isEmpty() ? previousIndentation : getIndentation(line);
generateCommentYAML(yamlBuilder, currentComment, commentId, indentation);
currentComment.clear();
}
//Add the non-comment line assuming it isn't empty
if (!trimmed.isEmpty()) {
yamlBuilder.append(line).append("\n");
}
}
/**
* Adds the given comment to the given list
*
* @param commentParts <p>The list to add to</p>
* @param comment <p>The comment to add</p>
*/
private void addComment(@NotNull List<String> commentParts, @NotNull String comment) {
if (comment.startsWith("# ")) {
commentParts.add(comment.replaceFirst("# ", START_OF_COMMENT_LINE));
} else {
commentParts.add(comment.replaceFirst("#", START_OF_COMMENT_LINE));
}
}
/**
* Generates a YAML-compatible string for one comment block
*
* @param yamlBuilder <p>The string builder to add the generated YAML to</p>
* @param commentLines <p>The lines of the comment to convert into YAML</p>
* @param commentId <p>The unique id of the comment</p>
* @param indentation <p>The indentation to add to every line</p>
*/
private void generateCommentYAML(@NotNull StringBuilder yamlBuilder, @NotNull List<String> commentLines,
int commentId, int indentation) {
String subIndentation = this.addIndentation(indentation + 2);
//Add the comment start marker
yamlBuilder.append(this.addIndentation(indentation)).append(START_OF_COMMENT).append(commentId).append(": |\n");
for (String commentLine : commentLines) {
//Add each comment line with the proper indentation
yamlBuilder.append(subIndentation).append(commentLine).append("\n");
}
//Add the comment end marker
yamlBuilder.append(subIndentation).append(subIndentation).append(END_OF_COMMENT).append("\n");
}
/**
* Converts the internal YAML mapping format to a readable config file
*
* <p>The internal YAML structure is converted to a string with the same format as a standard configuration file.
* The internal structure has comments in the format: START_OF_COMMENT + id + multi-line YAML string +
* END_OF_COMMENT.</p>
*
* @param yamlString <p>A string using the YAML format</p>
* @return <p>The corresponding comment string</p>
*/
@NotNull
private String convertYAMLMappingsToComments(@NotNull String yamlString) {
StringBuilder finalText = new StringBuilder();
String[] lines = yamlString.split("\n");
for (int currentIndex = 0; currentIndex < lines.length; currentIndex++) {
String line = lines[currentIndex];
String possibleComment = line.trim();
if (possibleComment.startsWith(START_OF_COMMENT)) {
//Add an empty line before every comment block
finalText.append("\n");
currentIndex = readComment(finalText, lines, currentIndex + 1, getIndentation(line));
} else {
//Output the configuration key
finalText.append(line).append("\n");
}
}
return finalText.toString().trim();
}
/**
* Fully reads a comment
*
* @param builder <p>The string builder to write to</p>
* @param lines <p>The lines to read from</p>
* @param startIndex <p>The index to start reading from</p>
* @param commentIndentation <p>The indentation of the read comment</p>
* @return <p>The index containing the next non-comment line</p>
*/
private int readComment(@NotNull StringBuilder builder, @NotNull String[] lines, int startIndex,
int commentIndentation) {
for (int currentIndex = startIndex; currentIndex < lines.length; currentIndex++) {
String line = lines[currentIndex];
String possibleComment = line.trim();
if (!line.contains(END_OF_COMMENT)) {
possibleComment = possibleComment.replace(START_OF_COMMENT_LINE, "");
builder.append(addIndentation(commentIndentation)).append("# ").append(possibleComment).append("\n");
} else {
return currentIndex;
}
}
return startIndex;
}
/**
* Gets a string containing the given indentation
*
* @param indentationSpaces <p>The number spaces to use for indentation</p>
* @return <p>A string containing the number of spaces specified</p>
*/
@NotNull
private String addIndentation(int indentationSpaces) {
return " ".repeat(Math.max(0, indentationSpaces));
}
/**
* Gets the indentation (number of spaces) of the given line
*
* @param line <p>The line to get indentation of</p>
* @return <p>The number of spaces in the line's indentation</p>
*/
private int getIndentation(@NotNull String line) {
int spacesFound = 0;
for (char aCharacter : line.toCharArray()) {
if (aCharacter == ' ') {
spacesFound++;
} else {
break;
}
}
return spacesFound;
}
}

View File

@@ -2,6 +2,7 @@ package net.knarcraft.stargate.listener;
import net.knarcraft.stargate.Stargate;
import net.knarcraft.stargate.config.Message;
import net.knarcraft.stargate.config.SGFormatBuilder;
import net.knarcraft.stargate.container.BlockChangeRequest;
import net.knarcraft.stargate.container.BlockLocation;
import net.knarcraft.stargate.event.StargateDestroyEvent;
@@ -94,7 +95,7 @@ public class BlockEventListener implements Listener {
Stargate.addControlBlockUpdateRequest(request);
}
Stargate.getMessageSender().sendSuccessMessage(player, Stargate.getString(Message.CREATED));
new SGFormatBuilder(Message.CREATED).success(player);
Stargate.debug("onSignChange", "Initialized stargate: " + portal.getName());
Stargate.getInstance().getServer().getScheduler().scheduleSyncDelayedTask(Stargate.getInstance(),
portal::drawSign, 1);
@@ -150,7 +151,7 @@ public class BlockEventListener implements Listener {
//Decide if the user can destroy the portal
if (!PermissionHelper.canDestroyPortal(player, portal)) {
denyMessage = Stargate.getString(Message.ACCESS_DENIED);
denyMessage = new SGFormatBuilder(Message.ACCESS_DENIED).toString();
deny = true;
Stargate.logInfo(String.format("%s tried to destroy gate", player.getName()));
}
@@ -168,7 +169,7 @@ public class BlockEventListener implements Listener {
//Destroy denied
if (destroyEvent.getDeny()) {
if (!destroyEvent.getDenyReason().trim().isEmpty()) {
Stargate.getMessageSender().sendErrorMessage(player, destroyEvent.getDenyReason());
new SGFormatBuilder(destroyEvent.getDenyReason()).error(player);
}
event.setCancelled(true);
return;
@@ -180,7 +181,7 @@ public class BlockEventListener implements Listener {
}
PortalRegistry.unregisterPortal(portal, true);
Stargate.getMessageSender().sendSuccessMessage(player, Stargate.getString(Message.DESTROYED));
new SGFormatBuilder(Message.DESTROYED).success(player);
}
/**

View File

@@ -1,9 +1,10 @@
package net.knarcraft.stargate.listener;
import net.knarcraft.knarlib.formatting.FormatBuilder;
import net.knarcraft.knarlib.util.UpdateChecker;
import net.knarcraft.stargate.Stargate;
import net.knarcraft.stargate.config.Message;
import net.knarcraft.stargate.config.MessageSender;
import net.knarcraft.stargate.config.SGFormatBuilder;
import net.knarcraft.stargate.container.BlockLocation;
import net.knarcraft.stargate.portal.Portal;
import net.knarcraft.stargate.portal.PortalActivator;
@@ -72,7 +73,7 @@ public class PlayerEventListener implements Listener {
if (availableUpdate != null && Stargate.getStargateConfig().alertAdminsAboutUpdates() &&
player.hasPermission("stargate.admin")) {
String updateMessage = UpdateChecker.getUpdateAvailableString(availableUpdate, Stargate.getPluginVersion());
Stargate.getMessageSender().sendErrorMessage(player, updateMessage);
new SGFormatBuilder(updateMessage).error(player);
}
if (!Stargate.getGateConfig().enableBungee()) {
@@ -162,7 +163,7 @@ public class PlayerEventListener implements Listener {
new PlayerTeleporter(destination, player).teleportPlayer(entrancePortal, event);
}
if (!entrancePortal.getOptions().isQuiet()) {
Stargate.getMessageSender().sendSuccessMessage(player, Stargate.getString(Message.TELEPORTED));
new SGFormatBuilder(Message.TELEPORTED).success(player);
}
entrancePortal.getPortalOpener().closePortal(false);
}
@@ -204,7 +205,7 @@ public class PlayerEventListener implements Listener {
//Decide if the user should be teleported to another bungee server
if (entrancePortal.getOptions().isBungee()) {
if (BungeeHelper.bungeeTeleport(player, entrancePortal, event) && !entrancePortal.getOptions().isQuiet()) {
Stargate.getMessageSender().sendSuccessMessage(player, Stargate.getString(Message.TELEPORTED));
new SGFormatBuilder(Message.TELEPORTED).success(player);
}
return false;
}
@@ -405,7 +406,7 @@ public class PlayerEventListener implements Listener {
if (PermissionHelper.portalAccessDenied(player, portal, deny)) {
if (!portal.getOptions().isQuiet()) {
Stargate.getMessageSender().sendErrorMessage(player, Stargate.getString(Message.ACCESS_DENIED));
new SGFormatBuilder(Message.ACCESS_DENIED).error(player);
}
return true;
}
@@ -476,19 +477,16 @@ public class PlayerEventListener implements Listener {
//Display portal information as a portal without a sign does not display any
if (portal.getOptions().hasNoSign() && (!portal.getOptions().isQuiet() || player.isSneaking())) {
MessageSender sender = Stargate.getMessageSender();
sender.sendSuccessMessage(player, ChatColor.GOLD + Stargate.getString(Message.PORTAL_INFO_TITLE));
sender.sendSuccessMessage(player, Stargate.replacePlaceholders(Stargate.getString(Message.PORTAL_INFO_NAME),
"%name%", portal.getName()));
sender.sendSuccessMessage(player, Stargate.replacePlaceholders(Stargate.getString(Message.PORTAL_INFO_DESTINATION),
"%destination%", portal.getDestinationName()));
FormatBuilder builder = new SGFormatBuilder();
builder.append(ChatColor.GOLD).append(Message.PORTAL_INFO_TITLE).append("\n").
append(Message.PORTAL_INFO_NAME).replace("%name%", portal.getName()).append("\n").
append(Message.PORTAL_INFO_DESTINATION).replace("%destination%", portal.getDestinationName()).append("\n");
if (portal.getOptions().isBungee()) {
sender.sendSuccessMessage(player, Stargate.replacePlaceholders(Stargate.getString(Message.PORTAL_INFO_SERVER),
"%server%", portal.getNetwork()));
builder.append(Message.PORTAL_INFO_SERVER).replace("%server%", portal.getNetwork());
} else {
sender.sendSuccessMessage(player, Stargate.replacePlaceholders(Stargate.getString(Message.PORTAL_INFO_NETWORK),
"%network%", portal.getNetwork()));
builder.append(Message.PORTAL_INFO_NETWORK).replace("%network%", portal.getNetwork());
}
builder.displayRaw(player);
}
}

View File

@@ -2,6 +2,7 @@ package net.knarcraft.stargate.listener;
import net.knarcraft.stargate.Stargate;
import net.knarcraft.stargate.config.Message;
import net.knarcraft.stargate.config.SGFormatBuilder;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.server.PluginDisableEvent;
@@ -39,8 +40,7 @@ public class PluginEventListener implements Listener {
Plugin vault = Stargate.getEconomyConfig().getVault();
if (vault != null) {
String vaultVersion = vault.getDescription().getVersion();
Stargate.logInfo(Stargate.replacePlaceholders(Stargate.getString(Message.VAULT_LOADED), "%version%",
vaultVersion));
Stargate.logInfo(new SGFormatBuilder(Message.VAULT_LOADED).replace("%version%", vaultVersion).toString());
}
}
}

View File

@@ -2,6 +2,7 @@ package net.knarcraft.stargate.listener;
import net.knarcraft.stargate.Stargate;
import net.knarcraft.stargate.config.Message;
import net.knarcraft.stargate.config.SGFormatBuilder;
import net.knarcraft.stargate.portal.Portal;
import net.knarcraft.stargate.portal.PortalHandler;
import net.knarcraft.stargate.portal.teleporter.VehicleTeleporter;
@@ -101,7 +102,7 @@ public class VehicleEventListener implements Listener {
if (destinationPortal == null) {
cancelTeleportation = true;
if (!entrancePortal.getOptions().isQuiet()) {
Stargate.getMessageSender().sendErrorMessage(player, Stargate.getString(Message.INVALID_DESTINATION));
new SGFormatBuilder(Message.INVALID_DESTINATION).error(player);
}
} else if (!TeleportHelper.playerCanTeleport(player, entrancePortal, destinationPortal)) {
cancelTeleportation = true;
@@ -138,7 +139,7 @@ public class VehicleEventListener implements Listener {
if (!entrancePortal.getOptions().isQuiet()) {
for (Player player : players) {
Stargate.getMessageSender().sendSuccessMessage(player, Stargate.getString(Message.TELEPORTED));
new SGFormatBuilder(Message.TELEPORTED).success(player);
}
}
entrancePortal.getPortalOpener().closePortal(false);

View File

@@ -2,6 +2,7 @@ package net.knarcraft.stargate.portal;
import net.knarcraft.stargate.Stargate;
import net.knarcraft.stargate.config.Message;
import net.knarcraft.stargate.config.SGFormatBuilder;
import net.knarcraft.stargate.event.StargateActivateEvent;
import net.knarcraft.stargate.event.StargateDeactivateEvent;
import net.knarcraft.stargate.utility.ListHelper;
@@ -259,7 +260,7 @@ public class PortalActivator {
//If no destinations are available, just tell the player and quit
if (destinations.isEmpty()) {
if (!portal.getOptions().isQuiet()) {
Stargate.getMessageSender().sendErrorMessage(player, Stargate.getString(Message.NO_DESTINATION));
new SGFormatBuilder(Message.NO_DESTINATION).error(player);
}
return;
}

View File

@@ -2,6 +2,7 @@ package net.knarcraft.stargate.portal;
import net.knarcraft.stargate.Stargate;
import net.knarcraft.stargate.config.Message;
import net.knarcraft.stargate.config.SGFormatBuilder;
import net.knarcraft.stargate.container.BlockLocation;
import net.knarcraft.stargate.container.RelativeBlockVector;
import net.knarcraft.stargate.event.StargateCreateEvent;
@@ -132,7 +133,7 @@ public class PortalCreator {
String networkName = getNetworkName(portalStrings);
if (networkName == null) {
deny = true;
denyMessage = Stargate.getString(Message.CREATION_NETWORK_DENIED);
denyMessage = new SGFormatBuilder(Message.CREATION_NETWORK_DENIED).toString();
} else {
portalStrings = new PortalStrings(portalStrings.name(), networkName, portalStrings.destination());
}
@@ -184,7 +185,7 @@ public class PortalCreator {
network = network.substring(0, getMaxNameNetworkLength());
}
Stargate.debug(route, "Creating personal portal");
Stargate.getMessageSender().sendErrorMessage(player, Stargate.getString(Message.CREATION_PERSONAL));
new SGFormatBuilder(Message.CREATION_PERSONAL).error(player);
return network;
} else {
Stargate.debug(route, "Player does not have access to network");
@@ -203,7 +204,7 @@ public class PortalCreator {
gateName = gateName.substring(0, gateName.indexOf('.'));
if (!PermissionHelper.canCreatePortal(player, gateName)) {
Stargate.debug("PortalCreator::canCreatePortal", "Player does not have access to gate layout");
return Stargate.getString(Message.CREATION_GATE_DENIED);
return new SGFormatBuilder(Message.CREATION_GATE_DENIED).toString();
}
//Check if the user can create portals to this world.
@@ -213,7 +214,7 @@ public class PortalCreator {
String world = destinationPortal.getWorld().getName();
if (PermissionHelper.cannotAccessWorld(player, world)) {
Stargate.debug("PortalCreator::canCreatePortal", "Player does not have access to destination world");
return Stargate.getString(Message.CREATION_WORLD_DENIED);
return new SGFormatBuilder(Message.CREATION_WORLD_DENIED).toString();
}
}
}
@@ -250,7 +251,7 @@ public class PortalCreator {
//Tell the user why it was denied from creating the portal
if (stargateCreateEvent.getDeny()) {
if (!stargateCreateEvent.getDenyReason().trim().isEmpty()) {
Stargate.getMessageSender().sendErrorMessage(player, stargateCreateEvent.getDenyReason());
new SGFormatBuilder(stargateCreateEvent.getDenyReason()).error(player);
}
return null;
}
@@ -297,7 +298,7 @@ public class PortalCreator {
if (portal.getCleanName().isEmpty() || portal.getCleanName().length() > getMaxNameNetworkLength()) {
Stargate.debug(route, String.format("Name length error. %s is too long.",
portal.getCleanName()));
Stargate.getMessageSender().sendErrorMessage(player, Stargate.getString(Message.CREATION_NAME_LENGTH));
new SGFormatBuilder(Message.CREATION_NAME_LENGTH).error(player);
return false;
}
@@ -305,14 +306,14 @@ public class PortalCreator {
//Check if the bungee portal's name has been duplicated
if (PortalRegistry.getBungeePortal(portal.getCleanName()) != null) {
Stargate.debug(route, "Gate name duplicate");
Stargate.getMessageSender().sendErrorMessage(player, Stargate.getString(Message.CREATION_NAME_COLLISION));
new SGFormatBuilder(Message.CREATION_NAME_COLLISION).error(player);
return false;
}
} else {
//Check if the portal name has been duplicated on the network
if (PortalHandler.getByName(portal.getCleanName(), portal.getCleanNetwork()) != null) {
Stargate.debug(route, "Gate name duplicate");
Stargate.getMessageSender().sendErrorMessage(player, Stargate.getString(Message.CREATION_NAME_COLLISION));
new SGFormatBuilder(Message.CREATION_NAME_COLLISION).error(player);
return false;
}
@@ -320,7 +321,7 @@ public class PortalCreator {
List<String> networkList = PortalHandler.getNetwork(portal.getCleanNetwork());
int maxGates = Stargate.getGateConfig().maxGatesEachNetwork();
if (maxGates > 0 && networkList != null && networkList.size() >= maxGates) {
Stargate.getMessageSender().sendErrorMessage(player, Stargate.getString(Message.CREATION_NETWORK_FULL));
new SGFormatBuilder(Message.CREATION_NETWORK_FULL).error(player);
return false;
}
}
@@ -384,7 +385,7 @@ public class PortalCreator {
if (PortalHandler.getByBlock(borderBlockLocation.getBlock()) != null) {
Stargate.debug("PortalCreator::conflictsWithExistingPortal",
"Gate conflicts with existing gate");
Stargate.getMessageSender().sendErrorMessage(player, Stargate.getString(Message.CREATION_CONFLICT));
new SGFormatBuilder(Message.CREATION_CONFLICT).error(player);
return true;
}
}

View File

@@ -2,6 +2,7 @@ package net.knarcraft.stargate.portal;
import net.knarcraft.stargate.Stargate;
import net.knarcraft.stargate.config.Message;
import net.knarcraft.stargate.config.SGFormatBuilder;
import net.knarcraft.stargate.config.material.BukkitTagSpecifier;
import net.knarcraft.stargate.container.BlockLocation;
import net.knarcraft.stargate.container.RelativeBlockVector;
@@ -148,13 +149,13 @@ public class PortalHandler {
return true;
}
if (!PermissionHelper.hasPermission(player, "stargate.admin.bungee")) {
Stargate.getMessageSender().sendErrorMessage(player, Stargate.getString(Message.BUNGEE_CREATION_DENIED));
new SGFormatBuilder(Message.BUNGEE_CREATION_DENIED).error(player);
return false;
} else if (!Stargate.getGateConfig().enableBungee()) {
Stargate.getMessageSender().sendErrorMessage(player, Stargate.getString(Message.BUNGEE_DISABLED));
new SGFormatBuilder(Message.BUNGEE_DISABLED).error(player);
return false;
} else if (destinationName.isEmpty() || network.isEmpty()) {
Stargate.getMessageSender().sendErrorMessage(player, Stargate.getString(Message.BUNGEE_MISSING_INFO));
new SGFormatBuilder(Message.BUNGEE_MISSING_INFO).error(player);
return false;
}
return true;

View File

@@ -4,6 +4,7 @@ import net.knarcraft.knarlib.property.ColorConversion;
import net.knarcraft.knarlib.util.ColorHelper;
import net.knarcraft.stargate.Stargate;
import net.knarcraft.stargate.config.Message;
import net.knarcraft.stargate.config.SGFormatBuilder;
import net.knarcraft.stargate.container.SignData;
import net.knarcraft.stargate.portal.property.PortalLocation;
import net.knarcraft.stargate.utility.PermissionHelper;
@@ -327,7 +328,7 @@ public class PortalSignDrawer {
private void drawBungeeSign(@NotNull SignData signData, @NotNull String[] output) {
ChatColor highlightColor = signData.getHighlightSignColor();
ChatColor mainColor = signData.getMainSignColor();
setLine(signData, 1, Stargate.getString(Message.BUNGEE_SIGN), output);
setLine(signData, 1, new SGFormatBuilder(Message.BUNGEE_SIGN).toString(), output);
setLine(signData, 2, highlightColor + ">" + mainColor +
translateAllColorCodes(portal.getDestinationName()) + highlightColor + "<", output);
setLine(signData, 3, highlightColor + "[" + mainColor + translateAllColorCodes(portal.getNetwork()) +
@@ -345,8 +346,8 @@ public class PortalSignDrawer {
private void drawInactiveSign(@NotNull SignData signData, @NotNull String[] output) {
ChatColor highlightColor = signData.getHighlightSignColor();
ChatColor mainColor = signData.getMainSignColor();
setLine(signData, 1, Stargate.getString(Message.SIGN_RIGHT_CLICK), output);
setLine(signData, 2, Stargate.getString(Message.SIGN_TO_USE), output);
setLine(signData, 1, new SGFormatBuilder(Message.SIGN_RIGHT_CLICK).toString(), output);
setLine(signData, 2, new SGFormatBuilder(Message.SIGN_TO_USE).toString(), output);
if (!portal.getOptions().isNoNetwork()) {
setLine(signData, 3, highlightColor + "(" + mainColor + translateAllColorCodes(portal.getNetwork()) +
highlightColor + ")", output);
@@ -365,7 +366,7 @@ public class PortalSignDrawer {
ChatColor highlightColor = signData.getHighlightSignColor();
ChatColor mainColor = signData.getMainSignColor();
Portal destinationPortal = PortalHandler.getByName(portal.getDestinationName(), portal.getCleanNetwork());
String destinationName = portal.getOptions().isRandom() ? Stargate.getString(Message.SIGN_RANDOM) :
String destinationName = portal.getOptions().isRandom() ? new SGFormatBuilder(Message.SIGN_RANDOM).toString() :
(destinationPortal != null ? destinationPortal.getName() : portal.getDestinationName());
setLine(signData, 1, highlightColor + ">" + mainColor + translateAllColorCodes(destinationName) +
highlightColor + "<", output);
@@ -378,7 +379,7 @@ public class PortalSignDrawer {
}
Portal destination = PortalHandler.getByName(portal.getDestinationName(), portal.getNetwork());
if (destination == null && !portal.getOptions().isRandom()) {
setLine(signData, 3, errorColor + Stargate.getString(Message.SIGN_DISCONNECTED), output);
setLine(signData, 3, errorColor + new SGFormatBuilder(Message.SIGN_DISCONNECTED).toString(), output);
} else {
setLine(signData, 3, "", output);
}
@@ -397,7 +398,7 @@ public class PortalSignDrawer {
if (!(blockState instanceof Sign sign)) {
return;
}
SignHelper.setSignLine(sign, 3, errorColor + Stargate.getString(Message.SIGN_INVALID));
SignHelper.setSignLine(sign, 3, errorColor + new SGFormatBuilder(Message.SIGN_INVALID).toString());
sign.update();
Stargate.logInfo(String.format("Gate layout on line %d does not exist [%s]", lineIndex, gateName));

View File

@@ -173,7 +173,7 @@ public class VehicleTeleporter extends EntityTeleporter {
Vehicle newVehicle = (Vehicle) vehicleWorld.spawn(exit,
Objects.requireNonNull(teleportingVehicle.getType().getEntityClass()));
if (teleportingVehicle instanceof Boat boat) {
((Boat) newVehicle).setBoatType(boat.getBoatType());
boat.setBoatType(boat.getBoatType());
}
//Remove the old vehicle
if (teleportingVehicle.eject()) {

View File

@@ -2,6 +2,7 @@ package net.knarcraft.stargate.utility;
import net.knarcraft.stargate.Stargate;
import net.knarcraft.stargate.config.Message;
import net.knarcraft.stargate.config.SGFormatBuilder;
import net.knarcraft.stargate.portal.Portal;
import net.knarcraft.stargate.portal.PortalHandler;
import net.knarcraft.stargate.portal.teleporter.PlayerTeleporter;
@@ -186,7 +187,7 @@ public final class BungeeHelper {
//Check if bungee is actually enabled
if (!Stargate.getGateConfig().enableBungee()) {
if (!entrancePortal.getOptions().isQuiet()) {
Stargate.getMessageSender().sendErrorMessage(player, Stargate.getString(Message.BUNGEE_DISABLED));
new SGFormatBuilder(Message.BUNGEE_DISABLED).error(player);
}
entrancePortal.getPortalOpener().closePortal(false);
return false;

View File

@@ -1,9 +1,10 @@
package net.knarcraft.stargate.utility;
import net.knarcraft.knarlib.formatting.StringFormatter;
import net.knarcraft.knarlib.formatting.FormatBuilder;
import net.knarcraft.stargate.Stargate;
import net.knarcraft.stargate.config.EconomyConfig;
import net.knarcraft.stargate.config.Message;
import net.knarcraft.stargate.config.SGFormatBuilder;
import net.knarcraft.stargate.portal.Portal;
import net.knarcraft.stargate.portal.property.PortalOwner;
import net.milkbowl.vault.economy.Economy;
@@ -82,9 +83,7 @@ public final class EconomyHelper {
* @param earnings <p>The amount the owner earned</p>
*/
public static void sendObtainMessage(@NotNull String portalName, @NotNull Player portalOwner, int earnings) {
String obtainedMsg = Stargate.getString(Message.ECONOMY_OBTAINED);
obtainedMsg = replacePlaceholders(obtainedMsg, portalName, earnings);
Stargate.getMessageSender().sendSuccessMessage(portalOwner, obtainedMsg);
replacePlaceholders(new SGFormatBuilder(Message.ECONOMY_OBTAINED), portalName, earnings).success(portalOwner);
}
/**
@@ -95,9 +94,7 @@ public final class EconomyHelper {
* @param cost <p>The cost of the interaction</p>
*/
public static void sendDeductMessage(@NotNull String portalName, @NotNull Player player, int cost) {
String deductMsg = Stargate.getString(Message.ECONOMY_DEDUCTED);
deductMsg = replacePlaceholders(deductMsg, portalName, cost);
Stargate.getMessageSender().sendSuccessMessage(player, deductMsg);
replacePlaceholders(new SGFormatBuilder(Message.ECONOMY_DEDUCTED), portalName, cost).success(player);
}
/**
@@ -108,9 +105,7 @@ public final class EconomyHelper {
* @param cost <p>The cost of the interaction</p>
*/
public static void sendInsufficientFundsMessage(@NotNull String portalName, @NotNull Player player, int cost) {
String inFundMsg = Stargate.getString(Message.ECONOMY_INSUFFICIENT);
inFundMsg = replacePlaceholders(inFundMsg, portalName, cost);
Stargate.getMessageSender().sendErrorMessage(player, inFundMsg);
replacePlaceholders(new SGFormatBuilder(Message.ECONOMY_INSUFFICIENT), portalName, cost).error(player);
}
/**
@@ -121,9 +116,7 @@ public final class EconomyHelper {
* @param cost <p>The amount the user has to pay for destroying the portal. (expects a negative value)</p>
*/
public static void sendRefundMessage(@NotNull String portalName, @NotNull Player player, int cost) {
String refundMsg = Stargate.getString(Message.ECONOMY_REFUNDED);
refundMsg = replacePlaceholders(refundMsg, portalName, -cost);
Stargate.getMessageSender().sendSuccessMessage(player, refundMsg);
replacePlaceholders(new SGFormatBuilder(Message.ECONOMY_REFUNDED), portalName, -cost).success(player);
}
/**
@@ -272,17 +265,16 @@ public final class EconomyHelper {
}
/**
* Replaces the cost and portal variables in a string
* Replaces the cost and portal variables in a format builder
*
* @param message <p>The message to replace variables in</p>
* @param builder <p>The format builder to replace variables for</p>
* @param portalName <p>The name of the relevant portal</p>
* @param cost <p>The cost for a given interaction</p>
* @return <p>The same string with cost and portal variables replaced</p>
* @return <p>The same format builder</p>
*/
@NotNull
private static String replacePlaceholders(@NotNull String message, @NotNull String portalName, int cost) {
return StringFormatter.replacePlaceholders(message, new String[]{"%cost%", "%portal%"},
new String[]{Stargate.getEconomyConfig().format(cost), portalName});
private static FormatBuilder replacePlaceholders(@NotNull FormatBuilder builder, @NotNull String portalName, int cost) {
builder.replace("%cost%", Stargate.getEconomyConfig().format(cost)).replace("%portal%", portalName);
return builder;
}
}

View File

@@ -2,6 +2,7 @@ package net.knarcraft.stargate.utility;
import net.knarcraft.stargate.Stargate;
import net.knarcraft.stargate.config.Message;
import net.knarcraft.stargate.config.SGFormatBuilder;
import net.knarcraft.stargate.event.StargateAccessEvent;
import net.knarcraft.stargate.portal.Portal;
import net.knarcraft.stargate.portal.property.PortalOption;
@@ -39,7 +40,7 @@ public final class PermissionHelper {
//Destination is invalid or the same portal. Send an error message
if (destination == null || destination == portal) {
if (!portal.getOptions().isQuiet()) {
Stargate.getMessageSender().sendErrorMessage(player, Stargate.getString(Message.INVALID_DESTINATION));
new SGFormatBuilder(Message.INVALID_DESTINATION).error(player);
}
return;
}
@@ -75,7 +76,7 @@ public final class PermissionHelper {
if (!portal.getOptions().isFixed() && portal.getPortalActivator().isActive() &&
portal.getActivePlayer() != player) {
if (!portal.getOptions().isQuiet()) {
Stargate.getMessageSender().sendErrorMessage(player, Stargate.getString(Message.ACCESS_DENIED));
new SGFormatBuilder(Message.ACCESS_DENIED).error(player);
}
return true;
}
@@ -83,7 +84,7 @@ public final class PermissionHelper {
//Check if the player can use the private gate
if (portal.getOptions().isPrivate() && !PermissionHelper.canUsePrivatePortal(player, portal)) {
if (!portal.getOptions().isQuiet()) {
Stargate.getMessageSender().sendErrorMessage(player, Stargate.getString(Message.ACCESS_DENIED));
new SGFormatBuilder(Message.ACCESS_DENIED).error(player);
}
return true;
}
@@ -91,7 +92,7 @@ public final class PermissionHelper {
//Destination is currently in use by another player, blocking teleportation
if (destination.isOpen() && !destination.getOptions().isAlwaysOn()) {
if (!portal.getOptions().isQuiet()) {
Stargate.getMessageSender().sendErrorMessage(player, Stargate.getString(Message.DESTINATION_BLOCKED));
new SGFormatBuilder(Message.DESTINATION_BLOCKED).error(player);
}
return true;
}
@@ -415,7 +416,7 @@ public final class PermissionHelper {
//Not open for this player
if (!entrancePortal.getPortalOpener().isOpenFor(player)) {
if (!entrancePortal.getOptions().isQuiet()) {
Stargate.getMessageSender().sendErrorMessage(player, Stargate.getString(Message.ACCESS_DENIED));
new SGFormatBuilder(Message.ACCESS_DENIED).error(player);
}
new PlayerTeleporter(entrancePortal, player).teleportPlayer(entrancePortal, event);
return true;
@@ -430,7 +431,7 @@ public final class PermissionHelper {
//Player cannot access portal
if (PermissionHelper.cannotAccessPortal(player, entrancePortal, destination)) {
if (!entrancePortal.getOptions().isQuiet()) {
Stargate.getMessageSender().sendErrorMessage(player, Stargate.getString(Message.ACCESS_DENIED));
new SGFormatBuilder(Message.ACCESS_DENIED).error(player);
}
new PlayerTeleporter(entrancePortal, player).teleportPlayer(entrancePortal, event);
Stargate.debug("PermissionHelper::playerCannotTeleport", "Closed portal because player is " +

View File

@@ -2,6 +2,7 @@ package net.knarcraft.stargate.utility;
import net.knarcraft.stargate.Stargate;
import net.knarcraft.stargate.config.Message;
import net.knarcraft.stargate.config.SGFormatBuilder;
import net.knarcraft.stargate.portal.Portal;
import net.knarcraft.stargate.portal.teleporter.EntityTeleporter;
import org.bukkit.Bukkit;
@@ -230,7 +231,7 @@ public final class TeleportHelper {
//Make sure the user can access the portal
if (PermissionHelper.cannotAccessPortal(player, entrancePortal, destinationPortal)) {
if (!entrancePortal.getOptions().isQuiet()) {
Stargate.getMessageSender().sendErrorMessage(player, Stargate.getString(Message.ACCESS_DENIED));
new SGFormatBuilder(Message.ACCESS_DENIED).error(player);
}
entrancePortal.getPortalOpener().closePortal(false);
return false;
@@ -241,7 +242,7 @@ public final class TeleportHelper {
boolean canAffordFee = cost <= 0 || Stargate.getEconomyConfig().canAffordFee(player, cost);
if (!canAffordFee) {
if (!entrancePortal.getOptions().isQuiet()) {
Stargate.getMessageSender().sendErrorMessage(player, Stargate.getString(Message.ECONOMY_INSUFFICIENT));
new SGFormatBuilder(Message.ECONOMY_INSUFFICIENT).error(player);
}
return false;
}

View File

@@ -1,33 +0,0 @@
package net.knarcraft.stargate;
import net.knarcraft.stargate.container.RelativeBlockVector;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
public class RelativeBlockVectorTest {
@Test
public void getTest() {
RelativeBlockVector relativeBlockVector = new RelativeBlockVector(56, 44, 23);
assertEquals(56, relativeBlockVector.right());
assertEquals(44, relativeBlockVector.down());
assertEquals(23, relativeBlockVector.out());
}
@Test
public void equalsTest() {
RelativeBlockVector vector1 = new RelativeBlockVector(56, 34, 76);
RelativeBlockVector vector2 = new RelativeBlockVector(56, 34, 76);
assertEquals(vector1, vector2);
}
@Test
public void notEqualsTest() {
RelativeBlockVector vector1 = new RelativeBlockVector(456, 78, 234);
RelativeBlockVector vector2 = new RelativeBlockVector(56, 34, 76);
assertNotEquals(vector1, vector2);
}
}

View File

@@ -1,8 +1,9 @@
package net.knarcraft.stargate.container;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class RelativeBlockVectorTest {
@Test
@@ -16,13 +17,13 @@ public class RelativeBlockVectorTest {
for (int i = 0; i < 1000; i++) {
int randomValue = getRandomNumber();
RelativeBlockVector newVector = relativeBlockVector.addRight(randomValue);
Assertions.assertEquals(new RelativeBlockVector(right + randomValue, down, out), newVector);
assertEquals(new RelativeBlockVector(right + randomValue, down, out), newVector);
newVector = relativeBlockVector.addOut(randomValue);
Assertions.assertEquals(new RelativeBlockVector(right, down, out + randomValue), newVector);
assertEquals(new RelativeBlockVector(right, down, out + randomValue), newVector);
newVector = relativeBlockVector.addDown(randomValue);
Assertions.assertEquals(new RelativeBlockVector(right, down + randomValue, out), newVector);
assertEquals(new RelativeBlockVector(right, down + randomValue, out), newVector);
}
}
@@ -37,7 +38,7 @@ public class RelativeBlockVectorTest {
randomNumber3);
RelativeBlockVector invertedBlockVector = new RelativeBlockVector(-randomNumber1, -randomNumber2,
-randomNumber3);
Assertions.assertEquals(invertedBlockVector, relativeBlockVector.invert());
assertEquals(invertedBlockVector, relativeBlockVector.invert());
}
}