Search in sources :

Example 41 with DefaultFullHttpResponse

use of io.netty.handler.codec.http.DefaultFullHttpResponse in project netty by netty.

the class WebSocketServerHandshaker13 method newHandshakeResponse.

/**
     * <p>
     * Handle the web socket handshake for the web socket specification <a href=
     * "http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17">HyBi versions 13-17</a>. Versions 13-17
     * share the same wire protocol.
     * </p>
     *
     * <p>
     * Browser request to the server:
     * </p>
     *
     * <pre>
     * GET /chat HTTP/1.1
     * Host: server.example.com
     * Upgrade: websocket
     * Connection: Upgrade
     * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
     * Sec-WebSocket-Origin: http://example.com
     * Sec-WebSocket-Protocol: chat, superchat
     * Sec-WebSocket-Version: 13
     * </pre>
     *
     * <p>
     * Server response:
     * </p>
     *
     * <pre>
     * HTTP/1.1 101 Switching Protocols
     * Upgrade: websocket
     * Connection: Upgrade
     * Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
     * Sec-WebSocket-Protocol: chat
     * </pre>
     */
@Override
protected FullHttpResponse newHandshakeResponse(FullHttpRequest req, HttpHeaders headers) {
    FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.SWITCHING_PROTOCOLS);
    if (headers != null) {
        res.headers().add(headers);
    }
    CharSequence key = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_KEY);
    if (key == null) {
        throw new WebSocketHandshakeException("not a WebSocket request: missing key");
    }
    String acceptSeed = key + WEBSOCKET_13_ACCEPT_GUID;
    byte[] sha1 = WebSocketUtil.sha1(acceptSeed.getBytes(CharsetUtil.US_ASCII));
    String accept = WebSocketUtil.base64(sha1);
    if (logger.isDebugEnabled()) {
        logger.debug("WebSocket version 13 server handshake key: {}, response: {}", key, accept);
    }
    res.headers().add(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET);
    res.headers().add(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE);
    res.headers().add(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT, accept);
    String subprotocols = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL);
    if (subprotocols != null) {
        String selectedSubprotocol = selectSubprotocol(subprotocols);
        if (selectedSubprotocol == null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Requested subprotocol(s) not supported: {}", subprotocols);
            }
        } else {
            res.headers().add(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, selectedSubprotocol);
        }
    }
    return res;
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse)

Example 42 with DefaultFullHttpResponse

use of io.netty.handler.codec.http.DefaultFullHttpResponse in project netty by netty.

the class WebSocketServerProtocolHandler method forbiddenHttpRequestResponder.

static ChannelHandler forbiddenHttpRequestResponder() {
    return new ChannelInboundHandlerAdapter() {

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            if (msg instanceof FullHttpRequest) {
                ((FullHttpRequest) msg).release();
                FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.FORBIDDEN);
                ctx.channel().writeAndFlush(response);
            } else {
                ctx.fireChannelRead(msg);
            }
        }
    };
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 43 with DefaultFullHttpResponse

use of io.netty.handler.codec.http.DefaultFullHttpResponse in project netty by netty.

the class InboundHttp2ToHttpAdapterTest method serverRequestPushPromise.

