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:edu.upennlib.redirect.RedirectHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpRequest msg) throws Exception {
    QueryStringDecoder orig = new QueryStringDecoder(msg.getUri());
    List<String> vals = orig.parameters().get(REDIRECT_PARAM_KEY);
    String val;
    if (vals == null || vals.isEmpty() || (val = vals.get(0)) == null) {
        badRequest("no redirect specified", ctx);
        return;/*from   w w  w . j ava2s .  c om*/
    }
    Matcher m = PRE_PATH.matcher(val);
    String parsed = null;
    if (!m.find() || !validHosts.contains(parsed = m.group())) {
        badRequest("redirect not permitted: " + val + ", parsed=" + parsed, ctx);
        return;
    }
    DefaultFullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FOUND);
    resp.headers().add(LOCATION, val);
    resp.headers().add(CONNECTION, CLOSE);
    ctx.writeAndFlush(resp).addListener(ChannelFutureListener.CLOSE);
}

From source file:edu.upennlib.redirect.RedirectHandler.java

License:Apache License

private void badRequest(String message, ChannelHandlerContext ctx) {
    ByteBuf content = Unpooled.wrappedBuffer(message.getBytes(UTF8));
    DefaultFullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
            HttpResponseStatus.BAD_REQUEST, content);
    HttpHeaders.setContentLength(resp, content.readableBytes());
    ctx.writeAndFlush(resp).addListener(ChannelFutureListener.CLOSE);
}

From source file:edu.upennlib.redirect.RedirectHandler.java

License:Apache License

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    super.exceptionCaught(ctx, cause);
    ctx.writeAndFlush(//ww w.  j  a  v  a 2s . c om
            new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR))
            .addListener(ChannelFutureListener.CLOSE);
}

From source file:errorcode.DaumStatusServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    FullHttpResponse response = null;/*from  w w w  .ja  v  a  2  s .  c  o  m*/

    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;
        QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri());

        if (is100ContinueExpected(req)) {
            ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
        }
        boolean keepAlive = isKeepAlive(req);
        if (queryDecoder.path().startsWith("/503.html")) {
            response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(E503));
            response.setStatus(SERVICE_UNAVAILABLE);
        } else {
            response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(E404));
            response.setStatus(NOT_FOUND);
        }

        response.headers().set(CONTENT_TYPE, "text/html");
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());

        if (!keepAlive) {
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(CONNECTION, Values.KEEP_ALIVE);
            ctx.write(response);
        }
    }
}

From source file:esens.wp6.ibmJmsBackend.log4http.HttpLogServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;

        if (HttpHeaderUtil.is100ContinueExpected(req)) {
            ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
        }// ww w. j ava 2s  .c  om
        boolean keepAlive = HttpHeaderUtil.isKeepAlive(req);
        System.out.println(req.uri());

        //get number of lines to show from the request uri.

        String lines = "-n 500"; //pull last 500 lines as default
        if (req.uri().equals("/")) {
            //all lines
        } else {
            try {
                lines = "-n " + Integer.parseInt(req.uri().substring(1));
            } catch (NumberFormatException ex) {

            }
        }
        //LOGGER.debug("# of lines to tail \"" + lines + "\"");
        /**
         * *********** DOES NOT WORK ON WINDOWS because uses tail command
         */
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        try {
            final Process exec = Runtime.getRuntime().exec("tail " + lines + " logs/ibm-jms-backend.log");

            BufferedReader br = new BufferedReader(new InputStreamReader(exec.getInputStream()));

            String line = null;

            while ((line = br.readLine()) != null) {
                pw.println(line);
            }
        } catch (Exception ex) {
            LOGGER.error("Couldn't run tail, are you using Windows (smirk)");
            pw.println("Couldn't run tail, are you using Windows (smirk)");
            LOGGER.error(ex.getMessage(), ex);
            ex.printStackTrace(pw);
        }

        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK,
                Unpooled.wrappedBuffer(sw.toString().getBytes()));
        response.headers().set(CONTENT_TYPE, "text/plain");
        response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());

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

From source file:example.http2.helloworld.server.HelloWorldHttp1Handler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
    if (HttpUtil.is100ContinueExpected(req)) {
        ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
    }//ww w .  j ava 2s  . c o m
    boolean keepAlive = HttpUtil.isKeepAlive(req);

    ByteBuf content = ctx.alloc().buffer();
    content.writeBytes(HelloWorldHttp2Handler.RESPONSE_BYTES.duplicate());
    ByteBufUtil.writeAscii(content, " - via " + req.protocolVersion() + " (" + establishApproach + ")");

    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, content);
    response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
    response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());

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

