Uses KnarLib for common tasks

This commit is contained in:
Kristian Knarvik 2022-11-07 00:07:32 +01:00
parent 3c4394d6fa
commit 3c805ee284
21 changed files with 159 additions and 501 deletions

59
pom.xml
View File

@ -12,6 +12,7 @@
<!-- Properties -->
<properties>
<java.version>16</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<build.number>Unknown</build.number>
</properties>
@ -63,33 +64,65 @@
<groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId>
<version>23.0.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>net.knarcraft</groupId>
<artifactId>knarlib</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
</dependencies>
<!-- Build information -->
<build>
<defaultGoal>clean package install</defaultGoal>
<resources>
<resource>
<filtering>true</filtering>
<directory>${basedir}/src/main/resources</directory>
<includes>
<include>*.yml</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<version>3.8.1</version>
<configuration>
<source>16</source>
<target>16</target>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
<filters>
<filter>
<artifact>net.knarcraft:knarlib</artifact>
<includes>
<include>net/knarcraft/knarlib/**</include>
</includes>
</filter>
<filter>
<excludes>
<exclude>*.MF</exclude>
<exclude>*.yml</exclude>
</excludes>
</filter>
</filters>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>

View File

@ -8,11 +8,14 @@ import net.knarcraft.blacksmith.command.BlackSmithEditTabCompleter;
import net.knarcraft.blacksmith.command.PresetCommand;
import net.knarcraft.blacksmith.command.PresetTabCompleter;
import net.knarcraft.blacksmith.config.GlobalSettings;
import net.knarcraft.blacksmith.formatting.Translator;
import net.knarcraft.blacksmith.formatting.BlacksmithTranslatableMessage;
import net.knarcraft.blacksmith.listener.NPCClickListener;
import net.knarcraft.blacksmith.listener.PlayerListener;
import net.knarcraft.blacksmith.manager.EconomyManager;
import net.knarcraft.blacksmith.trait.BlacksmithTrait;
import net.knarcraft.knarlib.KnarLib;
import net.knarcraft.knarlib.formatting.TranslatableTimeUnit;
import net.knarcraft.knarlib.formatting.Translator;
import org.bukkit.command.PluginCommand;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.plugin.PluginManager;
@ -63,6 +66,7 @@ public class BlacksmithPlugin extends JavaPlugin {
@Override
public void onEnable() {
instance = this;
KnarLib.setPlugin(this);
//Copy default config to disk
FileConfiguration fileConfiguration = this.getConfig();
@ -75,6 +79,9 @@ public class BlacksmithPlugin extends JavaPlugin {
config = new GlobalSettings(this);
config.load();
//Prepare the translator
Translator.registerMessageCategory(TranslatableTimeUnit.UNIT_SECOND);
Translator.registerMessageCategory(BlacksmithTranslatableMessage.ITEM_TYPE_ENCHANTMENT);
Translator.loadLanguages(fileConfiguration.getString("language", "en"));
//Set up Vault integration

View File

@ -5,10 +5,11 @@ import net.knarcraft.blacksmith.config.GlobalSetting;
import net.knarcraft.blacksmith.config.GlobalSettings;
import net.knarcraft.blacksmith.config.NPCSetting;
import net.knarcraft.blacksmith.config.SettingValueType;
import net.knarcraft.blacksmith.formatting.BlacksmithTranslatableMessage;
import net.knarcraft.blacksmith.formatting.ItemType;
import net.knarcraft.blacksmith.formatting.TranslatableMessage;
import net.knarcraft.blacksmith.util.InputParsingHelper;
import net.knarcraft.blacksmith.util.TypeValidationHelper;
import net.knarcraft.knarlib.formatting.StringFormatter;
import net.md_5.bungee.api.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
@ -19,9 +20,7 @@ import org.jetbrains.annotations.NotNull;
import java.util.Arrays;
import static net.knarcraft.blacksmith.formatting.StringFormatter.displayErrorMessage;
import static net.knarcraft.blacksmith.formatting.StringFormatter.displaySuccessMessage;
import static net.knarcraft.blacksmith.formatting.TranslatableMessage.getValueChangedMessage;
import static net.knarcraft.blacksmith.formatting.BlacksmithTranslatableMessage.getValueChangedMessage;
/**
* The command used for changing global configuration options
@ -43,7 +42,7 @@ public class BlackSmithConfigCommand implements CommandExecutor {
//Changing reforge-able items' default isn't recommended
if (commandName.equalsIgnoreCase(NPCSetting.REFORGE_ABLE_ITEMS.getCommandName())) {
displayErrorMessage(sender, TranslatableMessage.DEFAULT_REFORGE_ABLE_ITEMS_UNCHANGEABLE);
StringFormatter.displayErrorMessage(sender, BlacksmithTranslatableMessage.DEFAULT_REFORGE_ABLE_ITEMS_UNCHANGEABLE);
return false;
}
@ -105,7 +104,7 @@ public class BlackSmithConfigCommand implements CommandExecutor {
String newValue = args[1];
if (detectedGlobalSetting != null) {
settings.changeValue(detectedGlobalSetting, newValue);
displaySuccessMessage(sender, getValueChangedMessage(detectedGlobalSetting.getCommandName(), newValue));
StringFormatter.displaySuccessMessage(sender, getValueChangedMessage(detectedGlobalSetting.getCommandName(), newValue));
return true;
} else if (detectedNPCSetting != null) {
//This makes sure all arguments are treated as a sentence
@ -113,7 +112,7 @@ public class BlackSmithConfigCommand implements CommandExecutor {
newValue = String.join(" ", Arrays.asList(args).subList(1, args.length));
}
settings.changeValue(detectedNPCSetting, newValue);
displaySuccessMessage(sender, getValueChangedMessage(detectedNPCSetting.getCommandName(), newValue));
StringFormatter.displaySuccessMessage(sender, getValueChangedMessage(detectedNPCSetting.getCommandName(), newValue));
return true;
} else {
return false;
@ -151,10 +150,10 @@ public class BlackSmithConfigCommand implements CommandExecutor {
return false;
}
//Display the current value of the setting
displaySuccessMessage(sender, TranslatableMessage.getCurrentValueMessage(correctCommandName, settingValue));
StringFormatter.displaySuccessMessage(sender, BlacksmithTranslatableMessage.getCurrentValueMessage(correctCommandName, settingValue));
//Print the value with any colors displayed as &a-f0-9
if (printRawValue) {
sender.sendMessage(TranslatableMessage.getRawValueMessage(
sender.sendMessage(BlacksmithTranslatableMessage.getRawValueMessage(
settingValue.replace(ChatColor.COLOR_CHAR, '&')));
}
return true;
@ -182,7 +181,7 @@ public class BlackSmithConfigCommand implements CommandExecutor {
} else {
currentValue = String.valueOf(settings.getPricePerDurabilityPoint(material));
}
displaySuccessMessage(sender, TranslatableMessage.getItemCurrentValueMessage(setting.getCommandName(),
StringFormatter.displaySuccessMessage(sender, BlacksmithTranslatableMessage.getItemCurrentValueMessage(setting.getCommandName(),
ItemType.MATERIAL, material.name(), currentValue));
return true;
} else if (setting == GlobalSetting.ENCHANTMENT_COST) {
@ -190,7 +189,7 @@ public class BlackSmithConfigCommand implements CommandExecutor {
if (enchantment == null) {
return false;
}
displaySuccessMessage(sender, TranslatableMessage.getItemCurrentValueMessage(setting.getCommandName(),
StringFormatter.displaySuccessMessage(sender, BlacksmithTranslatableMessage.getItemCurrentValueMessage(setting.getCommandName(),
ItemType.ENCHANTMENT, enchantment.getKey().getKey(),
String.valueOf(settings.getEnchantmentCost(enchantment))));
return true;
@ -257,8 +256,8 @@ public class BlackSmithConfigCommand implements CommandExecutor {
return false;
}
displaySuccessMessage(sender, TranslatableMessage.getItemValueChangedMessage(detectedGlobalSetting.getCommandName(),
itemType, itemChanged, newValue));
StringFormatter.displaySuccessMessage(sender, BlacksmithTranslatableMessage.getItemValueChangedMessage(
detectedGlobalSetting.getCommandName(), itemType, itemChanged, newValue));
return true;
}

View File

@ -14,7 +14,7 @@ import java.util.ArrayList;
import java.util.List;
import static net.knarcraft.blacksmith.util.TabCompleteValuesHelper.getTabCompletions;
import static net.knarcraft.blacksmith.util.TabCompletionHelper.filterMatchingContains;
import static net.knarcraft.knarlib.util.TabCompletionHelper.filterMatchingContains;
/**
* The tab completer for the command used for changing global configuration options

View File

@ -5,12 +5,12 @@ import net.citizensnpcs.api.npc.NPC;
import net.knarcraft.blacksmith.BlacksmithPlugin;
import net.knarcraft.blacksmith.config.NPCSetting;
import net.knarcraft.blacksmith.config.SettingValueType;
import net.knarcraft.blacksmith.formatting.StringFormatter;
import net.knarcraft.blacksmith.formatting.TranslatableMessage;
import net.knarcraft.blacksmith.formatting.Translator;
import net.knarcraft.blacksmith.formatting.BlacksmithTranslatableMessage;
import net.knarcraft.blacksmith.trait.BlacksmithTrait;
import net.knarcraft.blacksmith.util.InputParsingHelper;
import net.knarcraft.blacksmith.util.TypeValidationHelper;
import net.knarcraft.knarlib.formatting.StringFormatter;
import net.knarcraft.knarlib.formatting.Translator;
import net.md_5.bungee.api.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
@ -19,9 +19,8 @@ import org.jetbrains.annotations.NotNull;
import java.util.Arrays;
import static net.knarcraft.blacksmith.formatting.StringFormatter.displaySuccessMessage;
import static net.knarcraft.blacksmith.formatting.TranslatableMessage.getCurrentValueMessage;
import static net.knarcraft.blacksmith.formatting.TranslatableMessage.getValueChangedMessage;
import static net.knarcraft.blacksmith.formatting.BlacksmithTranslatableMessage.getCurrentValueMessage;
import static net.knarcraft.blacksmith.formatting.BlacksmithTranslatableMessage.getValueChangedMessage;
/**
* The main command used for blacksmith editing
@ -33,7 +32,7 @@ public class BlackSmithEditCommand implements CommandExecutor {
@NotNull String[] args) {
NPC npc = CitizensAPI.getDefaultNPCSelector().getSelected(sender);
if (npc == null || !npc.hasTrait(BlacksmithTrait.class)) {
StringFormatter.displayErrorMessage(sender, TranslatableMessage.NO_NPC_SELECTED);
StringFormatter.displayErrorMessage(sender, BlacksmithTranslatableMessage.NO_NPC_SELECTED);
return true;
}
@ -86,7 +85,7 @@ public class BlackSmithEditCommand implements CommandExecutor {
//Change the setting
blacksmithTrait.getSettings().changeSetting(npcSetting, newValue);
displaySuccessMessage(sender, getValueChangedMessage(npcSetting.getCommandName(), String.valueOf(newValue)));
StringFormatter.displaySuccessMessage(sender, getValueChangedMessage(npcSetting.getCommandName(), String.valueOf(newValue)));
//Save the changes immediately to prevent data loss on server crash
CitizensAPI.getNPCRegistry().saveToStore();
}
@ -105,14 +104,14 @@ public class BlackSmithEditCommand implements CommandExecutor {
if (InputParsingHelper.isEmpty(rawValue)) {
//Display the default value, if no custom value has been specified
rawValue = String.valueOf(BlacksmithPlugin.getInstance().getSettings().getRawValue(npcSetting));
displaySuccessMessage(sender, getCurrentValueMessage(npcSetting.getCommandName(), rawValue));
StringFormatter.displaySuccessMessage(sender, getCurrentValueMessage(npcSetting.getCommandName(), rawValue));
} else {
//Add a marker if the value has been customized
String marker = Translator.getTranslatedMessage(TranslatableMessage.SETTING_OVERRIDDEN_MARKER);
displaySuccessMessage(sender, getCurrentValueMessage(npcSetting.getCommandName(), rawValue) + marker);
String marker = Translator.getTranslatedMessage(BlacksmithTranslatableMessage.SETTING_OVERRIDDEN_MARKER);
StringFormatter.displaySuccessMessage(sender, getCurrentValueMessage(npcSetting.getCommandName(), rawValue) + marker);
}
if (npcSetting.getPath().startsWith("defaults.messages")) {
sender.sendMessage(TranslatableMessage.getRawValueMessage(rawValue.replace(ChatColor.COLOR_CHAR, '&')));
sender.sendMessage(BlacksmithTranslatableMessage.getRawValueMessage(rawValue.replace(ChatColor.COLOR_CHAR, '&')));
}
}

View File

@ -2,7 +2,7 @@ package net.knarcraft.blacksmith.command;
import net.knarcraft.blacksmith.config.NPCSetting;
import net.knarcraft.blacksmith.util.TabCompleteValuesHelper;
import net.knarcraft.blacksmith.util.TabCompletionHelper;
import net.knarcraft.knarlib.util.TabCompletionHelper;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;

View File

@ -2,9 +2,9 @@ package net.knarcraft.blacksmith.command;
import net.knarcraft.blacksmith.config.SmithPreset;
import net.knarcraft.blacksmith.config.SmithPresetFilter;
import net.knarcraft.blacksmith.formatting.StringFormatter;
import net.knarcraft.blacksmith.formatting.TranslatableMessage;
import net.knarcraft.blacksmith.formatting.Translator;
import net.knarcraft.blacksmith.formatting.BlacksmithTranslatableMessage;
import net.knarcraft.knarlib.formatting.StringFormatter;
import net.knarcraft.knarlib.formatting.Translator;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
@ -14,9 +14,6 @@ import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
import static net.knarcraft.blacksmith.formatting.StringFormatter.displayErrorMessage;
import static net.knarcraft.blacksmith.formatting.StringFormatter.displaySuccessMessage;
/**
* The command for displaying which materials are contained in a preset
*/
@ -40,7 +37,7 @@ public class PresetCommand implements CommandExecutor {
SmithPresetFilter filter = SmithPresetFilter.valueOf(parts[1]);
if (!smithPreset.supportsFilter(filter)) {
displayErrorMessage(sender, TranslatableMessage.INVALID_FILTER_FOR_PRESET);
StringFormatter.displayErrorMessage(sender, BlacksmithTranslatableMessage.INVALID_FILTER_FOR_PRESET);
return false;
}
includedMaterials = smithPreset.getFilteredMaterials(filter);
@ -48,7 +45,7 @@ public class PresetCommand implements CommandExecutor {
includedMaterials = SmithPreset.valueOf(presetName).getMaterials();
}
} catch (IllegalArgumentException exception) {
displayErrorMessage(sender, TranslatableMessage.INVALID_PRESET_OR_FILTER);
StringFormatter.displayErrorMessage(sender, BlacksmithTranslatableMessage.INVALID_PRESET_OR_FILTER);
return false;
}
@ -57,8 +54,8 @@ public class PresetCommand implements CommandExecutor {
for (Material material : includedMaterials) {
materialNames.add(material.name());
}
displaySuccessMessage(sender, StringFormatter.replacePlaceholder(Translator.getTranslatedMessage(
TranslatableMessage.PRESET_MATERIALS), "{materials}", String.join(", ", materialNames)));
StringFormatter.displaySuccessMessage(sender, StringFormatter.replacePlaceholder(Translator.getTranslatedMessage(
BlacksmithTranslatableMessage.PRESET_MATERIALS), "{materials}", String.join(", ", materialNames)));
return true;
}

