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:net.anyflow.lannister.packetreceiver.UnsubscribeReceiver.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, MqttUnsubscribeMessage msg) throws Exception {
    logger.debug("packet incoming [message={}]", msg.toString());

    Session session = Session.NEXUS.get(ctx.channel().id());
    if (session == null) {
        logger.error("None exist session message [message={}]", msg.toString());

        ctx.channel().disconnect().addListener(ChannelFutureListener.CLOSE).addListener(fs -> // [MQTT-4.8.0-1]
        Plugins.SELF.get(DisconnectEventListener.class).disconnected(new AbnormalDisconnectEventArgs()));
        return;//  www.j av a 2s . co  m
    }

    session.setLastIncomingTime(new Date());

    List<String> topicFilters = msg.payload().topics();

    if (topicFilters == null || topicFilters.isEmpty()) {
        session.dispose(true); // [MQTT-4.8.0-1]
        return;
    }

    topicFilters.stream().forEach(tf -> session.topicSubscriptions().remove(tf));

    Plugins.SELF.get(UnsubscribeEventListener.class).unsubscribed(new UnsubscribeEventArgs() {
        @Override
        public String clientId() {
            return session.clientId();
        }

        @Override
        public List<String> topicFilters() {
            return topicFilters;
        }
    });

    session.send(MessageFactory.unsuback(msg.variableHeader().messageId())); // [MQTT-2.3.1-7],[MQTT-3.10.4-4],[MQTT-3.10.4-5]
}

From source file:net.anyflow.lannister.session.Session.java

License:Apache License

public void dispose(boolean sendWill) {
    setConnected(false);/*w w w .j  ava 2 s  .co  m*/

    if (sendWill && will != null) { // [MQTT-3.1.2-12]
        Topic.NEXUS.publish(will);
        will(null); // [MQTT-3.1.2-10]
    }

    ChannelId channelId = null;
    ChannelHandlerContext ctx = NEXUS.channelHandlerContext(clientId);
    if (ctx != null) {
        ctx.channel().disconnect().addListener(ChannelFutureListener.CLOSE).addListener(fs -> Plugins.SELF
                .get(DisconnectEventListener.class).disconnected(new AbnormalDisconnectEventArgs()));

        channelId = ctx.channel().id();
    }

    logger.debug("Session disposed [clientId={}/channelId={}]", clientId, ctx == null ? "null" : channelId);

    NEXUS.remove(this);

    Plugins.SELF.get(DisconnectEventListener.class).disconnected(new DisconnectEventArgs() {
        @Override
        public String clientId() {
            return clientId;
        }

        @Override
        public Boolean cleanSession() {
            return cleanSession;
        }

        @Override
        public Boolean byDisconnectMessage() {
            return !sendWill;
        }
    });
}

From source file:net.anyflow.menton.http.HttpRequestRouter.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (HttpHeaderValues.WEBSOCKET.toString().equalsIgnoreCase(request.headers().get(HttpHeaderNames.UPGRADE))
            && HttpHeaderValues.UPGRADE.toString()
                    .equalsIgnoreCase(request.headers().get(HttpHeaderNames.CONNECTION))) {

        if (ctx.pipeline().get(WebsocketFrameHandler.class) == null) {
            logger.error("No WebSocket Handler available.");

            ctx.channel()//from   w ww. j av  a2  s  . c  o  m
                    .writeAndFlush(
                            new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN))
                    .addListener(ChannelFutureListener.CLOSE);
            return;
        }

        ctx.fireChannelRead(request.retain());
        return;
    }

    if (HttpUtil.is100ContinueExpected(request)) {
        ctx.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE));
        return;
    }

    HttpResponse response = HttpResponse.createServerDefault(request.headers().get(HttpHeaderNames.COOKIE));

    String requestPath = new URI(request.uri()).getPath();

    if (isWebResourcePath(requestPath)) {
        handleWebResourceRequest(ctx, request, response, requestPath);
    } else {
        try {
            processRequest(ctx, request, response);
        } catch (URISyntaxException e) {
            response.setStatus(HttpResponseStatus.NOT_FOUND);
            logger.info("unexcepted URI : {}", request.uri());
        } catch (Exception e) {
            response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
            logger.error("Unknown exception was thrown in business logic handler.\r\n" + e.getMessage(), e);
        }
    }
}

