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.xiovr.unibot.bot.network.impl.BotConnectionServerImpl.java

License:Open Source License

@Override
public void connect(@NonNull InetSocketAddress address) {

    cf = bs.connect(address);/*from  ww  w  .ja  va  2  s  .c om*/
    cf.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                // botContext.getCryptorPlugin().onConnected(ScriptPlugin.CONN_TO_SERVER);
                // final ScriptPlugin sp = botContext.getScript();
                // if (sp != null)
                // sp.onConnected(ScriptPlugin.CONN_TO_SERVER);
                // bConnected = true;

            }
        }
    });
}

From source file:com.xx_dev.apn.proxy.ApnProxyRemoteForwardHandler.java

License:Apache License

public void channelRead(final ChannelHandlerContext remoteChannelCtx, final Object msg) throws Exception {
    LoggerUtil.debug(logger, uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY), "Remote msg", msg);

    remainMsgCount++;/*from   ww  w.  j  av  a 2  s .  c o  m*/

    if (remainMsgCount <= 5) {
        remoteChannelCtx.read();
    }

    HttpObject ho = (HttpObject) msg;

    if (ho instanceof HttpResponse) {
        HttpResponse httpResponse = (HttpResponse) ho;

        LoggerUtil.info(forwardRestLogger, uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY),
                httpResponse.getStatus(), httpResponse.getProtocolVersion());

        httpResponse.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
        httpResponse.headers().set("Proxy-Connection", HttpHeaders.Values.KEEP_ALIVE);
    }

    if (uaChannel.isActive()) {
        uaChannel.writeAndFlush(ho).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                LoggerUtil.debug(logger, uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY),
                        "Write to UA finished: " + future.isSuccess());
                if (future.isSuccess()) {
                    remainMsgCount--;
                    remoteChannelCtx.read();
                    LoggerUtil.debug(logger, uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY),
                            "Fire read again");
                } else {
                    remoteChannelCtx.close();
                }
            }
        });
    } else {
        remoteChannelCtx.close();
    }
}

From source file:com.xx_dev.apn.proxy.ApnProxyUserAgentForwardHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext uaChannelCtx, final Object msg) throws Exception {

    final Channel uaChannel = uaChannelCtx.channel();

    final ApnProxyRemote apnProxyRemote = uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY).get()
            .getRemote();/*from w  w  w.  j a  v a 2 s . c om*/

    if (msg instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) msg;

        Channel remoteChannel = remoteChannelMap.get(apnProxyRemote.getRemoteAddr());

        if (remoteChannel != null && remoteChannel.isActive()) {
            LoggerUtil.debug(logger, uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY),
                    "Use old remote channel");
            HttpRequest request = constructRequestForProxy(httpRequest, apnProxyRemote);
            remoteChannel.writeAndFlush(request);
        } else {
            LoggerUtil.debug(logger, uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY),
                    "Create new remote channel");

            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(uaChannel.eventLoop()).channel(NioSocketChannel.class)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                    .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .option(ChannelOption.AUTO_READ, false)
                    .handler(new ApnProxyRemoteForwardChannelInitializer(uaChannel, this));

            // set local address
            if (StringUtils.isNotBlank(ApnProxyLocalAddressChooser.choose(apnProxyRemote.getRemoteHost()))) {
                bootstrap.localAddress(new InetSocketAddress(
                        (ApnProxyLocalAddressChooser.choose(apnProxyRemote.getRemoteHost())), 0));
            }

            ChannelFuture remoteConnectFuture = bootstrap.connect(apnProxyRemote.getRemoteHost(),
                    apnProxyRemote.getRemotePort());

            remoteChannel = remoteConnectFuture.channel();
            remoteChannelMap.put(apnProxyRemote.getRemoteAddr(), remoteChannel);

            remoteConnectFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        future.channel().write(constructRequestForProxy((HttpRequest) msg, apnProxyRemote));

                        for (HttpContent hc : httpContentBuffer) {
                            future.channel().writeAndFlush(hc);

                            if (hc instanceof LastHttpContent) {
                                future.channel().writeAndFlush(Unpooled.EMPTY_BUFFER)
                                        .addListener(new ChannelFutureListener() {
                                            @Override
                                            public void operationComplete(ChannelFuture future)
                                                    throws Exception {
                                                if (future.isSuccess()) {
                                                    future.channel().read();
                                                }

                                            }
                                        });
                            }
                        }
                        httpContentBuffer.clear();
                    } else {
                        LoggerUtil.error(logger, uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY),
                                "Remote channel create fail");

                        // send error response
                        String errorMsg = "remote connect to "
                                + uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY).get().getRemote()
                                        .getRemoteAddr()
                                + " fail";
                        HttpMessage errorResponseMsg = HttpErrorUtil
                                .buildHttpErrorMessage(HttpResponseStatus.INTERNAL_SERVER_ERROR, errorMsg);
                        uaChannel.writeAndFlush(errorResponseMsg);
                        httpContentBuffer.clear();

                        future.channel().close();
                    }
                }
            });

        }
        ReferenceCountUtil.release(msg);
    } else {
        Channel remoteChannel = remoteChannelMap.get(apnProxyRemote.getRemoteAddr());

        HttpContent hc = ((HttpContent) msg);
        //hc.retain();

        //HttpContent _hc = hc.copy();

        if (remoteChannel != null && remoteChannel.isActive()) {
            remoteChannel.writeAndFlush(hc);

            if (hc instanceof LastHttpContent) {
                remoteChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (future.isSuccess()) {
                            future.channel().read();
                        }

                    }
                });
            }
        } else {
            httpContentBuffer.add(hc);
        }
    }

}

