Java Code Examples for org.spongepowered.api.event.Order#EARLY

The following examples show how to use org.spongepowered.api.event.Order#EARLY . 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: VirtualChestPlugin.java    From VirtualChest with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Listener(order = Order.EARLY)
public void onInteractItemPrimary(InteractItemEvent.Primary event, @First Player player)
{
    String name = "";
    for (String inventoryName : this.dispatcher.ids())
    {
        if (player.hasPermission("virtualchest.open.self." + inventoryName))
        {
            if (this.dispatcher.isInventoryMatchingPrimaryAction(inventoryName, event.getItemStack()))
            {
                event.setCancelled(true);
                name = inventoryName;
                break;
            }
        }
    }
    if (!name.isEmpty())
    {
        this.logger.debug("Player {} tries to create the GUI ({}) by primary action", player.getName(), name);
        this.dispatcher.open(name, player);
    }
}
 
Example 2
Source File: VirtualChestPlugin.java    From VirtualChest with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Listener(order = Order.EARLY)
public void onInteractItemSecondary(InteractItemEvent.Secondary event, @First Player player)
{
    String name = "";
    for (String inventoryName : this.dispatcher.ids())
    {
        if (player.hasPermission("virtualchest.open.self." + inventoryName))
        {
            if (this.dispatcher.isInventoryMatchingSecondaryAction(inventoryName, event.getItemStack()))
            {
                event.setCancelled(true);
                name = inventoryName;
                break;
            }
        }
    }
    if (!name.isEmpty())
    {
        this.logger.debug("Player {} tries to create the GUI ({}) by secondary action", player.getName(), name);
        this.dispatcher.open(name, player);
    }
}
 
Example 3
Source File: FireListener.java    From Nations with MIT License 6 votes vote down vote up
@Listener(order=Order.EARLY, beforeModifications = true)
public void onFire(ChangeBlockEvent event)
{
	if (!ConfigHandler.getNode("worlds").getNode(event.getTargetWorld().getName()).getNode("enabled").getBoolean())
	{
		return;
	}
	event
	.getTransactions()
	.stream()
	.filter(trans -> trans.getFinal().getState().getType() == BlockTypes.FIRE)
	.filter(trans -> {
		Optional<Location<World>> optLoc = trans.getFinal().getLocation();
		if (!optLoc.isPresent())
			return false;
		return !DataHandler.getFlag("fire", optLoc.get());
	})
	.forEach(trans -> trans.setValid(false));
}
 
Example 4
Source File: WorldEventHandler.java    From GriefPrevention with MIT License 6 votes vote down vote up
@Listener(order = Order.EARLY, beforeModifications = true)
public void onWorldLoad(LoadWorldEvent event) {
    if (!SpongeImpl.getServer().isServerRunning() || !GriefPreventionPlugin.instance.claimsEnabledForWorld(event.getTargetWorld().getProperties())) {
        return;
    }

    GPTimings.WORLD_LOAD_EVENT.startTimingIfSync();
    GriefPreventionPlugin.instance.dataStore.loadWorldData(event.getTargetWorld());
    net.minecraft.world.World world = (net.minecraft.world.World) event.getTargetWorld();
    world.addEventListener(new EntityRemovalListener());
    GPTimings.WORLD_LOAD_EVENT.stopTimingIfSync();
    if (!GriefPreventionPlugin.getActiveConfig(event.getTargetWorld().getProperties()).getConfig().claim.bankTaxSystem) {
        return;
    }
    if (GriefPreventionPlugin.instance.economyService.isPresent()) {
        // run tax task
        TaxApplyTask taxTask = new TaxApplyTask(event.getTargetWorld().getProperties());
        int taxHour = GriefPreventionPlugin.getActiveConfig(event.getTargetWorld().getProperties()).getConfig().claim.taxApplyHour;
        long delay = TaskUtils.computeDelay(taxHour, 0, 0);
        Sponge.getScheduler().createTaskBuilder().delay(delay, TimeUnit.SECONDS).interval(1, TimeUnit.DAYS).execute(taxTask).submit(GriefPreventionPlugin.instance);
    }
}
 
Example 5
Source File: SignListener.java    From UltimateCore with MIT License 6 votes vote down vote up
@Listener(order = Order.EARLY)
public void onSignCreate(ChangeSignEvent event, @Root Player p) {
    //Sign colors
    List<Text> lines = event.getText().lines().get();
    lines.set(0, TextUtil.replaceColors(lines.get(0), p, "uc.sign"));
    lines.set(1, TextUtil.replaceColors(lines.get(1), p, "uc.sign"));
    lines.set(2, TextUtil.replaceColors(lines.get(2), p, "uc.sign"));
    lines.set(3, TextUtil.replaceColors(lines.get(3), p, "uc.sign"));
    event.getText().setElements(lines);

    //Registered signs
    for (UCSign sign : UltimateCore.get().getSignService().get().getRegisteredSigns()) {
        if (event.getText().get(0).orElse(Text.of()).toPlain().equalsIgnoreCase("[" + sign.getIdentifier() + "]")) {
            if (!p.hasPermission(sign.getCreatePermission().get())) {
                Messages.send(p, "core.nopermissions");
            }
            SignCreateEvent cevent = new SignCreateEvent(sign, event.getTargetTile().getLocation(), Cause.builder().append(UltimateCore.getContainer()).append(p).build(EventContext.builder().build()));
            Sponge.getEventManager().post(cevent);
            if (!cevent.isCancelled() && sign.onCreate(p, event)) {
                //Color sign
                event.getTargetTile().offer(Keys.SIGN_LINES, event.getText().setElement(0, Text.of(TextColors.AQUA, "[" + StringUtil.firstUpperCase(sign.getIdentifier()) + "]")).asList());
                Messages.send(p, "sign.create", "%sign%", sign.getIdentifier());
            }
        }
    }
}
 
