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.datastax.driver.core.Connection.java

License:Apache License

public ListenableFuture<Void> initAsync() {
    if (factory.isShutdown)
        return Futures
                .immediateFailedFuture(new ConnectionException(address, "Connection factory is shut down"));

    ProtocolVersion protocolVersion = factory.protocolVersion == null ? ProtocolVersion.NEWEST_SUPPORTED
            : factory.protocolVersion;/*w  ww.ja v a  2s. c  om*/
    final SettableFuture<Void> channelReadyFuture = SettableFuture.create();

    try {
        Bootstrap bootstrap = factory.newBootstrap();
        ProtocolOptions protocolOptions = factory.configuration.getProtocolOptions();
        bootstrap.handler(new Initializer(this, protocolVersion, protocolOptions.getCompression().compressor(),
                protocolOptions.getSSLOptions(),
                factory.configuration.getPoolingOptions().getHeartbeatIntervalSeconds(),
                factory.configuration.getNettyOptions()));

        ChannelFuture future = bootstrap.connect(address);

        writer.incrementAndGet();
        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                writer.decrementAndGet();
                channel = future.channel();
                if (isClosed()) {
                    channel.close().addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture future) throws Exception {
                            channelReadyFuture.setException(new TransportException(Connection.this.address,
                                    "Connection closed during initialization."));
                        }
                    });
                } else {
                    Connection.this.factory.allChannels.add(channel);
                    if (!future.isSuccess()) {
                        if (logger.isDebugEnabled())
                            logger.debug(String.format("%s Error connecting to %s%s", Connection.this,
                                    Connection.this.address, extractMessage(future.cause())));
                        channelReadyFuture.setException(new TransportException(Connection.this.address,
                                "Cannot connect", future.cause()));
                    } else {
                        logger.debug("{} Connection established, initializing transport", Connection.this);
                        channel.closeFuture().addListener(new ChannelCloseListener());
                        channelReadyFuture.set(null);
                    }
                }
            }
        });
    } catch (RuntimeException e) {
        closeAsync().force();
        throw e;
    }

    Executor initExecutor = factory.manager.configuration.getPoolingOptions().getInitializationExecutor();

    ListenableFuture<Void> initializeTransportFuture = Futures.transformAsync(channelReadyFuture,
            onChannelReady(protocolVersion, initExecutor), initExecutor);

    // Fallback on initializeTransportFuture so we can properly propagate specific exceptions.
    ListenableFuture<Void> initFuture = Futures.catchingAsync(initializeTransportFuture, Throwable.class,
            new AsyncFunction<Throwable, Void>() {
                @Override
                public ListenableFuture<Void> apply(@Nullable Throwable t) throws Exception {
                    SettableFuture<Void> future = SettableFuture.create();
                    // Make sure the connection gets properly closed.
                    if (t instanceof ClusterNameMismatchException
                            || t instanceof UnsupportedProtocolVersionException) {
                        // Just propagate
                        closeAsync().force();
                        future.setException(t);
                    } else {
                        // Defunct to ensure that the error will be signaled (marking the host down)
                        Exception e = (t instanceof ConnectionException || t instanceof DriverException
                                || t instanceof InterruptedException) ? (Exception) t
                                        : new ConnectionException(Connection.this.address, String.format(
                                                "Unexpected error during transport initialization (%s)", t), t);
                        future.setException(defunct(e));
                    }
                    return future;
                }
            }, initExecutor);

    // Ensure the connection gets closed if the caller cancels the returned future.
    Futures.addCallback(initFuture, new MoreFutures.FailureCallback<Void>() {
        @Override
        public void onFailure(Throwable t) {
            if (!isClosed()) {
                closeAsync().force();
            }
        }
    }, initExecutor);

    return initFuture;
}

From source file:com.digisky.stresstest.HttpSnoopClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    uri = new URI(URL);
    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
    String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    int port = uri.getPort();
    if (port == -1) {
        if ("http".equalsIgnoreCase(scheme)) {
            port = 80;//from  w ww .  j  ava  2 s .  co  m
        } else if ("https".equalsIgnoreCase(scheme)) {
            port = 443;
        }
    }

    if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
        System.err.println("Only HTTP(S) is supported.");
        return;
    }

    // Configure SSL context if necessary.
    final boolean ssl = "https".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } else {
        sslCtx = null;
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new HttpSnoopClientInitializer(sslCtx));

        // Make the connection attempt.
        System.out.println("try to connect!");
        ChannelFuture f = b.connect(host, port);
        f.addListener(new ChannelFutureListener() {
            public void operationComplete(ChannelFuture future) {
                // Perform post-closure operation
                // ...
                System.out.println("complete!");
                if (!future.isSuccess()) {
                    // You might get a NullPointerException here because the future
                    // might not be completed yet.
                    future.cause().printStackTrace();
                } else {
                    System.out.println("ok!!!!");
                }
            }
        });
    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.dingwang.netty.handler.DiscardServerHandler.java

