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

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

Introduction

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

Prototype

@Override
    public boolean isActive() 

Source Link

Usage

From source file:com.github.ambry.rest.NettyMessageProcessorTest.java

License:Open Source License

/**
 * Tests for error handling flow when bad input streams are provided to the {@link NettyMessageProcessor}.
 *//*from   w w  w  . ja  va  2  s.  c  om*/
@Test
public void requestHandleWithBadInputTest() throws IOException {
    String content = "@@randomContent@@@";
    // content without request.
    EmbeddedChannel channel = createChannel();
    channel.writeInbound(new DefaultLastHttpContent(Unpooled.wrappedBuffer(content.getBytes())));
    HttpResponse response = (HttpResponse) channel.readOutbound();
    assertEquals("Unexpected response status", HttpResponseStatus.BAD_REQUEST, response.getStatus());

    // content without request on a channel that was kept alive
    channel = createChannel();
    // send and receive response for a good request and keep the channel alive
    channel.writeInbound(
            RestTestUtils.createRequest(HttpMethod.GET, MockBlobStorageService.ECHO_REST_METHOD, null));
    channel.writeInbound(LastHttpContent.EMPTY_LAST_CONTENT);
    response = (HttpResponse) channel.readOutbound();
    assertEquals("Unexpected response status", HttpResponseStatus.OK, response.getStatus());
    // drain the content
    while (channel.readOutbound() != null) {
        ;
    }
    assertTrue("Channel is not active", channel.isActive());
    // send content without request
    channel.writeInbound(LastHttpContent.EMPTY_LAST_CONTENT);
    response = (HttpResponse) channel.readOutbound();
    assertEquals("Unexpected response status", HttpResponseStatus.BAD_REQUEST, response.getStatus());

    // content when no content is expected.
    channel = createChannel();
    channel.writeInbound(RestTestUtils.createRequest(HttpMethod.GET, "/", null));
    channel.writeInbound(new DefaultLastHttpContent(Unpooled.wrappedBuffer(content.getBytes())));
    response = (HttpResponse) channel.readOutbound();
    assertEquals("Unexpected response status", HttpResponseStatus.BAD_REQUEST, response.getStatus());

    // wrong HTTPObject.
    channel = createChannel();
    channel.writeInbound(new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK));
    response = (HttpResponse) channel.readOutbound();
    assertEquals("Unexpected response status", HttpResponseStatus.BAD_REQUEST, response.getStatus());
}

From source file:com.github.ambry.rest.NettyResponseChannelTest.java

License:Open Source License

/**
 * Tests the common workflow of the {@link NettyResponseChannel} i.e., add some content to response body via
 * {@link NettyResponseChannel#write(ByteBuffer, Callback)} and then completes the response.
 * <p/>/*from   w  w  w. j ava 2  s. c om*/
 * For a description of what different URIs do, check {@link TestingUri}. For the actual functionality, check
 * {@link MockNettyMessageProcessor}).
 * @throws IOException
 */
@Test
public void commonCaseTest() throws IOException {
    String content = "@@randomContent@@@";
    String lastContent = "@@randomLastContent@@@";
    EmbeddedChannel channel = createEmbeddedChannel();
    AtomicLong requestIdGenerator = new AtomicLong(0);

    final int ITERATIONS = 5;
    for (int i = 0; i < 5; i++) {
        boolean isKeepAlive = i != (ITERATIONS - 1);
        String contentToSend = content + requestIdGenerator.getAndIncrement();
        HttpRequest httpRequest = RestTestUtils.createRequest(HttpMethod.POST, "/", null);
        HttpHeaders.setKeepAlive(httpRequest, isKeepAlive);
        channel.writeInbound(httpRequest);
        channel.writeInbound(createContent(contentToSend, false));
        channel.writeInbound(createContent(lastContent, true));
        // first outbound has to be response.
        HttpResponse response = (HttpResponse) channel.readOutbound();
        assertEquals("Unexpected response status", HttpResponseStatus.OK, response.getStatus());
        // content echoed back.
        String returnedContent = RestTestUtils.getContentString((HttpContent) channel.readOutbound());
        assertEquals("Content does not match with expected content", contentToSend, returnedContent);
        // last content echoed back.
        returnedContent = RestTestUtils.getContentString((HttpContent) channel.readOutbound());
        assertEquals("Content does not match with expected content", lastContent, returnedContent);
        assertTrue("Did not receive end marker", channel.readOutbound() instanceof LastHttpContent);
        assertEquals("Unexpected channel state on the server", isKeepAlive, channel.isActive());
    }
}

