Example usage for io.netty.buffer Unpooled wrappedBuffer

List of usage examples for io.netty.buffer Unpooled wrappedBuffer

Introduction

In this page you can find the example usage for io.netty.buffer Unpooled wrappedBuffer.

Prototype

public static ByteBuf wrappedBuffer(ByteBuffer... buffers) 

Source Link

Document

Creates a new big-endian composite buffer which wraps the slices of the specified NIO buffers without copying them.

Usage

From source file:io.github.lordakkarin.nbt.event.TagWriterTest.java

License:Apache License

@NonNull
private ByteBuf readResource(@NonNull ReadableByteChannel channel) throws IOException {
    ByteBuf target = Unpooled.directBuffer();

    ByteBuffer tmp = ByteBuffer.allocateDirect(128);
    ByteBuf wrapped = Unpooled.wrappedBuffer(tmp);
    int length;/* w  ww  .j  a  v  a 2s .c  o  m*/

    while ((length = channel.read(tmp)) > 0) {
        tmp.flip();
        target.writeBytes(wrapped, length);

        wrapped.resetReaderIndex();
        tmp.rewind();
    }

    return target;
}

From source file:io.github.stormcloud_dev.stormcloud.StormCloudHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    server.getLogger().info("Channel active: " + ctx.channel());
    //Random random = new Random();
    //Multiplayer ID's are starting at 9
    Player player = new Player(server, getPlayerId(9.0, ctx.channel().remoteAddress().toString().split(":")[0]),
            210.0, ctx.channel().remoteAddress().toString().split(":")[0]);
    player.setChannel(ctx.channel());// w  w w . j  a  v a2 s . c o m
    ctx.channel().attr(PLAYER).set(player);
    channels.add(ctx.channel());

    ctx.writeAndFlush(Unpooled.wrappedBuffer("GM:Studio-Connect\u0000".getBytes("utf8")));
    //Thread that tests if the connection is alive (The client needs that, else it will disconnect)
    Thread testThread = new Thread(() -> {
        Channel channel = ctx.channel();
        scheduleTestPacket(channel);
    });
    testThread.start();
}

