Java Code Examples for org.bukkit.event.Event

The following examples show how to use org.bukkit.event.Event. These examples are extracted from open source projects. 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 Project: skRayFall   Source File: EffTabTitlesV1_9.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void execute(Event evt) {
    IChatBaseComponent header =
            ChatSerializer.a("{\"text\": \"" + coreHeader.getSingle(evt).replace("\"", "") + "\"}");
    IChatBaseComponent footer =
            ChatSerializer.a("{\"text\": \"" + coreFooter.getSingle(evt).replace("\"", "") + "\"}");
    PacketPlayOutPlayerListHeaderFooter packet = new PacketPlayOutPlayerListHeaderFooter();
    try {
        Field headerField = packet.getClass().getDeclaredField("a");
        headerField.setAccessible(true);
        headerField.set(packet, header);
        headerField.setAccessible(!headerField.isAccessible());

        Field footerField = packet.getClass().getDeclaredField("b");
        footerField.setAccessible(true);
        footerField.set(packet, footer);
        footerField.setAccessible(!footerField.isAccessible());
    } catch (Exception exception) {
        exception.printStackTrace();
    }
    ((CraftPlayer) player.getSingle(evt)).getHandle().playerConnection.sendPacket(packet);
}
 
Example 2
Source Project: skUtilities   Source File: ExprFromBin.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
@Nullable
protected String[] get(Event e) {
  String bin = str.getSingle(e);
  String binV = bin.trim();
  for (char character : binV.toCharArray()) {
    if (character != '0' && character != '1' && character != ' ') {
      skUtilities.prSysE("Binary Strings can only contain 1's, 0's or spaces!", getClass().getSimpleName());
      return null;
    }
  }
  if (ty == 0) {
    StringBuilder sb = new StringBuilder();
    for (String s : bin.split(" ")) {
      sb.append((char) Integer.parseInt(s, 2));
    }
    return new String[]{sb.toString()};
  } else if (ty == 1) {
    return new String[]{Integer.toString(Integer.parseInt(bin, 2))};
  } else if (ty == 2) {
    return new String[]{Integer.toHexString(Integer.parseInt(bin, 2))};
  } else {
    return new String[]{Integer.toOctalString(Integer.parseInt(bin, 2))};
  }
}
 
Example 3
Source Project: Skript   Source File: Variable.java    License: GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Nullable
private Object get(final Event e) {
	final Object val = getRaw(e);
	if (!list)
		return val;
	if (val == null)
		return Array.newInstance(types[0], 0);
	final List<Object> l = new ArrayList<>();
	final String name = StringUtils.substring(this.name.toString(e), 0, -1);
	for (final Entry<String, ?> v : ((Map<String, ?>) val).entrySet()) {
		if (v.getKey() != null && v.getValue() != null) {
			Object o;
			if (v.getValue() instanceof Map)
				o = ((Map<String, ?>) v.getValue()).get(null);
			else
				o = v.getValue();	
			l.add(convertIfOldPlayer(name + v.getKey(), e, o));
		}
	}
	return l.toArray();
}
 
Example 4
@Override
@Nullable
protected Integer[] get(Event e) {
  try {
    HttpURLConnection.setFollowRedirects(false);
    HttpURLConnection c = (HttpURLConnection) new URL(url.getSingle(e)).openConnection();
    c.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
    c.setRequestMethod("HEAD");
    int r = c.getResponseCode();
    c.disconnect();
    return new Integer[]{r};
  } catch (Exception x) {
    skUtilities.prSysE("Error Reading from: '" + url.getSingle(e) + "' Is the site down?", getClass().getSimpleName(), x);
  }
  return null;
}
 
