Example usage for io.netty.buffer ByteBuf retainedSlice

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

Introduction

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

Prototype

public abstract ByteBuf retainedSlice(int index, int length);

Source Link

Document

Returns a retained slice of this buffer's sub-region.

Usage

From source file:com.chat.common.netty.handler.decode.LengthFieldBasedFrameDecoder.java

License:Apache License

/**
 * Extract the sub-region of the specified buffer.
 * <p>//from www. ja va  2 s  . c  o  m
 * If you are sure that the frame and its content are not accessed after
 * the current {@link #decode(ChannelHandlerContext, ByteBuf)}
 * call returns, you can even avoid memory copy by returning the sliced
 * sub-region (i.e. <tt>return buffer.slice(index, length)</tt>).
 * It's often useful when you convert the extracted frame into an object.
 * Refer to the source code of {@link ObjectDecoder} to see how this method
 * is overridden to avoid memory copy.
 */
protected ByteBuf extractFrame(ChannelHandlerContext ctx, ByteBuf buffer, int index, int length) {
    return buffer.retainedSlice(index, length);
}

From source file:com.linecorp.armeria.internal.Http1ObjectEncoder.java

License:Apache License

private static ByteBuf dataChunk(HttpData data, int offset, int chunkSize) {
    if (data instanceof ByteBufHolder) {
        final ByteBuf buf = ((ByteBufHolder) data).content();
        return buf.retainedSlice(offset, chunkSize);
    } else {/*from   ww  w .ja  v  a2s  . c om*/
        return Unpooled.wrappedBuffer(data.array(), offset, chunkSize);
    }
}

From source file:io.airlift.drift.transport.netty.codec.TestHeaderTransport.java

License:Apache License

@Test
public void testTryDecodeSequenceId() throws Exception {
    try (TestingPooledByteBufAllocator allocator = new TestingPooledByteBufAllocator()) {
        ByteBuf message = createTestFrame(allocator, "method", CALL, 0xFFAA, BINARY, true);
        try {/*from   w  ww  .j  a  va2s.c o  m*/
            assertDecodeFrameInfo(message.retainedSlice(0, 0), Optional.empty());
            assertDecodeFrameInfo(message.retainedSlice(0, 1), Optional.empty());
            assertDecodeFrameInfo(message.retainedSlice(0, 5), Optional.empty());
            assertDecodeFrameInfo(message.retainedSlice(0, 10), Optional.empty());
            assertDecodeFrameInfo(message.retainedSlice(0, 15), Optional.empty());
            assertDecodeFrameInfo(message.retainedDuplicate(),
                    Optional.of(new FrameInfo("method", CALL, 0xFFAA, HEADER, BINARY, true)));
        } finally {
            message.release();
        }
        assertDecodeFrameInfo(createTestFrame(allocator, "method1", ONEWAY, 123, FB_COMPACT, false),
                Optional.of(new FrameInfo("method1", ONEWAY, 123, HEADER, FB_COMPACT, false)));
    }
}

From source file:io.airlift.drift.transport.netty.codec.ThriftFramedDecoder.java

License:Apache License

private Optional<ByteBuf> decode(ByteBuf buffer) {
    if (bytesToDiscard > 0) {
        discardTooLongFrame(buffer);/* w w  w  .j ava 2s. c om*/
        return Optional.empty();
    }

    int initialReaderIndex = buffer.readerIndex();

    if (buffer.readableBytes() < Integer.BYTES) {
        return Optional.empty();
    }
    long frameSizeInBytes = buffer.readUnsignedInt();

    if (frameSizeInBytes > maxFrameSizeInBytes) {
        // this invocation doesn't move the readerIndex
        Optional<FrameInfo> frameInfo = frameInfoDecoder.tryDecodeFrameInfo(buffer);
        if (frameInfo.isPresent()) {
            tooLongFrameInfo = frameInfo;
            tooLongFrameSizeInBytes = frameSizeInBytes;
            bytesToDiscard = frameSizeInBytes;
            discardTooLongFrame(buffer);
            return Optional.empty();
        }
        // Basic frame info cannot be decoded and the max frame size is already exceeded.
        // Instead of waiting forever, fail without providing the sequence ID.
        if (buffer.readableBytes() >= maxFrameSizeInBytes) {
            tooLongFrameInfo = Optional.empty();
            tooLongFrameSizeInBytes = frameSizeInBytes;
            bytesToDiscard = frameSizeInBytes;
            discardTooLongFrame(buffer);
            return Optional.empty();
        }
        buffer.readerIndex(initialReaderIndex);
        return Optional.empty();
    }

    if (buffer.readableBytes() >= frameSizeInBytes) {
        // toIntExact must be safe, as frameSizeInBytes <= maxFrameSize
        ByteBuf frame = buffer.retainedSlice(buffer.readerIndex(), toIntExact(frameSizeInBytes));
        buffer.readerIndex(buffer.readerIndex() + toIntExact(frameSizeInBytes));
        return Optional.of(frame);
    }

    buffer.readerIndex(initialReaderIndex);
    return Optional.empty();
}