From source file:com.xx_dev.apn.proxy.ApnProxyUserAgentTunnelHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext uaChannelCtx, Object msg) throws Exception {

    if (msg instanceof HttpRequest) {
        final HttpRequest httpRequest = (HttpRequest) msg;

        //Channel uaChannel = uaChannelCtx.channel();

        // connect remote
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(uaChannelCtx.channel().eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .option(ChannelOption.AUTO_READ, false)
                .handler(new ApnProxyTunnelChannelInitializer(uaChannelCtx.channel()));

        final ApnProxyRemote apnProxyRemote = uaChannelCtx.channel()
                .attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY).get().getRemote();

        // set local address
        if (StringUtils.isNotBlank(ApnProxyLocalAddressChooser.choose(apnProxyRemote.getRemoteHost()))) {
            bootstrap.localAddress(new InetSocketAddress(
                    (ApnProxyLocalAddressChooser.choose(apnProxyRemote.getRemoteHost())), 0));
        }/*  w ww. j a va  2 s.co  m*/

        bootstrap.connect(apnProxyRemote.getRemoteHost(), apnProxyRemote.getRemotePort())
                .addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(final ChannelFuture future1) throws Exception {
                        if (future1.isSuccess()) {
                            if (apnProxyRemote.isAppleyRemoteRule()) {
                                uaChannelCtx.pipeline().remove("codec");
                                uaChannelCtx.pipeline().remove(ApnProxyPreHandler.HANDLER_NAME);
                                uaChannelCtx.pipeline().remove(ApnProxyUserAgentTunnelHandler.HANDLER_NAME);

                                // add relay handler
                                uaChannelCtx.pipeline()
                                        .addLast(new ApnProxyRelayHandler("UA --> Remote", future1.channel()));

                                future1.channel()
                                        .writeAndFlush(Unpooled.copiedBuffer(
                                                constructConnectRequestForProxy(httpRequest, apnProxyRemote),
                                                CharsetUtil.UTF_8))
                                        .addListener(new ChannelFutureListener() {
                                            @Override
                                            public void operationComplete(ChannelFuture future2)
                                                    throws Exception {
                                                if (!future2.channel().config()
                                                        .getOption(ChannelOption.AUTO_READ)) {
                                                    future2.channel().read();
                                                }
                                            }
                                        });

                            } else {
                                HttpResponse proxyConnectSuccessResponse = new DefaultFullHttpResponse(
                                        HttpVersion.HTTP_1_1,
                                        new HttpResponseStatus(200, "Connection established"));
                                uaChannelCtx.writeAndFlush(proxyConnectSuccessResponse)
                                        .addListener(new ChannelFutureListener() {
                                            @Override
                                            public void operationComplete(ChannelFuture future2)
                                                    throws Exception {
                                                // remove handlers
                                                uaChannelCtx.pipeline().remove("codec");
                                                uaChannelCtx.pipeline().remove(ApnProxyPreHandler.HANDLER_NAME);
                                                uaChannelCtx.pipeline()
                                                        .remove(ApnProxyUserAgentTunnelHandler.HANDLER_NAME);

                                                // add relay handler
                                                uaChannelCtx.pipeline()
                                                        .addLast(new ApnProxyRelayHandler(
                                                                "UA --> " + apnProxyRemote.getRemoteAddr(),
                                                                future1.channel()));
                                            }

                                        });
                            }

                        } else {
                            if (uaChannelCtx.channel().isActive()) {
                                uaChannelCtx.channel().writeAndFlush(Unpooled.EMPTY_BUFFER)
                                        .addListener(ChannelFutureListener.CLOSE);
                            }
                        }
                    }
                });

    }
    ReferenceCountUtil.release(msg);
}

