Example usage for io.netty.channel ChannelFuture isSuccess

List of usage examples for io.netty.channel ChannelFuture isSuccess

Introduction

In this page you can find the example usage for io.netty.channel ChannelFuture isSuccess.

Prototype

boolean isSuccess();

Source Link

Document

Returns true if and only if the I/O operation was completed successfully.

Usage

From source file:com.tongbanjie.tarzan.rpc.netty.NettyRpcAbstract.java

License:Apache License

public RpcCommand invokeSyncImpl(final Channel channel, final RpcCommand request, final long timeoutMillis)
        throws InterruptedException, RpcTooMuchRequestException, RpcSendRequestException, RpcTimeoutException {
    //check channel writable
    if (!channel.isWritable()) {
        throw new RpcTooMuchRequestException(
                String.format("Invoke request too much, the channel[%s] is not writable", channel.toString()));
    }/*from   w w w. j  a  va  2 s  .  com*/

    final int opaque = request.getOpaque();

    try {
        final ResponseFuture responseFuture = new ResponseFuture(opaque, timeoutMillis, null, null);
        this.responseTable.put(opaque, responseFuture);
        final SocketAddress addr = channel.remoteAddress();
        channel.writeAndFlush(request).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture f) throws Exception {
                if (f.isSuccess()) {
                    responseFuture.setSendRequestOK(true);
                    return;
                } else {
                    responseFuture.setSendRequestOK(false);
                }

                responseTable.remove(opaque);
                responseFuture.setCause(f.cause());
                responseFuture.putResponse(null);
                LOGGER.warn("send a request command to channel <" + addr + "> failed.");
            }
        });

        RpcCommand responseCommand = responseFuture.waitResponse(timeoutMillis);
        if (null == responseCommand) {
            if (responseFuture.isSendRequestOK()) {
                throw new RpcTimeoutException(RpcHelper.parseSocketAddressAddr(addr), timeoutMillis,
                        responseFuture.getCause());
            } else {
                throw new RpcSendRequestException(RpcHelper.parseSocketAddressAddr(addr),
                        responseFuture.getCause());
            }
        }

        return responseCommand;
    } finally {
        this.responseTable.remove(opaque);
    }
}

From source file:com.tongbanjie.tarzan.rpc.netty.NettyRpcAbstract.java

License:Apache License

public void invokeAsyncImpl(final Channel channel, final RpcCommand request, final long timeoutMillis,
        final InvokeCallback invokeCallback)
        throws InterruptedException, RpcTooMuchRequestException, RpcTimeoutException, RpcSendRequestException {
    //check channel writable
    if (!channel.isWritable()) {
        throw new RpcTooMuchRequestException(
                String.format("Invoke request too much, the channel[%s] is not writable", channel.toString()));
    }//from  w w  w  .  ja  va2 s .co  m

    final int opaque = request.getOpaque();
    boolean acquired = this.semaphoreAsync.tryAcquire(timeoutMillis, TimeUnit.MILLISECONDS);
    if (acquired) {
        final OnceSemaphore once = new OnceSemaphore(this.semaphoreAsync);

        final ResponseFuture responseFuture = new ResponseFuture(opaque, timeoutMillis, invokeCallback, once);
        this.responseTable.put(opaque, responseFuture);
        try {
            channel.writeAndFlush(request).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture f) throws Exception {
                    if (f.isSuccess()) {
                        responseFuture.setSendRequestOK(true);
                        return;
                    } else {
                        responseFuture.setSendRequestOK(false);
                    }

                    responseFuture.putResponse(null);
                    responseTable.remove(opaque);
                    try {
                        responseFuture.executeInvokeCallback();
                    } catch (Throwable e) {
                        LOGGER.warn("execute callback in writeAndFlush addListener, and callback throw", e);
                    } finally {
                        responseFuture.release();
                    }

                    LOGGER.warn("send a request command to channel <{}> failed.",
                            RpcHelper.parseChannelRemoteAddr(channel));
                }
            });
        } catch (Exception e) {
            responseFuture.release();
            LOGGER.warn("send a request command to channel <" + RpcHelper.parseChannelRemoteAddr(channel)
                    + "> Exception", e);
            throw new RpcSendRequestException(RpcHelper.parseChannelRemoteAddr(channel), e);
        }
    } else {
        if (timeoutMillis <= 0) {
            throw new RpcTooMuchRequestException("invokeAsyncImpl invoke too fast");
        } else {
            String info = String.format(
                    "invokeAsyncImpl tryAcquire semaphore timeout, %dms, waiting thread nums: %d semaphoreAsyncValue: %d", //
                    timeoutMillis, //
                    this.semaphoreAsync.getQueueLength(), //
                    this.semaphoreAsync.availablePermits()//
            );
            LOGGER.warn(info);
            throw new RpcTimeoutException(info);
        }
    }
}

From source file:com.tongbanjie.tarzan.rpc.netty.NettyRpcAbstract.java

License:Apache License