@Test
public void serverRequestPushPromise() throws Exception {
    boostrapEnv(1, 1, 1);
    final String text = "hello world big time data!";
    final ByteBuf content = Unpooled.copiedBuffer(text.getBytes());
    final String text2 = "hello world smaller data?";
    final ByteBuf content2 = Unpooled.copiedBuffer(text2.getBytes());
    final FullHttpMessage response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content, true);
    final FullHttpMessage response2 = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CREATED, content2, true);
    final FullHttpMessage request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/push/test", true);
    try {
        HttpHeaders httpHeaders = response.headers();
        httpHeaders.setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), 3);
        httpHeaders.setInt(HttpHeaderNames.CONTENT_LENGTH, text.length());
        httpHeaders.setShort(HttpConversionUtil.ExtensionHeaderNames.STREAM_WEIGHT.text(), (short) 16);
        HttpHeaders httpHeaders2 = response2.headers();
        httpHeaders2.set(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), "https");
        httpHeaders2.set(HttpHeaderNames.HOST, "example.org");
        httpHeaders2.setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), 5);
        httpHeaders2.setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_PROMISE_ID.text(), 3);
        httpHeaders2.setInt(HttpHeaderNames.CONTENT_LENGTH, text2.length());
        httpHeaders = request.headers();
        httpHeaders.setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), 3);
        httpHeaders.setInt(HttpHeaderNames.CONTENT_LENGTH, 0);
        httpHeaders.setShort(HttpConversionUtil.ExtensionHeaderNames.STREAM_WEIGHT.text(), (short) 16);
        final Http2Headers http2Headers3 = new DefaultHttp2Headers().method(new AsciiString("GET")).path(new AsciiString("/push/test"));
        runInChannel(clientChannel, new Http2Runnable() {

            @Override
            public void run() throws Http2Exception {
                clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers3, 0, true, newPromiseClient());
                clientChannel.flush();
            }
        });
        awaitRequests();
        ArgumentCaptor<FullHttpMessage> requestCaptor = ArgumentCaptor.forClass(FullHttpMessage.class);
        verify(serverListener).messageReceived(requestCaptor.capture());
        capturedRequests = requestCaptor.getAllValues();
        assertEquals(request, capturedRequests.get(0));
        final Http2Headers http2Headers = new DefaultHttp2Headers().status(new AsciiString("200"));
        final Http2Headers http2Headers2 = new DefaultHttp2Headers().status(new AsciiString("201")).scheme(new AsciiString("https")).authority(new AsciiString("example.org"));
        runInChannel(serverConnectedChannel, new Http2Runnable() {

            @Override
            public void run() throws Http2Exception {
                serverHandler.encoder().writeHeaders(ctxServer(), 3, http2Headers, 0, false, newPromiseServer());
                serverHandler.encoder().writePushPromise(ctxServer(), 3, 2, http2Headers2, 0, newPromiseServer());
                serverHandler.encoder().writeData(ctxServer(), 3, content.retainedDuplicate(), 0, true, newPromiseServer());
                serverHandler.encoder().writeData(ctxServer(), 5, content2.retainedDuplicate(), 0, true, newPromiseServer());
                serverConnectedChannel.flush();
            }
        });
        awaitResponses();
        ArgumentCaptor<FullHttpMessage> responseCaptor = ArgumentCaptor.forClass(FullHttpMessage.class);
        verify(clientListener).messageReceived(responseCaptor.capture());
        capturedResponses = responseCaptor.getAllValues();
        assertEquals(response, capturedResponses.get(0));
    } finally {
        request.release();
        response.release();
        response2.release();
    }
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) Http2CodecUtil.getEmbeddedHttp2Exception(io.netty.handler.codec.http2.Http2CodecUtil.getEmbeddedHttp2Exception) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) Http2Runnable(io.netty.handler.codec.http2.Http2TestUtil.Http2Runnable) FullHttpMessage(io.netty.handler.codec.http.FullHttpMessage) AsciiString(io.netty.util.AsciiString) AsciiString(io.netty.util.AsciiString) ByteBuf(io.netty.buffer.ByteBuf) Test(org.junit.Test)

Example 44 with DefaultFullHttpResponse

use of io.netty.handler.codec.http.DefaultFullHttpResponse in project netty by netty.

the class InboundHttp2ToHttpAdapterTest method serverResponseHeaderInformational.

