Example usage for io.netty.channel EventLoop newPromise

List of usage examples for io.netty.channel EventLoop newPromise

Introduction

In this page you can find the example usage for io.netty.channel EventLoop newPromise.

Prototype

<V> Promise<V> newPromise();

Source Link

Document

Return a new Promise .

Usage

From source file:com.linecorp.armeria.client.circuitbreaker.CircuitBreakerRemoteInvoker.java

License:Apache License

@Override
public <T> Future<T> invoke(EventLoop eventLoop, URI uri, ClientOptions options, ClientCodec codec,
        Method method, Object[] args) throws Exception {

    final CircuitBreaker circuitBreaker;
    try {/*  ww w.j av a  2  s .com*/
        circuitBreaker = mapping.get(eventLoop, uri, options, codec, method, args);
    } catch (Throwable t) {
        logger.warn("Failed to get a circuit breaker from mapping", t);
        return delegate().invoke(eventLoop, uri, options, codec, method, args);
    }

    if (circuitBreaker.canRequest()) {
        final Future<T> resultFut = delegate().invoke(eventLoop, uri, options, codec, method, args);
        resultFut.addListener(future -> {
            if (future.isSuccess()) {
                // reports success event
                circuitBreaker.onSuccess();
            } else {
                circuitBreaker.onFailure(future.cause());
            }
        });
        return resultFut;
    } else {
        // the circuit is tripped

        // prepares a failed resultPromise
        final Promise<T> resultPromise = eventLoop.newPromise();
        resultPromise.setFailure(new FailFastException(circuitBreaker));
        codec.prepareRequest(method, args, resultPromise);

        // returns immediately without calling succeeding remote invokers
        return resultPromise;
    }
}

From source file:com.linecorp.armeria.client.http.DefaultSimpleHttpClient.java

License:Apache License

@Override
public Future<SimpleHttpResponse> execute(SimpleHttpRequest sReq) {
    final EventLoop eventLoop = client.eventLoop0();
    final Promise<SimpleHttpResponse> promise = eventLoop.newPromise();
    try {/*from  w  ww  .  j a  va2  s  . c  o  m*/
        URI uri = sReq.uri();
        StringBuilder uriBuilder = new StringBuilder(uri.getPath());
        if (uri.getQuery() != null) {
            uriBuilder.append('?');
            uriBuilder.append(uri.getQuery());
        }
        if (uri.getFragment() != null) {
            uriBuilder.append('#');
            uriBuilder.append(uri.getFragment());
        }
        final AggregatedHttpMessage aReq = AggregatedHttpMessage.of(HttpMethod.valueOf(sReq.method().name()),
                uriBuilder.toString(), HttpData.of(sReq.content()));

        // Convert the headers.
        ArmeriaHttpUtil.toArmeria(sReq.headers(), aReq.headers());

        final HttpResponse res = client.execute(eventLoop, aReq);
        res.aggregate().handle(voidFunction((aRes, cause) -> {
            if (cause != null) {
                promise.setFailure(cause);
            } else {
                try {
                    final HttpData aContent = aRes.content();
                    final byte[] content;
                    if (aContent.offset() == 0 && aContent.length() == aContent.array().length) {
                        content = aContent.array();
                    } else {
                        content = Arrays.copyOfRange(aContent.array(), aContent.offset(), aContent.length());
                    }

                    final SimpleHttpResponse sRes = new SimpleHttpResponse(
                            HttpResponseStatus.valueOf(aRes.status().code()),
                            ArmeriaHttpUtil.toNettyHttp1(aRes.headers()), content);

                    promise.setSuccess(sRes);
                } catch (Throwable t) {
                    promise.setFailure(t);
                }
            }
        })).exceptionally(CompletionActions::log);
    } catch (Throwable t) {
        promise.setFailure(t);
    }

    return promise;
}

From source file:com.linecorp.armeria.client.HttpRemoteInvoker.java

License:Apache License

