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

The following examples show how to use com.netflix.zuul.context.RequestContext#setRequest() . 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: SwaggerBasePathRewritingFilterTest.java    From flair-registry with Apache License 2.0 6 votes vote down vote up
@Test
public void run_on_valid_response_gzip() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/service1" + DEFAULT_URL);
    RequestContext context = RequestContext.getCurrentContext();
    context.setRequest(request);

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

    context.setResponseDataStream(new ByteArrayInputStream(gzipData("{\"basePath\":\"/\"}")));

    filter.run();

    assertEquals("UTF-8", response.getCharacterEncoding());

    InputStream responseDataStream = new GZIPInputStream(context.getResponseDataStream());
    String responseBody = IOUtils.toString(responseDataStream, StandardCharsets.UTF_8);
    assertEquals("{\"basePath\":\"/service1\"}", responseBody);
}
 
Example 2
Source File: SwaggerBasePathRewritingFilterTest.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 6 votes vote down vote up
@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.setResponse(response);

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

    filter.run();

    assertEquals("UTF-8", response.getCharacterEncoding());
    assertEquals("{\"basePath\":\"/service1\"}", context.getResponseBody());
}
 
Example 3
Source File: RateLimitPreFilterTest.java    From spring-cloud-zuul-ratelimit with Apache License 2.0 6 votes vote down vote up
@BeforeEach
public void setUp() {
    MockitoAnnotations.initMocks(this);
    CounterFactory.initialize(new EmptyCounterFactory());

    when(httpServletRequest.getContextPath()).thenReturn("");
    when(httpServletRequest.getRequestURI()).thenReturn("/servicea/test");
    when(httpServletRequest.getRemoteAddr()).thenReturn("127.0.0.1");
    RequestContext requestContext = new RequestContext();
    requestContext.setRequest(httpServletRequest);
    requestContext.setResponse(httpServletResponse);
    RequestContext.testSetCurrentContext(requestContext);
    RequestContextHolder.setRequestAttributes(requestAttributes);
    rateLimitProperties = new RateLimitProperties();
    rateLimitProperties.setAddResponseHeaders(false);
    UrlPathHelper urlPathHelper = new UrlPathHelper();
    RateLimitUtils rateLimitUtils = new DefaultRateLimitUtils(rateLimitProperties);
    Route route = new Route("servicea", "/test", "servicea", "/servicea", null, Collections.emptySet());
    TestRouteLocator routeLocator = new TestRouteLocator(Collections.emptyList(), Lists.newArrayList(route));
    target = new RateLimitPreFilter(rateLimitProperties, routeLocator, urlPathHelper, rateLimiter, rateLimitKeyGenerator, rateLimitUtils, eventPublisher);
}
 
Example 4
Source File: SwaggerBasePathRewritingFilterTest.java    From java-microservices-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void run_on_valid_response_gzip() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/service1" + DEFAULT_URL);
    RequestContext context = RequestContext.getCurrentContext();
    context.setRequest(request);

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

    context.setResponseDataStream(new ByteArrayInputStream(gzipData("{\"basePath\":\"/\"}")));

    filter.run();

    assertEquals("UTF-8", response.getCharacterEncoding());

    InputStream responseDataStream = new GZIPInputStream(context.getResponseDataStream());
    String responseBody = IOUtils.toString(responseDataStream, StandardCharsets.UTF_8);
    assertEquals("{\"basePath\":\"/service1\"}", responseBody);
}
 
Example 5
Source File: ServletRateLimitFilterTest.java    From bucket4j-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
@Test
public void should_execute_only_one_check_when_using_RateLimitConditionMatchingStrategy_FIRST() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/url");
       RequestContext context = new RequestContext();
       context.setRequest(request);
       RequestContext.testSetCurrentContext(context);
       
       configuration.setStrategy(RateLimitConditionMatchingStrategy.FIRST);

       when(rateLimitCheck1.rateLimit(any(), Mockito.anyBoolean())).thenReturn(consumptionProbeHolder);
       
       standaloneSetup(new TestController())
		.addFilters(filter).build()
		.perform(get(("/test")));
       
       
       verify(rateLimitCheck1, times(1)).rateLimit(any(), Mockito.anyBoolean());
       verify(rateLimitCheck2, times(0)).rateLimit(any(), Mockito.anyBoolean());
       verify(rateLimitCheck3, times(0)).rateLimit(any(), Mockito.anyBoolean());
}
 
