org.spongepowered.api.item.inventory.Inventory Java Examples

The following examples show how to use org.spongepowered.api.item.inventory.Inventory. 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: VersionHelper56.java    From RedProtect with GNU General Public License v3.0 6 votes vote down vote up
@Override
public long getInvValue(Iterable<Inventory> inv) {
    long value = 0;
    for (Inventory item : inv) {
        if (!item.peek().isPresent()) {
            continue;
        }
        ItemStack stack = item.peek().get();
        value += ((RedProtect.get().config.ecoRoot().items.values.get(stack.getItem().getName()) * stack.getQuantity()));
        if (stack.get(Keys.ITEM_ENCHANTMENTS).isPresent()) {
            for (ItemEnchantment enchant : stack.get(Keys.ITEM_ENCHANTMENTS).get()) {
                value += ((RedProtect.get().config.ecoRoot().enchantments.values.get(enchant.getEnchantment().getName()) * enchant.getLevel()));
            }
        }
    }
    return value;
}
 
Example #2
Source File: InventoryListener.java    From UltimateCore with MIT License 6 votes vote down vote up
@Listener
@Exclude({ClickInventoryEvent.Close.class, ClickInventoryEvent.Open.class})
public void onInteract(ClickInventoryEvent event, @Root Player p) {
    try {
        //Get target inventory owner
        Inventory inv = event.getTargetInventory();
        if (!(inv instanceof CarriedInventory)) return;
        CarriedInventory cinv = (CarriedInventory) inv;
        if (!cinv.getCarrier().isPresent() || !(cinv.getCarrier().get() instanceof User)) return;
        User t = (User) cinv.getCarrier().get();

        //Check if player is in invsee & Cancel event if player doesn't have permission
        UltimateUser up = UltimateCore.get().getUserService().getUser(p);
        if (up.get(InventoryKeys.INVSEE_TARGET).isPresent() && up.get(InventoryKeys.INVSEE_TARGET).get().equals(t.getUniqueId())) {
            if (!p.hasPermission("uc.inventory.invsee.modify")) {
                event.getCursorTransaction().setValid(false);
                event.setCancelled(true);
            }
        }
    } catch (Exception ignore) {
    }
}
 
Example #3
Source File: ItemListener.java    From UltimateCore with MIT License 6 votes vote down vote up
@Listener
public void onChange(ChangeInventoryEvent event, @First Player p) {
    ModuleConfig config = Modules.BLACKLIST.get().getConfig().get();
    CommentedConfigurationNode hnode = config.get();
    try {
        for (Inventory s : event.getTargetInventory().slots()) {
            ItemStack item = s.peek();
            CommentedConfigurationNode node = hnode.getNode("items", item.getType().getKey());
            if (!node.isVirtual()) {
                if (node.getNode("deny-possession").getBoolean()) {
                    s.poll();
                }
            }
        }
    } catch (Exception ignore) {
    }
}
 
Example #4
Source File: VersionHelper8.java    From RedProtect with GNU General Public License v3.0 6 votes vote down vote up
@Override
public long getInvValue(Iterable<Inventory> inv) {
    long value = 0;
    for (Inventory item : inv) {
        if (item.peek().isEmpty()) {
            continue;
        }
        ItemStack stack = item.peek();
        value += ((RedProtect.get().config.ecoRoot().items.values.get(stack.getType().getName()) * stack.getQuantity()));
        if (stack.get(Keys.ITEM_ENCHANTMENTS).isPresent()) {
            for (Enchantment enchant : stack.get(Keys.ITEM_ENCHANTMENTS).get()) {
                value += ((RedProtect.get().config.ecoRoot().enchantments.values.get(enchant.getType().getName()) * enchant.getLevel()));
            }
        }
    }
    return value;
}
 
Example #5
Source File: VersionHelper7.java    From RedProtect with GNU General Public License v3.0 6 votes vote down vote up
@Override
public long getInvValue(Iterable<Inventory> inv) {
    long value = 0;
    for (Inventory item : inv) {
        if (!item.peek().isPresent()) {
            continue;
        }
        ItemStack stack = item.peek().get();
        value += ((RedProtect.get().config.ecoRoot().items.values.get(stack.getType().getName()) * stack.getQuantity()));
        if (stack.get(Keys.ITEM_ENCHANTMENTS).isPresent()) {
            for (Enchantment enchant : stack.get(Keys.ITEM_ENCHANTMENTS).get()) {
                value += ((RedProtect.get().config.ecoRoot().enchantments.values.get(enchant.getType().getName()) * enchant.getLevel()));
            }
        }
    }
    return value;
}
 
