Example usage for io.netty.util.concurrent Promise addListener

List of usage examples for io.netty.util.concurrent Promise addListener

Introduction

In this page you can find the example usage for io.netty.util.concurrent Promise addListener.

Prototype

@Override
    Promise<V> addListener(GenericFutureListener<? extends Future<? super V>> listener);

Source Link

Usage

From source file:com.linecorp.armeria.common.tracing.TracingTestBase.java

License:Apache License

@SuppressWarnings("unchecked")
public static <T> Promise<T> mockPromise() {
    Promise<T> promise = (Promise<T>) mock(Promise.class);
    when(promise.addListener(any())).then(invoc -> {
        GenericFutureListener<Future<T>> listener = invoc.getArgumentAt(0, GenericFutureListener.class);
        listener.operationComplete(promise);
        return promise;
    });//  w w w .j av  a 2 s  .c o  m
    return promise;
}

From source file:com.linecorp.armeria.server.http.ServiceCodecPromiseTest.java

License:Apache License

protected static void setupServer(ServerBuilder sb,
        GenericFutureListener<? extends Future<? super Object>> listener, ServiceInvocationHandler handler) {
    Service service = Service.of(new DecoratingServiceCodec(new HttpServiceCodec()) {
        @Override//from   ww w  . j a va 2  s  .c o m
        public DecodeResult decodeRequest(ServiceConfig cfg, Channel ch, SessionProtocol sessionProtocol,
                String hostname, String path, String mappedPath, ByteBuf in, Object originalRequest,
                Promise<Object> promise) throws Exception {
            promise.addListener(listener);
            return delegate().decodeRequest(cfg, ch, sessionProtocol, hostname, path, mappedPath, in,
                    originalRequest, promise);
        }

        @Override
        public ByteBuf encodeResponse(ServiceInvocationContext ctx, Object response) throws Exception {
            return Unpooled.EMPTY_BUFFER;
        }
    }, handler);

    sb.serviceAt("/", service);
}

From source file:com.linecorp.armeria.server.metrics.MetricCollectingServiceCodec.java

License:Apache License

@Override
public DecodeResult decodeRequest(ServiceConfig cfg, Channel ch, SessionProtocol sessionProtocol,
        String hostname, String path, String mappedPath, ByteBuf in, Object originalRequest,
        Promise<Object> promise) throws Exception {

    final long startTime = System.nanoTime();
    final int requestSize = in.readableBytes();

    DecodeResult decodeResult = delegate().decodeRequest(cfg, ch, sessionProtocol, hostname, path, mappedPath,
            in, originalRequest, promise);

    LongSupplier lazyElapsedTime = () -> System.nanoTime() - startTime;

    switch (decodeResult.type()) {
    case SUCCESS: {
        ServiceInvocationContext context = decodeResult.invocationContext();
        context.attr(METRICS).set(new MetricsData(requestSize, startTime));
        metricConsumer.invocationStarted(context.scheme(), hostname, path, decodeResult.decodedMethod());

        promise.addListener(future -> {
            if (!future.isSuccess()) {
                // encodeFailureResponse will process this case.
                return;
            }//ww w. j a v a  2s. c  o  m
            Object result = future.getNow();

            if (result instanceof FullHttpResponse) {
                FullHttpResponse httpResponse = (FullHttpResponse) result;
                metricConsumer.invocationComplete(context.scheme(), httpResponse.status().code(),
                        lazyElapsedTime.getAsLong(), requestSize, httpResponse.content().readableBytes(),
                        hostname, path, decodeResult.decodedMethod(), true);
            }
            // encodeResponse will process this case.
        });
        break;
    }
    case FAILURE: {
        final Object errorResponse = decodeResult.errorResponse();
        if (errorResponse instanceof FullHttpResponse) {
            FullHttpResponse httpResponse = (FullHttpResponse) errorResponse;
            metricConsumer.invocationComplete(
                    Scheme.of(decodeResult.decodedSerializationFormat(), sessionProtocol),
                    httpResponse.status().code(), lazyElapsedTime.getAsLong(), requestSize,
                    httpResponse.content().readableBytes(), hostname, path, decodeResult.decodedMethod(),
                    false);
        } else {
            metricConsumer.invocationComplete(
                    Scheme.of(decodeResult.decodedSerializationFormat(), sessionProtocol),
                    HttpResponseStatus.BAD_REQUEST.code(), lazyElapsedTime.getAsLong(), requestSize, 0,
                    hostname, path, decodeResult.decodedMethod(), false);
        }
        break;
    }
    case NOT_FOUND:
        metricConsumer.invocationComplete(Scheme.of(decodeResult.decodedSerializationFormat(), sessionProtocol),
                HttpResponseStatus.NOT_FOUND.code(), lazyElapsedTime.getAsLong(), requestSize, 0, hostname,
                path, decodeResult.decodedMethod(), false);
        break;
    }

    return decodeResult;
}

