List of usage examples for io.netty.channel ChannelPipeline replace
<T extends ChannelHandler> T replace(Class<T> oldHandlerType, String newName, ChannelHandler newHandler);
From source file:io.vertx.core.http.impl.ClientConnection.java
License:Open Source License
public NetSocket createNetSocket() { // connection was upgraded to raw TCP socket NetSocketImpl socket = new NetSocketImpl(vertx, channel, context, client.getSslHelper(), metrics); socket.metric(metric());/*w w w .ja v a2 s .c om*/ Map<Channel, NetSocketImpl> connectionMap = new HashMap<>(1); connectionMap.put(channel, socket); // Flush out all pending data endReadAndFlush(); // remove old http handlers and replace the old handler with one that handle plain sockets ChannelPipeline pipeline = channel.pipeline(); ChannelHandler inflater = pipeline.get(HttpContentDecompressor.class); if (inflater != null) { pipeline.remove(inflater); } pipeline.remove("codec"); pipeline.replace("handler", "handler", new VertxNetHandler<NetSocketImpl>(channel, socket, connectionMap) { @Override public void exceptionCaught(ChannelHandlerContext chctx, Throwable t) throws Exception { // remove from the real mapping pool.removeChannel(channel); super.exceptionCaught(chctx, t); } @Override public void channelInactive(ChannelHandlerContext chctx) throws Exception { // remove from the real mapping pool.removeChannel(channel); super.channelInactive(chctx); } @Override public void channelRead(ChannelHandlerContext chctx, Object msg) throws Exception { if (msg instanceof HttpContent) { if (msg instanceof LastHttpContent) { handleResponseEnd((LastHttpContent) msg); } ReferenceCountUtil.release(msg); return; } super.channelRead(chctx, msg); } @Override protected void handleMsgReceived(NetSocketImpl conn, Object msg) { ByteBuf buf = (ByteBuf) msg; conn.handleDataReceived(Buffer.buffer(buf)); } }); return socket; }
From source file:io.vertx.core.http.impl.Http1xClientConnection.java
License:Open Source License
private synchronized NetSocket upgrade(StreamImpl stream) { if (options.isPipelining()) { throw new IllegalStateException("Cannot upgrade a pipe-lined request"); }/*from w ww . j a va2 s .c om*/ if (upgraded) { throw new IllegalStateException("Request already upgraded to NetSocket"); } upgraded = true; // connection was upgraded to raw TCP socket AtomicBoolean paused = new AtomicBoolean(false); NetSocketImpl socket = new NetSocketImpl(vertx, chctx, context, client.getSslHelper(), metrics) { { super.pause(); } @Override public synchronized NetSocket handler(Handler<Buffer> dataHandler) { return super.handler(dataHandler); } @Override public synchronized NetSocket pause() { paused.set(true); return super.pause(); } @Override public synchronized NetSocket resume() { paused.set(false); return super.resume(); } }; socket.metric(metric()); // Flush out all pending data endReadAndFlush(); // remove old http handlers and replace the old handler with one that handle plain sockets ChannelPipeline pipeline = chctx.pipeline(); ChannelHandler inflater = pipeline.get(HttpContentDecompressor.class); if (inflater != null) { pipeline.remove(inflater); } pipeline.replace("handler", "handler", new VertxNetHandler(socket) { @Override public void channelRead(ChannelHandlerContext chctx, Object msg) throws Exception { if (msg instanceof HttpContent) { if (msg instanceof LastHttpContent) { stream.endResponse((LastHttpContent) msg); } ReferenceCountUtil.release(msg); return; } super.channelRead(chctx, msg); } }.removeHandler(sock -> listener.onDiscard())); // Removing this codec might fire pending buffers in the HTTP decoder // this happens when the channel reads the HTTP response and the following data in a single buffer pipeline.remove("codec"); // Async check to deliver the pending messages // because the netSocket access in HttpClientResponse is synchronous // we need to pause the NetSocket to avoid losing or reordering buffers // and then asynchronously un-pause it unless it was actually paused by the application context.runOnContext(v -> { if (!paused.get()) { socket.resume(); } }); return socket; }
From source file:me.netty.http.Http2ServerInitializer.java
License:Apache License
/** * Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2.0 *//*from w w w . java 2 s . co m*/ private 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 channelRead0(ChannelHandlerContext ctx, HttpMessage msg) throws Exception { // If this handler is hit then no upgrade has been attempted and the client is just talking HTTP. ChannelPipeline pipeline = ctx.pipeline(); ChannelHandlerContext thisCtx = pipeline.context(this); pipeline.addAfter(thisCtx.name(), null, new Http1Handler()); pipeline.replace(this, null, new HttpObjectAggregator(maxHttpContentLength)); ctx.fireChannelRead(ReferenceCountUtil.retain(msg)); } }); p.addLast(new UserEventLogger()); }
From source file:net.tomp2p.connection.Sender.java
License:Apache License
private boolean addOrReplace(ChannelPipeline pipeline, String before, String name, ChannelHandler channelHandler) { List<String> names = pipeline.names(); if (names.contains(name)) { pipeline.replace(name, name, channelHandler); return false; } else {/*w w w. jav a 2s.co m*/ if (before == null) { pipeline.addFirst(name, channelHandler); } else { pipeline.addBefore(before, name, channelHandler); } return true; } }
From source file:org.apache.hadoop.hdfs.server.datanode.web.URLDispatcher.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, HttpRequest req) throws Exception { String uri = req.getUri();//from ww w . j a v a 2 s . c o m ChannelPipeline p = ctx.pipeline(); if (uri.startsWith(WEBHDFS_PREFIX)) { WebHdfsHandler h = new WebHdfsHandler(conf, confForCreate); p.replace(this, WebHdfsHandler.class.getSimpleName(), h); h.channelRead0(ctx, req); } else { SimpleHttpProxyHandler h = new SimpleHttpProxyHandler(proxyHost); p.replace(this, SimpleHttpProxyHandler.class.getSimpleName(), h); h.channelRead0(ctx, req); } }
From source file:org.asynchttpclient.providers.netty.channel.Channels.java
License:Apache License
public void upgradeProtocol(ChannelPipeline p, String scheme, String host, int port) throws IOException, GeneralSecurityException { if (p.get(HTTP_HANDLER) != null) { p.remove(HTTP_HANDLER);//from w w w .j av a 2 s.co m } if (isSecure(scheme)) { if (p.get(SSL_HANDLER) == null) { p.addFirst(HTTP_HANDLER, newHttpClientCodec()); p.addFirst(SSL_HANDLER, createSslHandler(host, port)); } else { p.addAfter(SSL_HANDLER, HTTP_HANDLER, newHttpClientCodec()); } } else { p.addFirst(HTTP_HANDLER, newHttpClientCodec()); } if (isWebSocket(scheme)) { p.replace(HTTP_PROCESSOR, WS_PROCESSOR, wsProcessor); } }
From source file:org.glassfish.jersey.netty.httpserver.JerseyServerInitializer.java
License:Open Source License
/** * Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2. *///from www . j av a 2 s . c om private void configureClearText(SocketChannel ch) { final ChannelPipeline p = ch.pipeline(); final HttpServerCodec sourceCodec = new HttpServerCodec(); p.addLast(sourceCodec); p.addLast(new HttpServerUpgradeHandler(sourceCodec, new HttpServerUpgradeHandler.UpgradeCodecFactory() { @Override public HttpServerUpgradeHandler.UpgradeCodec newUpgradeCodec(CharSequence protocol) { if (AsciiString.contentEquals(Http2CodecUtil.HTTP_UPGRADE_PROTOCOL_NAME, protocol)) { return new Http2ServerUpgradeCodec( new Http2Codec(true, new JerseyHttp2ServerHandler(baseUri, container))); } else { return null; } } })); p.addLast(new SimpleChannelInboundHandler<HttpMessage>() { @Override protected void channelRead0(ChannelHandlerContext ctx, HttpMessage msg) throws Exception { // If this handler is hit then no upgrade has been attempted and the client is just talking HTTP. // "Directly talking: " + msg.protocolVersion() + " (no upgrade was attempted)"); ChannelPipeline pipeline = ctx.pipeline(); ChannelHandlerContext thisCtx = pipeline.context(this); pipeline.addAfter(thisCtx.name(), null, new JerseyServerHandler(baseUri, container)); pipeline.replace(this, null, new ChunkedWriteHandler()); ctx.fireChannelRead(msg); } }); }
From source file:org.infinispan.server.core.transport.SaslServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buf = (ByteBuf) msg;/*from w ww . j av a2 s . c o m*/ Channel ch = ctx.channel(); try { if (!firstPass) { readHeader(buf); } else { firstPass = false; } byte[] bytes = readBytes(buf); byte[] challenge = server.evaluateResponse(bytes); if (!server.isComplete()) { ch.writeAndFlush(newContinueMessage(ctx, Unpooled.wrappedBuffer(challenge))); } else { ch.writeAndFlush(newSuccessMessage(ctx, Unpooled.wrappedBuffer(challenge))); ChannelPipeline pipeline = ctx.pipeline(); String qop = (String) server.getNegotiatedProperty(Sasl.QOP); if (qop != null && (qop.equalsIgnoreCase(AUTH_INT) || qop.equalsIgnoreCase(AUTO_CONF))) { SaslServer server = this.server; this.server = null; // Replace this handler now with the QopHandler // This is mainly done as the QopHandler itself will not block at all and so we can // get rid of the usage of the EventExecutorGroup after the negation took place. pipeline.replace(this, ctx.name(), new QopHandler(server)); } else { // there is no need for any QOP handling so we are done now and can just remove ourself from the // pipeline pipeline.remove(this); } } } catch (SaslException e) { Object errorMsg = newErrorMessage(ctx, e); if (errorMsg != null) { ch.writeAndFlush(errorMsg).addListener(ChannelFutureListener.CLOSE); } } }
From source file:org.vertx.java.core.http.impl.ClientConnection.java
License:Open Source License
NetSocket createNetSocket() { // connection was upgraded to raw TCP socket upgradedConnection = true;//from ww w . j a v a2 s. c o m DefaultNetSocket socket = new DefaultNetSocket(vertx, channel, context, client.tcpHelper, true); Map<Channel, DefaultNetSocket> connectionMap = new HashMap<Channel, DefaultNetSocket>(1); connectionMap.put(channel, socket); // Flush out all pending data endReadAndFlush(); // remove old http handlers and replace the old handler with one that handle plain sockets ChannelPipeline pipeline = channel.pipeline(); ChannelHandler inflater = pipeline.get(HttpContentDecompressor.class); if (inflater != null) { pipeline.remove(inflater); } pipeline.remove("codec"); pipeline.replace("handler", "handler", new VertxNetHandler(client.vertx, connectionMap) { @Override public void exceptionCaught(ChannelHandlerContext chctx, Throwable t) throws Exception { // remove from the real mapping client.connectionMap.remove(channel); super.exceptionCaught(chctx, t); } @Override public void channelInactive(ChannelHandlerContext chctx) throws Exception { // remove from the real mapping client.connectionMap.remove(channel); super.channelInactive(chctx); } @Override public void channelRead(ChannelHandlerContext chctx, Object msg) throws Exception { if (msg instanceof HttpContent) { ReferenceCountUtil.release(msg); return; } super.channelRead(chctx, msg); } }); return socket; }
From source file:org.wso2.carbon.transport.http.netty.contractimpl.websocket.message.WebSocketInitMessageImpl.java
License:Open Source License
private HandshakeFuture handleHandshake(WebSocketServerHandshaker handshaker, int idleTimeout) { HandshakeFutureImpl handshakeFuture = new HandshakeFutureImpl(); if (isCancelled) { Throwable e = new IllegalAccessException("Handshake is already cancelled!"); handshakeFuture.notifyError(e);/* ww w . j a va 2 s .co m*/ return handshakeFuture; } try { ChannelFuture future = handshaker.handshake(ctx.channel(), httpRequest); handshakeFuture.setChannelFuture(future); future.addListener(new GenericFutureListener<Future<? super Void>>() { @Override public void operationComplete(Future<? super Void> future) throws Exception { String selectedSubProtocol = handshaker.selectedSubprotocol(); webSocketSourceHandler.setNegotiatedSubProtocol(selectedSubProtocol); setSubProtocol(selectedSubProtocol); WebSocketSessionImpl session = (WebSocketSessionImpl) getChannelSession(); session.setIsOpen(true); session.setNegotiatedSubProtocol(selectedSubProtocol); //Replace HTTP handlers with new Handlers for WebSocket in the pipeline ChannelPipeline pipeline = ctx.pipeline(); if (idleTimeout > 0) { pipeline.replace(Constants.IDLE_STATE_HANDLER, Constants.IDLE_STATE_HANDLER, new IdleStateHandler(idleTimeout, idleTimeout, idleTimeout, TimeUnit.MILLISECONDS)); } else { pipeline.remove(Constants.IDLE_STATE_HANDLER); } pipeline.addLast(Constants.WEBSOCKET_SOURCE_HANDLER, webSocketSourceHandler); pipeline.remove(Constants.HTTP_SOURCE_HANDLER); setProperty(Constants.SRC_HANDLER, webSocketSourceHandler); handshakeFuture.notifySuccess(webSocketSourceHandler.getChannelSession()); } }); return handshakeFuture; } catch (Exception e) { /* Code 1002 : indicates that an endpoint is terminating the connection due to a protocol error. */ handshaker.close(ctx.channel(), new CloseWebSocketFrame(1002, "Terminating the connection due to a protocol error.")); handshakeFuture.notifyError(e); return handshakeFuture; } }