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:io.flood.rpc.network.AcceptorImpl.java

License:Apache License

private void bind(final SocketAddress address) {
    id = SocketIdGenerator.nextId();//from  w  w w. j a  va 2 s  .c  o  m
    boot = new ServerBootstrap();
    boot.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {

                protected void initChannel(SocketChannel ch) throws Exception {
                    LinkedHashMap<String, ChannelHandler> handlers = getHandlers();
                    for (Map.Entry<String, ChannelHandler> entry : handlers.entrySet()) {
                        ch.pipeline().addLast(entry.getKey(), entry.getValue());
                    }
                    ch.pipeline().addLast("messageDecoder", new MessageDecoder());
                    ch.pipeline().addLast("messageEncoder", new MessageEncoder());
                    ch.pipeline().addLast("messageHandler", new MessageHandler(AcceptorImpl.this));
                }
            });

    try {
        final ChannelFuture future = boot.bind(address).sync();

        if (future.isSuccess()) {
            id = SocketIdGenerator.nextId();
            LOG.info(format(id, "socket bind success({})"), address);
            ConnectionManager.put(id, Connection.Type.Server, future.channel());
            onBindCompleted(future);
            future.channel().closeFuture()
                    .addListener(new GenericFutureListener<io.netty.util.concurrent.Future<? super Void>>() {

                        public void operationComplete(Future<? super Void> completefuture) throws Exception {
                            LOG.info(format(id, "socket closed()"));
                            serverChannel.remove(future.channel());
                        }

                    });
        }

        else {
            LOG.error(format(id, "socket bind failed({})"), address, future.cause());
        }

    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}

From source file:io.gomint.proxprox.network.DownstreamConnection.java

License:BSD License

/**
 * Create a new AbstractConnection to a server.
 *
 * @param proxProx           The proxy instance
 * @param upstreamConnection The upstream connection which requested to connect to this downstream
 * @param ip                 The ip of the server we want to connect to
 * @param port               The port of the server we want to connect to
 *//*from  w  ww .ja va 2 s .c om*/
DownstreamConnection(ProxProxProxy proxProx, UpstreamConnection upstreamConnection, String ip, int port) {
    this.upstreamConnection = upstreamConnection;
    this.proxProx = proxProx;

    this.ip = ip;
    this.port = port;

    // Check if we use UDP or TCP for downstream connections
    if (proxProx.getConfig().isUseTCP()) {
        io.netty.bootstrap.Bootstrap bootstrap = Initializer.buildBootstrap(this.upstreamConnection, ip, port,
                new Consumer<ConnectionHandler>() {
                    @Override
                    public void accept(ConnectionHandler connectionHandler) {
                        DownstreamConnection.this.tcpConnection = connectionHandler;

                        // There are no batches in TCP
                        connectionHandler.onData(DownstreamConnection.this::handlePacket);

                        connectionHandler.whenDisconnected(new Consumer<Void>() {
                            @Override
                            public void accept(Void aVoid) {
                                if (upstreamConnection.isConnected()) {
                                    LOGGER.info("Disconnected downstream...");
                                    if (!DownstreamConnection.this.manualClose) {
                                        DownstreamConnection.this.close(true, "Server disconnected");

                                        // Check if we need to disconnect upstream
                                        if (DownstreamConnection.this
                                                .equals(upstreamConnection.getDownStream())) {
                                            if (upstreamConnection.getPendingDownStream() != null
                                                    || upstreamConnection.connectToLastKnown()) {
                                                return;
                                            } else {
                                                upstreamConnection.disconnect("The Server has gone down");
                                            }
                                        } else {
                                            upstreamConnection.resetPendingDownStream();
                                        }
                                    }
                                }
                            }
                        });

                        DownstreamConnection.this.upstreamConnection
                                .onDownStreamConnected(DownstreamConnection.this);
                    }
                });
        bootstrap.connect(this.ip, this.port).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                if (!channelFuture.isSuccess()) {
                    LOGGER.warn("Could not connect to {}:{}", DownstreamConnection.this.ip,
                            DownstreamConnection.this.port, channelFuture.cause());
                    DownstreamConnection.this.upstreamConnection.resetPendingDownStream();
                }
            }
        });
    } else {
        this.initDecompressor();
        this.connection = new ClientSocket();
        this.connection.setMojangModificationEnabled(true);
        this.connection.setEventHandler((socket, socketEvent) -> {
            LOGGER.debug("Got socketEvent: " + socketEvent.getType().name());
            switch (socketEvent.getType()) {
            case CONNECTION_ATTEMPT_SUCCEEDED:
                // We got accepted *yay*
                DownstreamConnection.this.setup();
                DownstreamConnection.this.upstreamConnection.onDownStreamConnected(DownstreamConnection.this);
                break;

            case CONNECTION_CLOSED:
            case CONNECTION_DISCONNECTED:
                LOGGER.info("Disconnected downstream...");
                if (!DownstreamConnection.this.manualClose) {
                    DownstreamConnection.this.updateIncoming(socketEvent.getConnection());
                    DownstreamConnection.this.close(true, "Raknet disconnected");

                    // Check if we need to disconnect upstream
                    if (DownstreamConnection.this.equals(upstreamConnection.getDownStream())) {
                        if (upstreamConnection.getPendingDownStream() != null
                                || upstreamConnection.connectToLastKnown()) {
                            return;
                        } else {
                            upstreamConnection.disconnect("The Server has gone down");
                        }
                    } else {
                        upstreamConnection.resetPendingDownStream();
                    }
                }

                break;

            default:
                break;
            }
        });

        try {
            this.connection.initialize();
        } catch (SocketException e) {
            LOGGER.warn("Could not connect to {}:{}", this.ip, this.port, e);
        }

        this.connection.connect(ip, port);
    }
}

