下面列出了怎么用org.bukkit.NamespacedKey的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void registerLugolsIodinePotion(final NamespacedKey potionKey, final LugolsIodinePotion.Config config) {
try {
Object basePotion = getPotion.invoke(potionRegistry, newMinecraftKey.invoke(null, config.getRecipe().getBasePotion().name().toLowerCase()));
Object ingredient = getItem.invoke(null, config.getRecipe().getIngredient());
Object registryType = this.iRegistryClass.getDeclaredField("POTION").get(null);
Object mobEffectArray = Array.newInstance(this.mobEffectClass, 0);
Object newPotion = this.potionRegistryClass.getConstructor(mobEffectArray.getClass()).newInstance(mobEffectArray);
Method registerMethod = this.iRegistryClass.getDeclaredMethod("a", this.iRegistryClass, String.class, Object.class);
Object potion = registerMethod.invoke(null, registryType, potionKey.getKey(), newPotion);
Method registerBrewingRecipe = this.potionBrewerClass.getDeclaredMethod("a", this.potionRegistryClass, this.itemClass, this.potionRegistryClass);
registerBrewingRecipe.setAccessible(true);
registerBrewingRecipe.invoke(null, basePotion, ingredient, potion);
} catch (Exception e) {
this.plugin.getLogger().log(Level.SEVERE, "Could not handle reflective operation.", e);
}
}
@Test
public void testHasUnlocked() throws InterruptedException {
SlimefunPlugin.getRegistry().setResearchingEnabled(true);
Player player = server.addPlayer();
PlayerProfile profile = TestUtilities.awaitProfile(player);
NamespacedKey key = new NamespacedKey(plugin, "player_profile_test");
Research research = new Research(key, 280, "Test", 100);
research.register();
profile.setResearched(research, true);
Assertions.assertTrue(profile.hasUnlocked(research));
Assertions.assertTrue(profile.hasUnlocked(null));
profile.setResearched(research, false);
Assertions.assertFalse(profile.hasUnlocked(research));
// Researches are disabled now, so this method should pass
// Whether Research#isEnabled() works correctly is covered elsewhere
SlimefunPlugin.getRegistry().setResearchingEnabled(false);
Assertions.assertTrue(profile.hasUnlocked(research));
}
@Override
public void safeGuard(@NotNull Entity entity) {
if (!(entity instanceof ArmorStand)) {
Util.debugLog(
"Failed to safeGuard " + entity.getLocation() + ", cause target not a ArmorStand");
return;
}
ArmorStand armorStand = (ArmorStand) entity;
// Set item protect in the armorstand's hand
this.guardedIstack = DisplayItem.createGuardItemStack(this.originalItemStack, this.shop);
armorStand.setHelmet(guardedIstack);
try {
armorStand
.getPersistentDataContainer()
.set(
new NamespacedKey(plugin, "displayMark"),
DisplayItemPersistentDataType.INSTANCE,
DisplayItem.createShopProtectionFlag(this.originalItemStack, shop));
} catch (Throwable ignored) {
}
}
@Test
public void testLockedCategoriesParents() {
Assertions.assertThrows(IllegalArgumentException.class, () -> new LockedCategory(new NamespacedKey(plugin, "locked"), new CustomItem(Material.GOLD_NUGGET, "&6Locked Test"), (NamespacedKey) null));
Category category = new Category(new NamespacedKey(plugin, "unlocked"), new CustomItem(Material.EMERALD, "&5I am SHERlocked"));
category.register();
Category unregistered = new Category(new NamespacedKey(plugin, "unregistered"), new CustomItem(Material.EMERALD, "&5I am unregistered"));
LockedCategory locked = new LockedCategory(new NamespacedKey(plugin, "locked"), new CustomItem(Material.GOLD_NUGGET, "&6Locked Test"), category.getKey(), unregistered.getKey());
locked.register();
Assertions.assertTrue(locked.getParents().contains(category));
Assertions.assertFalse(locked.getParents().contains(unregistered));
locked.removeParent(category);
Assertions.assertFalse(locked.getParents().contains(category));
Assertions.assertThrows(IllegalArgumentException.class, () -> locked.addParent(locked));
Assertions.assertThrows(IllegalArgumentException.class, () -> locked.addParent(null));
locked.addParent(category);
Assertions.assertTrue(locked.getParents().contains(category));
}
@Test
public void testShapelessRecipeShape() {
MinecraftRecipeService service = new MinecraftRecipeService(plugin);
Assertions.assertThrows(IllegalArgumentException.class, () -> service.getRecipeShape(null));
NamespacedKey key = new NamespacedKey(plugin, "shapeless_test");
ShapelessRecipe recipe = new ShapelessRecipe(key, new ItemStack(Material.TNT_MINECART));
MaterialChoice choice = new MaterialChoice(Material.TNT);
recipe.addIngredient(choice);
server.addRecipe(recipe);
service.refresh();
Assertions.assertArrayEquals(new RecipeChoice[] { choice }, service.getRecipeShape(recipe));
}
@Test
public void testOilResource() {
NamespacedKey key = new NamespacedKey(plugin, "oil");
GEOResource resource = testResource(key, "Oil", SlimefunItems.OIL_BUCKET, false, 8);
Assertions.assertEquals(0, resource.getDefaultSupply(Environment.NETHER, Biome.NETHER_WASTES));
Assertions.assertNotEquals(0, resource.getDefaultSupply(Environment.NORMAL, Biome.BEACH));
Assertions.assertTrue(resource.getDefaultSupply(Environment.NORMAL, Biome.DESERT) > 10);
Assertions.assertTrue(resource.getDefaultSupply(Environment.NORMAL, Biome.MOUNTAINS) > 10);
Assertions.assertTrue(resource.getDefaultSupply(Environment.NORMAL, Biome.ICE_SPIKES) > 10);
Assertions.assertTrue(resource.getDefaultSupply(Environment.NORMAL, Biome.BADLANDS) > 10);
Assertions.assertTrue(resource.getDefaultSupply(Environment.NORMAL, Biome.OCEAN) > 10);
Assertions.assertTrue(resource.getDefaultSupply(Environment.NORMAL, Biome.SWAMP) > 10);
Assertions.assertEquals(10, resource.getDefaultSupply(Environment.NORMAL, Biome.SUNFLOWER_PLAINS));
}
@Test
public void testSeasonalCategories() {
// Category with current Month
Month month = LocalDate.now().getMonth();
SeasonalCategory category = new SeasonalCategory(new NamespacedKey(plugin, "seasonal"), month, 1, new CustomItem(Material.NETHER_STAR, "&cSeasonal Test"));
SlimefunItem item = TestUtilities.mockSlimefunItem(plugin, "SEASONAL_ITEM", new CustomItem(Material.NETHER_STAR, "&dSeasonal Test Star"));
item.setCategory(category);
item.register(plugin);
item.load();
Player player = server.addPlayer();
Assertions.assertEquals(month, category.getMonth());
Assertions.assertFalse(category.isHidden(player));
// Category with future Month
SeasonalCategory category2 = new SeasonalCategory(category.getKey(), month.plus(6), 1, new CustomItem(Material.MILK_BUCKET, "&dSeasonal Test"));
Assertions.assertTrue(category2.isHidden(player));
}
@Test
public void testRecipe() {
MinecraftRecipeService service = new MinecraftRecipeService(plugin);
NamespacedKey key = new NamespacedKey(plugin, "furnace_recipe_test");
ItemStack result = new ItemStack(Material.EMERALD_BLOCK);
FurnaceRecipe recipe = new FurnaceRecipe(key, result, new MaterialChoice(Material.DIAMOND), 1, 2);
server.addRecipe(recipe);
// The Snapshot has not been taken, so it should fallback to an empty array
Assertions.assertEquals(0, service.getRecipesFor(result).length);
service.refresh();
Recipe[] recipes = service.getRecipesFor(result);
Assertions.assertEquals(1, recipes.length);
Assertions.assertEquals(recipe, recipes[0]);
}
@Test
public void testResearchRegistration() {
NamespacedKey key = new NamespacedKey(plugin, "testResearch");
Research research = new Research(key, 1, "Test", 100);
SlimefunItem item = TestUtilities.mockSlimefunItem(plugin, "RESEARCH_TEST", new CustomItem(Material.TORCH, "&bResearch Test"));
research.addItems(item, null);
research.register();
SlimefunPlugin.getRegistry().setResearchingEnabled(true);
Assertions.assertTrue(research.isEnabled());
Assertions.assertEquals(research, item.getResearch());
Assertions.assertTrue(SlimefunPlugin.getRegistry().getResearches().contains(research));
Optional<Research> optional = Research.getResearch(key);
Assertions.assertTrue(optional.isPresent());
Assertions.assertEquals(research, optional.get());
}
@Override
public ComplexRecipe getRecipe(CommandContext cmdCtx, String key) throws CommandSyntaxException {
IRecipe<?> recipe = ArgumentMinecraftKeyRegistered.b(cmdCtx, key);
return new ComplexRecipe() {
@SuppressWarnings("deprecation")
@Override
public NamespacedKey getKey() {
return new NamespacedKey(recipe.getKey().getNamespace(), recipe.getKey().getKey());
}
@Override
public ItemStack getResult() {
return recipe.toBukkitRecipe().getResult();
}
};
}
@Override
public FunctionWrapper[] getFunction(CommandContext cmdCtx, String str) throws CommandSyntaxException {
Collection<CustomFunction> customFuncList = ArgumentTag.a(cmdCtx, str);
FunctionWrapper[] result = new FunctionWrapper[customFuncList.size()];
CustomFunctionData customFunctionData = getCLW(cmdCtx).getServer().getFunctionData();
CommandListenerWrapper commandListenerWrapper = getCLW(cmdCtx).a().b(2);
int count = 0;
for(CustomFunction customFunction : customFuncList) {
@SuppressWarnings("deprecation")
NamespacedKey minecraftKey = new NamespacedKey(customFunction.a().getNamespace(), customFunction.a().getKey());
ToIntBiFunction<CustomFunction, CommandListenerWrapper> obj = customFunctionData::a;
FunctionWrapper wrapper = new FunctionWrapper(minecraftKey, obj, customFunction, commandListenerWrapper, e -> {
return (Object) getCLW(cmdCtx).a(((CraftEntity) e).getHandle());
});
result[count] = wrapper;
count++;
}
return result;
}
@Test
public void testCategoryRegistration() {
SlimefunItem item = TestUtilities.mockSlimefunItem(plugin, "CATEGORY_TEST", new CustomItem(Material.DIAMOND, "&cTest"));
item.register(plugin);
item.load();
// null should not be a valid argument
Assertions.assertThrows(IllegalArgumentException.class, () -> item.setCategory(null));
Category category = item.getCategory();
Category category2 = new Category(new NamespacedKey(plugin, "test2"), new CustomItem(Material.OBSIDIAN, "&6Test 2"));
Assertions.assertTrue(category.contains(item));
Assertions.assertFalse(category2.contains(item));
Assertions.assertEquals(category, item.getCategory());
item.setCategory(category2);
Assertions.assertFalse(category.contains(item));
Assertions.assertTrue(category2.contains(item));
Assertions.assertEquals(category2, item.getCategory());
}
@Test
public void testCategory() throws InterruptedException {
Player player = server.addPlayer();
PlayerProfile profile = TestUtilities.awaitProfile(player);
GuideHistory history = profile.getGuideHistory();
Category category = new Category(new NamespacedKey(plugin, "category_guide_history"), new CustomItem(Material.BEDROCK, "&4Can't touch this"));
Assertions.assertThrows(IllegalArgumentException.class, () -> history.add((Category) null, 1));
Assertions.assertThrows(IllegalArgumentException.class, () -> history.add(category, -20));
Assertions.assertEquals(0, history.size());
history.add(category, 1);
Assertions.assertEquals(1, history.size());
// This should not add a new entry but rather only update the page
history.add(category, 2);
Assertions.assertEquals(1, history.size());
}
@Test
public void testFreeCreativeResearch() {
SlimefunPlugin.getRegistry().setResearchingEnabled(true);
Player player = server.addPlayer();
NamespacedKey key = new NamespacedKey(plugin, "freeCreativeResearch");
Research research = new Research(key, 153, "Test", 100);
SlimefunPlugin.getRegistry().setFreeCreativeResearchingEnabled(false);
player.setGameMode(GameMode.SURVIVAL);
Assertions.assertFalse(research.canUnlock(player));
player.setGameMode(GameMode.CREATIVE);
Assertions.assertFalse(research.canUnlock(player));
SlimefunPlugin.getRegistry().setFreeCreativeResearchingEnabled(true);
player.setGameMode(GameMode.SURVIVAL);
Assertions.assertFalse(research.canUnlock(player));
player.setGameMode(GameMode.CREATIVE);
Assertions.assertTrue(research.canUnlock(player));
}
@EventHandler(priority = EventPriority.NORMAL)
public void onMetricSubmit(MetricSubmitEvent event) {
Map<NamespacedKey, Object> data = event.getData();
data.put(this.key("lugols_iodine_duration"), this.potion.getDuration().getSeconds());
data.put(this.key("lugols_iodione_affected_count"), (int) this.server.getOnlinePlayers().stream()
.filter(player -> this.effect.getEffect(player) != null)
.count());
}
public void enable(RadiationNmsBridge nmsBridge) {
Objects.requireNonNull(nmsBridge, "nmsBridge");
this.potionKey = new NamespacedKey(this.plugin, "lugols_iodine");
this.durationKey = new NamespacedKey(this.plugin, "duration");
this.durationSecondsKey = new NamespacedKey(this.plugin, "duration_seconds");
if (this.config.getRecipe().enabled) {
nmsBridge.registerLugolsIodinePotion(this.potionKey, this.config);
}
this.plugin.getServer().getPluginManager().registerEvents(this, this.plugin);
}
@Test
public void testResearchGloballyDisabled() {
NamespacedKey key = new NamespacedKey(plugin, "globallyDisabledResearch");
Research research = new Research(key, 3, "Test", 100);
SlimefunPlugin.getRegistry().setResearchingEnabled(true);
Assertions.assertTrue(research.isEnabled());
SlimefunPlugin.getRegistry().setResearchingEnabled(false);
Assertions.assertFalse(research.isEnabled());
SlimefunPlugin.getRegistry().setResearchingEnabled(true);
}
/**
* Gets an enchantment from Vanilla and bukkit names.
* There are also some aliases available.
*
* @param enchant the name of the enchantment.
* @return an enchantment.
* @since 1.0.0
*/
@Nullable
public static Optional<Enchantment> getByName(@Nonnull String enchant) {
Validate.notEmpty(enchant, "Enchantment name cannot be null or empty");
Enchantment enchantment = null;
enchant = StringUtils.deleteWhitespace(StringUtils.lowerCase(enchant, Locale.ENGLISH));
if (ISFLAT) enchantment = Enchantment.getByKey(NamespacedKey.minecraft(enchant)); // 1.13+ only
if (enchantment == null) enchantment = Enchantment.getByName(enchant);
if (enchantment == null) enchantment = ENCHANTMENTS.get(enchant);
if (enchantment == null) enchantment = ALIASENCHANTMENTS.get(enchant);
return Optional.ofNullable(enchantment);
}
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);
}
/**
* Attempts to get a {@link Research} with the given {@link NamespacedKey}.
*
* @param key
* the {@link NamespacedKey} of the {@link Research} you are looking for
*
* @return An {@link Optional} with or without the found {@link Research}
*/
public static Optional<Research> getResearch(NamespacedKey key) {
if (key == null) {
return Optional.empty();
}
for (Research research : SlimefunPlugin.getRegistry().getResearches()) {
if (research.getKey().equals(key)) {
return Optional.of(research);
}
}
return Optional.empty();
}
@SuppressWarnings("deprecation")
public static NamespacedKey fromString(String s) {
if ((s == null) || s.isEmpty()) {
return null;
}
String[] split = s.split(SEPARATOR, 2);
if (split.length == 1) {
return NamespacedKey.minecraft(split[0]);
} else {
return new NamespacedKey(split[0], split[1]);
}
}
@Test
public void testUnlockableResearch() {
Player player = server.addPlayer();
NamespacedKey key = new NamespacedKey(plugin, "freeCreativeResearch");
Research research = new Research(key, 235, "Test", 4);
Assertions.assertFalse(research.canUnlock(player));
player.setLevel(8);
Assertions.assertTrue(research.canUnlock(player));
}
void applyToItem(NBTTagCompound itemData) {
super.applyToItem(itemData);
if (hasRecipes()) {
NBTTagList list = new NBTTagList();
for (NamespacedKey recipe : this.recipes) {
list.appendTag(new NBTTagString(recipe.toString()));
}
itemData.setTag(BOOK_RECIPES.NBT, list);
}
}
@Override
public Stream<? extends Arguments> provideArguments(ExtensionContext context) throws Exception {
Plugin plugin = Mockito.mock(Plugin.class);
Mockito.when(plugin.getName()).thenReturn(namespace);
return Arrays.stream(keys).map(key -> new NamespacedKey(plugin, key)).map(Arguments::of);
}
private CraftItemEvent mockCraftingEvent(ItemStack item) {
Recipe recipe = new ShapedRecipe(new NamespacedKey(plugin, "test_recipe"), new ItemStack(Material.EMERALD));
Player player = server.addPlayer();
CraftingInventory inv = Mockito.mock(CraftingInventory.class);
Mockito.when(inv.getContents()).thenReturn(new ItemStack[] { item, null, null, null, null, null, null, null, null });
InventoryView view = player.openInventory(inv);
CraftItemEvent event = new CraftItemEvent(recipe, view, SlotType.RESULT, 9, ClickType.LEFT, InventoryAction.PICKUP_ALL);
listener.onCraft(event);
return event;
}
@Override
public FunctionWrapper[] getFunction(CommandContext cmdCtx, String str) throws CommandSyntaxException {
Collection<CustomFunction> customFuncList = ArgumentTag.a(cmdCtx, str);
FunctionWrapper[] result = new FunctionWrapper[customFuncList.size()];
CustomFunctionData customFunctionData = getCLW(cmdCtx).getServer().getFunctionData();
CommandListenerWrapper commandListenerWrapper = getCLW(cmdCtx).a().b(2);
int count = 0;
for (CustomFunction customFunction : customFuncList) {
@SuppressWarnings("deprecation")
NamespacedKey minecraftKey = new NamespacedKey(customFunction.a().getNamespace(),
customFunction.a().getKey());
ToIntBiFunction<CustomFunction, CommandListenerWrapper> obj = customFunctionData::a;
FunctionWrapper wrapper = new FunctionWrapper(minecraftKey, obj, customFunction, commandListenerWrapper,
e -> {
return (Object) getCLW(cmdCtx).a(((CraftEntity) e).getHandle());
});
result[count] = wrapper;
count++;
}
return result;
}
@Test
public void testSaltResource() {
NamespacedKey key = new NamespacedKey(plugin, "salt");
GEOResource resource = testResource(key, "Salt", SlimefunItems.SALT, true, 18);
Assertions.assertEquals(0, resource.getDefaultSupply(Environment.NETHER, Biome.NETHER_WASTES));
Assertions.assertEquals(0, resource.getDefaultSupply(Environment.THE_END, Biome.THE_END));
Assertions.assertNotEquals(0, resource.getDefaultSupply(Environment.NORMAL, Biome.MOUNTAINS));
Assertions.assertTrue(resource.getDefaultSupply(Environment.NORMAL, Biome.BEACH) > 10);
Assertions.assertTrue(resource.getDefaultSupply(Environment.NORMAL, Biome.OCEAN) > 10);
Assertions.assertTrue(resource.getDefaultSupply(Environment.NORMAL, Biome.SWAMP) > 10);
}
@Test
public void testAddItems() {
NamespacedKey key = new NamespacedKey(plugin, "addItemsResearch");
Research research = new Research(key, 17, "Test", 100);
SlimefunItem item = TestUtilities.mockSlimefunItem(plugin, "RESEARCH_ITEMS_TEST", new CustomItem(Material.LAPIS_LAZULI, "&9Adding items is fun"));
item.register(plugin);
research.addItems(item.getItem(), null);
Assertions.assertTrue(research.getAffectedItems().contains(item));
Assertions.assertEquals(research, item.getResearch());
}
@SuppressWarnings("deprecation")
@Override
public LootTable getLootTable(CommandContext cmdCtx, String str) {
MinecraftKey minecraftKey = ArgumentMinecraftKeyRegistered.c(cmdCtx, str);
String namespace = minecraftKey.b();
String key = minecraftKey.getKey();
net.minecraft.server.v1_13_R1.LootTable lootTable = getCLW(cmdCtx).getServer().aP().a(minecraftKey);
return new CraftLootTable(new NamespacedKey(namespace, key), lootTable);
}