Right click on door without item in hand

This was provided in the list of changes I gave you, but it appears that doors are separate items and have their own type that you can check against - no need for Keys.

But how to get the target block as an ItemStack ?

Use your IDE, the javadocs, search through the API, or simply click on the link to the docs that I’ve sent twice.

Here is my code :
String owners = “”;

@Listener
public void onRightClickOnBlock(InteractBlockEvent.Secondary event) {
    Player player = event.getCause().last(Player.class).get();
    BlockSnapshot block = event.getTargetBlock();
    
    Optional<EconomyService> serviceOpt = Sponge.getServiceManager().provide(EconomyService.class);
    EconomyService economyService = serviceOpt.get();
		
    	// Système de claim des portes    	
    	if(isClaimableDoor(block.getLocation().get())) {
    		final int x = block.getPosition().getX();
    		final int z = block.getPosition().getZ();
    		
    		event.setCancelled(true);
    		
			if(isLockPick(player.getItemInHand(HandTypes.MAIN_HAND).orElse(null))) {
        		event.setCancelled(false);
        		player.sendMessage(Text.of(TextColors.GREEN, "Vous avez ouvert la porte avec un Lock Pick !"));
    		} 
			
			if(isKey(player.getItemInHand(HandTypes.MAIN_HAND).orElse(null))) {
        		if(owners.contains("| " + x + " " + z + " " + player.getName() + " |")) {
                	event.setCancelled(false);
        		}
                else if(owners.contains("| " + x + " " + z + " ")) {
                	event.setCancelled(true);
                	player.sendMessage(Text.of(TextColors.RED, "Cette porte ne vous appartient pas !"));
                } else {
        			Optional<UniqueAccount> uOpt = economyService.getOrCreateAccount(player.getUniqueId());
    				if (uOpt.isPresent()) {
    				    UniqueAccount acc = uOpt.get();
    				    BigDecimal balance = acc.getBalance(economyService.getDefaultCurrency());
    				    
    					if(balance.intValue() >= 200) {
    						Sponge.getCommandManager().process(Sponge.getServer().getConsole(), "econ remove " + player.getName() + " 1000");
    						player.sendMessage(Text.of(TextColors.GREEN, "Vous avez acheté cette propriété pour 1000 euros ! Elle vous appartient désormais !"));
    						owners = owners + "| " + x + " " + z + " " + player.getName() + " |";
    					}
    					else {
    						player.sendMessage(Text.of(TextColors.RED, "Vous n'avez pas assez d'argent pour acheter cette propriété !"));
    					}
    				}
                }
    		}
			
			if(isKey(player.getItemInHand(HandTypes.OFF_HAND).orElse(null))) {
        		if(owners.contains("| " + x + " " + z + " " + player.getName() + " |")) {
                	event.setCancelled(false);
        		}
                else if(owners.contains("| " + x + " " + z + " ")) {
                	event.setCancelled(true);
                	player.sendMessage(Text.of(TextColors.RED, "Cette porte ne vous appartient pas !"));
                } else {
        			Optional<UniqueAccount> uOpt = economyService.getOrCreateAccount(player.getUniqueId());
    				if (uOpt.isPresent()) {
    				    UniqueAccount acc = uOpt.get();
    				    BigDecimal balance = acc.getBalance(economyService.getDefaultCurrency());
    				    
    					if(balance.intValue() >= 200) {
    						Sponge.getCommandManager().process(Sponge.getServer().getConsole(), "econ remove " + player.getName() + " 1000");
    						player.sendMessage(Text.of(TextColors.GREEN, "Vous avez acheté cette propriété pour 1000 euros ! Elle vous appartient désormais !"));
    						owners = owners + "| " + x + " " + z + " " + player.getName() + " |";
    					}
    					else {
    						player.sendMessage(Text.of(TextColors.RED, "Vous n'avez pas assez d'argent pour acheter cette propriété !"));
    					}
    				}
                }
    		}
		}
    }


    public boolean isLockPick(ItemStack stack)
	{
		ItemType type = stack.getItem();
		return type.equals(ItemTypes.FLINT);
	}
    
    public boolean isKey(ItemStack stack)
	{
		ItemType type = stack.getItem();
		return type.equals(ItemTypes.FEATHER);
	}
    
    public boolean isClaimableDoor(Location<World> blockLoc)
	{
    	BlockType type = blockLoc.getBlock().getType();
        return type.equals(BlockTypes.DARK_OAK_DOOR);
	}

