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:com.zextras.modules.chat.server.xmpp.netty.StanzaWriterImp.java

License:Open Source License

@Override
public void onEventQueued(EventQueue eventQueue) {
    try {//from  w ww  .j  a v a  2 s  .  c  o  m
        final ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
        for (Event event : eventQueue.popAllEvents()) {
            LogContext logContext = CurrentLogContext.begin();
            if (event.getTarget().getAddresses().size() == 1) {
                logContext.setAccountName(event.getTarget().toSingleAddress());
            }
            logContext.freeze();
            try {
                out.reset();
                XmppEncoder encoder = (XmppEncoder) event.interpret(mEncoderFactory);
                if (encoder == null) {
                    ChatLog.log.debug("No encoder found for event " + event.getClass().getName());
                    continue;
                }

                final SpecificAddress exposedAddress = mXmppConnectionHandler.getSession().getExposedAddress();

                encoder.encode(out, exposedAddress);

                String stanzaDebug = new String(out.toByteArray(), "UTF-8");
                ChatLog.log.debug("writing: " + event.getClass().getName());
                ChatLog.log.debug("writing stanza(" + stanzaDebug.length() + "): " + stanzaDebug);
                ByteBuf stanza = Unpooled.copiedBuffer(out.toByteArray());
                ChannelFuture writeFuture = mXmppConnectionHandler.write(stanza);

                final Event eventToNotify = event;

                writeFuture.addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (future.isSuccess()) {
                            EventInterceptor interceptor = eventToNotify
                                    .interpret(mXmppEventInterceptorFactory);
                            interceptor.intercept(mEventManager, exposedAddress);
                        }
                    }
                });
            } finally {
                CurrentLogContext.end();
            }
        }
    } catch (Throwable ex) {
        ChatLog.log.warn("Exception: " + Utils.exceptionToString(ex));
    }
}

From source file:com.zextras.modules.chat.server.xmpp.netty.TransparentProxy.java

License:Open Source License

public Future<Channel> connect() {
    final Promise<Channel> channelFuture = new DefaultProgressivePromise<Channel>(
            ImmediateEventExecutor.INSTANCE);

    if (mServerChannel == null) {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(mNettyService.getEventLoopGroup()).channel(NioSocketChannel.class)
                .remoteAddress(new InetSocketAddress(mAccount.getMailHost(), mPort)).handler(new Initializer());

        ChannelFuture serverChannelFuture = bootstrap.connect();
        serverChannelFuture.addListener(new ChannelFutureListener() {
            @Override/*from   w  ww .j a v  a2s .com*/
            public void operationComplete(ChannelFuture future) {
                if (future.isSuccess()) {
                    ChatLog.log.info(
                            "Proxy xmpp requests for " + mAccount.getName() + " to " + mAccount.getMailHost());
                    mServerChannel = future.channel();

                    mServerChannel.write(Unpooled.wrappedBuffer(mStreamInit.getBytes()));
                    mServerChannel.writeAndFlush(Unpooled.wrappedBuffer(mInitialPayload.getBytes()));

                    mServerChannel.pipeline().addLast("proxyToClient", new Proxy(mClientChannel));

                    mClientChannel.pipeline().addLast("proxyToServer", new Proxy(mServerChannel));

                    mServerChannel.closeFuture().addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture future) throws Exception {
                            mClientChannel.close();
                        }
                    });

                    mClientChannel.closeFuture().addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture future) throws Exception {
                            mServerChannel.close();
                        }
                    });

                    future.channel().closeFuture();

                    channelFuture.setSuccess(mServerChannel);
                } else {
                    ChatLog.log.info("Cannot proxy xmpp requests for " + mAccount.getName() + " to "
                            + mAccount.getMailHost() + ": " + Utils.exceptionToString(future.cause()));
                    sendInternalError(mClientChannel);
                    mClientChannel.flush().close();
                    channelFuture.setFailure(future.cause());
                }
            }
        });

        return channelFuture;
    } else {
        mServerChannel.pipeline().addLast("proxyToClient", new Proxy(mClientChannel));

        mServerChannel.writeAndFlush(mInitialPayload.getBytes());

        channelFuture.setSuccess(mServerChannel);
        return channelFuture;
    }
}

