Example usage for io.netty.channel ChannelFuture addListener

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

Introduction

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

Prototype

@Override
    ChannelFuture addListener(GenericFutureListener<? extends Future<? super Void>> listener);

Source Link

Usage

From source file:bftsmart.communication.client.netty.NettyClientServerCommunicationSystemClientSide.java

License:Apache License

@Override
public void send(boolean sign, int[] targets, TOMMessage sm) {

    int quorum;//from w  w w.  j  a  va 2s.c o  m

    Integer[] targetArray = Arrays.stream(targets).boxed().toArray(Integer[]::new);
    Collections.shuffle(Arrays.asList(targetArray), new Random());

    if (controller.getStaticConf().isBFT()) {
        quorum = (int) Math.ceil((controller.getCurrentViewN() + controller.getCurrentViewF()) / 2) + 1;
    } else {
        quorum = (int) Math.ceil((controller.getCurrentViewN()) / 2) + 1;
    }

    listener.waitForChannels(quorum); // wait for the previous transmission to complete

    logger.debug("Sending request from " + sm.getSender() + " with sequence number " + sm.getSequence() + " to "
            + Arrays.toString(targetArray));

    if (sm.serializedMessage == null) {

        // serialize message
        DataOutputStream dos = null;
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            dos = new DataOutputStream(baos);
            sm.wExternal(dos);
            dos.flush();
            sm.serializedMessage = baos.toByteArray();
        } catch (IOException ex) {
            logger.debug("Impossible to serialize message: " + sm);
        }
    }

    // Logger.println("Sending message with "+sm.serializedMessage.length+" bytes of
    // content.");

    // produce signature
    if (sign && sm.serializedMessageSignature == null) {
        sm.serializedMessageSignature = signMessage(privKey, sm.serializedMessage);
    }

    int sent = 0;

    for (int target : targetArray) {
        // This is done to avoid a race condition with the writeAndFush method. Since
        // the method is asynchronous,
        // each iteration of this loop could overwrite the destination of the previous
        // one
        try {
            sm = (TOMMessage) sm.clone();
        } catch (CloneNotSupportedException e) {
            logger.error("Failed to clone TOMMessage", e);
            continue;
        }

        sm.destination = targets[target];

        rl.readLock().lock();
        Channel channel = ((NettyClientServerSession) sessionClientToReplica.get(targets[target])).getChannel();
        rl.readLock().unlock();
        if (channel.isActive()) {
            sm.signed = sign;
            ChannelFuture f = channel.writeAndFlush(sm);

            f.addListener(listener);

            sent++;
        } else {
            logger.debug("Channel to " + targets[target] + " is not connected");
        }
    }

    if (targets.length > controller.getCurrentViewF() && sent < controller.getCurrentViewF() + 1) {
        // if less than f+1 servers are connected send an exception to the client
        throw new RuntimeException("Impossible to connect to servers!");
    }
    if (targets.length == 1 && sent == 0)
        throw new RuntimeException("Server not connected");
}

From source file:books.netty.protocol.http.fileServer.HttpFileServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (!request.getDecoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);//from w ww  .  jav  a2  s  .c o m
        return;
    }
    if (request.getMethod() != GET) {
        sendError(ctx, METHOD_NOT_ALLOWED);
        return;
    }
    final String uri = request.getUri();
    final String path = sanitizeUri(uri);
    if (path == null) {
        sendError(ctx, FORBIDDEN);
        return;
    }
    File file = new File(path);
    if (file.isHidden() || !file.exists()) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    if (file.isDirectory()) {
        if (uri.endsWith("/")) {
            sendListing(ctx, file);
        } else {
            sendRedirect(ctx, uri + '/');
        }
        return;
    }
    if (!file.isFile()) {
        sendError(ctx, FORBIDDEN);
        return;
    }
    RandomAccessFile randomAccessFile = null;
    try {
        randomAccessFile = new RandomAccessFile(file, "r");// ??
    } catch (FileNotFoundException fnfe) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    long fileLength = randomAccessFile.length();
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    setContentLength(response, fileLength);
    setContentTypeHeader(response, file);
    if (isKeepAlive(request)) {
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }
    ctx.write(response);
    ChannelFuture sendFileFuture;
    sendFileFuture = ctx.write(new ChunkedFile(randomAccessFile, 0, fileLength, 8192),
            ctx.newProgressivePromise());
    sendFileFuture.addListener(new ChannelProgressiveFutureListener() {
        @Override
        public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) {
            if (total < 0) { // total unknown
                System.err.println("Transfer progress: " + progress);
            } else {
                System.err.println("Transfer progress: " + progress + " / " + total);
            }
        }

        @Override
        public void operationComplete(ChannelProgressiveFuture future) {
            System.out.println("Transfer complete.");
        }
    });
    ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    if (!isKeepAlive(request)) {
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:books.netty.protocol.http.xml.server.HttpXmlServerHandler.java

License:Apache License

public void messageReceived(final ChannelHandlerContext ctx, HttpXmlRequest xmlRequest) {
    HttpRequest request = xmlRequest.getRequest();
    Order order = (Order) xmlRequest.getBody();
    System.out.println("Http server receive request : " + order);
    dobusiness(order);/*  ww w . jav a2  s .co m*/
    ChannelFuture future = ctx.writeAndFlush(new HttpXmlResponse(null, order));
    if (!isKeepAlive(request)) {
        future.addListener(new GenericFutureListener<Future<? super Void>>() {
            public void operationComplete(Future future) {
                ctx.close();
            }
        });
    }
}

From source file:books.netty.protocol.websocket.server.WebSocketServerHandler.java

License:Apache License

private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // /*w ww  .ja  v  a2  s. co  m*/
    if (res.getStatus().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);
        buf.release();
        setContentLength(res, res.content().readableBytes());
    }

    // ?Keep-Alive
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!isKeepAlive(req) || res.getStatus().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:c5db.client.FutureBasedMessageHandler.java