From source file:com.github.ambry.rest.NettyResponseChannelTest.java

License:Open Source License

/**
 * Checks the case where no body needs to be returned but just a
 * {@link RestResponseChannel#onResponseComplete(Exception)} is called on the server. This should return just
 * response metadata./*from   ww w .  j  a  v a  2s . co  m*/
 */
@Test
public void noResponseBodyTest() {
    EmbeddedChannel channel = createEmbeddedChannel();
    HttpRequest httpRequest = RestTestUtils.createRequest(HttpMethod.GET,
            TestingUri.ImmediateResponseComplete.toString(), null);
    HttpHeaders.setKeepAlive(httpRequest, false);
    channel.writeInbound(httpRequest);
    // There should be a response.
    HttpResponse response = (HttpResponse) channel.readOutbound();
    assertEquals("Unexpected response status", HttpResponseStatus.OK, response.getStatus());
    // Channel should be closed.
    assertFalse("Channel not closed on the server", channel.isActive());
}

From source file:com.github.ambry.rest.NettyResponseChannelTest.java

License:Open Source License

/**
 * Tests behaviour of various functions of {@link NettyResponseChannel} under write failures.
 * @throws Exception/* w w  w  .  j  av a  2  s. c  o m*/
 */
@Test
public void behaviourUnderWriteFailuresTest() throws Exception {
    onResponseCompleteUnderWriteFailureTest(TestingUri.ImmediateResponseComplete);
    onResponseCompleteUnderWriteFailureTest(TestingUri.OnResponseCompleteWithNonRestException);

    // writing to channel with a outbound handler that generates an Exception
    try {
        String content = "@@randomContent@@@";
        MockNettyMessageProcessor processor = new MockNettyMessageProcessor();
        ChannelOutboundHandler badOutboundHandler = new ExceptionOutboundHandler();
        EmbeddedChannel channel = new EmbeddedChannel(badOutboundHandler, processor);
        channel.writeInbound(RestTestUtils.createRequest(HttpMethod.GET, "/", null));
        // channel gets closed because of write failure
        channel.writeInbound(createContent(content, true));
        fail("Callback for write would have thrown an Exception");
    } catch (Exception e) {
        assertEquals("Exception not as expected", ExceptionOutboundHandler.EXCEPTION_MESSAGE, e.getMessage());
    }

    // writing to channel with a outbound handler that generates an Error
    EmbeddedChannel channel = new EmbeddedChannel(new ErrorOutboundHandler(), new MockNettyMessageProcessor());
    try {
        channel.writeInbound(RestTestUtils.createRequest(HttpMethod.GET,
                TestingUri.WriteFailureWithThrowable.toString(), null));
    } catch (Error e) {
        assertEquals("Unexpected error", ErrorOutboundHandler.ERROR_MESSAGE, e.getMessage());
    }

    channel = createEmbeddedChannel();
    channel.writeInbound(
            RestTestUtils.createRequest(HttpMethod.GET, TestingUri.ResponseFailureMidway.toString(), null));
    assertFalse("Channel is not closed at the remote end", channel.isActive());
}

From source file:com.github.ambry.rest.NettyResponseChannelTest.java

License:Open Source License

