Example usage for io.netty.util.concurrent Future isSuccess

List of usage examples for io.netty.util.concurrent Future isSuccess

Introduction

In this page you can find the example usage for io.netty.util.concurrent Future isSuccess.

Prototype

boolean isSuccess();

Source Link

Document

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

Usage

From source file:de.unipassau.isl.evs.ssh.slave.handler.SlaveLightHandler.java

License:Open Source License

private void handleSet(LightPayload payload, final Message.AddressedMessage original) {
    final Key<EdimaxPlugSwitch> key = new Key<>(EdimaxPlugSwitch.class, payload.getModule().getName());
    final EdimaxPlugSwitch plugSwitch = requireComponent(key);
    final boolean setOn = payload.getOn();

    plugSwitch.setOnAsync(setOn).addListener(new FutureListener<Boolean>() {
        @Override/*from w  w w .  ja  v  a 2  s.  c  o m*/
        public void operationComplete(Future<Boolean> future) throws Exception {
            if (future.isSuccess()) {
                if (future.get() == Boolean.TRUE) {
                    replyStatus(original, setOn);
                } else {
                    sendReply(original, new Message(new ErrorPayload("Cannot switch light")));
                }
            } else {
                sendReply(original, new Message(new ErrorPayload(future.cause())));
            }
        }
    });
}

From source file:de.unipassau.isl.evs.ssh.slave.handler.SlaveLightHandler.java

License:Open Source License

private void handleGet(LightPayload payload, final Message.AddressedMessage original) {
    final Key<EdimaxPlugSwitch> key = new Key<>(EdimaxPlugSwitch.class, payload.getModule().getName());
    requireComponent(key).isOnAsync().addListener(new FutureListener<Boolean>() {
        @Override//from   w w w.  ja va  2s . c o  m
        public void operationComplete(Future<Boolean> future) throws Exception {
            if (future.isSuccess()) {
                replyStatus(original, future.get());
            } else {
                sendReply(original, new Message(new ErrorPayload(future.cause())));
            }
        }
    });
}

From source file:divconq.api.HyperSession.java

License:Open Source License

public Channel allocateHttpChannel(final ChannelHandler handler, OperationResult or) {
    final AtomicReference<Future<Channel>> sslready = new AtomicReference<>();

    Bootstrap b = new Bootstrap();

    b.group(Hub.instance.getEventLoopGroup()).channel(NioSocketChannel.class)
            .option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator())
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override/* w  ww . ja  v  a 2s.co m*/
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();

                    if (HyperSession.this.info.isSecurel()) {
                        SslHandler sh = new SslHandler(HyperSession.this.sslfac.getClientEngine());
                        sslready.set(sh.handshakeFuture());
                        pipeline.addLast("ssl", sh);
                    }

                    pipeline.addLast("decoder", new HttpResponseDecoder());
                    pipeline.addLast("encoder", new HttpRequestEncoder());

                    // TODO maybe
                    //pipeline.addLast("deflater", new HttpContentCompressor());

                    pipeline.addLast("handler", handler);
                }
            });

    or.info("Web Client connecting");

    try {
        // must wait here to make sure we don't release connectLock too soon
        // we want channel init (above) to complete before we try connect again
        ChannelFuture f = b.connect(this.info.getAddress()).sync();

        if (!f.isSuccess()) {
            or.error(1, "Web Client unable to successfully connect: " + f.cause());
        }

        // it has appeared that sometimes we "overshoot" the ssl handshake in code - to prevent
        // that lets wait for the handshake to be done for sure
        if (sslready.get() != null) {
            Future<Channel> sf = sslready.get().sync();

            if (!sf.isSuccess()) {
                or.error(1, "Web Client unable to securely connect: " + sf.cause());
            }
        }

        if (handler instanceof ClientHandler)
            ((ClientHandler) handler).waitConnect();

        return f.channel();
    } catch (InterruptedException x) {
        or.error(1, "Web Client interrupted while connecting: " + x);
    } catch (Exception x) {
        or.error(1, "Web Client unable to connect: " + x);
    }

    return null;
}

From source file:divconq.api.HyperSession.java

License:Open Source License