View File

@ -2,7 +2,7 @@ package net.knarcraft.blacksmith.command;
import net.knarcraft.blacksmith.config.SmithPreset;
import net.knarcraft.blacksmith.config.SmithPresetFilter;
import net.knarcraft.blacksmith.util.TabCompletionHelper;
import net.knarcraft.knarlib.util.TabCompletionHelper;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;

View File

@ -1,7 +1,8 @@
package net.knarcraft.blacksmith.command;
import net.knarcraft.blacksmith.BlacksmithPlugin;
import net.knarcraft.blacksmith.formatting.TranslatableMessage;
import net.knarcraft.blacksmith.formatting.BlacksmithTranslatableMessage;
import net.knarcraft.knarlib.formatting.StringFormatter;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
@ -11,8 +12,6 @@ import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import static net.knarcraft.blacksmith.formatting.StringFormatter.displaySuccessMessage;
/**
* The command for re-loading the plugin
*/
@ -22,7 +21,7 @@ public class ReloadCommand implements TabExecutor {
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label,
@NotNull String[] args) {
BlacksmithPlugin.getInstance().reload();
displaySuccessMessage(sender, TranslatableMessage.PLUGIN_RELOADED);
StringFormatter.displaySuccessMessage(sender, BlacksmithTranslatableMessage.PLUGIN_RELOADED);
return true;
}

