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:com.volumetricpixels.rockyplugin.packet.RockyPacketHandler.java

/**
 * /* www  .ja  v  a  2 s  .c  om*/
 * @param packet
 */
public void sendMessagePlugin(com.volumetricpixels.rockyapi.packet.Packet packet) {
    ByteArrayDataOutput bos = ByteStreams.newDataOutput();
    try {
        bos.writeShort(packet.getType().getId());

        PacketOutputStream out = new PacketOutputStream();
        packet.writeData(out);

        ByteBuffer buffer = out.getRawBuffer();
        buffer.flip();
        bos.writeShort(buffer.limit());
        bos.write(buffer.array());
        buffer.clear();
    } catch (IOException ex) {
        return;
    }
    Packet250CustomPayload payload = new Packet250CustomPayload("Rocky", bos.toByteArray());
    sendOfflinePacket(payload);
}

From source file:de.jonas.Rush.java

@EventHandler
public void onInteract(PlayerInteractEvent e) {
    Player p = e.getPlayer();//from w ww.  j av a2  s .  c  o  m
    if (p.getItemInHand().equals(spec_tpred)) {
        e.setCancelled(true);
        p.teleport(redspawn);
    }
    if (p.getItemInHand().equals(spec_tpblue)) {
        e.setCancelled(true);
        p.teleport(bluespawn);
    }
    if (p.getItemInHand().equals(spec_tpitem)) {
        e.setCancelled(true);
        Inventory inv = Bukkit.createInventory(p, InventoryType.CHEST, ChatColor.GOLD + "Spieler");
        for (ItemStack iss : spec_tp) {
            inv.addItem(iss);
        }
        p.openInventory(inv);
    }
    if (p.getItemInHand().equals(lobbyitem)) {
        e.setCancelled(true);
        ByteArrayDataOutput out = ByteStreams.newDataOutput(); //BungeeCoord Connection
        out.writeUTF("Connect");
        out.writeUTF(this.getConfig().getString("main.lobbyservername"));
        p.sendPluginMessage(this, "BungeeCord", out.toByteArray());
        game.players.remove(p.getName()); //Remove Players from the List
    }
    Integer maxblue = this.getConfig().getInt("teams.blue.max");
    Integer maxred = this.getConfig().getInt("teams.red.max");
    if (e.getAction() == Action.RIGHT_CLICK_BLOCK) {

        if (e.getClickedBlock().getState() instanceof Sign) {

            Sign s = (Sign) e.getClickedBlock().getState();

            if (s.getLine(0).equalsIgnoreCase("[RushTeam]")) {
                if (s.getLine(1).equals("Red")) {
                    s.setLine(0, "[Team]");
                    s.setLine(1, ChatColor.RED + "Rot");
                    s.update();
                }
                if (s.getLine(1).equals("Blue")) {
                    s.setLine(0, "[Team]");
                    s.setLine(1, ChatColor.BLUE + "Blau");
                    s.update();
                }
            }
            if (s.getLine(0).equalsIgnoreCase("[Team]")) {
                String sign_team = s.getLine(1);
                if (sign_team.equals(ChatColor.BLUE + "Blau")) {
                    if (blue.players.size() - 2 <= maxblue) {
                        if (blue.players.size() == red.players.size()
                                || blue.players.size() < red.players.size()) {
                            GamePlayer gp = game.gameplayers.get(p);
                            gp.team = GamePlayerTeam.BLUE;
                            game.gameplayers.put(p, gp);
                            p.sendMessage(ChatColor.BLUE + "Du bist jetzt in Team Blau.");
                            blue.add(p);
                            red.remove(p);
                            TagAPI.refreshPlayer(p);
                        } else {
                            if (blue.players.size() > red.players.size()) {
                                p.sendMessage(ChatColor.RED + "Das Rote Team hat zu wenig Mitspieler!");
                            }
                        }
                    } else {
                        p.sendMessage(ChatColor.BLUE + "Dieses Team ist voll!");
                    }
                }
                if (sign_team.equals(ChatColor.RED + "Rot")) {
                    if (red.players.size() - 2 <= maxred) {
                        if (red.players.size() == blue.players.size()
                                || red.players.size() < blue.players.size()) {
                            GamePlayer gp = game.gameplayers.get(p);
                            gp.team = GamePlayerTeam.RED;
                            game.gameplayers.put(p, gp);
                            p.sendMessage(ChatColor.RED + "Du bist jetzt in Team Rot.");
                            red.add(p);
                            blue.remove(p);
                            TagAPI.refreshPlayer(p);
                        } else {
                            if (red.players.size() > blue.players.size()) {
                                p.sendMessage(ChatColor.BLUE + "Das Blaue Team hat zu wenig Mitspieler!");
                            }
                        }
                    } else {
                        p.sendMessage(ChatColor.RED + "Dieses Team ist voll!");
                    }
                }
            }
        }
    } else {
        return;
    }

}

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