Example 5
Source Project: Skript   Source File: ExprSpectatorTarget.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void change(Event e, @Nullable Object[] delta, Changer.ChangeMode mode) {
	for (Player player : getExpr().getArray(e)) {
		if (player.getGameMode() == GameMode.SPECTATOR) {
			switch (mode) {
				case SET:
					assert delta != null;
					player.setSpectatorTarget((Entity) delta[0]);
					break;
				case RESET:
				case DELETE:
					player.setSpectatorTarget(null);
			}
		}
	}
}
 
Example 6
Source Project: Kettle   Source File: SimplePluginManager.java    License: GNU General Public License v3.0 5 votes vote down vote up
private Class<? extends Event> getRegistrationClass(Class<? extends Event> clazz) {
    try {
        clazz.getDeclaredMethod("getHandlerList");
        return clazz;
    } catch (NoSuchMethodException e) {
        if (clazz.getSuperclass() != null
                && !clazz.getSuperclass().equals(Event.class)
                && Event.class.isAssignableFrom(clazz.getSuperclass())) {
            return getRegistrationClass(clazz.getSuperclass().asSubclass(Event.class));
        } else {
            throw new IllegalPluginAccessException("Unable to find handler list for event " + clazz.getName() + ". Static getHandlerList method required!");
        }
    }
}
 
Example 7
Source Project: Skript   Source File: CondIsEnchanted.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean check(final Event e) {
	if (enchs != null)
		return items.check(e, item -> enchs.check(e, ench -> item.hasEnchantments(ench)), isNegated());
	else
		return items.check(e, ItemType::hasEnchantments, isNegated());
	
}
 
Example 8
Source Project: skUtilities   Source File: CondYamlExists.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean check(Event e) {
  File pth = new File(skUtilities.getDefaultPath(path.getSingle(e)));
  FileConfiguration con = YamlConfiguration.loadConfiguration(pth);
  Boolean v = con.contains(yaml.getSingle(e));
  return (isNegated() ? !v : v);
}
 
Example 9
Source Project: VoxelGamesLibv2   Source File: EventHandler.java    License: MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
public <T extends Event> void callEvent(@Nonnull T event) {
    Class<Event> eventClass = (Class<Event>) event.getClass();
    while (!eventClass.equals(Object.class)) {
        if (activeEvents.containsKey(eventClass)) {
            activeEvents.get(eventClass).forEach(registeredListener -> {
                Optional<User> user = Optional.empty();
                boolean tried = false;
                for (EventFilter filter : registeredListener.getFilters()) {
                    if (!user.isPresent() && !tried) {
                        user = figureOutUser(event);
                        tried = true;
                    }
                    if (!filter.filter(event, registeredListener, user)) {
                        return;
                    }
                }

                try {
                    if (registeredListener.getMethod().getParameterCount() == 2) {
                        registeredListener.getMethod().invoke(registeredListener.getListener(), event, user.orElse(null));
                    } else {
                        registeredListener.getMethod().invoke(registeredListener.getListener(), event);
                    }
                } catch (IllegalAccessException | InvocationTargetException e) {
                    log.log(Level.SEVERE, "Error while calling eventhandler!", e);
                }
            });
            break;
        } else {
            eventClass = (Class<Event>) eventClass.getSuperclass();
        }
    }
}
 
Example 10
Source Project: skRayFall   Source File: EffParticlesV1_8_4.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void execute(Event evt) {
    float hx = 0f;
    float hy = 0f;
    float hz = 0f;
    float id = 0;
    int[] array = new int[0];
    if (xoffset != null) {
        hx = xoffset.getSingle(evt).floatValue();
    }
    if (yoffset != null) {
        hy = yoffset.getSingle(evt).floatValue();
    }
    if (zoffset != null) {
        hz = zoffset.getSingle(evt).floatValue();
    }
    String core = type.getSingle(evt);
    if (core.toUpperCase().replace(" ", "_").contains("BLOCK_CRACK")
            || core.toUpperCase().replace(" ", "_").contains("BLOCK_DUST")) {
        int index = type.getSingle(evt).lastIndexOf("_");
        try {
            id = Integer.parseInt(type.getSingle(evt).substring(index + 1));
        } catch (Exception exception) {
            Skript.error("Could not parse datavalue!");
            id = 0;
        }
        core = core.substring(0, index);
        array = new int[1];
    }
    EnumParticle part = PacketParticleGetterV1_8_4.get(core);

    PacketPlayOutWorldParticles packet =
            new PacketPlayOutWorldParticles(part, true, (float) location.getSingle(evt).getX(),
                    (float) location.getSingle(evt).getY(), (float) location.getSingle(evt).getZ(), hx, hy,
                    hz, id, partNum.getSingle(evt).intValue(), array);
    ((CraftPlayer) player.getSingle(evt)).getHandle().playerConnection.sendPacket(packet);
}
 