License:Apache License

@Override
public ListenableFuture<Response> buffer(final Call request, final Channel channel) {
    SettableFuture<Response> settableFuture = SettableFuture.create();
    futures.put(request.getCommandId(), settableFuture);
    // Keep track of how many outstanding requests we have and limit it.
    ChannelFuture future = channel.write(request);
    future.addListener(objectFuture -> inFlightCalls.decrementAndGet());

    if (inFlightCalls.incrementAndGet() > C5Constants.IN_FLIGHT_CALLS) {
        System.out.println("Backing off:" + C5Constants.IN_FLIGHT_CALLS);
        try {/*from   ww  w . j av  a 2  s .  com*/
            future.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    return settableFuture;
}

From source file:c5db.control.SimpleControlClient.java

License:Apache License

public ListenableFuture<CommandReply> sendRequest(CommandRpcRequest<?> request,
        InetSocketAddress remoteAddress) {
    SettableFuture<CommandReply> replyMessageFuture = SettableFuture.create();
    ChannelFuture connectFuture = client.connect(remoteAddress);
    connectFuture.addListener(new ChannelFutureListener() {
        @Override/*from w  w  w.  j  a  v a  2 s .  c  o  m*/
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                future.channel().pipeline().addLast(new SimpleChannelInboundHandler<CommandReply>() {
                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, CommandReply msg) throws Exception {
                        replyMessageFuture.set(msg);
                        ctx.channel().close();
                    }
                });

                // connected is fine, flush message:
                future.channel().writeAndFlush(request);
            } else {
                replyMessageFuture.setException(future.cause());
                future.channel().close();
            }
        }
    });

    return replyMessageFuture;
}

From source file:c5db.replication.ReplicatorService.java

License:Apache License

