當前位置: 首頁>>代碼示例>>Java>>正文


Java RequestContext類代碼示例

本文整理匯總了Java中com.netflix.zuul.context.RequestContext的典型用法代碼示例。如果您正苦於以下問題:Java RequestContext類的具體用法?Java RequestContext怎麽用?Java RequestContext使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


RequestContext類屬於com.netflix.zuul.context包,在下文中一共展示了RequestContext類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: run

import com.netflix.zuul.context.RequestContext; //導入依賴的package包/類
@Override
public Object run() {
    RequestContext ctx = RequestContext.getCurrentContext();
    HttpServletRequest request = ctx.getRequest();

    log.info(String.format("%s request to %s", request.getMethod(), request.getRequestURL().toString()));

    Object accessToken = request.getParameter("accessToken");
    if(accessToken == null) {
        log.warn("access token is empty");
        ctx.setSendZuulResponse(false);
        ctx.setResponseBody("401");
        ctx.setResponseStatusCode(401);
        return null;
    }
    log.info("access token ok");
    return null;
}
 
開發者ID:DemoHubs,項目名稱:hlxy-docker,代碼行數:19,代碼來源:AccessFilter.java

示例2: run

import com.netflix.zuul.context.RequestContext; //導入依賴的package包/類
@Override
public Object run() {
  try {
    RequestContext currentContext = RequestContext.getCurrentContext();
    HttpServletResponse response = currentContext.getResponse();

    if (!rateLimiter.tryAcquire()) {

      response.setContentType(MediaType.TEXT_PLAIN_VALUE);
      response.setStatus(this.tooManyRequests.value());
      response.getWriter().append(this.tooManyRequests.getReasonPhrase());

      currentContext.setSendZuulResponse(false);

      throw new ZuulException(this.tooManyRequests.getReasonPhrase(),
          this.tooManyRequests.value(),
          this.tooManyRequests.getReasonPhrase());
    }
  } catch (Exception e) {
    ReflectionUtils.rethrowRuntimeException(e);
  }
  return null;
}
 
開發者ID:drm317,項目名稱:cloud-native-reference,代碼行數:24,代碼來源:ThrottlingPreFilter.java

示例3: run_on_valid_response

import com.netflix.zuul.context.RequestContext; //導入依賴的package包/類
@Test
public void run_on_valid_response() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/service1" + DEFAULT_URL);
    RequestContext context = RequestContext.getCurrentContext();
    context.setRequest(request);

    MockHttpServletResponse response = new MockHttpServletResponse();
    context.setResponseGZipped(false);
    context.setResponse(response);

    InputStream in = IOUtils.toInputStream("{\"basePath\":\"/\"}", StandardCharsets.UTF_8);
    context.setResponseDataStream(in);

    filter.run();

    assertEquals("UTF-8", response.getCharacterEncoding());
    assertEquals("{\"basePath\":\"/service1\"}", context.getResponseBody());
}
 
開發者ID:ElectronicArmory,項目名稱:Armory,代碼行數:19,代碼來源:SwaggerBasePathRewritingFilterTest.java

示例4: run

import com.netflix.zuul.context.RequestContext; //導入依賴的package包/類
public Object run() {
	try {
		RequestContext context = getCurrentContext();
		InputStream in = (InputStream) context.get("requestEntity");
		if (in == null) {
			in = context.getRequest().getInputStream();
		}
		String body = StreamUtils.copyToString(in, Charset.forName("UTF-8"));
		// body = "request body modified via set('requestEntity'): "+ body;
		body = body.toUpperCase();
		context.set("requestEntity", new ByteArrayInputStream(body.getBytes("UTF-8")));
	}
	catch (IOException e) {
		rethrowRuntimeException(e);
	}
	return null;
}
 
開發者ID:spring-cloud-samples,項目名稱:sample-zuul-filters,代碼行數:18,代碼來源:UppercaseRequestEntityFilter.java

示例5: run

import com.netflix.zuul.context.RequestContext; //導入依賴的package包/類
@Override
public Object run() {
    RequestContext ctx = RequestContext.getCurrentContext();
    HttpServletRequest request = ctx.getRequest();

    Object token = request.getHeaders("token");

    //校驗token
    if (token == null || "".equals(token)) {
        logger.info("token為空,禁止訪問!");
        ctx.setSendZuulResponse(false);
        ctx.setResponseStatusCode(401);
        return null;
    } else {
        ctx.setSendZuulResponse(true);
        ctx.setResponseStatusCode(200);
    }

    //添加Basic Auth認證信息
    ctx.addZuulRequestHeader("Authorization", "Basic " + getBase64Credentials("app01", "*****"));

    return null;
}
 
開發者ID:kenly333,項目名稱:service-hive,代碼行數:24,代碼來源:AccessTokenFilter.java

示例6: run

