Example usage for io.netty.channel.embedded EmbeddedChannel writeInbound

List of usage examples for io.netty.channel.embedded EmbeddedChannel writeInbound

Introduction

In this page you can find the example usage for io.netty.channel.embedded EmbeddedChannel writeInbound.

Prototype

public boolean writeInbound(Object... msgs) 

Source Link

Document

Write messages to the inbound of this Channel .

Usage

From source file:alluxio.client.block.stream.NettyPacketReaderTest.java

License:Apache License

/**
 * Sends read responses to the channel.// w  ww  .j  a v  a  2 s . c om
 *
 * @param channel the channel
 * @param length the length
 * @param start the start position to calculate the checksum
 * @param end the end position to calculate the checksum
 * @return the checksum
 */
private Future<Long> sendReadResponses(final EmbeddedChannel channel, final long length, final long start,
        final long end) {
    return EXECUTOR.submit(new Callable<Long>() {
        @Override
        public Long call() {
            long checksum = 0;
            long pos = 0;

            long remaining = length;
            while (remaining > 0) {
                int bytesToSend = (int) Math.min(remaining, PACKET_SIZE);
                byte[] data = new byte[bytesToSend];
                RANDOM.nextBytes(data);
                ByteBuf buf = Unpooled.wrappedBuffer(data);
                RPCProtoMessage message = RPCProtoMessage.createOkResponse(new DataNettyBufferV2(buf));
                channel.writeInbound(message);
                remaining -= bytesToSend;

                for (int i = 0; i < data.length; i++) {
                    if (pos >= start && pos <= end) {
                        checksum += BufferUtils.byteToInt(data[i]);
                    }
                    pos++;
                }
            }

            // send EOF.
            channel.writeInbound(RPCProtoMessage.createOkResponse(null));
            return checksum;
        }
    });
}

From source file:alluxio.client.block.stream.NettyPacketWriterTest.java

License:Apache License

/**
 * Verifies the packets written. After receiving the last packet, it will also send an EOF to
 * the channel./*from  www  .jav  a  2  s.co m*/
 *
 * @param checksumStart the start position to calculate the checksum
 * @param checksumEnd the end position to calculate the checksum
 * @return the checksum of the data read starting from checksumStart
 */
private Future<Long> verifyWriteRequests(final EmbeddedChannel channel, final long checksumStart,
        final long checksumEnd) {
    return EXECUTOR.submit(new Callable<Long>() {
        @Override
        public Long call() {
            try {
                long checksum = 0;
                long pos = 0;
                while (true) {
                    RPCProtoMessage request = (RPCProtoMessage) CommonUtils.waitForResult("wrtie request",
                            new Function<Void, Object>() {
                                @Override
                                public Object apply(Void v) {
                                    return channel.readOutbound();
                                }
                            }, WaitForOptions.defaults().setTimeout(Constants.MINUTE_MS));
                    validateWriteRequest(request.getMessage().<Protocol.WriteRequest>getMessage(), pos);

                    DataBuffer buffer = request.getPayloadDataBuffer();
                    // Last packet.
                    if (buffer == null) {
                        channel.writeInbound(RPCProtoMessage.createOkResponse(null));
                        return checksum;
                    }
                    try {
                        Assert.assertTrue(buffer instanceof DataNettyBufferV2);
                        ByteBuf buf = (ByteBuf) buffer.getNettyOutput();
                        while (buf.readableBytes() > 0) {
                            if (pos >= checksumStart && pos <= checksumEnd) {
                                checksum += BufferUtils.byteToInt(buf.readByte());
                            } else {
                                buf.readByte();
                            }
                            pos++;
                        }
                    } finally {
                        buffer.release();
                    }
                }
            } catch (Throwable throwable) {
                LOG.error("Failed to verify write requests.", throwable);
                Assert.fail();
                throw throwable;
            }
        }
    });
}

From source file:alluxio.client.block.stream.UfsFallbackLocalFilePacketWriterTest.java

License:Apache License

