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.soho.framework.server.netty.http.HttpServletHandler.java

License:Apache License

protected void handleHttpServletRequest(ChannelHandlerContext ctx, HttpRequest request, FilterChainImpl chain)
        throws Exception {
    // ?/*from   ww w  .  ja  v a2s .co  m*/
    interceptOnRequestReceived(ctx, request);

    // Netty HTTP?Servlet
    HttpServletRequestImpl req = buildHttpServletRequest(request, chain);

    // Netty HTTP??Servlet?
    DefaultFullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK);
    HttpServletResponseImpl resp = buildHttpServletResponse(response);

    // 
    chain.doFilter(req, resp);

    // ?
    interceptOnRequestSuccessed(ctx, request, response);

    resp.getWriter().flush();

    boolean keepAlive = HttpHeaders.isKeepAlive(request);
    if (keepAlive) {
        // Add 'Content-Length' header only for a keep-alive connection.
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
        // Add keep alive header as per:
        // -
        // http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }

    // ?
    if (req.isAsyncSupported() && req.isAsyncStarted()) {
        ctx.fireChannelRead(resp);
    } else {
        // write response...
        ChannelFuture future = ctx.channel().writeAndFlush(response);

        if (!keepAlive) {
            future.addListener(ChannelFutureListener.CLOSE);
        }
    }
}

From source file:com.soho.framework.server.netty.http.HttpServletHandler.java

License:Apache License

protected void handleStaticResourceRequest(ChannelHandlerContext ctx, HttpRequest request) throws Exception {
    if (request.method() != GET) {
        sendError(ctx, METHOD_NOT_ALLOWED);
        return;//  w  ww. jav a2 s. c om
    }

    String uri = Utils.sanitizeUri(request.uri());
    final String path = (uri != null
            ? ServletWebApp.get().getStaticResourcesFolder().getAbsolutePath() + File.separator + uri
            : null);

    if (path == null) {
        sendError(ctx, FORBIDDEN);
        return;
    }

    File file = new File(path);
    if (file.isHidden() || !file.exists()) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    if (!file.isFile()) {
        sendError(ctx, FORBIDDEN);
        return;
    }

    RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException fnfe) {
        sendError(ctx, NOT_FOUND);
        return;
    }

    long fileLength = raf.length();

    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    setContentLength(response, fileLength);

    Channel ch = ctx.channel();

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

    // Write the content.
    ChannelFuture writeFuture;
    if (isSslChannel(ch)) {
        // Cannot use zero-copy with HTTPS.
        writeFuture = ch.write(new ChunkedFile(raf, 0, fileLength, 8192));
    } else {
        // No encryption - use zero-copy.
        final FileRegion region = new DefaultFileRegion(raf.getChannel(), 0, fileLength);
        writeFuture = ch.write(region);
        writeFuture.addListener(new ChannelProgressiveFutureListener() {

            @Override
            public void operationProgressed(ChannelProgressiveFuture channelProgressiveFuture, long current,
                    long total) throws Exception {
                System.out.printf("%s: %d / %d (+%d)%n", path, current, total, total);
            }

            @Override
            public void operationComplete(ChannelProgressiveFuture channelProgressiveFuture) throws Exception {
                region.release();
            }
        });
    }

}

From source file:com.spotify.ffwd.protocol.RetryingProtocolConnection.java

License:Apache License

private void trySetup(final int attempt) {
    log.info("Attempt {}", action);

    final ChannelFuture connect = action.setup();

    connect.addListener(new ChannelFutureListener() {
        @Override// w  ww.  j  a  v a  2  s . c o  m
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                log.info("Successful {}", action);
                setChannel(future.channel());
                return;
            }

            final long delay = policy.delay(attempt);

            log.warn("Failed {} (attempt: {}), retrying in {}s: {}", action, attempt + 1,
                    TimeUnit.SECONDS.convert(delay, TimeUnit.MILLISECONDS), future.cause().getMessage());

            timer.newTimeout(new TimerTask() {
                @Override
                public void run(Timeout timeout) throws Exception {
                    if (stopped.get()) {
                        return;
                    }

                    trySetup(attempt + 1);
                }
            }, delay, TimeUnit.MILLISECONDS);
        }
    });
}

From source file:com.spotify.folsom.client.DefaultRawMemcacheClient.java

License:Apache License

