Example usage for com.google.common.io ByteArrayDataOutput toByteArray

List of usage examples for com.google.common.io ByteArrayDataOutput toByteArray

Introduction

In this page you can find the example usage for com.google.common.io ByteArrayDataOutput toByteArray.

Prototype

byte[] toByteArray();

Source Link

Document

Returns the contents that have been written to this instance, as a byte array.

Usage

From source file:io.github.leonardosnt.bungeechannelapi.BungeeChannelApi.java

/**
 * Send a custom plugin message to specific player.
 *
 * @param playerName the name of the player to send to.
 * @param channelName Subchannel for plugin usage.
 * @param data data to send.//from  ww  w  .  j a v a 2s  .c  om
 * @throws IllegalArgumentException if there is no players online.
 */
public void forwardToPlayer(String playerName, String channelName, byte[] data) {
    Player player = getFirstPlayer();

    ByteArrayDataOutput output = ByteStreams.newDataOutput();
    output.writeUTF("ForwardToPlayer");
    output.writeUTF(playerName);
    output.writeUTF(channelName);
    output.writeShort(data.length);
    output.write(data);
    player.sendPluginMessage(this.plugin, "BungeeCord", output.toByteArray());
}

From source file:co.cask.cdap.data2.transaction.stream.AbstractStreamFileConsumer.java

/**
 * Try to claim a stream event offset./*from w w  w .  j  av  a  2  s.c  om*/
 *
 * @return The row key for writing to the state table if successfully claimed or {@code null} if not claimed.
 */
private byte[] claimEntry(StreamFileOffset offset, byte[] claimedStateContent) throws IOException {
    ByteArrayDataOutput out = ByteStreams.newDataOutput(50);
    out.writeLong(consumerConfig.getGroupId());
    StreamUtils.encodeOffset(out, offset);
    byte[] row = out.toByteArray();

    SortedMap<byte[], byte[]> rowStates = getInitRowStates(row);

    // See if the entry should be ignored. If it is in the rowStates with null value, then it should be ignored.
    byte[] rowState = rowStates.get(row);
    if (rowStates.containsKey(row) && rowState == null) {
        return null;
    }

    // Only need to claim entry if FIFO and group size > 1
    if (consumerConfig.getDequeueStrategy() == DequeueStrategy.FIFO && consumerConfig.getGroupSize() > 1) {
        return claimFifoEntry(row, claimedStateContent, rowState) ? row : null;
    }

    // For Hash, RR and FIFO with group size == 1, no need to claim and check,
    // as it's already handled by the readFilter
    return row;
}

From source file:org.haiku.pkg.AttributeIterator.java

/**
 * <p>This method will return the next {@link Attribute}.  If there is not another value to return then
 * this method will return null.  It will throw an instance of @{link HpkException} in any situation in which
 * it is not able to parse the data or chunks such that it is not able to read the next attribute.</p>
 *//*www  .ja v  a  2 s.co m*/

