Java Code Examples for protocolsupport.api.Connection

The following examples show how to use protocolsupport.api.Connection. 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
@EventHandler
public void onConnectionHandshake(ConnectionHandshakeEvent e) {
	Connection con = e.getConnection();
	if (PocketCon.isPocketConnection(con)) {
		// = Packet Listeners = \\
		//con.addPacketListener(new ModalResponsePacket().new decodeHandler(this, con));
		//if (getConfig().getBoolean("hacks.player-heads-skins.skull-blocks")) { con.addPacketListener(new SkullTilePacketListener(this, con)); }
		if (ServerPlatformIdentifier.get() == ServerPlatformIdentifier.SPIGOT) {
			/*if (getConfig().getBoolean("hacks.itemframes")) {
				con.addPacketListener(new ItemFramesPacketListener(this, con));
			}
			if (getConfig().getBoolean("hacks.bossbars")) {
				con.addPacketListener(new BossBarPacketListener(con));
			}*/
		}
	}
}
 
Example 2
/**
 * Sends title, subtitle, and it's params <br>
 * Title and subtitle can't be both null
 * @param player Player to which title is sent
 * @param titleJson title chat json or null
 * @param subtitleJson subtitle chat json or null
 * @param fadeIn ticks to spend fading in
 * @param stay ticks to display
 * @param fadeOut ticks to spend fading out
 */
public static void sendSimpleTitle(Player player, String titleJson, String subtitleJson, int fadeIn, int stay, int fadeOut) {
	Validate.notNull(player, "Player can't be null");
	if ((titleJson == null) && (subtitleJson == null)) {
		throw new IllegalArgumentException("Title and subtitle can't be both null");
	}
	Connection connection = ProtocolSupportAPI.getConnection(player);
	connection.sendPacket(ServerPlatform.get().getPacketFactory().createTitleParamsPacket(fadeIn, stay, fadeOut));
	if (subtitleJson != null) {
		connection.sendPacket(ServerPlatform.get().getPacketFactory().createTitleSubPacket(subtitleJson));
	}
	if (titleJson == null) {
		titleJson = "";
	}
	connection.sendPacket(ServerPlatform.get().getPacketFactory().createTitleMainPacket(titleJson));
}
 
Example 3
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onEntityDamage(EntityDamageEvent event) {
	if (((event.getCause() == DamageCause.FIRE_TICK) || (event.getCause() == DamageCause.FIRE) || (event.getCause() == DamageCause.DROWNING))) {
		for (Player player : ServerPlatform.get().getMiscUtils().getNearbyPlayers(event.getEntity().getLocation(), 48, 128, 48)) {
			if (player != null) {
				Connection connection = ProtocolSupportAPI.getConnection(player);
				if (
					(connection != null) &&
					(connection.getVersion().getProtocolType() == ProtocolType.PC) &&
					connection.getVersion().isBefore(ProtocolVersion.MINECRAFT_1_12)
				) {
					connection.sendPacket(ServerPlatform.get().getPacketFactory().createEntityStatusPacket(event.getEntity(), 2));
				}
			}
		}
	}
}
 
Example 4
@EventHandler
public void onChat(AsyncPlayerChatEvent e) {
	if(e.getMessage().contains(".meep")) {
		e.getPlayer().sendMessage("Meep!");
		for(Connection con : PocketCon.getPocketConnections()) {
			e.getPlayer().sendMessage("MEEEEEP!!");
			SimpleForm f = new SimpleForm("hoi", "hallo");
			f.clone();
			PocketCon.sendModal(con, 
				new SimpleForm("hoi", "hallo")
					.addButton(new ModalButton("Magbot").setImage(new ModalImage(ModalImageType.EXTERNAL_IMAGE, "http://magbot.nl/img/MagBot.png")))
					.addButton(new ModalButton("Awesome").setImage(new ModalImage(ModalImageType.EXTERNAL_IMAGE, "http://yumamom.com/wp-content/uploads/2015/05/LEGO.jpg"))), response -> {
						if (response.asSimpleFormResponse().getClickedButton() == 1) {
							response.getPlayer().sendMessage("You are awesome!");
						} else {
							response.getPlayer().sendMessage("You are not awesome! :(");
						}
					});
		}
	}
}
 