Example 11
@EventHandler(priority = EventPriority.LOWEST)
public void onCreativeSlotChange(InventoryCreativeEvent event) {
    if (timeouts.isEmpty()) {
        return; // Saves performance for most common case
    }
    InventoryHolder holder = event.getInventory().getHolder();
    if (holder instanceof Player && timeouts.containsKey(((Player) holder).getUniqueId())) {
        event.setResult(Event.Result.DENY);
    }
}
 
Example 12
Source Project: skUtilities   Source File: ExprFileDirSize.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
@Nullable
protected String[] get(Event e) {
  Path pth = Paths.get(skUtilities.getDefaultPath(path.getSingle(e)));
  try {
    if (ty == 0) {
      return new String[]{skUtilities.getFileSize(Files.size(pth))};
    } else {
      return new String[]{skUtilities.getFileSize(FileUtils.sizeOfDirectory(pth.toFile()))};
    }
  } catch (Exception x) {
    skUtilities.prSysE("'" + pth + "' doesn't exist!", getClass().getSimpleName());
  }
  return null;
}
 
Example 13
Source Project: skript-yaml   Source File: CondYamlIsLoaded.java    License: MIT License 5 votes vote down vote up
@Override
public boolean check(final Event event) {
	return file.check(event, new Checker<String>() {
		@Override
		public boolean check(final String s) {
			if (!SkriptYaml.YAML_STORE.containsKey(file.getSingle(event)))
				return false;
			return true;
		}
	}, isNegated());
}
 
Example 14
Source Project: Skript   Source File: CondCanBuild.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean check(final Event e) {
	return players.check(e, new Checker<Player>() {
		@Override
		public boolean check(final Player p) {
			return locations.check(e, new Checker<Location>() {
				@Override
				public boolean check(final Location l) {
					return RegionsPlugin.canBuild(p, l);
				}
			}, isNegated());
		}
	});
}
 
Example 15
Source Project: Skript   Source File: ExprDifficulty.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void change(Event e, @Nullable Object[] delta, ChangeMode mode) {
	if (delta == null)
		return;
	
	Difficulty difficulty = (Difficulty) delta[0];
	for (World world : getExpr().getArray(e)) {
		world.setDifficulty(difficulty);
	}
}
 
Example 16
Source Project: skRayFall   Source File: EffCitizenAttack.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void execute(Event evt) {
    NPCRegistry registry = CitizensAPI.getNPCRegistry();
    NPC attacker = registry.getById(id.getSingle(evt).intValue());
    if (attacker != null) {
        attacker.getNavigator().setTarget(toBeAttacked.getSingle(evt), true);
    }
}
 
Example 17
Source Project: skRayFall   Source File: EvtUnscope.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean check(Event evt) {
    if (evt instanceof WeaponScopeEvent && !((WeaponScopeEvent) evt).isZoomIn()) {
        return true;
    } else {
        return false;
    }
}
 
Example 18
Source Project: skUtilities   Source File: CondIsFile.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean check(Event e) {
  Path pth = Paths.get(skUtilities.getDefaultPath(path.getSingle(e)));
  if (!Files.exists(pth)) return false;
  Boolean b = !Files.isRegularFile(pth);
  return (isNegated() ? !b : b);
}
 
