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

The following examples show how to use com.netflix.zuul.context.RequestContext#get() . 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: LogWriterService.java    From heimdall with Apache License 2.0 6 votes vote down vote up
private String getRequestBody(RequestContext context) {
    try (InputStream in = (InputStream) context.get("requestEntity")) {

        String bodyText;
        if (in == null) {
            bodyText = StreamUtils.copyToString(context.getRequest().getInputStream(), Charset.forName("UTF-8"));
        } else {
            bodyText = StreamUtils.copyToString(in, Charset.forName("UTF-8"));
        }

        return bodyText;
    } catch (Exception e) {

        return null;
    }
}
 
Example 2
Source File: ErrorExtFilter.java    From xmfcn-spring-cloud with Apache License 2.0 5 votes vote down vote up
@Override
public boolean shouldFilter() {
    // 判断:仅处理来自post过滤器引起的异常
    RequestContext ctx = RequestContext.getCurrentContext();
    ZuulFilter failedFilter = (ZuulFilter) ctx.get("failed.filter");
    if (failedFilter != null && ("post".equals(failedFilter.filterType()) || "get".equals(failedFilter.filterType()))) {
        return true;
    }
    return true;
}
 
Example 3
Source File: SlashFilter.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean shouldFilter() {
    RequestContext context = RequestContext.getCurrentContext();
    String url = context.getRequest().getRequestURL().toString().toLowerCase();
    String serviceId = (String) context.get(SERVICE_ID_KEY);
    String proxy = (String) context.get(PROXY_KEY);
    boolean checkProxy = (proxy != null) && proxy.toLowerCase().contains(UI_IDENTIFIER);
    boolean checkServiceId = (serviceId != null) && !serviceId.isEmpty() && url.endsWith(serviceId);
    return checkProxy && checkServiceId;
}
 
Example 4
Source File: SentinelEntryUtils.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
static void tryTraceExceptionThenExitFromCurrentContext(Throwable t) {
    RequestContext ctx = RequestContext.getCurrentContext();
    if (ctx.containsKey(ZuulConstant.ZUUL_CTX_SENTINEL_ENTRIES_KEY)) {
        Deque<EntryHolder> holders = (Deque<EntryHolder>) ctx.get(ZuulConstant.ZUUL_CTX_SENTINEL_ENTRIES_KEY);
        EntryHolder holder;
        while (!holders.isEmpty()) {
            holder = holders.pop();
            Tracer.traceEntry(t, holder.getEntry());
            exit(holder);
        }
        ctx.remove(ZuulConstant.ZUUL_CTX_SENTINEL_ENTRIES_KEY);
    }
    ContextUtil.exit();
}
 
Example 5
Source File: CustomHostRoutingFilter.java    From heimdall with Apache License 2.0 5 votes vote down vote up
/**
 * Runs the custom routing filter.
 */
@Override
public Object run() {
	long startTime = System.currentTimeMillis();

	RequestContext context = RequestContext.getCurrentContext();
	HttpServletRequest request = context.getRequest();
	HttpHost httpHost = new HttpHost(context.getRouteHost().getHost(), context.getRouteHost().getPort(),
			context.getRouteHost().getProtocol());

	Long operationId = (Long) context.get(OPERATION_ID);
	String operationPath = (String) context.get(OPERATION_PATH);

	try {
		Callable<Object> callable = super::run;
		Object obj = circuitBreakerManager.failsafe(callable, operationId, operationPath);
		detail.setStatus(Constants.SUCCESS);
		return obj;
	} catch (Exception e) {
		detail.setStatus(Constants.FAILED);
		log.error("Exception: {} - Message: {} - during routing request to (hostPath + uri): {} - Verb: {} - HostName: {} - Port: {} - SchemeName: {}",
				e.getClass().getName(), 
				e.getMessage(), 
				request.getRequestURI(), 
				request.getMethod().toUpperCase(),
				httpHost.getHostName(), 
				httpHost.getPort(), 
				httpHost.getSchemeName());
		throw e;
	} finally {
		long endTime = System.currentTimeMillis();

		long duration = (endTime - startTime);

		detail.setTimeInMillisRun(duration);
		TraceContextHolder.getInstance().getActualTrace().addFilter(this.getClass().getSimpleName(), detail);
	}
}
 
