Java Code Examples for com.netflix.zuul.context.RequestContext#set()

The following examples show how to use com.netflix.zuul.context.RequestContext#set() . 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: TokenFilter.java    From springcloud_for_noob with MIT License 6 votes vote down vote up
@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 2
Source File: TracePreZuulFilter.java    From java-spring-cloud with Apache License 2.0 6 votes vote down vote up
@Override
public Object run() {
  RequestContext ctx = RequestContext.getCurrentContext();

  // span is a child of one created in servlet-filter
  Span span = tracer.buildSpan(ctx.getRequest().getMethod())
      .withTag(Tags.COMPONENT.getKey(), COMPONENT_NAME)
      .start();

  tracer.inject(span.context(), Format.Builtin.HTTP_HEADERS,
      new TextMapAdapter(ctx.getZuulRequestHeaders()));

  ctx.set(CONTEXT_SPAN_KEY, span);

  return null;
}
 
Example 3
Source File: TokenFilter.java    From xmfcn-spring-cloud with Apache License 2.0 6 votes vote down vote up
/**
 * 处理逻辑
 *
 * @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 4
Source File: AuthFilter.java    From xmfcn-spring-cloud with Apache License 2.0 6 votes vote down vote up
@Override
public Object run() {
    RequestContext requestContext = RequestContext.getCurrentContext();
    HttpServletRequest request = requestContext.getRequest();
    String requestUrl = request.getRequestURI();
    String url = StringUtil.getSystemUrl(request);
    logger.info("请求requestUrl:"+requestUrl);
    logger.trace("请求url:"+url);
    //添加Basic Auth认证信息
    if (requestUrl.contains("/server/")) {
        requestContext.addZuulRequestHeader("Authorization", "Basic " + getBase64Credentials(serviceName, servicePassword));
    } else {
        requestContext.addZuulRequestHeader("Authorization", "Basic " + getBase64Credentials(apiName, apiPassword));
    }
    requestContext.set("isSuccess", true);// 设值,让下一个Filter看到上一个Filter的状态
    return null;
}
 
Example 5
Source File: SlashFilterTest.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void proxyStartsWithSlash() throws Exception {
    final RequestContext ctx = RequestContext.getCurrentContext();
    ctx.set(PROXY_KEY, "/ui/service");
    this.filter.run();
    String location = "";
    List<Pair<String, String>> zuulResponseHeaders = ctx.getZuulResponseHeaders();
    if (zuulResponseHeaders != null) {
        for (Pair<String, String> header : zuulResponseHeaders) {
            if (header.first().equals("Location"))
                location = header.second();
        }
    }
    assertEquals("/ui/service/", location);
    assertEquals(302, ctx.getResponseStatusCode());
}
 
Example 6
Source File: TokenFilter.java    From spring-boot-demo with MIT License 6 votes vote down vote up
@Override
public Object run() {
    RequestContext ctx = RequestContext.getCurrentContext();
    HttpServletRequest request = ctx.getRequest();

    log.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 7
Source File: SlashFilterTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@BeforeEach
public void setUp() throws Exception {
    this.filter = new SlashFilter();
    RequestContext ctx = RequestContext.getCurrentContext();
    ctx.clear();
    ctx.set(PROXY_KEY, "ui/service");
    ctx.set(SERVICE_ID_KEY, "service");
    ctx.setResponse(new MockHttpServletResponse());
    MockHttpServletRequest mockRequest = new MockHttpServletRequest();
    mockRequest.setRequestURI("/ui/service");
    ctx.setRequest(mockRequest);
}
 
Example 8
Source File: LocationFilter.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Object run() {
    RequestContext context = RequestContext.getCurrentContext();

    final String serviceId = (String) context.get(SERVICE_ID_KEY);
    final String proxy = UrlUtils.removeFirstAndLastSlash((String) context.get(PROXY_KEY));
    final String requestPath = UrlUtils.addFirstSlash((String) context.get(REQUEST_URI_KEY));

    if (isRequestThatCanBeProcessed(serviceId, proxy, requestPath)) {
        RoutedServices routedServices = routedServicesMap.get(serviceId);

        if (routedServices != null) {
            @SuppressWarnings("squid:S2259")
            int i = proxy.lastIndexOf('/');

            if (i > 0) {
                String route = proxy.substring(0, i);
                String originalPath = normalizeOriginalPath(routedServices.findServiceByGatewayUrl(route).getServiceUrl());
                context.set(REQUEST_URI_KEY, originalPath + requestPath);
                log.debug("Routing: The request was routed to {}", originalPath + requestPath);
            }
        } else {
            log.trace("Routing: No routing metadata for service {} found.", serviceId);
        }
    } else {
        log.trace("Routing: Incorrect serviceId {}, proxy {} or requestPath {}.", serviceId, proxy, requestPath);
    }

    return null;
}
 
Example 9
Source File: SentinelZuulPreFilterTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
    when(httpServletRequest.getContextPath()).thenReturn("");
    when(httpServletRequest.getPathInfo()).thenReturn(URI);
    RequestContext requestContext = new RequestContext();
    requestContext.set(SERVICE_ID_KEY, SERVICE_ID);
    requestContext.setRequest(httpServletRequest);
    RequestContext.testSetCurrentContext(requestContext);
}
 
Example 10
Source File: LocationFilterTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void requestURIStartsWithoutSlash() {
    final RequestContext ctx = RequestContext.getCurrentContext();
    ctx.set(REQUEST_URI_KEY, "path");
    this.filter.run();
    assertEquals("/service/v1/path", ctx.get(REQUEST_URI_KEY));
}
 
Example 11
Source File: LocationFilterTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void proxyIsEmpty() {
    final RequestContext ctx = RequestContext.getCurrentContext();
    ctx.set(PROXY_KEY, "");
    this.filter.run();
    assertEquals("/path", ctx.get(REQUEST_URI_KEY));
}
 
Example 12
Source File: LocationFilterTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void proxyStartsWithSlash() {
    final RequestContext ctx = RequestContext.getCurrentContext();
    ctx.set(PROXY_KEY, "/api/v2/service");
    this.filter.run();
    assertEquals("/service/v2/path", ctx.get(REQUEST_URI_KEY));
}
 
Example 13
Source File: ErrorFilter.java    From fw-spring-cloud with Apache License 2.0 5 votes vote down vote up
@Override
public Object run() {
    RequestContext ctx=RequestContext.getCurrentContext();
    Throwable throwable = ctx.getThrowable();
    ctx.setSendZuulResponse(false); //不对其进行路由
    ctx.setResponseStatusCode(401);
    HttpServletResponse response = ctx.getResponse();
    response.setHeader("content-type", "text/html;charset=utf8");
    ctx.setResponseBody("认证失败"+throwable.getCause().getMessage());
    ctx.set("code", 500);
    log.error("异常信息,{}",throwable.getCause().getMessage());
    return null;
}
 
Example 14
Source File: SentinelZuulPreFilterTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
    when(httpServletRequest.getContextPath()).thenReturn("");
    when(httpServletRequest.getPathInfo()).thenReturn(URI);
    RequestContext requestContext = new RequestContext();
    requestContext.set(SERVICE_ID_KEY, SERVICE_ID);
    requestContext.setRequest(httpServletRequest);
    RequestContext.testSetCurrentContext(requestContext);
}
 
Example 15
Source File: LocationFilterTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void serviceIdIsNull() {
    final RequestContext ctx = RequestContext.getCurrentContext();
    ctx.set(SERVICE_ID_KEY, null);
    this.filter.run();
    assertEquals("/path", ctx.get(REQUEST_URI_KEY));
}
 
Example 16
Source File: ErrorFilter.java    From open-capacity-platform with Apache License 2.0 5 votes vote down vote up
@Override
public Object processZuulFilter(ZuulFilter filter) throws ZuulException {
    try {
        return super.processZuulFilter(filter);
    } catch (ZuulException e) {
        RequestContext ctx = RequestContext.getCurrentContext();
        ctx.set(FAILED_FILTER, filter);
        throw e;
    }
}
 
Example 17
Source File: RewritePathFilter.java    From skywalking with Apache License 2.0 4 votes vote down vote up
@Override
public Object run() {
    RequestContext ctx = RequestContext.getCurrentContext();
    ctx.set(REQUEST_URI, path);
    return null;
}
 
Example 18
Source File: HeimdallDecorationFilter.java    From heimdall with Apache License 2.0 4 votes vote down vote up
protected void process() {

        RequestContext ctx = RequestContext.getCurrentContext();
        final String requestURI = getPathWithoutStripSuffix(ctx.getRequest());

        if (pathMatcher.match(ConstantsPath.PATH_MANAGER_PATTERN, requestURI) || "/error".equals(requestURI)) {
            ctx.set(FORWARD_TO_KEY, requestURI);
            return;
        }

        final String method = ctx.getRequest().getMethod().toUpperCase();
        HeimdallRoute heimdallRoute = getMatchingHeimdallRoute(requestURI, method, ctx);

        if (heimdallRoute != null) {

            if (heimdallRoute.isMethodNotAllowed()) {
                ctx.setSendZuulResponse(false);
                ctx.setResponseStatusCode(HttpStatus.METHOD_NOT_ALLOWED.value());
                ctx.setResponseBody(HttpStatus.METHOD_NOT_ALLOWED.getReasonPhrase());
                return;
            }

            if (heimdallRoute.getRoute() == null || heimdallRoute.getRoute().getLocation() == null) {
                log.warn("Environment not configured for this location: {} and inbound: {}", ctx.getRequest().getRequestURL(), requestURI);
                ctx.setSendZuulResponse(false);
                ctx.setResponseStatusCode(HttpStatus.FORBIDDEN.value());
                ctx.setResponseBody("Environment not configured for this inbound");
                ctx.getResponse().setContentType(MediaType.TEXT_PLAIN_VALUE);
                TraceContextHolder.getInstance().getActualTrace().setRequest(requestHelper.dumpRequest());
                return;
            }

            String location = heimdallRoute.getRoute().getLocation();
            ctx.put(REQUEST_URI_KEY, heimdallRoute.getRoute().getPath());
            ctx.put(PROXY_KEY, heimdallRoute.getRoute().getId());
            if (!heimdallRoute.getRoute().isCustomSensitiveHeaders()) {
                this.proxyRequestHelper.addIgnoredHeaders(this.properties.getSensitiveHeaders().toArray(new String[0]));
            } else {
                this.proxyRequestHelper.addIgnoredHeaders(heimdallRoute.getRoute().getSensitiveHeaders().toArray(new String[0]));
            }

            if (heimdallRoute.getRoute().getRetryable() != null) {
                ctx.put(RETRYABLE_KEY, heimdallRoute.getRoute().getRetryable());
            }

            if (location.startsWith(HTTP_SCHEME + ":") || location.startsWith(HTTPS_SCHEME + ":")) {
                ctx.setRouteHost(UrlUtil.getUrl(location));
                ctx.addOriginResponseHeader(SERVICE_HEADER, location);
            } else if (location.startsWith(FORWARD_LOCATION_PREFIX)) {
                ctx.set(FORWARD_TO_KEY, StringUtils.cleanPath(location.substring(FORWARD_LOCATION_PREFIX.length()) + heimdallRoute.getRoute().getPath()));
                ctx.setRouteHost(null);
                return;
            } else {
                // set serviceId for use in filters.route.RibbonRequest
                ctx.set(SERVICE_ID_KEY, location);
                ctx.setRouteHost(null);
                ctx.addOriginResponseHeader(SERVICE_ID_HEADER, location);
            }
            if (this.properties.isAddProxyHeaders()) {
                addProxyHeaders(ctx);
                String xforwardedfor = ctx.getRequest().getHeader(X_FORWARDED_FOR_HEADER);
                String remoteAddr = ctx.getRequest().getRemoteAddr();
                if (xforwardedfor == null) {
                    xforwardedfor = remoteAddr;
                } else if (!xforwardedfor.contains(remoteAddr)) { // Prevent duplicates
                    xforwardedfor += ", " + remoteAddr;
                }
                ctx.addZuulRequestHeader(X_FORWARDED_FOR_HEADER, xforwardedfor);
            }
            if (this.properties.isAddHostHeader()) {
                ctx.addZuulRequestHeader(HttpHeaders.HOST, toHostHeader(ctx.getRequest()));
            }
        } else {
            log.warn("No route found for uri: " + requestURI);
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(HttpStatus.NOT_FOUND.value());
            ctx.setResponseBody(HttpStatus.NOT_FOUND.getReasonPhrase());
            ctx.getResponse().setContentType(MediaType.TEXT_PLAIN_VALUE);
            TraceContextHolder.getInstance().getActualTrace().setRequest(requestHelper.dumpRequest());
        }
    }
 
Example 19
Source File: SlashFilterTest.java    From api-layer with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void serviceIdIsEmpty() throws Exception {
    final RequestContext ctx = RequestContext.getCurrentContext();
    ctx.set(SERVICE_ID_KEY, "");
    assertEquals(false, this.filter.shouldFilter());
}
 
Example 20
Source File: SentinelZuulPreFilter.java    From Sentinel with Apache License 2.0 4 votes vote down vote up
@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;
}