org.spongepowered.api.item.inventory.ItemStackSnapshot Java Examples
The following examples show how to use
org.spongepowered.api.item.inventory.ItemStackSnapshot.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PlayerEventHandler.java From GriefDefender with MIT License | 6 votes |
@Listener(order = Order.FIRST, beforeModifications = true) public void onPlayerInteractInventoryClose(InteractInventoryEvent.Close event, @Root Player player) { final ItemStackSnapshot cursor = event.getCursorTransaction().getOriginal(); if (cursor == ItemStackSnapshot.NONE || !GDFlags.ITEM_DROP || !GriefDefenderPlugin.getInstance().claimsEnabledForWorld(player.getWorld().getUniqueId())) { return; } if (GriefDefenderPlugin.isTargetIdBlacklisted(Flags.ITEM_DROP.getName(), cursor, player.getWorld().getProperties())) { return; } GDTimings.PLAYER_INTERACT_INVENTORY_CLOSE_EVENT.startTimingIfSync(); final Location<World> location = player.getLocation(); final GDClaim claim = this.dataStore.getClaimAt(location); if (GDPermissionManager.getInstance().getFinalPermission(event, location, claim, Flags.ITEM_DROP, player, cursor, player, TrustTypes.ACCESSOR, true) == Tristate.FALSE) { final Component message = GriefDefenderPlugin.getInstance().messageData.getMessage(MessageStorage.PERMISSION_ITEM_DROP, ImmutableMap.of( "player", claim.getOwnerName(), "item", cursor.getType().getId())); GriefDefenderPlugin.sendClaimDenyMessage(claim, player, message); event.setCancelled(true); } GDTimings.PLAYER_INTERACT_INVENTORY_CLOSE_EVENT.stopTimingIfSync(); }
Example #2
Source File: InventoryListener.java From Prism with MIT License | 6 votes |
/** * Saves event records when a player picks up an item off of the ground. * * @param event ChangeInventoryEvent.Pickup * @param player Player */ @Listener(order = Order.POST) public void onChangeInventoryPickup(ChangeInventoryEvent.Pickup event, @Root Player player) { if (event.getTransactions().isEmpty() || !Prism.getInstance().getConfig().getEventCategory().isItemPickup()) { return; } for (SlotTransaction transaction : event.getTransactions()) { ItemStackSnapshot itemStack = transaction.getFinal(); int quantity = itemStack.getQuantity(); if (transaction.getOriginal().getType() != ItemTypes.NONE) { quantity -= transaction.getOriginal().getQuantity(); } Prism.getInstance().getLogger().debug("Inventory pickup - {} x{}", itemStack.getType().getId(), quantity); PrismRecord.create() .source(event.getCause()) .event(PrismEvents.ITEM_PICKUP) .itemStack(itemStack, quantity) .location(player.getLocation()) .buildAndSave(); } }
Example #3
Source File: PlayerEventHandler.java From GriefPrevention with MIT License | 6 votes |
@Listener(order = Order.FIRST, beforeModifications = true) public void onPlayerInteractInventoryClose(InteractInventoryEvent.Close event, @Root Player player) { final ItemStackSnapshot cursor = event.getCursorTransaction().getOriginal(); if (cursor == ItemStackSnapshot.NONE || !GPFlags.ITEM_DROP || !GriefPreventionPlugin.instance.claimsEnabledForWorld(player.getWorld().getProperties())) { return; } if (GriefPreventionPlugin.isTargetIdBlacklisted(ClaimFlag.ITEM_DROP.toString(), cursor, player.getWorld().getProperties())) { return; } GPTimings.PLAYER_INTERACT_INVENTORY_CLOSE_EVENT.startTimingIfSync(); final Location<World> location = player.getLocation(); final GPClaim claim = this.dataStore.getClaimAt(location); if (GPPermissionHandler.getClaimPermission(event, location, claim, GPPermissions.ITEM_DROP, player, cursor, player, TrustType.ACCESSOR, true) == Tristate.FALSE) { Text message = GriefPreventionPlugin.instance.messageData.permissionItemDrop .apply(ImmutableMap.of( "owner", claim.getOwnerName(), "item", cursor.getType().getId())).build(); GriefPreventionPlugin.sendClaimDenyMessage(claim, player, message); event.setCancelled(true); } GPTimings.PLAYER_INTERACT_INVENTORY_CLOSE_EVENT.stopTimingIfSync(); }
Example #4
Source File: FlagGui.java From RedProtect with GNU General Public License v3.0 | 6 votes |
private void applyFlag(String flag, ItemStack item, ClickInventoryEvent event) { if (this.region.setFlag(RedProtect.get().getVersionHelper().getCause(this.player), flag, !this.region.getFlagBool(flag))) { RedProtect.get().lang.sendMessage(player, RedProtect.get().lang.get("cmdmanager.region.flag.set").replace("{flag}", "'" + flag + "'") + " " + this.region.getFlagBool(flag)); if (!this.region.getFlagBool(flag)) { item.remove(Keys.ITEM_ENCHANTMENTS); } else { item = RedProtect.get().getVersionHelper().offerEnchantment(item); } item.offer(Keys.HIDE_ENCHANTMENTS, true); item.offer(Keys.HIDE_ATTRIBUTES, true); List<Text> lore = new ArrayList<>(Arrays.asList( Text.joinWith(Text.of(" "), RedProtect.get().guiLang.getFlagString("value"), RedProtect.get().guiLang.getFlagString(region.getFlags().get(flag).toString())), RedProtect.get().getUtil().toText("&0" + flag))); lore.addAll(RedProtect.get().guiLang.getFlagDescription(flag)); item.offer(Keys.ITEM_LORE, lore); event.getCursorTransaction().setCustom(ItemStackSnapshot.NONE); event.getTransactions().get(0).getSlot().offer(item); RedProtect.get().getVersionHelper().removeGuiItem(this.player); RedProtect.get().logger.addLog("(World " + this.region.getWorld() + ") Player " + player.getName() + " CHANGED flag " + flag + " of region " + this.region.getName() + " to " + this.region.getFlagString(flag)); } }
Example #5
Source File: CreatekitCommand.java From UltimateCore with MIT License | 6 votes |
@Override public CommandResult execute(CommandSource sender, CommandContext args) throws CommandException { checkIfPlayer(sender); checkPermission(sender, KitPermissions.UC_KIT_CREATEKIT_BASE); Player p = (Player) sender; String name = args.<String>getOne("name").get().toLowerCase(); long cooldown = args.hasAny("cooldown") ? args.<Long>getOne("cooldown").get() : -1L; String description = args.hasAny("description") ? args.<String>getOne("description").get() : Messages.getFormatted("kit.defaultdescription").toPlain(); List<ItemStackSnapshot> items = new ArrayList<>(); p.getInventory().slots().forEach(slot -> { ItemStack stack = slot.peek(); if (!stack.getType().equals(ItemTypes.NONE)) { items.add(stack.createSnapshot()); } }); Kit kit = new Kit(name, description, items, new ArrayList<>(), cooldown); List<Kit> kits = GlobalData.get(KitKeys.KITS).get(); kits.add(kit); GlobalData.offer(KitKeys.KITS, kits); Messages.send(sender, "kit.command.createkit.success", "%name%", name); return CommandResult.success(); }
Example #6
Source File: Kit.java From UltimateCore with MIT License | 5 votes |
public Kit(String id, String description, List<ItemStackSnapshot> items, List<String> commands, Long cooldown) { this.id = id; this.description = description; this.items = items; this.commands = commands; this.cooldown = cooldown; }
Example #7
Source File: SerializeService.java From Web-API with MIT License | 5 votes |
public ObjectMapper getDefaultObjectMapper(boolean xml, boolean details, TreeNode perms) { if (perms == null) { throw new NullPointerException("Permissions may not be null"); } ObjectMapper om = xml ? new XmlMapper() : new ObjectMapper(); if (xml) { ((XmlMapper)om).configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true); } om.setSerializationInclusion(JsonInclude.Include.NON_NULL); SimpleModule mod = new SimpleModule(); for (Map.Entry<Class, BaseSerializer> entry : serializers.entrySet()) { mod.addSerializer(entry.getKey(), entry.getValue()); } mod.addDeserializer(ItemStack.class, new ItemStackDeserializer()); mod.addDeserializer(BlockState.class, new BlockStateDeserializer()); mod.addDeserializer(ItemStackSnapshot.class, new ItemStackSnapshotDeserializer()); mod.addDeserializer(CachedLocation.class, new CachedLocationDeserializer()); mod.addDeserializer(CachedPlayer.class, new CachedPlayerDeserializer()); mod.addDeserializer(CachedWorld.class, new CachedWorldDeserializer()); mod.addDeserializer(CachedCatalogType.class, new CachedCatalogTypeDeserializer<>(CatalogType.class)); om.registerModule(mod); SimpleFilterProvider filterProvider = new SimpleFilterProvider(); filterProvider.addFilter(BaseFilter.ID, new BaseFilter(details, perms)); om.setFilterProvider(filterProvider); om.setAnnotationIntrospector(new AnnotationIntrospector()); return om; }
Example #8
Source File: ItemStackSnapshotDeserializer.java From Web-API with MIT License | 5 votes |
@Override public ItemStackSnapshot deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { JsonNode root = p.readValueAsTree(); if (root.path("type").isMissingNode()) throw new IOException("Missing item type"); String id = root.path("type").isTextual() ? root.path("type").asText() : root.path("type").path("id").asText(); Optional<ItemType> optType = Sponge.getRegistry().getType(ItemType.class, id); if (!optType.isPresent()) throw new IOException("Invalid item type " + id); Integer amount = root.path("quantity").isMissingNode() ? 1 : root.path("quantity").asInt(); ItemType type = optType.get(); ItemStack.Builder builder = ItemStack.builder().itemType(type).quantity(amount); ItemStack item = builder.build(); if (!root.path("data").isMissingNode()) { Iterator<Map.Entry<String, JsonNode>> it = root.path("data").fields(); while (it.hasNext()) { Map.Entry<String, JsonNode> entry = it.next(); Class<? extends DataManipulator> c = WebAPI.getSerializeService().getSupportedData().get(entry.getKey()); if (c == null) continue; Optional<? extends DataManipulator> optData = item.getOrCreate(c); if (!optData.isPresent()) throw new IOException("Invalid item data: " + entry.getKey()); DataManipulator data = optData.get(); item.offer(data); } } return item.createSnapshot(); }
Example #9
Source File: FlagGui.java From RedProtect with GNU General Public License v3.0 | 5 votes |
@Listener public void onInventoryClick(ClickInventoryEvent event) { if (event.getTargetInventory().getName().get().equals(this.inv.getName().get())) { if (this.editable) { return; } if (event.getTransactions().size() > 0) { Transaction<ItemStackSnapshot> clickTransaction = event.getTransactions().get(0); ItemStack item = clickTransaction.getOriginal().createStack(); if (!RedProtect.get().getVersionHelper().getItemType(item).equals(ItemTypes.NONE) && item.get(Keys.ITEM_LORE).isPresent()) { String flag = item.get(Keys.ITEM_LORE).get().get(1).toPlain().replace("ยง0", ""); if (RedProtect.get().config.getDefFlags().contains(flag)) { if (RedProtect.get().config.configRoot().flags_configuration.change_flag_delay.enable) { if (RedProtect.get().config.configRoot().flags_configuration.change_flag_delay.flags.contains(flag)) { if (!RedProtect.get().changeWait.contains(this.region.getName() + flag)) { applyFlag(flag, item, event); RedProtect.get().getUtil().startFlagChanger(this.region.getName(), flag, this.player); } else { RedProtect.get().lang.sendMessage(player, RedProtect.get().lang.get("gui.needwait.tochange").replace("{seconds}", RedProtect.get().config.configRoot().flags_configuration.change_flag_delay.seconds + "")); event.setCancelled(true); } return; } else { applyFlag(flag, item, event); return; } } else { applyFlag(flag, item, event); return; } } event.setCancelled(true); } } } }
Example #10
Source File: ItemListener.java From UltimateCore with MIT License | 5 votes |
@Listener public void onInteract(InteractItemEvent event) { ModuleConfig config = Modules.BLACKLIST.get().getConfig().get(); CommentedConfigurationNode hnode = config.get(); ItemStackSnapshot item = event.getItemStack(); CommentedConfigurationNode node = hnode.getNode("items", item.getType().getId()); if (!node.isVirtual()) { if (node.getNode("deny-use").getBoolean()) { event.setCancelled(true); } } }
Example #11
Source File: SpongeUnimplemented.java From VirtualChest with GNU Lesser General Public License v3.0 | 5 votes |
public static boolean isNBTMatched(Optional<DataView> matcher, ItemStackSnapshot item) { try { Object nbt2 = GET_TAG_COMPOUND.invoke(FROM_SNAPSHOT_TO_NATIVE.invoke(item)); Object nbt1 = matcher.isPresent() ? TRANSLATE_DATA.invoke(GET_INSTANCE.invoke(), matcher.get()) : null; return (boolean) ARE_NBT_EQUALS.invoke(nbt1, nbt2, true); } catch (Throwable throwable) { throw new UnsupportedOperationException(throwable); } }
Example #12
Source File: SpongeUnimplemented.java From VirtualChest with GNU Lesser General Public License v3.0 | 5 votes |
public static void setItemHeldByMouse(Player player, ItemStackSnapshot stack) { try { SET_ITEM_STACK.invoke(player.getInventory(), FROM_SNAPSHOT_TO_NATIVE.invoke(stack)); UPDATE_HELD_ITEM.invoke(player); } catch (Throwable throwable) { throw new UnsupportedOperationException(throwable); } }
Example #13
Source File: SpongeUnimplemented.java From VirtualChest with GNU Lesser General Public License v3.0 | 5 votes |
public static ItemStackSnapshot getItemHeldByMouse(Player player) { try { return (ItemStackSnapshot) SNAPSHOT_OF.invoke(GET_ITEM_STACK.invoke(player.getInventory())); } catch (Throwable throwable) { throw new UnsupportedOperationException(throwable); } }
Example #14
Source File: PlayerInteractListener.java From EagleFactions with MIT License | 5 votes |
@Listener(order = Order.FIRST, beforeModifications = true) public void onItemUse(final InteractItemEvent event, @Root final Player player) { if (event.getItemStack() == ItemStackSnapshot.NONE) return; final Vector3d interactionPoint = event.getInteractionPoint().orElse(player.getLocation().getPosition()); Location<World> location = new Location<>(player.getWorld(), interactionPoint); //Handle hitting entities boolean hasHitEntity = event.getContext().containsKey(EventContextKeys.ENTITY_HIT); if(hasHitEntity) { final Entity hitEntity = event.getContext().get(EventContextKeys.ENTITY_HIT).get(); if (hitEntity instanceof Living && !(hitEntity instanceof ArmorStand)) return; location = hitEntity.getLocation(); } final ProtectionResult protectionResult = super.getPlugin().getProtectionManager().canUseItem(location, player, event.getItemStack(), true); if (!protectionResult.hasAccess()) { event.setCancelled(true); return; } }
Example #15
Source File: InventoryListener.java From Prism with MIT License | 5 votes |
/** * Saves event records when a player drops an item on to the ground. * * @param event DropItemEvent.Dispense * @param player Player */ @Listener(order = Order.POST) public void onDropItemDispense(DropItemEvent.Dispense event, @Root Player player) { if (event.getEntities().isEmpty() || !Prism.getInstance().getConfig().getEventCategory().isItemDrop()) { return; } for (Entity entity : event.getEntities()) { if (!(entity instanceof Item)) { continue; } Item item = (Item) entity; if (!item.item().exists()) { continue; } ItemStackSnapshot itemStack = item.item().get(); Prism.getInstance().getLogger().debug("Inventory dropped - {} x{}", itemStack.getType().getId(), itemStack.getQuantity()); PrismRecord.create() .source(event.getCause()) .event(PrismEvents.ITEM_DROP) .itemStack(itemStack) .location(player.getLocation()) .buildAndSave(); } }
Example #16
Source File: Kit.java From UltimateCore with MIT License | 4 votes |
public List<ItemStackSnapshot> getItems() { return this.items; }
Example #17
Source File: CachedKit.java From Web-API with MIT License | 4 votes |
@JsonDetails @ApiModelProperty(value = "The ItemStacks that are awarded to the player who buys/acquires this kit", required = true) public List<ItemStackSnapshot> getStacks() { return stacks; }
Example #18
Source File: Kit.java From UltimateCore with MIT License | 4 votes |
public void setItems(List<ItemStackSnapshot> items) { this.items = items; }
Example #19
Source File: ItemStackSnapshotSerializer.java From UltimateCore with MIT License | 4 votes |
@Override public ItemStackSnapshot deserialize(TypeToken<?> type, ConfigurationNode node) throws ObjectMappingException { ItemStack item = node.getValue(TypeToken.of(ItemStack.class)); return item.createSnapshot(); }
Example #20
Source File: CacheService.java From Web-API with MIT License | 4 votes |
/** * Returns the specified object as a cached object. Performs a deep copy if necessary. Converts all applicable * data types to their cached variants. This is especially useful if you're working with an object whose type * you don't know. Just call this method on it and the returned object will be a thread safe copy, or null if * a thread safe copy cannot be created because the object is of an unknown type. * @param obj The object which is returned in it's cached form. * @return The cached version of the object. Not necessarily the same type as the original object. {@code Null} * if the object is of an unknown type. */ public Object asCachedObject(Object obj) { // If the object is already clearly a cached object then just return it if (obj instanceof CachedObject) return obj; // If the object is a primitive type we don't have to do anything either if (obj instanceof Boolean) return obj; if (obj instanceof Integer) return obj; if (obj instanceof Float) return obj; if (obj instanceof Double) return obj; if (obj instanceof String) return obj; // Other POJOs if (obj instanceof Instant) return Instant.ofEpochMilli(((Instant)obj).toEpochMilli()); // If the object is of a type that we have a cached version for, then create one of those if (obj instanceof Player) return getPlayer((Player)obj); if (obj instanceof World) return getWorld((World)obj); if (obj instanceof Entity) return new CachedEntity((Entity)obj); if (obj instanceof Chunk) return new CachedChunk((Chunk)obj); if (obj instanceof TileEntity) return new CachedTileEntity((TileEntity)obj); if (obj instanceof PluginContainer) return getPlugin((PluginContainer)obj); if (obj instanceof Inventory) return new CachedInventory((Inventory)obj); if (obj instanceof CommandMapping) return getCommand((CommandMapping)obj); if (obj instanceof Advancement) return new CachedAdvancement((Advancement)obj); if (obj instanceof ItemStack) return ((ItemStack)obj).copy(); if (obj instanceof ItemStackSnapshot) return ((ItemStackSnapshot)obj).copy(); if (obj instanceof Cause) return new CachedCause((Cause)obj); if (obj instanceof Location) return new CachedLocation((Location)obj); if (obj instanceof Transform) return new CachedTransform((Transform)obj); if (obj instanceof CatalogType) return new CachedCatalogType((CatalogType)obj); // If this is an unknown object type then we can't create a cached version of it, so we better not try // and save it because we don't know if it's thread safe or not. return obj.getClass().getName(); }
Example #21
Source File: ItemStackSnapshotSerializer.java From UltimateCore with MIT License | 4 votes |
@Override public void serialize(TypeToken<?> type, ItemStackSnapshot obj, ConfigurationNode value) throws ObjectMappingException { DataContainer container = obj.toContainer(); ConfigurationNode root = DataTranslators.CONFIGURATION_NODE.translate(container); value.setValue(root); }
Example #22
Source File: ItemStackSnapshotDeserializer.java From Web-API with MIT License | 4 votes |
public ItemStackSnapshotDeserializer() { super(ItemStackSnapshot.class); }
Example #23
Source File: ItemStackSnapshotView.java From Web-API with MIT License | 4 votes |
public ItemStackSnapshotView(ItemStackSnapshot value) { super(value); this.stack = value.createStack(); }
Example #24
Source File: CachedStockItem.java From Web-API with MIT License | 4 votes |
@JsonProperty @ApiModelProperty(value = "The raw ItemStack data for this shop listing", required = true) public ItemStackSnapshot getItem() { return item; }
Example #25
Source File: VirtualChestActions.java From VirtualChest with GNU Lesser General Public License v3.0 | 4 votes |
private CompletableFuture<CommandResult> processCostItem(CommandResult parent, String command, ClassToInstanceMap<Context> contextMap) { int count = Integer.parseInt(command.replaceFirst("\\s++$", "")); HandheldItemContext itemTemplate = contextMap.getInstance(Context.HANDHELD_ITEM); Optional<Player> playerOptional = contextMap.getInstance(Context.PLAYER).getPlayer(); if (Objects.isNull(itemTemplate) || !playerOptional.isPresent()) { return CompletableFuture.completedFuture(CommandResult.empty()); } Player player = playerOptional.get(); ItemStackSnapshot itemHeldByMouse = SpongeUnimplemented.getItemHeldByMouse(player); int stackUsedQuantity = SpongeUnimplemented.getCount(itemHeldByMouse); if (itemTemplate.matchItem(itemHeldByMouse)) { count -= stackUsedQuantity; if (count < 0) { ItemStack stackUsed = itemHeldByMouse.createStack(); stackUsed.setQuantity(-count); SpongeUnimplemented.setItemHeldByMouse(player, stackUsed.createSnapshot()); } else { SpongeUnimplemented.setItemHeldByMouse(player, ItemStackSnapshot.NONE); } } if (count <= 0) { return CompletableFuture.completedFuture(CommandResult.success()); } else { for (Slot slot : player.getInventory().<Slot>slots()) { Optional<ItemStack> stackOptional = slot.peek(); if (stackOptional.isPresent()) { ItemStackSnapshot slotItem = stackOptional.get().createSnapshot(); int slotItemSize = SpongeUnimplemented.getCount(slotItem); if (itemTemplate.matchItem(slotItem)) { count -= slotItemSize; if (count < 0) { ItemStack slotItemStack = slotItem.createStack(); slotItemStack.setQuantity(-count); slot.set(slotItemStack); } else { slot.clear(); } } } if (count <= 0) { return CompletableFuture.completedFuture(CommandResult.success()); } } return CompletableFuture.completedFuture(CommandResult.empty()); } }
Example #26
Source File: VirtualChestInventoryDispatcher.java From VirtualChest with GNU Lesser General Public License v3.0 | 4 votes |
public boolean isInventoryMatchingSecondaryAction(String id, ItemStackSnapshot item) { VirtualChest chest = inventories.get(id); return chest instanceof VirtualChestInventory && ((VirtualChestInventory) chest).matchSecondaryAction(item); }
Example #27
Source File: VirtualChestInventoryDispatcher.java From VirtualChest with GNU Lesser General Public License v3.0 | 4 votes |
public boolean isInventoryMatchingPrimaryAction(String id, ItemStackSnapshot item) { VirtualChest chest = inventories.get(id); return chest instanceof VirtualChestInventory && ((VirtualChestInventory) chest).matchPrimaryAction(item); }
Example #28
Source File: VirtualChestTriggerItem.java From VirtualChest with GNU Lesser General Public License v3.0 | 4 votes |
public boolean matchItemForOpeningWithSecondaryAction(ItemStackSnapshot item) { return this.enableSecondary && this.matchItem(item); }
Example #29
Source File: VirtualChestTriggerItem.java From VirtualChest with GNU Lesser General Public License v3.0 | 4 votes |
public boolean matchItemForOpeningWithPrimaryAction(ItemStackSnapshot item) { return this.enablePrimary && this.matchItem(item); }
Example #30
Source File: VirtualChestItemTemplate.java From VirtualChest with GNU Lesser General Public License v3.0 | 4 votes |
private boolean matchItemDamage(ItemStackSnapshot item) { Integer d = item.toContainer().getInt(UNSAFE_DAMAGE).orElse(0); return container.getInt(UNSAFE_DAMAGE).orElse(d).equals(d); }