From source file:com.zhang.pool.NettyChannelPool.java

License:Apache License

private boolean sendRequestUseNewChannel(final InetSocketAddress route, final HttpRequest request,
        final NettyHttpResponseFuture responseFuture, boolean forceConnect) {
    ChannelFuture future = createChannelFuture(route, forceConnect);
    if (null != future) {
        NettyHttpResponseFutureUtil.attributeResponse(future.channel(), responseFuture);
        NettyHttpResponseFutureUtil.attributeRoute(future.channel(), route);
        future.addListener(new ChannelFutureListener() {

            @Override// w  w w.java2s  .c om
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {

                    future.channel().closeFuture().addListener(new ChannelFutureListener() {

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

                            logger.log(Level.SEVERE,
                                    future.channel() + " closed, exception: " + future.cause());
                            removeChannel(future.channel(), future.cause());
                        }

                    });
                    future.channel().writeAndFlush(request).addListener(CLOSE_ON_FAILURE);
                } else {
                    logger.log(Level.SEVERE,
                            future.channel() + " connect failed, exception: " + future.cause());

                    NettyHttpResponseFutureUtil.cancel(future.channel(), future.cause());
                    if (!NettyHttpResponseFutureUtil.getForceConnect(future.channel())) {
                        releaseCreatePerRoute(future.channel());
                    }
                }
            }

        });
        return true;
    }
    return false;
}

From source file:com.zhaopeng.timeserver.netty.delimiter.EchoClientHandler.java

License:Apache License

public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

    ChannelFuture future = ctx.channel().close();

    System.out.println(Thread.currentThread().getName() + "" + future + "  " + counter);

    future.addListener(new ChannelFutureListener());
    result = msg;// w  w w .j  a  va  2  s  .  com

    System.out.println("This is " + ++counter + " times receive server : [" + result + "]");
}

From source file:com.zhucode.longio.transport.netty.NettyClient.java

License:Open Source License

@Override
public void send(MessageBlock mb) {
    long sid = channel.attr(NettyConnector.sessionKey).get();
    mb.setSessionId(sid);/*from w  w w  . j  a  va2  s.c  o m*/
    ChannelFuture f = this.connector.send(mb);
    f.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isCancelled() || future.cause() != null) {
                throw new Exception("service maybe unavailable");
            }
        }
    });

}

From source file:de.dentrassi.varlink.internal.ConnectionImpl.java

License:Open Source License

@Override
public CompletableFuture<CallResponse> call(final CallRequest call) {

    final CompletableFuture<CallResponse> result = new CompletableFuture<>();

    final Bootstrap bootstrap = new Bootstrap().group(this.group).channel(EpollDomainSocketChannel.class)
            .handler(new ChannelInitializer<Channel>() {

                @Override/* w w w  .  j  a v  a  2s.  c o  m*/
                protected void initChannel(final Channel channel) throws Exception {

                    if (PROTOCOL_LOGGER.isDebugEnabled()) {
                        channel.pipeline().addLast(new LoggingHandler(PROTOCOL_LOGGER_NAME));
                    }

                    channel.pipeline().addLast(new DelimiterBasedFrameDecoder(MAX_FRAME_LENGTH, nulDelimiter()))
                            .addLast(NullByteEncoder.INSTANCE).addLast(new JsonObjectDecoder())
                            .addLast(ConnectionImpl.this.stringEncoder).addLast(new StringDecoder(UTF_8))
                            .addLast(new VarlinkCodec()).addLast(new CallHandler(call, result));

                }
            });

    logger.debug("Connecting: {}", this.address);

    final ChannelFuture future = bootstrap.connect(this.address);

    final Channel channel = future.channel();

    future.addListener(v -> {

        logger.debug("connect complete");

        try {
            future.get();

            logger.debug("connect completed successfully");
        } catch (final Throwable e) {
            logger.debug("connect failed", e);
            channel.close();
            result.completeExceptionally(e);
        }
    });

    return result;
}

