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.github.nettybook.ch8.TelnetServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, String request) throws Exception {
    // Generate and write a response.
    String response;/*from w w  w .  j ava2s.  c  o m*/
    boolean close = false;
    if (request.isEmpty()) {
        response = "?  .\r\n";
    } else if ("bye".equals(request.toLowerCase())) {
        response = " !\r\n";
        close = true;
    } else {
        response = " ? '" + request + "' .\r\n";
    }

    // TelnetPipelineFactory? ? StringEncoder? ?? ?   
    // ChannelBuffer?  ?    ? ?? .   
    ChannelFuture future = ctx.write(response);

    // ??? bye ?  close  true? ? ? ?.
    if (close) {
        future.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.github.rmannibucau.featuredmock.http.FeaturedHandler.java

License:Apache License

@Override
protected void channelRead0(final ChannelHandlerContext ctx, final FullHttpRequest request) throws Exception {
    if (!request.getDecoderResult().isSuccess()) {
        sendError(ctx, HttpResponseStatus.BAD_REQUEST);
        return;/*w w w  . j  av a2  s  .  c  o  m*/
    }

    InputStream stream = null;
    String type = null;

    final String accept = request.headers().get(HttpHeaders.Names.ACCEPT);
    if (accept != null) {
        for (final String a : accept.split(",")) {
            if (mappers != null) {
                for (final ContentTypeMapper mapper : mappers) {
                    if (mapper.handle(a)) {
                        final String extension = mapper.extension(a);
                        stream = findResource(request, extension);
                        if (stream == null && extension != null && !extension.startsWith(".")) {
                            stream = findResource(request, "." + extension);
                        }
                        if (stream != null) {
                            type = mapper.contentType(a);
                            break;
                        }
                    }
                }
            }

            if (stream == null) {
                for (final String ext : EXTENSIONS) {
                    if (a.contains(ext.substring(1))) {
                        stream = findResource(request, ext);
                        if (stream != null) {
                            type = "application/" + ext.substring(1); // remove dot
                        }
                        break;
                    }
                }
            }

            if (stream != null) {
                break;
            }
        }
    }

    if (stream == null) { // not found from content type so try all extensions
        for (final String ext : EXTENSIONS) {
            stream = findResource(request, ext);
            if (stream != null) {
                type = "application/" + ext.substring(1); // remove dot
                break;
            }
        }
    }

    if (stream == null) { // try without extension
        stream = findResource(request, "");
        if (stream != null) {
            type = "text/plain";
        }
    }

    if (stream == null) {
        sendError(ctx, HttpResponseStatus.NOT_FOUND);
        return;
    }

    final byte[] bytes = IOs.slurp(stream);
    final HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
            Unpooled.copiedBuffer(bytes));
    HttpHeaders.setContentLength(response, bytes.length);
    response.headers().set(HttpHeaders.Names.CONTENT_TYPE, type);
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}

From source file:com.github.rmannibucau.featuredmock.http.FeaturedHandler.java

License:Apache License

private static void sendError(final ChannelHandlerContext ctx, final HttpResponseStatus status) {
    final FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status,
            Unpooled.copiedBuffer("Failure: " + status.toString() + "\r\n", CharsetUtil.UTF_8));
    response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain; charset=UTF-8");
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}

From source file:com.github.thinker0.mesos.MesosHealthCheckerServer.java

License:Apache License

/**
 * Writes a HTTP response.//from  w  w  w. ja v a 2 s.  co m
 *
 * @param ctx           The channel context.
 * @param request       The HTTP request.
 * @param status        The HTTP status code.
 * @param buf           The response content buffer.
 * @param contentType   The response content type.
 * @param contentLength The response content length;
 */
private void writeResponse(final ChannelHandlerContext ctx, final FullHttpRequest request,
        final HttpResponseStatus status, final ByteBuf buf, final CharSequence contentType,
        final int contentLength) {

    // Decide whether to close the connection or not.
    final boolean keepAlive = isKeepAlive(request);

    // Build the response object.
    final FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, buf, false);

    final ZonedDateTime dateTime = ZonedDateTime.now();
    final DateTimeFormatter formatter = DateTimeFormatter.RFC_1123_DATE_TIME;

    final DefaultHttpHeaders headers = (DefaultHttpHeaders) response.headers();
    headers.set(HttpHeaderNames.SERVER, SERVER_NAME);
    headers.set(HttpHeaderNames.DATE, dateTime.format(formatter));
    headers.set(HttpHeaderNames.CONTENT_TYPE, contentType);
    headers.set(HttpHeaderNames.CONTENT_LENGTH, Integer.toString(contentLength));

    // Close the non-keep-alive connection after the write operation is done.
    if (!keepAlive) {
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    } else {
        ctx.writeAndFlush(response, ctx.voidPromise());
    }
}

From source file:com.github.unafraid.signer.server.ServerHandler.java

License:Apache License

