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.l2jmobius.gameserver.network.telnet.TelnetServerHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    // Cast to a String first.
    // We know it is a String because we put some codec in TelnetPipelineFactory.
    String request = (String) msg;

    // Generate and write a response.
    String response = null;//from   w ww.  ja  va  2  s  .c  o m
    boolean close = false;

    if (Boolean.FALSE.equals(ctx.attr(AUTHORIZED).get())) {
        if (Config.TELNET_PASSWORD.equals(request)) {
            ctx.attr(AUTHORIZED).set(Boolean.TRUE);
            request = "";
        } else {
            response = "Wrong password!" + Config.EOL;
            close = true;
        }
    }

    if (Boolean.TRUE.equals(ctx.attr(AUTHORIZED).get())) {
        if (request.isEmpty()) {
            response = "Type 'help' to see all available commands." + Config.EOL;
        } else if (request.toLowerCase().equals("exit")) {
            response = "Have a good day!" + Config.EOL;
            close = true;
        } else {
            final Matcher m = COMMAND_ARGS_PATTERN.matcher(request);

            if (m.find()) {
                final String command = m.group();
                final List<String> args = new ArrayList<>();
                String arg;

                while (m.find()) {
                    arg = m.group(1);

                    if (arg == null) {
                        arg = m.group(0);
                    }

                    args.add(arg);
                }

                response = tryHandleCommand(ctx, command, args.toArray(new String[args.size()]));
                if (!response.endsWith(Config.EOL)) {
                    response += Config.EOL;
                }
            }
        }
    }

    // We do not need to write a ChannelBuffer here.
    // We know the encoder inserted at TelnetPipelineFactory will do the conversion.
    final ChannelFuture future = ctx.write(response);

    // Close the connection after sending 'Have a good day!'
    // if the client has sent 'exit'.
    if (close) {
        future.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.leadtone.riders.server.RidersWebSocketServerHandler.java

License:Apache License

private static 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) {
        res.content().writeBytes(Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8));
        setContentLength(res, res.content().readableBytes());
    }//from w  ww.  j a  v a2 s  .  c o m

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

From source file:com.liferay.sync.engine.lan.server.file.LanFileServerHandler.java

License:Open Source License

