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:com.topsec.bdc.platform.api.test.http.websocketx.benchmarkserver.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  w  w . j  a v 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);
    }
}

From source file:com.topsec.bdc.platform.api.test.http.websocketx.server.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   w  w w  .j a  va 2 s  .  c om
    }

    // 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;
    }
    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:com.twitter.http2.HttpStreamDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {
    if (msg instanceof HttpHeadersFrame) {

        HttpHeadersFrame httpHeadersFrame = (HttpHeadersFrame) msg;
        int streamId = httpHeadersFrame.getStreamId();
        StreamedHttpMessage message = messageMap.get(streamId);

        if (message == null) {
            if (httpHeadersFrame.headers().contains(":status")) {

                // If a client receives a reply with a truncated header block,
                // reply with a RST_STREAM frame with error code INTERNAL_ERROR.
                if (httpHeadersFrame.isTruncated()) {
                    HttpRstStreamFrame httpRstStreamFrame = new DefaultHttpRstStreamFrame(streamId,
                            HttpErrorCode.INTERNAL_ERROR);
                    out.add(httpRstStreamFrame);
                    return;
                }// w  w w  .j  av a2 s  . c  o m

                try {
                    StreamedHttpResponse response = createHttpResponse(httpHeadersFrame);

                    if (httpHeadersFrame.isLast()) {
                        HttpHeaders.setContentLength(response, 0);
                        response.getContent().close();
                    } else {
                        // Response body will follow in a series of Data Frames
                        if (!HttpHeaders.isContentLengthSet(response)) {
                            HttpHeaders.setTransferEncodingChunked(response);
                        }
                        messageMap.put(streamId, response);
                    }
                    out.add(response);
                } catch (Exception e) {
                    // If a client receives a SYN_REPLY without valid getStatus and version headers
                    // the client must reply with a RST_STREAM frame indicating a PROTOCOL_ERROR
                    HttpRstStreamFrame httpRstStreamFrame = new DefaultHttpRstStreamFrame(streamId,
                            HttpErrorCode.PROTOCOL_ERROR);
                    ctx.writeAndFlush(httpRstStreamFrame);
                    out.add(httpRstStreamFrame);
                }

            } else {

                // If a client sends a request with a truncated header block, the server must
                // reply with a HTTP 431 REQUEST HEADER FIELDS TOO LARGE reply.
                if (httpHeadersFrame.isTruncated()) {
                    httpHeadersFrame = new DefaultHttpHeadersFrame(streamId);
                    httpHeadersFrame.setLast(true);
                    httpHeadersFrame.headers().set(":status",
                            HttpResponseStatus.REQUEST_HEADER_FIELDS_TOO_LARGE.code());
                    ctx.writeAndFlush(httpHeadersFrame);
                    return;
                }

                try {
                    message = createHttpRequest(httpHeadersFrame);

                    if (httpHeadersFrame.isLast()) {
                        message.setDecoderResult(DecoderResult.SUCCESS);
                        message.getContent().close();
                    } else {
                        // Request body will follow in a series of Data Frames
                        messageMap.put(streamId, message);
                    }

                    out.add(message);

                } catch (Exception e) {
                    // If a client sends a SYN_STREAM without all of the method, url (host and path),
                    // scheme, and version headers the server must reply with a HTTP 400 BAD REQUEST reply.
                    // Also sends HTTP 400 BAD REQUEST reply if header name/value pairs are invalid
                    httpHeadersFrame = new DefaultHttpHeadersFrame(streamId);
                    httpHeadersFrame.setLast(true);
                    httpHeadersFrame.headers().set(":status", HttpResponseStatus.BAD_REQUEST.code());
                    ctx.writeAndFlush(httpHeadersFrame);
                }
            }
        } else {
            LastHttpContent trailer = trailerMap.remove(streamId);
            if (trailer == null) {
                trailer = new DefaultLastHttpContent();
            }

            // Ignore trailers in a truncated HEADERS frame.
            if (!httpHeadersFrame.isTruncated()) {
                for (Map.Entry<String, String> e : httpHeadersFrame.headers()) {
                    trailer.trailingHeaders().add(e.getKey(), e.getValue());
                }
            }

            if (httpHeadersFrame.isLast()) {
                messageMap.remove(streamId);
                message.addContent(trailer);
            } else {
                trailerMap.put(streamId, trailer);
            }
        }

    } else if (msg instanceof HttpDataFrame) {

        HttpDataFrame httpDataFrame = (HttpDataFrame) msg;
        int streamId = httpDataFrame.getStreamId();
        StreamedHttpMessage message = messageMap.get(streamId);

        // If message is not in map discard Data Frame.
        if (message == null) {
            return;
        }

        ByteBuf content = httpDataFrame.content();
        if (content.isReadable()) {
            content.retain();
            message.addContent(new DefaultHttpContent(content));
        }

        if (httpDataFrame.isLast()) {
            messageMap.remove(streamId);
            message.addContent(LastHttpContent.EMPTY_LAST_CONTENT);
            message.setDecoderResult(DecoderResult.SUCCESS);
        }

    } else if (msg instanceof HttpRstStreamFrame) {

        HttpRstStreamFrame httpRstStreamFrame = (HttpRstStreamFrame) msg;
        int streamId = httpRstStreamFrame.getStreamId();
        StreamedHttpMessage message = messageMap.remove(streamId);

        if (message != null) {
            message.getContent().close();
            message.setDecoderResult(DecoderResult.failure(CANCELLATION_EXCEPTION));
        }

    } else {
        // HttpGoAwayFrame
        out.add(msg);
    }
}

