org.spongepowered.api.block.tileentity.TileEntity Java Examples

The following examples show how to use org.spongepowered.api.block.tileentity.TileEntity. 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: SignUtil.java    From GriefDefender with MIT License 6 votes vote down vote up
public static Sign getSign(Location<World> location) {
    if (location == null) {
        return null;
    }

    final TileEntity tileEntity = location.getTileEntity().orElse(null);
    if (tileEntity == null) {
        return null;
    }

    if (!(tileEntity instanceof Sign)) {
        return null;
    }

    return (Sign) tileEntity;
}
 
Example #2
Source File: TileEntityServlet.java    From Web-API with MIT License 6 votes vote down vote up
@GET
@ExplicitDetails
@Permission("list")
@ApiOperation(
        value = "List tile entities",
        notes = "Get a list of all tile entities on the server (in all worlds, unless specified).")
public Collection<CachedTileEntity> listTileEntities(
        @QueryParam("world") @ApiParam("The world to filter tile entities by") CachedWorld world,
        @QueryParam("type") @ApiParam("The type if of tile entities to filter by") String typeId,
        @QueryParam("min") @ApiParam("The minimum coordinates at which the tile entity must be, min=x|y|z") Vector3i min,
        @QueryParam("max") @ApiParam("The maximum coordinates at which the tile entity must be, max=x|y|z") Vector3i max,
        @QueryParam("limit") @ApiParam("The maximum amount of tile entities returned") int limit) {

    Predicate<TileEntity> filter = te -> typeId == null || te.getType().getId().equalsIgnoreCase(typeId);

    return cacheService.getTileEntities(world, min, max, filter, limit);
}
 
Example #3
Source File: PlayerEventHandler.java    From GriefDefender with MIT License 5 votes vote down vote up
private void handleFakePlayerInteractBlockSecondary(InteractBlockEvent event, User user, Object source) {
    final BlockSnapshot clickedBlock = event.getTargetBlock();
    final Location<World> location = clickedBlock.getLocation().orElse(null);
    final GDClaim claim = this.dataStore.getClaimAt(location);
    final TileEntity tileEntity = clickedBlock.getLocation().get().getTileEntity().orElse(null);
    final TrustType trustType = (tileEntity != null && NMSUtil.getInstance().containsInventory(tileEntity)) ? TrustTypes.CONTAINER : TrustTypes.ACCESSOR;
    final Tristate result = GDPermissionManager.getInstance().getFinalPermission(event, location, claim, Flags.INTERACT_BLOCK_SECONDARY, source, event.getTargetBlock(), user, trustType, true);
    if (result == Tristate.FALSE) {
        event.setCancelled(true);
    }
}
 
Example #4
Source File: BlockEventHandler.java    From GriefDefender with MIT License 5 votes vote down vote up
public GDClaim getSourceClaim(Cause cause) {
    BlockSnapshot blockSource = cause.first(BlockSnapshot.class).orElse(null);
    LocatableBlock locatableBlock = null;
    TileEntity tileEntitySource = null;
    Entity entitySource = null;
    if (blockSource == null) {
        locatableBlock = cause.first(LocatableBlock.class).orElse(null);
        if (locatableBlock == null) {
            entitySource = cause.first(Entity.class).orElse(null);
        }
        if (locatableBlock == null && entitySource == null) {
            tileEntitySource = cause.first(TileEntity.class).orElse(null);
        }
    }

    GDClaim sourceClaim = null;
    if (blockSource != null) {
        sourceClaim = this.dataStore.getClaimAt(blockSource.getLocation().get());
    } else if (locatableBlock != null) {
        sourceClaim = this.dataStore.getClaimAt(locatableBlock.getLocation());
    } else if (tileEntitySource != null) {
        sourceClaim = this.dataStore.getClaimAt(tileEntitySource.getLocation());
    } else if (entitySource != null) {
        Entity entity = entitySource;
        if (entity instanceof Player) {
            Player player = (Player) entity;
            GDPlayerData playerData = GriefDefenderPlugin.getInstance().dataStore.getOrCreatePlayerData(player.getWorld(), player.getUniqueId());
            sourceClaim = this.dataStore.getClaimAtPlayer(playerData, player.getLocation());
        } else {
            sourceClaim = this.dataStore.getClaimAt(entity.getLocation());
        }
    }

    return sourceClaim;
}
 