Example 6
Source File: SwaggerBasePathRewritingFilterTest.java    From okta-jhipster-microservices-oauth-example with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example 7
Source File: SwaggerBasePathRewritingFilterTest.java    From okta-jhipster-microservices-oauth-example with Apache License 2.0 6 votes vote down vote up
@Test
public void run_on_valid_response_gzip() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/service1" + DEFAULT_URL);
    RequestContext context = RequestContext.getCurrentContext();
    context.setRequest(request);

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

    context.setResponseDataStream(new ByteArrayInputStream(gzipData("{\"basePath\":\"/\"}")));

    filter.run();

    assertEquals("UTF-8", response.getCharacterEncoding());

    InputStream responseDataStream = new GZIPInputStream(context.getResponseDataStream());
    String responseBody = IOUtils.toString(responseDataStream, StandardCharsets.UTF_8);
    assertEquals("{\"basePath\":\"/service1\"}", responseBody);
}
 
Example 8
Source File: _SwaggerBasePathRewritingFilterTest.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 6 votes vote down vote up
@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.setResponse(response);

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

    filter.run();

    assertEquals("UTF-8", response.getCharacterEncoding());
    assertEquals("{\"basePath\":\"/service1\"}", context.getResponseBody());
}
 
Example 9
Source File: SwaggerBasePathRewritingFilterTest.java    From jhipster-registry with Apache License 2.0 6 votes vote down vote up
@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();

    assertThat(response.getCharacterEncoding()).isEqualTo("UTF-8");
    assertThat(context.getResponseBody()).isEqualTo("{\"basePath\":\"/service1\"}");
}
 
Example 10
Source File: SwaggerBasePathRewritingFilterTest.java    From jhipster-microservices-example with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example 11
Source File: ZuulRateLimitFilterTest.java    From bucket4j-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
@Test
public void should_execute_only_one_check_when_using_RateLimitConditionMatchingStrategy_FIRST() {
	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/url");
       RequestContext context = new RequestContext();
       context.setRequest(request);
       RequestContext.testSetCurrentContext(context);
       
       configuration.setStrategy(RateLimitConditionMatchingStrategy.FIRST);

       when(rateLimitCheck1.rateLimit(any(), Mockito.anyBoolean())).thenReturn(consumptionProbeHolder);
       
       filter.run();
       
       
       verify(rateLimitCheck1, times(1)).rateLimit(any(), Mockito.anyBoolean());
       verify(rateLimitCheck2, times(0)).rateLimit(any(), Mockito.anyBoolean());
       verify(rateLimitCheck3, times(0)).rateLimit(any(), Mockito.anyBoolean());
}
 
Example 12
Source File: IpsInterceptorServiceTest.java    From heimdall with Apache License 2.0 6 votes vote down vote up
@Test
   public void allowIpsWithPortInWhitelist() throws Throwable {
	RequestContext ctx = RequestContext.getCurrentContext();
	MockHttpServletRequest mockHttp = new MockHttpServletRequest();
       mockHttp.addHeader("X-FORWARDED-FOR", "192.168.12.128:3000");
       mockHttp.setRemoteAddr("10.60.40.50");
       
       ctx.setRequest(mockHttp);
	
	Set<String> whitelist = new HashSet<>();
	whitelist.add("192.168.12.128");
	
	ipsInterceptorService.executeWhiteList(whitelist);
	
	Assert.assertEquals(HttpStatus.OK.value(), ctx.getResponse().getStatus());
}
 
