List of usage examples for io.netty.buffer CompositeByteBuf slice
@Override public ByteBuf slice(int index, int length)
From source file:io.grpc.alts.internal.AltsProtocolNegotiatorTest.java
License:Apache License
@Test @SuppressWarnings("unchecked") // List cast public void protectShouldRoundtrip() throws Exception { doHandshake();// ww w .j av a 2 s . c om // Write the message 1 character at a time. The message should be buffered // and not interfere with the handshake. final AtomicInteger writeCount = new AtomicInteger(); String message = "hello"; for (int ix = 0; ix < message.length(); ++ix) { ByteBuf in = Unpooled.copiedBuffer(message, ix, 1, UTF_8); @SuppressWarnings("unused") // go/futurereturn-lsc Future<?> possiblyIgnoredError = channel.write(in).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { writeCount.incrementAndGet(); } } }); } channel.flush(); // Capture the protected data written to the wire. assertEquals(1, channel.outboundMessages().size()); ByteBuf protectedData = channel.readOutbound(); assertEquals(message.length(), writeCount.get()); // Read the protected message at the server and verify it matches the original message. TsiFrameProtector serverProtector = serverHandshaker.createFrameProtector(channel.alloc()); List<ByteBuf> unprotected = new ArrayList<>(); serverProtector.unprotect(protectedData, (List<Object>) (List<?>) unprotected, channel.alloc()); // We try our best to remove the HTTP2 handler as soon as possible, but just by constructing it // a settings frame is written (and an HTTP2 preface). This is hard coded into Netty, so we // have to remove it here. See {@code Http2ConnectionHandler.PrefaceDecode.sendPreface}. int settingsFrameLength = 9; CompositeByteBuf unprotectedAll = new CompositeByteBuf(channel.alloc(), false, unprotected.size() + 1, unprotected); ByteBuf unprotectedData = unprotectedAll.slice(settingsFrameLength, message.length()); assertEquals(message, unprotectedData.toString(UTF_8)); // Protect the same message at the server. final AtomicReference<ByteBuf> newlyProtectedData = new AtomicReference<>(); serverProtector.protectFlush(Collections.singletonList(unprotectedData), new Consumer<ByteBuf>() { @Override public void accept(ByteBuf buf) { newlyProtectedData.set(buf); } }, channel.alloc()); // Read the protected message at the client and verify that it matches the original message. channel.writeInbound(newlyProtectedData.get()); assertEquals(1, channel.inboundMessages().size()); assertEquals(message, channel.<ByteBuf>readInbound().toString(UTF_8)); }