From source file:net.dongliu.prettypb.rpc.server.RequestHandler.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, WirePayload msg, List<Object> out) throws Exception {
    if (msg.hasConnectRequest()) {
        ConnectRequest connectRequest = msg.getConnectRequest();
        logger.info("Received ConnectRequest from {}:{}, use compress: {}.", connectRequest.getClientHostName(),
                connectRequest.getClientPort(), connectRequest.isCompress());
        PeerInfo clientInfo = new PeerInfo(connectRequest.getClientHostName(), connectRequest.getClientPort(),
                connectRequest.getClientPID());
        ConnectResponse connectResponse;

        RpcServerChannel rpcServerChannel = new RpcServerChannel(ctx.channel(), serverPeer, clientInfo,
                connectRequest.isCompress());
        if (rpcServerChannelRegistry.registerRpcServerChannel(rpcServerChannel)) {
            connectResponse = new ConnectResponse();
            connectResponse.setCorrelationId(connectRequest.getCorrelationId());
            connectResponse.setServerPID(serverPeer.getPid());
            connectResponse.setCompress(connectRequest.isCompress());
            WirePayload payload = new WirePayload();
            payload.setConnectResponse(connectResponse);
            ctx.channel().writeAndFlush(payload);

            completePipeline(rpcServerChannel);
        } else {//from w w  w.  j  a v  a  2  s  .c o m
            connectResponse = new ConnectResponse();
            connectResponse.setCorrelationId(connectRequest.getCorrelationId());
            connectResponse.setErrorCode(ConnectErrorCode.ALREADY_CONNECTED);
            WirePayload payload = new WirePayload();
            payload.setConnectResponse(connectResponse);

            logger.debug("Sending ConnectResponse({}). Already Connected.", connectResponse.getCorrelationId());
            ChannelFuture future = ctx.channel().writeAndFlush(payload);
            future.addListener(ChannelFutureListener.CLOSE); // close after write response.
        }
    } else {
        out.add(msg);
    }
}

From source file:net.hasor.rsf.console.TelnetHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, String request) throws Exception {
    request = request.trim();/*from w w w. ja v  a  2s. c om*/
    rxdLogger.info("RXD({})-> {}", ctx.channel().remoteAddress(), request);
    //
    Attribute<RsfCommandRequest> attr = ctx.attr(RequestKEY);
    boolean close = false;
    String result = "";
    boolean doRequest = false;
    if (StringUtils.isBlank(request)) {
        if (attr != null && attr.get() != null) {
            doRequest = true;
        }
    } else {
        doRequest = true;
    }
    //
    if (!doRequest) {
        logger.info("rsfConsole -> receive RXD :" + request);
    }
    //
    if (doRequest) {
        RsfCommandResponse response = this.doRequest(attr, ctx, request);
        if (response != null) {
            close = response.isCloseConnection();
            logger.info("rsfConsole -> receive RXD, response isComplete = {}, isCloseConnection = {}",
                    response.isComplete(), response.isCloseConnection());
            if (response.isComplete()) {
                result = response.getResult() + "\r\n" + CMD;
            } else {
                result = response.getResult() + "\r\n";
            }
        }
    } else {
        result = CMD;
    }
    //
    if (StringUtils.isNotBlank(result)) {
        rxdLogger.info("TXD({})-> {}", ctx.channel().remoteAddress(), result);
        ChannelFuture future = ctx.writeAndFlush(result);
        if (close) {
            logger.info("rsfConsole -> close connection.");
            future.addListener(ChannelFutureListener.CLOSE);
        }
    }
}

From source file:net.ieldor.network.session.impl.WorldListSession.java

License:Open Source License

@Override
public void message(Object obj) {
    WorldData[] worlds = {/*from   w  w  w  .  j a va 2 s. co  m*/
            new WorldData(1, "World 1", WorldData.FLAG_MEMBERS | WorldData.FLAG_QUICK_CHAT, Country.DEFAULT,
                    "Ieldor BETA", "127.0.0.1", ServerLocation.US_EAST_1),
            new WorldData(2, "World 2", WorldData.FLAG_MEMBERS | WorldData.FLAG_QUICK_CHAT, Country.DEFAULT,
                    "Ieldor BETA", "127.0.0.1", ServerLocation.US_EAST_2) };
    int[] players = { 0 };
    channel.write(new WorldListMessage(0xDEADBEEF, COUNTRIES, worlds, players))
            .addListener(ChannelFutureListener.CLOSE);
}

