List of usage examples for io.netty.channel ChannelPipeline get
<T extends ChannelHandler> T get(Class<T> handlerType);
From source file:io.jsync.http.impl.ClientConnection.java
License:Open Source License
NetSocket createNetSocket() { // connection was upgraded to raw TCP socket upgradedConnection = true;//from w w w .ja v a 2 s .c o m DefaultNetSocket socket = new DefaultNetSocket(async, 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 AsyncNetHandler(client.async, 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:io.jsync.http.impl.ServerConnection.java
License:Open Source License
NetSocket createNetSocket() { DefaultNetSocket socket = new DefaultNetSocket(async, channel, context, server.tcpHelper, false); Map<Channel, DefaultNetSocket> connectionMap = new HashMap<Channel, DefaultNetSocket>(1); connectionMap.put(channel, socket);// w ww . jav a2 s . c o m // 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 compressor = pipeline.get(HttpChunkContentCompressor.class); if (compressor != null) { pipeline.remove(compressor); } pipeline.remove("httpDecoder"); if (pipeline.get("chunkedWriter") != null) { pipeline.remove("chunkedWriter"); } channel.pipeline().replace("handler", "handler", new AsyncNetHandler(server.async, connectionMap) { @Override public void exceptionCaught(ChannelHandlerContext chctx, Throwable t) throws Exception { // remove from the real mapping server.connectionMap.remove(channel); super.exceptionCaught(chctx, t); } @Override public void channelInactive(ChannelHandlerContext chctx) throws Exception { // remove from the real mapping server.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); } }); // check if the encoder can be removed yet or not. if (lastWriteFuture == null) { channel.pipeline().remove("httpEncoder"); } else { lastWriteFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { channel.pipeline().remove("httpEncoder"); } }); } return socket; }
From source file:io.lettuce.core.AbstractRedisClient.java
License:Apache License
/** * Shutdown this client and close all open connections asynchronously. The client should be discarded after calling * shutdown.//from w w w.ja va 2 s. c o m * * @param quietPeriod the quiet period as described in the documentation * @param timeout the maximum amount of time to wait until the executor is shutdown regardless if a task was submitted * during the quiet period * @param timeUnit the unit of {@code quietPeriod} and {@code timeout} * @since 4.4 */ @SuppressWarnings("rawtypes") public CompletableFuture<Void> shutdownAsync(long quietPeriod, long timeout, TimeUnit timeUnit) { if (shutdown.compareAndSet(false, true)) { List<CompletableFuture<Void>> closeFutures = new ArrayList<>(); while (!closeableResources.isEmpty()) { Closeable closeableResource = closeableResources.iterator().next(); if (closeableResource instanceof AsyncCloseable) { closeFutures.add(((AsyncCloseable) closeableResource).closeAsync()); } else { try { closeableResource.close(); } catch (Exception e) { logger.debug("Exception on Close: " + e.getMessage(), e); } } closeableResources.remove(closeableResource); } for (Channel c : channels) { ChannelPipeline pipeline = c.pipeline(); ConnectionWatchdog commandHandler = pipeline.get(ConnectionWatchdog.class); if (commandHandler != null) { commandHandler.setListenOnChannelInactive(false); } } try { closeFutures.add(toCompletableFuture(channels.close())); } catch (Exception e) { logger.debug("Cannot close channels", e); } if (!sharedResources) { Future<?> groupCloseFuture = clientResources.shutdown(quietPeriod, timeout, timeUnit); closeFutures.add(toCompletableFuture(groupCloseFuture)); } else { for (EventLoopGroup eventExecutors : eventLoopGroups.values()) { Future<?> groupCloseFuture = clientResources.eventLoopGroupProvider().release(eventExecutors, quietPeriod, timeout, timeUnit); closeFutures.add(toCompletableFuture(groupCloseFuture)); } } return allOf(closeFutures.toArray(new CompletableFuture[0])); } return completedFuture(null); }
From source file:io.lettuce.core.protocol.ReconnectionHandler.java
License:Apache License
private void reconnect0(CompletableFuture<Channel> result, SocketAddress remoteAddress) { ChannelFuture connectFuture = bootstrap.connect(remoteAddress); ChannelPromise initFuture = connectFuture.channel().newPromise(); logger.debug("Reconnecting to Redis at {}", remoteAddress); result.whenComplete((c, t) -> {/*from ww w . j a va2s . c o m*/ if (t instanceof CancellationException) { connectFuture.cancel(true); initFuture.cancel(true); } }); initFuture.addListener((ChannelFuture it) -> { if (it.cause() != null) { connectFuture.cancel(true); close(it.channel()); result.completeExceptionally(it.cause()); } else { result.complete(connectFuture.channel()); } }); connectFuture.addListener((ChannelFuture it) -> { if (it.cause() != null) { initFuture.tryFailure(it.cause()); return; } ChannelPipeline pipeline = it.channel().pipeline(); RedisChannelInitializer channelInitializer = pipeline.get(RedisChannelInitializer.class); if (channelInitializer == null) { initFuture.tryFailure(new IllegalStateException( "Reconnection attempt without a RedisChannelInitializer in the channel pipeline")); return; } channelInitializer.channelInitialized().whenComplete((state, throwable) -> { if (throwable != null) { if (isExecutionException(throwable)) { initFuture.tryFailure(throwable); return; } if (clientOptions.isCancelCommandsOnReconnectFailure()) { connectionFacade.reset(); } if (clientOptions.isSuspendReconnectOnProtocolFailure()) { logger.error("Disabling autoReconnect due to initialization failure", throwable); setReconnectSuspended(true); } initFuture.tryFailure(throwable); return; } if (logger.isDebugEnabled()) { logger.info("Reconnected to {}, Channel {}", remoteAddress, ChannelLogDescriptor.logDescriptor(it.channel())); } else { logger.info("Reconnected to {}", remoteAddress); } initFuture.trySuccess(); }); }); Runnable timeoutAction = () -> { initFuture.tryFailure(new TimeoutException( String.format("Reconnection attempt exceeded timeout of %d %s ", timeout, timeoutUnit))); }; Timeout timeoutHandle = timer.newTimeout(it -> { if (connectFuture.isDone() && initFuture.isDone()) { return; } if (reconnectWorkers.isShutdown()) { timeoutAction.run(); return; } reconnectWorkers.submit(timeoutAction); }, this.timeout, timeoutUnit); initFuture.addListener(it -> timeoutHandle.cancel()); }
From source file:io.liveoak.container.protocols.PipelineConfigurator.java
License:Open Source License
public void switchToPureStomp(ChannelPipeline pipeline) { if (pipeline.get("protocol-detector") != null) { pipeline.remove("protocol-detector"); }/*w w w .j a v a2s .c om*/ StompServerContext serverContext = new SecuredStompServerContext(this.codecManager, this.subscriptionManager, this.client); AnalyticsService analyticsService = AnalyticsService.instance(); AnalyticsBandwidthHandler analyticsHandler = null; if (analyticsService != null && analyticsService.enabled()) { analyticsHandler = new AnalyticsBandwidthHandler(analyticsService); pipeline.addLast("analytics-handler", analyticsHandler); } pipeline.addLast(new StompFrameDecoder()); pipeline.addLast(new StompFrameEncoder()); // handle frames pipeline.addLast(new ConnectHandler(serverContext)); pipeline.addLast(new DisconnectHandler(serverContext)); pipeline.addLast(new SubscribeHandler(serverContext)); pipeline.addLast(new UnsubscribeHandler(serverContext)); // convert some frames to messages pipeline.addLast(new ReceiptHandler()); pipeline.addLast(new StompMessageDecoder()); pipeline.addLast(new StompMessageEncoder(true)); if (analyticsHandler != null) { pipeline.addLast(new AnalyticsNotificationHandler(analyticsHandler)); } // handle messages pipeline.addLast(new SendHandler(serverContext)); // catch errors, return an ERROR message. pipeline.addLast(new StompErrorHandler()); }
From source file:io.liveoak.container.protocols.PipelineConfigurator.java
License:Open Source License
public void switchToHttpWebSockets(ChannelPipeline pipeline) { if (pipeline.get("protocol-detector") != null) { pipeline.remove("protocol-detector"); }//from w w w.jav a2 s .c o m //pipeline.addLast(new DebugHandler("server-pre-http")); AnalyticsBandwidthHandler analyticsHandler = null; AnalyticsService analyticsService = AnalyticsService.instance(); if (analyticsService != null && analyticsService.enabled()) { analyticsHandler = new AnalyticsBandwidthHandler(analyticsService); pipeline.addLast("analytics-handler", analyticsHandler); } pipeline.addLast(new HttpRequestDecoder()); pipeline.addLast(new HttpResponseEncoder()); if (analyticsHandler != null) { pipeline.addLast(new AnalyticsResponseHandler(analyticsHandler)); } //pipeline.addLast( new DebugHandler( "server-post-http" ) ); //pipeline.addLast(new HttpObjectAggregator(1024 * 1024)); //TODO: Remove this to support chunked http pipeline.addLast("ws-handshake", new WebSocketHandshakerHandler(this)); }
From source file:io.liveoak.container.protocols.PipelineConfigurator.java
License:Open Source License
public void switchToWebSockets(ChannelPipeline pipeline) { pipeline.remove(WebSocketHandshakerHandler.class); //pipeline.addLast( new DebugHandler( "networkServer-1" ) ); pipeline.addLast(new WebSocketStompFrameDecoder()); pipeline.addLast(new WebSocketStompFrameEncoder()); StompServerContext serverContext = new SecuredStompServerContext(this.codecManager, this.subscriptionManager, this.client); // handle frames pipeline.addLast(new ConnectHandler(serverContext)); pipeline.addLast(new DisconnectHandler(serverContext)); pipeline.addLast(new SubscribeHandler(serverContext)); pipeline.addLast(new UnsubscribeHandler(serverContext)); // convert some frames to messages pipeline.addLast(new ReceiptHandler()); pipeline.addLast(new StompMessageDecoder()); pipeline.addLast(new StompMessageEncoder(true)); // place analytics handler in stomp pipeline to another position - it's now twice in the pipeline AnalyticsBandwidthHandler handler = (AnalyticsBandwidthHandler) pipeline.get("analytics-handler"); if (handler != null) { pipeline.addLast(new AnalyticsNotificationHandler(handler)); }/*from w w w. ja va2s .co m*/ // handle messages pipeline.addLast(new SendHandler(serverContext)); // catch errors, return an ERROR message. pipeline.addLast(new StompErrorHandler()); }
From source file:io.reactivesocket.netty.tcp.server.ReactiveSocketServerHandler.java
License:Apache License
@Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { ChannelPipeline cp = ctx.pipeline(); if (cp.get(LengthFieldBasedFrameDecoder.class) == null) { ctx.pipeline().addBefore(ctx.name(), LengthFieldBasedFrameDecoder.class.getName(), new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE >> 1, 0, BitUtil.SIZE_OF_INT, -1 * BitUtil.SIZE_OF_INT, 0)); }/*from w w w. j a v a2 s . c o m*/ }
From source file:io.reactivex.netty.client.ClientChannelFactoryImpl.java
License:Apache License
@Override public ChannelFuture connect(final Subscriber<? super ObservableConnection<I, O>> subscriber, RxClient.ServerInfo serverInfo,/*from w ww . jav a 2 s . c o m*/ final ClientConnectionFactory<I, O, ? extends ObservableConnection<I, O>> connectionFactory) { final long startTimeMillis = Clock.newStartTimeMillis(); eventsSubject.onEvent(ClientMetricsEvent.CONNECT_START); final ChannelFuture connectFuture = clientBootstrap.connect(serverInfo.getHost(), serverInfo.getPort()); subscriber.add(Subscriptions.create(new Action0() { @Override public void call() { if (!connectFuture.isDone()) { connectFuture.cancel(true); // Unsubscribe here means, no more connection is required. A close on connection is explicit. } } })); connectFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { try { if (!future.isSuccess()) { eventsSubject.onEvent(ClientMetricsEvent.CONNECT_FAILED, Clock.onEndMillis(startTimeMillis), future.cause()); subscriber.onError(future.cause()); } else { eventsSubject.onEvent(ClientMetricsEvent.CONNECT_SUCCESS, Clock.onEndMillis(startTimeMillis)); ChannelPipeline pipeline = future.channel().pipeline(); ChannelHandlerContext ctx = pipeline.lastContext(); // The connection uses the context for write which should always start from the tail. final ObservableConnection<I, O> newConnection = connectionFactory.newConnection(ctx); ChannelHandler lifecycleHandler = pipeline .get(RxRequiredConfigurator.CONN_LIFECYCLE_HANDLER_NAME); if (null == lifecycleHandler) { onNewConnection(newConnection, subscriber); } else { @SuppressWarnings("unchecked") ConnectionLifecycleHandler<I, O> handler = (ConnectionLifecycleHandler<I, O>) lifecycleHandler; SslHandler sslHandler = pipeline.get(SslHandler.class); if (null == sslHandler) { handler.setConnection(newConnection); onNewConnection(newConnection, subscriber); } else { sslHandler.handshakeFuture() .addListener(new GenericFutureListener<Future<? super Channel>>() { @Override public void operationComplete(Future<? super Channel> future) throws Exception { onNewConnection(newConnection, subscriber); } }); } } } } catch (Throwable throwable) { subscriber.onError(throwable); } } }); return connectFuture; }
From source file:io.reactivex.netty.pipeline.ReadTimeoutPipelineConfigurator.java
License:Apache License
public static void disableReadTimeout(ChannelPipeline pipeline) { /**/*from w ww .j a v a 2 s.c o m*/ * Since, ChannelPipeline.remove() is blocking when not called from the associated eventloop, we do not remove * the handler. Instead we decativate the handler (invoked by the associated eventloop) here so that it does not * generate any more timeouts. * The handler is activated on next write to this pipeline. * * See issue: https://github.com/Netflix/RxNetty/issues/145 */ final ChannelHandler timeoutHandler = pipeline.get(READ_TIMEOUT_HANDLER_NAME); if (timeoutHandler != null) { final ChannelHandlerContext handlerContext = pipeline.context(timeoutHandler); EventExecutor executor = handlerContext.executor(); // Since, we are calling the handler directly, we need to make sure, it is in the owner eventloop, else it // can get concurrent callbacks. if (executor.inEventLoop()) { disableHandler(timeoutHandler, handlerContext); } else { executor.submit(new Callable<Object>() { @Override public Object call() throws Exception { disableHandler(timeoutHandler, handlerContext); return null; } }); } } }