If you see some French, it’s because I’m French and the server I’m working for is French.

You have ignored most of the advice I gave above and still have many of the same issues. It is your choice to do so, but I will not waste any more of my time trying to help you.

For HandType I haven’t made it cause I would like to detect off_hand too.
For the player I’ve got no problem with the current solution.
For the Economy, I’m working for a server, and the server got an Economy plugin and I will nevet use this plugin for others servers.
For the toString I’ve change it.
For the String owners, I will maybe change it later, but it’s working so I’ve no problem.
For the getPlayer() and getUniqueId(), I don’t use getUniqueId() cause it’s a cracked server.
For the event.setCancelled(false), We haven’t got protection plugin.
For “If the player is not holding an item in their main hand, #isLockPick will throw an NPE from ItemStack#getItem You can check if the item is present first or use .orElse(ItemStack.empty()). For something a bit more advanced, you can also use #map” I don’t understand what you say.

So please explain me what are you saying by : “If the player is not holding an item in their main hand, #isLockPick will throw an NPE from ItemStack#getItem You can check if the item is present first or use .orElse(ItemStack.empty()). For something a bit more advanced, you can also use #map” ?

We don’t support cracked servers, and even so, any cracked server worth a damn should still have unique uuids…

That’s not my choice ! I’m just an Admin but I’m Premium !

That wasn’t my point. My point was, you should still be checking the UUID regardless, UUID represents the players identity, name doesn’t.

By using name you are opening yourself up for a world of hurt if people ever change names (which is possible on the Mojang site)

Cracked servers I don’t know if they support name changing, but I suspect at least some do.

player.getItemInHand(HandTypes.MAIN_HAND).orElse(null)