From source file:fileShare.HttpStaticFileServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (!request.getDecoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);/*w w  w.j  av a2  s .c  o  m*/
        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 fnfe) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    long fileLength = raf.length();

    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    setContentLength(response, fileLength);
    setContentTypeHeader(response, file);
    setDateAndCacheHeaders(response, file);
    if (isKeepAlive(request)) {
        response.headers().set(CONNECTION, Values.KEEP_ALIVE);
    }

    // Write the initial line and the header.
    ctx.write(response);

    // Write the content.
    ChannelFuture sendFileFuture;
    if (useSendFile) {
        sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength),
                ctx.newProgressivePromise());
    } else {
        sendFileFuture = ctx.write(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
                System.err.println("Transfer progress: " + progress);
            } else {
                System.err.println("Transfer progress: " + progress + " / " + total);
            }
        }

        @Override
        public void operationComplete(ChannelProgressiveFuture future) throws Exception {
            System.err.println("Transfer complete.");
        }
    });

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

    // Decide whether to close the connection or not.
    if (!isKeepAlive(request)) {
        // Close the connection when the whole content is written out.
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:fileShare.MyHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpMessage msg) throws Exception {
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;
        System.out.println("==================================HttpRequest==================================");
        System.out.println(msg.toString());
        URI uri = new URI(request.getUri());
        if (uri.getPath().startsWith("/getFile")) {

            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < 1000; i++) {
                sb.append(i + ",");
            }/*from  w  w  w  .  j ava 2 s  . com*/

            //HttpContent httpContent = blockingFile.take();
            //ByteBuf wrappedBufferA = Unpooled.wrappedBuffer(byteses);
            ByteBuf wrappedBufferA = copiedBuffer(sb.toString(), CharsetUtil.UTF_8);

            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
                    wrappedBufferA);

            response.headers().set(CONTENT_TYPE, "application/octet-stream");
            if (isKeepAlive(request)) {
                response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
            }
            response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, wrappedBufferA.readableBytes());
            // Write the initial line and the header.
            //ctx.write(response);

            ChannelFuture lastContentFuture = ctx.channel().writeAndFlush(response);
            // Decide whether to close the connection or not.
            if (!isKeepAlive(request)) {
                // Close the connection when the whole content is written out.
                lastContentFuture.addListener(ChannelFutureListener.CLOSE);
            }
        }
        if (!uri.getPath().startsWith("/form")) {
            // Write Menu
            writeMenu(ctx);
            return;
        }

        //            responseContent.setLength(0);
        //            responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n");
        //
        //            // if GET Method: should not try to create a HttpPostRequestDecoder
        //            try {
        //                decoder = new HttpPostRequestDecoder(factory, request);
        //            } catch (ErrorDataDecoderException e1) {
        //                e1.printStackTrace();
        //                responseContent.append(e1.getMessage());
        //                writeResponse(ctx.channel());
        //                ctx.channel().close();
        //                return;
        //            } catch (IncompatibleDataDecoderException e1) {
        //                // GET Method: should not try to create a HttpPostRequestDecoder
        //                // So OK but stop here
        //                responseContent.append(e1.getMessage());
        //                responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n");
        //                writeResponse(ctx.channel());
        //                return;
        //            }
        //
        //            readingChunks = HttpHeaders.isTransferEncodingChunked(request);
        //            responseContent.append("Is Chunked: " + readingChunks + "\r\n");
        //            responseContent.append("IsMultipart: " + decoder.isMultipart() + "\r\n");
        //            if (readingChunks) {
        //                // Chunk version
        //                responseContent.append("Chunks: ");
        //                readingChunks = true;
        //            }
    }

    // check if the decoder was constructed before
    // if not it handles the form get
    //        if (decoder != null) {
    //            if (msg instanceof HttpContent) {
    //                // New chunk is received
    //                HttpContent chunk = (HttpContent) msg;
    //                try {
    //                    System.out.println("==================================HttpContent==================================");
    //                    //?
    //                    System.out.println(new String(((DefaultHttpContent) chunk).content().array()));
    //                    blockingFile.put(chunk.copy());
    //                    decoder.offer(chunk);
    //                } catch (ErrorDataDecoderException e1) {
    //                    e1.printStackTrace();
    //                    responseContent.append(e1.getMessage());
    //                    writeResponse(ctx.channel());
    //                    ctx.channel().close();
    //                    return;
    //                }
    //                responseContent.append('o');
    //                // example of reading chunk by chunk (minimize memory usage due to
    //                // Factory)
    //                readHttpDataChunkByChunk();
    //                // example of reading only if at the end
    //                if (chunk instanceof LastHttpContent) {
    //                    writeResponse(ctx.channel());
    //                    readingChunks = false;
    //                    send = false;
    //                    reset();
    //                }
    //            }
    //        }
}