public Attribute next() throws HpkException {

    Attribute result = null;

    // first, the LEB128 has to be read in which is the 'tag' defining what sort of attribute this is that
    // we are dealing with.

    BigInteger tag = getNextTag();

    // if we encounter 0 tag then we know that we have finished the list.

    if (0 != tag.signum()) {

        int encoding = deriveAttributeTagEncoding(tag);
        int id = deriveAttributeTagId(tag);

        if (id <= 0 || id >= AttributeId.values().length) {
            throw new HpkException("illegal id; " + Integer.toString(id));
        }
        AttributeId attributeId = AttributeId.values()[id];

        switch (deriveAttributeTagType(tag)) {

        case ATTRIBUTE_TYPE_INVALID:
            throw new HpkException("an invalid attribute tag type has been encountered");

        case ATTRIBUTE_TYPE_INT: {
            ensureValidEncodingForInt(encoding);
            byte[] buffer = new byte[encoding + 1];
            context.getHeapReader().readHeap(buffer, 0, new HeapCoordinates(offset, encoding + 1));
            offset += encoding + 1;
            result = new IntAttribute(attributeId, new BigInteger(buffer));
        }
            break;

        case ATTRIBUTE_TYPE_UINT: {
            ensureValidEncodingForInt(encoding);
            byte[] buffer = new byte[encoding + 1];
            context.getHeapReader().readHeap(buffer, 0, new HeapCoordinates(offset, encoding + 1));
            offset += encoding + 1;
            result = new IntAttribute(attributeId, new BigInteger(1, buffer));
        }
            break;

        case ATTRIBUTE_TYPE_STRING: {
            switch (encoding) {

            case ATTRIBUTE_ENCODING_STRING_INLINE: {
                ByteArrayDataOutput assembly = ByteStreams.newDataOutput();

                while (null == result) {
                    int b = context.getHeapReader().readHeap(offset);
                    offset++;

                    if (0 != b) {
                        assembly.write(b);
                    } else {
                        result = new StringInlineAttribute(attributeId,
                                new String(assembly.toByteArray(), Charsets.UTF_8));
                    }
                }
            }
                break;

            case ATTRIBUTE_ENCODING_STRING_TABLE: {
                BigInteger index = readUnsignedLeb128();

                if (index.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) > 0) {
                    throw new IllegalStateException("the string table index is preposterously large");
                }

                result = new StringTableRefAttribute(attributeId, index.intValue());
            }
                break;

            default:
                throw new HpkException("unknown string encoding; " + encoding);
            }
        }
            break;

        case ATTRIBUTE_TYPE_RAW: {
            switch (encoding) {
            case ATTRIBUTE_ENCODING_RAW_INLINE: {
                BigInteger length = readUnsignedLeb128();

                if (length.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) > 0) {
                    throw new HpkException("the length of the inline data is too large");
                }

                byte[] buffer = new byte[length.intValue()];
                context.getHeapReader().readHeap(buffer, 0, new HeapCoordinates(offset, length.intValue()));
                offset += length.intValue();

                result = new RawInlineAttribute(attributeId, buffer);
            }
                break;

            case ATTRIBUTE_ENCODING_RAW_HEAP: {
                BigInteger rawLength = readUnsignedLeb128();
                BigInteger rawOffset = readUnsignedLeb128();

                if (rawLength.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) > 0) {
                    throw new HpkException("the length of the heap data is too large");
                }

                if (rawOffset.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) > 0) {
                    throw new HpkException("the offset of the heap data is too large");
                }

                result = new RawHeapAttribute(attributeId,
                        new HeapCoordinates(rawOffset.longValue(), rawLength.longValue()));
            }
                break;

            default:
                throw new HpkException("unknown raw encoding; " + encoding);
            }
        }
            break;

        default:
            throw new HpkException("unable to read the tag type; " + deriveAttributeTagType(tag));

        }

        // each attribute id has a type associated with it; now check that the attribute matches
        // its intended type.

        if (result.getAttributeId().getAttributeType() != result.getAttributeType()) {
            throw new HpkException(
                    String.format("mismatch in attribute type for id %s; expecting %s, but got %s",
                            result.getAttributeId().getName(), result.getAttributeId().getAttributeType(),
                            result.getAttributeType()));
        }

        // possibly there are child attributes after this attribute; if this is the
        // case then open-up a new iterator to work across those and load them in.

        if (deriveAttributeTagHasChildAttributes(tag)) {

            AttributeIterator childAttributeIterator = new AttributeIterator(context, offset);

            while (childAttributeIterator.hasNext()) {
                result.addChildAttribute(childAttributeIterator.next());
            }

            offset = childAttributeIterator.getOffset();

        }

        nextTag = null;
    }

    return result;
}

From source file:io.github.aritzhack.aritzh.bds.BDSCompound.java

private byte[] getUncompressedBytes() {
    ByteArrayDataOutput output = ByteStreams.newDataOutput();
    output.writeByte(this.getType().toByte());
    output.writeUTF(this.name);
    for (BDS bds : this.items) {
        if (bds instanceof BDSCompound) {
            output.write(((BDSCompound) bds).getUncompressedBytes());
        } else//from w  ww  .  j ava2  s  . co m
            output.write(bds.getBytes());
    }
    output.write(new BDSCompEnd().getBytes());
    return output.toByteArray();
}

From source file:de.emc.plugin.Plugin.java

@Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
    if (cmd.getName().equalsIgnoreCase("gbc")) {
        if (args.length < 2) {
            return false;
        }/*from w  ww .java2  s .  c om*/
        ByteArrayDataOutput out = ByteStreams.newDataOutput();
        out.writeUTF("Broadcast");
        out.writeUTF(args[0]);
        out.writeUTF(Store.getString("server"));
        String msg = "";
        for (int i = 1; i < args.length; i++) {
            msg = msg + " " + args[i];
        }
        msg = ChatColor.translateAlternateColorCodes('&', msg);
        out.writeUTF(msg);
        this.getServer().sendPluginMessage(this, "BungeeCord", out.toByteArray());
        sender.sendMessage(Store.getString("cmdexecuted"));
        return true;
    }
    return false;
}

From source file:com.android.tools.perflib.heap.SnapshotBuilder.java

public Snapshot build() {
    HprofStringBuilder strings = new HprofStringBuilder(0);
    List<HprofRecord> records = new ArrayList<HprofRecord>();
    List<HprofDumpRecord> dump = new ArrayList<HprofDumpRecord>();
    byte objType = HprofType.TYPE_OBJECT;

    // Roots go in the default heap. Add those first.
    for (Integer id : mRoots) {
        dump.add(new HprofRootUnknown(id));
    }//ww w.j a v  a2  s .com

    // Everything else goes in "testHeap" with id 13.
    dump.add(new HprofHeapDumpInfo(13, strings.get("testHeap")));

    // The SoftReference class
    records.add(new HprofLoadClass(0, 0, SOFT_REFERENCE_ID, 0, strings.get("java.lang.ref.Reference")));
    dump.add(new HprofClassDump(SOFT_REFERENCE_ID, 0, 0, 0, 0, 0, 0, 0, 0, new HprofConstant[0],
            new HprofStaticField[0],
            new HprofInstanceField[] { new HprofInstanceField(strings.get("referent"), objType) }));

    // The SoftAndHardReference class
    records.add(new HprofLoadClass(0, 1, SOFT_AND_HARD_REFERENCE_ID, 0, strings.get("SoftAndHardReference")));
    dump.add(new HprofClassDump(SOFT_AND_HARD_REFERENCE_ID, 0, 0, 0, 0, 0, 0, 0, 0, new HprofConstant[0],
            new HprofStaticField[0],
            new HprofInstanceField[] { new HprofInstanceField(strings.get("referent"), objType),
                    new HprofInstanceField(strings.get("hardReference"), objType) }));

    // Regular nodes and their classes
    for (int i = 1; i <= mNumNodes; i++) {
        HprofInstanceField[] fields = new HprofInstanceField[mReferences[i].size()];
        ByteArrayDataOutput values = ByteStreams.newDataOutput();
        for (int j = 0; j < fields.length; j++) {
            fields[j] = new HprofInstanceField(strings.get("field" + j), objType);
            values.writeShort(mReferences[i].get(j));
        }

        // Use same name classes on different loaders to extend test coverage
        records.add(new HprofLoadClass(0, 0, 100 + i, 0, strings.get("Class" + (i / 2))));
        dump.add(new HprofClassDump(100 + i, 0, 0, i % 2, 0, 0, 0, 0, i, new HprofConstant[0],
                new HprofStaticField[0], fields));

        dump.add(new HprofInstanceDump(i, 0, 100 + i, values.toByteArray()));
    }

    // Soft reference nodes.
    for (int i = mNumNodes + 1; i <= mNumNodes + mNumSoftNodes; ++i) {
        assertEquals(1, mReferences[i].size());
        ByteArrayDataOutput values = ByteStreams.newDataOutput();
        values.writeShort(mReferences[i].get(0));
        dump.add(new HprofInstanceDump(i, 0, SOFT_REFERENCE_ID, values.toByteArray()));
    }

    // Soft and hard reference nodes.
    for (int i = mNumNodes + mNumSoftNodes + 1; i <= mMaxTotalNodes; ++i) {
        assertEquals(2, mReferences[i].size());
        ByteArrayDataOutput values = ByteStreams.newDataOutput();
        values.writeShort(mReferences[i].get(0));
        values.writeShort(mReferences[i].get(1));
        dump.add(new HprofInstanceDump(i, 0, SOFT_AND_HARD_REFERENCE_ID, values.toByteArray()));
    }

    records.add(new HprofHeapDump(0, dump.toArray(new HprofDumpRecord[0])));

    // TODO: Should perflib handle the case where strings are referred to
    // before they are defined?
    List<HprofRecord> actualRecords = new ArrayList<HprofRecord>();
    actualRecords.addAll(strings.getStringRecords());
    actualRecords.addAll(records);

    Snapshot snapshot = null;
    try {
        Hprof hprof = new Hprof("JAVA PROFILE 1.0.3", 2, new Date(), actualRecords);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        hprof.write(os);
        InMemoryBuffer buffer = new InMemoryBuffer(os.toByteArray());
        snapshot = Snapshot.createSnapshot(buffer);
    } catch (IOException e) {
        fail("IOException when writing to byte output stream: " + e);
    }

    // TODO: Should the parser be setting isSoftReference, not the builder?
    for (Heap heap : snapshot.getHeaps()) {
        ClassObj softClass = heap.getClass(SOFT_REFERENCE_ID);
        if (softClass != null) {
            softClass.setIsSoftReference();
        }

        ClassObj softAndHardClass = heap.getClass(SOFT_AND_HARD_REFERENCE_ID);
        if (softAndHardClass != null) {
            softAndHardClass.setIsSoftReference();
        }
    }
    return snapshot;
}

