Example usage for io.netty.buffer ByteBuf readBytes

List of usage examples for io.netty.buffer ByteBuf readBytes

Introduction

In this page you can find the example usage for io.netty.buffer ByteBuf readBytes.

Prototype

public abstract ByteBuf readBytes(ByteBuffer dst);

Source Link

Document

Transfers this buffer's data to the specified destination starting at the current readerIndex until the destination's position reaches its limit, and increases the readerIndex by the number of the transferred bytes.

Usage

From source file:at.yawk.accordion.distributed.InternalProtocol.java

License:Mozilla Public License

/**
 * Read a byte array written by #writeByteArray.
 *///from  www .j ava2  s . c om
static byte[] readByteArray(ByteBuf from) {
    byte[] array = new byte[from.readUnsignedByte()];
    from.readBytes(array);
    return array;
}

From source file:at.yawk.accordion.minecraft.AccordionBungee.java

License:Mozilla Public License

public static AccordionApi createApi(Plugin plugin) {
    InetSocketAddress host = plugin.getProxy().getConfig().getListeners().stream().findAny().get().getHost();
    AccordionApi api = new AccordionApi().mcPort(host.getPort()).logger(plugin.getLogger()).listen(true)
            .tier(AccordionApi.DEFAULT_TIER_BUNGEE);

    // hack to get bungee thread group
    Object lock = new Object();
    plugin.getProxy().getScheduler().runAsync(plugin, () -> {
        api.threadGroup(Thread.currentThread().getThreadGroup());
        synchronized (lock) {
            lock.notifyAll();/*w  w  w . ja  v a2  s. com*/
        }
    });
    //noinspection SynchronizationOnLocalVariableOrMethodParameter
    synchronized (lock) {
        try {
            lock.wait();
        } catch (InterruptedException ignored) {
        }
    }

    // TODO reliable autostart
    plugin.getProxy().getScheduler().schedule(plugin, api::tryAutoStart, 3, TimeUnit.SECONDS);

    plugin.getProxy().getPluginManager().registerListener(plugin, new Listener() {
        @EventHandler
        public void onPluginMessage(PluginMessageEvent event) {
            // filter malicious peer packets from client
            if (event.getTag().equals(AccordionApi.PEER_DISCOVERY_PLUGIN_CHANNEL)) {
                event.setCancelled(true);
            }
        }

        @EventHandler
        public void onSwitch(ServerSwitchEvent event) {
            if (!api.isAutomaticDiscovery()) {
                return;
            }

            // send our known nodes to the server
            ByteBuf enc = api.getLocalNode().getKnownNodesEncoded();
            byte[] array = new byte[enc.readableBytes()];
            enc.readBytes(array);

            event.getPlayer().getServer().sendData(AccordionApi.PEER_DISCOVERY_PLUGIN_CHANNEL, array);
        }
    });

    return api;
}

From source file:at.yawk.accordion.netty.Framer.java

License:Mozilla Public License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
    if (msg.readableBytes() < 2) {
        // no (full) length header received yet, wait
        return;//  w  w  w . ja  va2  s .  c  om
    }

    // mark so we can reset here if the message isn't complete yet
    msg.markReaderIndex();
    int messageLength = msg.readUnsignedShort();
    if (messageLength > msg.readableBytes()) {
        // length header received but message not yet complete, wait
        msg.resetReaderIndex();
        return;
    }

    // message complete, queue for handling
    ByteBuf message = msg.readBytes(messageLength);
    out.add(message);
}

From source file:at.yawk.accordion.simulation.Simulation.java

License:Mozilla Public License

public static void main(String[] args) throws UnknownHostException, InterruptedException {
    Logger.getRootLogger().addAppender(new ConsoleAppender(new SimpleLayout(), ConsoleAppender.SYSTEM_OUT));
    Logger.getRootLogger().setLevel(Level.DEBUG);

    Simulation simulation = new Simulation();
    simulation.populate();/*from   w  w w .j  a  v  a 2 s .  c  om*/
    TimeUnit.SECONDS.sleep(1);

    simulation.nodes.get(simulation.tiers[0][0]).getConnectionManager().getChannel("test").subscribe(msg -> {
        int len = msg.readInt();
        byte[] blob = new byte[len];
        msg.readBytes(blob);
        Log.getDefaultLogger().info("Received: " + new String(blob));
    });
    TimeUnit.SECONDS.sleep(1);

    ByteBuf msg = Unpooled.buffer();
    byte[] text = "ping".getBytes();
    msg.writeInt(text.length);
    msg.writeBytes(text);

    simulation.nodes.get(simulation.tiers[0][1]).getConnectionManager().getChannel("test").publish(msg);
}

