Java Code Examples for io.netty.handler.codec.http.HttpHeaders#setContentLength()

The following examples show how to use io.netty.handler.codec.http.HttpHeaders#setContentLength() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Router.java    From minnal with Apache License 2.0 6 votes vote down vote up
/**
 * Creates the http response from container response</p>
 * 
 * <li> Sets the content length to the http response from the container response. If content length is not available, computes from the response entity
 * <li> 
 * 
 * @param context
 * @param containerResponse
 * @param buffer
 * @return
 */
protected FullHttpResponse createHttpResponse(MessageContext context, ContainerResponse containerResponse, ByteBuf buffer) {
	FullHttpRequest httpRequest = context.getRequest();
	DefaultFullHttpResponse httpResponse = new DefaultFullHttpResponse(httpRequest.getProtocolVersion(), HttpResponseStatus.valueOf(containerResponse.getStatus()), buffer);
	int length = containerResponse.getLength();
	
	// FIXME Hack. is there a better way?
	if (length == -1 && containerResponse.getEntity() instanceof String) {
		final String entity = (String) containerResponse.getEntity();
		final byte[] encodedBytes = entity.getBytes(Charset.forName("UTF-8"));
		length = encodedBytes.length;
	}
	if (! containerResponse.getHeaders().containsKey(HttpHeaders.Names.CONTENT_LENGTH)) {
		HttpHeaders.setContentLength(httpResponse, length);
		logger.trace("Writing response status and headers {}, length {}", containerResponse, containerResponse.getLength());
	}

	for (Map.Entry<String, List<Object>> headerEntry : containerResponse.getHeaders().entrySet()) {
		HttpHeaders.addHeader(httpResponse, headerEntry.getKey(), Joiner.on(", ").join(headerEntry.getValue()));
	}
	return httpResponse;
}
 
Example 2
Source File: FallbackResponder.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
public void sendResponse(FullHttpRequest req, ChannelHandlerContext ctx) throws Exception {
   counter.inc();
   byte[] content = null;

   try(InputStream is = FallbackResponder.class.getClassLoader().getResourceAsStream(resource)) {
      content = IOUtils.toByteArray(is);
   }

   FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
   HttpHeaders.setContentLength(response, content.length);
   response.headers().set(HttpHeaders.Names.CONTENT_TYPE, MediaType.APPLICATION_XML_UTF_8.toString());
   response.content().writeBytes(content);
   ctx.write(response);
   ChannelFuture future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
   future.addListener(ChannelFutureListener.CLOSE);
}
 
Example 3
Source File: BlacklistFilter.java    From browserup-proxy with Apache License 2.0 6 votes vote down vote up
@Override
public HttpResponse clientToProxyRequest(HttpObject httpObject) {
    if (httpObject instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) httpObject;

        String url = getFullUrl(httpRequest);

        for (BlacklistEntry entry : blacklistedUrls) {
            if (HttpMethod.CONNECT.equals(httpRequest.getMethod()) && entry.getHttpMethodPattern() == null) {
                // do not allow CONNECTs to be blacklisted unless a method pattern is explicitly specified
                continue;
            }

            if (entry.matches(url, httpRequest.getMethod().name())) {
                HttpResponseStatus status = HttpResponseStatus.valueOf(entry.getStatusCode());
                HttpResponse resp = new DefaultFullHttpResponse(httpRequest.getProtocolVersion(), status);
                HttpHeaders.setContentLength(resp, 0L);

                return resp;
            }
        }
    }

    return null;
}
 
Example 4
Source File: WebSocketServerHandler.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
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);
        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);
    }
}
 
Example 5
Source File: BlacklistFilter.java    From AndroidHttpCapture with MIT License 6 votes vote down vote up
@Override
public HttpResponse clientToProxyRequest(HttpObject httpObject) {
    if (httpObject instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) httpObject;

        String url = getFullUrl(httpRequest);

        for (BlacklistEntry entry : blacklistedUrls) {
            if (HttpMethod.CONNECT.equals(httpRequest.getMethod()) && entry.getHttpMethodPattern() == null) {
                // do not allow CONNECTs to be blacklisted unless a method pattern is explicitly specified
                continue;
            }

            if (entry.matches(url, httpRequest.getMethod().name())) {
                HttpResponseStatus status = HttpResponseStatus.valueOf(entry.getStatusCode());
                HttpResponse resp = new DefaultFullHttpResponse(httpRequest.getProtocolVersion(), status);
                HttpHeaders.setContentLength(resp, 0L);

                return resp;
            }
        }
    }

    return null;
}
 