public static ListenableFuture<RawMemcacheClient> connect(final HostAndPort address,
        final int outstandingRequestLimit, final boolean binary, final Executor executor,
        final long timeoutMillis) {

    final ChannelInboundHandler decoder;
    if (binary) {
        decoder = new BinaryMemcacheDecoder();
    } else {/*  w ww.j a  v a2  s  . c om*/
        decoder = new AsciiMemcacheDecoder();
    }

    final ChannelHandler initializer = new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(final Channel ch) throws Exception {
            ch.pipeline().addLast(new TcpTuningHandler(), decoder,

                    // Downstream
                    new MemcacheEncoder());
        }
    };

    final SettableFuture<RawMemcacheClient> clientFuture = SettableFuture.create();

    final Bootstrap bootstrap = new Bootstrap().group(EVENT_LOOP_GROUP).handler(initializer)
            .channel(NioSocketChannel.class)
            .option(ChannelOption.MESSAGE_SIZE_ESTIMATOR, SimpleSizeEstimator.INSTANCE);

    final ChannelFuture connectFuture = bootstrap
            .connect(new InetSocketAddress(address.getHostText(), address.getPort()));

    connectFuture.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                // Create client
                final RawMemcacheClient client = new DefaultRawMemcacheClient(address, future.channel(),
                        outstandingRequestLimit, executor, timeoutMillis);
                clientFuture.set(client);
            } else {
                clientFuture.setException(future.cause());
            }
        }
    });

    return onExecutor(clientFuture, executor);
}

From source file:com.spotify.heroic.rpc.nativerpc.NativeRpcProtocolServer.java

License:Apache License

private AsyncFuture<Void> start() {
    final ServerBootstrap s = new ServerBootstrap();
    s.channel(NioServerSocketChannel.class);
    s.group(bossGroup, workerGroup);/*from  w w w  . j a v a  2s.c o  m*/
    s.childHandler(new NativeRpcServerSession(timer, mapper, container, maxFrameSize, encoding));

    final ChannelFuture bind = s.bind(address);

    bind.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(final ChannelFuture f) throws Exception {
            if (!f.isSuccess()) {
                bindFuture.fail(f.cause());
                return;
            }

            serverChannel.set(f.channel());
            final InetSocketAddress address = (InetSocketAddress) f.channel().localAddress();
            bindFuture.resolve(address);
        }
    });

    return bindFuture.directTransform(a -> null);
}

From source file:com.springapp.mvc.netty.example.http.file.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  ww.  j  a  v  a 2 s  . 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;
    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.writeAndFlush(new HttpChunkedInput(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.tc.websocket.server.handler.ProxyFrontendHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) {
    final Channel inboundChannel = ctx.channel();

    this.handler = new ProxyBackendHandler(inboundChannel);

    // Start the connection attempt.
    Bootstrap b = new Bootstrap();
    b.group(inboundChannel.eventLoop()).channel(ctx.channel().getClass()).handler(this.handler)
            .option(ChannelOption.AUTO_READ, false);

    ChannelFuture f = b.connect(remoteHost, remotePort);
    outboundChannel = f.channel();/*from   w  w  w .  j a v a2  s. com*/

    f.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                // connection complete start to read first data
                inboundChannel.read();

            } else {
                // Close the connection if the connection attempt has failed.
                inboundChannel.close();
            }
        }
    });

}

From source file:com.tc.websocket.server.handler.WebSocketValidationHandler.java

License:Apache License

/**
 * Send http response./* w w w.j ava  2 s.  c  o m*/
 *
 * @param ctx the ctx
 * @param req the req
 * @param res the res
 */
private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // Generate an error page if response getStatus code is not OK (200).
    if (res.status().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);
        buf.release();
        HttpUtil.setContentLength(res, res.content().readableBytes());
    }

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

From source file:com.tesora.dve.parlb.MysqlClientHandler.java

License:Open Source License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    final Channel inboundChannel = ctx.channel();

    // Start the connection attempt.
    Bootstrap b = new Bootstrap();
    b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
            .handler(new LoadBalancerServerHandler(inboundChannel)).option(ChannelOption.AUTO_READ, false);
    ChannelFuture f = b.connect(peServerAddress);
    outboundChannel = f.channel();//from w  w w . j  a v  a  2  s . co  m
    f.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                // connection complete start to read first data
                inboundChannel.read();
            } else {
                // Close the connection if the connection attempt has failed.
                inboundChannel.close();
            }
        }
    });
}

From source file:com.test.AbstractBootstrap.java

License:Apache License

private ChannelFuture doBind(final SocketAddress localAddress) {
    final ChannelFuture regFuture = initAndRegister();
    final Channel channel = regFuture.channel();
    if (regFuture.cause() != null) {
        return regFuture;
    }/*from  w  ww.ja  v  a  2 s  . com*/

    if (regFuture.isDone()) {
        // At this point we know that the registration was complete and successful.
        ChannelPromise promise = channel.newPromise();
        doBind0(regFuture, channel, localAddress, promise);
        return promise;
    } else {
        // Registration future is almost always fulfilled already, but just in case it's not.
        final PendingRegistrationPromise promise = new PendingRegistrationPromise(channel);
        regFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                Throwable cause = future.cause();
                if (cause != null) {
                    // Registration on the EventLoop failed so fail the ChannelPromise directly to not cause an
                    // IllegalStateException once we try to access the EventLoop of the Channel.
                    promise.setFailure(cause);
                } else {
                    // Registration was successful, so set the correct executor to use.
                    // See https://github.com/netty/netty/issues/2586
                    promise.executor = channel.eventLoop();
                }
                doBind0(regFuture, channel, localAddress, promise);
            }
        });
        return promise;
    }
}