getFrom() {
+ return from;
+ }
+
+ public String getTo() {
+ return to;
+ }
+
+ public String replace(String origin) {
+ for (String from : from) {
+ origin = origin.replace("/" + from + "/", "/" + to + "/");
+ }
+ return origin;
+ }
+}
diff --git a/src/main/java/me/skymc/taboolib/damage/DamageUtils.java b/src/main/java/me/skymc/taboolib/damage/DamageUtils.java
index a614445..1ffdd99 100644
--- a/src/main/java/me/skymc/taboolib/damage/DamageUtils.java
+++ b/src/main/java/me/skymc/taboolib/damage/DamageUtils.java
@@ -1,58 +1,44 @@
package me.skymc.taboolib.damage;
-import me.skymc.taboolib.TabooLib;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
+import org.bukkit.entity.Projectile;
+import org.bukkit.event.entity.EntityDamageByEntityEvent;
-import java.lang.reflect.InvocationTargetException;
-
+/**
+ * @author sky
+ */
public class DamageUtils {
+ public static Player getAttackerInDamageEvent(EntityDamageByEntityEvent e) {
+ if (e.getDamager() instanceof Player) {
+ return (Player) e.getDamager();
+ } else if (e.getDamager() instanceof Projectile && ((Projectile) e.getDamager()).getShooter() instanceof Player) {
+ return (Player) ((Projectile) e.getDamager()).getShooter();
+ } else {
+ return null;
+ }
+ }
+
+ // *********************************
+ //
+ // Deprecated
+ //
+ // *********************************
+
+ @Deprecated
public static void damage(Player player, LivingEntity victim, double damage) {
dmg(player, victim, damage);
}
+ @Deprecated
public static void damage(Player player, Entity victim, double damage) {
- if (victim instanceof LivingEntity) {
- dmg(player, (LivingEntity) victim, damage);
- }
+ dmg(player, (LivingEntity) victim, damage);
}
- public static void dmg(LivingEntity paramLivingEntity1, LivingEntity paramLivingEntity2, double paramDouble) {
- if ((paramLivingEntity2.hasMetadata("NPC")) || (paramLivingEntity1.hasMetadata("NPC"))) {
- return;
- }
-
- Object localObject1;
- try {
- localObject1 = paramLivingEntity1.getClass().getDeclaredMethod("getHandle").invoke(paramLivingEntity1);
- } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException localIllegalAccessException1) {
- return;
- }
-
- Object localObject2;
- try {
- localObject2 = paramLivingEntity2.getClass().getDeclaredMethod("getHandle").invoke(paramLivingEntity2);
- } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException localIllegalAccessException2) {
- return;
- }
-
- try {
- Class> DamageSource = nmsClass("DamageSource");
- Object localObject3 = DamageSource.getDeclaredMethod("playerAttack", nmsClass("EntityHuman")).invoke(DamageSource, localObject1);
-
- localObject2.getClass().getDeclaredMethod("damageEntity", new Class[]{DamageSource, Float.TYPE}).invoke(localObject2, localObject3, (float) paramDouble);
- } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException ignored) {
- }
- }
-
- private static Class> nmsClass(String paramString) {
- String str = "net.minecraft.server." + TabooLib.getVersion() + "." + paramString;
- try {
- return Class.forName(str);
- } catch (ClassNotFoundException e) {
- return null;
- }
+ @Deprecated
+ public static void dmg(LivingEntity attacker, LivingEntity victim, double damage) {
+ attacker.damage(damage, victim);
}
}
diff --git a/src/main/java/me/skymc/taboolib/damage/GetDamager.java b/src/main/java/me/skymc/taboolib/damage/GetDamager.java
index aee2773..cb171d3 100644
--- a/src/main/java/me/skymc/taboolib/damage/GetDamager.java
+++ b/src/main/java/me/skymc/taboolib/damage/GetDamager.java
@@ -4,19 +4,11 @@ import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
+@Deprecated
public class GetDamager {
public static Player get(EntityDamageByEntityEvent e) {
- Player p = null;
- if (e.getDamager() instanceof Projectile) {
- Projectile arrow = (Projectile) e.getDamager();
- if (arrow.getShooter() instanceof Player) {
- p = (Player) arrow.getShooter();
- }
- } else if (e.getDamager() instanceof Player) {
- p = (Player) e.getDamager();
- }
- return p;
+ return DamageUtils.getAttackerInDamageEvent(e);
}
}
diff --git a/src/main/java/me/skymc/taboolib/damage/GetKiller.java b/src/main/java/me/skymc/taboolib/damage/GetKiller.java
index 1206c85..0fcc95b 100644
--- a/src/main/java/me/skymc/taboolib/damage/GetKiller.java
+++ b/src/main/java/me/skymc/taboolib/damage/GetKiller.java
@@ -1,22 +1,13 @@
package me.skymc.taboolib.damage;
import org.bukkit.entity.Player;
-import org.bukkit.entity.Projectile;
import org.bukkit.event.entity.EntityDeathEvent;
+@Deprecated
public class GetKiller {
public static Player get(EntityDeathEvent e) {
- Player p = null;
- if (e.getEntity().getKiller() instanceof Projectile) {
- Projectile arrow = (Projectile) e.getEntity().getKiller();
- if (arrow.getShooter() instanceof Player) {
- p = (Player) arrow.getShooter();
- }
- } else if (e.getEntity().getKiller() != null) {
- p = e.getEntity().getKiller();
- }
- return p;
+ return e.getEntity().getKiller();
}
}
diff --git a/src/main/java/me/skymc/taboolib/entity/VectorUtils.java b/src/main/java/me/skymc/taboolib/entity/VectorUtils.java
index 2428757..e174206 100644
--- a/src/main/java/me/skymc/taboolib/entity/VectorUtils.java
+++ b/src/main/java/me/skymc/taboolib/entity/VectorUtils.java
@@ -18,7 +18,7 @@ public class VectorUtils {
/**
* 物品丢弃
- *
+ *
* 常用参数:
* itemDrop(player, itemStack, 0.2, 0.5)
*
@@ -57,7 +57,7 @@ public class VectorUtils {
/**
* 生物抛射
- *
+ *
* 常用参数:
* entityPush(entity, location, 15)
*
@@ -69,17 +69,17 @@ public class VectorUtils {
Location from = entity.getLocation();
Vector test = to.clone().subtract(from).toVector();
- Double elevation = test.getY();
+ double elevation = test.getY();
Double launchAngle = calculateLaunchAngle(from, to, velocity, elevation, 20.0D);
- Double distance = Math.sqrt(Math.pow(test.getX(), 2.0D) + Math.pow(test.getZ(), 2.0D));
+ double distance = Math.sqrt(Math.pow(test.getX(), 2.0D) + Math.pow(test.getZ(), 2.0D));
if (distance == 0.0D) {
return;
}
if (launchAngle == null) {
launchAngle = Math.atan((40.0D * elevation + Math.pow(velocity, 2.0D)) / (40.0D * elevation + 2.0D * Math.pow(velocity, 2.0D)));
}
- Double hangTime = calculateHangTime(launchAngle, velocity, elevation, 20.0D);
+ double hangTime = calculateHangTime(launchAngle, velocity, elevation, 20.0D);
test.setY(Math.tan(launchAngle) * distance);
test = normalizeVector(test);
@@ -113,7 +113,7 @@ public class VectorUtils {
private static Double calculateLaunchAngle(Location from, Location to, double v, double elevation, double g) {
Vector vector = from.clone().subtract(to).toVector();
- Double distance = Math.sqrt(Math.pow(vector.getX(), 2.0D) + Math.pow(vector.getZ(), 2.0D));
+ double distance = Math.sqrt(Math.pow(vector.getX(), 2.0D) + Math.pow(vector.getZ(), 2.0D));
double v2 = Math.pow(v, 2.0D);
double v4 = Math.pow(v, 4.0D);
double check = g * (g * Math.pow(distance, 2.0D) + 2.0D * elevation * v2);
diff --git a/src/main/java/me/skymc/taboolib/events/DefaultEvent2.java b/src/main/java/me/skymc/taboolib/events/DefaultEvent2.java
deleted file mode 100644
index def7099..0000000
--- a/src/main/java/me/skymc/taboolib/events/DefaultEvent2.java
+++ /dev/null
@@ -1,53 +0,0 @@
-package me.skymc.taboolib.events;
-
-import org.bukkit.entity.Player;
-import org.bukkit.event.Cancellable;
-import org.bukkit.event.HandlerList;
-import org.bukkit.event.player.PlayerEvent;
-
-public class DefaultEvent2 extends PlayerEvent {
-
- private static final HandlerList handlers;
-
- static {
- handlers = new HandlerList();
- }
-
- private DefaultEvent2(final Player who) {
- super(who);
- }
-
- public static HandlerList getHandlerList() {
- return DefaultEvent2.handlers;
- }
-
- @Override
- public HandlerList getHandlers() {
- return DefaultEvent2.handlers;
- }
-
- public static class Pre extends DefaultEvent2 implements Cancellable {
- private boolean cancelled;
-
- public Pre(Player who) {
- super(who);
- this.cancelled = false;
- }
-
- @Override
- public boolean isCancelled() {
- return this.cancelled;
- }
-
- @Override
- public void setCancelled(final boolean cancelled) {
- this.cancelled = cancelled;
- }
- }
-
- public static class Post extends DefaultEvent2 {
- public Post(Player who) {
- super(who);
- }
- }
-}
diff --git a/src/main/java/me/skymc/taboolib/fileutils/FileUtils.java b/src/main/java/me/skymc/taboolib/fileutils/FileUtils.java
index 57b5046..861223c 100644
--- a/src/main/java/me/skymc/taboolib/fileutils/FileUtils.java
+++ b/src/main/java/me/skymc/taboolib/fileutils/FileUtils.java
@@ -1,13 +1,15 @@
package me.skymc.taboolib.fileutils;
import ch.njol.util.Closeable;
+import com.ilummc.eagletdl.EagletTask;
+import com.ilummc.eagletdl.ProgressEvent;
+import com.ilummc.tlib.resources.TLocale;
import com.ilummc.tlib.util.IO;
import me.skymc.taboolib.Main;
import org.apache.commons.io.IOUtils;
import org.bukkit.plugin.Plugin;
import java.io.*;
-import java.net.HttpURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
@@ -133,13 +135,9 @@ public class FileUtils {
public static InputStream getResource(Plugin plugin, String filename) {
try {
URL url = plugin.getClass().getClassLoader().getResource(filename);
- if (url == null) {
- return null;
- } else {
- URLConnection connection = url.openConnection();
- connection.setUseCaches(false);
- return connection.getInputStream();
- }
+ URLConnection connection = url.openConnection();
+ connection.setUseCaches(false);
+ return connection.getInputStream();
} catch (IOException ignored) {
return null;
}
@@ -409,35 +407,38 @@ public class FileUtils {
/**
* 下载文件
*
- * @param downloadURL 下载地址
- * @param file 保存位置
+ * @param url 下载地址
+ * @param file 下载位置
+ * @param async 是否异步
*/
- public static void download(String downloadURL, File file) {
- HttpURLConnection conn = null;
- InputStream inputStream = null;
- FileOutputStream fos = null;
- try {
- URL url = new URL(downloadURL);
- conn = (HttpURLConnection) url.openConnection();
- conn.setConnectTimeout(5 * 1000);
- conn.setRequestProperty("User-Agent", "Mozilla/31.0 (compatible; MSIE 10.0; Windows NT; DigExt)");
-
- inputStream = conn.getInputStream();
- byte[] data = read(inputStream);
-
- fos = new FileOutputStream(createNewFile(file));
- fos.write(data);
- } catch (Exception ignored) {
- } finally {
- IOUtils.close(conn);
- IOUtils.closeQuietly(fos);
- IOUtils.closeQuietly(inputStream);
+ public static void download(String url, File file, boolean async) {
+ EagletTask eagletTask = new EagletTask()
+ .url(url)
+ .file(file)
+ .setThreads(8)
+ .setOnError(event -> {
+ })
+ .setOnConnected(event -> TLocale.Logger.info("UTIL.DOWNLOAD-CONNECTED", file.getName(), ProgressEvent.format(event.getContentLength())))
+ .setOnProgress(event -> TLocale.Logger.info("UTIL.DOWNLOAD-PROGRESS", event.getSpeedFormatted(), event.getPercentageFormatted()))
+ .setOnComplete(event -> {
+ if (event.isSuccess()) {
+ TLocale.Logger.info("UTIL.DOWNLOAD-SUCCESS", file.getName());
+ } else {
+ TLocale.Logger.error("UTIL.DOWNLOAD-FAILED", file.getName());
+ }
+ }).start();
+ if (!async) {
+ eagletTask.waitUntil();
}
}
+ public static void download(String url, File file) {
+ download(url, file, false);
+ }
+
@Deprecated
- public static void download(String downloadURL, String filename, File saveDir) {
- download(downloadURL, new File(saveDir, filename));
+ public static void download(String url, String filename, File saveDir) {
+ download(url, new File(saveDir, filename));
}
@Deprecated
diff --git a/src/main/java/me/skymc/taboolib/inventory/ItemUtils.java b/src/main/java/me/skymc/taboolib/inventory/ItemUtils.java
index 2e38d61..5274c5a 100644
--- a/src/main/java/me/skymc/taboolib/inventory/ItemUtils.java
+++ b/src/main/java/me/skymc/taboolib/inventory/ItemUtils.java
@@ -4,13 +4,13 @@ import com.ilummc.tlib.resources.TLocale;
import me.clip.placeholderapi.PlaceholderAPI;
import me.skymc.taboolib.Main;
import me.skymc.taboolib.TabooLib;
+import me.skymc.taboolib.common.configuration.TConfiguration;
import me.skymc.taboolib.fileutils.ConfigUtils;
import me.skymc.taboolib.itemnbtapi.NBTItem;
import me.skymc.taboolib.itemnbtapi.NBTList;
import me.skymc.taboolib.itemnbtapi.NBTListCompound;
import me.skymc.taboolib.itemnbtapi.NBTType;
import me.skymc.taboolib.other.NumberUtils;
-import me.skymc.taboolib.string.Language;
import org.bukkit.Color;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
@@ -39,74 +39,59 @@ import java.util.stream.IntStream;
*/
public class ItemUtils {
- private static FileConfiguration itemdir = null;
-
- private static FileConfiguration itemCache = null;
-
private static File finalItemsFolder;
-
- private static LinkedHashMap itemlib = new LinkedHashMap<>();
-
+ private static FileConfiguration itemDir;
+ private static FileConfiguration itemCache;
+ private static TConfiguration itemName;
+ private static LinkedHashMap itemLib = new LinkedHashMap<>();
private static LinkedHashMap itemCaches = new LinkedHashMap<>();
-
private static LinkedHashMap itemCachesFinal = new LinkedHashMap<>();
- public static FileConfiguration getItemdir() {
- return itemdir;
- }
-
- public static FileConfiguration getItemCache() {
- return itemCache;
- }
-
- public static File getFinalItemsFolder() {
- return finalItemsFolder;
- }
-
- public static LinkedHashMap getItemlib() {
- return itemlib;
- }
-
- public static LinkedHashMap getItemCaches() {
- return itemCaches;
- }
-
- public static LinkedHashMap getItemCachesFinal() {
- return itemCachesFinal;
- }
-
- /**
- * 获取物品缓存
- * 检测顺序:
- * 1. 固定物品库
- * 2. 动态物品库
- *
- * @param name 物品名称
- * @return
- */
- public static ItemStack getCacheItem(String name) {
- // 检测固定物品库是否存在该物品
- if (itemCachesFinal.containsKey(name)) {
- return itemCachesFinal.get(name);
- }
- // 返回动态物品库
- return itemCaches.get(name);
- }
-
- public static boolean isExists(String name) {
- return itemCachesFinal.containsKey(name) || itemCaches.containsKey(name);
- }
-
- public static void LoadLib() {
+ public static void init() {
try {
+ reloadItemDir();
reloadItemName();
reloadItemCache();
- itemdir = YamlConfiguration.loadConfiguration(new File(Main.getInst().getConfig().getString("DATAURL.ITEMDIR")));
} catch (Exception e) {
TLocale.Logger.error("ITEM-UTILS.FAIL-LOAD-ITEMS", e.toString());
}
}
+ public static void reloadItemDir() {
+ File file = new File(Main.getInst().getConfig().getString("DATAURL.ITEMDIR"));
+ if (file.exists()) {
+ itemDir = YamlConfiguration.loadConfiguration(file);
+ }
+ }
+
+ public static void reloadItemName() {
+ itemName = TConfiguration.createInResource(Main.getInst(), "Language/ITEM_NAME.yml");
+ itemName.listener(() -> {
+ itemName.getConfigurationSection("").getKeys(false).forEach(a -> itemLib.put(a, itemName.getString(a)));
+ TLocale.Logger.info("ITEM-UTILS.SUCCESS-LOAD-NAMES", String.valueOf(itemLib.size()));
+ }).runListener();
+ }
+
+ public static void reloadItemCache() {
+ itemCaches.clear();
+ itemCachesFinal.clear();
+ loadItemsFile(getItemCacheFile(), false);
+ finalItemsFolder = new File(Main.getInst().getDataFolder(), "FinalItems");
+ if (!finalItemsFolder.exists()) {
+ finalItemsFolder.mkdir();
+ }
+ Arrays.stream(finalItemsFolder.listFiles()).forEach(file -> loadItemsFile(file, true));
+ TLocale.Logger.info("ITEM-UTILS.SUCCESS-LOAD-CACHES", String.valueOf(itemCaches.size() + itemCachesFinal.size()));
+ }
+
+ public static File getItemCacheFile() {
+ File itemCacheFile = new File(Main.getInst().getDataFolder(), "items.yml");
+ if (!itemCacheFile.exists()) {
+ Main.getInst().saveResource("items.yml", true);
+ }
+ return itemCacheFile;
+ }
+
public static void loadItemsFile(File file, boolean finalFile) {
FileConfiguration conf = ConfigUtils.load(Main.getInst(), file);
for (String name : conf.getConfigurationSection("").getKeys(false)) {
@@ -120,33 +105,22 @@ public class ItemUtils {
}
}
- public static void reloadItemCache() {
- itemCaches.clear();
- itemCachesFinal.clear();
- loadItemsFile(getItemCacheFile(), false);
- // 创建固定物品库
- finalItemsFolder = new File(Main.getInst().getDataFolder(), "FinalItems");
- if (!finalItemsFolder.exists()) {
- finalItemsFolder.mkdir();
- }
- // 检查固定物品库中的物品
- Arrays.stream(finalItemsFolder.listFiles()).forEach(file -> loadItemsFile(file, true));
- TLocale.Logger.info("ITEM-UTILS.SUCCESS-LOAD-CACHES", String.valueOf(itemCaches.size() + itemCachesFinal.size()));
+ // *********************************
+ //
+ // API
+ //
+ // *********************************
+
+ public static boolean isExists(String name) {
+ return itemCachesFinal.containsKey(name) || itemCaches.containsKey(name);
}
- public static void reloadItemName() {
- FileConfiguration conf = new Language("ITEM_NAME", Main.getInst(), true).getConfiguration();
- itemlib.clear();
- conf.getConfigurationSection("").getKeys(false).forEach(a -> itemlib.put(a, conf.getString(a)));
- TLocale.Logger.info("ITEM-UTILS.SUCCESS-LOAD-NAMES", String.valueOf(itemlib.size()));
+ public static ItemStack getCacheItem(String name) {
+ return itemCachesFinal.containsKey(name) ? itemCachesFinal.get(name) : itemCaches.get(name);
}
- public static File getItemCacheFile() {
- File itemCacheFile = new File(Main.getInst().getDataFolder(), "items.yml");
- if (!itemCacheFile.exists()) {
- Main.getInst().saveResource("items.yml", true);
- }
- return itemCacheFile;
+ public static ItemStack getItemFromDir(String name) {
+ return itemDir != null ? itemDir.getItemStack("item." + name) : null;
}
public static String getCustomName(ItemStack item) {
@@ -154,19 +128,7 @@ public class ItemUtils {
return TLocale.asString("ITEM-UTILS.EMPTY-ITEM");
}
int data = item.getType().getMaxDurability() == 0 ? item.getDurability() : 0;
- return item.getItemMeta().hasDisplayName() ? item.getItemMeta().getDisplayName() : itemlib.get(item.getType() + ":" + data) == null ? item.getType().toString() : itemlib.get(item.getType() + ":" + data);
- }
-
- public static ItemStack getItemFromDir(String name) {
- if (itemdir != null) {
- return itemdir.getItemStack("item." + name);
- }
- return null;
- }
-
- @SuppressWarnings("deprecation")
- public static ItemStack item(int n, int a, int d) {
- return new ItemStack(n, a, (short) d);
+ return item.getItemMeta().hasDisplayName() ? item.getItemMeta().getDisplayName() : itemLib.get(item.getType() + ":" + data) == null ? item.getType().toString() : itemLib.get(item.getType() + ":" + data);
}
public static ItemStack setName(ItemStack i, String n) {
@@ -176,7 +138,7 @@ public class ItemUtils {
return i;
}
- public static ItemStack Enchant(ItemStack i, Enchantment e, int l) {
+ public static ItemStack enchant(ItemStack i, Enchantment e, int l) {
ItemMeta meta = i.getItemMeta();
meta.addEnchant(e, l, false);
i.setItemMeta(meta);
@@ -203,10 +165,7 @@ public class ItemUtils {
}
public static String asString(String args, Player placeholderPlayer) {
- if (placeholderPlayer == null) {
- return args.replace("&", "§");
- }
- return PlaceholderAPI.setPlaceholders(placeholderPlayer, args.replace("&", "§"));
+ return placeholderPlayer == null ? args.replace("&", "§") : PlaceholderAPI.setPlaceholders(placeholderPlayer, args.replace("&", "§"));
}
public static List asString(List args, Player placeholderPlayer) {
@@ -281,58 +240,30 @@ public class ItemUtils {
}
}
- /**
- * 包含介绍
- *
- * @param i 物品
- * @param a 关键字
- */
+ public static int getLore(ItemStack i, String a) {
+ return isLored(i) ? IntStream.range(0, i.getItemMeta().getLore().size()).filter(j -> i.getItemMeta().getLore().get(j).contains(a)).findFirst().orElse(0) : 0;
+ }
+
public static boolean hasLore(ItemStack i, String a) {
return isLored(i) && i.getItemMeta().getLore().toString().contains(a);
}
- /**
- * 如果已描述
- *
- * @param i
- * @return
- */
public static boolean isLored(ItemStack i) {
return i != null && i.getItemMeta() != null && i.getItemMeta().getLore() != null;
}
- /**
- * 如果已命名
- *
- * @param i
- * @return
- */
public static boolean isNamed(ItemStack i) {
return i != null && i.getItemMeta() != null && i.getItemMeta().getDisplayName() != null;
}
- /**
- * 添加描述
- *
- * @param is 物品
- * @param lore 描述
- */
- public static ItemStack addLore(ItemStack is, String lore) {
+ public static ItemStack addLore(ItemStack is, String line) {
ItemMeta meta = is.getItemMeta();
-
- List _lore = meta.hasLore() ? meta.getLore() : Collections.emptyList();
- _lore.add(lore.replaceAll("&", "§"));
-
+ List lore = meta.hasLore() ? meta.getLore() : Collections.emptyList();
+ lore.add(TLocale.Translate.setColored(line));
is.setItemMeta(meta);
return is;
}
- /**
- * 移除描述
- *
- * @param is 物品
- * @param line 行数
- */
public static ItemStack delLore(ItemStack is, int line) {
ItemMeta meta = is.getItemMeta();
if (meta.hasLore()) {
@@ -346,40 +277,7 @@ public class ItemUtils {
return is;
}
- /**
- * 获取介绍所在行数
- *
- * @param i 物品
- * @param a 关键字
- */
- public static int getLore(ItemStack i, String a) {
- return isLored(i) ? IntStream.range(0, i.getItemMeta().getLore().size()).filter(j -> i.getItemMeta().getLore().get(j).contains(a)).findFirst().orElse(0) : 0;
- }
-
- /**
- * 添加耐久
- *
- * @param i 物品
- * @param d 耐久
- */
- public static ItemStack addDurability(ItemStack i, int d) {
- i.setDurability((short) (i.getDurability() + d));
- int min = i.getDurability();
- int max = i.getType().getMaxDurability();
- if (min >= max) {
- i.setType(Material.AIR);
- }
- return i;
- }
-
- /**
- * 替换描述
- *
- * @param i 物品
- * @param l1 关键字1
- * @param l2 关键字2
- */
- public static ItemStack repalceLore(ItemStack i, String l1, String l2) {
+ public static ItemStack replaceLore(ItemStack i, String l1, String l2) {
if (!isLored(i)) {
return i;
} else {
@@ -392,6 +290,16 @@ public class ItemUtils {
return i;
}
+ public static ItemStack addDurability(ItemStack i, int d) {
+ i.setDurability((short) (i.getDurability() + d));
+ int min = i.getDurability();
+ int max = i.getType().getMaxDurability();
+ if (min >= max) {
+ i.setType(Material.AIR);
+ }
+ return i;
+ }
+
public static ItemStack loadItem(FileConfiguration f, String s) {
return loadItem(f, s, null);
}
@@ -552,6 +460,62 @@ public class ItemUtils {
return nbt;
}
+ // *********************************
+ //
+ // Getter and Setter
+ //
+ // *********************************
+
+ public static FileConfiguration getItemDir() {
+ return itemDir;
+ }
+
+ public static LinkedHashMap getItemLib() {
+ return itemLib;
+ }
+
+ public static FileConfiguration getItemCache() {
+ return itemCache;
+ }
+
+ public static File getFinalItemsFolder() {
+ return finalItemsFolder;
+ }
+
+ public static LinkedHashMap getItemCaches() {
+ return itemCaches;
+ }
+
+ public static LinkedHashMap getItemCachesFinal() {
+ return itemCachesFinal;
+ }
+
+ // *********************************
+ //
+ // Deprecated
+ //
+ // *********************************
+
+ @Deprecated
+ public static FileConfiguration getItemdir() {
+ return itemDir;
+ }
+
+ @Deprecated
+ public static LinkedHashMap getItemlib() {
+ return itemLib;
+ }
+
+ @Deprecated
+ public static ItemStack item(int n, int a, int d) {
+ return new ItemStack(n, a, (short) d);
+ }
+
+ @Deprecated
+ public static ItemStack repalceLore(ItemStack i, String l1, String l2) {
+ return replaceLore(i, l1, l2);
+ }
+
@Deprecated
public static void putO(ItemStack item, Inventory inv, int i) {
inv.setItem(i, item);
diff --git a/src/main/java/me/skymc/taboolib/inventory/builder/ItemBuilder.java b/src/main/java/me/skymc/taboolib/inventory/builder/ItemBuilder.java
index e727c1c..6e3a7d5 100644
--- a/src/main/java/me/skymc/taboolib/inventory/builder/ItemBuilder.java
+++ b/src/main/java/me/skymc/taboolib/inventory/builder/ItemBuilder.java
@@ -3,8 +3,10 @@ package me.skymc.taboolib.inventory.builder;
import com.ilummc.tlib.resources.TLocale;
import me.skymc.taboolib.TabooLib;
import me.skymc.taboolib.string.ArrayUtils;
+import org.bukkit.Bukkit;
import org.bukkit.Color;
import org.bukkit.Material;
+import org.bukkit.OfflinePlayer;
import org.bukkit.block.banner.Pattern;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.EntityType;
@@ -20,7 +22,7 @@ import java.util.List;
/**
* @Author sky
* @Since 2018-08-22 11:37
- * @BuilderVersion 1.0
+ * @BuilderVersion 1.1
*/
public class ItemBuilder {
@@ -40,6 +42,11 @@ public class ItemBuilder {
itemMeta = itemStack.getItemMeta();
}
+ public ItemBuilder(OfflinePlayer player) {
+ this(Material.SKULL_ITEM, 1, 3);
+ this.skullOwner(player.getName());
+ }
+
public ItemBuilder material(int id) {
itemStack.setType(Material.getMaterial(id));
return this;
@@ -147,6 +154,13 @@ public class ItemBuilder {
return this;
}
+ public ItemBuilder skullOwner(String name) {
+ if (itemMeta instanceof SkullMeta) {
+ ((SkullMeta) itemMeta).setOwner(name);
+ }
+ return this;
+ }
+
public ItemBuilder unbreakable(boolean value) {
if (TabooLib.getVersionNumber() >= 12000) {
itemMeta.setUnbreakable(value);
@@ -173,4 +187,14 @@ public class ItemBuilder {
}
return buildItem;
}
+
+ /**
+ * 从文本中获取物品(name:名字;lore:描述||描述;material:材质)
+ *
+ * @param str
+ * @return
+ */
+ public static ItemStack fromString(String str) {
+ return null;
+ }
}
diff --git a/src/main/java/me/skymc/taboolib/itagapi/TagDataHandler.java b/src/main/java/me/skymc/taboolib/itagapi/TagDataHandler.java
index 4770dbf..aea9ec2 100644
--- a/src/main/java/me/skymc/taboolib/itagapi/TagDataHandler.java
+++ b/src/main/java/me/skymc/taboolib/itagapi/TagDataHandler.java
@@ -2,6 +2,7 @@ package me.skymc.taboolib.itagapi;
import com.google.common.base.Preconditions;
import me.skymc.taboolib.Main;
+import me.skymc.taboolib.TabooLib;
import me.skymc.taboolib.packet.PacketUtils;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
@@ -132,7 +133,10 @@ public class TagDataHandler implements Listener {
entryTeam.addEntry(playerData.getNameDisplay());
entryTeam.setPrefix(playerData.getPrefix());
entryTeam.setSuffix(playerData.getSuffix());
- TagUtils.cleanEmptyTeamInScoreboard(scoreboard);
+ // 傻逼 BedWarsRel 我草你妈的
+ if (TabooLib.instance().getConfig().getBoolean("TABLIST-AUTO-CLEAN-TEAM", true)) {
+ TagUtils.cleanEmptyTeamInScoreboard(scoreboard);
+ }
}
private void cancelPlayerVariable(Player player, TagPlayerData playerData) {
@@ -142,7 +146,10 @@ public class TagDataHandler implements Listener {
for (Player online : Bukkit.getOnlinePlayers()) {
Scoreboard scoreboard = TagUtils.getScoreboardComputeIfAbsent(player);
TagUtils.cleanEntryInScoreboard(scoreboard, playerData.getNameDisplay());
- TagUtils.cleanEmptyTeamInScoreboard(scoreboard);
+ // 傻逼 BedWarsRel 我草你妈的
+ if (TabooLib.instance().getConfig().getBoolean("TABLIST-AUTO-CLEAN-TEAM", true)) {
+ TagUtils.cleanEmptyTeamInScoreboard(scoreboard);
+ }
}
}
@@ -157,7 +164,7 @@ public class TagDataHandler implements Listener {
downloadPlayerVariable(e.getPlayer());
}
- @EventHandler (priority = EventPriority.MONITOR)
+ @EventHandler(priority = EventPriority.MONITOR)
public void onQuit(PlayerQuitEvent e) {
cancelPlayerVariable(e.getPlayer(), unregisterPlayerData(e.getPlayer()));
}
diff --git a/src/main/java/me/skymc/taboolib/json/tellraw/TellrawJson.java b/src/main/java/me/skymc/taboolib/json/tellraw/TellrawJson.java
index 0e88dd6..ba2e288 100644
--- a/src/main/java/me/skymc/taboolib/json/tellraw/TellrawJson.java
+++ b/src/main/java/me/skymc/taboolib/json/tellraw/TellrawJson.java
@@ -4,33 +4,30 @@ import com.ilummc.tlib.bungee.api.chat.*;
import com.ilummc.tlib.bungee.chat.ComponentSerializer;
import com.ilummc.tlib.logger.TLogger;
import com.ilummc.tlib.resources.TLocale;
-import me.skymc.taboolib.inventory.ItemUtils;
import me.skymc.taboolib.methods.ReflectionUtils;
import me.skymc.taboolib.nms.NMSUtils;
-import me.skymc.taboolib.other.NumberUtils;
import me.skymc.taboolib.string.ArrayUtils;
-import me.skymc.taboolib.string.VariableFormatter;
import org.bukkit.command.CommandSender;
import org.bukkit.inventory.ItemStack;
-import java.lang.reflect.Array;
import java.lang.reflect.Method;
-import java.util.Arrays;
-import java.util.Collections;
+import java.util.ArrayList;
import java.util.List;
-import java.util.Map;
+import java.util.stream.Collectors;
/**
* @Author sky
* @Since 2018-05-26 14:42json
+ * @BuilderLevel 1.2
*/
public class TellrawJson {
- private BaseComponent[] components = TextComponent.fromLegacyText("");
- private final Class> craftItemStackClazz = NMSUtils.getOBCClass("inventory.CraftItemStack");
- private final Class> nmsItemStackClazz = NMSUtils.getNMSClass("ItemStack");
- private final Class> nbtTagCompoundClazz = NMSUtils.getNMSClass("NBTTagCompound");
- private final String INVALID_ITEM = "{id:stone,tag:{display:{Name:§c* Invalid ItemStack *}}}";
+ private List components = new ArrayList<>();
+ private List componentsLatest = new ArrayList<>();
+ private static final Class> craftItemStackClazz = NMSUtils.getOBCClass("inventory.CraftItemStack");
+ private static final Class> nmsItemStackClazz = NMSUtils.getNMSClass("ItemStack");
+ private static final Class> nbtTagCompoundClazz = NMSUtils.getNMSClass("NBTTagCompound");
+ private static final String INVALID_ITEM = "{id:stone,tag:{display:{Name:§c* Invalid ItemStack *}}}";
TellrawJson() {
}
@@ -39,12 +36,16 @@ public class TellrawJson {
return new TellrawJson();
}
+ public void send(CommandSender sender) {
+ TLocale.Tellraw.send(sender, toRawMessage());
+ }
+
public String toRawMessage() {
- return ComponentSerializer.toString(components);
+ return ComponentSerializer.toString(getComponentsAll());
}
public String toLegacyText() {
- return TextComponent.toLegacyText(components);
+ return TextComponent.toLegacyText(getComponentsAll());
}
public TellrawJson newLine() {
@@ -52,50 +53,51 @@ public class TellrawJson {
}
public TellrawJson append(String text) {
- Arrays.stream(TextComponent.fromLegacyText(text)).forEach(component -> this.components = ArrayUtils.arrayAppend(this.components, component));
+ appendComponents();
+ componentsLatest.addAll(ArrayUtils.asList(TextComponent.fromLegacyText(text)));
return this;
}
public TellrawJson append(TellrawJson json) {
- BaseComponent[] newArray = new BaseComponent[components.length + json.components.length];
- System.arraycopy(components, 0, newArray, 0, components.length);
- System.arraycopy(json.components, 0, newArray, components.length, json.components.length);
- components = newArray;
+ appendComponents();
+ componentsLatest.addAll(ArrayUtils.asList(json.getComponentsAll()));
return this;
}
public TellrawJson hoverText(String text) {
- getLatestComponent().setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(text).create()));
+ getLatestComponent().forEach(component -> component.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(text).create())));
return this;
}
public TellrawJson hoverItem(ItemStack itemStack) {
- getLatestComponent().setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_ITEM, new ComponentBuilder(getItemComponent(itemStack)).create()));
+ getLatestComponent().forEach(component -> component.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_ITEM, new ComponentBuilder(getItemComponent(itemStack)).create())));
return this;
}
public TellrawJson clickCommand(String command) {
- getLatestComponent().setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, command));
+ getLatestComponent().forEach(component -> component.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, command)));
return this;
}
public TellrawJson clickSuggest(String command) {
- getLatestComponent().setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, command));
+ getLatestComponent().forEach(component -> component.setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, command)));
return this;
}
public TellrawJson clickOpenURL(String url) {
- getLatestComponent().setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, url));
+ getLatestComponent().forEach(component -> component.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, url)));
return this;
}
public TellrawJson clickChangePage(int page) {
- getLatestComponent().setClickEvent(new ClickEvent(ClickEvent.Action.CHANGE_PAGE, String.valueOf(page)));
+ getLatestComponent().forEach(component -> component.setClickEvent(new ClickEvent(ClickEvent.Action.CHANGE_PAGE, String.valueOf(page))));
return this;
}
- public void send(CommandSender sender) {
- TLocale.Tellraw.send(sender, toRawMessage());
+ public BaseComponent[] getComponentsAll() {
+ List components = this.components.stream().filter(component -> !(component instanceof TextComponent) || !((TextComponent) component).getText().isEmpty()).collect(Collectors.toList());
+ this.componentsLatest.stream().filter(component -> !(component instanceof TextComponent) || !((TextComponent) component).getText().isEmpty()).forEach(components::add);
+ return components.toArray(new BaseComponent[0]);
}
public String getItemComponent(ItemStack itemStack) {
@@ -106,7 +108,7 @@ public class TellrawJson {
Object nmsItemStackObj = asNMSCopyMethod.invoke(null, itemStack);
return saveNmsItemStackMethod.invoke(nmsItemStackObj, nmsNbtTagCompoundObj).toString();
} catch (Throwable t) {
- TLogger.getGlobalLogger().error("failed to serialize itemstack to nms item: " + t.toString());
+ TLogger.getGlobalLogger().error("failed to serialize bukkit item to nms item: " + t.toString());
return INVALID_ITEM;
}
}
@@ -117,12 +119,17 @@ public class TellrawJson {
//
// *********************************
- private BaseComponent getLatestComponent() {
- return components[components.length - 1];
+ private List getLatestComponent() {
+ return componentsLatest;
}
- private void setLatestComponent(BaseComponent component) {
- components[components.length - 1] = component;
+ private void setLatestComponent(BaseComponent... component) {
+ componentsLatest.addAll(ArrayUtils.asList(component));
+ }
+
+ private void appendComponents() {
+ components.addAll(componentsLatest);
+ componentsLatest.clear();
}
// *********************************
@@ -131,12 +138,11 @@ public class TellrawJson {
//
// *********************************
- public BaseComponent[] getComponents() {
- return components;
- }
-
public void setComponents(BaseComponent[] components) {
- this.components = components;
+ this.components = ArrayUtils.asList(components);
}
+ public BaseComponent[] getComponents() {
+ return components.toArray(new BaseComponent[0]);
+ }
}
diff --git a/src/main/java/me/skymc/taboolib/listener/ListenerPlayerCommand.java b/src/main/java/me/skymc/taboolib/listener/ListenerPlayerCommand.java
index e6da994..a417dc4 100644
--- a/src/main/java/me/skymc/taboolib/listener/ListenerPlayerCommand.java
+++ b/src/main/java/me/skymc/taboolib/listener/ListenerPlayerCommand.java
@@ -1,9 +1,12 @@
package me.skymc.taboolib.listener;
+import com.ilummc.tlib.logger.TLogger;
import me.skymc.taboolib.Main;
import me.skymc.taboolib.TabooLib;
import me.skymc.taboolib.database.PlayerDataManager;
+import me.skymc.taboolib.inventory.ItemUtils;
import me.skymc.taboolib.itemnbtapi.NBTItem;
+import me.skymc.taboolib.json.tellraw.TellrawJson;
import me.skymc.taboolib.message.MsgUtils;
import me.skymc.taboolib.permission.PermissionUtils;
import me.skymc.taboolib.playerdata.DataUtils;
@@ -13,31 +16,51 @@ import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.server.ServerCommandEvent;
+/**
+ * @author sky
+ */
@TListener
public class ListenerPlayerCommand implements Listener {
@EventHandler
public void cmd(ServerCommandEvent e) {
- if ("savefile".equals(e.getCommand())) {
+ if (e.getCommand().equalsIgnoreCase("saveFiles")) {
if (TabooLib.getVerint() > 10700) {
e.setCancelled(true);
}
Bukkit.getScheduler().runTask(Main.getInst(), DataUtils::saveAllCaches);
Bukkit.getScheduler().runTask(Main.getInst(), () -> PlayerDataManager.saveAllCaches(true, false));
+ TLogger.getGlobalLogger().info("Successfully.");
+ } else if (e.getCommand().equalsIgnoreCase("tDebug")) {
+ if (TabooLib.getVerint() > 10700) {
+ e.setCancelled(true);
+ }
+ if (TabooLib.isDebug()) {
+ TabooLib.setDebug(false);
+ TLogger.getGlobalLogger().info("&cDisabled.");
+ } else {
+ TabooLib.setDebug(true);
+ TLogger.getGlobalLogger().info("&aEnabled.");
+ }
}
}
@SuppressWarnings("deprecation")
@EventHandler
public void cmd(PlayerCommandPreprocessEvent e) {
- if ("/unbreakable".equals(e.getMessage()) && PermissionUtils.hasPermission(e.getPlayer(), "taboolib.unbreakable")) {
+ if (e.getMessage().equals("/unbreakable") && PermissionUtils.hasPermission(e.getPlayer(), "taboolib.unbreakable")) {
e.setCancelled(true);
-
- NBTItem nbti = new NBTItem(e.getPlayer().getItemInHand());
- nbti.setInteger("Unbreakable", 1);
- e.getPlayer().setItemInHand(nbti.getItem());
-
+ NBTItem nbt = new NBTItem(e.getPlayer().getItemInHand());
+ nbt.setInteger("Unbreakable", 1);
+ e.getPlayer().setItemInHand(nbt.getItem());
MsgUtils.send(e.getPlayer(), "Success!");
+ } else if (e.getMessage().equals("/tellrawTest") && PermissionUtils.hasPermission(e.getPlayer(), "taboolib.tellraw")) {
+ e.setCancelled(true);
+ TellrawJson.create()
+ .append("§8[§3§lTabooLib§8] §7TellrawJson Test: §f[")
+ .append(ItemUtils.getCustomName(e.getPlayer().getItemInHand())).hoverItem(e.getPlayer().getItemInHand())
+ .append("§f]")
+ .send(e.getPlayer());
}
}
}
diff --git a/src/main/java/me/skymc/taboolib/listener/ListenerPluginDisable.java b/src/main/java/me/skymc/taboolib/listener/ListenerPluginDisable.java
index c1b101b..b4083e1 100644
--- a/src/main/java/me/skymc/taboolib/listener/ListenerPluginDisable.java
+++ b/src/main/java/me/skymc/taboolib/listener/ListenerPluginDisable.java
@@ -1,9 +1,13 @@
package me.skymc.taboolib.listener;
+import com.ilummc.tlib.TLib;
+import com.ilummc.tlib.inject.TConfigWatcher;
import com.ilummc.tlib.resources.TLocale;
import me.skymc.taboolib.Main;
-import me.skymc.taboolib.message.MsgUtils;
+import me.skymc.taboolib.TabooLib;
+import me.skymc.taboolib.common.configuration.TConfiguration;
import me.skymc.taboolib.mysql.MysqlUtils;
+import me.skymc.taboolib.mysql.hikari.HikariHandler;
import me.skymc.taboolib.mysql.protect.MySQLConnection;
import me.skymc.taboolib.timecycle.TimeCycleManager;
import org.bukkit.event.EventHandler;
@@ -11,33 +15,48 @@ import org.bukkit.event.Listener;
import org.bukkit.event.server.PluginDisableEvent;
import org.bukkit.scheduler.BukkitRunnable;
+import java.io.File;
import java.util.ArrayList;
+import java.util.HashSet;
import java.util.List;
+import java.util.Optional;
+/**
+ * @author sky
+ */
@TListener
public class ListenerPluginDisable implements Listener {
@EventHandler
public void disable(PluginDisableEvent e) {
+ TabooLib.debug("Plugin \"" + e.getPlugin().getName() + "\" was disabled.");
// 注销时间周期
TimeCycleManager.cancel(e.getPlugin());
-
+ // 注销插件配置
+ Optional.ofNullable(TConfiguration.getFiles().get(e.getPlugin().getName())).ifPresent(files -> {
+ TConfigWatcher tConfigWatcher = TLib.getTLib().getConfigWatcher();
+ for (File file : files) {
+ tConfigWatcher.removeListener(file);
+ TabooLib.debug("Remove TConfiguration \"" + file.getName() + "\" from Plugin \"" + e.getPlugin().getName() + "\"");
+ }
+ });
+ // 注销数据库连接
+ new HashSet<>(HikariHandler.getDataSource().keySet()).stream().filter(host -> e.getPlugin().equals(host.getPlugin()) && host.isAutoClose()).forEach(HikariHandler::closeDataSource);
// 获取连接
- List conns = new ArrayList<>();
+ List connection = new ArrayList<>();
for (MySQLConnection conn : MysqlUtils.CONNECTIONS) {
if (conn.getPlugin().equals(e.getPlugin())) {
- conns.add(conn);
+ connection.add(conn);
MysqlUtils.CONNECTIONS.remove(conn);
}
}
-
// 异步注销
BukkitRunnable runnable = new BukkitRunnable() {
@Override
public void run() {
int i = 0;
- for (MySQLConnection conn : conns) {
+ for (MySQLConnection conn : connection) {
conn.setFallReconnection(false);
conn.closeConnection();
i++;
@@ -47,7 +66,6 @@ public class ListenerPluginDisable implements Listener {
}
}
};
-
// 如果插件关闭
try {
runnable.runTaskLater(Main.getInst(), 40);
diff --git a/src/main/java/me/skymc/taboolib/listener/TListenerHandler.java b/src/main/java/me/skymc/taboolib/listener/TListenerHandler.java
index 100e8ba..927419e 100644
--- a/src/main/java/me/skymc/taboolib/listener/TListenerHandler.java
+++ b/src/main/java/me/skymc/taboolib/listener/TListenerHandler.java
@@ -2,7 +2,8 @@ package me.skymc.taboolib.listener;
import com.ilummc.tlib.util.Strings;
import me.skymc.taboolib.TabooLib;
-import me.skymc.taboolib.fileutils.FileUtils;
+import me.skymc.taboolib.TabooLibLoader;
+import me.skymc.taboolib.methods.ReflectionUtils;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.HandlerList;
@@ -28,12 +29,10 @@ public class TListenerHandler implements Listener {
*/
public static void setupListeners() {
for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
- if (plugin.equals(TabooLib.instance()) || plugin.getDescription().getDepend().contains("TabooLib")) {
- try {
- setupListener(plugin);
- } catch (Exception e) {
- e.printStackTrace();
- }
+ try {
+ setupListener(plugin);
+ } catch (Exception e) {
+ e.printStackTrace();
}
}
}
@@ -45,25 +44,27 @@ public class TListenerHandler implements Listener {
* @param plugin 插件
*/
public static void setupListener(Plugin plugin) {
- List classes = FileUtils.getClasses(plugin);
- for (Class> pluginClass : classes) {
- if (Listener.class.isAssignableFrom(pluginClass) && pluginClass.isAnnotationPresent(TListener.class)) {
- try {
- TListener tListener = pluginClass.getAnnotation(TListener.class);
- // 检查注册条件
- if (tListener.depend().length > 0 && !Strings.isBlank(tListener.depend()[0])) {
- if (Arrays.stream(tListener.depend()).anyMatch(depend -> Bukkit.getPluginManager().getPlugin(depend) == null)) {
- continue;
+ TabooLibLoader.getPluginClasses(plugin).ifPresent(classes -> {
+ for (Class> pluginClass : classes) {
+ if (org.bukkit.event.Listener.class.isAssignableFrom(pluginClass) && pluginClass.isAnnotationPresent(TListener.class)) {
+ try {
+ TListener tListener = pluginClass.getAnnotation(TListener.class);
+ // 检查注册条件
+ if (tListener.depend().length > 0 && !Strings.isBlank(tListener.depend()[0])) {
+ if (Arrays.stream(tListener.depend()).anyMatch(depend -> Bukkit.getPluginManager().getPlugin(depend) == null)) {
+ continue;
+ }
}
+ // 实例化监听器
+ Listener listener = plugin.getClass().equals(pluginClass) ? (Listener) plugin : (Listener) ReflectionUtils.instantiateObject(pluginClass);
+ listeners.computeIfAbsent(plugin.getName(), name -> new ArrayList<>()).add(listener);
+ TabooLib.debug("Listener " + listener.getClass().getSimpleName() + " setup successfully. (" + plugin.getName() + ")");
+ } catch (Exception e) {
+ TabooLib.debug("Listener setup failed: " + e.toString());
}
- // 实例化监听器
- Listener listener = plugin.getClass().equals(pluginClass) ? (Listener) plugin : (Listener) pluginClass.newInstance();
- listeners.computeIfAbsent(plugin.getName(), name -> new ArrayList<>()).add(listener);
- } catch (Exception e) {
- e.printStackTrace();
}
}
- }
+ });
}
/**
@@ -113,6 +114,7 @@ public class TListenerHandler implements Listener {
}
// 注册监听
Bukkit.getPluginManager().registerEvents(listener, plugin);
+ TabooLib.debug("Listener " + listener.getClass().getSimpleName() + " registered. (" + plugin.getName() + ")");
}
});
}
@@ -154,6 +156,10 @@ public class TListenerHandler implements Listener {
});
}
+ public static HashMap> getListeners() {
+ return listeners;
+ }
+
@EventHandler
public void onPluginEnable(PluginEnableEvent e) {
try {
@@ -170,14 +176,4 @@ public class TListenerHandler implements Listener {
} catch (Exception ignored) {
}
}
-
- // *********************************
- //
- // Getter and Setter
- //
- // *********************************
-
- public static HashMap> getListeners() {
- return listeners;
- }
}
diff --git a/src/main/java/me/skymc/taboolib/message/MsgUtils.java b/src/main/java/me/skymc/taboolib/message/MsgUtils.java
index 8692de7..9ed7c56 100644
--- a/src/main/java/me/skymc/taboolib/message/MsgUtils.java
+++ b/src/main/java/me/skymc/taboolib/message/MsgUtils.java
@@ -5,6 +5,7 @@ import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.Plugin;
+@Deprecated
public class MsgUtils {
public static void send(CommandSender sender, String s) {
diff --git a/src/main/java/me/skymc/taboolib/methods/ReflectionUtils.java b/src/main/java/me/skymc/taboolib/methods/ReflectionUtils.java
index 6b2c54a..eede188 100644
--- a/src/main/java/me/skymc/taboolib/methods/ReflectionUtils.java
+++ b/src/main/java/me/skymc/taboolib/methods/ReflectionUtils.java
@@ -19,582 +19,585 @@ import java.util.Map;
* Don't claim this class as your own
* Don't remove this disclaimer
*
- *
+ *
* It would be nice if you provide credit to me if you use this class in a published project
- *
+ *
* @author DarkBlade12
* @version 1.1
*/
public final class ReflectionUtils {
- // Prevent accidental construction
- private ReflectionUtils() {}
+ // Prevent accidental construction
+ private ReflectionUtils() {
+ }
- /**
- * Returns the constructor of a given class with the given parameter types
- *
- * @param clazz Target class
- * @param parameterTypes Parameter types of the desired constructor
- * @return The constructor of the target class with the specified parameter types
- * @throws NoSuchMethodException If the desired constructor with the specified parameter types cannot be found
- * @see DataType
- * @see DataType#getPrimitive(Class[])
- * @see DataType#compare(Class[], Class[])
- */
- public static Constructor> getConstructor(Class> clazz, Class>... parameterTypes) throws NoSuchMethodException {
- Class>[] primitiveTypes = DataType.getPrimitive(parameterTypes);
- for (Constructor> constructor : clazz.getConstructors()) {
- if (!DataType.compare(DataType.getPrimitive(constructor.getParameterTypes()), primitiveTypes)) {
- continue;
- }
- return constructor;
- }
- throw new NoSuchMethodException("There is no such constructor in this class with the specified parameter types");
- }
+ /**
+ * Returns the constructor of a given class with the given parameter types
+ *
+ * @param clazz Target class
+ * @param parameterTypes Parameter types of the desired constructor
+ * @return The constructor of the target class with the specified parameter types
+ * @throws NoSuchMethodException If the desired constructor with the specified parameter types cannot be found
+ * @see DataType
+ * @see DataType#getPrimitive(Class[])
+ * @see DataType#compare(Class[], Class[])
+ */
+ public static Constructor> getConstructor(Class> clazz, Class>... parameterTypes) throws NoSuchMethodException {
+ Class>[] primitiveTypes = DataType.getPrimitive(parameterTypes);
+ for (Constructor> constructor : clazz.getDeclaredConstructors()) {
+ if (!DataType.compare(DataType.getPrimitive(constructor.getParameterTypes()), primitiveTypes)) {
+ continue;
+ }
+ constructor.setAccessible(true);
+ return constructor;
+ }
+ throw new NoSuchMethodException("There is no such constructor in this class with the specified parameter types");
+ }
- /**
- * Returns the constructor of a desired class with the given parameter types
- *
- * @param className Name of the desired target class
- * @param packageType Package where the desired target class is located
- * @param parameterTypes Parameter types of the desired constructor
- * @return The constructor of the desired target class with the specified parameter types
- * @throws NoSuchMethodException If the desired constructor with the specified parameter types cannot be found
- * @throws ClassNotFoundException ClassNotFoundException If the desired target class with the specified name and package cannot be found
- * @see #getConstructor(Class, Class...)
- */
- public static Constructor> getConstructor(String className, PackageType packageType, Class>... parameterTypes) throws NoSuchMethodException, ClassNotFoundException {
- return getConstructor(packageType.getClass(className), parameterTypes);
- }
+ /**
+ * Returns the constructor of a desired class with the given parameter types
+ *
+ * @param className Name of the desired target class
+ * @param packageType Package where the desired target class is located
+ * @param parameterTypes Parameter types of the desired constructor
+ * @return The constructor of the desired target class with the specified parameter types
+ * @throws NoSuchMethodException If the desired constructor with the specified parameter types cannot be found
+ * @throws ClassNotFoundException ClassNotFoundException If the desired target class with the specified name and package cannot be found
+ * @see #getConstructor(Class, Class...)
+ */
+ public static Constructor> getConstructor(String className, PackageType packageType, Class>... parameterTypes) throws NoSuchMethodException, ClassNotFoundException {
+ return getConstructor(packageType.getClass(className), parameterTypes);
+ }
- /**
- * Returns an instance of a class with the given arguments
- *
- * @param clazz Target class
- * @param arguments Arguments which are used to construct an object of the target class
- * @return The instance of the target class with the specified arguments
- * @throws InstantiationException If you cannot create an instance of the target class due to certain circumstances
- * @throws IllegalAccessException If the desired constructor cannot be accessed due to certain circumstances
- * @throws IllegalArgumentException If the types of the arguments do not match the parameter types of the constructor (this should not occur since it searches for a constructor with the types of the arguments)
- * @throws InvocationTargetException If the desired constructor cannot be invoked
- * @throws NoSuchMethodException If the desired constructor with the specified arguments cannot be found
- */
- public static Object instantiateObject(Class> clazz, Object... arguments) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException {
- return getConstructor(clazz, DataType.getPrimitive(arguments)).newInstance(arguments);
- }
+ /**
+ * Returns an instance of a class with the given arguments
+ *
+ * @param clazz Target class
+ * @param arguments Arguments which are used to construct an object of the target class
+ * @return The instance of the target class with the specified arguments
+ * @throws InstantiationException If you cannot create an instance of the target class due to certain circumstances
+ * @throws IllegalAccessException If the desired constructor cannot be accessed due to certain circumstances
+ * @throws IllegalArgumentException If the types of the arguments do not match the parameter types of the constructor (this should not occur since it searches for a constructor with the types of the arguments)
+ * @throws InvocationTargetException If the desired constructor cannot be invoked
+ * @throws NoSuchMethodException If the desired constructor with the specified arguments cannot be found
+ */
+ public static Object instantiateObject(Class> clazz, Object... arguments) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException {
+ return getConstructor(clazz, DataType.getPrimitive(arguments)).newInstance(arguments);
+ }
- /**
- * Returns an instance of a desired class with the given arguments
- *
- * @param className Name of the desired target class
- * @param packageType Package where the desired target class is located
- * @param arguments Arguments which are used to construct an object of the desired target class
- * @return The instance of the desired target class with the specified arguments
- * @throws InstantiationException If you cannot create an instance of the desired target class due to certain circumstances
- * @throws IllegalAccessException If the desired constructor cannot be accessed due to certain circumstances
- * @throws IllegalArgumentException If the types of the arguments do not match the parameter types of the constructor (this should not occur since it searches for a constructor with the types of the arguments)
- * @throws InvocationTargetException If the desired constructor cannot be invoked
- * @throws NoSuchMethodException If the desired constructor with the specified arguments cannot be found
- * @throws ClassNotFoundException If the desired target class with the specified name and package cannot be found
- * @see #instantiateObject(Class, Object...)
- */
- public static Object instantiateObject(String className, PackageType packageType, Object... arguments) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException {
- return instantiateObject(packageType.getClass(className), arguments);
- }
+ /**
+ * Returns an instance of a desired class with the given arguments
+ *
+ * @param className Name of the desired target class
+ * @param packageType Package where the desired target class is located
+ * @param arguments Arguments which are used to construct an object of the desired target class
+ * @return The instance of the desired target class with the specified arguments
+ * @throws InstantiationException If you cannot create an instance of the desired target class due to certain circumstances
+ * @throws IllegalAccessException If the desired constructor cannot be accessed due to certain circumstances
+ * @throws IllegalArgumentException If the types of the arguments do not match the parameter types of the constructor (this should not occur since it searches for a constructor with the types of the arguments)
+ * @throws InvocationTargetException If the desired constructor cannot be invoked
+ * @throws NoSuchMethodException If the desired constructor with the specified arguments cannot be found
+ * @throws ClassNotFoundException If the desired target class with the specified name and package cannot be found
+ * @see #instantiateObject(Class, Object...)
+ */
+ public static Object instantiateObject(String className, PackageType packageType, Object... arguments) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException {
+ return instantiateObject(packageType.getClass(className), arguments);
+ }
- /**
- * Returns a method of a class with the given parameter types
- *
- * @param clazz Target class
- * @param methodName Name of the desired method
- * @param parameterTypes Parameter types of the desired method
- * @return The method of the target class with the specified name and parameter types
- * @throws NoSuchMethodException If the desired method of the target class with the specified name and parameter types cannot be found
- * @see DataType#getPrimitive(Class[])
- * @see DataType#compare(Class[], Class[])
- */
- public static Method getMethod(Class> clazz, String methodName, Class>... parameterTypes) throws NoSuchMethodException {
- Class>[] primitiveTypes = DataType.getPrimitive(parameterTypes);
- for (Method method : clazz.getMethods()) {
- if (!method.getName().equals(methodName) || !DataType.compare(DataType.getPrimitive(method.getParameterTypes()), primitiveTypes)) {
- continue;
- }
- return method;
- }
- throw new NoSuchMethodException("There is no such method in this class with the specified name and parameter types");
- }
+ /**
+ * Returns a method of a class with the given parameter types
+ *
+ * @param clazz Target class
+ * @param methodName Name of the desired method
+ * @param parameterTypes Parameter types of the desired method
+ * @return The method of the target class with the specified name and parameter types
+ * @throws NoSuchMethodException If the desired method of the target class with the specified name and parameter types cannot be found
+ * @see DataType#getPrimitive(Class[])
+ * @see DataType#compare(Class[], Class[])
+ */
+ public static Method getMethod(Class> clazz, String methodName, Class>... parameterTypes) throws NoSuchMethodException {
+ Class>[] primitiveTypes = DataType.getPrimitive(parameterTypes);
+ for (Method method : clazz.getDeclaredMethods()) {
+ if (!method.getName().equals(methodName) || !DataType.compare(DataType.getPrimitive(method.getParameterTypes()), primitiveTypes)) {
+ continue;
+ }
+ method.setAccessible(true);
+ return method;
+ }
+ throw new NoSuchMethodException("There is no such method in this class with the specified name and parameter types");
+ }
- /**
- * Returns a method of a desired class with the given parameter types
- *
- * @param className Name of the desired target class
- * @param packageType Package where the desired target class is located
- * @param methodName Name of the desired method
- * @param parameterTypes Parameter types of the desired method
- * @return The method of the desired target class with the specified name and parameter types
- * @throws NoSuchMethodException If the desired method of the desired target class with the specified name and parameter types cannot be found
- * @throws ClassNotFoundException If the desired target class with the specified name and package cannot be found
- * @see #getMethod(Class, String, Class...)
- */
- public static Method getMethod(String className, PackageType packageType, String methodName, Class>... parameterTypes) throws NoSuchMethodException, ClassNotFoundException {
- return getMethod(packageType.getClass(className), methodName, parameterTypes);
- }
+ /**
+ * Returns a method of a desired class with the given parameter types
+ *
+ * @param className Name of the desired target class
+ * @param packageType Package where the desired target class is located
+ * @param methodName Name of the desired method
+ * @param parameterTypes Parameter types of the desired method
+ * @return The method of the desired target class with the specified name and parameter types
+ * @throws NoSuchMethodException If the desired method of the desired target class with the specified name and parameter types cannot be found
+ * @throws ClassNotFoundException If the desired target class with the specified name and package cannot be found
+ * @see #getMethod(Class, String, Class...)
+ */
+ public static Method getMethod(String className, PackageType packageType, String methodName, Class>... parameterTypes) throws NoSuchMethodException, ClassNotFoundException {
+ return getMethod(packageType.getClass(className), methodName, parameterTypes);
+ }
- /**
- * Invokes a method on an object with the given arguments
- *
- * @param instance Target object
- * @param methodName Name of the desired method
- * @param arguments Arguments which are used to invoke the desired method
- * @return The result of invoking the desired method on the target object
- * @throws IllegalAccessException If the desired method cannot be accessed due to certain circumstances
- * @throws IllegalArgumentException If the types of the arguments do not match the parameter types of the method (this should not occur since it searches for a method with the types of the arguments)
- * @throws InvocationTargetException If the desired method cannot be invoked on the target object
- * @throws NoSuchMethodException If the desired method of the class of the target object with the specified name and arguments cannot be found
- * @see #getMethod(Class, String, Class...)
- * @see DataType#getPrimitive(Object[])
- */
- public static Object invokeMethod(Object instance, String methodName, Object... arguments) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException {
- return getMethod(instance.getClass(), methodName, DataType.getPrimitive(arguments)).invoke(instance, arguments);
- }
+ /**
+ * Invokes a method on an object with the given arguments
+ *
+ * @param instance Target object
+ * @param methodName Name of the desired method
+ * @param arguments Arguments which are used to invoke the desired method
+ * @return The result of invoking the desired method on the target object
+ * @throws IllegalAccessException If the desired method cannot be accessed due to certain circumstances
+ * @throws IllegalArgumentException If the types of the arguments do not match the parameter types of the method (this should not occur since it searches for a method with the types of the arguments)
+ * @throws InvocationTargetException If the desired method cannot be invoked on the target object
+ * @throws NoSuchMethodException If the desired method of the class of the target object with the specified name and arguments cannot be found
+ * @see #getMethod(Class, String, Class...)
+ * @see DataType#getPrimitive(Object[])
+ */
+ public static Object invokeMethod(Object instance, String methodName, Object... arguments) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException {
+ return getMethod(instance.getClass(), methodName, DataType.getPrimitive(arguments)).invoke(instance, arguments);
+ }
- /**
- * Invokes a method of the target class on an object with the given arguments
- *
- * @param instance Target object
- * @param clazz Target class
- * @param methodName Name of the desired method
- * @param arguments Arguments which are used to invoke the desired method
- * @return The result of invoking the desired method on the target object
- * @throws IllegalAccessException If the desired method cannot be accessed due to certain circumstances
- * @throws IllegalArgumentException If the types of the arguments do not match the parameter types of the method (this should not occur since it searches for a method with the types of the arguments)
- * @throws InvocationTargetException If the desired method cannot be invoked on the target object
- * @throws NoSuchMethodException If the desired method of the target class with the specified name and arguments cannot be found
- * @see #getMethod(Class, String, Class...)
- * @see DataType#getPrimitive(Object[])
- */
- public static Object invokeMethod(Object instance, Class> clazz, String methodName, Object... arguments) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException {
- return getMethod(clazz, methodName, DataType.getPrimitive(arguments)).invoke(instance, arguments);
- }
+ /**
+ * Invokes a method of the target class on an object with the given arguments
+ *
+ * @param instance Target object
+ * @param clazz Target class
+ * @param methodName Name of the desired method
+ * @param arguments Arguments which are used to invoke the desired method
+ * @return The result of invoking the desired method on the target object
+ * @throws IllegalAccessException If the desired method cannot be accessed due to certain circumstances
+ * @throws IllegalArgumentException If the types of the arguments do not match the parameter types of the method (this should not occur since it searches for a method with the types of the arguments)
+ * @throws InvocationTargetException If the desired method cannot be invoked on the target object
+ * @throws NoSuchMethodException If the desired method of the target class with the specified name and arguments cannot be found
+ * @see #getMethod(Class, String, Class...)
+ * @see DataType#getPrimitive(Object[])
+ */
+ public static Object invokeMethod(Object instance, Class> clazz, String methodName, Object... arguments) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException {
+ return getMethod(clazz, methodName, DataType.getPrimitive(arguments)).invoke(instance, arguments);
+ }
- /**
- * Invokes a method of a desired class on an object with the given arguments
- *
- * @param instance Target object
- * @param className Name of the desired target class
- * @param packageType Package where the desired target class is located
- * @param methodName Name of the desired method
- * @param arguments Arguments which are used to invoke the desired method
- * @return The result of invoking the desired method on the target object
- * @throws IllegalAccessException If the desired method cannot be accessed due to certain circumstances
- * @throws IllegalArgumentException If the types of the arguments do not match the parameter types of the method (this should not occur since it searches for a method with the types of the arguments)
- * @throws InvocationTargetException If the desired method cannot be invoked on the target object
- * @throws NoSuchMethodException If the desired method of the desired target class with the specified name and arguments cannot be found
- * @throws ClassNotFoundException If the desired target class with the specified name and package cannot be found
- * @see #invokeMethod(Object, Class, String, Object...)
- */
- public static Object invokeMethod(Object instance, String className, PackageType packageType, String methodName, Object... arguments) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException {
- return invokeMethod(instance, packageType.getClass(className), methodName, arguments);
- }
+ /**
+ * Invokes a method of a desired class on an object with the given arguments
+ *
+ * @param instance Target object
+ * @param className Name of the desired target class
+ * @param packageType Package where the desired target class is located
+ * @param methodName Name of the desired method
+ * @param arguments Arguments which are used to invoke the desired method
+ * @return The result of invoking the desired method on the target object
+ * @throws IllegalAccessException If the desired method cannot be accessed due to certain circumstances
+ * @throws IllegalArgumentException If the types of the arguments do not match the parameter types of the method (this should not occur since it searches for a method with the types of the arguments)
+ * @throws InvocationTargetException If the desired method cannot be invoked on the target object
+ * @throws NoSuchMethodException If the desired method of the desired target class with the specified name and arguments cannot be found
+ * @throws ClassNotFoundException If the desired target class with the specified name and package cannot be found
+ * @see #invokeMethod(Object, Class, String, Object...)
+ */
+ public static Object invokeMethod(Object instance, String className, PackageType packageType, String methodName, Object... arguments) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException {
+ return invokeMethod(instance, packageType.getClass(className), methodName, arguments);
+ }
- /**
- * Returns a field of the target class with the given name
- *
- * @param clazz Target class
- * @param declared Whether the desired field is declared or not
- * @param fieldName Name of the desired field
- * @return The field of the target class with the specified name
- * @throws NoSuchFieldException If the desired field of the given class cannot be found
- * @throws SecurityException If the desired field cannot be made accessible
- */
- public static Field getField(Class> clazz, boolean declared, String fieldName) throws NoSuchFieldException, SecurityException {
- Field field = declared ? clazz.getDeclaredField(fieldName) : clazz.getField(fieldName);
- field.setAccessible(true);
- return field;
- }
+ /**
+ * Returns a field of the target class with the given name
+ *
+ * @param clazz Target class
+ * @param declared Whether the desired field is declared or not
+ * @param fieldName Name of the desired field
+ * @return The field of the target class with the specified name
+ * @throws NoSuchFieldException If the desired field of the given class cannot be found
+ * @throws SecurityException If the desired field cannot be made accessible
+ */
+ public static Field getField(Class> clazz, boolean declared, String fieldName) throws NoSuchFieldException, SecurityException {
+ Field field = declared ? clazz.getDeclaredField(fieldName) : clazz.getField(fieldName);
+ field.setAccessible(true);
+ return field;
+ }
- /**
- * Returns a field of a desired class with the given name
- *
- * @param className Name of the desired target class
- * @param packageType Package where the desired target class is located
- * @param declared Whether the desired field is declared or not
- * @param fieldName Name of the desired field
- * @return The field of the desired target class with the specified name
- * @throws NoSuchFieldException If the desired field of the desired class cannot be found
- * @throws SecurityException If the desired field cannot be made accessible
- * @throws ClassNotFoundException If the desired target class with the specified name and package cannot be found
- * @see #getField(Class, boolean, String)
- */
- public static Field getField(String className, PackageType packageType, boolean declared, String fieldName) throws NoSuchFieldException, SecurityException, ClassNotFoundException {
- return getField(packageType.getClass(className), declared, fieldName);
- }
+ /**
+ * Returns a field of a desired class with the given name
+ *
+ * @param className Name of the desired target class
+ * @param packageType Package where the desired target class is located
+ * @param declared Whether the desired field is declared or not
+ * @param fieldName Name of the desired field
+ * @return The field of the desired target class with the specified name
+ * @throws NoSuchFieldException If the desired field of the desired class cannot be found
+ * @throws SecurityException If the desired field cannot be made accessible
+ * @throws ClassNotFoundException If the desired target class with the specified name and package cannot be found
+ * @see #getField(Class, boolean, String)
+ */
+ public static Field getField(String className, PackageType packageType, boolean declared, String fieldName) throws NoSuchFieldException, SecurityException, ClassNotFoundException {
+ return getField(packageType.getClass(className), declared, fieldName);
+ }
- /**
- * Returns the value of a field of the given class of an object
- *
- * @param instance Target object
- * @param clazz Target class
- * @param declared Whether the desired field is declared or not
- * @param fieldName Name of the desired field
- * @return The value of field of the target object
- * @throws IllegalArgumentException If the target object does not feature the desired field
- * @throws IllegalAccessException If the desired field cannot be accessed
- * @throws NoSuchFieldException If the desired field of the target class cannot be found
- * @throws SecurityException If the desired field cannot be made accessible
- * @see #getField(Class, boolean, String)
- */
- public static Object getValue(Object instance, Class> clazz, boolean declared, String fieldName) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {
- return getField(clazz, declared, fieldName).get(instance);
- }
+ /**
+ * Returns the value of a field of the given class of an object
+ *
+ * @param instance Target object
+ * @param clazz Target class
+ * @param declared Whether the desired field is declared or not
+ * @param fieldName Name of the desired field
+ * @return The value of field of the target object
+ * @throws IllegalArgumentException If the target object does not feature the desired field
+ * @throws IllegalAccessException If the desired field cannot be accessed
+ * @throws NoSuchFieldException If the desired field of the target class cannot be found
+ * @throws SecurityException If the desired field cannot be made accessible
+ * @see #getField(Class, boolean, String)
+ */
+ public static Object getValue(Object instance, Class> clazz, boolean declared, String fieldName) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {
+ return getField(clazz, declared, fieldName).get(instance);
+ }
- /**
- * Returns the value of a field of a desired class of an object
- *
- * @param instance Target object
- * @param className Name of the desired target class
- * @param packageType Package where the desired target class is located
- * @param declared Whether the desired field is declared or not
- * @param fieldName Name of the desired field
- * @return The value of field of the target object
- * @throws IllegalArgumentException If the target object does not feature the desired field
- * @throws IllegalAccessException If the desired field cannot be accessed
- * @throws NoSuchFieldException If the desired field of the desired class cannot be found
- * @throws SecurityException If the desired field cannot be made accessible
- * @throws ClassNotFoundException If the desired target class with the specified name and package cannot be found
- * @see #getValue(Object, Class, boolean, String)
- */
- public static Object getValue(Object instance, String className, PackageType packageType, boolean declared, String fieldName) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException, ClassNotFoundException {
- return getValue(instance, packageType.getClass(className), declared, fieldName);
- }
+ /**
+ * Returns the value of a field of a desired class of an object
+ *
+ * @param instance Target object
+ * @param className Name of the desired target class
+ * @param packageType Package where the desired target class is located
+ * @param declared Whether the desired field is declared or not
+ * @param fieldName Name of the desired field
+ * @return The value of field of the target object
+ * @throws IllegalArgumentException If the target object does not feature the desired field
+ * @throws IllegalAccessException If the desired field cannot be accessed
+ * @throws NoSuchFieldException If the desired field of the desired class cannot be found
+ * @throws SecurityException If the desired field cannot be made accessible
+ * @throws ClassNotFoundException If the desired target class with the specified name and package cannot be found
+ * @see #getValue(Object, Class, boolean, String)
+ */
+ public static Object getValue(Object instance, String className, PackageType packageType, boolean declared, String fieldName) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException, ClassNotFoundException {
+ return getValue(instance, packageType.getClass(className), declared, fieldName);
+ }
- /**
- * Returns the value of a field with the given name of an object
- *
- * @param instance Target object
- * @param declared Whether the desired field is declared or not
- * @param fieldName Name of the desired field
- * @return The value of field of the target object
- * @throws IllegalArgumentException If the target object does not feature the desired field (should not occur since it searches for a field with the given name in the class of the object)
- * @throws IllegalAccessException If the desired field cannot be accessed
- * @throws NoSuchFieldException If the desired field of the target object cannot be found
- * @throws SecurityException If the desired field cannot be made accessible
- * @see #getValue(Object, Class, boolean, String)
- */
- public static Object getValue(Object instance, boolean declared, String fieldName) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {
- return getValue(instance, instance.getClass(), declared, fieldName);
- }
+ /**
+ * Returns the value of a field with the given name of an object
+ *
+ * @param instance Target object
+ * @param declared Whether the desired field is declared or not
+ * @param fieldName Name of the desired field
+ * @return The value of field of the target object
+ * @throws IllegalArgumentException If the target object does not feature the desired field (should not occur since it searches for a field with the given name in the class of the object)
+ * @throws IllegalAccessException If the desired field cannot be accessed
+ * @throws NoSuchFieldException If the desired field of the target object cannot be found
+ * @throws SecurityException If the desired field cannot be made accessible
+ * @see #getValue(Object, Class, boolean, String)
+ */
+ public static Object getValue(Object instance, boolean declared, String fieldName) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {
+ return getValue(instance, instance.getClass(), declared, fieldName);
+ }
- /**
- * Sets the value of a field of the given class of an object
- *
- * @param instance Target object
- * @param clazz Target class
- * @param declared Whether the desired field is declared or not
- * @param fieldName Name of the desired field
- * @param value New value
- * @throws IllegalArgumentException If the type of the value does not match the type of the desired field
- * @throws IllegalAccessException If the desired field cannot be accessed
- * @throws NoSuchFieldException If the desired field of the target class cannot be found
- * @throws SecurityException If the desired field cannot be made accessible
- * @see #getField(Class, boolean, String)
- */
- public static void setValue(Object instance, Class> clazz, boolean declared, String fieldName, Object value) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {
- getField(clazz, declared, fieldName).set(instance, value);
- }
+ /**
+ * Sets the value of a field of the given class of an object
+ *
+ * @param instance Target object
+ * @param clazz Target class
+ * @param declared Whether the desired field is declared or not
+ * @param fieldName Name of the desired field
+ * @param value New value
+ * @throws IllegalArgumentException If the type of the value does not match the type of the desired field
+ * @throws IllegalAccessException If the desired field cannot be accessed
+ * @throws NoSuchFieldException If the desired field of the target class cannot be found
+ * @throws SecurityException If the desired field cannot be made accessible
+ * @see #getField(Class, boolean, String)
+ */
+ public static void setValue(Object instance, Class> clazz, boolean declared, String fieldName, Object value) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {
+ getField(clazz, declared, fieldName).set(instance, value);
+ }
- /**
- * Sets the value of a field of a desired class of an object
- *
- * @param instance Target object
- * @param className Name of the desired target class
- * @param packageType Package where the desired target class is located
- * @param declared Whether the desired field is declared or not
- * @param fieldName Name of the desired field
- * @param value New value
- * @throws IllegalArgumentException If the type of the value does not match the type of the desired field
- * @throws IllegalAccessException If the desired field cannot be accessed
- * @throws NoSuchFieldException If the desired field of the desired class cannot be found
- * @throws SecurityException If the desired field cannot be made accessible
- * @throws ClassNotFoundException If the desired target class with the specified name and package cannot be found
- * @see #setValue(Object, Class, boolean, String, Object)
- */
- public static void setValue(Object instance, String className, PackageType packageType, boolean declared, String fieldName, Object value) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException, ClassNotFoundException {
- setValue(instance, packageType.getClass(className), declared, fieldName, value);
- }
+ /**
+ * Sets the value of a field of a desired class of an object
+ *
+ * @param instance Target object
+ * @param className Name of the desired target class
+ * @param packageType Package where the desired target class is located
+ * @param declared Whether the desired field is declared or not
+ * @param fieldName Name of the desired field
+ * @param value New value
+ * @throws IllegalArgumentException If the type of the value does not match the type of the desired field
+ * @throws IllegalAccessException If the desired field cannot be accessed
+ * @throws NoSuchFieldException If the desired field of the desired class cannot be found
+ * @throws SecurityException If the desired field cannot be made accessible
+ * @throws ClassNotFoundException If the desired target class with the specified name and package cannot be found
+ * @see #setValue(Object, Class, boolean, String, Object)
+ */
+ public static void setValue(Object instance, String className, PackageType packageType, boolean declared, String fieldName, Object value) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException, ClassNotFoundException {
+ setValue(instance, packageType.getClass(className), declared, fieldName, value);
+ }
- /**
- * Sets the value of a field with the given name of an object
- *
- * @param instance Target object
- * @param declared Whether the desired field is declared or not
- * @param fieldName Name of the desired field
- * @param value New value
- * @throws IllegalArgumentException If the type of the value does not match the type of the desired field
- * @throws IllegalAccessException If the desired field cannot be accessed
- * @throws NoSuchFieldException If the desired field of the target object cannot be found
- * @throws SecurityException If the desired field cannot be made accessible
- * @see #setValue(Object, Class, boolean, String, Object)
- */
- public static void setValue(Object instance, boolean declared, String fieldName, Object value) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {
- setValue(instance, instance.getClass(), declared, fieldName, value);
- }
+ /**
+ * Sets the value of a field with the given name of an object
+ *
+ * @param instance Target object
+ * @param declared Whether the desired field is declared or not
+ * @param fieldName Name of the desired field
+ * @param value New value
+ * @throws IllegalArgumentException If the type of the value does not match the type of the desired field
+ * @throws IllegalAccessException If the desired field cannot be accessed
+ * @throws NoSuchFieldException If the desired field of the target object cannot be found
+ * @throws SecurityException If the desired field cannot be made accessible
+ * @see #setValue(Object, Class, boolean, String, Object)
+ */
+ public static void setValue(Object instance, boolean declared, String fieldName, Object value) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {
+ setValue(instance, instance.getClass(), declared, fieldName, value);
+ }
- /**
- * Represents an enumeration of dynamic packages of NMS and CraftBukkit
- *
- * This class is part of the ReflectionUtils and follows the same usage conditions
- *
- * @author DarkBlade12
- * @since 1.0
- */
- public enum PackageType {
- MINECRAFT_SERVER("net.minecraft.server." + getServerVersion()),
- CRAFTBUKKIT("org.bukkit.craftbukkit." + getServerVersion()),
- CRAFTBUKKIT_BLOCK(CRAFTBUKKIT, "block"),
- CRAFTBUKKIT_CHUNKIO(CRAFTBUKKIT, "chunkio"),
- CRAFTBUKKIT_COMMAND(CRAFTBUKKIT, "command"),
- CRAFTBUKKIT_CONVERSATIONS(CRAFTBUKKIT, "conversations"),
- CRAFTBUKKIT_ENCHANTMENS(CRAFTBUKKIT, "enchantments"),
- CRAFTBUKKIT_ENTITY(CRAFTBUKKIT, "entity"),
- CRAFTBUKKIT_EVENT(CRAFTBUKKIT, "event"),
- CRAFTBUKKIT_GENERATOR(CRAFTBUKKIT, "generator"),
- CRAFTBUKKIT_HELP(CRAFTBUKKIT, "help"),
- CRAFTBUKKIT_INVENTORY(CRAFTBUKKIT, "inventory"),
- CRAFTBUKKIT_MAP(CRAFTBUKKIT, "map"),
- CRAFTBUKKIT_METADATA(CRAFTBUKKIT, "metadata"),
- CRAFTBUKKIT_POTION(CRAFTBUKKIT, "potion"),
- CRAFTBUKKIT_PROJECTILES(CRAFTBUKKIT, "projectiles"),
- CRAFTBUKKIT_SCHEDULER(CRAFTBUKKIT, "scheduler"),
- CRAFTBUKKIT_SCOREBOARD(CRAFTBUKKIT, "scoreboard"),
- CRAFTBUKKIT_UPDATER(CRAFTBUKKIT, "updater"),
- CRAFTBUKKIT_UTIL(CRAFTBUKKIT, "util");
+ /**
+ * Represents an enumeration of dynamic packages of NMS and CraftBukkit
+ *
+ * This class is part of the ReflectionUtils and follows the same usage conditions
+ *
+ * @author DarkBlade12
+ * @since 1.0
+ */
+ public enum PackageType {
+ MINECRAFT_SERVER("net.minecraft.server." + getServerVersion()),
+ CRAFTBUKKIT("org.bukkit.craftbukkit." + getServerVersion()),
+ CRAFTBUKKIT_BLOCK(CRAFTBUKKIT, "block"),
+ CRAFTBUKKIT_CHUNKIO(CRAFTBUKKIT, "chunkio"),
+ CRAFTBUKKIT_COMMAND(CRAFTBUKKIT, "command"),
+ CRAFTBUKKIT_CONVERSATIONS(CRAFTBUKKIT, "conversations"),
+ CRAFTBUKKIT_ENCHANTMENS(CRAFTBUKKIT, "enchantments"),
+ CRAFTBUKKIT_ENTITY(CRAFTBUKKIT, "entity"),
+ CRAFTBUKKIT_EVENT(CRAFTBUKKIT, "event"),
+ CRAFTBUKKIT_GENERATOR(CRAFTBUKKIT, "generator"),
+ CRAFTBUKKIT_HELP(CRAFTBUKKIT, "help"),
+ CRAFTBUKKIT_INVENTORY(CRAFTBUKKIT, "inventory"),
+ CRAFTBUKKIT_MAP(CRAFTBUKKIT, "map"),
+ CRAFTBUKKIT_METADATA(CRAFTBUKKIT, "metadata"),
+ CRAFTBUKKIT_POTION(CRAFTBUKKIT, "potion"),
+ CRAFTBUKKIT_PROJECTILES(CRAFTBUKKIT, "projectiles"),
+ CRAFTBUKKIT_SCHEDULER(CRAFTBUKKIT, "scheduler"),
+ CRAFTBUKKIT_SCOREBOARD(CRAFTBUKKIT, "scoreboard"),
+ CRAFTBUKKIT_UPDATER(CRAFTBUKKIT, "updater"),
+ CRAFTBUKKIT_UTIL(CRAFTBUKKIT, "util");
- private final String path;
+ private final String path;
- /**
- * Construct a new package type
- *
- * @param path Path of the package
- */
- PackageType(String path) {
- this.path = path;
- }
+ /**
+ * Construct a new package type
+ *
+ * @param path Path of the package
+ */
+ PackageType(String path) {
+ this.path = path;
+ }
- /**
- * Construct a new package type
- *
- * @param parent Parent package of the package
- * @param path Path of the package
- */
- PackageType(PackageType parent, String path) {
- this(parent + "." + path);
- }
+ /**
+ * Construct a new package type
+ *
+ * @param parent Parent package of the package
+ * @param path Path of the package
+ */
+ PackageType(PackageType parent, String path) {
+ this(parent + "." + path);
+ }
- /**
- * Returns the path of this package type
- *
- * @return The path
- */
- public String getPath() {
- return path;
- }
+ /**
+ * Returns the path of this package type
+ *
+ * @return The path
+ */
+ public String getPath() {
+ return path;
+ }
- /**
- * Returns the class with the given name
- *
- * @param className Name of the desired class
- * @return The class with the specified name
- * @throws ClassNotFoundException If the desired class with the specified name and package cannot be found
- */
- public Class> getClass(String className) throws ClassNotFoundException {
- return Class.forName(this + "." + className);
- }
+ /**
+ * Returns the class with the given name
+ *
+ * @param className Name of the desired class
+ * @return The class with the specified name
+ * @throws ClassNotFoundException If the desired class with the specified name and package cannot be found
+ */
+ public Class> getClass(String className) throws ClassNotFoundException {
+ return Class.forName(this + "." + className);
+ }
- // Override for convenience
- @Override
- public String toString() {
- return path;
- }
+ // Override for convenience
+ @Override
+ public String toString() {
+ return path;
+ }
- /**
- * Returns the version of your server
- *
- * @return The server version
- */
- public static String getServerVersion() {
- return Bukkit.getServer().getClass().getPackage().getName().substring(23);
- }
- }
+ /**
+ * Returns the version of your server
+ *
+ * @return The server version
+ */
+ public static String getServerVersion() {
+ return Bukkit.getServer().getClass().getPackage().getName().substring(23);
+ }
+ }
- /**
- * Represents an enumeration of Java data types with corresponding classes
- *
- * This class is part of the ReflectionUtils and follows the same usage conditions
- *
- * @author DarkBlade12
- * @since 1.0
- */
- public enum DataType {
- BYTE(byte.class, Byte.class),
- SHORT(short.class, Short.class),
- INTEGER(int.class, Integer.class),
- LONG(long.class, Long.class),
- CHARACTER(char.class, Character.class),
- FLOAT(float.class, Float.class),
- DOUBLE(double.class, Double.class),
- BOOLEAN(boolean.class, Boolean.class);
+ /**
+ * Represents an enumeration of Java data types with corresponding classes
+ *
+ * This class is part of the ReflectionUtils and follows the same usage conditions
+ *
+ * @author DarkBlade12
+ * @since 1.0
+ */
+ public enum DataType {
+ BYTE(byte.class, Byte.class),
+ SHORT(short.class, Short.class),
+ INTEGER(int.class, Integer.class),
+ LONG(long.class, Long.class),
+ CHARACTER(char.class, Character.class),
+ FLOAT(float.class, Float.class),
+ DOUBLE(double.class, Double.class),
+ BOOLEAN(boolean.class, Boolean.class);
- private static final Map, DataType> CLASS_MAP = new HashMap<>();
- private final Class> primitive;
- private final Class> reference;
+ private static final Map, DataType> CLASS_MAP = new HashMap<>();
+ private final Class> primitive;
+ private final Class> reference;
- // Initialize map for quick class lookup
- static {
- for (DataType type : values()) {
- CLASS_MAP.put(type.primitive, type);
- CLASS_MAP.put(type.reference, type);
- }
- }
+ // Initialize map for quick class lookup
+ static {
+ for (DataType type : values()) {
+ CLASS_MAP.put(type.primitive, type);
+ CLASS_MAP.put(type.reference, type);
+ }
+ }
- /**
- * Construct a new data type
- *
- * @param primitive Primitive class of this data type
- * @param reference Reference class of this data type
- */
- DataType(Class> primitive, Class> reference) {
- this.primitive = primitive;
- this.reference = reference;
- }
+ /**
+ * Construct a new data type
+ *
+ * @param primitive Primitive class of this data type
+ * @param reference Reference class of this data type
+ */
+ DataType(Class> primitive, Class> reference) {
+ this.primitive = primitive;
+ this.reference = reference;
+ }
- /**
- * Returns the primitive class of this data type
- *
- * @return The primitive class
- */
- public Class> getPrimitive() {
- return primitive;
- }
+ /**
+ * Returns the primitive class of this data type
+ *
+ * @return The primitive class
+ */
+ public Class> getPrimitive() {
+ return primitive;
+ }
- /**
- * Returns the reference class of this data type
- *
- * @return The reference class
- */
- public Class> getReference() {
- return reference;
- }
+ /**
+ * Returns the reference class of this data type
+ *
+ * @return The reference class
+ */
+ public Class> getReference() {
+ return reference;
+ }
- /**
- * Returns the data type with the given primitive/reference class
- *
- * @param clazz Primitive/Reference class of the data type
- * @return The data type
- */
- public static DataType fromClass(Class> clazz) {
- return CLASS_MAP.get(clazz);
- }
+ /**
+ * Returns the data type with the given primitive/reference class
+ *
+ * @param clazz Primitive/Reference class of the data type
+ * @return The data type
+ */
+ public static DataType fromClass(Class> clazz) {
+ return CLASS_MAP.get(clazz);
+ }
- /**
- * Returns the primitive class of the data type with the given reference class
- *
- * @param clazz Reference class of the data type
- * @return The primitive class
- */
- public static Class> getPrimitive(Class> clazz) {
- DataType type = fromClass(clazz);
- return type == null ? clazz : type.getPrimitive();
- }
+ /**
+ * Returns the primitive class of the data type with the given reference class
+ *
+ * @param clazz Reference class of the data type
+ * @return The primitive class
+ */
+ public static Class> getPrimitive(Class> clazz) {
+ DataType type = fromClass(clazz);
+ return type == null ? clazz : type.getPrimitive();
+ }
- /**
- * Returns the reference class of the data type with the given primitive class
- *
- * @param clazz Primitive class of the data type
- * @return The reference class
- */
- public static Class> getReference(Class> clazz) {
- DataType type = fromClass(clazz);
- return type == null ? clazz : type.getReference();
- }
+ /**
+ * Returns the reference class of the data type with the given primitive class
+ *
+ * @param clazz Primitive class of the data type
+ * @return The reference class
+ */
+ public static Class> getReference(Class> clazz) {
+ DataType type = fromClass(clazz);
+ return type == null ? clazz : type.getReference();
+ }
- /**
- * Returns the primitive class array of the given class array
- *
- * @param classes Given class array
- * @return The primitive class array
- */
- public static Class>[] getPrimitive(Class>[] classes) {
- int length = classes == null ? 0 : classes.length;
- Class>[] types = new Class>[length];
- for (int index = 0; index < length; index++) {
- types[index] = getPrimitive(classes[index]);
- }
- return types;
- }
+ /**
+ * Returns the primitive class array of the given class array
+ *
+ * @param classes Given class array
+ * @return The primitive class array
+ */
+ public static Class>[] getPrimitive(Class>[] classes) {
+ int length = classes == null ? 0 : classes.length;
+ Class>[] types = new Class>[length];
+ for (int index = 0; index < length; index++) {
+ types[index] = getPrimitive(classes[index]);
+ }
+ return types;
+ }
- /**
- * Returns the reference class array of the given class array
- *
- * @param classes Given class array
- * @return The reference class array
- */
- public static Class>[] getReference(Class>[] classes) {
- int length = classes == null ? 0 : classes.length;
- Class>[] types = new Class>[length];
- for (int index = 0; index < length; index++) {
- types[index] = getReference(classes[index]);
- }
- return types;
- }
+ /**
+ * Returns the reference class array of the given class array
+ *
+ * @param classes Given class array
+ * @return The reference class array
+ */
+ public static Class>[] getReference(Class>[] classes) {
+ int length = classes == null ? 0 : classes.length;
+ Class>[] types = new Class>[length];
+ for (int index = 0; index < length; index++) {
+ types[index] = getReference(classes[index]);
+ }
+ return types;
+ }
- /**
- * Returns the primitive class array of the given object array
- *
- * @return The primitive class array
- */
- public static Class>[] getPrimitive(Object[] objects) {
- int length = objects == null ? 0 : objects.length;
- Class>[] types = new Class>[length];
- for (int index = 0; index < length; index++) {
- types[index] = getPrimitive(objects[index].getClass());
- }
- return types;
- }
+ /**
+ * Returns the primitive class array of the given object array
+ *
+ * @return The primitive class array
+ */
+ public static Class>[] getPrimitive(Object[] objects) {
+ int length = objects == null ? 0 : objects.length;
+ Class>[] types = new Class>[length];
+ for (int index = 0; index < length; index++) {
+ types[index] = getPrimitive(objects[index].getClass());
+ }
+ return types;
+ }
- /**
- * Returns the reference class array of the given object array
- *
- * @return The reference class array
- */
- public static Class>[] getReference(Object[] objects) {
- int length = objects == null ? 0 : objects.length;
- Class>[] types = new Class>[length];
- for (int index = 0; index < length; index++) {
- types[index] = getReference(objects[index].getClass());
- }
- return types;
- }
+ /**
+ * Returns the reference class array of the given object array
+ *
+ * @return The reference class array
+ */
+ public static Class>[] getReference(Object[] objects) {
+ int length = objects == null ? 0 : objects.length;
+ Class>[] types = new Class>[length];
+ for (int index = 0; index < length; index++) {
+ types[index] = getReference(objects[index].getClass());
+ }
+ return types;
+ }
- /**
- * Compares two class arrays on equivalence
- *
- * @param primary Primary class array
- * @param secondary Class array which is compared to the primary array
- * @return Whether these arrays are equal or not
- */
- public static boolean compare(Class>[] primary, Class>[] secondary) {
- if (primary == null || secondary == null || primary.length != secondary.length) {
- return false;
- }
- for (int index = 0; index < primary.length; index++) {
- Class> primaryClass = primary[index];
- Class> secondaryClass = secondary[index];
- if (primaryClass.equals(secondaryClass) || primaryClass.isAssignableFrom(secondaryClass)) {
- continue;
- }
- return false;
- }
- return true;
- }
- }
+ /**
+ * Compares two class arrays on equivalence
+ *
+ * @param primary Primary class array
+ * @param secondary Class array which is compared to the primary array
+ * @return Whether these arrays are equal or not
+ */
+ public static boolean compare(Class>[] primary, Class>[] secondary) {
+ if (primary == null || secondary == null || primary.length != secondary.length) {
+ return false;
+ }
+ for (int index = 0; index < primary.length; index++) {
+ Class> primaryClass = primary[index];
+ Class> secondaryClass = secondary[index];
+ if (primaryClass.equals(secondaryClass) || primaryClass.isAssignableFrom(secondaryClass)) {
+ continue;
+ }
+ return false;
+ }
+ return true;
+ }
+ }
}
\ No newline at end of file
diff --git a/src/main/java/me/skymc/taboolib/mysql/builder/SQLColumn.java b/src/main/java/me/skymc/taboolib/mysql/builder/SQLColumn.java
index cf7ce3f..dd6463f 100644
--- a/src/main/java/me/skymc/taboolib/mysql/builder/SQLColumn.java
+++ b/src/main/java/me/skymc/taboolib/mysql/builder/SQLColumn.java
@@ -22,7 +22,7 @@ public class SQLColumn {
private SQLColumnOption[] columnOptions;
/**
- * 文本类型常用构造器
+ * 文本 类型常用构造器
* new SQLColumn(SQLColumnType.TEXT, "username");
*/
public SQLColumn(SQLColumnType columnType, String columnName) {
@@ -30,7 +30,17 @@ public class SQLColumn {
}
/**
- * 主键类型常用构造器
+ * CHAR 类型常用构造器
+ *
+ * @param columnType
+ * @param columnName
+ */
+ public SQLColumn(SQLColumnType columnType, int m, String columnName) {
+ this(columnType, m, 0, columnName, null);
+ }
+
+ /**
+ * 主键 类型常用构造器
* new SQLColumn(SQLColumnType.TEXT, "username", SQLColumnOption.PRIMARY_KEY, SQLColumnOption.AUTO_INCREMENT);
*/
public SQLColumn(SQLColumnType columnType, String columnName, SQLColumnOption... columnOptions) {
@@ -38,7 +48,7 @@ public class SQLColumn {
}
/**
- * 数据类型常用构造器
+ * 数据 类型常用构造器
* new SQLColumn(SQLColumnType.TEXT, "player_group", "PLAYER");
*/
public SQLColumn(SQLColumnType columnType, String columnName, Object defaultValue) {
@@ -99,25 +109,25 @@ public class SQLColumn {
for (SQLColumnOption options : columnOptions) {
switch (options) {
case NOTNULL:
- builder.append(" not null");
+ builder.append(" NOT NULL");
break;
case PRIMARY_KEY:
- builder.append(" primary key");
+ builder.append(" PRIMARY KEY");
break;
case AUTO_INCREMENT:
- builder.append(" auto_increment");
+ builder.append(" AUTO_INCREMENT");
break;
case UNIQUE_KEY:
- builder.append(" unique key");
+ builder.append(" UNIQUE KEY");
break;
default:
}
}
if (defaultValue != null) {
if (defaultValue instanceof String) {
- builder.append(" default '").append(defaultValue).append("'");
+ builder.append(" DEFAULT '").append(defaultValue).append("'");
} else {
- builder.append(" default ").append(defaultValue);
+ builder.append(" DEFAULT ").append(defaultValue);
}
}
return builder.toString();
diff --git a/src/main/java/me/skymc/taboolib/mysql/builder/SQLExample.java b/src/main/java/me/skymc/taboolib/mysql/builder/SQLExample.java
deleted file mode 100644
index e6dc79a..0000000
--- a/src/main/java/me/skymc/taboolib/mysql/builder/SQLExample.java
+++ /dev/null
@@ -1,31 +0,0 @@
-package me.skymc.taboolib.mysql.builder;
-
-import com.zaxxer.hikari.HikariDataSource;
-import org.bukkit.plugin.java.JavaPlugin;
-
-/**
- * @Author sky
- * @Since 2018-07-02 23:43
- */
-public class SQLExample extends JavaPlugin {
-
- private SQLHost sqlHost;
- private SQLTable sqlTable;
- private HikariDataSource dataSource;
-
- @Override
- public void onEnable() {
- int value = sqlTable.executeQuery("select * from table where username = ?")
- .dataSource(dataSource)
- .statement(statement -> statement.setString(1, "BlackSKY"))
- .resultNext(result -> result.getInt("value"))
- .run(0, 0);
-
- sqlTable.executeUpdate("statement table set value = ? where username = ?")
- .dataSource(dataSource)
- .statement(statement -> {
- statement.setInt(1, 999);
- statement.setString(2, "BlackSKY");
- }).run();
- }
-}
diff --git a/src/main/java/me/skymc/taboolib/mysql/builder/SQLHost.java b/src/main/java/me/skymc/taboolib/mysql/builder/SQLHost.java
index 13e9c15..a0195bb 100644
--- a/src/main/java/me/skymc/taboolib/mysql/builder/SQLHost.java
+++ b/src/main/java/me/skymc/taboolib/mysql/builder/SQLHost.java
@@ -4,7 +4,6 @@ import com.ilummc.tlib.util.Strings;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.plugin.Plugin;
-import java.text.MessageFormat;
import java.util.Objects;
/**
@@ -19,18 +18,28 @@ public class SQLHost {
private String password;
private String database;
private Plugin plugin;
+ private boolean autoClose;
public SQLHost(ConfigurationSection section, Plugin plugin) {
+ this(section, plugin, false);
+ }
+
+ public SQLHost(ConfigurationSection section, Plugin plugin, boolean autoClose) {
this(section.getString("host", "localhost"), section.getString("user", "root"), section.getString("port", "3306"), section.getString("password", ""), section.getString("database", "test"), plugin);
}
public SQLHost(String host, String user, String port, String password, String database, Plugin plugin) {
+ this(host, user, port, password, database, plugin, false);
+ }
+
+ public SQLHost(String host, String user, String port, String password, String database, Plugin plugin, boolean autoClose) {
this.host = host;
this.user = user;
this.port = port;
this.password = password;
this.database = database;
this.plugin = plugin;
+ this.autoClose = false;
}
public String getHost() {
@@ -57,6 +66,10 @@ public class SQLHost {
return plugin;
}
+ public boolean isAutoClose() {
+ return autoClose;
+ }
+
public String getConnectionUrl() {
return Strings.replaceWithOrder("jdbc:mysql://{0}:{1}/{2}?characterEncoding=utf-8&useSSL=false", this.host, this.port, this.database);
}
@@ -74,16 +87,18 @@ public class SQLHost {
return false;
}
SQLHost sqlHost = (SQLHost) o;
- return Objects.equals(getHost(), sqlHost.getHost()) &&
+ return autoClose == sqlHost.autoClose &&
+ Objects.equals(getHost(), sqlHost.getHost()) &&
Objects.equals(getUser(), sqlHost.getUser()) &&
Objects.equals(getPort(), sqlHost.getPort()) &&
Objects.equals(getPassword(), sqlHost.getPassword()) &&
- Objects.equals(getDatabase(), sqlHost.getDatabase());
+ Objects.equals(getDatabase(), sqlHost.getDatabase()) &&
+ Objects.equals(getPlugin(), sqlHost.getPlugin());
}
@Override
public int hashCode() {
- return Objects.hash(getHost(), getUser(), getPort(), getPassword(), getDatabase());
+ return Objects.hash(getHost(), getUser(), getPort(), getPassword(), getDatabase(), getPlugin(), autoClose);
}
@Override
@@ -95,6 +110,7 @@ public class SQLHost {
", password='" + password + '\'' +
", database='" + database + '\'' +
", plugin=" + plugin +
+ ", autoClose=" + autoClose +
'}';
}
}
diff --git a/src/main/java/me/skymc/taboolib/mysql/builder/SQLTable.java b/src/main/java/me/skymc/taboolib/mysql/builder/SQLTable.java
index ed2e5f5..d61e5fd 100644
--- a/src/main/java/me/skymc/taboolib/mysql/builder/SQLTable.java
+++ b/src/main/java/me/skymc/taboolib/mysql/builder/SQLTable.java
@@ -26,11 +26,7 @@ public class SQLTable {
}
public SQLTable addColumn(SQLColumn sqlColumn) {
- if (columns == null) {
- columns = new SQLColumn[] {sqlColumn};
- } else {
- columns = ArrayUtils.arrayAppend(columns, sqlColumn);
- }
+ columns = columns == null ? new SQLColumn[] {sqlColumn} : ArrayUtils.arrayAppend(columns, sqlColumn);
return this;
}
@@ -52,6 +48,22 @@ public class SQLTable {
return Strings.replaceWithOrder("truncate table `{0}`", tableName);
}
+ public RunnableUpdate executeInsert(String values) {
+ return executeUpdate("insert into " + tableName + " values(" + values + ")");
+ }
+
+ public RunnableQuery executeSelect(String where) {
+ return executeQuery("select * from " + tableName + " where " + where);
+ }
+
+ public RunnableQuery executeSelect() {
+ return executeQuery("select * from " + tableName);
+ }
+
+ public RunnableUpdate executeUpdate(String update, String where) {
+ return executeUpdate("update " + tableName + " set " + update + " where " + where);
+ }
+
public RunnableUpdate executeUpdate(String query) {
return new RunnableUpdate(query);
}
diff --git a/src/main/java/me/skymc/taboolib/mysql/hikari/HikariHandler.java b/src/main/java/me/skymc/taboolib/mysql/hikari/HikariHandler.java
index 410c3f5..a422313 100644
--- a/src/main/java/me/skymc/taboolib/mysql/hikari/HikariHandler.java
+++ b/src/main/java/me/skymc/taboolib/mysql/hikari/HikariHandler.java
@@ -6,10 +6,8 @@ import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import me.skymc.taboolib.Main;
import me.skymc.taboolib.fileutils.ConfigUtils;
-import me.skymc.taboolib.fileutils.FileUtils;
import me.skymc.taboolib.mysql.builder.SQLHost;
import org.bukkit.configuration.file.FileConfiguration;
-import org.bukkit.configuration.file.YamlConfiguration;
import javax.sql.DataSource;
import java.util.concurrent.ConcurrentHashMap;
@@ -91,4 +89,18 @@ public class HikariHandler {
}
return config;
}
+
+ // *********************************
+ //
+ // Getter and Setter
+ //
+ // *********************************
+
+ public static ConcurrentHashMap getDataSource() {
+ return dataSource;
+ }
+
+ public static FileConfiguration getSettings() {
+ return settings;
+ }
}
diff --git a/src/main/java/me/skymc/taboolib/object/Instantiable.java b/src/main/java/me/skymc/taboolib/object/Instantiable.java
new file mode 100644
index 0000000..fb7e32e
--- /dev/null
+++ b/src/main/java/me/skymc/taboolib/object/Instantiable.java
@@ -0,0 +1,18 @@
+package me.skymc.taboolib.object;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * @Author sky
+ * @Since 2018-08-27 10:04
+ */
+@Target(ElementType.TYPE)
+@Retention(RetentionPolicy.RUNTIME)
+public @interface Instantiable {
+
+ String value();
+
+}
diff --git a/src/main/java/me/skymc/taboolib/object/InstantiableLoader.java b/src/main/java/me/skymc/taboolib/object/InstantiableLoader.java
new file mode 100644
index 0000000..45e7c0d
--- /dev/null
+++ b/src/main/java/me/skymc/taboolib/object/InstantiableLoader.java
@@ -0,0 +1,82 @@
+package me.skymc.taboolib.object;
+
+import com.ilummc.tlib.util.Ref;
+import me.skymc.taboolib.TabooLibLoader;
+import me.skymc.taboolib.listener.TListener;
+import me.skymc.taboolib.methods.ReflectionUtils;
+import org.bukkit.Bukkit;
+import org.bukkit.event.EventHandler;
+import org.bukkit.event.Listener;
+import org.bukkit.event.server.PluginDisableEvent;
+import org.bukkit.event.server.PluginEnableEvent;
+import org.bukkit.plugin.Plugin;
+
+import java.util.Optional;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * @Author sky
+ * @Since 2018-08-27 10:04
+ */
+@TListener
+public class InstantiableLoader implements Listener {
+
+ private static ConcurrentHashMap instance = new ConcurrentHashMap<>();
+
+ public InstantiableLoader() {
+ loadInstantiable();
+ }
+
+ @EventHandler
+ public void onEnable(PluginEnableEvent e) {
+ loadInstantiable(e.getPlugin());
+ }
+
+ @EventHandler
+ public void onDisable(PluginDisableEvent e) {
+ clear(e.getPlugin());
+ }
+
+ public static void clear(Plugin plugin) {
+ instance.entrySet().stream().filter(entry -> Ref.getCallerPlugin(entry.getValue().getClass()).equals(plugin)).forEach(entry -> instance.remove(entry.getKey()));
+ }
+
+ public static void loadInstantiable() {
+ for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
+ try {
+ loadInstantiable(plugin);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ public static void loadInstantiable(Plugin plugin) {
+ TabooLibLoader.getPluginClasses(plugin).ifPresent(classes -> {
+ for (Class pluginClass : classes) {
+ if (pluginClass.isAnnotationPresent(Instantiable.class)) {
+ Instantiable instantiable = (Instantiable) pluginClass.getAnnotation(Instantiable.class);
+ try {
+ instance.put(instantiable.value(), ReflectionUtils.instantiateObject(pluginClass));
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ });
+ }
+
+ // *********************************
+ //
+ // Getter and Setter
+ //
+ // *********************************
+
+ public static ConcurrentHashMap getInstance() {
+ return instance;
+ }
+
+ public static Optional