/**
 * Verifies the packets written. After receiving the last packet, it will also send an EOF to
 * the channel./*from  w ww  . ja v  a2  s .co  m*/
 *
 * @return the checksum of the data read starting from checksumStart
 */
private Future<WriteSummary> getUfsWrite(final EmbeddedChannel channel) {
    return EXECUTOR.submit(new Callable<WriteSummary>() {
        @Override
        public WriteSummary call() throws TimeoutException, InterruptedException {
            try {
                long checksum = 0;
                long pos = 0;
                long len = 0;
                while (true) {
                    RPCProtoMessage request = (RPCProtoMessage) CommonUtils.waitForResult("write request",
                            () -> channel.readOutbound(),
                            WaitForOptions.defaults().setTimeoutMs(Constants.MINUTE_MS));
                    Protocol.WriteRequest writeRequest = request.getMessage().asWriteRequest();
                    validateWriteRequest(writeRequest, pos);
                    DataBuffer buffer = request.getPayloadDataBuffer();
                    // Last packet.
                    if (writeRequest.hasEof() && writeRequest.getEof()) {
                        assertTrue(buffer == null);
                        channel.writeInbound(RPCProtoMessage.createOkResponse(null));
                        return new WriteSummary(len, checksum);
                    }
                    // UFS block init
                    if (writeRequest.getCreateUfsBlockOptions().hasBytesInBlockStore()) {
                        assertTrue(buffer == null);
                        pos += writeRequest.getCreateUfsBlockOptions().getBytesInBlockStore();
                        continue;
                    }
                    try {
                        Assert.assertTrue(buffer instanceof DataNettyBufferV2);
                        ByteBuf buf = (ByteBuf) buffer.getNettyOutput();
                        while (buf.readableBytes() > 0) {
                            checksum += BufferUtils.byteToInt(buf.readByte());
                            pos++;
                            len++;
                        }
                    } finally {
                        buffer.release();
                    }
                }
            } catch (Throwable throwable) {
                fail("Failed to verify write requests." + throwable.getMessage());
                throw throwable;
            }
        }
    });
}

From source file:com.cloudera.livy.client.local.rpc.TestKryoMessageCodec.java

License:Apache License

@Test
public void testEmbeddedChannel() throws Exception {
    EmbeddedChannel c = new EmbeddedChannel(new LoggingHandler(getClass()), new KryoMessageCodec(0));
    c.writeAndFlush(MESSAGE);//from w  w  w. j  av  a  2s.c o  m
    assertEquals(1, c.outboundMessages().size());
    assertFalse(MESSAGE.getClass().equals(c.outboundMessages().peek().getClass()));
    c.writeInbound(c.readOutbound());
    assertEquals(1, c.inboundMessages().size());
    assertEquals(MESSAGE, c.readInbound());
    c.close();
}

From source file:com.cloudera.livy.client.local.rpc.TestRpc.java

License:Apache License

private void transfer(Rpc serverRpc, Rpc clientRpc) {
    EmbeddedChannel client = (EmbeddedChannel) clientRpc.getChannel();
    EmbeddedChannel server = (EmbeddedChannel) serverRpc.getChannel();

    int count = 0;
    while (!client.outboundMessages().isEmpty()) {
        server.writeInbound(client.readOutbound());
        count++;//from w  w  w. j a  v  a 2s. c  o  m
    }
    server.flush();
    LOG.debug("Transferred {} outbound client messages.", count);

    count = 0;
    while (!server.outboundMessages().isEmpty()) {
        client.writeInbound(server.readOutbound());
        count++;
    }
    client.flush();
    LOG.debug("Transferred {} outbound server messages.", count);
}

From source file:com.corundumstudio.socketio.transport.WebSocketTransportTest.java

License:Apache License

/**
 * Test method for {@link com.corundumstudio.socketio.transport.WebSocketTransport#channelRead()}.
 *///www  . ja v a  2s  .c o  m