@EventHandler
public void onSignChange(final SignChangeEvent evt) {
    if (evt.getLine(0).equals("[tps]")) {
        evt.setLine(0, "Pinging...");
        this.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
            @Override/*from ww w .jav a 2 s .c  om*/
            public void run() {
                ByteArrayDataOutput out = ByteStreams.newDataOutput();
                out.writeUTF("GetMotd");
                out.writeUTF(evt.getLine(1));
                if (!signs.containsKey(evt.getLine(1))) {
                    signs.put(evt.getLine(1), new ArrayList<org.bukkit.block.Sign>());
                }
                ArrayList<org.bukkit.block.Sign> list = signs.get(evt.getLine(1));
                org.bukkit.block.Sign s = (org.bukkit.block.Sign) plugin.getServer().getWorld("world")
                        .getBlockAt(evt.getBlock().getLocation()).getState();
                list.add(s);
                signs.put(evt.getLine(1), list);
                plugin.getServer().sendPluginMessage(plugin, "BungeeCord", out.toByteArray());
            }
        }, Utilities.ticks(5));
    }
}

From source file:org.wso2.carbon.analytics.data.commons.utils.AnalyticsCommonUtils.java

public static byte[] encodeElement(String name, Object value) throws AnalyticsException {
    ByteArrayDataOutput buffer = ByteStreams.newDataOutput();
    byte[] nameBytes = name.getBytes(StandardCharsets.UTF_8);
    buffer.writeInt(nameBytes.length);/*ww w  .j  ava2s .  c  om*/
    buffer.write(nameBytes);
    if (value instanceof String) {
        buffer.write(DATA_TYPE_STRING);
        String strVal = (String) value;
        byte[] strBytes = strVal.getBytes(StandardCharsets.UTF_8);
        buffer.writeInt(strBytes.length);
        buffer.write(strBytes);
    } else if (value instanceof Long) {
        buffer.write(DATA_TYPE_LONG);
        buffer.writeLong((Long) value);
    } else if (value instanceof Double) {
        buffer.write(DATA_TYPE_DOUBLE);
        buffer.writeDouble((Double) value);
    } else if (value instanceof Boolean) {
        buffer.write(DATA_TYPE_BOOLEAN);
        boolean boolVal = (Boolean) value;
        if (boolVal) {
            buffer.write(BOOLEAN_TRUE);
        } else {
            buffer.write(BOOLEAN_FALSE);
        }
    } else if (value instanceof Integer) {
        buffer.write(DATA_TYPE_INTEGER);
        buffer.writeInt((Integer) value);
    } else if (value instanceof Float) {
        buffer.write(DATA_TYPE_FLOAT);
        buffer.writeFloat((Float) value);
    } else if (value instanceof byte[]) {
        buffer.write(DATA_TYPE_BINARY);
        byte[] binData = (byte[]) value;
        buffer.writeInt(binData.length);
        buffer.write(binData);
    } else if (value == null) {
        buffer.write(DATA_TYPE_NULL);
    } else {
        buffer.write(DATA_TYPE_OBJECT);
        byte[] binData = serializeObject(value);
        buffer.writeInt(binData.length);
        buffer.write(binData);
    }
    return buffer.toByteArray();
}

From source file:org.wso2.carbon.analytics.datasource.core.util.GenericUtils.java

public static byte[] encodeElement(String name, Object value) throws AnalyticsException {
    ByteArrayDataOutput buffer = ByteStreams.newDataOutput();
    byte[] nameBytes = name.getBytes(StandardCharsets.UTF_8);
    buffer.writeInt(nameBytes.length);//  w  w w  .  j av a2s  . c  o m
    buffer.write(nameBytes);
    if (value instanceof String) {
        buffer.write(DATA_TYPE_STRING);
        String strVal = (String) value;
        byte[] strBytes = strVal.getBytes(StandardCharsets.UTF_8);
        buffer.writeInt(strBytes.length);
        buffer.write(strBytes);
    } else if (value instanceof Long) {
        buffer.write(DATA_TYPE_LONG);
        buffer.writeLong((Long) value);
    } else if (value instanceof Double) {
        buffer.write(DATA_TYPE_DOUBLE);
        buffer.writeDouble((Double) value);
    } else if (value instanceof Boolean) {
        buffer.write(DATA_TYPE_BOOLEAN);
        boolean boolVal = (Boolean) value;
        if (boolVal) {
            buffer.write(BOOLEAN_TRUE);
        } else {
            buffer.write(BOOLEAN_FALSE);
        }
    } else if (value instanceof Integer) {
        buffer.write(DATA_TYPE_INTEGER);
        buffer.writeInt((Integer) value);
    } else if (value instanceof Float) {
        buffer.write(DATA_TYPE_FLOAT);
        buffer.writeFloat((Float) value);
    } else if (value instanceof byte[]) {
        buffer.write(DATA_TYPE_BINARY);
        byte[] binData = (byte[]) value;
        buffer.writeInt(binData.length);
        buffer.write(binData);
    } else if (value == null) {
        buffer.write(DATA_TYPE_NULL);
    } else {
        buffer.write(DATA_TYPE_OBJECT);
        byte[] binData = GenericUtils.serializeObject(value);
        buffer.writeInt(binData.length);
        buffer.write(binData);
    }
    return buffer.toByteArray();
}