From source file:io.grpc.alts.internal.AltsProtocolNegotiatorTest.java

License:Apache License

@Test
@SuppressWarnings("unchecked") // List cast
public void protectShouldRoundtrip() throws Exception {
    doHandshake();/*www .j av a 2  s .c  o  m*/

    // Write the message 1 character at a time. The message should be buffered
    // and not interfere with the handshake.
    final AtomicInteger writeCount = new AtomicInteger();
    String message = "hello";
    for (int ix = 0; ix < message.length(); ++ix) {
        ByteBuf in = Unpooled.copiedBuffer(message, ix, 1, UTF_8);
        @SuppressWarnings("unused") // go/futurereturn-lsc
        Future<?> possiblyIgnoredError = channel.write(in).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    writeCount.incrementAndGet();
                }
            }
        });
    }
    channel.flush();

    // Capture the protected data written to the wire.
    assertEquals(1, channel.outboundMessages().size());
    ByteBuf protectedData = channel.readOutbound();
    assertEquals(message.length(), writeCount.get());

    // Read the protected message at the server and verify it matches the original message.
    TsiFrameProtector serverProtector = serverHandshaker.createFrameProtector(channel.alloc());
    List<ByteBuf> unprotected = new ArrayList<>();
    serverProtector.unprotect(protectedData, (List<Object>) (List<?>) unprotected, channel.alloc());
    // We try our best to remove the HTTP2 handler as soon as possible, but just by constructing it
    // a settings frame is written (and an HTTP2 preface).  This is hard coded into Netty, so we
    // have to remove it here.  See {@code Http2ConnectionHandler.PrefaceDecode.sendPreface}.
    int settingsFrameLength = 9;

    CompositeByteBuf unprotectedAll = new CompositeByteBuf(channel.alloc(), false, unprotected.size() + 1,
            unprotected);
    ByteBuf unprotectedData = unprotectedAll.slice(settingsFrameLength, message.length());
    assertEquals(message, unprotectedData.toString(UTF_8));

    // Protect the same message at the server.
    final AtomicReference<ByteBuf> newlyProtectedData = new AtomicReference<>();
    serverProtector.protectFlush(Collections.singletonList(unprotectedData), new Consumer<ByteBuf>() {
        @Override
        public void accept(ByteBuf buf) {
            newlyProtectedData.set(buf);
        }
    }, channel.alloc());

    // Read the protected message at the client and verify that it matches the original message.
    channel.writeInbound(newlyProtectedData.get());
    assertEquals(1, channel.inboundMessages().size());
    assertEquals(message, channel.<ByteBuf>readInbound().toString(UTF_8));
}

