List of usage examples for io.netty.channel ChannelHandlerContext pipeline
ChannelPipeline pipeline();
From source file:netty.http2.NettyHttp2ClientInitializer.java
License:Apache License
/** * Configure the pipeline for TLS NPN negotiation to HTTP/2. *///from w ww.j a va 2s. co m private void configureSsl(SocketChannel ch) { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(sslCtx.newHandler(ch.alloc())); // We must wait for the handshake to finish and the protocol to be negotiated before configuring // the HTTP/2 components of the pipeline. pipeline.addLast(new ApplicationProtocolNegotiationHandler("") { @Override protected void configurePipeline(ChannelHandlerContext ctx, String protocol) { if (ApplicationProtocolNames.HTTP_2.equals(protocol)) { System.out.println("HTTP/2 Negotiated"); ChannelPipeline p = ctx.pipeline(); p.addLast(connectionHandler); configureEndOfPipeline(p); return; } ctx.close(); throw new IllegalStateException("unknown protocol: " + protocol); } }); }
From source file:Netty4.book.http.file.HttpStaticFileServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (!request.decoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST);/*from w ww .j a v a 2 s. co m*/ return; } if (request.method() != GET) { sendError(ctx, METHOD_NOT_ALLOWED); return; } final String uri = request.uri(); final String path = sanitizeUri(uri); if (path == null) { sendError(ctx, FORBIDDEN); return; } File file = new File(path); if (file.isHidden() || !file.exists()) { sendError(ctx, NOT_FOUND); return; } if (file.isDirectory()) { if (uri.endsWith("/")) { sendListing(ctx, file); } else { sendRedirect(ctx, uri + '/'); } return; } if (!file.isFile()) { sendError(ctx, FORBIDDEN); return; } // Cache Validation String ifModifiedSince = request.headers().get(HttpHeaderNames.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; long fileLastModifiedSeconds = file.lastModified() / 1000; if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) { sendNotModified(ctx); return; } } RandomAccessFile raf; try { raf = new RandomAccessFile(file, "r"); } catch (FileNotFoundException ignore) { sendError(ctx, NOT_FOUND); return; } long fileLength = raf.length(); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); HttpHeaders.setContentLength(response, fileLength); setContentTypeHeader(response, file); setDateAndCacheHeaders(response, file); if (HttpHeaders.isKeepAlive(request)) { response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); } // Write the initial line and the header. ctx.write(response); // Write the content. ChannelFuture sendFileFuture; ChannelFuture lastContentFuture; if (ctx.pipeline().get(SslHandler.class) == null) { sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise()); // Write the end marker. lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); } else { sendFileFuture = ctx.writeAndFlush(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)), ctx.newProgressivePromise()); // HttpChunkedInput will write the end marker (LastHttpContent) for us. lastContentFuture = sendFileFuture; } sendFileFuture.addListener(new ChannelProgressiveFutureListener() { 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); } } public void operationComplete(ChannelProgressiveFuture future) throws Exception { System.err.println(future.channel() + " Transfer complete."); } } ); // Decide whether to close the connection or not. if (!HttpUtil.isKeepAlive(request)) { // Close the connection when the whole content is written out. lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }
From source file:netty4.fileExample.FileServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { RandomAccessFile raf = null;/* ww w. ja v a 2 s . c o m*/ long length = -1; try { raf = new RandomAccessFile(msg, "r"); length = raf.length(); } catch (Exception e) { ctx.writeAndFlush("ERR: " + e.getClass().getSimpleName() + ": " + e.getMessage() + '\n'); return; } finally { if (length < 0 && raf != null) { raf.close(); } } ctx.write("OK: " + raf.length() + '\n'); if (ctx.pipeline().get(SslHandler.class) == null) { // SSL not enabled - can use zero-copy file transfer. ctx.write(new DefaultFileRegion(raf.getChannel(), 0, length)); System.out.println("zero-copy"); } else { // SSL enabled - cannot use zero-copy file transfer. ctx.write(new ChunkedFile(raf)); System.out.println("non zero-copy"); } //ctx.writeAndFlush("\n"); ChannelFuture writeFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); }
From source file:netty5.http.server.Http2OrHttpHandler.java
License:Apache License
@Override protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception { if (ApplicationProtocolNames.HTTP_2.equals(protocol)) { ctx.pipeline().addLast(new HelloWorldHttp2Handler()); return;//from w ww . j a v a2 s .c o m } if (ApplicationProtocolNames.HTTP_1_1.equals(protocol)) { ctx.pipeline().addLast(new HttpServerCodec(), new HttpObjectAggregator(MAX_CONTENT_LENGTH), new HelloWorldHttp1Handler("ALPN Negotiation")); return; } throw new IllegalStateException("unknown protocol: " + protocol); }
From source file:netty5.http.server.Http2ServerInitializer.java
License:Apache License
/** * Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2. *//*from www.j a va 2 s. c o m*/ private static void configureClearText(SocketChannel ch) { final ChannelPipeline p = ch.pipeline(); final HttpServerCodec sourceCodec = new HttpServerCodec(); p.addLast(sourceCodec); p.addLast(new HttpServerUpgradeHandler(sourceCodec, upgradeCodecFactory)); p.addLast(new SimpleChannelInboundHandler<HttpMessage>() { @Override protected void messageReceived(ChannelHandlerContext ctx, HttpMessage msg) throws Exception { // If this handler is hit then no upgrade has been attempted and the client is just talking HTTP. System.err.println("Directly talking: " + msg.protocolVersion() + " (no upgrade was attempted)"); ctx.pipeline().replace(this, "http-hello-world", new HelloWorldHttp1Handler("Direct. No Upgrade Attempted.")); ctx.fireChannelRead(msg); } }); p.addLast(new UserEventLogger()); }
From source file:nettyFileServer.FileServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { msg = "index.html"; RandomAccessFile raf = null;/*from www .j av a 2 s . c o m*/ long length = -1; try { raf = new RandomAccessFile(msg, "r"); length = raf.length(); } catch (Exception e) { ctx.writeAndFlush("ERR: " + e.getClass().getSimpleName() + ": " + e.getMessage() + '\n'); return; } finally { if (length < 0 && raf != null) { raf.close(); } } ctx.write("OK: " + raf.length() + '\n'); if (ctx.pipeline().get(SslHandler.class) == null) { // SSL not enabled - can use zero-copy file transfer. ctx.write(new DefaultFileRegion(raf.getChannel(), 0, length)); } else { // SSL enabled - cannot use zero-copy file transfer. ctx.write(new ChunkedFile(raf)); } ctx.writeAndFlush("\n"); }
From source file:nl.thijsalders.spigotproxy.haproxy.HAProxyMessageDecoder.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { super.channelRead(ctx, msg); if (finished) { ctx.pipeline().remove(this); }//www. j av a 2 s . c o m }
From source file:nz.co.fortytwo.signalk.server.NettyServer.java
License:Open Source License
@Override public void process(Exchange exchange) throws Exception { logger.debug("Received msg : " + exchange.getIn().getBody()); String msg = exchange.getIn().getBody().toString(); if (msg != null) { //get the session String session = exchange.getIn().getHeader(WebsocketConstants.CONNECTION_KEY, String.class); if (WebsocketConstants.SEND_TO_ALL.equals(session)) { //udp if (udpPort > 0 && udpChannel != null && udpChannel.isWritable()) { for (InetSocketAddress client : udpHandler.getSessionList().values()) { if (logger.isDebugEnabled()) logger.debug("Sending udp: " + exchange.getIn().getBody()); //udpCtx.pipeline().writeAndFlush(msg+"\r\n"); udpChannel.writeAndFlush( new DatagramPacket(Unpooled.copiedBuffer(msg + "\r\n", CharsetUtil.UTF_8), client)); if (logger.isDebugEnabled()) logger.debug("Sent udp to " + client); }//ww w .ja va2s. c om } //tcp for (String key : forwardingHandler.getContextList().keySet()) { ChannelHandlerContext ctx = forwardingHandler.getChannel(key); if (ctx != null && ctx.channel().isWritable()) ctx.pipeline().writeAndFlush(msg + "\r\n"); } } else { //udp if (udpPort > 0 && udpChannel != null && udpChannel.isWritable()) { final InetSocketAddress client = udpHandler.getSessionList().get(session); if (logger.isDebugEnabled()) logger.debug("Sending udp: " + exchange.getIn().getBody()); //udpCtx.pipeline().writeAndFlush(msg+"\r\n"); udpChannel.writeAndFlush( new DatagramPacket(Unpooled.copiedBuffer(msg + "\r\n", CharsetUtil.UTF_8), client)); if (logger.isDebugEnabled()) logger.debug("Sent udp for session: " + session); //TODO: how do we tell when a UDP client is gone } //tcp ChannelHandlerContext ctx = forwardingHandler.getChannel(session); if (ctx != null && ctx.channel().isWritable()) ctx.pipeline().writeAndFlush(msg + "\r\n"); } } }
From source file:org.aesh.terminal.http.netty.TtyWebSocketFrameHandler.java
License:Open Source License
@Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt == WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE) { ctx.pipeline().remove(HttpRequestHandler.class); group.add(ctx.channel());/* w w w . j av a2 s . co m*/ conn = new HttpTtyConnection() { @Override protected void write(byte[] buffer) { ByteBuf byteBuf = Unpooled.buffer(); byteBuf.writeBytes(buffer); context.writeAndFlush(new TextWebSocketFrame(byteBuf)); } public void schedule(Runnable task, long delay, TimeUnit unit) { context.executor().schedule(task, delay, unit); } public void execute(Runnable task) { context.executor().execute(task); } @Override public void close() { context.close(); } }; handler.accept(conn); } else { super.userEventTriggered(ctx, evt); } }
From source file:org.animotron.bridge.http.WebSocketUpgradeHttpHandler.java
License:Open Source License
@Override public boolean handle(ChannelHandlerContext ctx, FullHttpRequest request) throws Throwable { if (!request.getUri().equals(uriContext)) return false; if (!request.getMethod().equals(GET)) { HttpErrorHelper.handle(ctx, request, METHOD_NOT_ALLOWED); return true; }// w w w. j a va 2 s . com if (!"websocket".equals(getHeader(request, UPGRADE))) { sendStatus(ctx, UPGRADE_REQUIRED); return true; } WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory( getWebSocketLocation(request), getProtocol(request), false); WebSocketServerHandshaker hs = wsFactory.newHandshaker(request); if (hs == null) { sendUnsupportedWebSocketVersionResponse(ctx.channel()); return true; } WebSocketHandler handler = selectHandler(getProtocol(request)); if (handler == null) { hs.handshake(ctx.channel(), request); hs.close(ctx.channel(), new CloseWebSocketFrame()); return true; } handler.open(hs, ctx); ctx.pipeline().removeLast(); ctx.pipeline().addLast(new WebSocketServerHandler(handler, hs)); hs.handshake(ctx.channel(), request); return true; }