Example usage for io.netty.channel FileRegion count

List of usage examples for io.netty.channel FileRegion count

Introduction

In this page you can find the example usage for io.netty.channel FileRegion count.

Prototype

long count();

Source Link

Document

Returns the number of bytes to transfer.

Usage

From source file:com.heliosapm.webrpc.jsonservice.services.InvocationChannel.java

License:Apache License

/**
 * {@inheritDoc}//w  w w .java2  s.c  o m
 * @see io.netty.channel.ChannelOutboundInvoker#write(java.lang.Object)
 */
@Override
public ChannelFuture write(Object message) {
    if (message != null) {
        if (message instanceof FileRegion) {
            try {
                Pipe pipe = Pipe.open();
                FileRegion fr = (FileRegion) message;

                long bytesToRead = fr.count();
                fr.transferTo(pipe.sink(), 0L);
                byte[] content = new byte[(int) bytesToRead];
                pipe.source().read(ByteBuffer.wrap(content));
                channelWrites.add(content);
            } catch (Exception ex) {
                log.error("Failed to read content from pipe", ex);
                channelWrites.add(ex);
            }
        } else {
            channelWrites.add(message);
        }
        log.info("Received Channel Write [{}]  type:[{}]", message, message.getClass().getName());
    }

    return null;
}

From source file:org.apache.rocketmq.remoting.netty.FileRegionEncoder.java

License:Apache License

/**
 * Encode a message into a {@link io.netty.buffer.ByteBuf}. This method will be called for each written message that
 * can be handled by this encoder./* www  . j  a  va  2s  .  c om*/
 *
 * @param ctx the {@link io.netty.channel.ChannelHandlerContext} which this {@link
 * io.netty.handler.codec.MessageToByteEncoder} belongs to
 * @param msg the message to encode
 * @param out the {@link io.netty.buffer.ByteBuf} into which the encoded message will be written
 * @throws Exception is thrown if an error occurs
 */
@Override
protected void encode(ChannelHandlerContext ctx, FileRegion msg, final ByteBuf out) throws Exception {
    WritableByteChannel writableByteChannel = new WritableByteChannel() {
        @Override
        public int write(ByteBuffer src) throws IOException {
            out.writeBytes(src);
            return out.capacity();
        }

        @Override
        public boolean isOpen() {
            return true;
        }

        @Override
        public void close() throws IOException {
        }
    };

    long toTransfer = msg.count();

    while (true) {
        long transferred = msg.transfered();
        if (toTransfer - transferred <= 0) {
            break;
        }
        msg.transferTo(writableByteChannel, transferred);
    }
}

From source file:org.apache.rocketmq.remoting.netty.FileRegionEncoderTest.java

License:Apache License

/**
 * This unit test case ensures that {@link FileRegionEncoder} indeed wraps {@link FileRegion} to
 * {@link ByteBuf}./*from w  ww  . ja  va 2s  .c o  m*/
 * @throws IOException if there is an error.
 */
@Test
public void testEncode() throws IOException {
    FileRegionEncoder fileRegionEncoder = new FileRegionEncoder();
    EmbeddedChannel channel = new EmbeddedChannel(fileRegionEncoder);
    File file = File.createTempFile(UUID.randomUUID().toString(), ".data");
    file.deleteOnExit();
    Random random = new Random(System.currentTimeMillis());
    int dataLength = 1 << 10;
    byte[] data = new byte[dataLength];
    random.nextBytes(data);
    write(file, data);
    FileRegion fileRegion = new DefaultFileRegion(file, 0, dataLength);
    Assert.assertEquals(0, fileRegion.transfered());
    Assert.assertEquals(dataLength, fileRegion.count());
    Assert.assertTrue(channel.writeOutbound(fileRegion));
    ByteBuf out = (ByteBuf) channel.readOutbound();
    byte[] arr = new byte[out.readableBytes()];
    out.getBytes(0, arr);
    Assert.assertArrayEquals("Data should be identical", data, arr);
}

From source file:org.apache.spark.network.crypto.AuthEngineSuite.java

License:Apache License

@Test
public void testEncryptedMessageWhenTransferringZeroBytes() throws Exception {
    AuthEngine client = new AuthEngine("appId", "secret", conf);
    AuthEngine server = new AuthEngine("appId", "secret", conf);
    try {//from w ww  .  j  a  v a2  s.co  m
        ClientChallenge clientChallenge = client.challenge();
        ServerResponse serverResponse = server.respond(clientChallenge);
        client.validate(serverResponse);

        TransportCipher cipher = server.sessionCipher();
        TransportCipher.EncryptionHandler handler = new TransportCipher.EncryptionHandler(cipher);

        int testDataLength = 4;
        FileRegion region = mock(FileRegion.class);
        when(region.count()).thenReturn((long) testDataLength);
        // Make `region.transferTo` do nothing in first call and transfer 4 bytes in the second one.
        when(region.transferTo(any(), anyLong())).thenAnswer(new Answer<Long>() {

            private boolean firstTime = true;

            @Override
            public Long answer(InvocationOnMock invocationOnMock) throws Throwable {
                if (firstTime) {
                    firstTime = false;
                    return 0L;
                } else {
                    WritableByteChannel channel = invocationOnMock.getArgument(0);
                    channel.write(ByteBuffer.wrap(new byte[testDataLength]));
                    return (long) testDataLength;
                }
            }
        });

        TransportCipher.EncryptedMessage emsg = handler.createEncryptedMessage(region);
        ByteArrayWritableChannel channel = new ByteArrayWritableChannel(testDataLength);
        // "transferTo" should act correctly when the underlying FileRegion transfers 0 bytes.
        assertEquals(0L, emsg.transferTo(channel, emsg.transfered()));
        assertEquals(testDataLength, emsg.transferTo(channel, emsg.transfered()));
        assertEquals(emsg.transfered(), emsg.count());
        assertEquals(4, channel.length());
    } finally {
        client.close();
        server.close();
    }
}