Example 13
Source File: SlashFilterTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldNotFilterAPI() throws Exception {
    final RequestContext ctx = RequestContext.getCurrentContext();
    MockHttpServletRequest mockRequest = new MockHttpServletRequest();
    mockRequest.setRequestURI("/api/v1/service");
    ctx.set(PROXY_KEY, "api/v1/service");
    ctx.setRequest(mockRequest);
    assertEquals(false, this.filter.shouldFilter());
}
 
Example 14
Source File: EncodedCharactersFilterTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldPassNullRequest() {
    RequestContext context = RequestContext.getCurrentContext();
    MockHttpServletRequest mockRequest = new MockHttpServletRequest();
    mockRequest.setRequestURI(null);
    context.setRequest(mockRequest);

    this.filter.run();

    assertEquals(200, context.getResponse().getStatus());
}
 
Example 15
Source File: SlashFilterTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldNotFilterWhenItEndsWithSlash() throws Exception {
    final RequestContext ctx = RequestContext.getCurrentContext();
    MockHttpServletRequest mockRequest = new MockHttpServletRequest();
    mockRequest.setRequestURI("/ui/service/");
    ctx.setRequest(mockRequest);
    assertEquals(false, this.filter.shouldFilter());
}
 
Example 16
Source File: WebfluxRateLimitFilterrTest.java    From bucket4j-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@Test
public void should_execute_only_one_check_when_using_RateLimitConditionMatchingStrategy_FIRST() {
	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/url");
       RequestContext context = new RequestContext();
       context.setRequest(request);
       RequestContext.testSetCurrentContext(context);
       
       configuration.setStrategy(RateLimitConditionMatchingStrategy.FIRST);

       rateLimitConfig(30L, rateLimitCheck1);
       rateLimitConfig(0L, rateLimitCheck2);
       rateLimitConfig(10L, rateLimitCheck3);
       
       HttpHeaders httpHeaders = Mockito.mock(HttpHeaders.class);
       when(serverHttpResponse.getHeaders()).thenReturn(httpHeaders);
       final ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
       
       try {
		filter.filter(exchange, chain );
	} catch(Exception e) {
		System.out.println(e.getMessage());
		fail("WebfluxRateLimitException expected");
	}
       
       verify(httpHeaders, times(1)).set(any(), captor.capture());

       List<String> values = captor.getAllValues();
       assertThat(values.stream().findFirst().get(), equalTo("30"));
       
       verify(rateLimitCheck1, times(1)).rateLimit(any(), Mockito.anyBoolean());
       verify(rateLimitCheck2, times(1)).rateLimit(any(), Mockito.anyBoolean());
       verify(rateLimitCheck3, times(1)).rateLimit(any(), Mockito.anyBoolean());
}
 
Example 17
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 18
Source File: PrefixRequestEntityFilter.java    From sample-zuul-filters with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 19
Source File: CustomPreZuulFilter.java    From spring-security-oauth with MIT License 5 votes vote down vote up
@Override
public Object run() {
    final RequestContext ctx = RequestContext.getCurrentContext();
    logger.info("in zuul filter " + ctx.getRequest().getRequestURI());
    byte[] encoded;
    try {
        encoded = Base64.getEncoder().encode("fooClientIdPassword:secret".getBytes("UTF-8"));
        ctx.addZuulRequestHeader("Authorization", "Basic " + new String(encoded));
        logger.info("pre filter");
        logger.info(ctx.getRequest().getHeader("Authorization"));

        final HttpServletRequest req = ctx.getRequest();

        final String refreshToken = extractRefreshToken(req);
        if (refreshToken != null) {
            final Map<String, String[]> param = new HashMap<String, String[]>();
            param.put("refresh_token", new String[] { refreshToken });
            param.put("grant_type", new String[] { "refresh_token" });

            ctx.setRequest(new CustomHttpServletRequest(req, param));
        }

    } catch (final UnsupportedEncodingException e) {
        logger.error("Error occured in pre filter", e);
    }

    //

    return null;
}
 
Example 20
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);
}