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:com.company.product.test.http.HttpServerHandler.java

License:Apache License

protected void messageReceived(ChannelHandlerContext ctx, Object msg) {
    FullHttpResponse response = null;/*from w w  w .  j av a2 s. c  o  m*/
    try {
        if (msg instanceof HttpRequest) {
            HttpRequest request = (HttpRequest) msg;

            QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri());
            Map<String, List<String>> params = queryStringDecoder.parameters();
            validateQueryString(params);
            compileAndSendMessage(params);

            // no need to provide a response, we did what was expected of us.
            response = new DefaultFullHttpResponse(HTTP_1_1, NO_CONTENT);
        }
    } catch (IllegalArgumentException iae) {
        response = new DefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR);
        throw iae;
    } catch (InvalidTopicException ite) {
        response = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST);
        throw ite;
    } finally {
        ctx.write(response);
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
        ReferenceCountUtil.release(msg);
    }
}

From source file:com.corundumstudio.socketio.handler.AuthorizeHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    SchedulerKey key = new SchedulerKey(Type.PING_TIMEOUT, ctx.channel());
    disconnectScheduler.cancel(key);/*  w  w  w.  j  av a 2s .  c  om*/

    if (msg instanceof FullHttpRequest) {
        FullHttpRequest req = (FullHttpRequest) msg;
        Channel channel = ctx.channel();
        QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri());

        if (!configuration.isAllowCustomRequests() && !queryDecoder.path().startsWith(connectPath)) {
            HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.BAD_REQUEST);
            channel.writeAndFlush(res).addListener(ChannelFutureListener.CLOSE);
            req.release();
            log.warn("Blocked wrong request! url: {}, ip: {}", queryDecoder.path(), channel.remoteAddress());
            return;
        }

        List<String> sid = queryDecoder.parameters().get("sid");
        if (queryDecoder.path().equals(connectPath) && sid == null) {
            String origin = req.headers().get(HttpHeaders.Names.ORIGIN);
            if (!authorize(ctx, channel, origin, queryDecoder.parameters(), req)) {
                req.release();
                return;
            }
            // forward message to polling or websocket handler to bind channel
        }
    }
    ctx.fireChannelRead(msg);
}

From source file:com.corundumstudio.socketio.handler.AuthorizeHandler.java

License:Apache License

private boolean authorize(ChannelHandlerContext ctx, Channel channel, String origin,
        Map<String, List<String>> params, FullHttpRequest req) throws IOException {
    Map<String, List<String>> headers = new HashMap<String, List<String>>(req.headers().names().size());
    for (String name : req.headers().names()) {
        List<String> values = req.headers().getAll(name);
        headers.put(name, values);/*from w w w  .  jav  a2  s. c o  m*/
    }

    HandshakeData data = new HandshakeData(headers, params, (InetSocketAddress) channel.remoteAddress(),
            req.getUri(), origin != null && !origin.equalsIgnoreCase("null"));

    boolean result = false;
    try {
        result = configuration.getAuthorizationListener().isAuthorized(data);
    } catch (Exception e) {
        log.error("Authorization error", e);
    }

    if (!result) {
        HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.UNAUTHORIZED);
        channel.writeAndFlush(res).addListener(ChannelFutureListener.CLOSE);
        log.debug("Handshake unauthorized, query params: {} headers: {}", params, headers);
        return false;
    }

    UUID sessionId = this.generateOrGetSessionIdFromRequest(headers);

    List<String> transportValue = params.get("transport");
    if (transportValue == null) {
        log.warn("Got no transports for request {}", req.getUri());

        HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.UNAUTHORIZED);
        channel.writeAndFlush(res).addListener(ChannelFutureListener.CLOSE);
        return false;
    }

    Transport transport = Transport.byName(transportValue.get(0));
    ClientHead client = new ClientHead(sessionId, ackManager, disconnectable, storeFactory, data, clientsBox,
            transport, disconnectScheduler, configuration);
    channel.attr(ClientHead.CLIENT).set(client);
    clientsBox.addClient(client);

    String[] transports = {};
    if (configuration.getTransports().contains(Transport.WEBSOCKET)) {
        transports = new String[] { "websocket" };
    }

    AuthPacket authPacket = new AuthPacket(sessionId, transports, configuration.getPingInterval(),
            configuration.getPingTimeout());
    Packet packet = new Packet(PacketType.OPEN);
    packet.setData(authPacket);
    client.send(packet);

    client.schedulePingTimeout();
    log.debug("Handshake authorized for sessionId: {}, query params: {} headers: {}", sessionId, params,
            headers);
    return true;
}