From source file:com.xx_dev.apn.socks.local.PortForwardProxyFrontendHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) {
    final Channel inboundChannel = ctx.channel();

    // Start the connection attempt.
    Bootstrap b = new Bootstrap();
    b.group(inboundChannel.eventLoop()).channel(ctx.channel().getClass())
            .handler(new PortForwardProxyBackendInitializer(inboundChannel))
            .option(ChannelOption.AUTO_READ, false);
    ChannelFuture f = b.connect(remoteHost, remotePort);
    outboundChannel = f.channel();//w w  w  .  j  a  va2s  . c o m
    f.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                // connection complete start to read first data
                logger.info("C: " + remoteHost + ":" + remotePort + ", T");
                inboundChannel.read();
            } else {
                logger.info("C: " + remoteHost + ":" + remotePort + ", F");
                inboundChannel.close();
            }
        }
    });
}

From source file:com.xx_dev.port_forwared.HexDumpProxyFrontendHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) {
    final Channel inboundChannel = ctx.channel();

    // Start the connection attempt.
    Bootstrap b = new Bootstrap();
    b.group(inboundChannel.eventLoop()).channel(ctx.channel().getClass())
            .handler(new HexDumpProxyBackendInitializer(inboundChannel, remoteSsl))
            .option(ChannelOption.AUTO_READ, false);
    ChannelFuture f = b.connect(remoteHost, remotePort);
    outboundChannel = f.channel();//  ww  w .j av a 2 s .c  om
    f.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                // connection complete start to read first data
                inboundChannel.read();
            } else {
                // Close the connection if the connection attempt has failed.
                inboundChannel.close();
            }
        }
    });
}

From source file:com.xyz.rpc.netty4.server.Netty4ServerHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, RequestWrapper request) throws Exception {
    long beginTime = System.currentTimeMillis();
    ResponseWrapper responseWrapper = ProtocolFactory.getServerHandler(request.getProtocolType())
            .handleRequest(request);/*from w  w w .  j av a2  s.  c om*/
    final int id = request.getId();
    // already timeout,so not return
    if ((System.currentTimeMillis() - beginTime) >= request.getTimeout()) {
        LOGGER.warn("timeout,so give up send response to client,requestId is:" + id + ",client is:"
                + ctx.channel().remoteAddress() + ",consumetime is:" + (System.currentTimeMillis() - beginTime)
                + ",timeout is:" + request.getTimeout());
        return;
    }
    ChannelFuture wf = ctx.channel().writeAndFlush(responseWrapper);
    wf.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                LOGGER.error("server write response error,request id is: " + id);
            }
        }
    });
}