Example #6
Source File: MobFlagGui.java    From RedProtect with GNU General Public License v3.0 6 votes vote down vote up
public void open() {
    //Register Listener
    Sponge.getGame().getEventManager().registerListeners(RedProtect.get().container, this);

    Inventory inv = RedProtect.get().getVersionHelper().newInventory(54, "Item flag GUI");

    int i = 0;
    while (i < this.guiItems.length) {
        int line = 0;
        int slot = i;
        if (i > 8) {
            line = i / 9;
            slot = i - (line * 9);
        }
        RedProtect.get().getVersionHelper().query(inv, slot, line).set(this.guiItems[i]);
        i++;
    }

    RedProtect.get().getVersionHelper().openInventory(inv, this.player);
}
 
Example #7
Source File: ItemFlagGui.java    From RedProtect with GNU General Public License v3.0 6 votes vote down vote up
public void open() {
    //Register Listener
    Sponge.getGame().getEventManager().registerListeners(RedProtect.get().container, this);

    Inventory inv = RedProtect.get().getVersionHelper().newInventory(54, "Item flag GUI");

    int i = 0;
    while (i < this.guiItems.length) {
        int line = 0;
        int slot = i;
        if (i > 8) {
            line = i / 9;
            slot = i - (line * 9);
        }
        RedProtect.get().getVersionHelper().query(inv, slot, line).set(this.guiItems[i]);
        i++;
    }

    RedProtect.get().getVersionHelper().openInventory(inv, this.player);
}
 
Example #8
Source File: WandCommand.java    From RedProtect with GNU General Public License v3.0 6 votes vote down vote up
public CommandSpec register() {
    return CommandSpec.builder()
            .description(Text.of("Command to get wand tool"))
            .permission("redprotect.command.wand")
            .executor((src, args) -> {
                if (!(src instanceof Player)) {
                    HandleHelpPage(src, 1);
                } else {
                    Player player = (Player) src;
                    if (RedProtect.get().config.getWorldClaimType(player.getWorld().getName()).equalsIgnoreCase("BLOCK") && !RedProtect.get().ph.hasPerm(player, "redprotect.command.admin.wand"))
                        return CommandResult.success();

                    Inventory inv = player.getInventory();
                    ItemType mat = Sponge.getRegistry().getType(ItemType.class, RedProtect.get().config.configRoot().wands.adminWandID).orElse(ItemTypes.GLASS_BOTTLE);
                    ItemStack item = ItemStack.of(mat, 1);
                    item.offer(Keys.ITEM_ENCHANTMENTS, new ArrayList<>());

                    if (inv.query(Hotbar.class).offer(item).getType().equals(InventoryTransactionResult.Type.SUCCESS)) {
                        RedProtect.get().lang.sendMessage(player, RedProtect.get().lang.get("cmdmanager.wand.given").replace("{item}", mat.getName()));
                    } else {
                        RedProtect.get().lang.sendMessage(player, RedProtect.get().lang.get("cmdmanager.wand.nospace").replace("{item}", mat.getName()));
                    }
                }
                return CommandResult.success();
            }).build();
}
 
Example #9
Source File: CachedInventory.java    From Web-API with MIT License 6 votes vote down vote up
public CachedInventory(Inventory inv) {
    super(inv, false);

    this.name = inv.getName().get();
    this.capacity = inv.capacity();
    this.totalItems = inv.totalItems();
    this.type = new CachedCatalogType<>(inv.getArchetype());

    try {
        this.slots = new ArrayList<>();
        for (Inventory subInv : inv.slots()) {
            if (subInv.totalItems() == 0) {
                continue;
            }
            this.slots.add(new CachedSlot((Slot) subInv));
        }
    } catch (AbstractMethodError ignored) {}
}
 
Example #10
Source File: SpongeUnimplemented.java    From VirtualChest with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static void openInventory(Player player, Inventory inventory, Object causeObj)
{
    try
    {
        if (PLAYER_OPEN_INVENTORY.type().parameterCount() > 2)
        {
            PLAYER_OPEN_INVENTORY.invoke(player, inventory, createCause(causeObj));
        }
        else
        {
            PLAYER_OPEN_INVENTORY.invoke(player, inventory);
        }
    }
    catch (Throwable throwable)
    {
        throw new UnsupportedOperationException(throwable);
    }
}
 
