Java Code Examples for com.google.common.io.ByteStreams#newDataOutput()

The following examples show how to use com.google.common.io.ByteStreams#newDataOutput() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BungeeCordImpl.java    From helper with MIT License 6 votes vote down vote up
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);
    }
}
 
Example 2
Source File: AuthmeLoginListener.java    From ResourcepacksPlugins with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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());
    }
}
 
Example 3
Source File: RedisPlayerManager.java    From BungeeTabListPlus with GNU General Public License v3.0 6 votes vote down vote up
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);
    }
}
 
Example 4
Source File: PlayerDataHelper.java    From PlayerSQL with GNU General Public License v2.0 6 votes vote down vote up
@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();
}
 
Example 5
Source File: PluginMessageMessenger.java    From LuckPerms with MIT License 6 votes vote down vote up
@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);
}
 
Example 6
Source File: RedisCommandParser.java    From redis-mock with MIT License 5 votes vote down vote up
@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());
}
 
Example 7
Source File: HLocation.java    From HubBasics with GNU Lesser General Public License v3.0 5 votes vote down vote up
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());
    }
}
 
Example 8
Source File: PartitionedEventSerializerTest.java    From eagle with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 9
Source File: ResourceFile.java    From android-chunk-utils with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] toByteArray(boolean shrink) throws IOException {
  ByteArrayDataOutput output = ByteStreams.newDataOutput();
  for (Chunk chunk : chunks) {
    output.write(chunk.toByteArray(shrink));
  }
  return output.toByteArray();
}
 
Example 10
Source File: MobSelector.java    From CloudNet with Apache License 2.0 5 votes vote down vote up
@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")));
        }
    }
}
 
Example 11
Source File: ChangeSkinBukkit.java    From ChangeSkin with MIT License 5 votes vote down vote up
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());
}
 
Example 12
Source File: TagContextDeserializationTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 13
Source File: HiveMetadataUtils.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 14
Source File: TypedByteArrayComparator.java    From eagle with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 15
Source File: ProtoBufConverter.java    From eagle with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 16
Source File: VectorIterator.java    From Indra with MIT License 5 votes vote down vote up
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]);
}
 
Example 17
Source File: TagContextDeserializationTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 18
Source File: TransactionEditTest.java    From phoenix-tephra with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 19
Source File: KafkaInputSplitTest.java    From kangaroo with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 20
Source File: RowValueFilter.java    From eagle with Apache License 2.0 3 votes vote down vote up
/**
 * 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();
}