public Channel allocateWsChannel(final ChannelHandler handler, OperationResult or) {
    final AtomicReference<Future<Channel>> sslready = new AtomicReference<>();

    Bootstrap b = new Bootstrap();

    b.group(Hub.instance.getEventLoopGroup()).option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator())
            .channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
                @Override/* ww  w . j  a va2  s . co  m*/
                public void initChannel(SocketChannel ch) throws Exception {
                    HttpHeaders customHeaders = new DefaultHttpHeaders();
                    customHeaders.add("x-DivConq-Mode", Hub.instance.getResources().getMode());

                    WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(
                            HyperSession.this.info.getUri(), WebSocketVersion.V13, null, false, customHeaders);

                    ChannelPipeline pipeline = ch.pipeline();

                    if (HyperSession.this.info.isSecurel()) {
                        SslHandler sh = new SslHandler(HyperSession.this.sslfac.getClientEngine());
                        sslready.set(sh.handshakeFuture());
                        pipeline.addLast("ssl", sh);
                    }

                    pipeline.addLast("http-codec", new HttpClientCodec());
                    pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
                    pipeline.addLast("ws-handler", new WebSocketClientProtocolHandler(handshaker));

                    pipeline.addLast("handler", handler);

                    /*
                    pipeline.addLast("handler", new SimpleChannelInboundHandler<Object>() {
                            
                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
                     System.out.println("read: " + msg);
                    }
                            
                            
                    @Override
                    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                      super.userEventTriggered(ctx, evt);
                              
                      Logger.debug("ue: " + evt);
                    }
                    });
                    */
                }
            });

    or.info("Web Client connecting");

    try {
        // must wait here to make sure we don't release connectLock too soon
        // we want channel init (above) to complete before we try connect again
        ChannelFuture f = b.connect(this.info.getAddress()).sync();

        if (!f.isSuccess()) {
            or.error(1, "Web Client unable to successfully connect: " + f.cause());
        }

        // it has appeared that sometimes we "overshoot" the ssl handshake in code - to prevent
        // that lets wait for the handshake to be done for sure
        if (sslready.get() != null) {
            Future<Channel> sf = sslready.get().sync();

            if (!sf.isSuccess()) {
                or.error(1, "Web Client unable to securely connect: " + sf.cause());
            }
        }

        if (handler instanceof ClientHandler)
            ((ClientHandler) handler).waitConnect();

        return f.channel();
    } catch (InterruptedException x) {
        or.error(1, "Web Client interrupted while connecting: " + x);
    } catch (Exception x) {
        or.error(1, "Web Client unable to connect: " + x);
    }

    return null;
}

From source file:divconq.api.internal.DownloadHandler.java

License:Open Source License

public Channel allocateChannel(final HyperSession parent, OperationResult or) {
    final AtomicReference<Future<Channel>> sslready = new AtomicReference<>();

    Bootstrap b = new Bootstrap();

    b.group(Hub.instance.getEventLoopGroup()).channel(NioSocketChannel.class)
            .option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator())
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override/*from   w w  w  . jav a 2s .  co m*/
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();

                    if (parent.getInfo().isSecurel()) {
                        SslHandler sh = new SslHandler(parent.getSsl().getClientEngine());
                        sslready.set(sh.handshakeFuture());
                        pipeline.addLast("ssl", sh);
                    }

                    pipeline.addLast("codec", new HttpClientCodec());
                    //pipeline.addLast("decoder", new HttpResponseDecoder());
                    //pipeline.addLast("encoder", new HttpRequestEncoder());

                    pipeline.addLast("handler", DownloadHandler.this);
                }
            });

    or.info("Web Data Client connecting");

    try {
        // must wait here to make sure we don't release connectLock too soon
        // we want chanel init (above) to complete before we try connect again
        ChannelFuture f = b.connect(parent.getInfo().getAddress()).sync();

        if (!f.isSuccess()) {
            or.error(1, "Web Data Client unable to successfully connect: " + f.cause());
        }

        // it has appeared that sometimes we "overshoot" the ssl handshake in code - to prevent
        // that lets wait for the handshake to be done for sure
        if (sslready.get() != null) {
            Future<Channel> sf = sslready.get().sync();

            if (!sf.isSuccess()) {
                or.error(1, "Web Data Client unable to securely connect: " + sf.cause());
            }
        }

        return f.channel();
    } catch (InterruptedException x) {
        or.error(1, "Web Data Client interrupted while connecting: " + x);
    } catch (Exception x) {
        or.error(1, "Web Data Client unable to connect: " + x);
    }

    return null;
}