Example 6
Source File: DefaultListener.java    From UltimateCore with MIT License 6 votes vote down vote up
@Listener(order = Order.EARLY)
public void onJoin(ClientConnectionEvent.Join event) {
    Player p = event.getTargetEntity();

    //Player file
    PlayerDataFile config = new PlayerDataFile(event.getTargetEntity().getUniqueId());
    CommentedConfigurationNode node = config.get();
    node.getNode("lastconnect").setValue(System.currentTimeMillis());
    String ip = event.getTargetEntity().getConnection().getAddress().getAddress().toString().replace("/", "");
    node.getNode("lastip").setValue(ip);
    config.save(node);

    //Ipcache file
    GlobalDataFile file = new GlobalDataFile("ipcache");
    CommentedConfigurationNode node2 = file.get();
    node2.getNode(ip, "name").setValue(p.getName());
    node2.getNode(ip, "uuid").setValue(p.getUniqueId().toString());
    file.save(node2);
}
 
Example 7
Source File: RequiredInteractListener.java    From Prism with MIT License 6 votes vote down vote up
/**
 * Listens for interactions by Players with active inspection wands.
 * <br>
 * This listener is required and does not track any events.
 *
 * @param event  InteractEntityEvent
 * @param player Player
 */
@Listener(order = Order.EARLY)
public void onInteractEntity(InteractEntityEvent event, @First Player player) {
    // Wand support
    if (!Prism.getInstance().getActiveWands().contains(player.getUniqueId())) {
        return;
    }

    event.setCancelled(true);

    // Ignore OffHand events
    if (event instanceof InteractEntityEvent.Primary.OffHand || event instanceof InteractEntityEvent.Secondary.OffHand) {
        return;
    }

    player.sendMessage(Format.error(Text.of("Cannot interact with entities while inspection is active!")));
}
 
Example 8
Source File: WorldEventHandler.java    From GriefDefender with MIT License 5 votes vote down vote up
@Listener(order = Order.EARLY, beforeModifications = true)
public void onWorldLoad(LoadWorldEvent event) {
    if (!SpongeImpl.getServer().isServerRunning() || !GriefDefenderPlugin.getInstance().claimsEnabledForWorld(event.getTargetWorld().getUniqueId())) {
        return;
    }

    GDTimings.WORLD_LOAD_EVENT.startTimingIfSync();
    GriefDefenderPlugin.getInstance().dataStore.registerWorld(event.getTargetWorld());
    GriefDefenderPlugin.getInstance().dataStore.loadWorldData(event.getTargetWorld());
    NMSUtil.getInstance().addEntityRemovalListener(event.getTargetWorld());
    GDTimings.WORLD_LOAD_EVENT.stopTimingIfSync();
}
 
Example 9
Source File: WorldEventHandler.java    From GriefDefender with MIT License 5 votes vote down vote up
@Listener(order = Order.EARLY)
public void onChunkLoad(LoadChunkEvent event) {
    if (!GriefDefenderPlugin.getInstance().claimsEnabledForWorld(event.getTargetChunk().getWorld().getUniqueId())) {
        return;
    }

    final GDClaimManager claimWorldManager = GriefDefenderPlugin.getInstance().dataStore.getClaimWorldManager(event.getTargetChunk().getWorld().getUniqueId());
    claimWorldManager.getChunk(event.getTargetChunk());
}
 
Example 10
Source File: SendCommandListener.java    From EagleFactions with MIT License 5 votes vote down vote up
@Listener(order = Order.EARLY)
public void onCommandSend(final SendCommandEvent event, final @Root Player player)
{
    if (EagleFactionsPlugin.getPlugin().getPVPLogger().isActive() && EagleFactionsPlugin.getPlugin().getPVPLogger().shouldBlockCommand(player, event.getCommand() + " " + event.getArguments()))
    {
        player.sendMessage(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, Messages.YOU_CANT_USE_COMMAND_WHILE_BEING_IN_A_FIGHT));
        player.sendMessage(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, MessageLoader.parseMessage(Messages.TIME_LEFT_NUMBER_SECONDS, TextColors.RED, ImmutableMap.of(Placeholders.NUMBER, Text.of(TextColors.YELLOW, super.getPlugin().getPVPLogger().getPlayerBlockTime(player))))));
        event.setCancelled(true);
    }
}
 
