Search in sources :

Example 6 with HttpVersion

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpVersion in project zuul by Netflix.

the class ClientResponseWriter method buildHttpResponse.

private HttpResponse buildHttpResponse(final HttpResponseMessage zuulResp) {
    final HttpRequestInfo zuulRequest = zuulResp.getInboundRequest();
    HttpVersion responseHttpVersion;
    final String inboundProtocol = zuulRequest.getProtocol();
    if (inboundProtocol.startsWith("HTTP/1")) {
        responseHttpVersion = HttpVersion.valueOf(inboundProtocol);
    } else {
        // Default to 1.1. We do this to cope with HTTP/2 inbound requests.
        responseHttpVersion = HttpVersion.HTTP_1_1;
    }
    // Create the main http response to send, with body.
    final DefaultHttpResponse nativeResponse = new DefaultHttpResponse(responseHttpVersion, HttpResponseStatus.valueOf(zuulResp.getStatus()), false, false);
    // Now set all of the response headers - note this is a multi-set in keeping with HTTP semantics
    final HttpHeaders nativeHeaders = nativeResponse.headers();
    for (Header entry : zuulResp.getHeaders().entries()) {
        nativeHeaders.add(entry.getKey(), entry.getValue());
    }
    // Netty does not automatically add Content-Length or Transfer-Encoding: chunked. So we add here if missing.
    if (!HttpUtil.isContentLengthSet(nativeResponse) && !HttpUtil.isTransferEncodingChunked(nativeResponse)) {
        nativeResponse.headers().add(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
    }
    final HttpRequest nativeReq = (HttpRequest) zuulResp.getContext().get(CommonContextKeys.NETTY_HTTP_REQUEST);
    if (!closeConnection && HttpUtil.isKeepAlive(nativeReq)) {
        HttpUtil.setKeepAlive(nativeResponse, true);
    } else {
        // Send a Connection: close response header (only needed for HTTP/1.0 but no harm in doing for 1.1 too).
        nativeResponse.headers().set("Connection", "close");
    }
    // TODO - temp hack for http/2 handling.
    if (nativeReq.headers().contains(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text())) {
        String streamId = nativeReq.headers().get(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text());
        nativeResponse.headers().set(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), streamId);
    }
    return nativeResponse;
}
Also used : HttpRequest(io.netty.handler.codec.http.HttpRequest) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) Header(com.netflix.zuul.message.Header) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) HttpRequestInfo(com.netflix.zuul.message.http.HttpRequestInfo) HttpVersion(io.netty.handler.codec.http.HttpVersion)

Example 7 with HttpVersion

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpVersion in project crate by crate.

the class SqlHttpHandler method sendResponse.

private void sendResponse(Session session, ChannelHandlerContext ctx, FullHttpRequest request, Map<String, List<String>> parameters, XContentBuilder result, @Nullable Throwable t) {
    final HttpVersion httpVersion = request.protocolVersion();
    final DefaultFullHttpResponse resp;
    final ByteBuf content;
    if (t == null) {
        content = Netty4Utils.toByteBuf(BytesReference.bytes(result));
        resp = new DefaultFullHttpResponse(httpVersion, HttpResponseStatus.OK, content);
        resp.headers().add(HttpHeaderNames.CONTENT_TYPE, result.contentType().mediaType());
    } else {
        var throwable = SQLExceptions.prepareForClientTransmission(getAccessControl.apply(session.sessionContext()), t);
        HttpError httpError = HttpError.fromThrowable(throwable);
        String mediaType;
        boolean includeErrorTrace = paramContainFlag(parameters, "error_trace");
        try (XContentBuilder contentBuilder = httpError.toXContent(includeErrorTrace)) {
            content = Netty4Utils.toByteBuf(BytesReference.bytes(contentBuilder));
            mediaType = contentBuilder.contentType().mediaType();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        resp = new DefaultFullHttpResponse(httpVersion, httpError.httpResponseStatus(), content);
        resp.headers().add(HttpHeaderNames.CONTENT_TYPE, mediaType);
    }
    Netty4CorsHandler.setCorsResponseHeaders(request, resp, corsConfig);
    resp.headers().add(HttpHeaderNames.CONTENT_LENGTH, String.valueOf(content.readableBytes()));
    boolean closeConnection = isCloseConnection(request);
    ChannelPromise promise = ctx.newPromise();
    if (closeConnection) {
        promise.addListener(ChannelFutureListener.CLOSE);
    } else {
        Headers.setKeepAlive(httpVersion, resp);
    }
    ctx.writeAndFlush(resp, promise);
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) ChannelPromise(io.netty.channel.ChannelPromise) IOException(java.io.IOException) ByteBuf(io.netty.buffer.ByteBuf) HttpVersion(io.netty.handler.codec.http.HttpVersion) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder)