public void invokeOneWayImpl(final Channel channel, final RpcCommand request, final long timeoutMillis)
        throws InterruptedException, RpcTooMuchRequestException, RpcTimeoutException, RpcSendRequestException {
    //check channel writable
    if (!channel.isWritable()) {
        throw new RpcTooMuchRequestException(
                String.format("Invoke request too much, the channel[%s] is not writable", channel.toString()));
    }/*from  www  .  j  av a2s  .c  o m*/

    request.setOneWayRpc(true);
    boolean acquired = this.semaphoreOneWay.tryAcquire(timeoutMillis, TimeUnit.MILLISECONDS);
    if (acquired) {
        final OnceSemaphore once = new OnceSemaphore(this.semaphoreOneWay);
        try {
            channel.writeAndFlush(request).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture f) throws Exception {
                    once.release();
                    if (!f.isSuccess()) {
                        LOGGER.warn(
                                "send a request command to channel <" + channel.remoteAddress() + "> failed.");
                    }
                }
            });
        } catch (Exception e) {
            once.release();
            LOGGER.warn("write send a request command to channel <" + channel.remoteAddress() + "> failed.");
            throw new RpcSendRequestException(RpcHelper.parseChannelRemoteAddr(channel), e);
        }
    } else {
        if (timeoutMillis <= 0) {
            throw new RpcTooMuchRequestException("invokeOneWayImpl invoke too fast");
        } else {
            String info = String.format(
                    "invokeOneWayImpl tryAcquire semaphore timeout, %dms, waiting thread nums: %d semaphoreAsyncValue: %d", //
                    timeoutMillis, //
                    this.semaphoreAsync.getQueueLength(), //
                    this.semaphoreAsync.availablePermits()//
            );
            LOGGER.warn(info);
            throw new RpcTimeoutException(info);
        }
    }
}

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

License:Open Source License

/**
 * <p>Sends a push notification to the APNs gateway.</p>
 *
 * <p>This method returns a {@code Future} that indicates whether the notification was accepted or rejected by the
 * gateway. If the notification was accepted, it may be delivered to its destination device at some time in the
 * future, but final delivery is not guaranteed. Rejections should be considered permanent failures, and callers
 * should <em>not</em> attempt to re-send the notification.</p>
 *
 * <p>The returned {@code Future} may fail with an exception if the notification could not be sent. Failures to
 * <em>send</em> a notification to the gatewayi.e. those that fail with exceptionsshould generally be considered
 * non-permanent, and callers should attempt to re-send the notification when the underlying problem has been
 * resolved.</p>//w ww  .ja  v  a2 s.  c o  m
 *
 * @param notification the notification to send to the APNs gateway
 *
 * @param <T> the type of notification to be sent
 *
 * @return a {@code Future} that will complete when the notification has been either accepted or rejected by the
 * APNs gateway
 *
 * @see com.turo.pushy.apns.util.concurrent.PushNotificationResponseListener
 *
 * @since 0.8
 */
@SuppressWarnings("unchecked")
public <T extends ApnsPushNotification> PushNotificationFuture<T, PushNotificationResponse<T>> sendNotification(
        final T notification) {
    final PushNotificationFuture<T, PushNotificationResponse<T>> responseFuture;

    if (!this.isClosed.get()) {
        final PushNotificationPromise<T, PushNotificationResponse<T>> responsePromise = new PushNotificationPromise<>(
                this.eventLoopGroup.next(), notification);

        final long notificationId = this.nextNotificationId.getAndIncrement();

        this.channelPool.acquire().addListener(new GenericFutureListener<Future<Channel>>() {
            @Override
            public void operationComplete(final Future<Channel> acquireFuture) throws Exception {
                if (acquireFuture.isSuccess()) {
                    final Channel channel = acquireFuture.getNow();

                    channel.writeAndFlush(responsePromise)
                            .addListener(new GenericFutureListener<ChannelFuture>() {

                                @Override
                                public void operationComplete(final ChannelFuture future) throws Exception {
                                    if (future.isSuccess()) {
                                        ApnsClient.this.metricsListener.handleNotificationSent(ApnsClient.this,
                                                notificationId);
                                    }
                                }
                            });

                    ApnsClient.this.channelPool.release(channel);
                } else {
                    responsePromise.tryFailure(acquireFuture.cause());
                }
            }
        });

        responsePromise.addListener(new PushNotificationResponseListener<T>() {
            @Override
            public void operationComplete(final PushNotificationFuture<T, PushNotificationResponse<T>> future)
                    throws Exception {
                if (future.isSuccess()) {
                    final PushNotificationResponse response = future.getNow();

                    if (response.isAccepted()) {
                        ApnsClient.this.metricsListener.handleNotificationAccepted(ApnsClient.this,
                                notificationId);
                    } else {
                        ApnsClient.this.metricsListener.handleNotificationRejected(ApnsClient.this,
                                notificationId);
                    }
                } else {
                    ApnsClient.this.metricsListener.handleWriteFailure(ApnsClient.this, notificationId);
                }
            }
        });

        responseFuture = responsePromise;
    } else {
        final PushNotificationPromise<T, PushNotificationResponse<T>> failedPromise = new PushNotificationPromise<>(
                GlobalEventExecutor.INSTANCE, notification);

        failedPromise.setFailure(CLIENT_CLOSED_EXCEPTION);

        responseFuture = failedPromise;
    }

    return responseFuture;
}

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