From source file:io.grpc.alts.internal.AltsProtocolNegotiatorTest.java

License:Apache License

@Test
public void flushShouldFailAllPromises() throws Exception {
    doHandshake();/*from  w  w w. java2 s.  co m*/

    channel.pipeline().addFirst(new ChannelDuplexHandler() {
        @Override
        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
            throw new Exception("Fake exception");
        }
    });

    // Write the message 1 character at a time.
    String message = "hello";
    final AtomicInteger failures = new AtomicInteger();
    for (int ix = 0; ix < message.length(); ++ix) {
        ByteBuf in = Unpooled.copiedBuffer(message, ix, 1, UTF_8);
        @SuppressWarnings("unused") // go/futurereturn-lsc
        Future<?> possiblyIgnoredError = channel.write(in).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    failures.incrementAndGet();
                }
            }
        });
    }
    channel.flush();

    // Verify that the promises fail.
    assertEquals(message.length(), failures.get());
}

From source file:io.grpc.netty.NettyClientHandler.java

License:Apache License

private void createStreamTraced(final int streamId, final NettyClientStream.TransportState stream,
        final Http2Headers headers, boolean isGet, final boolean shouldBeCountedForInUse,
        final ChannelPromise promise) {
    // Create an intermediate promise so that we can intercept the failure reported back to the
    // application.
    ChannelPromise tempPromise = ctx().newPromise();
    encoder().writeHeaders(ctx(), streamId, headers, 0, isGet, tempPromise)
            .addListener(new ChannelFutureListener() {
                @Override/*  w  w  w. ja v a 2 s  . c  o m*/
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        // The http2Stream will be null in case a stream buffered in the encoder
                        // was canceled via RST_STREAM.
                        Http2Stream http2Stream = connection().stream(streamId);
                        if (http2Stream != null) {
                            stream.getStatsTraceContext().clientOutboundHeaders();
                            http2Stream.setProperty(streamKey, stream);

                            // This delays the in-use state until the I/O completes, which technically may
                            // be later than we would like.
                            if (shouldBeCountedForInUse) {
                                inUseState.updateObjectInUse(http2Stream, true);
                            }

                            // Attach the client stream to the HTTP/2 stream object as user data.
                            stream.setHttp2Stream(http2Stream);
                        }
                        // Otherwise, the stream has been cancelled and Netty is sending a
                        // RST_STREAM frame which causes it to purge pending writes from the
                        // flow-controller and delete the http2Stream. The stream listener has already
                        // been notified of cancellation so there is nothing to do.

                        // Just forward on the success status to the original promise.
                        promise.setSuccess();
                    } else {
                        final Throwable cause = future.cause();
                        if (cause instanceof StreamBufferingEncoder.Http2GoAwayException) {
                            StreamBufferingEncoder.Http2GoAwayException e = (StreamBufferingEncoder.Http2GoAwayException) cause;
                            lifecycleManager.notifyShutdown(statusFromGoAway(e.errorCode(), e.debugData()));
                            promise.setFailure(lifecycleManager.getShutdownThrowable());
                        } else {
                            promise.setFailure(cause);
                        }
                    }
                }
            });
}

From source file:io.grpc.netty.NettyClientHandler.java

License:Apache License

/**
 * Sends a PING frame. If a ping operation is already outstanding, the callback in the message is
 * registered to be called when the existing operation completes, and no new frame is sent.
 *//* w w w.  ja  v a 2s  . c  o m*/
