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;
}
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);
}
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();
}
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));
}
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));
}
Aggregations