Example #5
Source File: CauseContextHelper.java    From GriefDefender with MIT License 5 votes vote down vote up
public static Object getEventFakePlayerSource(Event event) {
    Object source = event.getSource();
    if (NMSUtil.getInstance().isFakePlayer(source)) {
        final Object actualSource = event.getCause().last(Object.class).orElse(null);
        if (actualSource != source && (actualSource instanceof TileEntity || actualSource instanceof Entity)) {
            return actualSource;
        }
    }
    return source;
}
 
Example #6
Source File: CacheService.java    From Web-API with MIT License 5 votes vote down vote up
/**
 * Tries to get a tile entity at the specified location.
 * @param world The world in which the tile entity is located.
 * @param x The x-coordinate of the location where the tile entity is located.
 * @param y The y-coordinate of the location where the tile entity is located.
 * @param z The z-coordinate of the location where the tile entity is located.
 * @return An optional containing the tile entity if it was found, empty otherwise.
 */
public Optional<CachedTileEntity> getTileEntity(CachedWorld world, int x, int y, int z) {
    return WebAPI.runOnMain(() -> {
        Optional<?> w = world.getLive();
        if (!w.isPresent())
            throw new InternalServerErrorException("Could not get live world");

        Optional<TileEntity> ent = ((World)w.get()).getTileEntity(x, y, z);
        if (!ent.isPresent() || !ent.get().isValid()) {
            return Optional.empty();
        }

        return Optional.of(new CachedTileEntity(ent.get()));
    });
}
 
Example #7
Source File: CachedTileEntity.java    From Web-API with MIT License 5 votes vote down vote up
public CachedTileEntity(TileEntity te) {
    super(te);

    this.type = te.getType() instanceof CatalogType ? new CachedCatalogType(te.getType()) : null;
    this.location = new CachedLocation(te.getLocation());

    if (te instanceof TileEntityCarrier) {
        this.inventory = new CachedInventory(((TileEntityCarrier)te).getInventory());
    }
}
 
Example #8
Source File: BlockEventHandler.java    From GriefPrevention with MIT License 5 votes vote down vote up
public GPClaim getSourceClaim(Cause cause) {
    BlockSnapshot blockSource = cause.first(BlockSnapshot.class).orElse(null);
    LocatableBlock locatableBlock = null;
    TileEntity tileEntitySource = null;
    Entity entitySource = null;
    if (blockSource == null) {
        locatableBlock = cause.first(LocatableBlock.class).orElse(null);
        if (locatableBlock == null) {
            entitySource = cause.first(Entity.class).orElse(null);
        }
        if (locatableBlock == null && entitySource == null) {
            tileEntitySource = cause.first(TileEntity.class).orElse(null);
        }
    }

    GPClaim sourceClaim = null;
    if (blockSource != null) {
        sourceClaim = this.dataStore.getClaimAt(blockSource.getLocation().get());
    } else if (locatableBlock != null) {
        sourceClaim = this.dataStore.getClaimAt(locatableBlock.getLocation());
    } else if (tileEntitySource != null) {
        sourceClaim = this.dataStore.getClaimAt(tileEntitySource.getLocation());
    } else if (entitySource != null) {
        Entity entity = entitySource;
        if (entity instanceof Player) {
            Player player = (Player) entity;
            GPPlayerData playerData = GriefPreventionPlugin.instance.dataStore.getOrCreatePlayerData(player.getWorld(), player.getUniqueId());
            sourceClaim = this.dataStore.getClaimAtPlayer(playerData, player.getLocation());
        } else {
            sourceClaim = this.dataStore.getClaimAt(entity.getLocation());
        }
    }

    return sourceClaim;
}
 