License:Open Source License

@Override
//channelActive()??
//32??/*w w w.j  a va 2 s  .c  om*/
public void channelActive(ChannelHandlerContext ctx) throws Exception {

    //????????32?
    //?4ByteBufChannelHandlerContext.alloc()?ByteBufAllocator
    //??
    //        final ByteBuf time = ctx.alloc().buffer(4);
    //        time.writeInt((int) (System.currentTimeMillis() / 1000L + 2208988800L));

    //???ChannelHandlerContext.write()(
    //writeAndFlush())ChannelFutureChannelFuture?I/O?
    //????Netty????
    //?????
    //?write()ChannelFuture??close()????
    //??,close()??ChannelFuture
    //        final ChannelFuture f = ctx.writeAndFlush(time);

    //?????ChannelFuture
    //ChannelFutureListener??ChannelFutureListener???
    //Channel????:
    //f.addListener(ChannelFutureListener.CLOSE);
    //        f.addListener(new ChannelFutureListener() {
    //            @Override
    //
    //            public void operationComplete(ChannelFuture future) {
    //                assert f == future;
    //                ctx.close();
    //
    //            }
    //        });
    System.out.println("test idle");
    ChannelFuture f = ctx.writeAndFlush("hhhh");
    f.addListener(ChannelFutureListener.CLOSE);

}

From source file:com.dinstone.jrpc.transport.netty4.NettyConnection.java

License:Apache License

@Override
public ResultFuture call(Call call) {
    final int id = ID_GENERATOR.incrementAndGet();
    Map<Integer, ResultFuture> futureMap = SessionUtil.getResultFutureMap(ioSession);
    final ResultFuture resultFuture = new ResultFuture();
    futureMap.put(id, resultFuture);//from w  w  w  .j  a  va  2 s .  com

    ChannelFuture wf = ioSession.writeAndFlush(new Request(id, serializeType, call));
    wf.addListener(new GenericFutureListener<ChannelFuture>() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                resultFuture.setResult(new Result(500, "can't write request"));
            }
        }

    });

    return resultFuture;
}

From source file:com.dinstone.jrpc.transport.netty5.NettyConnection.java

License:Apache License

@Override
public ResultFuture call(Call call) {
    final int id = ID_GENERATOR.incrementAndGet();
    Map<Integer, ResultFuture> futureMap = SessionUtil.getResultFutureMap(ioSession);
    final ResultFuture resultFuture = new ResultFuture();
    futureMap.put(id, resultFuture);/*from   w  w  w .j  a va  2  s  . c  o m*/

    ChannelFuture wf = ioSession.writeAndFlush(new Request(id, serializeType, call));
    wf.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                resultFuture.setResult(new Result(500, "can't write request"));
            }
        }

    });

    return resultFuture;
}

From source file:com.dwarf.netty.guide.factorial.FactorialClientHandler.java

License:Apache License

private void sendNumbers() {
    // Do not send more than 4096 numbers.
    ChannelFuture future = null;
    for (int i = 0; i < 4096 && next <= FactorialClient.COUNT; i++) {
        future = ctx.write(Integer.valueOf(next));
        next++;/*from   w ww  .  j  a va 2s.  c om*/
    }
    if (next <= FactorialClient.COUNT) {
        assert future != null;
        future.addListener(numberSender);
    }
    ctx.flush();
}

From source file:com.e2e.management.HttpSocketHandler.java

License:Apache License

public void handleHttpFileRequest(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {

    if (!request.getDecoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);//from w w  w .j  a va 2 s.  com
        return;
    }

    if (request.getMethod() != GET) {
        sendError(ctx, METHOD_NOT_ALLOWED);
        return;
    }

    String uri = request.getUri();
    if (uri == null) {
        sendError(ctx, FORBIDDEN);
        return;
    }
    if ((uri.equals("")) || (uri.equals("/"))) {
        uri = "/index.html";
    }
    final String path = sanitizeUri(uri);

    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, Values.KEEP_ALIVE);
    }

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

    // Write the content.
    ChannelFuture sendFileFuture;
    ChannelFuture lastContentFuture;
    if (ctx.pipeline().get(SslHandler.class) == null) {
        sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength),
                ctx.newProgressivePromise());
        // Write the end marker.
        lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    } else {
        sendFileFuture = ctx.write(new ChunkedFile(raf, 0, fileLength, 8192), ctx.newProgressivePromise());
        // HttpChunkedInput will write the end marker (LastHttpContent) for us.
        lastContentFuture = sendFileFuture;
    }

    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.");
        }
    });

    // 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:com.earasoft.framework.http.WebSocketServerHandler.java

License:Apache License

