Example usage for io.netty.channel ChannelPromise trySuccess

List of usage examples for io.netty.channel ChannelPromise trySuccess

Introduction

In this page you can find the example usage for io.netty.channel ChannelPromise trySuccess.

Prototype

boolean trySuccess();

Source Link

Usage

From source file:com.relayrides.pushy.apns.ApnsClient.java

License:Open Source License

protected ApnsClient(final SslContext sslContext, final EventLoopGroup eventLoopGroup) {
    this.bootstrap = new Bootstrap();

    if (eventLoopGroup != null) {
        this.bootstrap.group(eventLoopGroup);
        this.shouldShutDownEventLoopGroup = false;
    } else {/*from w w  w  . j a  v  a  2  s  . c o  m*/
        this.bootstrap.group(new NioEventLoopGroup(1));
        this.shouldShutDownEventLoopGroup = true;
    }

    this.bootstrap.channel(SocketChannelClassUtil.getSocketChannelClass(this.bootstrap.config().group()));
    this.bootstrap.option(ChannelOption.TCP_NODELAY, true);
    this.bootstrap.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(final SocketChannel channel) throws Exception {
            final ChannelPipeline pipeline = channel.pipeline();

            final ProxyHandlerFactory proxyHandlerFactory = ApnsClient.this.proxyHandlerFactory;

            if (proxyHandlerFactory != null) {
                pipeline.addFirst(proxyHandlerFactory.createProxyHandler());
            }

            if (ApnsClient.this.writeTimeoutMillis > 0) {
                pipeline.addLast(
                        new WriteTimeoutHandler(ApnsClient.this.writeTimeoutMillis, TimeUnit.MILLISECONDS));
            }

            pipeline.addLast(sslContext.newHandler(channel.alloc()));
            pipeline.addLast(new ApplicationProtocolNegotiationHandler("") {
                @Override
                protected void configurePipeline(final ChannelHandlerContext context, final String protocol) {
                    if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
                        final ApnsClientHandler apnsClientHandler = new ApnsClientHandler.ApnsClientHandlerBuilder()
                                .server(false).apnsClient(ApnsClient.this)
                                .authority(
                                        ((InetSocketAddress) context.channel().remoteAddress()).getHostName())
                                .encoderEnforceMaxConcurrentStreams(true).build();

                        synchronized (ApnsClient.this.bootstrap) {
                            if (ApnsClient.this.gracefulShutdownTimeoutMillis != null) {
                                apnsClientHandler.gracefulShutdownTimeoutMillis(
                                        ApnsClient.this.gracefulShutdownTimeoutMillis);
                            }
                        }

                        context.pipeline().addLast(
                                new IdleStateHandler(0, 0, PING_IDLE_TIME_MILLIS, TimeUnit.MILLISECONDS));
                        context.pipeline().addLast(apnsClientHandler);

                        final ChannelPromise connectionReadyPromise = ApnsClient.this.connectionReadyPromise;

                        if (connectionReadyPromise != null) {
                            connectionReadyPromise.trySuccess();
                        }
                    } else {
                        throw new IllegalArgumentException("Unexpected protocol: " + protocol);
                    }
                }
            });
        }
    });
}

From source file:io.lettuce.core.protocol.CommandHandler.java

License:Apache License

private void writeSingleCommand(ChannelHandlerContext ctx, RedisCommand<?, ?, ?> command,
        ChannelPromise promise) {

    if (!isWriteable(command)) {
        promise.trySuccess();
        return;//  w  ww  .j  ava2s .c o  m
    }

    addToStack(command, promise);

    if (tracingEnabled && command instanceof CompleteableCommand) {

        TracedCommand provider = CommandWrapper.unwrap(command, TracedCommand.class);
        Tracer tracer = clientResources.tracing().getTracerProvider().getTracer();
        TraceContext context = (provider == null ? clientResources.tracing().initialTraceContextProvider()
                : provider).getTraceContext();

        Tracer.Span span = tracer.nextSpan(context);
        span.name(command.getType().name());

        if (command.getArgs() != null) {
            span.tag("redis.args", command.getArgs().toCommandString());
        }

        span.remoteEndpoint(tracedEndpoint);
        span.start();
        provider.setSpan(span);

        CompleteableCommand<?> completeableCommand = (CompleteableCommand<?>) command;
        completeableCommand.onComplete((o, throwable) -> {

            if (command.getOutput() != null) {

                String error = command.getOutput().getError();
                if (error != null) {
                    span.tag("error", error);
                } else if (throwable != null) {
                    span.tag("exception", throwable.toString());
                    span.error(throwable);
                }
            }

            span.finish();
        });
    }

    ctx.write(command, promise);
}

From source file:io.lettuce.core.protocol.CommandHandler.java

License:Apache License

