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

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

Introduction

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

Prototype

boolean trySuccess(V result);

Source Link

Document

Marks this future as a success and notifies all listeners.

Usage

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

License:Apache License

public static PromiseConverter<Set<byte[]>> toSet(EventExecutor executor) {
    return new PromiseConverter<Set<byte[]>>(executor) {

        @Override//  w  ww .j a v a  2s .c o  m
        public FutureListener<Object> newListener(final Promise<Set<byte[]>> promise) {
            return new FutureListener<Object>() {

                @SuppressWarnings("unchecked")
                @Override
                public void operationComplete(Future<Object> future) throws Exception {
                    if (future.isSuccess()) {
                        Object resp = future.getNow();
                        if (resp instanceof RedisResponseException) {
                            promise.tryFailure((RedisResponseException) resp);
                        } else if (resp == RedisResponseDecoder.NULL_REPLY) {
                            promise.trySuccess(null);
                        } else {
                            Set<byte[]> values = newBytesSet();
                            values.addAll((List<byte[]>) resp);
                            promise.trySuccess(values);
                        }
                    } else {
                        promise.tryFailure(future.cause());
                    }
                }
            };
        }
    };
}

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

License:Apache License

public static PromiseConverter<List<SortedSetEntry>> toSortedSetEntryList(EventExecutor executor) {
    return new PromiseConverter<List<SortedSetEntry>>(executor) {

        @Override/*  ww  w. ja  va2 s . com*/
        public FutureListener<Object> newListener(final Promise<List<SortedSetEntry>> promise) {
            return new FutureListener<Object>() {

                @Override
                public void operationComplete(Future<Object> future) throws Exception {
                    if (future.isSuccess()) {
                        Object resp = future.getNow();
                        if (resp instanceof RedisResponseException) {
                            promise.tryFailure((RedisResponseException) resp);
                        } else {
                            @SuppressWarnings("unchecked")
                            List<byte[]> rawValueList = (List<byte[]>) resp;
                            List<SortedSetEntry> values = new ArrayList<>(rawValueList.size() / 2);
                            for (Iterator<byte[]> iter = rawValueList.iterator(); iter.hasNext();) {
                                values.add(new SortedSetEntry(iter.next(), bytesToDouble(iter.next())));
                            }
                            promise.trySuccess(values);
                        }
                    } else {
                        promise.tryFailure(future.cause());
                    }
                }
            };
        }
    };
}

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

License:Apache License

public static PromiseConverter<List<Boolean>> toBooleanList(EventExecutor executor) {
    return new PromiseConverter<List<Boolean>>(executor) {

        @Override//from   w w  w  .jav  a2 s.  com
        public FutureListener<Object> newListener(final Promise<List<Boolean>> promise) {
            return new FutureListener<Object>() {

                @Override
                public void operationComplete(Future<Object> future) throws Exception {
                    if (future.isSuccess()) {
                        Object resp = future.getNow();
                        if (resp instanceof RedisResponseException) {
                            promise.tryFailure((RedisResponseException) resp);
                        } else if (resp == RedisResponseDecoder.NULL_REPLY) {
                            promise.trySuccess(null);
                        } else {
                            @SuppressWarnings("unchecked")
                            List<Long> rawValueList = (List<Long>) resp;
                            List<Boolean> values = new ArrayList<>(rawValueList.size());
                            for (long l : rawValueList) {
                                values.add(l != 0L);
                            }
                            promise.trySuccess(values);
                        }
                    } else {
                        promise.tryFailure(future.cause());
                    }
                }
            };
        }
    };
}

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

License:Apache License

public static PromiseConverter<List<Object>> toObjectList(EventExecutor executor) {
    return new PromiseConverter<List<Object>>(executor) {

        @Override//from w  ww .j a  va2  s  . c  o  m
        public FutureListener<Object> newListener(final Promise<List<Object>> promise) {
            return new FutureListener<Object>() {

                @SuppressWarnings("unchecked")
                @Override
                public void operationComplete(Future<Object> future) throws Exception {
                    if (future.isSuccess()) {
                        Object resp = future.getNow();
                        if (resp instanceof RedisResponseException) {
                            promise.tryFailure((RedisResponseException) resp);
                        } else if (resp == RedisResponseDecoder.NULL_REPLY) {
                            promise.trySuccess(null);
                        } else {
                            promise.trySuccess((List<Object>) resp);
                        }
                    } else {
                        promise.tryFailure(future.cause());
                    }
                }
            };
        }
    };
}