From source file:org.apache.bookkeeper.statelib.impl.mvcc.MVCCRecordCoder.java

License:Apache License

@Override
public MVCCRecord decode(ByteBuf data) {
    ByteBuf copy = data.slice();

    int metaLen = copy.readInt();
    ByteBuffer metaBuf = copy.slice(copy.readerIndex(), metaLen).nioBuffer();
    KeyMeta meta;// www. java 2s . com
    try {
        meta = KeyMeta.parseFrom(metaBuf);
    } catch (InvalidProtocolBufferException e) {
        throw new StateStoreRuntimeException("Failed to deserialize key metadata", e);
    }
    copy.skipBytes(metaLen);
    int valLen = copy.readInt();
    ByteBuf valBuf = copy.retainedSlice(copy.readerIndex(), valLen);

    MVCCRecord record = MVCCRecord.newRecord();
    record.setCreateRev(meta.getCreateRevision());
    record.setModRev(meta.getModRevision());
    record.setVersion(meta.getVersion());
    record.setValue(valBuf, meta.getValueType());
    return record;
}

From source file:org.apache.distributedlog.LogRecord.java

License:Apache License

protected void readPayload(ByteBuf in, boolean copyData) throws IOException {
    int length = in.readInt();
    if (length < 0) {
        throw new EOFException("Log Record is corrupt: Negative length " + length);
    }/*from ww w.  ja  v a  2s  . c om*/
    if (copyData) {
        setPayloadBuf(in.slice(in.readerIndex(), length), true);
    } else {
        setPayloadBuf(in.retainedSlice(in.readerIndex(), length), false);
    }
    in.skipBytes(length);
}

From source file:org.apache.hadoop.hbase.security.SaslChallengeDecoder.java

License:Apache License

private ByteBuf tryDecodeChallenge(ByteBuf in, int offset, int readableBytes) throws IOException {
    if (readableBytes < 4) {
        return null;
    }//from   w  w w. j  a  va 2  s .c  o  m
    int len = in.getInt(offset);
    if (len <= 0) {
        // fall back to simple
        in.readerIndex(offset + 4);
        return in.retainedSlice(offset, 4);
    }
    if (len > MAX_CHALLENGE_SIZE) {
        throw new IOException("Sasl challenge too large(" + len + "), max allowed is " + MAX_CHALLENGE_SIZE);
    }
    int totalLen = 4 + len;
    if (readableBytes < totalLen) {
        return null;
    }
    in.readerIndex(offset + totalLen);
    return in.retainedSlice(offset, totalLen);
}

From source file:org.apache.pulsar.broker.service.PersistentDispatcherFailoverConsumerTest.java

License:Apache License