@Test
public void testCloseFrame() {
    EmbeddedChannel channel = createChannel();

    channel.writeInbound(new CloseWebSocketFrame());
    Object msg = channel.readOutbound();

    // https://tools.ietf.org/html/rfc6455#section-5.5.1
    // If an endpoint receives a Close frame and did not previously send a Close frame, the endpoint
    // MUST send a Close frame in response.
    assertTrue(msg instanceof CloseWebSocketFrame);
}

From source file:com.couchbase.client.core.endpoint.AbstractGenericHandlerTest.java

License:Apache License

@Test(expected = CouchbaseException.class)
public void whenDecodeFailureShouldOnErrorFailureWrappedInCouchbaseException() {
    AbstractGenericHandler<Object, Object, GetDesignDocumentRequest> handler = createFakeHandler(
            new FakeHandlerDelegate<Object, Object, GetDesignDocumentRequest>() {
                @Override//from  ww w . ja v a2s.c o  m
                public Object encodeRequest(ChannelHandlerContext ctx, GetDesignDocumentRequest msg)
                        throws Exception {
                    return new Object();
                }

                @Override
                public CouchbaseResponse decodeResponse(ChannelHandlerContext ctx, Object msg)
                        throws Exception {
                    throw new IllegalStateException("this is fake");
                }
            });
    EmbeddedChannel channel = new EmbeddedChannel(handler);
    GetDesignDocumentRequest request = new GetDesignDocumentRequest("any", false, "bucket", "password");
    channel.writeOutbound(request);
    channel.writeInbound(new Object());

    try {
        request.observable().timeout(1, TimeUnit.SECONDS).toBlocking().last();
    } catch (CouchbaseException e) {
        assertNotNull(e.getCause());
        assertTrue(e.getCause() instanceof IllegalStateException);
        assertEquals("this is fake", e.getCause().getMessage());
        throw e;
    }
}

From source file:com.couchbase.client.core.endpoint.AbstractGenericHandlerTest.java

License:Apache License

@Test(expected = CouchbaseException.class)
public void whenDecodeFailureIsCouchbaseExceptionShouldOnErrorIt() {
    AbstractGenericHandler<Object, Object, GetDesignDocumentRequest> handler = createFakeHandler(
            new FakeHandlerDelegate<Object, Object, GetDesignDocumentRequest>() {
                @Override//  w  ww .  java 2s  .  c o m
                public Object encodeRequest(ChannelHandlerContext ctx, GetDesignDocumentRequest msg)
                        throws Exception {
                    return new Object();
                }

                @Override
                public CouchbaseResponse decodeResponse(ChannelHandlerContext ctx, Object msg)
                        throws Exception {
                    throw new CouchbaseException("this is fake");
                }
            });
    EmbeddedChannel channel = new EmbeddedChannel(handler);
    GetDesignDocumentRequest request = new GetDesignDocumentRequest("any", false, "bucket", "password");
    channel.writeOutbound(request);
    channel.writeInbound(new Object());

    try {
        request.observable().timeout(1, TimeUnit.SECONDS).toBlocking().last();
    } catch (CouchbaseException e) {
        assertNull(e.getCause());
        assertEquals("this is fake", e.getMessage());
        throw e;
    }
}

From source file:com.couchbase.client.core.endpoint.kv.KeyValueHandlerTest.java

License:Apache License