Example #9
Source File: EconomyManager.java    From RedProtect with GNU General Public License v3.0 5 votes vote down vote up
public static long getRegionValue(Region r) {
    long regionCost = 0;
    World w = RedProtect.get().getServer().getWorld(r.getWorld()).get();
    int maxX = r.getMaxMbrX();
    int minX = r.getMinMbrX();
    int maxZ = r.getMaxMbrZ();
    int minZ = r.getMinMbrZ();
    for (int x = minX; x < maxX; x++) {
        for (int y = 0; y < 256; y++) {
            for (int z = minZ; z < maxZ; z++) {

                BlockSnapshot b = w.createSnapshot(x, y, z);
                if (b.getState().getType().equals(BlockTypes.AIR)) {
                    continue;
                }

                if (b.getLocation().get().getTileEntity().isPresent()) {
                    TileEntity invTile = b.getLocation().get().getTileEntity().get();
                    if (invTile instanceof TileEntityInventory) {
                        TileEntityInventory<?> inv = (TileEntityInventory<?>) invTile;
                        regionCost += getInvValue(inv.slots());
                    }
                } else {
                    regionCost += RedProtect.get().config.ecoRoot().items.values.get(b.getState().getType().getName());
                }
            }
        }
    }
    r.setValue(regionCost);
    return regionCost;
}
 
Example #10
Source File: BlockEventHandler.java    From GriefDefender with MIT License 4 votes vote down vote up
@Listener(order = Order.FIRST, beforeModifications = true)
public void onBlockNotify(NotifyNeighborBlockEvent event) {
    LocatableBlock locatableBlock = event.getCause().first(LocatableBlock.class).orElse(null);
    TileEntity tileEntity = event.getCause().first(TileEntity.class).orElse(null);
    Location<World> sourceLocation = locatableBlock != null ? locatableBlock.getLocation() : tileEntity != null ? tileEntity.getLocation() : null;
    GDClaim sourceClaim = null;
    GDPlayerData playerData = null;
    if (sourceLocation != null) {
        if (GriefDefenderPlugin.isSourceIdBlacklisted("block-notify", event.getSource(), sourceLocation.getExtent().getProperties())) {
            return;
        }
    }

    final User user = CauseContextHelper.getEventUser(event);
    if (user == null) {
        return;
    }
    if (sourceLocation == null) {
        Player player = event.getCause().first(Player.class).orElse(null);
        if (player == null) {
            return;
        }

        sourceLocation = player.getLocation();
        playerData = GriefDefenderPlugin.getInstance().dataStore.getOrCreatePlayerData(player.getWorld(), player.getUniqueId());
        sourceClaim = this.dataStore.getClaimAtPlayer(playerData, player.getLocation());
    } else {
        playerData = GriefDefenderPlugin.getInstance().dataStore.getOrCreatePlayerData(sourceLocation.getExtent(), user.getUniqueId());
        sourceClaim = this.dataStore.getClaimAt(sourceLocation);
    }

    if (!GriefDefenderPlugin.getInstance().claimsEnabledForWorld(sourceLocation.getExtent().getUniqueId())) {
        return;
    }

    GDTimings.BLOCK_NOTIFY_EVENT.startTimingIfSync();
    Iterator<Direction> iterator = event.getNeighbors().keySet().iterator();
    GDClaim targetClaim = null;
    while (iterator.hasNext()) {
        Direction direction = iterator.next();
        Location<World> location = sourceLocation.getBlockRelative(direction);
        Vector3i pos = location.getBlockPosition();
        targetClaim = this.dataStore.getClaimAt(location, targetClaim);
        if (sourceClaim.isWilderness() && targetClaim.isWilderness()) {
            if (playerData != null) {
                playerData.eventResultCache = new EventResultCache(targetClaim, "block-notify", Tristate.TRUE);
            }
            continue;
        } else if (!sourceClaim.isWilderness() && targetClaim.isWilderness()) {
            if (playerData != null) {
                playerData.eventResultCache = new EventResultCache(targetClaim, "block-notify", Tristate.TRUE);
            }
            continue;
        } else if (sourceClaim.getUniqueId().equals(targetClaim.getUniqueId())) {
            if (playerData != null) {
                playerData.eventResultCache = new EventResultCache(targetClaim, "block-notify", Tristate.TRUE);
            }
            continue;
        } else {
            if (playerData.eventResultCache != null && playerData.eventResultCache.checkEventResultCache(targetClaim, "block-notify") == Tristate.TRUE) {
                continue;
            }
            // Needed to handle levers notifying doors to open etc.
            if (targetClaim.isUserTrusted(user, TrustTypes.ACCESSOR)) {
                if (playerData != null) {
                    playerData.eventResultCache = new EventResultCache(targetClaim, "block-notify", Tristate.TRUE, TrustTypes.ACCESSOR.getName().toLowerCase());
                }
                continue;
            }
        }

        // no claim crossing unless trusted
        iterator.remove();
    }
    GDTimings.BLOCK_NOTIFY_EVENT.stopTimingIfSync();
}
 
