下面列出了怎么用com.google.common.io.ByteArrayDataOutput的API类实例代码及写法,或者点击链接到github查看源代码。
static byte[] serializeBinary(TagContext tags) throws TagContextSerializationException {
// Use a ByteArrayDataOutput to avoid needing to handle IOExceptions.
final ByteArrayDataOutput byteArrayDataOutput = ByteStreams.newDataOutput();
byteArrayDataOutput.write(VERSION_ID);
int totalChars = 0; // Here chars are equivalent to bytes, since we're using ascii chars.
for (Iterator<Tag> i = InternalUtils.getTags(tags); i.hasNext(); ) {
Tag tag = i.next();
if (TagTtl.NO_PROPAGATION.equals(tag.getTagMetadata().getTagTtl())) {
continue;
}
totalChars += tag.getKey().getName().length();
totalChars += tag.getValue().asString().length();
encodeTag(tag, byteArrayDataOutput);
}
if (totalChars > TAGCONTEXT_SERIALIZED_SIZE_LIMIT) {
throw new TagContextSerializationException(
"Size of TagContext exceeds the maximum serialized size "
+ TAGCONTEXT_SERIALIZED_SIZE_LIMIT);
}
return byteArrayDataOutput.toByteArray();
}
@Override
public void execute(CommandSender commandSender, String[] strings) {
ServerInfo serverInfo = this.getLobby();
if (serverInfo != null && commandSender instanceof ProxiedPlayer) {
ProxiedPlayer player = (ProxiedPlayer) commandSender;
if (!player.getServer().getInfo().getName().equals(serverInfo.getName())) {
player.connect(getLobby());
} else {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("HubBasics");
out.writeUTF("Lobby");
player.sendData("BungeeCord", out.toByteArray());
}
} else if (serverInfo == null) {
commandSender.sendMessage(new TextComponent(Messages.get(commandSender, "LOBBY_NOT_DEFINED")));
} else {
commandSender.sendMessage(new TextComponent(Messages.get(commandSender, "COMMAND_PLAYER")));
}
}
private <T> void updateData(UUID uuid, DataKey<T> key, T value) {
try {
ByteArrayDataOutput data = ByteStreams.newDataOutput();
DataStreamUtils.writeUUID(data, uuid);
DataStreamUtils.writeDataKey(data, key);
data.writeBoolean(value == null);
if (value != null) {
typeRegistry.getTypeAdapter(key.getType()).write(data, value);
}
RedisBungee.getApi().sendChannelMessage(CHANNEL_DATA_UPDATE, Base64.getEncoder().encodeToString(data.toByteArray()));
} catch (RuntimeException ex) {
BungeeTabListPlus.getInstance().getLogger().log(Level.WARNING, "RedisBungee Error", ex);
} catch (Throwable th) {
BungeeTabListPlus.getInstance().getLogger().log(Level.SEVERE, "Failed to send data", th);
}
}
public static synchronized void report(String testName, Map<String, Object> context, Throwable error, ImmutableBitmapDataProvider... bitmaps) {
try {
Map<String, Object> output = new LinkedHashMap<>();
output.put("testName", testName);
output.put("error", getStackTrace(error));
output.putAll(context);
String[] base64 = new String[bitmaps.length];
for (int i = 0; i < bitmaps.length; ++i) {
ByteArrayDataOutput serialised = ByteStreams.newDataOutput(bitmaps[i].serializedSizeInBytes());
bitmaps[i].serialize(serialised);
base64[i] = Base64.getEncoder().encodeToString(serialised.toByteArray());
}
output.put("bitmaps", base64);
Path dir = Paths.get(OUTPUT_DIR);
if (!Files.exists(dir)) {
Files.createDirectory(dir);
}
Files.write(dir.resolve(testName + "-" + UUID.randomUUID() + ".json"), MAPPER.writeValueAsBytes(output));
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendSWRMessage(Player player, String server, ArrayList<String> messages) {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("Forward");
out.writeUTF(server);
out.writeUTF("SWRMessaging");
ByteArrayOutputStream msgbytes = new ByteArrayOutputStream();
DataOutputStream msgout = new DataOutputStream(msgbytes);
try {
for (String msg: messages) {
msgout.writeUTF(msg);
}
} catch (IOException e) {
e.printStackTrace();
}
out.writeShort(msgbytes.toByteArray().length);
out.write(msgbytes.toByteArray());
player.sendPluginMessage(this, "BungeeCord", out.toByteArray());
}
@EventHandler
public void onJoin(PlayerJoinEvent event) {
final Player player = event.getPlayer();
final Game game = Main.getApi().getFirstWaitingGame();
if (game != null) {
game.joinToGame(event.getPlayer());
} else if (!player.hasPermission("misat11.bw.admin")) {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("Connect");
out.writeUTF(Main.getApi().getHubServerName());
player.sendPluginMessage(Main.getInstance(), "BungeeCord", out.toByteArray());
}
}
@EventHandler
public void handleInventoryClick(InventoryClickEvent e) {
if (!(e.getWhoClicked() instanceof Player)) {
return;
}
if (inventories().contains(e.getInventory()) && e.getCurrentItem() != null && e.getSlot() == e.getRawSlot()) {
e.setCancelled(true);
if (ItemStackBuilder.getMaterialIgnoreVersion(mobConfig.getItemLayout().getItemName(),
mobConfig.getItemLayout().getItemId()) == e.getCurrentItem().getType()) {
MobImpl mob = find(e.getInventory());
if (mob.getServerPosition().containsKey(e.getSlot())) {
if (CloudAPI.getInstance().getServerId().equalsIgnoreCase(mob.getServerPosition().get(e.getSlot()))) {
return;
}
ByteArrayDataOutput byteArrayDataOutput = ByteStreams.newDataOutput();
byteArrayDataOutput.writeUTF("Connect");
byteArrayDataOutput.writeUTF(mob.getServerPosition().get(e.getSlot()));
((Player) e.getWhoClicked()).sendPluginMessage(CloudServer.getInstance().getPlugin(),
"BungeeCord",
byteArrayDataOutput.toByteArray());
}
}
}
}
private static void encodeLength(ByteArrayDataOutput output, int length, Type type) {
if (length < 0) {
output.write(0);
return;
}
if (type == Type.UTF8) {
if (length > 0x7F) {
output.write(((length & 0x7F00) >> 8) | 0x80);
}
output.write(length & 0xFF);
} else { // UTF-16
// TODO(acornwall): Replace output with a little-endian output.
if (length > 0x7FFF) {
int highBytes = ((length & 0x7FFF0000) >> 16) | 0x8000;
output.write(highBytes & 0xFF);
output.write((highBytes & 0xFF00) >> 8);
}
int lowBytes = length & 0xFFFF;
output.write(lowBytes & 0xFF);
output.write((lowBytes & 0xFF00) >> 8);
}
}
@Test
public void testDocWithRepeatingTerms() throws IOException {
MemoryFlamdex fdx = new MemoryFlamdex();
FlamdexDocument doc = new FlamdexDocument();
doc.setIntField("if1", new long[]{1, 1, 1, 3, 3});
fdx.addDocument(doc);
doc.setIntField("if1", new long[]{1, 2, 2, 2, 4});
fdx.addDocument(doc);
fdx.close();
innerTestBadDoc(fdx);
ByteArrayDataOutput out = ByteStreams.newDataOutput();
fdx.write(out);
MemoryFlamdex fdx2 = new MemoryFlamdex();
fdx2.readFields(ByteStreams.newDataInput(out.toByteArray()));
innerTestBadDoc(fdx2);
}
public static void sendPlayerBungeeMessage(Player player, String string) {
new BukkitRunnable() {
public void run() {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("Message");
out.writeUTF(player.getName());
out.writeUTF(string);
Bukkit.getServer().sendPluginMessage(Main.getInstance(), "BungeeCord", out.toByteArray());
}
}.runTaskLater(Main.getInstance(), 30L);
}
private static void internalMove(Player player) {
String server = Main.getConfigurator().config.getString("bungee.server");
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("Connect");
out.writeUTF(server);
player.sendPluginMessage(Main.getInstance(), "BungeeCord", out.toByteArray());
}
@Override
public byte[] serialize(I object) throws IOException {
byte[] serializedObject = delegate.serialize(object);
if(serializedObject.length > compressionThreshold) {
byte[] compressedBytes = lz4Compressor.compress(serializedObject);
ByteArrayDataOutput dataOutput = ByteStreams.newDataOutput(compressedBytes.length+8);
dataOutput.write(MAGIC_HEADER);
dataOutput.writeInt(serializedObject.length);
dataOutput.write(compressedBytes);
return dataOutput.toByteArray();
} else {
return serializedObject;
}
}
@SuppressWarnings("UnstableApiUsage")
private <T extends BinaryTag> T writeRead(final T a, final BinaryTagType<T> type) throws IOException {
final ByteArrayDataOutput output = ByteStreams.newDataOutput();
type.write(a, output);
final ByteArrayDataInput input = ByteStreams.newDataInput(output.toByteArray());
return type.read(input);
}
@Override
public ByteBuffer serialize(I object) throws IOException {
byte[] serializedObject = delegate.serialize(object);
if(serializedObject.length > compressionThreshold) {
byte[] compressedBytes = lz4Compressor.compress(serializedObject);
ByteArrayDataOutput dataOutput = ByteStreams.newDataOutput(compressedBytes.length+8);
dataOutput.write(MAGIC_HEADER);
dataOutput.writeInt(serializedObject.length);
dataOutput.write(compressedBytes);
return ByteBuffer.wrap(dataOutput.toByteArray());
} else {
return ByteBuffer.wrap(serializedObject);
}
}
public void requestPlaceholder(ITabPlayer player, String placeholder) {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("Placeholder");
out.writeUTF(placeholder);
if (player.getVelocityEntity().getCurrentServer().isPresent())
try {
player.getVelocityEntity().getCurrentServer().get().sendPluginMessage(mc, out.toByteArray());
} catch (IllegalStateException e) {
// java.lang.IllegalStateException: Not connected to server!
// this is not the best way to deal with this problem, but i could not find a better one
}
}
@Override
public byte[] serialize(I object) throws IOException {
byte[] serializedObject = delegate.serialize(object);
if(serializedObject.length > compressionThreshold) {
byte[] compressedBytes = lz4Compressor.compress(serializedObject);
ByteArrayDataOutput dataOutput = ByteStreams.newDataOutput(compressedBytes.length+8);
dataOutput.write(MAGIC_HEADER);
dataOutput.writeInt(serializedObject.length);
dataOutput.write(compressedBytes);
return dataOutput.toByteArray();
} else {
return serializedObject;
}
}
@Override
public void sendOutgoingMessage(@NonNull OutgoingMessage outgoingMessage) {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF(outgoingMessage.asEncodedString());
byte[] message = out.toByteArray();
dispatchMessage(message);
}
/***
* Get the bytes from the packet. If the total packet is not yet complete
* (and we're waiting for more to complete the sequence), we return null.
* Otherwise we return the full byte array
*
* @param payload
* one of the chunks
* @return the full byte array or null if not complete
*/
public synchronized byte[] consumeChunk(DataInput input, int payloadLength) throws IOException {
int numChunks = UnsignedBytes.toInt(input.readByte());
if (numChunks == 1) {
byte[] payload = new byte[payloadLength - 1];
input.readFully(payload);
return payload;
}
int chunkIndex = UnsignedBytes.toInt(input.readByte());
byte incomingPacketId = input.readByte();
byte[][] alreadyReceived = chunks.get(incomingPacketId);
if (alreadyReceived == null) {
alreadyReceived = new byte[numChunks][];
chunks.put(incomingPacketId, alreadyReceived);
}
byte[] chunkBytes = new byte[payloadLength - 3];
input.readFully(chunkBytes);
alreadyReceived[chunkIndex] = chunkBytes;
for (byte[] s : alreadyReceived)
if (s == null) return null; // not completed yet
ByteArrayDataOutput fullPacket = ByteStreams.newDataOutput();
for (short i = 0; i < numChunks; i++) {
byte[] chunkPart = alreadyReceived[i];
fullPacket.write(chunkPart);
}
chunks.remove(incomingPacketId);
return fullPacket.toByteArray();
}
public static Slice array(List<Slice> values) {
ByteArrayDataOutput bo = ByteStreams.newDataOutput();
bo.write(String.format("*%d\r\n", values.size()).getBytes());
for (Slice value : values) {
bo.write(value.data());
}
return new Slice(bo.toByteArray());
}
@Override
public void write(ByteArrayDataOutput out, int protocolId) {
writeVarInt(FishingBot.getInstance().getServerProtocol(), out);
writeString(serverName + "\0FML\0", out);
out.writeShort(serverPort);
writeVarInt(2, out); //next State = 2 -> LOGIN
}
public final Packet makePacket()
{
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeByte(getPacketId());
write(out);
return PacketDispatcher.getPacket(CHANNEL, out.toByteArray());
}
@Override
public void read(ByteArrayDataInputWrapper in, NetworkHandler networkHandler, int length, int protocolId) {
this.windowId = in.readByte();
this.slotId = in.readShort();
byte[] bytes = new byte[in.getAvailable()];
in.readBytes(bytes);
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.write(bytes.clone());
this.slotData = out;
FishingBot.getInstance().getEventManager().callEvent(new UpdateSlotEvent(windowId, slotId, slotData));
}
public void sendBungeeMessage(Player player, String message) {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("Message");
out.writeUTF(player.getName());
out.writeUTF(message);
player.sendPluginMessage(BedwarsRel.getInstance(), "BungeeCord", out.toByteArray());
}
@Test
public void testDeserializeInvalidTagKey() throws TagContextDeserializationException {
ByteArrayDataOutput output = ByteStreams.newDataOutput();
output.write(BinarySerializationUtils.VERSION_ID);
// Encode an invalid tag key and a valid tag value:
encodeTagToOutput("\2key", "value", output);
final byte[] bytes = output.toByteArray();
thrown.expect(TagContextDeserializationException.class);
thrown.expectMessage("Invalid tag key: \2key");
serializer.fromByteArray(bytes);
}
@Override
public void write(ByteArrayDataOutput out, int protocolId) {
out.writeDouble(getX());
out.writeDouble(getY());
out.writeDouble(getZ());
out.writeBoolean(isOnGround());
}
@Override
public byte[] toByteArray(boolean shrink) throws IOException {
ByteArrayDataOutput output = ByteStreams.newDataOutput();
for (Chunk chunk : chunks) {
output.write(chunk.toByteArray(shrink));
}
return output.toByteArray();
}
@Override
public void write(ByteArrayDataOutput out, int protocolId) {
switch (protocolId) {
case ProtocolConstants.MINECRAFT_1_8: {
out.writeLong(-1); //Position
out.writeByte(255); //Face
out.write(FishingBot.getInstance().getPlayer().getSlotData().toByteArray()); //Slot
out.writeByte(0); //Cursor X
out.writeByte(0); //Cursor Y
out.writeByte(0); //Cursor Z
new Thread(() -> {
try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); }
networkHandler.sendPacket(new PacketOutArmAnimation());
}).start();
break;
}
case ProtocolConstants.MINECRAFT_1_13_2:
case ProtocolConstants.MINECRAFT_1_13_1:
case ProtocolConstants.MINECRAFT_1_13:
case ProtocolConstants.MINECRAFT_1_12_2:
case ProtocolConstants.MINECRAFT_1_12_1:
case ProtocolConstants.MINECRAFT_1_12:
case ProtocolConstants.MINECRAFT_1_11_1:
case ProtocolConstants.MINECRAFT_1_11:
case ProtocolConstants.MINECRAFT_1_10:
case ProtocolConstants.MINECRAFT_1_9_4:
case ProtocolConstants.MINECRAFT_1_9_2:
case ProtocolConstants.MINECRAFT_1_9_1:
case ProtocolConstants.MINECRAFT_1_9:
case ProtocolConstants.MINECRAFT_1_14:
case ProtocolConstants.MINECRAFT_1_14_1:
case ProtocolConstants.MINECRAFT_1_14_2:
case ProtocolConstants.MINECRAFT_1_14_3:
case ProtocolConstants.MINECRAFT_1_14_4:
default: {
out.writeByte(0); //main hand
break;
}
}
}
private void writeTypeAnnotation(TypeAnnotations attribute) {
output.writeShort(pool.utf8(attribute.kind().signature()));
ByteArrayDataOutput tmp = ByteStreams.newDataOutput();
tmp.writeShort(attribute.annotations().size());
for (TypeAnnotationInfo annotation : attribute.annotations()) {
new AnnotationWriter(pool, tmp).writeTypeAnnotation(annotation);
}
byte[] data = tmp.toByteArray();
output.writeInt(data.length);
output.write(data);
}
public void sendBungeeMsg(Player player, String subchannel, String message) {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF(subchannel);
if (!message.equalsIgnoreCase("none")) {
out.writeUTF(message);
}
player.sendPluginMessage(this, "BungeeCord", out.toByteArray());
}
public void sendPluginMessage(PluginMessageRecipient player, ChannelMessage message) {
if (player != null) {
ByteArrayDataOutput dataOutput = ByteStreams.newDataOutput();
message.writeTo(dataOutput);
NamespaceKey channel = new NamespaceKey(plugin.getName(), message.getChannelName());
player.sendPluginMessage(plugin, channel.getCombinedName(), dataOutput.toByteArray());
}
}