License:Open Source License

@Override
public void userEventTriggered(final ChannelHandlerContext context, final Object event) throws Exception {
    if (event instanceof IdleStateEvent) {
        log.trace("Sending ping due to inactivity.");

        this.encoder().writePing(context, false, System.currentTimeMillis(), context.newPromise())
                .addListener(new GenericFutureListener<ChannelFuture>() {

                    @Override//w  ww .j a va  2s. c  o  m
                    public void operationComplete(final ChannelFuture future) {
                        if (!future.isSuccess()) {
                            log.debug("Failed to write PING frame.", future.cause());
                            future.channel().close();
                        }
                    }
                });

        this.pingTimeoutFuture = context.channel().eventLoop().schedule(new Runnable() {

            @Override
            public void run() {
                log.debug("Closing channel due to ping timeout.");
                context.channel().close();
            }
        }, pingTimeoutMillis, TimeUnit.MILLISECONDS);

        this.flush(context);
    }

    super.userEventTriggered(context, event);
}

From source file:com.twitter.http2.HttpStreamEncoder.java

License:Apache License

private ChannelPromise getMessageFuture(final ChannelHandlerContext ctx, final ChannelPromise promise,
        final int streamId, HttpMessage message) {
    if (message instanceof StreamedHttpMessage && !((StreamedHttpMessage) message).getContent().isClosed()) {
        final Pipe<HttpContent> pipe = ((StreamedHttpMessage) message).getContent();

        ChannelPromise writeFuture = ctx.channel().newPromise();
        writeFuture.addListener(new ChannelFutureListener() {
            @Override/*  www  .  j  a v a  2 s . c o m*/
            public void operationComplete(ChannelFuture future) throws Exception {
                // Channel's thread
                // First frame has been written

                if (future.isSuccess()) {
                    pipe.receive().addListener(new ChunkListener(ctx, streamId, pipe, promise));
                } else if (future.isCancelled()) {
                    pipe.close();
                    promise.cancel(true);
                } else {
                    pipe.close();
                    promise.setFailure(future.cause());
                }
            }
        });

        return writeFuture;
    } else {
        return promise;
    }
}

From source file:com.uber.jaeger.crossdock.resources.behavior.tchannel.TChannelServer.java

License:Apache License

public void start() throws InterruptedException {
    // listen for incoming connections
    ChannelFuture serverFuture = server.listen().awaitUninterruptibly();
    if (!serverFuture.isSuccess()) {
        throw new RuntimeException("Server future unsuccessful");
    }//from www  . java 2  s  .  c o  m
}

From source file:com.uber.tchannel.channels.Peer.java

License:Open Source License

public Connection connect(Bootstrap bootstrap, Connection.Direction preferredDirection) {
    Connection conn = getConnection(ConnectionState.IDENTIFIED, preferredDirection);
    if (conn != null && (conn.satisfy(preferredDirection) || preferredDirection == Connection.Direction.IN)) {
        return conn;
    }//from  www. ja v  a  2s .  c  om

    final ChannelFuture f = bootstrap.connect(remoteAddress);
    Channel channel = f.channel();
    final Connection connection = add(channel, Connection.Direction.OUT);

    // handle connection errors
    f.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                connection.setIndentified(new TChannelConnectionFailure(future.cause()));
            }
        }
    });

    return connection;
}

From source file:com.ura.proxy.HexDumpProxyInboundHandler.java

License:Apache License

@Override
public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    // Suspend incoming traffic until connected to the remote host.
    final Channel inboundChannel = e.getChannel();
    inboundChannel.setReadable(false);//  ww  w.ja v a2  s . co m

    // Start the connection attempt.
    ClientBootstrap cb = new ClientBootstrap(cf);
    cb.getPipeline().addLast("handler", new OutboundHandler(e.getChannel()));
    ChannelFuture f = cb.connect(new InetSocketAddress(remoteHost, remotePort));

    outboundChannel = f.getChannel();
    f.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                // Connection attempt succeeded:
                // Begin to accept incoming traffic.
                inboundChannel.setReadable(true);
            } else {
                // Close the connection if the connection attempt has failed.
                inboundChannel.close();
            }
        }
    });
}

From source file:com.util.MyServer.java

License:Apache License

synchronized protected void setBindStatus(ChannelFuture cf) {
    if (cf.isSuccess()) {
        bindSuccessCount++;/* w ww . ja  v  a 2  s. co m*/
        InetSocketAddress localAddress = (InetSocketAddress) cf.channel().localAddress();
        logger.info("Server listen on " + localAddress.getAddress().getHostAddress() + ":"
                + localAddress.getPort());
        if (bindSuccessCount >= bindAddress.length) {
            logger.info("Server started");
        }
    } else {
        logger.info("Server bind address failure:" + cf.cause().getMessage());
        this.stop();
    }
}