From source file:org.apache.hadoop.hdfs.client.impl.BlockReaderFactory.java

private BlockReader tryToCreateExternalBlockReader() {
    List<Class<? extends ReplicaAccessorBuilder>> clses = conf.getReplicaAccessorBuilderClasses();
    for (Class<? extends ReplicaAccessorBuilder> cls : clses) {
        try {/*from   w ww.  j  a va 2 s.  c o  m*/
            ByteArrayDataOutput bado = ByteStreams.newDataOutput();
            token.write(bado);
            byte tokenBytes[] = bado.toByteArray();

            Constructor<? extends ReplicaAccessorBuilder> ctor = cls.getConstructor();
            ReplicaAccessorBuilder builder = ctor.newInstance();
            long visibleLength = startOffset + length;
            ReplicaAccessor accessor = builder.setAllowShortCircuitReads(allowShortCircuitLocalReads)
                    .setBlock(block.getBlockId(), block.getBlockPoolId())
                    .setGenerationStamp(block.getGenerationStamp()).setBlockAccessToken(tokenBytes)
                    .setClientName(clientName).setConfiguration(configuration).setFileName(fileName)
                    .setVerifyChecksum(verifyChecksum).setVisibleLength(visibleLength).build();
            if (accessor == null) {
                LOG.trace("{}: No ReplicaAccessor created by {}", this, cls.getName());
            } else {
                return new ExternalBlockReader(accessor, visibleLength, startOffset);
            }
        } catch (Throwable t) {
            LOG.warn("Failed to construct new object of type " + cls.getName(), t);
        }
    }
    return null;
}

From source file:net.minecraftforge.gradle.patcher.TaskGenBinPatches.java

private void createBinPatches(HashMap<String, byte[]> patches, String root, File base, File target)
        throws Exception {
    JarFile cleanJ = new JarFile(base);
    JarFile dirtyJ = new JarFile(target);

    for (Map.Entry<String, String> entry : obfMapping.entrySet()) {
        String obf = entry.getKey();
        String srg = entry.getValue();

        if (!patchedFiles.contains(obf)) // Not in the list of patch files.. we didn't edit it.
        {/*from w w  w  .  jav  a  2 s  . co m*/
            continue;
        }

        JarEntry cleanE = cleanJ.getJarEntry(obf + ".class");
        JarEntry dirtyE = dirtyJ.getJarEntry(obf + ".class");

        if (dirtyE == null) //Something odd happened.. a base MC class wasn't in the obfed jar?
        {
            continue;
        }

        byte[] clean = (cleanE != null ? ByteStreams.toByteArray(cleanJ.getInputStream(cleanE)) : new byte[0]);
        byte[] dirty = ByteStreams.toByteArray(dirtyJ.getInputStream(dirtyE));

        byte[] diff = delta.compute(clean, dirty);

        ByteArrayDataOutput out = ByteStreams.newDataOutput(diff.length + 50);
        out.writeUTF(obf); // Clean name
        out.writeUTF(obf.replace('/', '.')); // Source Notch name
        out.writeUTF(srg.replace('/', '.')); // Source SRG Name
        out.writeBoolean(cleanE != null); // Exists in Clean
        if (cleanE != null) {
            out.writeInt(adlerHash(clean)); // Hash of Clean file
        }
        out.writeInt(diff.length); // Patch length
        out.write(diff); // Patch

        patches.put(root + srg.replace('/', '.') + ".binpatch", out.toByteArray());
    }

    cleanJ.close();
    dirtyJ.close();
}

