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:io.reactivex.netty.protocol.http.client.ClientRequestResponseConverter.java

License:Apache License

private void addWriteCompleteEvents(ChannelFuture future, final long startTimeMillis,
        final HttpClientMetricsEvent<HttpClientMetricsEvent.EventType> successEvent,
        final HttpClientMetricsEvent<HttpClientMetricsEvent.EventType> failureEvent) {
    future.addListener(new ChannelFutureListener() {
        @Override/*from  w  ww  . j  a  v a  2 s  . c o m*/
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                eventsSubject.onEvent(successEvent, Clock.onEndMillis(startTimeMillis));
            } else {
                eventsSubject.onEvent(failureEvent, Clock.onEndMillis(startTimeMillis), future.cause());
            }
        }
    });
}

From source file:io.reactivex.netty.protocol.http.MultipleFutureListener.java

License:Apache License

public void listen(ChannelFuture future) {
    pendingFutures.add(future);
    listeningToCount.incrementAndGet();
    future.addListener(this);
}

From source file:io.reactivex.netty.protocol.http.websocket.WebSocketServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof FullHttpRequest) {
        ChannelFuture upgradeFuture = handleHttpRequest(ctx, (FullHttpRequest) msg);
        if (upgradeFuture != null) {
            updatePipeline(ctx);//from   w  w  w .  j  av  a2s.co m
            upgradeFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        handshakeFuture.setSuccess();
                        eventsSubject.onEvent(WebSocketServerMetricsEvent.HANDSHAKE_PROCESSED);
                    } else {
                        handshakeFuture.setFailure(future.cause());
                        eventsSubject.onEvent(WebSocketServerMetricsEvent.HANDSHAKE_FAILURE);
                    }
                }
            });
        }
    } else {
        ctx.fireChannelRead(msg);
    }
}

From source file:io.riox.springxd.sinks.websocket.NettyWebSocketServerHandler.java

License:Apache License

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);/*  w  w  w .jav a 2  s .com*/
        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:io.scalecube.socketio.pipeline.FlashPolicyHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    // ?/*from  ww w  .ja va2 s. com*/
    if (msg instanceof ByteBuf) {
        ByteBuf message = (ByteBuf) msg;
        if (message.readableBytes() >= policyRequestBuffer.readableBytes()) {
            ByteBuf data = message.slice(0, policyRequestBuffer.readableBytes());
            if (data.equals(policyRequestBuffer)) {
                // Remove SSL handler from pipeline otherwise on channel close SSL handler
                // will fail all pending writes instead of flushing them and as a result
                // client won't get flash policy file.
                if (ctx.pipeline().get(SocketIOChannelInitializer.SSL_HANDLER) != null) {
                    ctx.pipeline().remove(SocketIOChannelInitializer.SSL_HANDLER);
                }

                // Send flash policy file and close connection
                ByteBuf response = PipelineUtils.copiedBuffer(ctx.alloc(), policyResponse);
                ChannelFuture f = ctx.writeAndFlush(response);
                f.addListener(ChannelFutureListener.CLOSE);
                if (log.isDebugEnabled())
                    log.debug("Sent flash policy file to channel: {}", ctx.channel());
                message.release();
                return;
            }
        }
        ctx.pipeline().remove(this);
    }
    ctx.fireChannelRead(msg);
}

From source file:io.scalecube.socketio.pipeline.HandshakeHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    // //  w  ww . j a  v a  2s .c o  m
    if (msg instanceof HttpRequest) {
        final HttpRequest req = (HttpRequest) msg;
        final HttpMethod requestMethod = req.getMethod();
        final QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri());
        final String requestPath = queryDecoder.path();

        if (!requestPath.startsWith(handshakePath)) {
            log.warn("Received HTTP bad request: {} {} from channel: {}", requestMethod, requestPath,
                    ctx.channel());

            HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.BAD_REQUEST);
            ChannelFuture f = ctx.channel().writeAndFlush(res);
            f.addListener(ChannelFutureListener.CLOSE);
            ReferenceCountUtil.release(req);
            return;
        }

        if (HttpMethod.GET.equals(requestMethod) && requestPath.equals(handshakePath)) {
            if (log.isDebugEnabled())
                log.debug("Received HTTP handshake request: {} {} from channel: {}", requestMethod, requestPath,
                        ctx.channel());

            handshake(ctx, req, queryDecoder);
            ReferenceCountUtil.release(req);
            return;
        }
    }

    super.channelRead(ctx, msg);
}