Example 6
Source File: TokenRelayFilter.java    From jhipster-microservices-example with Apache License 2.0 5 votes vote down vote up
@Override
public Object run() {
    RequestContext ctx = RequestContext.getCurrentContext();

    Set<String> headers = (Set<String>) ctx.get("ignoredHeaders");
    // We need our JWT tokens relayed to resource servers
    headers.remove("authorization");

    return null;
}
 
Example 7
Source File: TracePostZuulFilter.java    From java-spring-cloud with Apache License 2.0 5 votes vote down vote up
@Override
public Object run() {
  RequestContext ctx = RequestContext.getCurrentContext();

  Object spanObject = ctx.get(TracePreZuulFilter.CONTEXT_SPAN_KEY);
  if (spanObject instanceof Span) {
    Span span = (Span) spanObject;
    span.setTag(Tags.HTTP_STATUS.getKey(), ctx.getResponseStatusCode());

    if (ctx.getThrowable() != null) {
      onError(ctx.getThrowable(), span);
    } else {
      Object error = ctx.get("error.exception");
      if (error instanceof Exception) {
        onError((Exception) error, span);
      }
    }

    if (ctx.getRouteHost() != null) {
      span.setTag(ROUTE_HOST_TAG, ctx.getRouteHost().toString());
    }

    span.finish();
  }

  return null;
}
 
Example 8
Source File: ErrorFilter.java    From open-capacity-platform with Apache License 2.0 5 votes vote down vote up
@Override
public boolean shouldFilter() {
    // 判断:仅处理post过滤器引起的异常
    RequestContext ctx = RequestContext.getCurrentContext();
    ZuulFilter failedFilter = (ZuulFilter) ctx.get(FAILED_FILTER);
    return failedFilter != null && failedFilter.filterType().equals(FilterConstants.POST_TYPE);
}
 
Example 9
Source File: GrayPreZuulFilter.java    From spring-cloud-gray with Apache License 2.0 5 votes vote down vote up
@Override
public Object run() {
    RequestContext context = RequestContext.getCurrentContext();
    HttpServletRequest servletRequest = context.getRequest();


    String serviceId = (String) context.get(FilterConstants.SERVICE_ID_KEY);
    if (StringUtils.isEmpty(serviceId)) {
        return null;
    }

    GrayHttpRequest grayRequest = new GrayHttpRequest();
    URI uri = URI.create((String) context.get(FilterConstants.REQUEST_URI_KEY));
    grayRequest.setUri(uri);
    grayRequest.setServiceId(serviceId);
    grayRequest.addParameters(context.getRequestQueryParams());
    if (grayRequestProperties.isLoadBody()) {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(context.getRequest().getInputStream()));
            byte[] reqBody = IOUtils.toByteArray(reader);
            grayRequest.setBody(reqBody);
        } catch (IOException e) {
            String errorMsg = "获取request body出现异常";
            log.error(errorMsg, e);
        }
    }

    grayRequest.setMethod(servletRequest.getMethod());
    grayRequest.setHeaders(getHeaders(context));
    grayRequest.setAttribute(GRAY_REQUEST_ATTRIBUTE_NAME_ZUUL_REQUEST, servletRequest);
    grayRequest.setAttribute(GRAY_REQUEST_ATTRIBUTE_NAME_ZUUL_REQUEST_CONTEXT, context);
    //context.getZuulRequestHeaders().get(FilterConstants.X_FORWARDED_FOR_HEADER.toLowerCase())

    RoutingConnectPointContext connectPointContext = RoutingConnectPointContext.builder()
            .interceptroType(GrayNetflixClientConstants.INTERCEPTRO_TYPE_ZUUL)
            .grayRequest(grayRequest).build();
    routingConnectionPoint.executeConnectPoint(connectPointContext);
    return null;
}
 
