Java Code Examples for com.netflix.zuul.context.RequestContext#setResponseBody()
The following examples show how to use
com.netflix.zuul.context.RequestContext#setResponseBody() .
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 flair-registry with Apache License 2.0 | 7 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: AccessFilter.java From cloud-project with Apache License 2.0 | 6 votes |
/** * 过滤逻辑 * @return 过滤结果 */ @Override public Object run() { RequestContext requestContext = RequestContext.getCurrentContext(); HttpServletRequest request = requestContext.getRequest(); logger.info("send {} request to {}",request.getMethod(),request.getRequestURL().toString()); Object accessToken = request.getHeader("Authorization"); if (accessToken==null){ logger.warn("Authorization token is empty"); requestContext.setSendZuulResponse(false); requestContext.setResponseStatusCode(401); requestContext.setResponseBody("Authorization token is empty"); return null; } logger.info("Authorization token is ok"); return null; }
Example 3
Source File: TokenFilter.java From springcloud_for_noob with MIT License | 6 votes |
@Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); logger.info("--->>> TokenFilter {},{}", request.getMethod(), request.getRequestURL().toString()); String token = request.getParameter("token"); if (StringUtils.isNotBlank(token)) { ctx.setSendZuulResponse(true); //对请求进行路由 ctx.setResponseStatusCode(200); ctx.set("isSuccess", true); return null; } else { ctx.setSendZuulResponse(false); //不对其进行路由 ctx.setResponseStatusCode(400); ctx.setResponseBody("token is empty"); ctx.set("isSuccess", false); return null; } }
Example 4
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 5
Source File: TokenFilter.java From xmfcn-spring-cloud with Apache License 2.0 | 6 votes |
/** * 处理逻辑 * * @return */ @Override public Object run() { RequestContext requestContext = RequestContext.getCurrentContext(); HttpServletRequest request = requestContext.getRequest(); HttpServletResponse response = requestContext.getResponse(); String sourceCode = request.getParameter("sourceCode"); String dbCode = sysCommonService.getDictValue(ConstantUtil.DICT_TYPE_BASE_CONFIG, "sourceCode"); if (StringUtil.isBlank(dbCode)||!dbCode.equals(sourceCode)) { requestContext.setSendZuulResponse(false);// 对该请求不路由 requestContext.set("isSuccess", false);// 设值,让下一个Filter看到上一个Filter的状态 // 构建返回信息 RetData retData = new RetData(); retData.setCode(ResultCodeMessage.UNAUTHORIZED); retData.setMessage(ResultCodeMessage.UNAUTHORIZED_MESSAGE); String jsonString = JSON.toJSONString(retData, SerializerFeature.WriteMapNullValue); requestContext.setResponseBody(jsonString); requestContext.addZuulResponseHeader("content-type", MediaType.APPLICATION_JSON_UTF8_VALUE); return response; } requestContext.set("isSuccess", true);// 设值,让下一个Filter看到上一个Filter的状态 return null; }
Example 6
Source File: MyZuulFilter.java From springcloud-study with Apache License 2.0 | 6 votes |
@Override public Object run() throws ZuulException { //获取请求的上下文类 注意是:com.netflix.zuul.context包下的 RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); ctx.addZuulResponseHeader("Content-type", "text/json;charset=UTF-8"); ctx.getResponse().setCharacterEncoding("UTF-8"); System.out.println("请求地址:"+request.getRequestURI()); String token = request.getParameter("token"); String msg="请求成功!"; if(token==null) { //使其不进行转发 ctx.setSendZuulResponse(false); msg="请求失败!原因是token为空!"; ctx.setResponseBody(msg); ctx.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value()); //或者添加一个额外参数也可以 传递参数可以使用 // ctx.set("checkAuth",false); } System.out.println(msg); return msg; }
Example 7
Source File: ResponseLogFilter.java From tutorials with MIT License | 6 votes |
@Override public Object run() throws ZuulException { RequestContext context = RequestContext.getCurrentContext(); try (final InputStream responseDataStream = context.getResponseDataStream()) { if(responseDataStream == null) { logger.info("BODY: {}", ""); return null; } String responseData = CharStreams.toString(new InputStreamReader(responseDataStream, "UTF-8")); logger.info("BODY: {}", responseData); context.setResponseBody(responseData); } catch (Exception e) { throw new ZuulException(e, INTERNAL_SERVER_ERROR.value(), e.getMessage()); } return null; }
Example 8
Source File: SwaggerBasePathRewritingFilter.java From java-microservices-examples 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 9
Source File: AuthenticationFilter.java From DBus 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())); String token = getToken(request); ResultEntityBuilder builder = new ResultEntityBuilder(ms); if (StringUtils.isNotBlank(token)) { try { Jws<Claims> jws = JWTUtils.parseToken(token, SIGNING_KEY); setParameter(ctx, PARAMETER_KEY_USER, jws.getBody().get("userId").toString()); setParameter(ctx, PARAMETER_KEY_EMAIL, jws.getBody().get("email").toString()); setParameter(ctx, PARAMETER_KEY_ROLE, jws.getBody().get("roleType").toString()); logger.info("{}服务收到请求,URL参数:{},表单参数:{}", request.getRequestURI(), ctx.getRequestQueryParams(), getRequestBody(request)); ctx.setSendZuulResponse(true); return null; } catch (ExpiredJwtException ee) { ctx.setResponseBody(builder.status(MessageCode.TOKEN_EXPIRED).build().toJSON()); } catch (Exception e) { logger.error("parse token error", e); ctx.setResponseBody(builder.status(MessageCode.TOKEN_ILLEGAL).build().toJSON()); } } else { ctx.setResponseBody(builder.status(MessageCode.TOKEN_NOT_FOUND).build().toJSON()); } ctx.getResponse().setContentType(MediaType.APPLICATION_JSON_UTF8.toString()); ctx.setSendZuulResponse(false); return null; }
Example 10
Source File: BaseFilter.java From zuihou-admin-cloud with Apache License 2.0 | 5 votes |
/** * 网关抛异常 * * @param body * @param code */ protected void setFailedRequest(String body, int code) { log.debug("Reporting error ({}): {}", code, body); RequestContext ctx = RequestContext.getCurrentContext(); // 返回错误码 ctx.setResponseStatusCode(code); ctx.addZuulResponseHeader("Content-Type", "application/json;charset=UTF-8"); if (ctx.getResponseBody() == null) { // 返回错误内容 ctx.setResponseBody(body); // 过滤该请求,不对其进行路由 ctx.setSendZuulResponse(false); } }
Example 11
Source File: PreviewFilter.java From pig with MIT License | 5 votes |
@Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); R<String> result = new R<>(); result.setCode(479); result.setMsg("演示环境,没有权限操作"); ctx.setResponseStatusCode(479); ctx.setSendZuulResponse(false); ctx.getResponse().setContentType("application/json;charset=UTF-8"); ctx.setResponseBody(JSONObject.toJSONString(result)); return null; }
Example 12
Source File: RattingInterceptorService.java From heimdall with Apache License 2.0 | 5 votes |
/** * Limits the number of requests to a specific path * * @param name RLock name * @param path rate limit key */ public void execute(String name, String path, Long calls, Interval interval, Long id) { RequestContext ctx = RequestContext.getCurrentContext(); RLock lock = rateLimitRepository.getLock(name); lock.lock(); RateLimit rate = rateLimitRepository.find(path); if (rate == null) { rate = rateLimitRepository.mountRatelimit(id, calls, interval); } if (rate.getLastRequest() == null) { rate.setLastRequest(LocalDateTime.now()); } if (hasIntervalEnded(rate)) { rate.reset(); rate.decreaseRemaining(); rateLimitRepository.save(rate); } else { if (rate.hasRemaining()) { rate.decreaseRemaining(); rateLimitRepository.save(rate); } else { ctx.setSendZuulResponse(false); ctx.setResponseStatusCode(HttpStatus.TOO_MANY_REQUESTS.value()); ctx.setResponseBody(HttpStatus.TOO_MANY_REQUESTS.getReasonPhrase()); } } lock.unlock(); }
Example 13
Source File: RateLimitingFilter.java From cubeai 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 14
Source File: DataFilter.java From xmfcn-spring-cloud with Apache License 2.0 | 5 votes |
/** * 修改输出数据 */ private void modifyResponseBody() { try { RequestContext context = getCurrentContext(); InputStream stream = context.getResponseDataStream(); String body = StreamUtils.copyToString(stream, Charset.forName("UTF-8")); context.setResponseBody("Modified via setResponseBody(): " + body); } catch (IOException e) { rethrowRuntimeException(e); } }
Example 15
Source File: TokenFilter.java From fw-spring-cloud with Apache License 2.0 | 5 votes |
@Override public Object run() { // int i=10/0; RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); log.info("我是TokenFilter"); String token = request.getHeader("token");// 获取请求的参数 // 如果有token参数并且token值为123456,才进行路由 if (StringUtils.isNotBlank(token) && token.equals("123456")) { ctx.setSendZuulResponse(true); //对请求进行路由 ctx.setResponseStatusCode(200); ctx.set("code", 1); } else { //失败之后通知后续不应该执行了 ctx.set("isShould",false); ctx.setSendZuulResponse(false); //不对其进行路由 ctx.setResponseStatusCode(401); HttpServletResponse response = ctx.getResponse(); response.setHeader("content-type", "text/html;charset=utf8"); ctx.setResponseBody("认证失败"); ctx.set("code", 0); } return null; }
Example 16
Source File: RateLimitingFilter.java From tutorials with MIT License | 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 17
Source File: BlackIPAccessFilter.java From cloud-service with MIT License | 5 votes |
@Override public Object run() { RequestContext requestContext = RequestContext.getCurrentContext(); requestContext.setResponseStatusCode(HttpStatus.FORBIDDEN.value()); requestContext.setResponseBody("black ip"); requestContext.setSendZuulResponse(false); return null; }
Example 18
Source File: ScopesFilter.java From heimdall with Apache License 2.0 | 4 votes |
private void process() { final RequestContext context = RequestContext.getCurrentContext(); final String client_id = context.getRequest().getHeader(CLIENT_ID); if (client_id != null) { App app = appRepository.findByClientId(client_id); if (app == null || app.getPlans() == null) return; Set<Long> apis = app.getPlans().stream().map(plan -> plan.getApi().getId()).collect(Collectors.toSet()); Long apiId = (Long) context.get(API_ID); if (!apis.contains(apiId)) return; final Set<Long> allowedOperations = new HashSet<>(); app.getPlans() .forEach(plan -> { if (plan != null && plan.getApi().getId().equals(apiId)) plan.getScopes() .forEach(scope -> { if (scope != null) allowedOperations.addAll(scope.getOperationsIds()); }); }); final Long operation = (Long) context.get(OPERATION_ID); if (operation == null) return; // If the allowedOperations is empty it means that Scopes are not set if (allowedOperations.isEmpty()) return; if (!allowedOperations.contains(operation)) { context.setSendZuulResponse(false); context.setResponseStatusCode(HttpStatus.FORBIDDEN.value()); context.setResponseBody(HttpStatus.FORBIDDEN.getReasonPhrase()); context.getResponse().setContentType(MediaType.TEXT_PLAIN_VALUE); } } }
Example 19
Source File: RequestLimitFilter.java From oneplatform with Apache License 2.0 | 4 votes |
@Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); try { HttpServletRequest request = ctx.getRequest(); if(postOnly && !HttpMethod.POST.name().equalsIgnoreCase(request.getMethod())){ return null; } if(HttpMethod.OPTIONS.name().equalsIgnoreCase(request.getMethod()) || HttpMethod.HEAD.name().equalsIgnoreCase(request.getMethod())){ return null; } if(gloabalLimiter != null){ //limiter.acquire(); if(!gloabalLimiter.tryAcquire(1, TimeUnit.SECONDS)){ ctx.setSendZuulResponse(false); ctx.setResponseStatusCode(HttpStatus.TOO_MANY_REQUESTS.value()); ctx.setResponseBody(MSG_TOO_MANY_REQUESTS); return null; } } //后台系统不限制 if(perLimiter != null){ UserSession session = SecurityDelegating.getCurrentSession(); if(!perLimiter.tryAcquire(request,session.getSessionId())){ ctx.setSendZuulResponse(false); ctx.setResponseStatusCode(HttpStatus.TOO_MANY_REQUESTS.value()); ctx.setResponseBody(MSG_REQUEST_TOO_FAST); return null; } } } catch (Exception e) { String error = "Error during filtering[RequestLimitFilter]"; log.error(error,e); WebUtils.responseOutJson(ctx.getResponse(), JsonUtils.toJson(new WrapperResponse<>(500, error))); } return null; }
Example 20
Source File: SentinelZuulPreFilter.java From Sentinel-Dashboard-Nacos 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<AsyncEntry> asyncEntries = 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, asyncEntries); } 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, asyncEntries); } } 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 (!asyncEntries.isEmpty()) { ctx.put(ZuulConstant.ZUUL_CTX_SENTINEL_ENTRIES_KEY, asyncEntries); } } return null; }