@Override
public <T> Future<T> invoke(EventLoop eventLoop, URI uri, ClientOptions options, ClientCodec codec,
        Method method, Object[] args) throws Exception {

    requireNonNull(uri, "uri");
    requireNonNull(options, "options");
    requireNonNull(codec, "codec");
    requireNonNull(method, "method");

    final Scheme scheme = Scheme.parse(uri.getScheme());
    final SessionProtocol sessionProtocol = validateSessionProtocol(scheme.sessionProtocol());
    final InetSocketAddress remoteAddress = convertToSocketAddress(uri, sessionProtocol.isTls());

    final PoolKey poolKey = new PoolKey(remoteAddress, sessionProtocol);
    final Future<Channel> channelFuture = pool(eventLoop).acquire(poolKey);

    final Promise<T> resultPromise = eventLoop.newPromise();

    codec.prepareRequest(method, args, resultPromise);
    if (channelFuture.isSuccess()) {
        Channel ch = channelFuture.getNow();
        invoke0(codec, ch, method, args, options, resultPromise, poolKey);
    } else {/*  w  ww.j av a 2s .c  o m*/
        channelFuture.addListener((Future<Channel> future) -> {
            if (future.isSuccess()) {
                Channel ch = future.getNow();
                invoke0(codec, ch, method, args, options, resultPromise, poolKey);
            } else {
                resultPromise.setFailure(channelFuture.cause());
            }
        });
    }

    return resultPromise;
}

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

License:Apache License

private RoundRobinNedisClientPool(CuratorFramework curatorClient, boolean closeCurator, String zkProxyDir,
        NedisClientPoolBuilder poolBuilder) throws Exception {
    this.curatorClient = curatorClient;
    this.closeCurator = closeCurator;
    this.poolBuilder = poolBuilder;
    EventLoop eventLoop = poolBuilder.group().next();
    this.closePromise = eventLoop.newPromise();
    this.initPromise = eventLoop.newPromise();
    watcher = new PathChildrenCache(curatorClient, zkProxyDir, true);
    watcher.getListenable().addListener(new PathChildrenCacheListener() {

        private boolean initialized = false;

        @Override//www .  j  a  v a  2 s .co m
        public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
            StringBuilder sb = new StringBuilder("Zookeeper event received: type=").append(event.getType());
            if (event.getData() != null) {
                ChildData data = event.getData();
                sb.append(", path=").append(data.getPath()).append(", stat=").append(data.getStat());
            }
            LOG.info(sb.toString());
            if (!initialized) {
                if (event.getType() == INITIALIZED) {
                    resetPools();
                    initPromise.trySuccess(RoundRobinNedisClientPool.this);
                    initialized = true;
                }
            } else if (RESET_TYPES.contains(event.getType())) {
                resetPools();
            }
        }
    });
    watcher.start(StartMode.POST_INITIALIZED_EVENT);
}

From source file:io.gatling.http.client.impl.DefaultHttpClient.java

License:Apache License

private Future<List<InetSocketAddress>> resolveRemoteAddresses(Request request, EventLoop eventLoop,
        HttpListener listener, RequestTimeout requestTimeout) {
    if (!request.getUri().isSecured() && request.getProxyServer() instanceof HttpProxyServer) {
        // directly connect to proxy over clear HTTP
        InetSocketAddress remoteAddress = ((HttpProxyServer) request.getProxyServer()).getAddress();
        return ImmediateEventExecutor.INSTANCE.newSucceededFuture(singletonList(remoteAddress));
    } else {//from w  ww .j  ava2s.  c  o  m
        Promise<List<InetSocketAddress>> p = eventLoop.newPromise();

        request.getNameResolver().resolveAll(request.getUri().getHost(), eventLoop.newPromise())
                .addListener((Future<List<InetAddress>> whenAddresses) -> {
                    if (whenAddresses.isSuccess()) {
                        List<InetSocketAddress> remoteInetSocketAddresses = whenAddresses.getNow().stream().map(
                                address -> new InetSocketAddress(address, request.getUri().getExplicitPort()))
                                .collect(Collectors.toList());

                        p.setSuccess(remoteInetSocketAddresses);
                    } else {
                        if (!requestTimeout.isDone()) {
                            // only report if we haven't timed out
                            listener.onThrowable(whenAddresses.cause());
                        }
                        p.setFailure(whenAddresses.cause());
                    }
                });
        return p;
    }
}

From source file:io.gatling.http.client.impl.DefaultHttpClient.java

License:Apache License