private void sendPingFrameTraced(ChannelHandlerContext ctx, SendPingCommand msg, ChannelPromise promise) {
    // Don't check lifecycleManager.getShutdownStatus() since we want to allow pings after shutdown
    // but before termination. After termination, messages will no longer arrive because the
    // pipeline clears all handlers on channel close.

    PingCallback callback = msg.callback();
    Executor executor = msg.executor();
    // we only allow one outstanding ping at a time, so just add the callback to
    // any outstanding operation
    if (ping != null) {
        promise.setSuccess();
        ping.addCallback(callback, executor);
        return;
    }

    // Use a new promise to prevent calling the callback twice on write failure: here and in
    // NettyClientTransport.ping(). It may appear strange, but it will behave the same as if
    // ping != null above.
    promise.setSuccess();
    promise = ctx().newPromise();
    // set outstanding operation
    long data = USER_PING_PAYLOAD;
    Stopwatch stopwatch = stopwatchFactory.get();
    stopwatch.start();
    ping = new Http2Ping(data, stopwatch);
    ping.addCallback(callback, executor);
    // and then write the ping
    encoder().writePing(ctx, false, USER_PING_PAYLOAD, promise);
    ctx.flush();
    final Http2Ping finalPing = ping;
    promise.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                transportTracer.reportKeepAliveSent();
            } else {
                Throwable cause = future.cause();
                if (cause instanceof ClosedChannelException) {
                    cause = lifecycleManager.getShutdownThrowable();
                    if (cause == null) {
                        cause = Status.UNKNOWN.withDescription("Ping failed but for unknown reason.")
                                .withCause(future.cause()).asException();
                    }
                }
                finalPing.failed(cause);
                if (ping == finalPing) {
                    ping = null;
                }
            }
        }
    });
}

From source file:io.grpc.netty.NettyClientHandlerTest.java

License:Apache License

@Test
public void cancelBufferedStreamShouldChangeClientStreamStatus() throws Exception {
    // Force the stream to be buffered.
    receiveMaxConcurrentStreams(0);/*  w  ww  .j  a va2s.c o m*/
    // Create a new stream with id 3.
    ChannelFuture createFuture = enqueue(newCreateStreamCommand(grpcHeaders, streamTransportState));
    assertEquals(3, streamTransportState.id());
    // Cancel the stream.
    cancelStream(Status.CANCELLED);

    assertTrue(createFuture.isSuccess());
    verify(streamListener).closed(eq(Status.CANCELLED), same(PROCESSED), any(Metadata.class));
}

From source file:io.grpc.netty.NettyClientHandlerTest.java

License:Apache License

@Test
public void cancelWhileBufferedShouldSucceed() throws Exception {
    // Force the stream to be buffered.
    receiveMaxConcurrentStreams(0);/*from  w  w  w.jav a2 s  .c  o  m*/

    ChannelFuture createFuture = createStream();
    assertFalse(createFuture.isDone());

    ChannelFuture cancelFuture = cancelStream(Status.CANCELLED);
    assertTrue(cancelFuture.isSuccess());
    assertTrue(createFuture.isDone());
    assertTrue(createFuture.isSuccess());
}

From source file:io.grpc.netty.NettyClientHandlerTest.java

License:Apache License

/**
 * Although nobody is listening to an exception should it occur during cancel(), we don't want an
 * exception to be thrown because it would negatively impact performance, and we don't want our
 * users working around around such performance issues.
 *///from  w w  w . jav a 2s . com
@Test
public void cancelTwiceShouldSucceed() throws Exception {
    createStream();

    cancelStream(Status.CANCELLED);

    verifyWrite().writeRstStream(any(ChannelHandlerContext.class), eq(3), eq(Http2Error.CANCEL.code()),
            any(ChannelPromise.class));

    ChannelFuture future = cancelStream(Status.CANCELLED);
    assertTrue(future.isSuccess());
}

From source file:io.grpc.netty.NettyClientHandlerTest.java

License:Apache License

@Test
public void cancelTwiceDifferentReasons() throws Exception {
    createStream();/*from  w ww. ja v a  2s. c o  m*/

    cancelStream(Status.DEADLINE_EXCEEDED);

    verifyWrite().writeRstStream(eq(ctx()), eq(3), eq(Http2Error.CANCEL.code()), any(ChannelPromise.class));

    ChannelFuture future = cancelStream(Status.CANCELLED);
    assertTrue(future.isSuccess());
}