From source file:net.javaforge.netty.servlet.bridge.ServletBridgeHandler.java

License:Apache License

protected void handleHttpServletRequest(ChannelHandlerContext ctx, HttpRequest request, FilterChainImpl chain)
        throws Exception {

    interceptOnRequestReceived(ctx, request);

    DefaultFullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK);

    HttpServletResponseImpl resp = buildHttpServletResponse(response);
    HttpServletRequestImpl req = buildHttpServletRequest(request, chain);

    chain.doFilter(req, resp);//ww w.  j  a  va  2  s. c o  m

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

    // write response...
    ChannelFuture future = ctx.channel().writeAndFlush(response);

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

}

From source file:net.javaforge.netty.servlet.bridge.ServletBridgeHandler.java

License:Apache License

private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
    String text = "Failure: " + status.toString() + "\r\n";
    ByteBuf byteBuf = Unpooled.buffer();
    byte[] bytes = null;
    try {//from w ww  .j ava  2 s.  c  om
        bytes = text.getBytes("utf-8");
        byteBuf.writeBytes(bytes);
    } catch (UnsupportedEncodingException e) {
    }

    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, byteBuf);
    HttpHeaders headers = response.headers();

    headers.add(CONTENT_TYPE, "text/plain;charset=utf-8");
    headers.add(CACHE_CONTROL, "no-cache");
    headers.add(PRAGMA, "No-cache");
    headers.add(SERVER, "eBay Server");
    headers.add(CONTENT_LENGTH, byteBuf.readableBytes());
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}

From source file:net.mms_projects.copy_it.api.http.Handler.java

License:Open Source License

/**
 * Internal message handler, this is where all the http requests come in. This is where most of the authorization
 * and page logic goes on.//from   www .j a  v a  2 s. c o  m
 * @see net.mms_projects.copy_it.api.http.Page
 * @see net.mms_projects.copy_it.api.oauth.HeaderVerifier
 */
