Java Code Examples for com.netflix.zuul.context.RequestContext#getResponse()
The following examples show how to use
com.netflix.zuul.context.RequestContext#getResponse() .
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: ZuulFilter.java From fw-spring-cloud with Apache License 2.0 | 6 votes |
@Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); log.info("我是ZuulFilter"); String token = request.getHeader("name");// 获取请求的参数 // 如果有name参数并且token值为zuul,才进行路由 if (StringUtils.isNotBlank(token) && token.equals("zuul")) { ctx.setSendZuulResponse(true); //对请求进行路由 ctx.setResponseStatusCode(200); ctx.set("code", 1); } else { 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 2
Source File: ValidateCodeFilter.java From Taroco with Apache License 2.0 | 6 votes |
@Override public Object run() { try { checkCode(RequestContext.getCurrentContext().getRequest()); } catch (ValidateCodeException e) { final RequestContext ctx = RequestContext.getCurrentContext(); final Response result = Response.failure(e.getMessage()); final HttpServletResponse response = ctx.getResponse(); response.setCharacterEncoding(Charset.defaultCharset().name()); response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE); response.setStatus(478); try { response.getWriter().print(JsonUtils.toJsonString(result)); } catch (IOException e1) { log.error("response io异常"); e1.printStackTrace(); } ctx.setSendZuulResponse(false); ctx.setResponse(response); } return null; }
Example 3
Source File: PreviewFilter.java From Taroco with Apache License 2.0 | 6 votes |
@Override public Object run() { final RequestContext ctx = RequestContext.getCurrentContext(); final Response result = Response.failure(DefaultError.SHOW_AUTH_CONTROL); final HttpServletResponse response = ctx.getResponse(); response.setCharacterEncoding(Charset.defaultCharset().name()); response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE); response.setStatus(479); try { response.getWriter().print(JSONObject.toJSONString(result)); } catch (IOException e1) { log.error("response io异常"); e1.printStackTrace(); } ctx.setSendZuulResponse(false); ctx.setResponse(response); return null; }
Example 4
Source File: BaseFilter.java From convergent-ui with Apache License 2.0 | 6 votes |
protected void writeResponse(String responseBody, MimeType contentType) throws Exception { RequestContext context = RequestContext.getCurrentContext(); // there is no body to send if (responseBody == null || responseBody.isEmpty()) { return; } HttpServletResponse servletResponse = context.getResponse(); servletResponse.setCharacterEncoding("UTF-8"); servletResponse.setContentType(contentType.toString()); OutputStream outStream = servletResponse.getOutputStream(); InputStream is = null; try { writeResponse(new ByteArrayInputStream(responseBody.getBytes()), outStream); } finally { try { if (is != null) { is.close(); } outStream.flush(); outStream.close(); } catch (IOException ex) { } } }
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: 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 7
Source File: ZuulResponseFilter.java From open-cloud with MIT License | 5 votes |
/** * */ @Override public Object run() { // 代理后响应日志处理 RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); HttpServletResponse response = ctx.getResponse(); // 把路由的serviceId放入作用域 request.setAttribute(FilterConstants.SERVICE_ID_KEY, ctx.get(FilterConstants.SERVICE_ID_KEY)); accessLogService.sendLog(request, response,null); return null; }
Example 8
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 9
Source File: BaseFilter.java From convergent-ui with Apache License 2.0 | 5 votes |
protected void writeResponse(BufferedImage image, MediaType type) throws Exception { RequestContext context = RequestContext.getCurrentContext(); // there is no body to send if (image == null) { return; } HttpServletResponse servletResponse = context.getResponse(); // servletResponse.setCharacterEncoding("UTF-8"); servletResponse.setContentType(type.toString()); ByteArrayOutputStream tmp = new ByteArrayOutputStream(); ImageIO.write(image, type.getSubtype(), tmp); tmp.close(); Integer contentLength = tmp.size(); servletResponse.setContentLength(contentLength); OutputStream outStream = servletResponse.getOutputStream(); ByteArrayOutputStream os = new ByteArrayOutputStream(); ImageIO.write(image, type.getSubtype(), os); InputStream is = new ByteArrayInputStream(os.toByteArray()); try { writeResponse(is, outStream); } finally { try { if (is != null) { is.close(); } outStream.flush(); outStream.close(); } catch (IOException ex) { } } }
Example 10
Source File: RateLimitFilter.java From springcloud-course with GNU General Public License v3.0 | 5 votes |
@Override public Object run() throws ZuulException { try { RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); log.info(request.getRequestURI()); HttpServletResponse response = ctx.getResponse(); if (!rateLimiter.tryAcquire()) { // HttpStatus httpStatus = HttpStatus.TOO_MANY_REQUESTS; // response.setContentType(MediaType.TEXT_PLAIN_VALUE); // response.setStatus(httpStatus.value()); // response.getWriter().append(httpStatus.getReasonPhrase()); // ctx.setSendZuulResponse(false); // throw new ZuulException( // httpStatus.getReasonPhrase(), // httpStatus.value(), // httpStatus.getReasonPhrase() // ); ctx.setSendZuulResponse(false); response.setStatus(200); response.getWriter().write("{\"code\": 99999,\"message\": \"too many requests.\"}"); } } catch (Exception e) { log.warning(e.getMessage()); ReflectionUtils.rethrowRuntimeException(e); } return null; }
Example 11
Source File: RenewFilter.java From paascloud-master with Apache License 2.0 | 5 votes |
private void doSomething(RequestContext requestContext) { HttpServletRequest request = requestContext.getRequest(); String token = StringUtils.substringAfter(request.getHeader(HttpHeaders.AUTHORIZATION), "bearer "); if (StringUtils.isEmpty(token)) { return; } OAuth2AccessToken oAuth2AccessToken = jwtTokenStore.readAccessToken(token); int expiresIn = oAuth2AccessToken.getExpiresIn(); if (expiresIn < EXPIRES_IN) { HttpServletResponse servletResponse = requestContext.getResponse(); servletResponse.addHeader("Renew-Header", "true"); } }
Example 12
Source File: AddResponseHeaderFilter.java From sample-zuul-filters with Apache License 2.0 | 5 votes |
public Object run() { RequestContext context = RequestContext.getCurrentContext(); HttpServletResponse servletResponse = context.getResponse(); servletResponse.addHeader("X-Foo", UUID.randomUUID().toString()); return null; }
Example 13
Source File: ResponseLoggingFilter.java From Showcase with Apache License 2.0 | 5 votes |
@Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); HttpServletResponse response = ctx.getResponse(); String headers = response.getHeaderNames() .stream() .map(headername -> headername + "=" + response.getHeader(headername)) .collect(Collectors.joining("; ")); LOGGER.info(String.format("Response for %s request to %s has status %s and headers %s", request.getMethod(), request.getRequestURL().toString(), response.getStatus(), headers)); return null; }
Example 14
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 15
Source File: PostResponseHeaderFilter.java From code with Apache License 2.0 | 5 votes |
@Override public Object run() throws ZuulException { RequestContext requestContext = RequestContext.getCurrentContext(); HttpServletResponse response = requestContext.getResponse(); response.setHeader("X-Foo", UUID.randomUUID().toString()); return null; }
Example 16
Source File: ZuulErrorFilter.java From open-cloud with MIT License | 5 votes |
@Override public Object run() { // 代理错误日志记录 RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); HttpServletResponse response = ctx.getResponse(); Exception exception = new Exception(ctx.getThrowable()); if(StringUtils.toBoolean(ctx.get("rateLimitExceeded"))){ exception = new Exception(HttpStatus.TOO_MANY_REQUESTS.name()); } accessLogService.sendLog(request, response,exception); ResultBody resultBody = OpenGlobalExceptionHandler.resolveException(exception,request.getRequestURI()); WebUtils.writeJson(response, resultBody); return null; }
Example 17
Source File: RateLimitPreFilter.java From spring-cloud-zuul-ratelimit with Apache License 2.0 | 4 votes |
@Override public Object run() { final RequestContext ctx = RequestContext.getCurrentContext(); final HttpServletResponse response = ctx.getResponse(); final HttpServletRequest request = ctx.getRequest(); final Route route = route(request); policy(route, request).forEach(policy -> { Map<String, String> responseHeaders = Maps.newHashMap(); final String key = rateLimitKeyGenerator.key(request, route, policy); final Rate rate = rateLimiter.consume(policy, key, null); final Long limit = policy.getLimit(); final Long remaining = rate.getRemaining(); if (limit != null) { responseHeaders.put(HEADER_LIMIT, String.valueOf(limit)); responseHeaders.put(HEADER_REMAINING, String.valueOf(Math.max(remaining, 0))); } final Duration quota = policy.getQuota(); final Long remainingQuota = rate.getRemainingQuota(); if (quota != null) { request.setAttribute(REQUEST_START_TIME, System.currentTimeMillis()); responseHeaders.put(HEADER_QUOTA, String.valueOf(quota.getSeconds())); responseHeaders.put(HEADER_REMAINING_QUOTA, String.valueOf(MILLISECONDS.toSeconds(Math.max(remainingQuota, 0)))); } responseHeaders.put(HEADER_RESET, String.valueOf(rate.getReset())); if (VERBOSE.equals(properties.getResponseHeaders())) { final String httpHeaderKey = key.replaceAll("[^A-Za-z0-9-.]", "_").replaceAll("__", "_"); for (Map.Entry<String, String> headersEntry : responseHeaders.entrySet()) { String header = VERBOSE.equals(properties.getResponseHeaders()) ? headersEntry.getKey() + "-" + httpHeaderKey : headersEntry.getKey(); response.setHeader(header, headersEntry.getValue()); } } if ((limit != null && remaining < 0) || (quota != null && remainingQuota < 0)) { ctx.setResponseStatusCode(HttpStatus.TOO_MANY_REQUESTS.value()); ctx.put(RATE_LIMIT_EXCEEDED, "true"); ctx.setSendZuulResponse(false); eventPublisher.publishEvent(new RateLimitExceededEvent(this, policy, rateLimitUtils.getRemoteAddress(request))); throw new RateLimitExceededException(); } }); return null; }
Example 18
Source File: ResponseHelper.java From heimdall with Apache License 2.0 | 4 votes |
public static Map<String, String> getResponseHeaders(RequestContext context) { Map<String, String> headers = new HashMap<>(); final HttpServletResponse response = context.getResponse(); context.getZuulResponseHeaders().forEach(pair -> headers.put(pair.first(), pair.second())); final Collection<String> headerNames = response.getHeaderNames(); headerNames.forEach(s -> headers.putIfAbsent(s, response.getHeader(s))); if (!headers.containsKey(HttpHeaders.CONTENT_TYPE)) { headers.put(HttpHeaders.CONTENT_TYPE, context.getResponse().getContentType()); } headers.remove("X-Application-Context"); return headers; }
Example 19
Source File: CacheWriterFilter.java From heimdall with Apache License 2.0 | 4 votes |
private void process() throws Throwable { RequestContext context = RequestContext.getCurrentContext(); RBucket<ApiResponse> rBucket = (RBucket<ApiResponse>) context.get(CACHE_BUCKET); HttpServletResponse response = context.getResponse(); Map<String, String> headers = ResponseHelper.getResponseHeaders(context); ApiResponse apiResponse = new ApiResponseImpl(); apiResponse.setHeaders(headers); apiResponse.setBody(ResponseHelper.getResponseBody(context, headers)); apiResponse.setStatus(response.getStatus()); Long timeToLive = (Long) context.get(CACHE_TIME_TO_LIVE); if (timeToLive != null && timeToLive > 0) rBucket.set(apiResponse, timeToLive, TimeUnit.MILLISECONDS); else rBucket.set(apiResponse); }
Example 20
Source File: ErrorFilter.java From mini-platform with MIT License | 4 votes |
@Override public Object run() { try { RequestContext ctx = RequestContext.getCurrentContext(); Enumeration<String> headerIt = ctx.getRequest().getHeaderNames(); StringBuilder sb = new StringBuilder(); while (headerIt.hasMoreElements()) { String name = headerIt.nextElement(); String value = ctx.getRequest().getHeader(name); sb.append("REQUEST:: > " + name + ":" + value+"\n"); } log.debug(sb.toString()); Throwable throwable = getOriginException(ctx.getThrowable()); ExceptionResult result = getExceptionResult(ctx.getRequest(), throwable); ctx.setSendZuulResponse(false); String json = JsonUtils.toJson(result); HttpServletResponse response = ctx.getResponse(); response.setContentType("application/json;charset=UTF-8"); //response.getOutputStream().write(json.getBytes()); PrintWriter writer = null; try { writer = response.getWriter(); writer.print(json); } catch (IOException e) { e.printStackTrace(); } finally { if(writer!=null){ writer.close(); } } } catch (Exception ex) { log.error("-------------->Exception filtering in custom error filter", ex); ReflectionUtils.rethrowRuntimeException(ex); } return null; }