From source file:fileShare.ShareHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;
        System.out.println("==================================HttpRequest==================================");
        System.out.println(msg.toString());
        URI uri = new URI(request.getUri());
        if (uri.getPath().startsWith("/getFile")) {

            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < 1000; i++) {
                sb.append(i + ",");
            }/*w  w  w  . j a v  a 2 s  .  c o  m*/

            //HttpContent httpContent = blockingFile.take();
            //ByteBuf wrappedBufferA = Unpooled.wrappedBuffer(byteses);
            ByteBuf wrappedBufferA = copiedBuffer(sb.toString(), CharsetUtil.UTF_8);

            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
                    wrappedBufferA);

            response.headers().set(CONTENT_TYPE, "application/octet-stream");
            if (isKeepAlive(request)) {
                response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
            }
            response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, wrappedBufferA.readableBytes());
            // Write the initial line and the header.
            //ctx.write(response);

            ChannelFuture lastContentFuture = ctx.channel().writeAndFlush(response);
            // Decide whether to close the connection or not.
            if (!isKeepAlive(request)) {
                // Close the connection when the whole content is written out.
                lastContentFuture.addListener(ChannelFutureListener.CLOSE);
            }
        }
        if (!uri.getPath().startsWith("/form")) {
            // Write Menu
            writeMenu(ctx);
            return;
        }

        responseContent.setLength(0);
        responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n");

        // if GET Method: should not try to create a HttpPostRequestDecoder
        try {
            decoder = new HttpPostRequestDecoder(factory, request);
        } catch (ErrorDataDecoderException e1) {
            e1.printStackTrace();
            responseContent.append(e1.getMessage());
            writeResponse(ctx.channel());
            ctx.channel().close();
            return;
        } catch (IncompatibleDataDecoderException e1) {
            // GET Method: should not try to create a HttpPostRequestDecoder
            // So OK but stop here
            responseContent.append(e1.getMessage());
            responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n");
            writeResponse(ctx.channel());
            return;
        }

        readingChunks = HttpHeaders.isTransferEncodingChunked(request);
        responseContent.append("Is Chunked: " + readingChunks + "\r\n");
        responseContent.append("IsMultipart: " + decoder.isMultipart() + "\r\n");
        if (readingChunks) {
            // Chunk version
            responseContent.append("Chunks: ");
            readingChunks = true;
        }
    }

    // check if the decoder was constructed before
    // if not it handles the form get
    if (decoder != null) {
        if (msg instanceof HttpContent) {
            // New chunk is received
            HttpContent chunk = (HttpContent) msg;
            try {
                System.out.println(
                        "==================================HttpContent==================================");
                //?
                System.out.println(new String(((DefaultHttpContent) chunk).content().array()));
                blockingFile.put(chunk.copy());
                decoder.offer(chunk);
            } catch (ErrorDataDecoderException e1) {
                e1.printStackTrace();
                responseContent.append(e1.getMessage());
                writeResponse(ctx.channel());
                ctx.channel().close();
                return;
            }
            responseContent.append('o');
            // example of reading chunk by chunk (minimize memory usage due to
            // Factory)
            readHttpDataChunkByChunk();
            // example of reading only if at the end
            if (chunk instanceof LastHttpContent) {
                writeResponse(ctx.channel());
                readingChunks = false;
                send = false;
                reset();
            }
        }
    }
}

From source file:fixio.examples.priceclient.PriceReadingApp.java

License:Apache License

@Override
public void onMessage(ChannelHandlerContext ctx, FixMessage msg, List<Object> out) throws Exception {
    assert (msg != null) : "Message can't be null";
    switch (msg.getMessageType()) {
    case MessageTypes.QUOTE:
        onQuote(msg);//from   www .  j a v a  2  s. c  o  m
        break;
    default:
        return;
    }
    if (counter % 10000 == 0) {
        LOGGER.debug("Read {} Quotes", counter);
    }
    if (counter > MAX_QUOTE_COUNT && !finished) {
        finished = true;

        long timeMillis = (System.nanoTime() - startTimeNanos) / 1000000;
        LOGGER.info("Read {} Quotes in {} ms, ~{} Quote/sec", counter, timeMillis,
                counter * 1000.0 / timeMillis);

        ctx.writeAndFlush(createQuoteCancel()).addListener(ChannelFutureListener.CLOSE);
    }
}