List of usage examples for io.netty.handler.codec.http HttpHeaderNames CONTENT_TYPE
AsciiString CONTENT_TYPE
To view the source code for io.netty.handler.codec.http HttpHeaderNames CONTENT_TYPE.
Click Source Link
From source file:cn.dennishucd.nettyhttpserver.HttpServerHandler.java
License:Apache License
private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) { FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status, Unpooled.copiedBuffer("Failure: " + status + "\r\n", CharsetUtil.UTF_8)); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8"); // Close the connection as soon as the error message is sent. ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }
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//w ww. ja v a 2 s. c om 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 request body sent by the client *//* www . j a v a 2 s . c om*/ public String body() { if (body == null) { body = StringUtils.toString(bodyAsBytes(), Utils.getCharsetFromContentType(fullHttpRequest.headers().get(HttpHeaderNames.CONTENT_TYPE))); } return body; }
From source file:com.beeswax.hexbid.handler.BidHandler.java
License:Apache License
/** * // ww w .j av a2 s.com * Process full bid request with following error codes:</br> * </br> * 200 if it sets bid price in {@link BidAgentResponse} successfully.</br> * 204 if no bid is made for this request</br> * 400 if there is a parsing error {@link BidAgentRequest} or it fails to get bidding strategy.</br> * 500 if server experienced an error.</br> * * @param ChannelHandlerContext * * @return FullHttpResponse * */ public FullHttpResponse processRequest(ChannelHandlerContext ctx, FullHttpRequest request) { LOGGER.debug("/bid request"); try { final BidAgentRequest bidRequest = (BidAgentRequest) BidProtobufParser .parseProtoBytebuf(request.content(), BidAgentRequest.newBuilder()); final Optional<BidAgentResponse> bidResponse = bidder.SetBid(bidRequest); if (!bidResponse.isPresent()) { LOGGER.debug("No Bid"); return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NO_CONTENT); } final FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(bidResponse.get().toByteArray())); response.headers().set(HttpHeaderNames.CONTENT_TYPE, new AsciiString("application/x-protobuf")); return response; } catch (InvalidProtocolBufferException | IllegalArgumentException e) { return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST, Unpooled.wrappedBuffer("Bad request".getBytes())); } catch (Exception e) { LOGGER.error("Unexpected error when setting bid", e); return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR, Unpooled.wrappedBuffer("Internal error when setting bid".getBytes())); } }
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 ww .ja v a 2 s . c o m 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 2 s. c o m 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.chuck.netty4.websocket.WebSocketIndexPageHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception { // Handle a bad request. if (!req.decoderResult().isSuccess()) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); return;//from w ww .j a v a 2 s .co m } // Allow only GET methods. if (req.method() != GET) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); return; } // Send the index page if ("/".equals(req.uri()) || "/index.html".equals(req.uri())) { String webSocketLocation = getWebSocketLocation(ctx.pipeline(), req, websocketPath); ByteBuf content = WebSocketServerIndexPage.getContent(webSocketLocation); FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content); res.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8"); HttpUtil.setContentLength(res, content.readableBytes()); sendHttpResponse(ctx, req, res); } else { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND)); } }
From source file:com.cmz.http.file.HttpStaticFileServerHandler.java
License:Apache License
private static void sendListing(ChannelHandlerContext ctx, File dir, String dirPath) { FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8"); StringBuilder buf = new StringBuilder().append("<!DOCTYPE html>\r\n") .append("<html><head><meta charset='utf-8' /><title>").append("Listing of: ").append(dirPath) .append("</title></head><body>\r\n") .append("<h3>Listing of: ").append(dirPath).append("</h3>\r\n") .append("<ul>").append("<li><a href=\"../\">..</a></li>\r\n"); for (File f : dir.listFiles()) { if (f.isHidden() || !f.canRead()) { continue; }//from ww w .j ava 2s. c o m String name = f.getName(); if (!ALLOWED_FILE_NAME.matcher(name).matches()) { continue; } buf.append("<li><a href=\"").append(name).append("\">").append(name).append("</a></li>\r\n"); } buf.append("</ul></body></html>\r\n"); ByteBuf buffer = Unpooled.copiedBuffer(buf, CharsetUtil.UTF_8); response.content().writeBytes(buffer); buffer.release(); // Close the connection as soon as the error message is sent. ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }
From source file:com.cmz.http.file.HttpStaticFileServerHandler.java
License:Apache License
/** * Sets the content type header for the HTTP Response * * @param response//ww w . ja v a 2s .c o m * HTTP response * @param file * file to extract content type */ private static void setContentTypeHeader(HttpResponse response, File file) { MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap(); response.headers().set(HttpHeaderNames.CONTENT_TYPE, mimeTypesMap.getContentType(file.getPath())); }
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 ava 2 s .c o m*/ // 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; }