From source file:io.vertx.core.dns.impl.fix.DnsNameResolver.java

License:Apache License

private static void setSuccess(Promise<InetAddress> promise, InetAddress result) {
    if (!promise.trySuccess(result)) {
        logger.warn("Failed to notify success ({}) to a promise: {}", result, promise);
    }//from  ww  w  .j  a  va 2  s .co  m
}

From source file:io.vertx.core.dns.impl.fix.DnsNameResolver.java

License:Apache License

private void doResolveUncached(String hostname, Promise<InetAddress> promise, DnsCache resolveCache,
        boolean trySearchDomain) {
    if (trySearchDomain) {
        Promise<InetAddress> original = promise;
        promise = new DefaultPromise<>(executor());
        FutureListener<InetAddress> globalListener = future -> {
            if (future.isSuccess()) {
                original.setSuccess(future.getNow());
            } else {
                FutureListener<InetAddress> sdListener = new FutureListener<InetAddress>() {
                    int count;

                    @Override//ww w.  ja v  a  2s .c o m
                    public void operationComplete(Future<InetAddress> future) throws Exception {
                        if (future.isSuccess()) {
                            original.trySuccess(future.getNow());
                        } else {
                            if (count < searchDomains.size()) {
                                String searchDomain = searchDomains.get(count++);
                                Promise<InetAddress> p = new DefaultPromise<>(executor());
                                doResolveUncached(hostname + "." + searchDomain, p, resolveCache, false);
                                p.addListener(this);
                            } else {
                                original.tryFailure(future.cause());
                            }
                        }
                    }
                };
                future.addListener(sdListener);
            }
        };
        promise.addListener(globalListener);
    }
    if (searchDomains(hostname)) {
        promise.tryFailure(new UnknownHostException(hostname));
    } else {
        final DnsNameResolverContext<InetAddress> ctx = new DnsNameResolverContext<InetAddress>(this, hostname,
                promise, resolveCache) {
            @Override
            protected boolean finishResolve(Class<? extends InetAddress> addressType,
                    List<DnsCacheEntry> resolvedEntries) {

                final int numEntries = resolvedEntries.size();
                for (int i = 0; i < numEntries; i++) {
                    final InetAddress a = resolvedEntries.get(i).address();
                    if (addressType.isInstance(a)) {
                        setSuccess(promise(), a);
                        return true;
                    }
                }
                return false;
            }
        };

        ctx.resolve();
    }
}

From source file:io.vertx.core.dns.impl.fix.DnsNameResolver.java

License:Apache License

private boolean doResolveAllCached(String hostname, Promise<List<InetAddress>> promise, DnsCache resolveCache) {
    final List<DnsCacheEntry> cachedEntries = resolveCache.get(hostname);
    if (cachedEntries == null) {
        return false;
    }//from   w w w. jav a  2 s  . c  om

    List<InetAddress> result = null;
    Throwable cause = null;
    synchronized (cachedEntries) {
        final int numEntries = cachedEntries.size();
        assert numEntries > 0;

        if (cachedEntries.get(0).cause() != null) {
            cause = cachedEntries.get(0).cause();
        } else {
            for (InternetProtocolFamily f : resolvedAddressTypes) {
                for (int i = 0; i < numEntries; i++) {
                    final DnsCacheEntry e = cachedEntries.get(i);
                    if (f.addressType().isInstance(e.address())) {
                        if (result == null) {
                            result = new ArrayList<InetAddress>(numEntries);
                        }
                        result.add(e.address());
                    }
                }
            }
        }
    }

    if (result != null) {
        promise.trySuccess(result);
    } else if (cause != null) {
        promise.tryFailure(cause);
    } else {
        return false;
    }

    return true;
}

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

