add back spigot support, do a bunch of refactoring & fix lower versions not having adventure

This commit is contained in:
Pyrbu 2023-04-21 18:15:28 +01:00
parent c7ff0ed8e8
commit 983f240511
28 changed files with 91 additions and 218 deletions

@ -6,6 +6,9 @@ plugins {
repositories { repositories {
mavenCentral() mavenCentral()
maven {
url "https://hub.spigotmc.org/nexus/content/repositories/snapshots/"
}
maven { maven {
url "https://repo.papermc.io/repository/maven-public/" url "https://repo.papermc.io/repository/maven-public/"
} }
@ -18,7 +21,7 @@ repositories {
} }
dependencies { dependencies {
compileOnly "io.papermc.paper:paper-api:1.19.4-R0.1-SNAPSHOT" compileOnly "org.spigotmc:spigot-api:1.19.4-R0.1-SNAPSHOT"
compileOnly "me.clip:placeholderapi:2.11.1" compileOnly "me.clip:placeholderapi:2.11.1"
//noinspection GradlePackageUpdate //noinspection GradlePackageUpdate
@ -31,6 +34,7 @@ dependencies {
implementation "com.google.code.gson:gson:2.10.1" implementation "com.google.code.gson:gson:2.10.1"
implementation "org.bstats:bstats-bukkit:3.0.2" implementation "org.bstats:bstats-bukkit:3.0.2"
implementation "com.github.robertlit:SpigotResourcesAPI:2.0" implementation "com.github.robertlit:SpigotResourcesAPI:2.0"
implementation "net.kyori:adventure-platform-bukkit:4.3.0"
} }
group "lol.pyr" group "lol.pyr"

@ -4,15 +4,15 @@ import com.google.common.collect.Iterables;
import io.github.znetworkw.znpcservers.commands.exception.CommandException; import io.github.znetworkw.znpcservers.commands.exception.CommandException;
import io.github.znetworkw.znpcservers.commands.exception.CommandExecuteException; import io.github.znetworkw.znpcservers.commands.exception.CommandExecuteException;
import io.github.znetworkw.znpcservers.commands.exception.CommandPermissionException; import io.github.znetworkw.znpcservers.commands.exception.CommandPermissionException;
import org.bukkit.Bukkit; import io.github.znetworkw.znpcservers.reflection.Reflections;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.command.CommandMap;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.command.defaults.BukkitCommand; import org.bukkit.command.defaults.BukkitCommand;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.*; import java.util.*;
@SuppressWarnings("deprecation")
public class Command extends BukkitCommand { public class Command extends BukkitCommand {
private final Map<CommandInformation, CommandInvoker> subCommands; private final Map<CommandInformation, CommandInvoker> subCommands;
@ -23,7 +23,7 @@ public class Command extends BukkitCommand {
} }
private void load() { private void load() {
Bukkit.getCommandMap().register(getName(), this); ((CommandMap) Reflections.COMMAND_MAP_FIELD.get()).register(getName(), this);
for (Method method : getClass().getMethods()) { for (Method method : getClass().getMethods()) {
if (method.isAnnotationPresent(CommandInformation.class)) { if (method.isAnnotationPresent(CommandInformation.class)) {
CommandInformation cmdInfo = method.getAnnotation(CommandInformation.class); CommandInformation cmdInfo = method.getAnnotation(CommandInformation.class);

@ -7,19 +7,9 @@ import io.github.znetworkw.znpcservers.utility.GuavaCollectors;
public final class FunctionFactory { public final class FunctionFactory {
public static ImmutableList<NPCFunction> WITHOUT_FUNCTION = ImmutableList.of(new NPCFunction.WithoutFunction("look"), new NPCFunction.WithoutFunctionSelfUpdate("holo"), new NPCFunction.WithoutFunctionSelfUpdate("mirror")); public static ImmutableList<NPCFunction> WITHOUT_FUNCTION = ImmutableList.of(new NPCFunction.WithoutFunction("look"), new NPCFunction.WithoutFunctionSelfUpdate("holo"), new NPCFunction.WithoutFunctionSelfUpdate("mirror"));
public static ImmutableList<NPCFunction> WITH_FUNCTION = ImmutableList.of(new GlowFunction()); public static ImmutableList<NPCFunction> WITH_FUNCTION = ImmutableList.of(new GlowFunction());
public static ImmutableList<NPCFunction> ALL = new ImmutableList.Builder<NPCFunction>().addAll(WITHOUT_FUNCTION).addAll(WITH_FUNCTION).build();
public static ImmutableList<NPCFunction> ALL = new ImmutableList.Builder<NPCFunction>() public static ImmutableMap<String, NPCFunction> BY_NAME = ALL.stream().collect(GuavaCollectors.toImmutableMap(NPCFunction::getName, function -> function));
.addAll(WITHOUT_FUNCTION)
.addAll(WITH_FUNCTION)
.build();
public static ImmutableMap<String, NPCFunction> BY_NAME;
static {
BY_NAME = ALL.stream().collect(GuavaCollectors.toImmutableMap(NPCFunction::getName, function -> function));
}
public static NPCFunction findFunctionForName(String name) { public static NPCFunction findFunctionForName(String name) {
return BY_NAME.get(name); return BY_NAME.get(name);

@ -10,11 +10,8 @@ import org.bukkit.ChatColor;
public class NPCAction { public class NPCAction {
private final ActionType actionType; private final ActionType actionType;
private final ClickType clickType; private final ClickType clickType;
private final String action; private final String action;
private int delay; private int delay;
public NPCAction(ActionType actionType, ClickType clickType, String action, int delay) { public NPCAction(ActionType actionType, ClickType clickType, String action, int delay) {
@ -65,7 +62,6 @@ public class NPCAction {
.toString(); .toString();
} }
@SuppressWarnings("deprecation")
enum ActionType { enum ActionType {
CMD { CMD {
public void run(ZUser user, String actionValue) { public void run(ZUser user, String actionValue) {

@ -9,31 +9,18 @@ import java.util.*;
@SuppressWarnings("unused") @SuppressWarnings("unused")
public class NPCModel { public class NPCModel {
private int id; private int id;
private double hologramHeight; private double hologramHeight;
private String skin; private String skin;
private String signature = ""; private String signature = "";
private String pathName; private String pathName;
private String glowName; private String glowName;
private ConversationModel conversation; private ConversationModel conversation;
private ZLocation location; private ZLocation location;
private NPCType npcType; private NPCType npcType;
private List<String> hologramLines; private List<String> hologramLines;
private List<NPCAction> clickActions; private List<NPCAction> clickActions;
private Map<ItemSlot, ItemStack> npcEquip; private Map<ItemSlot, ItemStack> npcEquip;
private Map<String, Boolean> npcFunctions; private Map<String, Boolean> npcFunctions;
private Map<String, String[]> customizationMap; private Map<String, String[]> customizationMap;
public NPCModel(int id) { public NPCModel(int id) {

@ -20,11 +20,8 @@ import java.util.concurrent.ConcurrentMap;
@SuppressWarnings("ALL") @SuppressWarnings("ALL")
public interface NPCPath { public interface NPCPath {
void initialize(DataInputStream paramDataInputStream) throws IOException; void initialize(DataInputStream paramDataInputStream) throws IOException;
void write(DataOutputStream paramDataOutputStream) throws IOException; void write(DataOutputStream paramDataOutputStream) throws IOException;
void start(); void start();
PathInitializer getPath(NPC paramNPC); PathInitializer getPath(NPC paramNPC);
interface PathInitializer { interface PathInitializer {
@ -88,13 +85,9 @@ public interface NPCPath {
abstract class AbstractTypeWriter implements NPCPath { abstract class AbstractTypeWriter implements NPCPath {
private static final ConcurrentMap<String, AbstractTypeWriter> PATH_TYPES = new ConcurrentHashMap<>(); private static final ConcurrentMap<String, AbstractTypeWriter> PATH_TYPES = new ConcurrentHashMap<>();
private static final int PATH_DELAY = 1; private static final int PATH_DELAY = 1;
private final TypeWriter typeWriter; private final TypeWriter typeWriter;
private final File file; private final File file;
private final List<ZLocation> locationList; private final List<ZLocation> locationList;
public AbstractTypeWriter(TypeWriter typeWriter, File file) { public AbstractTypeWriter(TypeWriter typeWriter, File file) {

@ -5,12 +5,8 @@ import io.github.znetworkw.znpcservers.skin.SkinFetcherResult;
import io.github.znetworkw.znpcservers.utility.Utils; import io.github.znetworkw.znpcservers.utility.Utils;
public class NPCSkin { public class NPCSkin {
private static final String[] EMPTY_ARRAY = new String[0];
private static final int LAYER_INDEX = SkinLayerValues.findLayerByVersion(); private static final int LAYER_INDEX = SkinLayerValues.findLayerByVersion();
private final String texture; private final String texture;
private final String signature; private final String signature;
protected NPCSkin(String... values) { protected NPCSkin(String... values) {
@ -21,7 +17,7 @@ public class NPCSkin {
} }
public static NPCSkin forValues(String... values) { public static NPCSkin forValues(String... values) {
return new NPCSkin((values.length > 0) ? values : EMPTY_ARRAY); return new NPCSkin((values.length > 0) ? values : new String[0]);
} }
public static void forName(String skin, SkinFetcherResult skinFetcherResult) { public static void forName(String skin, SkinFetcherResult skinFetcherResult) {

@ -18,20 +18,13 @@ public enum TypeProperty {
} }
public static TypeProperty forType(Class<?> primitiveType) { public static TypeProperty forType(Class<?> primitiveType) {
if (primitiveType == String.class) if (primitiveType == String.class) return STRING;
return STRING; if (primitiveType == boolean.class) return BOOLEAN;
if (primitiveType == boolean.class) if (primitiveType == int.class) return INT;
return BOOLEAN; if (primitiveType == double.class) return DOUBLE;
if (primitiveType == int.class) if (primitiveType == float.class) return FLOAT;
return INT; if (primitiveType == short.class) return SHORT;
if (primitiveType == double.class) if (primitiveType == long.class) return LONG;
return DOUBLE;
if (primitiveType == float.class)
return FLOAT;
if (primitiveType == short.class)
return SHORT;
if (primitiveType == long.class)
return LONG;
return null; return null;
} }

@ -7,11 +7,8 @@ import java.util.List;
public class Conversation { public class Conversation {
private final String name; private final String name;
private final List<ConversationKey> texts; private final List<ConversationKey> texts;
private int radius = 5; private int radius = 5;
private int delay = 10; private int delay = 10;
public Conversation(String name) { public Conversation(String name) {

@ -10,13 +10,9 @@ import java.util.stream.StreamSupport;
public class ConversationKey { public class ConversationKey {
private static final Splitter SPACE_SPLITTER = Splitter.on(" "); private static final Splitter SPACE_SPLITTER = Splitter.on(" ");
private final List<String> lines; private final List<String> lines;
private final List<NPCAction> actions; private final List<NPCAction> actions;
private int delay = 1; private int delay = 1;
private String soundName; private String soundName;
public ConversationKey(String line) { public ConversationKey(String line) {

@ -16,15 +16,10 @@ import java.util.UUID;
public class ConversationProcessor { public class ConversationProcessor {
private static final Map<UUID, String> RUNNING_CONVERSATIONS = new HashMap<>(); private static final Map<UUID, String> RUNNING_CONVERSATIONS = new HashMap<>();
private final NPC npc; private final NPC npc;
private final ConversationModel conversationModel; private final ConversationModel conversationModel;
private final Player player; private final Player player;
private int conversationIndex = 0; private int conversationIndex = 0;
private long conversationIndexDelay = System.nanoTime(); private long conversationIndexDelay = System.nanoTime();
public ConversationProcessor(NPC npc, ConversationModel conversationModel, Player player) { public ConversationProcessor(NPC npc, ConversationModel conversationModel, Player player) {

@ -5,6 +5,7 @@ import org.bukkit.entity.Player;
import org.bukkit.event.Event; import org.bukkit.event.Event;
import org.bukkit.event.HandlerList; import org.bukkit.event.HandlerList;
@SuppressWarnings("unused")
public class NPCInteractEvent extends Event { public class NPCInteractEvent extends Event {
private static final HandlerList handlerList = new HandlerList(); private static final HandlerList handlerList = new HandlerList();
private final Player player; private final Player player;

@ -6,7 +6,6 @@ import net.md_5.bungee.api.ChatColor;
import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.ThreadLocalRandom;
@SuppressWarnings("deprecation")
public class RGBLine implements LineReplacer { public class RGBLine implements LineReplacer {
public String make(String string) { public String make(String string) {
String rgbString = string; String rgbString = string;

@ -4,6 +4,7 @@ import com.mojang.authlib.GameProfile;
import io.github.znetworkw.znpcservers.reflection.types.*; import io.github.znetworkw.znpcservers.reflection.types.*;
import io.github.znetworkw.znpcservers.utility.Utils; import io.github.znetworkw.znpcservers.utility.Utils;
import io.netty.channel.Channel; import io.netty.channel.Channel;
import org.bukkit.Bukkit;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import java.lang.reflect.Constructor; import java.lang.reflect.Constructor;
@ -538,22 +539,26 @@ public final class Reflections {
public static final ReflectionLazyLoader<Object> ADD_PLAYER_FIELD = new FieldReflection(new ReflectionBuilder(ReflectionPackage.PACKET) public static final ReflectionLazyLoader<Object> ADD_PLAYER_FIELD = new FieldReflection(new ReflectionBuilder(ReflectionPackage.PACKET)
.withClassName("PacketPlayOutPlayerInfo$EnumPlayerInfoAction") .withClassName("PacketPlayOutPlayerInfo$EnumPlayerInfoAction")
.withClassName("ClientboundPlayerInfoUpdatePacket$a") .withClassName("ClientboundPlayerInfoUpdatePacket$a")
.withFieldName((Utils.BUKKIT_VERSION > 16) ? "a" : "ADD_PLAYER")).asValueField(); .withFieldName((Utils.BUKKIT_VERSION > 16) ? "a" : "ADD_PLAYER")).staticValueLoader();
public static final ReflectionLazyLoader<Object> UPDATE_LISTED_FIELD = new FieldReflection(new ReflectionBuilder(ReflectionPackage.PACKET) public static final ReflectionLazyLoader<Object> UPDATE_LISTED_FIELD = new FieldReflection(new ReflectionBuilder(ReflectionPackage.PACKET)
.withClassName("ClientboundPlayerInfoUpdatePacket$a") .withClassName("ClientboundPlayerInfoUpdatePacket$a")
.withFieldName("d")).asValueField(); .withFieldName("d")).staticValueLoader();
public static final ReflectionLazyLoader<Object> REMOVE_PLAYER_FIELD = new FieldReflection(new ReflectionBuilder(ReflectionPackage.PACKET) public static final ReflectionLazyLoader<Object> REMOVE_PLAYER_FIELD = new FieldReflection(new ReflectionBuilder(ReflectionPackage.PACKET)
.withClassName("PacketPlayOutPlayerInfo$EnumPlayerInfoAction") .withClassName("PacketPlayOutPlayerInfo$EnumPlayerInfoAction")
.withClassName("ClientboundPlayerInfoUpdatePacket$a") .withClassName("ClientboundPlayerInfoUpdatePacket$a")
.withFieldName((Utils.BUKKIT_VERSION > 16) ? "e" : "REMOVE_PLAYER")).asValueField(); .withFieldName((Utils.BUKKIT_VERSION > 16) ? "e" : "REMOVE_PLAYER")).staticValueLoader();
public static final ReflectionLazyLoader<Object> DATA_WATCHER_REGISTER_FIELD = new FieldReflection(new ReflectionBuilder(ReflectionPackage.PACKET) public static final ReflectionLazyLoader<Object> DATA_WATCHER_REGISTER_FIELD = new FieldReflection(new ReflectionBuilder(ReflectionPackage.PACKET)
.withClassName(DATA_WATCHER_REGISTRY) .withClassName(DATA_WATCHER_REGISTRY)
.withFieldName("a")).asValueField(); .withFieldName("a")).staticValueLoader();
public static final ReflectionLazyLoader<Object> ENUM_TAG_VISIBILITY_NEVER_FIELD = new FieldReflection(new ReflectionBuilder(ReflectionPackage.PACKET) public static final ReflectionLazyLoader<Object> ENUM_TAG_VISIBILITY_NEVER_FIELD = new FieldReflection(new ReflectionBuilder(ReflectionPackage.PACKET)
.withClassName(ENUM_TAG_VISIBILITY) .withClassName(ENUM_TAG_VISIBILITY)
.withFieldName("b")).asValueField(); .withFieldName("b")).staticValueLoader();
public static final ReflectionLazyLoader<Object> COMMAND_MAP_FIELD = new FieldReflection(new ReflectionBuilder(ReflectionPackage.BUKKIT)
.withClassName("CraftServer")
.withFieldName("commandMap")).valueLoader(Bukkit.getServer());
} }

@ -29,21 +29,27 @@ public class FieldReflection extends ReflectionLazyLoader<Field> {
return field; return field;
} }
public AsValueField asValueField() { public FieldValueReflection staticValueLoader() {
return new AsValueField(this, possibleClassNames); return new FieldValueReflection(this, possibleClassNames, null);
} }
private static class AsValueField extends ReflectionLazyLoader<Object> { public FieldValueReflection valueLoader(Object obj) {
return new FieldValueReflection(this, possibleClassNames, obj);
}
private static class FieldValueReflection extends ReflectionLazyLoader<Object> {
private final Object obj;
private final FieldReflection fieldReflection; private final FieldReflection fieldReflection;
public AsValueField(FieldReflection fieldReflection, List<String> className) { public FieldValueReflection(FieldReflection fieldReflection, List<String> className, Object obj) {
super(className); super(className);
this.obj = obj;
this.fieldReflection = fieldReflection; this.fieldReflection = fieldReflection;
} }
protected Object load() throws IllegalAccessException, NoSuchFieldException { protected Object load() throws IllegalAccessException, NoSuchFieldException {
Field field = this.fieldReflection.load(); Field field = this.fieldReflection.get();
return field.get(null); return field.get(obj);
} }
} }
} }

@ -16,7 +16,6 @@ import java.util.concurrent.Executors;
public class SkinFetcher { public class SkinFetcher {
private static final ExecutorService SKIN_EXECUTOR_SERVICE = Executors.newCachedThreadPool(); private static final ExecutorService SKIN_EXECUTOR_SERVICE = Executors.newCachedThreadPool();
private final SkinFetcherBuilder builder; private final SkinFetcherBuilder builder;
public SkinFetcher(SkinFetcherBuilder builder) { public SkinFetcher(SkinFetcherBuilder builder) {
@ -31,32 +30,12 @@ public class SkinFetcher {
connection.setRequestMethod(this.builder.getAPIServer().getMethod()); connection.setRequestMethod(this.builder.getAPIServer().getMethod());
if (this.builder.isUrlType()) { if (this.builder.isUrlType()) {
connection.setDoOutput(true); connection.setDoOutput(true);
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
try {
outputStream.writeBytes("url=" + URLEncoder.encode(this.builder.getData(), StandardCharsets.UTF_8)); outputStream.writeBytes("url=" + URLEncoder.encode(this.builder.getData(), StandardCharsets.UTF_8));
outputStream.close();
} catch (Throwable throwable) {
try {
outputStream.close();
} catch (Throwable throwable1) {
throwable.addSuppressed(throwable1);
}
throw throwable;
} }
} }
try { try (Reader reader = new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8)) {
Reader reader = new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8);
try {
completableFuture.complete(JsonParser.parseReader(reader).getAsJsonObject()); completableFuture.complete(JsonParser.parseReader(reader).getAsJsonObject());
reader.close();
} catch (Throwable throwable) {
try {
reader.close();
} catch (Throwable throwable1) {
throwable.addSuppressed(throwable1);
}
throw throwable;
}
} finally { } finally {
connection.disconnect(); connection.disconnect();
} }

@ -35,9 +35,7 @@ public class EventService<T extends Event> {
} }
public static <T extends Event> EventService<T> addService(ZUser user, Class<T> eventClass) { public static <T extends Event> EventService<T> addService(ZUser user, Class<T> eventClass) {
if (EventService.hasService(user, eventClass)) { if (EventService.hasService(user, eventClass)) throw new IllegalStateException(eventClass.getSimpleName() + " is already register for " + user.getUUID().toString());
throw new IllegalStateException(eventClass.getSimpleName() + " is already register for " + user.getUUID().toString());
}
EventService<T> service = new EventService<>(eventClass, new ArrayList<>()); EventService<T> service = new EventService<>(eventClass, new ArrayList<>());
user.getEventServices().add(service); user.getEventServices().add(service);
user.toPlayer().closeInventory(); user.toPlayer().closeInventory();

@ -1,18 +1,17 @@
package io.github.znetworkw.znpcservers.user; package io.github.znetworkw.znpcservers.user;
import com.mojang.authlib.GameProfile; import com.mojang.authlib.GameProfile;
import io.github.znetworkw.znpcservers.reflection.Reflections;
import io.github.znetworkw.znpcservers.npc.NPC; import io.github.znetworkw.znpcservers.npc.NPC;
import io.github.znetworkw.znpcservers.npc.NPCAction; import io.github.znetworkw.znpcservers.npc.NPCAction;
import io.github.znetworkw.znpcservers.npc.event.ClickType; import io.github.znetworkw.znpcservers.npc.event.ClickType;
import io.github.znetworkw.znpcservers.npc.event.NPCInteractEvent; import io.github.znetworkw.znpcservers.npc.event.NPCInteractEvent;
import io.github.znetworkw.znpcservers.reflection.Reflections;
import io.netty.channel.Channel; import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder; import io.netty.handler.codec.MessageToMessageDecoder;
import lol.pyr.znpcsplus.ZNPCsPlus; import lol.pyr.znpcsplus.ZNPCsPlus;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitRunnable;
@ -72,9 +71,9 @@ public class ZUser {
} }
if (tries-- > 0) return; if (tries-- > 0) return;
cancel(); cancel();
player.kick(Component.text("[ZNPCsPlus]", NamedTextColor.RED).appendNewline() player.kickPlayer(ChatColor.RED + "[ZNPCsPlus]\n" +
.append(Component.text("Couldn't inject interaction detector to channel", NamedTextColor.WHITE)).appendNewline() ChatColor.WHITE + "Couldn't inject interaction detector to channel\n" +
.append(Component.text("Please report this at https://github.com/Pyrbu/ZNPCsPlus", NamedTextColor.WHITE))); ChatColor.WHITE + "Please report this at https://github.com/Pyrbu/ZNPCsPlus");
ZNPCsPlus.LOGGER.severe("Couldn't inject interaction detector to channel for player " + player.getName() + " (" + player.getUniqueId() + ")"); ZNPCsPlus.LOGGER.severe("Couldn't inject interaction detector to channel for player " + player.getName() + " (" + player.getUniqueId() + ")");
ex.printStackTrace(); ex.printStackTrace();
} }

@ -12,7 +12,6 @@ import org.bukkit.entity.Player;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.ThreadLocalRandom;
@SuppressWarnings("deprecation")
public final class Utils { public final class Utils {
public static final int BUKKIT_VERSION; public static final int BUKKIT_VERSION;
public static boolean PLACEHOLDER_SUPPORT = Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI"); public static boolean PLACEHOLDER_SUPPORT = Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI");
@ -50,7 +49,7 @@ public final class Utils {
} }
public static void sendTitle(Player player, String title, String subTitle) { public static void sendTitle(Player player, String title, String subTitle) {
player.sendTitle(toColor(title), toColor(subTitle)); player.sendTitle(toColor(title), toColor(subTitle), 1, 3, 1);
} }
public static void setValue(Object fieldInstance, String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException { public static void setValue(Object fieldInstance, String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException {

@ -7,9 +7,7 @@ import org.bukkit.inventory.Inventory;
public class ZInventory { public class ZInventory {
private final Player player; private final Player player;
private ZInventoryPage page; private ZInventoryPage page;
private Inventory inventory; private Inventory inventory;
public ZInventory(Player player) { public ZInventory(Player player) {
@ -32,12 +30,9 @@ public class ZInventory {
this.page = page; this.page = page;
} }
@SuppressWarnings("deprecation")
public Inventory build(ZInventoryPage page) { public Inventory build(ZInventoryPage page) {
if (page == null) if (page == null) throw new IllegalStateException("page is null");
throw new IllegalStateException("page is null"); if (page.getRows() / 9 > 6) throw new IllegalArgumentException(String.format("Unexpected rows size. Has %d, max %d", page.getRows(), 6));
if (page.getRows() / 9 > 6)
throw new IllegalArgumentException(String.format("Unexpected rows size. Has %d, max %d", page.getRows(), 6));
setCurrentPage(page); setCurrentPage(page);
page.getInventoryItems().removeIf(zInventoryItem -> !zInventoryItem.isDefault()); page.getInventoryItems().removeIf(zInventoryItem -> !zInventoryItem.isDefault());
page.update(); page.update();

@ -4,11 +4,8 @@ import org.bukkit.inventory.ItemStack;
public class ZInventoryItem { public class ZInventoryItem {
private final ItemStack itemStack; private final ItemStack itemStack;
private final int slot; private final int slot;
private final boolean isDefault; private final boolean isDefault;
private final ZInventoryCallback clickCallback; private final ZInventoryCallback clickCallback;
public ZInventoryItem(ItemStack itemStack, int slot, boolean isDefault, ZInventoryCallback zInventoryCallback) { public ZInventoryItem(ItemStack itemStack, int slot, boolean isDefault, ZInventoryCallback zInventoryCallback) {

@ -9,14 +9,10 @@ import org.bukkit.inventory.ItemStack;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@SuppressWarnings("deprecation")
public abstract class ZInventoryPage { public abstract class ZInventoryPage {
private final ZInventory zInventory; private final ZInventory zInventory;
private final String pageName; private final String pageName;
private final int rows; private final int rows;
private final List<ZInventoryItem> inventoryItems; private final List<ZInventoryItem> inventoryItems;
public ZInventoryPage(ZInventory zInventory, String inventoryName, int rows) { public ZInventoryPage(ZInventory zInventory, String inventoryName, int rows) {

@ -9,7 +9,6 @@ import java.util.Arrays;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.StreamSupport; import java.util.stream.StreamSupport;
@SuppressWarnings("deprecation")
public class ItemStackBuilder { public class ItemStackBuilder {
private final ItemStack itemStack; private final ItemStack itemStack;
@ -21,8 +20,7 @@ public class ItemStackBuilder {
} }
public static ItemStackBuilder forMaterial(Material material) { public static ItemStackBuilder forMaterial(Material material) {
if (material == null || material == Material.AIR) if (material == null || material == Material.AIR) throw new IllegalStateException("can't create builder for a NULL material.");
throw new IllegalStateException("can't create builder for a NULL material.");
return new ItemStackBuilder(new ItemStack(material, 1)); return new ItemStackBuilder(new ItemStack(material, 1));
} }
@ -32,8 +30,7 @@ public class ItemStackBuilder {
} }
public ItemStackBuilder setLore(Iterable<String> lore) { public ItemStackBuilder setLore(Iterable<String> lore) {
this.itemMeta.setLore(StreamSupport.stream(lore.spliterator(), false) this.itemMeta.setLore(StreamSupport.stream(lore.spliterator(), false).map(Utils::toColor).collect(Collectors.toList()));
.map(Utils::toColor).collect(Collectors.toList()));
this.itemStack.setItemMeta(this.itemMeta); this.itemStack.setItemMeta(this.itemMeta);
return this; return this;
} }
@ -42,11 +39,6 @@ public class ItemStackBuilder {
return setLore(Arrays.asList(lore)); return setLore(Arrays.asList(lore));
} }
public ItemStackBuilder setAmount(int amount) {
this.itemStack.setAmount(amount);
return this;
}
public ItemStack build() { public ItemStack build() {
this.itemStack.setItemMeta(this.itemMeta); this.itemStack.setItemMeta(this.itemMeta);
return this.itemStack; return this.itemStack;

@ -16,63 +16,19 @@ public class ItemStackSerializer implements JsonSerializer<ItemStack>, JsonDeser
private static final ItemStack DEFAULT = new ItemStack(Material.AIR); private static final ItemStack DEFAULT = new ItemStack(Material.AIR);
public ItemStack deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { public ItemStack deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
try {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(Base64.getDecoder().decode(json.getAsString())); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(Base64.getDecoder().decode(json.getAsString()));
try { try (BukkitObjectInputStream bukkitObjectOutputStream = new BukkitObjectInputStream(byteArrayInputStream)) {
BukkitObjectInputStream bukkitObjectOutputStream = new BukkitObjectInputStream(byteArrayInputStream); return (ItemStack) bukkitObjectOutputStream.readObject();
try {
ItemStack itemStack = (ItemStack) bukkitObjectOutputStream.readObject();
bukkitObjectOutputStream.close();
byteArrayInputStream.close();
return itemStack;
} catch (Throwable throwable) {
try {
bukkitObjectOutputStream.close();
} catch (Throwable throwable1) {
throwable.addSuppressed(throwable1);
}
throw throwable;
}
} catch (Throwable throwable) {
try {
byteArrayInputStream.close();
} catch (Throwable throwable1) {
throwable.addSuppressed(throwable1);
}
throw throwable;
}
} catch (IOException | ClassNotFoundException e) { } catch (IOException | ClassNotFoundException e) {
return DEFAULT; return DEFAULT;
} }
} }
public JsonElement serialize(ItemStack src, Type typeOfSrc, JsonSerializationContext context) { public JsonElement serialize(ItemStack src, Type typeOfSrc, JsonSerializationContext context) {
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try { try (BukkitObjectOutputStream bukkitObjectOutputStream = new BukkitObjectOutputStream(byteArrayOutputStream)) {
BukkitObjectOutputStream bukkitObjectOutputStream = new BukkitObjectOutputStream(byteArrayOutputStream);
try {
bukkitObjectOutputStream.writeObject(src); bukkitObjectOutputStream.writeObject(src);
JsonPrimitive jsonPrimitive = new JsonPrimitive(Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray())); return new JsonPrimitive(Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray()));
bukkitObjectOutputStream.close();
byteArrayOutputStream.close();
return jsonPrimitive;
} catch (Throwable throwable) {
try {
bukkitObjectOutputStream.close();
} catch (Throwable throwable1) {
throwable.addSuppressed(throwable1);
}
throw throwable;
}
} catch (Throwable throwable) {
try {
byteArrayOutputStream.close();
} catch (Throwable throwable1) {
throwable.addSuppressed(throwable1);
}
throw throwable;
}
} catch (IOException e) { } catch (IOException e) {
throw new JsonParseException("Cannot serialize itemstack", e); throw new JsonParseException("Cannot serialize itemstack", e);
} }

@ -1,5 +1,6 @@
package io.github.znetworkw.znpcservers.utility.location; package io.github.znetworkw.znpcservers.utility.location;
import com.google.common.base.Preconditions;
import com.google.gson.*; import com.google.gson.*;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Location; import org.bukkit.Location;
@ -9,19 +10,12 @@ import java.lang.reflect.Type;
public class ZLocation { public class ZLocation {
public static final ZLocationSerializer SERIALIZER = new ZLocationSerializer(); public static final ZLocationSerializer SERIALIZER = new ZLocationSerializer();
private final String worldName; private final String worldName;
private final double x; private final double x;
private final double y; private final double y;
private final double z; private final double z;
private final float yaw; private final float yaw;
private final float pitch; private final float pitch;
private Location bukkitLocation; private Location bukkitLocation;
public ZLocation(String worldName, double x, double y, double z, float yaw, float pitch) { public ZLocation(String worldName, double x, double y, double z, float yaw, float pitch) {
@ -34,7 +28,7 @@ public class ZLocation {
} }
public ZLocation(Location location) { public ZLocation(Location location) {
this(location.getWorld().getName(), location this(Preconditions.checkNotNull(location.getWorld()).getName(), location
.getX(), location .getX(), location
.getY(), location .getY(), location
.getZ(), location .getZ(), location

@ -17,10 +17,12 @@ import io.github.znetworkw.znpcservers.npc.task.NPCVisibilityTask;
import io.github.znetworkw.znpcservers.user.ZUser; import io.github.znetworkw.znpcservers.user.ZUser;
import io.github.znetworkw.znpcservers.utility.BungeeUtils; import io.github.znetworkw.znpcservers.utility.BungeeUtils;
import io.github.znetworkw.znpcservers.utility.SchedulerUtils; import io.github.znetworkw.znpcservers.utility.SchedulerUtils;
import io.github.znetworkw.znpcservers.utility.Utils;
import io.github.znetworkw.znpcservers.utility.itemstack.ItemStackSerializer; import io.github.znetworkw.znpcservers.utility.itemstack.ItemStackSerializer;
import io.github.znetworkw.znpcservers.utility.location.ZLocation; import io.github.znetworkw.znpcservers.utility.location.ZLocation;
import lol.pyr.znpcsplus.updater.UpdateChecker; import lol.pyr.znpcsplus.updater.UpdateChecker;
import lol.pyr.znpcsplus.updater.UpdateNotificationListener; import lol.pyr.znpcsplus.updater.UpdateNotificationListener;
import net.kyori.adventure.platform.bukkit.BukkitAudiences;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.bstats.bukkit.Metrics; import org.bstats.bukkit.Metrics;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
@ -47,6 +49,7 @@ public class ZNPCsPlus extends JavaPlugin {
private static final int PLUGIN_ID = 18244; private static final int PLUGIN_ID = 18244;
public static SchedulerUtils SCHEDULER; public static SchedulerUtils SCHEDULER;
public static BungeeUtils BUNGEE_UTILS; public static BungeeUtils BUNGEE_UTILS;
public static BukkitAudiences ADVENTURE;
private boolean enabled = false; private boolean enabled = false;
@ -73,18 +76,21 @@ public class ZNPCsPlus extends JavaPlugin {
PATH_FOLDER = new File(PLUGIN_FOLDER, "paths"); PATH_FOLDER = new File(PLUGIN_FOLDER, "paths");
} }
@SuppressWarnings("deprecation") private void log(Logger logger, String str) {
logger.info(Utils.versionNewer(12) ? str : ChatColor.stripColor(str).replace("\u2764 ", "<3"));
}
@Override @Override
public void onEnable() { public void onEnable() {
Logger serverLogger = getServer().getLogger(); Logger serverLogger = getServer().getLogger();
serverLogger.info(ChatColor.YELLOW + " ___ __ __ __"); log(serverLogger, ChatColor.YELLOW + " ___ __ __ __");
serverLogger.info(ChatColor.YELLOW + " _/ |\\ | |__) | (__` " + ChatColor.GOLD + "__|__ " + ChatColor.YELLOW + getDescription().getName() + " " + ChatColor.GOLD + "v" + getDescription().getVersion()); log(serverLogger, ChatColor.YELLOW + " _/ |\\ | |__) | (__` " + ChatColor.GOLD + "__|__ " + ChatColor.YELLOW + getDescription().getName() + " " + ChatColor.GOLD + "v" + getDescription().getVersion());
serverLogger.info(ChatColor.YELLOW + " /__ | \\| | |__ .__) " + ChatColor.GOLD + " | " + ChatColor.GRAY + "Maintained with " + ChatColor.RED + "\u2764 " + ChatColor.GRAY + " by Pyr#6969"); log(serverLogger, ChatColor.YELLOW + " /__ | \\| | |__ .__) " + ChatColor.GOLD + " | " + ChatColor.GRAY + "Maintained with " + ChatColor.RED + "\u2764 " + ChatColor.GRAY + " by Pyr#6969");
serverLogger.info(""); log(serverLogger, "");
if (Bukkit.getPluginManager().isPluginEnabled("ServersNPC")) { if (Bukkit.getPluginManager().isPluginEnabled("ServersNPC")) {
serverLogger.info(ChatColor.DARK_RED + " * Detected old version of ZNPCs! Disabling the plugin."); log(serverLogger, ChatColor.DARK_RED + " * Detected old version of ZNPCs! Disabling the plugin.");
serverLogger.info(""); log(serverLogger, "");
Bukkit.getPluginManager().disablePlugin(this); Bukkit.getPluginManager().disablePlugin(this);
return; return;
} }
@ -92,21 +98,24 @@ public class ZNPCsPlus extends JavaPlugin {
File oldFolder = new File(PLUGIN_FOLDER.getParent(), "ServersNPC"); File oldFolder = new File(PLUGIN_FOLDER.getParent(), "ServersNPC");
if (!PLUGIN_FOLDER.exists() && oldFolder.exists()) { if (!PLUGIN_FOLDER.exists() && oldFolder.exists()) {
serverLogger.info(ChatColor.WHITE + " * Converting old ZNPCs files..."); log(serverLogger, ChatColor.WHITE + " * Converting old ZNPCs files...");
try { try {
FileUtils.moveDirectory(oldFolder, PLUGIN_FOLDER); FileUtils.moveDirectory(oldFolder, PLUGIN_FOLDER);
} catch (IOException e) { } catch (IOException e) {
serverLogger.info(ChatColor.RED + " * Failed to convert old ZNPCs files" + (e.getMessage() == null ? "" : " due to " + e.getMessage())); log(serverLogger, ChatColor.RED + " * Failed to convert old ZNPCs files" + (e.getMessage() == null ? "" : " due to " + e.getMessage()));
} }
} }
log(serverLogger, ChatColor.WHITE + " * Initializing adventure...");
ADVENTURE = BukkitAudiences.create(this);
PLUGIN_FOLDER.mkdirs(); PLUGIN_FOLDER.mkdirs();
PATH_FOLDER.mkdirs(); PATH_FOLDER.mkdirs();
serverLogger.info(ChatColor.WHITE + " * Loading paths..."); log(serverLogger, ChatColor.WHITE + " * Loading paths...");
loadAllPaths(); loadAllPaths();
serverLogger.info(ChatColor.WHITE + " * Registering components..."); log(serverLogger, ChatColor.WHITE + " * Registering components...");
getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord"); getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");
new Metrics(this, PLUGIN_ID); new Metrics(this, PLUGIN_ID);
new DefaultCommand(); new DefaultCommand();
@ -114,7 +123,7 @@ public class ZNPCsPlus extends JavaPlugin {
BUNGEE_UTILS = new BungeeUtils(this); BUNGEE_UTILS = new BungeeUtils(this);
Bukkit.getOnlinePlayers().forEach(ZUser::find); Bukkit.getOnlinePlayers().forEach(ZUser::find);
serverLogger.info(ChatColor.WHITE + " * Starting tasks..."); log(serverLogger, ChatColor.WHITE + " * Starting tasks...");
new NPCPositionTask(this); new NPCPositionTask(this);
new NPCVisibilityTask(this); new NPCVisibilityTask(this);
new NPCSaveTask(this, ConfigurationConstants.SAVE_DELAY); new NPCSaveTask(this, ConfigurationConstants.SAVE_DELAY);
@ -123,8 +132,8 @@ public class ZNPCsPlus extends JavaPlugin {
if (ConfigurationConstants.CHECK_FOR_UPDATES) new UpdateNotificationListener(this, new UpdateChecker(this)); if (ConfigurationConstants.CHECK_FOR_UPDATES) new UpdateNotificationListener(this, new UpdateChecker(this));
enabled = true; enabled = true;
serverLogger.info(ChatColor.WHITE + " * Loading complete! (" + (System.currentTimeMillis() - before) + "ms)"); log(serverLogger, ChatColor.WHITE + " * Loading complete! (" + (System.currentTimeMillis() - before) + "ms)");
serverLogger.info(""); log(serverLogger, "");
} }
@Override @Override
@ -132,6 +141,8 @@ public class ZNPCsPlus extends JavaPlugin {
if (!enabled) return; if (!enabled) return;
Configuration.SAVE_CONFIGURATIONS.forEach(Configuration::save); Configuration.SAVE_CONFIGURATIONS.forEach(Configuration::save);
Bukkit.getOnlinePlayers().forEach(ZUser::unregister); Bukkit.getOnlinePlayers().forEach(ZUser::unregister);
ADVENTURE.close();
ADVENTURE = null;
} }
public void loadAllPaths() { public void loadAllPaths() {

@ -7,7 +7,6 @@ import org.bukkit.scheduler.BukkitRunnable;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@SuppressWarnings("deprecation")
public class UpdateChecker extends BukkitRunnable { public class UpdateChecker extends BukkitRunnable {
private final static SpigotResourcesAPI api = new SpigotResourcesAPI(1, TimeUnit.MINUTES); private final static SpigotResourcesAPI api = new SpigotResourcesAPI(1, TimeUnit.MINUTES);
public final static int RESOURCE_ID = 109380; public final static int RESOURCE_ID = 109380;

@ -9,7 +9,6 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerJoinEvent;
@SuppressWarnings("deprecation")
public class UpdateNotificationListener implements Listener { public class UpdateNotificationListener implements Listener {
private final ZNPCsPlus plugin; private final ZNPCsPlus plugin;
private final UpdateChecker updateChecker; private final UpdateChecker updateChecker;
@ -26,7 +25,8 @@ public class UpdateNotificationListener implements Listener {
if (updateChecker.getStatus() != UpdateChecker.Status.UPDATE_NEEDED) return; if (updateChecker.getStatus() != UpdateChecker.Status.UPDATE_NEEDED) return;
Bukkit.getScheduler().runTaskLater(plugin, () -> { Bukkit.getScheduler().runTaskLater(plugin, () -> {
if (!event.getPlayer().isOnline()) return; if (!event.getPlayer().isOnline()) return;
event.getPlayer().sendMessage(Component.text(plugin.getDescription().getName() + " v" + updateChecker.getLatestVersion() + " is available now!", NamedTextColor.GOLD).appendNewline() ZNPCsPlus.ADVENTURE.player(event.getPlayer())
.sendMessage(Component.text(plugin.getDescription().getName() + " v" + updateChecker.getLatestVersion() + " is available now!", NamedTextColor.GOLD).appendNewline()
.append(Component.text("Click this message to open the Spigot page (CLICK)", NamedTextColor.YELLOW)).clickEvent(ClickEvent.openUrl(UpdateChecker.DOWNLOAD_LINK))); .append(Component.text("Click this message to open the Spigot page (CLICK)", NamedTextColor.YELLOW)).clickEvent(ClickEvent.openUrl(UpdateChecker.DOWNLOAD_LINK)));
}, 100L); }, 100L);
} }