List of usage examples for io.netty.handler.codec.http HttpHeaders setContentLength
@Deprecated public static void setContentLength(HttpMessage message, long length)
From source file:adalightserver.http.HttpServer.java
License:Apache License
@SuppressWarnings("unused") private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, String response) { FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK); ByteBuf buf = Unpooled.copiedBuffer(response, CharsetUtil.US_ASCII); res.content().writeBytes(buf);//from w w w .j a v a2 s. c o m buf.release(); res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8"); HttpHeaders.setContentLength(res, res.content().readableBytes()); sendHttpResponse(ctx, req, res); }
From source file:adalightserver.http.HttpServer.java
License:Apache License
private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { // res.headers().set("Access-Control-Allow-Methods", "POST, OPTIONS, GET"); // res.headers().set("Access-Control-Allow-Origin", "*"); // res.headers().set("Access-Control-Allow-Headers", "*"); // Generate an error page if response getStatus code is not OK (200). if (res.getStatus().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8); res.content().writeBytes(buf);/* w ww. j a va 2s . c om*/ buf.release(); HttpHeaders.setContentLength(res, res.content().readableBytes()); } // Send the response and close the connection if necessary. ChannelFuture f = ctx.channel().writeAndFlush(res); if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } }
From source file:ca.lambtoncollege.netty.webSocket.ServerHandlerWebSocket.java
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) { // Handle a bad request. if (!req.getDecoderResult().isSuccess()) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); return;/* ww w.j a va 2 s. c o m*/ } // Allow only GET methods. if (req.getMethod() != GET) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); return; } // Send the demo page and favicon.ico if ("/".equals(req.getUri())) { ByteBuf content = ServerIndexPageWebSocket.getContent(getWebSocketLocation(req)); FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content); res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8"); HttpHeaders.setContentLength(res, content.readableBytes()); sendHttpResponse(ctx, req, res); return; } if ("/favicon.ico".equals(req.getUri())) { FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND); sendHttpResponse(ctx, req, res); return; } // Handshake WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req), null, true); handshaker = wsFactory.newHandshaker(req); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } else { handshaker.handshake(ctx.channel(), req); } }
From source file:ca.lambtoncollege.netty.webSocket.ServerHandlerWebSocket.java
private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { // Generate an error page if response getStatus code is not OK (200). if (res.getStatus().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8); res.content().writeBytes(buf);/* w w w . ja v a2 s .c o m*/ buf.release(); HttpHeaders.setContentLength(res, res.content().readableBytes()); } // Send the response and close the connection if necessary. ChannelFuture f = ctx.channel().writeAndFlush(res); if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } }
From source file:cn.npt.net.websocket.WebSocketServerHandler.java
License:Apache License
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) { // Handle a bad request. if (!req.getDecoderResult().isSuccess()) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); return;/*from w w w . j av a 2 s . c om*/ } // Allow only GET methods. if (req.getMethod() != GET) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); return; } // Send the demo page and favicon.ico if ("/".equals(req.getUri())) { ByteBuf content = WebSocketServerIndexPage.getContent(getWebSocketLocation(req)); FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content); res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8"); HttpHeaders.setContentLength(res, content.readableBytes()); sendHttpResponse(ctx, req, res); return; } if ("/favicon.ico".equals(req.getUri())) { FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND); sendHttpResponse(ctx, req, res); return; } // Handshake WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req), null, true); handshaker = wsFactory.newHandshaker(req); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } else { handshaker.handshake(ctx.channel(), req); } }
From source file:com.barchart.http.server.PooledServerResponse.java
License:BSD License
@Override public void setContentLength(final int length) { HttpHeaders.setContentLength(this, length); }
From source file:com.bloom.zerofs.rest.HealthCheckHandler.java
License:Open Source License
@Override public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception { logger.trace("Reading on channel {}", ctx.channel()); boolean forwardObj = false; if (obj instanceof HttpRequest) { if (request == null && ((HttpRequest) obj).getUri().equals(healthCheckUri)) { nettyMetrics.healthCheckRequestRate.mark(); startTimeInMs = System.currentTimeMillis(); logger.trace("Handling health check request while in state " + restServerState.isServiceUp()); request = (HttpRequest) obj; if (restServerState.isServiceUp()) { response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(GOOD)); HttpHeaders.setKeepAlive(response, HttpHeaders.isKeepAlive(request)); HttpHeaders.setContentLength(response, GOOD.length); } else { response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.SERVICE_UNAVAILABLE, Unpooled.wrappedBuffer(BAD)); HttpHeaders.setKeepAlive(response, false); HttpHeaders.setContentLength(response, BAD.length); }//ww w .j a va 2 s . c o m nettyMetrics.healthCheckRequestProcessingTimeInMs .update(System.currentTimeMillis() - startTimeInMs); } else { // Rest server could be down even if not for health check request. We intentionally don't take any action in this // handler for such cases and leave it to the downstream handlers to handle it forwardObj = true; } } if (obj instanceof LastHttpContent) { if (response != null) { // response was created when we received the request with health check uri ChannelFuture future = ctx.writeAndFlush(response); if (!HttpHeaders.isKeepAlive(response)) { future.addListener(ChannelFutureListener.CLOSE); } request = null; response = null; nettyMetrics.healthCheckRequestRoundTripTimeInMs.update(System.currentTimeMillis() - startTimeInMs); } else { // request was not for health check uri forwardObj = true; } } else if (request == null) { // http Content which is not LastHttpContent is not intended for this handler forwardObj = true; } if (forwardObj) { super.channelRead(ctx, obj); } else { ReferenceCountUtil.release(obj); } }
From source file:com.bloom.zerofs.rest.NettyResponseChannel.java
License:Open Source License
/** * Provided a cause, returns an error response with the right status and error message. * @param cause the cause of the error.// w w w. j a v a 2s . c om * @return a {@link FullHttpResponse} with the error message that can be sent to the client. */ private FullHttpResponse getErrorResponse(Throwable cause) { HttpResponseStatus status; StringBuilder errReason = new StringBuilder(); if (cause instanceof RestServiceException) { RestServiceErrorCode restServiceErrorCode = ((RestServiceException) cause).getErrorCode(); errorResponseStatus = ResponseStatus.getResponseStatus(restServiceErrorCode); status = getHttpResponseStatus(errorResponseStatus); if (status == HttpResponseStatus.BAD_REQUEST) { errReason.append(" [").append(Utils.getRootCause(cause).getMessage()).append("]"); } } else { nettyMetrics.internalServerErrorCount.inc(); status = HttpResponseStatus.INTERNAL_SERVER_ERROR; errorResponseStatus = ResponseStatus.InternalServerError; } String fullMsg = "Failure: " + status + errReason; logger.trace("Constructed error response for the client - [{}]", fullMsg); FullHttpResponse response; if (request != null && !request.getRestMethod().equals(RestMethod.HEAD)) { response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, Unpooled.wrappedBuffer(fullMsg.getBytes())); } else { // for HEAD, we cannot send the actual body but we need to return what the length would have been if this was GET. // https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html (Section 9.4) response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status); } HttpHeaders.setDate(response, new GregorianCalendar().getTime()); HttpHeaders.setContentLength(response, fullMsg.length()); HttpHeaders.setHeader(response, HttpHeaders.Names.CONTENT_TYPE, "text/plain; charset=UTF-8"); boolean keepAlive = !forceClose && HttpHeaders.isKeepAlive(responseMetadata) && request != null && !request.getRestMethod().equals(RestMethod.POST) && !CLOSE_CONNECTION_ERROR_STATUSES.contains(status); HttpHeaders.setKeepAlive(response, keepAlive); return response; }
From source file:com.corundumstudio.socketio.handler.EncoderHandler.java
License:Apache License
private void sendMessage(HttpMessage msg, Channel channel, ByteBuf out, String type) { HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK); res.headers().add(CONTENT_TYPE, type).add("Set-Cookie", "io=" + msg.getSessionId()).add(CONNECTION, KEEP_ALIVE);/*from w w w . ja v a2 s .com*/ addOriginHeaders(channel, res); HttpHeaders.setContentLength(res, out.readableBytes()); // prevent XSS warnings on IE // https://github.com/LearnBoost/socket.io/pull/1333 String userAgent = channel.attr(EncoderHandler.USER_AGENT).get(); if (userAgent != null && (userAgent.contains(";MSIE") || userAgent.contains("Trident/"))) { res.headers().add("X-XSS-Protection", "0"); } sendMessage(msg, channel, out, res); }
From source file:com.corundumstudio.socketio.SocketIOEncoder.java
License:Apache License
private HttpResponse createHttpResponse(String origin, ByteBuf message) { HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK); HttpHeaders.addHeader(res, CONTENT_TYPE, "text/plain; charset=UTF-8"); HttpHeaders.addHeader(res, CONNECTION, KEEP_ALIVE); if (origin != null) { HttpHeaders.addHeader(res, ACCESS_CONTROL_ALLOW_ORIGIN, origin); HttpHeaders.addHeader(res, ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); }/*from ww w.ja v a 2 s . c o m*/ HttpHeaders.setContentLength(res, message.readableBytes()); return res; }