From source file:at.yawk.votifier.LineSplitter.java

License:Mozilla Public License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    in.markReaderIndex();//w  w w .  j  a  va 2  s .c  o  m
    int lineLength = 0;
    boolean found = false;
    while (in.isReadable()) {
        if (in.readByte() == '\n') {
            found = true;
            break;
        }
        lineLength++;
    }
    in.resetReaderIndex();
    if (found) {
        byte[] line = new byte[lineLength];
        in.readBytes(line);
        in.readByte(); // newline
        out.add(new String(line, StandardCharsets.UTF_8));
    }
}

From source file:at.yawk.votifier.VoteDecrypter.java

License:Mozilla Public License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    int readable = in.readableBytes();
    if (readable < MESSAGE_SIZE) {
        // the message must be exactly 256 bytes long
        return;//from w  w w.  ja  v a 2 s .  c o m
    }

    byte[] encrypted = new byte[MESSAGE_SIZE];
    in.readBytes(encrypted);
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.DECRYPT_MODE, key);
    byte[] decrypted = cipher.doFinal(encrypted);
    out.add(Unpooled.wrappedBuffer(decrypted));
}

From source file:basic.TimeClientHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf buf = (ByteBuf) msg;
    byte[] req = new byte[buf.readableBytes()];
    buf.readBytes(req);
    String body = new String(req, "UTF-8");
    System.out.println("Now is : " + body);
}

From source file:basic.TimeServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf buf = (ByteBuf) msg;
    byte[] req = new byte[buf.readableBytes()];
    buf.readBytes(req);
    String body = new String(req, "UTF-8");
    System.out.println("The time server receive order : " + body);
    String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body)
            ? new java.util.Date(System.currentTimeMillis()).toString()
            : "BAD ORDER";
    ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
    ctx.write(resp);//from w  ww.  j a v  a  2s  . c o m
}

From source file:bftsmart.communication.client.netty.NettyTOMMessageDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext context, ByteBuf buffer, List<Object> list) throws Exception {

    // Wait until the length prefix is available.
    if (buffer.readableBytes() < Integer.BYTES) {
        return;/* w w w  .j a v a  2s  . c  o  m*/
    }

    int dataLength = buffer.getInt(buffer.readerIndex());

    //Logger.println("Receiving message with "+dataLength+" bytes.");

    // Wait until the whole data is available.
    if (buffer.readableBytes() < dataLength + Integer.BYTES) {
        return;
    }

    // Skip the length field because we know it already.
    buffer.skipBytes(Integer.BYTES);

    int size = buffer.readInt();
    byte[] data = new byte[size];
    buffer.readBytes(data);

    byte[] signature = null;
    size = buffer.readInt();

    if (size > 0) {
        signature = new byte[size];
        buffer.readBytes(signature);
    }

    DataInputStream dis = null;
    TOMMessage sm = null;

    try {
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        dis = new DataInputStream(bais);
        sm = new TOMMessage();
        sm.rExternal(dis);
        sm.serializedMessage = data;

        if (signature != null) {
            sm.serializedMessageSignature = signature;
            sm.signed = true;
        }

        if (!isClient) {
            rl.readLock().lock();
            if (!sessionTable.containsKey(sm.getSender())) {
                rl.readLock().unlock();

                NettyClientServerSession cs = new NettyClientServerSession(context.channel(), sm.getSender());

                rl.writeLock().lock();
                sessionTable.put(sm.getSender(), cs);
                logger.debug("Active clients: " + sessionTable.size());
                rl.writeLock().unlock();

            } else {
                rl.readLock().unlock();
            }
        }
        logger.debug("Decoded reply from " + sm.getSender() + " with sequence number " + sm.getSequence());
        list.add(sm);
    } catch (Exception ex) {

        logger.error("Failed to decode TOMMessage", ex);
    }
    return;
}

From source file:blazingcache.network.netty.DodoMessageUtils.java

License:Apache License

private static String readUTF8String(ByteBuf buf) {
    int len = buf.readInt();
    byte[] s = new byte[len];
    buf.readBytes(s);
    return new String(s, StandardCharsets.UTF_8);
}