@FiberOnly
private void handleOutgoingMessage(final Request<RpcRequest, RpcWireReply> message) {
    final RpcRequest request = message.getRequest();
    final long to = request.to;

    if (to == nodeId) {
        handleLoopBackMessage(message);/*from w  w  w .j  ava 2  s.  c  o m*/
        return;
    }

    // check to see if we have a connection:
    Channel channel = connections.get(to);
    if (channel != null && channel.isOpen()) {
        sendMessageAsync(message, channel);
        return;
    } else if (channel != null) {
        // stale?
        LOG.debug("Removing stale !isOpen channel from connections.get() for peer {}", to);
        connections.remove(to);
    }

    NodeInfoRequest nodeInfoRequest = new NodeInfoRequest(to, ModuleType.Replication);
    LOG.debug("node {} sending node info request {} ", nodeId, nodeInfoRequest);
    AsyncRequest.withOneReply(fiber, discoveryModule.getNodeInfo(), nodeInfoRequest,
            new Callback<NodeInfoReply>() {
                @SuppressWarnings("RedundantCast")
                @FiberOnly
                @Override
                public void onMessage(NodeInfoReply nodeInfoReply) {
                    if (!nodeInfoReply.found) {
                        LOG.debug("Can't find the info for the peer {}", to);
                        // TODO signal TCP/transport layer failure in a better way
                        //message.reply(null);
                        return;
                    }

                    LOG.debug("node {} got node info for node {} reply {} ", nodeId, to, nodeInfoReply);
                    // what if existing outgoing connection attempt?
                    Channel channel = connections.get(to);
                    if (channel != null && channel.isOpen()) {
                        sendMessageAsync(message, channel);
                        return;
                    } else if (channel != null) {
                        LOG.debug("Removing stale2 !isOpen channel from connections.get() for peer {}", to);
                        connections.remove(to);
                    }

                    // ok so we connect now:
                    ChannelFuture channelFuture = outgoingBootstrap.connect(nodeInfoReply.addresses.get(0),
                            nodeInfoReply.port);
                    LOG.trace("Connecting to peer {} at address {} port {}", to, nodeInfoReply.addresses.get(0),
                            nodeInfoReply.port);

                    // the channel might not be open, so defer the write.
                    connections.put(to, channelFuture.channel());
                    channelFuture.channel().closeFuture()
                            .addListener((ChannelFutureListener) future -> fiber.execute(() -> {
                                // remove only THIS channel. It might have been removed prior so.
                                connections.remove(to, future.channel());
                            }));

                    // funny hack, if the channel future is already open, we execute immediately!
                    channelFuture.addListener((ChannelFutureListener) future -> {
                        if (future.isSuccess()) {
                            sendMessageAsync(message, future.channel());
                        }
                    });
                }
            },
            // If the NodeInfoRequest times out:
            ReplicatorConstants.REPLICATOR_NODE_INFO_REQUEST_TIMEOUT_MILLISECONDS, TimeUnit.MILLISECONDS,
            () -> LOG.warn("node info request timeout {} ", nodeInfoRequest));
}

From source file:ca.lambtoncollege.netty.webSocket.ServerHandlerWebSocket.java

private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // Generate an error page if response getStatus code is not OK (200).
    if (res.getStatus().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);/*from  w  ww.j av a2s  . c o  m*/
        buf.release();
        HttpHeaders.setContentLength(res, res.content().readableBytes());
    }

    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:cc.agentx.client.net.nio.XClient.java

License:Apache License

public void start() {
    Configuration config = Configuration.INSTANCE;
    InternalLoggerFactory.setDefaultFactory(Slf4JLoggerFactory.INSTANCE);
    bossGroup = new NioEventLoopGroup(1);
    workerGroup = new NioEventLoopGroup();
    try {//from  ww  w .  j  a  va  2 s .co  m
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast("logging", new LoggingHandler(LogLevel.DEBUG))
                                .addLast(new SocksInitRequestDecoder()).addLast(new SocksMessageEncoder())
                                .addLast(new Socks5Handler()).addLast(Status.TRAFFIC_HANDLER);
                    }
                });
        log.info("\tStartup {}-{}-client [{}{}]", Constants.APP_NAME, Constants.APP_VERSION, config.getMode(),
                config.getMode().equals("socks5") ? "" : ":" + config.getProtocol());
        ChannelFuture future = bootstrap.bind(config.getLocalHost(), config.getLocalPort()).sync();
        future.addListener(
                future1 -> log.info("\tListening at {}:{}...", config.getLocalHost(), config.getLocalPort()));
        future.channel().closeFuture().sync();
    } catch (Exception e) {
        log.error("\tSocket bind failure ({})", e.getMessage());
    } finally {
        log.info("\tShutting down");
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:cc.agentx.server.net.nio.XServer.java

License:Apache License

public void start() {
    Configuration config = Configuration.INSTANCE;
    InternalLoggerFactory.setDefaultFactory(Slf4JLoggerFactory.INSTANCE);
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {// w  w  w  .  j av a  2s.  com
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast("logging", new LoggingHandler(LogLevel.DEBUG))
                                .addLast(new XConnectHandler());
                        if (config.getReadLimit() != 0 || config.getWriteLimit() != 0) {
                            socketChannel.pipeline().addLast(
                                    new GlobalTrafficShapingHandler(Executors.newScheduledThreadPool(1),
                                            config.getWriteLimit(), config.getReadLimit()));
                        }
                    }
                });
        log.info("\tStartup {}-{}-server [{}]", Constants.APP_NAME, Constants.APP_VERSION,
                config.getProtocol());
        ChannelFuture future = bootstrap.bind(config.getHost(), config.getPort()).sync();
        future.addListener(future1 -> log.info("\tListening at {}:{}...", config.getHost(), config.getPort()));
        future.channel().closeFuture().sync();
    } catch (Exception e) {
        log.error("\tSocket bind failure ({})", e.getMessage());
    } finally {
        log.info("\tShutting down and recycling...");
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
        Configuration.shutdownRelays();
    }
    System.exit(0);
}