/**
 * Tests handling of content that is larger than write buffer size. In this test case, the write buffer low and high
 * watermarks are requested to be set to 1 and 2 respectively so the content will be written byte by byte into the
 * {@link NettyResponseChannel}. This does <b><i>not</i></b> test for the same situation in a async scenario since
 * {@link EmbeddedChannel} only provides blocking semantics.
 * @throws IOException// w w  w . ja  v  a 2  s .co m
 */
@Test
public void fillWriteBufferTest() throws IOException {
    String content = "@@randomContent@@@";
    String lastContent = "@@randomLastContent@@@";
    EmbeddedChannel channel = createEmbeddedChannel();
    HttpRequest httpRequest = RestTestUtils.createRequest(HttpMethod.GET, TestingUri.FillWriteBuffer.toString(),
            null);
    HttpHeaders.setKeepAlive(httpRequest, false);
    channel.writeInbound(httpRequest);
    channel.writeInbound(createContent(content, false));
    channel.writeInbound(createContent(lastContent, true));

    // first outbound has to be response.
    HttpResponse response = (HttpResponse) channel.readOutbound();
    assertEquals("Unexpected response status", HttpResponseStatus.OK, response.getStatus());
    // content echoed back.
    StringBuilder returnedContent = new StringBuilder();
    while (returnedContent.length() < content.length()) {
        returnedContent.append(RestTestUtils.getContentString((HttpContent) channel.readOutbound()));
    }
    assertEquals("Content does not match with expected content", content, returnedContent.toString());
    // last content echoed back.
    StringBuilder returnedLastContent = new StringBuilder();
    while (returnedLastContent.length() < lastContent.length()) {
        returnedLastContent.append(RestTestUtils.getContentString((HttpContent) channel.readOutbound()));
    }
    assertEquals("Content does not match with expected content", lastContent, returnedLastContent.toString());
    assertFalse("Channel not closed on the server", channel.isActive());
}

From source file:com.github.ambry.rest.NettyResponseChannelTest.java

License:Open Source License

/**
 * Sends a request with certain headers that will copied into the response. Checks the response for those headers to
 * see that values match./*from w w  w. j a  v  a  2s  .  c  om*/
 * @throws ParseException
 */
@Test
public void headersPresenceTest() throws ParseException {
    HttpRequest request = createRequestWithHeaders(HttpMethod.GET, TestingUri.CopyHeaders.toString());
    HttpHeaders.setKeepAlive(request, false);
    EmbeddedChannel channel = createEmbeddedChannel();
    channel.writeInbound(request);

    HttpResponse response = (HttpResponse) channel.readOutbound();
    assertFalse("Channel not closed on the server", channel.isActive());

    checkHeaders(request, response);
}

From source file:com.github.ambry.rest.NettyResponseChannelTest.java

License:Open Source License

/**
 * Sends null input to {@link NettyResponseChannel#setHeader(String, Object)} (through
 * {@link MockNettyMessageProcessor}) and tests for reaction.
 *//*from www  . j  a  va2  s.  c o m*/
@Test
public void nullHeadersSetTest() {
    HttpRequest request = createRequestWithHeaders(HttpMethod.GET, TestingUri.SetNullHeader.toString());
    HttpHeaders.setKeepAlive(request, false);
    EmbeddedChannel channel = createEmbeddedChannel();
    channel.writeInbound(request);

    HttpResponse response = (HttpResponse) channel.readOutbound();
    assertEquals("Unexpected response status", HttpResponseStatus.ACCEPTED, response.getStatus());
    assertFalse("Channel not closed on the server", channel.isActive());
}

From source file:com.github.ambry.rest.NettyResponseChannelTest.java

License:Open Source License

/**
 * Tries different exception scenarios for {@link NettyResponseChannel#setRequest(NettyRequest)}.
 *///from w  w  w  .  ja v a 2  s  . c  om
