因 Idea 内置 Github 客户端的问题导致部分代码出错

以下类中的代码回档至上次提交时间:
- ItemUtils
- TConfigInjector
- Langauge2Format
This commit is contained in:
坏黑 2018-05-23 21:32:48 +08:00
parent 0acf324b15
commit fb38ef8977
3 changed files with 595 additions and 633 deletions

View File

@ -1,61 +1,113 @@
package com.ilummc.tlib.inject;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;
import com.ilummc.tlib.TLib;
import com.ilummc.tlib.annotations.Config;
import com.ilummc.tlib.bean.Property;
import com.ilummc.tlib.annotations.TConfig;
import com.ilummc.tlib.resources.TLocale;
import me.skymc.taboolib.fileutils.ConfigUtils;
import org.apache.commons.lang3.Validate;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.bukkit.configuration.serialization.ConfigurationSerialization;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.nio.charset.Charset;
import java.util.*;
import java.util.stream.Collectors;
import java.util.HashMap;
import java.util.Map;
public class TConfigInjector {
public static void fixUnicode(YamlConfiguration configuration) {
try {
Field field = YamlConfiguration.class.getDeclaredField("yamlOptions");
field.setAccessible(true);
field.set(configuration, NoUnicodeDumperOption.INSTANCE);
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
}
private static final class NoUnicodeDumperOption extends DumperOptions {
private static final NoUnicodeDumperOption INSTANCE = new NoUnicodeDumperOption();
@Override
public void setAllowUnicode(boolean allowUnicode) {
super.setAllowUnicode(false);
}
@Override
public boolean isAllowUnicode() {
return false;
}
@Override
public void setLineBreak(LineBreak lineBreak) {
super.setLineBreak(LineBreak.getPlatformLineBreak());
}
}
public static Object loadConfig(Plugin plugin, Class<?> clazz) {
try {
Config config = clazz.getAnnotation(Config.class);
TConfig config = clazz.getAnnotation(TConfig.class);
Validate.notNull(config);
File file = new File(plugin.getDataFolder(), config.name());
if (!file.exists()) if (config.fromJar()) plugin.saveResource(config.name(), true);
else saveConfig(plugin, clazz.newInstance());
return unserialize(plugin, clazz);
if (!file.exists()) {
if (config.fromJar()) {
plugin.saveResource(config.name(), true);
} else {
saveConfig(plugin, clazz.newInstance());
}
}
Object obj = unserialize(plugin, clazz);
if (config.readOnly()) {
saveConfig(plugin, obj);
}
return obj;
} catch (NullPointerException e) {
TLib.getTLib().getLogger().warn("插件 " + plugin + " 的配置类 " + clazz.getSimpleName() + " 加载失败:没有 @Config 注解");
TLocale.Logger.warn("CONFIG.LOAD-FAIL-NO-ANNOTATION", plugin.toString(), clazz.getSimpleName());
} catch (Exception e) {
TLib.getTLib().getLogger().warn("插件 " + plugin + " 的配置类 " + clazz.getSimpleName() + " 加载失败");
TLocale.Logger.warn("CONFIG.LOAD-FAIL", plugin.toString(), clazz.getSimpleName());
}
return null;
}
public static void reloadConfig(Plugin plugin, Object object) {
try {
TConfig config = object.getClass().getAnnotation(TConfig.class);
Validate.notNull(config);
File file = new File(plugin.getDataFolder(), config.name());
Map<String, Object> map = ConfigUtils.confToMap(ConfigUtils.loadYaml(plugin, file));
Object obj = ConfigUtils.mapToObj(map, object);
if (config.readOnly()) {
saveConfig(plugin, obj);
}
} catch (NullPointerException e) {
TLocale.Logger.warn("CONFIG.LOAD-FAIL-NO-ANNOTATION", plugin.toString(), object.getClass().getSimpleName());
} catch (Exception e) {
TLocale.Logger.warn("CONFIG.LOAD-FAIL", plugin.toString(), object.getClass().getSimpleName());
}
}
public static Object unserialize(Plugin plugin, Class<?> clazz) {
try {
Config config = clazz.getAnnotation(Config.class);
TConfig config = clazz.getAnnotation(TConfig.class);
Validate.notNull(config);
return new GsonBuilder().disableHtmlEscaping().excludeFieldsWithModifiers(config.excludeModifiers())
.create().fromJson(new Gson().toJson(new Yaml()
.dump(Files.toString(new File(plugin.getDataFolder(), config.name()), Charset.forName(config.charset())))), clazz);
return ConfigUtils.confToObj(
ConfigUtils.mapToConf(
ConfigUtils.yamlToMap(
Files.toString(new File(plugin.getDataFolder(), config.name()), Charset.forName(config.charset())))), clazz);
} catch (NullPointerException e) {
TLib.getTLib().getLogger().warn("插件 " + plugin + " 的配置类 " + clazz.getSimpleName() + " 加载失败:没有 @Config 注解或文件不存在");
TLocale.Logger.warn("CONFIG.LOAD-FAIL-NO-FILE", plugin.toString(), clazz.getSimpleName());
return null;
} catch (Exception e) {
try {
return clazz.newInstance();
} catch (InstantiationException | IllegalAccessException e1) {
TLib.getTLib().getLogger().warn("插件 " + plugin + " 的配置类 " + clazz.getSimpleName() + " 加载失败");
TLocale.Logger.warn("CONFIG.LOAD-FAIL", plugin.toString(), clazz.getSimpleName());
return null;
}
}
@ -63,95 +115,29 @@ public class TConfigInjector {
public static Map<String, Object> serialize(Plugin plugin, Object object) {
try {
Config config = object.getClass().getAnnotation(Config.class);
TConfig config = object.getClass().getAnnotation(TConfig.class);
Validate.notNull(config);
return new Serializer(new LinkedHashMap<>(), object, config.excludeModifiers()).get();
return ConfigUtils.objToMap(ConfigUtils.objToConf(object).getValues(false), config.excludeModifiers());
} catch (NullPointerException e) {
TLib.getTLib().getLogger().warn("插件 " + plugin + " 的配置类 " + object.getClass().getSimpleName() + " 序列化失败:没有 @Config 注解");
TLocale.Logger.warn("CONFIG.SAVE-FAIL-NO-ANNOTATION", plugin.toString(), object.getClass().getSimpleName());
} catch (Exception e) {
TLib.getTLib().getLogger().warn("插件 " + plugin + " 的配置类 " + object.getClass().getSimpleName() + " 序列化失败");
TLocale.Logger.warn("CONFIG.SAVE-FAIL", plugin.toString(), object.getClass().getSimpleName());
}
return null;
}
public static void saveConfig(Plugin plugin, Object object) throws IOException, NullPointerException {
Config config = object.getClass().getAnnotation(Config.class);
TConfig config = object.getClass().getAnnotation(TConfig.class);
Validate.notNull(config);
Object obj = serialize(plugin, object);
Validate.notNull(obj);
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
Map map = gson.fromJson(gson.toJson(object), HashMap.class);
YamlConfiguration configuration = (YamlConfiguration) ConfigUtils.mapToConf(map);
File target = new File(plugin.getDataFolder(), config.name());
if (!target.exists()) target.createNewFile();
DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml yaml = new Yaml(options);
String str = yaml.dump(obj);
byte[] arr = str.getBytes(config.charset());
if (!target.exists()) {
target.createNewFile();
}
byte[] arr = configuration.saveToString().getBytes(config.charset());
Files.write(arr, target);
}
private static final List<Class<?>> primitiveType = Lists.newArrayList(Integer.class,
Double.class, Float.class, Boolean.class, Short.class, Byte.class, Character.class, Long.class, String.class);
private static class Serializer {
private HashMap<String, Object> map;
private Object o;
private int modifiers;
private Serializer(HashMap<String, Object> map, Object o, int modifiers) {
this.map = map;
this.o = o;
this.modifiers = modifiers;
}
private HashMap<String, Object> get() {
for (Field field : o.getClass().getDeclaredFields()) {
if ((field.getModifiers() & modifiers) == 0 && !field.isSynthetic())
try {
SerializedName node = field.getAnnotation(SerializedName.class);
if (!field.isAccessible()) field.setAccessible(true);
Object obj = field.get(o);
map.put(node == null ? field.getName() : node.value(), serialize(obj));
} catch (Exception ignored) {
}
}
return map;
}
@SuppressWarnings({"unchecked", "rawtypes"})
private Object serialize(Object o) {
try {
if (o.getClass().isPrimitive() || primitiveType.contains(o.getClass())) {
return o;
} else if (o.getClass().isArray()) {
List list = new ArrayList<>();
int len = (int) o.getClass().getField("length").get(o);
for (int i = 0; i < len; i++) {
list.add(serialize(Array.get(o, i)));
}
return list;
} else if (o instanceof Collection) {
return ((Collection) o).stream().map(this::serialize).collect(Collectors.toList());
} else if (o instanceof Map) {
Map map = new LinkedHashMap<>();
((Map) o).forEach((o1, o2) -> map.put((String) o1, serialize(o2)));
return map;
} else if (o instanceof ConfigurationSerializable) {
Map map = new LinkedHashMap<>();
map.put(ConfigurationSerialization.SERIALIZED_TYPE_KEY,
ConfigurationSerialization.getAlias((Class<? extends ConfigurationSerializable>) o.getClass()));
map.putAll(((ConfigurationSerializable) o).serialize());
return map;
} else if (o instanceof Property) {
return serialize(((Property) o).get());
} else {
return new Serializer(new HashMap<>(), o, modifiers).get();
}
} catch (Exception ignored) {
return null;
}
}
}
}

View File

@ -1,6 +1,6 @@
package me.skymc.taboolib.inventory;
import lombok.Getter;
import com.ilummc.tlib.resources.TLocale;
import me.clip.placeholderapi.PlaceholderAPI;
import me.skymc.taboolib.Main;
import me.skymc.taboolib.TabooLib;
@ -9,7 +9,6 @@ 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.message.MsgUtils;
import me.skymc.taboolib.other.NumberUtils;
import me.skymc.taboolib.string.Language;
import org.bukkit.Color;
@ -29,226 +28,235 @@ import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.stream.IntStream;
public class ItemUtils {
@Getter
private static FileConfiguration itemdir = null;
@Getter
private static FileConfiguration itemCache = null;
@Getter
private static File finalItemsFolder;
@Getter
private static LinkedHashMap<String, String> itemlib = new LinkedHashMap<>();
@Getter
private static LinkedHashMap<String, ItemStack> itemCaches = new LinkedHashMap<>();
@Getter
private static LinkedHashMap<String, ItemStack> itemCachesFinal = new LinkedHashMap<>();
/**
* 获取物品缓存
* 检测顺序
* 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() {
try {
reloadItemName();
reloadItemCache();
itemdir = YamlConfiguration.loadConfiguration(new File(Main.getInst().getConfig().getString("DATAURL.ITEMDIR")));
} catch (Exception e) {
MsgUtils.warn("物品库载入失败: &4" + e.getMessage());
}
}
public static void loadItemsFile(File file, boolean finalFile) {
FileConfiguration conf = ConfigUtils.load(Main.getInst(), file);
for (String name : conf.getConfigurationSection("").getKeys(false)) {
if (isExists(name)) {
MsgUtils.warn("无法载入载入物品 &4" + name + "&c, 因为它已经存在了");
} else if (finalFile) {
itemCachesFinal.put(name, loadItem(conf, name));
} else {
itemCaches.put(name, loadItem(conf, name));
}
}
}
public static void reloadItemCache() {
itemCaches.clear();
itemCachesFinal.clear();
loadItemsFile(getItemCacheFile(), false);
// 创建固定物品库
finalItemsFolder = new File(Main.getInst().getDataFolder(), "FinalItems");
if (!finalItemsFolder.exists()) {
finalItemsFolder.mkdir();
}
// 检查固定物品库中的物品
for (File file : finalItemsFolder.listFiles()) {
loadItemsFile(file, true);
}
MsgUtils.send("载入 " + (itemCaches.size() + itemCachesFinal.size()) + " 项缓存物品");
}
public static void reloadItemName() {
FileConfiguration conf = new Language("ITEM_NAME", Main.getInst(), true).getConfiguration();
itemlib.clear();
for (String a : conf.getConfigurationSection("").getKeys(false)) {
itemlib.put(a, conf.getString(a));
}
MsgUtils.send("载入 " + itemlib.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 String getCustomName(ItemStack item) {
if (item == null || item.getType().equals(Material.AIR)) {
return "";
}
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")
private static FileConfiguration itemdir = null;
private static FileConfiguration itemCache = null;
private static File finalItemsFolder;
private static LinkedHashMap<String, String> itemlib = new LinkedHashMap<>();
private static LinkedHashMap<String, ItemStack> itemCaches = new LinkedHashMap<>();
private static LinkedHashMap<String, ItemStack> itemCachesFinal = new LinkedHashMap<>();
public static FileConfiguration getItemdir() {
return itemdir;
}
public static FileConfiguration getItemCache() {
return itemCache;
}
public static File getFinalItemsFolder() {
return finalItemsFolder;
}
public static LinkedHashMap<String, String> getItemlib() {
return itemlib;
}
public static LinkedHashMap<String, ItemStack> getItemCaches() {
return itemCaches;
}
public static LinkedHashMap<String, ItemStack> 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() {
try {
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 loadItemsFile(File file, boolean finalFile) {
FileConfiguration conf = ConfigUtils.load(Main.getInst(), file);
for (String name : conf.getConfigurationSection("").getKeys(false)) {
if (isExists(name)) {
TLocale.Logger.error("ITEM-UTILS.FAIL-LOAD-ITEMS", name);
} else if (finalFile) {
itemCachesFinal.put(name, loadItem(conf, name));
} else {
itemCaches.put(name, loadItem(conf, name));
}
}
}
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 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 File getItemCacheFile() {
File itemCacheFile = new File(Main.getInst().getDataFolder(), "items.yml");
if (!itemCacheFile.exists()) {
Main.getInst().saveResource("items.yml", true);
}
return itemCacheFile;
}
public static String getCustomName(ItemStack item) {
if (item == null || item.getType().equals(Material.AIR)) {
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);
}
public static ItemStack setName(ItemStack i, String n) {
ItemMeta meta = i.getItemMeta();
meta.setDisplayName(n);
i.setItemMeta(meta);
return i;
}
public static ItemStack Enchant(ItemStack i, Enchantment e, int l) {
ItemMeta meta = i.getItemMeta();
meta.addEnchant(e, l, false);
i.setItemMeta(meta);
return i;
}
public static ItemStack addFlag(ItemStack i, ItemFlag f) {
ItemMeta meta = i.getItemMeta();
meta.addItemFlags(f);
i.setItemMeta(meta);
return i;
}
public static boolean isNull(ItemStack item) {
return item == null || item.getType().equals(Material.AIR);
return item == null || item.getType().equals(Material.AIR);
}
public static boolean isName(ItemStack i, String a) {
return isNamed(i) && i.getItemMeta() != null && i.getItemMeta().getDisplayName() != null && i.getItemMeta().getDisplayName().equals(a);
}
public static boolean isNameAs(ItemStack i, String a) {
return isNamed(i) && i.getItemMeta().getDisplayName().contains(a);
}
public static String asString(String args, Player placeholderPlayer) {
if (placeholderPlayer == null) {
return args.replace("&", "§");
}
return PlaceholderAPI.setPlaceholders(placeholderPlayer, args.replace("&", "§"));
if (placeholderPlayer == null) {
return args.replace("&", "§");
}
return PlaceholderAPI.setPlaceholders(placeholderPlayer, args.replace("&", "§"));
}
public static List<String> asString(List<String> args, Player placeholderPlayer) {
for (int i = 0 ; i < args.size() ; i ++) {
args.set(i, asString(args.get(i), placeholderPlayer));
}
return args;
IntStream.range(0, args.size()).forEach(i -> args.set(i, asString(args.get(i), placeholderPlayer)));
return args;
}
public static ItemFlag asItemFlag(String flag) {
try {
return ItemFlag.valueOf(flag);
}
catch (Exception e) {
return null;
}
try {
return ItemFlag.valueOf(flag);
} catch (Exception e) {
return null;
}
}
@SuppressWarnings("deprecation")
public static Material asMaterial(String args) {
try {
Material material = Material.getMaterial(args);
return material != null ? material : Material.getMaterial(Integer.valueOf(args));
}
catch (Exception e) {
return Material.STONE;
}
}
@SuppressWarnings({ "deprecation" })
public static Enchantment asEnchantment(String enchant) {
try {
Enchantment enchantment = Enchantment.getByName(enchant);
return enchantment != null ? enchantment : Enchantment.getById(Integer.valueOf(enchant));
}
catch (Exception e) {
return null;
}
public static Material asMaterial(String args) {
try {
Material material = Material.getMaterial(args);
return material != null ? material : Material.getMaterial(Integer.valueOf(args));
} catch (Exception e) {
return Material.STONE;
}
}
@SuppressWarnings({"deprecation"})
public static Enchantment asEnchantment(String enchant) {
try {
Enchantment enchantment = Enchantment.getByName(enchant);
return enchantment != null ? enchantment : Enchantment.getById(Integer.valueOf(enchant));
} catch (Exception e) {
return null;
}
}
@SuppressWarnings("deprecation")
public static PotionEffectType asPotionEffectType(String potion) {
try {
PotionEffectType type = PotionEffectType.getByName(potion);
return type != null ? type : PotionEffectType.getById(Integer.valueOf(potion));
}
catch (Exception e) {
return null;
}
public static PotionEffectType asPotionEffectType(String potion) {
try {
PotionEffectType type = PotionEffectType.getByName(potion);
return type != null ? type : PotionEffectType.getById(Integer.valueOf(potion));
} catch (Exception e) {
return null;
}
}
public static Color asColor(String color) {
try {
return Color.fromBGR(Integer.valueOf(color.split("-")[0]), Integer.valueOf(color.split("-")[1]), Integer.valueOf(color.split("-")[2]));
}
catch (Exception e) {
return Color.fromBGR(0, 0, 0);
}
try {
return Color.fromBGR(Integer.valueOf(color.split("-")[0]), Integer.valueOf(color.split("-")[1]), Integer.valueOf(color.split("-")[2]));
} catch (Exception e) {
return Color.fromBGR(0, 0, 0);
}
}
public static String asAttribute(String name) {
switch (name.toLowerCase()) {
case "damage":
@ -265,321 +273,292 @@ public class ItemUtils {
return "generic.armor";
case "luck":
return "generic.luck";
default:
return null;
}
return null;
}
/**
* 包含介绍
*
*
* @param i 物品
* @param a 关键字
*/
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) {
public static boolean isNamed(ItemStack i) {
return i != null && i.getItemMeta() != null && i.getItemMeta().getDisplayName() != null;
}
/**
* 添加描述
*
* @param is 物品
*
* @param is 物品
* @param lore 描述
*/
public static ItemStack addLore(ItemStack is, String lore) {
ItemMeta meta = is.getItemMeta();
List<String> _lore = meta.hasLore() ? meta.getLore() : new ArrayList<>();
_lore.add(lore.replaceAll("&", "§"));
ItemMeta meta = is.getItemMeta();
List<String> _lore = meta.hasLore() ? meta.getLore() : Collections.emptyList();
_lore.add(lore.replaceAll("&", "§"));
is.setItemMeta(meta);
return is;
}
/**
* 移除描述
*
* @param is 物品
*
* @param is 物品
* @param line 行数
*/
public static ItemStack delLore(ItemStack is, int line) {
ItemMeta meta = is.getItemMeta();
ItemMeta meta = is.getItemMeta();
if (meta.hasLore()) {
List<String> l = meta.getLore();
if (l.size() >= line) {
l.remove(line);
meta.setLore(l);
is.setItemMeta(meta);
}
List<String> l = meta.getLore();
if (l.size() >= line) {
l.remove(line);
meta.setLore(l);
is.setItemMeta(meta);
}
}
return is;
}
/**
* 获取介绍所在行数
*
*
* @param i 物品
* @param a 关键字
*/
public static int getLore(ItemStack i, String a) {
if (isLored(i)) {
for (int j = 0; j < i.getItemMeta().getLore().size() ; j++) {
if (i.getItemMeta().getLore().get(j).contains(a)) {
return j;
}
}
}
return 0;
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;
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 i 物品
* @param l1 关键字1
* @param l2 关键字2
*/
public static ItemStack repalceLore(ItemStack i, String l1, String l2) {
if (!isLored(i)) {
return i;
}
else {
ItemMeta meta = i.getItemMeta();
List<String> lore = meta.getLore();
for (int j = 0 ; j < lore.size() ; j++) {
lore.set(j, lore.get(j).replace(l1, l2));
}
meta.setLore(lore);
i.setItemMeta(meta);
}
return i;
if (!isLored(i)) {
return i;
} else {
ItemMeta meta = i.getItemMeta();
List<String> lore = meta.getLore();
IntStream.range(0, lore.size()).forEach(j -> lore.set(j, lore.get(j).replace(l1, l2)));
meta.setLore(lore);
i.setItemMeta(meta);
}
return i;
}
public static ItemStack loadItem(FileConfiguration f, String s) {
return loadItem(f, s, null);
return loadItem(f, s, null);
}
public static ItemStack loadItem(FileConfiguration f, String s, Player papiPlayer) {
return loadItem(f.getConfigurationSection(s), papiPlayer);
return loadItem(f.getConfigurationSection(s), papiPlayer);
}
public static ItemStack loadItem(ConfigurationSection section, Player papiPlayer) {
if (section.get("bukkit") instanceof ItemStack) {
return section.getItemStack("bukkit");
}
// 材质
ItemStack item = new ItemStack(asMaterial(section.get("material").toString()));
// 数量
item.setAmount(section.contains("amount") ? section.getInt("amount") : 1);
// 耐久
item.setDurability((short) section.getInt("data"));
// 元数据
ItemMeta meta = item.getItemMeta();
// 展示名
if (section.contains("name")) {
meta.setDisplayName(asString(section.getString("name"), papiPlayer));
}
// 描述
if (section.contains("lore")) {
meta.setLore(asString(section.getStringList("lore"), papiPlayer));
}
// 附魔
if (section.contains("enchants")) {
for (String preEnchant : section.getConfigurationSection("enchants").getKeys(false)) {
Enchantment enchant = asEnchantment(preEnchant);
if (enchant != null) {
meta.addEnchant(enchant, section.getInt("enchants." + preEnchant), true);
}
else {
MsgUtils.warn("&8" + preEnchant + " &c不是一个有效的附魔名称");
MsgUtils.warn("&c输入 &4/taboolib enchants&c 查看所有附魔");
}
}
}
// 标签
if (section.contains("flags") && TabooLib.getVerint() > 10700) {
for (String preFlag : section.getStringList("flags")) {
ItemFlag flag = asItemFlag(preFlag);
if (flag != null) {
meta.addItemFlags(flag);
}
else {
MsgUtils.warn("&8" + preFlag + " &c不是一个有效的标签名称");
MsgUtils.warn("&c输入 &4/taboolib flags&c 查看所有标签");
}
}
}
// 皮革
if (meta instanceof LeatherArmorMeta && section.contains("color")) {
((LeatherArmorMeta) meta).setColor(asColor(section.getString("color")));
}
// 药水
if (meta instanceof PotionMeta && section.contains("potions")) {
PotionMeta potionMeta = (PotionMeta) meta;
for (String prePotionName : section.getConfigurationSection("potions").getKeys(false)) {
PotionEffectType potionEffectType = asPotionEffectType(prePotionName);
if (potionEffectType != null) {
potionMeta.addCustomEffect(new PotionEffect(
potionEffectType,
NumberUtils.getInteger(section.getString("potions." + prePotionName).split("-")[0]),
NumberUtils.getInteger(section.getString("potions." + prePotionName).split("-")[1]) - 1), true);
}
else {
MsgUtils.warn("&8" + potionEffectType + " &c不是一个有效的药水名称");
MsgUtils.warn("&c输入 &4/taboolib potions&c 查看所有药水");
}
}
}
// 元数据
item.setItemMeta(meta);
// 数据
NBTItem nbt = new NBTItem(item);
// 物品标签
if (section.contains("nbt")) {
for (String name : section.getConfigurationSection("nbt").getKeys(false)) {
Object obj = section.get("nbt." + name);
if (obj instanceof String) {
nbt.setString(name, obj.toString());
}
else if (obj instanceof Double) {
nbt.setDouble(name, Double.valueOf(obj.toString()));
}
else if (obj instanceof Integer) {
nbt.setInteger(name, Integer.valueOf(obj.toString()));
}
else if (obj instanceof Long) {
nbt.setLong(name, Long.valueOf(obj.toString()));
}
else {
nbt.setObject(name, obj);
}
}
}
// 物品属性
if (section.contains("attributes")) {
NBTList attr = nbt.getList("AttributeModifiers", NBTType.NBTTagCompound);
for (String hand : section.getConfigurationSection("attributes").getKeys(false)) {
for (String name : section.getConfigurationSection("attributes." + hand).getKeys(false)) {
if (asAttribute(name) != null) {
try {
NBTListCompound _attr = attr.addCompound();
Object num = section.get("attributes." + hand + "." + name);
if (num.toString().contains("%")) {
_attr.setDouble("Amount", Double.valueOf(num.toString().replace("%", "")) / 100D);
_attr.setInteger("Operation", 1);
}
else {
_attr.setDouble("Amount", Double.valueOf(num.toString()));
_attr.setInteger("Operation", 0);
}
_attr.setString("AttributeName", asAttribute(name));
_attr.setInteger("UUIDMost", NumberUtils.getRand().nextInt(Integer.MAX_VALUE));
_attr.setInteger("UUIDLeast", NumberUtils.getRand().nextInt(Integer.MAX_VALUE));
_attr.setString("Name", asAttribute(name));
if (!hand.equals("all")) {
_attr.setString("Slot", hand);
}
}
catch (Exception e) {
MsgUtils.warn("&8" + name + " &c属性载入失败: &8" + e.getMessage());
}
}
else {
MsgUtils.warn("&8" + name + " &c不是一个有效的属性名称");
MsgUtils.warn("&c输入 &4/taboolib attributes&c 查看所有属性");
}
}
}
}
return nbt.getItem();
if (section.get("bukkit") instanceof ItemStack) {
return section.getItemStack("bukkit");
}
// 材质
ItemStack item = new ItemStack(asMaterial(section.getString("material")));
// 数量
item.setAmount(section.contains("amount") ? section.getInt("amount") : 1);
// 耐久
item.setDurability((short) section.getInt("data"));
// 元数据
ItemMeta meta = item.getItemMeta();
// 展示名
if (section.contains("name")) {
meta.setDisplayName(asString(section.getString("name"), papiPlayer));
}
// 描述
if (section.contains("lore")) {
meta.setLore(asString(section.getStringList("lore"), papiPlayer));
}
// 附魔
if (section.contains("enchants")) {
for (String preEnchant : section.getConfigurationSection("enchants").getKeys(false)) {
Enchantment enchant = asEnchantment(preEnchant);
if (enchant != null) {
meta.addEnchant(enchant, section.getInt("enchants." + preEnchant), true);
} else {
TLocale.Logger.error("ITEM-UTILS.FAIL-LOAD-ENCHANTS", preEnchant);
}
}
}
// 标签
if (section.contains("flags") && TabooLib.getVerint() > 10700) {
for (String preFlag : section.getStringList("flags")) {
ItemFlag flag = asItemFlag(preFlag);
if (flag != null) {
meta.addItemFlags(flag);
} else {
TLocale.Logger.error("ITEM-UTILS.FAIL-LOAD-FLAG", preFlag);
}
}
}
// 皮革
if (meta instanceof LeatherArmorMeta && section.contains("color")) {
((LeatherArmorMeta) meta).setColor(asColor(section.getString("color")));
}
// 药水
if (meta instanceof PotionMeta && section.contains("potions")) {
PotionMeta potionMeta = (PotionMeta) meta;
for (String prePotionName : section.getConfigurationSection("potions").getKeys(false)) {
PotionEffectType potionEffectType = asPotionEffectType(prePotionName);
if (potionEffectType != null) {
potionMeta.addCustomEffect(new PotionEffect(
potionEffectType,
NumberUtils.getInteger(section.getString("potions." + prePotionName).split("-")[0]),
NumberUtils.getInteger(section.getString("potions." + prePotionName).split("-")[1]) - 1), true);
} else {
TLocale.Logger.error("ITEM-UTILS.FAIL-LOAD-POTION", prePotionName);
}
}
}
// 元数据
item.setItemMeta(meta);
// 数据
NBTItem nbt = new NBTItem(item);
// 物品标签
if (section.contains("nbt")) {
for (String name : section.getConfigurationSection("nbt").getKeys(false)) {
Object obj = section.get("nbt." + name);
if (obj instanceof String) {
nbt.setString(name, obj.toString());
} else if (obj instanceof Double) {
nbt.setDouble(name, Double.valueOf(obj.toString()));
} else if (obj instanceof Integer) {
nbt.setInteger(name, Integer.valueOf(obj.toString()));
} else if (obj instanceof Long) {
nbt.setLong(name, Long.valueOf(obj.toString()));
} else {
nbt.setObject(name, obj);
}
}
}
// 物品属性
if (section.contains("attributes")) {
NBTList attr = nbt.getList("AttributeModifiers", NBTType.NBTTagCompound);
for (String hand : section.getConfigurationSection("attributes").getKeys(false)) {
for (String name : section.getConfigurationSection("attributes." + hand).getKeys(false)) {
if (asAttribute(name) != null) {
try {
NBTListCompound _attr = attr.addCompound();
Object num = section.get("attributes." + hand + "." + name);
if (num.toString().contains("%")) {
_attr.setDouble("Amount", Double.valueOf(num.toString().replace("%", "")) / 100D);
_attr.setInteger("Operation", 1);
} else {
_attr.setDouble("Amount", Double.valueOf(num.toString()));
_attr.setInteger("Operation", 0);
}
_attr.setString("AttributeName", asAttribute(name));
_attr.setInteger("UUIDMost", NumberUtils.getRandom().nextInt(Integer.MAX_VALUE));
_attr.setInteger("UUIDLeast", NumberUtils.getRandom().nextInt(Integer.MAX_VALUE));
_attr.setString("Name", asAttribute(name));
if (!"all".equals(hand)) {
_attr.setString("Slot", hand);
}
} catch (Exception ignored) {
}
} else {
TLocale.Logger.error("ITEM-UTILS.FAIL-LOAD-POTION", name);
}
}
}
}
return nbt.getItem();
}
public static NBTItem setAttribute(NBTItem nbt, String name, Object num, String hand) {
NBTList attr = nbt.getList("AttributeModifiers", NBTType.NBTTagCompound);
if (asAttribute(name) != null) {
try {
NBTListCompound _attr = null;
for (int i = 0 ; i < attr.size() ; i++) {
NBTListCompound nlc = attr.getCompound(i);
if (nlc.getString("AttributeName").equals(asAttribute(name))) {
_attr = nlc;
}
}
if (_attr == null) {
_attr = attr.addCompound();
}
if (num.toString().contains("%")) {
_attr.setDouble("Amount", Double.valueOf(num.toString().replace("%", "")) / 100D);
_attr.setInteger("Operation", 1);
}
else {
_attr.setDouble("Amount", Double.valueOf(num.toString()));
_attr.setInteger("Operation", 0);
}
_attr.setString("AttributeName", asAttribute(name));
_attr.setInteger("UUIDMost", NumberUtils.getRand().nextInt(Integer.MAX_VALUE));
_attr.setInteger("UUIDLeast", NumberUtils.getRand().nextInt(Integer.MAX_VALUE));
_attr.setString("Name", asAttribute(name));
if (!hand.equals("all")) {
_attr.setString("Slot", hand);
}
}
catch (Exception e) {
MsgUtils.warn("&8" + name + " &c属性载入失败: &8" + e.getMessage());
}
}
else {
MsgUtils.warn("&8" + name + " &c不是一个有效的属性名称");
MsgUtils.warn("&c输入 &4/taboolib attributes&c 查看所有属性");
}
return nbt;
NBTList attr = nbt.getList("AttributeModifiers", NBTType.NBTTagCompound);
if (asAttribute(name) != null) {
try {
NBTListCompound _attr = null;
for (int i = 0; i < attr.size(); i++) {
NBTListCompound nlc = attr.getCompound(i);
if (nlc.getString("AttributeName").equals(asAttribute(name))) {
_attr = nlc;
}
}
if (_attr == null) {
_attr = attr.addCompound();
}
if (num.toString().contains("%")) {
_attr.setDouble("Amount", Double.valueOf(num.toString().replace("%", "")) / 100D);
_attr.setInteger("Operation", 1);
} else {
_attr.setDouble("Amount", Double.valueOf(num.toString()));
_attr.setInteger("Operation", 0);
}
_attr.setString("AttributeName", asAttribute(name));
_attr.setInteger("UUIDMost", NumberUtils.getRandom().nextInt(Integer.MAX_VALUE));
_attr.setInteger("UUIDLeast", NumberUtils.getRandom().nextInt(Integer.MAX_VALUE));
_attr.setString("Name", asAttribute(name));
if (!"all".equals(hand)) {
_attr.setString("Slot", hand);
}
} catch (NumberFormatException ignored) {
}
} else {
TLocale.Logger.error("ITEM-UTILS.FAIL-LOAD-POTION", name);
}
return nbt;
}
@Deprecated
public static void putO(ItemStack item, Inventory inv, int i) {
inv.setItem(i, item);
inv.setItem(i+1, item);
inv.setItem(i+2, item);
inv.setItem(i+9, item);
inv.setItem(i+10, null);
inv.setItem(i+11, item);
inv.setItem(i+18, item);
inv.setItem(i+19, item);
inv.setItem(i+20, item);
}
inv.setItem(i, item);
inv.setItem(i + 1, item);
inv.setItem(i + 2, item);
inv.setItem(i + 9, item);
inv.setItem(i + 10, null);
inv.setItem(i + 11, item);
inv.setItem(i + 18, item);
inv.setItem(i + 19, item);
inv.setItem(i + 20, item);
}
}

View File

@ -1,9 +1,6 @@
package me.skymc.taboolib.string.language2;
import lombok.Getter;
import me.skymc.taboolib.string.language2.value.*;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.util.ArrayList;
@ -15,97 +12,101 @@ import java.util.List;
* @since 2018-03-08 22:45:56
*/
public class Language2Format implements Language2Line {
@Getter
private Language2Value language2Value = null;
@Getter
private List<Language2Line> language2Lines = new ArrayList<>();
public Language2Format(Player player, Language2Value value) {
language2Value = value;
// 语言类型
Language2Type type = Language2Type.TEXT;
// 递交数据
List<String> values = new LinkedList<>();
// 遍历内容
for (String line : value.getLanguageValue()) {
// 文本类型
if (line.contains("[text]")) {
// 递交数据
parseValue(player, values, type);
// 更改类型
type = Language2Type.TEXT;
}
// 大标题
else if (line.contains("[title]")) {
// 递交数据
parseValue(player, values, type);
// 更改类型
type = Language2Type.TITLE;
}
// 小标题
else if (line.contains("[action]")) {
// 递交数据
parseValue(player, values, type);
// 更改类型
type = Language2Type.ACTION;
}
// JSON
else if (line.contains("[json]")) {
// 递交数据
parseValue(player, values, type);
// 更改类型
type = Language2Type.JSON;
}
// JSON2
else if (line.contains("[json2]")) {
// 递交数据
parseValue(player, values, type);
// 更改类型
type = Language2Type.JSON2;
}
// 音效
else if (line.contains("[sound]")) {
// 递交数据
parseValue(player, values, type);
// 更改类型
type = Language2Type.SOUND;
}
// 书本
else if (line.contains("[book]")) {
// 递交数据
parseValue(player, values, type);
// 更改类型
type = Language2Type.BOOK;
}
else if (line.contains("[return]")) {
// 递交数据
parseValue(player, values, type);
}
// 默认
else {
// 追加内容
values.add(line);
}
}
}
/**
* 识别内容
*
* @param player 玩家
* @param list 数据
* @param type 类型
*/
private void parseValue(Player player, List<String> list, Language2Type type) {
if (list.size() == 0) {
return;
}
// 变量转换
List<String> listPlaceholder = language2Value.setPlaceholder(list, player);
// 大标题
private Language2Value language2Value;
private List<Language2Line> language2Lines = new ArrayList<>();
public Language2Format(Player player, Language2Value value) {
language2Value = value;
// 语言类型
Language2Type type = Language2Type.TEXT;
// 递交数据
List<String> values = new LinkedList<>();
// 遍历内容
for (String line : value.getLanguageValue()) {
// 文本类型
if (line.contains("[text]")) {
// 递交数据
parseValue(player, values, type);
// 更改类型
type = Language2Type.TEXT;
}
// 大标题
else if (line.contains("[title]")) {
// 递交数据
parseValue(player, values, type);
// 更改类型
type = Language2Type.TITLE;
}
// 小标题
else if (line.contains("[action]")) {
// 递交数据
parseValue(player, values, type);
// 更改类型
type = Language2Type.ACTION;
}
// JSON
else if (line.contains("[json]")) {
// 递交数据
parseValue(player, values, type);
// 更改类型
type = Language2Type.JSON;
}
// JSON2
else if (line.contains("[json2]")) {
// 递交数据
parseValue(player, values, type);
// 更改类型
type = Language2Type.JSON2;
}
// 音效
else if (line.contains("[sound]")) {
// 递交数据
parseValue(player, values, type);
// 更改类型
type = Language2Type.SOUND;
}
// 书本
else if (line.contains("[book]")) {
// 递交数据
parseValue(player, values, type);
// 更改类型
type = Language2Type.BOOK;
} else if (line.contains("[return]")) {
// 递交数据
parseValue(player, values, type);
}
// 默认
else {
// 追加内容
values.add(line);
}
}
}
public Language2Value getLanguage2Value() {
return language2Value;
}
public List<Language2Line> getLanguage2Lines() {
return language2Lines;
}
/**
* 识别内容
*
* @param player 玩家
* @param list 数据
* @param type 类型
*/
private void parseValue(Player player, List<String> list, Language2Type type) {
if (list.size() == 0) {
return;
}
// 变量转换
List<String> listPlaceholder = language2Value.setPlaceholder(list, player);
// 大标题
switch (type) {
case TITLE:
language2Lines.add(new Language2Title(this, listPlaceholder));
@ -133,23 +134,19 @@ public class Language2Format implements Language2Line {
default:
language2Lines.add(new Language2Text(this, listPlaceholder));
break;
}
// 清理数据
list.clear();
listPlaceholder.clear();
}
}
// 清理数据
list.clear();
listPlaceholder.clear();
}
@Override
public void send(Player player) {
for (Language2Line line : language2Lines) {
line.send(player);
}
}
@Override
public void send(Player player) {
language2Lines.forEach(line -> line.send(player));
}
@Override
public void console() {
for (Language2Line line : language2Lines) {
line.console();
}
}
@Override
public void console() {
language2Lines.forEach(Language2Line::console);
}
}