Example #11
Source File: InventorySerializer.java    From EagleFactions with MIT License 6 votes vote down vote up
public static List<DataView> serializeInventory(Inventory inventory) {
    DataContainer container;
    List<DataView> slots = new LinkedList<>();

    int i = 0;
    Optional<ItemStack> stack;

    for (Inventory inv : inventory.slots()) {
        stack = inv.peek();

        if (stack.isPresent()) {
            container = DataContainer.createNew(SafetyMode.ALL_DATA_CLONED);

            container.set(SLOT, i);
            container.set(STACK, serializeItemStack(stack.get()));

            slots.add(container);
        }

        i++;
    }

    return slots;
}
 
Example #12
Source File: AbstractFactionStorage.java    From EagleFactions with MIT License 6 votes vote down vote up
private FactionChest getFactionChest(final Connection connection, final String factionName) throws SQLException, IOException, ClassNotFoundException
{
    FactionChest factionChest = new FactionChestImpl(factionName);
    PreparedStatement preparedStatement = connection.prepareStatement(SELECT_CHEST_WHERE_FACTIONNAME);
    preparedStatement.setString(1, factionName);
    ResultSet resultSet = preparedStatement.executeQuery();
    if (resultSet.first())
    {
        byte[] factionChestItems = resultSet.getBytes("ChestItems");
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(factionChestItems);
        DataContainer dataContainer = DataFormats.NBT.readFrom(byteArrayInputStream);
        byteArrayInputStream.close();
        Inventory inventory = Inventory.builder().of(InventoryArchetypes.CHEST).build(this.plugin);
        InventorySerializer.deserializeInventory(dataContainer.getViewList(DataQuery.of("inventory")).orElse(new ArrayList<>()), inventory);
        factionChest = new FactionChestImpl(factionName, inventory);
    }
    resultSet.close();
    preparedStatement.close();
    return factionChest;
}
 
Example #13
Source File: FactionChestImpl.java    From EagleFactions with MIT License 6 votes vote down vote up
private List<SlotItem> toSlotItems(final Inventory inventory)
{
    final List<FactionChest.SlotItem> slotItemList = new ArrayList<>();
    final Iterable<Inventory> slots = inventory.slots();
    int column = 1;
    int row = 1;
    for(Inventory slot : slots)
    {
        Optional<ItemStack> optionalItemStack = slot.peek();
        if(optionalItemStack.isPresent())
        {
            slotItemList.add(new FactionChestImpl.SlotItemImpl(column, row, optionalItemStack.get()));
        }

        column++;
        if(column > 9)
        {
            row++;
            column = 1;
        }

        if(row > 3)
            break;
    }
    return slotItemList;
}
 
Example #14
Source File: StateContainer.java    From HuskyUI-Plugin with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Opens a specific {@link State} for a {@link Player},
 * based on the expected ID of the State.
 *
 * @param player the Player to display the State to
 * @param id the ID of the State being requested
 */
public void openState(@Nonnull final Player player, @Nonnull final String id) {
    int pagenum = 0;
    String pageID = id;
    if(id.contains("#")){
        try {
            pagenum = Integer.valueOf(id.split("#")[1]);
            pageID=id.split("#")[0];
        }catch(Exception e){
            fail(player, "Attempted to open an invalid pagenum!");
        }
    }
    State state = this.states.get(pageID);

    if (state == null) {
        fail(player, "Attempted to open a nonexistent state!");
        fail(player, "Invalid ID: " + id);
        InventoryUtil.close(player);
        return;
    }
    state = state.copy(this);

    state.setObserver(player);

    if (state instanceof Page) {
        //InventoryUtil.close(player);
        Page page = (Page) state;
        Inventory toShow = page.getPageView(pagenum);
        InventoryUtil.open(player, toShow);

        return;
    }

    InventoryUtil.close(player);
    fail(player, "Attempted to open an invalid or incomplete state!");
    fail(player, "Invalid ID: " + id);
}
 
Example #15
Source File: VersionHelper7.java    From RedProtect with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Inventory newInventory(int size, String name) {
    return Inventory.builder().of(InventoryArchetypes.DOUBLE_CHEST)
            .property(InventoryDimension.of(new Vector2i(9, size / 9)))
            .property(InventoryTitle.of(RedProtect.get().getUtil().toText(name)))
            .build(RedProtect.get().container);
}
 
Example #16
Source File: FactionChestImpl.java    From EagleFactions with MIT License 5 votes vote down vote up
@Override
public Inventory getInventory()
{
    if(this.inventory == null)
        this.inventory = buildInventory(new ArrayList<>());
    return this.inventory;
}
 