From source file:com.corundumstudio.socketio.handler.ClientHead.java

License:Apache License

public void disconnect() {
    ChannelFuture future = send(new Packet(PacketType.DISCONNECT));
    future.addListener(ChannelFutureListener.CLOSE);

    onChannelDisconnect();
}

From source file:com.corundumstudio.socketio.handler.EncoderHandler.java

License:Apache License

private void sendMessage(HttpMessage msg, Channel channel, ByteBuf out, HttpResponse res) {
    channel.write(res);// w w  w . java  2  s .  c o m

    if (log.isTraceEnabled()) {
        log.trace("Out message: {} - sessionId: {}", out.toString(CharsetUtil.UTF_8), msg.getSessionId());
    }

    if (out.isReadable()) {
        channel.write(out);
    } else {
        out.release();
    }

    channel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT).addListener(ChannelFutureListener.CLOSE);
}

From source file:com.corundumstudio.socketio.handler.ResourceHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof FullHttpRequest) {
        FullHttpRequest req = (FullHttpRequest) msg;
        QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri());
        URL resUrl = resources.get(queryDecoder.path());
        if (resUrl != null) {
            URLConnection fileUrl = resUrl.openConnection();
            long lastModified = fileUrl.getLastModified();
            // check if file has been modified since last request
            if (isNotModified(req, lastModified)) {
                sendNotModified(ctx);//from  w w w  .  j a v a  2s . c  o  m
                req.release();
                return;
            }
            // create resource input-stream and check existence
            final InputStream is = fileUrl.getInputStream();
            if (is == null) {
                sendError(ctx, NOT_FOUND);
                return;
            }
            // create ok response
            HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK);
            // set Content-Length header
            setContentLength(res, fileUrl.getContentLength());
            // 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(SocketIOChannelInitializer.RESOURCE_HANDLER, "chunkedWriter",
                    new ChunkedWriteHandler());
            ChannelFuture writeFuture = ctx.channel().write(new ChunkedStream(is, fileUrl.getContentLength()));
            // add operation complete listener so we can close the channel and the input stream
            writeFuture.addListener(ChannelFutureListener.CLOSE);
            return;
        }
    }
    ctx.fireChannelRead(msg);
}

From source file:com.corundumstudio.socketio.handler.ResourceHandler.java

License:Apache License

private void sendNotModified(ChannelHandlerContext ctx) {
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.NOT_MODIFIED);
    setDateHeader(response);//from   w  ww .  ja v  a  2 s . c om

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

From source file:com.corundumstudio.socketio.handler.ResourceHandler.java

License:Apache License

/**
 * Sends an Error response with status message
 *
 * @param ctx//  ww w .  j  a  v  a 2  s .  co m
 * @param status
 */
private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);
    HttpHeaders.setHeader(response, CONTENT_TYPE, "text/plain; charset=UTF-8");
    ByteBuf content = Unpooled.copiedBuffer("Failure: " + status.toString() + "\r\n", CharsetUtil.UTF_8);

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

From source file:com.corundumstudio.socketio.handler.WrongUrlHandler.java

License:Apache License

public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof FullHttpRequest) {
        FullHttpRequest req = (FullHttpRequest) msg;
        Channel channel = ctx.channel();
        QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri());

        HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.BAD_REQUEST);
        ChannelFuture f = channel.writeAndFlush(res);
        f.addListener(ChannelFutureListener.CLOSE);
        req.release();/*from   ww  w.ja  v  a  2 s.com*/
        log.warn("Blocked wrong socket.io-context request! url: {}, params: {}, ip: {}", queryDecoder.path(),
                queryDecoder.parameters(), channel.remoteAddress());
    }
}

From source file:com.corundumstudio.socketio.SocketIOEncoder.java

License:Apache License

private void sendMessage(HttpMessage msg, Channel channel, ByteBuf out) {
    HttpResponse res = createHttpResponse(msg.getOrigin(), out);
    channel.write(res);/*from   w w  w. j a  va  2s  .com*/

    if (log.isTraceEnabled()) {
        log.trace("Out message: {} - sessionId: {}", out.toString(CharsetUtil.UTF_8), msg.getSessionId());
    }
    if (out.isReadable()) {
        channel.write(out);
    } else {
        out.release();
    }

    ChannelFuture f = channel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    f.addListener(ChannelFutureListener.CLOSE);
}