Example 6
Source File: BlacklistFilter.java    From CapturePacket with MIT License 6 votes vote down vote up
@Override
public HttpResponse clientToProxyRequest(HttpObject httpObject) {
    if (httpObject instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) httpObject;

        String url = getFullUrl(httpRequest);

        for (BlacklistEntry entry : blacklistedUrls) {
            if (HttpMethod.CONNECT.equals(httpRequest.getMethod()) && entry.getHttpMethodPattern() == null) {
                // do not allow CONNECTs to be blacklisted unless a method pattern is explicitly specified
                continue;
            }

            if (entry.matches(url, httpRequest.getMethod().name())) {
                HttpResponseStatus status = HttpResponseStatus.valueOf(entry.getStatusCode());
                HttpResponse resp = new DefaultFullHttpResponse(httpRequest.getProtocolVersion(), status);
                HttpHeaders.setContentLength(resp, 0L);

                return resp;
            }
        }
    }

    return null;
}
 
Example 7
Source File: NettyHttpFileHandler.java    From khs-stockticker with Apache License 2.0 6 votes vote down vote up
public void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
   if (res.getStatus().code() != 200) {
      ByteBuf f = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
      res.content().clear();
      res.content().writeBytes(f);
      f.release();
   }

   HttpHeaders.setContentLength(res, res.content().readableBytes());
   ChannelFuture f1;
   f1 = ctx.channel().writeAndFlush(res);

   if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) {
      f1.addListener(ChannelFutureListener.CLOSE);
   }
}
 
Example 8
Source File: BlacklistFilter.java    From Dream-Catcher with MIT License 6 votes vote down vote up
@Override
public HttpResponse clientToProxyRequest(HttpObject httpObject) {
    if (httpObject instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) httpObject;

        String url = getFullUrl(httpRequest);

        for (BlacklistEntry entry : blacklistedUrls) {
            if (HttpMethod.CONNECT.equals(httpRequest.getMethod()) && entry.getHttpMethodPattern() == null) {
                // do not allow CONNECTs to be blacklisted unless a method pattern is explicitly specified
                continue;
            }

            if (entry.matches(url, httpRequest.getMethod().name())) {
                HttpResponseStatus status = HttpResponseStatus.valueOf(entry.getStatusCode());
                HttpResponse resp = new DefaultFullHttpResponse(httpRequest.getProtocolVersion(), status);
                HttpHeaders.setContentLength(resp, 0L);

                return resp;
            }
        }
    }

    return null;
}
 
Example 9
Source File: SimpleWampWebsocketListener.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
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);
        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);
    }
}
 
Example 10
Source File: HttpResponseOutputStream.java    From spring-boot-starter-netty with Apache License 2.0 5 votes vote down vote up
private void writeResponse(boolean lastContent) {
    HttpResponse response = servletResponse.getNettyResponse();
    // TODO implement exceptions required by http://tools.ietf.org/html/rfc2616#section-4.4
    if (!HttpHeaders.isContentLengthSet(response)) {
        if (lastContent) {
            HttpHeaders.setContentLength(response, count);
        } else {
            HttpHeaders.setTransferEncodingChunked(response);
        }
    }
    ctx.write(response, ctx.voidPromise());
}
 
Example 11
Source File: WhitelistFilter.java    From AndroidHttpCapture with MIT License 5 votes vote down vote up
@Override
public HttpResponse clientToProxyRequest(HttpObject httpObject) {
    if (!whitelistEnabled) {
        return null;
    }

    if (httpObject instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) httpObject;

        // do not allow HTTP CONNECTs to be short-circuited
        if (ProxyUtils.isCONNECT(httpRequest)) {
            return null;
        }

        boolean urlWhitelisted = false;

        String url = getFullUrl(httpRequest);

        for (Pattern pattern : whitelistUrls) {
            if (pattern.matcher(url).matches()) {
                urlWhitelisted = true;
                break;
            }
        }

        if (!urlWhitelisted) {
            HttpResponseStatus status = HttpResponseStatus.valueOf(whitelistResponseCode);
            HttpResponse resp = new DefaultFullHttpResponse(httpRequest.getProtocolVersion(), status);
            HttpHeaders.setContentLength(resp, 0L);

            return resp;
        }
    }

    return null;
}
 
Example 12
Source File: WebsocketSinkServerHandler.java    From spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
private 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);
		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);
	}
}
 