is passed into isLockPick() here: if(isLockPick(player.getItemInHand(HandTypes.MAIN_HAND).orElse(null))) {

isLockPick will then call ItemType type = stack.getItem(); which could potentially throw a Null pointer exception.

you need to deal with the null case in isLockPick

public boolean isLockPick(@Nullable ItemStack stack)
{
	return stack != null && stack.getType().equals(ItemTypes.FLINT);
}

This will cause it to return false, if null is passed in.

Or just reverse it

public boolean isLockPick(@Nullable ItemStack stack)
{
	return ItemTypes.FLINT.equals(stack.getType());
}

When I rightclick without item, got effectively a NPE, but not with isLockPick()

   [20:06:50] [Server thread/ERROR] [Sponge]: Could not pass InteractBlockEvent$Secondary$MainHand$Impl to Plugin{id=alpharp, name=AlphaRP Core, version=1.0, description=Plugin principal d'AlphaRP, url=http://alpharp.ga, authors=[Renaud42], source=D:\Base de données\Fire-Softwares\Aide\Serveurs de jeux\AlphaRP\Serveur de test\mods\AlphaRP-1.0-SNAPSHOT.jar}
java.lang.NullPointerException
        at ga.alpharp.Main.isPrinter(Main.java:518) ~[Main.class:?]
        at ga.alpharp.Main.onRightClickOnBlock(Main.java:248) ~[Main.class:?]
        at org.spongepowered.common.event.listener.SecondaryListener_Main_onRightClickOnBlock7.handle(Unknown Source) ~[?:?]
        at org.spongepowered.common.event.RegisteredListener.handle(RegisteredListener.java:95) ~[RegisteredListener.class:1.10.2-2281-5.2.0-BETA-2597]
        at org.spongepowered.mod.event.SpongeModEventManager.post(SpongeModEventManager.java:313) ~[SpongeModEventManager.class:1.10.2-2281-5.2.0-BETA-2597]
        at org.spongepowered.mod.event.SpongeModEventManager.post(SpongeModEventManager.java:297) ~[SpongeModEventManager.class:1.10.2-2281-5.2.0-BETA-2597]
        at org.spongepowered.mod.event.SpongeModEventManager.post(SpongeModEventManager.java:338) ~[SpongeModEventManager.class:1.10.2-2281-5.2.0-BETA-2597]
        at org.spongepowered.mod.event.SpongeModEventManager.post(SpongeModEventManager.java:326) ~[SpongeModEventManager.class:1.10.2-2281-5.2.0-BETA-2597]
        at org.spongepowered.common.SpongeImpl.postEvent(SpongeImpl.java:143) ~[SpongeImpl.class:1.10.2-2281-5.2.0-BETA-2597]
        at org.spongepowered.common.event.SpongeCommonEventFactory.callInteractBlockEventSecondary(SpongeCommonEventFactory.java:541) ~[SpongeCommonEventFactory.class:1.10.2-2281-5.2.0-BETA-2597]
        at org.spongepowered.common.event.SpongeCommonEventFactory.callInteractBlockEventSecondary(SpongeCommonEventFactory.java:531) ~[SpongeCommonEventFactory.class:1.10.2-2281-5.2.0-BETA-2597]
        at net.minecraft.server.management.PlayerInteractionManager.func_187251_a(PlayerInteractionManager.java:1186) ~[lv.class:?]
        at net.minecraft.network.NetHandlerPlayServer.redirect$onProcessRightClickBlock$zhf000(NetHandlerPlayServer.java:2292) ~[me.class:?]
        at net.minecraft.network.NetHandlerPlayServer.func_184337_a(NetHandlerPlayServer.java:679) ~[me.class:?]
        at net.minecraft.network.play.client.CPacketPlayerTryUseItemOnBlock.func_148833_a(SourceFile:55) ~[jj.class:?]
        at net.minecraft.network.play.client.CPacketPlayerTryUseItemOnBlock.func_148833_a(SourceFile:11) ~[jj.class:?]
        at org.spongepowered.common.network.PacketUtil.lambda$onProcessPacket$0(PacketUtil.java:157) ~[PacketUtil.class:1.10.2-2281-5.2.0-BETA-2597]
        at org.spongepowered.common.event.tracking.CauseTracker.switchToPhase(CauseTracker.java:163) [CauseTracker.class:1.10.2-2281-5.2.0-BETA-2597]
        at org.spongepowered.common.network.PacketUtil.onProcessPacket(PacketUtil.java:156) [PacketUtil.class:1.10.2-2281-5.2.0-BETA-2597]
        at net.minecraft.network.PacketThreadUtil$1.redirect$onProcessPacket$zjj000(SourceFile:539) [fl$1.class:?]
        at net.minecraft.network.PacketThreadUtil$1.run(SourceFile:13) [fl$1.class:?]
        at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) [?:1.8.0_144]
        at java.util.concurrent.FutureTask.run(Unknown Source) [?:1.8.0_144]
        at net.minecraft.util.Util.func_181617_a(SourceFile:45) [h.class:?]
        at org.spongepowered.common.SpongeImplHooks.onUtilRunTask(SpongeImplHooks.java:238) [SpongeImplHooks.class:1.10.2-2281-5.2.0-BETA-2597]
        at net.minecraft.server.MinecraftServer.redirect$onRun$zhp000(MinecraftServer.java:3951) [MinecraftServer.class:?]
        at net.minecraft.server.MinecraftServer.func_71190_q(MinecraftServer.java:668) [MinecraftServer.class:?]
        at net.minecraft.server.dedicated.DedicatedServer.func_71190_q(DedicatedServer.java:387) [ld.class:?]
        at net.minecraft.server.MinecraftServer.func_71217_p(MinecraftServer.java:613) [MinecraftServer.class:?]
        at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:471) [MinecraftServer.class:?]
        at java.lang.Thread.run(Unknown Source) [?:1.8.0_144]

If you want all my code related to isPrinter() (this is a money-printer system) :

