类com.google.common.io.ByteArrayDataOutput源码实例Demo

下面列出了怎么用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();
}
 
源代码2 项目: HubBasics   文件: LobbyCommand.java
@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")));
    }
}
 
源代码3 项目: BungeeTabListPlus   文件: RedisPlayerManager.java
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);
    }
}
 
源代码4 项目: RoaringBitmap   文件: Reporter.java
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();
  }
}
 
源代码5 项目: SkyWarsReloaded   文件: SkyWarsReloaded.java
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());
}
 
源代码6 项目: BedWars   文件: PlayerListener.java
@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());
    }
}
 
源代码7 项目: CloudNet   文件: MobSelector.java
@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());
            }
        }
    }
}
 
源代码8 项目: android-chunk-utils   文件: ResourceString.java
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);
  }
}
 
源代码9 项目: imhotep   文件: TestMemoryFlamdex.java
@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);
}
 
源代码10 项目: BedWars   文件: BungeeUtils.java
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);
}
 
源代码11 项目: BedWars   文件: BungeeUtils.java
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());
}
 
源代码12 项目: elasticactors   文件: CompressingSerializer.java
@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;
    }
}
 
源代码13 项目: adventure   文件: ReadWriteTest.java
@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);
}
 
源代码14 项目: elasticactors   文件: CompressingSerializer.java
@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);
    }
}
 
源代码15 项目: TAB   文件: PluginMessenger.java
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
		}
		
}
 
源代码16 项目: elasticactors   文件: CompressingSerializer.java
@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;
    }
}
 
源代码17 项目: LuckPerms   文件: PluginMessageMessenger.java
@Override
public void sendOutgoingMessage(@NonNull OutgoingMessage outgoingMessage) {
    ByteArrayDataOutput out = ByteStreams.newDataOutput();
    out.writeUTF(outgoingMessage.asEncodedString());

    byte[] message = out.toByteArray();
    dispatchMessage(message);
}
 
源代码18 项目: OpenModsLib   文件: PacketChunker.java
/***
 * 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();
}
 
源代码19 项目: redis-mock   文件: Response.java
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());
}
 
源代码20 项目: FishingBot   文件: PacketOutHandshake.java
@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
}
 
源代码21 项目: ExtraCells1   文件: AbstractPacket.java
public final Packet makePacket()
{
	ByteArrayDataOutput out = ByteStreams.newDataOutput();
	out.writeByte(getPacketId());
	write(out);
	return PacketDispatcher.getPacket(CHANNEL, out.toByteArray());
}
 
源代码22 项目: FishingBot   文件: PacketInSetSlot.java
@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));
}
 
源代码23 项目: BedwarsRel   文件: BungeeGameCycle.java
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);
}
 
源代码25 项目: FishingBot   文件: PacketOutPosition.java
@Override
public void write(ByteArrayDataOutput out, int protocolId) {
    out.writeDouble(getX());
    out.writeDouble(getY());
    out.writeDouble(getZ());
    out.writeBoolean(isOnGround());
}
 
源代码26 项目: apkfile   文件: ResourceFile.java
@Override
public byte[] toByteArray(boolean shrink) throws IOException {
    ByteArrayDataOutput output = ByteStreams.newDataOutput();
    for (Chunk chunk : chunks) {
        output.write(chunk.toByteArray(shrink));
    }
    return output.toByteArray();
}
 
源代码27 项目: FishingBot   文件: PacketOutUseItem.java
@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;
        }
    }
}
 
源代码28 项目: turbine   文件: AttributeWriter.java
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);
}
 
源代码29 项目: SkyWarsReloaded   文件: SkyWarsReloaded.java
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());
}
 
源代码30 项目: FastLogin   文件: BungeeManager.java
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());
    }
}