Example usage for io.netty.channel ChannelFutureListener CLOSE

List of usage examples for io.netty.channel ChannelFutureListener CLOSE

Introduction

In this page you can find the example usage for io.netty.channel ChannelFutureListener CLOSE.

Prototype

ChannelFutureListener CLOSE

To view the source code for io.netty.channel ChannelFutureListener CLOSE.

Click Source Link

Document

A ChannelFutureListener that closes the Channel which is associated with the specified ChannelFuture .

Usage

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

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    // // w w  w  . j  av  a 2 s.  com
    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   w  w w. j a  va  2s  .co  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.ResourceHandler.java

License:Apache License

private void sendNotModified(ChannelHandlerContext ctx) {
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_MODIFIED);
    setDateHeader(response);/*  w w w  . jav a 2  s . c  o m*/

    // Close the connection as soon as the error message is sent.
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}

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

License:Apache License

/**
 * Sends an Error response with status message
 *
 * @param ctx channel context/*  w  ww .  jav a2s. c om*/
 * @param status status
 */
private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status);
    HttpHeaders.setHeader(response, HttpHeaders.Names.CONTENT_TYPE, "text/plain; charset=UTF-8");
    ByteBuf content = Unpooled.copiedBuffer("Failure: " + status.toString() + "\r\n", CharsetUtil.UTF_8);

    ctx.write(response);
    // Close the connection as soon as the error message is sent.
    ctx.writeAndFlush(content).addListener(ChannelFutureListener.CLOSE);
}

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());/*from w w  w. j  ava  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 sendResponse(ChannelHandlerContext ctx, Response response) throws Exception {
    HttpResponseStatus responseStatus = null;
    switch (response.getCode()) {
    case INTERNAL_ERROR:
        responseStatus = HttpResponseStatus.INTERNAL_SERVER_ERROR;
        break;//  w w  w. j  a  v a  2  s.  co m
    case NOT_FOUND:
        responseStatus = HttpResponseStatus.NOT_FOUND;
        break;
    case PERMANENT_REDIRECT:
        responseStatus = HttpResponseStatus.MOVED_PERMANENTLY;
        break;
    case TEMPORARY_REDIRECT:
        responseStatus = HttpResponseStatus.FOUND;
        break;
    default:
        responseStatus = HttpResponseStatus.OK;
        break;
    }

    ByteArrayOutputStream bos = (ByteArrayOutputStream) response.getOutputStream();
    ByteBuf buf = copiedBuffer(bos.toByteArray());

    // Build the response object.
    FullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, responseStatus, buf);

    httpResponse.headers().set(HttpHeaderNames.SERVER, "Sync-AS");
    // default content-type header... likely to be overwritten by the Result Content-Type header...
    httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=" + charset);
    httpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
    httpResponse.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, buf.readableBytes());

    //
    // 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 response.
    ctx.channel().writeAndFlush(httpResponse).addListener(ChannelFutureListener.CLOSE);
    reset();

    return true;
}

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 ww.  ja v a 2s. c o  m

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

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

License:Apache License

private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status,
            Unpooled.copiedBuffer("Failure: " + status + "\r\n", CharsetUtil.UTF_8));
    response.headers().set(CONTENT_TYPE, "text/plain; charset=" + charset);
    // Close the connection as soon as the error message is sent.
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    reset();/*  ww w  .j  av  a2 s.  co  m*/
}

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

License:Apache License

private void sendException(ChannelHandlerContext ctx, Exception e) {
    if (log.isTraceEnabled())
        log.trace("delivering exception message to the client");

    StringBuilder sb = new StringBuilder();
    sb.append("<html><head><title>Error</title></head>");
    sb.append("<style>");
    sb.append(//from w w  w. j  av  a2 s .c  o m
            "body { font-size: 13px; font-family: \"Helvetica Neue\",Helvetica,Arial,\"Lucida Grande\",sans-serif; }\n");
    sb.append("ul { list-style-type: none }\n");
    sb.append(
            ".code { margin: 10px 0px 10px 0px; padding: 10px; border: 1px solid #c0c0c0; background: #f0f000 }\n");
    sb.append("</style>");
    sb.append("<body>");

    if (e instanceof ControllerBeanException) {
        ControllerBeanException cbe = (ControllerBeanException) e;
        sb.append("Exception caught while executing @Controller ").append(cbe.getController())
                .append("<br/>\n");
        sb.append("<div class=\"code\">");
        sb.append(ExceptionUtils.printStackTraceHtml(e));
        sb.append("</div>");
        log.error("Exception caught while executing @Controller {}", cbe.getController());
        log.error(ExceptionUtils.printStackTrace(e));
    } else if (e instanceof InterceptorBeanException) {
        InterceptorBeanException ibe = (InterceptorBeanException) e;
        sb.append("Exception caught while executing @Interceptor ").append(ibe.getInterceptor())
                .append("<br/>\n");
        sb.append("<div class=\"code\">");
        sb.append(ExceptionUtils.printStackTraceHtml(e));
        sb.append("</div>");
        log.error("Exception caught while executing @Interceptor {}", ibe.getInterceptor());
        log.error(ExceptionUtils.printStackTrace(e));
    } else {
        sb.append("Exception caught while executing request<br/>\n");
        sb.append("<div class=\"code\">");
        sb.append(ExceptionUtils.printStackTraceHtml(e));
        sb.append("</div>");
        log.error(ExceptionUtils.printStackTrace(e));
    }
    sb.append("</body></html>");

    ByteBuf buf = copiedBuffer(sb.toString().getBytes());

    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR,
            buf);
    response.headers().set(CONTENT_TYPE, "text/html; charset=" + charset);

    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    reset();
}