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.urmia.proxy.HttpProxyFrontendHandler.java

License:Open Source License

private void writeToAllOutbounds(final ChannelHandlerContext ctx, final HttpContent msg) {

    writeSet.clear();/* w ww  . ja  v a2 s .c o m*/

    final int contentSize = msg.content().writableBytes();

    int i = 0;

    for (final Channel outboundChannel : outboundChannels) {

        final int chIdx = i++;

        outboundChannel.writeAndFlush(msg.duplicate()) // duplicate because different widx
                .addListener(new GenericFutureListener<ChannelFuture>() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (future.isSuccess()) {
                            writtenSizes[chIdx].addAndGet(contentSize);
                            onSuccessfulWrite(ctx, chIdx);
                        } else {
                            log.error("error to write to outbound", future.cause());
                            future.channel().close();
                        }

                    }
                });
    }
}

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

License:Apache License

private void onQueryWriteCompletion(ChannelFuture writeFuture) {
    if (!writeFuture.isSuccess()) {
        setFailure("failed to send a query", writeFuture.cause());
        return;/*w  ww.  ja va  2 s  . c  o  m*/
    }

    // Schedule a query timeout task if necessary.
    final long queryTimeoutMillis = parent.queryTimeoutMillis();
    if (queryTimeoutMillis > 0) {
        timeoutFuture = parent.ch.eventLoop().schedule(new OneTimeTask() {
            @Override
            public void run() {
                if (promise.isDone()) {
                    // Received a response before the query times out.
                    return;
                }

                setFailure("query timed out after " + queryTimeoutMillis + " milliseconds", null);
            }
        }, queryTimeoutMillis, TimeUnit.MILLISECONDS);
    }
}

From source file:io.vertx.core.http.impl.HttpClientImpl.java

License:Open Source License

private void internalConnect(ContextImpl context, int port, String host,
        Handler<ClientConnection> connectHandler, Handler<Throwable> connectErrorHandler,
        ConnectionLifeCycleListener listener) {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(context.eventLoop());
    bootstrap.channelFactory(new VertxNioSocketChannelFactory());
    sslHelper.validate(vertx);//w  w  w .  ja v  a  2 s .c o  m
    bootstrap.handler(new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            if (options.isSsl()) {
                pipeline.addLast("ssl", sslHelper.createSslHandler(vertx, true, host, port));
            }

            pipeline.addLast("codec", new HttpClientCodec(4096, 8192, 8192, false, false));
            if (options.isTryUseCompression()) {
                pipeline.addLast("inflater", new HttpContentDecompressor(true));
            }
            if (options.getIdleTimeout() > 0) {
                pipeline.addLast("idle", new IdleStateHandler(0, 0, options.getIdleTimeout()));
            }
            pipeline.addLast("handler", new ClientHandler(vertx, context));
        }
    });
    applyConnectionOptions(bootstrap);
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
    future.addListener((ChannelFuture channelFuture) -> {
        Channel ch = channelFuture.channel();
        if (channelFuture.isSuccess()) {
            if (options.isSsl()) {
                // TCP connected, so now we must do the SSL handshake

                SslHandler sslHandler = ch.pipeline().get(SslHandler.class);

                io.netty.util.concurrent.Future<Channel> fut = sslHandler.handshakeFuture();
                fut.addListener(fut2 -> {
                    if (fut2.isSuccess()) {
                        connected(context, port, host, ch, connectHandler, connectErrorHandler, listener);
                    } else {
                        connectionFailed(context, ch, connectErrorHandler,
                                new SSLHandshakeException("Failed to create SSL connection"), listener);
                    }
                });
            } else {
                connected(context, port, host, ch, connectHandler, connectErrorHandler, listener);
            }
        } else {
            connectionFailed(context, ch, connectErrorHandler, channelFuture.cause(), listener);
        }
    });
}

From source file:io.vertx.core.net.impl.ChannelFutureListenerAdapter.java

License:Open Source License

