Example usage for io.netty.handler.codec.http HttpHeaders setKeepAlive

List of usage examples for io.netty.handler.codec.http HttpHeaders setKeepAlive

Introduction

In this page you can find the example usage for io.netty.handler.codec.http HttpHeaders setKeepAlive.

Prototype

@Deprecated
public static void setKeepAlive(HttpMessage message, boolean keepAlive) 

Source Link

Usage

From source file:com.bloom.zerofs.rest.HealthCheckHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception {
    logger.trace("Reading on channel {}", ctx.channel());
    boolean forwardObj = false;
    if (obj instanceof HttpRequest) {
        if (request == null && ((HttpRequest) obj).getUri().equals(healthCheckUri)) {
            nettyMetrics.healthCheckRequestRate.mark();
            startTimeInMs = System.currentTimeMillis();
            logger.trace("Handling health check request while in state " + restServerState.isServiceUp());
            request = (HttpRequest) obj;
            if (restServerState.isServiceUp()) {
                response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
                        Unpooled.wrappedBuffer(GOOD));
                HttpHeaders.setKeepAlive(response, HttpHeaders.isKeepAlive(request));
                HttpHeaders.setContentLength(response, GOOD.length);
            } else {
                response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                        HttpResponseStatus.SERVICE_UNAVAILABLE, Unpooled.wrappedBuffer(BAD));
                HttpHeaders.setKeepAlive(response, false);
                HttpHeaders.setContentLength(response, BAD.length);
            }/*from w  ww  .  jav  a 2 s . c  o m*/
            nettyMetrics.healthCheckRequestProcessingTimeInMs
                    .update(System.currentTimeMillis() - startTimeInMs);
        } else {
            // Rest server could be down even if not for health check request. We intentionally don't take any action in this
            // handler for such cases and leave it to the downstream handlers to handle it
            forwardObj = true;
        }
    }
    if (obj instanceof LastHttpContent) {
        if (response != null) {
            // response was created when we received the request with health check uri
            ChannelFuture future = ctx.writeAndFlush(response);
            if (!HttpHeaders.isKeepAlive(response)) {
                future.addListener(ChannelFutureListener.CLOSE);
            }
            request = null;
            response = null;
            nettyMetrics.healthCheckRequestRoundTripTimeInMs.update(System.currentTimeMillis() - startTimeInMs);
        } else {
            // request was not for health check uri
            forwardObj = true;
        }
    } else if (request == null) {
        // http Content which is not LastHttpContent is not intended for this handler
        forwardObj = true;
    }
    if (forwardObj) {
        super.channelRead(ctx, obj);
    } else {
        ReferenceCountUtil.release(obj);
    }
}

From source file:com.bloom.zerofs.rest.NettyResponseChannel.java

License:Open Source License

/**
 * Sets the request whose response is being served through this instance of NettyResponseChannel.
 * @param request the {@link NettyRequest} whose response is being served through this instance of
 *                NettyResponseChannel.//from  w ww.  j a va2s .c  om
 */
void setRequest(NettyRequest request) {
    if (request != null) {
        if (this.request == null) {
            this.request = request;
            HttpHeaders.setKeepAlive(responseMetadata, request.isKeepAlive());
        } else {
            throw new IllegalStateException(
                    "Request has already been set inside NettyResponseChannel for channel {} " + ctx.channel());
        }
    } else {
        throw new IllegalArgumentException("RestRequest provided is null");
    }
}

From source file:com.bloom.zerofs.rest.NettyResponseChannel.java

License:Open Source License

/**
 * Provided a cause, returns an error response with the right status and error message.
 * @param cause the cause of the error./*w  w  w  . j a v  a2 s.  co m*/
 * @return a {@link FullHttpResponse} with the error message that can be sent to the client.
 */