Example 19
@Override
@Nullable
protected Number[] get(Event evt) {
    if (entity.getSingle(evt) != null && entity.getSingle(evt).hasMetadata("NPC")) {
        NPCRegistry registry = CitizensAPI.getNPCRegistry();
        return new Number[]{registry.getNPC(entity.getSingle(evt)).getId()};
    }
    return null;
}
 
Example 20
Source Project: Skript   Source File: EffMakeFly.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void execute(Event e) {
	for (Player player : players.getArray(e)) {
		player.setAllowFlight(flying);
		player.setFlying(flying);
	}
}
 
Example 21
Source Project: ce   Source File: Gooey.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void effect(Event e, ItemStack item, final int level) {
	final EntityDamageByEntityEvent event = (EntityDamageByEntityEvent) e;

	new BukkitRunnable() {

		@Override
		public void run() {
			event.getEntity().setVelocity(event.getEntity().getVelocity().setY((strength * level * 0.05) + 0.75));
			event.getEntity().getWorld().playEffect(event.getEntity().getLocation(), Effect.SMOKE, 60);
		}
	}.runTaskLater(getPlugin(), 1l);
}
 
Example 22
Source Project: Skript   Source File: ExprEnchantmentLevel.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void change(Event e, @Nullable Object[] delta, ChangeMode mode) {
	if (delta == null)
		return;
	
	ItemType[] source = items.getArray(e);
	Enchantment[] enchantments = enchants.getArray(e);
	int newLevel = ((Number) delta[0]).intValue();
	
	for (ItemType item : source) {
		if (!item.hasAnyEnchantments(enchantments))
			continue;
		
		EnchantmentType[] enchants = item.getEnchantmentTypes();
		assert enchants != null; // Can't be null at this point due to the above check
		for (EnchantmentType enchant : enchants) {
			item.removeEnchantments(enchant);
			Enchantment type = enchant.getType();
			int changed = newLevel;
			assert type != null;
			
			if (mode == ChangeMode.ADD)
				changed = Math.max(0, enchant.getLevel() + changed);
			else if (mode == ChangeMode.REMOVE)
				changed = Math.max(0, enchant.getLevel() - changed);
			
			if (changed > 0)
				item.addEnchantments(new EnchantmentType(type, newLevel));
		}
	}
}
 
Example 23
Source Project: skript-yaml   Source File: SimpleExpressionFork.java    License: MIT License 5 votes vote down vote up
protected final boolean setTime(final int time, final Class<? extends Event> applicableEvent, final Expression<?>... mustbeDefaultVars) {
	if (ScriptLoader.hasDelayBefore == Kleenean.TRUE && time != 0) {
		Skript.error("Can't use time states after the event has already passed");
		return false;
	}
	if (!ScriptLoader.isCurrentEvent(applicableEvent))
		return false;
	for (final Expression<?> var : mustbeDefaultVars) {
		if (!var.isDefault()) {
			return false;
		}
	}
	this.time = time;
	return true;
}
 
Example 24
Source Project: Skript   Source File: ExprBlocksInRegion.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
@NonNull
public Iterator<Block> iterator(final Event e) {
	final Region[] rs = regions.getArray(e);
	if (rs.length == 0)
		return EmptyIterator.get();
	return new Iterator<Block>() {
		private Iterator<Block> current = rs[0].getBlocks();
		private final Iterator<Region> iter = new ArrayIterator<>(rs, 1);
		
		@Override
		public boolean hasNext() {
			while (!current.hasNext() && iter.hasNext()) {
				final Region r = iter.next();
				if (r != null)
					current = r.getBlocks();
			}
			return current.hasNext();
		}
		
		@SuppressWarnings("null")
		@Override
		public Block next() {
			if (!hasNext())
				throw new NoSuchElementException();
			return current.next();
		}
		
		@Override
		public void remove() {
			throw new UnsupportedOperationException();
		}
	};
}
 