From source file:codecrafter47.bungeetablistplus.bukkitbridge.BukkitBridge.java

public void onEnable() {
    try {/*from  w  w w .j  a  v  a 2  s.co m*/
        Field field = BungeeTabListPlusBukkitAPI.class.getDeclaredField("instance");
        field.setAccessible(true);
        field.set(null, this);
    } catch (NoSuchFieldException | IllegalAccessException ex) {
        plugin.getLogger().log(Level.SEVERE, "Failed to initialize API", ex);
    }

    plugin.getServer().getMessenger().registerOutgoingPluginChannel(plugin, BridgeProtocolConstants.CHANNEL);
    plugin.getServer().getMessenger().registerIncomingPluginChannel(plugin, BridgeProtocolConstants.CHANNEL,
            (string, player, bytes) -> {

                DataInput input = new DataInputStream(new ByteArrayInputStream(bytes));

                try {
                    int messageId = input.readUnsignedByte();

                    switch (messageId) {
                    case BridgeProtocolConstants.MESSAGE_ID_PROXY_HANDSHAKE:
                        UUID proxyId = DataStreamUtils.readUUID(input);
                        int protocolVersion = input.readInt();

                        if (protocolVersion > BridgeProtocolConstants.VERSION) {
                            rlExecutor.execute(() -> plugin.getLogger()
                                    .warning("BungeeTabListPlus_BukkitBridge is outdated."));
                        } else if (protocolVersion < BridgeProtocolConstants.VERSION) {
                            rlExecutor.execute(() -> plugin.getLogger()
                                    .warning("BungeeTabListPlus proxy plugin outdated."));
                        } else {
                            playerData.put(player, new PlayerBridgeData(proxyId));
                            serverData.computeIfAbsent(proxyId, uuid -> new ServerBridgeData());
                            ByteArrayDataOutput data = ByteStreams.newDataOutput();
                            data.writeByte(BridgeProtocolConstants.MESSAGE_ID_SERVER_HANDSHAKE);
                            player.sendPluginMessage(plugin, BridgeProtocolConstants.CHANNEL,
                                    data.toByteArray());
                        }

                        break;

                    case BridgeProtocolConstants.MESSAGE_ID_PROXY_REQUEST_DATA:
                        BridgeData bridgeData = playerData.get(player);
                        if (bridgeData != null) {
                            handleDataRequest(bridgeData, input);
                        }
                        break;

                    case BridgeProtocolConstants.MESSAGE_ID_PROXY_REQUEST_SERVER_DATA:
                        PlayerBridgeData playerBridgeData = playerData.get(player);
                        if (playerBridgeData != null) {
                            bridgeData = serverData.get(playerBridgeData.proxyId);
                            if (bridgeData != null) {
                                handleDataRequest(bridgeData, input);
                            }
                        }
                        break;

                    case BridgeProtocolConstants.MESSAGE_ID_PROXY_OUTDATED:
                        rlExecutor.execute(
                                () -> plugin.getLogger().warning("BungeeTabListPlus proxy plugin outdated."));
                        break;

                    case BridgeProtocolConstants.MESSAGE_ID_PROXY_REQUEST_RESET_SERVER_DATA:
                        playerBridgeData = playerData.get(player);
                        if (playerBridgeData != null) {
                            bridgeData = serverData.get(playerBridgeData.proxyId);
                            if (bridgeData != null) {
                                serverData.put(playerBridgeData.proxyId, new ServerBridgeData());
                            }
                        }
                        break;

                    default:
                        plugin.getLogger().warning("Received unknown message id " + messageId);
                        break;
                    }
                } catch (IOException ex) {
                    plugin.getLogger().log(Level.SEVERE,
                            "An unexpected error occurred while processing a plugin message.", ex);
                }
            });

    plugin.getServer().getPluginManager().registerEvents(this, plugin);

    updateDataHooks();

    // initialize bridge for players already on the server
    for (Player player : plugin.getServer().getOnlinePlayers()) {
        ByteArrayDataOutput data = ByteStreams.newDataOutput();
        data.writeByte(BridgeProtocolConstants.MESSAGE_ID_SERVER_ENABLE_CONNECTION);
        try {
            DataStreamUtils.writeUUID(data, serverId);
        } catch (IOException e) {
            throw new AssertionError(e);
        }
        player.sendPluginMessage(plugin, BridgeProtocolConstants.CHANNEL, data.toByteArray());
    }

    // start update task
    plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, () -> {
        long now = System.currentTimeMillis();
        Map<UUID, Player> proxyIds = new HashMap<>();

        for (Map.Entry<Player, PlayerBridgeData> e : playerData.entrySet()) {
            Player player = e.getKey();
            PlayerBridgeData bridgeData = e.getValue();

            proxyIds.putIfAbsent(bridgeData.proxyId, player);

            int size = 0;

            for (CacheEntry entry : bridgeData.requestedData) {
                Object value = playerDataAccess.get(entry.key, player);
                entry.dirty = !Objects.equals(value, entry.value);
                entry.value = value;

                if (entry.dirty) {
                    size++;
                }
            }

            if (size != 0) {
                ByteArrayDataOutput data = ByteStreams.newDataOutput();
                data.writeByte(BridgeProtocolConstants.MESSAGE_ID_SERVER_UPDATE_DATA);
                data.writeInt(size);

                for (CacheEntry entry : bridgeData.requestedData) {
                    if (entry.dirty) {
                        data.writeInt(entry.netId);
                        data.writeBoolean(entry.value == null);
                        if (entry.value != null) {
                            try {
                                typeRegistry.getTypeAdapter((TypeToken<Object>) entry.key.getType()).write(data,
                                        entry.value);
                            } catch (java.io.IOException e1) {
                                e1.printStackTrace();
                            }
                        }
                    }
                }

                player.sendPluginMessage(plugin, BridgeProtocolConstants.CHANNEL, data.toByteArray());
            }
        }

        for (Map.Entry<UUID, Player> e : proxyIds.entrySet()) {
            UUID proxyId = e.getKey();
            Player player = e.getValue();
            ServerBridgeData bridgeData = serverData.get(proxyId);

            if (bridgeData == null) {
                continue;
            }

            bridgeData.lastUpdate = now;

            int size = 0;

            for (CacheEntry entry : bridgeData.requestedData) {
                Object value = serverDataAccess.get(entry.key, plugin.getServer());
                entry.dirty = !Objects.equals(value, entry.value);
                entry.value = value;

                if (entry.dirty) {
                    size++;
                }
            }

            ByteArrayDataOutput data = ByteStreams.newDataOutput();
            data.writeByte(BridgeProtocolConstants.MESSAGE_ID_SERVER_UPDATE_SERVER_DATA);

            if (size > 0) {
                bridgeData.revision++;
            }

            data.writeInt(bridgeData.revision);
            data.writeInt(size);

            for (CacheEntry entry : bridgeData.requestedData) {
                if (entry.dirty) {
                    data.writeInt(entry.netId);
                    data.writeBoolean(entry.value == null);
                    if (entry.value != null) {
                        try {
                            typeRegistry.getTypeAdapter((TypeToken<Object>) entry.key.getType()).write(data,
                                    entry.value);
                        } catch (java.io.IOException e1) {
                            e1.printStackTrace();
                        }
                    }
                }
            }

            player.sendPluginMessage(plugin, BridgeProtocolConstants.CHANNEL, data.toByteArray());
        }

        for (Iterator<ServerBridgeData> iterator = serverData.values().iterator(); iterator.hasNext();) {
            ServerBridgeData data = iterator.next();
            if (now - data.lastUpdate > 900000) {
                iterator.remove();
            }
        }

    }, 20, 20);
}