From source file:com.linecorp.armeria.server.tracing.TracingServiceInvocationHandler.java

License:Apache License

@Override
public final void invoke(ServiceInvocationContext ctx, Executor blockingTaskExecutor, Promise<Object> promise)
        throws Exception {

    final TraceData traceData = getTraceData(ctx);

    final ServerRequestAdapter requestAdapter = new InternalServerRequestAdapter(ctx.method(), traceData);

    final ServerSpan serverSpan = serverInterceptor.openSpan(requestAdapter);
    if (serverSpan != null) {
        ctx.onEnter(() -> serverInterceptor.setSpan(serverSpan)).onExit(serverInterceptor::clearSpan);
        if (serverSpan.getSample()) {
            promise.addListener(f -> serverInterceptor.closeSpan(serverSpan, createResponseAdapter(ctx, f)));
        }/*from w  w w  . jav a  2  s  .co  m*/
    }
    try {
        super.invoke(ctx, blockingTaskExecutor, promise);
    } finally {
        serverInterceptor.clearSpan();
    }
}

From source file:com.look.netty.demo.socksproxy.SocksServerConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksMessage message) throws Exception {
    if (message instanceof Socks4CommandRequest) {
        final Socks4CommandRequest request = (Socks4CommandRequest) message;
        Promise<Channel> promise = ctx.executor().newPromise();
        promise.addListener(new FutureListener<Channel>() {
            @Override//from  w  w  w  .j  a  va  2s  .  c  o m
            public void operationComplete(final Future<Channel> future) throws Exception {
                final Channel outboundChannel = future.getNow();
                if (future.isSuccess()) {
                    ChannelFuture responseFuture = ctx.channel()
                            .writeAndFlush(new DefaultSocks4CommandResponse(Socks4CommandStatus.SUCCESS));

                    responseFuture.addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture channelFuture) {
                            ctx.pipeline().remove(SocksServerConnectHandler.this);
                            outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                            ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                        }
                    });
                } else {
                    ctx.channel().writeAndFlush(
                            new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });

        final Channel inboundChannel = ctx.channel();
        b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new DirectClientHandler(promise));

        b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    // Connection established use handler provided results
                } else {
                    // Close the connection if the connection attempt has failed.
                    ctx.channel().writeAndFlush(
                            new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
    } else if (message instanceof Socks5CommandRequest) {
        final Socks5CommandRequest request = (Socks5CommandRequest) message;
        Promise<Channel> promise = ctx.executor().newPromise();
        promise.addListener(new FutureListener<Channel>() {
            @Override
            public void operationComplete(final Future<Channel> future) throws Exception {
                final Channel outboundChannel = future.getNow();
                if (future.isSuccess()) {
                    ChannelFuture responseFuture = ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(
                            Socks5CommandStatus.SUCCESS, request.dstAddrType()));

                    responseFuture.addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture channelFuture) {
                            ctx.pipeline().remove(SocksServerConnectHandler.this);
                            outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                            ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                        }
                    });
                } else {
                    ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE,
                            request.dstAddrType()));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });

        final Channel inboundChannel = ctx.channel();
        b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new DirectClientHandler(promise));

        b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    // Connection established use handler provided results
                } else {
                    // Close the connection if the connection attempt has failed.
                    ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE,
                            request.dstAddrType()));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
    } else {
        ctx.close();
    }
}

From source file:com.turo.pushy.apns.ApnsChannelFactory.java

License:Open Source License

/**
 * Creates and connects a new channel. The initial connection attempt may be delayed to accommodate exponential
 * back-off requirements.//from   ww w .jav a2  s.  c  o m
 *
 * @param channelReadyPromise the promise to be notified when a channel has been created and connected to the APNs
 * server
 *
 * @return a future that will be notified once a channel has been created and connected to the APNs server
 */