Example 25
@SuppressWarnings("null")
@Override
protected Location[] get(Event e) {
	Location l = location.getSingle(e);
	if (l == null)
		return null;
	Location clone = l.clone();
	for (Vector v : vectors.getArray(e))
		clone.add(v);
	return CollectionUtils.array(clone);
}
 
Example 26
@Override
public void change(final Event e, final @Nullable Object[] delta, final ChangeMode mode) {
	int d = delta == null ? 0 : ((Number) delta[0]).intValue();
	for (LivingEntity le : getExpr().getArray(e)) {
		if (le instanceof Creeper) {
			Creeper c = (Creeper) le;
			switch (mode) {
				case ADD:
					int r1 = c.getMaxFuseTicks() + d;
					if (r1 < 0) r1 = 0;
					c.setMaxFuseTicks(r1);
					break;
				case SET:
					c.setMaxFuseTicks(d);
					break;
				case DELETE:
					c.setMaxFuseTicks(0);
					break;
				case RESET:
					c.setMaxFuseTicks(30); //Seems to be the same for powered creepers?
					break;
				case REMOVE:
					int r2 = c.getMaxFuseTicks() - d;
					if (r2 < 0) r2 = 0;
					c.setMaxFuseTicks(r2);
					break;
				case REMOVE_ALL:
					assert false;		
			}
		}
	}
}
 
Example 27
public <T extends Event> void addPostAction(SpleefPlayer player, Class<T> event, PostActionCallback<T> callback, Object cookie) {
	Validate.notNull(player, "player cannot be null");
	Validate.notNull(event, "event class cannot be null");
	Validate.notNull(callback, "callback cannot be null");
	
	PostDataContainer<T> container = new PostDataContainer<T>(event, callback, cookie);
	awaitingPostAction.put(player, container);
}
 
Example 28
Source Project: skRayFall   Source File: EffEffectLibWave.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void execute(Event evt) {
    Object tar = target.getSingle(evt);
    WaveEffect effect = new WaveEffect(Core.effectManager);
    if (tar instanceof Entity) {
        effect.setDynamicOrigin(new DynamicLocation((Entity) tar));
        if (particle != null) {
            effect.particle = particle.getSingle(evt);
        }
        effect.infinite();
        effect.start();
        Boolean check = Core.rayfallEffectManager.setEffect(effect, id.getSingle(evt).replace("\"", ""));
        if (!check) {
            effect.cancel();
        }
    } else if (tar instanceof Location) {
        effect.setDynamicOrigin(new DynamicLocation((Location) tar));
        effect.infinite();
        if (particle != null) {
            effect.particle = particle.getSingle(evt);
        }
        effect.start();
        Boolean check = Core.rayfallEffectManager.setEffect(effect, id.getSingle(evt).replace("\"", ""));
        if (!check) {
            effect.cancel();
        }
    } else {
        assert false;
    }
}
 
Example 29
Source Project: Skript   Source File: ExprSpawn.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void change(final Event e, final @Nullable Object[] delta, final ChangeMode mode) {
	assert mode == ChangeMode.SET;
	assert delta != null;
	
	final Location l = (Location) delta[0];
	final int x = l.getBlockX(), y = l.getBlockY(), z = l.getBlockZ();
	for (final World w : getExpr().getArray(e)) {
		w.setSpawnLocation(x, y, z);
	}
}
 
Example 30
/**
 * Query the custom damage filters with the given damage event
 */
public Filter.QueryResponse queryRules(Event event, ParticipantState victim, DamageInfo damageInfo) {
    IQuery query = getQuery(event, victim, damageInfo);

    for(Filter filter : filters) {
        Filter.QueryResponse response = filter.query(query);
        if(response != Filter.QueryResponse.ABSTAIN) return response;
    }

    return Filter.QueryResponse.ABSTAIN;
}