Example usage for io.netty.handler.codec.http DefaultLastHttpContent DefaultLastHttpContent

List of usage examples for io.netty.handler.codec.http DefaultLastHttpContent DefaultLastHttpContent

Introduction

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

Prototype

public DefaultLastHttpContent() 

Source Link

Usage

From source file:com.bunjlabs.fuga.network.netty.NettyHttpServerHandler.java

License:Apache License

private void writeResponse(ChannelHandlerContext ctx, Request request, Response response) {
    HttpResponse httpresponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            HttpResponseStatus.valueOf(response.status()));

    httpresponse.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
    httpresponse.headers().set(HttpHeaderNames.CONTENT_TYPE, response.contentType());

    // Disable cache by default
    httpresponse.headers().set(HttpHeaderNames.CACHE_CONTROL, "no-cache, no-store, must-revalidate, max-age=0");
    httpresponse.headers().set(HttpHeaderNames.PRAGMA, "no-cache");
    httpresponse.headers().set(HttpHeaderNames.EXPIRES, "0");

    response.headers().entrySet().stream().forEach((e) -> httpresponse.headers().set(e.getKey(), e.getValue()));

    httpresponse.headers().set(HttpHeaderNames.SERVER, "Fuga Netty Web Server/" + serverVersion);

    // Set cookies
    httpresponse.headers().set(HttpHeaderNames.SET_COOKIE,
            ServerCookieEncoder.STRICT.encode(NettyCookieConverter.convertListToNetty(response.cookies())));

    if (response.length() >= 0) {
        httpresponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.length());
    }/*from   w w  w .  j  a v a 2  s  . c o  m*/

    if (HttpUtil.isKeepAlive(httprequest)) {
        httpresponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    } else {
        httpresponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
    }

    ctx.write(httpresponse);

    if (response.stream() != null) {
        ctx.write(new HttpChunkedInput(new ChunkedStream(response.stream())));
    }

    LastHttpContent fs = new DefaultLastHttpContent();
    ChannelFuture sendContentFuture = ctx.writeAndFlush(fs);
    if (!HttpUtil.isKeepAlive(httprequest)) {
        sendContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.couchbase.client.core.endpoint.query.QueryHandlerTest.java

License:Apache License

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

    QueryHandler testHandler = new QueryHandler(endpoint, responseRingBuffer, queue, false) {
        @Override//  ww w  .  j av a 2  s. c o m
        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 query keepAlive request and hook is called
    testHandler.userEventTriggered(ctxRef.get(), IdleStateEvent.FIRST_READER_IDLE_STATE_EVENT);

    assertEquals(1, keepAliveEventCounter.get());
    assertTrue(queue.peek() instanceof QueryHandler.KeepAliveRequest);
    QueryHandler.KeepAliveRequest keepAliveRequest = (QueryHandler.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);
    LastHttpContent responseEnd = new DefaultLastHttpContent();
    channel.writeInbound(response, responseEnd);
    QueryHandler.KeepAliveResponse keepAliveResponse = keepAliveRequest.observable()
            .cast(QueryHandler.KeepAliveResponse.class).timeout(1, TimeUnit.SECONDS).toBlocking().single();

    channel.pipeline().remove(testHandler);
    assertEquals(2, keepAliveEventCounter.get());
    assertEquals(ResponseStatus.NOT_EXISTS, keepAliveResponse.status());
    assertEquals(0, responseEnd.refCnt());
}

From source file:com.couchbase.client.core.endpoint.search.SearchHandlerTest.java

License:Apache License

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

    SearchHandler searchKeepAliveHandler = new SearchHandler(endpoint, responseRingBuffer, queue, false,
            false) {/*from  w ww .  j  a  va  2 s .  co m*/
        @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());
        }
    };
    EmbeddedChannel channel = new EmbeddedChannel(searchKeepAliveHandler);

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

    assertEquals(1, keepAliveEventCounter.get());
    assertTrue(queue.peek() instanceof SearchHandler.KeepAliveRequest);
    SearchHandler.KeepAliveRequest keepAliveRequest = (SearchHandler.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);
    LastHttpContent responseEnd = new DefaultLastHttpContent();
    channel.writeInbound(response, responseEnd);
    SearchHandler.KeepAliveResponse keepAliveResponse = keepAliveRequest.observable()
            .cast(SearchHandler.KeepAliveResponse.class).timeout(1, TimeUnit.SECONDS).toBlocking().single();

    channel.pipeline().remove(searchKeepAliveHandler);
    assertEquals(2, keepAliveEventCounter.get());
    assertEquals(ResponseStatus.NOT_EXISTS, keepAliveResponse.status());
    assertEquals(0, responseEnd.refCnt());
}

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