From source file:de.dfki.kiara.netty.ListenableConstantFutureAdapter.java

License:Open Source License

@Override
public void addListener(final Runnable r, final Executor exctr) {
    future.addListener(new ChannelFutureListener() {
        @Override/* www  . ja v a  2 s  .c om*/
        public void operationComplete(ChannelFuture future) throws Exception {
            exctr.execute(r);
        }
    });
}

From source file:de.eightnine.rec.HttpStaticFileServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (!request.getDecoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);//from   w w  w  .j ava 2s.  com
        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;
    }

    // Cache Validation
    String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE);
    if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
        SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
        Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);

        // Only compare up to the second because the datetime format we send to the client
        // does not have milliseconds
        long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
        long fileLastModifiedSeconds = file.lastModified() / 1000;
        if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
            sendNotModified(ctx);
            return;
        }
    }

    RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException ignore) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    long fileLength = raf.length();

    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    HttpHeaders.setContentLength(response, fileLength);
    setContentTypeHeader(response, file);
    setDateAndCacheHeaders(response, file);
    if (HttpHeaders.isKeepAlive(request)) {
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }

    // Write the initial line and the header.
    ctx.write(response);

    // Write the content.
    ChannelFuture sendFileFuture;
    if (ctx.pipeline().get(SslHandler.class) == null) {
        sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength),
                ctx.newProgressivePromise());
    } else {
        sendFileFuture = ctx.write(new HttpChunkedInput(new ChunkedFile(raf, 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(future.channel() + " Transfer progress: " + progress);
            } else {
                System.err.println(future.channel() + " Transfer progress: " + progress + " / " + total);
            }
        }

        @Override
        public void operationComplete(ChannelProgressiveFuture future) {
            System.err.println(future.channel() + " Transfer complete.");
        }
    });

    // Write the end marker
    ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);

    // Decide whether to close the connection or not.
    if (!HttpHeaders.isKeepAlive(request)) {
        // Close the connection when the whole content is written out.
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:de.felix_klauke.pegasus.client.network.NettyClient.java

License:Apache License

/**
 *
 * You can send a new Object (would be cool when you choose a
 * {@link de.felix_klauke.pegasus.protocol.Packet}).
 *
 * @param object the object to send through our pipeline
 *///  w  ww. ja  va 2 s.  co m
public void send(Object object) {
    System.out.println("Sending a packet");
    ChannelFuture future = getChannel().writeAndFlush(object);
    future.addListener(new GenericFutureListener<Future<? super Void>>() {
        public void operationComplete(Future<? super Void> future) throws Exception {
            if (!future.isSuccess()) {
                future.cause().printStackTrace();
            }
        }
    });
}

From source file:de.felix_klauke.pegasus.server.handler.listener.PacketMessageListener.java

License:Apache License

/**
 * Handle any incoming PacketMessage.//ww w .  j  a  va  2  s  .  co m
 *
 * @param channel the channel the message cam from
 * @param packet  the packet
 */
public void handlePacket(Channel channel, PacketMessage packet) {
    PacketMessage packetMessage = new PacketMessage(packet.getMessage());
    packetMessage.setAuthor(userManager.getUser(channel).getUsername());
    for (User user : userManager.getUsers()) {
        if (user.getChannel().id() == channel.id())
            continue;
        System.out.println("Sending Packet to: " + user.getUsername() + " -> " + packetMessage.getMessage());
        ChannelFuture future = user.getChannel().writeAndFlush(packetMessage);
        future.addListener(new GenericFutureListener<Future<? super Void>>() {
            public void operationComplete(Future<? super Void> future) throws Exception {
                if (!future.isSuccess()) {
                    future.cause().printStackTrace();
                }
            }
        });
    }
}