@Listener
public void onRightClickOnBlock(InteractBlockEvent.Secondary event) {
	Player player = event.getCause().last(Player.class).get();
	BlockSnapshot block = event.getTargetBlock();
        // Système de printers
    	if(block.toString().contains("blockState=minecraft:")) {
	    	if(isPrinter(player.getItemInHand(HandTypes.MAIN_HAND).orElse(null))) {
	    		event.setCancelled(true);
	    		
				final String yP = "" + player.getLocation().getY();
	    		int patchY = player.getLocation().getBlockY();
				// Patch de sécurité 2 (PrinterBlockBreak)
				if(!yP.contains(".0")) {
					patchY++;
				}
	    		
				final int x = player.getLocation().getBlockX();
				final int y = patchY;
				final int z = player.getLocation().getBlockZ();
				
				Sponge.getCommandManager().process(Sponge.getServer().getConsole(), "setblock " + x + " " + y + " " + z + " minecraft:gold_ore");
				
				Optional<ItemStack> itemToRemove = player.getInventory().query(ItemTypes.GOLD_ORE).poll(1);
				if(itemToRemove.isPresent()) {
					ItemStack stack = itemToRemove.get().copy();
					stack.setQuantity(itemToRemove.get().getQuantity() - 1) ;
				}
            	
				Task task = Task.builder()
	            .execute(new Runnable() {
	            	Random r = new Random();
	            	int randomNumber;
	            	int amount;
	            	
					@Override
					public void run() {
		            	randomNumber = r.nextInt(16);
		            	amount = 15 + randomNumber;
						player.sendMessage(ChatTypes.ACTION_BAR, Text.of("§a§l+ " + amount + " euros !"));
						Sponge.getCommandManager().process(Sponge.getServer().getConsole(), "econ add " + player.getName() + " " + amount);
					}
	            })
	            .async()
	            .interval(20, TimeUnit.SECONDS)
	            .name("thread" + x + y + z)
	            .submit(this);
	
				@SuppressWarnings("unused")
				Task taskRemove = Task.builder()
	            .execute(new Runnable() {
	            	int time;
	            	
					@Override
					public void run() {
						time++;
						
						if(time == 15) {
							Sponge.getCommandManager().process(Sponge.getServer().getConsole(), "setblock " + x + " " + y + " " + z + " minecraft:air");
							Sponge.getCommandManager().process(Sponge.getServer().getConsole(), "particle largeexplode " + x + " " + y + " " + z + " 0 0 0 1 1");
							Sponge.getCommandManager().process(Sponge.getServer().getConsole(), "particle blockcrack " + x + " " + y + " " + z + " 0 0 0 1 100");
							Sponge.getCommandManager().process(Sponge.getServer().getConsole(), "playsound minecraft:entity.generic.explode neutral @a " + x + " " + y + " " + z);
							task.cancel();
						}
					}
	            })
	            .async()
	            .interval(20010, TimeUnit.MILLISECONDS)
	            .name("thread" + x + y + z + "-removetask")
	            .submit(this);
		}
    	}
    }

    
   public boolean isPrinter(@Nullable ItemStack stack) {
	   return ItemTypes.GOLD_ORE.equals(stack.getItem());
    }

But the printers are working…really weird…

It’s nearly useless without line numbers, please use Gist.

Long story short, I think you are best off avoiding null whenever possible. don’t use orElse(null) don’t call get() unless you know something is present, otherwise you are going to be running into these issues again and again.

It’s the whole reason why Sponge pays the performance costs to wrap stuff in optionals to begin with.

I give u the complete code of the class : https://gist.github.com/anonymous/38056c6ec69c7936a42c6557aa1d4d2b

L518 does not match a line of code, the code you have given me is different to the code that made the exception.

Looking around the line, I see many errors.

You consistently create helper methods called isLockpick etc, and pass null to them.

If you are going to pass in null, you need to check for it explicitly before calling methods on the variable.

e.g.

public boolean isPickpocket(ItemStack stack)
{
	ItemType type = stack.getItem();
	return type.equals(ItemTypes.NETHERBRICK);
}

if stack is null, calling any method on a null will result in error.

Either DO NOT use .orElse(null) in your code.

Or change your helper ‘is’ methods to be able to handle null.

This is basic Java, if there is a language barrier between us, you may be able to find a tutorial on Optionals, and Null Values, or Null Pointer Exceptions elsewhere on the internet in your native language.

I LOVE ALL THE PEOPLE WHO HELPED ME IT WORKS !
Thanks a lot !

1 Like