From source file:io.druid.indexer.InputRowSerde.java

public static final byte[] toBytes(final InputRow row, AggregatorFactory[] aggs) {
    try {//from   www  .jav  a  2  s .  co m
        ByteArrayDataOutput out = ByteStreams.newDataOutput();

        //write timestamp
        out.writeLong(row.getTimestampFromEpoch());

        //writing all dimensions
        List<String> dimList = row.getDimensions();

        Text[] dims = EMPTY_TEXT_ARRAY;
        if (dimList != null) {
            dims = new Text[dimList.size()];
            for (int i = 0; i < dims.length; i++) {
                dims[i] = new Text(dimList.get(i));
            }
        }
        StringArrayWritable sw = new StringArrayWritable(dims);
        sw.write(out);

        MapWritable mw = new MapWritable();

        if (dimList != null) {
            for (String dim : dimList) {
                List<String> dimValue = row.getDimension(dim);

                if (dimValue == null || dimValue.size() == 0) {
                    continue;
                }

                if (dimValue.size() == 1) {
                    mw.put(new Text(dim), new Text(dimValue.get(0)));
                } else {
                    Text[] dimValueArr = new Text[dimValue.size()];
                    for (int i = 0; i < dimValueArr.length; i++) {
                        dimValueArr[i] = new Text(dimValue.get(i));
                    }
                    mw.put(new Text(dim), new StringArrayWritable(dimValueArr));
                }
            }
        }

        //writing all metrics
        Supplier<InputRow> supplier = new Supplier<InputRow>() {
            @Override
            public InputRow get() {
                return row;
            }
        };
        for (AggregatorFactory aggFactory : aggs) {
            String k = aggFactory.getName();

            Aggregator agg = aggFactory
                    .factorize(IncrementalIndex.makeColumnSelectorFactory(aggFactory, supplier, true));
            agg.aggregate();

            String t = aggFactory.getTypeName();

            if (t.equals("float")) {
                mw.put(new Text(k), new FloatWritable(agg.getFloat()));
            } else if (t.equals("long")) {
                mw.put(new Text(k), new LongWritable(agg.getLong()));
            } else {
                //its a complex metric
                Object val = agg.get();
                ComplexMetricSerde serde = getComplexMetricSerde(t);
                mw.put(new Text(k), new BytesWritable(serde.toBytes(val)));
            }
        }

        mw.write(out);
        return out.toByteArray();
    } catch (IOException ex) {
        throw Throwables.propagate(ex);
    }
}

From source file:de.minigameslib.mclib.impl.MclibPlugin.java

@Override
public void broadcastClients(CommunicationEndpointId id, DataSection... data) {
    if (data != null) {
        for (final DataSection section : data) {
            final ByteArrayDataOutput out = ByteStreams.newDataOutput();
            out.writeByte(0);/*  w w w . j  ava2 s  .  co m*/
            new NetMessage(id, section).toBytes(out);
            byte[] bytes = out.toByteArray();
            if (this.getLogger().isLoggable(Level.FINEST)) {
                this.getLogger().finest("Sending NetMessage to all players\n" + Arrays.toString(bytes)); //$NON-NLS-1$
            }
            // TODO find a way to broadcast to all players connected to any server in bungee cord network
            Bukkit.getServer().sendPluginMessage(this, MCLIB_SERVER_TO_CLIENT_CHANNEL, bytes);
        }
    }
}

From source file:de.minigameslib.mclib.impl.MclibPlugin.java

/**
 * Initialize networking stuff./*w  ww.j av a2s  .c  om*/
 */