From source file:divconq.api.internal.UploadPostHandler.java

License:Open Source License

public Channel allocateChannel(final HyperSession parent, OperationResult or) {
    final AtomicReference<Future<Channel>> sslready = new AtomicReference<>();

    Bootstrap b = new Bootstrap();

    b.group(Hub.instance.getEventLoopGroup()).channel(NioSocketChannel.class)
            .option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator())
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override//from   www. j  a v a  2s. c o  m
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();

                    if (parent.getInfo().isSecurel()) {
                        SslHandler sh = new SslHandler(parent.getSsl().getClientEngine());
                        sslready.set(sh.handshakeFuture());
                        pipeline.addLast("ssl", sh);
                    }

                    pipeline.addLast("codec", new HttpClientCodec());

                    // Remove the following line if you don't want automatic content decompression.
                    //pipeline.addLast("inflater", new HttpContentDecompressor());

                    // to be used since huge file transfer
                    pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());

                    // so we can get the upload response (200 or not)
                    pipeline.addLast("handler", UploadPostHandler.this);
                }
            });

    System.out.println("Web Data Client connecting");

    try {
        // must wait here to make sure we don't release connectLock too soon
        // we want chanel init (above) to complete before we try connect again
        ChannelFuture f = b.connect(parent.getInfo().getAddress()).sync();

        if (!f.isSuccess()) {
            or.error(1, "Web Client unable to successfully connect: " + f.cause());
            System.out.println("Web Client unable to successfully connect: " + f.cause());
        }

        // it has appeared that sometimes we "overshoot" the ssl handshake in code - to prevent
        // that lets wait for the handshake to be done for sure
        if (sslready.get() != null) {
            Future<Channel> sf = sslready.get().sync();

            if (!sf.isSuccess()) {
                or.error(1, "Web Client unable to securely connect: " + sf.cause());
                System.out.println("Web Client unable to securely connect: " + sf.cause());
            }
        }

        return f.channel();
    } catch (InterruptedException x) {
        or.error(1, "Web Client interrupted while connecting: " + x);
        System.out.println("Web Client interrupted while connecting: " + x);
    } catch (Exception x) {
        or.error(1, "Web Client unable to connect: " + x);
        System.out.println("Web Client unable to connect: " + x);
    }

    return null;
}

From source file:divconq.api.internal.UploadPutHandler.java

License:Open Source License

public Channel allocateChannel(final HyperSession parent, OperationResult or) {
    final AtomicReference<Future<Channel>> sslready = new AtomicReference<>();

    Bootstrap b = new Bootstrap();

    b.group(Hub.instance.getEventLoopGroup()).channel(NioSocketChannel.class)
            .option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator())
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override/*from   w  w w  .  ja v  a  2 s.c om*/
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();

                    if (parent.getInfo().isSecurel()) {
                        SslHandler sh = new SslHandler(parent.getSsl().getClientEngine());
                        sslready.set(sh.handshakeFuture());
                        pipeline.addLast("ssl", sh);
                    }

                    pipeline.addLast("codec", new HttpClientCodec());

                    // so we can get the upload response (200 or not)
                    pipeline.addLast("handler", UploadPutHandler.this);
                }
            });

    or.info("Web Data Client connecting");

    try {
        // must wait here to make sure we don't release connectLock too soon
        // we want chanel init (above) to complete before we try connect again
        ChannelFuture f = b.connect(parent.getInfo().getAddress()).sync();

        if (!f.isSuccess()) {
            or.error(1, "Web Client unable to successfully connect: " + f.cause());
        }

        // it has appeared that sometimes we "overshoot" the ssl handshake in code - to prevent
        // that lets wait for the handshake to be done for sure
        if (sslready.get() != null) {
            Future<Channel> sf = sslready.get().sync();

            if (!sf.isSuccess()) {
                or.error(1, "Web Client unable to securely connect: " + sf.cause());
            }
        }

        return f.channel();
    } catch (InterruptedException x) {
        or.error(1, "Web Client interrupted while connecting: " + x);
    } catch (Exception x) {
        or.error(1, "Web Client unable to connect: " + x);
    }

    return null;
}