From source file:io.github.stormcloud_dev.stormcloud.StormCloudHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    //The player that send a frame
    Player sender = ctx.channel().attr(PLAYER).get();
    if (msg instanceof HandshakeFrame) { //These packets have to send in the exact order with exactly these values, else the client gets a black screen...
        ctx.writeAndFlush(//  w w  w  . j  ava 2 s  .  co  m
                Unpooled.wrappedBuffer(new byte[] { -83, -66, -81, -34, -21, -66, 13, -16, 12, 0, 0, 0 }));
        //40 = Room ID of Lobby, 15 = Object Index for set player
        ctx.writeAndFlush(new SetPlayerClientBoundFrame(15.0, 0.0, sender.getMId(), 40.0, "v1.2.4"));
        ctx.writeAndFlush(new UpdateDiffClientBoundFrame(0.0, 0.0, (byte) 2, (byte) 0, (byte) 0, (byte) 0,
                (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0));
        //We tell the player listener that there's a new player
        PlayerAddEvent event = new PlayerAddEvent(sender);
        server.getEventManager().onEvent(new PlayerAddEvent(sender));
        server.getLogger().info(event.getPlayer().getName() + " joined the game!");
        server.getPlayers().put(event.getPlayer().getMId(), event.getPlayer());
        server.getChannels().stream().forEach(channel -> { //Telling the clients that there's a new player and informing the new player about current players
            if (channel.attr(PLAYER).get().equals(event.getPlayer())) { //Sending the new player, which players are already in the game
                server.getChannels().stream().filter(playerChannel -> !playerChannel.equals(channel))
                        .forEach(playerChannel -> {
                            Player currentPlayer = playerChannel.attr(PLAYER).get();
                            channel.writeAndFlush(new AddPlayerClientBoundFrame(currentPlayer.getObjectIndex(),
                                    currentPlayer.getMId(), 0.0, 0.0, currentPlayer.getMId(),
                                    currentPlayer.getClazz(), 0, currentPlayer.getName()));
                        });
            } else { //Sending each player that a new player joined the game
                channel.writeAndFlush(new AddPlayerClientBoundFrame(event.getPlayer().getObjectIndex(),
                        event.getPlayer().getMId(), 0.0, 0.0, event.getPlayer().getMId(),
                        event.getPlayer().getClazz(), 0, event.getPlayer().getName()));
            }
        });
    } else if (msg instanceof ChatPlayerServerBoundFrame) {
        ChatPlayerServerBoundFrame frame = (ChatPlayerServerBoundFrame) msg;
        if (frame.getText().startsWith("!")) {
            String[] messageParts = frame.getText().split("\\s+");
            String[] args = new String[messageParts.length - 1];
            System.arraycopy(messageParts, 1, args, 0, messageParts.length - 1);
            server.getCommandManager().onCommand(sender, messageParts[0].substring(1), args);
        } else {
            PlayerChatEvent event = new PlayerChatEvent(sender, frame);
            server.getEventManager().onEvent(event);
            getChannels().stream().filter(channel -> channel != ctx.channel())
                    .forEach(channel -> channel
                            .writeAndFlush(new ChatPlayerClientBoundFrame(event.getPlayer().getObjectIndex(),
                                    event.getPlayer().getMId(), event.getMessage())));
        }
    } else if (msg instanceof UpdatePlayerServerBoundFrame) {
        UpdatePlayerServerBoundFrame frame = (UpdatePlayerServerBoundFrame) msg;
        PlayerUpdateEvent event = new PlayerUpdateEvent(sender, frame);
        server.getEventManager().onEvent(event);
        event.getPlayer().setName(event.getFrame().getName().replace("|", ""));
        //event.getPlayer().setLogin(event.getPlayer().getName());
        if (ingame) { //Ingame -> direct transport to the map
            if (event.getFrame().getClazz() == -1) { //The first player update says that this player has no clazz
                if (server.getDisconnectedPlayers().containsKey(event.getPlayer().getLogin())) { //If there was a player on that slot he has to get the same clazz etc.
                    //event.getPlayer().setMId(oldPlayerList.get(event.getPlayer().getLogin()).getClazz());
                    event.getPlayer().setClazz(
                            server.getDisconnectedPlayers().get(event.getPlayer().getLogin()).getClazz());
                    event.getPlayer()
                            .setX(server.getDisconnectedPlayers().get(event.getPlayer().getLogin()).getX());
                    event.getPlayer()
                            .setY(server.getDisconnectedPlayers().get(event.getPlayer().getLogin()).getY());
                    server.getDisconnectedPlayers().remove(event.getPlayer().getLogin());
                }
                //Only to the new player
                server.getChannels().stream()
                        .filter(channel -> channel.attr(PLAYER).get().equals(event.getPlayer()))
                        .forEach(channel -> {
                            //We have to update the positions of the other players if we join mid game
                            server.getPlayers().entrySet().stream()
                                    .filter(entry -> !entry.getValue().equals(event.getPlayer()))
                                    .forEach(entry -> {
                                        Player player = entry.getValue();
                                        channel.writeAndFlush(new UpdatePlayerClientBoundFrame(210.0,
                                                player.getMId(), player.getClazz(), player.getX(),
                                                player.getY(), player.getName() + "|"));
                                    });
                            //We have to setup the disconnected players too (If more than one player disconnects)
                            server.getDisconnectedPlayers().entrySet().stream()
                                    .filter(entry -> !entry.getValue().equals(event.getPlayer()))
                                    .forEach(entry -> {
                                        Player player = entry.getValue();
                                        channel.writeAndFlush(new UpdatePlayerClientBoundFrame(210.0,
                                                player.getMId(), player.getClazz(), player.getX(),
                                                player.getY(), player.getName() + "|"));
                                    });
                            //Setup the old character status and go ingame
                            channel.writeAndFlush(
                                    new UpdatePlayerClientBoundFrame(210.0, event.getPlayer().getMId(),
                                            event.getPlayer().getClazz(), event.getPlayer().getX(),
                                            event.getPlayer().getY(), event.getPlayer().getName() + "|"));
                            channel.writeAndFlush(new CrewChoiceClientBoundFrame(0.0, 0.0, (short) 2));
                            channel.writeAndFlush(
                                    new TransportClientBoundFrame(0.0, 0.0, 23.0, event.getPlayer().getX(),
                                            event.getPlayer().getY(), 2440.0, 832.0, (byte) 0));
                            //We have to update the positions of the other players if we join mid game
                            server.getPlayers().entrySet().stream()
                                    .filter(entry -> !entry.getValue().equals(event.getPlayer()))
                                    .forEach(entry -> {
                                        Player player = entry.getValue();
                                        channel.writeAndFlush(new PositionInfoClientBoundFrame(167.0,
                                                player.getMId(), player.getX(), player.getY(), (byte) 0,
                                                (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0));

                                    });
                            //We also update the positions of the other disconnected players
                            server.getDisconnectedPlayers().entrySet().stream()
                                    .filter(entry -> !entry.getValue().equals(event.getPlayer()))
                                    .forEach(entry -> {
                                        Player player = entry.getValue();
                                        channel.writeAndFlush(new PositionInfoClientBoundFrame(167.0,
                                                player.getMId(), player.getX(), player.getY(), (byte) 0,
                                                (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0));
                                    });
                        });
                return; // We won't remove the character selection if it was already set
            }
        }
        server.getLogger()
                .info(event.getPlayer().getName() + " changed class to " + event.getFrame().getClazz());
        event.getPlayer().setClazz(
                (event.getFrame().getClazz() != -1 ? CrewMember.values()[event.getFrame().getClazz()] : null));
        server.getChannels().stream().filter(channel -> !channel.attr(PLAYER).get().equals(event.getPlayer()))
                .forEach(channel -> {
                    // Object Index of 210 required (seems to be the index for player updates)
                    channel.writeAndFlush(new UpdatePlayerClientBoundFrame(210.0, event.getPlayer().getMId(),
                            event.getFrame().getClazz(), event.getFrame().getX(), event.getFrame().getY(),
                            event.getFrame().getName()));
                });
    } else if (msg instanceof LagPlayerServerBoundFrame) {
        PlayerLagEvent event = new PlayerLagEvent(sender);
        server.getEventManager().onEvent(event);
        getChannels().stream().filter(channel -> channel != ctx.channel())
                .forEach(channel -> channel
                        .writeAndFlush(new LagPlayerClientBoundFrame(event.getPlayer().getObjectIndex(),
                                event.getPlayer().getMId(), event.getPlayer().getName())));
    } else if (msg instanceof SetReadyServerBoundFrame) {
        SetReadyServerBoundFrame frame = (SetReadyServerBoundFrame) msg;
        PlayerReadyChangeEvent event = new PlayerReadyChangeEvent(sender, frame);
        server.getEventManager().onEvent(event);
        server.getLogger().info(event.getPlayer().getName() + " is ready!");
        server.getPlayers().get(event.getPlayer().getMId()).setReady(event.isReady());
        //Check if all players are ready
        boolean allReady = true;
        for (Map.Entry<Double, Player> entry : server.getPlayers().entrySet()) {
            if (!entry.getValue().isReady()) {
                allReady = false;
            }
        }
        if (ingame) { //When we are ingame, players have to take the slots of left players (Can't add new players)
            server.getChannels().stream()
                    .filter(channel -> channel.attr(PLAYER).get().equals(event.getPlayer()))
                    .forEach(channel -> {
                        channel.writeAndFlush(new CrewChoiceClientBoundFrame(0.0, 0.0, (short) 2));
                        channel.writeAndFlush(new TransportClientBoundFrame(0.0, 0.0, 23.0,
                                event.getPlayer().getX(), event.getPlayer().getY(), 2440.0, 832.0, (byte) 0));
                        //We have to update the positions of the other players if we join mid game
                        server.getChannels().stream().filter(
                                playerChannel -> !playerChannel.attr(PLAYER).get().equals(event.getPlayer()))
                                .forEach(playerChannel -> {
                                    Player player = playerChannel.attr(PLAYER).get();
                                    channel.writeAndFlush(new PositionInfoClientBoundFrame(167.0,
                                            player.getMId(), player.getX(), player.getY(), (byte) 0, (byte) 0,
                                            (byte) 0, (byte) 0, (byte) 0, (byte) 0));
                                });
                    });
        } else if (allReady) { //If all players are ready, we send the frames to start the game
            server.getLogger().info("All players are ready... game starting!");
            //Random random = new Random();
            server.getChannels().stream().forEach(channel -> {
                //Player player = channel.attr(PLAYER).get();
                //TODO: Level generation
                channel.writeAndFlush(new CrewChoiceClientBoundFrame(0.0, 0.0, (short) 2));
                //First double = 40 means lobby
                //Levels start at 18
                channel.writeAndFlush(
                        new TransportClientBoundFrame(0.0, 0.0, 23.0, 1216.0, 736.0, 2440.0, 832.0, (byte) 0));
                //channel.writeAndFlush(new TransportClientBoundFrame(0.0, 0.0, 23.0, 1216.0, 736.0, 2440.0, 832.0, (byte) 0));
            });
            this.ingame = true;
        } else { //Telling the other clients that someone pressed ready
            server.getChannels().stream()
                    .filter(channel -> !channel.attr(PLAYER).get().equals(event.getPlayer()))
                    .forEach(channel -> {
                        channel.writeAndFlush(new SetReadyClientBoundFrame(event.getPlayer().getObjectIndex(),
                                event.getPlayer().getMId(), (byte) (event.getPlayer().isReady() ? 1 : 0)));
                    });
        }
    } else if (msg instanceof PositionInfoServerBoundFrame) {
        PositionInfoServerBoundFrame frame = (PositionInfoServerBoundFrame) msg;
        PlayerPositionEvent event = new PlayerPositionEvent(sender, frame);
        server.getEventManager().onEvent(event);
        event.getPlayer().setX((int) event.getX());
        event.getPlayer().setY((int) event.getY());
        getChannels().stream().filter(channel -> !channel.attr(PLAYER).get().equals(event.getPlayer()))
                .forEach(channel -> {
                    // Object Index of 167 required (seems to be the index for position updates)
                    channel.writeAndFlush(new PositionInfoClientBoundFrame(167.0, event.getPlayer().getMId(),
                            event.getX(), event.getY(), event.isLeft() ? (byte) 1 : (byte) 0,
                            event.isRight() ? (byte) 1 : (byte) 0, event.isJump() ? (byte) 1 : (byte) 0,
                            event.isJumpHeld() ? (byte) 1 : (byte) 0, event.isUp() ? (byte) 1 : (byte) 0,
                            event.isDown() ? (byte) 1 : (byte) 0));
                });
    } else if (msg instanceof KeyPlayerServerBoundFrame) {
        KeyPlayerServerBoundFrame frame = (KeyPlayerServerBoundFrame) msg;
        PlayerKeyEvent event = new PlayerKeyEvent(sender, frame);
        server.getEventManager().onEvent(event);
        getChannels().stream().filter(channel -> !channel.attr(PLAYER).get().equals(event.getPlayer()))
                .forEach(channel -> {
                    //Object Index of 167 required (seems to be the index for position updates)
                    channel.writeAndFlush(new KeyPlayerClientBoundFrame(167.0, event.getPlayer().getMId(),
                            event.getFrame().getX(), event.getFrame().getY(), event.getFrame().getZAction(),
                            event.getFrame().getXAction(), event.getFrame().getCAction(),
                            event.getFrame().getVAction(), event.getFrame().getItemUsed(),
                            event.getFrame().getUnknown()));
                });
    } else {
        server.getLogger().info(msg.getClass().getSimpleName());
    }

    //        if (msg instanceof ByteBuf) {
    //            ByteBuf buf = (ByteBuf) msg;
    //            byte[] bytes = new byte[buf.readableBytes()];
    //            buf.readBytes(bytes);
    //            System.out.println(join(bytes, ", "));
    //            if (bytes.length > 12) {
    //                byte id = bytes[12];
    //                byte length = (byte) Math.min(bytes[8], bytes.length - 8);
    //                byte[] data = new byte[length];
    //                System.arraycopy(bytes, bytes.length - length, data, 0, length);
    //                System.out.printf("id: %d\nlength: %d\ndata: %s\n\n", id, length, join(data, ", "));
    //                handlePacket(ctx, id, data);
    //            }
    //        }
}

From source file:io.grpc.alts.internal.AltsProtocolNegotiatorTest.java

License:Apache License

@Test
public void unprotectLargeIncomingFrame() throws Exception {

    // We use a server frameprotector with twice the standard frame size.
    int serverFrameSize = 4096 * 2;
    // This should fit into one frame.
    byte[] unprotectedBytes = new byte[serverFrameSize - 500];
    Arrays.fill(unprotectedBytes, (byte) 7);
    ByteBuf unprotectedData = Unpooled.wrappedBuffer(unprotectedBytes);
    unprotectedData.writerIndex(unprotectedBytes.length);

    // Perform handshake.
    doHandshake();/*from  w  w  w  . j  ava 2s .  co m*/

    // Protect the message on the server.
    TsiFrameProtector serverProtector = serverHandshaker.createFrameProtector(serverFrameSize, channel.alloc());
    serverProtector.protectFlush(Collections.singletonList(unprotectedData), new Consumer<ByteBuf>() {
        @Override
        public void accept(ByteBuf buf) {
            channel.writeInbound(buf);
        }
    }, channel.alloc());
    channel.flushInbound();

    // Read the protected message at the client and verify that it matches the original message.
    assertEquals(1, channel.inboundMessages().size());

    ByteBuf receivedData1 = channel.readInbound();
    int receivedLen1 = receivedData1.readableBytes();
    byte[] receivedBytes = new byte[receivedLen1];
    receivedData1.readBytes(receivedBytes, 0, receivedLen1);

    assertThat(unprotectedBytes.length).isEqualTo(receivedBytes.length);
    assertThat(unprotectedBytes).isEqualTo(receivedBytes);
}

From source file:io.grpc.alts.internal.TsiTest.java

License:Apache License

/** Sends a message between the sender and receiver. */
private static void sendMessage(TsiFrameProtector sender, TsiFrameProtector receiver, int recvFragmentSize,
        String message, RegisterRef ref) throws GeneralSecurityException {

    ByteBuf plaintextBuffer = Unpooled.wrappedBuffer(message.getBytes(UTF_8));
    final List<ByteBuf> protectOut = new ArrayList<>();
    List<Object> unprotectOut = new ArrayList<>();

    sender.protectFlush(Collections.singletonList(plaintextBuffer), new Consumer<ByteBuf>() {
        @Override//from   w w w. j a  v  a 2s  .  c o m
        public void accept(ByteBuf buf) {
            protectOut.add(buf);
        }
    }, alloc);
    assertThat(protectOut.size()).isEqualTo(1);

    ByteBuf protect = ref.register(protectOut.get(0));
    while (protect.isReadable()) {
        ByteBuf buf = protect;
        if (recvFragmentSize > 0) {
            int size = Math.min(protect.readableBytes(), recvFragmentSize);
            buf = protect.readSlice(size);
        }
        receiver.unprotect(buf, unprotectOut, alloc);
    }
    ByteBuf plaintextRecvd = getDirectBuffer(message.getBytes(UTF_8).length, ref);
    for (Object unprotect : unprotectOut) {
        ByteBuf unprotectBuf = ref.register((ByteBuf) unprotect);
        plaintextRecvd.writeBytes(unprotectBuf);
    }
    assertThat(plaintextRecvd).isEqualTo(Unpooled.wrappedBuffer(message.getBytes(UTF_8)));
}

From source file:io.grpc.alts.internal.TsiTest.java

License:Apache License

/** Test corrupted counter. */
public static void corruptedCounterTest(Handshakers handshakers, RegisterRef ref)
        throws GeneralSecurityException {
    performHandshake(DEFAULT_TRANSPORT_BUFFER_SIZE, handshakers);

    TsiFrameProtector sender = handshakers.getClient().createFrameProtector(alloc);
    TsiFrameProtector receiver = handshakers.getServer().createFrameProtector(alloc);

    String message = "hello world";
    ByteBuf plaintextBuffer = Unpooled.wrappedBuffer(message.getBytes(UTF_8));
    final List<ByteBuf> protectOut = new ArrayList<>();
    List<Object> unprotectOut = new ArrayList<>();

    sender.protectFlush(Collections.singletonList(plaintextBuffer), new Consumer<ByteBuf>() {
        @Override//ww  w .ja v a2 s.  c  o  m
        public void accept(ByteBuf buf) {
            protectOut.add(buf);
        }
    }, alloc);
    assertThat(protectOut.size()).isEqualTo(1);

    ByteBuf protect = ref.register(protectOut.get(0));
    // Unprotect once to increase receiver counter.
    receiver.unprotect(protect.slice(), unprotectOut, alloc);
    assertThat(unprotectOut.size()).isEqualTo(1);
    ref.register((ByteBuf) unprotectOut.get(0));

    try {
        receiver.unprotect(protect, unprotectOut, alloc);
        fail("Exception expected");
    } catch (AEADBadTagException ex) {
        assertThat(ex).hasMessageThat().contains(DECRYPTION_FAILURE_RE);
    }

    sender.destroy();
    receiver.destroy();
}

From source file:io.grpc.alts.internal.TsiTest.java

License:Apache License

/** Test corrupted ciphertext. */
public static void corruptedCiphertextTest(Handshakers handshakers, RegisterRef ref)
        throws GeneralSecurityException {
    performHandshake(DEFAULT_TRANSPORT_BUFFER_SIZE, handshakers);

    TsiFrameProtector sender = handshakers.getClient().createFrameProtector(alloc);
    TsiFrameProtector receiver = handshakers.getServer().createFrameProtector(alloc);

    String message = "hello world";
    ByteBuf plaintextBuffer = Unpooled.wrappedBuffer(message.getBytes(UTF_8));
    final List<ByteBuf> protectOut = new ArrayList<>();
    List<Object> unprotectOut = new ArrayList<>();

    sender.protectFlush(Collections.singletonList(plaintextBuffer), new Consumer<ByteBuf>() {
        @Override/*from  w  w  w. j av  a 2s.co m*/
        public void accept(ByteBuf buf) {
            protectOut.add(buf);
        }
    }, alloc);
    assertThat(protectOut.size()).isEqualTo(1);

    ByteBuf protect = ref.register(protectOut.get(0));
    int ciphertextIdx = protect.writerIndex() - FakeChannelCrypter.getTagBytes() - 2;
    protect.setByte(ciphertextIdx, protect.getByte(ciphertextIdx) + 1);

    try {
        receiver.unprotect(protect, unprotectOut, alloc);
        fail("Exception expected");
    } catch (AEADBadTagException ex) {
        assertThat(ex).hasMessageThat().contains(DECRYPTION_FAILURE_RE);
    }

    sender.destroy();
    receiver.destroy();
}

From source file:io.grpc.alts.internal.TsiTest.java

License:Apache License

/** Test corrupted tag. */
public static void corruptedTagTest(Handshakers handshakers, RegisterRef ref) throws GeneralSecurityException {
    performHandshake(DEFAULT_TRANSPORT_BUFFER_SIZE, handshakers);

    TsiFrameProtector sender = handshakers.getClient().createFrameProtector(alloc);
    TsiFrameProtector receiver = handshakers.getServer().createFrameProtector(alloc);

    String message = "hello world";
    ByteBuf plaintextBuffer = Unpooled.wrappedBuffer(message.getBytes(UTF_8));
    final List<ByteBuf> protectOut = new ArrayList<>();
    List<Object> unprotectOut = new ArrayList<>();

    sender.protectFlush(Collections.singletonList(plaintextBuffer), new Consumer<ByteBuf>() {
        @Override//from w w  w  .  jav a 2  s .  co m
        public void accept(ByteBuf buf) {
            protectOut.add(buf);
        }
    }, alloc);
    assertThat(protectOut.size()).isEqualTo(1);

    ByteBuf protect = ref.register(protectOut.get(0));
    int tagIdx = protect.writerIndex() - 1;
    protect.setByte(tagIdx, protect.getByte(tagIdx) + 1);

    try {
        receiver.unprotect(protect, unprotectOut, alloc);
        fail("Exception expected");
    } catch (AEADBadTagException ex) {
        assertThat(ex).hasMessageThat().contains(DECRYPTION_FAILURE_RE);
    }

    sender.destroy();
    receiver.destroy();
}

From source file:io.grpc.alts.internal.TsiTest.java

License:Apache License

/** Test reflected ciphertext. */
public static void reflectedCiphertextTest(Handshakers handshakers, RegisterRef ref)
        throws GeneralSecurityException {
    performHandshake(DEFAULT_TRANSPORT_BUFFER_SIZE, handshakers);

    TsiFrameProtector sender = handshakers.getClient().createFrameProtector(alloc);
    TsiFrameProtector receiver = handshakers.getServer().createFrameProtector(alloc);

    String message = "hello world";
    ByteBuf plaintextBuffer = Unpooled.wrappedBuffer(message.getBytes(UTF_8));
    final List<ByteBuf> protectOut = new ArrayList<>();
    List<Object> unprotectOut = new ArrayList<>();

    sender.protectFlush(Collections.singletonList(plaintextBuffer), new Consumer<ByteBuf>() {
        @Override/*from w w  w .  j  av  a2s .  c o m*/
        public void accept(ByteBuf buf) {
            protectOut.add(buf);
        }
    }, alloc);
    assertThat(protectOut.size()).isEqualTo(1);

    ByteBuf protect = ref.register(protectOut.get(0));
    try {
        sender.unprotect(protect.slice(), unprotectOut, alloc);
        fail("Exception expected");
    } catch (AEADBadTagException ex) {
        assertThat(ex).hasMessageThat().contains(DECRYPTION_FAILURE_RE);
    }

    sender.destroy();
    receiver.destroy();
}

From source file:io.grpc.netty.NettyClientStreamTest.java

License:Apache License

private ByteBuf simpleGrpcFrame() {
    return Unpooled.wrappedBuffer(new byte[] { 0, 0, 0, 0, 2, 3, 14 });
}