private FullHttpResponse getErrorResponse(Throwable cause) {
    HttpResponseStatus status;
    StringBuilder errReason = new StringBuilder();
    if (cause instanceof RestServiceException) {
        RestServiceErrorCode restServiceErrorCode = ((RestServiceException) cause).getErrorCode();
        errorResponseStatus = ResponseStatus.getResponseStatus(restServiceErrorCode);
        status = getHttpResponseStatus(errorResponseStatus);
        if (status == HttpResponseStatus.BAD_REQUEST) {
            errReason.append(" [").append(Utils.getRootCause(cause).getMessage()).append("]");
        }
    } else {
        nettyMetrics.internalServerErrorCount.inc();
        status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
        errorResponseStatus = ResponseStatus.InternalServerError;
    }
    String fullMsg = "Failure: " + status + errReason;
    logger.trace("Constructed error response for the client - [{}]", fullMsg);
    FullHttpResponse response;
    if (request != null && !request.getRestMethod().equals(RestMethod.HEAD)) {
        response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status,
                Unpooled.wrappedBuffer(fullMsg.getBytes()));
    } else {
        // for HEAD, we cannot send the actual body but we need to return what the length would have been if this was GET.
        // https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html (Section 9.4)
        response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status);
    }
    HttpHeaders.setDate(response, new GregorianCalendar().getTime());
    HttpHeaders.setContentLength(response, fullMsg.length());
    HttpHeaders.setHeader(response, HttpHeaders.Names.CONTENT_TYPE, "text/plain; charset=UTF-8");
    boolean keepAlive = !forceClose && HttpHeaders.isKeepAlive(responseMetadata) && request != null
            && !request.getRestMethod().equals(RestMethod.POST)
            && !CLOSE_CONNECTION_ERROR_STATUSES.contains(status);
    HttpHeaders.setKeepAlive(response, keepAlive);
    return response;
}

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

License:Open Source License

/**
 * Does a test to see that a health check request results in expected response from the health check handler
 * @param httpMethod the {@link HttpMethod} for the request.
 * @param keepAlive true if keep alive has to be set in the request, false otherwise
 * @throws IOException//from w w w  .j  av  a2s . c o m
 */
private void testHealthCheckRequest(HttpMethod httpMethod, boolean isServiceUp, boolean keepAlive)
        throws IOException {
    EmbeddedChannel channel = createChannel();
    for (int i = 0; i < 2; i++) {
        if (isServiceUp) {
            restServerState.markServiceUp();
        }
        HttpRequest request = RestTestUtils.createRequest(httpMethod, healthCheckUri, null);
        HttpHeaders.setKeepAlive(request, keepAlive);
        FullHttpResponse response = sendRequestAndGetResponse(channel, request);
        HttpResponseStatus httpResponseStatus = (isServiceUp) ? HttpResponseStatus.OK
                : HttpResponseStatus.SERVICE_UNAVAILABLE;
        assertEquals("Unexpected response status", httpResponseStatus, response.getStatus());
        String expectedStr = (isServiceUp) ? goodStr : badStr;
        assertEquals("Unexpected content", expectedStr, RestTestUtils.getContentString(response));
        restServerState.markServiceDown();
        if (keepAlive && isServiceUp) {
            Assert.assertTrue("Channel should not be closed ", channel.isOpen());
        } else {
            Assert.assertFalse("Channel should have been closed by now ", channel.isOpen());
            channel = createChannel();
        }
    }
    channel.close();
}

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

License:Open Source License

/**
 * Sends the provided {@code httpRequest} and verifies that the response is an echo of the {@code restMethod}.
 * @param channel the {@link EmbeddedChannel} to send the request over.
 * @param httpMethod the {@link HttpMethod} for the request.
 * @param restMethod the equivalent {@link RestMethod} for {@code httpMethod}. Used to check for correctness of
 *                   response.//from   w ww . j av  a2s.  c  o m
 * @param isKeepAlive if the request needs to be keep-alive.
 * @throws IOException
 */
private void sendRequestCheckResponse(EmbeddedChannel channel, HttpMethod httpMethod, RestMethod restMethod,
        boolean isKeepAlive) throws IOException {
    long requestId = requestIdGenerator.getAndIncrement();
    String uri = MockBlobStorageService.ECHO_REST_METHOD + requestId;
    HttpRequest httpRequest = RestTestUtils.createRequest(httpMethod, uri, null);
    HttpHeaders.setKeepAlive(httpRequest, isKeepAlive);
    channel.writeInbound(httpRequest);
    channel.writeInbound(new DefaultLastHttpContent());
    HttpResponse response = (HttpResponse) channel.readOutbound();
    assertEquals("Unexpected response status", HttpResponseStatus.OK, response.getStatus());
    // MockBlobStorageService echoes the RestMethod + request id.
    String expectedResponse = restMethod.toString() + requestId;
    assertEquals("Unexpected content", expectedResponse,
            RestTestUtils.getContentString((HttpContent) channel.readOutbound()));
    assertTrue("End marker was expected", channel.readOutbound() instanceof LastHttpContent);
}

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