From source file:io.scalecube.socketio.pipeline.HandshakeHandler.java

License:Apache License

private void handshake(final ChannelHandlerContext ctx, final HttpRequest req,
        final QueryStringDecoder queryDecoder) throws IOException {
    // Generate session ID
    final String sessionId = UUID.randomUUID().toString();
    if (log.isDebugEnabled())
        log.debug("New sessionId: {} generated", sessionId);

    // Send handshake response
    final String handshakeMessage = getHandshakeMessage(sessionId, queryDecoder);

    ByteBuf content = PipelineUtils.copiedBuffer(ctx.alloc(), handshakeMessage);
    HttpResponse res = PipelineUtils.createHttpResponse(PipelineUtils.getOrigin(req), content, false);
    ChannelFuture f = ctx.writeAndFlush(res);
    f.addListener(ChannelFutureListener.CLOSE);
    if (log.isDebugEnabled())
        log.debug("Sent handshake response: {} to channel: {}", handshakeMessage, ctx.channel());
}

From source file:io.scalecube.socketio.pipeline.ResourceHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    // ?/*from  ww w.  j a  v  a  2s.c  o m*/
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;
        QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri());
        String requestPath = queryDecoder.path();
        URL resUrl = resources.get(requestPath);
        if (resUrl != null) {
            if (log.isDebugEnabled())
                log.debug("Received HTTP resource request: {} {} from channel: {}", req.getMethod(),
                        requestPath, ctx.channel());

            URLConnection fileUrl = resUrl.openConnection();
            long lastModified = fileUrl.getLastModified();
            // check if file has been modified since last request
            if (isNotModified(req, lastModified)) {
                sendNotModified(ctx);
                return;
            }
            // create resource input-stream and check existence
            final InputStream is = fileUrl.getInputStream();
            if (is == null) {
                sendError(ctx, HttpResponseStatus.NOT_FOUND);
                return;
            }
            // create ok response
            HttpResponse res = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
            // set Content-Length header
            HttpHeaders.setContentLength(res, fileUrl.getContentLengthLong());
            // set Content-Type header
            setContentTypeHeader(res, fileUrl);
            // set Date, Expires, Cache-Control and Last-Modified headers
            setDateAndCacheHeaders(res, lastModified);
            // write initial response header
            ctx.write(res);

            // write the content stream
            ctx.pipeline().addBefore(ctx.name(), "chunked-writer-handler", new ChunkedWriteHandler());
            ChannelFuture writeFuture = ctx.writeAndFlush(new ChunkedStream(is, fileUrl.getContentLength()));
            // add operation complete listener so we can close the channel and the input stream
            writeFuture.addListener(ChannelFutureListener.CLOSE);
            ReferenceCountUtil.release(msg);
            return;
        }
    }
    super.channelRead(ctx, msg);
}

From source file:io.scalecube.socketio.pipeline.WebSocketHandler.java

License:Apache License

private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame msg) throws Exception {
    if (log.isDebugEnabled())
        log.debug("Received {} WebSocketFrame: {} from channel: {}", getTransportType().getName(), msg,
                ctx.channel());/*  ww w  .  j av a 2 s  .c  o  m*/

    if (msg instanceof CloseWebSocketFrame) {
        sessionIdByChannel.remove(ctx.channel());
        ChannelFuture f = ctx.writeAndFlush(msg);
        f.addListener(ChannelFutureListener.CLOSE);
        return;
    } else if (msg instanceof PingWebSocketFrame) {
        ctx.writeAndFlush(new PongWebSocketFrame(msg.content()));
        return;
    } else if (!(msg instanceof TextWebSocketFrame)) {
        msg.release();
        log.warn(String.format("%s frame types not supported", msg.getClass().getName()));
        return;
    }

    TextWebSocketFrame frame = (TextWebSocketFrame) msg;
    Packet packet = PacketDecoder.decodePacket(frame.content());
    packet.setTransportType(getTransportType());
    String sessionId = sessionIdByChannel.get(ctx.channel());
    packet.setSessionId(sessionId);
    msg.release();
    ctx.fireChannelRead(packet);
}