License:Apache License

private static void processWriteBlockResponse(Channel channel, final DatanodeInfo dnInfo,
        final Promise<Channel> promise, final int timeoutMs) {
    channel.pipeline().addLast(new IdleStateHandler(timeoutMs, 0, 0, TimeUnit.MILLISECONDS),
            new ProtobufVarint32FrameDecoder(), new ProtobufDecoder(BlockOpResponseProto.getDefaultInstance()),
            new SimpleChannelInboundHandler<BlockOpResponseProto>() {

                @Override/* ww w  . jav a2 s.  co m*/
                protected void channelRead0(ChannelHandlerContext ctx, BlockOpResponseProto resp)
                        throws Exception {
                    Status pipelineStatus = resp.getStatus();
                    if (PipelineAck.isRestartOOBStatus(pipelineStatus)) {
                        throw new IOException("datanode " + dnInfo + " is restarting");
                    }
                    String logInfo = "ack with firstBadLink as " + resp.getFirstBadLink();
                    if (resp.getStatus() != Status.SUCCESS) {
                        if (resp.getStatus() == Status.ERROR_ACCESS_TOKEN) {
                            throw new InvalidBlockTokenException("Got access token error" + ", status message "
                                    + resp.getMessage() + ", " + logInfo);
                        } else {
                            throw new IOException("Got error" + ", status=" + resp.getStatus().name()
                                    + ", status message " + resp.getMessage() + ", " + logInfo);
                        }
                    }
                    // success
                    ChannelPipeline p = ctx.pipeline();
                    for (ChannelHandler handler; (handler = p.removeLast()) != null;) {
                        // do not remove all handlers because we may have wrap or unwrap handlers at the header
                        // of pipeline.
                        if (handler instanceof IdleStateHandler) {
                            break;
                        }
                    }
                    // Disable auto read here. Enable it after we setup the streaming pipeline in
                    // FanOutOneBLockAsyncDFSOutput.
                    ctx.channel().config().setAutoRead(false);
                    promise.trySuccess(ctx.channel());
                }

                @Override
                public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                    promise.tryFailure(new IOException("connection to " + dnInfo + " is closed"));
                }

                @Override
                public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                    if (evt instanceof IdleStateEvent && ((IdleStateEvent) evt).state() == READER_IDLE) {
                        promise.tryFailure(
                                new IOException("Timeout(" + timeoutMs + "ms) waiting for response"));
                    } else {
                        super.userEventTriggered(ctx, evt);
                    }
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                    promise.tryFailure(cause);
                }
            });
}

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

License:Apache License