From source file:com.wx3.galacdecks.networking.HttpHandler.java

License:Open Source License

private static 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 www  .  jav  a  2  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);
    }
}

From source file:com.wx3.galacdecks.networking.HttpHandler.java

License:Open Source License

private void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, String text) {
    ByteBuf content = Unpooled.copiedBuffer(text.getBytes());
    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);/* ww  w.  j a va2s  .  com*/
}

From source file:com.xx_dev.apn.proxy.ApnProxyPreHandler.java

License:Apache License

private boolean preCheck(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) msg;

        String originalHost = HostNamePortUtil.getHostName(httpRequest);

        LoggerUtil.info(httpRestLogger, ctx.channel().remoteAddress().toString(),
                httpRequest.getMethod().name(), httpRequest.getUri(), httpRequest.getProtocolVersion().text(),
                httpRequest.headers().get(HttpHeaders.Names.USER_AGENT));

        isPacRequest = false;// ww  w . ja  v a  2  s.  c  om

        // pac request
        if (StringUtils.equals(originalHost, ApnProxyConfig.getConfig().getPacHost())) {
            isPacRequest = true;

            String pacContent = null;
            if (ApnProxyConfig.getConfig().getListenType() == ApnProxyListenType.SSL) {
                pacContent = buildPacForSsl();
            } else {
                pacContent = buildPacForPlain();
            }

            ByteBuf pacResponseContent = Unpooled.copiedBuffer(pacContent, CharsetUtil.UTF_8);
            FullHttpMessage pacResponseMsg = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    HttpResponseStatus.OK, pacResponseContent);
            HttpHeaders.setContentLength(pacResponseMsg, pacResponseContent.readableBytes());
            HttpHeaders.setHeader(pacResponseMsg, "X-APN-PROXY-PAC", "OK");
            HttpHeaders.setHeader(pacResponseMsg, "X-APN-PROXY-URL", "https://github.com/apn-proxy/apn-proxy");
            HttpHeaders.setHeader(pacResponseMsg, "X-APN-PROXY-MSG", "We need more commiters!");

            ctx.write(pacResponseMsg);
            ctx.flush();
            return false;
        }

        // forbid request to proxy server internal network
        for (String forbiddenIp : forbiddenIps) {
            if (StringUtils.startsWith(originalHost, forbiddenIp)) {
                String errorMsg = "Forbidden";
                ctx.write(HttpErrorUtil.buildHttpErrorMessage(HttpResponseStatus.FORBIDDEN, errorMsg));
                ctx.flush();
                return false;
            }
        }

        // forbid request to proxy server local
        if (StringUtils.equals(originalHost, "127.0.0.1") || StringUtils.equals(originalHost, "localhost")) {
            String errorMsg = "Forbidden Host";
            ctx.write(HttpErrorUtil.buildHttpErrorMessage(HttpResponseStatus.FORBIDDEN, errorMsg));
            ctx.flush();
            return false;
        }

        // forbid reqeust to some port
        int originalPort = HostNamePortUtil.getPort(httpRequest);
        for (int fobiddenPort : forbiddenPorts) {
            if (originalPort == fobiddenPort) {
                String errorMsg = "Forbidden Port";
                ctx.write(HttpErrorUtil.buildHttpErrorMessage(HttpResponseStatus.FORBIDDEN, errorMsg));
                ctx.flush();
                return false;
            }
        }

    } else {
        if (isPacRequest) {
            return false;
        }
    }

    return true;
}

From source file:de.eightnine.rec.HttpStaticFileServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (!request.getDecoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);//  w  ww.  jav  a 2s . c om
        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
                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.");
        }
    });

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

From source file:divconq.bus.net.ServerHandler.java

License:Open Source License

@Override
public void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
    // Handle a bad request.
    if (!req.getDecoderResult().isSuccess()) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
        return;/*from   ww w .  java2s .  co m*/
    }

    // Allow only GET methods.
    if (req.getMethod() != HttpMethod.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;
    }

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

    if (CommonHandler.BUS_PATH.equals(req.getUri())) {
        // Handshake
        WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
                getWebSocketLocation(req), null, false);

        this.handshaker = wsFactory.newHandshaker(req);

        if (this.handshaker == null)
            WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
        else
            this.handshaker.handshake(ctx.channel(), req);

        return;
    }

    FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND);
    this.sendHttpResponse(ctx, req, res);
}

From source file:divconq.bus.net.ServerHandler.java

License:Open Source License

public 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  w  w .  ja v a  2  s .  com
        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);
}

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