List of usage examples for io.netty.handler.codec.http HttpMethod GET
HttpMethod GET
To view the source code for io.netty.handler.codec.http HttpMethod GET.
Click Source Link
From source file:com.rackspacecloud.blueflood.http.HttpRequestWithDecodedQueryParamsTest.java
License:Apache License
@Test public void testQueryParamsDecode() { final DefaultFullHttpRequest defaultRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "http://localhost/v1.0/ac98760XYZ/experimental/metric_views/metXYZ?from=12345&to=56789&points=100" + "&foo=x,y,z&foo=p"); final HttpRequestWithDecodedQueryParams requestWithParams = HttpRequestWithDecodedQueryParams .create(defaultRequest);/*from w w w .j ava 2s.c o m*/ Map<String, List<String>> queryParams = requestWithParams.getQueryParams(); Assert.assertEquals(4, queryParams.size()); final String fromParam = queryParams.get("from").get(0); final String toParam = queryParams.get("to").get(0); final String pointsParam = queryParams.get("points").get(0); List<String> fooParams = queryParams.get("foo"); Assert.assertEquals(12345, Integer.parseInt(fromParam)); Assert.assertEquals(56789, Integer.parseInt(toParam)); Assert.assertEquals(100, Integer.parseInt(pointsParam)); Assert.assertEquals(2, fooParams.size()); for (String fooParam : fooParams) { Assert.assertTrue(fooParam.equals("x,y,z") || fooParam.equals("p")); } }
From source file:com.rackspacecloud.blueflood.http.QueryStringDecoderAndRouter.java
License:Apache License
@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; }/* w w w. j av a 2s . c o m*/ } // 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)); }
From source file:com.rackspacecloud.blueflood.http.RouteMatcher.java
License:Apache License
public void route(ChannelHandlerContext context, FullHttpRequest request) { final String method = request.getMethod().name(); final String URI = request.getUri(); // Method not implemented for any resource. So return 501. if (method == null || !implementedVerbs.contains(method)) { route(context, request, unsupportedVerbsHandler); return;//from www . j av a 2 s . com } final Pattern pattern = getMatchingPatternForURL(URI); // No methods registered for this pattern i.e. URL isn't registered. Return 404. if (pattern == null) { route(context, request, noRouteHandler); return; } final Set<String> supportedMethods = getSupportedMethods(pattern); if (supportedMethods == null) { log.warn("No supported methods registered for a known pattern " + pattern); route(context, request, noRouteHandler); return; } // The method requested is not available for the resource. Return 405. if (!supportedMethods.contains(method)) { route(context, request, unsupportedMethodHandler); return; } PatternRouteBinding binding = null; if (method.equals(HttpMethod.GET.name())) { binding = getBindings.get(pattern); } else if (method.equals(HttpMethod.PUT.name())) { binding = putBindings.get(pattern); } else if (method.equals(HttpMethod.POST.name())) { binding = postBindings.get(pattern); } else if (method.equals(HttpMethod.DELETE.name())) { binding = deleteBindings.get(pattern); } else if (method.equals(HttpMethod.PATCH.name())) { binding = deleteBindings.get(pattern); } else if (method.equals(HttpMethod.OPTIONS.name())) { binding = optionsBindings.get(pattern); } else if (method.equals(HttpMethod.HEAD.name())) { binding = headBindings.get(pattern); } else if (method.equals(HttpMethod.TRACE.name())) { binding = traceBindings.get(pattern); } else if (method.equals(HttpMethod.CONNECT.name())) { binding = connectBindings.get(pattern); } if (binding != null) { request = updateRequestHeaders(request, binding); route(context, request, binding.handler); } else { throw new RuntimeException("Cannot find a valid binding for URL " + URI); } }
From source file:com.rackspacecloud.blueflood.http.RouteMatcher.java
License:Apache License
public void get(String pattern, HttpRequestHandler handler) { addBinding(pattern, HttpMethod.GET.name(), handler, getBindings); }
From source file:com.rackspacecloud.blueflood.http.RouteMatcherTest.java
License:Apache License
@Test public void testNoRouteHandler() throws Exception { final HttpRequestHandler dummyHandler = new HttpRequestHandler() { @Override// ww w. j a va 2 s .c o m public void handle(ChannelHandlerContext ctx, FullHttpRequest request) { // pass } }; routeMatcher.get("/", dummyHandler); routeMatcher.get("/blah", dummyHandler); routeMatcher.route(null, new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/chat")); Assert.assertTrue(testRouteHandlerCalled); }
From source file:com.rackspacecloud.blueflood.http.RouteMatcherTest.java
License:Apache License
@Test public void testValidRouteHandler() throws Exception { RouteMatcher router = new RouteMatcher(); router.get("/", new TestRouteHandler()); router.route(null, new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/")); Assert.assertTrue(testRouteHandlerCalled); }
From source file:com.rackspacecloud.blueflood.http.RouteMatcherTest.java
License:Apache License
private FullHttpRequest testPattern(String pattern, String URI) throws Exception { RouteMatcher router = new RouteMatcher(); final TestRouteHandler handler = new TestRouteHandler(); // Register handler for pattern router.get(pattern, handler);/*from w w w.jav a 2 s . com*/ // See if handler is called when URI matching pattern is received router.route(null, new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, URI)); // Return modified request (headers might be updated with paramsPositionMap from URI) return handler.getRequest(); }
From source file:com.sangupta.swift.netty.http.HttpStaticFileServerHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext context, FullHttpRequest request) throws Exception { if (!request.getDecoderResult().isSuccess()) { NettyUtils.sendError(context, HttpResponseStatus.BAD_REQUEST); return;/*from w w w . ja va 2 s .c o m*/ } if (request.getMethod() != HttpMethod.GET) { NettyUtils.sendError(context, HttpResponseStatus.METHOD_NOT_ALLOWED); return; } final String uri = request.getUri(); final String path = NettyUtils.sanitizeUri(uri); if (path == null) { NettyUtils.sendError(context, HttpResponseStatus.FORBIDDEN); return; } File file = new File(documentRoot, path); if (file.isHidden() || !file.exists()) { NettyUtils.sendError(context, HttpResponseStatus.NOT_FOUND); return; } if (file.isDirectory()) { if (uri.endsWith("/")) { NettyUtils.sendListing(context, file); } else { NettyUtils.sendRedirect(context, uri + '/'); } return; } if (!file.isFile()) { NettyUtils.sendError(context, HttpResponseStatus.FORBIDDEN); return; } // Cache Validation String ifModifiedSince = request.headers().get(HttpHeaders.Names.IF_MODIFIED_SINCE); if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) { Date ifModifiedSinceDate = NettyUtils.parseDateHeader(ifModifiedSince); if (ifModifiedSinceDate != null) { // Only compare up to the second because the datetime format we send to the client // does not have milliseconds long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000; long fileLastModifiedSeconds = file.lastModified() / 1000; if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) { NettyUtils.sendNotModified(context); return; } } } RandomAccessFile raf; try { raf = new RandomAccessFile(file, "r"); } catch (FileNotFoundException ignore) { NettyUtils.sendError(context, HttpResponseStatus.NOT_FOUND); return; } final long fileLength = file.length(); HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); HttpHeaders.setContentLength(response, fileLength); NettyUtils.setContentTypeHeader(response, file); NettyUtils.setDateAndCacheHeaders(response, file, 3600); // cache for an hour // check for keep alive if (HttpHeaders.isKeepAlive(request)) { response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } // Write the initial line and the header. context.write(response); // Write the content. ChannelFuture sendFileFuture; if (context.pipeline().get(SslHandler.class) == null) { sendFileFuture = context.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), context.newProgressivePromise()); } else { sendFileFuture = context.write(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)), context.newProgressivePromise()); } // sendFileFuture.addListener(new ChannelProgressiveFutureListener() { // // @Override // public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) { // if (total < 0) { // total unknown // System.err.println(future.channel() + " Transfer progress: " + progress); // } else { // System.err.println(future.channel() + " Transfer progress: " + progress + " / " + total); // } // } // // @Override // public void operationComplete(ChannelProgressiveFuture future) { // System.err.println(future.channel() + " Transfer complete."); // } // // }); // Write the end marker ChannelFuture lastContentFuture = context.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); } }
From source file:com.sangupta.swift.netty.spdy.SpdyStaticFileServerHandler.java
License:Apache License
@Override protected void channelRead0(final ChannelHandlerContext context, final FullHttpRequest request) throws Exception { if (!request.getDecoderResult().isSuccess()) { NettyUtils.sendError(context, HttpResponseStatus.BAD_REQUEST); return;/*from w w w . j a v a2s. c om*/ } // check for server name if (this.checkServerName) { String host = request.headers().get(HttpHeaders.Names.HOST); if (!host.startsWith(this.swiftServer.getServerName())) { NettyUtils.sendError(context, HttpResponseStatus.BAD_REQUEST); return; } } // check method if (request.getMethod() != HttpMethod.GET) { NettyUtils.sendError(context, HttpResponseStatus.METHOD_NOT_ALLOWED); return; } // check for SPDY support final boolean spdyRequest = request.headers().contains(NettyUtils.SPDY_STREAM_ID); // check for URI path to be proper final String uri = request.getUri(); final String path = NettyUtils.sanitizeUri(uri); if (path == null) { NettyUtils.sendError(context, HttpResponseStatus.FORBIDDEN); return; } File file = new File(documentRoot, path); if (file.isHidden() || !file.exists()) { NettyUtils.sendError(context, HttpResponseStatus.NOT_FOUND); return; } if (file.isDirectory()) { if (uri.endsWith("/")) { NettyUtils.sendListing(context, file, request.headers().get(NettyUtils.SPDY_STREAM_ID)); return; } // redirect to the listing page NettyUtils.sendRedirect(context, uri + '/'); return; } if (!file.isFile()) { NettyUtils.sendError(context, HttpResponseStatus.FORBIDDEN); return; } // Cache Validation String ifModifiedSince = request.headers().get(HttpHeaders.Names.IF_MODIFIED_SINCE); if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) { Date ifModifiedSinceDate = NettyUtils.parseDateHeader(ifModifiedSince); if (ifModifiedSinceDate != null) { // Only compare up to the second because the datetime format we send to the client // does not have milliseconds long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000; long fileLastModifiedSeconds = file.lastModified() / 1000; if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) { NettyUtils.sendNotModified(context); return; } } } RandomAccessFile raf; try { raf = new RandomAccessFile(file, "r"); } catch (FileNotFoundException ignore) { NettyUtils.sendError(context, HttpResponseStatus.NOT_FOUND); return; } final long fileLength = file.length(); HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); HttpHeaders.setContentLength(response, fileLength); NettyUtils.setContentTypeHeader(response, file); NettyUtils.setDateAndCacheHeaders(response, file, 3600); // cache for an hour // check for keep alive if (HttpHeaders.isKeepAlive(request)) { response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } else { context.write(response).addListener(ChannelFutureListener.CLOSE); } // Write the initial line and the header. context.write(response); // Write the content. ChannelFuture sendFileFuture; if (context.pipeline().get(SslHandler.class) == null) { sendFileFuture = context.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), context.newProgressivePromise()); } else { sendFileFuture = context.write(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)), context.newProgressivePromise()); } // sendFileFuture.addListener(new ChannelProgressiveFutureListener() { // // @Override // public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) { // if (total < 0) { // total unknown // System.err.println(future.channel() + " Transfer progress: " + progress); // } else { // System.err.println(future.channel() + " Transfer progress: " + progress + " / " + total); // } // } // // @Override // public void operationComplete(ChannelProgressiveFuture future) { // System.err.println(future.channel() + " Transfer complete."); // } // // }); // Write the end marker ChannelFuture lastContentFuture = context.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); } }
From source file:com.shiyq.netty.http.HttpUploadServerHandler1.java
@Override public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; URI uri = new URI(request.uri()); if (!uri.getPath().startsWith("/upload")) { // Write Menu //writeMenu(ctx); responseContent.append("{code:-1,message:''}"); writeResponse(ctx.channel()); return; }/*from w ww. ja v a 2 s. co m*/ // new getMethod for (Entry<String, String> entry : request.headers()) { responseContent.append("HEADER: " + entry.getKey() + '=' + entry.getValue() + "\r\n"); } responseContent.append("\r\n\r\n"); // new getMethod Set<Cookie> cookies; String value = request.headers().get(HttpHeaderNames.COOKIE); if (value == null) { cookies = Collections.emptySet(); } else { cookies = ServerCookieDecoder.STRICT.decode(value); } for (Cookie cookie : cookies) { responseContent.append("COOKIE: " + cookie + "\r\n"); } responseContent.append("\r\n\r\n"); QueryStringDecoder decoderQuery = new QueryStringDecoder(request.uri()); Map<String, List<String>> uriAttributes = decoderQuery.parameters(); for (Entry<String, List<String>> attr : uriAttributes.entrySet()) { for (String attrVal : attr.getValue()) { map.put(attr.getKey(), attrVal); } } // if GET Method: should not try to create a HttpPostRequestDecoder if (request.method().equals(HttpMethod.GET)) { // GET Method: should not try to create a HttpPostRequestDecoder // So stop here responseContent.append("{code:-2,message:'??get'}"); // Not now: LastHttpContent will be sent writeResponse(ctx.channel()); return; } try { decoder = new HttpPostRequestDecoder(factory, request); } catch (ErrorDataDecoderException e1) { e1.printStackTrace(); responseContent.append("{code:-3,message:'" + e1.getMessage() + "'}"); writeResponse(ctx.channel()); ctx.channel().close(); return; } readingChunks = HttpUtil.isTransferEncodingChunked(request); if (readingChunks) { // Chunk version //responseContent.append("Chunks: "); readingChunks = true; } } // check if the decoder was constructed before // if not it handles the form get if (decoder != null) { if (msg instanceof HttpContent) { // New chunk is received HttpContent chunk = (HttpContent) msg; try { decoder.offer(chunk); } catch (ErrorDataDecoderException e1) { e1.printStackTrace(); responseContent.append("{code:-4,message:'" + e1.getMessage() + "'}"); writeResponse(ctx.channel()); ctx.channel().close(); return; } //responseContent.append('o'); // example of reading chunk by chunk (minimize memory usage due to // Factory) readHttpDataChunkByChunk(); // example of reading only if at the end if (chunk instanceof LastHttpContent) { writeResponse(ctx.channel()); readingChunks = false; reset(); } } } else { writeResponse(ctx.channel()); } }