Example #11
Source File: ExplosionListener.java    From EagleFactions with MIT License 4 votes vote down vote up
@Listener(order = Order.FIRST, beforeModifications = true)
public void onExplosionPre(final ExplosionEvent.Pre event)
{
    final EventContext context = event.getContext();
    final Cause cause = event.getCause();

    User user = null;
    if (cause.root() instanceof TileEntity) {
        user = context.get(EventContextKeys.OWNER)
                .orElse(context.get(EventContextKeys.NOTIFIER)
                        .orElse(context.get(EventContextKeys.CREATOR)
                                .orElse(null)));
    } else {
        user = context.get(EventContextKeys.NOTIFIER)
                .orElse(context.get(EventContextKeys.OWNER)
                        .orElse(context.get(EventContextKeys.CREATOR)
                                .orElse(null)));
    }

    if(event.getCause().containsType(Player.class))
    {
        user = event.getCause().first(Player.class).get();
    }
    else if(event.getCause().containsType(User.class))
    {
        user = event.getCause().first(User.class).get();
    }

    final Location<World> location = event.getExplosion().getLocation();
    if (user == null)
    {
        if(!super.getPlugin().getProtectionManager().canExplode(location).hasAccess())
        {
            event.setCancelled(true);
            return;
        }
    }
    else
    {
        if (!super.getPlugin().getProtectionManager().canExplode(location, user, false).hasAccess())
        {
            event.setCancelled(true);
            return;
        }
    }
}
 
Example #12
Source File: ExplosionListener.java    From EagleFactions with MIT License 4 votes vote down vote up
@Listener(order = Order.FIRST, beforeModifications = true)
public void onExplosion(final ExplosionEvent.Detonate event)
{
    final List<Location<World>> locationList = new ArrayList<>(event.getAffectedLocations());
    final List<Entity> entityList = new ArrayList<>(event.getEntities());
    User user = null;
    final Cause cause = event.getCause();
    final EventContext context = event.getContext();
    if (cause.root() instanceof TileEntity) {
        user = context.get(EventContextKeys.OWNER)
                .orElse(context.get(EventContextKeys.NOTIFIER)
                        .orElse(context.get(EventContextKeys.CREATOR)
                                .orElse(null)));
    } else {
        user = context.get(EventContextKeys.NOTIFIER)
                .orElse(context.get(EventContextKeys.OWNER)
                        .orElse(context.get(EventContextKeys.CREATOR)
                                .orElse(null)));
    }

    if(event.getCause().containsType(Player.class))
    {
        user = event.getCause().first(Player.class).get();
    }
    else if(event.getCause().containsType(User.class))
    {
        user = event.getCause().first(User.class).get();
    }

    for(final Entity entity : entityList)
    {
        final Location<World> entityLocation = entity.getLocation();
        if(user != null)
        {
            if(!super.getPlugin().getProtectionManager().canExplode(entityLocation, user, false).hasAccess())
            {
                event.getEntities().remove(entity);
            }
        }
        else if(!super.getPlugin().getProtectionManager().canExplode(entityLocation).hasAccess())
        {
            event.getEntities().remove(entity);
        }
    }

    for(final Location<World> location : locationList)
    {
        if(user != null)
        {
            if(!super.getPlugin().getProtectionManager().canExplode(location, user, false).hasAccess())
            {
                event.getAffectedLocations().remove(location);
            }
        }
        else if(!super.getPlugin().getProtectionManager().canExplode(location).hasAccess())
        {
            event.getAffectedLocations().remove(location);
        }
    }
}
 