protected void messageReceived(final ChannelHandlerContext chx, final HttpObject o) throws Exception {
    if (o instanceof HttpRequest) {
        final HttpRequest http = (HttpRequest) o;
        this.request = http;
        final URI uri = new URI(request.getUri());
        if ((page = Page.getNoAuthPage(uri.getPath())) != null) {
            database = DatabasePool.getDBConnection();
            if (request.getMethod() == HttpMethod.GET) {
                try {
                    final FullHttpResponse response = page.onGetRequest(request, database);
                    HttpHeaders.setContentLength(response, response.content().readableBytes());
                    HttpHeaders.setHeader(response, CONTENT_TYPE, page.GetContentType());
                    if (isKeepAlive(request)) {
                        HttpHeaders.setKeepAlive(response, true);
                        chx.write(response);
                    } else
                        chx.write(response).addListener(ChannelFutureListener.CLOSE);
                } catch (ErrorException e) {
                    e.printStackTrace();
                    final FullHttpResponse response = new DefaultFullHttpResponse(request.getProtocolVersion(),
                            e.getStatus(), Unpooled.copiedBuffer(e.toString(), CharsetUtil.UTF_8));
                    HttpHeaders.setHeader(response, CONTENT_TYPE, Page.ContentTypes.JSON_TYPE);
                    chx.write(response).addListener(ChannelFutureListener.CLOSE);
                } catch (Exception e) {
                    e.printStackTrace();
                    final FullHttpResponse response = new DefaultFullHttpResponse(request.getProtocolVersion(),
                            INTERNAL_SERVER_ERROR);
                    chx.write(response).addListener(ChannelFutureListener.CLOSE);
                }
            } else if (request.getMethod() == HttpMethod.POST)
                postRequestDecoder = new HttpPostRequestDecoder(request);
        } else if ((page = Page.getAuthPage(uri.getPath())) == null) {
            final FullHttpResponse response = new DefaultFullHttpResponse(request.getProtocolVersion(),
                    NOT_FOUND, Unpooled.copiedBuffer("404", CharsetUtil.UTF_8));
            chx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            try {
                headerVerifier = new HeaderVerifier(http, uri);
                database = DatabasePool.getDBConnection();
                headerVerifier.verifyConsumer(database);
                headerVerifier.verifyOAuthToken(database);
                headerVerifier.verifyOAuthNonce(database);
                if (request.getMethod() == HttpMethod.GET) {
                    headerVerifier.checkSignature(null, false);
                    final FullHttpResponse response = ((AuthPage) page).onGetRequest(request, database,
                            headerVerifier);
                    HttpHeaders.setContentLength(response, response.content().readableBytes());
                    HttpHeaders.setHeader(response, CONTENT_TYPE, page.GetContentType());
                    if (isKeepAlive(request)) {
                        HttpHeaders.setKeepAlive(response, true);
                        chx.write(response);
                    } else
                        chx.write(response).addListener(ChannelFutureListener.CLOSE);
                } else if (request.getMethod() == HttpMethod.POST)
                    postRequestDecoder = new HttpPostRequestDecoder(request);
            } catch (ErrorException e) {
                e.printStackTrace();
                final FullHttpResponse response = new DefaultFullHttpResponse(request.getProtocolVersion(),
                        e.getStatus(), Unpooled.copiedBuffer(e.toString(), CharsetUtil.UTF_8));
                HttpHeaders.setHeader(response, CONTENT_TYPE, Page.ContentTypes.JSON_TYPE);
                chx.write(response).addListener(ChannelFutureListener.CLOSE);
            } catch (Exception e) {
                e.printStackTrace();
                final FullHttpResponse response = new DefaultFullHttpResponse(request.getProtocolVersion(),
                        INTERNAL_SERVER_ERROR);
                chx.write(response).addListener(ChannelFutureListener.CLOSE);
            }
        }
    } else if (o instanceof HttpContent && request != null && request.getMethod() == HttpMethod.POST) {
        final HttpContent httpContent = (HttpContent) o;
        postRequestDecoder.offer(httpContent);
        if (o instanceof LastHttpContent && page != null) {
            try {
                FullHttpResponse response;
                if (headerVerifier != null && page instanceof AuthPage) {
                    headerVerifier.checkSignature(postRequestDecoder, false);
                    response = ((AuthPage) page).onPostRequest(request, postRequestDecoder, database,
                            headerVerifier);
                } else
                    response = page.onPostRequest(request, postRequestDecoder, database);
                HttpHeaders.setContentLength(response, response.content().readableBytes());
                HttpHeaders.setHeader(response, CONTENT_TYPE, page.GetContentType());
                if (isKeepAlive(request)) {
                    HttpHeaders.setKeepAlive(response, true);
                    chx.write(response);
                } else
                    chx.write(response).addListener(ChannelFutureListener.CLOSE);
            } catch (ErrorException e) {
                e.printStackTrace();
                final FullHttpResponse response = new DefaultFullHttpResponse(request.getProtocolVersion(),
                        e.getStatus(), Unpooled.copiedBuffer(e.toString(), CharsetUtil.UTF_8));
                HttpHeaders.setHeader(response, CONTENT_TYPE, Page.ContentTypes.JSON_TYPE);
                chx.write(response).addListener(ChannelFutureListener.CLOSE);
            } catch (Exception e) {
                e.printStackTrace();
                final FullHttpResponse response = new DefaultFullHttpResponse(request.getProtocolVersion(),
                        INTERNAL_SERVER_ERROR);
                chx.write(response).addListener(ChannelFutureListener.CLOSE);
            }
        }
    }
    if (o instanceof LastHttpContent && database != null)
        database.free();
}

From source file:net.NettyEngine4.file.HttpStaticFileServerHandler.java

License:Apache License

/**
 * <strong>Please keep in mind that this method will be renamed to
 * {@code messageReceived(ChannelHandlerContext, I)} in 5.0.</strong>
 * <p/>//from  ww w . ja  v  a2 s.c o m
 * Is called for each message of type {@link SimpleChannelInboundHandler#channelRead0(io.netty.channel.ChannelHandlerContext, Object)}.
 *
 * @param ctx     the {@link ChannelHandlerContext} which this {@link SimpleChannelInboundHandler}
 *                belongs to
 * @param request the message to handle
 * @throws Exception is thrown if an error occurred
 */
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {

    if (!request.getDecoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);
        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;
    if (ctx.pipeline().get(SslHandler.class) == null) {
        sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength),
                ctx.newProgressivePromise());
    } else {
        sendFileFuture = ctx.write(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)),
                ctx.newProgressivePromise());
    }

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

        @Override
        public void operationComplete(ChannelProgressiveFuture future) {
            LOGGER.debug(future.channel() + " Transfer complete.");
        }
    });

    // Write the end marker
    ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);

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