use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultHttpResponse 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.DefaultHttpResponse in project crate by crate.
the class HttpBlobHandler method partialContentResponse.
private void partialContentResponse(String range, HttpRequest request, String index, final String digest) throws IOException {
assert range != null : "Getting partial response but no byte-range is not present.";
Matcher matcher = CONTENT_RANGE_PATTERN.matcher(range);
if (!matcher.matches()) {
LOGGER.warn("Invalid byte-range: {}; returning full content", range);
fullContentResponse(request, index, digest);
return;
}
BlobShard blobShard = localBlobShard(index, digest);
final RandomAccessFile raf = blobShard.blobContainer().getRandomAccessFile(digest);
long start;
long end;
try {
try {
start = Long.parseLong(matcher.group(1));
if (start > raf.length()) {
LOGGER.warn("416 Requested Range not satisfiable");
simpleResponse(request, HttpResponseStatus.REQUESTED_RANGE_NOT_SATISFIABLE);
raf.close();
return;
}
end = raf.length() - 1;
if (!matcher.group(2).equals("")) {
end = Long.parseLong(matcher.group(2));
}
} catch (NumberFormatException ex) {
LOGGER.error("Couldn't parse Range Header", ex);
start = 0;
end = raf.length();
}
DefaultHttpResponse response = new DefaultHttpResponse(HTTP_1_1, PARTIAL_CONTENT);
maybeSetConnectionCloseHeader(response);
HttpUtil.setContentLength(response, end - start + 1);
Netty4CorsHandler.setCorsResponseHeaders(request, response, corsConfig);
response.headers().set(HttpHeaderNames.CONTENT_RANGE, "bytes " + start + "-" + end + "/" + raf.length());
setDefaultGetHeaders(response);
ctx.channel().write(response);
ChannelFuture writeFuture = transferFile(digest, raf, start, end - start + 1);
if (!HttpUtil.isKeepAlive(request)) {
writeFuture.addListener(ChannelFutureListener.CLOSE);
}
} catch (Throwable t) {
/*
* Make sure RandomAccessFile is closed when exception is raised.
* In case of success, the ChannelFutureListener in "transferFile" will take care
* that the resources are released.
*/
raf.close();
throw t;
}
}
use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultHttpResponse in project cxf by apache.
the class NettyHttpServletHandler method channelRead.
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
HttpRequest request = (HttpRequest) msg;
if (HttpUtil.is100ContinueExpected(request)) {
ctx.write(new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE));
}
// find the nettyHttpContextHandler by lookup the request url
NettyHttpContextHandler nettyHttpContextHandler = pipelineFactory.getNettyHttpHandler(request.uri());
if (nettyHttpContextHandler != null) {
handleHttpServletRequest(ctx, request, nettyHttpContextHandler);
} else {
throw new RuntimeException(new Fault(new Message("NO_NETTY_SERVLET_HANDLER_FOUND", LOG, request.uri())));
}
}
use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultHttpResponse in project ambry by linkedin.
the class NettyMessageProcessorTest method requestHandleWithBadInputTest.
/**
* Tests for error handling flow when bad input streams are provided to the {@link NettyMessageProcessor}.
*/
@Test
public void requestHandleWithBadInputTest() throws IOException {
String content = "@@randomContent@@@";
// content without request.
EmbeddedChannel channel = createChannel();
channel.writeInbound(new DefaultLastHttpContent(Unpooled.wrappedBuffer(content.getBytes())));
HttpResponse response = (HttpResponse) channel.readOutbound();
assertEquals("Unexpected response status", HttpResponseStatus.BAD_REQUEST, response.status());
assertFalse("Channel is not closed", channel.isOpen());
// content without request on a channel that was kept alive
channel = createChannel();
// send and receive response for a good request and keep the channel alive
channel.writeInbound(RestTestUtils.createRequest(HttpMethod.GET, MockRestRequestService.ECHO_REST_METHOD, null));
channel.writeInbound(LastHttpContent.EMPTY_LAST_CONTENT);
response = (HttpResponse) channel.readOutbound();
assertEquals("Unexpected response status", HttpResponseStatus.OK, response.status());
// drain the content
while (channel.readOutbound() != null) {
;
}
assertTrue("Channel is not active", channel.isActive());
// send content without request
channel.writeInbound(LastHttpContent.EMPTY_LAST_CONTENT);
response = (HttpResponse) channel.readOutbound();
assertEquals("Unexpected response status", HttpResponseStatus.BAD_REQUEST, response.status());
assertFalse("Channel is not closed", channel.isOpen());
// content when no content is expected.
channel = createChannel();
channel.writeInbound(RestTestUtils.createRequest(HttpMethod.GET, "/", null));
channel.writeInbound(new DefaultLastHttpContent(Unpooled.wrappedBuffer(content.getBytes())));
response = (HttpResponse) channel.readOutbound();
assertEquals("Unexpected response status", HttpResponseStatus.BAD_REQUEST, response.status());
assertFalse("Channel is not closed", channel.isOpen());
// wrong HTTPObject.
channel = createChannel();
channel.writeInbound(new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK));
response = (HttpResponse) channel.readOutbound();
assertEquals("Unexpected response status", HttpResponseStatus.BAD_REQUEST, response.status());
assertFalse("Channel is not closed", channel.isOpen());
// request while another request is in progress.
channel = createChannel();
channel.writeInbound(RestTestUtils.createRequest(HttpMethod.GET, "/", null));
channel.writeInbound(RestTestUtils.createRequest(HttpMethod.GET, "/", null));
// channel should be closed by now
assertFalse("Channel is not closed", channel.isOpen());
response = (HttpResponse) channel.readOutbound();
assertEquals("Unexpected response status", HttpResponseStatus.BAD_REQUEST, response.status());
// decoding failure
channel = createChannel();
HttpRequest httpRequest = RestTestUtils.createRequest(HttpMethod.GET, "/", null);
httpRequest.setDecoderResult(DecoderResult.failure(new IllegalStateException("Induced failure")));
channel.writeInbound(httpRequest);
// channel should be closed by now
assertFalse("Channel is not closed", channel.isOpen());
response = (HttpResponse) channel.readOutbound();
assertEquals("Unexpected response status", HttpResponseStatus.BAD_REQUEST, response.status());
// unsupported method
channel = createChannel();
channel.writeInbound(RestTestUtils.createRequest(HttpMethod.TRACE, "/", null));
// channel should be closed by now
assertFalse("Channel is not closed", channel.isOpen());
response = (HttpResponse) channel.readOutbound();
assertEquals("Unexpected response status", HttpResponseStatus.BAD_REQUEST, response.status());
}
use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultHttpResponse in project proxyee-down by monkeyWie.
the class CookieIntercept method beforeRequest.
@Override
public void beforeRequest(Channel clientChannel, HttpRequest httpRequest, HttpProxyInterceptPipeline pipeline) throws Exception {
String acceptValue = httpRequest.headers().get(HttpHeaderNames.ACCEPT);
if (acceptValue != null && acceptValue.contains("application/x-sniff-cookie")) {
HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, new DefaultHttpHeaders());
httpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0);
// https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Access-Control-Expose-Headers
AsciiString customHeadKey = AsciiString.cached("X-Sniff-Cookie");
String cookie = pipeline.getHttpRequest().headers().get(HttpHeaderNames.COOKIE);
httpResponse.headers().set(customHeadKey, cookie == null ? "" : cookie);
httpResponse.headers().set(HttpHeaderNames.ACCESS_CONTROL_EXPOSE_HEADERS, customHeadKey);
String origin = httpRequest.headers().get(HttpHeaderNames.ORIGIN);
if (StringUtil.isNullOrEmpty(origin)) {
String referer = httpRequest.headers().get(HttpHeaderNames.REFERER);
URL url = new URL(referer);
origin = url.getHost();
}
httpResponse.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, origin);
httpResponse.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS, true);
clientChannel.writeAndFlush(httpResponse);
clientChannel.writeAndFlush(new DefaultLastHttpContent());
clientChannel.close();
} else {
super.beforeRequest(clientChannel, httpRequest, pipeline);
}
}
Aggregations