import com.netflix.zuul.context.RequestContext; //導入依賴的package包/類
public Object run() {
	try {
		RequestContext context = getCurrentContext();
		InputStream in = (InputStream) context.get("requestEntity");
		if (in == null) {
			in = context.getRequest().getInputStream();
		}
		String body = StreamUtils.copyToString(in, Charset.forName("UTF-8"));
		body = "request body modified via request wrapper: "+ body;
		byte[] bytes = body.getBytes("UTF-8");
		context.setRequest(new HttpServletRequestWrapper(getCurrentContext().getRequest()) {
			@Override
			public ServletInputStream getInputStream() throws IOException {
				return new ServletInputStreamWrapper(bytes);
			}

			@Override
			public int getContentLength() {
				return bytes.length;
			}

			@Override
			public long getContentLengthLong() {
				return bytes.length;
			}
		});
	}
	catch (IOException e) {
		rethrowRuntimeException(e);
	}
	return null;
}
 
開發者ID:spring-cloud-samples,項目名稱:sample-zuul-filters,代碼行數:33,代碼來源:PrefixRequestEntityFilter.java

示例7: shouldFilter

import com.netflix.zuul.context.RequestContext; //導入依賴的package包/類
/**
 * Filter requests on endpoints that are not in the list of authorized microservices endpoints.
 */
@Override
public boolean shouldFilter() {
    String requestUri = RequestContext.getCurrentContext().getRequest().getRequestURI();

    // If the request Uri does not start with the path of the authorized endpoints, we block the request
    for (Route route : routeLocator.getRoutes()) {
        String serviceUrl = route.getFullPath();
        String serviceName = route.getId();

        // If this route correspond to the current request URI
        // We do a substring to remove the "**" at the end of the route URL
        if (requestUri.startsWith(serviceUrl.substring(0, serviceUrl.length() - 2))) {
return !isAuthorizedRequest(serviceUrl, serviceName, requestUri);
        }
    }
    return true;
}
 
開發者ID:IBM,項目名稱:Microservices-with-JHipster-and-Spring-Boot,代碼行數:21,代碼來源:AccessControlFilter.java

示例8: run

import com.netflix.zuul.context.RequestContext; //導入依賴的package包/類
/**
 * filter 具體的邏輯
 */
@Override
public Object run() {
    RequestContext ctx = RequestContext.getCurrentContext();
    HttpServletRequest request = ctx.getRequest();
    String uri = request.getRequestURI();
    if (uri.equals("/hi-service/upload") || uri.equals("/zuul/hi-service/upload")) {
        return ctx;
    }
    String token = request.getHeader("x-auth-token");
    if (StringUtils.isEmpty(token)) {
        ctx.setSendZuulResponse(false);
        ctx.setResponseStatusCode(401);
        ctx.setResponseBody("no token");
        return null;
    }
    if (!TOKEN_AUTH.equals(token)) {
        ctx.setSendZuulResponse(false);
        ctx.setResponseStatusCode(401);
        ctx.setResponseBody("token auth fail");
        return null;
    }
    ctx.addZuulRequestHeader("userInfo", "{\"name\":\"Tom\",\"age\":18}");
    return ctx;
}
 
開發者ID:yangdd1205,項目名稱:spring-cloud-master,代碼行數:28,代碼來源:CustomAuthFilter.java

示例9: run

import com.netflix.zuul.context.RequestContext; //導入依賴的package包/類
@Override
public Object run() {
    String id = getId(RequestContext.getCurrentContext().getRequest());
    Date date = getPeriod();

    // check current rate limit
    // default limit per user is 100,000 API calls per hour
    Long count = rateLimitingRepository.getCounter(id, TIME_PERIOD, date);
    log.debug("Rate limiting for user {} at {} - {}",  id, date, count);
    if (count > rateLimit) {
        apiLimitExceeded();
    } else {
        // count calls per hour
        rateLimitingRepository.incrementCounter(id, TIME_PERIOD, date);
    }
    return null;
}
 
開發者ID:ElectronicArmory,項目名稱:Armory,代碼行數:18,代碼來源:RateLimitingFilter.java

示例10: run

import com.netflix.zuul.context.RequestContext; //導入依賴的package包/類
@Override
public Object run() {
	log.info("This is a post filter, system throw a RuntimeException");
	RequestContext ctx = RequestContext.getCurrentContext();
	try {
		doSomething();
	} catch (Exception e) {
		/*
		 * ctx.set("error.status_code",
		 * HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
		 * ctx.set("error.exception", e); ctx.set("error.message",
		 * "有一些錯誤發生");
		 */
		ctx.setResponseStatusCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
		ctx.setResponseBody("{\"result\":\"server error\"}");// 返回錯誤內容
	}
	return null;
}
 
開發者ID:rongwei84n,項目名稱:Auts_Assert_manager,代碼行數:19,代碼來源:ThrowExceptionFilter.java

示例11: run