License:Open Source License

/**
 * Does the post test by sending the request and content to {@link NettyMessageProcessor} through an
 * {@link EmbeddedChannel} and returns the data stored in the {@link InMemoryRouter} as a result of the post.
 * @param postRequest the POST request as a {@link HttpRequest}.
 * @param contentToSend the content to be sent as a part of the POST.
 * @return the data stored in the {@link InMemoryRouter} as a result of the POST.
 * @throws InterruptedException//from  www.j  a v a2s . c o  m
 */
private ByteBuffer doPostTest(HttpRequest postRequest, List<ByteBuffer> contentToSend)
        throws InterruptedException {
    EmbeddedChannel channel = createChannel();

    // POST
    notificationSystem.reset();
    HttpHeaders.setHeader(postRequest, RestUtils.Headers.AMBRY_CONTENT_TYPE, "application/octet-stream");
    HttpHeaders.setKeepAlive(postRequest, false);
    channel.writeInbound(postRequest);
    if (contentToSend != null) {
        for (ByteBuffer content : contentToSend) {
            channel.writeInbound(new DefaultHttpContent(Unpooled.wrappedBuffer(content)));
        }
        channel.writeInbound(LastHttpContent.EMPTY_LAST_CONTENT);
    }
    if (!notificationSystem.operationCompleted.await(100, TimeUnit.MILLISECONDS)) {
        fail("Post did not succeed after 100ms. There is an error or timeout needs to increase");
    }
    assertNotNull("Blob id operated on cannot be null", notificationSystem.blobIdOperatedOn);
    return router.getActiveBlobs().get(notificationSystem.blobIdOperatedOn).getBlob();
}

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

License:Open Source License

/**
 * Sets the request whose response is being served through this instance of NettyResponseChannel.
 * @param request the {@link NettyRequest} whose response is being served through this instance of
 *                NettyResponseChannel.//from ww  w .  j  a  v a2  s .  com
 */
protected void setRequest(NettyRequest request) {
    if (request != null) {
        if (this.request == null) {
            this.request = request;
            HttpHeaders.setKeepAlive(responseMetadata, request.isKeepAlive());
        } else {
            throw new IllegalStateException(
                    "Request has already been set inside NettyResponseChannel for channel {} " + ctx.channel());
        }
    } else {
        throw new IllegalArgumentException("RestRequest provided is null");
    }
}

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

License:Open Source License

/**
 * Provided a cause, returns an error response with the right status and error message.
 * @param cause the cause of the error.// w  w  w.j a  va 2  s  .com
 * @return a {@link FullHttpResponse} with the error message that can be sent to the client.
 */
private FullHttpResponse getErrorResponse(Throwable cause) {
    HttpResponseStatus status;
    StringBuilder errReason = new StringBuilder();
    if (cause instanceof RestServiceException) {
        RestServiceErrorCode restServiceErrorCode = ((RestServiceException) cause).getErrorCode();
        status = getHttpResponseStatus(ResponseStatus.getResponseStatus(restServiceErrorCode));
        if (status == HttpResponseStatus.BAD_REQUEST) {
            errReason.append(" [").append(Utils.getRootCause(cause).getMessage()).append("]");
        }
    } else {
        nettyMetrics.internalServerErrorCount.inc();
        status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
    }
    String fullMsg = "Failure: " + status + errReason;
    logger.trace("Constructed error response for the client - [{}]", fullMsg);
    FullHttpResponse response;
    if (request != null && !request.getRestMethod().equals(RestMethod.HEAD)) {
        response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status,
                Unpooled.wrappedBuffer(fullMsg.getBytes()));
    } else {
        // for HEAD, we cannot send the actual body but we need to return what the length would have been if this was GET.
        // https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html (Section 9.4)
        response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status);
    }
    HttpHeaders.setDate(response, new GregorianCalendar().getTime());
    HttpHeaders.setContentLength(response, fullMsg.length());
    HttpHeaders.setHeader(response, HttpHeaders.Names.CONTENT_TYPE, "text/plain; charset=UTF-8");
    boolean keepAlive = request != null && !request.getRestMethod().equals(RestMethod.POST)
            && !CLOSE_CONNECTION_ERROR_STATUSES.contains(status);
    HttpHeaders.setKeepAlive(response, keepAlive);
    return response;
}

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   ww w . ja v  a 2s .c  o  m*/
 * 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.//  w  w  w . j  av a  2  s. c o  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());
}