@Override
public Future<Channel> create(final Promise<Channel> channelReadyPromise) {
    final long delay = this.currentDelaySeconds.get();

    channelReadyPromise.addListener(new GenericFutureListener<Future<Channel>>() {

        @Override
        public void operationComplete(final Future<Channel> future) {
            final long updatedDelay = future.isSuccess() ? 0
                    : Math.max(Math.min(delay * 2, MAX_CONNECT_DELAY_SECONDS), MIN_CONNECT_DELAY_SECONDS);

            ApnsChannelFactory.this.currentDelaySeconds.compareAndSet(delay, updatedDelay);
        }
    });

    this.bootstrapTemplate.config().group().schedule(new Runnable() {

        @Override
        public void run() {

            final Bootstrap bootstrap = ApnsChannelFactory.this.bootstrapTemplate.clone()
                    .channelFactory(new AugmentingReflectiveChannelFactory<>(
                            ClientChannelClassUtil.getSocketChannelClass(
                                    ApnsChannelFactory.this.bootstrapTemplate.config().group()),
                            CHANNEL_READY_PROMISE_ATTRIBUTE_KEY, channelReadyPromise));

            final ChannelFuture connectFuture = bootstrap.connect();

            connectFuture.addListener(new GenericFutureListener<ChannelFuture>() {

                @Override
                public void operationComplete(final ChannelFuture future) {
                    if (!future.isSuccess()) {
                        // This may seem spurious, but our goal here is to accurately report the cause of
                        // connection failure; if we just wait for connection closure, we won't be able to
                        // tell callers anything more specific about what went wrong.
                        tryFailureAndLogRejectedCause(channelReadyPromise, future.cause());
                    }
                }
            });

            connectFuture.channel().closeFuture().addListener(new GenericFutureListener<ChannelFuture>() {

                @Override
                public void operationComplete(final ChannelFuture future) {
                    // We always want to try to fail the "channel ready" promise if the connection closes; if it has
                    // already succeeded, this will have no effect.
                    channelReadyPromise.tryFailure(
                            new IllegalStateException("Channel closed before HTTP/2 preface completed."));
                }
            });

        }
    }, delay, TimeUnit.SECONDS);

    return channelReadyPromise;
}

From source file:com.xx_dev.apn.socks.remote.SocksServerConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception {
    Promise<Channel> promise = ctx.executor().newPromise();
    promise.addListener(new GenericFutureListener<Future<Channel>>() {
        @Override//from  w w w .  j a  v a  2  s .c  o  m
        public void operationComplete(final Future<Channel> future) throws Exception {
            final Channel outboundChannel = future.getNow();
            if (future.isSuccess()) {
                restLogger.info(request.host() + ":" + request.port() + "," + "T");
                ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.SUCCESS, request.addressType()))
                        .addListener(new ChannelFutureListener() {
                            @Override
                            public void operationComplete(ChannelFuture channelFuture) {
                                ctx.pipeline().remove(SocksServerConnectHandler.this);
                                outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                                ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                            }
                        });
            } else {
                restLogger.info(request.host() + ":" + request.port() + "," + "F");
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.closeOnFlush(ctx.channel());
            }
        }
    });

    final Channel inboundChannel = ctx.channel();
    b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
            .handler(new DirectClientHandler(promise));

    b.connect(request.host(), request.port()).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                // Connection established use handler provided results
            } else {
                // Close the connection if the connection attempt has failed.
                restLogger.info(request.host() + ":" + request.port() + "," + "F");
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.closeOnFlush(ctx.channel());
            }
        }
    });
}

From source file:de.unipassau.isl.evs.ssh.app.handler.AbstractAppHandler.java

License:Open Source License

/**
 * Generate a new Future that will track the status of the request contained in the given sent AddressedMessage.
 * If the AddressedMessage couldn't be sent due to an IOException, the returned Future will also fail.
 * Otherwise, the returned Future will complete once {@link #handleResponse(Message.AddressedMessage)} with the
 * according response message is called.
 * <p/>//from   w  ww . j  av a  2  s  .  c  om
 * <i>The generic return type of this method T must match the payload of the response message.
 * If you are e.g. expecting a {@link de.unipassau.isl.evs.ssh.core.messaging.RoutingKeys#MASTER_LIGHT_GET_REPLY}
 * response, the returned Future should be a Future<LightPayload>. If a error response with an {@link ErrorPayload}
 * is received, the Future will fail the cause being the received ErrorPayload.
 * If the request can have more than one successful response
 * (except for the ErrorPayload, which is always handled as described above and doesn't count here),
 * the most common supertype of both payloads (i.e. MessagePayload) must be declared as generic type for the Future.</i>
 */
