List of usage examples for com.google.common.io ByteArrayDataOutput writeByte
@Override void writeByte(int v);
From source file:codecrafter47.bungeetablistplus.bukkitbridge.BukkitBridge.java
@EventHandler @SneakyThrows/*from w ww . java 2 s.com*/ public void onChannelRegistration(PlayerRegisterChannelEvent event) { if (BridgeProtocolConstants.CHANNEL.equals(event.getChannel())) { ByteArrayDataOutput data = ByteStreams.newDataOutput(); data.writeByte(BridgeProtocolConstants.MESSAGE_ID_SERVER_ENABLE_CONNECTION); DataStreamUtils.writeUUID(data, serverId); event.getPlayer().sendPluginMessage(plugin, BridgeProtocolConstants.CHANNEL, data.toByteArray()); } }
From source file:codecrafter47.bungeetablistplus.bridge.BukkitBridge.java
@EventHandler public void onPluginMessage(PluginMessageEvent event) { if (event.getReceiver() instanceof ProxiedPlayer && event.getSender() instanceof Server) { ProxiedPlayer player = (ProxiedPlayer) event.getReceiver(); Server server = (Server) event.getSender(); if (event.getTag().equals(BridgeProtocolConstants.CHANNEL)) { event.setCancelled(true);//from w w w . j av a 2 s .c om ConnectedPlayer connectedPlayer = plugin.getConnectedPlayerManager().getPlayerIfPresent(player); if (connectedPlayer != null) { PlayerBridgeDataCache cache = connectedPlayer.getBridgeDataCache(); DataInput input = new DataInputStream(new ByteArrayInputStream(event.getData())); try { int messageId = input.readUnsignedByte(); switch (messageId) { case BridgeProtocolConstants.MESSAGE_ID_SERVER_HANDSHAKE: if (cache.connection != null) { disableConnection(cache); } cache.connection = server; getServerDataCache(server.getInfo().getName()).addConnection(server); ArrayList<DataKey<?>> keys = Lists.newArrayList(cache.getQueriedKeys()); ByteArrayDataOutput data = ByteStreams.newDataOutput(); data.writeByte(BridgeProtocolConstants.MESSAGE_ID_PROXY_REQUEST_DATA); data.writeInt(keys.size()); for (DataKey<?> key : keys) { DataStreamUtils.writeDataKey(data, key); data.writeInt(idMap.getNetId(key)); } server.sendData(BridgeProtocolConstants.CHANNEL, data.toByteArray()); break; case BridgeProtocolConstants.MESSAGE_ID_SERVER_UPDATE_DATA: if (cache.connection == server) { onDataReceived(cache, input, input.readInt()); } break; case BridgeProtocolConstants.MESSAGE_ID_SERVER_UPDATE_SERVER_DATA: if (cache.connection == server) { ServerBridgeDataCache serverDataCache = getServerDataCache( server.getInfo().getName()); int revision = input.readInt(); int size = input.readInt(); if (size > 0 && revision == serverDataCache.lastRevision + 1) { onDataReceived(serverDataCache, input, size); serverDataCache.lastRevision = revision; } else if (size > 0 || revision > serverDataCache.lastRevision) { Server connection = serverDataCache.getConnection(); if (connection != null) { ByteArrayDataOutput output = ByteStreams.newDataOutput(); output.writeByte( BridgeProtocolConstants.MESSAGE_ID_PROXY_REQUEST_RESET_SERVER_DATA); connection.sendData(BridgeProtocolConstants.CHANNEL, output.toByteArray()); serverDataCache.lastRevision = 0; } } } break; case BridgeProtocolConstants.MESSAGE_ID_SERVER_DISABLE_CONNECTION: disableConnection(cache); serverInformation.get(server.getInfo().getName()).reset(); break; case BridgeProtocolConstants.MESSAGE_ID_SERVER_ENABLE_CONNECTION: UUID serverId = DataStreamUtils.readUUID(input); ServerBridgeDataCache serverData = getServerDataCache(server.getInfo().getName()); if (!serverData.serverId.equals(serverId)) { serverData.serverId = serverId; serverData.reset(); } initializeHandshake(server); break; case BridgeProtocolConstants.MESSAGE_ID_SERVER_OUTDATED: rlExecutor.execute(() -> plugin.getLogger().warning( "Bridge plugin on server " + server.getInfo().getName() + " is outdated.")); break; } } catch (IOException ex) { plugin.getLogger().log(Level.SEVERE, "An unexpected error occurred while processing bridge data.", ex); } } } } }
From source file:cpw.mods.fml.common.network.EntitySpawnPacket.java
@Override public byte[] generatePacket(Object... data) { EntityRegistration er = (EntityRegistration) data[0]; Entity ent = (Entity) data[1]; NetworkModHandler handler = (NetworkModHandler) data[2]; ByteArrayDataOutput dat = ByteStreams.newDataOutput(); dat.writeInt(handler.getNetworkId()); dat.writeInt(er.getModEntityId());/*ww w . j a va 2s . c om*/ // entity id dat.writeInt(ent.field_70157_k); // entity pos x,y,z dat.writeInt(MathHelper.func_76128_c(ent.field_70165_t * 32D)); dat.writeInt(MathHelper.func_76128_c(ent.field_70163_u * 32D)); dat.writeInt(MathHelper.func_76128_c(ent.field_70161_v * 32D)); // yaw, pitch dat.writeByte((byte) (ent.field_70177_z * 256.0F / 360.0F)); dat.writeByte((byte) (ent.field_70125_A * 256.0F / 360.0F)); // head yaw if (ent instanceof EntityLiving) { dat.writeByte((byte) (((EntityLiving) ent).field_70759_as * 256.0F / 360.0F)); } else { dat.writeByte(0); } ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos); try { ent.func_70096_w().func_75689_a(dos); } catch (IOException e) { // unpossible } dat.write(bos.toByteArray()); if (ent instanceof IThrowableEntity) { Entity owner = ((IThrowableEntity) ent).getThrower(); dat.writeInt(owner == null ? ent.field_70157_k : owner.field_70157_k); double maxVel = 3.9D; double mX = ent.field_70159_w; double mY = ent.field_70181_x; double mZ = ent.field_70179_y; if (mX < -maxVel) mX = -maxVel; if (mY < -maxVel) mY = -maxVel; if (mZ < -maxVel) mZ = -maxVel; if (mX > maxVel) mX = maxVel; if (mY > maxVel) mY = maxVel; if (mZ > maxVel) mZ = maxVel; dat.writeInt((int) (mX * 8000D)); dat.writeInt((int) (mY * 8000D)); dat.writeInt((int) (mZ * 8000D)); } else { dat.writeInt(0); } if (ent instanceof IEntityAdditionalSpawnData) { ((IEntityAdditionalSpawnData) ent).writeSpawnData(dat); } return dat.toByteArray(); }
From source file:codecrafter47.bungeetablistplus.bukkitbridge.BukkitBridge.java
public void onEnable() { try {// w ww . j av a 2s .c om Field field = BungeeTabListPlusBukkitAPI.class.getDeclaredField("instance"); field.setAccessible(true); field.set(null, this); } catch (NoSuchFieldException | IllegalAccessException ex) { plugin.getLogger().log(Level.SEVERE, "Failed to initialize API", ex); } plugin.getServer().getMessenger().registerOutgoingPluginChannel(plugin, BridgeProtocolConstants.CHANNEL); plugin.getServer().getMessenger().registerIncomingPluginChannel(plugin, BridgeProtocolConstants.CHANNEL, (string, player, bytes) -> { DataInput input = new DataInputStream(new ByteArrayInputStream(bytes)); try { int messageId = input.readUnsignedByte(); switch (messageId) { case BridgeProtocolConstants.MESSAGE_ID_PROXY_HANDSHAKE: UUID proxyId = DataStreamUtils.readUUID(input); int protocolVersion = input.readInt(); if (protocolVersion > BridgeProtocolConstants.VERSION) { rlExecutor.execute(() -> plugin.getLogger() .warning("BungeeTabListPlus_BukkitBridge is outdated.")); } else if (protocolVersion < BridgeProtocolConstants.VERSION) { rlExecutor.execute(() -> plugin.getLogger() .warning("BungeeTabListPlus proxy plugin outdated.")); } else { playerData.put(player, new PlayerBridgeData(proxyId)); serverData.computeIfAbsent(proxyId, uuid -> new ServerBridgeData()); ByteArrayDataOutput data = ByteStreams.newDataOutput(); data.writeByte(BridgeProtocolConstants.MESSAGE_ID_SERVER_HANDSHAKE); player.sendPluginMessage(plugin, BridgeProtocolConstants.CHANNEL, data.toByteArray()); } break; case BridgeProtocolConstants.MESSAGE_ID_PROXY_REQUEST_DATA: BridgeData bridgeData = playerData.get(player); if (bridgeData != null) { handleDataRequest(bridgeData, input); } break; case BridgeProtocolConstants.MESSAGE_ID_PROXY_REQUEST_SERVER_DATA: PlayerBridgeData playerBridgeData = playerData.get(player); if (playerBridgeData != null) { bridgeData = serverData.get(playerBridgeData.proxyId); if (bridgeData != null) { handleDataRequest(bridgeData, input); } } break; case BridgeProtocolConstants.MESSAGE_ID_PROXY_OUTDATED: rlExecutor.execute( () -> plugin.getLogger().warning("BungeeTabListPlus proxy plugin outdated.")); break; case BridgeProtocolConstants.MESSAGE_ID_PROXY_REQUEST_RESET_SERVER_DATA: playerBridgeData = playerData.get(player); if (playerBridgeData != null) { bridgeData = serverData.get(playerBridgeData.proxyId); if (bridgeData != null) { serverData.put(playerBridgeData.proxyId, new ServerBridgeData()); } } break; default: plugin.getLogger().warning("Received unknown message id " + messageId); break; } } catch (IOException ex) { plugin.getLogger().log(Level.SEVERE, "An unexpected error occurred while processing a plugin message.", ex); } }); plugin.getServer().getPluginManager().registerEvents(this, plugin); updateDataHooks(); // initialize bridge for players already on the server for (Player player : plugin.getServer().getOnlinePlayers()) { ByteArrayDataOutput data = ByteStreams.newDataOutput(); data.writeByte(BridgeProtocolConstants.MESSAGE_ID_SERVER_ENABLE_CONNECTION); try { DataStreamUtils.writeUUID(data, serverId); } catch (IOException e) { throw new AssertionError(e); } player.sendPluginMessage(plugin, BridgeProtocolConstants.CHANNEL, data.toByteArray()); } // start update task plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, () -> { long now = System.currentTimeMillis(); Map<UUID, Player> proxyIds = new HashMap<>(); for (Map.Entry<Player, PlayerBridgeData> e : playerData.entrySet()) { Player player = e.getKey(); PlayerBridgeData bridgeData = e.getValue(); proxyIds.putIfAbsent(bridgeData.proxyId, player); int size = 0; for (CacheEntry entry : bridgeData.requestedData) { Object value = playerDataAccess.get(entry.key, player); entry.dirty = !Objects.equals(value, entry.value); entry.value = value; if (entry.dirty) { size++; } } if (size != 0) { ByteArrayDataOutput data = ByteStreams.newDataOutput(); data.writeByte(BridgeProtocolConstants.MESSAGE_ID_SERVER_UPDATE_DATA); data.writeInt(size); for (CacheEntry entry : bridgeData.requestedData) { if (entry.dirty) { data.writeInt(entry.netId); data.writeBoolean(entry.value == null); if (entry.value != null) { try { typeRegistry.getTypeAdapter((TypeToken<Object>) entry.key.getType()).write(data, entry.value); } catch (java.io.IOException e1) { e1.printStackTrace(); } } } } player.sendPluginMessage(plugin, BridgeProtocolConstants.CHANNEL, data.toByteArray()); } } for (Map.Entry<UUID, Player> e : proxyIds.entrySet()) { UUID proxyId = e.getKey(); Player player = e.getValue(); ServerBridgeData bridgeData = serverData.get(proxyId); if (bridgeData == null) { continue; } bridgeData.lastUpdate = now; int size = 0; for (CacheEntry entry : bridgeData.requestedData) { Object value = serverDataAccess.get(entry.key, plugin.getServer()); entry.dirty = !Objects.equals(value, entry.value); entry.value = value; if (entry.dirty) { size++; } } ByteArrayDataOutput data = ByteStreams.newDataOutput(); data.writeByte(BridgeProtocolConstants.MESSAGE_ID_SERVER_UPDATE_SERVER_DATA); if (size > 0) { bridgeData.revision++; } data.writeInt(bridgeData.revision); data.writeInt(size); for (CacheEntry entry : bridgeData.requestedData) { if (entry.dirty) { data.writeInt(entry.netId); data.writeBoolean(entry.value == null); if (entry.value != null) { try { typeRegistry.getTypeAdapter((TypeToken<Object>) entry.key.getType()).write(data, entry.value); } catch (java.io.IOException e1) { e1.printStackTrace(); } } } } player.sendPluginMessage(plugin, BridgeProtocolConstants.CHANNEL, data.toByteArray()); } for (Iterator<ServerBridgeData> iterator = serverData.values().iterator(); iterator.hasNext();) { ServerBridgeData data = iterator.next(); if (now - data.lastUpdate > 900000) { iterator.remove(); } } }, 20, 20); }
From source file:shadowmage.ancient_warfare.common.gates.EntityGate.java
@Override public void writeSpawnData(ByteArrayDataOutput data) { data.writeInt(pos1.x);//from w w w . ja va 2s. c o m data.writeInt(pos1.y); data.writeInt(pos1.z); data.writeInt(pos2.x); data.writeInt(pos2.y); data.writeInt(pos2.z); data.writeInt(this.gateType.getGlobalID()); data.writeInt(this.teamNum); data.writeFloat(this.edgePosition); data.writeFloat(this.edgeMax); data.writeByte(this.gateStatus); data.writeByte(this.gateOrientation); data.writeInt(health); }
From source file:org.apache.druid.indexer.InputRowSerde.java
public static final SerializeResult toBytes(final Map<String, IndexSerdeTypeHelper> typeHelperMap, final InputRow row, AggregatorFactory[] aggs) { try {//ww w .j a v a2s . co m List<String> parseExceptionMessages = new ArrayList<>(); ByteArrayDataOutput out = ByteStreams.newDataOutput(); //write timestamp out.writeLong(row.getTimestampFromEpoch()); //writing all dimensions List<String> dimList = row.getDimensions(); WritableUtils.writeVInt(out, dimList.size()); for (String dim : dimList) { IndexSerdeTypeHelper typeHelper = typeHelperMap.get(dim); if (typeHelper == null) { typeHelper = STRING_HELPER; } writeString(dim, out); try { typeHelper.serialize(out, row.getRaw(dim)); } catch (ParseException pe) { parseExceptionMessages.add(pe.getMessage()); } } //writing all metrics Supplier<InputRow> supplier = () -> row; WritableUtils.writeVInt(out, aggs.length); for (AggregatorFactory aggFactory : aggs) { String k = aggFactory.getName(); writeString(k, out); try (Aggregator agg = aggFactory.factorize(IncrementalIndex .makeColumnSelectorFactory(VirtualColumns.EMPTY, aggFactory, supplier, true))) { try { agg.aggregate(); } catch (ParseException e) { // "aggregate" can throw ParseExceptions if a selector expects something but gets something else. log.debug(e, "Encountered parse error, skipping aggregator[%s].", k); parseExceptionMessages.add(e.getMessage()); } String t = aggFactory.getTypeName(); if (agg.isNull()) { out.writeByte(NullHandling.IS_NULL_BYTE); } else { out.writeByte(NullHandling.IS_NOT_NULL_BYTE); if ("float".equals(t)) { out.writeFloat(agg.getFloat()); } else if ("long".equals(t)) { WritableUtils.writeVLong(out, agg.getLong()); } else if ("double".equals(t)) { out.writeDouble(agg.getDouble()); } else { //its a complex metric Object val = agg.get(); ComplexMetricSerde serde = getComplexMetricSerde(t); writeBytes(serde.toBytes(val), out); } } } } return new SerializeResult(out.toByteArray(), parseExceptionMessages); } catch (IOException ex) { throw new RuntimeException(ex); } }
From source file:de.minigameslib.mclib.impl.MclibPlugin.java
@Override public void broadcastClients(CommunicationEndpointId id, DataSection... data) { if (data != null) { for (final DataSection section : data) { final ByteArrayDataOutput out = ByteStreams.newDataOutput(); out.writeByte(0); new NetMessage(id, section).toBytes(out); byte[] bytes = out.toByteArray(); if (this.getLogger().isLoggable(Level.FINEST)) { this.getLogger().finest("Sending NetMessage to all players\n" + Arrays.toString(bytes)); //$NON-NLS-1$ }/*from www. j av a 2 s . c o m*/ // TODO find a way to broadcast to all players connected to any server in bungee cord network Bukkit.getServer().sendPluginMessage(this, MCLIB_SERVER_TO_CLIENT_CHANNEL, bytes); } } }
From source file:de.minigameslib.mclib.impl.MclibPlugin.java
@Override public void send(CommunicationEndpointId id, DataSection... data) { // check if we have a server-to-server endpoint or server-to-client endpoint if (this.endpointTypes.get(id)) { // server to player final McPlayerInterface player = this.getCurrentPlayer(); if (player == null) { this.getLogger().fine("Trying to send data to unknown player (invalid context)"); //$NON-NLS-1$ } else if (data != null) { for (final DataSection section : data) { final ByteArrayDataOutput out = ByteStreams.newDataOutput(); out.writeByte(0); new NetMessage(id, section).toBytes(out); byte[] bytes = out.toByteArray(); if (this.getLogger().isLoggable(Level.FINEST)) { this.getLogger().finest("Sending NetMessage to player " + player.getPlayerUUID() + "\n" //$NON-NLS-1$//$NON-NLS-2$ + Arrays.toString(bytes)); }/*from w w w.j a v a2 s . co m*/ player.getBukkitPlayer().sendPluginMessage(this, MCLIB_SERVER_TO_CLIENT_CHANNEL, bytes); } } } else { // server to server means: broadcast to everyone this.broadcastServers(id, data); } }
From source file:de.minigameslib.mclib.impl.MclibPlugin.java
@Override public void broadcastServers(CommunicationEndpointId id, DataSection... data) { if (data != null) { for (final DataSection section : data) { // TODO only works if both servers have online players // TODO if target servers do not have online players the messages should be queued by bungeecord. // TODO ensure that we are really within bungeecord environments, else this will be sent to clients (not good) final ByteArrayDataOutput out2 = ByteStreams.newDataOutput(); final ByteArrayDataOutput out = ByteStreams.newDataOutput(); out2.writeUTF("Forward"); //$NON-NLS-1$ out2.writeUTF("ALL"); //$NON-NLS-1$ out2.writeUTF(MCLIB_SERVER_TO_SERVER_CHANNEL); out.writeByte(0); new NetMessage(id, section).toBytes(out); byte[] bytes = out.toByteArray(); if (this.getLogger().isLoggable(Level.FINEST)) { this.getLogger().finest("Sending NetMessage to all servers\n" + Arrays.toString(bytes)); //$NON-NLS-1$ }//from w w w . j a v a 2 s . c o m out2.writeShort(bytes.length); out2.write(bytes); final ObjectServiceInterface osi = ObjectServiceInterface.instance(); final Optional<? extends Player> player = Bukkit.getOnlinePlayers().stream() .filter(p -> !osi.isHuman(p)).findFirst(); if (player.isPresent()) { // bungee cord ensures this is not send to the client. player.get().sendPluginMessage(this, BUNGEECORD_CHANNEL, bytes); } else { this.bungeeQueue.add(p -> p.sendPluginMessage(this, BUNGEECORD_CHANNEL, bytes)); } } } }