import com.netflix.zuul.context.RequestContext; //導入依賴的package包/類
@Override
public Object run() {
    RequestContext ctx = RequestContext.getCurrentContext();
    HttpServletRequest request = ctx.getRequest();

    String fullUrl = request.getRequestURL().toString();
    String url = request.getRequestURI();

    logger.debug(String.format("send %s request to %s", request.getMethod(),fullUrl));
    try {
        requestVerificationService.execute(request,url);
        ctx.setSendZuulResponse(true);
        ctx.setResponseStatusCode(200);
        return request;
    } catch (VerificationException e) {
        logger.error(e.getMessage());
        ctx.setSendZuulResponse(false);
        ctx.setResponseStatusCode(200);
        ctx.setResponseBody(String.format(ERROR_MSG_FORMAT,e.getVerificationState()));
        return request;
    }
}
 
開發者ID:codingapi,項目名稱:filter,代碼行數:23,代碼來源:PreRequestFilter.java

示例12: shouldFilter

import com.netflix.zuul.context.RequestContext; //導入依賴的package包/類
/**
 * Filter requests on endpoints that are not in the list of authorized microservices endpoints.
 */
@Override
public boolean shouldFilter() {
    String requestUri = RequestContext.getCurrentContext().getRequest().getRequestURI();

    // If the request Uri does not start with the path of the authorized endpoints, we block the request
    for (Route route : routeLocator.getRoutes()) {
        String serviceUrl = route.getFullPath();
        String serviceName = route.getId();

        // If this route correspond to the current request URI
        // We do a substring to remove the "**" at the end of the route URL
        if (requestUri.startsWith(serviceUrl.substring(0, serviceUrl.length() - 2))) {
            return !isAuthorizedRequest(serviceUrl, serviceName, requestUri);
        }
    }
    return true;
}
 
開發者ID:xm-online,項目名稱:xm-gate,代碼行數:21,代碼來源:AccessControlFilter.java

示例13: run

import com.netflix.zuul.context.RequestContext; //導入依賴的package包/類
/**
 * 過濾器的具體邏輯。需要注意,這裏我們通過ctx.setSendZuulResponse(false)令zuul過濾該請求,不對其進行路由,
 * 然後通過ctx.setResponseStatusCode(401)設置了其返回的錯誤碼,當然我們也可以進一步優化我們的返回,
 * 比如,通過ctx.setResponseBody(body)對返回body內容進行編輯等。
 */
@Override
public Object run() {
	RequestContext ctx = RequestContext.getCurrentContext();
	HttpServletRequest request = ctx.getRequest();
	log.info(String.format("%s request to %s", request.getMethod(), request
			.getRequestURL().toString()));
	Object accessToken = request.getParameter("accessToken");
	if (accessToken == null) {
		log.warn("access token is empty");
		ctx.setSendZuulResponse(false);
		ctx.setResponseStatusCode(401);
		return null;
	}
	log.info("access token ok");
	return null;
}
 
開發者ID:hutou-workhouse,項目名稱:miscroServiceHello,代碼行數:22,代碼來源:AccessFilter.java

示例14: run

import com.netflix.zuul.context.RequestContext; //導入依賴的package包/類
@Override
public Object run() {
    RequestContext ctx = RequestContext.getCurrentContext();
    HttpServletRequest request = ctx.getRequest();
    logger.info("send {} request to {}",request.getMethod(), request.getRequestURL().toString());

    Object accessToken = request.getParameter("accessToken");
    if(accessToken == null){
        logger.warn("access token is empty");
        ctx.setSendZuulResponse(false);
        ctx.setResponseStatusCode(401);
        return null;
    }
    logger.info("access token ok");
    return null;
}
 
開發者ID:frank-jian,項目名稱:SpringCloudDemo,代碼行數:17,代碼來源:AccessFilter.java

示例15: run

import com.netflix.zuul.context.RequestContext; //導入依賴的package包/類
@Override
public Object run() {
	RequestContext context = RequestContext.getCurrentContext();
	HttpServletRequest request = context.getRequest();

       Long remainingLimit = null;
	for (RateLimitCheck rl : filterConfig.getRateLimitChecks()) {
		ConsumptionProbe probe = rl.rateLimit(request);
		if (probe != null) {
			if (probe.isConsumed()) {
				remainingLimit = getRemainingLimit(remainingLimit, probe);
			} else {
				context.setResponseStatusCode(HttpStatus.TOO_MANY_REQUESTS.value());
				context.setResponseBody(filterConfig.getHttpResponseBody());
				context.setSendZuulResponse(false);
			}
			if(filterConfig.getStrategy().equals(RateLimitConditionMatchingStrategy.FIRST)) {
				break;
			}
		}
	};

	return null;
}
 
開發者ID:MarcGiffing,項目名稱:bucket4j-spring-boot-starter,代碼行數:25,代碼來源:ServletRateLimitFilter.java


注:本文中的com.netflix.zuul.context.RequestContext類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。