protected <T> Future<T> newResponseFuture(final Message.AddressedMessage message) {
    if (!message.getFromID().equals(requireComponent(NamingManager.KEY).getOwnID())) {
        throw new IllegalArgumentException("Can only track messages sent by me");
    }
    final Promise<T> promise = requireComponent(ExecutionServiceComponent.KEY).newPromise();
    final MessageMetrics metrics;
    if (CoreConstants.TRACK_STATISTICS) {
        metrics = new MessageMetrics(message);
        promise.addListener(new FutureListener<T>() {
            @Override
            public void operationComplete(Future<T> future) throws Exception {
                metrics.finished(future);
                Log.v(AbstractAppHandler.this.getClass().getSimpleName() + "-Metrics", metrics.toString());
            }
        });
    } else {
        metrics = null;
    }
    message.getSendFuture().addListener(new FutureListener<Void>() {
        @Override
        public void operationComplete(Future<Void> future) throws Exception {
            if (!future.isSuccess()) {
                promise.setFailure(future.cause());
            } else {
                if (metrics != null) {
                    metrics.sent(future);
                }
            }
        }
    });
    promise.setUncancellable();
    mappings.put(message.getSequenceNr(), promise);
    return promise;
}

From source file:io.aos.netty5.socksproxy.SocksServerConnectHandler.java

License:Apache License

@Override
public void messageReceived(final ChannelHandlerContext ctx, final SocksRequest message) throws Exception {
    if (message instanceof Socks4CmdRequest) {
        final Socks4CmdRequest request = (Socks4CmdRequest) message;
        Promise<Channel> promise = ctx.executor().newPromise();
        promise.addListener(new GenericFutureListener<Future<Channel>>() {
            @Override// ww  w  .  j  a v a 2 s .  co m
            public void operationComplete(final Future<Channel> future) throws Exception {
                final Channel outboundChannel = future.getNow();
                if (future.isSuccess()) {
                    ctx.channel().writeAndFlush(new Socks4CmdResponse(Socks4CmdStatus.SUCCESS))
                            .addListener(new ChannelFutureListener() {
                                @Override
                                public void operationComplete(ChannelFuture channelFuture) {
                                    ctx.pipeline().remove(SocksServerConnectHandler.this);
                                    outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                                    ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                                }
                            });
                } else {
                    ctx.channel().writeAndFlush(new Socks4CmdResponse(Socks4CmdStatus.REJECTED_OR_FAILED));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });

        final Channel inboundChannel = ctx.channel();
        b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new DirectClientHandler(promise));

        b.connect(request.host(), request.port()).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    // Connection established use handler provided results
                } else {
                    // Close the connection if the connection attempt has failed.
                    ctx.channel().writeAndFlush(new Socks4CmdResponse(Socks4CmdStatus.REJECTED_OR_FAILED));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
    } else if (message instanceof Socks5CmdRequest) {
        final Socks5CmdRequest request = (Socks5CmdRequest) message;
        Promise<Channel> promise = ctx.executor().newPromise();
        promise.addListener(new GenericFutureListener<Future<Channel>>() {
            @Override
            public void operationComplete(final Future<Channel> future) throws Exception {
                final Channel outboundChannel = future.getNow();
                if (future.isSuccess()) {
                    ctx.channel()
                            .writeAndFlush(
                                    new Socks5CmdResponse(Socks5CmdStatus.SUCCESS, request.addressType()))
                            .addListener(new ChannelFutureListener() {
                                @Override
                                public void operationComplete(ChannelFuture channelFuture) {
                                    ctx.pipeline().remove(SocksServerConnectHandler.this);
                                    outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                                    ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                                }
                            });
                } else {
                    ctx.channel().writeAndFlush(
                            new Socks5CmdResponse(Socks5CmdStatus.FAILURE, request.addressType()));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });

        final Channel inboundChannel = ctx.channel();
        b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new DirectClientHandler(promise));

        b.connect(request.host(), request.port()).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    // Connection established use handler provided results
                } else {
                    // Close the connection if the connection attempt has failed.
                    ctx.channel().writeAndFlush(
                            new Socks5CmdResponse(Socks5CmdStatus.FAILURE, request.addressType()));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
    } else {
        ctx.close();
    }
}

From source file:io.codis.nedis.NedisClientImpl.java

License:Apache License

private <T> Future<T> execTxnCmd(PromiseConverter<T> converter, RedisCommand cmd) {
    Promise<Object> rawPromise = eventLoop().newPromise();
    channel.writeAndFlush(new TxnRedisRequest(rawPromise, cmd));
    Promise<T> promise = converter.newPromise();
    rawPromise.addListener(converter.newListener(promise));
    return promise;
}