Example 5
@Override
public void buildBungeeClientCodec(Channel channel, Connection connection) {
	ChannelPipeline pipeline = channel.pipeline();
	NetworkDataCache cache = new NetworkDataCache();
	cache.storeIn(connection);
	pipeline.replace(PipelineUtils.PACKET_DECODER, PipelineUtils.PACKET_DECODER, new FromClientPacketDecoder(connection, cache));
	pipeline.replace(PipelineUtils.PACKET_ENCODER, PipelineUtils.PACKET_ENCODER, new ToClientPacketEncoder(connection, cache));
	pipeline.get(CustomHandlerBoss.class).setHandlerChangeListener((handler) -> {
		try {
			return (handler instanceof UpstreamBridge) ? new EntityRewriteUpstreamBridge(
				ReflectionUtils.getFieldValue(handler, "con"), connection.getVersion()
			) : handler;
		} catch (IllegalArgumentException | IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	});
}
 
Example 6
@Override
public void buildBungeeServer(Channel channel, Connection connection) {
	ChannelPipeline pipeline = channel.pipeline();
	pipeline.addFirst(new EncapsulatedHandshakeSender(null, false));
	NetworkDataCache cache = NetworkDataCache.getFrom(connection);
	pipeline.replace(PipelineUtils.PACKET_DECODER, PipelineUtils.PACKET_DECODER, new FromServerPacketDecoder(connection, cache));
	pipeline.replace(PipelineUtils.PACKET_ENCODER, PipelineUtils.PACKET_ENCODER, new ToServerPacketEncoder(connection, cache));
	pipeline.get(CustomHandlerBoss.class).setHandlerChangeListener(handler -> {
		try {
			return (handler instanceof DownstreamBridge) ? new EntityRewriteDownstreamBridge(
				ReflectionUtils.getFieldValue(handler, "con"), connection.getVersion()
			) : handler;
		} catch (IllegalArgumentException | IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	});
}
 
Example 7
@Override
public void buildBungeeClientCodec(Channel channel, Connection connection) {
	ChannelPipeline pipeline = channel.pipeline();
	NetworkDataCache cache = new NetworkDataCache();
	cache.storeIn(connection);
	pipeline.replace(PipelineUtils.PACKET_DECODER, PipelineUtils.PACKET_DECODER, new FromClientPacketDecoder(connection, cache));
	pipeline.replace(PipelineUtils.PACKET_ENCODER, PipelineUtils.PACKET_ENCODER, new ToClientPacketEncoder(connection, cache));
	pipeline.get(CustomHandlerBoss.class).setHandlerChangeListener((handler) -> {
		try {
			return (handler instanceof UpstreamBridge) ? new EntityRewriteUpstreamBridge(
				ReflectionUtils.getFieldValue(handler, "con"), connection.getVersion()
			) : handler;
		} catch (IllegalArgumentException | IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	});
}
 
Example 8
@Override
public void buildBungeeServer(Channel channel, Connection connection) {
	ChannelPipeline pipeline = channel.pipeline();
	pipeline.addFirst(new EncapsulatedHandshakeSender(null, false));
	NetworkDataCache cache = NetworkDataCache.getFrom(connection);
	pipeline.replace(PipelineUtils.PACKET_DECODER, PipelineUtils.PACKET_DECODER, new FromServerPacketDecoder(connection, cache));
	pipeline.replace(PipelineUtils.PACKET_ENCODER, PipelineUtils.PACKET_ENCODER, new ToServerPacketEncoder(connection, cache));
	pipeline.get(CustomHandlerBoss.class).setHandlerChangeListener(handler -> {
		try {
			return (handler instanceof DownstreamBridge) ? new EntityRewriteDownstreamBridge(
				ReflectionUtils.getFieldValue(handler, "con"), connection.getVersion()
			) : handler;
		} catch (IllegalArgumentException | IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	});
}
 
Example 9
@Override
public void buildBungeeClientCodec(Channel channel, Connection connection) {
	ChannelPipeline pipeline = channel.pipeline();
	NetworkDataCache cache = new NetworkDataCache();
	cache.storeIn(connection);
	pipeline.replace(PipelineUtils.PACKET_DECODER, PipelineUtils.PACKET_DECODER, new FromClientPacketDecoder(connection, cache));
	pipeline.replace(PipelineUtils.PACKET_ENCODER, PipelineUtils.PACKET_ENCODER, new ToClientPacketEncoder(connection, cache));
	pipeline.get(CustomHandlerBoss.class).setHandlerChangeListener((handler) -> {
		try {
			return (handler instanceof UpstreamBridge) ? new EntityRewriteUpstreamBridge(
				ReflectionUtils.getFieldValue(handler, "con"), connection.getVersion()
			) : handler;
		} catch (IllegalArgumentException | IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	});
}
 
Example 10
@Override
public void buildBungeeServer(Channel channel, Connection connection) {
	ChannelPipeline pipeline = channel.pipeline();
	pipeline.addFirst(new EncapsulatedHandshakeSender(null, false));
	NetworkDataCache cache = NetworkDataCache.getFrom(connection);
	pipeline.replace(PipelineUtils.PACKET_DECODER, PipelineUtils.PACKET_DECODER, new FromServerPacketDecoder(connection, cache));
	pipeline.replace(PipelineUtils.PACKET_ENCODER, PipelineUtils.PACKET_ENCODER, new ToServerPacketEncoder(connection, cache));
	pipeline.get(CustomHandlerBoss.class).setHandlerChangeListener(handler -> {
		try {
			return (handler instanceof DownstreamBridge) ? new EntityRewriteDownstreamBridge(
				ReflectionUtils.getFieldValue(handler, "con"), connection.getVersion()
			) : handler;
		} catch (IllegalArgumentException | IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	});
}
 
Example 11
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockPlace(BlockPlaceEvent event) {
	Player player = event.getPlayer();
	Connection connection = ProtocolSupportAPI.getConnection(player);
	if (
		(connection != null) &&
		(connection.getVersion().getProtocolType() == ProtocolType.PC) &&
		connection.getVersion().isBefore(ProtocolVersion.MINECRAFT_1_9)
	) {
		BlockDataEntry blockdataentry = MinecraftBlockData.get(MaterialAPI.getBlockDataNetworkId(event.getBlock().getBlockData()));
		player.playSound(
			event.getBlock().getLocation(),
			blockdataentry.getBreakSound(),
			SoundCategory.BLOCKS,
			(blockdataentry.getVolume() + 1.0F) / 2.0F,
			blockdataentry.getPitch() * 0.8F
		);
	}
}
 
Example 12
/**
 * Sets the scale of an entity using its ID
 * @param entityId
 * @param scale
 */
public static void setScale(int entityId, float scale) {
	if (scale == 1) {
		entityScales.remove(entityId);
	} else {
		entityScales.put(entityId, scale);
	}
	// Update to all players
	CollectionsUtils.ArrayMap<DataWatcherObject<?>> metadata = new CollectionsUtils.ArrayMap<>(PeMetaBase.SCALE);
	metadata.put(PeMetaBase.SCALE, new DataWatcherObjectFloatLe(scale));
	EntityDataPacket packet = new EntityDataPacket(entityId, metadata);
	for (Connection connection : PocketCon.getPocketConnections()) {
		PocketCon.sendPocketPacket(connection, packet);
	}
}
 
Example 13
/**
 * Sets the interact text of an entity using its id.
 * You can see the text when you look at an entity on pocketedition.
 * @param entityId
 * @param interactText
 */
public static void setInteractText(int entityId, String interactText) {
	if (interactText.equals(EntityMetadataProvider.DEFAULTINTERACT)) {
		entityInteracts.remove(entityId);
	} else {
		entityInteracts.put(entityId, interactText);
	}
	// Update to all players
	CollectionsUtils.ArrayMap<DataWatcherObject<?>> metadata = new CollectionsUtils.ArrayMap<>(PeMetaBase.BUTTON_TEXT_V1);
	metadata.put(PeMetaBase.BUTTON_TEXT_V1, new DataWatcherObjectString(interactText));
	EntityDataPacket packet = new EntityDataPacket(entityId, metadata);
	for (Connection connection : PocketCon.getPocketConnections()) {
		PocketCon.sendPocketPacket(connection, packet);
	}
}
 
Example 14
/***
 * Gets the last (send) modalType from the client.
 * <em>This method can only be called once 
 * as it removes the metadata from client when called.</em>
 * @param connection
 * @return the type.
 */
public static ModalType getSentType(Connection connection) {
	if (connection.hasMetadata(modalTypeKey)) {
		return (ModalType) connection.removeMetadata(modalTypeKey);
	} else {
		return ModalType.UNKNOWN;
	}
}
 
Example 15
@Override
public ServerPingResponseEvent createResponse(Connection connection) {
	PaperServerListPingEvent bevent = new PaperServerListPingEvent(
		new StatusClientImpl(connection),
		Bukkit.getMotd(),
		Bukkit.getOnlinePlayers().size(), Bukkit.getMaxPlayers(),
		createServerVersionString(), connection.getVersion().getId(),
		Bukkit.getServerIcon()
	);
	List<PlayerProfile> playerSample = bevent.getPlayerSample();
	Bukkit.getOnlinePlayers().stream()
	.limit(SpigotConfig.playerSample)
	.map(player -> new NameUUIDPlayerProfile(player.getUniqueId(), player.getName()))
	.forEach(playerSample::add);
	Bukkit.getPluginManager().callEvent(bevent);

	ServerPingResponseEvent revent = new ServerPingResponseEvent(
		connection,
		new ProtocolInfo(bevent.getProtocolVersion(), bevent.getVersion()),
		bevent.getServerIcon() != null ? ServerPlatform.get().getMiscUtils().convertBukkitIconToBase64(bevent.getServerIcon()) : null,
		bevent.getMotd(),
		bevent.getNumPlayers(), bevent.getMaxPlayers(),
		bevent.getPlayerSample().stream().map(PlayerProfile::getName).collect(Collectors.toList())
	);
	Bukkit.getPluginManager().callEvent(revent);

	return revent;
}
 
Example 16
@PocketPacketHandler
public void onModalResponse(Connection connection, ModalResponsePacket packet) {
	ModalType type = ModalUtils.getSentType(connection);
	JsonElement element = GsonUtils.JSON_PARSER.parse(packet.getModalJSON());
	boolean isClosed = element.isJsonNull();
	ModalResponseEvent responseEvent;
	switch(type) {
		case MODAL_WINDOW: {
			responseEvent = new ModalWindowResponseEvent(connection, packet.getModalId(), packet.getModalJSON(), type, isClosed ? false : element.getAsBoolean());
			break;
		}
		case SIMPLE_FORM: {
			responseEvent = new SimpleFormResponseEvent(connection, packet.getModalId(), packet.getModalJSON(), type, isClosed ? 0 : element.getAsInt());
			break;
		}
		case COMPLEX_FORM: {
			List<ElementResponse> responses = new ArrayList<>();
			if (!isClosed) {
				element.getAsJsonArray().forEach(elementResponse -> responses.add(new ElementResponse(elementResponse)));
			}
			responseEvent = new ComplexFormResponseEvent(connection, packet.getModalId(), packet.getModalJSON(), type, responses);
			break;
		}
		default:
		case UNKNOWN: {
			responseEvent = new ModalResponseEvent(connection, packet.getModalId(), packet.getModalJSON(), type);
		}
	}
	responseEvent.setCancelled(isClosed);
	Bukkit.getScheduler().runTask(ProtocolSupportPocketStuff.getInstance(), () -> {
		Bukkit.getPluginManager().callEvent(responseEvent);
		ModalUtils.getCallback(connection).ifPresent(consumer -> consumer.accept(responseEvent));
	});
}
 
Example 17
@PocketPacketHandler
public void onConnect(Connection connection, ClientLoginPacket packet) {
	if (packet.getJsonPayload() == null) { return; }
	byte[] skin = Base64.getDecoder().decode(packet.getJsonPayload().get("SkinData").getAsString());
	boolean isSlim = SkinUtils.slimFromModel(packet.getJsonPayload().get("SkinGeometryName").getAsString());
	new MineskinThread(skin, isSlim, (skindata) -> {
		connection.addMetadata(TRANSFER_SKIN, skindata);
		//Dynamically update when we can, propagate the skin to everyone.
		new PacketUtils.RunWhenOnline(connection, () -> {
			SkinUtils.updateSkin(connection.getPlayer(), skin, skindata, isSlim);
		}, 2, true, 200L);
	}).start();
}
 
Example 18
@PocketPacketHandler
public void onSkinChange(Connection connection, SkinPacket packet) {
	boolean slim = SkinUtils.slimFromModel(packet.getGeometryId());
	new MineskinThread(packet.getSkinData(), slim, (skindata) -> {
		plugin.debug(connection.getPlayer().getName() + " did a dynamic skin update!");
		SkinUtils.updateSkin(connection.getPlayer(), packet.getSkinData(), skindata, slim);
	}).start();
}
 
Example 19
@PocketPacketHandler
public void onConnect(Connection connection, ClientLoginPacket packet) {
	JsonObject clientPayload = packet.getJsonPayload();
	JsonObject chain = packet.getChainPayload();
	HashMap<String, Object> clientInfo = new HashMap<>();
	// "In general you shouldn't really expect the payload to be sent with psbpe" -Shevchik
	if (chain != null && clientPayload != null) {
		clientInfo.put("UUID", UUID.fromString(JsonUtils.getString(chain, "identity")));
		if (clientPayload.get("ClientRandomId") != null) clientInfo.put("ClientRandomId", clientPayload.get("ClientRandomId").getAsLong());
		if (clientPayload.get("DeviceModel") != null) clientInfo.put("DeviceModel", clientPayload.get("DeviceModel").getAsString());
		if (clientPayload.get("DeviceOS") != null) clientInfo.put("DeviceOS", clientPayload.get("DeviceOS").getAsInt());
		if (clientPayload.get("GameVersion") != null) clientInfo.put("GameVersion", clientPayload.get("GameVersion").getAsString());
	}
	connection.addMetadata(StuffUtils.CLIENT_INFO_KEY, clientInfo);
}
 
Example 20
public RunWhenOnline(Connection connection, Runnable run, int maxtries, boolean sync, long logindelay) {
	this.connection = connection;
	this.run = run;
	this.maxtries = maxtries;
	this.sync = sync;
	this.logindelay = logindelay;
}
 
Example 21
public void handle(Connection connection, PEPacket packet) {
	try {
		method.invoke(listener, connection, packet);
	} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
		e.printStackTrace();
	}
}
 
Example 22
public static void encodeAttributes(Connection connection, ByteBuf serializer, List<Attribute> attributes) {
	VarNumberSerializer.writeVarInt(serializer, attributes.size());
	for (Attribute attribute : attributes) {
		serializer.writeFloatLE(attribute.getMinimum());
		serializer.writeFloatLE(attribute.getMaximum());
		serializer.writeFloatLE(attribute.getValue());
		serializer.writeFloatLE(attribute.getDefaultValue()); //default value
		StringSerializer.writeString(serializer, connection.getVersion(), attribute.getName());
	}
}
 
Example 23
public ServerPingResponseEvent(Connection connection, ProtocolInfo info, String icon, String motd, int onlinePlayers, int maxPlayers, List<String> players) {
	super(connection);
	setProtocolInfo(info);
	setIcon(icon);
	setMotd(motd);
	this.onlinePlayers = onlinePlayers;
	setMaxPlayers(maxPlayers);
	setPlayers(players);
}
 
Example 24
public AbstractPacketEncoder(Connection connection, NetworkDataCache cache) {
	super(Protocol.HANDSHAKE, true, ProtocolVersionsHelper.LATEST_PC.getId());
	this.connection = connection;
	this.cache = cache;
	registry.setCallBack(transformer -> {
		transformer.setConnection(this.connection);
		transformer.setSharedStorage(this.cache);
	});
}
 
Example 25
public LegacyAbstractFromServerPacketDecoder(Connection connection, NetworkDataCache cache) {
	super(Protocol.GAME, false, ProtocolVersionsHelper.LATEST_PC.getId());
	this.connection = connection;
	this.cache = cache;
	registry.setCallBack(transformer -> {
		transformer.setConnection(this.connection);
		transformer.setSharedStorage(this.cache);
	});
}
 
Example 26
public PlayerAbstractLoginEvent(Connection connection) {
	this(connection, true);
}
 
Example 27
/***
 * @return The connection of the responding player.
 */
public Connection getConnection() {
	return connection;
}
 
Example 28
public PlayerLoginFinishEvent(Connection connection) {
	super(connection);
}
 
Example 29
public StatusClientImpl(Connection connection) {
	this.connection = connection;
}
 
Example 30
public ConnectionOpenEvent(Connection connection) {
	super(connection);
}