Java Code Examples for io.netty.handler.codec.http.FullHttpRequest#getMethod()
The following examples show how to use
io.netty.handler.codec.http.FullHttpRequest#getMethod() .
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: ChunkEndPoint.java From ThinkMap with Apache License 2.0 | 6 votes |
@Override public void handle(ChannelHandlerContext context, URI uri, FullHttpRequest request) { FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, context.alloc().buffer()); response.headers().add("Access-Control-Allow-Origin", "*"); response.headers().add("Access-Control-Allow-Methods", "POST"); if (request.getMethod() == OPTIONS) { response.headers().add("Access-Control-Allow-Headers", "origin, content-type, accept"); } if (request.getMethod() == POST) { String[] args = request.content().toString(Charsets.UTF_8).split(":"); ByteBuf out = response.content(); if (plugin.getChunkManager(plugin.getTargetWorld()).getChunkBytes(Integer.parseInt(args[0]), Integer.parseInt(args[1]), out)) { response.headers().add("Content-Encoding", "gzip"); } else { out.writeBytes(new byte[1]); } } sendHttpResponse(context, request, response); }
Example 2
Source File: QueryStringDecoderAndRouter.java From blueflood with Apache License 2.0 | 6 votes |
@Override public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { // for POST requests, check Content-Type header if ( request.getMethod() == HttpMethod.POST ) { if (!mediaTypeChecker.isContentTypeValid(request.headers())) { DefaultHandler.sendErrorResponse(ctx, request, String.format("Unsupported media type for Content-Type: %s", request.headers().get(HttpHeaders.Names.CONTENT_TYPE)), HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE ); return; } } // for GET or POST requests, check Accept header if ( request.getMethod() == HttpMethod.GET || request.getMethod() == HttpMethod.POST ) { if (!mediaTypeChecker.isAcceptValid(request.headers())) { DefaultHandler.sendErrorResponse(ctx, request, String.format("Unsupported media type for Accept: %s", request.headers().get(HttpHeaders.Names.ACCEPT)), HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE ); return; } } router.route(ctx, HttpRequestWithDecodedQueryParams.create(request)); }
Example 3
Source File: ServiceConnector.java From JgFramework with Apache License 2.0 | 6 votes |
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception { // Handle a bad request. if (!req.getDecoderResult().isSuccess()) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); return; } if (req.getMethod() != GET) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); return; } if (!WEB_SOCKET_PATH.equals(req.getUri())) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); return; } // Handshake WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory( getWebSocketLocation(req), null, true); handshake = wsFactory.newHandshaker(req); if (handshake == null) { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } else { handshake.handshake(ctx.channel(), req); } }
Example 4
Source File: TestHttp.java From netty-pubsub with MIT License | 5 votes |
@Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception { // TODO Auto-generated method stub try { ByteBuf content = msg.content(); byte[] bts = new byte[content.readableBytes()]; content.readBytes(bts); String result = null; if(msg.getMethod() == HttpMethod.GET) { String url = msg.getUri().toString(); //result = "get method and paramters is "+JSON.toJSONString(UrlUtil.parse(url).params); }else if(msg.getMethod() == HttpMethod.POST) { result = "post method and paramters is "+ new String(bts); } FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); response.headers().set("content-Type","text/html;charset=UTF-8"); StringBuilder sb = new StringBuilder(); sb.append("<html>") .append("<head>") .append("<title>netty http server</title>") .append("</head>") .append("<body>") .append(result) .append("</body>") .append("</html>\r\n"); ByteBuf responseBuf = Unpooled.copiedBuffer(sb,CharsetUtil.UTF_8); response.content().writeBytes(responseBuf); responseBuf.release(); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }catch (Exception e) { e.printStackTrace(); } }
Example 5
Source File: HttpHandler.java From netty-pubsub with MIT License | 5 votes |
@Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception { // TODO Auto-generated method stub try { ByteBuf content = msg.content(); byte[] bts = new byte[content.readableBytes()]; content.readBytes(bts); String result = null; if(msg.getMethod() == HttpMethod.GET) { String url = msg.getUri().toString(); result =JSON.toJSONString(UrlUtil.parse(url).params); doGet(result); }else if(msg.getMethod() == HttpMethod.POST) { //result = "post method and paramters is "+ new String(bts); doPost(new String(bts,"utf-8")); } FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); response.headers().set("content-Type","text/html;charset=UTF-8"); StringBuilder sb = new StringBuilder(); sb.append("OK"); ByteBuf responseBuf = Unpooled.copiedBuffer(sb,CharsetUtil.UTF_8); response.content().writeBytes(responseBuf); responseBuf.release(); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }catch (Exception e) { e.printStackTrace(); } }
Example 6
Source File: WebsocketSinkServerHandler.java From spring-cloud-stream-app-starters with Apache License 2.0 | 5 votes |
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) { // Handle a bad request. if (!req.getDecoderResult().isSuccess()) { logger.warn(String.format("Bad request: %s", req.getUri())); sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); return; } // Allow only GET methods. if (req.getMethod() != GET) { logger.warn(String.format("Unsupported HTTP method: %s", req.getMethod())); sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); return; } // enable subclasses to do additional processing if (!additionalHttpRequestHandler(ctx, req)) { 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); WebsocketSinkServer.channels.add(ctx.channel()); } }
Example 7
Source File: WebSocketServerProtocolHandshakeHandler.java From netty4.0.27Learn with Apache License 2.0 | 5 votes |
@Override public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception { FullHttpRequest req = (FullHttpRequest) msg; try { if (req.getMethod() != GET) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); return; } final WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory( getWebSocketLocation(ctx.pipeline(), req, websocketPath), subprotocols, allowExtensions, maxFramePayloadSize); final WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } else { final ChannelFuture handshakeFuture = handshaker.handshake(ctx.channel(), req); handshakeFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { ctx.fireExceptionCaught(future.cause()); } else { ctx.fireUserEventTriggered( WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE); } } }); WebSocketServerProtocolHandler.setHandshaker(ctx, handshaker); ctx.pipeline().replace(this, "WS403Responder", WebSocketServerProtocolHandler.forbiddenHttpRequestResponder()); } } finally { req.release(); } }
Example 8
Source File: StockTickerServerHandler.java From khs-stockticker with Apache License 2.0 | 4 votes |
protected void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception { // Handle a bad request. if (!req.getDecoderResult().isSuccess()) { httpFileHandler.sendError(ctx, HttpResponseStatus.BAD_REQUEST); return; } // If you're going to do normal HTTP POST authentication before upgrading the // WebSocket, the recommendation is to handle it right here if (req.getMethod() == HttpMethod.POST) { httpFileHandler.sendError(ctx, HttpResponseStatus.FORBIDDEN); return; } // Allow only GET methods. if (req.getMethod() != HttpMethod.GET) { httpFileHandler.sendError(ctx, HttpResponseStatus.FORBIDDEN); return; } // Send the demo page and favicon.ico if ("/".equals(req.getUri())) { httpFileHandler.sendRedirect(ctx, "/index.html"); return; } // check for websocket upgrade request String upgradeHeader = req.headers().get("Upgrade"); if (upgradeHeader != null && "websocket".equalsIgnoreCase(upgradeHeader)) { // Handshake. Ideally you'd want to configure your websocket uri String url = "ws://" + req.headers().get("Host") + "/wsticker"; WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(url, null, false); handshaker = wsFactory.newHandshaker(req); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } else { handshaker.handshake(ctx.channel(), req); } } else { boolean handled = handleREST(ctx, req); if (!handled) { httpFileHandler.sendFile(ctx, req); } } }
Example 9
Source File: HttpClasspathServerHandler.java From camunda-bpm-workbench with GNU Affero General Public License v3.0 | 4 votes |
@Override public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (!request.getDecoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST); return; } if (request.getMethod() != GET) { sendError(ctx, METHOD_NOT_ALLOWED); return; } final String uri = request.getUri(); final String path = sanitizeUri(uri); if (path == null) { sendError(ctx, FORBIDDEN); return; } // Cache Validation String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE); if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) { SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US); Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince); // Only compare up to the second because the datetime format we send to the client // does not have milliseconds long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000; // we use the start time of the JVM as last modified date long lastModifiedSeconds = ManagementFactory.getRuntimeMXBean().getStartTime(); if (ifModifiedSinceDateSeconds == lastModifiedSeconds) { sendNotModified(ctx); return; } } ClassLoader classLoader = HttpClasspathServerHandler.class.getClassLoader(); InputStream stream = classLoader.getResourceAsStream(path); if(stream == null) { sendError(ctx, NOT_FOUND); return; } HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); HttpHeaders.setContentLength(response, stream.available()); setContentTypeHeader(response, path); setDateAndCacheHeaders(response); if (HttpHeaders.isKeepAlive(request)) { response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } // Write the initial line and the header. ctx.write(response); // Write the content. ChannelFuture sendFileFuture = ctx.write(new ChunkedStream(stream), ctx.newProgressivePromise()); // Write the end marker. ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); // Decide whether to close the connection or not. if (!HttpHeaders.isKeepAlive(request)) { // Close the connection when the whole content is written out. lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }
Example 10
Source File: InternalWebServer.java From ThinkMap with Apache License 2.0 | 4 votes |
@Override public void handle(ChannelHandlerContext context, URI uri, FullHttpRequest request) throws Exception { if (request.getMethod() != HttpMethod.GET) { sendHttpResponse(context, request, new DefaultFullHttpResponse(HTTP_1_1, METHOD_NOT_ALLOWED)); return; } String modified = request.headers().get(IF_MODIFIED_SINCE); if (modified != null && !modified.isEmpty()) { Date modifiedDate = format.parse(modified); if (modifiedDate.equals(plugin.getStartUpDate())) { sendHttpResponse(context, request, new DefaultFullHttpResponse(HTTP_1_1, NOT_MODIFIED)); return; } } String path = uri.getPath(); if (path.equals("/")) { path = "/index.html"; } ByteBuf buffer; try (InputStream stream = this.getClass().getClassLoader().getResourceAsStream("www" + path)) { if (stream == null) { sendHttpResponse(context, request, new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND)); return; } ByteBufOutputStream out = new ByteBufOutputStream(context.alloc().buffer()); IOUtils.copy(stream, out); buffer = out.buffer(); out.close(); } if (path.equals("/index.html")) { String page = buffer.toString(Charsets.UTF_8); page = page.replaceAll("%SERVERPORT%", Integer.toString(plugin.getConfiguration().getPort())); buffer.release(); buffer = Unpooled.wrappedBuffer(page.getBytes(Charsets.UTF_8)); } FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, buffer); response.headers().set(DATE, format.format(new Date())); response.headers().set(LAST_MODIFIED, format.format(plugin.getStartUpDate())); String ext = path.substring(path.lastIndexOf('.') + 1); String type = mimeTypes.containsKey(ext) ? mimeTypes.get(ext) : "text/plain"; if (type.startsWith("text/")) { type += "; charset=UTF-8"; } response.headers().set(CONTENT_TYPE, type); sendHttpResponse(context, request, response); }