Example 8 with HttpVersion

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpVersion in project vert.x by eclipse.

the class ServerConnection method processMessage.

private void processMessage(Object msg) {
    if (msg instanceof HttpObject) {
        HttpObject obj = (HttpObject) msg;
        DecoderResult result = obj.decoderResult();
        if (result.isFailure()) {
            Throwable cause = result.cause();
            if (cause instanceof TooLongFrameException) {
                String causeMsg = cause.getMessage();
                HttpVersion version;
                if (msg instanceof HttpRequest) {
                    version = ((HttpRequest) msg).protocolVersion();
                } else if (currentRequest != null) {
                    version = currentRequest.version() == io.vertx.core.http.HttpVersion.HTTP_1_0 ? HttpVersion.HTTP_1_0 : HttpVersion.HTTP_1_1;
                } else {
                    version = HttpVersion.HTTP_1_1;
                }
                HttpResponseStatus status = causeMsg.startsWith("An HTTP line is larger than") ? HttpResponseStatus.REQUEST_URI_TOO_LONG : HttpResponseStatus.BAD_REQUEST;
                DefaultFullHttpResponse resp = new DefaultFullHttpResponse(version, status);
                writeToChannel(resp);
            }
            // That will close the connection as it is considered as unusable
            channel.pipeline().fireExceptionCaught(result.cause());
            return;
        }
        if (msg instanceof HttpRequest) {
            HttpRequest request = (HttpRequest) msg;
            if (server.options().isHandle100ContinueAutomatically()) {
                if (HttpHeaders.is100ContinueExpected(request)) {
                    write100Continue();
                }
            }
            HttpServerResponseImpl resp = new HttpServerResponseImpl(vertx, this, request);
            HttpServerRequestImpl req = new HttpServerRequestImpl(this, request, resp);
            handleRequest(req, resp);
        }
        if (msg instanceof HttpContent) {
            HttpContent chunk = (HttpContent) msg;
            if (chunk.content().isReadable()) {
                Buffer buff = Buffer.buffer(chunk.content());
                handleChunk(buff);
            }
            //TODO chunk trailers
            if (msg instanceof LastHttpContent) {
                if (!paused) {
                    handleEnd();
                } else {
                    // Requeue
                    pending.add(LastHttpContent.EMPTY_LAST_CONTENT);
                }
            }
        }
    } else if (msg instanceof WebSocketFrameInternal) {
        WebSocketFrameInternal frame = (WebSocketFrameInternal) msg;
        handleWsFrame(frame);
    }
    checkNextTick();
}
Also used : Buffer(io.vertx.core.buffer.Buffer) TooLongFrameException(io.netty.handler.codec.TooLongFrameException) WebSocketFrameInternal(io.vertx.core.http.impl.ws.WebSocketFrameInternal) DecoderResult(io.netty.handler.codec.DecoderResult) HttpVersion(io.netty.handler.codec.http.HttpVersion)

Example 9 with HttpVersion

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpVersion in project riposte by Nike-Inc.

the class RequestInfoImplTest method uber_constructor_works_for_valid_values.

