mirror of
https://github.com/songoda/SongodaCore.git
synced 2024-11-26 20:16:18 +01:00
refactor: Refactors a couple of classes by applying our code style
This commit is contained in:
parent
8c06a740d5
commit
dce7adf81f
@ -20,7 +20,7 @@ public final class CoreLogger extends Logger {
|
||||
LogManager.getLogManager().addLogger(this);
|
||||
}
|
||||
|
||||
protected void setPlugin(Plugin plugin) {
|
||||
void setPlugin(Plugin plugin) {
|
||||
this.pluginPrefix = "[" + plugin.getName() + "] ";
|
||||
}
|
||||
|
||||
|
@ -224,7 +224,7 @@ public class SongodaCore {
|
||||
this.loginListener = null;
|
||||
}
|
||||
|
||||
private ArrayList<BukkitTask> tasks = new ArrayList<>();
|
||||
private final ArrayList<BukkitTask> tasks = new ArrayList<>();
|
||||
|
||||
private void register(JavaPlugin plugin, int pluginID, String icon, String libraryVersion) {
|
||||
getLogger().info(getPrefix() + "Hooked " + plugin.getName() + ".");
|
||||
|
@ -71,7 +71,7 @@ public abstract class SongodaPlugin extends JavaPlugin {
|
||||
public abstract List<Config> getExtraConfig();
|
||||
|
||||
@Override
|
||||
public FileConfiguration getConfig() {
|
||||
public @NotNull FileConfiguration getConfig() {
|
||||
return this.config.getFileConfig();
|
||||
}
|
||||
|
||||
@ -172,7 +172,6 @@ public abstract class SongodaPlugin extends JavaPlugin {
|
||||
return;
|
||||
}
|
||||
|
||||
// Start Metrics
|
||||
Metrics.start(this);
|
||||
} catch (Throwable th) {
|
||||
criticalErrorOnPluginStartup(th);
|
||||
@ -225,7 +224,6 @@ public abstract class SongodaPlugin extends JavaPlugin {
|
||||
* @param localeName locale to use, eg "en_US"
|
||||
* @param reload optionally reload the loaded locale if the locale didn't
|
||||
* change
|
||||
*
|
||||
* @return true if the locale exists and was loaded successfully
|
||||
*/
|
||||
public boolean setLocale(String localeName, boolean reload) {
|
||||
@ -233,9 +231,9 @@ public abstract class SongodaPlugin extends JavaPlugin {
|
||||
return !reload || this.locale.reloadMessages();
|
||||
}
|
||||
|
||||
Locale l = Locale.loadLocale(this, localeName);
|
||||
if (l != null) {
|
||||
this.locale = l;
|
||||
Locale loadedLocale = Locale.loadLocale(this, localeName);
|
||||
if (loadedLocale != null) {
|
||||
this.locale = loadedLocale;
|
||||
return true;
|
||||
}
|
||||
|
||||
@ -249,23 +247,23 @@ public abstract class SongodaPlugin extends JavaPlugin {
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs one or multiple errors that occurred during plugin startup and calls {@link #emergencyStop()} afterwards
|
||||
* Logs one or multiple errors that occurred during plugin startup and calls {@link #emergencyStop()} afterward
|
||||
*
|
||||
* @param th The error(s) that occurred
|
||||
* @param throwable The error(s) that occurred
|
||||
*/
|
||||
protected void criticalErrorOnPluginStartup(Throwable th) {
|
||||
protected void criticalErrorOnPluginStartup(Throwable throwable) {
|
||||
Bukkit.getLogger().log(Level.SEVERE,
|
||||
String.format(
|
||||
"Unexpected error while loading %s v%s (core v%s): Disabling plugin!",
|
||||
getDescription().getName(),
|
||||
getDescription().getVersion(),
|
||||
SongodaCore.getVersion()
|
||||
), th);
|
||||
), throwable);
|
||||
|
||||
emergencyStop();
|
||||
}
|
||||
|
||||
//New database stuff
|
||||
// New database stuff
|
||||
public Config getDatabaseConfig() {
|
||||
File databaseFile = new File(getDataFolder(), "database.yml");
|
||||
if (!databaseFile.exists()) {
|
||||
@ -316,13 +314,13 @@ public abstract class SongodaPlugin extends JavaPlugin {
|
||||
}
|
||||
|
||||
if (this.dataManager.getDatabaseConnector().isInitialized()) {
|
||||
//Check if the type is SQLite
|
||||
// Check if the type is SQLite
|
||||
if (this.dataManager.getDatabaseConnector().getType() == DatabaseType.SQLITE) {
|
||||
//Let's convert it to H2
|
||||
// Let's convert it to H2
|
||||
try {
|
||||
DataManager newDataManager = DataMigration.convert(this, DatabaseType.H2);
|
||||
if (newDataManager != null && newDataManager.getDatabaseConnector().isInitialized()) {
|
||||
//Set the new data manager
|
||||
// Set the new data manager
|
||||
setDataManager(newDataManager);
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
|
@ -23,30 +23,31 @@ import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
public class AdventureUtils {
|
||||
|
||||
private static Method displayNameMethod = null;
|
||||
private static Method loreMethod = null;
|
||||
private static Class<?> componentClass;
|
||||
private static Object gsonComponentSerializer;
|
||||
private static Method gsonDeserializeMethod;
|
||||
|
||||
static {
|
||||
if (ServerProject.isServer(ServerProject.PAPER) && ServerVersion.isServerVersionAtLeast(ServerVersion.V1_18)) {
|
||||
try {
|
||||
componentClass = Class.forName("net;kyori;adventure;text;Component".replace(";", "."));
|
||||
Class<?> componentClass = Class.forName("net;kyori;adventure;text;Component".replace(";", "."));
|
||||
displayNameMethod = ItemMeta.class.getDeclaredMethod("displayName", componentClass);
|
||||
loreMethod = ItemMeta.class.getDeclaredMethod("lore", List.class);
|
||||
gsonComponentSerializer = Class.forName("net;kyori;adventure;text;serializer;gson;GsonComponentSerializer".replace(";", ".")).getDeclaredMethod("gson").invoke(null);
|
||||
gsonDeserializeMethod = gsonComponentSerializer.getClass().getDeclaredMethod("deserialize", String.class);
|
||||
gsonDeserializeMethod.setAccessible(true);
|
||||
|
||||
} catch (Exception ignored) {}
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a shaded component to a json string
|
||||
*
|
||||
* @param component The shaded Component to convert
|
||||
*
|
||||
* @return Json string
|
||||
*/
|
||||
public static String convertToJson(Component component) {
|
||||
@ -56,14 +57,16 @@ public class AdventureUtils {
|
||||
/**
|
||||
* Convert a json string to the non-shaded component
|
||||
* Cast it to the correct type
|
||||
*
|
||||
* @param json Json string
|
||||
*
|
||||
* @return Non-shaded component
|
||||
*/
|
||||
public static Object convertToOriginalComponent(String json) {
|
||||
try {
|
||||
return gsonDeserializeMethod.invoke(gsonComponentSerializer, json);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@ -71,14 +74,16 @@ public class AdventureUtils {
|
||||
/**
|
||||
* Convert the shaded Component to the original one
|
||||
* Cast it to the correct type
|
||||
*
|
||||
* @param component Shaded component
|
||||
*
|
||||
* @return Original component
|
||||
*/
|
||||
public static Object convertToOriginalComponent(Component component) {
|
||||
try {
|
||||
return gsonDeserializeMethod.invoke(gsonComponentSerializer, convertToJson(component));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@ -86,18 +91,20 @@ public class AdventureUtils {
|
||||
/**
|
||||
* Convert a list of shaded components to a list of original components
|
||||
* Cast it to the correct type
|
||||
* @param component List of shaded components
|
||||
*
|
||||
* @param components List of shaded components
|
||||
*
|
||||
* @return List of original components
|
||||
*/
|
||||
public static Object convertToOriginalComponent(List<Component> component) {
|
||||
public static Object convertToOriginalComponent(List<Component> components) {
|
||||
try {
|
||||
LinkedList<Object> list = new LinkedList<>();
|
||||
for (Component c : component) {
|
||||
list.add(convertToOriginalComponent(c));
|
||||
for (Component component : components) {
|
||||
list.add(convertToOriginalComponent(component));
|
||||
}
|
||||
return list;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@ -105,22 +112,24 @@ public class AdventureUtils {
|
||||
/**
|
||||
* Convert a list of shaded components to a list of original components
|
||||
* Cast it to the correct type
|
||||
* @param component List of shaded components
|
||||
*
|
||||
* @param components List of shaded components
|
||||
*
|
||||
* @return List of original components
|
||||
*/
|
||||
public static Object convertToOriginalComponent(Component... component) {
|
||||
public static Object convertToOriginalComponent(Component... components) {
|
||||
try {
|
||||
LinkedList<Object> list = new LinkedList<>();
|
||||
for (Component c : component) {
|
||||
list.add(convertToOriginalComponent(c));
|
||||
for (Component component : components) {
|
||||
list.add(convertToOriginalComponent(component));
|
||||
}
|
||||
return list;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static void sendMessage(Plugin plugin, Component message, CommandSender... target) {
|
||||
try (BukkitAudiences bukkitAudiences = BukkitAudiences.create(plugin)) {
|
||||
for (CommandSender sender : target) {
|
||||
@ -160,14 +169,18 @@ public class AdventureUtils {
|
||||
|
||||
private static void setItemName(ItemStack item, Component name) {
|
||||
ItemMeta meta = item.getItemMeta();
|
||||
if (meta == null) return;
|
||||
if (meta == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (isMiniMessageEnabled()) {
|
||||
//Set name as component
|
||||
//Set name as a component
|
||||
try {
|
||||
displayNameMethod.invoke(meta, convertToOriginalComponent(name));
|
||||
item.setItemMeta(meta);
|
||||
return;
|
||||
} catch (Exception ignored) {}
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
meta.setDisplayName(toLegacy(name));
|
||||
item.setItemMeta(meta);
|
||||
@ -176,19 +189,21 @@ public class AdventureUtils {
|
||||
private static void setItemLore(ItemStack item, Component... lore) {
|
||||
ItemMeta meta = item.getItemMeta();
|
||||
if (meta == null) return;
|
||||
|
||||
if (isMiniMessageEnabled()) {
|
||||
//Set lore as component
|
||||
try {
|
||||
loreMethod.invoke(meta, convertToOriginalComponent(lore));
|
||||
item.setItemMeta(meta);
|
||||
return;
|
||||
} catch (Exception ignored) {}
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
meta.setLore(toLegacy(lore));
|
||||
item.setItemMeta(meta);
|
||||
}
|
||||
|
||||
//Formatting stuff
|
||||
// Formatting stuff
|
||||
public static Component formatComponent(String text) {
|
||||
MiniMessage miniMessage = MiniMessage.builder().build();
|
||||
Component component = MiniMessage.miniMessage().deserialize(replaceLegacy(text));
|
||||
@ -198,7 +213,7 @@ public class AdventureUtils {
|
||||
return component;
|
||||
}
|
||||
|
||||
public static Component formatComponent(String text, MiniMessagePlaceholder...placeholders) {
|
||||
public static Component formatComponent(String text, MiniMessagePlaceholder... placeholders) {
|
||||
MiniMessage miniMessage = MiniMessage.builder().editTags(builder -> {
|
||||
Arrays.stream(placeholders).forEach(placeholder ->
|
||||
builder.resolver(Placeholder.parsed(placeholder.getPlaceholder(), placeholder.getValue()))
|
||||
@ -223,7 +238,7 @@ public class AdventureUtils {
|
||||
return result;
|
||||
}
|
||||
|
||||
public static List<Component> formatComponent(String...list) {
|
||||
public static List<Component> formatComponent(String... list) {
|
||||
List<Component> result = new ArrayList<>();
|
||||
for (String line : list) {
|
||||
result.add(formatComponent(line));
|
||||
@ -320,60 +335,63 @@ public class AdventureUtils {
|
||||
|
||||
public static String getColor(char c) {
|
||||
ChatColor color = ChatColor.getByChar(c);
|
||||
if (color == null) return null;
|
||||
if (color == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
switch (c) {
|
||||
case '0':
|
||||
return "<black>";
|
||||
return "<black>";
|
||||
case '1':
|
||||
return "<dark_blue>";
|
||||
return "<dark_blue>";
|
||||
case '2':
|
||||
return "<dark_green>";
|
||||
return "<dark_green>";
|
||||
case '3':
|
||||
return "<dark_aqua>";
|
||||
return "<dark_aqua>";
|
||||
case '4':
|
||||
return "<dark_red>";
|
||||
return "<dark_red>";
|
||||
case '5':
|
||||
return "<dark_purple>";
|
||||
return "<dark_purple>";
|
||||
case '6':
|
||||
return "<gold>";
|
||||
return "<gold>";
|
||||
case '7':
|
||||
return "<gray>";
|
||||
return "<gray>";
|
||||
case '8':
|
||||
return "<dark_gray>";
|
||||
return "<dark_gray>";
|
||||
case '9':
|
||||
return "<blue>";
|
||||
return "<blue>";
|
||||
case 'a':
|
||||
return "<green>";
|
||||
return "<green>";
|
||||
case 'b':
|
||||
return "<aqua>";
|
||||
return "<aqua>";
|
||||
case 'c':
|
||||
return "<red>";
|
||||
return "<red>";
|
||||
case 'd':
|
||||
return "<light_purple>";
|
||||
return "<light_purple>";
|
||||
case 'e':
|
||||
return "<yellow>";
|
||||
return "<yellow>";
|
||||
case 'f':
|
||||
return "<white>";
|
||||
return "<white>";
|
||||
case 'k':
|
||||
return "<obfuscated>";
|
||||
return "<obfuscated>";
|
||||
case 'l':
|
||||
return "<b>";
|
||||
return "<b>";
|
||||
case 'm':
|
||||
return "<st>";
|
||||
return "<st>";
|
||||
case 'n':
|
||||
return "<u>";
|
||||
return "<u>";
|
||||
case 'o':
|
||||
return "<i>";
|
||||
return "<i>";
|
||||
case 'r':
|
||||
return "<reset>";
|
||||
return "<reset>";
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static String clear(String msg) {
|
||||
msg = msg.replaceAll("&[0-9kabcdefklmnor]", "");
|
||||
msg = msg.replaceAll("§[0-9kabcdefklmnor]", "");
|
||||
msg = msg.replaceAll("&[0-9abcdefklmnor]", "");
|
||||
msg = msg.replaceAll("§[0-9abcdefklmnor]", "");
|
||||
msg = msg.replaceAll("&#[0-9a-fA-F]{6}", "");
|
||||
return PlainTextComponentSerializer.plainText().serialize(MiniMessage.miniMessage().deserialize(msg));
|
||||
}
|
||||
|
@ -23,11 +23,11 @@ import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class ChatMessage {
|
||||
private static final Gson gson = new GsonBuilder().create();
|
||||
private static final Gson GSON = new GsonBuilder().create();
|
||||
private final List<JsonObject> textList = new ArrayList<>();
|
||||
|
||||
public void clear() {
|
||||
textList.clear();
|
||||
this.textList.clear();
|
||||
}
|
||||
|
||||
public ChatMessage fromText(String text) {
|
||||
@ -44,7 +44,7 @@ public class ChatMessage {
|
||||
ColorContainer color = null;
|
||||
String match1 = matcher.group(1);
|
||||
|
||||
if (matcher.groupCount() == 0 || match1.length() == 0) {
|
||||
if (matcher.groupCount() == 0 || match1.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@ -69,7 +69,9 @@ public class ChatMessage {
|
||||
List<ColorCode> stackedCodes = new ArrayList<>();
|
||||
while (subMatcher.find()) {
|
||||
String match2 = subMatcher.group(1);
|
||||
if (match2.length() == 0) continue;
|
||||
if (match2.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
ColorCode code = ColorCode.getByChar(Character.toLowerCase(match2.charAt(0)));
|
||||
|
||||
@ -81,7 +83,7 @@ public class ChatMessage {
|
||||
match2 = match2.substring(1);
|
||||
}
|
||||
|
||||
if (match2.length() != 0) {
|
||||
if (!match2.isEmpty()) {
|
||||
addMessage(match2, color, stackedCodes);
|
||||
}
|
||||
}
|
||||
@ -97,7 +99,7 @@ public class ChatMessage {
|
||||
public String toText(boolean noHex) {
|
||||
StringBuilder text = new StringBuilder();
|
||||
|
||||
for (JsonObject object : textList) {
|
||||
for (JsonObject object : this.textList) {
|
||||
if (object.has("color")) {
|
||||
String color = object.get("color").getAsString();
|
||||
text.append("&");
|
||||
@ -110,7 +112,9 @@ public class ChatMessage {
|
||||
}
|
||||
|
||||
for (ColorCode code : ColorCode.values()) {
|
||||
if (code.isColor()) continue;
|
||||
if (code.isColor()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
String c = code.name().toLowerCase();
|
||||
if (object.has(c) && object.get(c).getAsBoolean()) {
|
||||
@ -128,7 +132,7 @@ public class ChatMessage {
|
||||
JsonObject txt = new JsonObject();
|
||||
txt.addProperty("text", s);
|
||||
|
||||
textList.add(txt);
|
||||
this.textList.add(txt);
|
||||
|
||||
return this;
|
||||
}
|
||||
@ -151,7 +155,7 @@ public class ChatMessage {
|
||||
}
|
||||
}
|
||||
|
||||
textList.add(txt);
|
||||
this.textList.add(txt);
|
||||
return this;
|
||||
}
|
||||
|
||||
@ -169,7 +173,7 @@ public class ChatMessage {
|
||||
click.addProperty("value", cmd);
|
||||
txt.add("clickEvent", click);
|
||||
|
||||
textList.add(txt);
|
||||
this.textList.add(txt);
|
||||
return this;
|
||||
}
|
||||
|
||||
@ -187,7 +191,7 @@ public class ChatMessage {
|
||||
click.addProperty("value", cmd);
|
||||
txt.add("clickEvent", click);
|
||||
|
||||
textList.add(txt);
|
||||
this.textList.add(txt);
|
||||
return this;
|
||||
}
|
||||
|
||||
@ -205,13 +209,13 @@ public class ChatMessage {
|
||||
click.addProperty("value", url);
|
||||
txt.add("clickEvent", hover);
|
||||
|
||||
textList.add(txt);
|
||||
this.textList.add(txt);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return gson.toJson(textList);
|
||||
return GSON.toJson(this.textList);
|
||||
}
|
||||
|
||||
public void sendTo(CommandSender sender) {
|
||||
@ -226,14 +230,14 @@ public class ChatMessage {
|
||||
|
||||
Object packet;
|
||||
if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_19)) {
|
||||
packet = mc_PacketPlayOutChat_new.newInstance(mc_IChatBaseComponent_ChatSerializer_a.invoke(null, gson.toJson(textList)), mc_PacketPlayOutChat_new_1_19_0 ? 1 : false);
|
||||
packet = mc_PacketPlayOutChat_new.newInstance(mc_IChatBaseComponent_ChatSerializer_a.invoke(null, GSON.toJson(textList)), mc_PacketPlayOutChat_new_1_19_0 ? 1 : false);
|
||||
} else if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_16)) {
|
||||
packet = mc_PacketPlayOutChat_new.newInstance(
|
||||
mc_IChatBaseComponent_ChatSerializer_a.invoke(null, gson.toJson(textList)),
|
||||
mc_IChatBaseComponent_ChatSerializer_a.invoke(null, GSON.toJson(textList)),
|
||||
mc_chatMessageType_Chat.get(null),
|
||||
((Player) sender).getUniqueId());
|
||||
} else {
|
||||
packet = mc_PacketPlayOutChat_new.newInstance(mc_IChatBaseComponent_ChatSerializer_a.invoke(null, gson.toJson(textList)));
|
||||
packet = mc_PacketPlayOutChat_new.newInstance(mc_IChatBaseComponent_ChatSerializer_a.invoke(null, GSON.toJson(textList)));
|
||||
}
|
||||
|
||||
Nms.getImplementations().getPlayer().sendPacket((Player) sender, packet);
|
||||
@ -250,10 +254,9 @@ public class ChatMessage {
|
||||
|
||||
private static boolean enabled = ServerVersion.isServerVersionAtLeast(ServerVersion.V1_8);
|
||||
|
||||
private static Class<?> mc_ChatMessageType;
|
||||
private static Method mc_IChatBaseComponent_ChatSerializer_a, cb_craftPlayer_getHandle;
|
||||
private static Constructor mc_PacketPlayOutChat_new;
|
||||
private static Field mc_entityPlayer_playerConnection, mc_chatMessageType_Chat;
|
||||
private static Method mc_IChatBaseComponent_ChatSerializer_a;
|
||||
private static Constructor<?> mc_PacketPlayOutChat_new;
|
||||
private static Field mc_chatMessageType_Chat;
|
||||
private static boolean mc_PacketPlayOutChat_new_1_19_0 = false;
|
||||
|
||||
static {
|
||||
@ -263,14 +266,8 @@ public class ChatMessage {
|
||||
static void init() {
|
||||
if (enabled) {
|
||||
try {
|
||||
final String version = ServerVersion.getServerVersionString();
|
||||
Class<?> cb_craftPlayerClazz, mc_entityPlayerClazz,
|
||||
mc_IChatBaseComponent, mc_IChatBaseComponent_ChatSerializer, mc_PacketPlayOutChat;
|
||||
Class<?> mc_IChatBaseComponent, mc_IChatBaseComponent_ChatSerializer, mc_PacketPlayOutChat;
|
||||
|
||||
cb_craftPlayerClazz = ClassMapping.CRAFT_PLAYER.getClazz();
|
||||
cb_craftPlayer_getHandle = cb_craftPlayerClazz.getDeclaredMethod("getHandle");
|
||||
mc_entityPlayerClazz = ClassMapping.ENTITY_PLAYER.getClazz();
|
||||
mc_entityPlayer_playerConnection = mc_entityPlayerClazz.getDeclaredField(ServerVersion.isServerVersionAtLeast(ServerVersion.V1_17) ? "b" : "playerConnection");
|
||||
mc_IChatBaseComponent = ClassMapping.I_CHAT_BASE_COMPONENT.getClazz();
|
||||
mc_IChatBaseComponent_ChatSerializer = ClassMapping.I_CHAT_BASE_COMPONENT.getClazz("ChatSerializer");
|
||||
mc_IChatBaseComponent_ChatSerializer_a = mc_IChatBaseComponent_ChatSerializer.getMethod("a", String.class);
|
||||
@ -284,7 +281,7 @@ public class ChatMessage {
|
||||
mc_PacketPlayOutChat_new_1_19_0 = true;
|
||||
}
|
||||
} else if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_16)) {
|
||||
mc_ChatMessageType = ClassMapping.CHAT_MESSAGE_TYPE.getClazz();
|
||||
Class<?> mc_ChatMessageType = ClassMapping.CHAT_MESSAGE_TYPE.getClazz();
|
||||
mc_chatMessageType_Chat = mc_ChatMessageType.getField(ServerVersion.isServerVersionAtLeast(ServerVersion.V1_17) ? "a" : "CHAT");
|
||||
mc_PacketPlayOutChat_new = mc_PacketPlayOutChat.getConstructor(mc_IChatBaseComponent, mc_ChatMessageType, UUID.class);
|
||||
} else {
|
||||
@ -298,7 +295,7 @@ public class ChatMessage {
|
||||
}
|
||||
|
||||
public ChatMessage replaceAll(String toReplace, String replaceWith) {
|
||||
for (JsonObject object : textList) {
|
||||
for (JsonObject object : this.textList) {
|
||||
String text = object.get("text").getAsString().replaceAll(toReplace, replaceWith);
|
||||
|
||||
object.remove("text");
|
||||
|
@ -52,11 +52,11 @@ public enum ColorCode {
|
||||
}
|
||||
|
||||
public char getCode() {
|
||||
return code;
|
||||
return this.code;
|
||||
}
|
||||
|
||||
public ChatColor getChatColor() {
|
||||
return chatColor;
|
||||
return this.chatColor;
|
||||
}
|
||||
|
||||
public boolean isColor() {
|
||||
|
@ -10,10 +10,10 @@ public class MiniMessagePlaceholder {
|
||||
}
|
||||
|
||||
public String getPlaceholder() {
|
||||
return placeholder;
|
||||
return this.placeholder;
|
||||
}
|
||||
|
||||
public String getValue() {
|
||||
return value;
|
||||
return this.value;
|
||||
}
|
||||
}
|
||||
|
@ -39,11 +39,11 @@ public abstract class AbstractCommand {
|
||||
}
|
||||
|
||||
public final List<String> getCommands() {
|
||||
return Collections.unmodifiableList(_handledCommands);
|
||||
return Collections.unmodifiableList(this._handledCommands);
|
||||
}
|
||||
|
||||
public final void addSubCommand(String command) {
|
||||
_handledCommands.add(command);
|
||||
this._handledCommands.add(command);
|
||||
}
|
||||
|
||||
protected abstract ReturnType runCommand(CommandSender sender, String... args);
|
||||
@ -57,11 +57,11 @@ public abstract class AbstractCommand {
|
||||
public abstract String getDescription();
|
||||
|
||||
public boolean hasArgs() {
|
||||
return _hasArgs;
|
||||
return this._hasArgs;
|
||||
}
|
||||
|
||||
public boolean isNoConsole() {
|
||||
return _cmdType == CommandType.PLAYER_ONLY;
|
||||
return this._cmdType == CommandType.PLAYER_ONLY;
|
||||
}
|
||||
|
||||
public enum ReturnType {SUCCESS, NEEDS_PLAYER, FAILURE, SYNTAX_ERROR}
|
||||
|
@ -13,6 +13,7 @@ import org.bukkit.command.TabCompleter;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Field;
|
||||
@ -62,11 +63,11 @@ public class CommandManager implements CommandExecutor, TabCompleter {
|
||||
}
|
||||
|
||||
public Set<String> getCommands() {
|
||||
return Collections.unmodifiableSet(commands.keySet());
|
||||
return Collections.unmodifiableSet(this.commands.keySet());
|
||||
}
|
||||
|
||||
public List<String> getSubCommands(String command) {
|
||||
SimpleNestedCommand nested = command == null ? null : commands.get(command.toLowerCase());
|
||||
SimpleNestedCommand nested = command == null ? null : this.commands.get(command.toLowerCase());
|
||||
|
||||
if (nested == null) {
|
||||
return Collections.emptyList();
|
||||
@ -78,13 +79,15 @@ public class CommandManager implements CommandExecutor, TabCompleter {
|
||||
public Set<AbstractCommand> getAllCommands() {
|
||||
HashSet<AbstractCommand> all = new HashSet<>();
|
||||
|
||||
commands.values().stream()
|
||||
.filter(c -> c.parent != null && !all.contains(c.parent))
|
||||
.forEach(c -> {
|
||||
all.add(c.parent);
|
||||
this.commands.values()
|
||||
.stream()
|
||||
.filter(cmd -> cmd.parent != null && !all.contains(cmd.parent))
|
||||
.forEach(cmd -> {
|
||||
all.add(cmd.parent);
|
||||
|
||||
c.children.values().stream()
|
||||
.filter(s -> !all.contains(s))
|
||||
cmd.children.values()
|
||||
.stream()
|
||||
.filter(child -> !all.contains(child))
|
||||
.forEach(all::add);
|
||||
});
|
||||
|
||||
@ -92,7 +95,7 @@ public class CommandManager implements CommandExecutor, TabCompleter {
|
||||
}
|
||||
|
||||
public CommandManager registerCommandDynamically(String command) {
|
||||
CommandManager.registerCommandDynamically(plugin, command, this, this);
|
||||
CommandManager.registerCommandDynamically(this.plugin, command, this, this);
|
||||
return this;
|
||||
}
|
||||
|
||||
@ -100,15 +103,15 @@ public class CommandManager implements CommandExecutor, TabCompleter {
|
||||
SimpleNestedCommand nested = new SimpleNestedCommand(abstractCommand);
|
||||
|
||||
abstractCommand.getCommands().forEach(cmd -> {
|
||||
CommandManager.registerCommandDynamically(plugin, cmd, this, this);
|
||||
commands.put(cmd.toLowerCase(), nested);
|
||||
PluginCommand pcmd = plugin.getCommand(cmd);
|
||||
CommandManager.registerCommandDynamically(this.plugin, cmd, this, this);
|
||||
this.commands.put(cmd.toLowerCase(), nested);
|
||||
PluginCommand pcmd = this.plugin.getCommand(cmd);
|
||||
|
||||
if (pcmd != null) {
|
||||
pcmd.setExecutor(this);
|
||||
pcmd.setTabCompleter(this);
|
||||
} else {
|
||||
plugin.getLogger().warning("Failed to register command: /" + cmd);
|
||||
this.plugin.getLogger().warning("Failed to register command: /" + cmd);
|
||||
}
|
||||
});
|
||||
|
||||
@ -119,38 +122,38 @@ public class CommandManager implements CommandExecutor, TabCompleter {
|
||||
SimpleNestedCommand nested = new SimpleNestedCommand(abstractCommand);
|
||||
|
||||
abstractCommand.getCommands().forEach(cmd -> {
|
||||
commands.put(cmd.toLowerCase(), nested);
|
||||
PluginCommand pcmd = plugin.getCommand(cmd);
|
||||
this.commands.put(cmd.toLowerCase(), nested);
|
||||
PluginCommand pluginCommand = this.plugin.getCommand(cmd);
|
||||
|
||||
if (pcmd == null) {
|
||||
plugin.getLogger().warning("Failed to register command: /" + cmd);
|
||||
if (pluginCommand == null) {
|
||||
this.plugin.getLogger().warning("Failed to register command: /" + cmd);
|
||||
return;
|
||||
}
|
||||
|
||||
pcmd.setExecutor(this);
|
||||
pcmd.setTabCompleter(this);
|
||||
pluginCommand.setExecutor(this);
|
||||
pluginCommand.setTabCompleter(this);
|
||||
});
|
||||
|
||||
return nested;
|
||||
}
|
||||
|
||||
public MainCommand addMainCommand(String command) {
|
||||
MainCommand nested = new MainCommand(plugin, command);
|
||||
commands.put(command.toLowerCase(), nested.nestedCommands);
|
||||
MainCommand nested = new MainCommand(this.plugin, command);
|
||||
this.commands.put(command.toLowerCase(), nested.nestedCommands);
|
||||
|
||||
PluginCommand pcmd = plugin.getCommand(command);
|
||||
if (pcmd != null) {
|
||||
pcmd.setExecutor(this);
|
||||
pcmd.setTabCompleter(this);
|
||||
PluginCommand pluginCommand = this.plugin.getCommand(command);
|
||||
if (pluginCommand != null) {
|
||||
pluginCommand.setExecutor(this);
|
||||
pluginCommand.setTabCompleter(this);
|
||||
} else {
|
||||
plugin.getLogger().warning("Failed to register command: /" + command);
|
||||
this.plugin.getLogger().warning("Failed to register command: /" + command);
|
||||
}
|
||||
|
||||
return nested;
|
||||
}
|
||||
|
||||
public MainCommand getMainCommand(String command) {
|
||||
SimpleNestedCommand nested = command == null ? null : commands.get(command.toLowerCase());
|
||||
SimpleNestedCommand nested = command == null ? null : this.commands.get(command.toLowerCase());
|
||||
|
||||
if (nested != null && nested.parent instanceof MainCommand) {
|
||||
return (MainCommand) nested.parent;
|
||||
@ -168,26 +171,26 @@ public class CommandManager implements CommandExecutor, TabCompleter {
|
||||
}
|
||||
|
||||
public CommandManager setExecutor(String command) {
|
||||
PluginCommand pcmd = command == null ? null : plugin.getCommand(command);
|
||||
PluginCommand pluginCommand = command == null ? null : this.plugin.getCommand(command);
|
||||
|
||||
if (pcmd != null) {
|
||||
pcmd.setExecutor(this);
|
||||
if (pluginCommand != null) {
|
||||
pluginCommand.setExecutor(this);
|
||||
} else {
|
||||
plugin.getLogger().warning("Failed to register command: /" + command);
|
||||
this.plugin.getLogger().warning("Failed to register command: /" + command);
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public CommandManager setUseClosestCommand(boolean bool) {
|
||||
allowLooseCommands = bool;
|
||||
public CommandManager setUseClosestCommand(boolean allowLooseCommands) {
|
||||
this.allowLooseCommands = allowLooseCommands;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCommand(CommandSender commandSender, Command command, String label, String[] args) {
|
||||
public boolean onCommand(@NotNull CommandSender sender, Command command, @NotNull String label, String[] args) {
|
||||
// grab the specific command that's being called
|
||||
SimpleNestedCommand nested = commands.get(command.getName().toLowerCase());
|
||||
SimpleNestedCommand nested = this.commands.get(command.getName().toLowerCase());
|
||||
|
||||
if (nested != null) {
|
||||
// check to see if we're trying to call a sub-command
|
||||
@ -204,19 +207,19 @@ public class CommandManager implements CommandExecutor, TabCompleter {
|
||||
System.arraycopy(args, i, newArgs, 0, newArgs.length);
|
||||
|
||||
// now process the command
|
||||
processRequirements(sub, commandSender, newArgs);
|
||||
processRequirements(sub, sender, newArgs);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// if we've gotten this far, then just use the command we have
|
||||
if (nested.parent != null) {
|
||||
processRequirements(nested.parent, commandSender, args);
|
||||
processRequirements(nested.parent, sender, args);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
commandSender.sendMessage(msg_noCommand);
|
||||
sender.sendMessage(this.msg_noCommand);
|
||||
return true;
|
||||
}
|
||||
|
||||
@ -227,7 +230,7 @@ public class CommandManager implements CommandExecutor, TabCompleter {
|
||||
}
|
||||
|
||||
String match = null;
|
||||
// support for mulit-argument subcommands
|
||||
// support for multi-argument subcommands
|
||||
if (args.length >= 2 && nested.children.keySet().stream().anyMatch(k -> k.indexOf(' ') != -1)) {
|
||||
for (int len = args.length; len > 1; --len) {
|
||||
String cmd2 = String.join(" ", Arrays.copyOf(args, len)).toLowerCase();
|
||||
@ -238,12 +241,12 @@ public class CommandManager implements CommandExecutor, TabCompleter {
|
||||
}
|
||||
|
||||
// if we don't have a subcommand, should we search for one?
|
||||
if (allowLooseCommands) {
|
||||
if (this.allowLooseCommands) {
|
||||
// do a "closest match"
|
||||
int count = 0;
|
||||
for (String c : nested.children.keySet()) {
|
||||
if (c.startsWith(cmd)) {
|
||||
match = c;
|
||||
for (String child : nested.children.keySet()) {
|
||||
if (child.startsWith(cmd)) {
|
||||
match = child;
|
||||
if (++count > 1) {
|
||||
// there can only be one!
|
||||
match = null;
|
||||
@ -258,7 +261,7 @@ public class CommandManager implements CommandExecutor, TabCompleter {
|
||||
|
||||
private void processRequirements(AbstractCommand command, CommandSender sender, String[] args) {
|
||||
if (!(sender instanceof Player) && command.isNoConsole()) {
|
||||
sender.sendMessage(msg_noConsole);
|
||||
sender.sendMessage(this.msg_noConsole);
|
||||
return;
|
||||
}
|
||||
|
||||
@ -266,12 +269,12 @@ public class CommandManager implements CommandExecutor, TabCompleter {
|
||||
AbstractCommand.ReturnType returnType = command.runCommand(sender, args);
|
||||
|
||||
if (returnType == AbstractCommand.ReturnType.NEEDS_PLAYER) {
|
||||
sender.sendMessage(msg_noConsole);
|
||||
sender.sendMessage(this.msg_noConsole);
|
||||
return;
|
||||
}
|
||||
|
||||
if (returnType == AbstractCommand.ReturnType.SYNTAX_ERROR) {
|
||||
for (String s : msg_syntaxError) {
|
||||
for (String s : this.msg_syntaxError) {
|
||||
sender.sendMessage(s.replace("%syntax%", command.getSyntax()));
|
||||
}
|
||||
}
|
||||
@ -279,13 +282,13 @@ public class CommandManager implements CommandExecutor, TabCompleter {
|
||||
return;
|
||||
}
|
||||
|
||||
sender.sendMessage(msg_noPerms);
|
||||
sender.sendMessage(this.msg_noPerms);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
|
||||
public List<String> onTabComplete(@NotNull CommandSender sender, Command command, @NotNull String alias, String[] args) {
|
||||
// grab the specific command that's being called
|
||||
SimpleNestedCommand nested = commands.get(command.getName().toLowerCase());
|
||||
SimpleNestedCommand nested = this.commands.get(command.getName().toLowerCase());
|
||||
|
||||
if (nested != null) {
|
||||
if (args.length == 0 || nested.children.isEmpty()) {
|
||||
@ -332,7 +335,7 @@ public class CommandManager implements CommandExecutor, TabCompleter {
|
||||
if (args.length != 0) {
|
||||
String str = args[args.length - 1];
|
||||
|
||||
if (list != null && str != null && str.length() >= 1) {
|
||||
if (list != null && str != null && !str.isEmpty()) {
|
||||
try {
|
||||
list.removeIf(s -> !s.toLowerCase().startsWith(str.toLowerCase()));
|
||||
} catch (UnsupportedOperationException ignore) {
|
||||
@ -381,12 +384,4 @@ public class CommandManager implements CommandExecutor, TabCompleter {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
private class DCommand extends PluginCommand {
|
||||
|
||||
protected DCommand(@NotNull String name, @NotNull Plugin owner) {
|
||||
super(name, owner);
|
||||
}
|
||||
} */
|
||||
}
|
||||
|
@ -44,12 +44,12 @@ public class MainCommand extends AbstractCommand {
|
||||
}
|
||||
|
||||
public MainCommand addSubCommand(AbstractCommand command) {
|
||||
nestedCommands.addSubCommand(command);
|
||||
this.nestedCommands.addSubCommand(command);
|
||||
return this;
|
||||
}
|
||||
|
||||
public MainCommand addSubCommands(AbstractCommand... commands) {
|
||||
nestedCommands.addSubCommands(commands);
|
||||
this.nestedCommands.addSubCommands(commands);
|
||||
return this;
|
||||
}
|
||||
|
||||
@ -57,38 +57,38 @@ public class MainCommand extends AbstractCommand {
|
||||
protected ReturnType runCommand(CommandSender sender, String... args) {
|
||||
sender.sendMessage("");
|
||||
|
||||
if (header != null) {
|
||||
sender.sendMessage(header);
|
||||
if (this.header != null) {
|
||||
sender.sendMessage(this.header);
|
||||
} else {
|
||||
new ChatMessage().fromText(String.format("#ff8080&l%s &8» &7Version %s Created with <3 by #ec4e74&l&oS#fa5b65&l&oo#ff6c55&l&on#ff7f44&l&og#ff9432&l&oo#ffaa1e&l&od#f4c009&l&oa",
|
||||
plugin.getDescription().getName(), plugin.getDescription().getVersion()), sender instanceof ConsoleCommandSender)
|
||||
this.plugin.getDescription().getName(), this.plugin.getDescription().getVersion()), sender instanceof ConsoleCommandSender)
|
||||
.sendTo(sender);
|
||||
}
|
||||
|
||||
sender.sendMessage(ChatColor.DARK_GRAY + "- " + ChatColor.YELLOW + "/songoda" + ChatColor.GRAY + " - Opens the Songoda plugin GUI");
|
||||
sender.sendMessage("");
|
||||
|
||||
if (nestedCommands != null) {
|
||||
List<String> commands = nestedCommands.children.values().stream().distinct().map(c -> c.getCommands().get(0)).collect(Collectors.toList());
|
||||
if (this.nestedCommands != null) {
|
||||
List<String> commands = this.nestedCommands.children.values().stream().distinct().map(c -> c.getCommands().get(0)).collect(Collectors.toList());
|
||||
|
||||
if (sortHelp) {
|
||||
if (this.sortHelp) {
|
||||
Collections.sort(commands);
|
||||
}
|
||||
|
||||
boolean isPlayer = sender instanceof Player;
|
||||
// todo? pagation if commands.size is too large? (player-only)
|
||||
// todo? pagination if commands.size is too large? (player-only)
|
||||
sender.sendMessage(ChatColor.DARK_GRAY + "- " + ChatColor.YELLOW + getSyntax() + ChatColor.GRAY + " - " + getDescription());
|
||||
|
||||
for (String cmdStr : commands) {
|
||||
final AbstractCommand cmd = nestedCommands.children.get(cmdStr);
|
||||
final AbstractCommand cmd = this.nestedCommands.children.get(cmdStr);
|
||||
if (cmd == null) continue;
|
||||
if (!isPlayer) {
|
||||
sender.sendMessage(ChatColor.DARK_GRAY + "- " + ChatColor.YELLOW + cmd.getSyntax() + ChatColor.GRAY + " - " + cmd.getDescription());
|
||||
} else if (cmd.getPermissionNode() == null || sender.hasPermission(cmd.getPermissionNode())) {
|
||||
ChatMessage chatMessage = new ChatMessage();
|
||||
final String c = "/" + command + " ";
|
||||
final String command = "/" + this.command + " ";
|
||||
chatMessage.addMessage(ChatColor.DARK_GRAY + "- ")
|
||||
.addPromptCommand(ChatColor.YELLOW + c + cmd.getSyntax(), ChatColor.YELLOW + c + cmdStr, c + cmdStr)
|
||||
.addPromptCommand(ChatColor.YELLOW + command + cmd.getSyntax(), ChatColor.YELLOW + command + cmdStr, command + cmdStr)
|
||||
.addMessage(ChatColor.GRAY + " - " + cmd.getDescription());
|
||||
chatMessage.sendTo(sender);
|
||||
}
|
||||
@ -114,11 +114,11 @@ public class MainCommand extends AbstractCommand {
|
||||
|
||||
@Override
|
||||
public String getSyntax() {
|
||||
return "/" + command;
|
||||
return "/" + this.command;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getDescription() {
|
||||
return description;
|
||||
return this.description;
|
||||
}
|
||||
}
|
||||
|
@ -38,20 +38,20 @@ public class SelectorArguments {
|
||||
return null;
|
||||
}
|
||||
|
||||
Matcher m = selectorPattern.matcher(argument);
|
||||
if (!m.find()) {
|
||||
Matcher matcher = selectorPattern.matcher(argument);
|
||||
if (!matcher.find()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
SelectorType type = SelectorType.getType(m.group(1));
|
||||
SelectorType type = SelectorType.getType(matcher.group(1));
|
||||
if (type == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
SelectorArguments selector = new SelectorArguments(sender, type);
|
||||
|
||||
if (m.group(3) != null) {
|
||||
selector.parseArguments(m.group(3));
|
||||
if (matcher.group(3) != null) {
|
||||
selector.parseArguments(matcher.group(3));
|
||||
}
|
||||
|
||||
return selector;
|
||||
@ -82,17 +82,17 @@ public class SelectorArguments {
|
||||
Matcher distGroup = selectorRangePattern.matcher(v[1]);
|
||||
if (distGroup.find()) {
|
||||
if (distGroup.group(1) != null) {
|
||||
rangeMin = Double.parseDouble(distGroup.group(1));
|
||||
this.rangeMin = Double.parseDouble(distGroup.group(1));
|
||||
}
|
||||
|
||||
if (distGroup.group(3) == null) {
|
||||
rangeMax = rangeMin;
|
||||
this.rangeMax = this.rangeMin;
|
||||
} else if (distGroup.group(4) != null) {
|
||||
rangeMax = Double.parseDouble(distGroup.group(4));
|
||||
this.rangeMax = Double.parseDouble(distGroup.group(4));
|
||||
}
|
||||
}
|
||||
} else if (v[0].equals("type")) {
|
||||
entityType = EntityNamespace.minecraftToBukkit(v[1]);
|
||||
this.entityType = EntityNamespace.minecraftToBukkit(v[1]);
|
||||
}
|
||||
|
||||
// more arguments can be parsed here (TODO)
|
||||
@ -126,7 +126,7 @@ public class SelectorArguments {
|
||||
}
|
||||
|
||||
public Collection<Entity> getSelection() {
|
||||
final Location location = sender instanceof Player ? ((Player) sender).getLocation() : ((BlockCommandSender) sender).getBlock().getLocation();
|
||||
final Location location = this.sender instanceof Player ? ((Player) this.sender).getLocation() : ((BlockCommandSender) this.sender).getBlock().getLocation();
|
||||
Collection<Entity> list = preSelect(location);
|
||||
|
||||
if (list.isEmpty()) {
|
||||
@ -139,7 +139,7 @@ public class SelectorArguments {
|
||||
return list2;
|
||||
}
|
||||
|
||||
switch (selector) {
|
||||
switch (this.selector) {
|
||||
case PLAYER:
|
||||
list2.sort((o1, o2) -> (int) (o1.getLocation().distanceSquared(location) - o2.getLocation().distanceSquared(location)));
|
||||
|
||||
@ -157,22 +157,22 @@ public class SelectorArguments {
|
||||
}
|
||||
|
||||
protected Collection<Entity> preSelect(Location location) {
|
||||
switch (selector) {
|
||||
switch (this.selector) {
|
||||
case PLAYER:
|
||||
case RANDOM_PLAYER:
|
||||
case ALL_PLAYER:
|
||||
return rangeMax == Double.POSITIVE_INFINITY
|
||||
return this.rangeMax == Double.POSITIVE_INFINITY
|
||||
? location.getWorld().getEntitiesByClasses(Player.class)
|
||||
: location.getWorld().getNearbyEntities(location, rangeMax * 2, rangeMax * 2, rangeMax * 2).stream()
|
||||
: location.getWorld().getNearbyEntities(location, this.rangeMax * 2, this.rangeMax * 2, this.rangeMax * 2).stream()
|
||||
.filter(Player.class::isInstance).collect(Collectors.toSet());
|
||||
|
||||
case ALL_ENTITIES:
|
||||
return rangeMax == Double.POSITIVE_INFINITY
|
||||
return this.rangeMax == Double.POSITIVE_INFINITY
|
||||
? location.getWorld().getEntities()
|
||||
: location.getWorld().getNearbyEntities(location, rangeMax * 2, rangeMax * 2, rangeMax * 2);
|
||||
: location.getWorld().getNearbyEntities(location, this.rangeMax * 2, this.rangeMax * 2, this.rangeMax * 2);
|
||||
|
||||
case SELF:
|
||||
return sender instanceof Entity ? Arrays.asList((Entity) sender) : Collections.emptyList();
|
||||
return this.sender instanceof Entity ? Arrays.asList((Entity) this.sender) : Collections.emptyList();
|
||||
}
|
||||
|
||||
return Collections.emptyList();
|
||||
@ -180,8 +180,8 @@ public class SelectorArguments {
|
||||
|
||||
protected List<Entity> filter(Location location, Collection<Entity> list) {
|
||||
Stream<Entity> stream = list.stream()
|
||||
.filter(p -> rangeMin == 0 || p.getLocation().distance(location) > rangeMin)
|
||||
.filter(e -> entityType == null || e.getType() == entityType);
|
||||
.filter(p -> this.rangeMin == 0 || p.getLocation().distance(location) > this.rangeMin)
|
||||
.filter(e -> this.entityType == null || e.getType() == this.entityType);
|
||||
|
||||
return stream.collect(Collectors.toList());
|
||||
}
|
||||
|
@ -12,12 +12,12 @@ public class SimpleNestedCommand {
|
||||
}
|
||||
|
||||
public SimpleNestedCommand addSubCommand(AbstractCommand command) {
|
||||
command.getCommands().forEach(cmd -> children.put(cmd.toLowerCase(), command));
|
||||
command.getCommands().forEach(cmd -> this.children.put(cmd.toLowerCase(), command));
|
||||
return this;
|
||||
}
|
||||
|
||||
public SimpleNestedCommand addSubCommands(AbstractCommand... commands) {
|
||||
Stream.of(commands).forEach(command -> command.getCommands().forEach(cmd -> children.put(cmd.toLowerCase(), command)));
|
||||
Stream.of(commands).forEach(command -> command.getCommands().forEach(cmd -> this.children.put(cmd.toLowerCase(), command)));
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
@ -39,7 +39,7 @@ public class Comment {
|
||||
}
|
||||
|
||||
public ConfigFormattingRules.CommentStyle getCommentStyle() {
|
||||
return commentStyle;
|
||||
return this.commentStyle;
|
||||
}
|
||||
|
||||
public void setCommentStyle(ConfigFormattingRules.CommentStyle commentStyle) {
|
||||
@ -47,12 +47,12 @@ public class Comment {
|
||||
}
|
||||
|
||||
public List<String> getLines() {
|
||||
return lines;
|
||||
return this.lines;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return lines.isEmpty() ? "" : String.join("\n", lines);
|
||||
return this.lines.isEmpty() ? "" : String.join("\n", this.lines);
|
||||
}
|
||||
|
||||
public static Comment loadComment(List<String> lines) {
|
||||
@ -66,13 +66,13 @@ public class Comment {
|
||||
}
|
||||
|
||||
public void writeComment(Writer output, int offset, ConfigFormattingRules.CommentStyle defaultStyle) throws IOException {
|
||||
ConfigFormattingRules.CommentStyle style = commentStyle != null ? commentStyle : defaultStyle;
|
||||
ConfigFormattingRules.CommentStyle style = this.commentStyle != null ? this.commentStyle : defaultStyle;
|
||||
int minSpacing = 0, borderSpacing = 0;
|
||||
|
||||
// first draw the top of the comment
|
||||
if (style.drawBorder) {
|
||||
// grab the longest line in the list of lines
|
||||
minSpacing = lines.stream().max(Comparator.comparingInt(String::length)).orElse("").length();
|
||||
minSpacing = this.lines.stream().max(Comparator.comparingInt(String::length)).orElse("").length();
|
||||
borderSpacing = minSpacing + style.commentPrefix.length() + style.commentSuffix.length();
|
||||
|
||||
// draw the first line
|
||||
@ -89,7 +89,7 @@ public class Comment {
|
||||
}
|
||||
|
||||
// then the actual comment lines
|
||||
for (String line : lines) {
|
||||
for (String line : this.lines) {
|
||||
// todo? should we auto-wrap comment lines that are longer than 80 characters?
|
||||
output.write((new String(new char[offset])).replace('\0', ' ') + "#" + style.commentPrefix
|
||||
+ (minSpacing == 0 ? line : line + (new String(new char[minSpacing - line.length()])).replace('\0', ' ')) + style.commentSuffix + (style.drawBorder ? "#\n" : "\n"));
|
||||
|
@ -17,8 +17,6 @@ import org.yaml.snakeyaml.representer.Representer;
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStreamWriter;
|
||||
@ -28,6 +26,7 @@ import java.io.StringWriter;
|
||||
import java.io.Writer;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
@ -66,7 +65,7 @@ public class Config extends ConfigSection {
|
||||
final Plugin plugin;
|
||||
final DumperOptions yamlOptions = new DumperOptions();
|
||||
final Representer yamlRepresenter = new YamlRepresenter();
|
||||
final Yaml yaml = new Yaml(new YamlConstructor(), yamlRepresenter, yamlOptions);
|
||||
final Yaml yaml = new Yaml(new YamlConstructor(), this.yamlRepresenter, this.yamlOptions);
|
||||
Charset defaultCharset = StandardCharsets.UTF_8;
|
||||
SaveTask saveTask;
|
||||
Timer autosaveTimer;
|
||||
@ -117,59 +116,59 @@ public class Config extends ConfigSection {
|
||||
this.plugin = null;
|
||||
this.file = null;
|
||||
|
||||
dirName = null;
|
||||
fileName = null;
|
||||
this.dirName = null;
|
||||
this.fileName = null;
|
||||
}
|
||||
|
||||
public Config(@NotNull File file) {
|
||||
this.plugin = null;
|
||||
this.file = file.getAbsoluteFile();
|
||||
|
||||
dirName = null;
|
||||
fileName = null;
|
||||
this.dirName = null;
|
||||
this.fileName = null;
|
||||
}
|
||||
|
||||
public Config(@NotNull Plugin plugin) {
|
||||
this.plugin = plugin;
|
||||
|
||||
dirName = null;
|
||||
fileName = null;
|
||||
this.dirName = null;
|
||||
this.fileName = null;
|
||||
}
|
||||
|
||||
public Config(@NotNull Plugin plugin, @NotNull String file) {
|
||||
this.plugin = plugin;
|
||||
|
||||
dirName = null;
|
||||
fileName = file;
|
||||
this.dirName = null;
|
||||
this.fileName = file;
|
||||
}
|
||||
|
||||
public Config(@NotNull Plugin plugin, @Nullable String directory, @NotNull String file) {
|
||||
this.plugin = plugin;
|
||||
|
||||
dirName = directory;
|
||||
fileName = file;
|
||||
this.dirName = directory;
|
||||
this.fileName = file;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ConfigFileConfigurationAdapter getFileConfig() {
|
||||
return config;
|
||||
return this.config;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public File getFile() {
|
||||
if (file == null) {
|
||||
if (dirName != null) {
|
||||
this.file = new File(plugin.getDataFolder() + dirName, fileName != null ? fileName : "config.yml");
|
||||
if (this.file == null) {
|
||||
if (this.dirName != null) {
|
||||
this.file = new File(this.plugin.getDataFolder() + this.dirName, this.fileName != null ? this.fileName : "config.yml");
|
||||
} else {
|
||||
this.file = new File(plugin.getDataFolder(), fileName != null ? fileName : "config.yml");
|
||||
this.file = new File(this.plugin.getDataFolder(), this.fileName != null ? this.fileName : "config.yml");
|
||||
}
|
||||
}
|
||||
|
||||
return file;
|
||||
return this.file;
|
||||
}
|
||||
|
||||
public Charset getDefaultCharset() {
|
||||
return defaultCharset;
|
||||
return this.defaultCharset;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -195,7 +194,7 @@ public class Config extends ConfigSection {
|
||||
}
|
||||
|
||||
public boolean getLoadComments() {
|
||||
return loadComments;
|
||||
return this.loadComments;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -208,7 +207,7 @@ public class Config extends ConfigSection {
|
||||
}
|
||||
|
||||
public boolean getAutosave() {
|
||||
return autosave;
|
||||
return this.autosave;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -226,7 +225,7 @@ public class Config extends ConfigSection {
|
||||
}
|
||||
|
||||
public int getAutosaveInterval() {
|
||||
return autosaveInterval;
|
||||
return this.autosaveInterval;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -244,7 +243,7 @@ public class Config extends ConfigSection {
|
||||
}
|
||||
|
||||
public boolean getAutoremove() {
|
||||
return autoremove;
|
||||
return this.autoremove;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -268,7 +267,7 @@ public class Config extends ConfigSection {
|
||||
*/
|
||||
@Nullable
|
||||
public ConfigFormattingRules.CommentStyle getDefaultNodeCommentFormat() {
|
||||
return defaultNodeCommentFormat;
|
||||
return this.defaultNodeCommentFormat;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -287,7 +286,7 @@ public class Config extends ConfigSection {
|
||||
*/
|
||||
@Nullable
|
||||
public ConfigFormattingRules.CommentStyle getDefaultSectionCommentFormat() {
|
||||
return defaultSectionCommentFormat;
|
||||
return this.defaultSectionCommentFormat;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -305,7 +304,7 @@ public class Config extends ConfigSection {
|
||||
* Extra lines to put between root nodes
|
||||
*/
|
||||
public int getRootNodeSpacing() {
|
||||
return rootNodeSpacing;
|
||||
return this.rootNodeSpacing;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -324,7 +323,7 @@ public class Config extends ConfigSection {
|
||||
* This is separate from rootNodeSpacing, if applicable.
|
||||
*/
|
||||
public int getCommentSpacing() {
|
||||
return commentSpacing;
|
||||
return this.commentSpacing;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -342,9 +341,9 @@ public class Config extends ConfigSection {
|
||||
@NotNull
|
||||
public Config setHeader(@NotNull String... description) {
|
||||
if (description.length == 0) {
|
||||
headerComment = null;
|
||||
this.headerComment = null;
|
||||
} else {
|
||||
headerComment = new Comment(description);
|
||||
this.headerComment = new Comment(description);
|
||||
}
|
||||
|
||||
return this;
|
||||
@ -353,9 +352,9 @@ public class Config extends ConfigSection {
|
||||
@NotNull
|
||||
public Config setHeader(@Nullable ConfigFormattingRules.CommentStyle commentStyle, @NotNull String... description) {
|
||||
if (description.length == 0) {
|
||||
headerComment = null;
|
||||
this.headerComment = null;
|
||||
} else {
|
||||
headerComment = new Comment(commentStyle, description);
|
||||
this.headerComment = new Comment(commentStyle, description);
|
||||
}
|
||||
|
||||
return this;
|
||||
@ -364,9 +363,9 @@ public class Config extends ConfigSection {
|
||||
@NotNull
|
||||
public Config setHeader(@Nullable List<String> description) {
|
||||
if (description == null || description.isEmpty()) {
|
||||
headerComment = null;
|
||||
this.headerComment = null;
|
||||
} else {
|
||||
headerComment = new Comment(description);
|
||||
this.headerComment = new Comment(description);
|
||||
}
|
||||
|
||||
return this;
|
||||
@ -375,9 +374,9 @@ public class Config extends ConfigSection {
|
||||
@NotNull
|
||||
public Config setHeader(@Nullable ConfigFormattingRules.CommentStyle commentStyle, @Nullable List<String> description) {
|
||||
if (description == null || description.isEmpty()) {
|
||||
headerComment = null;
|
||||
this.headerComment = null;
|
||||
} else {
|
||||
headerComment = new Comment(commentStyle, description);
|
||||
this.headerComment = new Comment(commentStyle, description);
|
||||
}
|
||||
|
||||
return this;
|
||||
@ -385,28 +384,28 @@ public class Config extends ConfigSection {
|
||||
|
||||
@NotNull
|
||||
public List<String> getHeader() {
|
||||
if (headerComment != null) {
|
||||
return headerComment.getLines();
|
||||
if (this.headerComment != null) {
|
||||
return this.headerComment.getLines();
|
||||
}
|
||||
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
public Config clearConfig(boolean clearDefaults) {
|
||||
root.values.clear();
|
||||
root.configComments.clear();
|
||||
this.root.values.clear();
|
||||
this.root.configComments.clear();
|
||||
|
||||
if (clearDefaults) {
|
||||
root.defaultComments.clear();
|
||||
root.defaults.clear();
|
||||
this.root.defaultComments.clear();
|
||||
this.root.defaults.clear();
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public Config clearDefaults() {
|
||||
root.defaultComments.clear();
|
||||
root.defaults.clear();
|
||||
this.root.defaultComments.clear();
|
||||
this.root.defaults.clear();
|
||||
|
||||
return this;
|
||||
}
|
||||
@ -418,19 +417,19 @@ public class Config extends ConfigSection {
|
||||
public boolean load(@NotNull File file) {
|
||||
Validate.notNull(file, "File cannot be null");
|
||||
if (file.exists()) {
|
||||
try (BufferedInputStream stream = new BufferedInputStream(new FileInputStream(file))) {
|
||||
try (BufferedInputStream stream = new BufferedInputStream(Files.newInputStream(file.toPath()))) {
|
||||
Charset charset = TextUtils.detectCharset(stream, StandardCharsets.UTF_8);
|
||||
|
||||
// upgrade charset if file was saved in a more complex format
|
||||
if (charset == StandardCharsets.UTF_16BE || charset == StandardCharsets.UTF_16LE) {
|
||||
defaultCharset = StandardCharsets.UTF_16;
|
||||
this.defaultCharset = StandardCharsets.UTF_16;
|
||||
}
|
||||
|
||||
this.load(new InputStreamReader(stream, charset));
|
||||
|
||||
return true;
|
||||
} catch (IOException | InvalidConfigurationException ex) {
|
||||
(plugin != null ? plugin.getLogger() : Bukkit.getLogger()).log(Level.SEVERE, "Failed to load config file: " + file.getName(), ex);
|
||||
(this.plugin != null ? this.plugin.getLogger() : Bukkit.getLogger()).log(Level.SEVERE, "Failed to load config file: " + file.getName(), ex);
|
||||
}
|
||||
|
||||
return false;
|
||||
@ -461,7 +460,7 @@ public class Config extends ConfigSection {
|
||||
Map<?, ?> input;
|
||||
|
||||
try {
|
||||
input = (Map<?, ?>) this.yaml.load(contents);
|
||||
input = this.yaml.load(contents);
|
||||
} catch (YAMLException e2) {
|
||||
throw new InvalidConfigurationException(e2);
|
||||
} catch (ClassCastException e3) {
|
||||
@ -469,7 +468,7 @@ public class Config extends ConfigSection {
|
||||
}
|
||||
|
||||
if (input != null) {
|
||||
if (loadComments) {
|
||||
if (this.loadComments) {
|
||||
this.parseComments(contents, input);
|
||||
}
|
||||
|
||||
@ -511,7 +510,7 @@ public class Config extends ConfigSection {
|
||||
if (firstNode && !commentBlock.isEmpty()) {
|
||||
// header comment
|
||||
firstNode = false;
|
||||
headerComment = Comment.loadComment(commentBlock);
|
||||
this.headerComment = Comment.loadComment(commentBlock);
|
||||
commentBlock.clear();
|
||||
}
|
||||
continue;
|
||||
@ -525,10 +524,10 @@ public class Config extends ConfigSection {
|
||||
int lineOffset = getOffset(line);
|
||||
insideScalar &= lineOffset <= index;
|
||||
Matcher m;
|
||||
if (!insideScalar && (m = yamlNode.matcher(line)).find()) {
|
||||
if (!insideScalar && (m = this.yamlNode.matcher(line)).find()) {
|
||||
// we found a config node! ^.^
|
||||
// check to see what the full path is
|
||||
int depth = (m.group(1).length() / indentation);
|
||||
int depth = (m.group(1).length() / this.indentation);
|
||||
while (depth < currentPath.size()) {
|
||||
currentPath.removeLast();
|
||||
}
|
||||
@ -536,7 +535,7 @@ public class Config extends ConfigSection {
|
||||
|
||||
// do we have a comment for this node?
|
||||
if (!commentBlock.isEmpty()) {
|
||||
String path = currentPath.stream().collect(Collectors.joining(String.valueOf(pathChar)));
|
||||
String path = currentPath.stream().collect(Collectors.joining(String.valueOf(this.pathChar)));
|
||||
Comment comment = Comment.loadComment(commentBlock);
|
||||
commentBlock.clear();
|
||||
setComment(path, comment);
|
||||
@ -553,7 +552,7 @@ public class Config extends ConfigSection {
|
||||
}
|
||||
|
||||
if (!commentBlock.isEmpty()) {
|
||||
footerComment = Comment.loadComment(commentBlock);
|
||||
this.footerComment = Comment.loadComment(commentBlock);
|
||||
commentBlock.clear();
|
||||
}
|
||||
} catch (IOException ex) {
|
||||
@ -563,53 +562,53 @@ public class Config extends ConfigSection {
|
||||
|
||||
public void deleteNonDefaultSettings() {
|
||||
// Delete old config values (thread-safe)
|
||||
List<String> defaultKeys = Arrays.asList(defaults.keySet().toArray(new String[0]));
|
||||
List<String> defaultKeys = Arrays.asList(this.defaults.keySet().toArray(new String[0]));
|
||||
|
||||
for (String key : values.keySet().toArray(new String[0])) {
|
||||
for (String key : this.values.keySet().toArray(new String[0])) {
|
||||
if (!defaultKeys.contains(key)) {
|
||||
values.remove(key);
|
||||
this.values.remove(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onChange() {
|
||||
if (autosave) {
|
||||
if (this.autosave) {
|
||||
delaySave();
|
||||
}
|
||||
}
|
||||
|
||||
public void delaySave() {
|
||||
// save async even if no plugin or if plugin disabled
|
||||
if (saveTask == null && (changed || hasNewDefaults())) {
|
||||
autosaveTimer = new Timer((plugin != null ? plugin.getName() + "-ConfigSave-" : "ConfigSave-") + getFile().getName());
|
||||
autosaveTimer.schedule(saveTask = new SaveTask(), autosaveInterval * 1000L);
|
||||
if (this.saveTask == null && (this.changed || hasNewDefaults())) {
|
||||
this.autosaveTimer = new Timer((this.plugin != null ? this.plugin.getName() + "-ConfigSave-" : "ConfigSave-") + getFile().getName());
|
||||
this.autosaveTimer.schedule(this.saveTask = new SaveTask(), this.autosaveInterval * 1000L);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean saveChanges() {
|
||||
boolean saved = true;
|
||||
|
||||
if (changed || hasNewDefaults()) {
|
||||
if (this.changed || hasNewDefaults()) {
|
||||
saved = save();
|
||||
}
|
||||
|
||||
if (saveTask != null) {
|
||||
if (this.saveTask != null) {
|
||||
//Close Threads
|
||||
saveTask.cancel();
|
||||
autosaveTimer.cancel();
|
||||
saveTask = null;
|
||||
autosaveTimer = null;
|
||||
this.saveTask.cancel();
|
||||
this.autosaveTimer.cancel();
|
||||
this.saveTask = null;
|
||||
this.autosaveTimer = null;
|
||||
}
|
||||
|
||||
return saved;
|
||||
}
|
||||
|
||||
boolean hasNewDefaults() {
|
||||
if (file != null && !file.exists()) return true;
|
||||
if (this.file != null && !this.file.exists()) return true;
|
||||
|
||||
for (String def : defaults.keySet()) {
|
||||
if (!values.containsKey(def)) {
|
||||
for (String def : this.defaults.keySet()) {
|
||||
if (!this.values.containsKey(def)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@ -618,12 +617,12 @@ public class Config extends ConfigSection {
|
||||
}
|
||||
|
||||
public boolean save() {
|
||||
if (saveTask != null) {
|
||||
if (this.saveTask != null) {
|
||||
//Close Threads
|
||||
saveTask.cancel();
|
||||
autosaveTimer.cancel();
|
||||
saveTask = null;
|
||||
autosaveTimer = null;
|
||||
this.saveTask.cancel();
|
||||
this.autosaveTimer.cancel();
|
||||
this.saveTask = null;
|
||||
this.autosaveTimer = null;
|
||||
}
|
||||
|
||||
return save(getFile());
|
||||
@ -642,7 +641,7 @@ public class Config extends ConfigSection {
|
||||
}
|
||||
|
||||
String data = this.saveToString();
|
||||
try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), defaultCharset)) {
|
||||
try (OutputStreamWriter writer = new OutputStreamWriter(Files.newOutputStream(file.toPath()), this.defaultCharset)) {
|
||||
writer.write(data);
|
||||
} catch (IOException ex) {
|
||||
return false;
|
||||
@ -654,30 +653,30 @@ public class Config extends ConfigSection {
|
||||
@NotNull
|
||||
public String saveToString() {
|
||||
try {
|
||||
if (autoremove) {
|
||||
if (this.autoremove) {
|
||||
deleteNonDefaultSettings();
|
||||
}
|
||||
|
||||
yamlOptions.setIndent(indentation);
|
||||
yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
|
||||
yamlOptions.setSplitLines(false);
|
||||
yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
|
||||
this.yamlOptions.setIndent(this.indentation);
|
||||
this.yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
|
||||
this.yamlOptions.setSplitLines(false);
|
||||
this.yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
|
||||
|
||||
StringWriter str = new StringWriter();
|
||||
|
||||
if (headerComment != null) {
|
||||
headerComment.writeComment(str, 0, ConfigFormattingRules.CommentStyle.BLOCKED);
|
||||
if (this.headerComment != null) {
|
||||
this.headerComment.writeComment(str, 0, ConfigFormattingRules.CommentStyle.BLOCKED);
|
||||
str.write("\n"); // add one space after the header
|
||||
}
|
||||
|
||||
String dump = yaml.dump(this.getValues(false));
|
||||
String dump = this.yaml.dump(this.getValues(false));
|
||||
if (!dump.equals(BLANK_CONFIG)) {
|
||||
writeComments(dump, str);
|
||||
}
|
||||
|
||||
if (footerComment != null) {
|
||||
if (this.footerComment != null) {
|
||||
str.write("\n");
|
||||
footerComment.writeComment(str, 0, ConfigFormattingRules.CommentStyle.BLOCKED);
|
||||
this.footerComment.writeComment(str, 0, ConfigFormattingRules.CommentStyle.BLOCKED);
|
||||
}
|
||||
|
||||
return str.toString();
|
||||
@ -711,20 +710,20 @@ public class Config extends ConfigSection {
|
||||
int lineOffset = getOffset(line);
|
||||
insideScalar &= lineOffset <= index;
|
||||
Matcher m;
|
||||
if (!insideScalar && (m = yamlNode.matcher(line)).find()) {
|
||||
if (!insideScalar && (m = this.yamlNode.matcher(line)).find()) {
|
||||
// we found a config node! ^.^
|
||||
// check to see what the full path is
|
||||
int depth = (m.group(1).length() / indentation);
|
||||
int depth = (m.group(1).length() / this.indentation);
|
||||
while (depth < currentPath.size()) {
|
||||
currentPath.removeLast();
|
||||
}
|
||||
|
||||
currentPath.add(m.group(2));
|
||||
String path = currentPath.stream().collect(Collectors.joining(String.valueOf(pathChar)));
|
||||
String path = currentPath.stream().collect(Collectors.joining(String.valueOf(this.pathChar)));
|
||||
|
||||
// if this is a root-level node, apply extra spacing if we aren't the first node
|
||||
if (!firstNode && depth == 0 && rootNodeSpacing > 0) {
|
||||
out.write((new String(new char[rootNodeSpacing])).replace("\0", "\n")); // yes it's silly, but it works :>
|
||||
if (!firstNode && depth == 0 && this.rootNodeSpacing > 0) {
|
||||
out.write((new String(new char[this.rootNodeSpacing])).replace("\0", "\n")); // yes it's silly, but it works :>
|
||||
}
|
||||
firstNode = false; // we're no longer on the first node
|
||||
|
||||
@ -733,7 +732,7 @@ public class Config extends ConfigSection {
|
||||
if (comment != null) {
|
||||
// add spacing between previous nodes and comments
|
||||
if (depth != 0) {
|
||||
out.write((new String(new char[commentSpacing])).replace("\0", "\n"));
|
||||
out.write((new String(new char[this.commentSpacing])).replace("\0", "\n"));
|
||||
}
|
||||
|
||||
// formatting style for this node
|
||||
@ -742,7 +741,7 @@ public class Config extends ConfigSection {
|
||||
// check to see what type of node this is
|
||||
if (!m.group(3).trim().isEmpty()) {
|
||||
// setting node
|
||||
style = defaultNodeCommentFormat;
|
||||
style = this.defaultNodeCommentFormat;
|
||||
} else {
|
||||
// probably a section? (need to peek ahead to check if this is a list)
|
||||
in.mark(1000);
|
||||
@ -750,9 +749,9 @@ public class Config extends ConfigSection {
|
||||
in.reset();
|
||||
if (nextLine.startsWith("-")) {
|
||||
// not a section :P
|
||||
style = defaultNodeCommentFormat;
|
||||
style = this.defaultNodeCommentFormat;
|
||||
} else {
|
||||
style = defaultSectionCommentFormat;
|
||||
style = this.defaultSectionCommentFormat;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -22,62 +22,62 @@ public class ConfigFileConfigurationAdapter extends FileConfiguration {
|
||||
}
|
||||
|
||||
public Config getCoreConfig() {
|
||||
return config;
|
||||
return this.config;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String saveToString() {
|
||||
return config.saveToString();
|
||||
return this.config.saveToString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void loadFromString(String string) throws InvalidConfigurationException {
|
||||
config.loadFromString(string);
|
||||
this.config.loadFromString(string);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String buildHeader() {
|
||||
return "#" + String.join("\n#", config.getHeader());
|
||||
return "#" + String.join("\n#", this.config.getHeader());
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigOptionsAdapter options() {
|
||||
return new ConfigOptionsAdapter(config);
|
||||
return new ConfigOptionsAdapter(this.config);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<String> getKeys(boolean deep) {
|
||||
return config.getKeys(deep);
|
||||
return this.config.getKeys(deep);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> getValues(boolean deep) {
|
||||
return config.getValues(deep);
|
||||
return this.config.getValues(deep);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean contains(String path) {
|
||||
return config.contains(path);
|
||||
return this.config.contains(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSet(String path) {
|
||||
return config.isSet(path);
|
||||
return this.config.isSet(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getCurrentPath() {
|
||||
return config.getCurrentPath();
|
||||
return this.config.getCurrentPath();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return config.getName();
|
||||
return this.config.getName();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Configuration getRoot() {
|
||||
return config;
|
||||
return this.config;
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -87,186 +87,186 @@ public class ConfigFileConfigurationAdapter extends FileConfiguration {
|
||||
|
||||
@Override
|
||||
public void addDefault(String path, Object value) {
|
||||
config.addDefault(path, value);
|
||||
this.config.addDefault(path, value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigurationSection getDefaultSection() {
|
||||
return config.getDefaultSection();
|
||||
return this.config.getDefaultSection();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void set(String path, Object value) {
|
||||
config.set(path, value);
|
||||
this.config.set(path, value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object get(String path) {
|
||||
return config.get(path);
|
||||
return this.config.get(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object get(String path, Object def) {
|
||||
return config.get(path, def);
|
||||
return this.config.get(path, def);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigurationSection createSection(String path) {
|
||||
return config.createSection(path);
|
||||
return this.config.createSection(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigurationSection createSection(String path, Map<?, ?> map) {
|
||||
return config.createSection(path, map);
|
||||
return this.config.createSection(path, map);
|
||||
}
|
||||
|
||||
// Other non-FileConfiguration methods
|
||||
|
||||
@NotNull
|
||||
public ConfigSection createDefaultSection(@NotNull String path) {
|
||||
return config.createDefaultSection(path);
|
||||
return this.config.createDefaultSection(path);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ConfigSection createDefaultSection(@NotNull String path, String... comment) {
|
||||
return config.createDefaultSection(path, comment);
|
||||
return this.config.createDefaultSection(path, comment);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ConfigSection createDefaultSection(@NotNull String path, ConfigFormattingRules.CommentStyle commentStyle, String... comment) {
|
||||
return config.createDefaultSection(path, commentStyle, comment);
|
||||
return this.config.createDefaultSection(path, commentStyle, comment);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ConfigSection setComment(@NotNull String path, @Nullable ConfigFormattingRules.CommentStyle commentStyle, String... lines) {
|
||||
return config.setComment(path, commentStyle, lines);
|
||||
return this.config.setComment(path, commentStyle, lines);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ConfigSection setComment(@NotNull String path, @Nullable ConfigFormattingRules.CommentStyle commentStyle, @Nullable List<String> lines) {
|
||||
return config.setComment(path, commentStyle, lines);
|
||||
return this.config.setComment(path, commentStyle, lines);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ConfigSection setDefaultComment(@NotNull String path, String... lines) {
|
||||
return config.setDefaultComment(path, lines);
|
||||
return this.config.setDefaultComment(path, lines);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ConfigSection setDefaultComment(@NotNull String path, @Nullable List<String> lines) {
|
||||
return config.setDefaultComment(path, lines);
|
||||
return this.config.setDefaultComment(path, lines);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ConfigSection setDefaultComment(@NotNull String path, ConfigFormattingRules.CommentStyle commentStyle, String... lines) {
|
||||
return config.setDefaultComment(path, commentStyle, lines);
|
||||
return this.config.setDefaultComment(path, commentStyle, lines);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ConfigSection setDefaultComment(@NotNull String path, ConfigFormattingRules.CommentStyle commentStyle, @Nullable List<String> lines) {
|
||||
return config.setDefaultComment(path, commentStyle, lines);
|
||||
return this.config.setDefaultComment(path, commentStyle, lines);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Comment getComment(@NotNull String path) {
|
||||
return config.getComment(path);
|
||||
return this.config.getComment(path);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public String getCommentString(@NotNull String path) {
|
||||
return config.getCommentString(path);
|
||||
return this.config.getCommentString(path);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public List<ConfigSection> getSections(String path) {
|
||||
return config.getSections(path);
|
||||
return this.config.getSections(path);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ConfigSection set(@NotNull String path, @Nullable Object value, String... comment) {
|
||||
return config.set(path, value, comment);
|
||||
return this.config.set(path, value, comment);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ConfigSection set(@NotNull String path, @Nullable Object value, List<String> comment) {
|
||||
return config.set(path, value, comment);
|
||||
return this.config.set(path, value, comment);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ConfigSection set(@NotNull String path, @Nullable Object value, @Nullable ConfigFormattingRules.CommentStyle commentStyle, String... comment) {
|
||||
return config.set(path, value, commentStyle, comment);
|
||||
return this.config.set(path, value, commentStyle, comment);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ConfigSection set(@NotNull String path, @Nullable Object value, @Nullable ConfigFormattingRules.CommentStyle commentStyle, List<String> comment) {
|
||||
return config.set(path, value, commentStyle, comment);
|
||||
return this.config.set(path, value, commentStyle, comment);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ConfigSection setDefault(@NotNull String path, @Nullable Object value) {
|
||||
return config.setDefault(path, value);
|
||||
return this.config.setDefault(path, value);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ConfigSection setDefault(@NotNull String path, @Nullable Object value, String... comment) {
|
||||
return config.setDefault(path, value, comment);
|
||||
return this.config.setDefault(path, value, comment);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ConfigSection setDefault(@NotNull String path, @Nullable Object value, List<String> comment) {
|
||||
return config.setDefault(path, value, comment);
|
||||
return this.config.setDefault(path, value, comment);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ConfigSection setDefault(@NotNull String path, @Nullable Object value, ConfigFormattingRules.CommentStyle commentStyle, String... comment) {
|
||||
return config.setDefault(path, value, commentStyle, comment);
|
||||
return this.config.setDefault(path, value, commentStyle, comment);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ConfigSection setDefault(@NotNull String path, @Nullable Object value, ConfigFormattingRules.CommentStyle commentStyle, List<String> comment) {
|
||||
return config.setDefault(path, value, commentStyle, comment);
|
||||
return this.config.setDefault(path, value, commentStyle, comment);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ConfigSection createSection(@NotNull String path, String... comment) {
|
||||
return config.createSection(path, comment);
|
||||
return this.config.createSection(path, comment);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ConfigSection createSection(@NotNull String path, @Nullable List<String> comment) {
|
||||
return config.createSection(path, comment);
|
||||
return this.config.createSection(path, comment);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ConfigSection createSection(@NotNull String path, @Nullable ConfigFormattingRules.CommentStyle commentStyle, String... comment) {
|
||||
return config.createSection(path, commentStyle, comment);
|
||||
return this.config.createSection(path, commentStyle, comment);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ConfigSection createSection(@NotNull String path, @Nullable ConfigFormattingRules.CommentStyle commentStyle, @Nullable List<String> comment) {
|
||||
return config.createSection(path, commentStyle, comment);
|
||||
return this.config.createSection(path, commentStyle, comment);
|
||||
}
|
||||
|
||||
public char getChar(@NotNull String path) {
|
||||
return config.getChar(path);
|
||||
return this.config.getChar(path);
|
||||
}
|
||||
|
||||
public char getChar(@NotNull String path, char def) {
|
||||
return config.getChar(path, def);
|
||||
return this.config.getChar(path, def);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public XMaterial getMaterial(@NotNull String path) {
|
||||
return config.getMaterial(path);
|
||||
return this.config.getMaterial(path);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public XMaterial getMaterial(@NotNull String path, @Nullable XMaterial def) {
|
||||
return config.getMaterial(path, def);
|
||||
return this.config.getMaterial(path, def);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ConfigSection getOrCreateConfigurationSection(@NotNull String path) {
|
||||
return config.getOrCreateConfigurationSection(path);
|
||||
return this.config.getOrCreateConfigurationSection(path);
|
||||
}
|
||||
}
|
||||
|
@ -32,7 +32,7 @@ public class ConfigFormattingRules {
|
||||
* #|_________|# <br />
|
||||
* ############# <br />
|
||||
*/
|
||||
BLOCKSPACED(true, true, "|\u00AF", '\u00AF', "\u00AF|", "| ", " |", "|_", '_', "_|");
|
||||
BLOCKSPACED(true, true, "|¯", '¯', "¯|", "| ", " |", "|_", '_', "_|");
|
||||
|
||||
final boolean drawBorder, drawSpace;
|
||||
final String commentPrefix, spacePrefixTop, spacePrefixBottom;
|
||||
|
@ -15,13 +15,13 @@ public class ConfigOptionsAdapter extends FileConfigurationOptions {
|
||||
}
|
||||
|
||||
public Config getConfig() {
|
||||
return (Config) config.root;
|
||||
return (Config) this.config.root;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public ConfigFileConfigurationAdapter configuration() {
|
||||
return new ConfigFileConfigurationAdapter((Config) config.root);
|
||||
return new ConfigFileConfigurationAdapter((Config) this.config.root);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@ -34,7 +34,7 @@ public class ConfigOptionsAdapter extends FileConfigurationOptions {
|
||||
@NotNull
|
||||
@Override
|
||||
public ConfigOptionsAdapter pathSeparator(char value) {
|
||||
(config.root).setPathSeparator(value);
|
||||
(this.config.root).setPathSeparator(value);
|
||||
return this;
|
||||
}
|
||||
|
||||
@ -42,9 +42,9 @@ public class ConfigOptionsAdapter extends FileConfigurationOptions {
|
||||
@Override
|
||||
public ConfigOptionsAdapter header(@Nullable String value) {
|
||||
if (value == null) {
|
||||
((Config) config.root).setHeader((List) null);
|
||||
((Config) this.config.root).setHeader((List<String>) null);
|
||||
} else {
|
||||
((Config) config.root).setHeader(value.split("\n"));
|
||||
((Config) this.config.root).setHeader(value.split("\n"));
|
||||
}
|
||||
|
||||
return this;
|
||||
@ -54,19 +54,19 @@ public class ConfigOptionsAdapter extends FileConfigurationOptions {
|
||||
@Override
|
||||
public ConfigOptionsAdapter copyHeader(boolean value) {
|
||||
if (!value) {
|
||||
((Config) config.root).setHeader((List) null);
|
||||
((Config) this.config.root).setHeader((List<String>) null);
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public int indent() {
|
||||
return config.root.getIndent();
|
||||
return this.config.root.getIndent();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ConfigOptionsAdapter indent(int value) {
|
||||
config.root.setIndent(value);
|
||||
this.config.root.setIndent(value);
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
@ -42,13 +42,13 @@ public class ConfigSection extends MemoryConfiguration {
|
||||
ConfigSection() {
|
||||
this.root = this;
|
||||
this.parent = null;
|
||||
isDefault = false;
|
||||
nodeKey = fullPath = "";
|
||||
this.isDefault = false;
|
||||
this.nodeKey = this.fullPath = "";
|
||||
|
||||
configComments = new HashMap<>();
|
||||
defaultComments = new HashMap<>();
|
||||
defaults = new LinkedHashMap<>();
|
||||
values = new LinkedHashMap<>();
|
||||
this.configComments = new HashMap<>();
|
||||
this.defaultComments = new HashMap<>();
|
||||
this.defaults = new LinkedHashMap<>();
|
||||
this.values = new LinkedHashMap<>();
|
||||
}
|
||||
|
||||
ConfigSection(ConfigSection root, ConfigSection parent, String nodeKey, boolean isDefault) {
|
||||
@ -57,22 +57,22 @@ public class ConfigSection extends MemoryConfiguration {
|
||||
this.nodeKey = nodeKey;
|
||||
this.fullPath = nodeKey != null ? parent.fullPath + nodeKey + root.pathChar : parent.fullPath;
|
||||
this.isDefault = isDefault;
|
||||
configComments = defaultComments = null;
|
||||
defaults = null;
|
||||
values = null;
|
||||
this.configComments = this.defaultComments = null;
|
||||
this.defaults = null;
|
||||
this.values = null;
|
||||
}
|
||||
|
||||
public int getIndent() {
|
||||
return root.indentation;
|
||||
return this.root.indentation;
|
||||
}
|
||||
|
||||
public void setIndent(int indentation) {
|
||||
root.indentation = indentation;
|
||||
this.root.indentation = indentation;
|
||||
}
|
||||
|
||||
protected void onChange() {
|
||||
if (parent != null) {
|
||||
root.onChange();
|
||||
if (this.parent != null) {
|
||||
this.root.onChange();
|
||||
}
|
||||
}
|
||||
|
||||
@ -83,29 +83,29 @@ public class ConfigSection extends MemoryConfiguration {
|
||||
* @param pathChar character to use
|
||||
*/
|
||||
public void setPathSeparator(char pathChar) {
|
||||
if (!root.values.isEmpty() || !root.defaults.isEmpty()) {
|
||||
if (!this.root.values.isEmpty() || !this.root.defaults.isEmpty()) {
|
||||
throw new RuntimeException("Path change after config initialization");
|
||||
}
|
||||
|
||||
root.pathChar = pathChar;
|
||||
this.root.pathChar = pathChar;
|
||||
}
|
||||
|
||||
public char getPathSeparator() {
|
||||
return root.pathChar;
|
||||
return this.root.pathChar;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return The full key for this section node
|
||||
*/
|
||||
public String getKey() {
|
||||
return !fullPath.endsWith(String.valueOf(root.pathChar)) ? fullPath : fullPath.substring(0, fullPath.length() - 1);
|
||||
return !this.fullPath.endsWith(String.valueOf(this.root.pathChar)) ? this.fullPath : this.fullPath.substring(0, this.fullPath.length() - 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return The specific key that was used from the last node to get to this node
|
||||
*/
|
||||
public String getNodeKey() {
|
||||
return nodeKey;
|
||||
return this.nodeKey;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -116,19 +116,19 @@ public class ConfigSection extends MemoryConfiguration {
|
||||
* @param useDefault set to true if this is a default value
|
||||
*/
|
||||
protected void createNodePath(@NotNull String path, boolean useDefault) {
|
||||
if (path.indexOf(root.pathChar) != -1) {
|
||||
if (path.indexOf(this.root.pathChar) != -1) {
|
||||
// if any intermediate nodes don't exist, create them
|
||||
String[] pathParts = path.split(Pattern.quote(String.valueOf(root.pathChar)));
|
||||
StringBuilder nodePath = new StringBuilder(fullPath);
|
||||
LinkedHashMap<String, Object> writeTo = useDefault ? root.defaults : root.values;
|
||||
String[] pathParts = path.split(Pattern.quote(String.valueOf(this.root.pathChar)));
|
||||
StringBuilder nodePath = new StringBuilder(this.fullPath);
|
||||
LinkedHashMap<String, Object> writeTo = useDefault ? this.root.defaults : this.root.values;
|
||||
ConfigSection travelNode = this;
|
||||
|
||||
synchronized (root.lock) {
|
||||
synchronized (this.root.lock) {
|
||||
for (int i = 0; i < pathParts.length - 1; ++i) {
|
||||
final String node = (i != 0 ? nodePath.append(root.pathChar) : nodePath).append(pathParts[i]).toString();
|
||||
final String node = (i != 0 ? nodePath.append(this.root.pathChar) : nodePath).append(pathParts[i]).toString();
|
||||
|
||||
if (!(writeTo.get(node) instanceof ConfigSection)) {
|
||||
writeTo.put(node, travelNode = new ConfigSection(root, travelNode, pathParts[i], useDefault));
|
||||
writeTo.put(node, travelNode = new ConfigSection(this.root, travelNode, pathParts[i], useDefault));
|
||||
} else {
|
||||
travelNode = (ConfigSection) writeTo.get(node);
|
||||
}
|
||||
@ -140,10 +140,10 @@ public class ConfigSection extends MemoryConfiguration {
|
||||
@NotNull
|
||||
public ConfigSection createDefaultSection(@NotNull String path) {
|
||||
createNodePath(path, true);
|
||||
ConfigSection section = new ConfigSection(root, this, path, true);
|
||||
ConfigSection section = new ConfigSection(this.root, this, path, true);
|
||||
|
||||
synchronized (root.lock) {
|
||||
root.defaults.put(fullPath + path, section);
|
||||
synchronized (this.root.lock) {
|
||||
this.root.defaults.put(this.fullPath + path, section);
|
||||
}
|
||||
|
||||
return section;
|
||||
@ -152,11 +152,11 @@ public class ConfigSection extends MemoryConfiguration {
|
||||
@NotNull
|
||||
public ConfigSection createDefaultSection(@NotNull String path, String... comment) {
|
||||
createNodePath(path, true);
|
||||
ConfigSection section = new ConfigSection(root, this, path, true);
|
||||
ConfigSection section = new ConfigSection(this.root, this, path, true);
|
||||
|
||||
synchronized (root.lock) {
|
||||
root.defaults.put(fullPath + path, section);
|
||||
root.defaultComments.put(fullPath + path, new Comment(comment));
|
||||
synchronized (this.root.lock) {
|
||||
this.root.defaults.put(this.fullPath + path, section);
|
||||
this.root.defaultComments.put(this.fullPath + path, new Comment(comment));
|
||||
}
|
||||
|
||||
return section;
|
||||
@ -165,11 +165,11 @@ public class ConfigSection extends MemoryConfiguration {
|
||||
@NotNull
|
||||
public ConfigSection createDefaultSection(@NotNull String path, ConfigFormattingRules.CommentStyle commentStyle, String... comment) {
|
||||
createNodePath(path, true);
|
||||
ConfigSection section = new ConfigSection(root, this, path, true);
|
||||
ConfigSection section = new ConfigSection(this.root, this, path, true);
|
||||
|
||||
synchronized (root.lock) {
|
||||
root.defaults.put(fullPath + path, section);
|
||||
root.defaultComments.put(fullPath + path, new Comment(commentStyle, comment));
|
||||
synchronized (this.root.lock) {
|
||||
this.root.defaults.put(this.fullPath + path, section);
|
||||
this.root.defaultComments.put(this.fullPath + path, new Comment(commentStyle, comment));
|
||||
}
|
||||
|
||||
return section;
|
||||
@ -187,11 +187,11 @@ public class ConfigSection extends MemoryConfiguration {
|
||||
|
||||
@NotNull
|
||||
public ConfigSection setComment(@NotNull String path, @Nullable Comment comment) {
|
||||
synchronized (root.lock) {
|
||||
if (isDefault) {
|
||||
root.defaultComments.put(fullPath + path, comment);
|
||||
synchronized (this.root.lock) {
|
||||
if (this.isDefault) {
|
||||
this.root.defaultComments.put(this.fullPath + path, comment);
|
||||
} else {
|
||||
root.configComments.put(fullPath + path, comment);
|
||||
this.root.configComments.put(this.fullPath + path, comment);
|
||||
}
|
||||
}
|
||||
|
||||
@ -205,8 +205,8 @@ public class ConfigSection extends MemoryConfiguration {
|
||||
|
||||
@NotNull
|
||||
public ConfigSection setDefaultComment(@NotNull String path, @Nullable List<String> lines) {
|
||||
synchronized (root.lock) {
|
||||
root.defaultComments.put(fullPath + path, new Comment(lines));
|
||||
synchronized (this.root.lock) {
|
||||
this.root.defaultComments.put(this.fullPath + path, new Comment(lines));
|
||||
}
|
||||
|
||||
return this;
|
||||
@ -219,8 +219,8 @@ public class ConfigSection extends MemoryConfiguration {
|
||||
|
||||
@NotNull
|
||||
public ConfigSection setDefaultComment(@NotNull String path, ConfigFormattingRules.CommentStyle commentStyle, @Nullable List<String> lines) {
|
||||
synchronized (root.lock) {
|
||||
root.defaultComments.put(fullPath + path, new Comment(commentStyle, lines));
|
||||
synchronized (this.root.lock) {
|
||||
this.root.defaultComments.put(this.fullPath + path, new Comment(commentStyle, lines));
|
||||
}
|
||||
|
||||
return this;
|
||||
@ -228,8 +228,8 @@ public class ConfigSection extends MemoryConfiguration {
|
||||
|
||||
@NotNull
|
||||
public ConfigSection setDefaultComment(@NotNull String path, @Nullable Comment comment) {
|
||||
synchronized (root.lock) {
|
||||
root.defaultComments.put(fullPath + path, comment);
|
||||
synchronized (this.root.lock) {
|
||||
this.root.defaultComments.put(this.fullPath + path, comment);
|
||||
}
|
||||
|
||||
return this;
|
||||
@ -237,10 +237,10 @@ public class ConfigSection extends MemoryConfiguration {
|
||||
|
||||
@Nullable
|
||||
public Comment getComment(@NotNull String path) {
|
||||
Comment result = root.configComments.get(fullPath + path);
|
||||
Comment result = this.root.configComments.get(this.fullPath + path);
|
||||
|
||||
if (result == null) {
|
||||
result = root.defaultComments.get(fullPath + path);
|
||||
result = this.root.defaultComments.get(this.fullPath + path);
|
||||
}
|
||||
|
||||
return result;
|
||||
@ -248,10 +248,10 @@ public class ConfigSection extends MemoryConfiguration {
|
||||
|
||||
@Nullable
|
||||
public String getCommentString(@NotNull String path) {
|
||||
Comment result = root.configComments.get(fullPath + path);
|
||||
Comment result = this.root.configComments.get(this.fullPath + path);
|
||||
|
||||
if (result == null) {
|
||||
result = root.defaultComments.get(fullPath + path);
|
||||
result = this.root.defaultComments.get(this.fullPath + path);
|
||||
}
|
||||
|
||||
return result != null ? result.toString() : null;
|
||||
@ -261,8 +261,8 @@ public class ConfigSection extends MemoryConfiguration {
|
||||
public void addDefault(@NotNull String path, @Nullable Object value) {
|
||||
createNodePath(path, true);
|
||||
|
||||
synchronized (root.lock) {
|
||||
root.defaults.put(fullPath + path, value);
|
||||
synchronized (this.root.lock) {
|
||||
this.root.defaults.put(this.fullPath + path, value);
|
||||
}
|
||||
}
|
||||
|
||||
@ -273,56 +273,56 @@ public class ConfigSection extends MemoryConfiguration {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setDefaults(Configuration c) {
|
||||
if (fullPath.isEmpty()) {
|
||||
root.defaults.clear();
|
||||
public void setDefaults(Configuration cfg) {
|
||||
if (this.fullPath.isEmpty()) {
|
||||
this.root.defaults.clear();
|
||||
} else {
|
||||
root.defaults.keySet().stream()
|
||||
.filter(k -> k.startsWith(fullPath))
|
||||
.forEach(root.defaults::remove);
|
||||
this.root.defaults.keySet().stream()
|
||||
.filter(k -> k.startsWith(this.fullPath))
|
||||
.forEach(this.root.defaults::remove);
|
||||
}
|
||||
|
||||
addDefaults(c);
|
||||
addDefaults(cfg);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigSection getDefaults() {
|
||||
return new ConfigSection(root, this, null, true);
|
||||
return new ConfigSection(this.root, this, null, true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigSection getDefaultSection() {
|
||||
return new ConfigSection(root, this, null, true);
|
||||
return new ConfigSection(this.root, this, null, true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigOptionsAdapter options() {
|
||||
return new ConfigOptionsAdapter(root);
|
||||
return new ConfigOptionsAdapter(this.root);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public Set<String> getKeys(boolean deep) {
|
||||
LinkedHashSet<String> result = new LinkedHashSet<>();
|
||||
int pathIndex = fullPath.lastIndexOf(root.pathChar);
|
||||
int pathIndex = this.fullPath.lastIndexOf(this.root.pathChar);
|
||||
|
||||
if (deep) {
|
||||
result.addAll(root.defaults.keySet().stream()
|
||||
.filter(k -> k.startsWith(fullPath))
|
||||
.map(k -> !k.endsWith(String.valueOf(root.pathChar)) ? k.substring(pathIndex + 1) : k.substring(pathIndex + 1, k.length() - 1))
|
||||
result.addAll(this.root.defaults.keySet().stream()
|
||||
.filter(k -> k.startsWith(this.fullPath))
|
||||
.map(k -> !k.endsWith(String.valueOf(this.root.pathChar)) ? k.substring(pathIndex + 1) : k.substring(pathIndex + 1, k.length() - 1))
|
||||
.collect(Collectors.toCollection(LinkedHashSet::new)));
|
||||
result.addAll(root.values.keySet().stream()
|
||||
.filter(k -> k.startsWith(fullPath))
|
||||
.map(k -> !k.endsWith(String.valueOf(root.pathChar)) ? k.substring(pathIndex + 1) : k.substring(pathIndex + 1, k.length() - 1))
|
||||
result.addAll(this.root.values.keySet().stream()
|
||||
.filter(k -> k.startsWith(this.fullPath))
|
||||
.map(k -> !k.endsWith(String.valueOf(this.root.pathChar)) ? k.substring(pathIndex + 1) : k.substring(pathIndex + 1, k.length() - 1))
|
||||
.collect(Collectors.toCollection(LinkedHashSet::new)));
|
||||
} else {
|
||||
result.addAll(root.defaults.keySet().stream()
|
||||
.filter(k -> k.startsWith(fullPath) && k.lastIndexOf(root.pathChar) == pathIndex)
|
||||
.map(k -> !k.endsWith(String.valueOf(root.pathChar)) ? k.substring(pathIndex + 1) : k.substring(pathIndex + 1, k.length() - 1))
|
||||
result.addAll(this.root.defaults.keySet().stream()
|
||||
.filter(k -> k.startsWith(this.fullPath) && k.lastIndexOf(this.root.pathChar) == pathIndex)
|
||||
.map(k -> !k.endsWith(String.valueOf(this.root.pathChar)) ? k.substring(pathIndex + 1) : k.substring(pathIndex + 1, k.length() - 1))
|
||||
.collect(Collectors.toCollection(LinkedHashSet::new)));
|
||||
result.addAll(root.values.keySet().stream()
|
||||
.filter(k -> k.startsWith(fullPath) && k.lastIndexOf(root.pathChar) == pathIndex)
|
||||
.map(k -> !k.endsWith(String.valueOf(root.pathChar)) ? k.substring(pathIndex + 1) : k.substring(pathIndex + 1, k.length() - 1))
|
||||
result.addAll(this.root.values.keySet().stream()
|
||||
.filter(k -> k.startsWith(this.fullPath) && k.lastIndexOf(this.root.pathChar) == pathIndex)
|
||||
.map(k -> !k.endsWith(String.valueOf(this.root.pathChar)) ? k.substring(pathIndex + 1) : k.substring(pathIndex + 1, k.length() - 1))
|
||||
.collect(Collectors.toCollection(LinkedHashSet::new)));
|
||||
}
|
||||
|
||||
@ -333,43 +333,43 @@ public class ConfigSection extends MemoryConfiguration {
|
||||
@Override
|
||||
public Map<String, Object> getValues(boolean deep) {
|
||||
LinkedHashMap<String, Object> result = new LinkedHashMap<>();
|
||||
int pathIndex = fullPath.lastIndexOf(root.pathChar);
|
||||
int pathIndex = this.fullPath.lastIndexOf(this.root.pathChar);
|
||||
|
||||
if (deep) {
|
||||
result.putAll((Map<String, Object>) root.defaults.entrySet().stream()
|
||||
.filter(k -> k.getKey().startsWith(fullPath))
|
||||
result.putAll((Map<String, Object>) this.root.defaults.entrySet().stream()
|
||||
.filter(k -> k.getKey().startsWith(this.fullPath))
|
||||
.collect(Collectors.toMap(
|
||||
e -> !e.getKey().endsWith(String.valueOf(root.pathChar)) ? e.getKey().substring(pathIndex + 1) : e.getKey().substring(pathIndex + 1, e.getKey().length() - 1),
|
||||
e -> !e.getKey().endsWith(String.valueOf(this.root.pathChar)) ? e.getKey().substring(pathIndex + 1) : e.getKey().substring(pathIndex + 1, e.getKey().length() - 1),
|
||||
Map.Entry::getValue,
|
||||
(v1, v2) -> {
|
||||
throw new IllegalStateException();
|
||||
}, // never going to be merging keys
|
||||
LinkedHashMap::new)));
|
||||
|
||||
result.putAll((Map<String, Object>) root.values.entrySet().stream()
|
||||
.filter(k -> k.getKey().startsWith(fullPath))
|
||||
result.putAll((Map<String, Object>) this.root.values.entrySet().stream()
|
||||
.filter(k -> k.getKey().startsWith(this.fullPath))
|
||||
.collect(Collectors.toMap(
|
||||
e -> !e.getKey().endsWith(String.valueOf(root.pathChar)) ? e.getKey().substring(pathIndex + 1) : e.getKey().substring(pathIndex + 1, e.getKey().length() - 1),
|
||||
e -> !e.getKey().endsWith(String.valueOf(this.root.pathChar)) ? e.getKey().substring(pathIndex + 1) : e.getKey().substring(pathIndex + 1, e.getKey().length() - 1),
|
||||
Map.Entry::getValue,
|
||||
(v1, v2) -> {
|
||||
throw new IllegalStateException();
|
||||
}, // never going to be merging keys
|
||||
LinkedHashMap::new)));
|
||||
} else {
|
||||
result.putAll((Map<String, Object>) root.defaults.entrySet().stream()
|
||||
.filter(k -> k.getKey().startsWith(fullPath) && k.getKey().lastIndexOf(root.pathChar) == pathIndex)
|
||||
result.putAll((Map<String, Object>) this.root.defaults.entrySet().stream()
|
||||
.filter(k -> k.getKey().startsWith(this.fullPath) && k.getKey().lastIndexOf(this.root.pathChar) == pathIndex)
|
||||
.collect(Collectors.toMap(
|
||||
e -> !e.getKey().endsWith(String.valueOf(root.pathChar)) ? e.getKey().substring(pathIndex + 1) : e.getKey().substring(pathIndex + 1, e.getKey().length() - 1),
|
||||
e -> !e.getKey().endsWith(String.valueOf(this.root.pathChar)) ? e.getKey().substring(pathIndex + 1) : e.getKey().substring(pathIndex + 1, e.getKey().length() - 1),
|
||||
Map.Entry::getValue,
|
||||
(v1, v2) -> {
|
||||
throw new IllegalStateException();
|
||||
}, // never going to be merging keys
|
||||
LinkedHashMap::new)));
|
||||
|
||||
result.putAll((Map<String, Object>) root.values.entrySet().stream()
|
||||
.filter(k -> k.getKey().startsWith(fullPath) && k.getKey().lastIndexOf(root.pathChar) == pathIndex)
|
||||
result.putAll((Map<String, Object>) this.root.values.entrySet().stream()
|
||||
.filter(k -> k.getKey().startsWith(this.fullPath) && k.getKey().lastIndexOf(this.root.pathChar) == pathIndex)
|
||||
.collect(Collectors.toMap(
|
||||
e -> !e.getKey().endsWith(String.valueOf(root.pathChar)) ? e.getKey().substring(pathIndex + 1) : e.getKey().substring(pathIndex + 1, e.getKey().length() - 1),
|
||||
e -> !e.getKey().endsWith(String.valueOf(this.root.pathChar)) ? e.getKey().substring(pathIndex + 1) : e.getKey().substring(pathIndex + 1, e.getKey().length() - 1),
|
||||
Map.Entry::getValue,
|
||||
(v1, v2) -> {
|
||||
throw new IllegalStateException();
|
||||
@ -399,51 +399,51 @@ public class ConfigSection extends MemoryConfiguration {
|
||||
|
||||
@Override
|
||||
public boolean contains(@NotNull String path) {
|
||||
return root.defaults.containsKey(fullPath + path) || root.values.containsKey(fullPath + path);
|
||||
return this.root.defaults.containsKey(this.fullPath + path) || this.root.values.containsKey(this.fullPath + path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean contains(@NotNull String path, boolean ignoreDefault) {
|
||||
return (!ignoreDefault && root.defaults.containsKey(fullPath + path)) || root.values.containsKey(fullPath + path);
|
||||
return (!ignoreDefault && this.root.defaults.containsKey(this.fullPath + path)) || this.root.values.containsKey(this.fullPath + path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSet(@NotNull String path) {
|
||||
return root.defaults.get(fullPath + path) != null || root.values.get(fullPath + path) != null;
|
||||
return this.root.defaults.get(this.fullPath + path) != null || this.root.values.get(this.fullPath + path) != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getCurrentPath() {
|
||||
return fullPath.isEmpty() ? "" : fullPath.substring(0, fullPath.length() - 1);
|
||||
return this.fullPath.isEmpty() ? "" : this.fullPath.substring(0, this.fullPath.length() - 1);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
if (fullPath.isEmpty()) {
|
||||
if (this.fullPath.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
|
||||
String[] parts = fullPath.split(Pattern.quote(String.valueOf(root.pathChar)));
|
||||
String[] parts = this.fullPath.split(Pattern.quote(String.valueOf(this.root.pathChar)));
|
||||
return parts[parts.length - 1];
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigSection getRoot() {
|
||||
return root;
|
||||
return this.root;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigSection getParent() {
|
||||
return parent;
|
||||
return this.parent;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public Object get(@NotNull String path) {
|
||||
Object result = root.values.get(fullPath + path);
|
||||
Object result = this.root.values.get(this.fullPath + path);
|
||||
|
||||
if (result == null) {
|
||||
result = root.defaults.get(fullPath + path);
|
||||
result = this.root.defaults.get(this.fullPath + path);
|
||||
}
|
||||
|
||||
return result;
|
||||
@ -452,36 +452,36 @@ public class ConfigSection extends MemoryConfiguration {
|
||||
@Nullable
|
||||
@Override
|
||||
public Object get(@NotNull String path, @Nullable Object def) {
|
||||
Object result = root.values.get(fullPath + path);
|
||||
Object result = this.root.values.get(this.fullPath + path);
|
||||
|
||||
return result != null ? result : def;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void set(@NotNull String path, @Nullable Object value) {
|
||||
if (isDefault) {
|
||||
if (this.isDefault) {
|
||||
addDefault(path, value);
|
||||
return;
|
||||
}
|
||||
|
||||
createNodePath(path, false);
|
||||
Object last;
|
||||
synchronized (root.lock) {
|
||||
synchronized (this.root.lock) {
|
||||
if (value != null) {
|
||||
root.changed |= (last = root.values.put(fullPath + path, value)) != value;
|
||||
this.root.changed |= (last = this.root.values.put(this.fullPath + path, value)) != value;
|
||||
} else {
|
||||
root.changed |= (last = root.values.remove(fullPath + path)) != null;
|
||||
this.root.changed |= (last = this.root.values.remove(this.fullPath + path)) != null;
|
||||
}
|
||||
}
|
||||
|
||||
if (last != value && last instanceof ConfigSection) {
|
||||
// clean up orphaned nodes
|
||||
final String trim = fullPath + path + root.pathChar;
|
||||
synchronized (root.lock) {
|
||||
root.values.keySet().stream()
|
||||
final String trim = this.fullPath + path + this.root.pathChar;
|
||||
synchronized (this.root.lock) {
|
||||
this.root.values.keySet().stream()
|
||||
.filter(k -> k.startsWith(trim))
|
||||
.collect(Collectors.toSet())
|
||||
.forEach(root.values::remove);
|
||||
.forEach(this.root.values::remove);
|
||||
}
|
||||
}
|
||||
|
||||
@ -546,13 +546,13 @@ public class ConfigSection extends MemoryConfiguration {
|
||||
@Override
|
||||
public ConfigSection createSection(@NotNull String path) {
|
||||
createNodePath(path, false);
|
||||
ConfigSection section = new ConfigSection(root, this, path, false);
|
||||
ConfigSection section = new ConfigSection(this.root, this, path, false);
|
||||
|
||||
synchronized (root.lock) {
|
||||
root.values.put(fullPath + path, section);
|
||||
synchronized (this.root.lock) {
|
||||
this.root.values.put(this.fullPath + path, section);
|
||||
}
|
||||
|
||||
root.changed = true;
|
||||
this.root.changed = true;
|
||||
onChange();
|
||||
|
||||
return section;
|
||||
@ -576,14 +576,14 @@ public class ConfigSection extends MemoryConfiguration {
|
||||
@NotNull
|
||||
public ConfigSection createSection(@NotNull String path, @Nullable ConfigFormattingRules.CommentStyle commentStyle, @Nullable List<String> comment) {
|
||||
createNodePath(path, false);
|
||||
ConfigSection section = new ConfigSection(root, this, path, false);
|
||||
ConfigSection section = new ConfigSection(this.root, this, path, false);
|
||||
|
||||
synchronized (root.lock) {
|
||||
root.values.put(fullPath + path, section);
|
||||
synchronized (this.root.lock) {
|
||||
this.root.values.put(this.fullPath + path, section);
|
||||
}
|
||||
|
||||
setComment(path, commentStyle, comment);
|
||||
root.changed = true;
|
||||
this.root.changed = true;
|
||||
onChange();
|
||||
|
||||
return section;
|
||||
@ -593,10 +593,10 @@ public class ConfigSection extends MemoryConfiguration {
|
||||
@Override
|
||||
public ConfigSection createSection(@NotNull String path, Map<?, ?> map) {
|
||||
createNodePath(path, false);
|
||||
ConfigSection section = new ConfigSection(root, this, path, false);
|
||||
ConfigSection section = new ConfigSection(this.root, this, path, false);
|
||||
|
||||
synchronized (root.lock) {
|
||||
root.values.put(fullPath + path, section);
|
||||
synchronized (this.root.lock) {
|
||||
this.root.values.put(this.fullPath + path, section);
|
||||
}
|
||||
|
||||
for (Map.Entry<?, ?> entry : map.entrySet()) {
|
||||
@ -608,7 +608,7 @@ public class ConfigSection extends MemoryConfiguration {
|
||||
section.set(entry.getKey().toString(), entry.getValue());
|
||||
}
|
||||
|
||||
root.changed = true;
|
||||
this.root.changed = true;
|
||||
onChange();
|
||||
|
||||
return section;
|
||||
|
@ -35,88 +35,88 @@ public class ConfigSetting {
|
||||
|
||||
@NotNull
|
||||
public String getKey() {
|
||||
return key;
|
||||
return this.key;
|
||||
}
|
||||
|
||||
public List<Integer> getIntegerList() {
|
||||
return config.getIntegerList(key);
|
||||
return this.config.getIntegerList(this.key);
|
||||
}
|
||||
|
||||
public List<String> getStringList() {
|
||||
return config.getStringList(key);
|
||||
return this.config.getStringList(this.key);
|
||||
}
|
||||
|
||||
public boolean getBoolean() {
|
||||
return config.getBoolean(key);
|
||||
return this.config.getBoolean(this.key);
|
||||
}
|
||||
|
||||
public boolean getBoolean(boolean def) {
|
||||
return config.getBoolean(key, def);
|
||||
return this.config.getBoolean(this.key, def);
|
||||
}
|
||||
|
||||
public int getInt() {
|
||||
return config.getInt(key);
|
||||
return this.config.getInt(this.key);
|
||||
}
|
||||
|
||||
public int getInt(int def) {
|
||||
return config.getInt(key, def);
|
||||
return this.config.getInt(this.key, def);
|
||||
}
|
||||
|
||||
public long getLong() {
|
||||
return config.getLong(key);
|
||||
return this.config.getLong(this.key);
|
||||
}
|
||||
|
||||
public long getLong(long def) {
|
||||
return config.getLong(key, def);
|
||||
return this.config.getLong(this.key, def);
|
||||
}
|
||||
|
||||
public double getDouble() {
|
||||
return config.getDouble(key);
|
||||
return this.config.getDouble(this.key);
|
||||
}
|
||||
|
||||
public double getDouble(double def) {
|
||||
return config.getDouble(key, def);
|
||||
return this.config.getDouble(this.key, def);
|
||||
}
|
||||
|
||||
public String getString() {
|
||||
return config.getString(key);
|
||||
return this.config.getString(this.key);
|
||||
}
|
||||
|
||||
public String getString(String def) {
|
||||
return config.getString(key, def);
|
||||
return this.config.getString(this.key, def);
|
||||
}
|
||||
|
||||
public Object getObject() {
|
||||
return config.get(key);
|
||||
return this.config.get(this.key);
|
||||
}
|
||||
|
||||
public Object getObject(Object def) {
|
||||
return config.get(key, def);
|
||||
return this.config.get(this.key, def);
|
||||
}
|
||||
|
||||
public <T> T getObject(@NotNull Class<T> clazz) {
|
||||
return config.getObject(key, clazz);
|
||||
return this.config.getObject(this.key, clazz);
|
||||
}
|
||||
|
||||
public <T> T getObject(@NotNull Class<T> clazz, @Nullable T def) {
|
||||
return config.getObject(key, clazz, def);
|
||||
return this.config.getObject(this.key, clazz, def);
|
||||
}
|
||||
|
||||
public char getChar() {
|
||||
return config.getChar(key);
|
||||
return this.config.getChar(this.key);
|
||||
}
|
||||
|
||||
public char getChar(char def) {
|
||||
return config.getChar(key, def);
|
||||
return this.config.getChar(this.key, def);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public XMaterial getMaterial() {
|
||||
String val = config.getString(key);
|
||||
Optional<XMaterial> mat = CompatibleMaterial.getMaterial(config.getString(key));
|
||||
String val = this.config.getString(this.key);
|
||||
Optional<XMaterial> mat = CompatibleMaterial.getMaterial(this.config.getString(this.key));
|
||||
|
||||
if (!mat.isPresent()) {
|
||||
SongodaCore.getLogger().log(Level.WARNING, String.format("Config value \"%s\" has an invalid material name: \"%s\"", key, val));
|
||||
SongodaCore.getLogger().log(Level.WARNING, String.format("Config value \"%s\" has an invalid material name: \"%s\"", this.key, val));
|
||||
}
|
||||
return mat.orElse(XMaterial.STONE);
|
||||
}
|
||||
@ -124,11 +124,11 @@ public class ConfigSetting {
|
||||
@NotNull
|
||||
public XMaterial getMaterial(@NotNull XMaterial def) {
|
||||
//return config.getMaterial(key, def);
|
||||
String val = config.getString(key);
|
||||
String val = this.config.getString(this.key);
|
||||
Optional<XMaterial> mat = val != null ? CompatibleMaterial.getMaterial(val) : Optional.empty();
|
||||
|
||||
if (!mat.isPresent()) {
|
||||
SongodaCore.getLogger().log(Level.WARNING, String.format("Config value \"%s\" has an invalid material name: \"%s\"", key, val));
|
||||
SongodaCore.getLogger().log(Level.WARNING, String.format("Config value \"%s\" has an invalid material name: \"%s\"", this.key, val));
|
||||
}
|
||||
return mat.orElse(def);
|
||||
}
|
||||
|
@ -39,7 +39,7 @@ public class SimpleDataStore<T extends DataStoreObject> {
|
||||
public SimpleDataStore(@NotNull Plugin plugin, @NotNull String filename, @NotNull Function<ConfigurationSection, T> loadFunction) {
|
||||
this.plugin = plugin;
|
||||
this.filename = filename;
|
||||
dirName = null;
|
||||
this.dirName = null;
|
||||
this.getFromSection = loadFunction;
|
||||
}
|
||||
|
||||
@ -52,23 +52,22 @@ public class SimpleDataStore<T extends DataStoreObject> {
|
||||
|
||||
@NotNull
|
||||
public File getFile() {
|
||||
if (file == null) {
|
||||
if (dirName != null) {
|
||||
this.file = new File(plugin.getDataFolder() + dirName, filename != null ? filename : "data.yml");
|
||||
if (this.file == null) {
|
||||
if (this.dirName != null) {
|
||||
this.file = new File(this.plugin.getDataFolder() + this.dirName, this.filename != null ? this.filename : "data.yml");
|
||||
} else {
|
||||
this.file = new File(plugin.getDataFolder(), filename != null ? filename : "data.yml");
|
||||
this.file = new File(this.plugin.getDataFolder(), this.filename != null ? this.filename : "data.yml");
|
||||
}
|
||||
}
|
||||
|
||||
return file;
|
||||
return this.file;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return a directly-modifiable instance of the data mapping for this
|
||||
* storage
|
||||
* @return a directly modifiable instance of the data mapping for this storage
|
||||
*/
|
||||
public Map<Object, T> getData() {
|
||||
return data;
|
||||
return this.data;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -82,7 +81,7 @@ public class SimpleDataStore<T extends DataStoreObject> {
|
||||
*/
|
||||
@Nullable
|
||||
public T get(Object key) {
|
||||
return data.get(key);
|
||||
return this.data.get(key);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -97,8 +96,8 @@ public class SimpleDataStore<T extends DataStoreObject> {
|
||||
public T remove(@NotNull Object key) {
|
||||
T temp;
|
||||
|
||||
synchronized (lock) {
|
||||
temp = data.remove(key);
|
||||
synchronized (this.lock) {
|
||||
temp = this.data.remove(key);
|
||||
}
|
||||
|
||||
save();
|
||||
@ -122,8 +121,8 @@ public class SimpleDataStore<T extends DataStoreObject> {
|
||||
|
||||
T temp;
|
||||
|
||||
synchronized (lock) {
|
||||
temp = data.remove(value.getKey());
|
||||
synchronized (this.lock) {
|
||||
temp = this.data.remove(value.getKey());
|
||||
}
|
||||
|
||||
save();
|
||||
@ -148,8 +147,8 @@ public class SimpleDataStore<T extends DataStoreObject> {
|
||||
|
||||
T temp;
|
||||
|
||||
synchronized (lock) {
|
||||
temp = data.put(value.getKey(), value);
|
||||
synchronized (this.lock) {
|
||||
temp = this.data.put(value.getKey(), value);
|
||||
}
|
||||
|
||||
save();
|
||||
@ -168,10 +167,10 @@ public class SimpleDataStore<T extends DataStoreObject> {
|
||||
return;
|
||||
}
|
||||
|
||||
synchronized (lock) {
|
||||
synchronized (this.lock) {
|
||||
for (T t : value) {
|
||||
if (t != null) {
|
||||
data.put(t.getKey(), t);
|
||||
this.data.put(t.getKey(), t);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -191,10 +190,10 @@ public class SimpleDataStore<T extends DataStoreObject> {
|
||||
return;
|
||||
}
|
||||
|
||||
synchronized (lock) {
|
||||
synchronized (this.lock) {
|
||||
for (T v : value) {
|
||||
if (v != null) {
|
||||
data.put(v.getKey(), v);
|
||||
this.data.put(v.getKey(), v);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -213,27 +212,27 @@ public class SimpleDataStore<T extends DataStoreObject> {
|
||||
try {
|
||||
YamlConfiguration f = new YamlConfiguration();
|
||||
f.options().pathSeparator('\0');
|
||||
f.load(file);
|
||||
f.load(this.file);
|
||||
|
||||
synchronized (lock) {
|
||||
data.clear();
|
||||
synchronized (this.lock) {
|
||||
this.data.clear();
|
||||
|
||||
f.getValues(false).values().stream()
|
||||
.filter(ConfigurationSection.class::isInstance)
|
||||
.map(v -> getFromSection.apply((ConfigurationSection) v))
|
||||
.forEach(v -> data.put(v.getKey(), v));
|
||||
.map(v -> this.getFromSection.apply((ConfigurationSection) v))
|
||||
.forEach(v -> this.data.put(v.getKey(), v));
|
||||
}
|
||||
} catch (IOException | InvalidConfigurationException ex) {
|
||||
plugin.getLogger().log(Level.SEVERE, "Failed to load data from " + file.getName(), ex);
|
||||
this.plugin.getLogger().log(Level.SEVERE, "Failed to load data from " + this.file.getName(), ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Optionally save this storage's data to file if there have been changes
|
||||
* Optionally, save this storage's data to file if there have been changes
|
||||
* made
|
||||
*/
|
||||
public void saveChanges() {
|
||||
if (saveTask != null || data.values().stream().anyMatch(DataStoreObject::hasChanged)) {
|
||||
if (this.saveTask != null || this.data.values().stream().anyMatch(DataStoreObject::hasChanged)) {
|
||||
flushSave();
|
||||
}
|
||||
}
|
||||
@ -243,9 +242,9 @@ public class SimpleDataStore<T extends DataStoreObject> {
|
||||
*/
|
||||
public void save() {
|
||||
// save async even if no plugin or if plugin disabled
|
||||
if (saveTask == null) {
|
||||
autosaveTimer = new Timer((plugin != null ? plugin.getName() + "-DataStoreSave-" : "DataStoreSave-") + getFile().getName());
|
||||
autosaveTimer.schedule(saveTask = new SaveTask(), autosaveInterval * 1000L);
|
||||
if (this.saveTask == null) {
|
||||
this.autosaveTimer = new Timer((this.plugin != null ? this.plugin.getName() + "-DataStoreSave-" : "DataStoreSave-") + getFile().getName());
|
||||
this.autosaveTimer.schedule(this.saveTask = new SaveTask(), this.autosaveInterval * 1000L);
|
||||
}
|
||||
}
|
||||
|
||||
@ -253,25 +252,25 @@ public class SimpleDataStore<T extends DataStoreObject> {
|
||||
* Force a new save of this storage's data
|
||||
*/
|
||||
public void flushSave() {
|
||||
if (saveTask != null) {
|
||||
if (this.saveTask != null) {
|
||||
//Close Threads
|
||||
saveTask.cancel();
|
||||
autosaveTimer.cancel();
|
||||
saveTask = null;
|
||||
autosaveTimer = null;
|
||||
this.saveTask.cancel();
|
||||
this.autosaveTimer.cancel();
|
||||
this.saveTask = null;
|
||||
this.autosaveTimer = null;
|
||||
}
|
||||
|
||||
YamlConfiguration f = new YamlConfiguration();
|
||||
YamlConfiguration yamlConfig = new YamlConfiguration();
|
||||
|
||||
synchronized (lock) {
|
||||
data.values().forEach(e -> e.saveToSection(f.createSection(e.getConfigKey())));
|
||||
synchronized (this.lock) {
|
||||
this.data.values().forEach(e -> e.saveToSection(yamlConfig.createSection(e.getConfigKey())));
|
||||
}
|
||||
|
||||
try {
|
||||
f.save(getFile());
|
||||
data.values().forEach(e -> e.setChanged(false));
|
||||
yamlConfig.save(getFile());
|
||||
this.data.values().forEach(e -> e.setChanged(false));
|
||||
} catch (IOException ex) {
|
||||
plugin.getLogger().log(Level.SEVERE, "Failed to save data to " + file.getName(), ex);
|
||||
this.plugin.getLogger().log(Level.SEVERE, "Failed to save data to " + this.file.getName(), ex);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -59,19 +59,19 @@ public class ConfigEditorGui extends SimplePagedGui {
|
||||
if (!(parent instanceof ConfigEditorGui)) {
|
||||
setOnClose((gui) -> save());
|
||||
} else {
|
||||
setOnClose((gui) -> ((ConfigEditorGui) parent).edits |= edits);
|
||||
setOnClose((gui) -> ((ConfigEditorGui) parent).edits |= this.edits);
|
||||
}
|
||||
|
||||
// if we have a ConfigSection, we can also grab comments
|
||||
try {
|
||||
configSection_getCommentString = node.getClass().getDeclaredMethod("getCommentString", String.class);
|
||||
this.configSection_getCommentString = node.getClass().getDeclaredMethod("getCommentString", String.class);
|
||||
} catch (Exception ignore) {
|
||||
}
|
||||
|
||||
// decorate header
|
||||
this.setTitle(ChatColor.DARK_BLUE + file);
|
||||
this.setUseHeader(true);
|
||||
headerBackItem = footerBackItem = GuiUtils.getBorderItem(XMaterial.GRAY_STAINED_GLASS_PANE.parseItem());
|
||||
this.headerBackItem = this.footerBackItem = GuiUtils.getBorderItem(XMaterial.GRAY_STAINED_GLASS_PANE.parseItem());
|
||||
final String path = node.getCurrentPath();
|
||||
this.setItem(4, configItem(XMaterial.FILLED_MAP, !path.isEmpty() ? path : file, config, !path.isEmpty() ? path : null, ChatColor.BLACK.toString()));
|
||||
this.setButton(8, GuiUtils.createButtonItem(XMaterial.OAK_DOOR, "Exit"), (event) -> event.player.closeInventory());
|
||||
@ -79,22 +79,22 @@ public class ConfigEditorGui extends SimplePagedGui {
|
||||
// compile list of settings
|
||||
for (String key : node.getKeys(false)) {
|
||||
if (node.isConfigurationSection(key)) {
|
||||
sections.add(key);
|
||||
this.sections.add(key);
|
||||
continue;
|
||||
}
|
||||
|
||||
settings.add(key);
|
||||
this.settings.add(key);
|
||||
}
|
||||
|
||||
// next we need to display the config settings
|
||||
int index = 9;
|
||||
for (final String sectionKey : sections) {
|
||||
for (final String sectionKey : this.sections) {
|
||||
setButton(index++, configItem(XMaterial.WRITABLE_BOOK, ChatColor.YELLOW + sectionKey, node, sectionKey, "Click to open this section"),
|
||||
(event) -> event.manager.showGUI(event.player, new ConfigEditorGui(player, plugin, this, file, config, node.getConfigurationSection(sectionKey))));
|
||||
}
|
||||
|
||||
// now display individual settings
|
||||
for (final String settingKey : settings) {
|
||||
for (final String settingKey : this.settings) {
|
||||
final Object val = node.get(settingKey);
|
||||
if (val == null) {
|
||||
continue;
|
||||
@ -130,7 +130,7 @@ public class ConfigEditorGui extends SimplePagedGui {
|
||||
(event) -> {
|
||||
SimplePagedGui paged = new SimplePagedGui(this);
|
||||
paged.setTitle(ChatColor.BLUE + settingKey);
|
||||
paged.setHeaderBackItem(headerBackItem).setFooterBackItem(footerBackItem).setDefaultItem(blankItem);
|
||||
paged.setHeaderBackItem(this.headerBackItem).setFooterBackItem(this.footerBackItem).setDefaultItem(this.blankItem);
|
||||
paged.setItem(4, configItem(XMaterial.FILLED_MAP, settingKey, node, settingKey, "Choose an item to change this value to"));
|
||||
int i = 9;
|
||||
for (XMaterial mat : getAllValidMaterials()) {
|
||||
@ -179,18 +179,18 @@ public class ConfigEditorGui extends SimplePagedGui {
|
||||
}
|
||||
|
||||
public ConfigurationSection getCurrentNode() {
|
||||
return node;
|
||||
return this.node;
|
||||
}
|
||||
|
||||
protected void updateValue(int clickCell, String path) {
|
||||
ItemStack item = inventory.getItem(clickCell);
|
||||
ItemStack item = this.inventory.getItem(clickCell);
|
||||
|
||||
if (item == null || item == AIR) {
|
||||
return;
|
||||
}
|
||||
|
||||
ItemMeta meta = item.getItemMeta();
|
||||
Object val = node.get(path);
|
||||
Object val = this.node.get(path);
|
||||
|
||||
if (meta != null && val != null) {
|
||||
String valStr;
|
||||
@ -212,17 +212,17 @@ public class ConfigEditorGui extends SimplePagedGui {
|
||||
setItem(clickCell, item);
|
||||
}
|
||||
|
||||
edits = true;
|
||||
this.edits = true;
|
||||
}
|
||||
|
||||
void toggle(int clickCell, String path) {
|
||||
boolean val = !node.getBoolean(path);
|
||||
node.set(path, val);
|
||||
boolean val = !this.node.getBoolean(path);
|
||||
this.node.set(path, val);
|
||||
|
||||
if (val) {
|
||||
setItem(clickCell, ItemUtils.addGlow(inventory.getItem(clickCell)));
|
||||
setItem(clickCell, ItemUtils.addGlow(this.inventory.getItem(clickCell)));
|
||||
} else {
|
||||
setItem(clickCell, ItemUtils.removeGlow(inventory.getItem(clickCell)));
|
||||
setItem(clickCell, ItemUtils.removeGlow(this.inventory.getItem(clickCell)));
|
||||
}
|
||||
|
||||
updateValue(clickCell, path);
|
||||
@ -230,12 +230,12 @@ public class ConfigEditorGui extends SimplePagedGui {
|
||||
|
||||
boolean setNumber(int clickCell, String path, String input) {
|
||||
try {
|
||||
if (node.isInt(path)) {
|
||||
node.set(path, Integer.parseInt(input));
|
||||
} else if (node.isDouble(path)) {
|
||||
node.set(path, Double.parseDouble(input));
|
||||
} else if (node.isLong(path)) {
|
||||
node.set(path, Long.parseLong(input));
|
||||
if (this.node.isInt(path)) {
|
||||
this.node.set(path, Integer.parseInt(input));
|
||||
} else if (this.node.isDouble(path)) {
|
||||
this.node.set(path, Double.parseDouble(input));
|
||||
} else if (this.node.isLong(path)) {
|
||||
this.node.set(path, Long.parseLong(input));
|
||||
}
|
||||
|
||||
updateValue(clickCell, path);
|
||||
@ -250,42 +250,42 @@ public class ConfigEditorGui extends SimplePagedGui {
|
||||
Optional<XMaterial> mat = CompatibleMaterial.getMaterial(item.getType());
|
||||
|
||||
if (!mat.isPresent()) {
|
||||
node.set(path, XMaterial.STONE.name());
|
||||
this.node.set(path, XMaterial.STONE.name());
|
||||
} else {
|
||||
node.set(path, mat.get().name());
|
||||
this.node.set(path, mat.get().name());
|
||||
}
|
||||
|
||||
updateValue(clickCell, path);
|
||||
}
|
||||
|
||||
void setList(int clickCell, String path, List<String> list) {
|
||||
node.set(path, list);
|
||||
this.node.set(path, list);
|
||||
updateValue(clickCell, path);
|
||||
}
|
||||
|
||||
void save() {
|
||||
if (!edits) {
|
||||
if (!this.edits) {
|
||||
return;
|
||||
}
|
||||
|
||||
// could also check and call saveChanges()
|
||||
if (config instanceof FileConfiguration) {
|
||||
if (this.config instanceof FileConfiguration) {
|
||||
try {
|
||||
((FileConfiguration) config).save(new File(plugin.getDataFolder(), file));
|
||||
((FileConfiguration) this.config).save(new File(this.plugin.getDataFolder(), this.file));
|
||||
} catch (IOException ex) {
|
||||
plugin.getLogger().log(Level.SEVERE, "Failed to save config changes to " + file, ex);
|
||||
this.plugin.getLogger().log(Level.SEVERE, "Failed to save config changes to " + this.file, ex);
|
||||
return;
|
||||
}
|
||||
} else if (config instanceof Config) {
|
||||
((Config) config).save();
|
||||
} else if (this.config instanceof Config) {
|
||||
((Config) this.config).save();
|
||||
} else {
|
||||
player.sendMessage(ChatColor.RED + "Unknown configuration type '" + config.getClass().getName() + "' - Please report this error!");
|
||||
plugin.getLogger().log(Level.WARNING, "Unknown configuration type '" + config.getClass().getName() + "' - Please report this error!");
|
||||
this.player.sendMessage(ChatColor.RED + "Unknown configuration type '" + this.config.getClass().getName() + "' - Please report this error!");
|
||||
this.plugin.getLogger().log(Level.WARNING, "Unknown configuration type '" + this.config.getClass().getName() + "' - Please report this error!");
|
||||
return;
|
||||
}
|
||||
|
||||
plugin.reloadConfig();
|
||||
player.sendMessage(ChatColor.GREEN + "Config " + file + " saved!");
|
||||
this.plugin.reloadConfig();
|
||||
this.player.sendMessage(ChatColor.GREEN + "Config " + this.file + " saved!");
|
||||
}
|
||||
|
||||
private boolean isNumber(Object value) {
|
||||
@ -307,9 +307,9 @@ public class ConfigEditorGui extends SimplePagedGui {
|
||||
protected ItemStack configItem(XMaterial type, String name, ConfigurationSection node, String path, String def) {
|
||||
String[] info = null;
|
||||
|
||||
if (configSection_getCommentString != null) {
|
||||
if (this.configSection_getCommentString != null) {
|
||||
try {
|
||||
Object comment = configSection_getCommentString.invoke(node, path);
|
||||
Object comment = this.configSection_getCommentString.invoke(node, path);
|
||||
|
||||
if (comment != null) {
|
||||
info = comment.toString().split("\n");
|
||||
@ -328,9 +328,9 @@ public class ConfigEditorGui extends SimplePagedGui {
|
||||
|
||||
String[] info = null;
|
||||
|
||||
if (configSection_getCommentString != null) {
|
||||
if (this.configSection_getCommentString != null) {
|
||||
try {
|
||||
Object comment = configSection_getCommentString.invoke(node, path);
|
||||
Object comment = this.configSection_getCommentString.invoke(node, path);
|
||||
if (comment != null) {
|
||||
info = (value + "\n" + comment).split("\n");
|
||||
}
|
||||
|
@ -24,7 +24,7 @@ public class ConfigEditorListEditorGui extends SimplePagedGui {
|
||||
|
||||
this.current = current;
|
||||
this.blankItem = current.getDefaultItem();
|
||||
headerBackItem = footerBackItem = current.getHeaderBackItem();
|
||||
this.headerBackItem = this.footerBackItem = current.getHeaderBackItem();
|
||||
setTitle(ChatColor.DARK_BLUE + "String List Editor");
|
||||
this.setUseHeader(true);
|
||||
this.setItem(4, current.configItem(XMaterial.FILLED_MAP, key, current.getCurrentNode(), key, null));
|
||||
@ -33,14 +33,14 @@ public class ConfigEditorListEditorGui extends SimplePagedGui {
|
||||
|
||||
this.setButton(8, GuiUtils.createButtonItem(XMaterial.LAVA_BUCKET, ChatColor.RED + "Discard Changes"), (event) -> event.player.closeInventory());
|
||||
this.setButton(0, GuiUtils.createButtonItem(XMaterial.REDSTONE, ChatColor.GREEN + "Save"), (event) -> {
|
||||
saveChanges = true;
|
||||
this.saveChanges = true;
|
||||
event.player.closeInventory();
|
||||
});
|
||||
this.setButton(1, GuiUtils.createButtonItem(XMaterial.CHEST, ChatColor.BLUE + "Add Item"),
|
||||
(event) -> {
|
||||
event.gui.exit();
|
||||
ChatPrompt.showPrompt(event.manager.getPlugin(), event.player, "Enter a new value to add:", response -> {
|
||||
values.add(response.getMessage().trim());
|
||||
this.values.add(response.getMessage().trim());
|
||||
redraw();
|
||||
})
|
||||
.setOnClose(() -> event.manager.showGUI(event.player, this))
|
||||
@ -54,24 +54,24 @@ public class ConfigEditorListEditorGui extends SimplePagedGui {
|
||||
}
|
||||
|
||||
void redraw() {
|
||||
page = 1;
|
||||
this.page = 1;
|
||||
|
||||
// clear old display
|
||||
if (inventory != null) {
|
||||
for (Integer i : cellItems.keySet().toArray(new Integer[0])) {
|
||||
if (this.inventory != null) {
|
||||
for (Integer i : this.cellItems.keySet().toArray(new Integer[0])) {
|
||||
if (i > 8) {
|
||||
cellItems.remove(i);
|
||||
conditionalButtons.remove(i);
|
||||
this.cellItems.remove(i);
|
||||
this.conditionalButtons.remove(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// update items
|
||||
int i = 9;
|
||||
for (String item : values) {
|
||||
for (String item : this.values) {
|
||||
final int index = i - 9;
|
||||
setButton(i++, GuiUtils.createButtonItem(XMaterial.PAPER, item, "Right-click to remove"), ClickType.RIGHT, (event) -> {
|
||||
values.remove(index);
|
||||
this.values.remove(index);
|
||||
redraw();
|
||||
});
|
||||
}
|
||||
|
@ -34,11 +34,11 @@ public class PluginConfigGui extends SimplePagedGui {
|
||||
this.plugin = plugin;
|
||||
|
||||
// collect list of plugins
|
||||
configs.put(plugin.getCoreConfig().getFile().getName(), plugin.getCoreConfig());
|
||||
this.configs.put(plugin.getCoreConfig().getFile().getName(), plugin.getCoreConfig());
|
||||
List<Config> more = plugin.getExtraConfig();
|
||||
if (more != null && !more.isEmpty()) {
|
||||
for (Config cfg : more) {
|
||||
configs.put(cfg.getFile().getName(), cfg);
|
||||
this.configs.put(cfg.getFile().getName(), cfg);
|
||||
}
|
||||
}
|
||||
|
||||
@ -54,7 +54,7 @@ public class PluginConfigGui extends SimplePagedGui {
|
||||
this.plugin = plugin;
|
||||
|
||||
// collect list of plugins
|
||||
configs.put("config.yml", plugin.getConfig());
|
||||
this.configs.put("config.yml", plugin.getConfig());
|
||||
|
||||
try {
|
||||
// can we also grab extra config from this mysterious plugin?
|
||||
@ -64,11 +64,11 @@ public class PluginConfigGui extends SimplePagedGui {
|
||||
// if we have the getExtraConfig function, we should also be able to get the file
|
||||
Method method_Config_getFile = ((List<?>) more).get(0).getClass().getDeclaredMethod("getFile");
|
||||
for (Object cfg : ((List<?>) more)) {
|
||||
configs.put(((File) method_Config_getFile.invoke(cfg)).getName(), (MemoryConfiguration) cfg);
|
||||
this.configs.put(((File) method_Config_getFile.invoke(cfg)).getName(), (MemoryConfiguration) cfg);
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
// include a failsafe, I guess
|
||||
((List<?>) more).forEach(cfg -> configs.put("(File " + configs.size() + ")", (MemoryConfiguration) cfg));
|
||||
((List<?>) more).forEach(cfg -> this.configs.put("(File " + this.configs.size() + ")", (MemoryConfiguration) cfg));
|
||||
}
|
||||
}
|
||||
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
|
||||
@ -82,16 +82,16 @@ public class PluginConfigGui extends SimplePagedGui {
|
||||
this.blankItem = GuiUtils.getBorderItem(XMaterial.LIGHT_GRAY_STAINED_GLASS_PANE);
|
||||
|
||||
// decorate header
|
||||
this.setTitle(ChatColor.DARK_BLUE + plugin.getName() + " Plugin Config");
|
||||
this.setTitle(ChatColor.DARK_BLUE + this.plugin.getName() + " Plugin Config");
|
||||
this.setUseHeader(true);
|
||||
headerBackItem = footerBackItem = GuiUtils.getBorderItem(XMaterial.GRAY_STAINED_GLASS_PANE.parseItem());
|
||||
this.headerBackItem = this.footerBackItem = GuiUtils.getBorderItem(XMaterial.GRAY_STAINED_GLASS_PANE.parseItem());
|
||||
this.setButton(8, GuiUtils.createButtonItem(XMaterial.OAK_DOOR, "Exit"), (event) -> event.player.closeInventory());
|
||||
|
||||
// List out all config files that this plugin has
|
||||
int i = 9;
|
||||
for (Map.Entry<String, MemoryConfiguration> config : configs.entrySet()) {
|
||||
for (Map.Entry<String, MemoryConfiguration> config : this.configs.entrySet()) {
|
||||
this.setButton(i++, GuiUtils.createButtonItem(XMaterial.BOOK, ChatColor.YELLOW + config.getKey(), "Click to edit this config"),
|
||||
(event) -> event.manager.showGUI(event.player, new ConfigEditorGui(event.player, plugin, this, config.getKey(), config.getValue())));
|
||||
(event) -> event.manager.showGUI(event.player, new ConfigEditorGui(event.player, this.plugin, this, config.getKey(), config.getValue())));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -11,11 +11,11 @@ import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public final class PluginInfo {
|
||||
protected final JavaPlugin javaPlugin;
|
||||
protected final int songodaId;
|
||||
protected final String coreIcon;
|
||||
protected final XMaterial icon;
|
||||
protected final String coreLibraryVersion;
|
||||
private final JavaPlugin javaPlugin;
|
||||
private final int songodaId;
|
||||
private final String coreIcon;
|
||||
private final XMaterial icon;
|
||||
private final String coreLibraryVersion;
|
||||
|
||||
private final List<PluginInfoModule> modules = new ArrayList<>();
|
||||
private boolean hasUpdate = false;
|
||||
@ -34,17 +34,17 @@ public final class PluginInfo {
|
||||
}
|
||||
|
||||
public String getLatestVersion() {
|
||||
return latestVersion;
|
||||
return this.latestVersion;
|
||||
}
|
||||
|
||||
public void setLatestVersion(String latestVersion) {
|
||||
this.latestVersion = latestVersion;
|
||||
|
||||
hasUpdate = latestVersion != null && !latestVersion.isEmpty() && !javaPlugin.getDescription().getVersion().equalsIgnoreCase(latestVersion);
|
||||
this.hasUpdate = latestVersion != null && !latestVersion.isEmpty() && !this.javaPlugin.getDescription().getVersion().equalsIgnoreCase(latestVersion);
|
||||
}
|
||||
|
||||
public String getNotification() {
|
||||
return notification;
|
||||
return this.notification;
|
||||
}
|
||||
|
||||
public void setNotification(String notification) {
|
||||
@ -52,7 +52,7 @@ public final class PluginInfo {
|
||||
}
|
||||
|
||||
public boolean hasUpdate() {
|
||||
return hasUpdate;
|
||||
return this.hasUpdate;
|
||||
}
|
||||
|
||||
public void setHasUpdate(boolean hasUpdate) {
|
||||
@ -60,7 +60,7 @@ public final class PluginInfo {
|
||||
}
|
||||
|
||||
public String getChangeLog() {
|
||||
return changeLog;
|
||||
return this.changeLog;
|
||||
}
|
||||
|
||||
public void setChangeLog(String changeLog) {
|
||||
@ -68,7 +68,7 @@ public final class PluginInfo {
|
||||
}
|
||||
|
||||
public String getMarketplaceLink() {
|
||||
return marketplaceLink;
|
||||
return this.marketplaceLink;
|
||||
}
|
||||
|
||||
public void setMarketplaceLink(String marketplaceLink) {
|
||||
@ -76,7 +76,7 @@ public final class PluginInfo {
|
||||
}
|
||||
|
||||
public JSONObject getJson() {
|
||||
return json;
|
||||
return this.json;
|
||||
}
|
||||
|
||||
public void setJson(JSONObject json) {
|
||||
@ -84,29 +84,33 @@ public final class PluginInfo {
|
||||
}
|
||||
|
||||
public PluginInfoModule addModule(PluginInfoModule module) {
|
||||
modules.add(module);
|
||||
this.modules.add(module);
|
||||
|
||||
return module;
|
||||
}
|
||||
|
||||
public List<PluginInfoModule> getModules() {
|
||||
return Collections.unmodifiableList(modules);
|
||||
return Collections.unmodifiableList(this.modules);
|
||||
}
|
||||
|
||||
public JavaPlugin getJavaPlugin() {
|
||||
return javaPlugin;
|
||||
return this.javaPlugin;
|
||||
}
|
||||
|
||||
public int getSongodaId() {
|
||||
return songodaId;
|
||||
return this.songodaId;
|
||||
}
|
||||
|
||||
public String getCoreIcon() {
|
||||
return coreIcon;
|
||||
return this.coreIcon;
|
||||
}
|
||||
|
||||
public XMaterial getIcon() {
|
||||
return this.icon;
|
||||
}
|
||||
|
||||
public String getCoreLibraryVersion() {
|
||||
return coreLibraryVersion;
|
||||
return this.coreLibraryVersion;
|
||||
}
|
||||
|
||||
public int getDependencyVersion() {
|
||||
|
@ -18,11 +18,11 @@ public class SongodaCoreCommand extends AbstractCommand {
|
||||
@Override
|
||||
protected ReturnType runCommand(CommandSender sender, String... args) {
|
||||
if (sender instanceof Player) {
|
||||
if (guiManager == null || guiManager.isClosed()) {
|
||||
guiManager = new GuiManager(SongodaCore.getHijackedPlugin());
|
||||
if (this.guiManager == null || this.guiManager.isClosed()) {
|
||||
this.guiManager = new GuiManager(SongodaCore.getHijackedPlugin());
|
||||
}
|
||||
|
||||
guiManager.showGUI((Player) sender, new SongodaCoreOverviewGUI());
|
||||
this.guiManager.showGUI((Player) sender, new SongodaCoreOverviewGUI());
|
||||
} else {
|
||||
sender.sendMessage("/songoda diag");
|
||||
}
|
||||
|
@ -11,7 +11,7 @@ import org.bukkit.event.inventory.ClickType;
|
||||
import java.util.List;
|
||||
|
||||
final class SongodaCoreOverviewGUI extends Gui {
|
||||
protected SongodaCoreOverviewGUI() {
|
||||
SongodaCoreOverviewGUI() {
|
||||
List<PluginInfo> plugins = SongodaCore.getPlugins();
|
||||
// could do pages, too, but don't think we'll have that many at a time for a while
|
||||
int max = (int) Math.ceil(plugins.size() / 9.);
|
||||
@ -20,11 +20,11 @@ final class SongodaCoreOverviewGUI extends Gui {
|
||||
|
||||
// TODO: this could use some decorating
|
||||
|
||||
for (int i = 0; i < plugins.size(); i++) {
|
||||
for (int i = 0; i < plugins.size(); ++i) {
|
||||
final PluginInfo plugin = plugins.get(i);
|
||||
|
||||
if (plugin.hasUpdate()) {
|
||||
setButton(i, GuiUtils.createButtonItem(plugin.icon != null ? plugin.icon : XMaterial.STONE,
|
||||
setButton(i, GuiUtils.createButtonItem(plugin.getIcon() != null ? plugin.getIcon() : XMaterial.STONE,
|
||||
ChatColor.GOLD + plugin.getJavaPlugin().getName(),
|
||||
ChatColor.GRAY + "Latest Version: " + plugin.getLatestVersion(),
|
||||
ChatColor.GRAY + "Installed Version: " + plugin.getJavaPlugin().getDescription().getVersion(),
|
||||
@ -42,7 +42,7 @@ final class SongodaCoreOverviewGUI extends Gui {
|
||||
continue;
|
||||
}
|
||||
|
||||
setButton(i, GuiUtils.createButtonItem(plugin.icon != null ? plugin.icon : XMaterial.STONE,
|
||||
setButton(i, GuiUtils.createButtonItem(plugin.getIcon() != null ? plugin.getIcon() : XMaterial.STONE,
|
||||
ChatColor.GOLD + plugin.getJavaPlugin().getName(),
|
||||
ChatColor.GRAY + "Installed Version: " + plugin.getJavaPlugin().getDescription().getVersion(),
|
||||
"",
|
||||
|
@ -1,6 +1,5 @@
|
||||
package com.craftaro.core.data;
|
||||
|
||||
public interface ComputedValue {
|
||||
|
||||
Object compute();
|
||||
}
|
||||
|
@ -5,7 +5,6 @@ import org.jooq.DSLContext;
|
||||
import java.sql.SQLException;
|
||||
|
||||
public interface DatabaseConnector {
|
||||
|
||||
/**
|
||||
* Checks if the connection to the database has been created
|
||||
*
|
||||
@ -35,5 +34,4 @@ public interface DatabaseConnector {
|
||||
interface ConnectionCallback {
|
||||
void accept(DSLContext ctx) throws SQLException;
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -12,49 +12,48 @@ import java.io.File;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class DatabaseManager {
|
||||
|
||||
private static DatabaseManager INSTANCE;
|
||||
|
||||
private final MonitoredThread thread;
|
||||
private DatabaseConnector connector;
|
||||
private final DatabaseConnector connector;
|
||||
|
||||
private final Config databaseConfig;
|
||||
|
||||
public DatabaseManager(SongodaPlugin plugin) {
|
||||
INSTANCE = this;
|
||||
thread = new MonitoredThread(plugin.getName().toLowerCase() + "-sql-thread", 15, TimeUnit.SECONDS);
|
||||
databaseConfig = new Config(plugin, "database.yml");
|
||||
this.thread = new MonitoredThread(plugin.getName().toLowerCase() + "-sql-thread", 15, TimeUnit.SECONDS);
|
||||
this.databaseConfig = new Config(plugin, "database.yml");
|
||||
|
||||
if (!new File(plugin.getDataFolder(), "database.yml").exists())
|
||||
plugin.saveResource("database.yml", false);
|
||||
databaseConfig.load();
|
||||
this.databaseConfig.load();
|
||||
|
||||
String type = databaseConfig.getString("type", "H2").toUpperCase();
|
||||
String host = databaseConfig.getString("host", "localhost");
|
||||
int port = databaseConfig.getInt("port", 3306);
|
||||
String database = databaseConfig.getString("database", "plugin");
|
||||
String username = databaseConfig.getString("username", "root");
|
||||
String password = databaseConfig.getString("password", "");
|
||||
int poolSize = databaseConfig.getInt("poolSize", 10);
|
||||
boolean useSSL = databaseConfig.getBoolean("useSSL", false);
|
||||
boolean autoReconnect = databaseConfig.getBoolean("autoReconnect", true);
|
||||
String type = this.databaseConfig.getString("type", "H2").toUpperCase();
|
||||
String host = this.databaseConfig.getString("host", "localhost");
|
||||
int port = this.databaseConfig.getInt("port", 3306);
|
||||
String database = this.databaseConfig.getString("database", "plugin");
|
||||
String username = this.databaseConfig.getString("username", "root");
|
||||
String password = this.databaseConfig.getString("password", "");
|
||||
int poolSize = this.databaseConfig.getInt("poolSize", 10);
|
||||
boolean useSSL = this.databaseConfig.getBoolean("useSSL", false);
|
||||
boolean autoReconnect = this.databaseConfig.getBoolean("autoReconnect", true);
|
||||
|
||||
String dataPath = plugin.getDataFolder().getPath().replaceAll("\\\\", "/") + "/";
|
||||
|
||||
String dbFile = "./" + dataPath + databaseConfig.getString("file", "data");
|
||||
String dbFile = "./" + dataPath + this.databaseConfig.getString("file", "data");
|
||||
|
||||
switch (DatabaseType.valueOf(type)) {
|
||||
case H2:
|
||||
connector = new H2Connector(dbFile, poolSize);
|
||||
this.connector = new H2Connector(dbFile, poolSize);
|
||||
break;
|
||||
case MYSQL:
|
||||
connector = new MySQLConnector(host, port, database, username, password, useSSL, autoReconnect, poolSize);
|
||||
this.connector = new MySQLConnector(host, port, database, username, password, useSSL, autoReconnect, poolSize);
|
||||
break;
|
||||
case SQLITE:
|
||||
connector = new SQLiteConnector(dbFile, poolSize);
|
||||
this.connector = new SQLiteConnector(dbFile, poolSize);
|
||||
break;
|
||||
case MARIADB:
|
||||
connector = new MariaDBConnector(host, port, database, username, password, useSSL, autoReconnect, poolSize);
|
||||
this.connector = new MariaDBConnector(host, port, database, username, password, useSSL, autoReconnect, poolSize);
|
||||
break;
|
||||
default:
|
||||
throw new IllegalArgumentException("Invalid database type: " + type);
|
||||
@ -66,7 +65,7 @@ public class DatabaseManager {
|
||||
}
|
||||
|
||||
public void execute(Runnable runnable, boolean nonDisruptable) {
|
||||
thread.execute(runnable, nonDisruptable);
|
||||
this.thread.execute(runnable, nonDisruptable);
|
||||
}
|
||||
|
||||
public void load(String name, Runnable load) {
|
||||
@ -75,11 +74,11 @@ public class DatabaseManager {
|
||||
}
|
||||
|
||||
public DatabaseConnector getDatabaseConnector() {
|
||||
return connector;
|
||||
return this.connector;
|
||||
}
|
||||
|
||||
public Config getConfig() {
|
||||
return databaseConfig;
|
||||
return this.databaseConfig;
|
||||
}
|
||||
|
||||
public static DatabaseManager getInstance() {
|
||||
|
@ -3,7 +3,6 @@ package com.craftaro.core.data;
|
||||
import org.jooq.SQLDialect;
|
||||
|
||||
public enum DatabaseType {
|
||||
|
||||
MARIADB,
|
||||
MYSQL,
|
||||
H2,
|
||||
|
@ -3,8 +3,6 @@ package com.craftaro.core.data;
|
||||
import org.jooq.DSLContext;
|
||||
|
||||
public interface LoadsData {
|
||||
|
||||
|
||||
default void loadData() {
|
||||
DatabaseManager.getInstance().getDatabaseConnector().connect(false, ctx -> {
|
||||
setupTables(ctx);
|
||||
@ -15,5 +13,4 @@ public interface LoadsData {
|
||||
void loadDataImpl(DSLContext ctx);
|
||||
|
||||
void setupTables(DSLContext ctx);
|
||||
|
||||
}
|
||||
|
@ -7,7 +7,6 @@ import org.jooq.impl.DSL;
|
||||
import java.util.Collection;
|
||||
|
||||
public class SQLBase {
|
||||
|
||||
protected final DSLContext ctx;
|
||||
|
||||
public SQLBase(DSLContext ctx) {
|
||||
@ -39,8 +38,10 @@ public class SQLBase {
|
||||
|
||||
protected Field getField(String field, Class<?> type) {
|
||||
String fieldFinal = "`" + field + "`";
|
||||
if (type == boolean.class)
|
||||
if (type == boolean.class) {
|
||||
return DSL.field(fieldFinal, int.class);
|
||||
}
|
||||
|
||||
return type == null ? DSL.field(fieldFinal) : DSL.field(fieldFinal, type);
|
||||
}
|
||||
}
|
||||
|
@ -8,41 +8,42 @@ import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
public class SQLBatch implements SavesData {
|
||||
|
||||
private final List<SavesData> batch = new LinkedList<>();
|
||||
|
||||
public SQLBatch add(SavesData... data) {
|
||||
batch.addAll(Arrays.asList(data));
|
||||
this.batch.addAll(Arrays.asList(data));
|
||||
return this;
|
||||
}
|
||||
|
||||
public SQLBatch addAll(Collection<? extends SavesData> data) {
|
||||
batch.addAll(data);
|
||||
this.batch.addAll(data);
|
||||
return this;
|
||||
}
|
||||
|
||||
public List<SavesData> getBatch() {
|
||||
return batch;
|
||||
return this.batch;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(String... columns) {
|
||||
DatabaseManager.getInstance().getDatabaseConnector().connect(ctx -> {
|
||||
for (SavesData data : batch)
|
||||
for (SavesData data : this.batch) {
|
||||
data.saveImpl(ctx, columns);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void saveImpl(DSLContext ctx, String... columns) {
|
||||
for (SavesData data : batch)
|
||||
for (SavesData data : this.batch) {
|
||||
data.saveImpl(ctx, columns);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteImpl(DSLContext ctx) {
|
||||
for (SavesData data : batch)
|
||||
for (SavesData data : this.batch) {
|
||||
data.deleteImpl(ctx);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -4,7 +4,6 @@ import org.jooq.DSLContext;
|
||||
import org.jooq.impl.DSL;
|
||||
|
||||
public class SQLDelete extends SQLBase {
|
||||
|
||||
private SQLDelete(DSLContext ctx) {
|
||||
super(ctx);
|
||||
}
|
||||
@ -14,11 +13,11 @@ public class SQLDelete extends SQLBase {
|
||||
}
|
||||
|
||||
public void delete(String table, String id, Object value) {
|
||||
new SQLExecutable(ctx, ctx.delete(DSL.table(table)).where(DSL.field(id).eq(value))).execute();
|
||||
new SQLExecutable(this.ctx, this.ctx.delete(DSL.table(table)).where(DSL.field(id).eq(value))).execute();
|
||||
}
|
||||
|
||||
public void delete(String table, String id, Object value, String id2, Object value2) {
|
||||
new SQLExecutable(ctx, ctx.delete(DSL.table(table)).where(DSL.field(id).eq(value))
|
||||
new SQLExecutable(this.ctx, this.ctx.delete(DSL.table(table)).where(DSL.field(id).eq(value))
|
||||
.and(DSL.field(id2).eq(value2))).execute();
|
||||
}
|
||||
}
|
||||
|
@ -9,7 +9,6 @@ import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class SQLExecutable extends SQLBase {
|
||||
|
||||
protected Query query;
|
||||
|
||||
public SQLExecutable(DSLContext ctx, Query query) {
|
||||
@ -18,14 +17,18 @@ public class SQLExecutable extends SQLBase {
|
||||
}
|
||||
|
||||
public int execute() {
|
||||
return query.execute();
|
||||
return this.query.execute();
|
||||
}
|
||||
|
||||
public Stream<SQLResult.StoredRecord> get() {
|
||||
if (query instanceof ResultQuery) {
|
||||
ResultQuery<?> resultQuery = (ResultQuery<?>) query;
|
||||
if (this.query instanceof ResultQuery) {
|
||||
ResultQuery<?> resultQuery = (ResultQuery<?>) this.query;
|
||||
Result<?> result = resultQuery.getResult();
|
||||
return result.stream().map(SQLResult::new).map(SQLResult::getResults).flatMap(List::stream);
|
||||
return result
|
||||
.stream()
|
||||
.map(SQLResult::new)
|
||||
.map(SQLResult::getResults)
|
||||
.flatMap(List::stream);
|
||||
} else {
|
||||
throw new IllegalStateException("Query is not an instance of ResultQuery");
|
||||
}
|
||||
|
@ -15,7 +15,6 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class SQLInsert extends SQLBase {
|
||||
|
||||
private String table;
|
||||
private final Map<String, Object> fields = new LinkedHashMap<>();
|
||||
private boolean voidedKey = false;
|
||||
@ -36,55 +35,58 @@ public class SQLInsert extends SQLBase {
|
||||
}
|
||||
|
||||
public SQLInsert withField(String field, Object value, boolean voidKey) {
|
||||
if (voidKey)
|
||||
voidedKey = true;
|
||||
if (voidKey) {
|
||||
this.voidedKey = true;
|
||||
}
|
||||
return voidKey ? this : withField(field, value);
|
||||
}
|
||||
|
||||
public SQLInsert withField(String field, Object value) {
|
||||
if (field.equalsIgnoreCase("desc"))
|
||||
if (field.equalsIgnoreCase("desc")) {
|
||||
field = "`desc`";
|
||||
fields.put(field.toLowerCase(), value);
|
||||
}
|
||||
this.fields.put(field.toLowerCase(), value);
|
||||
return this;
|
||||
}
|
||||
|
||||
// For some reason this must be used before we submit. So I'm going to apply the values here.
|
||||
// For some reason, this must be used before we submit. So I'm going to apply the values here.
|
||||
public SQLExecutable onDuplicateKeyUpdate(String... columns) {
|
||||
currentStep = ctx.insertInto(DSL.table(table), fields.keySet().stream().map(DSL::field).toArray(Field[]::new));
|
||||
currentStep = currentStep.values(fields.values().stream().map(this::cleanValue).toArray());
|
||||
this.currentStep = this.ctx.insertInto(DSL.table(this.table), this.fields.keySet().stream().map(DSL::field).toArray(Field[]::new));
|
||||
this.currentStep = this.currentStep.values(this.fields.values().stream().map(this::cleanValue).toArray());
|
||||
|
||||
if (voidedKey)
|
||||
return new SQLExecutable(ctx, currentStep);
|
||||
if (this.voidedKey) {
|
||||
return new SQLExecutable(this.ctx, this.currentStep);
|
||||
}
|
||||
|
||||
SQLOnDupeUpdate sqlOnDupeUpdate = new SQLOnDupeUpdate(ctx, currentStep, columns);
|
||||
for (String column : (columns.length > 0 ? new HashSet<>(Arrays.asList(columns)) : fields.keySet()))
|
||||
sqlOnDupeUpdate.set(column.replace("`", ""), fields.get(column.toLowerCase()));
|
||||
SQLOnDupeUpdate sqlOnDupeUpdate = new SQLOnDupeUpdate(this.ctx, this.currentStep, columns);
|
||||
for (String column : (columns.length > 0 ? new HashSet<>(Arrays.asList(columns)) : this.fields.keySet())) {
|
||||
sqlOnDupeUpdate.set(column.replace("`", ""), this.fields.get(column.toLowerCase()));
|
||||
}
|
||||
return sqlOnDupeUpdate;
|
||||
}
|
||||
|
||||
public static class SQLOnDupeUpdate extends SQLExecutable {
|
||||
|
||||
private InsertOnDuplicateSetStep currentStep;
|
||||
private final List<String> columnsToUpdate = new ArrayList<>();
|
||||
|
||||
|
||||
public SQLOnDupeUpdate(DSLContext ctx, InsertValuesStepN currentStep, String... columns) {
|
||||
super(ctx, null);
|
||||
this.currentStep = currentStep.onDuplicateKeyUpdate();
|
||||
columnsToUpdate.addAll(Arrays.asList(columns));
|
||||
this.columnsToUpdate.addAll(Arrays.asList(columns));
|
||||
}
|
||||
|
||||
public SQLOnDupeUpdate set(String field, Object value) {
|
||||
if (!columnsToUpdate.isEmpty() && !columnsToUpdate.contains(field))
|
||||
if (!this.columnsToUpdate.isEmpty() && !this.columnsToUpdate.contains(field)) {
|
||||
return this;
|
||||
}
|
||||
|
||||
value = cleanValue(value);
|
||||
Field fieldName = getField(field, value == null ? null : value.getClass());
|
||||
|
||||
if (currentStep != null) {
|
||||
if (this.currentStep != null) {
|
||||
this.query = value == null ? this.currentStep.setNull(fieldName)
|
||||
: this.currentStep.set(fieldName, value);
|
||||
currentStep = null;
|
||||
this.currentStep = null;
|
||||
} else {
|
||||
this.query = value == null ? ((InsertOnDuplicateSetMoreStep) this.query).setNull(fieldName)
|
||||
: ((InsertOnDuplicateSetMoreStep) this.query).set(fieldName, value);
|
||||
|
@ -19,7 +19,7 @@ public class SQLResult {
|
||||
Object value = record.get(fieldName);
|
||||
map.put(fieldName, new StoredData(value));
|
||||
}
|
||||
results.add(new StoredRecord(map));
|
||||
this.results.add(new StoredRecord(map));
|
||||
}
|
||||
}
|
||||
|
||||
@ -30,11 +30,11 @@ public class SQLResult {
|
||||
Object value = record.get(fieldName);
|
||||
map.put(fieldName, new StoredData(value));
|
||||
}
|
||||
results.add(new StoredRecord(map));
|
||||
this.results.add(new StoredRecord(map));
|
||||
}
|
||||
|
||||
public List<StoredRecord> getResults() {
|
||||
return results;
|
||||
return this.results;
|
||||
}
|
||||
|
||||
public interface SQLResultI {
|
||||
@ -49,15 +49,15 @@ public class SQLResult {
|
||||
}
|
||||
|
||||
public StoredData get(String key) {
|
||||
return record.get(key);
|
||||
return this.record.get(key);
|
||||
}
|
||||
|
||||
public boolean has(String key) {
|
||||
return record.containsKey(key) && record.get(key).asString() != null;
|
||||
return this.record.containsKey(key) && this.record.get(key).asString() != null;
|
||||
}
|
||||
|
||||
public boolean isNull(String key) {
|
||||
return record.containsKey(key) && record.get(key).isNull();
|
||||
return this.record.containsKey(key) && this.record.get(key).isNull();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -8,7 +8,6 @@ import org.jooq.SelectWhereStep;
|
||||
import org.jooq.impl.DSL;
|
||||
|
||||
public class SQLSelect extends SQLBase {
|
||||
|
||||
private Select<?> currentStep;
|
||||
|
||||
public SQLSelect(DSLContext ctx) {
|
||||
@ -22,23 +21,23 @@ public class SQLSelect extends SQLBase {
|
||||
|
||||
public SQLSelect select(String... fields) {
|
||||
if (fields.length > 0) {
|
||||
currentStep = ctx.select(DSL.field(fields[0]));
|
||||
this.currentStep = this.ctx.select(DSL.field(fields[0]));
|
||||
for (int i = 1; i < fields.length; i++) {
|
||||
currentStep = ((SelectSelectStep<?>)currentStep).select(DSL.field(fields[i]));
|
||||
this.currentStep = ((SelectSelectStep<?>) this.currentStep).select(DSL.field(fields[i]));
|
||||
}
|
||||
} else {
|
||||
currentStep = ctx.select();
|
||||
this.currentStep = this.ctx.select();
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public SQLSelect from(String table) {
|
||||
currentStep = ((SelectSelectStep<?>)currentStep).from(DSL.table(table));
|
||||
this.currentStep = ((SelectSelectStep<?>) this.currentStep).from(DSL.table(table));
|
||||
return this;
|
||||
}
|
||||
|
||||
public void from(String table, SQLResult.SQLResultI result) {
|
||||
Result<?> resultData = ((SelectSelectStep<?>)currentStep).from(DSL.table(table)).fetch();
|
||||
Result<?> resultData = ((SelectSelectStep<?>) this.currentStep).from(DSL.table(table)).fetch();
|
||||
SQLResult rs = new SQLResult(resultData);
|
||||
for (SQLResult.StoredRecord record : rs.getResults()) {
|
||||
result.forEach(record);
|
||||
@ -46,12 +45,12 @@ public class SQLSelect extends SQLBase {
|
||||
}
|
||||
|
||||
public SQLWhere where(String id, Object value) {
|
||||
currentStep = ((SelectWhereStep<?>)currentStep).where(DSL.field(id).eq(value));
|
||||
return new SQLWhere(ctx, currentStep);
|
||||
this.currentStep = ((SelectWhereStep<?>) this.currentStep).where(DSL.field(id).eq(value));
|
||||
return new SQLWhere(this.ctx, this.currentStep);
|
||||
}
|
||||
|
||||
public SQLWhere whereBetween(String id, Object value1, Object value2) {
|
||||
currentStep = ((SelectWhereStep<?>)currentStep).where(DSL.field(id).between(value1, value2));
|
||||
return new SQLWhere(ctx, currentStep);
|
||||
this.currentStep = ((SelectWhereStep<?>) this.currentStep).where(DSL.field(id).between(value1, value2));
|
||||
return new SQLWhere(this.ctx, this.currentStep);
|
||||
}
|
||||
}
|
||||
|
@ -11,14 +11,13 @@ import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class SQLUpdate extends SQLBase {
|
||||
|
||||
private final List<String> columnsToUpdate = new ArrayList<>();
|
||||
|
||||
private UpdateSetStep currentStep;
|
||||
|
||||
private SQLUpdate(DSLContext ctx, String... columns) {
|
||||
super(ctx);
|
||||
columnsToUpdate.addAll(Arrays.asList(columns));
|
||||
this.columnsToUpdate.addAll(Arrays.asList(columns));
|
||||
}
|
||||
|
||||
public static SQLUpdate create(DSLContext ctx, String... columns) {
|
||||
@ -26,13 +25,14 @@ public class SQLUpdate extends SQLBase {
|
||||
}
|
||||
|
||||
public SQLUpdate update(String table) {
|
||||
this.currentStep = ctx.update(DSL.table(table));
|
||||
this.currentStep = this.ctx.update(DSL.table(table));
|
||||
return this;
|
||||
}
|
||||
|
||||
public SQLUpdate set(String field, Object value) {
|
||||
if (!columnsToUpdate.isEmpty() && !columnsToUpdate.contains(field))
|
||||
if (!this.columnsToUpdate.isEmpty() && !this.columnsToUpdate.contains(field)) {
|
||||
return this;
|
||||
}
|
||||
|
||||
value = cleanValue(value);
|
||||
Field fieldName = getField(field, value == null ? null : value.getClass());
|
||||
@ -42,6 +42,6 @@ public class SQLUpdate extends SQLBase {
|
||||
}
|
||||
|
||||
public SQLWhere where(String id, Object value) {
|
||||
return new SQLWhere(ctx, ((UpdateSetMoreStep) this.currentStep).where(DSL.field(id).eq(value)));
|
||||
return new SQLWhere(this.ctx, ((UpdateSetMoreStep) this.currentStep).where(DSL.field(id).eq(value)));
|
||||
}
|
||||
}
|
||||
|
@ -6,18 +6,17 @@ import org.jooq.UpdateConditionStep;
|
||||
import org.jooq.impl.DSL;
|
||||
|
||||
public class SQLWhere extends SQLExecutable {
|
||||
|
||||
public SQLWhere(DSLContext ctx, Query query) {
|
||||
super(ctx, query);
|
||||
}
|
||||
|
||||
public SQLWhere and(String id, Object value) {
|
||||
query = ((UpdateConditionStep) query).and(DSL.field(id).eq(value));
|
||||
this.query = ((UpdateConditionStep) this.query).and(DSL.field(id).eq(value));
|
||||
return this;
|
||||
}
|
||||
|
||||
public SQLWhere or(String id, Object value) {
|
||||
query = ((UpdateConditionStep) query).or(DSL.field(id).eq(value));
|
||||
this.query = ((UpdateConditionStep) this.query).or(DSL.field(id).eq(value));
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
@ -6,7 +6,6 @@ import org.jooq.Result;
|
||||
import org.jooq.impl.DSL;
|
||||
|
||||
public interface SavesData {
|
||||
|
||||
default void save(String... columns) {
|
||||
DatabaseManager.getInstance().getDatabaseConnector().connect(ctx ->
|
||||
saveImpl(ctx, columns));
|
||||
@ -32,8 +31,8 @@ public interface SavesData {
|
||||
Result<Record1<Object>> results = ctx.select(DSL.field("id")).from(DSL.table(table)).orderBy(DSL.field("id").desc()).fetch();
|
||||
Record1<Object> result = results.get(0);
|
||||
return result != null ? result.get(DSL.field("id"), Integer.class) : -1;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
@ -7,7 +7,6 @@ import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
|
||||
public class StoredData {
|
||||
|
||||
private Object object;
|
||||
|
||||
public StoredData(Object object) {
|
||||
@ -15,16 +14,20 @@ public class StoredData {
|
||||
}
|
||||
|
||||
public Object getObject() {
|
||||
return object;
|
||||
return this.object;
|
||||
}
|
||||
|
||||
public String asString() {
|
||||
if (object == null) return null;
|
||||
return object.toString();
|
||||
if (this.object == null) {
|
||||
return null;
|
||||
}
|
||||
return this.object.toString();
|
||||
}
|
||||
|
||||
public int asInt() {
|
||||
if (object == null) return 0;
|
||||
if (this.object == null) {
|
||||
return 0;
|
||||
}
|
||||
return Integer.parseInt(asString());
|
||||
}
|
||||
|
||||
@ -34,7 +37,9 @@ public class StoredData {
|
||||
|
||||
public long asLong() {
|
||||
String string = asString();
|
||||
if (string == null) return 0;
|
||||
if (string == null) {
|
||||
return 0;
|
||||
}
|
||||
return Long.parseLong(string);
|
||||
}
|
||||
|
||||
@ -47,8 +52,9 @@ public class StoredData {
|
||||
}
|
||||
|
||||
public boolean asBoolean() {
|
||||
if (object instanceof Integer)
|
||||
return (int) object == 1;
|
||||
if (this.object instanceof Integer) {
|
||||
return (int) this.object == 1;
|
||||
}
|
||||
return Boolean.parseBoolean(asString());
|
||||
}
|
||||
|
||||
@ -57,12 +63,12 @@ public class StoredData {
|
||||
}
|
||||
|
||||
public boolean isNull() {
|
||||
return object == null;
|
||||
return this.object == null;
|
||||
}
|
||||
|
||||
// get longblob
|
||||
public byte[] asBytes() {
|
||||
return (byte[]) object;
|
||||
return (byte[]) this.object;
|
||||
}
|
||||
|
||||
public UUID asUniqueID() {
|
||||
|
@ -50,9 +50,10 @@ public class H2Connector implements DatabaseConnector {
|
||||
}
|
||||
};
|
||||
|
||||
if (sqlThread)
|
||||
if (sqlThread) {
|
||||
DatabaseManager.getInstance().execute(runnable);
|
||||
else
|
||||
} else {
|
||||
runnable.run();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -53,7 +53,10 @@ public class MariaDBConnector implements DatabaseConnector {
|
||||
}
|
||||
};
|
||||
|
||||
if (sqlThread) DatabaseManager.getInstance().execute(runnable);
|
||||
else runnable.run();
|
||||
if (sqlThread) {
|
||||
DatabaseManager.getInstance().execute(runnable);
|
||||
} else {
|
||||
runnable.run();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -10,7 +10,6 @@ import org.jooq.impl.DSL;
|
||||
import java.sql.Connection;
|
||||
|
||||
public class MySQLConnector implements DatabaseConnector {
|
||||
|
||||
private HikariDataSource hikari;
|
||||
private boolean initializedSuccessfully;
|
||||
|
||||
@ -52,10 +51,11 @@ public class MySQLConnector implements DatabaseConnector {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
};
|
||||
if (sqlThread)
|
||||
if (sqlThread) {
|
||||
DatabaseManager.getInstance().execute(runnable);
|
||||
else
|
||||
} else {
|
||||
runnable.run();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -49,9 +49,10 @@ public class SQLiteConnector implements DatabaseConnector {
|
||||
}
|
||||
};
|
||||
|
||||
if (sqlThread)
|
||||
if (sqlThread) {
|
||||
DatabaseManager.getInstance().execute(runnable);
|
||||
else
|
||||
} else {
|
||||
runnable.run();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -3,16 +3,15 @@ package com.craftaro.core.data.lazy;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public class Lazy<T> {
|
||||
|
||||
private Supplier<T> supplier = null;
|
||||
private T value = null;
|
||||
|
||||
public synchronized T get() {
|
||||
if (value == null && supplier != null) {
|
||||
value = supplier.get();
|
||||
supplier = null;
|
||||
if (this.value == null && this.supplier != null) {
|
||||
this.value = this.supplier.get();
|
||||
this.supplier = null;
|
||||
}
|
||||
return value;
|
||||
return this.value;
|
||||
}
|
||||
|
||||
public synchronized T getOrDefault(T def) {
|
||||
@ -21,7 +20,7 @@ public class Lazy<T> {
|
||||
}
|
||||
|
||||
public synchronized Lazy<T> reset() {
|
||||
value = null;
|
||||
this.value = null;
|
||||
return this;
|
||||
}
|
||||
|
||||
@ -36,7 +35,7 @@ public class Lazy<T> {
|
||||
}
|
||||
|
||||
public synchronized boolean isLoaded() {
|
||||
return supplier != null;
|
||||
return this.supplier != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -7,60 +7,66 @@ import java.util.Set;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public class LazyList<T> {
|
||||
|
||||
private final List<T> list;
|
||||
private List<Lazy<T>> lazyList;
|
||||
|
||||
public LazyList(List list) {
|
||||
public LazyList(List<T> list) {
|
||||
this.list = list == null ? new LinkedList<>() : list;
|
||||
this.lazyList = new LinkedList<>();
|
||||
}
|
||||
|
||||
public List<T> getList() {
|
||||
loadList();
|
||||
return list;
|
||||
return this.list;
|
||||
}
|
||||
|
||||
public Set<T> getSet() {
|
||||
loadList();
|
||||
return new HashSet<>(list);
|
||||
return new HashSet<>(this.list);
|
||||
}
|
||||
|
||||
public void add(Supplier<T> supplier) {
|
||||
if (lazyList == null)
|
||||
list.add(supplier.get());
|
||||
else if (supplier != null)
|
||||
lazyList.add(new Lazy<T>().set(supplier));
|
||||
if (this.lazyList == null) {
|
||||
this.list.add(supplier.get());
|
||||
} else if (supplier != null) {
|
||||
this.lazyList.add(new Lazy<T>().set(supplier));
|
||||
}
|
||||
}
|
||||
|
||||
public void add(T items) {
|
||||
list.add(items);
|
||||
this.list.add(items);
|
||||
}
|
||||
|
||||
public void addAll(List<T> items) {
|
||||
list.addAll(items);
|
||||
this.list.addAll(items);
|
||||
}
|
||||
|
||||
public void addAll(Supplier<T>... suppliers) {
|
||||
for (Supplier<T> supplier : suppliers)
|
||||
for (Supplier<T> supplier : suppliers) {
|
||||
add(supplier);
|
||||
}
|
||||
}
|
||||
|
||||
private void loadList() {
|
||||
if (lazyList == null) return;
|
||||
for (Lazy<T> lazy : lazyList)
|
||||
list.add(lazy.get());
|
||||
lazyList = null;
|
||||
if (this.lazyList == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (Lazy<T> lazy : this.lazyList) {
|
||||
this.list.add(lazy.get());
|
||||
}
|
||||
this.lazyList = null;
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
list.clear();
|
||||
lazyList.clear();
|
||||
this.list.clear();
|
||||
this.lazyList.clear();
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
if (lazyList != null)
|
||||
return lazyList.isEmpty();
|
||||
return list.isEmpty();
|
||||
if (this.lazyList != null) {
|
||||
return this.lazyList.isEmpty();
|
||||
}
|
||||
return this.list.isEmpty();
|
||||
}
|
||||
}
|
||||
|
@ -4,7 +4,6 @@ import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface Data {
|
||||
|
||||
/**
|
||||
* Gets the auto increment id of this data
|
||||
*
|
||||
@ -40,6 +39,7 @@ public interface Data {
|
||||
|
||||
/**
|
||||
* No plugin prefix is required for the table
|
||||
*
|
||||
* @return The table name where the data should be stored
|
||||
*/
|
||||
String getTableName();
|
||||
|
@ -78,30 +78,30 @@ public class DataManager {
|
||||
}
|
||||
|
||||
private void load(DatabaseType forcedType) throws SQLException {
|
||||
String databaseType = databaseConfig.getString("Connection Settings.Type").toUpperCase();
|
||||
String databaseType = this.databaseConfig.getString("Connection Settings.Type").toUpperCase();
|
||||
if (forcedType != null) {
|
||||
databaseType = forcedType.name();
|
||||
}
|
||||
switch (databaseType) {
|
||||
case "MYSQL": {
|
||||
this.databaseConnector = new MySQLConnector(plugin, databaseConfig);
|
||||
this.databaseConnector = new MySQLConnector(this.plugin, this.databaseConfig);
|
||||
break;
|
||||
}
|
||||
case "MARIADB": {
|
||||
this.databaseConnector = new MariaDBConnector(plugin, databaseConfig);
|
||||
this.databaseConnector = new MariaDBConnector(this.plugin, this.databaseConfig);
|
||||
break;
|
||||
}
|
||||
case "SQLITE": {
|
||||
this.databaseConnector = new SQLiteConnector(plugin);
|
||||
this.databaseConnector = new SQLiteConnector(this.plugin);
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
this.databaseConnector = new H2Connector(plugin);
|
||||
this.databaseConnector = new H2Connector(this.plugin);
|
||||
break;
|
||||
}
|
||||
}
|
||||
this.type = databaseConnector.getType();
|
||||
this.plugin.getLogger().info("Data handler connected using " + databaseConnector.getType().name() + ".");
|
||||
this.type = this.databaseConnector.getType();
|
||||
this.plugin.getLogger().info("Data handler connected using " + this.databaseConnector.getType().name() + ".");
|
||||
|
||||
runMigrations();
|
||||
}
|
||||
@ -110,14 +110,14 @@ public class DataManager {
|
||||
* @return the database connector
|
||||
*/
|
||||
public DatabaseConnector getDatabaseConnector() {
|
||||
return databaseConnector;
|
||||
return this.databaseConnector;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the database executor service
|
||||
*/
|
||||
public ExecutorService getAsyncPool() {
|
||||
return asyncPool;
|
||||
return this.asyncPool;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -216,7 +216,7 @@ public class DataManager {
|
||||
public synchronized int getNextId(String table) {
|
||||
String prefixedTable = getTablePrefix() + table;
|
||||
if (!this.autoIncrementCache.containsKey(prefixedTable)) {
|
||||
databaseConnector.connectDSL(context -> {
|
||||
this.databaseConnector.connectDSL(context -> {
|
||||
// context.select(DSL.max(DSL.field("id"))).from(prefixedTable).fetchOptional().ifPresentOrElse(record -> {
|
||||
// if (record.get(0, Integer.class) == null) {
|
||||
// this.autoIncrementCache.put(prefixedTable, new AtomicInteger(1));
|
||||
@ -238,13 +238,13 @@ public class DataManager {
|
||||
return this.autoIncrementCache.get(prefixedTable).incrementAndGet();
|
||||
}
|
||||
|
||||
//TODO: Fix/create javadocs for all methods
|
||||
// TODO: Fix/create javadocs for all methods
|
||||
|
||||
/**
|
||||
* Saves the data to the database
|
||||
*/
|
||||
public void save(Data data) {
|
||||
asyncPool.execute(() -> {
|
||||
this.asyncPool.execute(() -> {
|
||||
saveSync(data);
|
||||
});
|
||||
}
|
||||
@ -253,7 +253,7 @@ public class DataManager {
|
||||
* Saves the data to the database
|
||||
*/
|
||||
public void save(Data data, String idField, Object idValue) {
|
||||
asyncPool.execute(() -> {
|
||||
this.asyncPool.execute(() -> {
|
||||
saveSync(data, idField, idValue);
|
||||
});
|
||||
}
|
||||
@ -262,7 +262,7 @@ public class DataManager {
|
||||
* Saves the data to the database
|
||||
*/
|
||||
public void saveSync(Data data, String idField, Object idValue) {
|
||||
databaseConnector.connectDSL(context -> {
|
||||
this.databaseConnector.connectDSL(context -> {
|
||||
context.insertInto(DSL.table(getTablePrefix() + data.getTableName()))
|
||||
.set(data.serialize())
|
||||
.onConflict(DSL.field(idField)).doUpdate()
|
||||
@ -276,7 +276,7 @@ public class DataManager {
|
||||
* Saves the data to the database synchronously
|
||||
*/
|
||||
public void saveSync(Data data) {
|
||||
databaseConnector.connectDSL(context -> {
|
||||
this.databaseConnector.connectDSL(context -> {
|
||||
context.insertInto(DSL.table(getTablePrefix() + data.getTableName()))
|
||||
.set(data.serialize())
|
||||
.onConflict(data.getId() != -1 ? DSL.field("id") : DSL.field("uuid")).doUpdate()
|
||||
@ -290,7 +290,7 @@ public class DataManager {
|
||||
* Saves the data in batch to the database
|
||||
*/
|
||||
public void saveBatch(Collection<Data> dataBatch) {
|
||||
asyncPool.execute(() -> {
|
||||
this.asyncPool.execute(() -> {
|
||||
saveBatchSync(dataBatch);
|
||||
});
|
||||
}
|
||||
@ -299,7 +299,7 @@ public class DataManager {
|
||||
* Saves the data in batch to the database
|
||||
*/
|
||||
public void saveBatchSync(Collection<Data> dataBatch) {
|
||||
databaseConnector.connectDSL(context -> {
|
||||
this.databaseConnector.connectDSL(context -> {
|
||||
List<Query> queries = new ArrayList<>();
|
||||
for (Data data : dataBatch) {
|
||||
queries.add(context.insertInto(DSL.table(getTablePrefix() + data.getTableName()))
|
||||
@ -317,7 +317,7 @@ public class DataManager {
|
||||
* Deletes the data from the database
|
||||
*/
|
||||
public void delete(Data data) {
|
||||
asyncPool.execute(() -> {
|
||||
this.asyncPool.execute(() -> {
|
||||
deleteSync(data);
|
||||
});
|
||||
}
|
||||
@ -326,7 +326,7 @@ public class DataManager {
|
||||
* Deletes the data from the database
|
||||
*/
|
||||
public void deleteSync(Data data) {
|
||||
databaseConnector.connectDSL(context -> {
|
||||
this.databaseConnector.connectDSL(context -> {
|
||||
context.delete(DSL.table(getTablePrefix() + data.getTableName()))
|
||||
.where(data.getId() != -1 ? DSL.field("id").eq(data.getId()) : DSL.field("uuid").eq(data.getUniqueId().toString()))
|
||||
.execute();
|
||||
@ -334,13 +334,13 @@ public class DataManager {
|
||||
}
|
||||
|
||||
public void delete(Data data, String idField, Object idValue) {
|
||||
asyncPool.execute(() -> {
|
||||
this.asyncPool.execute(() -> {
|
||||
deleteSync(data, idField, idValue);
|
||||
});
|
||||
}
|
||||
|
||||
public void deleteSync(Data data, String idField, Object idValue) {
|
||||
databaseConnector.connectDSL(context -> {
|
||||
this.databaseConnector.connectDSL(context -> {
|
||||
context.delete(DSL.table(getTablePrefix() + data.getTableName()))
|
||||
.where(DSL.field(idField).eq(idValue))
|
||||
.execute();
|
||||
@ -351,8 +351,8 @@ public class DataManager {
|
||||
* Deletes the data from the database
|
||||
*/
|
||||
public void delete(Data data, String uuidColumn) {
|
||||
asyncPool.execute(() -> {
|
||||
databaseConnector.connectDSL(context -> {
|
||||
this.asyncPool.execute(() -> {
|
||||
this.databaseConnector.connectDSL(context -> {
|
||||
context.delete(DSL.table(getTablePrefix() + data.getTableName()))
|
||||
.where(data.getId() != -1 ? DSL.field("id").eq(data.getId()) : DSL.field(uuidColumn).eq(data.getUniqueId().toString()))
|
||||
.execute();
|
||||
@ -372,7 +372,7 @@ public class DataManager {
|
||||
try {
|
||||
AtomicReference<Data> data = new AtomicReference<>();
|
||||
AtomicBoolean found = new AtomicBoolean(false);
|
||||
databaseConnector.connectDSL(context -> {
|
||||
this.databaseConnector.connectDSL(context -> {
|
||||
try {
|
||||
Data newData = (Data) clazz.getConstructor().newInstance();
|
||||
data.set(newData.deserialize(Objects.requireNonNull(context.select()
|
||||
@ -410,7 +410,7 @@ public class DataManager {
|
||||
try {
|
||||
AtomicReference<Data> data = new AtomicReference<>();
|
||||
AtomicBoolean found = new AtomicBoolean(false);
|
||||
databaseConnector.connectDSL(context -> {
|
||||
this.databaseConnector.connectDSL(context -> {
|
||||
try {
|
||||
Data newData = (Data) clazz.getConstructor().newInstance();
|
||||
data.set(newData.deserialize(Objects.requireNonNull(context.select()
|
||||
@ -449,7 +449,7 @@ public class DataManager {
|
||||
try {
|
||||
AtomicReference<Data> data = new AtomicReference<>();
|
||||
AtomicBoolean found = new AtomicBoolean(false);
|
||||
databaseConnector.connectDSL(context -> {
|
||||
this.databaseConnector.connectDSL(context -> {
|
||||
try {
|
||||
Data newData = (Data) clazz.getConstructor().newInstance();
|
||||
data.set(newData.deserialize(Objects.requireNonNull(context.select()
|
||||
@ -482,7 +482,7 @@ public class DataManager {
|
||||
public <T extends Data> List<T> loadBatch(Class<?> clazz, String table) {
|
||||
try {
|
||||
List<Data> dataList = Collections.synchronizedList(new ArrayList<>());
|
||||
databaseConnector.connectDSL(context -> {
|
||||
this.databaseConnector.connectDSL(context -> {
|
||||
try {
|
||||
for (@NotNull Record record : Objects.requireNonNull(context.select()
|
||||
.from(DSL.table(getTablePrefix() + table))
|
||||
@ -509,7 +509,7 @@ public class DataManager {
|
||||
public <T extends Data> List<T> loadBatch(Class<?> clazz, String table, Condition... conditions) {
|
||||
try {
|
||||
List<Data> dataList = Collections.synchronizedList(new ArrayList<>());
|
||||
databaseConnector.connectDSL(context -> {
|
||||
this.databaseConnector.connectDSL(context -> {
|
||||
try {
|
||||
for (@NotNull Record record : Objects.requireNonNull(context.select()
|
||||
.from(DSL.table(getTablePrefix() + table))
|
||||
|
@ -31,6 +31,7 @@ public abstract class DataMigration {
|
||||
/**
|
||||
* @param plugin The plugin to convert data for
|
||||
* @param toType The new database type
|
||||
*
|
||||
* @return The new data manager instance
|
||||
*/
|
||||
public static DataManager convert(SongodaPlugin plugin, DatabaseType toType) throws Exception {
|
||||
@ -41,7 +42,7 @@ public abstract class DataMigration {
|
||||
}
|
||||
DataManager to = new DataManager(plugin, Collections.emptyList(), toType);
|
||||
if (!to.getDatabaseConnector().isInitialized()) {
|
||||
plugin.getLogger().severe("Invalid database configuration for " + toType.name() +"! Please check your "+plugin.getName()+"/database.yml file.");
|
||||
plugin.getLogger().severe("Invalid database configuration for " + toType.name() + "! Please check your " + plugin.getName() + "/database.yml file.");
|
||||
return null;
|
||||
}
|
||||
|
||||
@ -56,7 +57,7 @@ public abstract class DataMigration {
|
||||
|
||||
// Export schema
|
||||
DatabaseMetaData meta = fromConnection.getMetaData();
|
||||
ResultSet tables = meta.getTables(null, null, null, new String[]{"TABLE"});
|
||||
ResultSet tables = meta.getTables(null, null, null, new String[] {"TABLE"});
|
||||
|
||||
while (tables.next()) {
|
||||
String tableName = tables.getString("TABLE_NAME");
|
||||
@ -74,7 +75,7 @@ public abstract class DataMigration {
|
||||
String columnType = metaRs.getColumnTypeName(i);
|
||||
int columnSize = metaRs.getColumnDisplaySize(i);
|
||||
//Fix EpicHoppers BIT column type from corrupted db
|
||||
if (columnType.equals("BIT") && plugin.getName().toLowerCase().equals("epichoppers")) {
|
||||
if (columnType.equals("BIT") && plugin.getName().equalsIgnoreCase("epichoppers")) {
|
||||
columnType = "VARCHAR";
|
||||
columnSize = 20;
|
||||
}
|
||||
@ -120,22 +121,22 @@ public abstract class DataMigration {
|
||||
|
||||
toConnection.commit();
|
||||
plugin.getLogger().info("Successfully migrated data from " + from.getDatabaseConnector().getType() + " to " + to.getDatabaseConnector().getType());
|
||||
} catch (Exception e) {
|
||||
} catch (Exception ex) {
|
||||
if (toConnection != null) {
|
||||
try {
|
||||
toConnection.rollback();
|
||||
} catch (SQLException e1) {
|
||||
e1.printStackTrace();
|
||||
} catch (SQLException ex1) {
|
||||
ex1.printStackTrace();
|
||||
plugin.getLogger().severe("Failed to rollback data for the new database");
|
||||
}
|
||||
}
|
||||
e.printStackTrace();
|
||||
ex.printStackTrace();
|
||||
plugin.getLogger().severe("Failed to migrate data from " + from.getDatabaseConnector().getType() + " to " + to.getDatabaseConnector().getType());
|
||||
return null;
|
||||
}
|
||||
fromConnector.closeConnection();
|
||||
//Get rid of the old SQLite database file if it exists and create a backup
|
||||
File databaseFile = new File(plugin.getDataFolder(), plugin.getName().toLowerCase()+".db");
|
||||
File databaseFile = new File(plugin.getDataFolder(), plugin.getName().toLowerCase() + ".db");
|
||||
if (databaseFile.exists()) {
|
||||
|
||||
//rename it to .old
|
||||
@ -159,8 +160,8 @@ public abstract class DataMigration {
|
||||
}
|
||||
|
||||
rs.close();
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
} catch (SQLException ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
|
||||
columns.setLength(columns.length() - 2);
|
||||
@ -168,7 +169,7 @@ public abstract class DataMigration {
|
||||
}
|
||||
|
||||
|
||||
// Utility method to convert byte array to hexadecimal string
|
||||
// Utility method to convert a byte array to hexadecimal string
|
||||
private static String bytesToHex(byte[] bytes) {
|
||||
StringBuilder hexString = new StringBuilder();
|
||||
for (byte b : bytes) {
|
||||
|
@ -29,6 +29,7 @@ public interface DatabaseConnector {
|
||||
* Executes a callback with a Connection passed and automatically closes it when finished
|
||||
*
|
||||
* @param callback The callback to execute once the connection is retrieved
|
||||
*
|
||||
* @return The result of the callback
|
||||
*/
|
||||
OptionalResult connectOptional(ConnectionOptionalCallback callback);
|
||||
@ -44,6 +45,7 @@ public interface DatabaseConnector {
|
||||
* Executes a callback with a DSLContext passed and automatically closes it when finished
|
||||
*
|
||||
* @param callback The callback to execute once the connection is retrieved
|
||||
*
|
||||
* @return The result of the callback
|
||||
*/
|
||||
OptionalResult connectDSLOptional(DSLContextOptionalCallback callback);
|
||||
@ -82,12 +84,14 @@ public interface DatabaseConnector {
|
||||
|
||||
/**
|
||||
* Gets a connection from the database
|
||||
*
|
||||
* @return The connection
|
||||
*/
|
||||
Connection getConnection() throws SQLException;
|
||||
|
||||
/**
|
||||
* Gets the database type
|
||||
*
|
||||
* @return The database type
|
||||
*/
|
||||
DatabaseType getType();
|
||||
|
@ -3,7 +3,6 @@ package com.craftaro.core.database;
|
||||
import org.jooq.SQLDialect;
|
||||
|
||||
public enum DatabaseType {
|
||||
|
||||
MARIADB,
|
||||
MYSQL,
|
||||
H2,
|
||||
|
@ -12,7 +12,6 @@ import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class MariaDBConnector implements DatabaseConnector {
|
||||
|
||||
private final SongodaPlugin plugin;
|
||||
private HikariDataSource hikari;
|
||||
private boolean initializedSuccessfully;
|
||||
@ -78,7 +77,7 @@ public class MariaDBConnector implements DatabaseConnector {
|
||||
try (Connection connection = getConnection()) {
|
||||
return callback.accept(connection);
|
||||
} catch (Exception ex) {
|
||||
SongodaCore.getInstance().getLogger().severe("An error occurred executing a MariaDB query: " + ex.getMessage());
|
||||
SongodaCore.getLogger().severe("An error occurred executing a MariaDB query: " + ex.getMessage());
|
||||
ex.printStackTrace();
|
||||
}
|
||||
return OptionalResult.empty();
|
||||
@ -99,7 +98,7 @@ public class MariaDBConnector implements DatabaseConnector {
|
||||
try (Connection connection = getConnection()) {
|
||||
return callback.accept(DSL.using(connection, SQLDialect.MARIADB));
|
||||
} catch (Exception ex) {
|
||||
SongodaCore.getInstance().getLogger().severe("An error occurred executing a MariaDB query: " + ex.getMessage());
|
||||
SongodaCore.getLogger().severe("An error occurred executing a MariaDB query: " + ex.getMessage());
|
||||
ex.printStackTrace();
|
||||
}
|
||||
return OptionalResult.empty();
|
||||
|
@ -73,7 +73,7 @@ public class MySQLConnector implements DatabaseConnector {
|
||||
try (Connection connection = getConnection()) {
|
||||
return callback.accept(connection);
|
||||
} catch (Exception ex) {
|
||||
SongodaCore.getInstance().getLogger().severe("An error occurred executing a MySQL query: " + ex.getMessage());
|
||||
SongodaCore.getLogger().severe("An error occurred executing a MySQL query: " + ex.getMessage());
|
||||
ex.printStackTrace();
|
||||
}
|
||||
return OptionalResult.empty();
|
||||
@ -81,7 +81,7 @@ public class MySQLConnector implements DatabaseConnector {
|
||||
|
||||
@Override
|
||||
public void connectDSL(DSLContextCallback callback) {
|
||||
try (Connection connection = getConnection()){
|
||||
try (Connection connection = getConnection()) {
|
||||
callback.accept(DSL.using(connection, SQLDialect.MYSQL));
|
||||
} catch (Exception ex) {
|
||||
this.plugin.getLogger().severe("An error occurred executing a MySQL query: " + ex.getMessage());
|
||||
@ -94,7 +94,7 @@ public class MySQLConnector implements DatabaseConnector {
|
||||
try (Connection connection = getConnection()) {
|
||||
return callback.accept(DSL.using(connection, SQLDialect.MYSQL));
|
||||
} catch (Exception ex) {
|
||||
SongodaCore.getInstance().getLogger().severe("An error occurred executing a MySQL query: " + ex.getMessage());
|
||||
SongodaCore.getLogger().severe("An error occurred executing a MySQL query: " + ex.getMessage());
|
||||
ex.printStackTrace();
|
||||
}
|
||||
return OptionalResult.empty();
|
||||
|
@ -1,7 +1,6 @@
|
||||
package com.craftaro.core.database;
|
||||
|
||||
public class OptionalResult {
|
||||
|
||||
private final Object value;
|
||||
private final boolean present;
|
||||
|
||||
@ -11,15 +10,15 @@ public class OptionalResult {
|
||||
}
|
||||
|
||||
public <T> T get(Class<T> clazz) {
|
||||
return clazz.cast(value);
|
||||
return clazz.cast(this.value);
|
||||
}
|
||||
|
||||
public boolean isPresent() {
|
||||
return present;
|
||||
return this.present;
|
||||
}
|
||||
|
||||
public <V> V getOrDefault(V defaultValue) {
|
||||
return present ? (V) value : defaultValue;
|
||||
return this.present ? (V) this.value : defaultValue;
|
||||
}
|
||||
|
||||
public static OptionalResult empty() {
|
||||
|
@ -18,7 +18,7 @@ public class SQLiteConnector implements DatabaseConnector {
|
||||
|
||||
SQLiteConnector() {
|
||||
this.plugin = null;
|
||||
this.connectionString = "jdbc:sqlite:" + "."+File.separator+"db_test"+File.separator+"CraftaroCoreTestSQLite.db";
|
||||
this.connectionString = "jdbc:sqlite:" + "." + File.separator + "db_test" + File.separator + "CraftaroCoreTestSQLite.db";
|
||||
}
|
||||
|
||||
public SQLiteConnector(Plugin plugin) {
|
||||
@ -63,7 +63,7 @@ public class SQLiteConnector implements DatabaseConnector {
|
||||
try (Connection connection = getConnection()) {
|
||||
return callback.accept(connection);
|
||||
} catch (Exception ex) {
|
||||
SongodaCore.getInstance().getLogger().severe("An error occurred executing a SQLite query: " + ex.getMessage());
|
||||
SongodaCore.getLogger().severe("An error occurred executing a SQLite query: " + ex.getMessage());
|
||||
ex.printStackTrace();
|
||||
}
|
||||
return OptionalResult.empty();
|
||||
@ -71,7 +71,7 @@ public class SQLiteConnector implements DatabaseConnector {
|
||||
|
||||
@Override
|
||||
public void connectDSL(DSLContextCallback callback) {
|
||||
try (Connection connection = getConnection()){
|
||||
try (Connection connection = getConnection()) {
|
||||
callback.accept(DSL.using(connection, SQLDialect.SQLITE));
|
||||
} catch (Exception ex) {
|
||||
this.plugin.getLogger().severe("An error occurred executing a SQLite query: " + ex.getMessage());
|
||||
@ -84,7 +84,7 @@ public class SQLiteConnector implements DatabaseConnector {
|
||||
try (Connection connection = getConnection()) {
|
||||
return callback.accept(DSL.using(connection, SQLDialect.SQLITE));
|
||||
} catch (Exception ex) {
|
||||
SongodaCore.getInstance().getLogger().severe("An error occurred executing a SQLite query: " + ex.getMessage());
|
||||
SongodaCore.getLogger().severe("An error occurred executing a SQLite query: " + ex.getMessage());
|
||||
ex.printStackTrace();
|
||||
}
|
||||
return OptionalResult.empty();
|
||||
|
@ -7,13 +7,12 @@ import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class SerializedLocation {
|
||||
|
||||
private String world;
|
||||
private double x;
|
||||
private double y;
|
||||
private double z;
|
||||
private float pitch = 0;
|
||||
private float yaw = 0;
|
||||
private final String world;
|
||||
private final double x;
|
||||
private final double y;
|
||||
private final double z;
|
||||
private final float pitch;
|
||||
private final float yaw;
|
||||
|
||||
public SerializedLocation(Location location) {
|
||||
this.world = location.getWorld().getName();
|
||||
@ -23,6 +22,9 @@ public class SerializedLocation {
|
||||
if (location.getPitch() != 0 && location.getYaw() != 0) {
|
||||
this.pitch = location.getPitch();
|
||||
this.yaw = location.getYaw();
|
||||
} else {
|
||||
this.pitch = 0;
|
||||
this.yaw = 0;
|
||||
}
|
||||
}
|
||||
|
||||
@ -31,8 +33,8 @@ public class SerializedLocation {
|
||||
(double) map.get("x"),
|
||||
(double) map.get("y"),
|
||||
(double) map.get("z"),
|
||||
Double.valueOf((double)map.getOrDefault("yaw", 0.0)).floatValue(),
|
||||
Double.valueOf((double)map.getOrDefault("pitch", 0.0)).floatValue());
|
||||
Double.valueOf((double) map.getOrDefault("yaw", 0.0)).floatValue(),
|
||||
Double.valueOf((double) map.getOrDefault("pitch", 0.0)).floatValue());
|
||||
}
|
||||
|
||||
public static Map<String, Object> of(Location location) {
|
||||
@ -49,18 +51,18 @@ public class SerializedLocation {
|
||||
}
|
||||
|
||||
public Location asLocation() {
|
||||
return new Location(Bukkit.getWorld(world), x, y, z, yaw, pitch);
|
||||
return new Location(Bukkit.getWorld(this.world), this.x, this.y, this.z, this.yaw, this.pitch);
|
||||
}
|
||||
|
||||
public Map<String, Object> asMap() {
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("world", world);
|
||||
map.put("x", x);
|
||||
map.put("y", y);
|
||||
map.put("z", z);
|
||||
if (pitch != 0 && yaw != 0) {
|
||||
map.put("pitch", pitch);
|
||||
map.put("yaw", yaw);
|
||||
map.put("world", this.world);
|
||||
map.put("x", this.x);
|
||||
map.put("y", this.y);
|
||||
map.put("z", this.z);
|
||||
if (this.pitch != 0 && this.yaw != 0) {
|
||||
map.put("pitch", this.pitch);
|
||||
map.put("yaw", this.yaw);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
@ -48,7 +48,7 @@ public class Dependency {
|
||||
this.artifactId = artifactId;
|
||||
this.version = version;
|
||||
if (baseRelocate) {
|
||||
//Add base relocate
|
||||
// Add base relocate
|
||||
this.relocations.add(new Relocation(groupId, "com.craftaro.third_party." + groupId));
|
||||
}
|
||||
if (extraRelocations.length > 0) {
|
||||
|
@ -28,7 +28,7 @@ public class DependencyLoader {
|
||||
private final ClassLoaderAccess parentClassLoaderAccess;
|
||||
|
||||
public DependencyLoader(Plugin plugin) {
|
||||
//Bind loaded dependencies to the plugin's parent class loader so classes could be accessed across plugins
|
||||
// Bind loaded dependencies to the plugin's parent class loader so classes could be accessed across plugins
|
||||
ClassLoader parentClassLoader = plugin.getClass().getClassLoader().getParent();
|
||||
if (parentClassLoader instanceof URLClassLoader) {
|
||||
this.libraryLoader = new LibraryLoader(
|
||||
@ -38,7 +38,7 @@ public class DependencyLoader {
|
||||
);
|
||||
this.parentClassLoaderAccess = new ClassLoaderAccess((URLClassLoader) parentClassLoader);
|
||||
} else {
|
||||
//We have AppClassLoader here
|
||||
// We have AppClassLoader here
|
||||
this.libraryLoader = new LibraryLoader(
|
||||
parentClassLoader,
|
||||
new File(plugin.getDataFolder().getParentFile(), CraftaroCoreConstants.getProjectName() + "/dependencies/v" + DEPENDENCY_VERSION),
|
||||
@ -108,11 +108,11 @@ public class DependencyLoader {
|
||||
}
|
||||
|
||||
try {
|
||||
//Do not check path here, it uses the original non relocated paths. Use isJarLoaded instead
|
||||
// Do not check the path here, it uses the original non-relocated paths. Use isJarLoaded instead
|
||||
this.libraryLoader.load(new LibraryLoader.Dependency(dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion(), dependency.getRepositoryUrl()), false);
|
||||
} catch (Exception e) {
|
||||
} catch (Exception ex) {
|
||||
// Something went wrong
|
||||
e.printStackTrace();
|
||||
ex.printStackTrace();
|
||||
}
|
||||
SongodaCore.getLogger().info("----------------------------");
|
||||
}
|
||||
|
@ -44,7 +44,7 @@ public class AnvilGui extends Gui {
|
||||
}
|
||||
|
||||
protected void open() {
|
||||
anvil.open();
|
||||
this.anvil.open();
|
||||
}
|
||||
|
||||
public AnvilGui setInput(ItemStack item) {
|
||||
@ -60,26 +60,26 @@ public class AnvilGui extends Gui {
|
||||
}
|
||||
|
||||
public AnvilGui setOutputPrompt(String str) {
|
||||
endPrompt = Arrays.asList(str);
|
||||
this.endPrompt = Arrays.asList(str);
|
||||
return this;
|
||||
}
|
||||
|
||||
public AnvilGui setOutputPrompt(String... str) {
|
||||
endPrompt = Arrays.asList(str);
|
||||
this.endPrompt = Arrays.asList(str);
|
||||
return this;
|
||||
}
|
||||
|
||||
public AnvilGui setOutputPrompt(List<String> str) {
|
||||
endPrompt = str;
|
||||
this.endPrompt = str;
|
||||
return this;
|
||||
}
|
||||
|
||||
void updateOutputPrompt() {
|
||||
if (endPrompt != null) {
|
||||
ItemStack in = cellItems.get(0);
|
||||
if (this.endPrompt != null) {
|
||||
ItemStack in = this.cellItems.get(0);
|
||||
|
||||
if (in != null) {
|
||||
setItem(2, GuiUtils.createButtonItem(in, endPrompt));
|
||||
setItem(2, GuiUtils.createButtonItem(in, this.endPrompt));
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -89,7 +89,7 @@ public class AnvilGui extends Gui {
|
||||
}
|
||||
|
||||
public String getInputText() {
|
||||
return anvil != null ? anvil.getRenameText() : null;
|
||||
return this.anvil != null ? this.anvil.getRenameText() : null;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@ -99,42 +99,40 @@ public class AnvilGui extends Gui {
|
||||
|
||||
createInventory();
|
||||
ItemStack item;
|
||||
if (cellItems.containsKey(0)) {
|
||||
item = cellItems.get(0);
|
||||
if (this.cellItems.containsKey(0)) {
|
||||
item = this.cellItems.get(0);
|
||||
|
||||
inventory.setItem(0, item);
|
||||
} else if (cellItems.containsKey(1)) {
|
||||
item = cellItems.get(1);
|
||||
this.inventory.setItem(0, item);
|
||||
} else if (this.cellItems.containsKey(1)) {
|
||||
item = this.cellItems.get(1);
|
||||
|
||||
inventory.setItem(1, item);
|
||||
} else if (!acceptsItems) {
|
||||
this.inventory.setItem(1, item);
|
||||
} else if (!this.acceptsItems) {
|
||||
item = GuiUtils.createButtonItem(XMaterial.PAPER, " ", " ");
|
||||
|
||||
cellItems.put(0, item);
|
||||
inventory.setItem(0, item);
|
||||
this.cellItems.put(0, item);
|
||||
this.inventory.setItem(0, item);
|
||||
}
|
||||
|
||||
if (cellItems.containsKey(2)) {
|
||||
item = cellItems.get(2);
|
||||
if (this.cellItems.containsKey(2)) {
|
||||
item = this.cellItems.get(2);
|
||||
|
||||
inventory.setItem(2, item);
|
||||
this.inventory.setItem(2, item);
|
||||
}
|
||||
|
||||
return inventory;
|
||||
return this.inventory;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void createInventory() {
|
||||
AnvilCore nms = Nms.getImplementations().getAnvil();
|
||||
|
||||
if (nms != null) {
|
||||
anvil = nms.createAnvil(player, new GuiHolder(guiManager, this));
|
||||
anvil.setCustomTitle(title);
|
||||
anvil.setLevelCost(0);
|
||||
this.anvil = nms.createAnvil(this.player, new GuiHolder(this.guiManager, this));
|
||||
this.anvil.setCustomTitle(this.title);
|
||||
this.anvil.setLevelCost(0);
|
||||
|
||||
inventory = anvil.getInventory();
|
||||
this.inventory = this.anvil.getInventory();
|
||||
|
||||
anvil.setOnChange(this::updateOutputPrompt);
|
||||
}
|
||||
this.anvil.setOnChange(this::updateOutputPrompt);
|
||||
}
|
||||
}
|
||||
|
@ -29,7 +29,7 @@ public class CustomizableGui extends Gui {
|
||||
private static boolean showGuiKeys = false;
|
||||
private int activationCount = 0;
|
||||
|
||||
private static final Map<String, CustomContent> loadedGuis = new HashMap<>();
|
||||
private static final Map<String, CustomContent> LOADED_GUIS = new HashMap<>();
|
||||
private final CustomContent customContent;
|
||||
|
||||
public CustomizableGui(Plugin plugin, String guiKey) {
|
||||
@ -39,9 +39,8 @@ public class CustomizableGui extends Gui {
|
||||
public CustomizableGui(@NotNull Plugin plugin, @NotNull String guiKey, @Nullable Gui parent) {
|
||||
super(parent);
|
||||
|
||||
if (!loadedGuis.containsKey(guiKey) || showGuiKeys) {
|
||||
if (!LOADED_GUIS.containsKey(guiKey) || showGuiKeys) {
|
||||
File localeFolder = new File(plugin.getDataFolder(), "gui/");
|
||||
|
||||
if (!localeFolder.exists()) {
|
||||
localeFolder.mkdir();
|
||||
}
|
||||
@ -74,8 +73,8 @@ public class CustomizableGui extends Gui {
|
||||
config.saveChanges();
|
||||
}
|
||||
|
||||
CustomContent customContent = loadedGuis.computeIfAbsent(guiKey, g -> new CustomContent(guiKey));
|
||||
loadedGuis.put(guiKey, customContent);
|
||||
CustomContent customContent = LOADED_GUIS.computeIfAbsent(guiKey, g -> new CustomContent(guiKey));
|
||||
LOADED_GUIS.put(guiKey, customContent);
|
||||
this.customContent = customContent;
|
||||
|
||||
int rows = config.getInt("overrides.__ROWS__", -1);
|
||||
@ -113,7 +112,7 @@ public class CustomizableGui extends Gui {
|
||||
customContent.disableButton(disabled);
|
||||
}
|
||||
} else {
|
||||
this.customContent = loadedGuis.get(guiKey);
|
||||
this.customContent = LOADED_GUIS.get(guiKey);
|
||||
}
|
||||
|
||||
setPrivateDefaultAction(event -> {
|
||||
|
@ -15,6 +15,7 @@ import org.bukkit.event.inventory.ClickType;
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
@ -288,7 +289,7 @@ public class DoubleGui extends Gui {
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean onClickPlayerInventory(GuiManager manager, Player player, Inventory openInv, InventoryClickEvent event) {
|
||||
protected boolean onClickPlayerInventory(@NotNull GuiManager manager, @NotNull Player player, @NotNull Inventory openInv, InventoryClickEvent event) {
|
||||
final int cell = event.getSlot(), offsetCell = clickOffset(cell);
|
||||
Map<ClickType, Clickable> conditionals = this.conditionalButtons.get(offsetCell);
|
||||
Clickable button;
|
||||
@ -307,7 +308,7 @@ public class DoubleGui extends Gui {
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean onClickOutside(GuiManager manager, Player player, InventoryClickEvent event) {
|
||||
protected boolean onClickOutside(@NotNull GuiManager manager, @NotNull Player player, @NotNull InventoryClickEvent event) {
|
||||
if (this.dropper != null) {
|
||||
return this.dropper.onDrop(new GuiDropItemEvent(manager, this, player, event));
|
||||
}
|
||||
@ -317,7 +318,7 @@ public class DoubleGui extends Gui {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onOpen(GuiManager manager, Player player) {
|
||||
public void onOpen(@NotNull GuiManager manager, @NotNull Player player) {
|
||||
// replace the player's inventory
|
||||
if (this.startStashed) {
|
||||
stashItems(player);
|
||||
@ -328,7 +329,7 @@ public class DoubleGui extends Gui {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClose(GuiManager manager, Player player) {
|
||||
public void onClose(@NotNull GuiManager manager, @NotNull Player player) {
|
||||
// restore the player's inventory
|
||||
restoreStash(player);
|
||||
|
||||
@ -361,32 +362,32 @@ public class DoubleGui extends Gui {
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui setUnlocked(int cell) {
|
||||
public @NotNull DoubleGui setUnlocked(int cell) {
|
||||
return (DoubleGui) super.setUnlocked(cell);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui setUnlocked(int cell, boolean open) {
|
||||
public @NotNull DoubleGui setUnlocked(int cell, boolean open) {
|
||||
return (DoubleGui) super.setUnlocked(cell, open);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui setUnlocked(int row, int col) {
|
||||
public @NotNull DoubleGui setUnlocked(int row, int col) {
|
||||
return (DoubleGui) super.setUnlocked(row, col);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui setUnlocked(int row, int col, boolean open) {
|
||||
public @NotNull DoubleGui setUnlocked(int row, int col, boolean open) {
|
||||
return (DoubleGui) super.setUnlocked(row, col, open);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui setUnlockedRange(int cellFirst, int cellLast) {
|
||||
public @NotNull DoubleGui setUnlockedRange(int cellFirst, int cellLast) {
|
||||
return (DoubleGui) super.setUnlockedRange(cellFirst, cellLast);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui setUnlockedRange(int cellRowFirst, int cellColFirst, int cellRowLast, int cellColLast) {
|
||||
public @NotNull DoubleGui setUnlockedRange(int cellRowFirst, int cellColFirst, int cellRowLast, int cellColLast) {
|
||||
return (DoubleGui) super.setUnlockedRange(cellRowFirst, cellColFirst, cellRowLast, cellColLast);
|
||||
}
|
||||
|
||||
@ -401,192 +402,192 @@ public class DoubleGui extends Gui {
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui setTitle(String title) {
|
||||
public @NotNull DoubleGui setTitle(String title) {
|
||||
return (DoubleGui) super.setTitle(title);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui setRows(int rows) {
|
||||
public @NotNull DoubleGui setRows(int rows) {
|
||||
return (DoubleGui) super.setRows(rows);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui setDefaultItem(ItemStack item) {
|
||||
public @NotNull DoubleGui setDefaultItem(ItemStack item) {
|
||||
return (DoubleGui) super.setDefaultItem(item);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui setItem(int cell, ItemStack item) {
|
||||
public @NotNull DoubleGui setItem(int cell, ItemStack item) {
|
||||
return (DoubleGui) super.setItem(cell, item);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui setItem(int row, int col, ItemStack item) {
|
||||
public @NotNull DoubleGui setItem(int row, int col, ItemStack item) {
|
||||
return (DoubleGui) super.setItem(row, col, item);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui highlightItem(int cell) {
|
||||
public @NotNull DoubleGui highlightItem(int cell) {
|
||||
return (DoubleGui) super.highlightItem(cell);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui highlightItem(int row, int col) {
|
||||
public @NotNull DoubleGui highlightItem(int row, int col) {
|
||||
return (DoubleGui) super.highlightItem(row, col);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui updateItem(int cell, String name, String... lore) {
|
||||
public @NotNull DoubleGui updateItem(int cell, String name, String... lore) {
|
||||
return (DoubleGui) super.updateItem(cell, name, lore);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui updateItem(int row, int col, String name, List<String> lore) {
|
||||
public @NotNull DoubleGui updateItem(int row, int col, String name, List<String> lore) {
|
||||
return (DoubleGui) super.updateItem(col + row * 9, name, lore);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui updateItem(int cell, String name, List<String> lore) {
|
||||
public @NotNull DoubleGui updateItem(int cell, @NotNull String name, List<String> lore) {
|
||||
return (DoubleGui) super.updateItem(cell, name, lore);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui updateItem(int row, int col, ItemStack itemTo, String title, String... lore) {
|
||||
public @NotNull DoubleGui updateItem(int row, int col, @NotNull ItemStack itemTo, String title, String... lore) {
|
||||
return (DoubleGui) super.updateItem(col + row * 9, itemTo, title, lore);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui updateItem(int cell, ItemStack itemTo, String title, String... lore) {
|
||||
public @NotNull DoubleGui updateItem(int cell, @NotNull ItemStack itemTo, String title, String... lore) {
|
||||
return (DoubleGui) super.updateItem(cell, itemTo, title, lore);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui updateItem(int row, int col, XMaterial itemTo, String title, String... lore) {
|
||||
public @NotNull DoubleGui updateItem(int row, int col, @NotNull XMaterial itemTo, String title, String... lore) {
|
||||
return (DoubleGui) super.updateItem(col + row * 9, itemTo, title, lore);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui updateItem(int cell, XMaterial itemTo, String title, String... lore) {
|
||||
public @NotNull DoubleGui updateItem(int cell, @NotNull XMaterial itemTo, String title, String... lore) {
|
||||
return (DoubleGui) super.updateItem(cell, itemTo, title, lore);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui updateItem(int row, int col, ItemStack itemTo, String title, List<String> lore) {
|
||||
public @NotNull DoubleGui updateItem(int row, int col, @NotNull ItemStack itemTo, String title, List<String> lore) {
|
||||
return (DoubleGui) super.updateItem(col + row * 9, itemTo, title, lore);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui updateItem(int cell, ItemStack itemTo, String title, List<String> lore) {
|
||||
public @NotNull DoubleGui updateItem(int cell, @NotNull ItemStack itemTo, String title, List<String> lore) {
|
||||
return (DoubleGui) super.updateItem(cell, itemTo, title, lore);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui updateItem(int row, int col, XMaterial itemTo, String title, List<String> lore) {
|
||||
public @NotNull DoubleGui updateItem(int row, int col, @NotNull XMaterial itemTo, String title, List<String> lore) {
|
||||
return (DoubleGui) super.updateItem(col + row * 9, itemTo, title, lore);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui updateItem(int cell, XMaterial itemTo, String title, List<String> lore) {
|
||||
public @NotNull DoubleGui updateItem(int cell, @NotNull XMaterial itemTo, String title, List<String> lore) {
|
||||
return (DoubleGui) super.updateItem(cell, itemTo, title, lore);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui setAction(int cell, Clickable action) {
|
||||
public @NotNull DoubleGui setAction(int cell, Clickable action) {
|
||||
return (DoubleGui) super.setAction(cell, action);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui setAction(int row, int col, Clickable action) {
|
||||
public @NotNull DoubleGui setAction(int row, int col, Clickable action) {
|
||||
return (DoubleGui) super.setAction(row, col, action);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui setAction(int cell, ClickType type, Clickable action) {
|
||||
public @NotNull DoubleGui setAction(int cell, ClickType type, Clickable action) {
|
||||
return (DoubleGui) super.setAction(cell, type, action);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui setAction(int row, int col, ClickType type, Clickable action) {
|
||||
public @NotNull DoubleGui setAction(int row, int col, ClickType type, Clickable action) {
|
||||
return (DoubleGui) super.setAction(row, col, type, action);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui setActionForRange(int cellFirst, int cellLast, Clickable action) {
|
||||
public @NotNull DoubleGui setActionForRange(int cellFirst, int cellLast, Clickable action) {
|
||||
return (DoubleGui) super.setActionForRange(cellFirst, cellLast, action);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui setActionForRange(int cellRowFirst, int cellColFirst, int cellRowLast, int cellColLast, Clickable action) {
|
||||
public @NotNull DoubleGui setActionForRange(int cellRowFirst, int cellColFirst, int cellRowLast, int cellColLast, Clickable action) {
|
||||
return (DoubleGui) super.setActionForRange(cellRowFirst, cellColFirst, cellRowLast, cellColLast, action);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui setActionForRange(int cellFirst, int cellLast, ClickType type, Clickable action) {
|
||||
public @NotNull DoubleGui setActionForRange(int cellFirst, int cellLast, ClickType type, Clickable action) {
|
||||
return (DoubleGui) super.setActionForRange(cellFirst, cellLast, type, action);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui setActionForRange(int cellRowFirst, int cellColFirst, int cellRowLast, int cellColLast, ClickType type, Clickable action) {
|
||||
public @NotNull DoubleGui setActionForRange(int cellRowFirst, int cellColFirst, int cellRowLast, int cellColLast, ClickType type, Clickable action) {
|
||||
return (DoubleGui) super.setActionForRange(cellRowFirst, cellColFirst, cellRowLast, cellColLast, type, action);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui clearActions(int cell) {
|
||||
public @NotNull DoubleGui clearActions(int cell) {
|
||||
return (DoubleGui) super.clearActions(cell);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui clearActions(int row, int col) {
|
||||
public @NotNull DoubleGui clearActions(int row, int col) {
|
||||
return (DoubleGui) super.clearActions(row, col);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui setButton(int cell, ItemStack item, Clickable action) {
|
||||
public @NotNull DoubleGui setButton(int cell, ItemStack item, Clickable action) {
|
||||
return (DoubleGui) super.setButton(cell, item, action);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui setButton(int row, int col, ItemStack item, Clickable action) {
|
||||
public @NotNull DoubleGui setButton(int row, int col, ItemStack item, Clickable action) {
|
||||
return (DoubleGui) super.setButton(row, col, item, action);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui setButton(int cell, ItemStack item, ClickType type, Clickable action) {
|
||||
public @NotNull DoubleGui setButton(int cell, ItemStack item, ClickType type, Clickable action) {
|
||||
return (DoubleGui) super.setButton(cell, item, type, action);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui setButton(int row, int col, ItemStack item, ClickType type, Clickable action) {
|
||||
public @NotNull DoubleGui setButton(int row, int col, ItemStack item, ClickType type, Clickable action) {
|
||||
return (DoubleGui) super.setButton(row, col, item, type, action);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui setOnOpen(Openable action) {
|
||||
public @NotNull DoubleGui setOnOpen(Openable action) {
|
||||
return (DoubleGui) super.setOnOpen(action);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui setOnClose(Closable action) {
|
||||
public @NotNull DoubleGui setOnClose(Closable action) {
|
||||
return (DoubleGui) super.setOnClose(action);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui setOnDrop(Droppable action) {
|
||||
public @NotNull DoubleGui setOnDrop(Droppable action) {
|
||||
return (DoubleGui) super.setOnDrop(action);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui setOnPage(Pagable action) {
|
||||
public @NotNull DoubleGui setOnPage(Pagable action) {
|
||||
return (DoubleGui) super.setOnPage(action);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui setNextPage(int row, int col, ItemStack item) {
|
||||
public @NotNull DoubleGui setNextPage(int row, int col, @NotNull ItemStack item) {
|
||||
return (DoubleGui) super.setNextPage(row, col, item);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleGui setPrevPage(int row, int col, ItemStack item) {
|
||||
public @NotNull DoubleGui setPrevPage(int row, int col, @NotNull ItemStack item) {
|
||||
return (DoubleGui) super.setPrevPage(row, col, item);
|
||||
}
|
||||
}
|
||||
|
@ -896,7 +896,7 @@ public class Gui {
|
||||
}
|
||||
|
||||
if (ServerVersion.isServerVersionAtOrBelow(ServerVersion.V1_8) && title.length() > 32) {
|
||||
return title.charAt(30) == '\u00A7' ? title.substring(0, 30) : title.substring(0, 31);
|
||||
return title.charAt(30) == '§' ? title.substring(0, 30) : title.substring(0, 31);
|
||||
}
|
||||
|
||||
return title;
|
||||
@ -932,7 +932,7 @@ public class Gui {
|
||||
return true;
|
||||
}
|
||||
|
||||
protected boolean onClickPlayerInventory(@NotNull GuiManager manager, @NotNull Player player, @NotNull Inventory openInv, @NotNull InventoryClickEvent event) {
|
||||
protected boolean onClickPlayerInventory(@NotNull GuiManager manager, @NotNull Player player, @NotNull Inventory openInv, InventoryClickEvent event) {
|
||||
// no events for this yet
|
||||
return false;
|
||||
}
|
||||
|
@ -8,9 +8,9 @@ public enum GuiType {
|
||||
HOPPER(InventoryType.HOPPER, 5, 1),
|
||||
FURNACE(InventoryType.FURNACE, 3, 2);
|
||||
|
||||
protected final InventoryType type;
|
||||
protected final int rows;
|
||||
protected final int columns;
|
||||
final InventoryType type;
|
||||
final int rows;
|
||||
final int columns;
|
||||
|
||||
GuiType(InventoryType type, int rows, int columns) {
|
||||
this.type = type;
|
||||
|
@ -56,8 +56,8 @@ public class GuiUtils {
|
||||
// fix newlines
|
||||
ArrayList<String> newLore = new ArrayList<>();
|
||||
|
||||
for (String l : lines) {
|
||||
for (String l2 : l.split("\n")) {
|
||||
for (String line : lines) {
|
||||
for (String l2 : line.split("\n")) {
|
||||
if (l2.length() < 54) {
|
||||
newLore.add(l2);
|
||||
continue;
|
||||
@ -66,7 +66,7 @@ public class GuiUtils {
|
||||
// try to shorten the string
|
||||
String shorterString = l2;
|
||||
ChatColor lastColor = null; // todo? probably should also track formatting codes..
|
||||
int line = 0;
|
||||
int lineNumber = 0;
|
||||
while (shorterString.length() > 50) {
|
||||
int breakingSpace = -1;
|
||||
|
||||
@ -80,18 +80,18 @@ public class GuiUtils {
|
||||
|
||||
if (breakingSpace == -1) {
|
||||
breakingSpace = Math.max(50, shorterString.length());
|
||||
newLore.add((line != 0 && lastColor != null ? lastColor.toString() : "") + shorterString.substring(0, breakingSpace) + "-");
|
||||
newLore.add((lineNumber != 0 && lastColor != null ? lastColor.toString() : "") + shorterString.substring(0, breakingSpace) + "-");
|
||||
shorterString = breakingSpace == shorterString.length() ? "" : shorterString.substring(breakingSpace + 1);
|
||||
} else {
|
||||
newLore.add((line != 0 && lastColor != null ? lastColor.toString() : "") + shorterString.substring(0, breakingSpace));
|
||||
newLore.add((lineNumber != 0 && lastColor != null ? lastColor.toString() : "") + shorterString.substring(0, breakingSpace));
|
||||
shorterString = breakingSpace == shorterString.length() ? "" : shorterString.substring(breakingSpace + 1);
|
||||
}
|
||||
|
||||
++line;
|
||||
++lineNumber;
|
||||
}
|
||||
|
||||
if (!shorterString.isEmpty()) {
|
||||
newLore.add((line != 0 && lastColor != null ? lastColor.toString() : "") + " " + shorterString);
|
||||
newLore.add((lineNumber != 0 && lastColor != null ? lastColor.toString() : "") + " " + shorterString);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -24,8 +24,8 @@ import java.util.UUID;
|
||||
* Calling this class on anything below 1.12 will cause ClassLoader Exceptions!
|
||||
*/
|
||||
class PopupMessage {
|
||||
private static final Gson gson = new GsonBuilder().setPrettyPrinting().create();
|
||||
private static final HashSet<UUID> registeredMessages = new HashSet<>();
|
||||
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
|
||||
private static final HashSet<UUID> REGISTERED_MESSAGES = new HashSet<>();
|
||||
|
||||
final UUID id = UUID.randomUUID();
|
||||
private final NamespacedKey key;
|
||||
@ -63,7 +63,7 @@ class PopupMessage {
|
||||
advDisplay.add("icon", displayIcon);
|
||||
}
|
||||
|
||||
advDisplay.add("title", gson.fromJson(ComponentSerializer.toString(this.title), JsonElement.class));
|
||||
advDisplay.add("title", GSON.fromJson(ComponentSerializer.toString(this.title), JsonElement.class));
|
||||
advDisplay.addProperty("background", this.background.key);
|
||||
advDisplay.addProperty("description", "");
|
||||
advDisplay.addProperty("frame", this.frame.id);
|
||||
@ -84,7 +84,7 @@ class PopupMessage {
|
||||
}*/
|
||||
advCriteria.add("mentioned", advTrigger);
|
||||
|
||||
return gson.toJson(json);
|
||||
return GSON.toJson(json);
|
||||
}
|
||||
|
||||
protected void grant(final Player pl) {
|
||||
@ -110,8 +110,8 @@ class PopupMessage {
|
||||
}
|
||||
|
||||
protected void add() {
|
||||
if (!registeredMessages.contains(this.id)) {
|
||||
registeredMessages.add(this.id);
|
||||
if (!REGISTERED_MESSAGES.contains(this.id)) {
|
||||
REGISTERED_MESSAGES.add(this.id);
|
||||
|
||||
try {
|
||||
Bukkit.getUnsafe().loadAdvancement(this.key, getJSON());
|
||||
@ -122,8 +122,8 @@ class PopupMessage {
|
||||
}
|
||||
|
||||
protected void remove() {
|
||||
if (registeredMessages.contains(this.id)) {
|
||||
registeredMessages.remove(this.id);
|
||||
if (REGISTERED_MESSAGES.contains(this.id)) {
|
||||
REGISTERED_MESSAGES.remove(this.id);
|
||||
Bukkit.getUnsafe().removeAdvancement(this.key);
|
||||
}
|
||||
}
|
||||
|
@ -9,6 +9,7 @@ import org.bukkit.event.inventory.ClickType;
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@ -58,12 +59,12 @@ public class SimplePagedGui extends Gui {
|
||||
}
|
||||
|
||||
@Override
|
||||
public SimplePagedGui setItem(int row, int col, ItemStack item) {
|
||||
public @NotNull SimplePagedGui setItem(int row, int col, ItemStack item) {
|
||||
return setItem(col + row * 9, item);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SimplePagedGui setItem(int cell, ItemStack item) {
|
||||
public @NotNull SimplePagedGui setItem(int cell, ItemStack item) {
|
||||
// set the cell relative to the current page
|
||||
int cellIndex = cell < 0 ? cell : (this.page == 1 || (this.useHeader && cell < 9) ? cell : (cell + (this.page - 1) * (this.rowsPerPage * 9)));
|
||||
|
||||
@ -130,7 +131,7 @@ public class SimplePagedGui extends Gui {
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Inventory generateInventory(GuiManager manager) {
|
||||
protected @NotNull Inventory generateInventory(@NotNull GuiManager manager) {
|
||||
this.guiManager = manager;
|
||||
|
||||
// calculate pages here
|
||||
@ -189,7 +190,7 @@ public class SimplePagedGui extends Gui {
|
||||
}
|
||||
}
|
||||
|
||||
// last row is dedicated to pagation
|
||||
// the last row is dedicated to pagination
|
||||
final int cells = this.rows * 9;
|
||||
for (int i = cells - 9; i < cells; ++i) {
|
||||
this.inventory.setItem(i, this.footerBackItem != null ? this.footerBackItem : this.blankItem);
|
||||
@ -207,7 +208,7 @@ public class SimplePagedGui extends Gui {
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean onClick(GuiManager manager, Player player, Inventory inventory, InventoryClickEvent event) {
|
||||
protected boolean onClick(@NotNull GuiManager manager, @NotNull Player player, @NotNull Inventory inventory, InventoryClickEvent event) {
|
||||
int cell = event.getSlot();
|
||||
Map<ClickType, Clickable> conditionals;
|
||||
|
||||
|
@ -16,7 +16,7 @@ import java.util.UUID;
|
||||
import java.util.logging.Level;
|
||||
|
||||
public class ChatPrompt implements Listener {
|
||||
private static final List<UUID> registered = new ArrayList<>();
|
||||
private static final List<UUID> REGISTERED = new ArrayList<>();
|
||||
|
||||
private final Plugin plugin;
|
||||
private final ChatConfirmHandler handler;
|
||||
@ -25,19 +25,19 @@ public class ChatPrompt implements Listener {
|
||||
private OnCancel onCancel = null;
|
||||
private Listener listener;
|
||||
|
||||
private ChatPrompt(Plugin plugin, Player player, ChatConfirmHandler hander) {
|
||||
private ChatPrompt(Plugin plugin, Player player, ChatConfirmHandler handler) {
|
||||
this.plugin = plugin;
|
||||
this.handler = hander;
|
||||
this.handler = handler;
|
||||
|
||||
registered.add(player.getUniqueId());
|
||||
REGISTERED.add(player.getUniqueId());
|
||||
}
|
||||
|
||||
public static ChatPrompt showPrompt(Plugin plugin, Player player, ChatConfirmHandler hander) {
|
||||
return showPrompt(plugin, player, null, hander);
|
||||
public static ChatPrompt showPrompt(Plugin plugin, Player player, ChatConfirmHandler handler) {
|
||||
return showPrompt(plugin, player, null, handler);
|
||||
}
|
||||
|
||||
public static ChatPrompt showPrompt(Plugin plugin, Player player, String message, ChatConfirmHandler hander) {
|
||||
ChatPrompt prompt = new ChatPrompt(plugin, player, hander);
|
||||
public static ChatPrompt showPrompt(Plugin plugin, Player player, String message, ChatConfirmHandler handler) {
|
||||
ChatPrompt prompt = new ChatPrompt(plugin, player, handler);
|
||||
prompt.startListener(plugin);
|
||||
player.closeInventory();
|
||||
|
||||
@ -49,11 +49,11 @@ public class ChatPrompt implements Listener {
|
||||
}
|
||||
|
||||
public static boolean isRegistered(Player player) {
|
||||
return registered.contains(player.getUniqueId());
|
||||
return REGISTERED.contains(player.getUniqueId());
|
||||
}
|
||||
|
||||
public static boolean unregister(Player player) {
|
||||
return registered.remove(player.getUniqueId());
|
||||
return REGISTERED.remove(player.getUniqueId());
|
||||
}
|
||||
|
||||
public ChatPrompt setOnClose(OnClose onClose) {
|
||||
@ -67,13 +67,13 @@ public class ChatPrompt implements Listener {
|
||||
}
|
||||
|
||||
public ChatPrompt setTimeOut(Player player, long ticks) {
|
||||
taskId = Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> {
|
||||
if (onClose != null) {
|
||||
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () ->
|
||||
onClose.onClose(), 0L);
|
||||
this.taskId = Bukkit.getScheduler().scheduleSyncDelayedTask(this.plugin, () -> {
|
||||
if (this.onClose != null) {
|
||||
this.plugin.getServer().getScheduler().scheduleSyncDelayedTask(this.plugin, () ->
|
||||
this.onClose.onClose(), 0L);
|
||||
}
|
||||
|
||||
HandlerList.unregisterAll(listener);
|
||||
HandlerList.unregisterAll(this.listener);
|
||||
player.sendMessage("Your action has timed out.");
|
||||
}, ticks);
|
||||
|
||||
@ -95,20 +95,20 @@ public class ChatPrompt implements Listener {
|
||||
|
||||
ChatConfirmEvent chatConfirmEvent = new ChatConfirmEvent(player, event.getMessage());
|
||||
|
||||
player.sendMessage("\u00BB " + event.getMessage());
|
||||
player.sendMessage("» " + event.getMessage());
|
||||
|
||||
try {
|
||||
handler.onChat(chatConfirmEvent);
|
||||
ChatPrompt.this.handler.onChat(chatConfirmEvent);
|
||||
} catch (Throwable t) {
|
||||
plugin.getLogger().log(Level.SEVERE, "Failed to process chat prompt", t);
|
||||
}
|
||||
|
||||
if (onClose != null) {
|
||||
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> onClose.onClose(), 0L);
|
||||
if (ChatPrompt.this.onClose != null) {
|
||||
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> ChatPrompt.this.onClose.onClose(), 0L);
|
||||
}
|
||||
|
||||
HandlerList.unregisterAll(listener);
|
||||
Bukkit.getScheduler().cancelTask(taskId);
|
||||
HandlerList.unregisterAll(ChatPrompt.this.listener);
|
||||
Bukkit.getScheduler().cancelTask(ChatPrompt.this.taskId);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOWEST)
|
||||
@ -125,18 +125,18 @@ public class ChatPrompt implements Listener {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
|
||||
if (onCancel != null) {
|
||||
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> onCancel.onCancel(), 0L);
|
||||
} else if (onClose != null) {
|
||||
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> onClose.onClose(), 0L);
|
||||
if (ChatPrompt.this.onCancel != null) {
|
||||
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> ChatPrompt.this.onCancel.onCancel(), 0L);
|
||||
} else if (ChatPrompt.this.onClose != null) {
|
||||
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> ChatPrompt.this.onClose.onClose(), 0L);
|
||||
}
|
||||
|
||||
HandlerList.unregisterAll(listener);
|
||||
Bukkit.getScheduler().cancelTask(taskId);
|
||||
HandlerList.unregisterAll(ChatPrompt.this.listener);
|
||||
Bukkit.getScheduler().cancelTask(ChatPrompt.this.taskId);
|
||||
}
|
||||
};
|
||||
|
||||
Bukkit.getPluginManager().registerEvents(listener, plugin);
|
||||
Bukkit.getPluginManager().registerEvents(this.listener, plugin);
|
||||
}
|
||||
|
||||
public interface ChatConfirmHandler {
|
||||
@ -161,11 +161,11 @@ public class ChatPrompt implements Listener {
|
||||
}
|
||||
|
||||
public Player getPlayer() {
|
||||
return player;
|
||||
return this.player;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
return this.message;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -12,13 +12,13 @@ import java.io.BufferedReader;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
@ -191,7 +191,9 @@ public class Locale {
|
||||
}
|
||||
|
||||
File localeFolder = new File(plugin.getDataFolder(), "locales/");
|
||||
if (!localeFolder.exists()) localeFolder.mkdirs();
|
||||
if (!localeFolder.exists()) {
|
||||
localeFolder.mkdirs();
|
||||
}
|
||||
|
||||
if (!fileName.endsWith(FILE_EXTENSION)) {
|
||||
fileName = fileName + FILE_EXTENSION;
|
||||
@ -202,7 +204,7 @@ public class Locale {
|
||||
return updateFiles(plugin, in, destinationFile, builtin);
|
||||
}
|
||||
|
||||
try (OutputStream outputStream = new FileOutputStream(destinationFile)) {
|
||||
try (OutputStream outputStream = Files.newOutputStream(destinationFile.toPath())) {
|
||||
copy(in, outputStream);
|
||||
|
||||
fileName = fileName.substring(0, fileName.lastIndexOf('.'));
|
||||
@ -217,7 +219,7 @@ public class Locale {
|
||||
// Write new changes to existing files, if any at all
|
||||
private static boolean updateFiles(Plugin plugin, InputStream defaultFile, File existingFile, boolean builtin) {
|
||||
try (BufferedInputStream defaultIn = new BufferedInputStream(defaultFile);
|
||||
BufferedInputStream existingIn = new BufferedInputStream(new FileInputStream(existingFile))) {
|
||||
BufferedInputStream existingIn = new BufferedInputStream(Files.newInputStream(existingFile.toPath()))) {
|
||||
|
||||
Charset defaultCharset = TextUtils.detectCharset(defaultIn, StandardCharsets.UTF_8);
|
||||
Charset existingCharset = TextUtils.detectCharset(existingIn, StandardCharsets.UTF_8);
|
||||
@ -291,29 +293,29 @@ public class Locale {
|
||||
*/
|
||||
public boolean reloadMessages() {
|
||||
if (!this.file.exists()) {
|
||||
plugin.getLogger().warning("Could not find file for locale \"" + this.name + "\"");
|
||||
this.plugin.getLogger().warning("Could not find file for locale \"" + this.name + "\"");
|
||||
return false;
|
||||
}
|
||||
|
||||
this.nodes.clear(); // Clear previous data (if any)
|
||||
|
||||
// guess what encoding this file is in
|
||||
Charset charset = TextUtils.detectCharset(file, null);
|
||||
Charset charset = TextUtils.detectCharset(this.file, null);
|
||||
if (charset == null) {
|
||||
plugin.getLogger().warning("Could not determine charset for locale \"" + this.name + "\"");
|
||||
this.plugin.getLogger().warning("Could not determine charset for locale \"" + this.name + "\"");
|
||||
charset = StandardCharsets.UTF_8;
|
||||
}
|
||||
|
||||
// load in the file!
|
||||
try (FileInputStream stream = new FileInputStream(file);
|
||||
try (FileInputStream stream = new FileInputStream(this.file);
|
||||
BufferedReader source = new BufferedReader(new InputStreamReader(stream, charset));
|
||||
BufferedReader reader = translatePropertyToYAML(source, charset)) {
|
||||
Config lang = new Config(file);
|
||||
Config lang = new Config(this.file);
|
||||
lang.load(reader);
|
||||
translateMsgRoot(lang, file, charset);
|
||||
translateMsgRoot(lang, this.file, charset);
|
||||
|
||||
// load lists as strings with newlines
|
||||
lang.getValues(true).forEach((k, v) -> nodes.put(k,
|
||||
lang.getValues(true).forEach((k, v) -> this.nodes.put(k,
|
||||
v instanceof List
|
||||
? (((List<?>) v).stream().map(Object::toString).collect(Collectors.joining("\n")))
|
||||
: v.toString()));
|
||||
@ -322,7 +324,7 @@ public class Locale {
|
||||
} catch (IOException ex) {
|
||||
ex.printStackTrace();
|
||||
} catch (InvalidConfigurationException ex) {
|
||||
Logger.getLogger(Locale.class.getName()).log(Level.SEVERE, "Configuration error in language file \"" + file.getName() + "\"", ex);
|
||||
Logger.getLogger(Locale.class.getName()).log(Level.SEVERE, "Configuration error in language file \"" + this.file.getName() + "\"", ex);
|
||||
}
|
||||
|
||||
return false;
|
||||
@ -426,7 +428,7 @@ public class Locale {
|
||||
* @return applied message
|
||||
*/
|
||||
private Message supplyPrefix(Message message) {
|
||||
return message.setPrefix(this.nodes.getOrDefault("general.nametag.prefix", "[" + plugin.getName() + "]"));
|
||||
return message.setPrefix(this.nodes.getOrDefault("general.nametag.prefix", "[" + this.plugin.getName() + "]"));
|
||||
}
|
||||
|
||||
/**
|
||||
@ -477,7 +479,7 @@ public class Locale {
|
||||
* @return the locale name
|
||||
*/
|
||||
public String getName() {
|
||||
return name;
|
||||
return this.name;
|
||||
}
|
||||
|
||||
private static void copy(InputStream input, OutputStream output) {
|
||||
|
@ -69,7 +69,7 @@ public class Message {
|
||||
* @param sender command sender to send the message to
|
||||
*/
|
||||
public void sendMessage(CommandSender sender) {
|
||||
message.sendTo(sender);
|
||||
this.message.sendTo(sender);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -129,7 +129,7 @@ public class Message {
|
||||
* @return the prefixed message
|
||||
*/
|
||||
public String getPrefixedMessage() {
|
||||
return TextUtils.formatText((prefix == null ? "" : this.prefix.toText()) + " " + this.message.toText());
|
||||
return TextUtils.formatText((this.prefix == null ? "" : this.prefix.toText()) + " " + this.message.toText());
|
||||
}
|
||||
|
||||
/**
|
||||
@ -170,7 +170,7 @@ public class Message {
|
||||
*/
|
||||
public Message processPlaceholder(String placeholder, Object replacement) {
|
||||
final String place = Matcher.quoteReplacement(placeholder);
|
||||
this.message = message.replaceAll("%" + place + "%|\\{" + place + "\\}", replacement == null ? "" : Matcher.quoteReplacement(replacement.toString()));
|
||||
this.message = this.message.replaceAll("%" + place + "%|\\{" + place + "\\}", replacement == null ? "" : Matcher.quoteReplacement(replacement.toString()));
|
||||
|
||||
return this;
|
||||
}
|
||||
|
@ -13,10 +13,10 @@ public class Lootables {
|
||||
}
|
||||
|
||||
public String getLootablesDir() {
|
||||
return lootablesDir;
|
||||
return this.lootablesDir;
|
||||
}
|
||||
|
||||
public LootManager getLootManager() {
|
||||
return lootManager;
|
||||
return this.lootManager;
|
||||
}
|
||||
}
|
||||
|
@ -31,14 +31,14 @@ public abstract class AbstractGuiListEditor extends Gui {
|
||||
setButton(2, GuiUtils.createButtonItem(XMaterial.OAK_FENCE_GATE,
|
||||
TextUtils.formatText("&cBack")),
|
||||
(event) -> {
|
||||
guiManager.showGUI(event.player, returnGui);
|
||||
((GuiLootEditor) returnGui).paint();
|
||||
this.guiManager.showGUI(event.player, this.returnGui);
|
||||
((GuiLootEditor) this.returnGui).paint();
|
||||
});
|
||||
setButton(6, GuiUtils.createButtonItem(XMaterial.OAK_FENCE_GATE,
|
||||
TextUtils.formatText("&cBack")),
|
||||
(event) -> {
|
||||
guiManager.showGUI(event.player, returnGui);
|
||||
((GuiLootEditor) returnGui).paint();
|
||||
this.guiManager.showGUI(event.player, this.returnGui);
|
||||
((GuiLootEditor) this.returnGui).paint();
|
||||
});
|
||||
setButton(3, GuiUtils.createButtonItem(XMaterial.ARROW,
|
||||
TextUtils.formatText("&aAdd new line")),
|
||||
@ -54,7 +54,7 @@ public abstract class AbstractGuiListEditor extends Gui {
|
||||
}
|
||||
}));
|
||||
gui.setTitle("Enter a new line");
|
||||
guiManager.showGUI(event.player, gui);
|
||||
this.guiManager.showGUI(event.player, gui);
|
||||
}));
|
||||
|
||||
setItem(4, GuiUtils.createButtonItem(XMaterial.WRITABLE_BOOK,
|
||||
|
@ -29,35 +29,35 @@ public class GuiEditor extends Gui {
|
||||
}
|
||||
|
||||
private void paint() {
|
||||
if (inventory != null) {
|
||||
inventory.clear();
|
||||
if (this.inventory != null) {
|
||||
this.inventory.clear();
|
||||
}
|
||||
|
||||
setActionForRange(0, 0, 5, 9, null);
|
||||
|
||||
List<Lootable> lootables = new ArrayList<>(lootManager.getRegisteredLootables().values());
|
||||
List<Lootable> lootables = new ArrayList<>(this.lootManager.getRegisteredLootables().values());
|
||||
|
||||
double itemCount = lootables.size();
|
||||
this.pages = (int) Math.max(1, Math.ceil(itemCount / 36));
|
||||
|
||||
if (page != 1) {
|
||||
if (this.page != 1) {
|
||||
setButton(5, 2, GuiUtils.createButtonItem(XMaterial.ARROW, "Back"),
|
||||
(event) -> {
|
||||
page--;
|
||||
this.page--;
|
||||
paint();
|
||||
});
|
||||
}
|
||||
|
||||
if (page != pages) {
|
||||
if (this.page != this.pages) {
|
||||
setButton(5, 6, GuiUtils.createButtonItem(XMaterial.ARROW, "Next"),
|
||||
(event) -> {
|
||||
page++;
|
||||
this.page++;
|
||||
paint();
|
||||
});
|
||||
}
|
||||
|
||||
for (int i = 9; i < 45; i++) {
|
||||
int current = ((page - 1) * 36) - 9;
|
||||
int current = ((this.page - 1) * 36) - 9;
|
||||
if (current + i >= lootables.size()) {
|
||||
setItem(i, null);
|
||||
continue;
|
||||
@ -69,7 +69,7 @@ public class GuiEditor extends Gui {
|
||||
}
|
||||
|
||||
setButton(i, getIcon(lootable.getKey()),
|
||||
(event) -> guiManager.showGUI(event.player, new GuiLootableEditor(lootManager, lootable, this)));
|
||||
(event) -> this.guiManager.showGUI(event.player, new GuiLootableEditor(this.lootManager, lootable, this)));
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -31,19 +31,19 @@ public class GuiEnchantEditor extends Gui {
|
||||
}
|
||||
|
||||
public void paint() {
|
||||
Map<String, Integer> lore = loot.getEnchants() == null ? new HashMap<>() : new HashMap<>(loot.getEnchants());
|
||||
Map<String, Integer> lore = this.loot.getEnchants() == null ? new HashMap<>() : new HashMap<>(this.loot.getEnchants());
|
||||
|
||||
setButton(2, GuiUtils.createButtonItem(XMaterial.OAK_FENCE_GATE,
|
||||
TextUtils.formatText("&cBack")),
|
||||
(event) -> {
|
||||
guiManager.showGUI(event.player, returnGui);
|
||||
((GuiLootEditor) returnGui).paint();
|
||||
this.guiManager.showGUI(event.player, this.returnGui);
|
||||
((GuiLootEditor) this.returnGui).paint();
|
||||
});
|
||||
setButton(6, GuiUtils.createButtonItem(XMaterial.OAK_FENCE_GATE,
|
||||
TextUtils.formatText("&cBack")),
|
||||
(event) -> {
|
||||
guiManager.showGUI(event.player, returnGui);
|
||||
((GuiLootEditor) returnGui).paint();
|
||||
this.guiManager.showGUI(event.player, this.returnGui);
|
||||
((GuiLootEditor) this.returnGui).paint();
|
||||
});
|
||||
setButton(3, GuiUtils.createButtonItem(XMaterial.ARROW,
|
||||
TextUtils.formatText("&aAdd new line")),
|
||||
@ -59,16 +59,16 @@ public class GuiEnchantEditor extends Gui {
|
||||
AnvilGui gui1 = new AnvilGui(event.player, this);
|
||||
gui1.setAction((ee -> {
|
||||
lore.put(gui.getInputText().toUpperCase().trim(), Integer.parseInt(gui1.getInputText().trim()));
|
||||
loot.setEnchants(lore);
|
||||
this.loot.setEnchants(lore);
|
||||
ee.player.closeInventory();
|
||||
paint();
|
||||
}));
|
||||
gui1.setTitle("Enter a level");
|
||||
guiManager.showGUI(event.player, gui1);
|
||||
this.guiManager.showGUI(event.player, gui1);
|
||||
}));
|
||||
|
||||
gui.setTitle("Enter an enchant");
|
||||
guiManager.showGUI(event.player, gui);
|
||||
this.guiManager.showGUI(event.player, gui);
|
||||
}));
|
||||
|
||||
List<String> enchantments = new ArrayList<>();
|
||||
@ -93,7 +93,7 @@ public class GuiEnchantEditor extends Gui {
|
||||
TextUtils.formatText("&cRemove the last line")),
|
||||
(event -> {
|
||||
lore.remove(lastFinal);
|
||||
loot.setEnchants(lore);
|
||||
this.loot.setEnchants(lore);
|
||||
paint();
|
||||
}));
|
||||
}
|
||||
|
@ -14,12 +14,12 @@ public class GuiEntityEditor extends AbstractGuiListEditor {
|
||||
|
||||
@Override
|
||||
protected List<String> getData() {
|
||||
return loot.getOnlyDropFor().stream().map(Enum::name).collect(Collectors.toList());
|
||||
return this.loot.getOnlyDropFor().stream().map(Enum::name).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void updateData(List<String> list) {
|
||||
loot.setOnlyDropFor(list.stream().map(EntityType::valueOf).collect(Collectors.toList()));
|
||||
this.loot.setOnlyDropFor(list.stream().map(EntityType::valueOf).collect(Collectors.toList()));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -41,52 +41,52 @@ public class GuiLootEditor extends Gui {
|
||||
}
|
||||
|
||||
public void paint() {
|
||||
if (inventory != null) {
|
||||
inventory.clear();
|
||||
if (this.inventory != null) {
|
||||
this.inventory.clear();
|
||||
}
|
||||
|
||||
setActionForRange(0, 0, 5, 9, null);
|
||||
|
||||
setButton(8, GuiUtils.createButtonItem(XMaterial.OAK_DOOR, TextUtils.formatText("&cBack")),
|
||||
(event) -> guiManager.showGUI(event.player, returnGui));
|
||||
(event) -> this.guiManager.showGUI(event.player, this.returnGui));
|
||||
|
||||
setButton(9, GuiUtils.createButtonItem(loot.getMaterial() == null ? XMaterial.BARRIER : loot.getMaterial(),
|
||||
TextUtils.formatText("&7Current Material: &6" + (loot.getMaterial() != null
|
||||
? loot.getMaterial().name() : "None")), TextUtils.formatText(
|
||||
setButton(9, GuiUtils.createButtonItem(this.loot.getMaterial() == null ? XMaterial.BARRIER : this.loot.getMaterial(),
|
||||
TextUtils.formatText("&7Current Material: &6" + (this.loot.getMaterial() != null
|
||||
? this.loot.getMaterial().name() : "None")), TextUtils.formatText(
|
||||
Arrays.asList("",
|
||||
"&8Click to set the material to",
|
||||
"&8the material in your hand.")
|
||||
)), (event) -> {
|
||||
ItemStack stack = event.player.getInventory().getItemInMainHand();
|
||||
loot.setMaterial(CompatibleMaterial.getMaterial(stack.getType()).get());
|
||||
this.loot.setMaterial(CompatibleMaterial.getMaterial(stack.getType()).get());
|
||||
|
||||
paint();
|
||||
});
|
||||
|
||||
setButton(10, GuiUtils.createButtonItem(XMaterial.PAPER,
|
||||
TextUtils.formatText("&7Name Override: &6" + (loot.getName() == null ? "None set" : loot.getName()))),
|
||||
TextUtils.formatText("&7Name Override: &6" + (this.loot.getName() == null ? "None set" : this.loot.getName()))),
|
||||
(event) -> {
|
||||
AnvilGui gui = new AnvilGui(event.player, this);
|
||||
gui.setAction((e -> {
|
||||
loot.setName(gui.getInputText().trim());
|
||||
this.loot.setName(gui.getInputText().trim());
|
||||
|
||||
paint();
|
||||
e.player.closeInventory();
|
||||
}));
|
||||
|
||||
guiManager.showGUI(event.player, gui);
|
||||
gui.setInput(GuiUtils.createButtonItem(XMaterial.PAPER, loot.getName()));
|
||||
this.guiManager.showGUI(event.player, gui);
|
||||
gui.setInput(GuiUtils.createButtonItem(XMaterial.PAPER, this.loot.getName()));
|
||||
});
|
||||
|
||||
setButton(11, GuiUtils.createButtonItem(XMaterial.WRITABLE_BOOK,
|
||||
TextUtils.formatText("&7Lore Override:"),
|
||||
TextUtils.formatText(loot.getLore() == null ? Collections.singletonList("&6None set") : loot.getLore())),
|
||||
(event) -> guiManager.showGUI(event.player, new GuiLoreEditor(loot, this)));
|
||||
TextUtils.formatText(this.loot.getLore() == null ? Collections.singletonList("&6None set") : this.loot.getLore())),
|
||||
(event) -> this.guiManager.showGUI(event.player, new GuiLoreEditor(this.loot, this)));
|
||||
|
||||
List<String> enchantments = new ArrayList<>();
|
||||
|
||||
if (loot.getEnchants() != null) {
|
||||
for (Map.Entry<String, Integer> entry : loot.getEnchants().entrySet()) {
|
||||
if (this.loot.getEnchants() != null) {
|
||||
for (Map.Entry<String, Integer> entry : this.loot.getEnchants().entrySet()) {
|
||||
enchantments.add("&6" + entry.getKey() + " " + entry.getValue());
|
||||
}
|
||||
}
|
||||
@ -94,29 +94,29 @@ public class GuiLootEditor extends Gui {
|
||||
setButton(12, GuiUtils.createButtonItem(XMaterial.ENCHANTED_BOOK,
|
||||
TextUtils.formatText("&7Enchantments:"),
|
||||
TextUtils.formatText(enchantments.isEmpty() ? Collections.singletonList("&6None set") : enchantments)),
|
||||
(event) -> guiManager.showGUI(event.player, new GuiEnchantEditor(loot, this)));
|
||||
(event) -> this.guiManager.showGUI(event.player, new GuiEnchantEditor(this.loot, this)));
|
||||
|
||||
setButton(13, GuiUtils.createButtonItem(
|
||||
loot.getBurnedMaterial() == null
|
||||
this.loot.getBurnedMaterial() == null
|
||||
? XMaterial.FIRE_CHARGE
|
||||
: loot.getBurnedMaterial(),
|
||||
: this.loot.getBurnedMaterial(),
|
||||
TextUtils.formatText("&7Current Burned Material: &6"
|
||||
+ (loot.getBurnedMaterial() == null
|
||||
+ (this.loot.getBurnedMaterial() == null
|
||||
? "None"
|
||||
: loot.getBurnedMaterial().name())), TextUtils.formatText(
|
||||
: this.loot.getBurnedMaterial().name())), TextUtils.formatText(
|
||||
Arrays.asList("",
|
||||
"&8Click to set the burned material to",
|
||||
"&8the material in your hand.")
|
||||
)),
|
||||
(event) -> {
|
||||
ItemStack stack = event.player.getInventory().getItemInMainHand();
|
||||
loot.setBurnedMaterial(CompatibleMaterial.getMaterial(stack.getType()).get());
|
||||
this.loot.setBurnedMaterial(CompatibleMaterial.getMaterial(stack.getType()).get());
|
||||
|
||||
paint();
|
||||
});
|
||||
|
||||
setButton(14, GuiUtils.createButtonItem(XMaterial.CLOCK,
|
||||
TextUtils.formatText("&7Chance: &6" + loot.getChance()),
|
||||
TextUtils.formatText("&7Chance: &6" + this.loot.getChance()),
|
||||
TextUtils.formatText(
|
||||
Arrays.asList("",
|
||||
"&8Click to edit this loots",
|
||||
@ -126,124 +126,124 @@ public class GuiLootEditor extends Gui {
|
||||
AnvilGui gui = new AnvilGui(event.player, this);
|
||||
|
||||
gui.setAction((e) -> {
|
||||
loot.setChance(Double.parseDouble(gui.getInputText()));
|
||||
this.loot.setChance(Double.parseDouble(gui.getInputText()));
|
||||
|
||||
paint();
|
||||
e.player.closeInventory();
|
||||
});
|
||||
|
||||
gui.setInput(GuiUtils.createButtonItem(XMaterial.PAPER, String.valueOf(loot.getChance())));
|
||||
guiManager.showGUI(event.player, gui);
|
||||
gui.setInput(GuiUtils.createButtonItem(XMaterial.PAPER, String.valueOf(this.loot.getChance())));
|
||||
this.guiManager.showGUI(event.player, gui);
|
||||
});
|
||||
|
||||
setButton(15, GuiUtils.createButtonItem(XMaterial.REDSTONE,
|
||||
TextUtils.formatText("&7Min Drop Amount: &6" + loot.getMin())),
|
||||
TextUtils.formatText("&7Min Drop Amount: &6" + this.loot.getMin())),
|
||||
(event) -> {
|
||||
AnvilGui gui = new AnvilGui(event.player, this);
|
||||
|
||||
gui.setAction((e) -> {
|
||||
loot.setMin(Integer.parseInt(gui.getInputText()));
|
||||
this.loot.setMin(Integer.parseInt(gui.getInputText()));
|
||||
|
||||
paint();
|
||||
e.player.closeInventory();
|
||||
});
|
||||
|
||||
gui.setInput(GuiUtils.createButtonItem(XMaterial.PAPER,
|
||||
String.valueOf(loot.getMin())));
|
||||
guiManager.showGUI(event.player, gui);
|
||||
String.valueOf(this.loot.getMin())));
|
||||
this.guiManager.showGUI(event.player, gui);
|
||||
});
|
||||
|
||||
setButton(16, GuiUtils.createButtonItem(XMaterial.GLOWSTONE_DUST,
|
||||
TextUtils.formatText("&7Max Drop Amount: &6" + loot.getMax())),
|
||||
TextUtils.formatText("&7Max Drop Amount: &6" + this.loot.getMax())),
|
||||
(event) -> {
|
||||
AnvilGui gui = new AnvilGui(event.player, this);
|
||||
|
||||
gui.setAction((e) -> {
|
||||
loot.setMax(Integer.parseInt(gui.getInputText()));
|
||||
this.loot.setMax(Integer.parseInt(gui.getInputText()));
|
||||
|
||||
paint();
|
||||
e.player.closeInventory();
|
||||
});
|
||||
|
||||
gui.setInput(GuiUtils.createButtonItem(XMaterial.PAPER, String.valueOf(loot.getMax())));
|
||||
guiManager.showGUI(event.player, gui);
|
||||
gui.setInput(GuiUtils.createButtonItem(XMaterial.PAPER, String.valueOf(this.loot.getMax())));
|
||||
this.guiManager.showGUI(event.player, gui);
|
||||
});
|
||||
|
||||
setButton(17, GuiUtils.createButtonItem(XMaterial.REDSTONE,
|
||||
TextUtils.formatText("&7Min Item Damage: &6" + loot.getDamageMin())),
|
||||
TextUtils.formatText("&7Min Item Damage: &6" + this.loot.getDamageMin())),
|
||||
(event) -> {
|
||||
AnvilGui gui = new AnvilGui(event.player, this);
|
||||
gui.setAction((e) -> {
|
||||
loot.setDamageMin(Integer.parseInt(gui.getInputText()));
|
||||
this.loot.setDamageMin(Integer.parseInt(gui.getInputText()));
|
||||
|
||||
paint();
|
||||
e.player.closeInventory();
|
||||
});
|
||||
|
||||
gui.setInput(GuiUtils.createButtonItem(XMaterial.PAPER, String.valueOf(loot.getDamageMin())));
|
||||
guiManager.showGUI(event.player, gui);
|
||||
gui.setInput(GuiUtils.createButtonItem(XMaterial.PAPER, String.valueOf(this.loot.getDamageMin())));
|
||||
this.guiManager.showGUI(event.player, gui);
|
||||
});
|
||||
|
||||
setButton(18, GuiUtils.createButtonItem(XMaterial.GLOWSTONE_DUST,
|
||||
TextUtils.formatText("&7Max Item Damage: &6" + loot.getDamageMax())),
|
||||
TextUtils.formatText("&7Max Item Damage: &6" + this.loot.getDamageMax())),
|
||||
(event) -> {
|
||||
AnvilGui gui = new AnvilGui(event.player, this);
|
||||
gui.setAction((e) -> {
|
||||
loot.setDamageMax(Integer.parseInt(gui.getInputText()));
|
||||
this.loot.setDamageMax(Integer.parseInt(gui.getInputText()));
|
||||
|
||||
paint();
|
||||
e.player.closeInventory();
|
||||
});
|
||||
|
||||
gui.setInput(GuiUtils.createButtonItem(XMaterial.PAPER, String.valueOf(loot.getDamageMax())));
|
||||
guiManager.showGUI(event.player, gui);
|
||||
gui.setInput(GuiUtils.createButtonItem(XMaterial.PAPER, String.valueOf(this.loot.getDamageMax())));
|
||||
this.guiManager.showGUI(event.player, gui);
|
||||
});
|
||||
|
||||
setButton(19, GuiUtils.createButtonItem(XMaterial.CHEST,
|
||||
TextUtils.formatText("&7Allow Looting Enchantment?: &6" + loot.isAllowLootingEnchant())),
|
||||
TextUtils.formatText("&7Allow Looting Enchantment?: &6" + this.loot.isAllowLootingEnchant())),
|
||||
(event) -> {
|
||||
loot.setAllowLootingEnchant(!loot.isAllowLootingEnchant());
|
||||
this.loot.setAllowLootingEnchant(!this.loot.isAllowLootingEnchant());
|
||||
|
||||
paint();
|
||||
event.player.closeInventory();
|
||||
});
|
||||
|
||||
setButton(20, GuiUtils.createButtonItem(XMaterial.REDSTONE,
|
||||
TextUtils.formatText("&7Min Child Loot Min: &6" + loot.getChildDropCountMin())),
|
||||
TextUtils.formatText("&7Min Child Loot Min: &6" + this.loot.getChildDropCountMin())),
|
||||
(event) -> {
|
||||
AnvilGui gui = new AnvilGui(event.player, this);
|
||||
|
||||
gui.setAction((e) -> {
|
||||
loot.setChildDropCountMin(Integer.parseInt(gui.getInputText()));
|
||||
this.loot.setChildDropCountMin(Integer.parseInt(gui.getInputText()));
|
||||
|
||||
paint();
|
||||
e.player.closeInventory();
|
||||
});
|
||||
|
||||
gui.setInput(GuiUtils.createButtonItem(XMaterial.PAPER, String.valueOf(loot.getChildDropCountMin())));
|
||||
guiManager.showGUI(event.player, gui);
|
||||
gui.setInput(GuiUtils.createButtonItem(XMaterial.PAPER, String.valueOf(this.loot.getChildDropCountMin())));
|
||||
this.guiManager.showGUI(event.player, gui);
|
||||
});
|
||||
|
||||
setButton(21, GuiUtils.createButtonItem(XMaterial.GLOWSTONE_DUST,
|
||||
TextUtils.formatText("&7Min Child Loot Max: &6" + loot.getChildDropCountMax())),
|
||||
TextUtils.formatText("&7Min Child Loot Max: &6" + this.loot.getChildDropCountMax())),
|
||||
(event) -> {
|
||||
AnvilGui gui = new AnvilGui(event.player, this);
|
||||
|
||||
gui.setAction((e) -> {
|
||||
loot.setChildDropCountMax(Integer.parseInt(gui.getInputText()));
|
||||
this.loot.setChildDropCountMax(Integer.parseInt(gui.getInputText()));
|
||||
|
||||
paint();
|
||||
e.player.closeInventory();
|
||||
});
|
||||
|
||||
gui.setInput(GuiUtils.createButtonItem(XMaterial.PAPER, String.valueOf(loot.getChildDropCountMax())));
|
||||
guiManager.showGUI(event.player, gui);
|
||||
gui.setInput(GuiUtils.createButtonItem(XMaterial.PAPER, String.valueOf(this.loot.getChildDropCountMax())));
|
||||
this.guiManager.showGUI(event.player, gui);
|
||||
});
|
||||
|
||||
List<String> entities = new ArrayList<>();
|
||||
|
||||
if (loot.getOnlyDropFor() != null) {
|
||||
for (EntityType entity : loot.getOnlyDropFor()) {
|
||||
if (this.loot.getOnlyDropFor() != null) {
|
||||
for (EntityType entity : this.loot.getOnlyDropFor()) {
|
||||
entities.add("&6" + entity.name());
|
||||
}
|
||||
}
|
||||
@ -251,7 +251,7 @@ public class GuiLootEditor extends Gui {
|
||||
setButton(22, GuiUtils.createButtonItem(XMaterial.ENCHANTED_BOOK,
|
||||
TextUtils.formatText("&7Only Drop For:"),
|
||||
TextUtils.formatText(entities)),
|
||||
(event) -> guiManager.showGUI(event.player, new GuiEntityEditor(loot, this)));
|
||||
(event) -> this.guiManager.showGUI(event.player, new GuiEntityEditor(this.loot, this)));
|
||||
|
||||
setButton(4, 0, GuiUtils.createButtonItem(XMaterial.LIME_DYE, TextUtils.formatText("&aCreate new Child Loot")),
|
||||
(event -> {
|
||||
@ -259,7 +259,7 @@ public class GuiLootEditor extends Gui {
|
||||
|
||||
gui.setAction((event1 -> {
|
||||
try {
|
||||
loot.addChildLoots(new LootBuilder().setMaterial(XMaterial.valueOf(gui.getInputText().trim())).build());
|
||||
this.loot.addChildLoots(new LootBuilder().setMaterial(XMaterial.valueOf(gui.getInputText().trim())).build());
|
||||
} catch (IllegalArgumentException ignore) {
|
||||
event.player.sendMessage("That is not a valid material.");
|
||||
}
|
||||
@ -269,11 +269,11 @@ public class GuiLootEditor extends Gui {
|
||||
}));
|
||||
|
||||
gui.setTitle("Enter a material");
|
||||
guiManager.showGUI(event.player, gui);
|
||||
this.guiManager.showGUI(event.player, gui);
|
||||
}));
|
||||
|
||||
int i = 9 * 5;
|
||||
for (Loot loot : loot.getChildLoot()) {
|
||||
for (Loot loot : this.loot.getChildLoot()) {
|
||||
ItemStack item = loot.getMaterial() == null
|
||||
? XMaterial.BARRIER.parseItem()
|
||||
: GuiUtils.createButtonItem(loot.getMaterial(), null,
|
||||
@ -286,7 +286,7 @@ public class GuiLootEditor extends Gui {
|
||||
this.loot.removeChildLoot(loot);
|
||||
paint();
|
||||
} else if (event.clickType == ClickType.LEFT) {
|
||||
guiManager.showGUI(event.player, new GuiLootEditor(lootManager, loot, this));
|
||||
this.guiManager.showGUI(event.player, new GuiLootEditor(this.lootManager, loot, this));
|
||||
}
|
||||
});
|
||||
|
||||
|
@ -33,8 +33,8 @@ public class GuiLootableEditor extends Gui {
|
||||
}
|
||||
|
||||
private void paint() {
|
||||
if (inventory != null) {
|
||||
inventory.clear();
|
||||
if (this.inventory != null) {
|
||||
this.inventory.clear();
|
||||
}
|
||||
|
||||
setActionForRange(0, 0, 5, 9, null);
|
||||
@ -44,7 +44,7 @@ public class GuiLootableEditor extends Gui {
|
||||
AnvilGui gui = new AnvilGui(event.player, this);
|
||||
gui.setAction((event1 -> {
|
||||
try {
|
||||
lootable.registerLoot(new LootBuilder().setMaterial(XMaterial.valueOf(gui.getInputText().trim().toUpperCase())).build());
|
||||
this.lootable.registerLoot(new LootBuilder().setMaterial(XMaterial.valueOf(gui.getInputText().trim().toUpperCase())).build());
|
||||
} catch (IllegalArgumentException ex) {
|
||||
event.player.sendMessage("That is not a valid material.");
|
||||
}
|
||||
@ -54,14 +54,14 @@ public class GuiLootableEditor extends Gui {
|
||||
}));
|
||||
|
||||
gui.setTitle("Enter a material");
|
||||
guiManager.showGUI(event.player, gui);
|
||||
this.guiManager.showGUI(event.player, gui);
|
||||
}));
|
||||
|
||||
setButton(8, GuiUtils.createButtonItem(XMaterial.OAK_DOOR, TextUtils.formatText("&cBack")),
|
||||
(event -> guiManager.showGUI(event.player, returnGui)));
|
||||
(event -> this.guiManager.showGUI(event.player, this.returnGui)));
|
||||
|
||||
int i = 9;
|
||||
for (Loot loot : lootable.getRegisteredLoot()) {
|
||||
for (Loot loot : this.lootable.getRegisteredLoot()) {
|
||||
ItemStack item = loot.getMaterial() == null
|
||||
? XMaterial.BARRIER.parseItem()
|
||||
: GuiUtils.createButtonItem(loot.getMaterial(), null,
|
||||
@ -71,14 +71,14 @@ public class GuiLootableEditor extends Gui {
|
||||
setButton(i, item,
|
||||
(event) -> {
|
||||
if (event.clickType == ClickType.RIGHT) {
|
||||
lootable.removeLoot(loot);
|
||||
this.lootable.removeLoot(loot);
|
||||
paint();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.clickType == ClickType.LEFT) {
|
||||
guiManager.showGUI(event.player, new GuiLootEditor(lootManager, loot, this));
|
||||
this.guiManager.showGUI(event.player, new GuiLootEditor(this.lootManager, loot, this));
|
||||
}
|
||||
});
|
||||
|
||||
|
@ -12,12 +12,12 @@ public class GuiLoreEditor extends AbstractGuiListEditor {
|
||||
|
||||
@Override
|
||||
protected List<String> getData() {
|
||||
return loot.getLore();
|
||||
return this.loot.getLore();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void updateData(List<String> list) {
|
||||
loot.setLore(list);
|
||||
this.loot.setLore(list);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -22,7 +22,7 @@ public class Drop {
|
||||
}
|
||||
|
||||
public String getCommand() {
|
||||
return command;
|
||||
return this.command;
|
||||
}
|
||||
|
||||
public void setCommand(String command) {
|
||||
@ -30,7 +30,7 @@ public class Drop {
|
||||
}
|
||||
|
||||
public int getXp() {
|
||||
return xp;
|
||||
return this.xp;
|
||||
}
|
||||
|
||||
public void setXp(int xp) {
|
||||
@ -38,7 +38,7 @@ public class Drop {
|
||||
}
|
||||
|
||||
public ItemStack getItemStack() {
|
||||
return itemStack;
|
||||
return this.itemStack;
|
||||
}
|
||||
|
||||
public void setItemStack(ItemStack itemStack) {
|
||||
|
@ -71,7 +71,7 @@ public class DropUtils {
|
||||
List<StackedItem> stacks = new ArrayList<>();
|
||||
int maxSize = UltimateStackerApi.getSettings().getMaxItemStackSize() - 64;
|
||||
for (ItemStack item : items) {
|
||||
StackedItem stack = stacks.stream().filter(stackedItem -> stackedItem.getItem().getType() == item.getType()).filter(stackedItem -> stackedItem.getAmount() < Integer.MAX_VALUE/2).findFirst().orElse(null);
|
||||
StackedItem stack = stacks.stream().filter(stackedItem -> stackedItem.getItem().getType() == item.getType()).filter(stackedItem -> stackedItem.getAmount() < Integer.MAX_VALUE / 2).findFirst().orElse(null);
|
||||
if (stack == null) {
|
||||
stacks.add(new StackedItem(item, item.getAmount()));
|
||||
continue;
|
||||
@ -138,14 +138,6 @@ public class DropUtils {
|
||||
return this.amount;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use {@link #setAmount(int)} instead.
|
||||
*/
|
||||
@Deprecated
|
||||
public void setamount(int amount) {
|
||||
this.amount = amount;
|
||||
}
|
||||
|
||||
public void setAmount(int amount) {
|
||||
this.amount = amount;
|
||||
}
|
||||
|
@ -97,7 +97,7 @@ public class Loot {
|
||||
private boolean requireCharged = false;
|
||||
|
||||
public XMaterial getMaterial() {
|
||||
return material;
|
||||
return this.material;
|
||||
}
|
||||
|
||||
public void setMaterial(XMaterial material) {
|
||||
@ -105,7 +105,7 @@ public class Loot {
|
||||
}
|
||||
|
||||
public String getCommand() {
|
||||
return command;
|
||||
return this.command;
|
||||
}
|
||||
|
||||
public void setCommand(String command) {
|
||||
@ -113,7 +113,7 @@ public class Loot {
|
||||
}
|
||||
|
||||
public int getXp() {
|
||||
return xp;
|
||||
return this.xp;
|
||||
}
|
||||
|
||||
public void setXp(int xp) {
|
||||
@ -121,7 +121,7 @@ public class Loot {
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return TextUtils.formatText(name);
|
||||
return TextUtils.formatText(this.name);
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
@ -129,7 +129,7 @@ public class Loot {
|
||||
}
|
||||
|
||||
public List<String> getLore() {
|
||||
if (lore == null) {
|
||||
if (this.lore == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@ -147,12 +147,12 @@ public class Loot {
|
||||
}
|
||||
|
||||
public ItemStack getEnchants(ItemStack item) {
|
||||
if (enchants == null) {
|
||||
if (this.enchants == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
//Create enchantment book
|
||||
if (item.getType().equals(Material.ENCHANTED_BOOK)) {
|
||||
// Create enchantment book
|
||||
if (item.getType() == Material.ENCHANTED_BOOK) {
|
||||
EnchantmentStorageMeta meta = (EnchantmentStorageMeta) item.getItemMeta();
|
||||
for (Map.Entry<String, Integer> entry : this.enchants.entrySet()) {
|
||||
if (entry.getValue() == null) continue;
|
||||
@ -172,7 +172,9 @@ public class Loot {
|
||||
|
||||
Map<Enchantment, Integer> enchants = new HashMap<>();
|
||||
for (Map.Entry<String, Integer> entry : this.enchants.entrySet()) {
|
||||
if (entry.getValue() == null) continue;
|
||||
if (entry.getValue() == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (entry.getKey().equalsIgnoreCase("RANDOM")) {
|
||||
item = ItemUtils.applyRandomEnchants(item, entry.getValue());
|
||||
@ -197,11 +199,11 @@ public class Loot {
|
||||
}
|
||||
|
||||
public Map<String, Integer> getEnchants() {
|
||||
return enchants == null ? null : Collections.unmodifiableMap(enchants);
|
||||
return this.enchants == null ? null : Collections.unmodifiableMap(this.enchants);
|
||||
}
|
||||
|
||||
public XMaterial getBurnedMaterial() {
|
||||
return burnedMaterial;
|
||||
return this.burnedMaterial;
|
||||
}
|
||||
|
||||
public void setBurnedMaterial(XMaterial burnedMaterial) {
|
||||
@ -209,7 +211,7 @@ public class Loot {
|
||||
}
|
||||
|
||||
public double getChance() {
|
||||
return chance;
|
||||
return this.chance;
|
||||
}
|
||||
|
||||
public void setChance(double chance) {
|
||||
@ -219,28 +221,25 @@ public class Loot {
|
||||
public boolean runChance(int looting, ItemStack murderWeapon) {
|
||||
double chance = this.chance;
|
||||
|
||||
if (enchantChances != null && murderWeapon != null && enchants != null) {
|
||||
if (this.enchantChances != null && murderWeapon != null && this.enchants != null) {
|
||||
for (Map.Entry<Enchantment, Integer> entry : murderWeapon.getEnchantments().entrySet()) {
|
||||
String key = entry.getKey().getName() + ":" + entry.getValue();
|
||||
|
||||
if (!enchants.containsKey(key)) {
|
||||
if (!this.enchants.containsKey(key)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
double ch = enchantChances.get(key);
|
||||
|
||||
if (ch > chance) {
|
||||
chance = enchantChances.get(key);
|
||||
if (this.enchantChances.get(key) > chance) {
|
||||
chance = this.enchantChances.get(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (Math.random() * 100) - (chance + (lootingIncrease == null ? 1
|
||||
: lootingIncrease * looting)) < 0 || chance == 100;
|
||||
return (Math.random() * 100) - (chance + (this.lootingIncrease == null ? 1 : this.lootingIncrease * looting)) < 0 || chance == 100;
|
||||
}
|
||||
|
||||
public int getMin() {
|
||||
return min;
|
||||
return this.min;
|
||||
}
|
||||
|
||||
public void setMin(int min) {
|
||||
@ -248,7 +247,7 @@ public class Loot {
|
||||
}
|
||||
|
||||
public int getMax() {
|
||||
return max;
|
||||
return this.max;
|
||||
}
|
||||
|
||||
public void setMax(int max) {
|
||||
@ -256,7 +255,7 @@ public class Loot {
|
||||
}
|
||||
|
||||
public int getDamageMax() {
|
||||
return damageMax == null ? 0 : damageMax;
|
||||
return this.damageMax == null ? 0 : this.damageMax;
|
||||
}
|
||||
|
||||
public void setDamageMax(int damageMax) {
|
||||
@ -264,7 +263,7 @@ public class Loot {
|
||||
}
|
||||
|
||||
public int getDamageMin() {
|
||||
return damageMin == null ? 0 : damageMin;
|
||||
return this.damageMin == null ? 0 : this.damageMin;
|
||||
}
|
||||
|
||||
public void setDamageMin(int damageMin) {
|
||||
@ -272,15 +271,15 @@ public class Loot {
|
||||
}
|
||||
|
||||
public int getAmountToDrop(int looting) {
|
||||
return min == max ? (max + getLooting(looting)) : new Random().nextInt((max + getLooting(looting)) - min + 1) + min;
|
||||
return this.min == this.max ? (this.max + getLooting(looting)) : new Random().nextInt((this.max + getLooting(looting)) - this.min + 1) + this.min;
|
||||
}
|
||||
|
||||
public int getLooting(int looting) {
|
||||
return allowLootingEnchant ? looting : 0;
|
||||
return this.allowLootingEnchant ? looting : 0;
|
||||
}
|
||||
|
||||
public boolean isAllowLootingEnchant() {
|
||||
return allowLootingEnchant;
|
||||
return this.allowLootingEnchant;
|
||||
}
|
||||
|
||||
public void setAllowLootingEnchant(boolean allowLootingEnchant) {
|
||||
@ -295,7 +294,7 @@ public class Loot {
|
||||
this.childDropCountMin = 1;
|
||||
this.childDropCountMax = 1;
|
||||
|
||||
if (childLoot == null) {
|
||||
if (this.childLoot == null) {
|
||||
this.childLoot = new ArrayList<>();
|
||||
}
|
||||
|
||||
@ -303,7 +302,7 @@ public class Loot {
|
||||
}
|
||||
|
||||
public void removeChildLoot(Loot loot) {
|
||||
if (childLoot == null) {
|
||||
if (this.childLoot == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
@ -311,11 +310,11 @@ public class Loot {
|
||||
}
|
||||
|
||||
public List<Loot> getChildLoot() {
|
||||
return childLoot == null ? new ArrayList<>() : new ArrayList<>(childLoot);
|
||||
return this.childLoot == null ? new ArrayList<>() : new ArrayList<>(this.childLoot);
|
||||
}
|
||||
|
||||
public List<EntityType> getOnlyDropFor() {
|
||||
return onlyDropFor == null ? new ArrayList<>() : new ArrayList<>(onlyDropFor);
|
||||
return this.onlyDropFor == null ? new ArrayList<>() : new ArrayList<>(this.onlyDropFor);
|
||||
}
|
||||
|
||||
public void addOnlyDropFor(EntityType... types) {
|
||||
@ -336,23 +335,23 @@ public class Loot {
|
||||
}
|
||||
|
||||
public Integer getChildDropCountMin() {
|
||||
return childDropCountMin;
|
||||
return this.childDropCountMin;
|
||||
}
|
||||
|
||||
public Integer getChildDropCountMax() {
|
||||
return childDropCountMax;
|
||||
return this.childDropCountMax;
|
||||
}
|
||||
|
||||
public int getChildDropCount() {
|
||||
if (childDropCountMin == null || childDropCountMax == null) {
|
||||
if (this.childDropCountMin == null || this.childDropCountMax == null) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return new Random().nextInt(childDropCountMax - childDropCountMin + 1) + childDropCountMin;
|
||||
return new Random().nextInt(this.childDropCountMax - this.childDropCountMin + 1) + this.childDropCountMin;
|
||||
}
|
||||
|
||||
public boolean isRequireCharged() {
|
||||
return requireCharged;
|
||||
return this.requireCharged;
|
||||
}
|
||||
|
||||
public void setRequireCharged(boolean requireCharged) {
|
||||
|
@ -30,11 +30,11 @@ public final class LootBuilder {
|
||||
return this;
|
||||
}
|
||||
|
||||
public LootBuilder addEnchants(Tuple... tuples) {
|
||||
public LootBuilder addEnchants(Tuple<String, Integer>... tuples) {
|
||||
Map<String, Integer> enchants = new HashMap<>();
|
||||
|
||||
for (Tuple tuple : tuples) {
|
||||
enchants.put((String) tuple.getKey(), (int) tuple.getValue());
|
||||
for (Tuple<String, Integer> tuple : tuples) {
|
||||
enchants.put(tuple.getKey(), tuple.getValue());
|
||||
}
|
||||
|
||||
this.loot.setEnchants(enchants);
|
||||
|
@ -33,13 +33,13 @@ public class LootManager {
|
||||
}
|
||||
|
||||
public Lootable addLootable(Lootable lootable) {
|
||||
return registeredLootables.put(lootable.getKey(), lootable);
|
||||
return this.registeredLootables.put(lootable.getKey(), lootable);
|
||||
}
|
||||
|
||||
public void removeLootable(String key) {
|
||||
registeredLootables.remove(key);
|
||||
this.registeredLootables.remove(key);
|
||||
|
||||
File file = new File(lootables.getLootablesDir(), key.toLowerCase() + ".json");
|
||||
File file = new File(this.lootables.getLootablesDir(), key.toLowerCase() + ".json");
|
||||
file.delete();
|
||||
}
|
||||
|
||||
@ -58,12 +58,13 @@ public class LootManager {
|
||||
((Math.random() * 100) - rerollChance < 0 || rerollChance == 100) &&
|
||||
loot.runChance(looting, murderWeapon)) {
|
||||
|
||||
if (loot.getOnlyDropFor().size() != 0
|
||||
if (!loot.getOnlyDropFor().isEmpty()
|
||||
&& loot.getOnlyDropFor().stream().noneMatch(type -> looter != null && type == looter)
|
||||
|| !isCharged && loot.isRequireCharged())
|
||||
|| !isCharged && loot.isRequireCharged()) {
|
||||
return toDrop;
|
||||
}
|
||||
|
||||
if (loot.getChildLoot().size() > 0) {
|
||||
if (!loot.getChildLoot().isEmpty()) {
|
||||
List<Loot> childLoot = loot.getChildLoot();
|
||||
Collections.shuffle(childLoot);
|
||||
|
||||
@ -153,9 +154,9 @@ public class LootManager {
|
||||
}
|
||||
|
||||
public void loadLootables() {
|
||||
registeredLootables.clear();
|
||||
this.registeredLootables.clear();
|
||||
|
||||
File dir = new File(lootables.getLootablesDir());
|
||||
File dir = new File(this.lootables.getLootablesDir());
|
||||
File[] directoryListing = dir.listFiles();
|
||||
|
||||
if (directoryListing != null) {
|
||||
@ -170,7 +171,7 @@ public class LootManager {
|
||||
|
||||
Lootable lootable = gson.fromJson(reader, Lootable.class);
|
||||
|
||||
if (lootable.getRegisteredLoot().size() != 0) {
|
||||
if (!lootable.getRegisteredLoot().isEmpty()) {
|
||||
addLootable(lootable);
|
||||
}
|
||||
|
||||
@ -183,13 +184,13 @@ public class LootManager {
|
||||
}
|
||||
|
||||
public void saveLootables(boolean defaults) {
|
||||
File dir = new File(lootables.getLootablesDir());
|
||||
File dir = new File(this.lootables.getLootablesDir());
|
||||
dir.mkdir();
|
||||
|
||||
// Save to file
|
||||
for (Lootable lootable : registeredLootables.values()) {
|
||||
for (Lootable lootable : this.registeredLootables.values()) {
|
||||
try {
|
||||
File file = new File(lootables.getLootablesDir(), lootable.getKey().toLowerCase() + ".json");
|
||||
File file = new File(this.lootables.getLootablesDir(), lootable.getKey().toLowerCase() + ".json");
|
||||
|
||||
if (file.exists() && defaults) {
|
||||
continue;
|
||||
@ -205,11 +206,11 @@ public class LootManager {
|
||||
}
|
||||
|
||||
if (defaults) {
|
||||
registeredLootables.clear();
|
||||
this.registeredLootables.clear();
|
||||
}
|
||||
}
|
||||
|
||||
public Map<String, Lootable> getRegisteredLootables() {
|
||||
return Collections.unmodifiableMap(registeredLootables);
|
||||
return Collections.unmodifiableMap(this.registeredLootables);
|
||||
}
|
||||
}
|
||||
|
@ -22,19 +22,19 @@ public class Lootable {
|
||||
public Lootable(String key, Loot... loots) {
|
||||
this.type = key;
|
||||
|
||||
registeredLoot.addAll(Arrays.asList(loots));
|
||||
this.registeredLoot.addAll(Arrays.asList(loots));
|
||||
}
|
||||
|
||||
public List<Loot> getRegisteredLoot() {
|
||||
return new ArrayList<>(registeredLoot);
|
||||
return new ArrayList<>(this.registeredLoot);
|
||||
}
|
||||
|
||||
public void registerLoot(Loot... loots) {
|
||||
registeredLoot.addAll(Arrays.asList(loots));
|
||||
this.registeredLoot.addAll(Arrays.asList(loots));
|
||||
}
|
||||
|
||||
public String getKey() {
|
||||
return type;
|
||||
return this.type;
|
||||
}
|
||||
|
||||
public void removeLoot(Loot loot) {
|
||||
|
@ -14,14 +14,14 @@ public class EnchantChance {
|
||||
}
|
||||
|
||||
public Enchantment getEnchantment() {
|
||||
return enchantment;
|
||||
return this.enchantment;
|
||||
}
|
||||
|
||||
public int getLevel() {
|
||||
return level;
|
||||
return this.level;
|
||||
}
|
||||
|
||||
public double getChanceOverride() {
|
||||
return chanceOverride;
|
||||
return this.chanceOverride;
|
||||
}
|
||||
}
|
||||
|
@ -1,7 +1,8 @@
|
||||
package com.craftaro.core.math;
|
||||
|
||||
public class Eval {
|
||||
private int pos = -1, ch;
|
||||
private int pos = -1;
|
||||
private int ch;
|
||||
private final String toParse;
|
||||
private final String warningMessage;
|
||||
|
||||
|
@ -6,13 +6,13 @@ import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class MathUtils {
|
||||
private static final Map<String, Double> cache = new HashMap<>();
|
||||
private static final Map<String, Double> CACHE = new HashMap<>();
|
||||
|
||||
public static double eval(String toParse) {
|
||||
return eval(toParse, CraftaroCoreConstants.getProjectName() + " Eval Engine");
|
||||
}
|
||||
|
||||
public static double eval(String toParse, String warningMessage) {
|
||||
return cache.computeIfAbsent(toParse, t -> new Eval(toParse, warningMessage).parse());
|
||||
return CACHE.computeIfAbsent(toParse, t -> new Eval(toParse, warningMessage).parse());
|
||||
}
|
||||
}
|
||||
|
@ -8,7 +8,6 @@ import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class MonitoredThread {
|
||||
|
||||
private final String name;
|
||||
private final int timeout;
|
||||
private final TimeUnit timeUnit;
|
||||
@ -29,56 +28,57 @@ public class MonitoredThread {
|
||||
public void execute(Runnable runnable, boolean nonDisruptable) {
|
||||
this.nonDisruptable = nonDisruptable;
|
||||
StackTraceElement[] trace = Thread.currentThread().getStackTrace();
|
||||
executor.execute(() -> {
|
||||
started = Instant.now();
|
||||
this.executor.execute(() -> {
|
||||
this.started = Instant.now();
|
||||
this.trace = trace;
|
||||
try {
|
||||
runnable.run();
|
||||
} catch (Exception e) {
|
||||
StackTraceElement[] newTrace = new StackTraceElement[e.getStackTrace().length + trace.length];
|
||||
System.arraycopy(e.getStackTrace(), 0, newTrace, 0, e.getStackTrace().length);
|
||||
System.arraycopy(trace, 0, newTrace, e.getStackTrace().length, trace.length);
|
||||
e.setStackTrace(newTrace);
|
||||
System.out.println("Thread '" + name + "' failed with exception: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
} catch (Exception ex) {
|
||||
StackTraceElement[] newTrace = new StackTraceElement[ex.getStackTrace().length + trace.length];
|
||||
System.arraycopy(ex.getStackTrace(), 0, newTrace, 0, ex.getStackTrace().length);
|
||||
System.arraycopy(trace, 0, newTrace, ex.getStackTrace().length, trace.length);
|
||||
ex.setStackTrace(newTrace);
|
||||
System.out.println("Thread '" + this.name + "' failed with exception: " + ex.getMessage());
|
||||
ex.printStackTrace();
|
||||
}
|
||||
started = null;
|
||||
this.started = null;
|
||||
});
|
||||
}
|
||||
|
||||
public MonitoredThread start() {
|
||||
if (executor != null) {
|
||||
executor.shutdown();
|
||||
System.out.println("Thread '" + name + "' was restarted due to a stall. Stack trace:");
|
||||
for (StackTraceElement element : this.trace)
|
||||
if (this.executor != null) {
|
||||
this.executor.shutdown();
|
||||
System.out.println("Thread '" + this.name + "' was restarted due to a stall. Stack trace:");
|
||||
for (StackTraceElement element : this.trace) {
|
||||
System.out.println(" " + element.toString());
|
||||
}
|
||||
}
|
||||
executor = Executors.newSingleThreadScheduledExecutor(r -> new Thread(r, name));
|
||||
this.executor = Executors.newSingleThreadScheduledExecutor(r -> new Thread(r, this.name));
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
return this.name;
|
||||
}
|
||||
|
||||
public boolean isStalled() {
|
||||
return !nonDisruptable && started != null && started.plusMillis(timeUnit.toMillis(timeout)).isBefore(Instant.now())
|
||||
|| started != null && started.plusMillis(TimeUnit.HOURS.toMillis(1)).isBefore(Instant.now());
|
||||
return !this.nonDisruptable && this.started != null && this.started.plusMillis(this.timeUnit.toMillis(this.timeout)).isBefore(Instant.now())
|
||||
|| this.started != null && this.started.plusMillis(TimeUnit.HOURS.toMillis(1)).isBefore(Instant.now());
|
||||
}
|
||||
|
||||
public boolean isRunning() {
|
||||
return started != null;
|
||||
return this.started != null;
|
||||
}
|
||||
|
||||
public Instant getStarted() {
|
||||
return started;
|
||||
return this.started;
|
||||
}
|
||||
|
||||
public ScheduledFuture<?> schedule(Runnable runnable, long delay, TimeUnit timeUnit) {
|
||||
return executor.schedule(runnable, delay, timeUnit);
|
||||
return this.executor.schedule(runnable, delay, timeUnit);
|
||||
}
|
||||
|
||||
public void destroy() {
|
||||
executor.shutdownNow();
|
||||
this.executor.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
@ -5,7 +5,6 @@ import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class MonitoredThreadPool {
|
||||
|
||||
private final HashSet<MonitoredThread> threads = new HashSet<>();
|
||||
private final String name;
|
||||
private final int size;
|
||||
@ -19,13 +18,14 @@ public class MonitoredThreadPool {
|
||||
this.size = size;
|
||||
this.threadTimeout = timeout;
|
||||
this.threadTimeoutUnit = timeUnit;
|
||||
for (int i = 0; i < size; i++)
|
||||
for (int i = 0; i < size; ++i) {
|
||||
createThread(name);
|
||||
}
|
||||
}
|
||||
|
||||
public MonitoredThread createThread(String name) {
|
||||
MonitoredThread thread = new MonitoredThread((name + "-" + latestThread++).toLowerCase(), threadTimeout, threadTimeoutUnit);
|
||||
threads.add(thread);
|
||||
MonitoredThread thread = new MonitoredThread((name + "-" + this.latestThread++).toLowerCase(), this.threadTimeout, this.threadTimeoutUnit);
|
||||
this.threads.add(thread);
|
||||
return thread;
|
||||
}
|
||||
|
||||
@ -49,7 +49,7 @@ public class MonitoredThreadPool {
|
||||
}
|
||||
|
||||
private MonitoredThread getHealthyThread() {
|
||||
for (MonitoredThread thread : threads) {
|
||||
for (MonitoredThread thread : this.threads) {
|
||||
if (!thread.isRunning()) {
|
||||
return thread;
|
||||
} else if (thread.isStalled()) {
|
||||
@ -63,9 +63,11 @@ public class MonitoredThreadPool {
|
||||
|
||||
public int getRunningThreads() {
|
||||
int runningThreads = 0;
|
||||
for (MonitoredThread thread : threads)
|
||||
if (thread.isRunning())
|
||||
for (MonitoredThread thread : this.threads) {
|
||||
if (thread.isRunning()) {
|
||||
runningThreads++;
|
||||
}
|
||||
}
|
||||
return runningThreads;
|
||||
}
|
||||
|
||||
|
@ -3,9 +3,7 @@ package com.craftaro.core.thread;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class SingleMonitoredThread extends MonitoredThreadPool {
|
||||
|
||||
public SingleMonitoredThread(String name, int timeout, TimeUnit timeUnit) {
|
||||
super(name, 1, timeout, timeUnit);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -8,7 +8,6 @@ import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public abstract class TaskScheduler {
|
||||
|
||||
private final SongodaPlugin plugin;
|
||||
private final Map<TaskWrapper, Long> tasks = new ConcurrentHashMap<>();
|
||||
private BukkitRunnable runnable;
|
||||
@ -18,31 +17,31 @@ public abstract class TaskScheduler {
|
||||
}
|
||||
|
||||
private void startScheduler() {
|
||||
if (runnable == null || runnable.isCancelled()) {
|
||||
runnable = new BukkitRunnable() {
|
||||
if (this.runnable == null || this.runnable.isCancelled()) {
|
||||
this.runnable = new BukkitRunnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
executeTasks();
|
||||
}
|
||||
};
|
||||
runnable.runTaskTimerAsynchronously(plugin, 20L, 20L);
|
||||
this.runnable.runTaskTimerAsynchronously(this.plugin, 20L, 20L);
|
||||
}
|
||||
}
|
||||
|
||||
private void stopScheduler() {
|
||||
if (runnable != null && !runnable.isCancelled()) {
|
||||
runnable.cancel();
|
||||
if (this.runnable != null && !this.runnable.isCancelled()) {
|
||||
this.runnable.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
private void executeTasks() {
|
||||
if (tasks.isEmpty()) {
|
||||
if (this.tasks.isEmpty()) {
|
||||
stopScheduler();
|
||||
return;
|
||||
}
|
||||
|
||||
long currentTime = System.currentTimeMillis();
|
||||
Iterator<Map.Entry<TaskWrapper, Long>> iterator = tasks.entrySet().iterator();
|
||||
Iterator<Map.Entry<TaskWrapper, Long>> iterator = this.tasks.entrySet().iterator();
|
||||
|
||||
while (iterator.hasNext()) {
|
||||
Map.Entry<TaskWrapper, Long> entry = iterator.next();
|
||||
@ -55,7 +54,7 @@ public abstract class TaskScheduler {
|
||||
public void run() {
|
||||
taskWrapper.getTask().run();
|
||||
}
|
||||
}.runTaskAsynchronously(plugin);
|
||||
}.runTaskAsynchronously(this.plugin);
|
||||
} else {
|
||||
// Run the task synchronously
|
||||
new BukkitRunnable() {
|
||||
@ -63,7 +62,7 @@ public abstract class TaskScheduler {
|
||||
public void run() {
|
||||
taskWrapper.getTask().run();
|
||||
}
|
||||
}.runTask(plugin);
|
||||
}.runTask(this.plugin);
|
||||
}
|
||||
iterator.remove();
|
||||
}
|
||||
@ -71,7 +70,7 @@ public abstract class TaskScheduler {
|
||||
}
|
||||
|
||||
public synchronized void addTask(Runnable task, long delay, boolean async) {
|
||||
tasks.put(new TaskWrapper(task, async), System.currentTimeMillis() + delay);
|
||||
this.tasks.put(new TaskWrapper(task, async), System.currentTimeMillis() + delay);
|
||||
startScheduler();
|
||||
}
|
||||
|
||||
@ -89,11 +88,11 @@ public abstract class TaskScheduler {
|
||||
}
|
||||
|
||||
public Runnable getTask() {
|
||||
return task;
|
||||
return this.task;
|
||||
}
|
||||
|
||||
public boolean isAsync() {
|
||||
return async;
|
||||
return this.async;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -7,25 +7,25 @@ import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
|
||||
public class ColorUtils {
|
||||
private static final Map<ColorCode, ColorSet<Integer, Integer, Integer>> colorMap = new HashMap<>();
|
||||
private static final Map<ColorCode, ColorSet<Integer, Integer, Integer>> COLOR_MAP = new HashMap<>();
|
||||
|
||||
static {
|
||||
colorMap.put(ColorCode.BLACK, new ColorSet<>(0, 0, 0));
|
||||
colorMap.put(ColorCode.DARK_BLUE, new ColorSet<>(0, 0, 170));
|
||||
colorMap.put(ColorCode.DARK_GREEN, new ColorSet<>(0, 170, 0));
|
||||
colorMap.put(ColorCode.DARK_AQUA, new ColorSet<>(0, 170, 170));
|
||||
colorMap.put(ColorCode.DARK_RED, new ColorSet<>(170, 0, 0));
|
||||
colorMap.put(ColorCode.DARK_PURPLE, new ColorSet<>(170, 0, 170));
|
||||
colorMap.put(ColorCode.GOLD, new ColorSet<>(255, 170, 0));
|
||||
colorMap.put(ColorCode.GRAY, new ColorSet<>(170, 170, 170));
|
||||
colorMap.put(ColorCode.DARK_GRAY, new ColorSet<>(85, 85, 85));
|
||||
colorMap.put(ColorCode.BLUE, new ColorSet<>(85, 85, 255));
|
||||
colorMap.put(ColorCode.GREEN, new ColorSet<>(85, 255, 85));
|
||||
colorMap.put(ColorCode.AQUA, new ColorSet<>(85, 255, 255));
|
||||
colorMap.put(ColorCode.RED, new ColorSet<>(255, 85, 85));
|
||||
colorMap.put(ColorCode.LIGHT_PURPLE, new ColorSet<>(255, 85, 255));
|
||||
colorMap.put(ColorCode.YELLOW, new ColorSet<>(255, 255, 85));
|
||||
colorMap.put(ColorCode.WHITE, new ColorSet<>(255, 255, 255));
|
||||
COLOR_MAP.put(ColorCode.BLACK, new ColorSet<>(0, 0, 0));
|
||||
COLOR_MAP.put(ColorCode.DARK_BLUE, new ColorSet<>(0, 0, 170));
|
||||
COLOR_MAP.put(ColorCode.DARK_GREEN, new ColorSet<>(0, 170, 0));
|
||||
COLOR_MAP.put(ColorCode.DARK_AQUA, new ColorSet<>(0, 170, 170));
|
||||
COLOR_MAP.put(ColorCode.DARK_RED, new ColorSet<>(170, 0, 0));
|
||||
COLOR_MAP.put(ColorCode.DARK_PURPLE, new ColorSet<>(170, 0, 170));
|
||||
COLOR_MAP.put(ColorCode.GOLD, new ColorSet<>(255, 170, 0));
|
||||
COLOR_MAP.put(ColorCode.GRAY, new ColorSet<>(170, 170, 170));
|
||||
COLOR_MAP.put(ColorCode.DARK_GRAY, new ColorSet<>(85, 85, 85));
|
||||
COLOR_MAP.put(ColorCode.BLUE, new ColorSet<>(85, 85, 255));
|
||||
COLOR_MAP.put(ColorCode.GREEN, new ColorSet<>(85, 255, 85));
|
||||
COLOR_MAP.put(ColorCode.AQUA, new ColorSet<>(85, 255, 255));
|
||||
COLOR_MAP.put(ColorCode.RED, new ColorSet<>(255, 85, 85));
|
||||
COLOR_MAP.put(ColorCode.LIGHT_PURPLE, new ColorSet<>(255, 85, 255));
|
||||
COLOR_MAP.put(ColorCode.YELLOW, new ColorSet<>(255, 255, 85));
|
||||
COLOR_MAP.put(ColorCode.WHITE, new ColorSet<>(255, 255, 255));
|
||||
}
|
||||
|
||||
private static class ColorSet<R, G, B> {
|
||||
@ -54,7 +54,7 @@ public class ColorUtils {
|
||||
|
||||
public static ColorCode fromRGB(int r, int g, int b) {
|
||||
TreeMap<Integer, ColorCode> closest = new TreeMap<>();
|
||||
colorMap.forEach((color, set) -> {
|
||||
COLOR_MAP.forEach((color, set) -> {
|
||||
int red = Math.abs(r - set.getRed());
|
||||
int green = Math.abs(g - set.getGreen());
|
||||
int blue = Math.abs(b - set.getBlue());
|
||||
|
@ -60,7 +60,7 @@ public class NumberUtils {
|
||||
*/
|
||||
@Deprecated
|
||||
public static boolean isNumeric(String s) {
|
||||
if (s == null || s.equals("")) {
|
||||
if (s == null || s.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
@ -17,23 +17,24 @@ import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class TextUtils {
|
||||
private static final List<Charset> supportedCharsets = new ArrayList<>();
|
||||
private static final List<Charset> SUPPORTED_CHARSETS = new ArrayList<>();
|
||||
|
||||
static {
|
||||
supportedCharsets.add(StandardCharsets.UTF_8); // UTF-8 BOM: EF BB BF
|
||||
supportedCharsets.add(StandardCharsets.ISO_8859_1); // also starts with EF BB BF
|
||||
SUPPORTED_CHARSETS.add(StandardCharsets.UTF_8); // UTF-8 BOM: EF BB BF
|
||||
SUPPORTED_CHARSETS.add(StandardCharsets.ISO_8859_1); // also starts with EF BB BF
|
||||
// supportedCharsets.add(StandardCharsets.UTF_16LE); // FF FE
|
||||
// supportedCharsets.add(StandardCharsets.UTF_16BE); // FE FF
|
||||
// supportedCharsets.add(StandardCharsets.UTF_16);
|
||||
|
||||
// FIXME: One unsupported charset causes other ones not to be tried
|
||||
try {
|
||||
supportedCharsets.add(Charset.forName("windows-1253"));
|
||||
supportedCharsets.add(Charset.forName("ISO-8859-7"));
|
||||
} catch (Exception ignore) { // UnsupportedCharsetException technically can be thrown, but can also be ignored
|
||||
SUPPORTED_CHARSETS.add(Charset.forName("windows-1253"));
|
||||
SUPPORTED_CHARSETS.add(Charset.forName("ISO-8859-7"));
|
||||
} catch (
|
||||
Exception ignore) { // UnsupportedCharsetException technically can be thrown, but can also be ignored
|
||||
}
|
||||
|
||||
supportedCharsets.add(StandardCharsets.US_ASCII);
|
||||
SUPPORTED_CHARSETS.add(StandardCharsets.US_ASCII);
|
||||
}
|
||||
|
||||
public static String formatText(String text) {
|
||||
@ -41,7 +42,7 @@ public class TextUtils {
|
||||
}
|
||||
|
||||
public static String formatText(String text, boolean capitalize) {
|
||||
if (text == null || text.equals("")) {
|
||||
if (text == null || text.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
|
||||
@ -103,11 +104,10 @@ public class TextUtils {
|
||||
* Note: Do not use semi-colons or § in this string, or they will be lost when decoding!
|
||||
*
|
||||
* @param s string to convert
|
||||
*
|
||||
* @return encoded string
|
||||
*/
|
||||
public static String convertToInvisibleLoreString(String s) {
|
||||
if (s == null || s.equals("")) {
|
||||
if (s == null || s.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
|
||||
@ -126,14 +126,13 @@ public class TextUtils {
|
||||
/**
|
||||
* Convert a string to an invisible colored string <br />
|
||||
* (Not safe to use as lore) <br />
|
||||
* Note: Do not use semi-colons or § in this string, or they will be lost when decoding!
|
||||
* Note: Do not use semicolons or § in this string, or they will be lost when decoding!
|
||||
*
|
||||
* @param s string to convert
|
||||
*
|
||||
* @return encoded string
|
||||
*/
|
||||
public static String convertToInvisibleString(String s) {
|
||||
if (s == null || s.equals("")) {
|
||||
if (s == null || s.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
|
||||
@ -147,27 +146,27 @@ public class TextUtils {
|
||||
}
|
||||
|
||||
// TODO: Is there a more reliable way?
|
||||
|
||||
/**
|
||||
* Removes color markers used to encode strings as invisible text
|
||||
*
|
||||
* @param s encoded string
|
||||
*
|
||||
* @return string with color markers removed
|
||||
*/
|
||||
public static String convertFromInvisibleString(String s) {
|
||||
if (s == null || s.equals("")) {
|
||||
if (s == null || s.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
|
||||
return s.replaceAll(ChatColor.COLOR_CHAR + ";" + ChatColor.COLOR_CHAR + "|" + ChatColor.COLOR_CHAR, "");
|
||||
}
|
||||
|
||||
public static Charset detectCharset(File f, Charset def) {
|
||||
public static Charset detectCharset(File file, Charset def) {
|
||||
byte[] buffer = new byte[2048];
|
||||
int len;
|
||||
|
||||
// Read the first 2 KiB of the file and test the file's encoding
|
||||
try (FileInputStream input = new FileInputStream(f)) {
|
||||
try (FileInputStream input = new FileInputStream(file)) {
|
||||
len = input.read(buffer);
|
||||
} catch (Exception ex) {
|
||||
return null;
|
||||
@ -205,10 +204,12 @@ public class TextUtils {
|
||||
}
|
||||
}
|
||||
|
||||
// Look for last Whitespace Character and ignore potentially broken words/multi-byte characters
|
||||
// Look for the last Whitespace Character and ignore potentially broken words/multibyte characters
|
||||
int newLen = len;
|
||||
for (; newLen > 0; --newLen) {
|
||||
if (Character.isWhitespace(data[newLen - 1])) break;
|
||||
if (Character.isWhitespace(data[newLen - 1])) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Buffer got too small? => checking whole buffer
|
||||
@ -219,7 +220,7 @@ public class TextUtils {
|
||||
ByteBuffer bBuff = ByteBuffer.wrap(data, 0, newLen).asReadOnlyBuffer();
|
||||
|
||||
// Check through a list of charsets and return the first one that could decode the buffer
|
||||
for (Charset charset : supportedCharsets) {
|
||||
for (Charset charset : SUPPORTED_CHARSETS) {
|
||||
if (charset != null && isCharset(bBuff, charset)) {
|
||||
return charset;
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user