Example 10
Source File: LifeCycleService.java    From heimdall with Apache License 2.0 5 votes vote down vote up
public boolean should(InterceptorLifeCycle interceptorLifeCycle,
                      Long referenceId,
                      Long apiId,
                      Set<Integer> ignoredResources,
                      Set<Integer> ignoredOperations,
                      Boolean status) {

    if (!status) return false;

    if (referenceId == null) return false;
    RequestContext context = RequestContext.getCurrentContext();

    Long requestApiId = (Long) context.get(API_ID);
    if (!apiId.equals(requestApiId)) return false;

    Long resourceId = (Long) context.get(RESOURCE_ID);
    if (ignoredResources.contains(resourceId.intValue())) return false;

    Long operationId = (Long) context.get(OPERATION_ID);
    if (ignoredOperations.contains(operationId.intValue())) return false;

    switch (interceptorLifeCycle) {
        case API:
            return referenceId.equals(apiId);
        case PLAN:
            return validatePlan(context, referenceId);
        case RESOURCE:
            return referenceId.equals(resourceId);
        case OPERATION:
            return referenceId.equals(operationId);
        default:
            return false;
    }

}
 
Example 11
Source File: TokenRelayFilter.java    From cubeai with Apache License 2.0 5 votes vote down vote up
@Override
public Object run() {
    RequestContext ctx = RequestContext.getCurrentContext();
    Set<String> headers = (Set<String>) ctx.get("ignoredHeaders");
    // JWT tokens should be relayed to the resource servers
    headers.remove("authorization");
    return null;
}
 
Example 12
Source File: SentinelEntryUtils.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
static void tryExitFromCurrentContext() {
    RequestContext ctx = RequestContext.getCurrentContext();
    if (ctx.containsKey(ZuulConstant.ZUUL_CTX_SENTINEL_ENTRIES_KEY)) {
        Deque<AsyncEntry> asyncEntries = (Deque<AsyncEntry>) ctx.get(ZuulConstant.ZUUL_CTX_SENTINEL_ENTRIES_KEY);
        AsyncEntry entry;
        while (!asyncEntries.isEmpty()) {
            entry = asyncEntries.pop();
            entry.exit();
        }
        ctx.remove(ZuulConstant.ZUUL_CTX_SENTINEL_ENTRIES_KEY);
    }

    ContextUtil.exit();
}
 
Example 13
Source File: PostRequestFilter.java    From ad with Apache License 2.0 5 votes vote down vote up
@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 14
Source File: CacheWriterFilter.java    From heimdall with Apache License 2.0 4 votes vote down vote up
@Override
public boolean shouldFilter() {
    RequestContext context = RequestContext.getCurrentContext();

    return (context.get(CACHE_BUCKET) != null);
}
 
Example 15
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;
}
 
Example 16
Source File: SentinelZuulPreFilter.java    From Sentinel-Dashboard-Nacos 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<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;
}
 
Example 17
Source File: CacheWriterFilter.java    From heimdall with Apache License 2.0 4 votes vote down vote up
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 18
Source File: CacheInterceptorService.java    From heimdall with Apache License 2.0 4 votes vote down vote up
private String createDeleteCacheKey(RequestContext context, String cacheName) {

        return context.get(API_ID) + "-" +
                context.get(API_NAME) + ":" +
                cacheName + ":*";
    }
 
Example 19
Source File: ServiceNotFoundFilter.java    From api-layer with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public boolean shouldFilter() {
    RequestContext currentContext = contextProvider.context();
    String serviceId = (String) currentContext.get(SERVICE_ID_KEY);
    return Strings.isEmpty(serviceId);
}
 
Example 20
Source File: ScopesFilter.java    From heimdall with Apache License 2.0 4 votes vote down vote up
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);
        }
    }
}