@Test
public void uber_constructor_works_for_valid_values() {
    // given
    String uri = "/some/uri/path/%24foobar%26?notused=blah";
    HttpMethod method = HttpMethod.PATCH;
    Charset contentCharset = CharsetUtil.US_ASCII;
    HttpHeaders headers = new DefaultHttpHeaders().add("header1", "val1").add(HttpHeaders.Names.CONTENT_TYPE, "text/text charset=" + contentCharset.displayName());
    QueryStringDecoder queryParams = new QueryStringDecoder(uri + "?foo=bar&secondparam=secondvalue");
    Set<Cookie> cookies = new HashSet<>(Arrays.asList(new DefaultCookie("cookie1", "val1"), new DefaultCookie("cookie2", "val2")));
    Map<String, String> pathParams = Arrays.stream(new String[][] { { "pathParam1", "val1" }, { "pathParam2", "val2" } }).collect(Collectors.toMap(pair -> pair[0], pair -> pair[1]));
    String content = UUID.randomUUID().toString();
    byte[] contentBytes = content.getBytes();
    LastHttpContent chunk = new DefaultLastHttpContent(Unpooled.copiedBuffer(contentBytes));
    chunk.trailingHeaders().add("trailingHeader1", "trailingVal1");
    List<HttpContent> contentChunks = Collections.singletonList(chunk);
    HttpVersion protocolVersion = HttpVersion.HTTP_1_1;
    boolean keepAlive = true;
    boolean fullRequest = true;
    boolean isMultipart = false;
    // when
    RequestInfoImpl<?> requestInfo = new RequestInfoImpl<>(uri, method, headers, chunk.trailingHeaders(), queryParams, cookies, pathParams, contentChunks, protocolVersion, keepAlive, fullRequest, isMultipart);
    // then
    assertThat("getUri should return passed in value", requestInfo.getUri(), is(uri));
    assertThat("getPath did not decode as expected", requestInfo.getPath(), is("/some/uri/path/$foobar&"));
    assertThat(requestInfo.getMethod(), is(method));
    assertThat(requestInfo.getHeaders(), is(headers));
    assertThat(requestInfo.getTrailingHeaders(), is(chunk.trailingHeaders()));
    assertThat(requestInfo.getQueryParams(), is(queryParams));
    assertThat(requestInfo.getCookies(), is(cookies));
    assertThat(requestInfo.pathTemplate, nullValue());
    assertThat(requestInfo.pathParams, is(pathParams));
    assertThat(requestInfo.getRawContentBytes(), is(contentBytes));
    assertThat(requestInfo.getRawContent(), is(content));
    assertThat(requestInfo.content, nullValue());
    assertThat(requestInfo.getContentCharset(), is(contentCharset));
    assertThat(requestInfo.getProtocolVersion(), is(protocolVersion));
    assertThat(requestInfo.isKeepAliveRequested(), is(keepAlive));
    assertThat(requestInfo.isCompleteRequestWithAllChunks, is(fullRequest));
    assertThat(requestInfo.isMultipart, is(isMultipart));
}
Also used : Cookie(io.netty.handler.codec.http.cookie.Cookie) DefaultCookie(io.netty.handler.codec.http.cookie.DefaultCookie) CoreMatchers.is(org.hamcrest.CoreMatchers.is) Arrays(java.util.Arrays) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) DataProviderRunner(com.tngtech.java.junit.dataprovider.DataProviderRunner) Unpooled(io.netty.buffer.Unpooled) CoreMatchers.notNullValue(org.hamcrest.CoreMatchers.notNullValue) CoreMatchers.instanceOf(org.hamcrest.CoreMatchers.instanceOf) Mockito.doThrow(org.mockito.Mockito.doThrow) Mockito.verifyNoMoreInteractions(org.mockito.Mockito.verifyNoMoreInteractions) Map(java.util.Map) CharsetUtil(io.netty.util.CharsetUtil) Assertions(org.assertj.core.api.Assertions) TypeReference(com.fasterxml.jackson.core.type.TypeReference) Mockito.doReturn(org.mockito.Mockito.doReturn) RequestContentDeserializationException(com.nike.riposte.server.error.exception.RequestContentDeserializationException) Set(java.util.Set) UUID(java.util.UUID) Cookie(io.netty.handler.codec.http.cookie.Cookie) InterfaceHttpData(io.netty.handler.codec.http.multipart.InterfaceHttpData) Collectors(java.util.stream.Collectors) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) Sets(com.google.common.collect.Sets) Matchers.any(org.mockito.Matchers.any) List(java.util.List) Whitebox(org.mockito.internal.util.reflection.Whitebox) Type(java.lang.reflect.Type) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) DefaultCookie(io.netty.handler.codec.http.cookie.DefaultCookie) HttpPostMultipartRequestDecoder(io.netty.handler.codec.http.multipart.HttpPostMultipartRequestDecoder) Mockito.mock(org.mockito.Mockito.mock) RequestInfo(com.nike.riposte.server.http.RequestInfo) HttpVersion(io.netty.handler.codec.http.HttpVersion) ByteArrayOutputStream(java.io.ByteArrayOutputStream) RunWith(org.junit.runner.RunWith) HashMap(java.util.HashMap) Mockito.spy(org.mockito.Mockito.spy) DataProvider(com.tngtech.java.junit.dataprovider.DataProvider) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) HashSet(java.util.HashSet) Charset(java.nio.charset.Charset) ByteBuf(io.netty.buffer.ByteBuf) ClientCookieEncoder(io.netty.handler.codec.http.cookie.ClientCookieEncoder) Assertions.catchThrowable(org.assertj.core.api.Assertions.catchThrowable) PathParameterMatchingException(com.nike.riposte.server.error.exception.PathParameterMatchingException) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) CoreMatchers.nullValue(org.hamcrest.CoreMatchers.nullValue) CoreMatchers.sameInstance(org.hamcrest.CoreMatchers.sameInstance) HttpContent(io.netty.handler.codec.http.HttpContent) FileUpload(io.netty.handler.codec.http.multipart.FileUpload) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) TestCase.fail(junit.framework.TestCase.fail) HttpMethod(io.netty.handler.codec.http.HttpMethod) Test(org.junit.Test) IOException(java.io.IOException) Mockito.verify(org.mockito.Mockito.verify) DefaultHttpContent(io.netty.handler.codec.http.DefaultHttpContent) Mockito.never(org.mockito.Mockito.never) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) QueryStringDecoder(io.netty.handler.codec.http.QueryStringDecoder) Pair(com.nike.internal.util.Pair) Collections(java.util.Collections) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) Charset(java.nio.charset.Charset) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) QueryStringDecoder(io.netty.handler.codec.http.QueryStringDecoder) DefaultCookie(io.netty.handler.codec.http.cookie.DefaultCookie) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) HttpVersion(io.netty.handler.codec.http.HttpVersion) HttpMethod(io.netty.handler.codec.http.HttpMethod) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) HttpContent(io.netty.handler.codec.http.HttpContent) DefaultHttpContent(io.netty.handler.codec.http.DefaultHttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 10 with HttpVersion

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpVersion in project riposte by Nike-Inc.

the class RequestInfoImplTest method netty_helper_constructor_populates_request_info_appropriately.

@Test
public void netty_helper_constructor_populates_request_info_appropriately() {
    // given
    String uri = "/some/uri/path/%24foobar%26?foo=bar&secondparam=secondvalue";
    Map<String, List<String>> expectedQueryParamMap = new HashMap<>();
    expectedQueryParamMap.put("foo", Arrays.asList("bar"));
    expectedQueryParamMap.put("secondparam", Arrays.asList("secondvalue"));
    HttpMethod method = HttpMethod.PATCH;
    String cookieName = UUID.randomUUID().toString();
    String cookieValue = UUID.randomUUID().toString();
    String content = UUID.randomUUID().toString();
    byte[] contentBytes = content.getBytes();
    Charset contentCharset = CharsetUtil.UTF_8;
    ByteBuf contentByteBuf = Unpooled.copiedBuffer(contentBytes);
    HttpHeaders headers = new DefaultHttpHeaders().add("header1", "val1").add(HttpHeaders.Names.CONTENT_TYPE, contentCharset).add(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE).add(HttpHeaders.Names.COOKIE, ClientCookieEncoder.LAX.encode(cookieName, cookieValue));
    HttpHeaders trailingHeaders = new DefaultHttpHeaders().add("trailingHeader1", "trailingVal1");
    HttpVersion protocolVersion = HttpVersion.HTTP_1_1;
    FullHttpRequest nettyRequestMock = mock(FullHttpRequest.class);
    doReturn(uri).when(nettyRequestMock).getUri();
    doReturn(method).when(nettyRequestMock).getMethod();
    doReturn(headers).when(nettyRequestMock).headers();
    doReturn(trailingHeaders).when(nettyRequestMock).trailingHeaders();
    doReturn(contentByteBuf).when(nettyRequestMock).content();
    doReturn(protocolVersion).when(nettyRequestMock).getProtocolVersion();
    // when
    RequestInfoImpl<?> requestInfo = new RequestInfoImpl<>(nettyRequestMock);
    // then
    assertThat("getUri was not the same value sent in", requestInfo.getUri(), is(uri));
    assertThat("getPath did not decode as expected", requestInfo.getPath(), is("/some/uri/path/$foobar&"));
    assertThat(requestInfo.getMethod(), is(method));
    assertThat(requestInfo.getHeaders(), is(headers));
    assertThat(requestInfo.getTrailingHeaders(), is(trailingHeaders));
    assertThat(requestInfo.getQueryParams(), notNullValue());
    assertThat(requestInfo.getQueryParams().parameters(), is(expectedQueryParamMap));
    assertThat(requestInfo.getCookies(), is(Sets.newHashSet(new DefaultCookie(cookieName, cookieValue))));
    assertThat(requestInfo.pathTemplate, nullValue());
    assertThat(requestInfo.pathParams.isEmpty(), is(true));
    assertThat(requestInfo.getRawContentBytes(), is(contentBytes));
    assertThat(requestInfo.getRawContent(), is(content));
    assertThat(requestInfo.content, nullValue());
    assertThat(requestInfo.getContentCharset(), is(contentCharset));
    assertThat(requestInfo.getProtocolVersion(), is(protocolVersion));
    assertThat(requestInfo.isKeepAliveRequested(), is(true));
}
Also used : HttpHeaders(io.netty.handler.codec.http.HttpHeaders) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) HashMap(java.util.HashMap) Charset(java.nio.charset.Charset) ByteBuf(io.netty.buffer.ByteBuf) DefaultCookie(io.netty.handler.codec.http.cookie.DefaultCookie) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) List(java.util.List) HttpVersion(io.netty.handler.codec.http.HttpVersion) HttpMethod(io.netty.handler.codec.http.HttpMethod) Test(org.junit.Test)

Aggregations

HttpVersion (io.netty.handler.codec.http.HttpVersion)19 HttpMethod (io.netty.handler.codec.http.HttpMethod)10 ByteBuf (io.netty.buffer.ByteBuf)8 HttpResponseStatus (io.netty.handler.codec.http.HttpResponseStatus)7 EOFException (java.io.EOFException)7 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)5 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)5 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)5 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)4 Map (java.util.Map)4 Date (java.util.Date)3 HashMap (java.util.HashMap)3 Test (org.junit.Test)3 AuditEvent (org.xipki.audit.AuditEvent)3 ResponderAndPath (org.xipki.ocsp.api.ResponderAndPath)3 DataProvider (com.tngtech.java.junit.dataprovider.DataProvider)2 Unpooled (io.netty.buffer.Unpooled)2 Channel (io.netty.channel.Channel)2 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)2 DefaultHttpHeaders (io.netty.handler.codec.http.DefaultHttpHeaders)2