private Future<Channel> openNewChannel(Request request, EventLoop eventLoop, EventLoopResources resources,
        List<InetSocketAddress> remoteAddresses, HttpListener listener, RequestTimeout requestTimeout) {

    InetSocketAddress localAddress = request.getLocalAddress() != null
            ? new InetSocketAddress(request.getLocalAddress(), 0)
            : null;//from w w w  . j  av  a  2s  . c  om
    Uri uri = request.getUri();
    ProxyServer proxyServer = request.getProxyServer();

    Bootstrap bootstrap = uri.isWebSocket() ? resources.wsBoostrap
            : uri.isSecured() && proxyServer != null ? resources.getBootstrapWithProxy(proxyServer)
                    : request.isAlpnRequired() && request.getUri().isSecured() ? resources.http2Bootstrap
                            : resources.http1Bootstrap;

    Promise<Channel> channelPromise = eventLoop.newPromise();
    openNewChannelRec(remoteAddresses, localAddress, 0, channelPromise, bootstrap, listener, requestTimeout);
    return channelPromise;
}

From source file:org.apache.hadoop.hbase.io.asyncfs.FanOutOneBlockAsyncDFSOutputHelper.java

License:Apache License

private static List<Future<Channel>> connectToDataNodes(final Configuration conf, final DFSClient client,
        String clientName, final LocatedBlock locatedBlock, long maxBytesRcvd, long latestGS,
        BlockConstructionStage stage, DataChecksum summer, EventLoop eventLoop) {
    Enum<?>[] storageTypes = locatedBlock.getStorageTypes();
    DatanodeInfo[] datanodeInfos = locatedBlock.getLocations();
    boolean connectToDnViaHostname = conf.getBoolean(DFS_CLIENT_USE_DN_HOSTNAME,
            DFS_CLIENT_USE_DN_HOSTNAME_DEFAULT);
    final int timeoutMs = conf.getInt(DFS_CLIENT_SOCKET_TIMEOUT_KEY, READ_TIMEOUT);
    ExtendedBlock blockCopy = new ExtendedBlock(locatedBlock.getBlock());
    blockCopy.setNumBytes(locatedBlock.getBlockSize());
    ClientOperationHeaderProto header = ClientOperationHeaderProto.newBuilder()
            .setBaseHeader(BaseHeaderProto.newBuilder().setBlock(PB_HELPER.convert(blockCopy))
                    .setToken(PB_HELPER.convert(locatedBlock.getBlockToken())))
            .setClientName(clientName).build();
    ChecksumProto checksumProto = DataTransferProtoUtil.toProto(summer);
    final OpWriteBlockProto.Builder writeBlockProtoBuilder = OpWriteBlockProto.newBuilder().setHeader(header)
            .setStage(OpWriteBlockProto.BlockConstructionStage.valueOf(stage.name())).setPipelineSize(1)
            .setMinBytesRcvd(locatedBlock.getBlock().getNumBytes()).setMaxBytesRcvd(maxBytesRcvd)
            .setLatestGenerationStamp(latestGS).setRequestedChecksum(checksumProto)
            .setCachingStrategy(CachingStrategyProto.newBuilder().setDropBehind(true).build());
    List<Future<Channel>> futureList = new ArrayList<>(datanodeInfos.length);
    for (int i = 0; i < datanodeInfos.length; i++) {
        final DatanodeInfo dnInfo = datanodeInfos[i];
        // Use Enum here because StoregType is moved to another package in hadoop 2.6. Use StorageType
        // will cause compilation error for hadoop 2.5 or before.
        final Enum<?> storageType = storageTypes[i];
        final Promise<Channel> promise = eventLoop.newPromise();
        futureList.add(promise);/*from   ww  w .j a  v  a2 s  .c  om*/
        String dnAddr = dnInfo.getXferAddr(connectToDnViaHostname);
        new Bootstrap().group(eventLoop).channel(NioSocketChannel.class)
                .option(CONNECT_TIMEOUT_MILLIS, timeoutMs).handler(new ChannelInitializer<Channel>() {

                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        // we need to get the remote address of the channel so we can only move on after
                        // channel connected. Leave an empty implementation here because netty does not allow
                        // a null handler.
                    }
                }).connect(NetUtils.createSocketAddr(dnAddr)).addListener(new ChannelFutureListener() {

                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (future.isSuccess()) {
                            initialize(conf, future.channel(), dnInfo, storageType, writeBlockProtoBuilder,
                                    timeoutMs, client, locatedBlock.getBlockToken(), promise);
                        } else {
                            promise.tryFailure(future.cause());
                        }
                    }
                });
    }
    return futureList;
}

From source file:org.apache.hadoop.hbase.util.FanOutOneBlockAsyncDFSOutputHelper.java