@Override
public void operationComplete(ChannelFuture future) {
    Future<T> res = future.isSuccess() ? Future.succeededFuture(result) : Future.failedFuture(future.cause());
    context.executeFromIO(res, handler);
}

From source file:io.viewserver.network.netty.NettyNetworkAdapter.java

License:Apache License

@Override
public ListenableFuture<IChannel> connect(IEndpoint endpoint) {
    SettableFuture<IChannel> promise = SettableFuture.create();
    final INettyEndpoint.IClient client = ((INettyEndpoint) endpoint).getClient(getClientWorkerGroup(),
            new NettyPipelineInitialiser(networkMessageWheel));
    ChannelFuture channelFuture = client.connect();
    channelFuture.addListener(new ChannelFutureListener() {
        @Override//from   w ww  .j  a v  a2s .  c om
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                NettyChannel channel = new NettyChannel(future.channel());
                promise.set(channel);
            } else {
                promise.setException(future.cause());
            }
        }
    });
    return promise;
}

From source file:it.jnrpe.JNRPE.java

License:Apache License

/**
 * Starts a new thread that listen for requests. The method is <b>not
 * blocking</b>/*ww w.j ava  2 s .com*/
 * 
 * @param address
 *            The address to bind to
 * @param port
 *            The listening port
 * @param useSSL
 *            <code>true</code> if an SSL socket must be created.
        
 * @throws UnknownHostException
 *             - */
public void listen(final String address, final int port, final boolean useSSL) throws UnknownHostException {

    // Bind and start to accept incoming connections.
    ChannelFuture cf = getServerBootstrap(useSSL).bind(address, port);
    cf.addListener(new ChannelFutureListener() {

        public void operationComplete(final ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                context.getEventBus().post(new JNRPEStatusEvent(STATUS.STARTED, this, "JNRPE Server started"));
                LOG.info(context, "Listening on " + (useSSL ? "SSL/" : "") + address + ":" + port);
            } else {
                getExecutionContext().getEventBus()
                        .post(new JNRPEStatusEvent(STATUS.FAILED, this, "JNRPE Server start failed"));
                LOG.error(context, "Unable to listen on " + (useSSL ? "SSL/" : "") + address + ":" + port,
                        future.cause());
            }
        }
    });

}

From source file:jgnash.engine.attachment.AttachmentTransferServer.java

License:Open Source License

public boolean startServer(final char[] password) {
    boolean result = false;

    // If a password has been specified, create an EncryptionManager
    if (password != null && password.length > 0) {
        encryptionManager = new EncryptionManager(password);
    }//w ww .j  a  va2s . c  o  m

    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(eventLoopGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    public void initChannel(final SocketChannel ch) throws Exception {

                        ch.pipeline().addLast(
                                new DelimiterBasedFrameDecoder(((TRANSFER_BUFFER_SIZE + 2) / 3) * 4 + PATH_MAX,
                                        true, Delimiters.lineDelimiter()),

                                new StringEncoder(CharsetUtil.UTF_8), new StringDecoder(CharsetUtil.UTF_8),

                                new Base64Encoder(), new Base64Decoder(),

                                new ServerTransferHandler());
                    }
                });

        // Start the server.
        final ChannelFuture future = b.bind(port).sync();

        if (future.isDone() && future.isSuccess()) {
            result = true;
            logger.info("File Transfer Server started successfully");
        } else {
            logger.info("Failed to start the File Transfer Server");
        }
    } catch (final InterruptedException e) {
        logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
        stopServer();
    }

    return result;
}

From source file:jgnash.engine.concurrent.DistributedLockServer.java

License:Open Source License

public boolean startServer(final char[] password) {
    boolean result = false;

    // If a password has been specified, create an EncryptionManager
    if (password != null && password.length > 0) {
        encryptionManager = new EncryptionManager(password);
    }/*  w  w w .j a  v a 2  s .  co  m*/

    eventLoopGroup = new NioEventLoopGroup();

    final ServerBootstrap bootstrap = new ServerBootstrap();

    try {
        bootstrap.group(eventLoopGroup).channel(NioServerSocketChannel.class).childHandler(new Initializer())
                .childOption(ChannelOption.SO_KEEPALIVE, true);

        final ChannelFuture future = bootstrap.bind(port);
        future.sync();

        if (future.isDone() && future.isSuccess()) {
            logger.info("Distributed Lock Server started successfully");
            result = true;
        } else {
            logger.info("Failed to start the Distributed Lock Server");
        }
    } catch (final InterruptedException e) {
        logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
        stopServer();
    }

    return result;
}

