List of usage examples for io.netty.handler.codec.http HttpRequest getUri
@Deprecated String getUri();
From source file:fileShare.MyHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, FullHttpMessage msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; System.out.println("==================================HttpRequest=================================="); System.out.println(msg.toString()); URI uri = new URI(request.getUri()); if (uri.getPath().startsWith("/getFile")) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < 1000; i++) { sb.append(i + ","); }// www. j a v a 2 s . co m //HttpContent httpContent = blockingFile.take(); //ByteBuf wrappedBufferA = Unpooled.wrappedBuffer(byteses); ByteBuf wrappedBufferA = copiedBuffer(sb.toString(), CharsetUtil.UTF_8); FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, wrappedBufferA); response.headers().set(CONTENT_TYPE, "application/octet-stream"); if (isKeepAlive(request)) { response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, wrappedBufferA.readableBytes()); // Write the initial line and the header. //ctx.write(response); ChannelFuture lastContentFuture = ctx.channel().writeAndFlush(response); // Decide whether to close the connection or not. if (!isKeepAlive(request)) { // Close the connection when the whole content is written out. lastContentFuture.addListener(ChannelFutureListener.CLOSE); } } if (!uri.getPath().startsWith("/form")) { // Write Menu writeMenu(ctx); return; } // responseContent.setLength(0); // responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n"); // // // if GET Method: should not try to create a HttpPostRequestDecoder // try { // decoder = new HttpPostRequestDecoder(factory, request); // } catch (ErrorDataDecoderException e1) { // e1.printStackTrace(); // responseContent.append(e1.getMessage()); // writeResponse(ctx.channel()); // ctx.channel().close(); // return; // } catch (IncompatibleDataDecoderException e1) { // // GET Method: should not try to create a HttpPostRequestDecoder // // So OK but stop here // responseContent.append(e1.getMessage()); // responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n"); // writeResponse(ctx.channel()); // return; // } // // readingChunks = HttpHeaders.isTransferEncodingChunked(request); // responseContent.append("Is Chunked: " + readingChunks + "\r\n"); // responseContent.append("IsMultipart: " + decoder.isMultipart() + "\r\n"); // 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 { // System.out.println("==================================HttpContent=================================="); // //? // System.out.println(new String(((DefaultHttpContent) chunk).content().array())); // blockingFile.put(chunk.copy()); // decoder.offer(chunk); // } catch (ErrorDataDecoderException e1) { // e1.printStackTrace(); // responseContent.append(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; // send = false; // reset(); // } // } // } }
From source file:fileShare.ShareHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; System.out.println("==================================HttpRequest=================================="); System.out.println(msg.toString()); URI uri = new URI(request.getUri()); if (uri.getPath().startsWith("/getFile")) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < 1000; i++) { sb.append(i + ","); }/*from w w w . j av a 2 s . co m*/ //HttpContent httpContent = blockingFile.take(); //ByteBuf wrappedBufferA = Unpooled.wrappedBuffer(byteses); ByteBuf wrappedBufferA = copiedBuffer(sb.toString(), CharsetUtil.UTF_8); FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, wrappedBufferA); response.headers().set(CONTENT_TYPE, "application/octet-stream"); if (isKeepAlive(request)) { response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, wrappedBufferA.readableBytes()); // Write the initial line and the header. //ctx.write(response); ChannelFuture lastContentFuture = ctx.channel().writeAndFlush(response); // Decide whether to close the connection or not. if (!isKeepAlive(request)) { // Close the connection when the whole content is written out. lastContentFuture.addListener(ChannelFutureListener.CLOSE); } } if (!uri.getPath().startsWith("/form")) { // Write Menu writeMenu(ctx); return; } responseContent.setLength(0); responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n"); // if GET Method: should not try to create a HttpPostRequestDecoder try { decoder = new HttpPostRequestDecoder(factory, request); } catch (ErrorDataDecoderException e1) { e1.printStackTrace(); responseContent.append(e1.getMessage()); writeResponse(ctx.channel()); ctx.channel().close(); return; } catch (IncompatibleDataDecoderException e1) { // GET Method: should not try to create a HttpPostRequestDecoder // So OK but stop here responseContent.append(e1.getMessage()); responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n"); writeResponse(ctx.channel()); return; } readingChunks = HttpHeaders.isTransferEncodingChunked(request); responseContent.append("Is Chunked: " + readingChunks + "\r\n"); responseContent.append("IsMultipart: " + decoder.isMultipart() + "\r\n"); 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 { System.out.println( "==================================HttpContent=================================="); //? System.out.println(new String(((DefaultHttpContent) chunk).content().array())); blockingFile.put(chunk.copy()); decoder.offer(chunk); } catch (ErrorDataDecoderException e1) { e1.printStackTrace(); responseContent.append(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; send = false; reset(); } } } }
From source file:godfinger.http.FaviconHandler.java
License:Apache License
@Override public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest request = (HttpRequest) msg; if ("/favicon.ico".equals(request.getUri())) { DefaultFullHttpResponse response = new DefaultFullHttpResponse(request.getProtocolVersion(), NOT_FOUND);/*from w w w. ja v a 2 s . co m*/ if (isKeepAlive(request)) { response.headers().set(CONNECTION, KEEP_ALIVE); ctx.writeAndFlush(response); } else { ctx.writeAndFlush(response).addListener(CLOSE); } return; } } ctx.fireChannelRead(msg); }
From source file:holon.internal.http.netty.HttpUploadServerHandlerTempl.java
License:Open Source License
@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.getUri()); if (!uri.getPath().startsWith("/form")) { // Write Menu writeMenu(ctx);//from w w w .j a v a2s. c om return; } responseContent.setLength(0); responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n"); responseContent.append("===================================\r\n"); responseContent.append("VERSION: " + request.getProtocolVersion().text() + "\r\n"); responseContent.append("REQUEST_URI: " + request.getUri() + "\r\n\r\n"); responseContent.append("\r\n\r\n"); // 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(COOKIE); if (value == null) { cookies = Collections.emptySet(); } else { cookies = CookieDecoder.decode(value); } for (Cookie cookie : cookies) { responseContent.append("COOKIE: " + cookie + "\r\n"); } responseContent.append("\r\n\r\n"); QueryStringDecoder decoderQuery = new QueryStringDecoder(request.getUri()); Map<String, List<String>> uriAttributes = decoderQuery.parameters(); for (Entry<String, List<String>> attr : uriAttributes.entrySet()) { for (String attrVal : attr.getValue()) { responseContent.append("URI: " + attr.getKey() + '=' + attrVal + "\r\n"); } } responseContent.append("\r\n\r\n"); if (request.getMethod().equals(HttpMethod.GET)) { // GET Method: should not try to create a HttpPostRequestDecoder // So stop here responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n"); // Not now: LastHttpContent will be sent writeResponse(ctx.channel()); return; } try { decoder = new HttpPostRequestDecoder(factory, request); } catch (ErrorDataDecoderException e1) { e1.printStackTrace(); responseContent.append(e1.getMessage()); writeResponse(ctx.channel()); ctx.channel().close(); return; } readingChunks = HttpHeaders.isTransferEncodingChunked(request); responseContent.append("Is Chunked: " + readingChunks + "\r\n"); responseContent.append("IsMultipart: " + decoder.isMultipart() + "\r\n"); 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(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()); } }
From source file:holon.internal.http.netty.work.NettyWorkHandler.java
License:Open Source License
@Override public void onEvent(NettyWorkEvent event) throws Exception { HttpRequest req = event.request(); router.invoke(req.getMethod().name().toLowerCase(), req.getUri().split("\\?")[0], ctx.initialize(req, event.channel(), event.formParams())); }
From source file:io.advantageous.conekt.http.impl.HttpServerImpl.java
License:Open Source License
private String getWebSocketLocation(ChannelPipeline pipeline, HttpRequest req) throws Exception { String prefix;/*ww w .j av a2 s . c o m*/ if (pipeline.get(SslHandler.class) == null) { prefix = "ws://"; } else { prefix = "wss://"; } URI uri = new URI(req.getUri()); String path = uri.getRawPath(); String loc = prefix + HttpHeaders.getHost(req) + path; String query = uri.getRawQuery(); if (query != null) { loc += "?" + query; } return loc; }
From source file:io.cettia.asity.bridge.netty4.AsityServerCodec.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; if (!accept(req)) { ctx.fireChannelRead(msg);// w w w. ja va 2s. c o m return; } if (req.getMethod() == HttpMethod.GET && req.headers().contains(HttpHeaders.Names.UPGRADE, HttpHeaders.Values.WEBSOCKET, true)) { // Because WebSocketServerHandshaker requires FullHttpRequest FullHttpRequest wsRequest = new DefaultFullHttpRequest(req.getProtocolVersion(), req.getMethod(), req.getUri()); wsRequest.headers().set(req.headers()); wsReqMap.put(ctx.channel(), wsRequest); // Set timeout to avoid memory leak ctx.pipeline().addFirst(new ReadTimeoutHandler(5)); } else { NettyServerHttpExchange http = new NettyServerHttpExchange(ctx, req); httpMap.put(ctx.channel(), http); httpActions.fire(http); } } else if (msg instanceof HttpContent) { FullHttpRequest wsReq = wsReqMap.get(ctx.channel()); if (wsReq != null) { wsReq.content().writeBytes(((HttpContent) msg).content()); if (msg instanceof LastHttpContent) { wsReqMap.remove(ctx.channel()); // Cancel timeout ctx.pipeline().remove(ReadTimeoutHandler.class); WebSocketServerHandshakerFactory factory = new WebSocketServerHandshakerFactory( getWebSocketLocation(ctx.pipeline(), wsReq), null, true); WebSocketServerHandshaker handshaker = factory.newHandshaker(wsReq); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } else { handshaker.handshake(ctx.channel(), wsReq); NettyServerWebSocket ws = new NettyServerWebSocket(ctx, wsReq, handshaker); wsMap.put(ctx.channel(), ws); wsActions.fire(ws); } } } else { NettyServerHttpExchange http = httpMap.get(ctx.channel()); if (http != null) { http.handleChunk((HttpContent) msg); } } } else if (msg instanceof WebSocketFrame) { NettyServerWebSocket ws = wsMap.get(ctx.channel()); if (ws != null) { ws.handleFrame((WebSocketFrame) msg); } } }
From source file:io.cettia.asity.bridge.netty4.AsityServerCodec.java
License:Apache License
private String getWebSocketLocation(ChannelPipeline pipeline, HttpRequest req) { return (pipeline.get(SslHandler.class) == null ? "ws://" : "wss://") + HttpHeaders.getHost(req) + req.getUri(); }
From source file:io.cettia.asity.bridge.netty4.NettyServerHttpExchangeTest.java
License:Apache License
@Override protected void startServer(int port, final Action<ServerHttpExchange> requestAction) throws Exception { bossGroup = new NioEventLoopGroup(); workerGroup = new NioEventLoopGroup(); channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override//w w w. j a va 2s . c o m public void channelActive(ChannelHandlerContext ctx) throws Exception { channels.add(ctx.channel()); } @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new HttpServerCodec()).addLast(new AsityServerCodec() { @Override protected boolean accept(HttpRequest req) { return URI.create(req.getUri()).getPath().equals(TEST_URI); } }.onhttp(requestAction)); } }); channels.add(bootstrap.bind(port).channel()); }
From source file:io.cettia.asity.bridge.netty4.NettyServerWebSocketTest.java
License:Apache License
@Override protected void startServer(int port, final Action<ServerWebSocket> websocketAction) { bossGroup = new NioEventLoopGroup(); workerGroup = new NioEventLoopGroup(); channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override/*from w w w . j a v a2 s .co m*/ public void channelActive(ChannelHandlerContext ctx) throws Exception { channels.add(ctx.channel()); } @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new HttpServerCodec()).addLast(new AsityServerCodec() { @Override protected boolean accept(HttpRequest req) { return URI.create(req.getUri()).getPath().equals(TEST_URI); } }.onwebsocket(websocketAction)); } }); channels.add(bootstrap.bind(port).channel()); }