License:Open Source License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject obj) throws Exception {
    logger.trace("Reading on channel {}", ctx.channel());
    if (obj instanceof HttpRequest) {
        HttpRequest request = (HttpRequest) obj;
        logger.trace("Handling incoming request " + request);
        requestUri = request.getUri();/* w  w  w  .  j  ava  2 s.co m*/
        byte[] methodBytes = request.getMethod().toString().getBytes();
        if (request.headers().get(IS_CHUNKED) == null || !request.headers().get(IS_CHUNKED).equals("true")) {
            response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
                    Unpooled.wrappedBuffer(methodBytes));
            updateHeaders(response, request, methodBytes.length);
        } else {
            httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
            HttpHeaders.setTransferEncodingChunked(httpResponse);
            httpContentList = new ArrayList<HttpContent>();
            ByteBuf content = Unpooled.wrappedBuffer(methodBytes);
            HttpContent httpContent = new DefaultHttpContent(content);
            httpContentList.add(httpContent);
            httpContentList.add(httpContent);
            updateHeaders(httpResponse, request, methodBytes.length);
        }
    } else if (obj instanceof LastHttpContent) {
        if (requestUri.equals(DISCONNECT_URI)) {
            ctx.disconnect();
        } else if (requestUri.equals(CLOSE_URI)) {
            ctx.close();
        } else {
            if (response != null) {
                ctx.writeAndFlush(response);
            } else if (httpResponse != null) {
                ctx.writeAndFlush(httpResponse);
                for (HttpContent httpContent : httpContentList) {
                    ctx.writeAndFlush(httpContent);
                }
                ctx.writeAndFlush(new DefaultLastHttpContent());
            }
        }
    }
}

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

License:Open Source License

/**
 * Sends request to the passed in channel and returns the response
 * @param channel to which the request has to be sent
 * @param request {@link HttpRequest} which has to be sent to the passed in channel
 * @return the HttpResponse in response to the request sent to the channel
 *///w  w w  . ja v  a2 s . c  om
private FullHttpResponse sendRequestAndGetResponse(EmbeddedChannel channel, HttpRequest request) {
    channel.writeInbound(request);
    channel.writeInbound(new DefaultLastHttpContent());
    FullHttpResponse response = (FullHttpResponse) channel.readOutbound();
    return response;
}

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./*w w  w  .j ava  2 s.com*/
 * @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 a test where the request handler inside {@link NettyMessageProcessor} fails. Checks for the right error code
 * in the response.//w ww . jav  a 2  s. c  o m
 * @param httpMethod the {@link HttpMethod} to use for the request.
 * @param expectedStatus the excepted {@link HttpResponseStatus} in the response.
 */
private void doRequestHandlerExceptionTest(HttpMethod httpMethod, HttpResponseStatus expectedStatus) {
    EmbeddedChannel channel = createChannel();
    channel.writeInbound(RestTestUtils.createRequest(httpMethod, "/", null));
    channel.writeInbound(new DefaultLastHttpContent());
    // first outbound has to be response.
    HttpResponse response = (HttpResponse) channel.readOutbound();
    assertEquals("Unexpected response status", expectedStatus, response.getStatus());
}

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

License:Open Source License

/**
 * Tests for POST request that has no content.
 * @throws Exception//from   w w  w  .  j  ava  2s.c  o  m
 */