View File

@ -0,0 +1,30 @@
package net.knarcraft.blacksmith.formatting;
import net.citizensnpcs.api.npc.NPC;
import net.knarcraft.knarlib.property.ColorConversion;
import net.knarcraft.knarlib.util.ColorHelper;
import net.md_5.bungee.api.ChatColor;
import org.bukkit.entity.Player;
/**
* A formatter for formatting displayed messages
*/
public final class BlacksmithStringFormatter {
private BlacksmithStringFormatter() {
}
/**
* Sends a message from a blacksmith NPC to a player
*
* @param npc <p>The NPC sending the message</p>
* @param player <p>The player to send the message to</p>
* @param message <p>The message to send</p>
*/
public static void sendNPCMessage(NPC npc, Player player, String message) {
player.sendMessage(ChatColor.GREEN + "[" + npc.getName() + "] -> You:" + ChatColor.RESET + " " +
ColorHelper.translateColorCodes(message, ColorConversion.NORMAL));
}
}

View File

@ -1,6 +1,8 @@
package net.knarcraft.blacksmith.formatting;
import static net.knarcraft.blacksmith.formatting.StringFormatter.replacePlaceholders;
import net.knarcraft.knarlib.formatting.StringFormatter;
import net.knarcraft.knarlib.formatting.TranslatableMessage;
import net.knarcraft.knarlib.formatting.Translator;
/**
* An enum containing all translatable global messages
@ -8,7 +10,7 @@ import static net.knarcraft.blacksmith.formatting.StringFormatter.replacePlaceho
* <p>This does not include NPC messages as they are configurable per-npc, and can be translated by changing the
* default message values in the main config file.</p>
*/
public enum TranslatableMessage {
public enum BlacksmithTranslatableMessage implements TranslatableMessage {
/**
* The message displayed when a configuration value has been successfully changed
@ -105,36 +107,6 @@ public enum TranslatableMessage {
*/
PRESET_MATERIALS,
/**
* The format for displaying the exact duration of a blacksmith's cool-down or delay
*/
DURATION_FORMAT,
/**
* The text to display for 0 seconds
*/
UNIT_NOW,
/**
* The text to display for 1 second
*/
UNIT_SECOND,
/**
* The text to display for a number of seconds
*/
UNIT_SECONDS,
/**
* The text to display for 1 minute
*/
UNIT_MINUTE,
/**
* The text to display for a number of minutes
*/
UNIT_MINUTES,
/**
* The text to display when describing less than 10 seconds remaining
*/
@ -172,7 +144,7 @@ public enum TranslatableMessage {
* @return <p>The message to display</p>
*/
public static String getRawValueMessage(String rawValue) {
return StringFormatter.replacePlaceholder(Translator.getTranslatedMessage(TranslatableMessage.RAW_VALUE),
return StringFormatter.replacePlaceholder(Translator.getTranslatedMessage(BlacksmithTranslatableMessage.RAW_VALUE),
"{rawValue}", rawValue);
}
@ -184,7 +156,7 @@ public enum TranslatableMessage {
* @return <p>The string to display to a user</p>
*/
public static String getValueChangedMessage(String setting, String newValue) {
return replacePlaceholders(Translator.getTranslatedMessage(TranslatableMessage.VALUE_CHANGED),
return StringFormatter.replacePlaceholders(Translator.getTranslatedMessage(BlacksmithTranslatableMessage.VALUE_CHANGED),
new String[]{"{setting}", "{newValue}"}, new String[]{setting, newValue});
}
@ -198,7 +170,7 @@ public enum TranslatableMessage {
* @return <p>The string to display to a user</p>
*/
public static String getItemValueChangedMessage(String setting, ItemType itemType, String item, String newValue) {
return replacePlaceholders(Translator.getTranslatedMessage(TranslatableMessage.VALUE_FOR_ITEM_CHANGED),
return StringFormatter.replacePlaceholders(Translator.getTranslatedMessage(BlacksmithTranslatableMessage.VALUE_FOR_ITEM_CHANGED),
new String[]{"{setting}", "{itemType}", "{item}", "{newValue}"},
new String[]{setting, itemType.getItemTypeName(), item, newValue});
}
@ -211,7 +183,7 @@ public enum TranslatableMessage {
* @return <p>The string to display to a user</p>
*/
public static String getCurrentValueMessage(String setting, String currentValue) {
return replacePlaceholders(Translator.getTranslatedMessage(TranslatableMessage.CURRENT_VALUE),
return StringFormatter.replacePlaceholders(Translator.getTranslatedMessage(BlacksmithTranslatableMessage.CURRENT_VALUE),
new String[]{"{setting}", "{currentValue}"}, new String[]{setting, currentValue});
}
@ -225,9 +197,13 @@ public enum TranslatableMessage {
* @return <p>The string to display to a user</p>
*/
public static String getItemCurrentValueMessage(String setting, ItemType itemType, String item, String currentValue) {
return replacePlaceholders(Translator.getTranslatedMessage(TranslatableMessage.CURRENT_VALUE_FOR_ITEM),
return StringFormatter.replacePlaceholders(Translator.getTranslatedMessage(BlacksmithTranslatableMessage.CURRENT_VALUE_FOR_ITEM),
new String[]{"{setting}", "{itemType}", "{item}", "{currentValue}"},
new String[]{setting, itemType.getItemTypeName(), item, currentValue});
}
@Override
public TranslatableMessage[] getAllMessages() {
return BlacksmithTranslatableMessage.values();
}
}

View File

@ -1,5 +1,7 @@
package net.knarcraft.blacksmith.formatting;
import net.knarcraft.knarlib.formatting.Translator;
/**
* An enum representing all item types used in messages
*/
@ -15,8 +17,8 @@ public enum ItemType {
*/
public String getItemTypeName() {
return switch (this) {
case MATERIAL -> Translator.getTranslatedMessage(TranslatableMessage.ITEM_TYPE_MATERIAL);
case ENCHANTMENT -> Translator.getTranslatedMessage(TranslatableMessage.ITEM_TYPE_ENCHANTMENT);
case MATERIAL -> Translator.getTranslatedMessage(BlacksmithTranslatableMessage.ITEM_TYPE_MATERIAL);
case ENCHANTMENT -> Translator.getTranslatedMessage(BlacksmithTranslatableMessage.ITEM_TYPE_ENCHANTMENT);
};
}

View File

@ -1,128 +0,0 @@
package net.knarcraft.blacksmith.formatting;
import net.citizensnpcs.api.npc.NPC;
import net.knarcraft.blacksmith.BlacksmithPlugin;
import net.md_5.bungee.api.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* A formatter for formatting displayed messages
*/
public final class StringFormatter {
private final static String pluginName = BlacksmithPlugin.getInstance().getDescription().getName();
private StringFormatter() {
}
/**
* Sends a message from a blacksmith NPC to a player
*
* @param npc <p>The NPC sending the message</p>
* @param player <p>The player to send the message to</p>
* @param message <p>The message to send</p>
*/
public static void sendNPCMessage(NPC npc, Player player, String message) {
player.sendMessage(ChatColor.GREEN + "[" + npc.getName() + "] -> You:" + ChatColor.RESET + " " +
translateColors(message));
}
/**
* Displays a message signifying a successful action
*
* @param sender <p>The command sender to display the message to</p>
* @param message <p>The translatable message to display</p>
*/
public static void displaySuccessMessage(CommandSender sender, TranslatableMessage message) {
sender.sendMessage(ChatColor.GREEN + getFormattedMessage(Translator.getTranslatedMessage(message)));
}
/**
* Displays a message signifying a successful action
*
* @param sender <p>The command sender to display the message to</p>
* @param message <p>The raw message to display</p>
*/
public static void displaySuccessMessage(CommandSender sender, String message) {
sender.sendMessage(ChatColor.GREEN + getFormattedMessage(message));
}
/**
* Displays a message signifying an unsuccessful action
*
* @param sender <p>The command sender to display the message to</p>
* @param message <p>The translatable message to display</p>
*/
public static void displayErrorMessage(CommandSender sender, TranslatableMessage message) {
sender.sendMessage(ChatColor.DARK_RED + getFormattedMessage(Translator.getTranslatedMessage(message)));
}
/**
* Gets the formatted version of any chat message
*
* @param message <p>The message to format</p>
* @return <p>The formatted message</p>
*/
private static String getFormattedMessage(String message) {
return "[" + pluginName + "] " + ChatColor.RESET + translateColors(message);
}
/**
* Translates & color codes to proper colors
*
* @param input <p>The input string to translate colors for</p>
* @return <p>The input with color codes translated</p>
*/
private static String translateColors(String input) {
return ChatColor.translateAlternateColorCodes('&', input);
}
/**
* Replaces a placeholder in a string
*
* @param input <p>The input string to replace in</p>
* @param placeholder <p>The placeholder to replace</p>
* @param replacement <p>The replacement value</p>
* @return <p>The input string with the placeholder replaced</p>
*/
public static String replacePlaceholder(String input, String placeholder, String replacement) {
return input.replace(placeholder, replacement);
}
/**
* Replaces placeholders in a string
*
* @param input <p>The input string to replace in</p>
* @param placeholders <p>The placeholders to replace</p>
* @param replacements <p>The replacement values</p>
* @return <p>The input string with placeholders replaced</p>
*/
public static String replacePlaceholders(String input, String[] placeholders, String[] replacements) {
for (int i = 0; i < Math.min(placeholders.length, replacements.length); i++) {
input = replacePlaceholder(input, placeholders[i], replacements[i]);
}
return input;
}
/**
* Translates all found color codes to formatting in a string
*
* @param message <p>The string to search for color codes</p>
* @return <p>The message with color codes translated</p>
*/
public static String translateAllColorCodes(String message) {
message = ChatColor.translateAlternateColorCodes('&', message);
Pattern pattern = Pattern.compile("(#[a-fA-F0-9]{6})");
Matcher matcher = pattern.matcher(message);
while (matcher.find()) {
message = message.replace(matcher.group(), "" + ChatColor.of(matcher.group()));
}
return message;
}
}

View File

@ -1,23 +1,16 @@
package net.knarcraft.blacksmith.formatting;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import net.knarcraft.knarlib.formatting.Translator;
import static net.knarcraft.blacksmith.formatting.StringFormatter.replacePlaceholder;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
/**
* A utility for formatting a string specifying an amount of time
*/
public final class TimeFormatter {
private static Map<Double, TranslatableMessage[]> timeUnits;
private static List<Double> sortedUnits;
private TimeFormatter() {
}
@ -31,7 +24,7 @@ public final class TimeFormatter {
*/
public static String formatTime(boolean exact, int seconds) {
if (exact) {
return getDurationString(seconds);
return net.knarcraft.knarlib.formatting.TimeFormatter.getDurationString(seconds);
} else {
return formatUnclearTime(seconds);
}
@ -60,7 +53,7 @@ public final class TimeFormatter {
* @return <p>Text describing the time interval</p>
*/
private static String getMessageFromInterval(TimeInterval interval) {
String text = Translator.getTranslatedMessage(TranslatableMessage.valueOf(interval.name()));
String text = Translator.getTranslatedMessage(BlacksmithTranslatableMessage.valueOf(interval.name()));
//Choose a random entry if a comma-separated list is provided
if (text != null && text.contains(",")) {
@ -79,68 +72,4 @@ public final class TimeFormatter {
}
}
/**
* Gets the string used for displaying this sign's duration
*
* @return <p>The string used for displaying this sign's duration</p>
*/
public static String getDurationString(int duration) {
if (duration == 0) {
return Translator.getTranslatedMessage(TranslatableMessage.UNIT_NOW);
} else {
if (sortedUnits == null) {
initializeUnits();
}
for (Double unit : sortedUnits) {
if (duration / unit >= 1) {
double units = round(duration / unit);
return formatDurationString(units, timeUnits.get(unit)[units == 1 ? 0 : 1],
(units * 10) % 10 == 0);
}
}
return formatDurationString(duration, TranslatableMessage.UNIT_SECONDS, false);
}
}
/**
* Rounds a number to its last two digits
*
* @param number <p>The number to round</p>
* @return <p>The rounded number</p>
*/
private static double round(double number) {
return Math.round(number * 100.0) / 100.0;
}
/**
* Formats a duration string
*
* @param duration <p>The duration to display</p>
* @param translatableMessage <p>The time unit to display</p>
* @param castToInt <p>Whether to cast the duration to an int</p>
* @return <p>The formatted duration string</p>
*/
private static String formatDurationString(double duration, TranslatableMessage translatableMessage, boolean castToInt) {
String durationFormat = Translator.getTranslatedMessage(TranslatableMessage.DURATION_FORMAT);
durationFormat = replacePlaceholder(durationFormat, "{unit}",
Translator.getTranslatedMessage(translatableMessage));
return replacePlaceholder(durationFormat, "{time}", castToInt ? String.valueOf((int) duration) :
String.valueOf(duration));
}
/**
* Initializes the mapping of available time units for formatting permission sign duration
*/
private static void initializeUnits() {
double minute = 60;
timeUnits = new HashMap<>();
timeUnits.put(minute, new TranslatableMessage[]{TranslatableMessage.UNIT_MINUTE, TranslatableMessage.UNIT_MINUTES});
timeUnits.put(1D, new TranslatableMessage[]{TranslatableMessage.UNIT_SECOND, TranslatableMessage.UNIT_SECONDS});
sortedUnits = new ArrayList<>(timeUnits.keySet());
Collections.sort(sortedUnits);
Collections.reverse(sortedUnits);
}
}

View File

@ -1,120 +0,0 @@
package net.knarcraft.blacksmith.formatting;
import net.knarcraft.blacksmith.BlacksmithPlugin;
import net.knarcraft.blacksmith.util.FileHelper;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
/**
* A tool to get strings translated to the correct language
*/
public final class Translator {
private static Map<TranslatableMessage, String> translatedMessages;
private static Map<TranslatableMessage, String> backupTranslatedMessages;
private Translator() {
}
/**
* Loads the languages used by this translator
*/
public static void loadLanguages(String selectedLanguage) {
backupTranslatedMessages = loadTranslatedMessages("en");
translatedMessages = loadCustomTranslatedMessages(selectedLanguage);
if (translatedMessages == null) {
translatedMessages = loadTranslatedMessages(selectedLanguage);
}
}
/**
* Gets a translated version of the given translatable message
*
* @param translatableMessage <p>The message to translate</p>
* @return <p>The translated message</p>
*/
public static String getTranslatedMessage(TranslatableMessage translatableMessage) {
if (translatedMessages == null) {
return "Translated strings not loaded";
}
String translatedMessage;
if (translatedMessages.containsKey(translatableMessage)) {
translatedMessage = translatedMessages.get(translatableMessage);
} else if (backupTranslatedMessages.containsKey(translatableMessage)) {
translatedMessage = backupTranslatedMessages.get(translatableMessage);
} else {
translatedMessage = translatableMessage.toString();
}
return StringFormatter.translateAllColorCodes(translatedMessage);
}
/**
* Loads all translated messages for the given language
*
* @param language <p>The language chosen by the user</p>
* @return <p>A mapping of all strings for the given language</p>
*/
public static Map<TranslatableMessage, String> loadTranslatedMessages(String language) {
try {
BufferedReader reader = FileHelper.getBufferedReaderForInternalFile("/strings.yml");
return loadTranslatableMessages(language, reader);
} catch (FileNotFoundException e) {
BlacksmithPlugin.getInstance().getLogger().log(Level.SEVERE, "Unable to load translated messages");
return null;
}
}
/**
* Tries to load translated messages from a custom strings.yml file
*
* @param language <p>The selected language</p>
* @return <p>The loaded translated strings, or null if no custom language file exists</p>
*/
public static Map<TranslatableMessage, String> loadCustomTranslatedMessages(String language) {
BlacksmithPlugin instance = BlacksmithPlugin.getInstance();
File strings = new File(instance.getDataFolder(), "strings.yml");
if (!strings.exists()) {
instance.getLogger().log(Level.FINEST, "Strings file not found");
return null;
}
try {
instance.getLogger().log(Level.INFO, "Loading custom strings...");
return loadTranslatableMessages(language, new BufferedReader(new InputStreamReader(new FileInputStream(strings))));
} catch (FileNotFoundException e) {
instance.getLogger().log(Level.WARNING, "Unable to load custom messages");
return null;
}
}
/**
* Loads translatable messages from the given reader
*
* @param language <p>The selected language</p>
* @param reader <p>The buffered reader to read from</p>
* @return <p>The loaded translated strings</p>
*/
private static Map<TranslatableMessage, String> loadTranslatableMessages(String language, BufferedReader reader) {
Map<TranslatableMessage, String> translatedMessages = new HashMap<>();
YamlConfiguration configuration = YamlConfiguration.loadConfiguration(reader);
for (TranslatableMessage message : TranslatableMessage.values()) {
String translated = configuration.getString(language + "." + message.toString());
if (translated != null) {
translatedMessages.put(message, translated);
}
}
return translatedMessages;
}
}

View File

@ -1,8 +1,8 @@
package net.knarcraft.blacksmith.listener;
import net.knarcraft.blacksmith.formatting.StringFormatter;
import net.knarcraft.blacksmith.formatting.TranslatableMessage;
import net.knarcraft.blacksmith.formatting.BlacksmithTranslatableMessage;
import net.knarcraft.blacksmith.trait.BlacksmithTrait;
import net.knarcraft.knarlib.formatting.StringFormatter;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
@ -25,7 +25,7 @@ public class NPCClickListener implements Listener {
//Permission check
if (!player.hasPermission("blacksmith.use")) {
StringFormatter.displayErrorMessage(player, TranslatableMessage.PERMISSION_DENIED);
StringFormatter.displayErrorMessage(player, BlacksmithTranslatableMessage.PERMISSION_DENIED);
return;
}

View File

@ -8,6 +8,7 @@ import net.knarcraft.blacksmith.config.NPCSettings;
import net.knarcraft.blacksmith.formatting.TimeFormatter;
import net.knarcraft.blacksmith.manager.EconomyManager;
import net.knarcraft.blacksmith.util.ItemHelper;
import net.knarcraft.knarlib.formatting.StringFormatter;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.enchantments.EnchantmentTarget;
@ -23,8 +24,7 @@ import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import static net.knarcraft.blacksmith.formatting.StringFormatter.replacePlaceholder;
import static net.knarcraft.blacksmith.formatting.StringFormatter.sendNPCMessage;
import static net.knarcraft.blacksmith.formatting.BlacksmithStringFormatter.sendNPCMessage;
/**
* The class representing the Blacksmith NPC trait
@ -124,7 +124,7 @@ public class BlacksmithTrait extends Trait {
if (!calendar.after(coolDowns.get(playerId))) {
int secondDifference = (int) (coolDowns.get(playerId).getTimeInMillis() - calendar.getTimeInMillis()) / 1000;
boolean exactTime = BlacksmithPlugin.getInstance().getSettings().getShowExactTime();
sendNPCMessage(this.npc, player, replacePlaceholder(config.getCoolDownUnexpiredMessage(),
sendNPCMessage(this.npc, player, StringFormatter.replacePlaceholder(config.getCoolDownUnexpiredMessage(),
"{time}", TimeFormatter.formatTime(exactTime, secondDifference)));
return false;
}
@ -157,7 +157,7 @@ public class BlacksmithTrait extends Trait {
if (session.isRunning()) {
int timeRemaining = (int) ((session.getFinishTime() - System.currentTimeMillis()) / 1000);
boolean showExactTime = BlacksmithPlugin.getInstance().getSettings().getShowExactTime();
sendNPCMessage(this.npc, player, replacePlaceholder(config.getBusyReforgingMessage(), "{time}",
sendNPCMessage(this.npc, player, StringFormatter.replacePlaceholder(config.getBusyReforgingMessage(), "{time}",
TimeFormatter.formatTime(showExactTime, timeRemaining)));
return;
}
@ -180,7 +180,7 @@ public class BlacksmithTrait extends Trait {
//Refuse if not repairable, or if reforge-able items is set, but doesn't include the held item
List<Material> reforgeAbleItems = config.getReforgeAbleItems();
if (!isRepairable(hand) || (!reforgeAbleItems.isEmpty() && !reforgeAbleItems.contains(hand.getType()))) {
String invalidMessage = replacePlaceholder(config.getInvalidItemMessage(),
String invalidMessage = StringFormatter.replacePlaceholder(config.getInvalidItemMessage(),
"{title}", config.getBlacksmithTitle());
sendNPCMessage(this.npc, player, invalidMessage);
return;

View File

@ -21,7 +21,7 @@ import java.util.Objects;
import java.util.Random;
import java.util.logging.Level;
import static net.knarcraft.blacksmith.formatting.StringFormatter.sendNPCMessage;
import static net.knarcraft.blacksmith.formatting.BlacksmithStringFormatter.sendNPCMessage;
/**
* A representation of the session between a player and a blacksmith

View File

@ -1,32 +0,0 @@
package net.knarcraft.blacksmith.util;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
/**
* A helper class for dealing with files
*/
public final class FileHelper {
private FileHelper() {
}
/**
* Gets a buffered reader for
*
* @return <p>A buffered read for reading the file</p>
* @throws FileNotFoundException <p>If unable to get an input stream for the given file</p>
*/
public static BufferedReader getBufferedReaderForInternalFile(String file) throws FileNotFoundException {
InputStream inputStream = FileHelper.class.getResourceAsStream(file);
if (inputStream == null) {
throw new FileNotFoundException("Unable to read the given file");
}
return new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
}
}

View File

@ -1,32 +0,0 @@
package net.knarcraft.blacksmith.util;
import java.util.ArrayList;
import java.util.List;
/**
* A helper class for tab-completion
*/
public final class TabCompletionHelper {
private TabCompletionHelper() {
}
/**
* Finds tab complete values that contain the typed text
*
* @param values <p>The values to filter</p>
* @param typedText <p>The text the player has started typing</p>
* @return <p>The given string values that contain the player's typed text</p>
*/
public static List<String> filterMatchingContains(List<String> values, String typedText) {
List<String> configValues = new ArrayList<>();
for (String value : values) {
if (value.toLowerCase().contains(typedText.toLowerCase())) {
configValues.add(value);
}
}
return configValues;
}
}

View File

@ -1,13 +1,12 @@
package net.knarcraft.blacksmith.util;
import net.knarcraft.blacksmith.config.SettingValueType;
import net.knarcraft.blacksmith.formatting.TranslatableMessage;
import net.knarcraft.blacksmith.formatting.BlacksmithTranslatableMessage;
import net.knarcraft.knarlib.formatting.StringFormatter;
import org.bukkit.command.CommandSender;
import java.util.List;
import static net.knarcraft.blacksmith.formatting.StringFormatter.displayErrorMessage;
/**
* A helper class for validating a value's type
*/
@ -52,7 +51,7 @@ public final class TypeValidationHelper {
private static boolean isStringList(Object value, CommandSender sender) {
boolean isStringList = value instanceof String[] || value instanceof List<?> || value instanceof String;
if (!isStringList && sender != null) {
displayErrorMessage(sender, TranslatableMessage.INPUT_STRING_LIST_REQUIRED);
StringFormatter.displayErrorMessage(sender, BlacksmithTranslatableMessage.INPUT_STRING_LIST_REQUIRED);
}
return isStringList;
}
@ -70,7 +69,7 @@ public final class TypeValidationHelper {
return intValue >= 0 && intValue <= 100;
} catch (NumberFormatException | NullPointerException exception) {
if (sender != null) {
displayErrorMessage(sender, TranslatableMessage.INPUT_PERCENTAGE_REQUIRED);
StringFormatter.displayErrorMessage(sender, BlacksmithTranslatableMessage.INPUT_PERCENTAGE_REQUIRED);
}
return false;
}
@ -86,7 +85,7 @@ public final class TypeValidationHelper {
private static boolean isNonEmptyString(Object value, CommandSender sender) {
boolean isString = value instanceof String string && !string.strip().isEmpty();
if (!isString && sender != null) {
displayErrorMessage(sender, TranslatableMessage.INPUT_STRING_REQUIRED);
StringFormatter.displayErrorMessage(sender, BlacksmithTranslatableMessage.INPUT_STRING_REQUIRED);
}
return isString;
}
@ -103,7 +102,7 @@ public final class TypeValidationHelper {
return ConfigHelper.asDouble(value) >= 0.0;
} catch (NumberFormatException | NullPointerException exception) {
if (sender != null) {
displayErrorMessage(sender, TranslatableMessage.INPUT_POSITIVE_DOUBLE_REQUIRED);
StringFormatter.displayErrorMessage(sender, BlacksmithTranslatableMessage.INPUT_POSITIVE_DOUBLE_REQUIRED);
}
return false;
}
@ -121,7 +120,7 @@ public final class TypeValidationHelper {
return ConfigHelper.asInt(value) >= 0;
} catch (NumberFormatException | NullPointerException exception) {
if (sender != null) {
displayErrorMessage(sender, TranslatableMessage.INPUT_POSITIVE_INTEGER_REQUIRED);
StringFormatter.displayErrorMessage(sender, BlacksmithTranslatableMessage.INPUT_POSITIVE_INTEGER_REQUIRED);
}
return false;
}