Example #13
Source File: TileEntityServlet.java    From Web-API with MIT License 4 votes vote down vote up
@PUT
@Path("/{world}/{x}/{y}/{z}")
@Permission("modify")
@ApiOperation(
        value = "Modify tile entity",
        notes = "Modify the properties of an existing tile entity.")
public CachedTileEntity modifyTileEntity(
        @PathParam("world") @ApiParam("The world the tile entity is in") CachedWorld world,
        @PathParam("x") @ApiParam("The x-coordinate of the tile-entity") Integer x,
        @PathParam("y") @ApiParam("The y-coordinate of the tile-entity") Integer y,
        @PathParam("z") @ApiParam("The z-coordinate of the tile-entity") Integer z,
        UpdateTileEntityRequest req)
        throws NotFoundException, BadRequestException {

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

    Optional<CachedTileEntity> optTe = cacheService.getTileEntity(world, x, y, z);
    if (!optTe.isPresent()) {
        throw new NotFoundException("Tile entity in world '" + world.getName() +
                "' at [" + x + "," + y + "," + z + "] could not be found");
    }

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

        TileEntity live = optLive.get();

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

            try {
                Inventory inv = ((TileEntityCarrier) live).getInventory();
                inv.clear();
                for (ItemStack stack : req.getInventory()) {
                    inv.offer(stack);
                }
            } catch (Exception e) {
                throw new InternalServerErrorException(e.getMessage());
            }
        }

        return new CachedTileEntity(live);
    });
}
 
Example #14
Source File: CacheService.java    From Web-API with MIT License 4 votes vote down vote up
/**
 * 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 #15
Source File: CachedTileEntity.java    From Web-API with MIT License 4 votes vote down vote up
@Override
public Optional<TileEntity> getLive() {
    Optional<Location> obj = location.getLive();
    return obj.flatMap(o -> ((Location<World>) o).getTileEntity());
}
 
Example #16
Source File: PlayerInteractListener.java    From EssentialCmds with MIT License 4 votes vote down vote up
@Listener
public void onPlayerInteractBlock(InteractBlockEvent event, @Root Player player)
{
	if (EssentialCmds.frozenPlayers.contains(player.getUniqueId()))
	{
		player.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "You cannot interact while frozen."));
		event.setCancelled(true);
		return;
	}

	if (EssentialCmds.jailedPlayers.contains(player.getUniqueId()))
	{
		player.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "You cannot interact while jailed."));
		event.setCancelled(true);
		return;
	}

	Optional<Location<World>> optLocation = event.getTargetBlock().getLocation();

	if (optLocation.isPresent() && optLocation.get().getTileEntity().isPresent())
	{
		Location<World> location = optLocation.get();
		TileEntity clickedEntity = location.getTileEntity().get();

		if (event.getTargetBlock().getState().getType().equals(BlockTypes.STANDING_SIGN) || event.getTargetBlock().getState().getType().equals(BlockTypes.WALL_SIGN))
		{
			Optional<SignData> signData = clickedEntity.getOrCreate(SignData.class);

			if (signData.isPresent())
			{
				SignData data = signData.get();
				CommandManager cmdService = Sponge.getGame().getCommandManager();
				String line0 = data.getValue(Keys.SIGN_LINES).get().get(0).toPlain();
				String line1 = data.getValue(Keys.SIGN_LINES).get().get(1).toPlain();
				String command = "warp " + line1;

				if (line0.equals("[Warp]"))
				{
					if (player.hasPermission("essentialcmds.warps.use.sign"))
					{
						cmdService.process(player, command);
					}
					else
					{
						player.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "You do not have permission to use Warp Signs!"));
					}
				}
			}
		}
	}
}