Example #17
Source File: FactionChestImpl.java    From EagleFactions with MIT License 5 votes vote down vote up
private Inventory buildInventory(final List<SlotItem> slotItems)
{
    //Create inventory
    final Inventory inventory = Inventory.builder()
            .of(InventoryArchetypes.CHEST)
            .property(InventoryTitle.of(Text.of(TextColors.BLUE, Text.of("Faction's chest"))))
            .listener(InteractInventoryEvent.Close.class, (x) ->
            {
                final Faction faction = EagleFactionsPlugin.getPlugin().getFactionLogic().getFactionByName(factionName);
                if(faction != null)
                {
                    EagleFactionsPlugin.getPlugin().getFactionLogic().setChest(faction, this);
                }
            })
            .build(EagleFactionsPlugin.getPlugin());

    //Fill it with items
    int column = 1;
    int row = 1;

    for(final Inventory slot : inventory.slots())
    {
        ItemStack itemStack = getAtPosition(slotItems, row, column);
        if(itemStack != null)
            slot.offer(itemStack);

        column++;
        if(column > 9)
        {
            column = 1;
            row++;
        }
    }

    return inventory;
}
 
Example #18
Source File: VersionHelper8.java    From RedProtect with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Inventory newInventory(int size, String name) {
    return Inventory.builder().of(InventoryArchetypes.DOUBLE_CHEST)
            .property(InventoryDimension.of(new Vector2i(9, size / 9)))
            .property(InventoryTitle.of(RedProtect.get().getUtil().toText(name)))
            .build(RedProtect.get().container);
}
 
Example #19
Source File: WorkbenchCommand.java    From UltimateCore with MIT License 5 votes vote down vote up
@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
    checkIfPlayer(src);
    Player p = (Player) src;

    Inventory i = Inventory.builder().of(InventoryArchetypes.WORKBENCH).build(UltimateCore.get());
    p.openInventory(i);
    return CommandResult.success();
}
 
Example #20
Source File: VersionHelper56.java    From RedProtect with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Inventory newInventory(int size, String name) {
    return Inventory.builder().of(InventoryArchetypes.DOUBLE_CHEST)
            .property(InventoryDimension.PROPERTY_NAME, new InventoryDimension(9, size / 9))
            .property(InventoryTitle.PROPERTY_NAME, InventoryTitle.of(RedProtect.get().getUtil().toText(name)))
            .build(RedProtect.get().container);
}
 
Example #21
Source File: Action.java    From HuskyUI-Plugin with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Performs this Action.
 *
 * @param currentState the current State before the Action is performed
 */
public void runAction(@Nonnull final String currentState, final Inventory inventory) {
    switch (this.type) {
        case CLOSE:
            InventoryUtil.close(this.observer);
            break;
        case BACK:
            if (this.container.hasState(currentState)) {
                if (this.container.getState(currentState).hasParent()) {
                    this.container.openState(this.observer, this.container.getState(currentState).getParent());
                } else {
                    this.observer.playSound(SoundTypes.BLOCK_ANVIL_LAND, this.observer.getLocation().getPosition(), 0.5);
                    InventoryUtil.close(this.observer);
                    this.observer.sendMessage(Text.of(TextColors.RED, "Impossible BACK action - closing broken State."));
                }
            }
            break;
        case NORMAL:
            this.container.openState(this.observer, this.goalState);
            break;
        case NONE:
            // do nothing
            break;
        case REFRESH:
            Page page = ((Page)getContainer().getState(currentState));
            try {
                Consumer<Page> goo = page.getUpdateConsumer();
                if (goo != null) {
                    goo.accept(page);
                }
            }catch (Exception e){
                this.observer.sendMessage(Text.of(TextColors.RED, "Impossible refresh action - closing broken State."));
            }
            break;
        default:
            this.observer.sendMessage(Text.of("??"));
            break;
    }
}
 
Example #22
Source File: RunnableAction.java    From HuskyUI-Plugin with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Runs the additional actions.
 *
 * @param currentState the current State before the Action is performed
 */
@Override
public void runAction(@Nonnull final String currentState, Inventory inventory) {
    if (this.runnable != null) {
        this.runnable.run(this);
    } else {
        this.getObserver().sendMessage(Text.of(TextColors.RED, "Cannot run a null action!"));
    }
    super.runAction(currentState,inventory);
}
 
Example #23
Source File: VirtualChestItem.java    From VirtualChest with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void fillInventory(Player player, Inventory inventory, int index, String name)
{
    try (Timing ignored = VirtualChestTimings.setItemInInventory(name, index).startTiming())
    {
        inventory.set(this.serializer.apply(player, this.serializedStack));
    }
    catch (InvalidDataException e)
    {
        String posString = VirtualChestInventory.slotIndexToKey(index);
        throw new InvalidDataException("Find error when generating item at " + posString, e);
    }
}
 