From source file:codecrafter47.bungeetablistplus.bridge.BukkitBridge.java

@EventHandler
public void onPluginMessage(PluginMessageEvent event) {
    if (event.getReceiver() instanceof ProxiedPlayer && event.getSender() instanceof Server) {

        ProxiedPlayer player = (ProxiedPlayer) event.getReceiver();
        Server server = (Server) event.getSender();

        if (event.getTag().equals(BridgeProtocolConstants.CHANNEL)) {
            event.setCancelled(true);//w  w w .  j  av a2  s .  c o  m

            ConnectedPlayer connectedPlayer = plugin.getConnectedPlayerManager().getPlayerIfPresent(player);
            if (connectedPlayer != null) {

                PlayerBridgeDataCache cache = connectedPlayer.getBridgeDataCache();

                DataInput input = new DataInputStream(new ByteArrayInputStream(event.getData()));

                try {
                    int messageId = input.readUnsignedByte();

                    switch (messageId) {
                    case BridgeProtocolConstants.MESSAGE_ID_SERVER_HANDSHAKE:

                        if (cache.connection != null) {
                            disableConnection(cache);
                        }
                        cache.connection = server;
                        getServerDataCache(server.getInfo().getName()).addConnection(server);
                        ArrayList<DataKey<?>> keys = Lists.newArrayList(cache.getQueriedKeys());

                        ByteArrayDataOutput data = ByteStreams.newDataOutput();
                        data.writeByte(BridgeProtocolConstants.MESSAGE_ID_PROXY_REQUEST_DATA);
                        data.writeInt(keys.size());
                        for (DataKey<?> key : keys) {
                            DataStreamUtils.writeDataKey(data, key);
                            data.writeInt(idMap.getNetId(key));
                        }
                        server.sendData(BridgeProtocolConstants.CHANNEL, data.toByteArray());
                        break;
                    case BridgeProtocolConstants.MESSAGE_ID_SERVER_UPDATE_DATA:

                        if (cache.connection == server) {
                            onDataReceived(cache, input, input.readInt());
                        }

                        break;
                    case BridgeProtocolConstants.MESSAGE_ID_SERVER_UPDATE_SERVER_DATA:

                        if (cache.connection == server) {
                            ServerBridgeDataCache serverDataCache = getServerDataCache(
                                    server.getInfo().getName());
                            int revision = input.readInt();
                            int size = input.readInt();
                            if (size > 0 && revision == serverDataCache.lastRevision + 1) {
                                onDataReceived(serverDataCache, input, size);
                                serverDataCache.lastRevision = revision;
                            } else if (size > 0 || revision > serverDataCache.lastRevision) {
                                Server connection = serverDataCache.getConnection();
                                if (connection != null) {
                                    ByteArrayDataOutput output = ByteStreams.newDataOutput();
                                    output.writeByte(
                                            BridgeProtocolConstants.MESSAGE_ID_PROXY_REQUEST_RESET_SERVER_DATA);
                                    connection.sendData(BridgeProtocolConstants.CHANNEL, output.toByteArray());
                                    serverDataCache.lastRevision = 0;
                                }
                            }
                        }

                        break;
                    case BridgeProtocolConstants.MESSAGE_ID_SERVER_DISABLE_CONNECTION:

                        disableConnection(cache);
                        serverInformation.get(server.getInfo().getName()).reset();
                        break;
                    case BridgeProtocolConstants.MESSAGE_ID_SERVER_ENABLE_CONNECTION:

                        UUID serverId = DataStreamUtils.readUUID(input);
                        ServerBridgeDataCache serverData = getServerDataCache(server.getInfo().getName());
                        if (!serverData.serverId.equals(serverId)) {
                            serverData.serverId = serverId;
                            serverData.reset();
                        }

                        initializeHandshake(server);
                        break;
                    case BridgeProtocolConstants.MESSAGE_ID_SERVER_OUTDATED:

                        rlExecutor.execute(() -> plugin.getLogger().warning(
                                "Bridge plugin on server " + server.getInfo().getName() + " is outdated."));
                        break;
                    }
                } catch (IOException ex) {
                    plugin.getLogger().log(Level.SEVERE,
                            "An unexpected error occurred while processing bridge data.", ex);
                }
            }
        }
    }
}