@Test
public void setRequestTest() {
    HttpRequest request = createRequestWithHeaders(HttpMethod.GET, TestingUri.SetRequest.toString());
    HttpHeaders.setKeepAlive(request, false);
    EmbeddedChannel channel = createEmbeddedChannel();
    channel.writeInbound(request);

    HttpResponse response = (HttpResponse) channel.readOutbound();
    assertEquals("Unexpected response status", HttpResponseStatus.ACCEPTED, response.getStatus());
    assertFalse("Channel not closed on the server", channel.isActive());
}

From source file:com.github.ambry.rest.NettyResponseChannelTest.java

License:Open Source License

/**
 * Tests setting of different available {@link ResponseStatus} codes and sees that they are recognized and converted
 * in {@link NettyResponseChannel}./*from   w w w. java 2  s.  com*/
 * <p/>
 * If this test fails, a case for conversion probably needs to be added in {@link NettyResponseChannel}.
 */
@Test
public void setStatusTest() {
    // ask for every status to be set
    for (ResponseStatus expectedResponseStatus : ResponseStatus.values()) {
        HttpRequest request = createRequestWithHeaders(HttpMethod.GET, TestingUri.SetStatus.toString());
        HttpHeaders.setHeader(request, MockNettyMessageProcessor.STATUS_HEADER_NAME, expectedResponseStatus);
        HttpHeaders.setKeepAlive(request, false);
        EmbeddedChannel channel = createEmbeddedChannel();
        channel.writeInbound(request);

        // pull but discard response
        channel.readOutbound();
        assertFalse("Channel not closed on the server", channel.isActive());
    }
    // check if all the ResponseStatus codes were recognized.
    String metricName = MetricRegistry.name(NettyResponseChannel.class, "UnknownResponseStatusCount");
    long metricCount = MockNettyMessageProcessor.METRIC_REGISTRY.getCounters().get(metricName).getCount();
    assertEquals("Some of the ResponseStatus codes were not recognized", 0, metricCount);
}

From source file:com.github.ambry.rest.NettyResponseChannelTest.java

License:Open Source License

/**
 * Tests that HEAD returns no body in error responses.
 *//*from  w ww .  j  av  a  2s . com*/
@Test
public void noBodyForHeadTest() {
    EmbeddedChannel channel = createEmbeddedChannel();
    for (Map.Entry<RestServiceErrorCode, HttpResponseStatus> entry : REST_ERROR_CODE_TO_HTTP_STATUS
            .entrySet()) {
        HttpHeaders httpHeaders = new DefaultHttpHeaders();
        httpHeaders.set(MockNettyMessageProcessor.REST_SERVICE_ERROR_CODE_HEADER_NAME, entry.getKey());
        channel.writeInbound(RestTestUtils.createRequest(HttpMethod.HEAD,
                TestingUri.OnResponseCompleteWithRestException.toString(), httpHeaders));
        HttpResponse response = (HttpResponse) channel.readOutbound();
        assertEquals("Unexpected response status", entry.getValue(), response.getStatus());
        if (response instanceof FullHttpResponse) {
            // assert that there is no content
            assertEquals("The response should not contain content", 0,
                    ((FullHttpResponse) response).content().readableBytes());
        } else {
            HttpContent content = (HttpContent) channel.readOutbound();
            assertTrue("End marker should be received", content instanceof LastHttpContent);
        }
        assertNull("There should be no more data in the channel", channel.readOutbound());
        boolean shouldBeAlive = !NettyResponseChannel.CLOSE_CONNECTION_ERROR_STATUSES
                .contains(entry.getValue());
        assertEquals("Channel state (open/close) not as expected", shouldBeAlive, channel.isActive());
        assertEquals("Connection header should be consistent with channel state", shouldBeAlive,
                HttpHeaders.isKeepAlive(response));
        if (!shouldBeAlive) {
            channel = createEmbeddedChannel();
        }
    }
    channel.close();
}