List of usage examples for io.netty.channel ChannelPromise addListener
@Override ChannelPromise addListener(GenericFutureListener<? extends Future<? super Void>> listener);
From source file:io.jsync.impl.ExceptionDispatchHandler.java
License:Open Source License
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { ctx.write(msg, promise.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE)); }
From source file:io.lettuce.core.protocol.CommandHandler.java
License:Apache License
private void addToStack(RedisCommand<?, ?, ?> command, ChannelPromise promise) { try {//from www. ja v a 2 s .c om validateWrite(1); if (command.getOutput() == null) { // fire&forget commands are excluded from metrics complete(command); } RedisCommand<?, ?, ?> redisCommand = potentiallyWrapLatencyCommand(command); if (promise.isVoid()) { stack.add(redisCommand); } else { promise.addListener(AddToStack.newInstance(stack, command)); } } catch (Exception e) { command.completeExceptionally(e); throw e; } }
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 av a 2s . 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.pravega.client.netty.impl.ClientConnectionInboundHandler.java
License:Open Source License
@Override public void sendAsync(List<Append> appends, CompletedCallback callback) { recentMessage.set(true);//from w w w . j ava 2 s. c om Channel channel = getChannel(); ChannelPromise promise = channel.newPromise(); for (Append append : appends) { batchSizeTracker.recordAppend(append.getEventNumber(), append.getData().readableBytes()); channel.write(append, promise); } channel.flush(); promise.addListener(new GenericFutureListener<Future<? super Void>>() { @Override public void operationComplete(Future<? super Void> future) throws Exception { callback.complete(new ConnectionFailedException(future.cause())); } }); }
From source file:io.reactivex.netty.metrics.BytesInspector.java
License:Apache License
@Override @SuppressWarnings("unchecked") public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { try {// w ww . j a v a 2 s .c o m if (ByteBuf.class.isAssignableFrom(msg.getClass())) { final long startTimeMillis = Clock.newStartTimeMillis(); final int bytesToWrite = ((ByteBuf) msg).readableBytes(); eventsSubject.onEvent(metricEventProvider.getWriteStartEvent(), (Object) bytesToWrite); promise.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { eventsSubject.onEvent(metricEventProvider.getWriteSuccessEvent(), Clock.onEndMillis(startTimeMillis), bytesToWrite); } else { eventsSubject.onEvent(metricEventProvider.getWriteFailedEvent(), Clock.onEndMillis(startTimeMillis), future.cause(), bytesToWrite); } } }); } } catch (Exception e) { logger.warn( "Failed to publish bytes write metrics event. This does *not* stop the pipeline processing.", e); } finally { super.write(ctx, msg, promise); } }
From source file:io.reactivex.netty.protocol.http.server.ServerRequestResponseConverter.java
License:Apache License
private void addWriteCompleteEvents(ChannelPromise promise, final long startTimeMillis, final HttpServerMetricsEvent<HttpServerMetricsEvent.EventType> successEvent, final HttpServerMetricsEvent<HttpServerMetricsEvent.EventType> failureEvent) { promise.addListener(new ChannelFutureListener() { @Override/* ww w .j av a2s. c o m*/ public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { eventsSubject.onEvent(successEvent, Clock.onEndMillis(startTimeMillis)); } else { eventsSubject.onEvent(failureEvent, Clock.onEndMillis(startTimeMillis), future.cause()); } } }); }
From source file:io.termd.core.ssh.netty.NettyIoSession.java
License:Apache License
@Override public IoWriteFuture write(Buffer buffer) { ByteBuf buf = Unpooled.buffer(buffer.available()); buf.writeBytes(buffer.array(), buffer.rpos(), buffer.available()); NettyIoWriteFuture msg = new NettyIoWriteFuture(); ChannelPromise next = context.newPromise(); prev.addListener(whatever -> {/* w ww . j a va 2 s . c o m*/ if (context != null) { context.writeAndFlush(buf, next); } }); prev = next; next.addListener(fut -> { if (fut.isSuccess()) { msg.setValue(Boolean.TRUE); } else { msg.setValue(fut.cause()); } }); return msg; }
From source file:io.vertx.core.http.impl.Http1xServerConnection.java
License:Open Source License
private void handleError(HttpObject obj) { DecoderResult result = obj.decoderResult(); Throwable cause = result.cause(); if (cause instanceof TooLongFrameException) { String causeMsg = cause.getMessage(); HttpVersion version;/* w w w. j av a 2 s. c o m*/ if (obj instanceof HttpRequest) { version = ((HttpRequest) obj).protocolVersion(); } else if (requestInProgress != null) { version = requestInProgress.version() == io.vertx.core.http.HttpVersion.HTTP_1_0 ? HttpVersion.HTTP_1_0 : HttpVersion.HTTP_1_1; } else { version = HttpVersion.HTTP_1_1; } HttpResponseStatus status = causeMsg.startsWith("An HTTP line is larger than") ? HttpResponseStatus.REQUEST_URI_TOO_LONG : HttpResponseStatus.BAD_REQUEST; DefaultFullHttpResponse resp = new DefaultFullHttpResponse(version, status); ChannelPromise fut = chctx.newPromise(); writeToChannel(resp, fut); fut.addListener(res -> { fail(result.cause()); }); } else { fail(result.cause()); } }
From source file:io.vertx.core.http.impl.VertxHttp2ConnectionHandler.java
License:Open Source License
void writePushPromise(int streamId, Http2Headers headers, Handler<AsyncResult<Integer>> completionHandler) { int promisedStreamId = connection().local().incrementAndGetNextStreamId(); ChannelPromise promise = ctx.newPromise(); promise.addListener(fut -> { if (fut.isSuccess()) { completionHandler.handle(Future.succeededFuture(promisedStreamId)); } else {/*from w ww . ja v a 2s .c om*/ completionHandler.handle(Future.failedFuture(fut.cause())); } }); EventExecutor executor = ctx.executor(); if (executor.inEventLoop()) { _writePushPromise(streamId, promisedStreamId, headers, promise); } else { executor.execute(() -> { _writePushPromise(streamId, promisedStreamId, headers, promise); }); } }
From source file:org.apache.drill.exec.server.rest.WebSessionResourcesTest.java
License:Apache License
/** * Validates successful {@link WebSessionResources#close()} with valid CloseFuture and {@link TestClosedListener} * getting invoked which is added to the close future. * @throws Exception/* w w w .j a v a2 s . c o m*/ */ @Test public void testCloseWithListener() throws Exception { try { // Assign latch, executor and closeListener for this test case GenericFutureListener<Future<Void>> closeListener = new TestClosedListener(); latch = new CountDownLatch(1); executor = TransportCheck.createEventLoopGroup(1, "Test-Thread").next(); ChannelPromise closeFuture = new DefaultChannelPromise(null, executor); // create WebSessionResources with above ChannelPromise to notify listener webSessionResources = new WebSessionResources(mock(BufferAllocator.class), mock(SocketAddress.class), mock(UserSession.class), closeFuture); // Add the Test Listener to close future assertTrue(!listenerComplete); closeFuture.addListener(closeListener); // Close the WebSessionResources webSessionResources.close(); // Verify the states verify(webSessionResources.getAllocator()).close(); verify(webSessionResources.getSession()).close(); assertTrue(webSessionResources.getCloseFuture() == null); // Since listener will be invoked so test should not wait forever latch.await(); assertTrue(listenerComplete); } catch (Exception e) { fail(); } finally { listenerComplete = false; executor.shutdownGracefully(); } }