Search in sources :

Example 61 with RequestContext

use of com.netflix.zuul.context.RequestContext in project spring-cloud-netflix by spring-cloud.

the class SendErrorFilter method run.

@Override
public Object run() {
    try {
        RequestContext ctx = RequestContext.getCurrentContext();
        ZuulException exception = findZuulException(ctx.getThrowable());
        HttpServletRequest request = ctx.getRequest();
        request.setAttribute("javax.servlet.error.status_code", exception.nStatusCode);
        log.warn("Error during filtering", exception);
        request.setAttribute("javax.servlet.error.exception", exception);
        if (StringUtils.hasText(exception.errorCause)) {
            request.setAttribute("javax.servlet.error.message", exception.errorCause);
        }
        RequestDispatcher dispatcher = request.getRequestDispatcher(this.errorPath);
        if (dispatcher != null) {
            ctx.set(SEND_ERROR_FILTER_RAN, true);
            if (!ctx.getResponse().isCommitted()) {
                ctx.setResponseStatusCode(exception.nStatusCode);
                dispatcher.forward(request, ctx.getResponse());
            }
        }
    } catch (Exception ex) {
        ReflectionUtils.rethrowRuntimeException(ex);
    }
    return null;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ZuulException(com.netflix.zuul.exception.ZuulException) RequestContext(com.netflix.zuul.context.RequestContext) RequestDispatcher(javax.servlet.RequestDispatcher) ZuulRuntimeException(org.springframework.cloud.netflix.zuul.util.ZuulRuntimeException) ZuulException(com.netflix.zuul.exception.ZuulException)

Example 62 with RequestContext

use of com.netflix.zuul.context.RequestContext in project spring-cloud-netflix by spring-cloud.

the class SendResponseFilter method writeResponse.

private void writeResponse() throws Exception {
    RequestContext context = RequestContext.getCurrentContext();
    // there is no body to send
    if (context.getResponseBody() == null && context.getResponseDataStream() == null) {
        return;
    }
    HttpServletResponse servletResponse = context.getResponse();
    if (servletResponse.getCharacterEncoding() == null) {
        // only set if not set
        servletResponse.setCharacterEncoding("UTF-8");
    }
    OutputStream outStream = servletResponse.getOutputStream();
    InputStream is = null;
    try {
        if (RequestContext.getCurrentContext().getResponseBody() != null) {
            String body = RequestContext.getCurrentContext().getResponseBody();
            writeResponse(new ByteArrayInputStream(body.getBytes(servletResponse.getCharacterEncoding())), outStream);
            return;
        }
        boolean isGzipRequested = false;
        final String requestEncoding = context.getRequest().getHeader(ZuulHeaders.ACCEPT_ENCODING);
        if (requestEncoding != null && HTTPRequestUtils.getInstance().isGzipped(requestEncoding)) {
            isGzipRequested = true;
        }
        is = context.getResponseDataStream();
        InputStream inputStream = is;
        if (is != null) {
            if (context.sendZuulResponse()) {
                // else, stream gzip directly to client
                if (context.getResponseGZipped() && !isGzipRequested) {
                    // If origin tell it's GZipped but the content is ZERO bytes,
                    // don't try to uncompress
                    final Long len = context.getOriginContentLength();
                    if (len == null || len > 0) {
                        try {
                            inputStream = new GZIPInputStream(is);
                        } catch (java.util.zip.ZipException ex) {
                            log.debug("gzip expected but not " + "received assuming unencoded response " + RequestContext.getCurrentContext().getRequest().getRequestURL().toString());
                            inputStream = is;
                        }
                    } else {
                    // Already done : inputStream = is;
                    }
                } else if (context.getResponseGZipped() && isGzipRequested) {
                    servletResponse.setHeader(ZuulHeaders.CONTENT_ENCODING, "gzip");
                }
                writeResponse(inputStream, outStream);
            }
        }
    } finally {
        /**
         * We must ensure that the InputStream provided by our upstream pooling mechanism is ALWAYS closed
         * even in the case of wrapped streams, which are supplied by pooled sources such as Apache's
         * PoolingHttpClientConnectionManager. In that particular case, the underlying HTTP connection will
         * be returned back to the connection pool iif either close() is explicitly called, a read
         * error occurs, or the end of the underlying stream is reached. If, however a write error occurs, we will
         * end up leaking a connection from the pool without an explicit close()
         *
         * @author Johannes Edmeier
         */
        if (is != null) {
            try {
                is.close();
            } catch (Exception ex) {
                log.warn("Error while closing upstream input stream", ex);
            }
        }
        try {
            Object zuulResponse = RequestContext.getCurrentContext().get("zuulResponse");
            if (zuulResponse instanceof Closeable) {
                ((Closeable) zuulResponse).close();
            }
            outStream.flush();
        // The container will close the stream for us
        } catch (IOException ex) {
            log.warn("Error while sending response to client: " + ex.getMessage());
        }
    }
}
Also used : GZIPInputStream(java.util.zip.GZIPInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) Closeable(java.io.Closeable) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) IOException(java.io.IOException) GZIPInputStream(java.util.zip.GZIPInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) RequestContext(com.netflix.zuul.context.RequestContext)