protected void sendFile(final ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest,
        SyncFile syncFile) throws Exception {

    Path path = Paths.get(syncFile.getFilePathName());

    if (Files.notExists(path)) {
        _syncTrafficShapingHandler.decrementConnectionsCount();

        if (_logger.isTraceEnabled()) {
            Channel channel = channelHandlerContext.channel();

            _logger.trace("Client {}: file not found {}", channel.remoteAddress(), path);
        }//from  w w w . java 2  s. c o  m

        _sendError(channelHandlerContext, NOT_FOUND);

        return;
    }

    if (_logger.isDebugEnabled()) {
        Channel channel = channelHandlerContext.channel();

        _logger.debug("Client {}: sending file {}", channel.remoteAddress(), path);
    }

    long modifiedTime = syncFile.getModifiedTime();
    long previousModifiedTime = syncFile.getPreviousModifiedTime();

    if (OSDetector.isApple()) {
        modifiedTime = modifiedTime / 1000 * 1000;
        previousModifiedTime = previousModifiedTime / 1000 * 1000;
    }

    FileTime currentFileTime = Files.getLastModifiedTime(path, LinkOption.NOFOLLOW_LINKS);

    long currentTime = currentFileTime.toMillis();

    if ((currentTime != modifiedTime) && (currentTime != previousModifiedTime)) {

        _syncTrafficShapingHandler.decrementConnectionsCount();

        Channel channel = channelHandlerContext.channel();

        _logger.error(
                "Client {}: file modified {}, currentTime {}, modifiedTime " + "{}, previousModifiedTime {}",
                channel.remoteAddress(), path, currentTime, modifiedTime, previousModifiedTime);

        _sendError(channelHandlerContext, NOT_FOUND);

        return;
    }

    HttpResponse httpResponse = new DefaultHttpResponse(HTTP_1_1, OK);

    long size = Files.size(path);

    HttpUtil.setContentLength(httpResponse, size);

    HttpHeaders httpHeaders = httpResponse.headers();

    MimetypesFileTypeMap mimetypesFileTypeMap = new MimetypesFileTypeMap();

    httpHeaders.set(HttpHeaderNames.CONTENT_TYPE, mimetypesFileTypeMap.getContentType(syncFile.getName()));

    if (HttpUtil.isKeepAlive(fullHttpRequest)) {
        httpHeaders.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }

    channelHandlerContext.write(httpResponse);

    SyncChunkedFile syncChunkedFile = new SyncChunkedFile(path, size, 4 * 1024 * 1024, currentTime);

    ChannelFuture channelFuture = channelHandlerContext.writeAndFlush(new HttpChunkedInput(syncChunkedFile),
            channelHandlerContext.newProgressivePromise());

    channelFuture.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture channelFuture) throws Exception {

            _syncTrafficShapingHandler.decrementConnectionsCount();

            if (channelFuture.isSuccess()) {
                return;
            }

            Throwable exception = channelFuture.cause();

            Channel channel = channelHandlerContext.channel();

            _logger.error("Client {}: {}", channel.remoteAddress(), exception.getMessage(), exception);

            channelHandlerContext.close();
        }

    });

    if (!HttpUtil.isKeepAlive(fullHttpRequest)) {
        channelFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.liferay.sync.engine.lan.server.file.LanFileServerHandler.java

License:Open Source License

private void _sendError(ChannelHandlerContext channelHandlerContext, HttpResponseStatus httpResponseStatus) {

    ChannelFuture channelFuture = channelHandlerContext
            .writeAndFlush(new DefaultFullHttpResponse(HTTP_1_1, httpResponseStatus));

    channelFuture.addListener(ChannelFutureListener.CLOSE);
}

From source file:com.linecorp.armeria.internal.http.Http1ObjectEncoder.java

License:Apache License

@Override
protected ChannelFuture doWriteReset(ChannelHandlerContext ctx, int id, int streamId, Http2Error error) {
    // NB: this.minClosedId can be overwritten more than once when 3+ pipelined requests are received
    //     and they are handled by different threads simultaneously.
    //     e.g. when the 3rd request triggers a reset and then the 2nd one triggers another.
    minClosedId = Math.min(minClosedId, id);
    for (int i = minClosedId; i <= maxIdWithPendingWrites; i++) {
        final PendingWrites pendingWrites = this.pendingWrites.remove(i);
        for (;;) {
            final Entry<HttpObject, ChannelPromise> e = pendingWrites.poll();
            if (e == null) {
                break;
            }/*from  w w  w  . jav a 2s. c  om*/
            e.getValue().tryFailure(ClosedSessionException.get());
        }
    }

    final ChannelFuture f = ctx.write(Unpooled.EMPTY_BUFFER);
    if (currentId >= minClosedId) {
        f.addListener(ChannelFutureListener.CLOSE);
    }

    return f;
}

From source file:com.linecorp.armeria.internal.Http1ObjectEncoder.java

License:Apache License

private ChannelFuture writeServerHeaders(ChannelHandlerContext ctx, int id, int streamId, HttpHeaders headers,
        boolean endStream) throws Http2Exception {

    final HttpObject converted = convertServerHeaders(streamId, headers, endStream);
    final HttpStatus status = headers.status();
    if (status == null) {
        // Trailing headers
        final ChannelFuture f = write(ctx, id, converted, endStream);
        ctx.flush();/*from   www  .j a  va2s.  c  o  m*/
        return f;
    }

    if (status.codeClass() == HttpStatusClass.INFORMATIONAL) {
        // Informational status headers.
        final ChannelFuture f = write(ctx, id, converted, false);
        if (endStream) {
            // Can't end a stream with informational status in HTTP/1.
            f.addListener(ChannelFutureListener.CLOSE);
        }
        ctx.flush();
        return f;
    }

    // Non-informational status headers.
    return writeNonInformationalHeaders(ctx, id, converted, endStream);
}

From source file:com.linecorp.armeria.internal.Http1ObjectEncoder.java

License:Apache License

@Override
protected ChannelFuture doWriteReset(ChannelHandlerContext ctx, int id, int streamId, Http2Error error) {
    // NB: this.minClosedId can be overwritten more than once when 3+ pipelined requests are received
    //     and they are handled by different threads simultaneously.
    //     e.g. when the 3rd request triggers a reset and then the 2nd one triggers another.
    minClosedId = Math.min(minClosedId, id);
    for (int i = minClosedId; i <= maxIdWithPendingWrites; i++) {
        final PendingWrites pendingWrites = pendingWritesMap.remove(i);
        for (;;) {
            final Entry<HttpObject, ChannelPromise> e = pendingWrites.poll();
            if (e == null) {
                break;
            }//from   w ww.ja  v  a2  s. c om
            e.getValue().tryFailure(ClosedSessionException.get());
        }
    }

    final ChannelFuture f = ctx.write(Unpooled.EMPTY_BUFFER);
    if (currentId >= minClosedId) {
        f.addListener(ChannelFutureListener.CLOSE);
    }

    return f;
}

From source file:com.linecorp.armeria.server.http.Http1RequestDecoder.java

License:Apache License

private void fail(ChannelHandlerContext ctx, HttpResponseStatus status) {
    discarding = true;/*from  w w  w  .jav a2s .c o  m*/
    req = null;

    final ChannelFuture future;
    if (receivedRequests <= sentResponses) {
        // Just close the connection if sending an error response will make the number of the sent
        // responses exceed the number of the received requests, which doesn't make sense.
        future = ctx.writeAndFlush(Unpooled.EMPTY_BUFFER);
    } else {
        final ByteBuf content = Unpooled.copiedBuffer(status.toString(), StandardCharsets.UTF_8);
        final FullHttpResponse res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, content);

        final HttpHeaders headers = res.headers();
        headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
        headers.set(HttpHeaderNames.CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8);
        headers.setInt(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());

        future = ctx.writeAndFlush(res);
    }

    future.addListener(ChannelFutureListener.CLOSE);
}

From source file:com.lufs.preresearch.nettyrouter.playground.HttpHelloWorldServerHandler.java

License:Apache License

private void sendError(ChannelHandlerContext ctx, HttpResponseStatus httpResponseStatus) {
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, httpResponseStatus);
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}

From source file:com.lxz.talk.websocketx.server.WebSocketServerHandler.java

License:Apache License

private static 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);//from w ww . j av a2  s  . c  o m
        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);
    }
}