From source file:jgnash.engine.message.MessageBusServer.java

License:Open Source License

public boolean startServer(final DataStoreType dataStoreType, final String dataBasePath,
        final char[] password) {
    boolean result = false;

    logger.info("Starting message bus server");

    this.dataBasePath = dataBasePath;
    this.dataStoreType = dataStoreType.name();

    // If a password has been specified, create an EncryptionManager
    if (password != null && password.length > 0) {
        encryptionManager = new EncryptionManager(password);
    }/*from   ww  w.j  a v  a2s  .  co  m*/

    eventLoopGroup = new NioEventLoopGroup();

    final ServerBootstrap bootstrap = new ServerBootstrap();

    try {
        bootstrap.group(eventLoopGroup).channel(NioServerSocketChannel.class)
                .childHandler(new MessageBusRemoteInitializer()).childOption(ChannelOption.SO_KEEPALIVE, true);

        final ChannelFuture future = bootstrap.bind(port);
        future.sync();

        if (future.isDone() && future.isSuccess()) {
            logger.info("Message Bus Server started successfully");
            result = true;
        } else {
            logger.info("Failed to start the Message Bus Server");
        }
    } catch (final InterruptedException e) {
        logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
        stopServer();
    }

    return result;
}

From source file:jj.http.server.websocket.WebSocketConnectionMaker.java

License:Apache License

private void doHandshake(final ChannelHandlerContext ctx, final FullHttpRequest request,
        final WebSocketServerHandshaker handshaker) {
    handshaker.handshake(ctx.channel(), request).addListener(new ChannelFutureListener() {

        private boolean isHandshakeFailure(ChannelFuture future) {
            return future.cause() != null && future.cause() instanceof WebSocketHandshakeException;
        }//from   w w w .  ja v  a 2  s .c  om

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {

                URIMatch uriMatch = new URIMatch(request.getUri());

                WebSocketConnectionHost host = null;

                for (Class<? extends WebSocketConnectionHost> hostClass : webSocketConnectionHostClasses) {
                    host = resourceFinder.findResource(hostClass, AppLocation.Virtual, uriMatch.name);
                    if (host != null)
                        break;
                }

                if (host == null) {

                    // 1011 indicates that a server is terminating the connection because
                    // it encountered an unexpected condition that prevented it from
                    // fulfilling the request.
                    ctx.writeAndFlush(new CloseWebSocketFrame(1011, null)).addListener(CLOSE);
                    // TODO: is closing here the right thing? or do we count on the client closing the connection
                    // to avoid the time_wait state? 

                } else if (!uriMatch.sha1.equals(host.sha1())) {

                    ctx.writeAndFlush(new TextWebSocketFrame("jj-reload"))
                            .addListener(new ChannelFutureListener() {

                                @Override
                                public void operationComplete(ChannelFuture future) throws Exception {
                                    // 1001 indicates that an endpoint is "going away", such as a server
                                    // going down or a browser having navigated away from a page.
                                    ctx.writeAndFlush(new CloseWebSocketFrame(1001, null)).addListener(CLOSE);
                                    // TODO: is closing here the right thing? or do we count on the client closing the connection
                                    // to avoid the time_wait state? 
                                }
                            });

                } else {

                    ctx.pipeline().replace(JJEngine.toString(), JJWebsocketHandler.toString(),
                            handlerCreator.createHandler(handshaker, host));
                }

            } else if (isHandshakeFailure(future)) {
                response.sendError(HttpResponseStatus.BAD_REQUEST);
            } else {
                ctx.close();
            }
        }
    });
}