下面列出了怎么用org.bukkit.persistence.PersistentDataType的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public boolean test(ItemStack itemStack) {
Objects.requireNonNull(itemStack, "itemStack");
if (!itemStack.hasItemMeta()) {
return false;
}
PersistentDataContainer container = itemStack.getItemMeta().getPersistentDataContainer();
if (container.has(this.potionKey, PersistentDataType.BYTE)) {
Byte value = container.get(this.potionKey, PersistentDataType.BYTE);
return value != null && value == TRUE;
}
return false;
}
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onPlayerItemConsume(PlayerItemConsumeEvent event) {
ItemStack item = event.getItem();
if (!this.test(item)) {
return;
}
PersistentDataContainer container = item.getItemMeta().getPersistentDataContainer();
int durationSeconds = 0;
if (container.has(this.durationSecondsKey, PersistentDataType.INTEGER)) {
durationSeconds = container.getOrDefault(this.durationSecondsKey, PersistentDataType.INTEGER, 0);
} else if (container.has(this.durationKey, PersistentDataType.INTEGER)) {
durationSeconds = (int) TimeUnit.MINUTES.toSeconds(container.getOrDefault(this.durationKey, PersistentDataType.INTEGER, 0)); // legacy
}
if (durationSeconds <= 0) {
return;
}
Player player = event.getPlayer();
this.effect.setEffect(player, durationSeconds);
this.broadcastConsumption(player, durationSeconds);
}
public PotionMeta convert(PotionMeta potionMeta) {
Objects.requireNonNull(potionMeta, "potionMeta");
Duration duration = this.config.duration();
String formattedDuration = this.formatDuration(this.config.duration());
if (this.config.color != null) {
potionMeta.setColor(this.config.color);
}
potionMeta.addItemFlags(ItemFlag.HIDE_POTION_EFFECTS);
potionMeta.setDisplayName(ChatColor.AQUA + this.config.name());
potionMeta.setLore(Collections.singletonList(ChatColor.BLUE + MessageFormat.format(this.config.description(), formattedDuration)));
PersistentDataContainer container = potionMeta.getPersistentDataContainer();
container.set(this.potionKey, PersistentDataType.BYTE, TRUE);
container.set(this.durationSecondsKey, PersistentDataType.INTEGER, (int) duration.getSeconds());
return potionMeta;
}
void tick(Player player) {
Objects.requireNonNull(player, "player");
PersistentDataContainer container = player.getPersistentDataContainer();
if (!container.has(secondsLeftKey, PersistentDataType.INTEGER)) {
return;
}
Integer secondsLeft = container.getOrDefault(secondsLeftKey, PersistentDataType.INTEGER, 0);
if (secondsLeft > 0) {
container.set(secondsLeftKey, PersistentDataType.INTEGER, --secondsLeft);
} else {
container.remove(initialSecondsKey);
container.remove(secondsLeftKey);
}
}
/**
* @param stack
* @param hash
*/
public static void hashIntoInvisibleString(ItemStack stack, String hash) {
ItemMeta meta = stack.getItemMeta();
try {
NamespacedKey key = new NamespacedKey((Plugin) BedwarsAPI.getInstance(), BEDWARS_NAMESPACED_KEY);
PersistentDataContainer container = meta.getPersistentDataContainer();
List<String> propertyLines = new ArrayList<>();
if (container.has(key, PersistentDataType.STRING)) {
String oldString = container.get(key, PersistentDataType.STRING);
propertyLines.addAll((List<String>) new Gson().fromJson(oldString, List.class));
}
propertyLines.add(hash);
container.set(key, PersistentDataType.STRING, new Gson().toJson(propertyLines));
} catch (Throwable ignored) {
// Use the Lore API instead
List<String> lore = meta.hasLore() ? meta.getLore() : new ArrayList<>();
lore.add(convertToInvisibleString(hash));
meta.setLore(lore);
}
stack.setItemMeta(meta);
}
private static ItemStack buildersWandCreator(Material m, String name) { //TODO: Modify to implement Modifiers
ItemStack wand = new ItemStack(m, 1);
ItemMeta meta = wand.getItemMeta();
if (meta != null) {
ArrayList<String> lore = new ArrayList<>();
if (config.getBoolean("OverrideLanguagesystem")) {
lore.add(ChatWriter.addColors(config.getString("Description")));
} else {
lore.add(LanguageManager.getString("Builderswand.Description"));
}
meta.setLore(lore);
meta.setDisplayName(ChatWriter.addColors(name));
meta.addItemFlags(ItemFlag.HIDE_DESTROYS);
wand.setItemMeta(meta);
}
//TODO: DataHandler.setStringList(wand, "CanDestroy", true, "minecraft:air");
DataHandler.setTag(wand, "identifier_builderswand", 0, PersistentDataType.INTEGER, false);
return wand;
}
@EventHandler
public void onQuit(PlayerQuitEvent event) {
if (event.getPlayer().getHealth() >= 20.0) { //has Tanky and enough health
ItemStack chest = event.getPlayer().getInventory().getChestplate();
if (modManager.isArmorViable(chest) && modManager.hasMod(chest, this)) {
DataHandler.setTag(chest, "modifier_berserk_health_save", event.getPlayer().getHealth(),
PersistentDataType.DOUBLE, false);
return;
}
chest = event.getPlayer().getInventory().getLeggings();
if (modManager.isArmorViable(chest) && modManager.hasMod(chest, this)) {
DataHandler.setTag(chest, "modifier_berserk_health_save", event.getPlayer().getHealth(),
PersistentDataType.DOUBLE, false);
}
}
}
public @NotNull ItemStack createModifierItem(@NotNull Material m, @NotNull String name, @NotNull String description, @NotNull Modifier mod) {
ItemStack is = new ItemStack(m, 1);
ItemMeta meta = is.getItemMeta();
if (meta != null) {
meta.setDisplayName(name);
ArrayList<String> lore = new ArrayList<>(ChatWriter.splitString(description, 40));
meta.setLore(lore);
meta.addItemFlags(ItemFlag.HIDE_PLACED_ON);
is.setItemMeta(meta);
}
DataHandler.setTag(is, "modifier_item", mod.getKey(), PersistentDataType.STRING, false);
//TODO: DataHandler.setStringList(is, "CanPlaceOn", true, "minecraft:air");
return is;
}
/**
* @param item the ItemStack
* @return the Modifier of the Modifier-Item (NULL if not found)
*/
@Nullable
public Modifier getModifierFromItem(ItemStack item) {
if (!isModifierItem(item)) {
return null;
}
if (!DataHandler.hasTag(item, "modifier_item", PersistentDataType.STRING, false)) {
return null;
}
String name = DataHandler.getTag(item, "modifier_item", PersistentDataType.STRING, false);
if (name == null) {
return null;
}
for (Modifier m : mods) {
if (m.getKey().equals(name)) {
return m;
}
}
return null;
}
/**
* @param stack
* @param hash
*/
public static void hashIntoInvisibleString(ItemStack stack, String hash) {
ItemMeta meta = stack.getItemMeta();
try {
NamespacedKey key = new NamespacedKey((Plugin) BedwarsAPI.getInstance(), BEDWARS_NAMESPACED_KEY);
PersistentDataContainer container = meta.getPersistentDataContainer();
List<String> propertyLines = new ArrayList<>();
if (container.has(key, PersistentDataType.STRING)) {
String oldString = container.get(key, PersistentDataType.STRING);
propertyLines.addAll((List<String>) new Gson().fromJson(oldString, List.class));
}
propertyLines.add(hash);
container.set(key, PersistentDataType.STRING, new Gson().toJson(propertyLines));
} catch (Throwable ignored) {
// Use the Lore API instead
List<String> lore = meta.hasLore() ? meta.getLore() : new ArrayList<>();
lore.add(convertToInvisibleString(hash));
meta.setLore(lore);
}
stack.setItemMeta(meta);
}
static void setCharge(ItemMeta meta, float charge, float capacity) {
BigDecimal decimal = BigDecimal.valueOf(charge).setScale(2, RoundingMode.HALF_UP);
float value = decimal.floatValue();
if (SlimefunPlugin.getMinecraftVersion().isAtLeast(MinecraftVersion.MINECRAFT_1_14)) {
meta.getPersistentDataContainer().set(CHARGE_KEY, PersistentDataType.FLOAT, value);
}
List<String> lore = meta.hasLore() ? meta.getLore() : new ArrayList<>();
for (int i = 0; i < lore.size(); i++) {
String line = lore.get(i);
if (line.startsWith(LORE_PREFIX)) {
lore.set(i, LORE_PREFIX + value + " / " + capacity + " J");
meta.setLore(lore);
return;
}
}
lore.add(LORE_PREFIX + value + " / " + capacity + " J");
meta.setLore(lore);
}
static float getCharge(ItemMeta meta) {
if (SlimefunPlugin.getMinecraftVersion().isAtLeast(MinecraftVersion.MINECRAFT_1_14)) {
Float value = meta.getPersistentDataContainer().get(CHARGE_KEY, PersistentDataType.FLOAT);
// If persistent data is available, we just return this value
if (value != null) {
return value;
}
}
// If no persistent data exists, we will just fall back to the lore
if (meta.hasLore()) {
for (String line : meta.getLore()) {
if (line.startsWith(LORE_PREFIX) && line.contains(" / ") && line.endsWith(" J")) {
return Float.parseFloat(PatternUtils.SLASH_SEPARATOR.split(line)[0].replace(LORE_PREFIX, ""));
}
}
}
return 0;
}
@Override
public PersistentDataContainer toPrimitive(WorldBorderData complex, PersistentDataAdapterContext context) {
PersistentDataContainer persistentDataContainer = context.newPersistentDataContainer();
persistentDataContainer.set(sizeKey, PersistentDataType.DOUBLE, complex.getSize());
complex.applyCenter((x, z) -> {
persistentDataContainer.set(xKey, PersistentDataType.DOUBLE, x);
persistentDataContainer.set(zKey, PersistentDataType.DOUBLE, z);
});
persistentDataContainer.set(damageBufferInBlocksKey, PersistentDataType.DOUBLE, complex.getDamageBuffer());
persistentDataContainer.set(damageAmountKey, PersistentDataType.DOUBLE, complex.getDamageAmount());
persistentDataContainer.set(warningTimeSecondsKey, PersistentDataType.INTEGER, complex.getWarningTimeSeconds());
persistentDataContainer.set(warningDistanceKey, PersistentDataType.INTEGER, complex.getWarningDistance());
return persistentDataContainer;
}
@Override
public WorldBorderData fromPrimitive(PersistentDataContainer primitive, PersistentDataAdapterContext context) {
WorldBorderData worldBorderData = new WorldBorderData();
get(primitive, sizeKey, PersistentDataType.DOUBLE).ifPresent(worldBorderData::setSize);
Optional<Double> centerX = get(primitive, xKey, PersistentDataType.DOUBLE);
Optional<Double> centerZ = get(primitive, zKey, PersistentDataType.DOUBLE);
if (centerX.isPresent() && centerZ.isPresent()) {
worldBorderData.setCenter(centerX.get(), centerZ.get());
}
get(primitive, damageBufferInBlocksKey, PersistentDataType.DOUBLE).ifPresent(worldBorderData::setDamageBuffer);
get(primitive, damageAmountKey, PersistentDataType.DOUBLE).ifPresent(worldBorderData::setDamageAmount);
get(primitive, warningTimeSecondsKey, PersistentDataType.INTEGER).ifPresent(worldBorderData::setWarningTimeSeconds);
get(primitive, warningDistanceKey, PersistentDataType.INTEGER).ifPresent(worldBorderData::setWarningDistance);
return worldBorderData;
}
public Effect getEffect(Entity entity) {
Objects.requireNonNull(entity, "entity");
PersistentDataContainer container = entity.getPersistentDataContainer();
int initialSeconds = container.getOrDefault(this.initialSecondsKey, PersistentDataType.INTEGER, -1);
int secondsLeft = container.getOrDefault(this.secondsLeftKey, PersistentDataType.INTEGER, -1);
if (initialSeconds != -1 && secondsLeft != -1) {
return new Effect(initialSeconds, secondsLeft);
}
return null;
}
public void setEffect(Entity entity, Effect effect) {
Objects.requireNonNull(entity, "entity");
Objects.requireNonNull(effect, "effect");
PersistentDataContainer container = entity.getPersistentDataContainer();
container.set(this.initialSecondsKey, PersistentDataType.INTEGER, effect.initialSeconds);
container.set(this.secondsLeftKey, PersistentDataType.INTEGER, effect.secondsLeft);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void onEntityDamage(MTEntityDamageEvent event) {
ItemStack armor = event.getTool();
if (ModManager.instance().isArmorViable(armor)) {
double finalDamage = event.getEvent().getFinalDamage();
Double old = DataHandler.getTag(armor, keyStart + "damage_received",
PersistentDataType.DOUBLE, false);
if (old == null) {
old = 0.0d;
}
DataHandler.setTag(armor, keyStart + "damage_received", old + finalDamage,
PersistentDataType.DOUBLE, false);
}
}
public static <T, Z> boolean hasTag(@NotNull ItemStack item, @NotNull String key, PersistentDataType<T, Z> dataType, boolean useMinecraft) {
ItemMeta meta = item.getItemMeta();
if (meta == null) return false;
PersistentDataContainer container = meta.getPersistentDataContainer();
return container.has((useMinecraft ? NamespacedKey.minecraft(key) : new NamespacedKey(MineTinker.getPlugin(), key)), dataType);
}
public static <T, Z> void setTag(@NotNull ItemStack item, @NotNull String key, Z value, PersistentDataType<T, Z> dataType, boolean useMinecraft) {
ItemMeta meta = item.getItemMeta();
if (meta == null) return;
PersistentDataContainer container = meta.getPersistentDataContainer();
container.set((useMinecraft ? NamespacedKey.minecraft(key) : new NamespacedKey(MineTinker.getPlugin(), key)), dataType, value);
item.setItemMeta(meta);
}
public static <T, Z> @Nullable Z getTag(@NotNull ItemStack item, @NotNull String key, PersistentDataType<T, Z> dataType, boolean useMinecraft) {
ItemMeta meta = item.getItemMeta();
if (meta == null) return null;
PersistentDataContainer container = meta.getPersistentDataContainer();
return container.get((useMinecraft ? NamespacedKey.minecraft(key) : new NamespacedKey(MineTinker.getPlugin(), key)), dataType);
}
@EventHandler
public void onJoin(PlayerJoinEvent event) {
Double health;
ItemStack chest = event.getPlayer().getInventory().getChestplate();
if (modManager.isArmorViable(chest) && modManager.hasMod(chest, this)) {
health = DataHandler.getTag(chest, "modifier_berserk_health_save", PersistentDataType.DOUBLE, false);
if (health != null) {
Bukkit.getScheduler().runTaskLater(MineTinker.getPlugin(), () -> event.getPlayer().setHealth(health), 10L);
DataHandler.removeTag(chest, "modifier_berserk_health_save", false);
} else {
return;
}
} else {
chest = event.getPlayer().getInventory().getLeggings();
if (modManager.isArmorViable(chest) && modManager.hasMod(chest, this)) {
health = DataHandler.getTag(chest, "modifier_berserk_health_save", PersistentDataType.DOUBLE, false);
if (health != null) {
Bukkit.getScheduler().runTaskLater(MineTinker.getPlugin(), () -> event.getPlayer().setHealth(health), 10L);
DataHandler.removeTag(chest, "modifier_berserk_health_save", false);
} else {
return;
}
} else {
return;
}
}
ChatWriter.logModifier(event.getPlayer(), event, this, chest, String.format("ApplyHealth(%.2f -> %.2f)", event.getPlayer().getHealth(), health));
}
/**
* get the level of a specified modifier on a tool
*
* @param is the item
* @param mod the modifier
*/
public int getModLevel(ItemStack is, @NotNull Modifier mod) {
if (!mod.isAllowed()) return 0;
Integer tag = DataHandler.getTag(is, mod.getKey(), PersistentDataType.INTEGER, false);
if (tag == null) return 0;
return tag;
}
/**
* This method checks whether the given {@link ItemStack} is considered {@link Soulbound}.
*
* @param item
* The {@link ItemStack} to check for
* @return Whether the given item is soulbound
*/
public static boolean isSoulbound(ItemStack item) {
if (item == null || item.getType() == Material.AIR) {
return false;
}
else {
ItemMeta meta = item.hasItemMeta() ? item.getItemMeta() : null;
if (meta != null && SlimefunPlugin.getMinecraftVersion().isAtLeast(MinecraftVersion.MINECRAFT_1_14)) {
PersistentDataContainer container = meta.getPersistentDataContainer();
if (container.has(SOULBOUND_KEY, PersistentDataType.BYTE)) {
return true;
}
}
if (SlimefunPlugin.getThirdPartySupportService().isEmeraldEnchantsInstalled()) {
// We wanna operate on a copy now
item = item.clone();
for (ItemEnchantment enchantment : EmeraldEnchants.getInstance().getRegistry().getEnchantments(item)) {
EmeraldEnchants.getInstance().getRegistry().applyEnchantment(item, enchantment.getEnchantment(), 0);
}
}
SlimefunItem sfItem = SlimefunItem.getByItem(item);
if (sfItem instanceof Soulbound) {
return !sfItem.isDisabled();
}
else if (meta != null) {
return meta.hasLore() && meta.getLore().contains(SOULBOUND_LORE);
}
return false;
}
}
/**
* Toggles an {@link ItemStack} to be Soulbound.<br>
* If true is passed, this will add the {@link #SOULBOUND_LORE} and
* add a {@link NamespacedKey} to the item so it can be quickly identified
* by {@link #isSoulbound(ItemStack)}.<br>
* If false is passed, this property will be removed.
*
* @param item
* The {@link ItemStack} you want to add/remove Soulbound from.
* @param makeSoulbound
* If they item should be soulbound.
*
* @see #isSoulbound(ItemStack)
*/
public static void setSoulbound(ItemStack item, boolean makeSoulbound) {
if (item == null || item.getType() == Material.AIR) {
throw new IllegalArgumentException("A soulbound item cannot be null or air!");
}
boolean isSoulbound = isSoulbound(item);
ItemMeta meta = item.getItemMeta();
if (SlimefunPlugin.getMinecraftVersion().isAtLeast(MinecraftVersion.MINECRAFT_1_14)) {
PersistentDataContainer container = meta.getPersistentDataContainer();
if (makeSoulbound && !isSoulbound) {
container.set(SOULBOUND_KEY, PersistentDataType.BYTE, (byte) 1);
}
if (!makeSoulbound && isSoulbound) {
container.remove(SOULBOUND_KEY);
}
}
List<String> lore = meta.hasLore() ? meta.getLore() : new ArrayList<>();
if (makeSoulbound && !isSoulbound) {
lore.add(SOULBOUND_LORE);
}
if (!makeSoulbound && isSoulbound) {
lore.remove(SOULBOUND_LORE);
}
meta.setLore(lore);
item.setItemMeta(meta);
}
private void useItem(Player p, ItemStack item, Location loc) {
loc.getWorld().strikeLightning(loc);
if (p.getInventory().getItemInMainHand().getType() == Material.SHEARS) {
return;
}
if (p.getGameMode() != GameMode.CREATIVE) {
FoodLevelChangeEvent event = new FoodLevelChangeEvent(p, p.getFoodLevel() - 4);
Bukkit.getPluginManager().callEvent(event);
if (!event.isCancelled()) {
p.setFoodLevel(event.getFoodLevel());
}
}
ItemMeta meta = item.getItemMeta();
int usesLeft = meta.getPersistentDataContainer().getOrDefault(usageKey, PersistentDataType.INTEGER, MAX_USES);
if (usesLeft == 1) {
p.playSound(p.getLocation(), Sound.ENTITY_ITEM_BREAK, 1, 1);
item.setAmount(0);
}
else {
usesLeft--;
meta.getPersistentDataContainer().set(usageKey, PersistentDataType.INTEGER, usesLeft);
List<String> lore = meta.getLore();
lore.set(4, ChatColors.color("&e" + usesLeft + ' ' + (usesLeft > 1 ? "Uses" : "Use") + " &7left"));
meta.setLore(lore);
item.setItemMeta(meta);
}
}
default Optional<String> getString(Object obj, NamespacedKey key) {
if (SlimefunPlugin.getMinecraftVersion().isAtLeast(MinecraftVersion.MINECRAFT_1_14) && obj instanceof PersistentDataHolder) {
PersistentDataContainer container = ((PersistentDataHolder) obj).getPersistentDataContainer();
return Optional.ofNullable(container.get(key, PersistentDataType.STRING));
}
return Optional.empty();
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void effect(PlayerDeathEvent event) {
if (event.getKeepInventory()) {
return;
}
Player player = event.getEntity();
Inventory inventory = player.getInventory();
for (ItemStack itemStack : inventory.getContents()) {
if (itemStack == null) {
continue; // More consistent nullability in NotNull fields
}
if (modManager.isArmorViable(itemStack) || modManager.isToolViable(itemStack) || modManager.isWandViable(itemStack)) {
if (!player.hasPermission("minetinker.modifiers.soulbound.use")) {
continue;
}
if (!modManager.hasMod(itemStack, this)) {
continue;
}
Random rand = new Random();
int n = rand.nextInt(100);
int c = modManager.getModLevel(itemStack, this) * percentagePerLevel;
ChatWriter.logModifier(player, event, this, itemStack, String.format("Chance(%d/%d)", n, c));
if (n > c) {
continue;
}
storedItemStacks.computeIfAbsent(player.getUniqueId(), k -> new ArrayList<>()); // ?
ArrayList<ItemStack> stored = storedItemStacks.get(player.getUniqueId());
if (stored.contains(itemStack)) {
continue;
}
if (decrementModLevelOnUse) {
int newLevel = modManager.getModLevel(itemStack, this) - 1;
if (newLevel == 0) {
modManager.removeMod(itemStack, this);
} else {
DataHandler.setTag(itemStack, getKey(), modManager.getModLevel(itemStack, this) - 1, PersistentDataType.INTEGER, false);
}
}
stored.add(itemStack.clone());
itemStack.setAmount(0);
}
}
}
/**
* gets how many free slots the tool has
*
* @param is the item to get the information from
*/
public int getFreeSlots(ItemStack is) {
Integer freeSlots = DataHandler.getTag(is, "FreeSlots", PersistentDataType.INTEGER, false);
if (freeSlots == null) return 0;
return freeSlots;
}
/**
* gets what level the tool has
*
* @param is the item to get the information from
*/
public int getLevel(ItemStack is) {
Integer level = DataHandler.getTag(is, "Level", PersistentDataType.INTEGER, false);
if (level == null) return 0;
return level;
}
/**
* gets the amount of exp the tool has
*
* @param is the item to get the information from
*/
public long getExp(ItemStack is) {
Long exp = DataHandler.getTag(is, "Exp", PersistentDataType.LONG, false);
if (exp == null) return 0;
return exp;
}