private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest request) {
    // Handle a bad request.
    if (!request.getDecoderResult().isSuccess()) {
        sendHttpResponse(ctx, request, new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
        return;//w  w  w .  j a va 2  s.  c  o m
    }

    if (RouterHits.checkIfMappingExit(request)) {
        //Do Router Mapping First
        RouterHits.execute(ctx, request);
        return;
    }

    if ("/websocket".equals(request.getUri())) {
        // Handshake
        WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
                getWebSocketLocation(request), null, true);
        handshaker = wsFactory.newHandshaker(request);
        if (handshaker == null) {
            WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
        } else {
            handshaker.handshake(ctx.channel(), request);
            channels.add(ctx.channel());
        }
        return;
    }

    final String uri = request.getUri();
    //System.out.println("uri: " + uri);
    final String path = sanitizeUri("www", uri);
    //System.out.println("path: " + path);
    if (path == null) {
        sendHttpResponse(ctx, request, new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.FORBIDDEN));

        return;
    }

    File file = new File(path);
    if (file.isHidden() || !file.exists()) {
        sendHttpResponse(ctx, request, new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.NOT_FOUND));
        return;
    }

    if (file.isDirectory()) {
        if (uri.endsWith("/")) {

            File checkIndexFile = new File(file.getAbsolutePath() + File.separator + "index.html");

            System.out.println(checkIndexFile.exists());
            if (checkIndexFile.exists()) {
                file = checkIndexFile;
            } else {
                sendListing(ctx, file);
                return;
            }
        } else {
            sendRedirect(ctx, uri + '/');

        }
    }

    if (!file.isFile()) {
        sendHttpResponse(ctx, request, new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.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 = null;
        try {
            ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // 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) {
        sendHttpResponse(ctx, request, new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.NOT_FOUND));
        return;
    }
    long fileLength = 0;
    try {
        fileLength = raf.length();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    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 = null;
    ChannelFuture lastContentFuture;
    if (ctx.pipeline().get(SslHandler.class) == null) {
        sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength),
                ctx.newProgressivePromise());
        // Write the end marker.
        lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    } else {
        try {
            sendFileFuture = ctx.writeAndFlush(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)),
                    ctx.newProgressivePromise());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // HttpChunkedInput will write the end marker (LastHttpContent) for us.
        lastContentFuture = sendFileFuture;
    }

    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.");
        }
    });

    // 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);
    }

    //        // Send the demo page and favicon.ico
    //        if ("/".equals(req.getUri()) && req.getMethod() == GET) {
    //            ByteBuf content = WebSocketServerIndexPage.getContent(getWebSocketLocation(req));
    //            FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content);
    //
    //            res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
    //            HttpHeaders.setContentLength(res, content.readableBytes());
    //
    //            sendHttpResponse(ctx, req, res);
    //            return;
    //        }
    //        
    //        if ("/favicon.ico".equals(req.getUri())) {
    //            FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND);
    //            sendHttpResponse(ctx, req, res);
    //            return;
    //        }

    sendHttpResponse(ctx, request, new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.FORBIDDEN));
    return;

}

From source file:com.ebay.jetstream.http.netty.server.AbstractHttpRequest.java

License:MIT License

protected void postResponse(Channel channel, HttpRequest request, HttpResponse response) {

    boolean keepAlive = HttpHeaders.isKeepAlive(request);

    String reqid = request.headers().get("X_EBAY_REQ_ID");

    if (reqid != null && !reqid.isEmpty()) // if request contains
                                           // X_EBAY_REQ_ID we will echo it
                                           // back
        HttpHeaders.setHeader(response, "X_EBAY_REQ_ID", reqid);

    // we will echo back cookies for now in the response. Our request ID is
    // set as a cookie

    String contentLenHeader = response.headers().get(HttpHeaders.Names.CONTENT_LENGTH);
    if (contentLenHeader == null)
        HttpHeaders.setContentLength(response, 0);

    // Write the response.
    ChannelFuture future = channel.writeAndFlush(response);

    // Close the non-keep-alive connection after the write operation is
    // done.//from w ww.  j a  v  a2  s .c  o  m
    if (!keepAlive) {
        future.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.ebay.jetstream.messaging.transport.netty.eventproducer.EventProducer.java

License:MIT License

/**
 * @param numConnections/*from   ww  w. jav  a  2  s . c  o m*/
 */
private void createAsyncMultipleConnections(EventConsumerInfo ecinfo, int numConnections) {

    for (int i = 0; i < numConnections; i++) {

        ChannelFuture cf = null;
        try {

            cf = m_bootstrap.connect(
                    new InetSocketAddress(InetAddress.getByName(ecinfo.getAdvertisement().getHostName()),
                            ecinfo.getAdvertisement().getListenTcpPort()));
        } catch (UnknownHostException e) {
            LOGGER.error("failed to connect to Host - " + ecinfo.getAdvertisement().getHostName() + " - "
                    + e.getLocalizedMessage());
        }

        final EventConsumerActivationRequest ar = new EventConsumerActivationRequest(this, ecinfo,
                m_transportConfig.getMaxNettyBackLog(), cf.channel()); // not sure if it makes sense to make this final

        if (cf != null)
            cf.addListener(ar);

    }
}