private void processResponse(ChannelHandlerContext ctx, HttpRequest req, FullHttpResponse response) {
    if (response.headers().get(CONTENT_TYPE, null) == null) {
        response.headers().set(CONTENT_TYPE, "text/html");
    }//from ww w .ja  v a2 s.  co  m
    response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());

    if (!HttpHeaderUtil.isKeepAlive(req)) {
        ctx.write(response).addListener(ChannelFutureListener.CLOSE);
    } else {
        response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        ctx.write(response);
    }
}

From source file:com.github.wens.netty.web.impl.ResponseImp.java

License:Apache License

public synchronized void finish(boolean keepAlive) {
    finish = true;/*from w  w w  .  jav a2 s  .c  o m*/
    writeHeader(keepAlive);
    writeBody();
    if (!keepAlive) {
        ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT).addListener(ChannelFutureListener.CLOSE);
    } else {

        ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    }
}

From source file:com.google.devtools.build.remote.worker.HttpCacheServerHandler.java

License:Open Source License

private void handleGet(ChannelHandlerContext ctx, FullHttpRequest request) {
    byte[] contents = cache.get(request.uri());

    if (contents == null) {
        sendError(ctx, request, HttpResponseStatus.NOT_FOUND);
        return;/*from   w w  w . j  a  v  a 2s  . c  om*/
    }

    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
            Unpooled.wrappedBuffer(contents));
    HttpUtil.setContentLength(response, contents.length);
    response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/octet-stream");
    ChannelFuture lastContentFuture = ctx.writeAndFlush(response);

    if (!HttpUtil.isKeepAlive(request)) {
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.google.devtools.build.remote.worker.HttpCacheServerHandler.java

License:Open Source License

private void handlePut(ChannelHandlerContext ctx, FullHttpRequest request) {
    if (!request.decoderResult().isSuccess()) {
        sendError(ctx, request, HttpResponseStatus.INTERNAL_SERVER_ERROR);
        return;//from   ww  w .jav  a  2  s .c o  m
    }

    byte[] contentBytes = new byte[request.content().readableBytes()];
    request.content().readBytes(contentBytes);
    cache.putIfAbsent(request.uri(), contentBytes);

    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
            HttpResponseStatus.NO_CONTENT);
    ChannelFuture lastContentFuture = ctx.writeAndFlush(response);

    if (!HttpUtil.isKeepAlive(request)) {
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.google.devtools.build.remote.worker.HttpCacheServerHandler.java

License:Open Source License

private static void sendError(ChannelHandlerContext ctx, FullHttpRequest request, HttpResponseStatus status) {
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status,
            Unpooled.copiedBuffer("Failure: " + status + "\r\n", CharsetUtil.UTF_8));
    response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
    ChannelFuture future = ctx.writeAndFlush(response);

    if (!HttpUtil.isKeepAlive(request)) {
        future.addListener(ChannelFutureListener.CLOSE);
    }/*from w ww . ja  v  a 2s  . co  m*/
}

From source file:com.googlecode.protobuf.pro.duplex.handler.ServerConnectRequestHandler.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, WirePayload msg, List<Object> out) throws Exception {
    if (msg.hasConnectRequest()) {
        ConnectRequest connectRequest = msg.getConnectRequest();
        if (log.isDebugEnabled()) {
            log.debug("Received [" + connectRequest.getCorrelationId() + "]ConnectRequest.");
        }/*w w  w .  j a  v a 2  s. c  om*/
        PeerInfo connectingClientInfo = new PeerInfo(connectRequest.getClientHostName(),
                connectRequest.getClientPort(), connectRequest.getClientPID());
        ConnectResponse connectResponse = null;

        RpcClient rpcClient = new RpcClient(ctx.channel(), pipelineFactory.getServerInfo(),
                connectingClientInfo, connectRequest.getCompress(), pipelineFactory.getLogger(),
                pipelineFactory.getExtensionRegistry());
        if (pipelineFactory.getRpcClientRegistry().registerRpcClient(rpcClient)) {
            connectResponse = ConnectResponse.newBuilder().setCorrelationId(connectRequest.getCorrelationId())
                    .setServerPID(pipelineFactory.getServerInfo().getPid())
                    .setCompress(connectRequest.getCompress()).build();
            WirePayload payload = WirePayload.newBuilder().setConnectResponse(connectResponse).build();

            if (log.isDebugEnabled()) {
                log.debug("Sending [" + connectResponse.getCorrelationId() + "]ConnectResponse.");
            }
            ctx.channel().writeAndFlush(payload);

            // now we swap this Handler out of the pipeline and complete the server side pipeline.
            RpcClientHandler clientHandler = pipelineFactory.completePipeline(rpcClient);
            clientHandler.notifyOpened();
        } else {
            connectResponse = ConnectResponse.newBuilder().setCorrelationId(connectRequest.getCorrelationId())
                    .setErrorCode(ConnectErrorCode.ALREADY_CONNECTED).build();
            WirePayload payload = WirePayload.newBuilder().setConnectResponse(connectResponse).build();

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