static void trySaslNegotiate(Configuration conf, Channel channel, DatanodeInfo dnInfo, int timeoutMs,
        DFSClient client, Token<BlockTokenIdentifier> accessToken, Promise<Void> saslPromise) {
    SaslPropertiesResolver saslPropsResolver = SASL_ADAPTOR.getSaslPropsResolver(client);
    TrustedChannelResolver trustedChannelResolver = SASL_ADAPTOR.getTrustedChannelResolver(client);
    AtomicBoolean fallbackToSimpleAuth = SASL_ADAPTOR.getFallbackToSimpleAuth(client);
    InetAddress addr = ((InetSocketAddress) channel.remoteAddress()).getAddress();
    if (trustedChannelResolver.isTrusted() || trustedChannelResolver.isTrusted(addr)) {
        saslPromise.trySuccess(null);
        return;/*from   www .  ja  v  a2  s . c  om*/
    }
    DataEncryptionKey encryptionKey;
    try {
        encryptionKey = SASL_ADAPTOR.createDataEncryptionKey(client);
    } catch (Exception e) {
        saslPromise.tryFailure(e);
        return;
    }
    if (encryptionKey != null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("SASL client doing encrypted handshake for addr = " + addr + ", datanodeId = " + dnInfo);
        }
        doSaslNegotiation(conf, channel, timeoutMs, getUserNameFromEncryptionKey(encryptionKey),
                encryptionKeyToPassword(encryptionKey.encryptionKey),
                createSaslPropertiesForEncryption(encryptionKey.encryptionAlgorithm), saslPromise);
    } else if (!UserGroupInformation.isSecurityEnabled()) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("SASL client skipping handshake in unsecured configuration for addr = " + addr
                    + ", datanodeId = " + dnInfo);
        }
        saslPromise.trySuccess(null);
    } else if (dnInfo.getXferPort() < 1024) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("SASL client skipping handshake in secured configuration with "
                    + "privileged port for addr = " + addr + ", datanodeId = " + dnInfo);
        }
        saslPromise.trySuccess(null);
    } else if (fallbackToSimpleAuth != null && fallbackToSimpleAuth.get()) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("SASL client skipping handshake in secured configuration with "
                    + "unsecured cluster for addr = " + addr + ", datanodeId = " + dnInfo);
        }
        saslPromise.trySuccess(null);
    } else if (saslPropsResolver != null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("SASL client doing general handshake for addr = " + addr + ", datanodeId = " + dnInfo);
        }
        doSaslNegotiation(conf, channel, timeoutMs, buildUsername(accessToken),
                buildClientPassword(accessToken), saslPropsResolver.getClientProperties(addr), saslPromise);
    } else {
        // It's a secured cluster using non-privileged ports, but no SASL. The only way this can
        // happen is if the DataNode has ignore.secure.ports.for.testing configured, so this is a rare
        // edge case.
        if (LOG.isDebugEnabled()) {
            LOG.debug("SASL client skipping handshake in secured configuration with no SASL "
                    + "protection configured for addr = " + addr + ", datanodeId = " + dnInfo);
        }
        saslPromise.trySuccess(null);
    }
}

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

License:Apache License

private static void processWriteBlockResponse(Channel channel, final DatanodeInfo dnInfo,
        final Promise<Channel> promise, final int timeoutMs) {
    channel.pipeline().addLast(new IdleStateHandler(timeoutMs, 0, 0, TimeUnit.MILLISECONDS),
            new ProtobufVarint32FrameDecoder(), new ProtobufDecoder(BlockOpResponseProto.getDefaultInstance()),
            new SimpleChannelInboundHandler<BlockOpResponseProto>() {

                @Override/*from  w w  w.j av a  2 s.c o  m*/
                protected void channelRead0(ChannelHandlerContext ctx, BlockOpResponseProto resp)
                        throws Exception {
                    Status pipelineStatus = resp.getStatus();
                    if (PipelineAck.isRestartOOBStatus(pipelineStatus)) {
                        throw new IOException("datanode " + dnInfo + " is restarting");
                    }
                    String logInfo = "ack with firstBadLink as " + resp.getFirstBadLink();
                    if (resp.getStatus() != Status.SUCCESS) {
                        if (resp.getStatus() == Status.ERROR_ACCESS_TOKEN) {
                            throw new InvalidBlockTokenException("Got access token error" + ", status message "
                                    + resp.getMessage() + ", " + logInfo);
                        } else {
                            throw new IOException("Got error" + ", status=" + resp.getStatus().name()
                                    + ", status message " + resp.getMessage() + ", " + logInfo);
                        }
                    }
                    // success
                    ChannelPipeline p = ctx.pipeline();
                    while (p.first() != null) {
                        p.removeFirst();
                    }
                    // Disable auto read here. Enable it after we setup the streaming pipeline in
                    // FanOutOneBLockAsyncDFSOutput.
                    ctx.channel().config().setAutoRead(false);
                    promise.trySuccess(ctx.channel());
                }

                @Override
                public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                    promise.tryFailure(new IOException("connection to " + dnInfo + " is closed"));
                }

                @Override
                public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                    if (evt instanceof IdleStateEvent
                            && ((IdleStateEvent) evt).state() == IdleState.READER_IDLE) {
                        promise.tryFailure(
                                new IOException("Timeout(" + timeoutMs + "ms) waiting for response"));
                    } else {
                        super.userEventTriggered(ctx, evt);
                    }
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                    promise.tryFailure(cause);
                }
            });
}