Java Code Examples for com.netflix.zuul.context.RequestContext#getCurrentContext()
The following examples show how to use
com.netflix.zuul.context.RequestContext#getCurrentContext() .
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: SwaggerBasePathRewritingFilter.java From e-commerce-microservice with Apache License 2.0 | 6 votes |
@Override public Object run() { RequestContext context = RequestContext.getCurrentContext(); context.getResponse().setCharacterEncoding("UTF-8"); String rewrittenResponse = rewriteBasePath(context); if (context.getResponseGZipped()) { try { context.setResponseDataStream(new ByteArrayInputStream(gzipData(rewrittenResponse))); } catch (IOException e) { log.error("Swagger-docs filter error", e); } } else { context.setResponseBody(rewrittenResponse); } return null; }
Example 2
Source File: ResponseFilter.java From demo-project with MIT License | 6 votes |
@Override public Object run(){ RequestContext ctx = RequestContext.getCurrentContext(); String id = ctx.getZuulRequestHeaders().get("id"); ctx.getResponse().addHeader("id", id); try { BufferedReader reader = new BufferedReader(new InputStreamReader(ctx.getResponseDataStream())); String response = reader.readLine(); LOGGER.info("响应为:{}", response); //写到输出流中,本来可以由zuul框架来操作,但是我们已经读取了输入流,zuul读不到数据了,所以要手动写响应到response ctx.getResponse().setHeader("Content-Type","application/json;charset=utf-8"); ctx.getResponse().getWriter().write(response); } catch (Exception e) { } return null; }
Example 3
Source File: ErrorFilter.java From micro-service with Apache License 2.0 | 6 votes |
@Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); //HttpServletResponse response = ctx.getResponse(); log.info("进入错误异常的过滤器!"); log.info("==============="); // log.info(String.format("%s request to %s", request.getMethod(), request.getRequestURL().toString())); // System.out.println(request.getRequestURL()); // Object accessToken = request.getParameter("accessToken"); // if(accessToken == null) { // log.warn("access token is empty"); // ctx.setSendZuulResponse(false); // ctx.setResponseStatusCode(401); // return null; // } // log.info("access token ok"); return null; }
Example 4
Source File: LmitFilterCluster.java From fw-spring-cloud with Apache License 2.0 | 6 votes |
@Override public Object run(){ RequestContext ctx = RequestContext.getCurrentContext(); long currentSecond = System.currentTimeMillis() / 1000; String key="fw-cloud-zuul-extend:"+"limit:"+currentSecond; try{ if(!redisTemplate.hasKey(key)){ redisTemplate.opsForValue().set(key,LIMIT_INIT_VALUE,LIMIT_CACHE_TIME,TimeUnit.SECONDS); } Long increment = redisTemplate.opsForValue().increment(key, 1); if(increment>=LIMIT_RATE_CLUSTER){ ctx.setSendZuulResponse(false); //失败之后通知后续不应该执行了 ctx.set("isShould",false); ctx.setResponseBody(JSONUtil.toJsonStr(FwResult.failedMsg("当前访问量较大,请稍后重试"))); ctx.getResponse().setContentType(APPLICATION_JSON_CHARSET_UTF8); return null; } }catch (Exception e){ log.error("LmitFilterCluster exception:{}",e); rateLimiter.acquire(); } return null; }
Example 5
Source File: SwaggerBasePathRewritingFilter.java From okta-jhipster-microservices-oauth-example with Apache License 2.0 | 6 votes |
@Override public Object run() { RequestContext context = RequestContext.getCurrentContext(); context.getResponse().setCharacterEncoding("UTF-8"); String rewrittenResponse = rewriteBasePath(context); if (context.getResponseGZipped()) { try { context.setResponseDataStream(new ByteArrayInputStream(gzipData(rewrittenResponse))); } catch (IOException e) { log.error("Swagger-docs filter error", e); } } else { context.setResponseBody(rewrittenResponse); } return null; }
Example 6
Source File: SwaggerBasePathRewritingFilterTest.java From java-microservices-examples with Apache License 2.0 | 6 votes |
@Test public void run_on_valid_response_gzip() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/service1" + DEFAULT_URL); RequestContext context = RequestContext.getCurrentContext(); context.setRequest(request); MockHttpServletResponse response = new MockHttpServletResponse(); context.setResponseGZipped(true); context.setResponse(response); context.setResponseDataStream(new ByteArrayInputStream(gzipData("{\"basePath\":\"/\"}"))); filter.run(); assertEquals("UTF-8", response.getCharacterEncoding()); InputStream responseDataStream = new GZIPInputStream(context.getResponseDataStream()); String responseBody = IOUtils.toString(responseDataStream, StandardCharsets.UTF_8); assertEquals("{\"basePath\":\"/service1\"}", responseBody); }
Example 7
Source File: AddResponseIDHeaderFilter.java From Mastering-Spring-Cloud with MIT License | 5 votes |
@Override public Object run() { RequestContext context = RequestContext.getCurrentContext(); HttpServletResponse servletResponse = context.getResponse(); servletResponse.addHeader("X-Response-ID", String.valueOf(id++)); return null; }
Example 8
Source File: JWTTokenRelayFilter.java From jhipster-registry with Apache License 2.0 | 5 votes |
@Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); @SuppressWarnings("unchecked") Set<String> headers = (Set<String>) ctx.get("ignoredHeaders"); // JWT tokens should be relayed to the resource servers headers.remove("authorization"); return null; }
Example 9
Source File: SpecialRoutesFilter.java From spring-microservices-in-action with Apache License 2.0 | 5 votes |
@Override public Object run() { // Action: The action to be executed if the Criteria is met RequestContext ctx = RequestContext.getCurrentContext(); AbTestingRoute abTestRoute = getAbRoutingInfo(filterUtils.getServiceId()); // Check the SpecialRoutes service to see is there any alternate endpoint for that service ID if (abTestRoute != null && useSpecialRoute(abTestRoute)) { // Determine that the request needs to be routed to that new alternate endpoint or not. String route = buildRouteString(ctx.getRequest().getRequestURI(), abTestRoute.getEndpoint(), ctx.get("serviceId").toString()); forwardToSpecialRoute(route); } return null; }
Example 10
Source File: PageRedirectionFilter.java From api-layer with Eclipse Public License 2.0 | 5 votes |
/** * When the filter runs, it first finds the Location url in cache. If matched url can be found in cache, it then replaces Location with the matched url. * If not, the filter will find the matched url in Discovery Service. If matched url can be found in Discovery Service, the filter will put the matched * url to cache, and replace Location with the matched url * * @return null */ @Override public Object run() { RequestContext context = RequestContext.getCurrentContext(); Optional<Pair<String, String>> locationHeader = context.getZuulResponseHeaders() .stream() .filter(stringPair -> LOCATION.equals(stringPair.first())) .findFirst(); if (locationHeader.isPresent()) { String location = locationHeader.get().second(); //find matched url in cache String transformedUrl = foundUrlInTable(location); if (transformedUrl != null) { transformLocation(locationHeader.get(), transformedUrl); } else { //find matched url in Discovery Service Optional<String> transformedUrlOp = getMatchedUrlFromDS(location); if (transformedUrlOp.isPresent()) { transformedUrl = transformedUrlOp.get(); //Put matched url to cache routeTable.put(location, transformedUrl); transformLocation(locationHeader.get(), transformedUrl); } } } return null; }
Example 11
Source File: RateLimitingFilter.java From e-commerce-microservice with Apache License 2.0 | 5 votes |
/** * Create a Zuul response error when the API limit is exceeded. */ private void apiLimitExceeded() { RequestContext ctx = RequestContext.getCurrentContext(); ctx.setResponseStatusCode(HttpStatus.TOO_MANY_REQUESTS.value()); if (ctx.getResponseBody() == null) { ctx.setResponseBody("API rate limit exceeded"); ctx.setSendZuulResponse(false); } }
Example 12
Source File: HandlerController.java From roncoo-education with MIT License | 5 votes |
@RequestMapping("/error") @ResponseStatus(HttpStatus.OK) public Result<String> error() { RequestContext ctx = RequestContext.getCurrentContext(); Throwable throwable = ctx.getThrowable(); if(null != throwable && throwable instanceof ZuulException ){ ZuulException e = (ZuulException) ctx.getThrowable(); return Result.error(e.nStatusCode, e.errorCause); } return Result.error(ResultEnum.ERROR); }
Example 13
Source File: RequestLoggingFilter.java From Showcase with Apache License 2.0 | 5 votes |
@Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); LOGGER.info(String.format("%s request to %s", request.getMethod(), request.getRequestURL().toString())); return null; }
Example 14
Source File: BaseResponseFilter.java From convergent-ui with Apache License 2.0 | 5 votes |
@Override public boolean shouldFilter() { RequestContext ctx = RequestContext.getCurrentContext(); String contentType = getContentType(ctx); String verb = getVerb(ctx.getRequest()); return "text/html".equals(contentType) && "GET".equalsIgnoreCase(verb) && (!ctx.getZuulResponseHeaders().isEmpty() || ctx.getResponseDataStream() != null || ctx.getResponseBody() != null); }
Example 15
Source File: CurrentRequestContextTest.java From api-layer with Eclipse Public License 2.0 | 5 votes |
public void lockAndClearRequestContext() { currentRequestContext.lock(); RequestContext.testSetCurrentContext(null); ctx = RequestContext.getCurrentContext(); ctx.clear(); ctx.setResponse(new MockHttpServletResponse()); }
Example 16
Source File: DataFilter.java From xmfcn-spring-cloud with Apache License 2.0 | 4 votes |
/** * 修改返回头 */ private void modifyResponseHeader() { RequestContext context = RequestContext.getCurrentContext(); HttpServletResponse servletResponse = context.getResponse(); servletResponse.addHeader("content-type", "image/jpeg;charset=utf-8"); }
Example 17
Source File: CustomFilter.java From Spring-Boot-Examples with MIT License | 4 votes |
@Override public Object run() { RequestContext context = RequestContext.getCurrentContext(); context.addZuulRequestHeader("Code-Couple-Header", "CodeCouple!"); return null; }
Example 18
Source File: AddRequestHeaderFilter.java From Spring with Apache License 2.0 | 4 votes |
@Override public Object run() throws ZuulException { final RequestContext currentContext = RequestContext.getCurrentContext(); currentContext.addZuulRequestHeader("x-location", "USA"); return null; //return doesn't matter }
Example 19
Source File: SentinelZuulPreFilter.java From Sentinel with Apache License 2.0 | 4 votes |
@Override public Object run() throws ZuulException { RequestContext ctx = RequestContext.getCurrentContext(); String origin = parseOrigin(ctx.getRequest()); String routeId = (String)ctx.get(ZuulConstant.PROXY_ID_KEY); Deque<EntryHolder> holders = new ArrayDeque<>(); String fallBackRoute = routeId; try { if (StringUtil.isNotBlank(routeId)) { ContextUtil.enter(GATEWAY_CONTEXT_ROUTE_PREFIX + routeId, origin); doSentinelEntry(routeId, RESOURCE_MODE_ROUTE_ID, ctx, holders); } Set<String> matchingApis = pickMatchingApiDefinitions(ctx); if (!matchingApis.isEmpty() && ContextUtil.getContext() == null) { ContextUtil.enter(ZuulConstant.ZUUL_DEFAULT_CONTEXT, origin); } for (String apiName : matchingApis) { fallBackRoute = apiName; doSentinelEntry(apiName, RESOURCE_MODE_CUSTOM_API_NAME, ctx, holders); } } catch (BlockException ex) { ZuulBlockFallbackProvider zuulBlockFallbackProvider = ZuulBlockFallbackManager.getFallbackProvider( fallBackRoute); BlockResponse blockResponse = zuulBlockFallbackProvider.fallbackResponse(fallBackRoute, ex); // Prevent routing from running ctx.setRouteHost(null); ctx.set(ZuulConstant.SERVICE_ID_KEY, null); // Set fallback response. ctx.setResponseBody(blockResponse.toString()); ctx.setResponseStatusCode(blockResponse.getCode()); // Set Response ContentType ctx.getResponse().setContentType("application/json; charset=utf-8"); } finally { // We don't exit the entry here. We need to exit the entries in post filter to record Rt correctly. // So here the entries will be carried in the request context. if (!holders.isEmpty()) { ctx.put(ZuulConstant.ZUUL_CTX_SENTINEL_ENTRIES_KEY, holders); } } return null; }
Example 20
Source File: FilterUtils.java From spring-microservices-in-action with Apache License 2.0 | 2 votes |
/** * Get the access token from the header of a HTTP request. * * @return The value of the authentication token. */ public final String getAuthToken(){ RequestContext ctx = RequestContext.getCurrentContext(); return ctx.getRequest().getHeader(AUTH_TOKEN); }