From source file:com.yahoo.pulsar.client.impl.ConnectionPool.java

License:Apache License

private CompletableFuture<ClientCnx> createConnection(InetSocketAddress address, int connectionKey) {
    if (log.isDebugEnabled()) {
        log.debug("Connection for {} not found in cache", address);
    }//from  w  ww.ja  v a2  s. com

    final CompletableFuture<ClientCnx> cnxFuture = new CompletableFuture<ClientCnx>();

    // Trigger async connect to broker
    bootstrap.connect(address).addListener((ChannelFuture future) -> {
        if (!future.isSuccess()) {
            cnxFuture.completeExceptionally(new PulsarClientException(future.cause()));
            cleanupConnection(address, connectionKey, cnxFuture);
            return;
        }

        log.info("[{}] Connected to server", future.channel());

        future.channel().closeFuture().addListener(v -> {
            // Remove connection from pool when it gets closed
            cleanupConnection(address, connectionKey, cnxFuture);
        });

        // We are connected to broker, but need to wait until the connect/connected handshake is
        // complete
        final ClientCnx cnx = (ClientCnx) future.channel().pipeline().get("handler");
        cnx.connectionFuture().thenRun(() -> {
            if (log.isDebugEnabled()) {
                log.debug("[{}] Connection handshake completed", cnx.channel());
            }
            cnxFuture.complete(cnx);
        }).exceptionally(exception -> {
            log.warn("[{}] Connection handshake failed: {}", cnx.channel(), exception.getMessage());
            cnxFuture.completeExceptionally(exception);
            cleanupConnection(address, connectionKey, cnxFuture);
            cnx.ctx().close();
            return null;
        });

    });

    return cnxFuture;
}

From source file:com.yahoo.pulsar.discovery.service.DiscoveryServiceTest.java

License:Apache License

/**
 * creates ClientHandler channel to connect and communicate with server
 * /*from  w  w w .  j a v a 2 s .  c  om*/
 * @param serviceUrl
 * @param latch
 * @return
 * @throws URISyntaxException
 */
public static NioEventLoopGroup connectToService(String serviceUrl, CountDownLatch latch, boolean tls)
        throws URISyntaxException {
    NioEventLoopGroup workerGroup = new NioEventLoopGroup();
    Bootstrap b = new Bootstrap();
    b.group(workerGroup);
    b.channel(NioSocketChannel.class);

    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            if (tls) {
                SslContextBuilder builder = SslContextBuilder.forClient();
                builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
                X509Certificate[] certificates = SecurityUtility
                        .loadCertificatesFromPemFile(TLS_CLIENT_CERT_FILE_PATH);
                PrivateKey privateKey = SecurityUtility.loadPrivateKeyFromPemFile(TLS_CLIENT_KEY_FILE_PATH);
                builder.keyManager(privateKey, (X509Certificate[]) certificates);
                SslContext sslCtx = builder.build();
                ch.pipeline().addLast("tls", sslCtx.newHandler(ch.alloc()));
            }
            ch.pipeline().addLast(new ClientHandler(latch));
        }
    });
    URI uri = new URI(serviceUrl);
    InetSocketAddress serviceAddress = new InetSocketAddress(uri.getHost(), uri.getPort());
    b.connect(serviceAddress).addListener((ChannelFuture future) -> {
        if (!future.isSuccess()) {
            throw new IllegalStateException(future.cause());
        }
    });
    return workerGroup;
}

From source file:com.zaradai.distributor.messaging.netty.ChannelConnection.java

License:Apache License

@Override
protected void doSend(final Message message) throws MessagingException {
    channel.writeAndFlush(message).addListener(new ChannelFutureListener() {
        @Override//from w  w w.j  ava  2s. com
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                onSuccess(message);
            } else {
                onFailure(message, future.cause());
            }
        }
    });
}