com.netflix.zuul.exception.ZuulException Java Examples
The following examples show how to use
com.netflix.zuul.exception.ZuulException.
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: BaseZuulFilterRunner.java From zuul with Apache License 2.0 | 6 votes |
protected void recordFilterError(final I inMesg, final ZuulFilter<I, O> filter, final Throwable t) { // Add a log statement for this exception. final String errorMsg = "Filter Exception: filter=" + filter.filterName() + ", request-info=" + inMesg.getInfoForLogging() + ", msg=" + String.valueOf(t.getMessage()); if (t instanceof ZuulException && !((ZuulException) t).shouldLogAsError()) { logger.warn(errorMsg); } else { logger.error(errorMsg, t); } // Store this filter error for possible future use. But we still continue with next filter in the chain. final SessionContext zuulCtx = inMesg.getContext(); zuulCtx.getFilterErrors().add(new FilterError(filter.filterName(), filter.filterType().toString(), t)); if (zuulCtx.debugRouting()) { Debug.addRoutingDebug(zuulCtx, "Running Filter failed " + filter.filterName() + " type:" + filter.filterType() + " order:" + filter.filterOrder() + " " + t.getMessage()); } }
Example #2
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 #3
Source File: MyFilter.java From kitty with GNU Lesser General Public License v3.0 | 6 votes |
@Override public Object run() throws ZuulException { // filter需要执行的具体操作 RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); String token = request.getParameter("token"); System.out.println(token); if(token==null){ log.warn("there is no request token"); ctx.setSendZuulResponse(false); ctx.setResponseStatusCode(401); try { ctx.getResponse().getWriter().write("there is no request token"); } catch (IOException e) { e.printStackTrace(); } return null; } log.info("ok"); return null; }
Example #4
Source File: LoginFilter.java From cloud-template with MIT License | 6 votes |
/** * 过滤器的具体业务逻辑 * * @return * @throws ZuulException */ @Override public Object run() throws ZuulException { RequestContext currentContext = RequestContext.getCurrentContext(); HttpServletRequest request = currentContext.getRequest(); logger.info("{} >>> {}", request.getMethod(), request.getRequestURI().toString()); String token = request.getParameter("token"); if (token == null) { logger.error("Error! Request Token is Empty"); currentContext.setSendZuulResponse(false); currentContext.setResponseStatusCode(401); try { currentContext.getResponse().getWriter().write("Request token is empty"); } catch (IOException e) { e.printStackTrace(); } } return null; }
Example #5
Source File: TimeoutErrorCheck.java From api-layer with Eclipse Public License 2.0 | 6 votes |
public ResponseEntity<ApiMessageView> checkError(HttpServletRequest request, Throwable exc) { if (exc instanceof ZuulException) { ZuulException zuulException = (ZuulException) exc; Throwable rootCause = ExceptionUtils.getRootCause(zuulException); if ((zuulException.nStatusCode == HttpStatus.GATEWAY_TIMEOUT.value()) || zuulException.errorCause.equals(ERROR_CAUSE_TIMEOUT)) { Throwable cause = zuulException.getCause(); String causeMessage; if (cause != null) { causeMessage = cause.getMessage(); } else { causeMessage = DEFAULT_MESSAGE; } return gatewayTimeoutResponse(causeMessage); } else if (rootCause instanceof SocketTimeoutException) { return gatewayTimeoutResponse(rootCause.getMessage()); } } return null; }
Example #6
Source File: SecurityTokenErrorCheck.java From api-layer with Eclipse Public License 2.0 | 6 votes |
/** * Validate whether the exception is related to token and sets the proper response and status code * * @param request Http request * @param exc Exception thrown * @return Response entity with appropriate response and status code */ @Override public ResponseEntity<ApiMessageView> checkError(HttpServletRequest request, Throwable exc) { if (exc instanceof ZuulException && (exc.getCause() instanceof AuthenticationException)) { ApiMessageView messageView = null; Throwable cause = exc.getCause(); if (cause instanceof TokenExpireException) { messageView = messageService.createMessage("org.zowe.apiml.gateway.security.expiredToken").mapToView(); } else if (cause instanceof TokenNotValidException) { messageView = messageService.createMessage("org.zowe.apiml.gateway.security.invalidToken").mapToView(); } return ResponseEntity.status(HttpStatus.UNAUTHORIZED).contentType(MediaType.APPLICATION_JSON_UTF8).body(messageView); } return null; }
Example #7
Source File: SecurityTokenErrorCheckTest.java From api-layer with Eclipse Public License 2.0 | 6 votes |
@Test public void shouldReturnCauseMessageWhenTokenExpireException() { MockHttpServletRequest request = new MockHttpServletRequest(); TokenExpireException tokenExpireException = new TokenExpireException("TOKEN_EXPIRE"); AuthenticationException exception = new TokenExpireException(tokenExpireException.getMessage(), tokenExpireException); ZuulException exc = new ZuulException(exception, HttpStatus.GATEWAY_TIMEOUT.value(), String.valueOf(exception)); request.setAttribute(ErrorUtils.ATTR_ERROR_EXCEPTION, exc); ResponseEntity<ApiMessageView> actualResponse = securityTokenErrorCheck.checkError(request, exc); assertNotNull(actualResponse); assertEquals(HttpStatus.UNAUTHORIZED, actualResponse.getStatusCode()); List<ApiMessage> actualMessageList = actualResponse.getBody().getMessages(); assertThat(actualMessageList, hasItem(new ApiMessage<>("org.zowe.apiml.gateway.security.expiredToken", MessageType.ERROR, "ZWEAG103E", "Token is expired"))); }
Example #8
Source File: SecurityTokenErrorCheckTest.java From api-layer with Eclipse Public License 2.0 | 6 votes |
@Test public void shouldReturnCauseMessageWhenTokenNotValidException() { MockHttpServletRequest request = new MockHttpServletRequest(); TokenNotValidException tokenNotValidException = new TokenNotValidException("TOKEN_NOT_VALID"); AuthenticationException exception = new TokenNotValidException(tokenNotValidException.getMessage(), tokenNotValidException); ZuulException exc = new ZuulException(exception, HttpStatus.GATEWAY_TIMEOUT.value(), String.valueOf(exception)); request.setAttribute(ErrorUtils.ATTR_ERROR_EXCEPTION, exc); ResponseEntity<ApiMessageView> actualResponse = securityTokenErrorCheck.checkError(request, exc); assertNotNull(actualResponse); assertEquals(HttpStatus.UNAUTHORIZED, actualResponse.getStatusCode()); List<ApiMessage> actualMessageList = actualResponse.getBody().getMessages(); assertThat(actualMessageList, hasItem(new ApiMessage<>("org.zowe.apiml.gateway.security.invalidToken", MessageType.ERROR, "ZWEAG102E", "Token is not valid"))); }
Example #9
Source File: ServiceAuthenticationFilterTest.java From api-layer with Eclipse Public License 2.0 | 6 votes |
@Test public void givenValidJwt_whenCommandFailed_thenInternalError() { String jwtToken = "validJwtToken"; AuthenticationCommand cmd = createJwtValidationCommand(jwtToken); doThrow(new RuntimeException()).when(cmd).apply(null); doReturn(TokenAuthentication.createAuthenticated("user", jwtToken)).when(authenticationService).validateJwtToken(jwtToken); CounterFactory.initialize(new CounterFactory() { @Override public void increment(String name) { } }); try { serviceAuthenticationFilter.run(); fail(); } catch (ZuulRuntimeException zre) { assertTrue(zre.getCause() instanceof ZuulException); ZuulException ze = (ZuulException) zre.getCause(); assertEquals(500, ze.nStatusCode); } }
Example #10
Source File: AuthHeaderFilter.java From paascloud-master with Apache License 2.0 | 6 votes |
private void doSomething(RequestContext requestContext) throws ZuulException { HttpServletRequest request = requestContext.getRequest(); String requestURI = request.getRequestURI(); if (OPTIONS.equalsIgnoreCase(request.getMethod()) || !requestURI.contains(AUTH_PATH) || !requestURI.contains(LOGOUT_URI) || !requestURI.contains(ALIPAY_CALL_URI)) { return; } String authHeader = RequestUtil.getAuthHeader(request); if (PublicUtil.isEmpty(authHeader)) { throw new ZuulException("刷新页面重试", 403, "check token fail"); } if (authHeader.startsWith(BEARER_TOKEN_TYPE)) { requestContext.addZuulRequestHeader(HttpHeaders.AUTHORIZATION, authHeader); log.info("authHeader={} ", authHeader); // 传递给后续微服务 requestContext.addZuulRequestHeader(CoreHeaderInterceptor.HEADER_LABEL, authHeader); } }
Example #11
Source File: AuthFilter.java From springcloud-course with GNU General Public License v3.0 | 6 votes |
@Override public Object run() throws ZuulException { RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); log.info(String.format("header-token:%s,param-token:%s", request.getHeader("token"), request.getParameter("token"))); String token_header = request.getHeader("token") == null ? "" : request.getHeader("token"); String token_param = request.getParameter("token") == null ? "" : request.getParameter("token"); if (token_header.equals("") && token_param.equals("")) { try { ctx.setSendZuulResponse(false); ctx.getResponse().getWriter().write("{\"code\": 9999,\"message\": \"token is empty.\"}"); } catch (Exception e) { log.warning("system error"); } } else if (!token_header.equals("")) { log.info(String.format("token is %s", token_header)); } else if (!token_param.equals("")) { log.info(String.format("token is %s", token_param)); } return null; }
Example #12
Source File: AuthFilter.java From springcloud-course with GNU General Public License v3.0 | 6 votes |
@Override public Object run() throws ZuulException { RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); log.info(String.format("header-token:%s,param-token:%s", request.getHeader("token"), request.getParameter("token"))); String token_header = request.getHeader("token") == null ? "" : request.getHeader("token"); String token_param = request.getParameter("token") == null ? "" : request.getParameter("token"); if (token_header.equals("") && token_param.equals("")) { try { ctx.setSendZuulResponse(false); ctx.getResponse().getWriter().write("{\"code\": 9999,\"message\": \"token is empty.\"}"); } catch (Exception e) { log.warning("system error"); } } else if (!token_header.equals("")) { log.info(String.format("token is %s", token_header)); } else if (!token_param.equals("")) { log.info(String.format("token is %s", token_param)); } return null; }
Example #13
Source File: CustomErrorZuulFilter.java From api-gateway-old with Apache License 2.0 | 6 votes |
@Override public Object run() { try { RequestContext ctx = RequestContext.getCurrentContext(); ctx.set(SEND_ERROR_FILTER_RAN); ctx.setResponseStatusCode(500); ctx.setResponseBody("forward service error"); ZuulException exception = findZuulException(ctx.getThrowable()); HttpServletRequest request = ctx.getRequest(); request.setAttribute("javax.servlet.error.status_code", exception.nStatusCode); LOGGER.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); } } catch (Exception e) { ReflectionUtils.rethrowRuntimeException(e); } return null; }
Example #14
Source File: CustomSendErrorFilter.java From heimdall with Apache License 2.0 | 6 votes |
public ZuulException getZuulException(Throwable throwable) { if (throwable.getCause() instanceof ZuulRuntimeException) { // this was a failure initiated by one of the local filters return (ZuulException) throwable.getCause().getCause(); } if (throwable.getCause() instanceof ZuulException) { // wrapped zuul exception return (ZuulException) throwable.getCause(); } if (throwable instanceof ZuulException) { // exception thrown by zuul lifecycle return (ZuulException) throwable; } // fallback, should never get here return new ZuulException(throwable, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null); }
Example #15
Source File: AbstractLimiterZuulFilter.java From onetwo with Apache License 2.0 | 6 votes |
@Override public Object run() { InvokeContext invokeContext = createInvokeContext(); for(InvokeLimiter limiter : limiters){ try { if(limiter.match(invokeContext)){ limiter.consume(invokeContext); } } catch (LimitInvokeException e) { ZuulException ze = new ZuulException(e, HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage()); throw new ZuulRuntimeException(ze); } } return null; }
Example #16
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 #17
Source File: AuthFilter.java From springcloud-course with GNU General Public License v3.0 | 6 votes |
@Override public Object run() throws ZuulException { RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); log.info(String.format("header-token:%s,param-token:%s", request.getHeader("token"), request.getParameter("token"))); String token_header = request.getHeader("token") == null ? "" : request.getHeader("token"); String token_param = request.getParameter("token") == null ? "" : request.getParameter("token"); if (token_header.equals("") && token_param.equals("")) { try { ctx.setSendZuulResponse(false); ctx.getResponse().getWriter().write("{\"code\": 9999,\"message\": \"token is empty.\"}"); } catch (Exception e) { log.warning("system error"); } } else if (!token_header.equals("")) { log.warning(String.format("token is %s", token_header)); } else if (!token_param.equals("")) { log.warning(String.format("token is %s", token_param)); } return null; }
Example #18
Source File: ClientRequestReceiver.java From zuul with Apache License 2.0 | 6 votes |
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (msg instanceof HttpResponse) { promise.addListener((future) -> { if (! future.isSuccess()) { fireWriteError("response headers", future.cause(), ctx); } }); super.write(ctx, msg, promise); } else if (msg instanceof HttpContent) { promise.addListener((future) -> { if (! future.isSuccess()) { fireWriteError("response content", future.cause(), ctx); } }); super.write(ctx, msg, promise); } else { //should never happen ReferenceCountUtil.release(msg); throw new ZuulException("Attempt to write invalid content type to client: "+msg.getClass().getSimpleName(), true); } }
Example #19
Source File: ClientRequestReceiver.java From zuul with Apache License 2.0 | 6 votes |
private void fireWriteError(String requestPart, Throwable cause, ChannelHandlerContext ctx) throws Exception { final String errMesg = String.format("Error writing %s to client", requestPart); if (cause instanceof java.nio.channels.ClosedChannelException || cause instanceof Errors.NativeIoException) { LOG.info(errMesg + " - client connection is closed."); if (zuulRequest != null) { zuulRequest.getContext().cancel(); StatusCategoryUtils.storeStatusCategoryIfNotAlreadyFailure(zuulRequest.getContext(), ZuulStatusCategory.FAILURE_CLIENT_CANCELLED); } } else { LOG.error(errMesg, cause); ctx.fireExceptionCaught(new ZuulException(cause, errMesg, true)); } }
Example #20
Source File: LoginFilter.java From leyou with Apache License 2.0 | 6 votes |
@Override public Object run() throws ZuulException { // 获取上下文 RequestContext context = RequestContext.getCurrentContext(); // 获取request HttpServletRequest request = context.getRequest(); // 获取token String token = CookieUtils.getCookieValue(request, this.jwtProperties.getCookieName()); // 校验 try { // 校验通过什么都不做,即放行 JwtUtils.getInfoFromToken(token, this.jwtProperties.getPublicKey()); } catch (Exception e) { // 校验出现异常,返回403 context.setSendZuulResponse(false); context.setResponseStatusCode(HttpStatus.FORBIDDEN.value()); } return null; }
Example #21
Source File: ModifyHeaderFilter.java From open-cloud with MIT License | 5 votes |
@Override public Object run() throws ZuulException { RequestContext ctx = RequestContext.getCurrentContext(); ctx.addZuulRequestHeader(FeignRequestInterceptor.X_REQUEST_ID, ctx.getRequest().getHeader(FeignRequestInterceptor.X_REQUEST_ID) ); return null; }
Example #22
Source File: OriginResponseReceiver.java From zuul with Apache License 2.0 | 5 votes |
@Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof CompleteEvent) { final CompleteReason reason = ((CompleteEvent) evt).getReason(); if ((reason != SESSION_COMPLETE) && (edgeProxy != null)) { LOG.error("Origin request completed with reason other than COMPLETE: {}, {}", reason.name(), ChannelUtils.channelInfoForLogging(ctx.channel())); final ZuulException ze = new ZuulException("CompleteEvent", reason.name(), true); edgeProxy.errorFromOrigin(ze); } // First let this event propagate along the pipeline, before cleaning vars from the channel. // See channelWrite() where these vars are first set onto the channel. try { super.userEventTriggered(ctx, evt); } finally { postCompleteHook(ctx, evt); } } else if (evt instanceof SslHandshakeCompletionEvent && !((SslHandshakeCompletionEvent) evt).isSuccess()) { Throwable cause = ((SslHandshakeCompletionEvent) evt).cause(); ctx.channel().attr(SSL_HANDSHAKE_UNSUCCESS_FROM_ORIGIN_THROWABLE).set(cause); } else if (evt instanceof IdleStateEvent) { if (edgeProxy != null) { LOG.error("Origin request received IDLE event: {}", ChannelUtils.channelInfoForLogging(ctx.channel())); edgeProxy.errorFromOrigin(new OutboundException(READ_TIMEOUT, edgeProxy.getRequestAttempts())); } super.userEventTriggered(ctx, evt); } else { super.userEventTriggered(ctx, evt); } }
Example #23
Source File: ZuulLoggingFilter.java From Spring with Apache License 2.0 | 5 votes |
@Override public Object run() throws ZuulException { final HttpServletRequest request = RequestContext.getCurrentContext().getRequest(); log.info("requests uri -> {}", request.getRequestURI()); return null; //return doesn't matter }
Example #24
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 #25
Source File: AuthSellerFilter.java From code with Apache License 2.0 | 5 votes |
@Override public Object run() throws ZuulException { RequestContext requestContext = RequestContext.getCurrentContext(); HttpServletRequest request = requestContext.getRequest(); /** * /order/finish seller */ Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN); if (cookie == null || StringUtils.isEmpty(cookie.getValue()) || StringUtils.isEmpty(stringRedisTemplate.opsForValue().get(String.format(RedisConstant.TOKEN_TEMPLATE, cookie.getValue())))) { requestContext.setSendZuulResponse(false); requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value()); } return null; }
Example #26
Source File: ZuulLoginFilter.java From Microservices-with-Spring-Cloud with MIT License | 5 votes |
@Override public Object run() throws ZuulException { try { RequestContext.getCurrentContext() .getResponse() .sendRedirect("/user/login"); } catch (IOException e) { e.printStackTrace(); } return null; }
Example #27
Source File: PostRequestFilter.java From ad with Apache License 2.0 | 5 votes |
@Override public Object run() throws ZuulException { RequestContext requestContext = RequestContext.getCurrentContext(); HttpServletRequest request = requestContext.getRequest(); long startTime = (long) requestContext.get("startTime"); String uri = request.getRequestURI(); long duration = Instant.now().toEpochMilli() - startTime; log.info("uri: " + uri + ", duration: " + duration + "ms"); return null; }
Example #28
Source File: ValidateTokenFilter.java From piggymetrics with MIT License | 5 votes |
@Override public Object run() throws ZuulException { RequestContext requestContext = RequestContext.getCurrentContext(); String token = requestContext.getRequest().getHeader("Authorization"); if (StringUtil.isNullOrEmpty(token)) { throw new ZuulException("no token found", HttpStatus.SC_UNAUTHORIZED, "no token found"); } token = token.replace("Bearer ", ""); // remove prefix HttpHeaders headers = new HttpHeaders(); headers.add("Authorization", "Basic " + config.getBase64Credentials()); MultiValueMap<String, String> map = new LinkedMultiValueMap<>(); map.add("token", token); map.add("token_type_hint", "access_token"); HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers); String url = config.getTokenIntrospectEndpoint(); @SuppressWarnings("unchecked") Map<String, Object> resultMap = restTemplate.postForEntity(url, request, Map.class) .getBody(); Boolean active = (Boolean) resultMap.get("active"); if (active == null || !active) { throw new ZuulException("token inactive", HttpStatus.SC_UNAUTHORIZED, "token inactive"); } String username = (String) resultMap.get("username"); if (StringUtil.isNullOrEmpty(username)) { throw new ZuulException("username empty", HttpStatus.SC_UNAUTHORIZED, "username empty"); } requestContext.addZuulRequestHeader("X-S2G-USERNAME", username); return null; }
Example #29
Source File: RateLimitExceededExceptionTest.java From spring-cloud-zuul-ratelimit with Apache License 2.0 | 5 votes |
@Test public void testExceptionInfo() { Throwable cause = target.getCause(); assertThat(cause).isInstanceOf(ZuulException.class); ZuulException zuulException = (ZuulException) cause; assertThat(zuulException.getMessage()).contains("429"); }
Example #30
Source File: CorrelationIdZuulFilter.java From Microservices-with-Spring-Cloud with MIT License | 5 votes |
@Override public Object run() throws ZuulException { String id = UUID.randomUUID().toString(); RequestContext.getCurrentContext().addZuulRequestHeader(CORRELATION_ID, id); MDC.put(CORRELATION_ID, id); return null; }