下面列出了com.google.common.io.ByteStreams#newDataOutput ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Send a plugin message to the Bungee when a player logged into AuthMe on subchannel authMeLogin with the name and UUID
* @param event AuthMe's LoginEvent
*/
@EventHandler
public void onAuthMeLogin(LoginEvent event) {
if(plugin.isEnabled()) {
long sendDelay = plugin.getPackManager().getAssignment(event.getPlayer().getWorld().getName()).getSendDelay();
if (sendDelay < 0) {
sendDelay = plugin.getPackManager().getGlobalAssignment().getSendDelay();
}
if (sendDelay > 0) {
plugin.getServer().getScheduler().runTaskLater(plugin, () -> plugin.getPackManager().applyPack(event.getPlayer().getUniqueId(), event.getPlayer().getWorld().getName()), sendDelay);
} else {
plugin.getPackManager().applyPack(event.getPlayer().getUniqueId(), event.getPlayer().getWorld().getName());
}
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("authMeLogin");
out.writeUTF(event.getPlayer().getName());
out.writeUTF(event.getPlayer().getUniqueId().toString());
event.getPlayer().sendPluginMessage(plugin, "rp:plugin", out.toByteArray());
}
}
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);
}
}
@SneakyThrows
public static byte[] encode(PlayerData dat) {
ByteArrayDataOutput output = ByteStreams.newDataOutput();
output.writeLong(dat.getUuid().getMostSignificantBits());
output.writeLong(dat.getUuid().getLeastSignificantBits());
output.writeDouble(dat.getHealth());
output.writeInt(dat.getFood());
output.writeInt(dat.getHand());
output.writeInt(dat.getExp());
write(output, dat.getInventory());
write(output, dat.getArmor());
write(output, dat.getChest());
write(output, dat.getEffect());
byte[] uncompressed = output.toByteArray();
output = ByteStreams.newDataOutput();
VarInt.writeUnsignedVarInt(output, uncompressed.length);
byte[] compressed = LZ4.compress(uncompressed);
if (Config.DEBUG) {
PluginMain.getPlugin().log(String.format("PlayerDataHelper.encode LZ4 compressor %s -> %s", uncompressed.length, compressed.length));
}
VarInt.writeUnsignedVarInt(output, compressed.length);
output.write(compressed);
return output.toByteArray();
}
@Override
public void sendOutgoingMessage(@NonNull OutgoingMessage outgoingMessage) {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF(outgoingMessage.asEncodedString());
byte[] data = out.toByteArray();
new BukkitRunnable() {
@Override
public void run() {
Collection<? extends Player> players = PluginMessageMessenger.this.plugin.getBootstrap().getServer().getOnlinePlayers();
Player p = Iterables.getFirst(players, null);
if (p == null) {
return;
}
p.sendPluginMessage(PluginMessageMessenger.this.plugin.getBootstrap(), CHANNEL, data);
cancel();
}
}.runTaskTimer(this.plugin.getBootstrap(), 1L, 100L);
}
private void sendToChannel(MessageAgent agent, Player player) {
ensureSetup();
// create a new data output stream for the message
ByteArrayDataOutput out = ByteStreams.newDataOutput();
// write the channel
out.writeUTF(agent.getSubChannel());
// append the agents data
agent.appendPayload(out);
byte[] buf = out.toByteArray();
player.sendPluginMessage(this.plugin, CHANNEL, buf);
// if the agent is also a MessageCallback, register it
if (agent instanceof MessageCallback) {
MessageCallback callback = (MessageCallback) agent;
registerCallback(callback);
}
}
/**
* For hbase 0.98
*
* @return serialized byte array
*/
@Override
public byte[] toByteArray() {
ByteArrayDataOutput byteArrayDataOutput = ByteStreams.newDataOutput();
try {
this.write(byteArrayDataOutput);
return byteArrayDataOutput.toByteArray();
} catch (IOException e) {
LOG.error("Failed to serialize due to: " + e.getMessage(), e);
throw new RuntimeException(e);
}
}
@Test
public void testSerialization() throws Exception {
final Broker broker = new Broker("127.0.0.1", 9092, 1);
final Partition partition = new Partition("topic_name", 0, broker);
final KafkaInputSplit split = new KafkaInputSplit(partition, 0, 10l, false);
final ByteArrayDataOutput out = ByteStreams.newDataOutput();
split.write(out);
final KafkaInputSplit actual = new KafkaInputSplit();
actual.readFields(ByteStreams.newDataInput(out.toByteArray()));
assertEquals(split, actual);
}
private void assertSerializedEdit(TransactionEdit originalEdit) throws IOException {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
originalEdit.write(out);
TransactionEdit decodedEdit = new TransactionEdit();
DataInput in = ByteStreams.newDataInput(out.toByteArray());
decodedEdit.readFields(in);
Assert.assertEquals(originalEdit, decodedEdit);
}
@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);
}
private void parseHeadline(LittleEndianDataInputStream input) throws IOException {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
byte c;
while((c = input.readByte()) != '\n') {
out.writeByte(c);
}
String[] headline = new String(out.toByteArray(), StandardCharsets.UTF_8).split(" ");
this.numberOfVectors = Integer.parseInt(headline[0]);
this.dimensions = Integer.parseInt(headline[1]);
}
public static AggregateProtos.AggregateResult toPBAggregateResult(AggregateResult result) throws IOException {
ByteArrayDataOutput output = ByteStreams.newDataOutput();
result.write(output);
return AggregateProtos.AggregateResult.newBuilder()
.setByteArray(ByteString.copyFrom(output.toByteArray()))
.build();
}
@VisibleForTesting
Slice consumeSlice(long len) throws ParseErrorException {
ByteArrayDataOutput bo = ByteStreams.newDataOutput();
for (long i = 0; i < len; i++) {
try {
bo.write(consumeByte());
} catch (EOFException e) {
throw new ParseErrorException();
}
}
return new Slice(bo.toByteArray());
}
public static HiveReaderProto.SerializedInputSplit serialize(InputSplit split) {
final ByteArrayDataOutput output = ByteStreams.newDataOutput();
try {
split.write(output);
} catch (IOException e) {
throw UserException.dataReadError(e).message(e.getMessage()).build(logger);
}
return HiveReaderProto.SerializedInputSplit.newBuilder()
.setInputSplitClass(split.getClass().getName())
.setInputSplit(com.google.protobuf.ByteString.copyFrom(output.toByteArray())).build();
}
@Test
public void testDeserializeDuplicateKeys() throws TagContextDeserializationException {
ByteArrayDataOutput output = ByteStreams.newDataOutput();
output.write(BinarySerializationUtils.VERSION_ID);
encodeTagToOutput("Key1", "Value1", output);
encodeTagToOutput("Key1", "Value2", output);
TagContext expected =
tagger.emptyBuilder().put(TagKey.create("Key1"), TagValue.create("Value2")).build();
assertThat(serializer.fromByteArray(output.toByteArray())).isEqualTo(expected);
}
public void sendPluginMessage(PluginMessageRecipient sender, ChannelMessage message) {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
message.writeTo(out);
NamespaceKey channel = new NamespaceKey(getName(), message.getChannelName());
sender.sendPluginMessage(this, channel.getCombinedName(), out.toByteArray());
}
@EventHandler
public void handleRightClick(PlayerInteractEntityEvent e) {
MobImpl mobImpl = CollectionWrapper.filter(mobs.values(), new Acceptable<MobImpl>() {
@Override
public boolean isAccepted(MobImpl value) {
return value.getEntity().getUniqueId().equals(e.getRightClicked().getUniqueId());
}
});
if (mobImpl != null) {
e.setCancelled(true);
if (!CloudAPI.getInstance().getServerGroupData(mobImpl.getMob().getTargetGroup()).isMaintenance()) {
if (mobImpl.getMob().getAutoJoin() != null && mobImpl.getMob().getAutoJoin()) {
ByteArrayDataOutput byteArrayDataOutput = ByteStreams.newDataOutput();
byteArrayDataOutput.writeUTF("Connect");
List<ServerInfo> serverInfos = getServers(mobImpl.getMob().getTargetGroup());
for (ServerInfo serverInfo : serverInfos) {
if (serverInfo.getOnlineCount() < serverInfo.getMaxPlayers() && serverInfo.getServerState()
.equals(ServerState.LOBBY)) {
byteArrayDataOutput.writeUTF(serverInfo.getServiceId().getServerId());
e.getPlayer().sendPluginMessage(CloudServer.getInstance().getPlugin(),
"BungeeCord",
byteArrayDataOutput.toByteArray());
return;
}
}
} else {
e.getPlayer().openInventory(mobImpl.getInventory());
}
} else {
e.getPlayer().sendMessage(ChatColor.translateAlternateColorCodes('&',
CloudAPI.getInstance()
.getCloudNetwork()
.getMessages()
.getString("mob-selector-maintenance-message")));
}
}
}
@Override
public byte[] toByteArray(boolean shrink) throws IOException {
ByteArrayDataOutput output = ByteStreams.newDataOutput();
for (Chunk chunk : chunks) {
output.write(chunk.toByteArray(shrink));
}
return output.toByteArray();
}
@SuppressWarnings("deprecation")
@Test
public void testPartitionEventSerialization() throws IOException {
PartitionedEvent partitionedEvent = MockSampleMetadataFactory.createPartitionedEventGroupedByName("sampleStream", System.currentTimeMillis());
;
PartitionedEventSerializerImpl serializer = new PartitionedEventSerializerImpl(MockSampleMetadataFactory::createSampleStreamDefinition);
ByteArrayDataOutput dataOutput1 = ByteStreams.newDataOutput();
serializer.serialize(partitionedEvent, dataOutput1);
byte[] serializedBytes = dataOutput1.toByteArray();
PartitionedEvent deserializedEvent = serializer.deserialize(ByteStreams.newDataInput(serializedBytes));
Assert.assertEquals(partitionedEvent, deserializedEvent);
PartitionedEventSerializerImpl compressSerializer = new PartitionedEventSerializerImpl(MockSampleMetadataFactory::createSampleStreamDefinition, true);
byte[] serializedBytesCompressed = compressSerializer.serialize(partitionedEvent);
PartitionedEvent deserializedEventCompressed = compressSerializer.deserialize(serializedBytesCompressed);
Assert.assertEquals(partitionedEvent, deserializedEventCompressed);
PartitionedEventDigestSerializer serializer2 = new PartitionedEventDigestSerializer(MockSampleMetadataFactory::createSampleStreamDefinition);
ByteArrayDataOutput dataOutput2 = ByteStreams.newDataOutput();
serializer2.serialize(partitionedEvent, dataOutput2);
byte[] serializedBytes2 = dataOutput2.toByteArray();
ByteArrayDataInput dataInput2 = ByteStreams.newDataInput(serializedBytes2);
PartitionedEvent deserializedEvent2 = serializer2.deserialize(dataInput2);
Assert.assertEquals(partitionedEvent, deserializedEvent2);
byte[] javaSerialization = new DefaultSerializationDelegate().serialize(partitionedEvent);
Kryo kryo = new DefaultKryoFactory.KryoSerializableDefault();
Output output = new Output(10000);
kryo.writeClassAndObject(output, partitionedEvent);
byte[] kryoBytes = output.toBytes();
Input input = new Input(kryoBytes);
PartitionedEvent kryoDeserializedEvent = (PartitionedEvent) kryo.readClassAndObject(input);
Assert.assertEquals(partitionedEvent, kryoDeserializedEvent);
LOG.info("\nCached Stream:{}\nCompressed Cached Stream :{}\nCached Stream + Cached Partition: {}\nJava Native: {}\nKryo: {}\nKryo + Cached Stream: {}\nKryo + Cached Stream + Cached Partition: {}", serializedBytes.length, serializedBytesCompressed.length, serializedBytes2.length, javaSerialization.length, kryoBytes.length, kryoSerialize(serializedBytes).length, kryoSerialize(serializedBytes2).length);
}
public void teleport(Player player) {
if (this.server != null) {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("Connect");
out.writeUTF(this.server);
player.sendPluginMessage(HubBasics.getInstance(), "BungeeCord", out.toByteArray());
} else {
player.teleport(this.toBukkitLocation());
}
}
/**
* TODO: Currently still use older serialization method from hbase-0.94, need to migrate into ProtoBuff
* based
*
* @return
* @throws IOException
*/
@Override
public byte[] toByteArray() throws IOException {
ByteArrayDataOutput byteArrayDataOutput = ByteStreams.newDataOutput();
this.comparator.write(byteArrayDataOutput);
return byteArrayDataOutput.toByteArray();
}