@Test
public void shouldFireKeepAlive() throws Exception {
    final AtomicInteger keepAliveEventCounter = new AtomicInteger();
    final AtomicReference<ChannelHandlerContext> ctxRef = new AtomicReference();

    KeyValueHandler testHandler = new KeyValueHandler(mock(AbstractEndpoint.class), eventSink, requestQueue,
            false) {//from   w w w .  ja  v a2 s  .  com

        @Override
        public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
            super.channelRegistered(ctx);
            ctxRef.compareAndSet(null, ctx);
        }

        @Override
        protected void onKeepAliveFired(ChannelHandlerContext ctx, CouchbaseRequest keepAliveRequest) {
            assertEquals(1, keepAliveEventCounter.incrementAndGet());
        }

        @Override
        protected void onKeepAliveResponse(ChannelHandlerContext ctx, CouchbaseResponse keepAliveResponse) {
            assertEquals(2, keepAliveEventCounter.incrementAndGet());
        }

        @Override
        protected CoreEnvironment env() {
            return DefaultCoreEnvironment.create();
        }
    };
    EmbeddedChannel channel = new EmbeddedChannel(testHandler);

    //test idle event triggers a k/v keepAlive request and hook is called
    testHandler.userEventTriggered(ctxRef.get(), IdleStateEvent.FIRST_READER_IDLE_STATE_EVENT);

    assertEquals(1, keepAliveEventCounter.get());
    assertTrue(requestQueue.peek() instanceof KeyValueHandler.KeepAliveRequest);
    KeyValueHandler.KeepAliveRequest keepAliveRequest = (KeyValueHandler.KeepAliveRequest) requestQueue.peek();

    //test responding to the request with memcached response is interpreted into a KeepAliveResponse, hook is called
    DefaultFullBinaryMemcacheResponse response = new DefaultFullBinaryMemcacheResponse(new byte[] {},
            Unpooled.EMPTY_BUFFER);
    response.setOpaque(keepAliveRequest.opaque());
    response.setStatus(KeyValueStatus.ERR_NO_MEM.code());

    channel.writeInbound(response);
    KeyValueHandler.KeepAliveResponse keepAliveResponse = keepAliveRequest.observable()
            .cast(KeyValueHandler.KeepAliveResponse.class).timeout(1, TimeUnit.SECONDS).toBlocking().single();

    assertEquals(2, keepAliveEventCounter.get());
    assertEquals(ResponseStatus.OUT_OF_MEMORY, keepAliveResponse.status());
}

From source file:com.couchbase.client.core.endpoint.view.ViewHandlerTest.java

License:Apache License

@Test
public void shouldFireKeepAlive() throws Exception {
    final AtomicInteger keepAliveEventCounter = new AtomicInteger();
    final AtomicReference<ChannelHandlerContext> ctxRef = new AtomicReference();

    ViewHandler testHandler = new ViewHandler(endpoint, responseRingBuffer, queue, false) {
        @Override// w w  w  . j a  v a2  s. c om
        public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
            super.channelRegistered(ctx);
            ctxRef.compareAndSet(null, ctx);
        }

        @Override
        protected void onKeepAliveFired(ChannelHandlerContext ctx, CouchbaseRequest keepAliveRequest) {
            assertEquals(1, keepAliveEventCounter.incrementAndGet());
        }

        @Override
        protected void onKeepAliveResponse(ChannelHandlerContext ctx, CouchbaseResponse keepAliveResponse) {
            assertEquals(2, keepAliveEventCounter.incrementAndGet());
        }
    };
    EmbeddedChannel channel = new EmbeddedChannel(testHandler);

    //test idle event triggers a view keepAlive request and hook is called
    testHandler.userEventTriggered(ctxRef.get(), IdleStateEvent.FIRST_READER_IDLE_STATE_EVENT);

    assertEquals(1, keepAliveEventCounter.get());
    assertTrue(queue.peek() instanceof ViewHandler.KeepAliveRequest);
    ViewHandler.KeepAliveRequest keepAliveRequest = (ViewHandler.KeepAliveRequest) queue.peek();

    //test responding to the request with http response is interpreted into a KeepAliveResponse and hook is called
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND);
    channel.writeInbound(response);
    ViewHandler.KeepAliveResponse keepAliveResponse = keepAliveRequest.observable()
            .cast(ViewHandler.KeepAliveResponse.class).timeout(1, TimeUnit.SECONDS).toBlocking().single();

    assertEquals(2, keepAliveEventCounter.get());
    assertEquals(ResponseStatus.NOT_EXISTS, keepAliveResponse.status());
    //different channel, needs to be closed to release the internal responseContent
    channel.close().awaitUninterruptibly();
}