@Test
public void zeroSizeContentTest() throws Exception {
    NettyRequest nettyRequest = createNettyRequest(HttpMethod.POST, "/", null);
    HttpContent httpContent = new DefaultLastHttpContent();

    nettyRequest.addContent(httpContent);
    assertEquals("Reference count is not as expected", 2, httpContent.refCnt());

    ByteBufferAsyncWritableChannel writeChannel = new ByteBufferAsyncWritableChannel();
    ReadIntoCallback callback = new ReadIntoCallback();
    Future<Long> future = nettyRequest.readInto(writeChannel, callback);
    assertEquals("There should be no content", 0, writeChannel.getNextChunk().remaining());
    writeChannel.resolveOldestChunk(null);
    closeRequestAndValidate(nettyRequest);
    writeChannel.close();
    assertEquals("Reference count of http content has changed", 1, httpContent.refCnt());
    if (callback.exception != null) {
        throw callback.exception;
    }
    long futureBytesRead = future.get();
    assertEquals("Total bytes read does not match (callback)", 0, callback.bytesRead);
    assertEquals("Total bytes read does not match (future)", 0, futureBytesRead);
}

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

License:Open Source License

/**
 * Sends the provided {@code httpRequest} and verifies that the response is as expected.
 * @param channel the {@link EmbeddedChannel} to send the request over.
 * @param httpRequest the {@link HttpRequest} that has to be sent
 * @param uri, Uri to be used for the request
 * @param headers {@link HttpHeaders} that is set in the request to be used for verification purposes
 * @param testErrorCase true if error case has to be tested, false otherwise
 *//* w  w  w  . j a v  a 2 s  . c om*/
private void sendRequestCheckResponse(EmbeddedChannel channel, HttpRequest httpRequest, String uri,
        HttpHeaders headers, boolean testErrorCase, boolean chunkedResponse) {
    channel.writeInbound(httpRequest);
    if (uri.equals(EchoMethodHandler.DISCONNECT_URI)) {
        channel.disconnect();
    } else {
        channel.writeInbound(new DefaultLastHttpContent());
    }
    String lastLogEntry = publicAccessLogger.getLastPublicAccessLogEntry();

    // verify remote host, http method and uri
    String subString = testErrorCase ? "Error"
            : "Info" + ":embedded" + " " + httpRequest.getMethod() + " " + uri;
    Assert.assertTrue("Public Access log entry doesn't have expected remote host/method/uri ",
            lastLogEntry.startsWith(subString));
    // verify request headers
    verifyPublicAccessLogEntryForRequestHeaders(lastLogEntry, headers, httpRequest.getMethod(), true);

    // verify response
    subString = "Response (";
    for (String responseHeader : RESPONSE_HEADERS.split(",")) {
        if (headers.contains(responseHeader)) {
            subString += "[" + responseHeader + "=" + headers.get(responseHeader) + "] ";
        }
    }
    subString += "[isChunked=" + chunkedResponse + "]), status=" + HttpResponseStatus.OK.code();

    if (!testErrorCase) {
        Assert.assertTrue("Public Access log entry doesn't have response set correctly",
                lastLogEntry.contains(subString));
    } else {
        Assert.assertTrue("Public Access log entry doesn't have error set correctly ",
                lastLogEntry.contains(": Channel closed while request in progress."));
    }
}

From source file:com.king.platform.net.http.netty.request.HttpClientRequestHandler.java

License:Apache License

private void writeLastHttpContent(ChannelHandlerContext ctx, final HttpRequestContext httpRequestContext,
        final RequestEventBus requestEventBus) {
    ChannelFuture future = ctx.writeAndFlush(new DefaultLastHttpContent());
    future.addListener(new ChannelFutureListener() {
        @Override//from   w w  w.  jav  a 2  s.  co  m
        public void operationComplete(ChannelFuture future) throws Exception {
            logger.trace("writeLastHttpContent operation completed, future: {}", future);

            if (future.isSuccess()) {
                requestEventBus.triggerEvent(Event.onWroteContentCompleted);
                requestEventBus.triggerEvent(Event.TOUCH);
                httpRequestContext.getTimeRecorder().completedWriteLastBody();

            } else {
                requestEventBus.triggerEvent(Event.ERROR, httpRequestContext, future.cause());
            }

        }
    });
}