diff --git a/zuul-simple-webapp/build.gradle b/zuul-simple-webapp/build.gradle index ef9851e751..7f21f769d5 100644 --- a/zuul-simple-webapp/build.gradle +++ b/zuul-simple-webapp/build.gradle @@ -4,8 +4,8 @@ apply plugin: 'jetty' dependencies { compile project(":zuul-core") - - compile 'org.apache.httpcomponents:httpclient:4.3.2' + + compile 'org.apache.httpcomponents:httpclient:4.5' providedCompile 'javax.servlet:servlet-api:2.5' } diff --git a/zuul-simple-webapp/src/main/groovy/filters/post/SendResponse.groovy b/zuul-simple-webapp/src/main/groovy/filters/post/SendResponseFilter.groovy similarity index 75% rename from zuul-simple-webapp/src/main/groovy/filters/post/SendResponse.groovy rename to zuul-simple-webapp/src/main/groovy/filters/post/SendResponseFilter.groovy index aeb5ed4083..c63cbf0af5 100644 --- a/zuul-simple-webapp/src/main/groovy/filters/post/SendResponse.groovy +++ b/zuul-simple-webapp/src/main/groovy/filters/post/SendResponseFilter.groovy @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +package filters.post import com.netflix.config.DynamicBooleanProperty import com.netflix.config.DynamicIntProperty @@ -23,22 +24,22 @@ import com.netflix.zuul.constants.ZuulConstants import com.netflix.zuul.constants.ZuulHeaders import com.netflix.zuul.context.Debug import com.netflix.zuul.context.RequestContext -import org.junit.Test -import org.junit.runner.RunWith -import org.mockito.Mockito -import org.mockito.runners.MockitoJUnitRunner +import org.slf4j.Logger +import org.slf4j.LoggerFactory +import javax.servlet.http.HttpServletResponse import java.nio.charset.Charset import java.util.zip.GZIPInputStream -import javax.servlet.http.HttpServletResponse +import java.util.zip.ZipException class SendResponseFilter extends ZuulFilter { + private static final Logger LOG = LoggerFactory.getLogger(SendResponseFilter.class); static DynamicBooleanProperty INCLUDE_DEBUG_HEADER = - DynamicPropertyFactory.getInstance().getBooleanProperty(ZuulConstants.ZUUL_INCLUDE_DEBUG_HEADER, false); + DynamicPropertyFactory.getInstance().getBooleanProperty(ZuulConstants.ZUUL_INCLUDE_DEBUG_HEADER, false); static DynamicIntProperty INITIAL_STREAM_BUFFER_SIZE = - DynamicPropertyFactory.getInstance().getIntProperty(ZuulConstants.ZUUL_INITIAL_STREAM_BUFFER_SIZE, 1024); + DynamicPropertyFactory.getInstance().getIntProperty(ZuulConstants.ZUUL_INITIAL_STREAM_BUFFER_SIZE, 1024); static DynamicBooleanProperty SET_CONTENT_LENGTH = DynamicPropertyFactory.getInstance().getBooleanProperty(ZuulConstants.ZUUL_SET_CONTENT_LENGTH, false); @@ -53,9 +54,9 @@ class SendResponseFilter extends ZuulFilter { } boolean shouldFilter() { - return !RequestContext.currentContext.getZuulResponseHeaders().isEmpty() || - RequestContext.currentContext.getResponseDataStream() != null || - RequestContext.currentContext.responseBody != null + return !RequestContext.getCurrentContext().getZuulResponseHeaders().isEmpty() || + RequestContext.getCurrentContext().getResponseDataStream() != null || + RequestContext.getCurrentContext().responseBody != null } Object run() { @@ -64,10 +65,11 @@ class SendResponseFilter extends ZuulFilter { } void writeResponse() { - RequestContext context = RequestContext.currentContext + RequestContext context = RequestContext.getCurrentContext() - // there is no body to send - if (context.getResponseBody() == null && context.getResponseDataStream() == null) return; + if (context.getResponseBody() == null && context.getResponseDataStream() == null) { + return + }; HttpServletResponse servletResponse = context.getResponse() servletResponse.setCharacterEncoding("UTF-8") @@ -75,8 +77,8 @@ class SendResponseFilter extends ZuulFilter { OutputStream outStream = servletResponse.getOutputStream(); InputStream is = null try { - if (RequestContext.currentContext.responseBody != null) { - String body = RequestContext.currentContext.responseBody + if (RequestContext.getCurrentContext().responseBody != null) { + String body = RequestContext.getCurrentContext().responseBody writeResponse(new ByteArrayInputStream(body.getBytes(Charset.forName("UTF-8"))), outStream) return; } @@ -90,19 +92,16 @@ class SendResponseFilter extends ZuulFilter { InputStream inputStream = is if (is != null) { if (context.sendZuulResponse()) { - // if origin response is gzipped, and client has not requested gzip, decompress stream - // before sending to client - // else, stream gzip directly to client if (context.getResponseGZipped() && !isGzipRequested) try { inputStream = new GZIPInputStream(is); - - } catch (java.util.zip.ZipException e) { - println("gzip expected but not received assuming unencoded response" + RequestContext.currentContext.getRequest().getRequestURL().toString()) + } catch (ZipException e) { + LOG.error("gzip expected but not received assuming unencoded response" + RequestContext.getCurrentContext().getRequest().getRequestURL().toString()) inputStream = is } - else if (context.getResponseGZipped() && isGzipRequested) + else if (context.getResponseGZipped() && isGzipRequested) { servletResponse.setHeader(ZuulHeaders.CONTENT_ENCODING, "gzip") + } writeResponse(inputStream, outStream) } } @@ -110,11 +109,9 @@ class SendResponseFilter extends ZuulFilter { } finally { try { is?.close(); - outStream.flush() outStream.close() } catch (IOException e) { - } } } @@ -123,15 +120,11 @@ class SendResponseFilter extends ZuulFilter { byte[] bytes = new byte[INITIAL_STREAM_BUFFER_SIZE.get()]; int bytesRead = -1; while ((bytesRead = zin.read(bytes)) != -1) { -// if (Debug.debugRequest() && !Debug.debugRequestHeadersOnly()) { -// Debug.addRequestDebug("OUTBOUND: < " + new String(bytes, 0, bytesRead)); -// } try { out.write(bytes, 0, bytesRead); out.flush(); } catch (IOException e) { - //ignore e.printStackTrace() } @@ -155,13 +148,6 @@ class SendResponseFilter extends ZuulFilter { debugHeader += "[[[${it}]]]"; } - /* - rd = (List) RequestContext.getCurrentContext().get("requestDebug"); - rd?.each { - debugHeader += "[[[REQUEST_DEBUG::${it}]]]"; - } - */ - if (INCLUDE_DEBUG_HEADER.get()) servletResponse.addHeader("X-Zuul-Debug-Header", debugHeader) if (Debug.debugRequest()) { @@ -185,4 +171,4 @@ class SendResponseFilter extends ZuulFilter { } } -} \ No newline at end of file +} diff --git a/zuul-simple-webapp/src/main/groovy/filters/post/Stats.groovy b/zuul-simple-webapp/src/main/groovy/filters/post/Stats.groovy index 041fe80eae..23b4f9800f 100755 --- a/zuul-simple-webapp/src/main/groovy/filters/post/Stats.groovy +++ b/zuul-simple-webapp/src/main/groovy/filters/post/Stats.groovy @@ -13,19 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package scripts.postProcess +package filters.post import com.netflix.zuul.ZuulFilter import com.netflix.zuul.context.RequestContext -import org.junit.Assert -import org.junit.Test -import org.junit.runner.RunWith -import org.mockito.Mock -import org.mockito.runners.MockitoJUnitRunner - -import javax.servlet.http.HttpServletRequest -import javax.servlet.http.HttpServletResponse - /** * @author Mikey Cohen * Date: 2/3/12 diff --git a/zuul-simple-webapp/src/main/groovy/filters/pre/Debug.groovy b/zuul-simple-webapp/src/main/groovy/filters/pre/DebugFilter.groovy similarity index 94% rename from zuul-simple-webapp/src/main/groovy/filters/pre/Debug.groovy rename to zuul-simple-webapp/src/main/groovy/filters/pre/DebugFilter.groovy index 72da19d5a3..14db5ba6e8 100644 --- a/zuul-simple-webapp/src/main/groovy/filters/pre/Debug.groovy +++ b/zuul-simple-webapp/src/main/groovy/filters/pre/DebugFilter.groovy @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package scripts.preProcess +package filters.pre import com.netflix.config.DynamicBooleanProperty import com.netflix.config.DynamicPropertyFactory @@ -38,9 +38,11 @@ class DebugFilter extends ZuulFilter { } boolean shouldFilter() { - if ("true".equals(RequestContext.getCurrentContext().getRequest().getParameter(debugParameter.get()))) return true; - return routingDebug.get(); + if ("true".equals(RequestContext.getCurrentContext().getRequest().getParameter(debugParameter.get()))) { + return true + } + return routingDebug.get(); } Object run() { diff --git a/zuul-simple-webapp/src/main/groovy/filters/pre/DebugRequest.groovy b/zuul-simple-webapp/src/main/groovy/filters/pre/DebugRequest.groovy index 5fd38d6d7e..b929220503 100644 --- a/zuul-simple-webapp/src/main/groovy/filters/pre/DebugRequest.groovy +++ b/zuul-simple-webapp/src/main/groovy/filters/pre/DebugRequest.groovy @@ -13,21 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package scripts.preProcess +package filters.pre import com.netflix.zuul.ZuulFilter import com.netflix.zuul.context.Debug import com.netflix.zuul.context.RequestContext -import org.junit.Assert -import org.junit.Test -import org.junit.runner.RunWith -import org.mockito.Mock -import org.mockito.Mockito -import org.mockito.runners.MockitoJUnitRunner import javax.servlet.http.HttpServletRequest -import javax.servlet.http.HttpServletResponse - /** * @author Mikey Cohen * Date: 3/12/12 @@ -62,7 +54,6 @@ class DebugRequest extends ZuulFilter { String name = (String) headerIt.next() String value = req.getHeader(name) Debug.addRequestDebug("REQUEST:: > " + name + ":" + value) - } final RequestContext ctx = RequestContext.getCurrentContext() diff --git a/zuul-simple-webapp/src/main/groovy/filters/pre/PreDecoration.groovy b/zuul-simple-webapp/src/main/groovy/filters/pre/PreDecorationFilter.groovy similarity index 98% rename from zuul-simple-webapp/src/main/groovy/filters/pre/PreDecoration.groovy rename to zuul-simple-webapp/src/main/groovy/filters/pre/PreDecorationFilter.groovy index e65d2c9340..2925753cdf 100644 --- a/zuul-simple-webapp/src/main/groovy/filters/pre/PreDecoration.groovy +++ b/zuul-simple-webapp/src/main/groovy/filters/pre/PreDecorationFilter.groovy @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +package filters.pre import com.netflix.zuul.ZuulFilter import com.netflix.zuul.context.RequestContext diff --git a/zuul-simple-webapp/src/main/groovy/filters/route/SimpleHostRequest.groovy b/zuul-simple-webapp/src/main/groovy/filters/route/SimpleHostRoutingFilter.groovy similarity index 56% rename from zuul-simple-webapp/src/main/groovy/filters/route/SimpleHostRequest.groovy rename to zuul-simple-webapp/src/main/groovy/filters/route/SimpleHostRoutingFilter.groovy index 6f7e11e4cc..64c2dd2ebf 100644 --- a/zuul-simple-webapp/src/main/groovy/filters/route/SimpleHostRequest.groovy +++ b/zuul-simple-webapp/src/main/groovy/filters/route/SimpleHostRoutingFilter.groovy @@ -13,8 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - - +package filters.route import com.netflix.config.DynamicIntProperty import com.netflix.config.DynamicPropertyFactory @@ -23,40 +22,33 @@ import com.netflix.zuul.constants.ZuulConstants import com.netflix.zuul.context.Debug import com.netflix.zuul.context.RequestContext import com.netflix.zuul.util.HTTPRequestUtils -import org.apache.http.Header -import org.apache.http.HttpHost -import org.apache.http.HttpRequest -import org.apache.http.HttpResponse +import org.apache.http.* import org.apache.http.client.HttpClient +import org.apache.http.client.RedirectStrategy import org.apache.http.client.methods.HttpPost import org.apache.http.client.methods.HttpPut -import org.apache.http.client.params.ClientPNames -import org.apache.http.conn.ClientConnectionManager -import org.apache.http.conn.scheme.PlainSocketFactory -import org.apache.http.conn.scheme.Scheme -import org.apache.http.conn.scheme.SchemeRegistry -import org.apache.http.conn.ssl.SSLSocketFactory -import org.apache.http.conn.ssl.TrustStrategy +import org.apache.http.client.methods.HttpUriRequest +import org.apache.http.config.Registry +import org.apache.http.config.RegistryBuilder +import org.apache.http.conn.HttpClientConnectionManager +import org.apache.http.conn.socket.ConnectionSocketFactory +import org.apache.http.conn.socket.PlainConnectionSocketFactory +import org.apache.http.conn.ssl.SSLConnectionSocketFactory +import org.apache.http.conn.ssl.SSLContexts import org.apache.http.entity.InputStreamEntity -import org.apache.http.impl.client.DefaultHttpClient +import org.apache.http.impl.client.CloseableHttpClient import org.apache.http.impl.client.DefaultHttpRequestRetryHandler -import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager +import org.apache.http.impl.client.HttpClientBuilder +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager import org.apache.http.message.BasicHeader import org.apache.http.message.BasicHttpRequest -import org.apache.http.params.CoreConnectionPNames -import org.apache.http.params.HttpParams import org.apache.http.protocol.HttpContext - import org.slf4j.Logger import org.slf4j.LoggerFactory import javax.net.ssl.SSLContext -import javax.net.ssl.TrustManager -import javax.net.ssl.X509TrustManager import javax.servlet.http.HttpServletRequest -import java.security.SecureRandom import java.util.concurrent.atomic.AtomicReference -import java.util.zip.GZIPInputStream class SimpleHostRoutingFilter extends ZuulFilter { @@ -71,12 +63,12 @@ class SimpleHostRoutingFilter extends ZuulFilter { } private static final DynamicIntProperty SOCKET_TIMEOUT = - DynamicPropertyFactory.getInstance().getIntProperty(ZuulConstants.ZUUL_HOST_SOCKET_TIMEOUT_MILLIS, 10000) + DynamicPropertyFactory.getInstance().getIntProperty(ZuulConstants.ZUUL_HOST_SOCKET_TIMEOUT_MILLIS, 10000) private static final DynamicIntProperty CONNECTION_TIMEOUT = - DynamicPropertyFactory.getInstance().getIntProperty(ZuulConstants.ZUUL_HOST_CONNECT_TIMEOUT_MILLIS, 2000) + DynamicPropertyFactory.getInstance().getIntProperty(ZuulConstants.ZUUL_HOST_CONNECT_TIMEOUT_MILLIS, 2000) - private static final AtomicReference CLIENT = new AtomicReference(newClient()); + private static final AtomicReference CLIENT = new AtomicReference(newClient()); private static final Timer CONNECTION_MANAGER_TIMER = new Timer(true); @@ -88,9 +80,13 @@ class SimpleHostRoutingFilter extends ZuulFilter { @Override void run() { try { - final HttpClient hc = CLIENT.get(); - if (hc == null) return; - hc.getConnectionManager().closeExpiredConnections(); + final CloseableHttpClient hc = CLIENT.get(); + + if (hc == null) { + return; + } + + hc.close(); } catch (Throwable t) { LOG.error("error closing expired connections", t); } @@ -100,38 +96,20 @@ class SimpleHostRoutingFilter extends ZuulFilter { public SimpleHostRoutingFilter() {} - private static final ClientConnectionManager newConnectionManager() { - SchemeRegistry schemeRegistry = new SchemeRegistry(); - schemeRegistry.register( - new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); - schemeRegistry.register(getSSLScheme()) + private static final HttpClientConnectionManager newConnectionManager() { + SSLContext sslContext = SSLContexts.createSystemDefault(); - ClientConnectionManager cm = new ThreadSafeClientConnManager(schemeRegistry); + Registry socketFactoryRegistry = RegistryBuilder.create() + .register("http", PlainConnectionSocketFactory.INSTANCE) + .register("https", new SSLConnectionSocketFactory(sslContext)) + .build(); + + HttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry); cm.setMaxTotal(Integer.parseInt(System.getProperty("zuul.max.host.connections", "200"))); cm.setDefaultMaxPerRoute(Integer.parseInt(System.getProperty("zuul.max.host.connections", "20"))); return cm; } - private static final Scheme getSSLScheme(){ - def nullTrustManager = [ - checkClientTrusted: { chain, authType -> }, - checkServerTrusted: { chain, authType -> }, - getAcceptedIssuers: { null } - ] - - def nullHostnameVerifier = [ - verify: { hostname, session -> true } - ] - - SSLContext sc = SSLContext.getInstance("SSL") - sc.init(null, [nullTrustManager as X509TrustManager] as TrustManager[], new SecureRandom()) - - SSLSocketFactory sf=new SSLSocketFactory(sc) - sf.hostnameVerifier=SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER - return new Scheme("https",sf,443) - - } - @Override String filterType() { return 'route' @@ -143,18 +121,18 @@ class SimpleHostRoutingFilter extends ZuulFilter { } boolean shouldFilter() { - return RequestContext.currentContext.getRouteHost() != null && RequestContext.currentContext.sendZuulResponse() + return RequestContext.getCurrentContext().getRouteHost() != null && RequestContext.getCurrentContext().sendZuulResponse() } private static final void loadClient() { - final HttpClient oldClient = CLIENT.get(); + final CloseableHttpClient oldClient = CLIENT.get(); CLIENT.set(newClient()) if (oldClient != null) { CONNECTION_MANAGER_TIMER.schedule(new TimerTask() { @Override void run() { try { - oldClient.getConnectionManager().shutdown(); + oldClient.close() } catch (Throwable t) { LOG.error("error shutting down old connection manager", t); } @@ -164,43 +142,42 @@ class SimpleHostRoutingFilter extends ZuulFilter { } - private static final HttpClient newClient() { - // I could statically cache the connection manager but we will probably want to make some of its properties - // dynamic in the near future also - HttpClient httpclient = new DefaultHttpClient(newConnectionManager()); - HttpParams httpParams = httpclient.getParams(); - httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, SOCKET_TIMEOUT.get()) - httpParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT.get()) - httpclient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, false)) - httpParams.setParameter(ClientPNames.COOKIE_POLICY, org.apache.http.client.params.CookiePolicy.IGNORE_COOKIES); - httpclient.setRedirectStrategy(new org.apache.http.client.RedirectStrategy() { + private static final CloseableHttpClient newClient() { + HttpClientBuilder builder = HttpClientBuilder.create() + builder.setConnectionManager(newConnectionManager()) + builder.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false)) + builder.setRedirectStrategy(new RedirectStrategy() { @Override - boolean isRedirected(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext httpContext) { + boolean isRedirected(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext httpContext) throws ProtocolException { return false } @Override - org.apache.http.client.methods.HttpUriRequest getRedirect(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext httpContext) { + HttpUriRequest getRedirect(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext httpContext) throws ProtocolException { return null } }) - return httpclient + + return builder.build() } Object run() { - HttpServletRequest request = RequestContext.currentContext.getRequest(); + HttpServletRequest request = RequestContext.getCurrentContext().getRequest(); Header[] headers = buildZuulRequestHeaders(request) String verb = getVerb(request); InputStream requestEntity = getRequestBody(request) - HttpClient httpclient = CLIENT.get() + CloseableHttpClient httpclient = CLIENT.get() String uri = request.getRequestURI() - if (RequestContext.currentContext.requestURI != null) { - uri = RequestContext.currentContext.requestURI + if (RequestContext.getCurrentContext().requestURI != null) { + uri = RequestContext.getCurrentContext().requestURI } try { HttpResponse response = forward(httpclient, verb, uri, request, headers, requestEntity) + Debug.addRequestDebug("ZUUL :: ${uri}") + Debug.addRequestDebug("ZUUL :: Response statusLine > ${response.getStatusLine()}") + Debug.addRequestDebug("ZUUL :: Response code > ${response.getStatusLine().statusCode}") setResponse(response) } catch (Exception e) { throw e; @@ -208,14 +185,12 @@ class SimpleHostRoutingFilter extends ZuulFilter { return null } - def InputStream debug(HttpClient httpclient, String verb, String uri, HttpServletRequest request, Header[] headers, InputStream requestEntity) { + InputStream debug(String verb, String uri, HttpServletRequest request, Header[] headers, InputStream requestEntity) { if (Debug.debugRequest()) { - - Debug.addRequestDebug("ZUUL:: host=${RequestContext.currentContext.getRouteHost()}") - + Debug.addRequestDebug("ZUUL:: host=${RequestContext.getCurrentContext().getRouteHost()}") headers.each { - Debug.addRequestDebug("ZUUL::> ${it.name} ${it.value}") + Debug.addRequestDebug("ZUUL:: Header > ${it.name} ${it.value}") } String query = request.queryString != null ? "?" + request.queryString : "" @@ -229,22 +204,24 @@ class SimpleHostRoutingFilter extends ZuulFilter { } InputStream debugRequestEntity(InputStream inputStream) { - if (Debug.debugRequestHeadersOnly()) return inputStream - if (inputStream == null) return null + if (Debug.debugRequestHeadersOnly()) { + return inputStream + } + + if (inputStream == null) { + return null + } + String entity = inputStream.getText() - Debug.addRequestDebug("ZUUL::> ${entity}") + Debug.addRequestDebug("ZUUL:: Entity > ${entity}") return new ByteArrayInputStream(entity.bytes) } - def HttpResponse forward(HttpClient httpclient, String verb, String uri, HttpServletRequest request, Header[] headers, InputStream requestEntity) { - - requestEntity = debug(httpclient, verb, uri, request, headers, requestEntity) - - org.apache.http.HttpHost httpHost - - httpHost = getHttpHost() + HttpResponse forward(CloseableHttpClient httpclient, String verb, String uri, HttpServletRequest request, Header[] headers, InputStream requestEntity) { - org.apache.http.HttpRequest httpRequest; + requestEntity = debug(verb, uri, request, headers, requestEntity) + HttpHost httpHost = getHttpHost() + HttpRequest httpRequest; switch (verb) { case 'POST': @@ -263,15 +240,10 @@ class SimpleHostRoutingFilter extends ZuulFilter { try { httpRequest.setHeaders(headers) - HttpResponse zuulResponse = forwardRequest(httpclient, httpHost, httpRequest) - return zuulResponse + return forwardRequest(httpclient, httpHost, httpRequest) } finally { - // When HttpClient instance is no longer needed, - // shut down the connection manager to ensure - // immediate deallocation of all system resources -// httpclient.getConnectionManager().shutdown(); + //httpclient.close(); } - } HttpResponse forwardRequest(HttpClient httpclient, HttpHost httpHost, HttpRequest httpRequest) { @@ -279,14 +251,14 @@ class SimpleHostRoutingFilter extends ZuulFilter { } String getQueryString() { - HttpServletRequest request = RequestContext.currentContext.getRequest(); + HttpServletRequest request = RequestContext.getCurrentContext().getRequest(); String query = request.getQueryString() return (query != null) ? "?${query}" : ""; } HttpHost getHttpHost() { HttpHost httpHost - URL host = RequestContext.currentContext.getRouteHost() + URL host = RequestContext.getCurrentContext().getRouteHost() httpHost = new HttpHost(host.getHost(), host.getPort(), host.getProtocol()) @@ -294,28 +266,35 @@ class SimpleHostRoutingFilter extends ZuulFilter { } - def getRequestBody(HttpServletRequest request) { - Object requestEntity = null; + InputStream getRequestBody(HttpServletRequest request) { try { - requestEntity = request.getInputStream(); + return request.getInputStream(); } catch (IOException e) { - //no requestBody is ok. + LOG.warn(e.getMessage()) + return null } - return requestEntity } boolean isValidHeader(String name) { - if (name.toLowerCase().contains("content-length")) return false; - if (name.toLowerCase().equals("host")) return false; // set host according to origin vhost - if (!RequestContext.currentContext.responseGZipped) { - if (name.toLowerCase().contains("accept-encoding")) return false; + if (name.toLowerCase().contains("content-length")) { + return false + } + + if (name.toLowerCase().equals("host")) { + return false + } + + if (!RequestContext.getCurrentContext().responseGZipped) { + if (name.toLowerCase().contains("accept-encoding")) { + return false + } } - return true; + return true } - def Header[] buildZuulRequestHeaders(HttpServletRequest request) { + Header[] buildZuulRequestHeaders(HttpServletRequest request) { - def headers = new ArrayList() + ArrayList headers = new ArrayList() Enumeration headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String name = ((String) headerNames.nextElement()).toLowerCase(); @@ -323,45 +302,58 @@ class SimpleHostRoutingFilter extends ZuulFilter { if (isValidHeader(name)) headers.add(new BasicHeader(name, value)) } - Map zuulRequestHeaders = RequestContext.getCurrentContext().getZuulRequestHeaders(); + Map zuulRequestHeaders = RequestContext.getCurrentContext().getZuulRequestHeaders(); - zuulRequestHeaders.keySet().each { + zuulRequestHeaders.keySet().each { String it -> String name = it.toLowerCase() BasicHeader h = headers.find { BasicHeader he -> he.name == name } if (h != null) { headers.remove(h) } - headers.add(new BasicHeader((String) it, (String) zuulRequestHeaders[it])) + headers.add(new BasicHeader(it, zuulRequestHeaders[it])) } - if (RequestContext.currentContext.responseGZipped) { + if (RequestContext.getCurrentContext().responseGZipped) { headers.add(new BasicHeader("accept-encoding", "deflate, gzip")) } + return headers } - - String getVerb(HttpServletRequest request) { - String sMethod = request.getMethod(); - return sMethod.toUpperCase(); + String getVerb(HttpServletRequest request) { + return getVerb(request.getMethod().toUpperCase()); } String getVerb(String sMethod) { - if (sMethod == null) return "GET"; + if (sMethod == null) { + return "GET" + } + sMethod = sMethod.toLowerCase(); - if (sMethod.equalsIgnoreCase("post")) return "POST" - if (sMethod.equalsIgnoreCase("put")) return "PUT" - if (sMethod.equalsIgnoreCase("delete")) return "DELETE" - if (sMethod.equalsIgnoreCase("options")) return "OPTIONS" - if (sMethod.equalsIgnoreCase("head")) return "HEAD" + + if (sMethod.equalsIgnoreCase("post")) { + return "POST" + } + if (sMethod.equalsIgnoreCase("put")) { + return "PUT" + } + if (sMethod.equalsIgnoreCase("delete")) { + return "DELETE" + } + if (sMethod.equalsIgnoreCase("options")) { + return "OPTIONS" + } + if (sMethod.equalsIgnoreCase("head")) { + return "HEAD" + } return "GET" } void setResponse(HttpResponse response) { RequestContext context = RequestContext.getCurrentContext() - RequestContext.currentContext.set("hostZuulResponse", response) + RequestContext.getCurrentContext().set("hostZuulResponse", response) RequestContext.getCurrentContext().setResponseStatusCode(response.getStatusLine().statusCode) RequestContext.getCurrentContext().responseDataStream = response?.entity?.content @@ -386,16 +378,8 @@ class SimpleHostRoutingFilter extends ZuulFilter { if (context.responseDataStream) { byte[] origBytes = context.getResponseDataStream().bytes - ByteArrayInputStream byteStream = new ByteArrayInputStream(origBytes) - InputStream inputStream = byteStream - if (RequestContext.currentContext.responseGZipped) { - inputStream = new GZIPInputStream(byteStream); - } - - context.setResponseDataStream(new ByteArrayInputStream(origBytes)) } - } else { response.getAllHeaders()?.each { Header header -> RequestContext ctx = RequestContext.getCurrentContext() @@ -424,7 +408,6 @@ class SimpleHostRoutingFilter extends ZuulFilter { return true } } - } diff --git a/zuul-simple-webapp/src/main/java/com/netflix/zuul/StartServer.java b/zuul-simple-webapp/src/main/java/com/netflix/zuul/StartServer.java index 95711b7a25..aae5aaab69 100644 --- a/zuul-simple-webapp/src/main/java/com/netflix/zuul/StartServer.java +++ b/zuul-simple-webapp/src/main/java/com/netflix/zuul/StartServer.java @@ -16,19 +16,16 @@ package com.netflix.zuul; -import java.io.File; - -import javax.servlet.ServletContextEvent; -import javax.servlet.ServletContextListener; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.netflix.zuul.context.RequestContext; import com.netflix.zuul.filters.FilterRegistry; import com.netflix.zuul.groovy.GroovyCompiler; import com.netflix.zuul.groovy.GroovyFileFilter; import com.netflix.zuul.monitoring.MonitoringHelper; +import java.io.File; +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class StartServer implements ServletContextListener {