private void writeBatch(ChannelHandlerContext ctx, Collection<RedisCommand<?, ?, ?>> batch,
        ChannelPromise promise) {

    Collection<RedisCommand<?, ?, ?>> deduplicated = new LinkedHashSet<>(batch.size(), 1);

    for (RedisCommand<?, ?, ?> command : batch) {

        if (isWriteable(command) && !deduplicated.add(command)) {
            deduplicated.remove(command);
            command.completeExceptionally(new RedisException(
                    "Attempting to write duplicate command that is already enqueued: " + command));
        }/*from   w w w . ja  v a2 s .co m*/
    }

    try {
        validateWrite(deduplicated.size());
    } catch (Exception e) {

        for (RedisCommand<?, ?, ?> redisCommand : deduplicated) {
            redisCommand.completeExceptionally(e);
        }

        throw e;
    }

    for (RedisCommand<?, ?, ?> command : deduplicated) {
        addToStack(command, promise);
    }

    if (!deduplicated.isEmpty()) {
        ctx.write(deduplicated, promise);
    } else {
        promise.trySuccess();
    }
}

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) -> {// ww w  .  j a  v  a2 s.  co 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:org.apache.hadoop.hbase.ipc.BufferCallBeforeInitHandler.java

License:Apache License

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
    if (msg instanceof Call) {
        Call call = (Call) msg;//from   ww  w  . java2  s .c  om
        id2Call.put(call.id, call);
        // The call is already in track so here we set the write operation as success.
        // We will fail the call directly if we can not write it out.
        promise.trySuccess();
    } else {
        ctx.write(msg, promise);
    }
}

From source file:org.dcache.xrootd.protocol.messages.AsyncResponse.java

License:Open Source License

@Override
public void writeTo(ChannelHandlerContext ctx, final ChannelPromise promise) {
    try {/*from  w w  w  . j  av a 2  s  .  c om*/
        int dlen = getDataLength();
        ByteBuf header = ctx.alloc().buffer(8 + dlen);
        try {
            header.writeShort(0);
            header.writeShort(kXR_attn);
            header.writeInt(dlen);
            header.writeInt(kXR_asynresp);
            header.writeInt(0);
        } catch (Error | RuntimeException t) {
            promise.setFailure(t);
            header.release();
            return;
        }
        ctx.write(header).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    promise.tryFailure(future.cause());
                }
            }
        });

        ChannelPromise channelPromise = ctx.newPromise();
        channelPromise.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    promise.trySuccess();
                } else {
                    promise.tryFailure(future.cause());
                }
            }
        });
        ReferenceCountUtil.retain(response).writeTo(ctx, channelPromise);
    } finally {
        release();
    }
}

From source file:org.dcache.xrootd.protocol.messages.ZeroCopyReadResponse.java

License:Open Source License

@Override
public void writeTo(ChannelHandlerContext ctx, final ChannelPromise promise) {
    ByteBuf header = ctx.alloc().buffer(8);
    header.writeShort(request.getStreamId());
    header.writeShort(kXR_ok);//from  w  w w  .  j  av  a 2  s .c  om
    header.writeInt(count);
    ctx.write(header).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                promise.tryFailure(future.cause());
            }
        }
    });
    ctx.write(new DefaultFileRegion(file, request.getReadOffset(), count))
            .addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        promise.trySuccess();
                    } else {
                        promise.tryFailure(future.cause());
                    }
                }
            });
}

From source file:reactor.io.net.impl.netty.http.NettyHttpClientHandler.java

License:Open Source License

@Override
protected void doOnTerminate(ChannelHandlerContext ctx, ChannelFuture last, final ChannelPromise promise) {
    if (request.method() == Method.WS) {
        return;/* ww w.j a v a2  s.  co  m*/
    }

    ByteBuffer byteBuffer = body.flip().byteBuffer();

    if (request.checkHeader()) {
        HttpRequest req = new DefaultFullHttpRequest(request.getNettyRequest().getProtocolVersion(),
                request.getNettyRequest().getMethod(), request.getNettyRequest().getUri(),
                byteBuffer != null ? Unpooled.wrappedBuffer(byteBuffer) : Unpooled.EMPTY_BUFFER);

        req.headers().add(request.headers().delegate());

        if (byteBuffer != null) {
            HttpHeaders.setContentLength(req, body.limit());
        }

        ctx.writeAndFlush(req).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    promise.trySuccess();
                } else {
                    promise.tryFailure(future.cause());
                }
            }
        });
    } else {
        ctx.write(new DefaultHttpContent(
                byteBuffer != null ? Unpooled.wrappedBuffer(byteBuffer) : Unpooled.EMPTY_BUFFER));
    }
    body.reset();
}

From source file:reactor.io.net.impl.netty.http.NettyHttpWSClientHandler.java

License:Open Source License

@Override
protected void doOnTerminate(ChannelHandlerContext ctx, ChannelFuture last, final ChannelPromise promise) {
    if (ctx.channel().isOpen()) {
        ChannelFutureListener listener = new ChannelFutureListener() {
            @Override// w ww  . jav  a 2  s .  co  m
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    promise.trySuccess();
                } else {
                    promise.tryFailure(future.cause());
                }
            }
        };

        if (last != null) {
            ctx.flush();
            last.addListener(listener);
        } else {
            ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(listener);
        }
    } else {
        promise.trySuccess();
    }
}

From source file:reactor.io.net.impl.netty.NettyChannelHandlerBridge.java

License:Apache License

protected void doOnTerminate(ChannelHandlerContext ctx, ChannelFuture last, final ChannelPromise promise) {
    if (ctx.channel().isOpen()) {
        ChannelFutureListener listener = new ChannelFutureListener() {
            @Override//from ww w. j a v  a  2 s.  co m
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    promise.trySuccess();
                } else {
                    promise.tryFailure(future.cause());
                }
            }
        };

        if (last != null) {
            ctx.flush();
            last.addListener(listener);
        } else {
            ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(listener);
        }
    } else {
        promise.trySuccess();
    }
}