@BeforeMethod
public void setup() throws Exception {
    ServiceConfiguration svcConfig = spy(new ServiceConfiguration());
    PulsarService pulsar = spy(new PulsarService(svcConfig));
    doReturn(svcConfig).when(pulsar).getConfiguration();

    mlFactoryMock = mock(ManagedLedgerFactory.class);
    doReturn(mlFactoryMock).when(pulsar).getManagedLedgerFactory();

    ZooKeeper mockZk = createMockZooKeeper();
    doReturn(mockZk).when(pulsar).getZkClient();
    doReturn(createMockBookKeeper(mockZk, pulsar.getOrderedExecutor().chooseThread(0))).when(pulsar)
            .getBookKeeperClient();/*from www .  j  a  va2  s  .  co  m*/

    configCacheService = mock(ConfigurationCacheService.class);
    @SuppressWarnings("unchecked")
    ZooKeeperDataCache<Policies> zkDataCache = mock(ZooKeeperDataCache.class);
    LocalZooKeeperCacheService zkCache = mock(LocalZooKeeperCacheService.class);
    doReturn(CompletableFuture.completedFuture(Optional.empty())).when(zkDataCache).getAsync(any());
    doReturn(zkDataCache).when(zkCache).policiesCache();
    doReturn(zkDataCache).when(configCacheService).policiesCache();
    doReturn(configCacheService).when(pulsar).getConfigurationCache();
    doReturn(zkCache).when(pulsar).getLocalZkCacheService();

    brokerService = spy(new BrokerService(pulsar));
    doReturn(brokerService).when(pulsar).getBrokerService();

    consumerChanges = new LinkedBlockingQueue<>();
    this.channelCtx = mock(ChannelHandlerContext.class);
    doAnswer(invocationOnMock -> {
        ByteBuf buf = invocationOnMock.getArgumentAt(0, ByteBuf.class);

        ByteBuf cmdBuf = buf.retainedSlice(4, buf.writerIndex() - 4);
        try {
            int cmdSize = (int) cmdBuf.readUnsignedInt();
            int writerIndex = cmdBuf.writerIndex();
            cmdBuf.writerIndex(cmdBuf.readerIndex() + cmdSize);
            ByteBufCodedInputStream cmdInputStream = ByteBufCodedInputStream.get(cmdBuf);

            BaseCommand.Builder cmdBuilder = BaseCommand.newBuilder();
            BaseCommand cmd = cmdBuilder.mergeFrom(cmdInputStream, null).build();
            cmdBuilder.recycle();
            cmdBuf.writerIndex(writerIndex);
            cmdInputStream.recycle();

            if (cmd.hasActiveConsumerChange()) {
                consumerChanges.put(cmd.getActiveConsumerChange());
            }
            cmd.recycle();
        } finally {
            cmdBuf.release();
        }

        return null;
    }).when(channelCtx).writeAndFlush(any(), any());

    serverCnx = spy(new ServerCnx(pulsar));
    doReturn(true).when(serverCnx).isActive();
    doReturn(true).when(serverCnx).isWritable();
    doReturn(new InetSocketAddress("localhost", 1234)).when(serverCnx).clientAddress();
    when(serverCnx.getRemoteEndpointProtocolVersion()).thenReturn(ProtocolVersion.v12.getNumber());
    when(serverCnx.ctx()).thenReturn(channelCtx);

    serverCnxWithOldVersion = spy(new ServerCnx(pulsar));
    doReturn(true).when(serverCnxWithOldVersion).isActive();
    doReturn(true).when(serverCnxWithOldVersion).isWritable();
    doReturn(new InetSocketAddress("localhost", 1234)).when(serverCnxWithOldVersion).clientAddress();
    when(serverCnxWithOldVersion.getRemoteEndpointProtocolVersion())
            .thenReturn(ProtocolVersion.v11.getNumber());
    when(serverCnxWithOldVersion.ctx()).thenReturn(channelCtx);

    NamespaceService nsSvc = mock(NamespaceService.class);
    doReturn(nsSvc).when(pulsar).getNamespaceService();
    doReturn(true).when(nsSvc).isServiceUnitOwned(any(NamespaceBundle.class));
    doReturn(true).when(nsSvc).isServiceUnitActive(any(TopicName.class));

    setupMLAsyncCallbackMocks();

}

From source file:org.elasticsearch.http.nio.HttpReadWriteHandlerTests.java

License:Apache License

public void testSuccessfulDecodeHttpRequest() throws IOException {
    String uri = "localhost:9090/" + randomAlphaOfLength(8);
    io.netty.handler.codec.http.HttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
            HttpMethod.GET, uri);// w  w w.ja v a 2 s  .  c  o  m

    ByteBuf buf = requestEncoder.encode(httpRequest);
    int slicePoint = randomInt(buf.writerIndex() - 1);
    ByteBuf slicedBuf = buf.retainedSlice(0, slicePoint);
    ByteBuf slicedBuf2 = buf.retainedSlice(slicePoint, buf.writerIndex());
    try {
        handler.consumeReads(toChannelBuffer(slicedBuf));

        verify(transport, times(0)).incomingRequest(any(HttpRequest.class), any(NioHttpChannel.class));

        handler.consumeReads(toChannelBuffer(slicedBuf2));

        ArgumentCaptor<HttpRequest> requestCaptor = ArgumentCaptor.forClass(HttpRequest.class);
        verify(transport).incomingRequest(requestCaptor.capture(), any(NioHttpChannel.class));

        HttpRequest nioHttpRequest = requestCaptor.getValue();
        assertEquals(HttpRequest.HttpVersion.HTTP_1_1, nioHttpRequest.protocolVersion());
        assertEquals(RestRequest.Method.GET, nioHttpRequest.method());
    } finally {
        handler.close();
        buf.release();
        slicedBuf.release();
        slicedBuf2.release();
    }
}