Example 13
Source File: BrowserMobHttpFilterChain.java    From Dream-Catcher with MIT License 5 votes vote down vote up
@Override
public HttpResponse clientToProxyRequest(HttpObject httpObject) {
    if (proxyServer.isStopped()) {
        log.warn("Aborting request to {} because proxy is stopped", originalRequest.getUri());
        HttpResponse abortedResponse = new DefaultFullHttpResponse(originalRequest.getProtocolVersion(), HttpResponseStatus.SERVICE_UNAVAILABLE);
        HttpHeaders.setContentLength(abortedResponse, 0L);
        return abortedResponse;
    }

    for (HttpFilters filter : filters) {
        try {
            HttpResponse filterResponse = filter.clientToProxyRequest(httpObject);
            if (filterResponse != null) {
                // if we are short-circuiting the response to an HttpRequest, update ModifiedRequestAwareFilter instances
                // with this (possibly) modified HttpRequest before returning the short-circuit response
                if (httpObject instanceof HttpRequest) {
                    updateFiltersWithModifiedResponse((HttpRequest) httpObject);
                }

                return filterResponse;
            }
        } catch (RuntimeException e) {
            log.warn("Filter in filter chain threw exception. Filter method may have been aborted.", e);
        }
    }

    // if this httpObject is the HTTP request, set the modified request object on all ModifiedRequestAwareFilter
    // instances, so they have access to all modifications the request filters made while filtering
    if (httpObject instanceof HttpRequest) {
        updateFiltersWithModifiedResponse((HttpRequest) httpObject);
    }

    return null;
}
 
Example 14
Source File: WhitelistFilter.java    From Dream-Catcher with MIT License 5 votes vote down vote up
@Override
public HttpResponse clientToProxyRequest(HttpObject httpObject) {
    if (!whitelistEnabled) {
        return null;
    }

    if (httpObject instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) httpObject;

        // do not allow HTTP CONNECTs to be short-circuited
        if (ProxyUtils.isCONNECT(httpRequest)) {
            return null;
        }

        boolean urlWhitelisted = false;

        String url = getFullUrl(httpRequest);

        for (Pattern pattern : whitelistUrls) {
            if (pattern.matcher(url).matches()) {
                urlWhitelisted = true;
                break;
            }
        }

        if (!urlWhitelisted) {
            HttpResponseStatus status = HttpResponseStatus.valueOf(whitelistResponseCode);
            HttpResponse resp = new DefaultFullHttpResponse(httpRequest.getProtocolVersion(), status);
            HttpHeaders.setContentLength(resp, 0L);

            return resp;
        }
    }

    return null;
}
 
Example 15
Source File: HttpMessageSupport.java    From styx with Apache License 2.0 5 votes vote down vote up
public static HttpRequest httpRequest(HttpMethod method, String url, String body) {
    ByteBuf content = Unpooled.copiedBuffer(body.getBytes(Charset.forName("US-ASCII")));
    HttpRequest request = new DefaultFullHttpRequest(HTTP_1_1,
            method,
            url,
            content);
    HttpHeaders.setContentLength(request, content.writerIndex());
    return request;
}
 
Example 16
Source File: HttpMessageSupport.java    From styx with Apache License 2.0 5 votes vote down vote up
public static HttpResponse httpResponse(HttpResponseStatus status, String body) {
    ByteBuf content = Unpooled.copiedBuffer(body.getBytes(Charset.forName("US-ASCII")));
    HttpResponse response = new DefaultFullHttpResponse(
            HTTP_1_1,
            status,
            content);
    HttpHeaders.setContentLength(response, content.writerIndex());
    return response;
}
 
Example 17
Source File: HttpResponseOutputStream.java    From Jinx with Apache License 2.0 5 votes vote down vote up
private void writeResponse(boolean lastContent) {
    HttpResponse response = servletResponse.getNettyResponse();
    // TODO implement exceptions required by http://tools.ietf.org/html/rfc2616#section-4.4
    if (!HttpHeaders.isContentLengthSet(response)) {
        if (lastContent) {
            HttpHeaders.setContentLength(response, count);
        } else {
            HttpHeaders.setTransferEncodingChunked(response);
        }
    }
    ctx.write(response, ctx.voidPromise());
}
 
Example 18
Source File: LittleProxyMitmProxy.java    From LittleProxy-mitm with Apache License 2.0 5 votes vote down vote up
private HttpResponse createOfflineResponse() {
    ByteBuf buffer = Unpooled.wrappedBuffer("Offline response".getBytes());
    HttpResponse response = new DefaultFullHttpResponse(
            HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buffer);
    HttpHeaders.setContentLength(response, buffer.readableBytes());
    HttpHeaders.setHeader(response, HttpHeaders.Names.CONTENT_TYPE,
            "text/html");
    return response;
}
 
Example 19
Source File: HttpUtil.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public static void sendHttpResponseFull(ChannelHandlerContext ctx, FullHttpResponse response) {
	HttpHeaders.setContentLength(response, response.content().readableBytes());
   ChannelFuture f1 = ctx.channel().writeAndFlush(response);
   if ( !HttpResponseStatus.OK.equals(response.getStatus())) {
      f1.addListener(ChannelFutureListener.CLOSE);
   }
}
 
Example 20
Source File: NettyHttpServletResponse.java    From Jinx with Apache License 2.0 4 votes vote down vote up
@Override
public void setContentLengthLong(long len) {
    HttpHeaders.setContentLength(response, len);
}