private void initNetworking() {
    this.registerPeerHandler(this, MclibCommunication.ClientServerCore, new MclibCoreHandler());

    // network
    // sc = s[erver]c[client] (both directions)
    Bukkit.getMessenger().registerOutgoingPluginChannel(this, MCLIB_SERVER_TO_CLIENT_CHANNEL);
    Bukkit.getMessenger().registerIncomingPluginChannel(this, MCLIB_SERVER_TO_CLIENT_CHANNEL, this);
    // bc = b[ungee]c[oord]
    Bukkit.getMessenger().registerOutgoingPluginChannel(this, MCLIB_SERVER_TO_SERVER_CHANNEL);
    Bukkit.getMessenger().registerIncomingPluginChannel(this, MCLIB_SERVER_TO_SERVER_CHANNEL, this);
    // bungeecord
    Bukkit.getMessenger().registerOutgoingPluginChannel(this, BUNGEECORD_CHANNEL);
    Bukkit.getMessenger().registerIncomingPluginChannel(this, BUNGEECORD_CHANNEL, this);

    final ByteArrayDataOutput out = ByteStreams.newDataOutput();
    out.writeUTF("GetServer"); //$NON-NLS-1$
    this.bungeeQueue.add(p -> p.sendPluginMessage(this, BUNGEECORD_CHANNEL, out.toByteArray()));
    final ByteArrayDataOutput out2 = ByteStreams.newDataOutput();
    out2.writeUTF("GetServers"); //$NON-NLS-1$
    this.bungeeQueue.add(p -> p.sendPluginMessage(this, BUNGEECORD_CHANNEL, out2.toByteArray()));

    this.serversPing = new GetServersPing();
    this.serversPing.runTaskTimer(this, 20 * 5, 20 * 60); // once per minute
}

From source file:de.minigameslib.mclib.impl.MclibPlugin.java

@Override
public void send(CommunicationEndpointId id, DataSection... data) {
    // check if we have a server-to-server endpoint or server-to-client endpoint
    if (this.endpointTypes.get(id)) {
        // server to player
        final McPlayerInterface player = this.getCurrentPlayer();
        if (player == null) {
            this.getLogger().fine("Trying to send data to unknown player (invalid context)"); //$NON-NLS-1$
        } else if (data != null) {
            for (final DataSection section : data) {
                final ByteArrayDataOutput out = ByteStreams.newDataOutput();
                out.writeByte(0);//w w  w.  jav a  2 s  . com
                new NetMessage(id, section).toBytes(out);
                byte[] bytes = out.toByteArray();
                if (this.getLogger().isLoggable(Level.FINEST)) {
                    this.getLogger().finest("Sending NetMessage to player " + player.getPlayerUUID() + "\n" //$NON-NLS-1$//$NON-NLS-2$
                            + Arrays.toString(bytes));
                }
                player.getBukkitPlayer().sendPluginMessage(this, MCLIB_SERVER_TO_CLIENT_CHANNEL, bytes);
            }
        }
    } else {
        // server to server means: broadcast to everyone
        this.broadcastServers(id, data);
    }
}

From source file:de.minigameslib.mclib.impl.MclibPlugin.java

@Override
public void broadcastServers(CommunicationEndpointId id, DataSection... data) {
    if (data != null) {
        for (final DataSection section : data) {
            // TODO only works if both servers have online players
            // TODO if target servers do not have online players the messages should be queued by bungeecord.
            // TODO ensure that we are really within bungeecord environments, else this will be sent to clients (not good)
            final ByteArrayDataOutput out2 = ByteStreams.newDataOutput();
            final ByteArrayDataOutput out = ByteStreams.newDataOutput();
            out2.writeUTF("Forward"); //$NON-NLS-1$
            out2.writeUTF("ALL"); //$NON-NLS-1$
            out2.writeUTF(MCLIB_SERVER_TO_SERVER_CHANNEL);
            out.writeByte(0);//  ww  w .j a v a 2 s.  c  o m
            new NetMessage(id, section).toBytes(out);
            byte[] bytes = out.toByteArray();
            if (this.getLogger().isLoggable(Level.FINEST)) {
                this.getLogger().finest("Sending NetMessage to all servers\n" + Arrays.toString(bytes)); //$NON-NLS-1$
            }
            out2.writeShort(bytes.length);
            out2.write(bytes);
            final ObjectServiceInterface osi = ObjectServiceInterface.instance();
            final Optional<? extends Player> player = Bukkit.getOnlinePlayers().stream()
                    .filter(p -> !osi.isHuman(p)).findFirst();
            if (player.isPresent()) {
                // bungee cord ensures this is not send to the client.
                player.get().sendPluginMessage(this, BUNGEECORD_CHANNEL, bytes);
            } else {
                this.bungeeQueue.add(p -> p.sendPluginMessage(this, BUNGEECORD_CHANNEL, bytes));
            }
        }
    }
}