List of usage examples for io.netty.handler.codec.http HttpHeaderNames CONTENT_LENGTH
AsciiString CONTENT_LENGTH
To view the source code for io.netty.handler.codec.http HttpHeaderNames CONTENT_LENGTH.
Click Source Link
From source file:com.android.tools.idea.diagnostics.crash.LocalTestServer.java
License:Apache License
public void start() throws Exception { ServerBootstrap b = new ServerBootstrap(); myEventLoopGroup = new OioEventLoopGroup(); b.group(myEventLoopGroup).channel(OioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override/*from w ww . j a v a2s .c o m*/ protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(new HttpServerCodec()); // Note: Netty's decompressor uses jcraft jzlib, which is not exported as a library // p.addLast(new HttpContentDecompressor()); p.addLast(new HttpObjectAggregator(32 * 1024)); // big enough to collect a full thread dump p.addLast(new ChannelInboundHandlerAdapter() { @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (!(msg instanceof FullHttpRequest)) { return; } FullHttpResponse response = myResponseSupplier.apply((FullHttpRequest) msg); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain"); response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); ctx.write(response).addListener(ChannelFutureListener.CLOSE); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.write(cause.toString()).addListener(ChannelFutureListener.CLOSE); } }); } }); myChannel = b.bind(myPort).sync().channel(); }
From source file:com.bay1ts.bay.core.Request.java
License:Apache License
/** * @return the length of request.body// w w w. ja v a 2s . co m */ public int contentLength() { if (fullHttpRequest.headers().get(HttpHeaderNames.CONTENT_LENGTH) != null && !"".equals(fullHttpRequest.headers().get(HttpHeaderNames.CONTENT_LENGTH))) { return Integer.valueOf(fullHttpRequest.headers().get(HttpHeaderNames.CONTENT_LENGTH)); } else { return -1; } }
From source file:com.beeswax.http.handler.GlobalHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { final QueryStringDecoder queryDecoder = new QueryStringDecoder(request.uri()); LOGGER.debug("path: {}", queryDecoder.path()); // trim trailing backslash so that the handler can recognize /PATH/ final RequestHandler handler = handlerFactory.getHandler(queryDecoder.path().replaceAll("/$", "")); final FullHttpResponse response = handler.processRequest(ctx, request); response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE) .set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); ctx.writeAndFlush(response);//www. j av a2s. c o m }
From source file:com.beeswax.http.handler.GlobalHandler.java
License:Apache License
@Override public void exceptionCaught(final ChannelHandlerContext ctx, Throwable cause) { try {//from w w w. ja v a2s. co m LOGGER.error("Exception occurred. Returning empty `500` response", cause); final FullHttpResponse errResponse; if (cause instanceof IllegalArgumentException) { errResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST); } else { errResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR); } errResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, errResponse.content().readableBytes()); ctx.writeAndFlush(errResponse); } catch (Throwable t) { LOGGER.error("Error occured when returning empty `500` response", t); } }
From source file:com.bunjlabs.fuga.network.netty.NettyHttpServerHandler.java
License:Apache License
private void writeResponse(ChannelHandlerContext ctx, Request request, Response response) { HttpResponse httpresponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(response.status())); httpresponse.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED); httpresponse.headers().set(HttpHeaderNames.CONTENT_TYPE, response.contentType()); // Disable cache by default httpresponse.headers().set(HttpHeaderNames.CACHE_CONTROL, "no-cache, no-store, must-revalidate, max-age=0"); httpresponse.headers().set(HttpHeaderNames.PRAGMA, "no-cache"); httpresponse.headers().set(HttpHeaderNames.EXPIRES, "0"); response.headers().entrySet().stream().forEach((e) -> httpresponse.headers().set(e.getKey(), e.getValue())); httpresponse.headers().set(HttpHeaderNames.SERVER, "Fuga Netty Web Server/" + serverVersion); // Set cookies httpresponse.headers().set(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(NettyCookieConverter.convertListToNetty(response.cookies()))); if (response.length() >= 0) { httpresponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.length()); }/*from w w w . java 2 s .c om*/ if (HttpUtil.isKeepAlive(httprequest)) { httpresponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); } else { httpresponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE); } ctx.write(httpresponse); if (response.stream() != null) { ctx.write(new HttpChunkedInput(new ChunkedStream(response.stream()))); } LastHttpContent fs = new DefaultLastHttpContent(); ChannelFuture sendContentFuture = ctx.writeAndFlush(fs); if (!HttpUtil.isKeepAlive(httprequest)) { sendContentFuture.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.caricah.iotracah.server.httpserver.transform.IOTHttpTransformerImpl.java
License:Apache License
@Override public FullHttpMessage toServerMessage(IOTMessage internalMessage) { JSONObject json = new JSONObject(); switch (internalMessage.getMessageType()) { case AcknowledgeMessage.MESSAGE_TYPE: AcknowledgeMessage ackMsg = (AcknowledgeMessage) internalMessage; json.put("messageId", ackMsg.getMessageId()); json.put("qos", ackMsg.getQos()); json.put("message", "published"); break;/*from w ww .j a va 2s .com*/ case ConnectAcknowledgeMessage.MESSAGE_TYPE: ConnectAcknowledgeMessage conAck = (ConnectAcknowledgeMessage) internalMessage; json.put("sessionId", conAck.getSessionId()); json.put("authKey", conAck.getAuthKey()); json.put("message", conAck.getReturnCode().name()); break; case SubscribeAcknowledgeMessage.MESSAGE_TYPE: SubscribeAcknowledgeMessage subAck = (SubscribeAcknowledgeMessage) internalMessage; json.put("message", "subscribed"); final JSONArray jsonGrantedQos = new JSONArray(); subAck.getGrantedQos().forEach(jsonGrantedQos::put); json.put("grantedQos", jsonGrantedQos); break; case UnSubscribeAcknowledgeMessage.MESSAGE_TYPE: UnSubscribeAcknowledgeMessage unSubAck = (UnSubscribeAcknowledgeMessage) internalMessage; json.put("message", "unsubscribed"); break; case DisconnectMessage.MESSAGE_TYPE: DisconnectMessage discMsg = (DisconnectMessage) internalMessage; json.put("sessionId", discMsg.getSessionId()); json.put("message", "disconnected"); break; default: /** * * Internally these are not expected to get here. * In such cases we just return a null * and log this anomaly as a gross error. * **/ json.put("message", "UnExpected outcome"); break; } ByteBuf buffer = Unpooled.copiedBuffer(json.toString(), CharsetUtil.UTF_8); // Build the response object. FullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buffer); httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=UTF-8"); httpResponse.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, buffer.readableBytes()); return httpResponse; }
From source file:com.chiorichan.http.HttpResponseWrapper.java
License:Mozilla Public License
/** * Sends the data to the client. Internal Use. * * @throws IOException/*from ww w . j a v a 2 s .c om*/ * if there was a problem sending the data, like the connection was unexpectedly closed. */ public void sendResponse() throws IOException { if (stage == HttpResponseStage.CLOSED || stage == HttpResponseStage.WRITTEN) return; FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, httpStatus, output); HttpHeaders h = response.headers(); if (request.hasSession()) { Session session = request.getSession(); /** * Initiate the Session Persistence Method. * This is usually done with a cookie but we should make a param optional */ session.processSessionCookie(request.getDomain()); for (HttpCookie c : session.getCookies().values()) if (c.needsUpdating()) h.add("Set-Cookie", c.toHeaderValue()); if (session.getSessionCookie().needsUpdating()) h.add("Set-Cookie", session.getSessionCookie().toHeaderValue()); } if (h.get("Server") == null) h.add("Server", Versioning.getProduct() + " Version " + Versioning.getVersion()); // This might be a temporary measure - TODO Properly set the charset for each request. h.set("Content-Type", httpContentType + "; charset=" + encoding.name()); h.add("Access-Control-Allow-Origin", request.getLocation().getConfig().getString("site.web-allowed-origin", "*")); for (Entry<String, String> header : headers.entrySet()) h.add(header.getKey(), header.getValue()); // Expires: Wed, 08 Apr 2015 02:32:24 GMT // DateTimeFormatter formatter = DateTimeFormat.forPattern( "EE, dd-MMM-yyyy HH:mm:ss zz" ); // h.set( HttpHeaders.Names.EXPIRES, formatter.print( DateTime.now( DateTimeZone.UTC ).plusDays( 1 ) ) ); // h.set( HttpHeaders.Names.CACHE_CONTROL, "public, max-age=86400" ); h.setInt(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); h.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); stage = HttpResponseStage.WRITTEN; request.getChannel().writeAndFlush(response); }
From source file:com.cmz.http.snoop.HttpSnoopServerHandler.java
License:Apache License
private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) { // Decide whether to close the connection or not. boolean keepAlive = HttpUtil.isKeepAlive(request); // Build the response object. FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, currentObj.decoderResult().isSuccess() ? OK : BAD_REQUEST, Unpooled.copiedBuffer(buf.toString(), CharsetUtil.UTF_8)); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8"); if (keepAlive) { // Add 'Content-Length' header only for a keep-alive connection. response.headers().setInt(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); }/*from w w w .j a v a 2s. com*/ // Encode the cookie. String cookieString = request.headers().get(HttpHeaderNames.COOKIE); if (cookieString != null) { Set<Cookie> cookies = ServerCookieDecoder.STRICT.decode(cookieString); if (!cookies.isEmpty()) { // Reset the cookies if necessary. for (Cookie cookie : cookies) { response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie)); } } } else { // Browser sent no cookie. Add some. response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode("key1", "value1")); response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode("key2", "value2")); } // Write the response. ctx.write(response); return keepAlive; }
From source file:com.cmz.http.upload.HttpUploadServerHandler.java
License:Apache License
private void writeResponse(Channel channel) { // Convert the response content to a ChannelBuffer. ByteBuf buf = copiedBuffer(responseContent.toString(), CharsetUtil.UTF_8); responseContent.setLength(0);//from ww w. j a v a 2 s. c o m // Decide whether to close the connection or not. boolean close = request.headers().contains(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE, true) || request.protocolVersion().equals(HttpVersion.HTTP_1_0) && !request.headers() .contains(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE, true); // Build the response object. FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8"); if (!close) { // There's no need to add 'Content-Length' header // if this is the last response. response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, buf.readableBytes()); } Set<Cookie> cookies; String value = request.headers().get(HttpHeaderNames.COOKIE); if (value == null) { cookies = Collections.emptySet(); } else { cookies = ServerCookieDecoder.STRICT.decode(value); } if (!cookies.isEmpty()) { // Reset the cookies if necessary. for (Cookie cookie : cookies) { response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie)); } } // Write the response. ChannelFuture future = channel.writeAndFlush(response); // Close the connection after the write operation is done if necessary. if (close) { future.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.cmz.http.upload.HttpUploadServerHandler.java
License:Apache License
private void writeMenu(ChannelHandlerContext ctx) { // print several HTML forms // Convert the response content to a ChannelBuffer. responseContent.setLength(0);//from w ww . ja v a2 s . co m // create Pseudo Menu responseContent.append("<html>"); responseContent.append("<head>"); responseContent.append("<title>Netty Test Form</title>\r\n"); responseContent.append("</head>\r\n"); responseContent.append("<body bgcolor=white><style>td{font-size: 12pt;}</style>"); responseContent.append("<table border=\"0\">"); responseContent.append("<tr>"); responseContent.append("<td>"); responseContent.append("<h1>Netty Test Form</h1>"); responseContent.append("Choose one FORM"); responseContent.append("</td>"); responseContent.append("</tr>"); responseContent.append("</table>\r\n"); // GET responseContent.append("<CENTER>GET FORM<HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>"); responseContent.append("<FORM ACTION=\"/formget\" METHOD=\"GET\">"); responseContent.append("<input type=hidden name=getform value=\"GET\">"); responseContent.append("<table border=\"0\">"); responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"info\" size=10></td></tr>"); responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"secondinfo\" size=20>"); responseContent .append("<tr><td>Fill with value: <br> <textarea name=\"thirdinfo\" cols=40 rows=10></textarea>"); responseContent.append("</td></tr>"); responseContent.append("<tr><td><INPUT TYPE=\"submit\" NAME=\"Send\" VALUE=\"Send\"></INPUT></td>"); responseContent.append("<td><INPUT TYPE=\"reset\" NAME=\"Clear\" VALUE=\"Clear\" ></INPUT></td></tr>"); responseContent.append("</table></FORM>\r\n"); responseContent.append("<CENTER><HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>"); // POST responseContent.append("<CENTER>POST FORM<HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>"); responseContent.append("<FORM ACTION=\"/formpost\" METHOD=\"POST\">"); responseContent.append("<input type=hidden name=getform value=\"POST\">"); responseContent.append("<table border=\"0\">"); responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"info\" size=10></td></tr>"); responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"secondinfo\" size=20>"); responseContent .append("<tr><td>Fill with value: <br> <textarea name=\"thirdinfo\" cols=40 rows=10></textarea>"); responseContent.append("<tr><td>Fill with file (only file name will be transmitted): <br> " + "<input type=file name=\"myfile\">"); responseContent.append("</td></tr>"); responseContent.append("<tr><td><INPUT TYPE=\"submit\" NAME=\"Send\" VALUE=\"Send\"></INPUT></td>"); responseContent.append("<td><INPUT TYPE=\"reset\" NAME=\"Clear\" VALUE=\"Clear\" ></INPUT></td></tr>"); responseContent.append("</table></FORM>\r\n"); responseContent.append("<CENTER><HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>"); // POST with enctype="multipart/form-data" responseContent.append("<CENTER>POST MULTIPART FORM<HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>"); responseContent .append("<FORM ACTION=\"/formpostmultipart\" ENCTYPE=\"multipart/form-data\" METHOD=\"POST\">"); responseContent.append("<input type=hidden name=getform value=\"POST\">"); responseContent.append("<table border=\"0\">"); responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"info\" size=10></td></tr>"); responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"secondinfo\" size=20>"); responseContent .append("<tr><td>Fill with value: <br> <textarea name=\"thirdinfo\" cols=40 rows=10></textarea>"); responseContent.append("<tr><td>Fill with file: <br> <input type=file name=\"myfile\">"); responseContent.append("</td></tr>"); responseContent.append("<tr><td><INPUT TYPE=\"submit\" NAME=\"Send\" VALUE=\"Send\"></INPUT></td>"); responseContent.append("<td><INPUT TYPE=\"reset\" NAME=\"Clear\" VALUE=\"Clear\" ></INPUT></td></tr>"); responseContent.append("</table></FORM>\r\n"); responseContent.append("<CENTER><HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>"); responseContent.append("</body>"); responseContent.append("</html>"); ByteBuf buf = copiedBuffer(responseContent.toString(), CharsetUtil.UTF_8); // Build the response object. FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8"); response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, buf.readableBytes()); // Write the response. ctx.channel().writeAndFlush(response); }