From source file:divconq.net.ssl.SslHandler.java

License:Apache License

@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
    if (!startTls && engine.getUseClientMode()) {
        // issue and handshake and add a listener to it which will fire an exception event if
        // an exception was thrown while doing the handshake
        handshake().addListener(new GenericFutureListener<Future<Channel>>() {
            @Override//  ww w  . ja  v  a2  s . c o  m
            public void operationComplete(Future<Channel> future) throws Exception {
                if (!future.isSuccess()) {
                    logger.debug("Failed to complete handshake", future.cause());
                    ctx.close();
                }
            }
        });
    }
    ctx.fireChannelActive();
}

From source file:dorkbox.network.connection.registration.remote.RegistrationRemoteHandler.java

License:Apache License

private void cleanupPipeline0(final int idleTimeout, final ChannelHandler connection, final Channel channel,
        final ChannelPromise channelPromise, final boolean isTcp) {
    final ChannelPipeline pipeline = channel.pipeline();

    // have to explicitly remove handlers based on the input type. Cannot use this.getClass()....
    boolean isClient = registrationWrapper.isClient();
    if (isClient) {
        if (isTcp) {
            pipeline.remove(RegistrationRemoteHandlerClientTCP.class);
        } else {//from  w ww .j  a v a  2s.  c  om
            pipeline.remove(RegistrationRemoteHandlerClientUDP.class);
        }
    } else {
        if (isTcp) {
            pipeline.remove(RegistrationRemoteHandlerServerTCP.class);
        } else {
            pipeline.remove(RegistrationRemoteHandlerServerUDP.class);
        }
    }

    pipeline.remove(ConnectionRegistrationImpl.class);

    if (idleTimeout > 0) {
        pipeline.replace(IDLE_HANDLER, IDLE_HANDLER_FULL,
                new IdleStateHandler(0, 0, idleTimeout, TimeUnit.MILLISECONDS));
    } else {
        pipeline.remove(IDLE_HANDLER);
    }

    pipeline.addLast(CONNECTION_HANDLER, connection);

    // we also DEREGISTER from the HANDSHAKE event-loop and run on the worker event-loop!
    ChannelFuture future = channel.deregister();
    future.addListener(new GenericFutureListener<Future<? super Void>>() {
        @Override
        public void operationComplete(final Future<? super Void> f) throws Exception {
            if (f.isSuccess()) {
                // TCP and UDP register on DIFFERENT event loops. The channel promise ONLY runs on 1 of them...
                if (channelPromise.channel() == channel) {
                    workerEventLoop.register(channelPromise);
                } else {
                    workerEventLoop.register(channel);
                }
            }
        }
    });
}

From source file:herddb.network.netty.NettyChannel.java

License:Apache License

@Override
public void sendOneWayMessage(ByteBuf message, SendResultCallback callback) {

    io.netty.channel.Channel _socket = this.socket;
    if (_socket == null || !_socket.isOpen()) {
        callback.messageSent(new Exception(this + " connection is closed"));
        return;//from   w w  w  .j a  va 2 s  .c  om
    }
    if (LOGGER.isLoggable(Level.FINEST)) {
        StringBuilder dumper = new StringBuilder();
        ByteBufUtil.appendPrettyHexDump(dumper, message);
        LOGGER.log(Level.FINEST, "Sending to {}: {}", new Object[] { _socket, dumper });
    }
    _socket.writeAndFlush(message).addListener(new GenericFutureListener() {

        @Override
        public void operationComplete(Future future) throws Exception {
            if (future.isSuccess()) {
                callback.messageSent(null);
            } else {
                LOGGER.log(Level.SEVERE, this + ": error " + future.cause(), future.cause());
                callback.messageSent(future.cause());
                close();
            }
        }
    });
    unflushedWrites.incrementAndGet();
}