Example 63 with RequestContext

use of com.netflix.zuul.context.RequestContext in project spring-cloud-netflix by spring-cloud.

the class ProxyRequestHelper method buildZuulRequestURI.

public String buildZuulRequestURI(HttpServletRequest request) {
    RequestContext context = RequestContext.getCurrentContext();
    String uri = request.getRequestURI();
    String contextURI = (String) context.get(REQUEST_URI_KEY);
    if (contextURI != null) {
        try {
            uri = UriUtils.encodePath(contextURI, characterEncoding(request));
        } catch (Exception e) {
            log.debug("unable to encode uri path from context, falling back to uri from request", e);
        }
    }
    return uri;
}
Also used : RequestContext(com.netflix.zuul.context.RequestContext) IOException(java.io.IOException)

Example 64 with RequestContext

use of com.netflix.zuul.context.RequestContext in project spring-cloud-netflix by spring-cloud.

the class ProxyRequestHelper method isIncludedHeader.

public boolean isIncludedHeader(String headerName) {
    String name = headerName.toLowerCase();
    RequestContext ctx = RequestContext.getCurrentContext();
    if (ctx.containsKey(IGNORED_HEADERS)) {
        Object object = ctx.get(IGNORED_HEADERS);
        if (object instanceof Collection && ((Collection<?>) object).contains(name)) {
            return false;
        }
    }
    switch(name) {
        case "host":
        case "connection":
        case "content-length":
        case "content-encoding":
        case "server":
        case "transfer-encoding":
        case "x-application-context":
            return false;
        default:
            return true;
    }
}
Also used : Collection(java.util.Collection) RequestContext(com.netflix.zuul.context.RequestContext)

Example 65 with RequestContext

use of com.netflix.zuul.context.RequestContext in project spring-cloud-netflix by spring-cloud.

the class ProxyRequestHelper method buildZuulRequestHeaders.

public MultiValueMap<String, String> buildZuulRequestHeaders(HttpServletRequest request) {
    RequestContext context = RequestContext.getCurrentContext();
    MultiValueMap<String, String> headers = new HttpHeaders();
    Enumeration<String> headerNames = request.getHeaderNames();
    if (headerNames != null) {
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            if (isIncludedHeader(name)) {
                Enumeration<String> values = request.getHeaders(name);
                while (values.hasMoreElements()) {
                    String value = values.nextElement();
                    headers.add(name, value);
                }
            }
        }
    }
    Map<String, String> zuulRequestHeaders = context.getZuulRequestHeaders();
    for (String header : zuulRequestHeaders.keySet()) {
        headers.set(header, zuulRequestHeaders.get(header));
    }
    headers.set(HttpHeaders.ACCEPT_ENCODING, "gzip");
    return headers;
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) RequestContext(com.netflix.zuul.context.RequestContext)

Aggregations

RequestContext (com.netflix.zuul.context.RequestContext)163 Test (org.junit.Test)59 HttpServletRequest (javax.servlet.http.HttpServletRequest)27 ZuulRoute (org.springframework.cloud.netflix.zuul.filters.ZuulProperties.ZuulRoute)24 Before (org.junit.Before)23 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)22 Set (java.util.Set)10 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)9 ZuulException (com.netflix.zuul.exception.ZuulException)7 InputStream (java.io.InputStream)7 HashSet (java.util.HashSet)7 HttpServletResponse (javax.servlet.http.HttpServletResponse)7 Route (org.springframework.cloud.netflix.zuul.filters.Route)7 ZuulProperties (org.springframework.cloud.netflix.zuul.filters.ZuulProperties)7 IOException (java.io.IOException)6 HttpServletRequestWrapper (com.netflix.zuul.http.HttpServletRequestWrapper)4 ByteArrayInputStream (java.io.ByteArrayInputStream)4 List (java.util.List)4 HttpHeaders (org.springframework.http.HttpHeaders)4 RateLimitCheck (com.giffing.bucket4j.spring.boot.starter.context.RateLimitCheck)3