diff --git a/src/main/java/io/github/znetworkw/znpcservers/cache/CacheCategory.java b/src/main/java/io/github/znetworkw/znpcservers/cache/CacheCategory.java index b218ecb..f653135 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/cache/CacheCategory.java +++ b/src/main/java/io/github/znetworkw/znpcservers/cache/CacheCategory.java @@ -16,8 +16,6 @@ public enum CacheCategory { SERVER_NETWORK("server.network"), SERVER("server"); - private static final String EMPTY_STRING = ""; - private final String subPackageName; private final String packageName; diff --git a/src/main/java/io/github/znetworkw/znpcservers/cache/CachePackage.java b/src/main/java/io/github/znetworkw/znpcservers/cache/CachePackage.java index 3d776fd..fcc4288 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/cache/CachePackage.java +++ b/src/main/java/io/github/znetworkw/znpcservers/cache/CachePackage.java @@ -7,10 +7,6 @@ public enum CachePackage { CRAFT_BUKKIT("org.bukkit.craftbukkit." + Utils.getBukkitPackage()), MINECRAFT_SERVER("net.minecraft"); - private static final String EMPTY_STRING = ""; - - private static final String DOT = "."; - private final String fixedPackageName; CachePackage(String packageName) { diff --git a/src/main/java/io/github/znetworkw/znpcservers/cache/TypeCache.java b/src/main/java/io/github/znetworkw/znpcservers/cache/TypeCache.java index 543291e..a7272c9 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/cache/TypeCache.java +++ b/src/main/java/io/github/znetworkw/znpcservers/cache/TypeCache.java @@ -2,7 +2,6 @@ package io.github.znetworkw.znpcservers.cache; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; -import com.google.common.collect.UnmodifiableIterator; import java.lang.reflect.Constructor; import java.lang.reflect.Field; @@ -53,8 +52,6 @@ public interface TypeCache { } class CacheBuilder { - private static final String EMPTY_STRING = ""; - private final CachePackage cachePackage; private final CacheCategory cacheCategory; @@ -67,8 +64,6 @@ public interface TypeCache { private final String additionalData; - private final Class clazz; - private final ImmutableList[]> parameterTypes; private final Class expectType; @@ -87,7 +82,6 @@ public interface TypeCache { this.fieldName = fieldName; this.additionalData = additionalData; this.parameterTypes = parameterTypes; - this.clazz = null; this.expectType = expectType; } @@ -97,20 +91,18 @@ public interface TypeCache { public CacheBuilder withClassName(String className) { return new CacheBuilder(this.cachePackage, this.cacheCategory, - (List) ImmutableList.builder().addAll(this.className) + new ImmutableList.Builder().addAll(this.className) .add(formatClass(className)).build(), this.fieldName, this.methods, this.additionalData, this.parameterTypes, this.expectType); } public CacheBuilder withClassName(Class clazz) { return new CacheBuilder(this.cachePackage, this.cacheCategory, - - (List) ImmutableList.builder().addAll(this.className).add((clazz == null) ? "" : clazz.getName()).build(), this.fieldName, this.methods, this.additionalData, this.parameterTypes, this.expectType); + new ImmutableList.Builder().addAll(this.className).add((clazz == null) ? "" : clazz.getName()).build(), this.fieldName, this.methods, this.additionalData, this.parameterTypes, this.expectType); } public CacheBuilder withMethodName(String methodName) { return new CacheBuilder(this.cachePackage, this.cacheCategory, this.className, this.fieldName, - - (List) ImmutableList.builder().addAll(this.methods).add(methodName).build(), this.additionalData, this.parameterTypes, this.expectType); + new ImmutableList.Builder().addAll(this.methods).add(methodName).build(), this.additionalData, this.parameterTypes, this.expectType); } public CacheBuilder withFieldName(String fieldName) { @@ -123,8 +115,7 @@ public interface TypeCache { public CacheBuilder withParameterTypes(Class... types) { return new CacheBuilder(this.cachePackage, this.cacheCategory, this.className, this.fieldName, this.methods, this.additionalData, - - ImmutableList.copyOf(Iterables.concat((Iterable) this.parameterTypes, (Iterable) ImmutableList.of(types))), this.expectType); + ImmutableList.copyOf(Iterables.concat(this.parameterTypes, ImmutableList.of(types))), this.expectType); } public CacheBuilder withExpectResult(Class expectType) { @@ -132,15 +123,11 @@ public interface TypeCache { } protected String formatClass(String className) { - switch (this.cachePackage) { - case MINECRAFT_SERVER: - case CRAFT_BUKKIT: - return String.format(((this.cachePackage == CachePackage.CRAFT_BUKKIT) ? - this.cachePackage.getFixedPackageName() : this.cachePackage.getForCategory(this.cacheCategory, this.additionalData)) + ".%s", className); - case DEFAULT: - return className; - } - throw new IllegalArgumentException("Unexpected package " + this.cachePackage.name()); + return switch (this.cachePackage) { + case MINECRAFT_SERVER, CRAFT_BUKKIT -> String.format(((this.cachePackage == CachePackage.CRAFT_BUKKIT) ? + this.cachePackage.getFixedPackageName() : this.cachePackage.getForCategory(this.cacheCategory, this.additionalData)) + ".%s", className); + case DEFAULT -> className; + }; } } @@ -160,7 +147,7 @@ public interface TypeCache { for (String classes : cacheBuilder.className) { try { this.BUILDER_CLASS = Class.forName(classes); - } catch (ClassNotFoundException classNotFoundException) { + } catch (ClassNotFoundException ignored) { } } } @@ -219,7 +206,7 @@ public interface TypeCache { try { Method maybeGet; if (!Iterables.isEmpty(this.cacheBuilder.parameterTypes)) { - maybeGet = this.BUILDER_CLASS.getDeclaredMethod(methodName, (Class[]) Iterables.get((Iterable) this.cacheBuilder.parameterTypes, 0)); + maybeGet = this.BUILDER_CLASS.getDeclaredMethod(methodName, Iterables.get(this.cacheBuilder.parameterTypes, 0)); } else { maybeGet = this.BUILDER_CLASS.getDeclaredMethod(methodName); } @@ -227,7 +214,7 @@ public interface TypeCache { continue; maybeGet.setAccessible(true); methodThis = maybeGet; - } catch (NoSuchMethodException noSuchMethodException) { + } catch (NoSuchMethodException ignored) { } } return methodThis; @@ -279,15 +266,14 @@ public interface TypeCache { protected Constructor onLoad() throws NoSuchMethodException { Constructor constructor = null; if (Iterables.size(this.cacheBuilder.parameterTypes) > 1) { - for (UnmodifiableIterator[]> unmodifiableIterator = this.cacheBuilder.parameterTypes.iterator(); unmodifiableIterator.hasNext(); ) { - Class[] keyParameters = unmodifiableIterator.next(); + for (Class[] keyParameters : this.cacheBuilder.parameterTypes) { try { constructor = this.BUILDER_CLASS.getDeclaredConstructor(keyParameters); - } catch (NoSuchMethodException noSuchMethodException) { + } catch (NoSuchMethodException ignored) { } } } else { - constructor = (Iterables.size(this.cacheBuilder.parameterTypes) > 0) ? this.BUILDER_CLASS.getDeclaredConstructor((Class[]) Iterables.get((Iterable) this.cacheBuilder.parameterTypes, 0)) : this.BUILDER_CLASS.getDeclaredConstructor(); + constructor = (Iterables.size(this.cacheBuilder.parameterTypes) > 0) ? this.BUILDER_CLASS.getDeclaredConstructor(Iterables.get(this.cacheBuilder.parameterTypes, 0)) : this.BUILDER_CLASS.getDeclaredConstructor(); } if (constructor != null) constructor.setAccessible(true); @@ -301,10 +287,10 @@ public interface TypeCache { } protected Enum[] onLoad() { - Enum[] arrayOfEnum = (Enum[]) this.BUILDER_CLASS.getEnumConstants(); + Enum[] arrayOfEnum = (Enum[]) this.BUILDER_CLASS.getEnumConstants(); for (Enum enumConstant : arrayOfEnum) TypeCache.ClassCache.register(enumConstant.name(), enumConstant, this.BUILDER_CLASS); - return (Enum[]) arrayOfEnum; + return arrayOfEnum; } } } diff --git a/src/main/java/io/github/znetworkw/znpcservers/commands/Command.java b/src/main/java/io/github/znetworkw/znpcservers/commands/Command.java index 7769713..50bb97e 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/commands/Command.java +++ b/src/main/java/io/github/znetworkw/znpcservers/commands/Command.java @@ -11,6 +11,7 @@ import org.bukkit.command.defaults.BukkitCommand; import java.lang.reflect.Method; import java.util.*; +@SuppressWarnings("deprecation") public class Command extends BukkitCommand { private static final String WHITESPACE = " "; @@ -69,15 +70,13 @@ public class Command extends BukkitCommand { public boolean execute(CommandSender sender, String commandLabel, String[] args) { Optional> subCommandOptional = this.subCommands.entrySet().stream().filter(command -> command.getKey().name().contentEquals((args.length > 0) ? args[0] : "")).findFirst(); - if (!subCommandOptional.isPresent()) { + if (subCommandOptional.isEmpty()) { sender.sendMessage(ChatColor.RED + "can't find command: " + commandLabel + "."); return false; } try { Map.Entry subCommand = subCommandOptional.get(); - ((CommandInvoker) subCommand.getValue()).execute(new CommandSender(sender), - - loadArgs(subCommand.getKey(), Arrays.asList(args))); + subCommand.getValue().execute(new io.github.znetworkw.znpcservers.commands.CommandSender(sender), loadArgs(subCommand.getKey(), Arrays.asList(args))); } catch (CommandExecuteException e) { sender.sendMessage(ChatColor.RED + "can't execute command."); e.printStackTrace(); diff --git a/src/main/java/io/github/znetworkw/znpcservers/commands/CommandSender.java b/src/main/java/io/github/znetworkw/znpcservers/commands/CommandSender.java index 5e0e023..e18d24d 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/commands/CommandSender.java +++ b/src/main/java/io/github/znetworkw/znpcservers/commands/CommandSender.java @@ -12,6 +12,7 @@ import org.bukkit.entity.Player; import java.util.Arrays; import java.util.stream.Collectors; +@SuppressWarnings("deprecation") public class CommandSender { static final Joiner LINE_SEPARATOR_JOINER = Joiner.on("\n"); diff --git a/src/main/java/io/github/znetworkw/znpcservers/commands/list/DefaultCommand.java b/src/main/java/io/github/znetworkw/znpcservers/commands/list/DefaultCommand.java index bd90d3d..4bb4ad8 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/commands/list/DefaultCommand.java +++ b/src/main/java/io/github/znetworkw/znpcservers/commands/list/DefaultCommand.java @@ -29,18 +29,16 @@ import java.util.List; import java.util.Map; import java.util.Objects; +@SuppressWarnings({"UnstableApiUsage", "deprecation"}) public class DefaultCommand extends Command { - private static final String WHITESPACE = " "; - private static final Splitter SPACE_SPLITTER = Splitter.on(" "); private static final Joiner SPACE_JOINER = Joiner.on(" "); - private static final SkinFunction DO_APPLY_SKIN; - - static { - DO_APPLY_SKIN = ((sender, npc, skin) -> NPCSkin.forName(skin, ())); - } + private static final SkinFunction DO_APPLY_SKIN = (sender, npc, skin) -> NPCSkin.forName(skin, (values, ex) -> { + if (ex != null) throw new RuntimeException(ex); + npc.changeSkin(NPCSkin.forValues(values)); + }); public DefaultCommand() { super("znpcs"); @@ -69,7 +67,7 @@ public class DefaultCommand extends Command { Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.INVALID_NUMBER); return; } - boolean foundNPC = ConfigurationConstants.NPC_LIST.stream().anyMatch(npc -> (npc.getId() == id.intValue())); + boolean foundNPC = ConfigurationConstants.NPC_LIST.stream().anyMatch(npc -> (npc.getId() == id)); if (foundNPC) { Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.NPC_FOUND); return; @@ -80,7 +78,7 @@ public class DefaultCommand extends Command { return; } NPCType npcType = NPCType.valueOf(args.get("type").toUpperCase()); - NPC npc = ZNPCsPlus.createNPC(id.intValue(), npcType, sender.getPlayer().getLocation(), name); + NPC npc = ZNPCsPlus.createNPC(id, npcType, sender.getPlayer().getLocation(), name); Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.SUCCESS); if (npcType == NPCType.PLAYER) { Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.FETCHING_SKIN, name); @@ -99,12 +97,12 @@ public class DefaultCommand extends Command { Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.INVALID_NUMBER); return; } - NPC foundNPC = NPC.find(id.intValue()); + NPC foundNPC = NPC.find(id); if (foundNPC == null) { Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.NPC_NOT_FOUND); return; } - ZNPCsPlus.deleteNPC(id.intValue()); + ZNPCsPlus.deleteNPC(id); Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.SUCCESS); } @@ -121,7 +119,7 @@ public class DefaultCommand extends Command { textComponent.setColor(ChatColor.GREEN); parts.add(textComponent); TextComponent textComponent2 = new TextComponent("[TELEPORT]"); - textComponent2.setBold(Boolean.valueOf(true)); + textComponent2.setBold(true); textComponent2.setColor(ChatColor.DARK_GREEN); textComponent2.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, (new ComponentBuilder("Click to teleport this npc!")) @@ -131,7 +129,7 @@ public class DefaultCommand extends Command { parts.add(textComponent2); parts.add(new TextComponent(" ")); TextComponent textComponent3 = new TextComponent("[DELETE]"); - textComponent3.setBold(Boolean.valueOf(true)); + textComponent3.setBold(true); textComponent3.setColor(ChatColor.DARK_RED); textComponent3.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, (new ComponentBuilder("Click to delete this npc!")) @@ -155,7 +153,7 @@ public class DefaultCommand extends Command { Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.INVALID_NUMBER); return; } - NPC foundNPC = NPC.find(id.intValue()); + NPC foundNPC = NPC.find(id); if (foundNPC == null) { Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.NPC_NOT_FOUND); return; @@ -176,7 +174,7 @@ public class DefaultCommand extends Command { Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.INVALID_NUMBER); return; } - NPC foundNPC = NPC.find(id.intValue()); + NPC foundNPC = NPC.find(id); if (foundNPC == null) { Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.NPC_NOT_FOUND); return; @@ -202,7 +200,7 @@ public class DefaultCommand extends Command { Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.INVALID_NUMBER); return; } - NPC foundNPC = NPC.find(id.intValue()); + NPC foundNPC = NPC.find(id); if (foundNPC == null) { Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.NPC_NOT_FOUND); return; @@ -223,7 +221,7 @@ public class DefaultCommand extends Command { Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.INVALID_NUMBER); return; } - NPC foundNPC = NPC.find(id.intValue()); + NPC foundNPC = NPC.find(id); if (foundNPC == null) { Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.NPC_NOT_FOUND); return; @@ -244,7 +242,7 @@ public class DefaultCommand extends Command { Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.INVALID_NUMBER); return; } - NPC foundNPC = NPC.find(id.intValue()); + NPC foundNPC = NPC.find(id); if (foundNPC == null) { Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.NPC_NOT_FOUND); return; @@ -275,7 +273,7 @@ public class DefaultCommand extends Command { Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.INVALID_NUMBER); return; } - NPC foundNPC = NPC.find(id.intValue()); + NPC foundNPC = NPC.find(id); if (foundNPC == null) { Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.NPC_NOT_FOUND); return; @@ -289,7 +287,7 @@ public class DefaultCommand extends Command { Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.INVALID_NUMBER); return; } - NPC foundNPC = NPC.find(id.intValue()); + NPC foundNPC = NPC.find(id); if (foundNPC == null) { Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.NPC_NOT_FOUND); return; @@ -298,7 +296,7 @@ public class DefaultCommand extends Command { if (actionId == null) { Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.INVALID_NUMBER); } else { - if (actionId.intValue() >= foundNPC.getNpcPojo().getClickActions().size()) { + if (actionId >= foundNPC.getNpcPojo().getClickActions().size()) { Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.NO_ACTION_FOUND); return; } @@ -316,21 +314,21 @@ public class DefaultCommand extends Command { Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.INVALID_NUMBER); return; } - NPC foundNPC = NPC.find(id.intValue()); + NPC foundNPC = NPC.find(id); if (foundNPC == null) { Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.NPC_NOT_FOUND); return; } Integer actionId = Ints.tryParse(split.get(1)); Integer actionDelay = Ints.tryParse(split.get(2)); - if (actionId == null || id == null || actionDelay == null) { + if (actionId == null || actionDelay == null) { Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.INVALID_NUMBER); } else { - if (actionId.intValue() >= foundNPC.getNpcPojo().getClickActions().size()) { + if (actionId >= foundNPC.getNpcPojo().getClickActions().size()) { Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.NO_ACTION_FOUND); return; } - foundNPC.getNpcPojo().getClickActions().get(actionId.intValue()).setDelay(actionDelay.intValue()); + foundNPC.getNpcPojo().getClickActions().get(actionId).setDelay(actionDelay); Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.SUCCESS); } } else if (args.containsKey("list")) { @@ -339,7 +337,7 @@ public class DefaultCommand extends Command { Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.INVALID_NUMBER); return; } - NPC foundNPC = NPC.find(id.intValue()); + NPC foundNPC = NPC.find(id); if (foundNPC == null) { Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.NPC_NOT_FOUND); return; @@ -363,7 +361,7 @@ public class DefaultCommand extends Command { Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.INVALID_NUMBER); return; } - NPC foundNPC = NPC.find(id.intValue()); + NPC foundNPC = NPC.find(id); if (foundNPC == null) { Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.NPC_NOT_FOUND); return; @@ -388,7 +386,7 @@ public class DefaultCommand extends Command { Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.INVALID_NUMBER); return; } - NPC foundNPC = NPC.find(id.intValue()); + NPC foundNPC = NPC.find(id); if (foundNPC == null) { Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.NPC_NOT_FOUND); return; @@ -434,7 +432,7 @@ public class DefaultCommand extends Command { Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.INVALID_NUMBER); return; } - NPC foundNPC = NPC.find(id.intValue()); + NPC foundNPC = NPC.find(id); if (foundNPC == null) { Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.NPC_NOT_FOUND); return; @@ -480,7 +478,7 @@ public class DefaultCommand extends Command { Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.INVALID_NUMBER); return; } - NPC foundNPC = NPC.find(id.intValue()); + NPC foundNPC = NPC.find(id); if (foundNPC == null) { Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.NPC_NOT_FOUND); return; @@ -499,7 +497,7 @@ public class DefaultCommand extends Command { Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.INVALID_NUMBER); return; } - NPC foundNPC = NPC.find(id.intValue()); + NPC foundNPC = NPC.find(id); if (foundNPC == null) { Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.NPC_NOT_FOUND); return; @@ -509,7 +507,7 @@ public class DefaultCommand extends Command { Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.INVALID_NUMBER); return; } - foundNPC.getNpcPojo().setHologramHeight(givenHeight.doubleValue()); + foundNPC.getNpcPojo().setHologramHeight(givenHeight); foundNPC.getHologram().createHologram(); Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.SUCCESS); } @@ -553,7 +551,7 @@ public class DefaultCommand extends Command { Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.INVALID_NUMBER); return; } - NPC foundNPC = NPC.find(id.intValue()); + NPC foundNPC = NPC.find(id); if (foundNPC == null) { Configuration.MESSAGES.sendMessage(sender.getCommandSender(), ConfigurationValue.NPC_NOT_FOUND); return; diff --git a/src/main/java/io/github/znetworkw/znpcservers/commands/list/inventory/ConversationGUI.java b/src/main/java/io/github/znetworkw/znpcservers/commands/list/inventory/ConversationGUI.java index 9461148..049e4c4 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/commands/list/inventory/ConversationGUI.java +++ b/src/main/java/io/github/znetworkw/znpcservers/commands/list/inventory/ConversationGUI.java @@ -2,6 +2,8 @@ package io.github.znetworkw.znpcservers.commands.list.inventory; import com.google.common.base.Joiner; import com.google.common.base.Splitter; +import com.google.common.collect.Iterables; +import com.google.common.primitives.Ints; import io.github.znetworkw.znpcservers.configuration.Configuration; import io.github.znetworkw.znpcservers.configuration.ConfigurationConstants; import io.github.znetworkw.znpcservers.configuration.ConfigurationValue; @@ -20,84 +22,82 @@ import org.bukkit.entity.Player; import org.bukkit.event.inventory.ClickType; import org.bukkit.event.player.AsyncPlayerChatEvent; +import java.util.Collections; +import java.util.List; + public class ConversationGUI extends ZInventory { - private static final String WHITESPACE = " "; - private static final Splitter SPACE_SPLITTER = Splitter.on(" "); - private static final Joiner SPACE_JOINER = Joiner.on(" "); public ConversationGUI(Player player) { super(player); - setCurrentPage(new MainPage(this)); + this.setCurrentPage(new MainPage(this)); } + @SuppressWarnings({"UnstableApiUsage", "deprecation"}) static class MainPage extends ZInventoryPage { public MainPage(ZInventory inventory) { super(inventory, "Conversations", 5); } + @Override public void update() { - for (int i = 0; i < ConfigurationConstants.NPC_CONVERSATIONS.size(); i++) { + for (int i = 0; i < ConfigurationConstants.NPC_CONVERSATIONS.size(); ++i) { Conversation conversation = ConfigurationConstants.NPC_CONVERSATIONS.get(i); - addItem(ItemStackBuilder.forMaterial(Material.PAPER).setName(ChatColor.GREEN + conversation.getName()).setLore(new String[]{"&7this conversation has &b" + conversation.getTexts().size() + " &7texts,", "&7it will activate when a player is on a &b" + conversation.getRadius() + "x" + conversation.getRadius() + " &7radius,", "&7or when a player interacts with an npc.", "&7when the conversation is finish, there is a &b" + conversation.getDelay() + "s &7delay to start again.", "&f&lUSES", " &bLeft-click &7to manage texts.", " &bRight-click &7to add a new text.", " &bQ &7to change the radius.", " &bMiddle-click &7to change the cooldown."}, ).build(), i, clickEvent -> { + this.addItem(ItemStackBuilder.forMaterial(Material.PAPER).setName(ChatColor.GREEN + conversation.getName()).setLore("&7this conversation has &b" + conversation.getTexts().size() + " &7texts,", "&7it will activate when a player is on a &b" + conversation.getRadius() + "x" + conversation.getRadius() + " &7radius,", "&7or when a player interacts with an npc.", "&7when the conversation is finish, there is a &b" + conversation.getDelay() + "s &7delay to start again.", "&f&lUSES", " &bLeft-click &7to manage texts.", " &bRight-click &7to add a new text.", " &bQ &7to change the radius.", " &bMiddle-click &7to change the cooldown.").build(), i, clickEvent -> { if (clickEvent.getClick() == ClickType.DROP) { - Utils.sendTitle(getPlayer(), "&b&lCHANGE RADIUS", "&7Type the new radius..."); - EventService.addService(ZUser.find(getPlayer()), AsyncPlayerChatEvent.class).addConsumer(()).addConsumer(()); + Utils.sendTitle(this.getPlayer(), "&b&lCHANGE RADIUS", "&7Type the new radius..."); + EventService.addService(ZUser.find(this.getPlayer()), AsyncPlayerChatEvent.class).addConsumer(event -> { + if (!ConfigurationConstants.NPC_CONVERSATIONS.contains(conversation)) { + Configuration.MESSAGES.sendMessage(this.getPlayer(), ConfigurationValue.NO_CONVERSATION_FOUND); + } else { + Integer radius = Ints.tryParse(event.getMessage()); + if (radius == null) { + Configuration.MESSAGES.sendMessage(this.getPlayer(), ConfigurationValue.INVALID_NUMBER); + } else if (radius < 0) { + Configuration.MESSAGES.sendMessage(this.getPlayer(), ConfigurationValue.INVALID_NUMBER); + } else { + conversation.setRadius(radius); + Configuration.MESSAGES.sendMessage(this.getPlayer(), ConfigurationValue.SUCCESS); + } + } + }).addConsumer(event -> this.openInventory()); } else if (clickEvent.isRightClick()) { - Utils.sendTitle(getPlayer(), "&e&lADD LINE", "&7Type the new line..."); - EventService.addService(ZUser.find(getPlayer()), AsyncPlayerChatEvent.class).addConsumer(()).addConsumer(()); + Utils.sendTitle(this.getPlayer(), "&e&lADD LINE", "&7Type the new line..."); + EventService.addService(ZUser.find(this.getPlayer()), AsyncPlayerChatEvent.class).addConsumer(event -> { + if (!ConfigurationConstants.NPC_CONVERSATIONS.contains(conversation)) { + Configuration.MESSAGES.sendMessage(this.getPlayer(), ConfigurationValue.NO_CONVERSATION_FOUND); + } else { + conversation.getTexts().add(new ConversationKey(event.getMessage())); + Configuration.MESSAGES.sendMessage(this.getPlayer(), ConfigurationValue.SUCCESS); + } + }).addConsumer(event -> this.openInventory()); } else if (clickEvent.isLeftClick()) { - (new EditConversationPage(getInventory(), conversation)).openInventory(); + new EditConversationPage(this.getInventory(), conversation).openInventory(); } else if (clickEvent.getClick() == ClickType.MIDDLE) { - Utils.sendTitle(getPlayer(), "&6&lCHANGE COOLDOWN", "&7Type the new cooldown..."); - EventService.addService(ZUser.find(getPlayer()), AsyncPlayerChatEvent.class).addConsumer(()).addConsumer(()); + Utils.sendTitle(this.getPlayer(), "&6&lCHANGE COOLDOWN", "&7Type the new cooldown..."); + EventService.addService(ZUser.find(this.getPlayer()), AsyncPlayerChatEvent.class).addConsumer(event -> { + if (!ConfigurationConstants.NPC_CONVERSATIONS.contains(conversation)) { + Configuration.MESSAGES.sendMessage(this.getPlayer(), ConfigurationValue.NO_CONVERSATION_FOUND); + } else { + Integer cooldown = Ints.tryParse(event.getMessage()); + if (cooldown == null) { + Configuration.MESSAGES.sendMessage(this.getPlayer(), ConfigurationValue.INVALID_NUMBER); + } else if (cooldown < 0) { + Configuration.MESSAGES.sendMessage(this.getPlayer(), ConfigurationValue.INVALID_NUMBER); + } else { + conversation.setDelay(cooldown); + Configuration.MESSAGES.sendMessage(this.getPlayer(), ConfigurationValue.SUCCESS); + } + } + }).addConsumer(event -> this.openInventory()); } }); } } - static class EditConversationPage extends ZInventoryPage { - private final Conversation conversation; - - public EditConversationPage(ZInventory inventory, Conversation conversation) { - super(inventory, "Editing conversation " + conversation.getName(), 5); - this.conversation = conversation; - } - - public void update() { - for (int i = 0; i < this.conversation.getTexts().size(); i++) { - ConversationKey conversationKey = this.conversation.getTexts().get(i); - addItem(ItemStackBuilder.forMaterial(Material.NAME_TAG).setName(ChatColor.AQUA + conversationKey.getTextFormatted() + "....").setLore(new String[]{ - "&7this conversation text has a delay of &b" + conversationKey.getDelay() + "s &7to be executed,", "&7the sound for the text is &b" + ((conversationKey.getSoundName() == null) ? "NONE" : conversationKey.getSoundName()) + "&7,", "&7before sending the text there is a delay of &b" + conversationKey.getDelay() + "s", "&7the index for the text is &b" + i + "&7,", "&7and the conversation has currently &b" + conversationKey.getActions().size() + " actions&7.", "&f&lUSES", " &bLeft-click &7to change the position.", " &bRight-click &7to remove text.", " &bLeft-Shift-click &7to change the sound.", " &bMiddle-click &7to change the delay.", - " &bRight-Shift-click &7to edit the text.", " &bQ &7to manage actions."}, ).build(), i, clickEvent -> { - if (clickEvent.getClick() == ClickType.SHIFT_LEFT) { - Utils.sendTitle(getPlayer(), "&c&lCHANGE SOUND", "&7Type the new sound..."); - EventService.addService(ZUser.find(getPlayer()), AsyncPlayerChatEvent.class).addConsumer(()).addConsumer(()); - } else if (clickEvent.getClick() == ClickType.SHIFT_RIGHT) { - Utils.sendTitle(getPlayer(), "&a&lEDIT TEXT", "&7Type the new text..."); - EventService.addService(ZUser.find(getPlayer()), AsyncPlayerChatEvent.class).addConsumer(()).addConsumer(()); - } else if (clickEvent.isLeftClick()) { - Utils.sendTitle(getPlayer(), "&e&lCHANGE POSITION &a>=0&c<=" + this.conversation.getTexts().size(), "&7Type the new position..."); - EventService.addService(ZUser.find(getPlayer()), AsyncPlayerChatEvent.class).addConsumer(()).addConsumer(()); - } else if (clickEvent.isRightClick()) { - this.conversation.getTexts().remove(conversationKey); - Configuration.MESSAGES.sendMessage(getPlayer(), ConfigurationValue.SUCCESS); - openInventory(); - } else if (clickEvent.getClick() == ClickType.MIDDLE) { - Utils.sendTitle(getPlayer(), "&d&lCHANGE DELAY", "&7Type the new delay..."); - EventService.addService(ZUser.find(getPlayer()), AsyncPlayerChatEvent.class).addConsumer(()).addConsumer(()); - } else if (clickEvent.getClick() == ClickType.DROP) { - (new ConversationGUI.MainPage.ActionManagementPage(getInventory(), this.conversation, conversationKey)).openInventory(); - } - }); - } - } - } - static class ActionManagementPage extends ZInventoryPage { private final Conversation conversation; - private final ConversationKey conversationKey; public ActionManagementPage(ZInventory inventory, Conversation conversation, ConversationKey conversationKey) { @@ -106,22 +106,117 @@ public class ConversationGUI extends ZInventory { this.conversationKey = conversationKey; } + @Override public void update() { - for (int i = 0; i < this.conversationKey.getActions().size(); i++) { + for (int i = 0; i < this.conversationKey.getActions().size(); ++i) { NPCAction znpcAction = this.conversationKey.getActions().get(i); - addItem(ItemStackBuilder.forMaterial(Material.ANVIL).setName(ChatColor.AQUA + znpcAction.getAction().substring(0, Math.min(znpcAction.getAction().length(), 24)) + "....").setLore("&7this action type is &b" + znpcAction.getActionType(), "&f&lUSES", " &bRight-click &7to remove text.").build(), i, clickEvent -> { + this.addItem(ItemStackBuilder.forMaterial(Material.ANVIL).setName(ChatColor.AQUA + znpcAction.getAction().substring(0, Math.min(znpcAction.getAction().length(), 24)) + "....").setLore("&7this action type is &b" + znpcAction.getActionType(), "&f&lUSES", " &bRight-click &7to remove text.").build(), i, clickEvent -> { if (clickEvent.isRightClick()) { this.conversationKey.getActions().remove(znpcAction); - Configuration.MESSAGES.sendMessage(getPlayer(), ConfigurationValue.SUCCESS); - openInventory(); + Configuration.MESSAGES.sendMessage(this.getPlayer(), ConfigurationValue.SUCCESS); + this.openInventory(); } }); } - addItem(ItemStackBuilder.forMaterial(Material.EMERALD).setName(ChatColor.AQUA + "ADD A NEW ACTION").setLore(new String[]{"&7click here..."}, ).build(), getRows() - 5, clickEvent -> { - Utils.sendTitle(getPlayer(), "&d&lADD ACTION", "&7Type the action..."); - EventService.addService(ZUser.find(getPlayer()), AsyncPlayerChatEvent.class).addConsumer(()).addConsumer(()); + this.addItem(ItemStackBuilder.forMaterial(Material.EMERALD).setName(ChatColor.AQUA + "ADD A NEW ACTION").setLore("&7click here...").build(), this.getRows() - 5, clickEvent -> { + Utils.sendTitle(this.getPlayer(), "&d&lADD ACTION", "&7Type the action..."); + EventService.addService(ZUser.find(this.getPlayer()), AsyncPlayerChatEvent.class).addConsumer(event -> { + if (ConfigurationConstants.NPC_CONVERSATIONS.contains(this.conversation) && this.conversation.getTexts().contains(this.conversationKey)) { + List stringList = SPACE_SPLITTER.splitToList(event.getMessage()); + if (stringList.size() < 2) { + Configuration.MESSAGES.sendMessage(this.getPlayer(), ConfigurationValue.INCORRECT_USAGE); + } else { + this.conversationKey.getActions().add(new NPCAction(stringList.get(0).toUpperCase(), SPACE_JOINER.join(Iterables.skip(stringList, 1)))); + Configuration.MESSAGES.sendMessage(this.getPlayer(), ConfigurationValue.SUCCESS); + } + } else { + Configuration.MESSAGES.sendMessage(this.getPlayer(), ConfigurationValue.NO_CONVERSATION_FOUND); + } + }).addConsumer(event -> this.openInventory()); }); } } + + @SuppressWarnings({"deprecation", "UnstableApiUsage"}) + static class EditConversationPage extends ZInventoryPage { + private final Conversation conversation; + + public EditConversationPage(ZInventory inventory, Conversation conversation) { + super(inventory, "Editing conversation " + conversation.getName(), 5); + this.conversation = conversation; + } + + @Override + public void update() { + for (int i = 0; i < this.conversation.getTexts().size(); ++i) { + ConversationKey conversationKey = this.conversation.getTexts().get(i); + this.addItem(ItemStackBuilder.forMaterial(Material.NAME_TAG).setName(ChatColor.AQUA + conversationKey.getTextFormatted() + "....").setLore("&7this conversation text has a delay of &b" + conversationKey.getDelay() + "s &7to be executed,", "&7the sound for the text is &b" + (conversationKey.getSoundName() == null ? "NONE" : conversationKey.getSoundName()) + "&7,", "&7before sending the text there is a delay of &b" + conversationKey.getDelay() + "s", "&7the index for the text is &b" + i + "&7,", "&7and the conversation has currently &b" + conversationKey.getActions().size() + " actions&7.", "&f&lUSES", " &bLeft-click &7to change the position.", " &bRight-click &7to remove text.", " &bLeft-Shift-click &7to change the sound.", " &bMiddle-click &7to change the delay.", " &bRight-Shift-click &7to edit the text.", " &bQ &7to manage actions.").build(), i, clickEvent -> { + if (clickEvent.getClick() == ClickType.SHIFT_LEFT) { + Utils.sendTitle(this.getPlayer(), "&c&lCHANGE SOUND", "&7Type the new sound..."); + EventService.addService(ZUser.find(this.getPlayer()), AsyncPlayerChatEvent.class).addConsumer(event -> { + if (ConfigurationConstants.NPC_CONVERSATIONS.contains(this.conversation) && this.conversation.getTexts().contains(conversationKey)) { + String sound = event.getMessage().trim(); + conversationKey.setSoundName(sound); + Configuration.MESSAGES.sendMessage(this.getPlayer(), ConfigurationValue.SUCCESS); + } else { + Configuration.MESSAGES.sendMessage(this.getPlayer(), ConfigurationValue.NO_CONVERSATION_FOUND); + } + }).addConsumer(event -> this.openInventory()); + } else if (clickEvent.getClick() == ClickType.SHIFT_RIGHT) { + Utils.sendTitle(this.getPlayer(), "&a&lEDIT TEXT", "&7Type the new text..."); + EventService.addService(ZUser.find(this.getPlayer()), AsyncPlayerChatEvent.class).addConsumer(event -> { + if (ConfigurationConstants.NPC_CONVERSATIONS.contains(this.conversation) && this.conversation.getTexts().contains(conversationKey)) { + conversationKey.getLines().clear(); + conversationKey.getLines().addAll(SPACE_SPLITTER.splitToList(event.getMessage())); + Configuration.MESSAGES.sendMessage(this.getPlayer(), ConfigurationValue.SUCCESS); + } else { + Configuration.MESSAGES.sendMessage(this.getPlayer(), ConfigurationValue.NO_CONVERSATION_FOUND); + } + }).addConsumer(event -> this.openInventory()); + } else if (clickEvent.isLeftClick()) { + Utils.sendTitle(this.getPlayer(), "&e&lCHANGE POSITION &a>=0&c<=" + this.conversation.getTexts().size(), "&7Type the new position..."); + EventService.addService(ZUser.find(this.getPlayer()), AsyncPlayerChatEvent.class).addConsumer(event -> { + if (ConfigurationConstants.NPC_CONVERSATIONS.contains(this.conversation) && this.conversation.getTexts().contains(conversationKey)) { + Integer position = Ints.tryParse(event.getMessage()); + if (position == null) { + Configuration.MESSAGES.sendMessage(this.getPlayer(), ConfigurationValue.INVALID_NUMBER); + } else if (position >= 0 && position <= this.conversation.getTexts().size() - 1) { + Collections.swap(this.conversation.getTexts(), this.conversation.getTexts().indexOf(conversationKey), position); + Configuration.MESSAGES.sendMessage(this.getPlayer(), ConfigurationValue.SUCCESS); + } else { + Configuration.MESSAGES.sendMessage(this.getPlayer(), ConfigurationValue.INVALID_SIZE); + } + } else { + Configuration.MESSAGES.sendMessage(this.getPlayer(), ConfigurationValue.NO_CONVERSATION_FOUND); + } + }).addConsumer(event -> this.openInventory()); + } else if (clickEvent.isRightClick()) { + this.conversation.getTexts().remove(conversationKey); + Configuration.MESSAGES.sendMessage(this.getPlayer(), ConfigurationValue.SUCCESS); + this.openInventory(); + } else if (clickEvent.getClick() == ClickType.MIDDLE) { + Utils.sendTitle(this.getPlayer(), "&d&lCHANGE DELAY", "&7Type the new delay..."); + EventService.addService(ZUser.find(this.getPlayer()), AsyncPlayerChatEvent.class).addConsumer(event -> { + if (ConfigurationConstants.NPC_CONVERSATIONS.contains(this.conversation) && this.conversation.getTexts().contains(conversationKey)) { + Integer delay = Ints.tryParse(event.getMessage()); + if (delay == null) { + Configuration.MESSAGES.sendMessage(this.getPlayer(), ConfigurationValue.INVALID_NUMBER); + } else if (delay < 0) { + Configuration.MESSAGES.sendMessage(this.getPlayer(), ConfigurationValue.INVALID_NUMBER); + } else { + conversationKey.setDelay(delay); + Configuration.MESSAGES.sendMessage(this.getPlayer(), ConfigurationValue.SUCCESS); + } + } else { + Configuration.MESSAGES.sendMessage(this.getPlayer(), ConfigurationValue.NO_CONVERSATION_FOUND); + } + }).addConsumer(event -> this.openInventory()); + } else if (clickEvent.getClick() == ClickType.DROP) { + new ActionManagementPage(this.getInventory(), this.conversation, conversationKey).openInventory(); + } + }); + } + } + } } } diff --git a/src/main/java/io/github/znetworkw/znpcservers/configuration/Configuration.java b/src/main/java/io/github/znetworkw/znpcservers/configuration/Configuration.java index 88d0b72..942033f 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/configuration/Configuration.java +++ b/src/main/java/io/github/znetworkw/znpcservers/configuration/Configuration.java @@ -1,17 +1,14 @@ package io.github.znetworkw.znpcservers.configuration; import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; import com.google.gson.JsonElement; import com.google.gson.JsonParser; -import lol.pyr.znpcsplus.ZNPCsPlus; import io.github.znetworkw.znpcservers.utility.Utils; -import org.bukkit.command.CommandSender; +import lol.pyr.znpcsplus.ZNPCsPlus; import java.io.IOException; import java.io.Reader; import java.io.Writer; -import java.lang.reflect.Type; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; @@ -21,107 +18,110 @@ import java.util.Map; import java.util.stream.Collectors; public class Configuration { + private static final Charset CHARSET = StandardCharsets.UTF_8; + private final String name; + private final Path path; + private final Map configurationValues; public static final Configuration CONFIGURATION = new Configuration("config"); public static final Configuration MESSAGES = new Configuration("messages"); public static final Configuration CONVERSATIONS = new Configuration("conversations"); public static final Configuration DATA = new Configuration("data"); public static final ImmutableList SAVE_CONFIGURATIONS = ImmutableList.of(CONVERSATIONS, DATA); - static final String CONFIG_FORMAT = ".json"; - private static final JsonParser JSON_PARSER = new JsonParser(); - private static final Charset CHARSET = StandardCharsets.UTF_8; - private final String name; - private final Path path; - private final Map configurationValues; protected Configuration(String name) { this(name, ZNPCsPlus.PLUGIN_FOLDER.toPath().resolve(name + ".json")); } private Configuration(String name, Path path) { - if (!path.getFileName().toString().endsWith(".json")) + if (!path.getFileName().toString().endsWith(".json")) { throw new IllegalStateException("invalid configuration format for: " + path.getFileName()); - this.name = name; - this.path = path; - this - - .configurationValues = (Map) ((ImmutableSet) ConfigurationValue.VALUES_BY_NAME.get(name)).stream().collect(Collectors.toMap(c -> c, ConfigurationValue::getValue)); - onLoad(); + } else { + this.name = name; + this.path = path; + this.configurationValues = ConfigurationValue.VALUES_BY_NAME.get(name).stream().collect(Collectors.toMap((c) -> c, ConfigurationValue::getValue)); + this.onLoad(); + } } protected void onLoad() { - synchronized (this.path) { + synchronized(this.path) { try { Reader reader = Files.newBufferedReader(this.path, CHARSET); + try { - JsonElement data = JSON_PARSER.parse(reader); - if (data == null) { - if (reader != null) - reader.close(); + JsonElement data = JsonParser.parseReader(reader); + if (data != null) { + for(ConfigurationValue configValue : this.configurationValues.keySet()) { + boolean single = this.configurationValues.size() == 1; + JsonElement jsonElement = single ? data : (data.isJsonObject() ? data.getAsJsonObject().get(configValue.name()) : null); + if (jsonElement != null && !jsonElement.isJsonNull()) { + if (!single && configValue.getPrimitiveType().isEnum()) { + this.configurationValues.put(configValue, ZNPCsPlus.GSON.fromJson(jsonElement, configValue.getPrimitiveType())); + } else { + throw new RuntimeException(); + // what is this fuckery?? + // this.configurationValues.put(configValue, ZNPCsPlus.GSON.fromJson(jsonElement, $Gson$Types.newParameterizedTypeWithOwner((Type)null, configValue.getValue().getClass(), new Type[]{configValue.getPrimitiveType()}))); + } + } + } + + reader.close(); + return; } - for (ConfigurationValue configValue : this.configurationValues.keySet()) { - boolean single = (this.configurationValues.size() == 1); - JsonElement jsonElement = single ? data : (data.isJsonObject() ? data.getAsJsonObject().get(configValue.name()) : null); - if (jsonElement != null && !jsonElement.isJsonNull()) { - if (!single && configValue.getPrimitiveType().isEnum()) { - this.configurationValues.put(configValue, ZNPCsPlus.GSON.fromJson(jsonElement, configValue.getPrimitiveType())); - continue; - } - this.configurationValues.put(configValue, ZNPCsPlus.GSON.fromJson(jsonElement,.Gson.Types.newParameterizedTypeWithOwner(null, configValue.getValue().getClass(), new Type[]{configValue.getPrimitiveType()}))) - } - } - if (reader != null) - reader.close(); - } catch (Throwable throwable) { - if (reader != null) - try { - reader.close(); - } catch (Throwable throwable1) { - throwable.addSuppressed(throwable1); - } - throw throwable; - } - } catch (NoSuchFileException noSuchFileException) { - } catch (IOException e) { + reader.close(); + } catch (Throwable var17) { + try { + reader.close(); + } catch (Throwable var16) { + var17.addSuppressed(var16); + } + + throw var17; + } + } catch (NoSuchFileException ignored) { + } catch (IOException var19) { throw new IllegalStateException("Failed to read config: " + this.name); } finally { - save(); + this.save(); } + } } public void save() { - synchronized (this.path) { + synchronized(this.path) { try { Writer writer = Files.newBufferedWriter(this.path, CHARSET); + try { - ZNPCsPlus.GSON.toJson((this.configurationValues.size() == 1) ? - this.configurationValues.values().iterator().next() : this.configurationValues, writer); - if (writer != null) + ZNPCsPlus.GSON.toJson(this.configurationValues.size() == 1 ? this.configurationValues.values().iterator().next() : this.configurationValues, writer); + writer.close(); + } catch (Throwable var7) { + try { writer.close(); - } catch (Throwable throwable) { - if (writer != null) - try { - writer.close(); - } catch (Throwable throwable1) { - throwable.addSuppressed(throwable1); - } - throw throwable; + } catch (Throwable var6) { + var7.addSuppressed(var6); + } + + throw var7; } - } catch (IOException e) { + } catch (IOException var8) { throw new IllegalStateException("Failed to save config: " + this.name); } + } } + @SuppressWarnings("unchecked") public T getValue(ConfigurationValue configValue) { - synchronized (this.path) { - return (T) this.configurationValues.get(configValue); + synchronized(this.path) { + return (T)this.configurationValues.get(configValue); } } - public void sendMessage(CommandSender sender, ConfigurationValue configValue, Object... replaces) { - sender.sendMessage(Utils.toColor(String.format(getValue(configValue), replaces))); + public void sendMessage(org.bukkit.command.CommandSender sender, ConfigurationValue configValue, Object... replaces) { + sender.sendMessage(Utils.toColor(String.format(this.getValue(configValue), replaces))); } } diff --git a/src/main/java/io/github/znetworkw/znpcservers/configuration/ConfigurationConstants.java b/src/main/java/io/github/znetworkw/znpcservers/configuration/ConfigurationConstants.java index 3424654..93dd639 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/configuration/ConfigurationConstants.java +++ b/src/main/java/io/github/znetworkw/znpcservers/configuration/ConfigurationConstants.java @@ -8,11 +8,11 @@ import java.util.List; public final class ConfigurationConstants { public static final String SPACE_SYMBOL = Configuration.CONFIGURATION.getValue(ConfigurationValue.REPLACE_SYMBOL); - public static final int VIEW_DISTANCE = Configuration.CONFIGURATION.getValue(ConfigurationValue.VIEW_DISTANCE).intValue(); + public static final int VIEW_DISTANCE = Configuration.CONFIGURATION.getValue(ConfigurationValue.VIEW_DISTANCE); - public static final int SAVE_DELAY = Configuration.CONFIGURATION.getValue(ConfigurationValue.SAVE_NPCS_DELAY_SECONDS).intValue(); + public static final int SAVE_DELAY = Configuration.CONFIGURATION.getValue(ConfigurationValue.SAVE_NPCS_DELAY_SECONDS); - public static final boolean RGB_ANIMATION = Configuration.CONFIGURATION.getValue(ConfigurationValue.ANIMATION_RGB).booleanValue(); + public static final boolean RGB_ANIMATION = Configuration.CONFIGURATION.getValue(ConfigurationValue.ANIMATION_RGB); public static final List NPC_LIST = Configuration.DATA.getValue(ConfigurationValue.NPC_LIST); diff --git a/src/main/java/io/github/znetworkw/znpcservers/configuration/ConfigurationValue.java b/src/main/java/io/github/znetworkw/znpcservers/configuration/ConfigurationValue.java index a4c3674..025a5d1 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/configuration/ConfigurationValue.java +++ b/src/main/java/io/github/znetworkw/znpcservers/configuration/ConfigurationValue.java @@ -12,14 +12,14 @@ import java.util.Map; import java.util.stream.Collectors; public enum ConfigurationValue { - NPC_LIST("data", new ArrayList(), NPCModel.class), - VIEW_DISTANCE("config", Integer.valueOf(32), Integer.class), + NPC_LIST("data", new ArrayList<>(), NPCModel.class), + VIEW_DISTANCE("config", 32, Integer.class), REPLACE_SYMBOL("config", "-", String.class), - SAVE_NPCS_DELAY_SECONDS("config", Integer.valueOf(600), Integer.class), - MAX_PATH_LOCATIONS("config", Integer.valueOf(500), Integer.class), + SAVE_NPCS_DELAY_SECONDS("config", 600, Integer.class), + MAX_PATH_LOCATIONS("config", 500, Integer.class), NAMING_METHOD("config", NamingType.DEFAULT, NamingType.class), DEBUG_ENABLED("config", Boolean.TRUE, Boolean.class), - LINE_SPACING("config", Double.valueOf(0.3D), Double.class), + LINE_SPACING("config", 0.3D, Double.class), ANIMATION_RGB("config", Boolean.FALSE, Boolean.class), NO_PERMISSION("messages", "&cYou do not have permission to execute this command.", String.class), SUCCESS("messages", "&aDone...", String.class), @@ -50,7 +50,7 @@ public enum ConfigurationValue { FETCHING_SKIN("messages", "&aFetching skin for name: &f%s&a, wait...", String.class), CANT_GET_SKIN("messages", "&ccan't fetch skin with name: %s.", String.class), GET_SKIN("messages", "&aSkin fetched.", String.class), - CONVERSATION_LIST("conversations", new ArrayList(), Conversation.class); + CONVERSATION_LIST("conversations", new ArrayList<>(), Conversation.class); public static final Map> VALUES_BY_NAME; diff --git a/src/main/java/io/github/znetworkw/znpcservers/listeners/PlayerListener.java b/src/main/java/io/github/znetworkw/znpcservers/listeners/PlayerListener.java index 2d154c8..b4edfb5 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/listeners/PlayerListener.java +++ b/src/main/java/io/github/znetworkw/znpcservers/listeners/PlayerListener.java @@ -11,6 +11,7 @@ import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.plugin.Plugin; +@SuppressWarnings("deprecation") public class PlayerListener implements Listener { public PlayerListener(Plugin serversNPC) { serversNPC.getServer().getPluginManager().registerEvents(this, serversNPC); diff --git a/src/main/java/io/github/znetworkw/znpcservers/npc/FunctionFactory.java b/src/main/java/io/github/znetworkw/znpcservers/npc/FunctionFactory.java index 595ffb4..305ab36 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/npc/FunctionFactory.java +++ b/src/main/java/io/github/znetworkw/znpcservers/npc/FunctionFactory.java @@ -10,7 +10,7 @@ public final class FunctionFactory { public static ImmutableList WITH_FUNCTION = ImmutableList.of(new GlowFunction()); - public static ImmutableList ALL = ImmutableList.builder() + public static ImmutableList ALL = new ImmutableList.Builder() .addAll(WITHOUT_FUNCTION) .addAll(WITH_FUNCTION) .build(); @@ -32,7 +32,7 @@ public final class FunctionFactory { } public static boolean isTrue(NPC npc, NPCFunction function) { - return npc.getNpcPojo().getFunctions().getOrDefault(function.getName(), Boolean.FALSE).booleanValue(); + return npc.getNpcPojo().getFunctions().getOrDefault(function.getName(), false); } public static boolean isTrue(NPC npc, String function) { diff --git a/src/main/java/io/github/znetworkw/znpcservers/npc/NPC.java b/src/main/java/io/github/znetworkw/znpcservers/npc/NPC.java index 787f8dc..3cf3680 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/npc/NPC.java +++ b/src/main/java/io/github/znetworkw/znpcservers/npc/NPC.java @@ -4,7 +4,6 @@ import com.google.common.collect.ImmutableList; import com.mojang.authlib.GameProfile; import com.mojang.authlib.properties.Property; import com.mojang.authlib.properties.PropertyMap; -import lol.pyr.znpcsplus.ZNPCsPlus; import io.github.znetworkw.znpcservers.UnexpectedCallException; import io.github.znetworkw.znpcservers.cache.CacheRegistry; import io.github.znetworkw.znpcservers.npc.conversation.ConversationModel; @@ -13,10 +12,10 @@ import io.github.znetworkw.znpcservers.npc.packet.PacketCache; import io.github.znetworkw.znpcservers.user.ZUser; import io.github.znetworkw.znpcservers.utility.Utils; import io.github.znetworkw.znpcservers.utility.location.ZLocation; +import lol.pyr.znpcsplus.ZNPCsPlus; import org.bukkit.Location; import org.bukkit.entity.Player; -import java.lang.reflect.Constructor; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; @@ -74,14 +73,14 @@ public class NPC { } public static NPC find(int id) { - return NPC_MAP.get(Integer.valueOf(id)); + return NPC_MAP.get(id); } public static void unregister(int id) { NPC npc = find(id); if (npc == null) throw new IllegalStateException("can't find npc with id " + id); - NPC_MAP.remove(Integer.valueOf(id)); + NPC_MAP.remove(id); npc.deleteViewers(); } @@ -90,7 +89,7 @@ public class NPC { } public void onLoad() { - if (NPC_MAP.containsKey(Integer.valueOf(getNpcPojo().getId()))) + if (NPC_MAP.containsKey(getNpcPojo().getId())) throw new IllegalStateException("npc with id " + getNpcPojo().getId() + " already exists."); this.gameProfile = new GameProfile(UUID.randomUUID(), "[ZNPC] " + this.npcName); this.gameProfile.getProperties().put("textures", new Property("textures", this.npcPojo.getSkin(), this.npcPojo.getSignature())); @@ -101,7 +100,7 @@ public class NPC { if (this.npcPojo.getPathName() != null) setPath(NPCPath.AbstractTypeWriter.find(this.npcPojo.getPathName())); this.npcPojo.getCustomizationMap().forEach((key, value) -> this.npcPojo.getNpcType().updateCustomization(this, key, value)); - NPC_MAP.put(Integer.valueOf(getNpcPojo().getId()), this); + NPC_MAP.put(getNpcPojo().getId(), this); } public NPCModel getNpcPojo() { @@ -160,8 +159,8 @@ public class NPC { this.lastMove = System.nanoTime(); this.npcPojo.setLocation(new ZLocation(location = new Location(location.getWorld(), location.getBlockX() + 0.5D, location.getY(), location.getBlockZ() + 0.5D, location.getYaw(), location.getPitch()))); } - CacheRegistry.SET_LOCATION_METHOD.load().invoke(this.nmsEntity, Double.valueOf(location.getX()), Double.valueOf(location.getY()), Double.valueOf(location.getZ()), Float.valueOf(location.getYaw()), Float.valueOf(location.getPitch())); - Object npcTeleportPacket = ((Constructor) CacheRegistry.PACKET_PLAY_OUT_ENTITY_TELEPORT_CONSTRUCTOR.load()).newInstance(this.nmsEntity); + CacheRegistry.SET_LOCATION_METHOD.load().invoke(this.nmsEntity, location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch()); + Object npcTeleportPacket = CacheRegistry.PACKET_PLAY_OUT_ENTITY_TELEPORT_CONSTRUCTOR.load().newInstance(this.nmsEntity); this.viewers.forEach(player -> Utils.sendPackets(player, npcTeleportPacket)); this.hologram.setLocation(location, this.npcPojo.getNpcType().getHoloHeight()); } catch (ReflectiveOperationException operationException) { @@ -183,11 +182,11 @@ public class NPC { try { Object dataWatcherObject = CacheRegistry.GET_DATA_WATCHER_METHOD.load().invoke(this.nmsEntity); if (Utils.versionNewer(9)) { - CacheRegistry.SET_DATA_WATCHER_METHOD.load().invoke(dataWatcherObject, ((Constructor) CacheRegistry.DATA_WATCHER_OBJECT_CONSTRUCTOR - .load()).newInstance(Integer.valueOf(this.npcSkin.getLayerIndex()), CacheRegistry.DATA_WATCHER_REGISTER_FIELD - .load()), Byte.valueOf(127)); + CacheRegistry.SET_DATA_WATCHER_METHOD.load().invoke(dataWatcherObject, CacheRegistry.DATA_WATCHER_OBJECT_CONSTRUCTOR + .load().newInstance(this.npcSkin.getLayerIndex(), CacheRegistry.DATA_WATCHER_REGISTER_FIELD + .load()), (byte) 127); } else { - CacheRegistry.WATCH_DATA_WATCHER_METHOD.load().invoke(dataWatcherObject, Integer.valueOf(10), Byte.valueOf(127)); + CacheRegistry.WATCH_DATA_WATCHER_METHOD.load().invoke(dataWatcherObject, 10, (byte) 127); } } catch (ReflectiveOperationException operationException) { throw new UnexpectedCallException(operationException); @@ -204,17 +203,17 @@ public class NPC { this.uuid = (UUID) CacheRegistry.GET_UNIQUE_ID_METHOD.load().invoke(this.nmsEntity, new Object[0]); if (isPlayer) { try { - this.tabConstructor = ((Constructor) CacheRegistry.PACKET_PLAY_OUT_PLAYER_INFO_CONSTRUCTOR.load()).newInstance(CacheRegistry.ADD_PLAYER_FIELD.load(), Collections.singletonList(this.nmsEntity)); + this.tabConstructor = CacheRegistry.PACKET_PLAY_OUT_PLAYER_INFO_CONSTRUCTOR.load().newInstance(CacheRegistry.ADD_PLAYER_FIELD.load(), Collections.singletonList(this.nmsEntity)); } catch (Throwable e) { - this.tabConstructor = ((Constructor) CacheRegistry.PACKET_PLAY_OUT_PLAYER_INFO_CONSTRUCTOR.load()).newInstance(CacheRegistry.ADD_PLAYER_FIELD.load(), this.nmsEntity); - this.updateTabConstructor = ((Constructor) CacheRegistry.PACKET_PLAY_OUT_PLAYER_INFO_CONSTRUCTOR.load()).newInstance(CacheRegistry.UPDATE_LISTED_FIELD.load(), this.nmsEntity); + this.tabConstructor = CacheRegistry.PACKET_PLAY_OUT_PLAYER_INFO_CONSTRUCTOR.load().newInstance(CacheRegistry.ADD_PLAYER_FIELD.load(), this.nmsEntity); + this.updateTabConstructor = CacheRegistry.PACKET_PLAY_OUT_PLAYER_INFO_CONSTRUCTOR.load().newInstance(CacheRegistry.UPDATE_LISTED_FIELD.load(), this.nmsEntity); } setSecondLayerSkin(); } this.npcPojo.setNpcType(npcType); setLocation(getLocation(), false); this.packets.flushCache("spawnPacket", "removeTab"); - this.entityID = ((Integer) CacheRegistry.GET_ENTITY_ID.load().invoke(this.nmsEntity, new Object[0])).intValue(); + this.entityID = (Integer) CacheRegistry.GET_ENTITY_ID.load().invoke(this.nmsEntity, new Object[0]); FunctionFactory.findFunctionsForNpc(this).forEach(function -> function.resolve(this)); getPackets().getProxyInstance().update(this.packets); this.hologram.createHologram(); @@ -278,8 +277,8 @@ public class NPC { return; Location direction = rotation ? location : this.npcPojo.getLocation().bukkitLocation().clone().setDirection(location.clone().subtract(this.npcPojo.getLocation().bukkitLocation().clone()).toVector()); try { - Object lookPacket = ((Constructor) CacheRegistry.PACKET_PLAY_OUT_ENTITY_LOOK_CONSTRUCTOR.load()).newInstance(Integer.valueOf(this.entityID), Byte.valueOf((byte) (int) (direction.getYaw() * 256.0F / 360.0F)), Byte.valueOf((byte) (int) (direction.getPitch() * 256.0F / 360.0F)), Boolean.TRUE); - Object headRotationPacket = ((Constructor) CacheRegistry.PACKET_PLAY_OUT_ENTITY_HEAD_ROTATION_CONSTRUCTOR.load()).newInstance(this.nmsEntity, Byte.valueOf((byte) (int) (direction.getYaw() * 256.0F / 360.0F))); + Object lookPacket = CacheRegistry.PACKET_PLAY_OUT_ENTITY_LOOK_CONSTRUCTOR.load().newInstance(this.entityID, (byte) (int) (direction.getYaw() * 256.0F / 360.0F), (byte) (int) (direction.getPitch() * 256.0F / 360.0F), true); + Object headRotationPacket = CacheRegistry.PACKET_PLAY_OUT_ENTITY_HEAD_ROTATION_CONSTRUCTOR.load().newInstance(this.nmsEntity, (byte) (int) (direction.getYaw() * 256.0F / 360.0F)); if (player != null) { Utils.sendPackets(player, lookPacket, headRotationPacket); } else { diff --git a/src/main/java/io/github/znetworkw/znpcservers/npc/NPCAction.java b/src/main/java/io/github/znetworkw/znpcservers/npc/NPCAction.java index 553fc6d..fa6e27f 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/npc/NPCAction.java +++ b/src/main/java/io/github/znetworkw/znpcservers/npc/NPCAction.java @@ -65,6 +65,7 @@ public class NPCAction { .toString(); } + @SuppressWarnings("deprecation") enum ActionType { CMD { public void run(ZUser user, String actionValue) { diff --git a/src/main/java/io/github/znetworkw/znpcservers/npc/NPCFunction.java b/src/main/java/io/github/znetworkw/znpcservers/npc/NPCFunction.java index 33e74f7..0712ef5 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/npc/NPCFunction.java +++ b/src/main/java/io/github/znetworkw/znpcservers/npc/NPCFunction.java @@ -20,7 +20,7 @@ public abstract class NPCFunction { return; ResultType resultType = runFunction(npc, functionContext); if (resultType == ResultType.SUCCESS) - npc.getNpcPojo().getFunctions().put(getName(), Boolean.valueOf(!isTrue(npc))); + npc.getNpcPojo().getFunctions().put(getName(), !isTrue(npc)); } protected ResultType resolve(NPC npc) { diff --git a/src/main/java/io/github/znetworkw/znpcservers/npc/NPCModel.java b/src/main/java/io/github/znetworkw/znpcservers/npc/NPCModel.java index 0ff287f..da7f69f 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/npc/NPCModel.java +++ b/src/main/java/io/github/znetworkw/znpcservers/npc/NPCModel.java @@ -6,6 +6,7 @@ import org.bukkit.inventory.ItemStack; import java.util.*; +@SuppressWarnings("unused") public class NPCModel { private static final String EMPTY_STRING = ""; diff --git a/src/main/java/io/github/znetworkw/znpcservers/npc/NPCPath.java b/src/main/java/io/github/znetworkw/znpcservers/npc/NPCPath.java index be99680..d8e3feb 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/npc/NPCPath.java +++ b/src/main/java/io/github/znetworkw/znpcservers/npc/NPCPath.java @@ -19,6 +19,7 @@ import java.util.concurrent.ConcurrentMap; import java.util.logging.Level; import java.util.logging.Logger; +@SuppressWarnings("ALL") public interface NPCPath { void initialize(DataInputStream paramDataInputStream) throws IOException; @@ -251,7 +252,7 @@ public interface NPCPath { this.npcUser.setHasPath(false); write(); } - }1, 1); + }, 1, 1); } public MovementPath getPath(NPC npc) { diff --git a/src/main/java/io/github/znetworkw/znpcservers/npc/NPCSkin.java b/src/main/java/io/github/znetworkw/znpcservers/npc/NPCSkin.java index 0328d9b..a86e796 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/npc/NPCSkin.java +++ b/src/main/java/io/github/znetworkw/znpcservers/npc/NPCSkin.java @@ -5,8 +5,6 @@ import io.github.znetworkw.znpcservers.skin.SkinFetcherResult; import io.github.znetworkw.znpcservers.utility.Utils; public class NPCSkin { - private static final String EMPTY_STRING = ""; - private static final String[] EMPTY_ARRAY = new String[]{"", ""}; private static final int LAYER_INDEX = SkinLayerValues.findLayerByVersion(); diff --git a/src/main/java/io/github/znetworkw/znpcservers/npc/NPCType.java b/src/main/java/io/github/znetworkw/znpcservers/npc/NPCType.java index e35761d..fa48fea 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/npc/NPCType.java +++ b/src/main/java/io/github/znetworkw/znpcservers/npc/NPCType.java @@ -1,108 +1,100 @@ package io.github.znetworkw.znpcservers.npc; import io.github.znetworkw.znpcservers.UnexpectedCallException; -import io.github.znetworkw.znpcservers.cache.CacheRegistry; import io.github.znetworkw.znpcservers.cache.TypeCache; import io.github.znetworkw.znpcservers.utility.Utils; import org.bukkit.entity.EntityType; import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Optional; +import static io.github.znetworkw.znpcservers.cache.CacheRegistry.*; + +@SuppressWarnings("unused") public enum NPCType { - PLAYER(CacheRegistry.ENTITY_PLAYER_CLASS, 0.0D, new String[0]), - ARMOR_STAND(CacheRegistry.ENTITY_ARMOR_STAND_CLASS, 0.0D, new String[]{"setSmall", "setArms"}), - CREEPER(CacheRegistry.ENTITY_CREEPER_CLASS, -0.15D, new String[]{"setPowered"}), - BAT(CacheRegistry.ENTITY_BAT_CLASS, -0.5D, new String[]{"setAwake"}), - BLAZE(CacheRegistry.ENTITY_BLAZE_CLASS, 0.0D, new String[0]), - CAVE_SPIDER(CacheRegistry.ENTITY_CAVE_SPIDER_CLASS, -1.0D, new String[0]), - COW(CacheRegistry.ENTITY_COW_CLASS, -0.25D, new String[]{"setAge"}), - CHICKEN(CacheRegistry.ENTITY_CHICKEN_CLASS, -1.0D, new String[]{"setAge"}), - ENDER_DRAGON(CacheRegistry.ENTITY_ENDER_DRAGON_CLASS, 1.5D, new String[0]), - ENDERMAN(CacheRegistry.ENTITY_ENDERMAN_CLASS, 0.7D, new String[0]), - ENDERMITE(CacheRegistry.ENTITY_ENDERMITE_CLASS, -1.5D, new String[0]), - GHAST(CacheRegistry.ENTITY_GHAST_CLASS, 3.0D, new String[0]), - IRON_GOLEM(CacheRegistry.ENTITY_IRON_GOLEM_CLASS, 0.75D, new String[0]), - GIANT(CacheRegistry.ENTITY_GIANT_ZOMBIE_CLASS, 11.0D, new String[0]), - GUARDIAN(CacheRegistry.ENTITY_GUARDIAN_CLASS, -0.7D, new String[0]), - HORSE(CacheRegistry.ENTITY_HORSE_CLASS, 0.0D, new String[]{"setStyle", "setAge", "setColor", "setVariant"}), - LLAMA(CacheRegistry.ENTITY_LLAMA_CLASS, 0.0D, new String[]{"setAge"}), - MAGMA_CUBE(CacheRegistry.ENTITY_MAGMA_CUBE_CLASS, -1.25D, new String[]{"setSize"}), - MUSHROOM_COW(CacheRegistry.ENTITY_MUSHROOM_COW_CLASS, -0.25D, new String[]{"setAge"}), - OCELOT(CacheRegistry.ENTITY_OCELOT_CLASS, -1.0D, new String[]{"setCatType", "setAge"}), - PARROT(CacheRegistry.ENTITY_PARROT_CLASS, -1.5D, new String[]{"setVariant"}), - PIG(CacheRegistry.ENTITY_PIG_CLASS, -1.0D, new String[]{"setAge"}), - PANDA(CacheRegistry.ENTITY_PANDA_CLASS, -0.6D, new String[]{"setAge", "setMainGene", "setHiddenGene"}), - RABBIT(CacheRegistry.ENTITY_RABBIT_CLASS, -1.0D, new String[]{"setRabbitType"}), - POLAR_BEAR(CacheRegistry.ENTITY_POLAR_BEAR_CLASS, -0.5D, new String[0]), - SHEEP(CacheRegistry.ENTITY_SHEEP_CLASS, -0.5D, new String[]{"setAge", "setSheared", "setColor"}), - SILVERFISH(CacheRegistry.ENTITY_SILVERFISH_CLASS, -1.5D, new String[0]), - SNOWMAN(CacheRegistry.ENTITY_SNOWMAN_CLASS, 0.0D, new String[]{"setHasPumpkin", "setDerp"}), - SKELETON(CacheRegistry.ENTITY_SKELETON_CLASS, 0.0D, new String[0]), - SHULKER(CacheRegistry.ENTITY_SHULKER_CLASS, 0.0D, new String[0]), - SLIME(CacheRegistry.ENTITY_SLIME_CLASS, -1.25D, new String[]{"setSize"}), - SPIDER(CacheRegistry.ENTITY_SPIDER_CLASS, -1.0D, new String[0]), - SQUID(CacheRegistry.ENTITY_SQUID_CLASS, -1.0D, new String[0]), - VILLAGER(CacheRegistry.ENTITY_VILLAGER_CLASS, 0.0D, new String[]{"setProfession", "setVillagerType", "setAge"}), - WITCH(CacheRegistry.ENTITY_WITCH_CLASS, 0.5D, new String[0]), - WITHER(CacheRegistry.ENTITY_WITHER_CLASS, 1.75D, new String[0]), - ZOMBIE(CacheRegistry.ENTITY_ZOMBIE_CLASS, 0.0D, new String[]{"setBaby"}), - WOLF(CacheRegistry.ENTITY_WOLF_CLASS, -1.0D, new String[]{"setSitting", "setTamed", "setAngry", "setAge", "setCollarColor"}), - FOX(CacheRegistry.ENTITY_FOX_CLASS, -1.0D, new String[]{"setFoxType", "setSitting", "setSleeping", "setAge", "setCrouching"}), - BEE(CacheRegistry.ENTITY_BEE_CLASS, -1.0D, new String[]{"setAnger", "setHasNectar", "setHasStung"}), - TURTLE(CacheRegistry.ENTITY_TURTLE, -1.0D, new String[0]), - WARDEN(CacheRegistry.ENTITY_WARDEN, 1.0D, new String[0]), - AXOLOTL(CacheRegistry.ENTITY_AXOLOTL_CLASS, -1.0D, new String[]{"setVariant", "setAge"}), - GOAT(CacheRegistry.ENTITY_GOAT_CLASS, -0.5D, new String[]{"setScreamingGoat", "setAge"}); + PLAYER(ENTITY_PLAYER_CLASS, 0.0), + ARMOR_STAND(ENTITY_ARMOR_STAND_CLASS, 0.0, "setSmall", "setArms"), + CREEPER(ENTITY_CREEPER_CLASS, -0.15, "setPowered"), + BAT(ENTITY_BAT_CLASS, -0.5, "setAwake"), + BLAZE(ENTITY_BLAZE_CLASS, 0.0), + CAVE_SPIDER(ENTITY_CAVE_SPIDER_CLASS, -1.0), + COW(ENTITY_COW_CLASS, -0.25, "setAge"), + CHICKEN(ENTITY_CHICKEN_CLASS, -1.0, "setAge"), + ENDER_DRAGON(ENTITY_ENDER_DRAGON_CLASS, 1.5), + ENDERMAN(ENTITY_ENDERMAN_CLASS, 0.7), + ENDERMITE(ENTITY_ENDERMITE_CLASS, -1.5), + GHAST(ENTITY_GHAST_CLASS, 3.0), + IRON_GOLEM(ENTITY_IRON_GOLEM_CLASS, 0.75), + GIANT(ENTITY_GIANT_ZOMBIE_CLASS, 11.0), + GUARDIAN(ENTITY_GUARDIAN_CLASS, -0.7), + HORSE(ENTITY_HORSE_CLASS, 0.0, "setStyle", "setAge", "setColor", "setVariant"), + LLAMA(ENTITY_LLAMA_CLASS, 0.0, "setAge"), + MAGMA_CUBE(ENTITY_MAGMA_CUBE_CLASS, -1.25, "setSize"), + MUSHROOM_COW(ENTITY_MUSHROOM_COW_CLASS, -0.25, "setAge"), + OCELOT(ENTITY_OCELOT_CLASS, -1.0, "setCatType", "setAge"), + PARROT(ENTITY_PARROT_CLASS, -1.5, "setVariant"), + PIG(ENTITY_PIG_CLASS, -1.0, "setAge"), + PANDA(ENTITY_PANDA_CLASS, -0.6, "setAge", "setMainGene", "setHiddenGene"), + RABBIT(ENTITY_RABBIT_CLASS, -1.0, "setRabbitType"), + POLAR_BEAR(ENTITY_POLAR_BEAR_CLASS, -0.5), + SHEEP(ENTITY_SHEEP_CLASS, -0.5, "setAge", "setSheared", "setColor"), + SILVERFISH(ENTITY_SILVERFISH_CLASS, -1.5), + SNOWMAN(ENTITY_SNOWMAN_CLASS, 0.0, "setHasPumpkin", "setDerp"), + SKELETON(ENTITY_SKELETON_CLASS, 0.0), + SHULKER(ENTITY_SHULKER_CLASS, 0.0), + SLIME(ENTITY_SLIME_CLASS, -1.25, "setSize"), + SPIDER(ENTITY_SPIDER_CLASS, -1.0), + SQUID(ENTITY_SQUID_CLASS, -1.0), + VILLAGER(ENTITY_VILLAGER_CLASS, 0.0, "setProfession", "setVillagerType", "setAge"), + WITCH(ENTITY_WITCH_CLASS, 0.5), + WITHER(ENTITY_WITHER_CLASS, 1.75), + ZOMBIE(ENTITY_ZOMBIE_CLASS, 0.0, "setBaby"), + WOLF(ENTITY_WOLF_CLASS, -1.0, "setSitting", "setTamed", "setAngry", "setAge", "setCollarColor"), + FOX(ENTITY_FOX_CLASS, -1.0, "setFoxType", "setSitting", "setSleeping", "setAge", "setCrouching"), + BEE(ENTITY_BEE_CLASS, -1.0, "setAnger", "setHasNectar", "setHasStung"), + TURTLE(ENTITY_TURTLE, -1.0), + WARDEN(ENTITY_WARDEN, 1.0), + AXOLOTL(ENTITY_AXOLOTL_CLASS, -1.0, "setVariant", "setAge"), + GOAT(ENTITY_GOAT_CLASS, -0.5, "setScreamingGoat", "setAge"); private static final String EMPTY_STRING = ""; - private final double holoHeight; - private final CustomizationLoader customizationLoader; - private final Constructor constructor; - private EntityType bukkitEntityType; - private Object nmsEntityType; - NPCType(Class entityClass, String newName, double holoHeight, String... methods) { + @SuppressWarnings("OptionalGetWithoutIsPresent") + NPCType(Class entityClass, String newName, double holoHeight, String ... methods) { this.holoHeight = holoHeight; - this - - .customizationLoader = (entityClass == null) ? null : new CustomizationLoader(this.bukkitEntityType = EntityType.valueOf((newName.length() > 0) ? newName : name()), Arrays.asList(methods)); - if (entityClass == null || entityClass - .isAssignableFrom(CacheRegistry.ENTITY_PLAYER_CLASS)) { + if (entityClass == null) { + customizationLoader = null; + } else { + this.bukkitEntityType = EntityType.valueOf(newName.length() > 0 ? newName : this.name()); + customizationLoader = new CustomizationLoader(this.bukkitEntityType, Arrays.asList(methods)); + } + if (entityClass == null || entityClass.isAssignableFrom(ENTITY_PLAYER_CLASS)) { this.constructor = null; return; } try { if (Utils.versionNewer(14)) { - this.nmsEntityType = ((Optional) CacheRegistry.ENTITY_TYPES_A_METHOD.load().invoke(null, new Object[]{this.bukkitEntityType.getKey().getKey().toLowerCase()})).get(); - this.constructor = entityClass.getConstructor(CacheRegistry.ENTITY_TYPES_CLASS, CacheRegistry.WORLD_CLASS); + this.nmsEntityType = ((Optional) ENTITY_TYPES_A_METHOD.load().invoke(null, this.bukkitEntityType.getKey().getKey().toLowerCase())).get(); + this.constructor = entityClass.getConstructor(ENTITY_TYPES_CLASS, WORLD_CLASS); } else { - this.constructor = entityClass.getConstructor(CacheRegistry.WORLD_CLASS); + this.constructor = entityClass.getConstructor(WORLD_CLASS); } - } catch (ReflectiveOperationException operationException) { + } + catch (ReflectiveOperationException operationException) { throw new UnexpectedCallException(operationException); } } - public static Object[] arrayToPrimitive(String[] strings, Method method) { - Class[] methodParameterTypes = method.getParameterTypes(); - Object[] newArray = new Object[methodParameterTypes.length]; - for (int i = 0; i < methodParameterTypes.length; i++) { - TypeProperty typeProperty = TypeProperty.forType(methodParameterTypes[i]); - if (typeProperty != null) { - newArray[i] = typeProperty.getFunction().apply(strings[i]); - } else { - newArray[i] = TypeCache.ClassCache.find(strings[i], methodParameterTypes[i]); - } - } - return newArray; + NPCType(Class entityClass, double holoHeight, String ... customization) { + this(entityClass, EMPTY_STRING, holoHeight, customization); } public double getHoloHeight() { @@ -121,15 +113,27 @@ public enum NPCType { return this.customizationLoader; } + public static Object[] arrayToPrimitive(String[] strings, Method method) { + Class[] methodParameterTypes = method.getParameterTypes(); + Object[] newArray = new Object[methodParameterTypes.length]; + for (int i = 0; i < methodParameterTypes.length; ++i) { + TypeProperty typeProperty = TypeProperty.forType(methodParameterTypes[i]); + newArray[i] = typeProperty != null ? typeProperty.getFunction().apply(strings[i]) : TypeCache.ClassCache.find(strings[i], methodParameterTypes[i]); + } + return newArray; + } + public void updateCustomization(NPC npc, String name, String[] values) { - if (!this.customizationLoader.contains(name)) + if (!this.customizationLoader.contains(name)) { return; + } try { Method method = this.customizationLoader.getMethods().get(name); - method.invoke(npc.getBukkitEntity(), arrayToPrimitive(values, method)); + method.invoke(npc.getBukkitEntity(), NPCType.arrayToPrimitive(values, method)); npc.updateMetadata(npc.getViewers()); - } catch (IllegalAccessException | java.lang.reflect.InvocationTargetException e) { + } + catch (IllegalAccessException | InvocationTargetException e) { throw new IllegalStateException("can't invoke method: " + name, e); } } -} +} \ No newline at end of file diff --git a/src/main/java/io/github/znetworkw/znpcservers/npc/NamingType.java b/src/main/java/io/github/znetworkw/znpcservers/npc/NamingType.java index 6b664a8..dd413a8 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/npc/NamingType.java +++ b/src/main/java/io/github/znetworkw/znpcservers/npc/NamingType.java @@ -9,7 +9,5 @@ public enum NamingType { } }; - private static final int FIXED_LENGTH = 6; - public abstract String resolve(NPC paramNPC); } diff --git a/src/main/java/io/github/znetworkw/znpcservers/npc/conversation/ConversationModel.java b/src/main/java/io/github/znetworkw/znpcservers/npc/conversation/ConversationModel.java index bde6095..2f8c33f 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/npc/conversation/ConversationModel.java +++ b/src/main/java/io/github/znetworkw/znpcservers/npc/conversation/ConversationModel.java @@ -43,14 +43,14 @@ public class ConversationModel { if (ConversationProcessor.isPlayerConversing(player.getUniqueId())) return; if (this.lastStarted.containsKey(player.getUniqueId())) { - long lastConversationNanos = System.nanoTime() - this.lastStarted.get(player.getUniqueId()).longValue(); + long lastConversationNanos = System.nanoTime() - this.lastStarted.get(player.getUniqueId()); if (lastConversationNanos < 1000000000L * getConversation().getDelay()) return; } this.lastStarted.remove(player.getUniqueId()); if (this.conversationType.canStart(npc, getConversation(), player)) { new ConversationProcessor(npc, this, player); - this.lastStarted.put(player.getUniqueId(), Long.valueOf(System.nanoTime())); + this.lastStarted.put(player.getUniqueId(), System.nanoTime()); } } diff --git a/src/main/java/io/github/znetworkw/znpcservers/npc/conversation/ConversationProcessor.java b/src/main/java/io/github/znetworkw/znpcservers/npc/conversation/ConversationProcessor.java index a4e6d0e..2488b5c 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/npc/conversation/ConversationProcessor.java +++ b/src/main/java/io/github/znetworkw/znpcservers/npc/conversation/ConversationProcessor.java @@ -69,11 +69,11 @@ public class ConversationProcessor { try { Sound sound = Sound.valueOf(conversationKey.getSoundName().toUpperCase()); ConversationProcessor.this.player.playSound(ConversationProcessor.this.player.getLocation(), sound, 0.2F, 1.0F); - } catch (IllegalArgumentException illegalArgumentException) { + } catch (IllegalArgumentException ignored) { } ConversationProcessor.this.conversationIndexDelay = System.nanoTime(); ConversationProcessor.this.conversationIndex++; } - }5, 20); + }, 5, 20); } } diff --git a/src/main/java/io/github/znetworkw/znpcservers/npc/function/GlowFunction.java b/src/main/java/io/github/znetworkw/znpcservers/npc/function/GlowFunction.java index 351f513..b15f0ae 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/npc/function/GlowFunction.java +++ b/src/main/java/io/github/znetworkw/znpcservers/npc/function/GlowFunction.java @@ -6,8 +6,6 @@ import io.github.znetworkw.znpcservers.npc.FunctionFactory; import io.github.znetworkw.znpcservers.npc.NPC; import io.github.znetworkw.znpcservers.npc.NPCFunction; -import java.lang.reflect.Constructor; - public class GlowFunction extends NPCFunction { public GlowFunction() { super("glow"); @@ -25,9 +23,9 @@ public class GlowFunction extends NPCFunction { npc.getNpcPojo().setGlowName(glowColorName); npc.setGlowColor(glowColor); CacheRegistry.SET_DATA_WATCHER_METHOD.load().invoke(CacheRegistry.GET_DATA_WATCHER_METHOD - .load().invoke(npc.getNmsEntity()), ((Constructor) CacheRegistry.DATA_WATCHER_OBJECT_CONSTRUCTOR - .load()).newInstance(Integer.valueOf(0), CacheRegistry.DATA_WATCHER_REGISTER_FIELD - .load()), Byte.valueOf(!FunctionFactory.isTrue(npc, this) ? 64 : 0)); + .load().invoke(npc.getNmsEntity()), CacheRegistry.DATA_WATCHER_OBJECT_CONSTRUCTOR + .load().newInstance(0, CacheRegistry.DATA_WATCHER_REGISTER_FIELD + .load()), (byte) (!FunctionFactory.isTrue(npc, this) ? 64 : 0)); npc.getPackets().getProxyInstance().update(npc.getPackets()); npc.deleteViewers(); return NPCFunction.ResultType.SUCCESS; diff --git a/src/main/java/io/github/znetworkw/znpcservers/npc/hologram/Hologram.java b/src/main/java/io/github/znetworkw/znpcservers/npc/hologram/Hologram.java index f9b0770..a9e3a08 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/npc/hologram/Hologram.java +++ b/src/main/java/io/github/znetworkw/znpcservers/npc/hologram/Hologram.java @@ -12,7 +12,6 @@ import io.github.znetworkw.znpcservers.utility.Utils; import org.bukkit.Location; import javax.annotation.Nullable; -import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; @@ -22,7 +21,7 @@ public class Hologram { private static final boolean NEW_METHOD = (Utils.BUKKIT_VERSION > 12); - private static final double LINE_SPACING = ((Double) Configuration.CONFIGURATION.getValue(ConfigurationValue.LINE_SPACING)).doubleValue(); + private static final double LINE_SPACING = Configuration.CONFIGURATION.getValue(ConfigurationValue.LINE_SPACING); private final List hologramLines = new ArrayList<>(); @@ -40,15 +39,15 @@ public class Hologram { Location location = this.npc.getLocation(); for (String line : this.npc.getNpcPojo().getHologramLines()) { boolean visible = !line.equalsIgnoreCase("%space%"); - Object armorStand = ((Constructor) CacheRegistry.ENTITY_CONSTRUCTOR.load()).newInstance(CacheRegistry.GET_HANDLE_WORLD_METHOD.load().invoke(location.getWorld()), - Double.valueOf(location.getX()), Double.valueOf(location.getY() - 0.15D + y), Double.valueOf(location.getZ())); + Object armorStand = CacheRegistry.ENTITY_CONSTRUCTOR.load().newInstance(CacheRegistry.GET_HANDLE_WORLD_METHOD.load().invoke(location.getWorld()), + location.getX(), location.getY() - 0.15D + y, location.getZ()); if (visible) { - CacheRegistry.SET_CUSTOM_NAME_VISIBLE_METHOD.load().invoke(armorStand, Boolean.valueOf(true)); + CacheRegistry.SET_CUSTOM_NAME_VISIBLE_METHOD.load().invoke(armorStand, true); updateLine(line, armorStand, null); } - CacheRegistry.SET_INVISIBLE_METHOD.load().invoke(armorStand, Boolean.valueOf(true)); - this.hologramLines.add(new HologramLine(line.replace(ConfigurationConstants.SPACE_SYMBOL, " "), armorStand, ((Integer) CacheRegistry.GET_ENTITY_ID - .load().invoke(armorStand, new Object[0])).intValue())); + CacheRegistry.SET_INVISIBLE_METHOD.load().invoke(armorStand, true); + this.hologramLines.add(new HologramLine(line.replace(ConfigurationConstants.SPACE_SYMBOL, " "), armorStand, (Integer) CacheRegistry.GET_ENTITY_ID + .load().invoke(armorStand))); y += LINE_SPACING; } setLocation(location, 0.0D); @@ -73,7 +72,7 @@ public class Hologram { public void delete(ZUser user) { this.hologramLines.forEach(hologramLine -> { try { - Utils.sendPackets(user, this.npc.getPackets().getProxyInstance().getDestroyPacket(HologramLine.access$200(hologramLine))); + Utils.sendPackets(user, this.npc.getPackets().getProxyInstance().getDestroyPacket(hologramLine.id)); } catch (ReflectiveOperationException operationException) { throw new UnexpectedCallException(operationException); } @@ -95,25 +94,26 @@ public class Hologram { public void updateLocation() { this.hologramLines.forEach(hologramLine -> { try { - Object packet = ((Constructor) CacheRegistry.PACKET_PLAY_OUT_ENTITY_TELEPORT_CONSTRUCTOR.load()).newInstance(new Object[]{HologramLine.access$100(hologramLine)}); - this.npc.getViewers().forEach(()); - } catch (ReflectiveOperationException operationException) { + Object packet = CacheRegistry.PACKET_PLAY_OUT_ENTITY_TELEPORT_CONSTRUCTOR.load().newInstance(hologramLine.armorStand); + this.npc.getViewers().forEach(player -> Utils.sendPackets(player, packet)); + } + catch (ReflectiveOperationException operationException) { throw new UnexpectedCallException(operationException); } }); } public void setLocation(Location location, double height) { - location = location.clone().add(0.0D, height, 0.0D); + location = location.clone().add(0.0, height, 0.0); try { double y = this.npc.getNpcPojo().getHologramHeight(); for (HologramLine hologramLine : this.hologramLines) { - CacheRegistry.SET_LOCATION_METHOD.load().invoke(hologramLine.armorStand, Double.valueOf(location.getX()), Double.valueOf(location.getY() - 0.15D + y), - Double.valueOf(location.getZ()), Float.valueOf(location.getYaw()), Float.valueOf(location.getPitch())); + CacheRegistry.SET_LOCATION_METHOD.load().invoke(hologramLine.armorStand, location.getX(), location.getY() - 0.15 + y, location.getZ(), location.getYaw(), location.getPitch()); y += LINE_SPACING; } - updateLocation(); - } catch (ReflectiveOperationException operationException) { + this.updateLocation(); + } + catch (ReflectiveOperationException operationException) { throw new UnexpectedCallException(operationException); } } diff --git a/src/main/java/io/github/znetworkw/znpcservers/npc/hologram/replacer/LineReplacer.java b/src/main/java/io/github/znetworkw/znpcservers/npc/hologram/replacer/LineReplacer.java index 7e731fc..6e7a562 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/npc/hologram/replacer/LineReplacer.java +++ b/src/main/java/io/github/znetworkw/znpcservers/npc/hologram/replacer/LineReplacer.java @@ -1,7 +1,6 @@ package io.github.znetworkw.znpcservers.npc.hologram.replacer; import com.google.common.collect.ImmutableList; -import com.google.common.collect.UnmodifiableIterator; import io.github.znetworkw.znpcservers.user.ZUser; import io.github.znetworkw.znpcservers.utility.Utils; @@ -9,10 +8,8 @@ public interface LineReplacer { ImmutableList LINE_REPLACERS = ImmutableList.of(new RGBLine()); static String makeAll(ZUser user, String string) { - for (UnmodifiableIterator unmodifiableIterator = LINE_REPLACERS.iterator(); unmodifiableIterator.hasNext(); ) { - LineReplacer lineReplacer = unmodifiableIterator.next(); - if (!lineReplacer.isSupported()) - continue; + for (LineReplacer lineReplacer : LINE_REPLACERS) { + if (!lineReplacer.isSupported()) continue; string = lineReplacer.make(string); } return Utils.toColor((Utils.PLACEHOLDER_SUPPORT && user != null) ? diff --git a/src/main/java/io/github/znetworkw/znpcservers/npc/hologram/replacer/RGBLine.java b/src/main/java/io/github/znetworkw/znpcservers/npc/hologram/replacer/RGBLine.java index 9b44402..6a9b8f3 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/npc/hologram/replacer/RGBLine.java +++ b/src/main/java/io/github/znetworkw/znpcservers/npc/hologram/replacer/RGBLine.java @@ -6,11 +6,8 @@ import net.md_5.bungee.api.ChatColor; import java.util.concurrent.ThreadLocalRandom; +@SuppressWarnings("deprecation") public class RGBLine implements LineReplacer { - private static final char HEX_COLOR_CHAR = '#'; - - private static final int HEX_COLOR_LENGTH = 6; - public String make(String string) { String rgbString = string; for (int i = 0; i < rgbString.length(); i++) { @@ -31,7 +28,7 @@ public class RGBLine implements LineReplacer { if (success) try { rgbString = rgbString.substring(0, i) + ChatColor.of(hexCodeStringBuilder.toString()) + rgbString.substring(endIndex); - } catch (Exception exception) { + } catch (Exception ignored) { } } } diff --git a/src/main/java/io/github/znetworkw/znpcservers/npc/packet/Packet.java b/src/main/java/io/github/znetworkw/znpcservers/npc/packet/Packet.java index ee5c5ec..94d925a 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/npc/packet/Packet.java +++ b/src/main/java/io/github/znetworkw/znpcservers/npc/packet/Packet.java @@ -11,7 +11,6 @@ import io.github.znetworkw.znpcservers.utility.ReflectionUtils; import io.github.znetworkw.znpcservers.utility.Utils; import org.bukkit.inventory.ItemStack; -import java.lang.reflect.Constructor; import java.util.Collection; import java.util.Collections; @@ -33,10 +32,11 @@ public interface Packet { @PacketValue(keyName = "hologramSpawnPacket", valueType = ValueType.ARGUMENTS) Object getHologramSpawnPacket(Object paramObject) throws ReflectiveOperationException; + @SuppressWarnings("SuspiciousTernaryOperatorInVarargsCall") @PacketValue(keyName = "destroyPacket", valueType = ValueType.ARGUMENTS) default Object getDestroyPacket(int entityId) throws ReflectiveOperationException { (new int[1])[0] = entityId; - return ((Constructor) CacheRegistry.PACKET_PLAY_OUT_ENTITY_DESTROY_CONSTRUCTOR.load()).newInstance(((Constructor) CacheRegistry.PACKET_PLAY_OUT_ENTITY_DESTROY_CONSTRUCTOR.load()).getParameterTypes()[0].isArray() ? new int[1] : Integer.valueOf(entityId)); + return CacheRegistry.PACKET_PLAY_OUT_ENTITY_DESTROY_CONSTRUCTOR.load().newInstance(CacheRegistry.PACKET_PLAY_OUT_ENTITY_DESTROY_CONSTRUCTOR.load().getParameterTypes()[0].isArray() ? new int[1] : entityId); } @PacketValue(keyName = "enumSlot", valueType = ValueType.ARGUMENTS) @@ -47,15 +47,15 @@ public interface Packet { @PacketValue(keyName = "removeTab") default Object getTabRemovePacket(Object nmsEntity) throws ReflectiveOperationException { try { - return ((Constructor) CacheRegistry.PACKET_PLAY_OUT_PLAYER_INFO_CONSTRUCTOR.load()).newInstance(CacheRegistry.REMOVE_PLAYER_FIELD + return CacheRegistry.PACKET_PLAY_OUT_PLAYER_INFO_CONSTRUCTOR.load().newInstance(CacheRegistry.REMOVE_PLAYER_FIELD .load(), Collections.singletonList(nmsEntity)); } catch (Throwable throwable) { boolean useOldMethod = (CacheRegistry.PACKET_PLAY_OUT_PLAYER_INFO_REMOVE_CLASS != null); if (useOldMethod) - return ((Constructor) CacheRegistry.PACKET_PLAY_OUT_PLAYER_INFO_REMOVE_CONSTRUCTOR.load()) + return CacheRegistry.PACKET_PLAY_OUT_PLAYER_INFO_REMOVE_CONSTRUCTOR.load() .newInstance(Collections.singletonList(CacheRegistry.GET_UNIQUE_ID_METHOD.load().invoke(nmsEntity))); - return ((Constructor) CacheRegistry.PACKET_PLAY_OUT_PLAYER_INFO_CONSTRUCTOR.load()).newInstance(CacheRegistry.REMOVE_PLAYER_FIELD + return CacheRegistry.PACKET_PLAY_OUT_PLAYER_INFO_CONSTRUCTOR.load().newInstance(CacheRegistry.REMOVE_PLAYER_FIELD .load(), nmsEntity); } } @@ -63,19 +63,20 @@ public interface Packet { @PacketValue(keyName = "equipPackets") ImmutableList getEquipPackets(NPC paramNPC) throws ReflectiveOperationException; + @SuppressWarnings("unchecked") @PacketValue(keyName = "scoreboardPackets") default ImmutableList updateScoreboard(NPC npc) throws ReflectiveOperationException { ImmutableList.Builder builder = ImmutableList.builder(); boolean isVersion17 = (Utils.BUKKIT_VERSION > 16); boolean isVersion9 = (Utils.BUKKIT_VERSION > 8); - Object scoreboardTeamPacket = isVersion17 ? ((Constructor) CacheRegistry.SCOREBOARD_TEAM_CONSTRUCTOR.load()).newInstance(new Object[]{null, npc.getGameProfile().getName()}) : ((Constructor) CacheRegistry.PACKET_PLAY_OUT_SCOREBOARD_TEAM_CONSTRUCTOR_OLD.load()).newInstance(); + Object scoreboardTeamPacket = isVersion17 ? CacheRegistry.SCOREBOARD_TEAM_CONSTRUCTOR.load().newInstance(null, npc.getGameProfile().getName()) : CacheRegistry.PACKET_PLAY_OUT_SCOREBOARD_TEAM_CONSTRUCTOR_OLD.load().newInstance(); if (!isVersion17) { Utils.setValue(scoreboardTeamPacket, "a", npc.getGameProfile().getName()); - Utils.setValue(scoreboardTeamPacket, isVersion9 ? "i" : "h", Integer.valueOf(1)); + Utils.setValue(scoreboardTeamPacket, isVersion9 ? "i" : "h", 1); } builder.add(isVersion17 ? CacheRegistry.PACKET_PLAY_OUT_SCOREBOARD_TEAM_CREATE_V1.load().invoke(null, scoreboardTeamPacket) : scoreboardTeamPacket); if (isVersion17) { - scoreboardTeamPacket = ((Constructor) CacheRegistry.SCOREBOARD_TEAM_CONSTRUCTOR.load()).newInstance(new Object[]{null, npc.getGameProfile().getName()}); + scoreboardTeamPacket = CacheRegistry.SCOREBOARD_TEAM_CONSTRUCTOR.load().newInstance(null, npc.getGameProfile().getName()); if (Utils.BUKKIT_VERSION > 17) { Utils.setValue(scoreboardTeamPacket, "d", npc.getGameProfile().getName()); ReflectionUtils.findFieldForClassAndSet(scoreboardTeamPacket, CacheRegistry.ENUM_TAG_VISIBILITY, CacheRegistry.ENUM_TAG_VISIBILITY_NEVER_FIELD.load()); @@ -85,12 +86,12 @@ public interface Packet { Utils.setValue(scoreboardTeamPacket, "l", CacheRegistry.ENUM_TAG_VISIBILITY_NEVER_FIELD.load()); } } else { - scoreboardTeamPacket = ((Constructor) CacheRegistry.PACKET_PLAY_OUT_SCOREBOARD_TEAM_CONSTRUCTOR_OLD.load()).newInstance(); + scoreboardTeamPacket = CacheRegistry.PACKET_PLAY_OUT_SCOREBOARD_TEAM_CONSTRUCTOR_OLD.load().newInstance(); Utils.setValue(scoreboardTeamPacket, "a", npc.getGameProfile().getName()); Utils.setValue(scoreboardTeamPacket, "e", "never"); - Utils.setValue(scoreboardTeamPacket, isVersion9 ? "i" : "h", Integer.valueOf(0)); + Utils.setValue(scoreboardTeamPacket, isVersion9 ? "i" : "h", 0); } - Collection collection = isVersion17 ? (Collection) CacheRegistry.SCOREBOARD_PLAYER_LIST.load().invoke(scoreboardTeamPacket, new Object[0]) : (Collection) Utils.getValue(scoreboardTeamPacket, isVersion9 ? "h" : "g"); + Collection collection = isVersion17 ? (Collection) CacheRegistry.SCOREBOARD_PLAYER_LIST.load().invoke(scoreboardTeamPacket) : (Collection) Utils.getValue(scoreboardTeamPacket, isVersion9 ? "h" : "g"); if (npc.getNpcPojo().getNpcType() == NPCType.PLAYER) { collection.add(npc.getGameProfile().getName()); } else { diff --git a/src/main/java/io/github/znetworkw/znpcservers/npc/packet/PacketCache.java b/src/main/java/io/github/znetworkw/znpcservers/npc/packet/PacketCache.java index d9ac9c6..ac755e6 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/npc/packet/PacketCache.java +++ b/src/main/java/io/github/znetworkw/znpcservers/npc/packet/PacketCache.java @@ -10,6 +10,7 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; +@SuppressWarnings("unused") public class PacketCache { protected static final ImmutableMap VALUE_LOOKUP_BY_NAME; @@ -47,6 +48,7 @@ public class PacketCache { if (!VALUE_LOOKUP_BY_NAME.containsKey(method)) throw new IllegalStateException("value not found for method: " + method.getName()); PacketValue packetValue = VALUE_LOOKUP_BY_NAME.get(method); + assert packetValue != null; String keyString = packetValue.valueType().resolve(packetValue.keyName(), args); return this.packetResultCache.computeIfAbsent(keyString, o -> { try { @@ -65,7 +67,7 @@ public class PacketCache { public void flushCache() { flushCache(VALUE_LOOKUP_BY_NAME.values().stream() - .map(PacketValue::keyName).toArray(x$0 -> new String[x$0])); + .map(PacketValue::keyName).toArray(String[]::new)); } private static class PacketHandler implements InvocationHandler { diff --git a/src/main/java/io/github/znetworkw/znpcservers/npc/packet/PacketFactory.java b/src/main/java/io/github/znetworkw/znpcservers/npc/packet/PacketFactory.java index b872bac..4689965 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/npc/packet/PacketFactory.java +++ b/src/main/java/io/github/znetworkw/znpcservers/npc/packet/PacketFactory.java @@ -6,7 +6,7 @@ import io.github.znetworkw.znpcservers.utility.Utils; import java.util.Comparator; public final class PacketFactory { - public static final ImmutableSet ALL = ImmutableSet.of(new PacketV8(), new PacketV9(), new PacketV16(), new PacketV17(), new PacketV18(), new PacketV19(), (Object[]) new Packet[0]); + public static final ImmutableSet ALL = ImmutableSet.of(new PacketV8(), new PacketV9(), new PacketV16(), new PacketV17(), new PacketV18(), new PacketV19()); public static final Packet PACKET_FOR_CURRENT_VERSION = findPacketForVersion(Utils.BUKKIT_VERSION); diff --git a/src/main/java/io/github/znetworkw/znpcservers/npc/packet/PacketV16.java b/src/main/java/io/github/znetworkw/znpcservers/npc/packet/PacketV16.java index b5a3e11..96888c2 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/npc/packet/PacketV16.java +++ b/src/main/java/io/github/znetworkw/znpcservers/npc/packet/PacketV16.java @@ -8,7 +8,6 @@ import io.github.znetworkw.znpcservers.npc.ItemSlot; import io.github.znetworkw.znpcservers.npc.NPC; import org.bukkit.inventory.ItemStack; -import java.lang.reflect.Constructor; import java.util.List; import java.util.Map; @@ -20,9 +19,9 @@ public class PacketV16 extends PacketV9 { public ImmutableList getEquipPackets(NPC npc) throws ReflectiveOperationException { List> pairs = Lists.newArrayListWithCapacity((ItemSlot.values()).length); for (Map.Entry entry : npc.getNpcPojo().getNpcEquip().entrySet()) - pairs.add(new Pair(getItemSlot(entry + pairs.add(new Pair<>(getItemSlot(entry .getKey().getSlot()), convertItemStack(npc.getEntityID(), entry.getKey(), entry.getValue()))); - return ImmutableList.of(((Constructor) CacheRegistry.PACKET_PLAY_OUT_ENTITY_EQUIPMENT_CONSTRUCTOR_V1.load()).newInstance(Integer.valueOf(npc.getEntityID()), pairs)); + return ImmutableList.of(CacheRegistry.PACKET_PLAY_OUT_ENTITY_EQUIPMENT_CONSTRUCTOR_V1.load().newInstance(npc.getEntityID(), pairs)); } } diff --git a/src/main/java/io/github/znetworkw/znpcservers/npc/packet/PacketV17.java b/src/main/java/io/github/znetworkw/znpcservers/npc/packet/PacketV17.java index 85eac78..1b50a90 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/npc/packet/PacketV17.java +++ b/src/main/java/io/github/znetworkw/znpcservers/npc/packet/PacketV17.java @@ -6,15 +6,13 @@ import io.github.znetworkw.znpcservers.npc.NPC; import io.github.znetworkw.znpcservers.utility.Utils; import org.bukkit.Bukkit; -import java.lang.reflect.Constructor; - public class PacketV17 extends PacketV16 { public int version() { return 17; } public Object getPlayerPacket(Object nmsWorld, GameProfile gameProfile) throws ReflectiveOperationException { - return ((Constructor) CacheRegistry.PLAYER_CONSTRUCTOR_NEW.load()).newInstance(new Object[]{CacheRegistry.GET_SERVER_METHOD.load().invoke(Bukkit.getServer()), nmsWorld, gameProfile}); + return CacheRegistry.PLAYER_CONSTRUCTOR_NEW.load().newInstance(CacheRegistry.GET_SERVER_METHOD.load().invoke(Bukkit.getServer()), nmsWorld, gameProfile); } public void updateGlowPacket(NPC npc, Object packet) throws ReflectiveOperationException { diff --git a/src/main/java/io/github/znetworkw/znpcservers/npc/packet/PacketV19.java b/src/main/java/io/github/znetworkw/znpcservers/npc/packet/PacketV19.java index 6595810..35ee4c0 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/npc/packet/PacketV19.java +++ b/src/main/java/io/github/znetworkw/znpcservers/npc/packet/PacketV19.java @@ -4,8 +4,6 @@ import com.mojang.authlib.GameProfile; import io.github.znetworkw.znpcservers.cache.CacheRegistry; import org.bukkit.Bukkit; -import java.lang.reflect.Constructor; - public class PacketV19 extends PacketV18 { public int version() { return 19; @@ -13,11 +11,11 @@ public class PacketV19 extends PacketV18 { public Object getPlayerPacket(Object nmsWorld, GameProfile gameProfile) throws ReflectiveOperationException { try { - return ((Constructor) CacheRegistry.PLAYER_CONSTRUCTOR_NEW_1.load()).newInstance(new Object[]{CacheRegistry.GET_SERVER_METHOD - .load().invoke(Bukkit.getServer()), nmsWorld, gameProfile, null}); + return CacheRegistry.PLAYER_CONSTRUCTOR_NEW_1.load().newInstance(CacheRegistry.GET_SERVER_METHOD + .load().invoke(Bukkit.getServer()), nmsWorld, gameProfile, null); } catch (Throwable e) { - return ((Constructor) CacheRegistry.PLAYER_CONSTRUCTOR_NEW_2.load()).newInstance(new Object[]{CacheRegistry.GET_SERVER_METHOD - .load().invoke(Bukkit.getServer()), nmsWorld, gameProfile}); + return CacheRegistry.PLAYER_CONSTRUCTOR_NEW_2.load().newInstance(CacheRegistry.GET_SERVER_METHOD + .load().invoke(Bukkit.getServer()), nmsWorld, gameProfile); } } } diff --git a/src/main/java/io/github/znetworkw/znpcservers/npc/packet/PacketV8.java b/src/main/java/io/github/znetworkw/znpcservers/npc/packet/PacketV8.java index aa5a076..f5998c9 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/npc/packet/PacketV8.java +++ b/src/main/java/io/github/znetworkw/znpcservers/npc/packet/PacketV8.java @@ -19,19 +19,19 @@ public class PacketV8 implements Packet { public Object getPlayerPacket(Object nmsWorld, GameProfile gameProfile) throws ReflectiveOperationException { Constructor constructor = (Utils.BUKKIT_VERSION > 13) ? CacheRegistry.PLAYER_INTERACT_MANAGER_NEW_CONSTRUCTOR.load() : CacheRegistry.PLAYER_INTERACT_MANAGER_OLD_CONSTRUCTOR.load(); - return ((Constructor) CacheRegistry.PLAYER_CONSTRUCTOR_OLD.load()).newInstance(new Object[]{CacheRegistry.GET_SERVER_METHOD + return CacheRegistry.PLAYER_CONSTRUCTOR_OLD.load().newInstance(CacheRegistry.GET_SERVER_METHOD .load().invoke(Bukkit.getServer()), nmsWorld, gameProfile, constructor - .newInstance(nmsWorld)}); + .newInstance(nmsWorld)); } public Object getSpawnPacket(Object nmsEntity, boolean isPlayer) throws ReflectiveOperationException { - return isPlayer ? ((Constructor) CacheRegistry.PACKET_PLAY_OUT_NAMED_ENTITY_CONSTRUCTOR.load()).newInstance(nmsEntity) : ((Constructor) CacheRegistry.PACKET_PLAY_OUT_SPAWN_ENTITY_CONSTRUCTOR.load()).newInstance(nmsEntity); + return isPlayer ? CacheRegistry.PACKET_PLAY_OUT_NAMED_ENTITY_CONSTRUCTOR.load().newInstance(nmsEntity) : CacheRegistry.PACKET_PLAY_OUT_SPAWN_ENTITY_CONSTRUCTOR.load().newInstance(nmsEntity); } public Object convertItemStack(int entityId, ItemSlot itemSlot, ItemStack itemStack) throws ReflectiveOperationException { - return ((Constructor) CacheRegistry.PACKET_PLAY_OUT_ENTITY_EQUIPMENT_CONSTRUCTOR_OLD.load()).newInstance(Integer.valueOf(entityId), - Integer.valueOf(itemSlot.getSlotOld()), CacheRegistry.AS_NMS_COPY_METHOD + return CacheRegistry.PACKET_PLAY_OUT_ENTITY_EQUIPMENT_CONSTRUCTOR_OLD.load().newInstance(entityId, + itemSlot.getSlotOld(), CacheRegistry.AS_NMS_COPY_METHOD .load().invoke(CacheRegistry.CRAFT_ITEM_STACK_CLASS, itemStack)); } @@ -42,24 +42,24 @@ public class PacketV8 implements Packet { public Object getMetadataPacket(int entityId, Object nmsEntity) throws ReflectiveOperationException { Object dataWatcher = CacheRegistry.GET_DATA_WATCHER_METHOD.load().invoke(nmsEntity); try { - return ((Constructor) CacheRegistry.PACKET_PLAY_OUT_ENTITY_META_DATA_CONSTRUCTOR.load()).newInstance(Integer.valueOf(entityId), dataWatcher, Boolean.valueOf(true)); + return CacheRegistry.PACKET_PLAY_OUT_ENTITY_META_DATA_CONSTRUCTOR.load().newInstance(entityId, dataWatcher, true); } catch (Exception e2) { - return ((Constructor) CacheRegistry.PACKET_PLAY_OUT_ENTITY_META_DATA_CONSTRUCTOR_V1 - .load()) - .newInstance(Integer.valueOf(entityId), CacheRegistry.GET_DATAWATCHER_B_LIST + return CacheRegistry.PACKET_PLAY_OUT_ENTITY_META_DATA_CONSTRUCTOR_V1 + .load() + .newInstance(entityId, CacheRegistry.GET_DATAWATCHER_B_LIST .load().invoke(dataWatcher)); } } public Object getHologramSpawnPacket(Object armorStand) throws ReflectiveOperationException { - return ((Constructor) CacheRegistry.PACKET_PLAY_OUT_SPAWN_ENTITY_CONSTRUCTOR.load()).newInstance(armorStand); + return CacheRegistry.PACKET_PLAY_OUT_SPAWN_ENTITY_CONSTRUCTOR.load().newInstance(armorStand); } public ImmutableList getEquipPackets(NPC npc) throws ReflectiveOperationException { ImmutableList.Builder builder = ImmutableList.builder(); for (Map.Entry stackEntry : npc.getNpcPojo().getNpcEquip().entrySet()) { - builder.add(((Constructor) CacheRegistry.PACKET_PLAY_OUT_ENTITY_EQUIPMENT_CONSTRUCTOR_OLD.load()).newInstance(Integer.valueOf(npc.getEntityID()), - Integer.valueOf(stackEntry.getKey().getSlotOld()), + builder.add(CacheRegistry.PACKET_PLAY_OUT_ENTITY_EQUIPMENT_CONSTRUCTOR_OLD.load().newInstance(npc.getEntityID(), + stackEntry.getKey().getSlotOld(), convertItemStack(npc.getEntityID(), stackEntry.getKey(), stackEntry.getValue()))); } return builder.build(); diff --git a/src/main/java/io/github/znetworkw/znpcservers/npc/packet/PacketV9.java b/src/main/java/io/github/znetworkw/znpcservers/npc/packet/PacketV9.java index 65ec2ff..2986d33 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/npc/packet/PacketV9.java +++ b/src/main/java/io/github/znetworkw/znpcservers/npc/packet/PacketV9.java @@ -7,7 +7,6 @@ import io.github.znetworkw.znpcservers.npc.NPC; import io.github.znetworkw.znpcservers.utility.Utils; import org.bukkit.inventory.ItemStack; -import java.lang.reflect.Constructor; import java.util.Map; public class PacketV9 extends PacketV8 { @@ -22,7 +21,7 @@ public class PacketV9 extends PacketV8 { public ImmutableList getEquipPackets(NPC npc) throws ReflectiveOperationException { ImmutableList.Builder builder = ImmutableList.builder(); for (Map.Entry stackEntry : npc.getNpcPojo().getNpcEquip().entrySet()) { - builder.add(((Constructor) CacheRegistry.PACKET_PLAY_OUT_ENTITY_EQUIPMENT_CONSTRUCTOR_NEWEST_OLD.load()).newInstance(Integer.valueOf(npc.getEntityID()), + builder.add(CacheRegistry.PACKET_PLAY_OUT_ENTITY_EQUIPMENT_CONSTRUCTOR_NEWEST_OLD.load().newInstance(npc.getEntityID(), getItemSlot(stackEntry.getKey().getSlot()), convertItemStack(npc.getEntityID(), stackEntry.getKey(), stackEntry.getValue()))); } @@ -33,7 +32,7 @@ public class PacketV9 extends PacketV8 { Object enumChatString = CacheRegistry.ENUM_CHAT_TO_STRING_METHOD.load().invoke(npc.getGlowColor()); if (Utils.BUKKIT_VERSION > 12) { Utils.setValue(packet, npc.getGlowColor(), CacheRegistry.ENUM_CHAT_CLASS); - Utils.setValue(packet, "c", ((Constructor) CacheRegistry.I_CHAT_BASE_COMPONENT_A_CONSTRUCTOR.load()).newInstance(enumChatString)); + Utils.setValue(packet, "c", CacheRegistry.I_CHAT_BASE_COMPONENT_A_CONSTRUCTOR.load().newInstance(enumChatString)); } else { Utils.setValue(packet, "g", CacheRegistry.GET_ENUM_CHAT_ID_METHOD.load().invoke(npc.getGlowColor())); Utils.setValue(packet, "c", enumChatString); diff --git a/src/main/java/io/github/znetworkw/znpcservers/npc/task/NPCLoadTask.java b/src/main/java/io/github/znetworkw/znpcservers/npc/task/NPCLoadTask.java index c04040b..874ec61 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/npc/task/NPCLoadTask.java +++ b/src/main/java/io/github/znetworkw/znpcservers/npc/task/NPCLoadTask.java @@ -7,10 +7,6 @@ import org.bukkit.World; import org.bukkit.scheduler.BukkitRunnable; public class NPCLoadTask extends BukkitRunnable { - private static final int DELAY = 40; - - private static final int MAX_TRIES = 10; - private final NPC npc; private int tries = 0; diff --git a/src/main/java/io/github/znetworkw/znpcservers/skin/SkinFetcher.java b/src/main/java/io/github/znetworkw/znpcservers/skin/SkinFetcher.java index feecd7a..a697719 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/skin/SkinFetcher.java +++ b/src/main/java/io/github/znetworkw/znpcservers/skin/SkinFetcher.java @@ -15,14 +15,8 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class SkinFetcher { - private static final String EMPTY_STRING = ""; - - private static final String DEFAULT_CHARSET = "UTF-8"; - private static final ExecutorService SKIN_EXECUTOR_SERVICE = Executors.newCachedThreadPool(); - private static final JsonParser JSON_PARSER = new JsonParser(); - private final SkinFetcherBuilder builder; public SkinFetcher(SkinFetcherBuilder builder) { @@ -53,7 +47,7 @@ public class SkinFetcher { try { Reader reader = new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8); try { - completableFuture.complete(JSON_PARSER.parse(reader).getAsJsonObject()); + completableFuture.complete(JsonParser.parseReader(reader).getAsJsonObject()); reader.close(); } catch (Throwable throwable) { try { diff --git a/src/main/java/io/github/znetworkw/znpcservers/user/EventService.java b/src/main/java/io/github/znetworkw/znpcservers/user/EventService.java index 382eb56..a301b97 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/user/EventService.java +++ b/src/main/java/io/github/znetworkw/znpcservers/user/EventService.java @@ -10,7 +10,6 @@ import java.util.function.Consumer; public class EventService { private final Class eventClass; - private final List> eventConsumers; protected EventService(Class eventClass, List> eventConsumers) { @@ -18,29 +17,6 @@ public class EventService { this.eventConsumers = eventConsumers; } - public static EventService addService(ZUser user, Class eventClass) { - if (hasService(user, eventClass)) - throw new IllegalStateException(eventClass.getSimpleName() + " is already register for " + user.getUUID().toString()); - EventService service = new EventService<>(eventClass, new ArrayList<>()); - user.getEventServices().add(service); - user.toPlayer().closeInventory(); - return service; - } - - public static EventService findService(ZUser user, Class eventClass) { - Objects.requireNonNull(EventService.class); - Objects.requireNonNull(EventService.class); - return user.getEventServices().stream().filter(eventService -> eventService.getEventClass().isAssignableFrom(eventClass)).map(EventService.class::cast) - .findFirst() - .orElse(null); - } - - public static boolean hasService(ZUser user, Class eventClass) { - return user.getEventServices() - .stream() - .anyMatch(eventService -> (eventService.getEventClass() == eventClass)); - } - public Class getEventClass() { return this.eventClass; } @@ -50,11 +26,31 @@ public class EventService { } public EventService addConsumer(Consumer consumer) { - getEventConsumers().add(consumer); + this.getEventConsumers().add(consumer); return this; } public void runAll(T event) { - ZNPCsPlus.SCHEDULER.runTask(() -> this.eventConsumers.forEach(())); + ZNPCsPlus.SCHEDULER.runTask(() -> this.eventConsumers.forEach(consumer -> consumer.accept(event))); + } + + public static EventService addService(ZUser user, Class eventClass) { + if (EventService.hasService(user, eventClass)) { + throw new IllegalStateException(eventClass.getSimpleName() + " is already register for " + user.getUUID().toString()); + } + EventService service = new EventService<>(eventClass, new ArrayList<>()); + user.getEventServices().add(service); + user.toPlayer().closeInventory(); + return service; + } + + @SuppressWarnings("unchecked") + public static EventService findService(ZUser user, Class eventClass) { + Objects.requireNonNull(EventService.class); + return user.getEventServices().stream().filter(eventService -> eventService.getEventClass().isAssignableFrom(eventClass)).map(EventService.class::cast).findFirst().orElse(null); + } + + public static boolean hasService(ZUser user, Class eventClass) { + return user.getEventServices().stream().anyMatch(eventService -> eventService.getEventClass() == eventClass); } } diff --git a/src/main/java/io/github/znetworkw/znpcservers/user/ZUser.java b/src/main/java/io/github/znetworkw/znpcservers/user/ZUser.java index ce155f4..138660a 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/user/ZUser.java +++ b/src/main/java/io/github/znetworkw/znpcservers/user/ZUser.java @@ -1,26 +1,21 @@ package io.github.znetworkw.znpcservers.user; import com.mojang.authlib.GameProfile; -import lol.pyr.znpcsplus.ZNPCsPlus; import io.github.znetworkw.znpcservers.cache.CacheRegistry; import io.github.znetworkw.znpcservers.npc.NPC; import io.github.znetworkw.znpcservers.npc.NPCAction; import io.github.znetworkw.znpcservers.npc.event.ClickType; import io.github.znetworkw.znpcservers.npc.event.NPCInteractEvent; import io.netty.channel.Channel; -import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToMessageDecoder; +import lol.pyr.znpcsplus.ZNPCsPlus; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import java.util.*; public class ZUser { - private static final String CHANNEL_NAME = "npc_interact"; - - private static final int DEFAULT_DELAY = 1; - private static final Map USER_MAP = new HashMap<>(); private final Map lastClicked; @@ -48,7 +43,7 @@ public class ZUser { .get(this.playerConnection = CacheRegistry.PLAYER_CONNECTION_FIELD.load().get(playerHandle))); if (channel.pipeline().names().contains("npc_interact")) channel.pipeline().remove("npc_interact"); - channel.pipeline().addAfter("decoder", "npc_interact", (ChannelHandler) new ZNPCSocketDecoder()); + channel.pipeline().addAfter("decoder", "npc_interact", new ZNPCSocketDecoder()); } catch (IllegalAccessException | java.lang.reflect.InvocationTargetException e) { throw new IllegalStateException("can't create player " + uuid.toString(), e.getCause()); } @@ -123,16 +118,16 @@ public class ZUser { continue; if (npcAction.getDelay() > 0) { int actionId = npc.getNpcPojo().getClickActions().indexOf(npcAction); - if (ZUser.this.lastClicked.containsKey(Integer.valueOf(actionId))) { - long lastClickNanos = System.nanoTime() - ZUser.this.lastClicked.get(Integer.valueOf(actionId)).longValue(); + if (ZUser.this.lastClicked.containsKey(actionId)) { + long lastClickNanos = System.nanoTime() - ZUser.this.lastClicked.get(actionId); if (lastClickNanos < npcAction.getFixedDelay()) continue; } - ZUser.this.lastClicked.put(Integer.valueOf(actionId), Long.valueOf(System.nanoTime())); + ZUser.this.lastClicked.put(actionId, System.nanoTime()); } npcAction.run(ZUser.this, npcAction.getAction()); } - }1); + }, 1); } } } diff --git a/src/main/java/io/github/znetworkw/znpcservers/utility/Utils.java b/src/main/java/io/github/znetworkw/znpcservers/utility/Utils.java index fe7b0af..522f93e 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/utility/Utils.java +++ b/src/main/java/io/github/znetworkw/znpcservers/utility/Utils.java @@ -4,6 +4,7 @@ import io.github.znetworkw.znpcservers.cache.CacheRegistry; import io.github.znetworkw.znpcservers.configuration.ConfigurationConstants; import io.github.znetworkw.znpcservers.user.ZUser; import me.clip.placeholderapi.PlaceholderAPI; +import org.apache.commons.lang.math.NumberUtils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; @@ -11,11 +12,9 @@ import org.bukkit.entity.Player; import java.lang.reflect.Field; import java.util.concurrent.ThreadLocalRandom; +@SuppressWarnings("deprecation") public final class Utils { public static final int BUKKIT_VERSION; - - public static final long SECOND_INTERVAL_NANOS = 1000000000L; - public static boolean PLACEHOLDER_SUPPORT = Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI"); static { diff --git a/src/main/java/io/github/znetworkw/znpcservers/utility/inventory/ZInventory.java b/src/main/java/io/github/znetworkw/znpcservers/utility/inventory/ZInventory.java index eddcac1..0f1172c 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/utility/inventory/ZInventory.java +++ b/src/main/java/io/github/znetworkw/znpcservers/utility/inventory/ZInventory.java @@ -32,11 +32,12 @@ public class ZInventory { this.page = page; } + @SuppressWarnings("deprecation") public Inventory build(ZInventoryPage page) { if (page == null) throw new IllegalStateException("page is null"); if (page.getRows() / 9 > 6) - throw new IllegalArgumentException(String.format("Unexpected rows size. Has %d, max %d", Integer.valueOf(page.getRows()), Integer.valueOf(6))); + throw new IllegalArgumentException(String.format("Unexpected rows size. Has %d, max %d", page.getRows(), 6)); setCurrentPage(page); page.getInventoryItems().removeIf(zInventoryItem -> !zInventoryItem.isDefault()); page.update(); diff --git a/src/main/java/io/github/znetworkw/znpcservers/utility/inventory/ZInventoryPage.java b/src/main/java/io/github/znetworkw/znpcservers/utility/inventory/ZInventoryPage.java index 52a38bc..971aa9d 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/utility/inventory/ZInventoryPage.java +++ b/src/main/java/io/github/znetworkw/znpcservers/utility/inventory/ZInventoryPage.java @@ -9,6 +9,7 @@ import org.bukkit.inventory.ItemStack; import java.util.ArrayList; import java.util.List; +@SuppressWarnings("deprecation") public abstract class ZInventoryPage { private final ZInventory zInventory; @@ -27,7 +28,7 @@ public abstract class ZInventoryPage { ZInventoryPage zInventoryPage = zInventory.getPage(); addItem(ItemStackBuilder.forMaterial(Material.ARROW) .setName(ChatColor.GREEN + "Go back") - .setLore(new String[]{ChatColor.GRAY + "click here..."}, ).build(), this.rows - 9, true, event -> { + .setLore(ChatColor.GRAY + "click here...").build(), this.rows - 9, true, event -> { zInventory.setCurrentPage(zInventoryPage); openInventory(); }); diff --git a/src/main/java/io/github/znetworkw/znpcservers/utility/itemstack/ItemStackBuilder.java b/src/main/java/io/github/znetworkw/znpcservers/utility/itemstack/ItemStackBuilder.java index 476982a..a956eb7 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/utility/itemstack/ItemStackBuilder.java +++ b/src/main/java/io/github/znetworkw/znpcservers/utility/itemstack/ItemStackBuilder.java @@ -9,6 +9,7 @@ import java.util.Arrays; import java.util.stream.Collectors; import java.util.stream.StreamSupport; +@SuppressWarnings("deprecation") public class ItemStackBuilder { private final ItemStack itemStack; diff --git a/src/main/java/io/github/znetworkw/znpcservers/utility/location/ZLocation.java b/src/main/java/io/github/znetworkw/znpcservers/utility/location/ZLocation.java index 5a8cdfb..d57341c 100644 --- a/src/main/java/io/github/znetworkw/znpcservers/utility/location/ZLocation.java +++ b/src/main/java/io/github/znetworkw/znpcservers/utility/location/ZLocation.java @@ -81,11 +81,11 @@ public class ZLocation { public JsonElement serialize(ZLocation src, Type typeOfSrc, JsonSerializationContext context) { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("world", src.getWorldName()); - jsonObject.addProperty("x", Double.valueOf(src.getX())); - jsonObject.addProperty("y", Double.valueOf(src.getY())); - jsonObject.addProperty("z", Double.valueOf(src.getZ())); - jsonObject.addProperty("yaw", Float.valueOf(src.getYaw())); - jsonObject.addProperty("pitch", Float.valueOf(src.getPitch())); + jsonObject.addProperty("x", src.getX()); + jsonObject.addProperty("y", src.getY()); + jsonObject.addProperty("z", src.getZ()); + jsonObject.addProperty("yaw", src.getYaw()); + jsonObject.addProperty("pitch", src.getPitch()); return jsonObject; } diff --git a/src/main/java/lol/pyr/znpcsplus/ZNPCsPlus.java b/src/main/java/lol/pyr/znpcsplus/ZNPCsPlus.java index 086f042..c17237c 100644 --- a/src/main/java/lol/pyr/znpcsplus/ZNPCsPlus.java +++ b/src/main/java/lol/pyr/znpcsplus/ZNPCsPlus.java @@ -16,10 +16,10 @@ import io.github.znetworkw.znpcservers.npc.task.NPCManagerTask; import io.github.znetworkw.znpcservers.npc.task.NPCSaveTask; import io.github.znetworkw.znpcservers.user.ZUser; import io.github.znetworkw.znpcservers.utility.BungeeUtils; -import io.github.znetworkw.znpcservers.utility.MetricsLite; import io.github.znetworkw.znpcservers.utility.SchedulerUtils; import io.github.znetworkw.znpcservers.utility.itemstack.ItemStackSerializer; import io.github.znetworkw.znpcservers.utility.location.ZLocation; +import org.bstats.bukkit.Metrics; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.inventory.ItemStack; @@ -65,7 +65,7 @@ public class ZNPCsPlus extends JavaPlugin { loadAllPaths(); getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord"); - new MetricsLite(this, PLUGIN_ID); + new Metrics(this, PLUGIN_ID); new DefaultCommand(); SCHEDULER = new SchedulerUtils(this); BUNGEE_UTILS = new BungeeUtils(this);