Java Code Examples for io.netty.handler.codec.http.HttpUtil#isKeepAlive()
The following examples show how to use
io.netty.handler.codec.http.HttpUtil#isKeepAlive() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HttpServerHandler.java From ext-opensource-netty with Mozilla Public License 2.0 | 6 votes |
private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { // Generate an error page if response getStatus code is not OK (200). int statusCode = res.status().code(); if (statusCode != HttpResponseStatus.OK.code() && res.content().readableBytes() == 0) { ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8); res.content().writeBytes(buf); buf.release(); } HttpUtil.setContentLength(res, res.content().readableBytes()); // Send the response and close the connection if necessary. if (!HttpUtil.isKeepAlive(req) || statusCode != HttpResponseStatus.OK.code()) { res.headers().set(CONNECTION, CLOSE); ctx.writeAndFlush(res).addListener(ChannelFutureListener.CLOSE); } else { res.headers().set(CONNECTION, CLOSE); /// //if (req.protocolVersion().equals(HTTP_1_0)) { // res.headers().set(CONNECTION, KEEP_ALIVE); //} ctx.writeAndFlush(res).addListener(ChannelFutureListener.CLOSE); } }
Example 2
Source File: HttpHelloWorldServerHandler.java From tools-journey with Apache License 2.0 | 6 votes |
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; boolean keepAlive = HttpUtil.isKeepAlive(req); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT)); response.headers().set(CONTENT_TYPE, "text/plain"); response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes()); if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(CONNECTION, KEEP_ALIVE); ctx.write(response); } } }
Example 3
Source File: HelloWorldHandler.java From brave with Apache License 2.0 | 6 votes |
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (!(msg instanceof HttpRequest)) return; HttpRequest req = (HttpRequest) msg; if (HttpUtil.is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); } boolean keepAlive = HttpUtil.isKeepAlive(req); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(HELLO_WORLD)); response.headers().set(CONTENT_TYPE, "text/plain"); response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE); ctx.write(response); } }
Example 4
Source File: HttpHelloWorldServerHandler.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; boolean keepAlive = HttpUtil.isKeepAlive(req); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT)); response.headers().set(CONTENT_TYPE, "text/plain"); response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes()); if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(CONNECTION, KEEP_ALIVE); ctx.write(response); } } }
Example 5
Source File: NettyClient.java From ambry with Apache License 2.0 | 6 votes |
@Override public void channelRead0(ChannelHandlerContext ctx, HttpObject in) { // Make sure that we increase refCnt because we are going to process it async. The other end has to release // after processing. responseParts.offer(ReferenceCountUtil.retain(in)); if (in instanceof HttpResponse && in.decoderResult().isSuccess()) { isKeepAlive = HttpUtil.isKeepAlive((HttpResponse) in); } else if (in.decoderResult().isFailure()) { Throwable cause = in.decoderResult().cause(); if (cause instanceof Exception) { exception = (Exception) cause; } else { exception = new Exception("Encountered Throwable when trying to decode response. Message: " + cause.getMessage()); } invokeFutureAndCallback("CommunicationHandler::channelRead0 - decoder failure"); } if (in instanceof LastHttpContent) { if (isKeepAlive) { invokeFutureAndCallback("CommunicationHandler::channelRead0 - last content"); } else { // if not, the future will be invoked when the channel is closed. ctx.close(); } } }
Example 6
Source File: HttpCacheServerHandler.java From bazel with Apache License 2.0 | 6 votes |
private void handleGet(ChannelHandlerContext ctx, FullHttpRequest request) { if (!isUriValid(request.uri())) { sendError(ctx, request, HttpResponseStatus.BAD_REQUEST); return; } byte[] contents = cache.get(request.uri()); if (contents == null) { sendError(ctx, request, HttpResponseStatus.NOT_FOUND); return; } FullHttpResponse response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(contents)); HttpUtil.setContentLength(response, contents.length); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/octet-stream"); ChannelFuture lastContentFuture = ctx.writeAndFlush(response); if (!HttpUtil.isKeepAlive(request)) { lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }
Example 7
Source File: HelloWorldHttp1Handler.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
@Override public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception { if (HttpUtil.is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); } boolean keepAlive = HttpUtil.isKeepAlive(req); ByteBuf content = ctx.alloc().buffer(); content.writeBytes(HelloWorldHttp2Handler.RESPONSE_BYTES.duplicate()); ByteBufUtil.writeAscii(content, " - via " + req.protocolVersion() + " (" + establishApproach + ")"); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, content); response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8"); response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes()); if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE); ctx.write(response); } }
Example 8
Source File: HttpUploadHandler.java From bazel-buildfarm with Apache License 2.0 | 5 votes |
@SuppressWarnings("FutureReturnValueIgnored") @Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse response) { if (!response.decoderResult().isSuccess()) { failAndClose(new IOException("Failed to parse the HTTP response."), ctx); return; } try { checkState(userPromise != null, "response before request"); if (!response.status().equals(HttpResponseStatus.OK) && !response.status().equals(HttpResponseStatus.ACCEPTED) && !response.status().equals(HttpResponseStatus.CREATED) && !response.status().equals(HttpResponseStatus.NO_CONTENT)) { // Supporting more than OK status to be compatible with nginx webdav. String errorMsg = response.status().toString(); if (response.content().readableBytes() > 0) { byte[] data = new byte[response.content().readableBytes()]; response.content().readBytes(data); errorMsg += "\n" + new String(data, HttpUtil.getCharset(response)); } failAndResetUserPromise(new HttpException(response, errorMsg, null)); } else { succeedAndResetUserPromise(); } } finally { if (!HttpUtil.isKeepAlive(response)) { ctx.close(); } } }
Example 9
Source File: HttpUploadHandler.java From bazel with Apache License 2.0 | 5 votes |
@SuppressWarnings("FutureReturnValueIgnored") @Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse response) { if (!response.decoderResult().isSuccess()) { failAndClose(new IOException("Failed to parse the HTTP response."), ctx); return; } try { checkState(userPromise != null, "response before request"); if (!response.status().equals(HttpResponseStatus.OK) && !response.status().equals(HttpResponseStatus.ACCEPTED) && !response.status().equals(HttpResponseStatus.CREATED) && !response.status().equals(HttpResponseStatus.NO_CONTENT)) { // Supporting more than OK status to be compatible with nginx webdav. String errorMsg = response.status().toString(); if (response.content().readableBytes() > 0) { byte[] data = new byte[response.content().readableBytes()]; response.content().readBytes(data); errorMsg += "\n" + new String(data, HttpUtil.getCharset(response)); } failAndResetUserPromise(new HttpException(response, errorMsg, null)); } else { succeedAndResetUserPromise(); } } finally { if (!HttpUtil.isKeepAlive(response)) { ctx.close(); } } }
Example 10
Source File: DefaultPampasRequest.java From pampas with Apache License 2.0 | 5 votes |
@Override public boolean isKeepalive() { if (keepalive == null) { this.keepalive = HttpUtil.isKeepAlive(requestData); } return this.keepalive; }
Example 11
Source File: DFWSRequestHandler.java From dfactor with MIT License | 5 votes |
private void _sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse rsp) { // Generate an error page if response getStatus code is not OK (200). if (rsp.status().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(rsp.status().toString(), CharsetUtil.UTF_8); rsp.content().writeBytes(buf); buf.release(); HttpUtil.setContentLength(rsp, rsp.content().readableBytes()); } // Send the response and close the connection if necessary. ChannelFuture f = ctx.channel().writeAndFlush(rsp); if (!HttpUtil.isKeepAlive(req) || rsp.status().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } }
Example 12
Source File: CorsHandler.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
private static void respond( final ChannelHandlerContext ctx, final HttpRequest request, final HttpResponse response) { final boolean keepAlive = HttpUtil.isKeepAlive(request); HttpUtil.setKeepAlive(response, keepAlive); final ChannelFuture future = ctx.writeAndFlush(response); if (!keepAlive) { future.addListener(ChannelFutureListener.CLOSE); } }
Example 13
Source File: HttpCacheServerHandler.java From bazel with Apache License 2.0 | 5 votes |
private static void sendError( ChannelHandlerContext ctx, FullHttpRequest request, HttpResponseStatus status) { ByteBuf data = Unpooled.copiedBuffer("Failure: " + status + "\r\n", CharsetUtil.UTF_8); FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, data); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8"); response.headers().set(HttpHeaderNames.CONTENT_LENGTH, data.readableBytes()); ChannelFuture future = ctx.writeAndFlush(response); if (!HttpUtil.isKeepAlive(request)) { future.addListener(ChannelFutureListener.CLOSE); } }
Example 14
Source File: NettyHttpServletHandler.java From cxf with Apache License 2.0 | 5 votes |
protected void handleHttpServletRequest(ChannelHandlerContext ctx, HttpRequest request, NettyHttpContextHandler nettyHttpContextHandler) throws Exception { interceptOnRequestReceived(ctx, request); FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); NettyServletResponse nettyServletResponse = buildHttpServletResponse(response); NettyHttpServletRequest nettyServletRequest = buildHttpServletRequest(request, nettyHttpContextHandler.getContextPath(), ctx); nettyHttpContextHandler.handle(nettyServletRequest.getRequestURI(), nettyServletRequest, nettyServletResponse); interceptOnRequestSuccessed(ctx, response); nettyServletResponse.getWriter().flush(); boolean keepAlive = HttpUtil.isKeepAlive(request); if (keepAlive) { // Add 'Content-Length' header only for a keep-alive connection. response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); // Add keep alive header as per: // - // http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); } // write response... ChannelFuture future = ctx.write(response); if (!keepAlive) { future.addListener(ChannelFutureListener.CLOSE); } }
Example 15
Source File: AbstractWebSocketHandler.java From nano-framework with Apache License 2.0 | 5 votes |
private void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { if (res.status().code() != HttpStatusCode.SC_OK) { ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8); res.content().writeBytes(buf); buf.release(); HttpUtil.setContentLength(res, res.content().readableBytes()); } ChannelFuture f = ctx.channel().writeAndFlush(res); if (!HttpUtil.isKeepAlive(req) || res.status().code() != HttpStatusCode.SC_OK) { f.addListener(ChannelFutureListener.CLOSE); } }
Example 16
Source File: NettyPerfClient.java From ambry with Apache License 2.0 | 4 votes |
@Override public void channelRead0(ChannelHandlerContext ctx, HttpObject in) { long currentChunkReceiveTime = System.currentTimeMillis(); boolean recognized = false; if (in instanceof HttpResponse) { recognized = true; long responseReceiveStart = currentChunkReceiveTime - requestStartTime; perfClientMetrics.timeToFirstResponseChunkInMs.update(responseReceiveStart); logger.trace("Response receive has started on channel {}. Took {} ms", ctx.channel(), responseReceiveStart); response = (HttpResponse) in; if (response.status().code() >= 200 && response.status().code() < 300) { logger.trace("Request succeeded"); if (response.headers().contains("Location")) { logger.info(response.headers().get("Location")); } } else if (response.status().code() >= 300 && response.status().code() < 400) { logger.warn("Redirection code {} and headers were {}", response.status().code(), response.headers()); } else { logger.error("Response error code {} and headers were {}", response.status().code(), response.headers()); } } if (in instanceof HttpContent) { recognized = true; perfClientMetrics.delayBetweenChunkReceiveInMs.update(currentChunkReceiveTime - lastChunkReceiveTime); chunksReceived++; int bytesReceivedThisTime = ((HttpContent) in).content().readableBytes(); sizeReceived += bytesReceivedThisTime; perfClientMetrics.bytesReceiveRate.mark(bytesReceivedThisTime); if (in instanceof LastHttpContent) { long requestRoundTripTime = currentChunkReceiveTime - requestStartTime; perfClientMetrics.requestRoundTripTimeInMs.update(requestRoundTripTime); perfClientMetrics.getContentSizeInBytes.update(sizeReceived); perfClientMetrics.getChunkCount.update(chunksReceived); logger.trace( "Final content received on channel {}. Took {} ms. Total chunks received - {}. Total size received - {}", ctx.channel(), requestRoundTripTime, chunksReceived, sizeReceived); if (HttpUtil.isKeepAlive(response) && isRunning) { logger.trace("Sending new request on channel {}", ctx.channel()); sendRequest(ctx); } else if (!isRunning) { logger.info("Closing channel {} because NettyPerfClient has been shutdown", ctx.channel()); ctx.close(); } else { perfClientMetrics.requestResponseError.inc(); logger.error("Channel {} not kept alive. Last response status was {} and header was {}", ctx.channel(), response.status(), response.headers()); ctx.close(); } } } if (!recognized) { throw new IllegalStateException("Unexpected HttpObject - " + in.getClass()); } lastChunkReceiveTime = currentChunkReceiveTime; }
Example 17
Source File: SegmentedHttp1Request.java From xio with Apache License 2.0 | 4 votes |
@Override public boolean keepAlive() { return HttpUtil.isKeepAlive(delegate); }
Example 18
Source File: ClientResponseWriter.java From zuul with Apache License 2.0 | 4 votes |
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; }
Example 19
Source File: DoradoServerHandler.java From dorado with Apache License 2.0 | 4 votes |
private void handleHttpRequest(ChannelHandlerContext ctx, Object msg) { FullHttpRequest request = (FullHttpRequest) msg; FullHttpResponse response = new DefaultFullHttpResponse(request.protocolVersion(), HttpResponseStatus.OK); boolean isKeepAlive = HttpUtil.isKeepAlive(request); HttpUtil.setKeepAlive(response, isKeepAlive); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html;charset=UTF-8"); response.headers().set(HttpHeaderNames.SERVER, "Dorado"); ChannelFuture channelFuture = null; try { set(ctx.channel()); HttpRequest _request = new HttpRequestImpl(request); HttpResponse _response = new HttpResponseImpl(response); Router router = webapp.getUriRoutingRegistry().findRouteController(_request); if (router == null) { response.setStatus(HttpResponseStatus.NOT_FOUND); ByteBufUtil.writeUtf8(response.content(), String.format("Resource not found, url: [%s], http_method: [%s]", _request.getRequestURI(), _request.getMethod())); } else { router.invoke(_request, _response); } } catch (Throwable ex) { LogUtils.error("handle http request error", ex); response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR); ByteBufUtil.writeUtf8(response.content(), ExceptionUtils.toString(ex)); } finally { unset(); if (isKeepAlive) { HttpUtil.setContentLength(response, response.content().readableBytes()); } channelFuture = ctx.channel().writeAndFlush(response); if (!isKeepAlive && channelFuture != null) { channelFuture.addListener(ChannelFutureListener.CLOSE); } ReferenceCountUtil.release(msg); status.handledRequestsIncrement(); } }
Example 20
Source File: NettyRequest.java From ambry with Apache License 2.0 | 2 votes |
/** * Provides info on whether this request desires keep-alive or not. * @return {@code true} if keep-alive. {@code false} otherwise. */ protected boolean isKeepAlive() { return HttpUtil.isKeepAlive(request); }