Example #24
Source File: VersionHelper56.java    From RedProtect with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Inventory query(Inventory inventory, int x, int y) {
    return inventory.query(SlotPos.of(x, y));
}
 
Example #25
Source File: VersionHelper8.java    From RedProtect with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void openInventory(Inventory inv, Player p) {
    p.openInventory(inv);
}
 
Example #26
Source File: VersionHelper7.java    From RedProtect with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Inventory query(Inventory inventory, int x, int y) {
    return inventory.query(QueryOperationTypes.INVENTORY_PROPERTY.of(SlotPos.of(x, y)));
}
 
Example #27
Source File: InventoryUtil.java    From HuskyUI-Plugin with GNU General Public License v3.0 4 votes vote down vote up
public static void open(Player player, Inventory inventory) {
    Task.builder().execute(()-> {
        player.openInventory(inventory);
    }).delayTicks(1).submit(HuskyUI.getInstance());
}
 
Example #28
Source File: VersionHelper7.java    From RedProtect with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void openInventory(Inventory inv, Player p) {
    p.openInventory(inv);
}
 
Example #29
Source File: FactionChestImpl.java    From EagleFactions with MIT License 4 votes vote down vote up
public FactionChestImpl(final String factionName, final Inventory inventory)
{
    this.factionName = factionName;
    this.inventory = buildInventory(toSlotItems(inventory));
}
 
Example #30
Source File: EntityServlet.java    From Web-API with MIT License 4 votes vote down vote up
@PUT
@Path("/{entity}")
@Permission("modify")
@ApiOperation(
        value = "Modify an entity",
        notes = "Modify the properties of an existing entity.")
public CachedEntity modifyEntity(
        @PathParam("entity") @ApiParam("The uuid of the entity") UUID uuid,
        UpdateEntityRequest req)
        throws NotFoundException, BadRequestException {

    if (req == null) {
        throw new BadRequestException("Request body is required");
    }

    Optional<CachedEntity> optEntity = WebAPI.getCacheService().getEntity(uuid);
    if (!optEntity.isPresent()) {
        throw new NotFoundException("Entity with UUID '" + uuid + "' could not be found");
    }

    return WebAPI.runOnMain(() -> {
        Optional<Entity> optLive = optEntity.get().getLive();
        if (!optLive.isPresent())
            throw new InternalServerErrorException("Could not get live entity");

        Entity live = optLive.get();

        if (req.getWorld().isPresent()) {
            Optional<World> optWorld = req.getWorld().get().getLive();
            if (!optWorld.isPresent())
                throw new InternalServerErrorException("Could not get live world");

            if (req.getPosition() != null) {
                live.transferToWorld(optWorld.get(), req.getPosition());
            } else {
                live.transferToWorld(optWorld.get());
            }
        } else if (req.getPosition() != null) {
            live.setLocation(new Location<>(live.getWorld(), req.getPosition()));
        }
        if (req.getVelocity() != null) {
            live.setVelocity(req.getVelocity());
        }
        if (req.getRotation() != null) {
            live.setRotation(req.getRotation());
        }

        if (req.getScale() != null) {
            live.setRotation(req.getScale());
        }

        if (req.getDamage() != null) {
            DamageRequest dmgReq = req.getDamage();
            DamageSource.Builder builder = DamageSource.builder();

            if (dmgReq.getType().isPresent()) {
                Optional<DamageType> optDmgType = dmgReq.getType().get().getLive(DamageType.class);
                if (!optDmgType.isPresent())
                    throw new InternalServerErrorException("Could not get live damage type");

                builder.type(optDmgType.get());
            }

            live.damage(req.getDamage().getAmount(), builder.build());
        }

        if (req.hasInventory()) {
            if (!(live instanceof Carrier)) {
                throw new BadRequestException("Entity does not have an inventory!");
            }

            try {
                Inventory inv = ((Carrier) live).getInventory();
                for (SlotRequest slotReq : req.getInventory()) {
                    for (Inventory slot : inv.slots()) {
                        Optional<SlotIndex> optIndex = slot.getInventoryProperty(SlotIndex.class);
                        if (!optIndex.isPresent() || !slotReq.getSlotIndex().equals(optIndex.get().getValue())) {
                            continue;
                        }
                        if (slotReq.getStack().isPresent()) {
                            slot.set(slotReq.getStack().get());
                        } else {
                            slot.clear();
                        }
                    }
                }
            } catch (Exception e) {
                throw new InternalServerErrorException(e.getMessage());
            }
        }

        return new CachedEntity(live);
    });
}