@Test
public void serverResponseHeaderInformational() throws Exception {
    boostrapEnv(1, 2, 1, 2, 1);
    final FullHttpMessage request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT, "/info/test", true);
    HttpHeaders httpHeaders = request.headers();
    httpHeaders.setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), 3);
    httpHeaders.set(HttpHeaderNames.EXPECT, HttpHeaderValues.CONTINUE);
    httpHeaders.setInt(HttpHeaderNames.CONTENT_LENGTH, 0);
    httpHeaders.setShort(HttpConversionUtil.ExtensionHeaderNames.STREAM_WEIGHT.text(), (short) 16);
    final Http2Headers http2Headers = new DefaultHttp2Headers().method(new AsciiString("PUT")).path(new AsciiString("/info/test")).set(new AsciiString(HttpHeaderNames.EXPECT.toString()), new AsciiString(HttpHeaderValues.CONTINUE.toString()));
    final FullHttpMessage response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE);
    final String text = "a big payload";
    final ByteBuf payload = Unpooled.copiedBuffer(text.getBytes());
    final FullHttpMessage request2 = request.replace(payload);
    final FullHttpMessage response2 = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    try {
        runInChannel(clientChannel, new Http2Runnable() {

            @Override
            public void run() throws Http2Exception {
                clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, false, newPromiseClient());
                clientChannel.flush();
            }
        });
        awaitRequests();
        httpHeaders = response.headers();
        httpHeaders.setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), 3);
        httpHeaders.setInt(HttpHeaderNames.CONTENT_LENGTH, 0);
        final Http2Headers http2HeadersResponse = new DefaultHttp2Headers().status(new AsciiString("100"));
        runInChannel(serverConnectedChannel, new Http2Runnable() {

            @Override
            public void run() throws Http2Exception {
                serverHandler.encoder().writeHeaders(ctxServer(), 3, http2HeadersResponse, 0, false, newPromiseServer());
                serverConnectedChannel.flush();
            }
        });
        awaitResponses();
        httpHeaders = request2.headers();
        httpHeaders.setInt(HttpHeaderNames.CONTENT_LENGTH, text.length());
        httpHeaders.remove(HttpHeaderNames.EXPECT);
        runInChannel(clientChannel, new Http2Runnable() {

            @Override
            public void run() {
                clientHandler.encoder().writeData(ctxClient(), 3, payload.retainedDuplicate(), 0, true, newPromiseClient());
                clientChannel.flush();
            }
        });
        awaitRequests2();
        httpHeaders = response2.headers();
        httpHeaders.setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), 3);
        httpHeaders.setInt(HttpHeaderNames.CONTENT_LENGTH, 0);
        httpHeaders.setShort(HttpConversionUtil.ExtensionHeaderNames.STREAM_WEIGHT.text(), (short) 16);
        final Http2Headers http2HeadersResponse2 = new DefaultHttp2Headers().status(new AsciiString("200"));
        runInChannel(serverConnectedChannel, new Http2Runnable() {

            @Override
            public void run() throws Http2Exception {
                serverHandler.encoder().writeHeaders(ctxServer(), 3, http2HeadersResponse2, 0, true, newPromiseServer());
                serverConnectedChannel.flush();
            }
        });
        awaitResponses2();
        ArgumentCaptor<FullHttpMessage> requestCaptor = ArgumentCaptor.forClass(FullHttpMessage.class);
        verify(serverListener, times(2)).messageReceived(requestCaptor.capture());
        capturedRequests = requestCaptor.getAllValues();
        assertEquals(2, capturedRequests.size());
        assertEquals(request, capturedRequests.get(0));
        assertEquals(request2, capturedRequests.get(1));
        ArgumentCaptor<FullHttpMessage> responseCaptor = ArgumentCaptor.forClass(FullHttpMessage.class);
        verify(clientListener, times(2)).messageReceived(responseCaptor.capture());
        capturedResponses = responseCaptor.getAllValues();
        assertEquals(2, capturedResponses.size());
        assertEquals(response, capturedResponses.get(0));
        assertEquals(response2, capturedResponses.get(1));
    } finally {
        request.release();
        request2.release();
        response.release();
        response2.release();
    }
}
Also used : HttpHeaders(io.netty.handler.codec.http.HttpHeaders) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) Http2CodecUtil.getEmbeddedHttp2Exception(io.netty.handler.codec.http2.Http2CodecUtil.getEmbeddedHttp2Exception) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) Http2Runnable(io.netty.handler.codec.http2.Http2TestUtil.Http2Runnable) FullHttpMessage(io.netty.handler.codec.http.FullHttpMessage) AsciiString(io.netty.util.AsciiString) AsciiString(io.netty.util.AsciiString) ByteBuf(io.netty.buffer.ByteBuf) Test(org.junit.Test)

Example 45 with DefaultFullHttpResponse

use of io.netty.handler.codec.http.DefaultFullHttpResponse in project netty by netty.

the class Http2ServerDowngraderTest method testUpgradeNonEmptyFullResponseWithTrailers.

@Test
public void testUpgradeNonEmptyFullResponseWithTrailers() throws Exception {
    EmbeddedChannel ch = new EmbeddedChannel(new Http2ServerDowngrader());
    ByteBuf hello = Unpooled.copiedBuffer("hello world", CharsetUtil.UTF_8);
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, hello);
    HttpHeaders trailers = response.trailingHeaders();
    trailers.set("key", "value");
    assertTrue(ch.writeOutbound(response));
    Http2HeadersFrame headersFrame = ch.readOutbound();
    assertThat(headersFrame.headers().status().toString(), is("200"));
    assertFalse(headersFrame.isEndStream());
    Http2DataFrame dataFrame = ch.readOutbound();
    try {
        assertThat(dataFrame.content().toString(CharsetUtil.UTF_8), is("hello world"));
        assertFalse(dataFrame.isEndStream());
    } finally {
        dataFrame.release();
    }
    Http2HeadersFrame trailersFrame = ch.readOutbound();
    assertThat(trailersFrame.headers().get("key").toString(), is("value"));
    assertTrue(trailersFrame.isEndStream());
    assertThat(ch.readOutbound(), is(nullValue()));
    assertFalse(ch.finish());
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) ByteBuf(io.netty.buffer.ByteBuf) Test(org.junit.Test)

Aggregations

DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)72 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)44 ByteBuf (io.netty.buffer.ByteBuf)27 HttpResponse (io.netty.handler.codec.http.HttpResponse)10 HttpResponseStatus (io.netty.handler.codec.http.HttpResponseStatus)8 Test (org.junit.Test)7 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)6 DefaultHttpResponse (io.netty.handler.codec.http.DefaultHttpResponse)5 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)5 HttpRequest (io.netty.handler.codec.http.HttpRequest)5 ChannelFuture (io.netty.channel.ChannelFuture)4 IOException (java.io.IOException)4 Map (java.util.Map)4 HttpContent (io.netty.handler.codec.http.HttpContent)3 LastHttpContent (io.netty.handler.codec.http.LastHttpContent)3 File (java.io.File)3 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)2 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)2 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)2 FullHttpMessage (io.netty.handler.codec.http.FullHttpMessage)2