List of usage examples for com.google.common.io ByteArrayDataOutput toByteArray
byte[] toByteArray();
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 {/*from w w w. j a v a2 s . com*/ 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: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());/*from w w w. j av a2s . c o m*/ // 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:de.nx42.maps4cim.header.CustomHeader.java
@Override public byte[] generateHeader() throws IOException { // first part ByteArrayDataOutput outP1 = ByteStreams.newDataOutput(4096); // static intro outP1.write(intro);// w w w.ja va 2s . c om outP1.write(formatHeaderString(staticString01)); // gap of 4 bytes outP1.write(new byte[4]); // dates and timestamps outP1.writeLong(DateUtils.dateToTicks(unusedDate1)); outP1.writeLong(DateUtils.dateToTicks(unusedDate2)); outP1.writeLong(DateUtils.dateToTicks(lastSaved)); outP1.writeLong(DateUtils.dateToTicks(mapCreated)); outP1.writeLong(workTime1); outP1.writeLong(workTime2); // static data outP1.write(staticBinary01); outP1.write(formatHeaderString(staticString02)); // map name outP1.write(formatHeaderString(mapName)); if (buildingSet == BuildingSet.EUROPEAN) { outP1.write(formatHeaderString(staticString02eur01)); } // map overview image outP1.write(pngLength); outP1.write(png); // static data outP1.write(staticBinary02); if (buildingSet == BuildingSet.EUROPEAN) { outP1.write(formatHeaderString(staticString02eur02)); outP1.write(staticBinary02eur); } outP1.write(formatHeaderString(staticString03)); outP1.write(new byte[34]); outP1.write(staticBinary03); outP1.write(formatHeaderString(staticString04)); outP1.write(formatHeaderString(staticString05)); // second part ByteArrayDataOutput outP2 = ByteStreams.newDataOutput(256); // static data outP2.write(intro); outP2.write(formatHeaderString(staticString06)); outP2.write(staticBinary04); for (String s : staticStrings07) { outP2.write(formatHeaderString(s)); } outP2.write(staticBinary05); // combine the parts ByteArrayDataOutput out = ByteStreams.newDataOutput(4352); byte[] p1 = outP1.toByteArray(); out.write(p1); // fill with 0s until next next free index % 4096 = 0 out.write(new byte[((p1.length / 4096) + 1) * 4096 - p1.length]); byte[] p2 = outP2.toByteArray(); out.write(p2); // fill with 0s until 256 bytes are filled after the beginning of p2 out.write(new byte[256 - p2.length]); // return combined result return out.toByteArray(); }
From source file:net.portalblock.rbbridge.MessageChannelListener.java
@EventHandler public void onPluginMessage(final PluginMessageEvent event) { if (event.getTag().equals("RedisBungee") && event.getSender() instanceof Server) { final byte[] data = Arrays.copyOf(event.getData(), event.getData().length); plugin.getProxy().getScheduler().runAsync(plugin, new Runnable() { @Override/* www . ja v a 2s.com*/ public void run() { ByteArrayDataInput in = ByteStreams.newDataInput(data); String subchannel = in.readUTF(); ByteArrayDataOutput out = ByteStreams.newDataOutput(); String type; switch (subchannel) { case "PlayerList": out.writeUTF("PlayerList"); Set<UUID> original = Collections.emptySet(); type = in.readUTF(); if (type.equals("ALL")) { out.writeUTF("ALL"); original = RedisBungee.getApi().getPlayersOnline(); } else { try { original = RedisBungee.getApi().getPlayersOnServer(type); } catch (IllegalArgumentException ignored) { } } Set<String> players = new HashSet<String>(); for (UUID uuid : original) players.add(RedisBungee.getApi().getNameFromUuid(uuid, false)); out.writeUTF(Joiner.on(',').join(players)); break; case "PlayerCount": out.writeUTF("PlayerCount"); type = in.readUTF(); if (type.equals("ALL")) { out.writeUTF("ALL"); out.writeInt(RedisBungee.getApi().getPlayerCount()); } else { out.writeUTF(type); try { out.writeInt(RedisBungee.getApi().getPlayersOnServer(type).size()); } catch (IllegalArgumentException e) { out.writeInt(0); } } break; case "LastOnline": String user = in.readUTF(); out.writeUTF("LastOnline"); out.writeUTF(user); out.writeLong(RedisBungee.getApi() .getLastOnline(RedisBungee.getApi().getUuidFromName(user, true))); break; default: break; } ((Server) event.getSender()).sendData("RedisBungee", out.toByteArray()); } }); } }
From source file:io.github.runelynx.runicparadise.RunicParadise.java
@SuppressWarnings("deprecation") public void updatePlayerInfoOnJoin(String name, UUID pUUID) { final Date now = new Date(); final String playerName = name; final UUID playerUUID = pUUID; MySQL MySQL = new MySQL(instance, instance.getConfig().getString("dbHost"), instance.getConfig().getString("dbPort"), instance.getConfig().getString("dbDatabase"), instance.getConfig().getString("dbUser"), instance.getConfig().getString("dbPassword")); final Connection dbConn = MySQL.openConnection(); int rowCount = -1; int rowCountnameMatch = -1; String previousName = ""; try {//from w w w . j av a 2 s . c o m PreparedStatement dStmt = dbConn .prepareStatement("SELECT COUNT(*) as Total, PlayerName FROM rp_PlayerInfo WHERE UUID = ?;"); dStmt.setString(1, playerUUID.toString()); ResultSet dbResult = dStmt.executeQuery(); while (dbResult.next()) { rowCount = dbResult.getInt("Total"); previousName = dbResult.getString("PlayerName"); } dStmt.close(); PreparedStatement zStmt = dbConn .prepareStatement("SELECT COUNT(*) as Total FROM rp_PlayerInfo WHERE PlayerName = ?;"); zStmt.setString(1, playerName); ResultSet zResult = zStmt.executeQuery(); while (zResult.next()) { rowCountnameMatch = zResult.getInt("Total"); } zStmt.close(); } catch (SQLException e) { getLogger().log(Level.SEVERE, "Cant check for row count in updatePlayerInfoOnJoin for " + playerName + " because: " + e.getMessage()); } if (rowCount != rowCountnameMatch) { Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "sc Name change detected for " + playerName + " (" + previousName + ")"); Bukkit.getLogger().log(Level.INFO, "[RP] Name change detected for " + playerName + " (" + previousName + ")"); } try { // if this player has no rows in the table yet if (rowCount == 0) { Bukkit.getServer().getScheduler().scheduleAsyncDelayedTask(instance, new Runnable() { public void run() { // tell the other server this one is reconnected // to the universe ByteArrayDataOutput out = ByteStreams.newDataOutput(); out.writeUTF("Forward"); // So BungeeCord knows // to forward it out.writeUTF("ONLINE"); out.writeUTF("NewPlayer"); // The channel name // to check if this // your data ByteArrayOutputStream msgbytes = new ByteArrayOutputStream(); DataOutputStream msgout = new DataOutputStream(msgbytes); try { msgout.writeUTF(Bukkit.getPlayer(playerUUID).getDisplayName()); // You // can // do // anything // msgout msgout.writeShort(123); } catch (IOException e) { } out.writeShort(msgbytes.toByteArray().length); out.write(msgbytes.toByteArray()); // If you don't care about the player // Player player = // Iterables.getFirst(Bukkit.getOnlinePlayers(), // null); // Else, specify them Bukkit.getPlayer(playerUUID).sendPluginMessage(instance, "BungeeCord", out.toByteArray()); } }, 140); // ///////////////////// PreparedStatement dStmt = dbConn.prepareStatement( "INSERT INTO rp_PlayerInfo (`PlayerName`, `UUID`, `ActiveFaith`, `LastIP`, `FirstSeen`, `LastSeen`) VALUES " + "(?, ?, ?, ?, ?, ?);"); dStmt.setString(1, playerName); dStmt.setString(2, playerUUID.toString()); dStmt.setString(3, "Sun"); dStmt.setString(4, Bukkit.getPlayer(playerUUID).getAddress().getAddress().getHostAddress()); dStmt.setLong(5, now.getTime()); dStmt.setLong(6, now.getTime()); dStmt.executeUpdate(); PreparedStatement pStmt = dbConn .prepareStatement("INSERT INTO rp_PlayerMobKills (`UUID`) VALUES " + "(?);"); pStmt.setString(1, playerUUID.toString()); pStmt.executeUpdate(); pStmt.close(); dStmt.close(); // if this player has 1 row in the table } else if (rowCount == 1) { PreparedStatement dStmt = dbConn.prepareStatement( "UPDATE `rp_PlayerInfo` SET LastSeen=?, PlayerName=?, LastIP=? WHERE UUID=?;"); dStmt.setLong(1, now.getTime()); dStmt.setString(2, playerName); dStmt.setString(3, Bukkit.getPlayer(playerUUID).getAddress().getAddress().getHostAddress()); dStmt.setString(4, playerUUID.toString()); dStmt.executeUpdate(); dStmt.close(); Bukkit.getLogger().log(Level.INFO, "[RP] PlayerInfo data updated for " + playerName); // if this player has MORE than 1 row in the // table } else if (rowCount > 1) { int counter = 1; PreparedStatement zStmt = dbConn .prepareStatement("SELECT * FROM rp_PlayerInfo WHERE UUID = ? ORDER BY ID ASC;"); zStmt.setString(1, playerUUID.toString()); ResultSet zResult = zStmt.executeQuery(); while (zResult.next()) { // The first row is our valid one - update // it! if (counter == 1) { PreparedStatement dStmt = dbConn.prepareStatement( "UPDATE `rp_PlayerInfo` SET LastSeen=?, PlayerName=? WHERE UUID=?;"); dStmt.setLong(1, now.getTime()); dStmt.setString(2, playerName); dStmt.setString(3, playerUUID.toString()); dStmt.executeUpdate(); dStmt.close(); Bukkit.getLogger().log(Level.INFO, "[RP] PlayerInfo data [row " + zResult.getInt("ID") + "] updated for " + playerName); // All further rows are invalid, delete // them! } else if (counter > 1) { PreparedStatement dStmt = dbConn .prepareStatement("DELETE FROM `rp_PlayerInfo` WHERE ID = ? LIMIT 1;"); dStmt.setInt(1, zResult.getInt("ID")); dStmt.executeUpdate(); dStmt.close(); Bukkit.getLogger().log(Level.INFO, "[RP] PlayerInfo dupe row cleanup (name change?)! Deleted row " + zResult.getInt("ID")); } counter++; } zStmt.close(); } dbConn.close(); } catch (SQLException e) { getLogger().log(Level.SEVERE, "Cant work with DB updatePlayerInfoOnJoin for " + playerName + " because: " + e.getMessage()); } }