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

The following examples show how to use com.netflix.zuul.context.RequestContext#setRouteHost() . 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: MultiVersionServerSupportFilter.java    From zuihou-admin-cloud with Apache License 2.0 5 votes vote down vote up
@Override
public Object run() {
    Route route = route();

    RequestContext ctx = RequestContext.getCurrentContext();
    final String requestURI = URL_PATH_HELPER.getPathWithinApplication(ctx.getRequest());
    String version = ctx.getRequest().getHeader("serviceSuffix");

    if (StrUtil.isEmpty(version)) {
        version = ctx.getRequest().getParameter("serviceSuffix");
    }

    StringBuilder serviceId = new StringBuilder(route.getLocation());
    if (StrUtil.isNotEmpty(version)) {
        serviceId.append("-");
        serviceId.append(version);
    }
    String serviceIdStr = serviceId.toString();
    List<ServiceInstance> instances = discoveryClient.getInstances(serviceIdStr);
    log.debug("serviceIdStr={}, size={}", serviceIdStr, instances.size());
    if (!instances.isEmpty()) {
        ctx.put(REQUEST_URI_KEY, requestURI.substring(requestURI.indexOf('/', 1)));
        ctx.set(SERVICE_ID_KEY, serviceIdStr);
        ctx.setRouteHost(null);
        ctx.addOriginResponseHeader(SERVICE_ID_HEADER, serviceIdStr);

    }
    return null;
}
 
Example 2
Source File: EnvironmentForward.java    From pulsar-manager with Apache License 2.0 5 votes vote down vote up
private Object forwardRequest(RequestContext ctx, HttpServletRequest request, String serviceUrl) {
    ctx.put(REQUEST_URI_KEY, request.getRequestURI());
    try {
        Map<String, String> authHeader = pulsarAdminService.getAuthHeader(serviceUrl);
        authHeader.entrySet().forEach(entry -> ctx.addZuulRequestHeader(entry.getKey(), entry.getValue()));
        ctx.setRouteHost(new URL(serviceUrl));
        pulsarEvent.parsePulsarEvent(request.getRequestURI(), request);
        log.info("Forward request to {} @ path {}",
                serviceUrl, request.getRequestURI());
    } catch (MalformedURLException e) {
        log.error("Route forward to {} path {} error: {}",
                serviceUrl, request.getRequestURI(), e.getMessage());
    }
    return null;
}
 
Example 3
Source File: QueryParamPortPreFilter.java    From sample-zuul-filters with Apache License 2.0 5 votes vote down vote up
public Object run() {
	RequestContext ctx = getCurrentContext();
	HttpServletRequest request = ctx.getRequest();
	// put the serviceId in `RequestContext`
	String port = request.getParameter("port");
	try {
		URL url = UriComponentsBuilder.fromUri(ctx.getRouteHost().toURI())
				.port(new Integer(port))
				.build().toUri().toURL();
		ctx.setRouteHost(url);
	} catch (Exception e) {
		ReflectionUtils.rethrowRuntimeException(e);
	}
	return null;
}
 
Example 4
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 5
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 6
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());
        }
    }