Example 11
Source File: WorldEventHandler.java    From GriefPrevention with MIT License 5 votes vote down vote up
@Listener(order = Order.EARLY)
public void onConstructWorldProperties(ConstructWorldPropertiesEvent event) {
    if (!SpongeImpl.getServer().isServerRunning() || !GriefPreventionPlugin.instance.claimsEnabledForWorld(event.getWorldProperties())) {
        return;
    }

    GriefPreventionPlugin.instance.dataStore.registerWorld(event.getWorldProperties());
}
 
Example 12
Source File: ConnectionListener.java    From FlexibleLogin with MIT License 5 votes vote down vote up
@Listener(order = Order.EARLY)
public void checkAlreadyOnline(Auth authEvent, @First GameProfile profile) {
    String playerName = profile.getName().get();
    if (Sponge.getServer().getPlayer(playerName)
            .map(Player::getName)
            .filter(name -> name.equals(playerName))
            .isPresent()) {
        authEvent.setMessage(settings.getText().getAlreadyOnline());
        authEvent.setCancelled(true);
    }
}
 
Example 13
Source File: SpongeConnectionListener.java    From LuckPerms with MIT License 4 votes vote down vote up
@Listener(order = Order.EARLY)
@IsCancelled(Tristate.UNDEFINED)
public void onClientAuth(ClientConnectionEvent.Auth e) {
    /* Called when the player first attempts a connection with the server.
       Listening on AFTER_PRE priority to allow plugins to modify username / UUID data here. (auth plugins)
       Also, give other plugins a chance to cancel the event. */

    final GameProfile profile = e.getProfile();
    final String username = profile.getName().orElseThrow(() -> new RuntimeException("No username present for user " + profile.getUniqueId()));

    if (this.plugin.getConfiguration().get(ConfigKeys.DEBUG_LOGINS)) {
        this.plugin.getLogger().info("Processing auth event for " + profile.getUniqueId() + " - " + profile.getName());
    }

    if (e.isCancelled()) {
        // another plugin has disallowed the login.
        this.plugin.getLogger().info("Another plugin has cancelled the connection for " + profile.getUniqueId() + " - " + username + ". No permissions data will be loaded.");
        this.deniedAsyncLogin.add(profile.getUniqueId());
        return;
    }

    /* Actually process the login for the connection.
       We do this here to delay the login until the data is ready.
       If the login gets cancelled later on, then this will be cleaned up.

       This includes:
       - loading uuid data
       - loading permissions
       - creating a user instance in the UserManager for this connection.
       - setting up cached data. */
    try {
        User user = loadUser(profile.getUniqueId(), username);
        recordConnection(profile.getUniqueId());
        this.plugin.getEventDispatcher().dispatchPlayerLoginProcess(profile.getUniqueId(), username, user);
    } catch (Exception ex) {
        this.plugin.getLogger().severe("Exception occurred whilst loading data for " + profile.getUniqueId() + " - " + profile.getName());
        ex.printStackTrace();

        this.deniedAsyncLogin.add(profile.getUniqueId());

        e.setCancelled(true);
        e.setMessageCancelled(false);
        //noinspection deprecation
        e.setMessage(TextSerializers.LEGACY_FORMATTING_CODE.deserialize(Message.LOADING_DATABASE_ERROR.asString(this.plugin.getLocaleManager())));
        this.plugin.getEventDispatcher().dispatchPlayerLoginProcess(profile.getUniqueId(), username, null);
    }
}
 
Example 14
Source File: RequiredInteractListener.java    From Prism with MIT License 4 votes vote down vote up
/**
 * Listens for interactions by Players with active inspection wands.
 * <br>
 * This listener is required and does not track any events.
 *
 * @param event  InteractBlockEvent
 * @param player Player
 */
@Listener(order = Order.EARLY)
public void onInteractBlock(InteractBlockEvent event, @First Player player) {
    // Wand support
    if (!Prism.getInstance().getActiveWands().contains(player.getUniqueId())) {
        return;
    }

    event.setCancelled(true);

    // Ignore OffHand events
    if (event instanceof InteractBlockEvent.Primary.OffHand || event instanceof InteractBlockEvent.Secondary.OffHand) {
        return;
    }

    // Verify target block is valid
    if (event.getTargetBlock() == BlockSnapshot.NONE || !event.getTargetBlock().getLocation().isPresent()) {
        return;
    }

    // Location of block
    Location<World> location = event.getTargetBlock().getLocation().get();

    // Secondary click gets location relative to side clicked
    if (event instanceof InteractBlockEvent.Secondary) {
        location = location.getRelative(event.getTargetSide());
    }

    QuerySession session = new QuerySession(player);
    // session.addFlag(Flag.EXTENDED);
    session.addFlag(Flag.NO_GROUP);
    session.newQuery().addCondition(ConditionGroup.from(location));

    player.sendMessage(Text.of(
            Format.prefix(), TextColors.GOLD,
            "--- Inspecting ", Format.item(location.getBlockType().getId(), true),
            " at ", location.getBlockX(), " ", location.getBlockY(), " ", location.getBlockZ(), " ---"));

    // Pass off to an async lookup helper
    AsyncUtil.lookup(session);
}