From source file:io.syncframework.netty.RequestHandler.java

License:Apache License

private boolean sendFile(ChannelHandlerContext ctx, Response response) throws Exception {
    Application application = response.getApplication();
    if (application == null) {
        log.error("no response.application has been set");
        sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR);
        return true;
    }/*from  w  w  w.ja v a 2s.  com*/

    File file = response.getFile();
    if (file == null) {
        log.error("no response.file has been set");
        sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR);
        return true;
    }

    if (!file.exists()) {
        // file not found try request dynamically
        if (log.isDebugEnabled())
            log.debug("{}: file not found: {}", application, file);
        return false;
    }
    if (file.isHidden()) {
        if (log.isDebugEnabled()) {
            log.debug("{}: file {} is hidden; returning File Not Found", application, file.getAbsolutePath());
        }
        sendFileNotFound(ctx);
        return true;
    }
    if (file.isDirectory()) {
        // once is a directory a dynamic handler can take it ...
        // even if a index.html, the @Action Controller.main() shall handle it
        return false;
    }
    //
    // Check if the file resides under the PUBLIC or PRIVATE folders. 
    // More important point for this verification is with PUBLIC requests where multiples ../../../..
    // may lead to security breach - exposing unwanted system files.
    //
    String path = file.getAbsolutePath();
    if (!path.startsWith(application.getConfig().getPublicDirectory().getAbsolutePath())
            && !path.startsWith(application.getConfig().getPrivateDirectory().getAbsolutePath())) {
        log.error("{}: file {} returned, is not located under Public or Private folders", application,
                file.getAbsolutePath());
        sendError(ctx, HttpResponseStatus.FORBIDDEN);
        return true;
    }
    if (!file.isFile()) {
        sendError(ctx, HttpResponseStatus.FORBIDDEN);
        return true;
    }

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

    if (log.isTraceEnabled())
        log.trace("{}: returning file: {}", application, file);

    HttpResponse httpResponse = new DefaultHttpResponse(HTTP_1_1, OK);
    HttpUtil.setContentLength(httpResponse, fileLength);
    httpResponse.headers().set(CONTENT_TYPE, MimeUtils.getContentType(file));
    setDateAndCacheHeaders(httpResponse, file);
    httpResponse.headers().set(CONNECTION, HttpHeaderValues.CLOSE);
    //
    // if response has declared specific Headers, then this may or may not override the default headers
    // declared above.
    //
    if (response.getHeaders() != null) {
        if (log.isTraceEnabled())
            log.trace("custom response headers identified... passing to the response");
        for (String header : response.getHeaders().keySet()) {
            if (log.isTraceEnabled())
                log.trace("setting response header: {}: {}", header, response.getHeaders().get(header));
            httpResponse.headers().set(header, response.getHeaders().get(header));
        }
    }

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

    // Write the content.
    ChannelFuture sendFileFuture;
    ChannelFuture lastContentFuture;

    sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength),
            ctx.newProgressivePromise());
    lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);

    sendFileFuture.addListener(new ChannelProgressiveFutureListener() {
        @Override
        public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) {
            if (total < 0) { // total unknown
                if (log.isTraceEnabled())
                    log.trace("{}: " + future.channel() + " transfer progress: " + progress, application);
            } else {
                if (log.isTraceEnabled())
                    log.trace("{}: " + future.channel() + " Transfer progress: " + progress + " / " + total,
                            application);
            }
        }

        @Override
        public void operationComplete(ChannelProgressiveFuture future) {
            if (log.isTraceEnabled())
                log.trace("{}: " + future.channel() + " transfer complete.", application);
            if (raf != null) {
                try {
                    raf.close();
                } catch (Exception ignore) {
                    if (log.isTraceEnabled())
                        log.trace("exception caught: {}", ignore);
                }
            }
        }
    });

    // Close the connection when the whole content is written out.
    ctx.flush();
    lastContentFuture.addListener(ChannelFutureListener.CLOSE);

    return true;
}