License:Apache License

private static List<Future<Channel>> connectToDataNodes(Configuration conf, String clientName,
        LocatedBlock locatedBlock, long maxBytesRcvd, long latestGS, BlockConstructionStage stage,
        DataChecksum summer, EventLoop eventLoop) {
    Enum<?>[] storageTypes = locatedBlock.getStorageTypes();
    DatanodeInfo[] datanodeInfos = locatedBlock.getLocations();
    boolean connectToDnViaHostname = conf.getBoolean(DFS_CLIENT_USE_DN_HOSTNAME,
            DFS_CLIENT_USE_DN_HOSTNAME_DEFAULT);
    final int timeoutMs = conf.getInt(DFS_CLIENT_SOCKET_TIMEOUT_KEY, HdfsServerConstants.READ_TIMEOUT);
    ExtendedBlock blockCopy = new ExtendedBlock(locatedBlock.getBlock());
    blockCopy.setNumBytes(locatedBlock.getBlockSize());
    ClientOperationHeaderProto header = ClientOperationHeaderProto.newBuilder()
            .setBaseHeader(BaseHeaderProto.newBuilder().setBlock(PBHelper.convert(blockCopy))
                    .setToken(PBHelper.convert(locatedBlock.getBlockToken())))
            .setClientName(clientName).build();
    ChecksumProto checksumProto = DataTransferProtoUtil.toProto(summer);
    final OpWriteBlockProto.Builder writeBlockProtoBuilder = OpWriteBlockProto.newBuilder().setHeader(header)
            .setStage(OpWriteBlockProto.BlockConstructionStage.valueOf(stage.name())).setPipelineSize(1)
            .setMinBytesRcvd(locatedBlock.getBlock().getNumBytes()).setMaxBytesRcvd(maxBytesRcvd)
            .setLatestGenerationStamp(latestGS).setRequestedChecksum(checksumProto)
            .setCachingStrategy(CachingStrategyProto.newBuilder().setDropBehind(true).build());
    List<Future<Channel>> futureList = new ArrayList<>(datanodeInfos.length);
    for (int i = 0; i < datanodeInfos.length; i++) {
        final DatanodeInfo dnInfo = datanodeInfos[i];
        // Use Enum here because StoregType is moved to another package in hadoop 2.6. Use StorageType
        // will cause compilation error for hadoop 2.5 or before.
        final Enum<?> storageType = storageTypes[i];
        final Promise<Channel> promise = eventLoop.newPromise();
        futureList.add(promise);/*from   www  . ja v  a  2  s  . com*/
        String dnAddr = dnInfo.getXferAddr(connectToDnViaHostname);
        new Bootstrap().group(eventLoop).channel(NioSocketChannel.class)
                .option(CONNECT_TIMEOUT_MILLIS, timeoutMs).handler(new ChannelInitializer<Channel>() {

                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        processWriteBlockResponse(ch, dnInfo, promise, timeoutMs);
                    }
                }).connect(NetUtils.createSocketAddr(dnAddr)).addListener(new ChannelFutureListener() {

                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (future.isSuccess()) {
                            requestWriteBlock(future.channel(), storageType, writeBlockProtoBuilder);
                        } else {
                            promise.tryFailure(future.cause());
                        }
                    }
                });
    }
    return futureList;
}

From source file:org.redisson.RedissonSortedSet.java

License:Apache License

public Future<Boolean> addAsync(final V value) {
    EventLoop loop = connectionManager.getGroup().next();
    final Promise<Boolean> promise = loop.newPromise();

    loop.execute(new Runnable() {
        @Override/*ww w  .  j  av a 2 s .  c  o m*/
        public void run() {
            try {
                boolean result = add(value);
                promise.setSuccess(result);
            } catch (Exception e) {
                promise.setFailure(e);
            }
        }
    });

    return promise;
}

From source file:org.redisson.RedissonSortedSet.java

License:Apache License

@Override
public Future<Boolean> removeAsync(final V value) {
    EventLoop loop = connectionManager.getGroup().next();
    final Promise<Boolean> promise = loop.newPromise();

    loop.execute(new Runnable() {
        @Override//from w  w  w .j a v  a 2  s .c  o  m
        public void run() {
            try {
                boolean result = remove(value);
                promise.setSuccess(result);
            } catch (Exception e) {
                promise.setFailure(e);
            }
        }
    });

    return promise;
}