Example usage for io.netty.handler.codec.http HttpHeaders setContentLength

List of usage examples for io.netty.handler.codec.http HttpHeaders setContentLength

Introduction

In this page you can find the example usage for io.netty.handler.codec.http HttpHeaders setContentLength.

Prototype

@Deprecated
public static void setContentLength(HttpMessage message, long length) 

Source Link

Usage

From source file:io.vertx.core.http.impl.HttpServerImpl.java

License:Open Source License

private void sendError(CharSequence err, HttpResponseStatus status, Channel ch) {
    FullHttpResponse resp = new DefaultFullHttpResponse(HTTP_1_1, status);
    if (status.code() == METHOD_NOT_ALLOWED.code()) {
        // SockJS requires this
        resp.headers().set(io.vertx.core.http.HttpHeaders.ALLOW, io.vertx.core.http.HttpHeaders.GET);
    }/* w  ww .  ja  v  a2  s.c o m*/
    if (err != null) {
        resp.content().writeBytes(err.toString().getBytes(CharsetUtil.UTF_8));
        HttpHeaders.setContentLength(resp, err.length());
    } else {
        HttpHeaders.setContentLength(resp, 0);
    }

    ch.writeAndFlush(resp);
}

From source file:io.viewserver.network.netty.websocket.WebSocketServerHandler.java

License:Apache License

private void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    if (res.getStatus().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);//from  w w w . j  a  v  a 2  s.c  o m
        buf.release();
        HttpHeaders.setContentLength(res, res.content().readableBytes());
    }

    ChannelFuture channelFuture = ctx.channel().writeAndFlush(res);
    if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) {
        channelFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:me.davehummel.tredserver.web.WebSocketServerHandler.java

License:Apache License

private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
    // Handle a bad request.
    if (!req.getDecoderResult().isSuccess()) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
        return;//from ww w .  j a  va 2 s . c  o m
    }

    // Allow only GET methods.
    if (req.getMethod() != GET) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
        return;
    }

    // Send the demo page and favicon.ico
    if ("/".equals(req.getUri())) {
        ByteBuf content = WebSocketServerIndexPage.getContent(getWebSocketLocation(req));
        FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content);

        res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
        HttpHeaders.setContentLength(res, content.readableBytes());

        sendHttpResponse(ctx, req, res);
        return;
    }
    // Send the demo page and favicon.ico
    if ("/voxel".equals(req.getUri())) {
        ByteBuf content = VoxelExplorerIndex.getContent(getWebSocketLocation(req));
        FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content);

        res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
        HttpHeaders.setContentLength(res, content.readableBytes());

        sendHttpResponse(ctx, req, res);
        return;
    }
    if ("/favicon.ico".equals(req.getUri())) {
        FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND);
        sendHttpResponse(ctx, req, res);
        return;
    }

    // Handshake
    WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req),
            null, true);
    handshaker = wsFactory.newHandshaker(req);
    if (handshaker == null) {
        WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
    } else {
        handshaker.handshake(ctx.channel(), req);
    }
}

From source file:me.jesonlee.jjfsserver.httpserver.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.ja va 2  s. c  om*/
        return;
    }

    if (request.getMethod() != GET) {
        sendError(ctx, METHOD_NOT_ALLOWED);
        return;
    }

    final String uri = request.getUri();
    final String path = PathUtil.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;
    ChannelFuture lastContentFuture;
    if (ctx.pipeline().get(SslHandler.class) == null) {
        sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength),
                ctx.newProgressivePromise());
        // Write the end marker.
        lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    } else {
        sendFileFuture = ctx.write(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)),
                ctx.newProgressivePromise());
        // HttpChunkedInput will write the end marker (LastHttpContent) for us.
        lastContentFuture = sendFileFuture;
    }

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

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

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

From source file:me.zhuoran.amoeba.netty.server.HttpServerHandler.java

License:Apache License

private static void sendHttpResponse(ChannelHandlerContext ctx, HttpRequest req, FullHttpResponse res) {
    if (res.getStatus().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);//from   w  w  w .  j a  v  a 2  s.  c o  m
        buf.release();
        HttpHeaders.setContentLength(res, (long) res.content().readableBytes());
    }

    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }

}

From source file:mmo.server.DataToHttpEncoder.java

License:Open Source License

@Override
protected void encode(ChannelHandlerContext ctx, Data msg, List<Object> out) throws Exception {
    ByteBuf buf = Unpooled.wrappedBuffer(mapper.writeValueAsBytes(msg));
    HttpResponse res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);
    HttpHeaders.setHeader(res, HttpHeaders.Names.CONTENT_TYPE, "text/plain; encoding=utf-8");
    HttpHeaders.setContentLength(res, buf.readableBytes());

    out.add(res);/*from w  w  w.  ja  v  a  2  s .c o  m*/
}

From source file:mmo.server.DefaultHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
    String filename = ctx.channel().attr(FILE).get();
    ByteBuf buf = Unpooled.wrappedBuffer(load(filename.isEmpty() ? "index.html" : filename));
    HttpResponse res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);
    HttpHeaders.setHeader(res, HttpHeaders.Names.CONTENT_TYPE, "text/html; encoding=utf-8");
    HttpHeaders.setContentLength(res, buf.readableBytes());

    ctx.writeAndFlush(res);//from   www  .ja  v a  2  s .  c  o m
}

From source file:mmo.server.PageNotFoundHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND);
    HttpHeaders.setContentLength(response, 0);

    ctx.writeAndFlush(response);//from w  w w  . j  a va2  s .  co  m
}

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.//w  w w  .  j a  v a  2 s  .  c om
 * @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/>//  w w  w  . j a v  a2s  . 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);
    }
}