Java Code Examples for org.springframework.web.server.ServerWebExchange

The following examples show how to use org.springframework.web.server.ServerWebExchange. These examples are extracted from open source projects. 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
@Test
public void resolveResourceSuccess() {
	String versionFile = "bar-version.css";
	String version = "version";
	String file = "bar.css";
	Resource expected = new ClassPathResource("test/" + file, getClass());
	MockServerHttpRequest request = MockServerHttpRequest.get("/resources/bar-version.css").build();
	ServerWebExchange exchange = MockServerWebExchange.from(request);
	given(this.chain.resolveResource(exchange, versionFile, this.locations)).willReturn(Mono.empty());
	given(this.chain.resolveResource(exchange, file, this.locations)).willReturn(Mono.just(expected));
	given(this.versionStrategy.extractVersion(versionFile)).willReturn(version);
	given(this.versionStrategy.removeVersion(versionFile, version)).willReturn(file);
	given(this.versionStrategy.getResourceVersion(expected)).willReturn(Mono.just(version));

	this.resolver.setStrategyMap(Collections.singletonMap("/**", this.versionStrategy));
	Resource actual = this.resolver
			.resolveResourceInternal(exchange, versionFile, this.locations, this.chain)
			.block(Duration.ofMillis(5000));

	assertEquals(expected.getFilename(), actual.getFilename());
	verify(this.versionStrategy, times(1)).getResourceVersion(expected);
	assertThat(actual, instanceOf(HttpResource.class));
	assertEquals("\"" + version + "\"", ((HttpResource)actual).getResponseHeaders().getETag());
}
 
Example 2
Source Project: open-cloud   Source File: AccessLogFilter.java    License: MIT License 6 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
    ServerHttpResponse response = exchange.getResponse();
    DataBufferFactory bufferFactory = response.bufferFactory();
    ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(response) {
        @Override
        public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
            if (body instanceof Flux) {
                Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
                return super.writeWith(fluxBody.map(dataBuffer -> {
                    // probably should reuse buffers
                    byte[] content = new byte[dataBuffer.readableByteCount()];
                    dataBuffer.read(content);
                    //释放掉内存
                    DataBufferUtils.release(dataBuffer);
                    return bufferFactory.wrap(content);
                }));
            }
            // if body is not a flux. never got there.
            return super.writeWith(body);
        }
    };
    return chain.filter(exchange.mutate().response(decoratedResponse).build()).then(Mono.fromRunnable(()->{
        accessLogService.sendLog(exchange, null);
    }));
}
 
Example 3
Source Project: sophia_scaffolding   Source File: CorsFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange serverWebExchange, GatewayFilterChain chain) {
    ServerHttpRequest request = serverWebExchange.getRequest();
    ServerHttpResponse response = serverWebExchange.getResponse();
    HttpHeaders headers = response.getHeaders();
    headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
    headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "POST, GET, PUT, OPTIONS, DELETE, PATCH");
    headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
    headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "*");
    headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, ALL);
    headers.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, MAX_AGE);
    if (request.getMethod() == HttpMethod.OPTIONS) {
        response.setStatusCode(HttpStatus.OK);
        return Mono.empty();
    }
    return chain.filter(serverWebExchange);
}
 
Example 4
@Override
public Mono<Void> filter(
    ServerWebExchange exchange, WebFilterChain chain
) {
    HttpHeaders httpHeaders = exchange.getRequest().getHeaders();
    
    if ("true".equals(httpHeaders.getFirst("throw-web-filter-exception"))) {
        throw ApiException
            .newBuilder()
            .withApiErrors(SampleProjectApiError.ERROR_THROWN_IN_WEB_FILTER)
            .withExceptionMessage("Exception thrown from WebFilter")
            .build();
    }

    if ("true".equals(httpHeaders.getFirst("return-exception-in-web-filter-mono"))) {
        return Mono.error(
            ApiException
                .newBuilder()
                .withApiErrors(SampleProjectApiError.ERROR_RETURNED_IN_WEB_FILTER_MONO)
                .withExceptionMessage("Exception returned from WebFilter Mono")
                .build()
        );
    }

    return chain.filter(exchange);
}
 
Example 5
@Override
public Mono<Void> render(@Nullable Map<String, ?> model, @Nullable MediaType contentType,
		ServerWebExchange exchange) {
	StringBuilder builder = new StringBuilder();
	builder.append("name=").append(this.name).append('\n');
	for (Map.Entry<String, ?> entry : model.entrySet()) {
		builder.append(entry.getKey()).append('=').append(entry.getValue()).append('\n');
	}
	builder.setLength(builder.length() - 1);
	byte[] bytes = builder.toString().getBytes(StandardCharsets.UTF_8);

	ServerHttpResponse response = exchange.getResponse();
	DataBuffer buffer = response.bufferFactory().wrap(bytes);
	response.getHeaders().setContentType(MediaType.TEXT_PLAIN);
	return response.writeWith(Mono.just(buffer));
}
 
Example 6
private Mono<?> createAttribute(
		String attributeName, Class<?> clazz, BindingContext context, ServerWebExchange exchange) {

	Constructor<?> ctor = BeanUtils.findPrimaryConstructor(clazz);
	if (ctor == null) {
		Constructor<?>[] ctors = clazz.getConstructors();
		if (ctors.length == 1) {
			ctor = ctors[0];
		}
		else {
			try {
				ctor = clazz.getDeclaredConstructor();
			}
			catch (NoSuchMethodException ex) {
				throw new IllegalStateException("No primary or default constructor found for " + clazz, ex);
			}
		}
	}
	return constructAttribute(ctor, attributeName, context, exchange);
}
 
Example 7
@Override
public HttpHeaders filter(HttpHeaders input, ServerWebExchange exchange) {
  log.debug("Will instrument spring cloud gateway the HTTP request headers");
  ServerHttpRequest.Builder builder = exchange.getRequest().mutate();
  Span span = this.tracer.buildSpan(path(builder))
      .asChildOf(tracer.activeSpan())
      .withTag(Tags.COMPONENT.getKey(), COMPONENT)
      .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT)
      .withTag(ROUTE_ID, getRouteId(exchange))
      .start();
  log.debug("Client span {} created for the request. New headers are {}", span, builder.build().getHeaders().toSingleValueMap());
  exchange.getAttributes().put(SPAN_ATTRIBUTE, span);
  HttpHeaders headersWithInput = new HttpHeaders();
  try {
    this.tracer.inject(span.context(), Format.Builtin.HTTP_HEADERS, new HttpHeadersCarrier(headersWithInput));
  } catch (Exception ignore) {
    log.error("TraceRequestHttpHeadersFilter error", ignore);
  }
  headersWithInput.addAll(input);
  addHeadersWithInput(builder, headersWithInput);
  return headersWithInput;
}
 
Example 8
private void testPrefixPathFilter(String prefix, String path, String expectedPath) {
	GatewayFilter filter = new PrefixPathGatewayFilterFactory()
			.apply(c -> c.setPrefix(prefix));
	MockServerHttpRequest request = MockServerHttpRequest
			.get("http://localhost" + path).build();

	ServerWebExchange exchange = MockServerWebExchange.from(request);

	GatewayFilterChain filterChain = mock(GatewayFilterChain.class);

	ArgumentCaptor<ServerWebExchange> captor = ArgumentCaptor
			.forClass(ServerWebExchange.class);
	when(filterChain.filter(captor.capture())).thenReturn(Mono.empty());

	filter.filter(exchange, filterChain);

	ServerWebExchange webExchange = captor.getValue();

	assertThat(webExchange.getRequest().getURI()).hasPath(expectedPath);
	LinkedHashSet<URI> uris = webExchange
			.getRequiredAttribute(GATEWAY_ORIGINAL_REQUEST_URL_ATTR);
	assertThat(uris).contains(request.getURI());
}
 
Example 9
Source Project: java-technology-stack   Source File: ResourceUrlProvider.java    License: MIT License 6 votes vote down vote up
private Mono<String> resolveResourceUrl(ServerWebExchange exchange, PathContainer lookupPath) {
	return this.handlerMap.entrySet().stream()
			.filter(entry -> entry.getKey().matches(lookupPath))
			.min((entry1, entry2) ->
					PathPattern.SPECIFICITY_COMPARATOR.compare(entry1.getKey(), entry2.getKey()))
			.map(entry -> {
				PathContainer path = entry.getKey().extractPathWithinPattern(lookupPath);
				int endIndex = lookupPath.elements().size() - path.elements().size();
				PathContainer mapping = lookupPath.subPath(0, endIndex);
				ResourceWebHandler handler = entry.getValue();
				List<ResourceResolver> resolvers = handler.getResourceResolvers();
				ResourceResolverChain chain = new DefaultResourceResolverChain(resolvers);
				return chain.resolveUrlPath(path.value(), handler.getLocations())
						.map(resolvedPath -> mapping.value() + resolvedPath);
			})
			.orElseGet(() ->{
				if (logger.isTraceEnabled()) {
					logger.trace(exchange.getLogPrefix() + "No match for \"" + lookupPath + "\"");
				}
				return Mono.empty();
			});
}
 
Example 10
Source Project: spring-analysis-note   Source File: ProducesRequestCondition.java    License: MIT License 6 votes vote down vote up
/**
 * Checks if any of the contained media type expressions match the given
 * request 'Content-Type' header and returns an instance that is guaranteed
 * to contain matching expressions only. The match is performed via
 * {@link MediaType#isCompatibleWith(MediaType)}.
 * @param exchange the current exchange
 * @return the same instance if there are no expressions;
 * or a new condition with matching expressions;
 * or {@code null} if no expressions match.
 */
@Override
@Nullable
public ProducesRequestCondition getMatchingCondition(ServerWebExchange exchange) {
	if (CorsUtils.isPreFlightRequest(exchange.getRequest())) {
		return EMPTY_CONDITION;
	}
	if (isEmpty()) {
		return this;
	}
	List<ProduceMediaTypeExpression> result = getMatchingExpressions(exchange);
	if (!CollectionUtils.isEmpty(result)) {
		return new ProducesRequestCondition(result, this);
	}
	else {
		try {
			if (MediaType.ALL.isPresentIn(getAcceptedMediaTypes(exchange))) {
				return EMPTY_CONDITION;
			}
		}
		catch (NotAcceptableStatusException | UnsupportedMediaTypeStatusException ex) {
			// Ignore
		}
	}
	return null;
}
 
Example 11
@Override
public List<MediaType> resolveMediaTypes(ServerWebExchange exchange) throws NotAcceptableStatusException {
	String key = exchange.getRequest().getQueryParams().getFirst(getParameterName());
	if (!StringUtils.hasText(key)) {
		return MEDIA_TYPE_ALL_LIST;
	}
	key = formatKey(key);
	MediaType match = this.mediaTypes.get(key);
	if (match == null) {
		match = MediaTypeFactory.getMediaType("filename." + key)
				.orElseThrow(() -> {
					List<MediaType> supported = new ArrayList<>(this.mediaTypes.values());
					return new NotAcceptableStatusException(supported);
				});
	}
	this.mediaTypes.putIfAbsent(key, match);
	return Collections.singletonList(match);
}
 
Example 12
Source Project: openapi-generator   Source File: PetApi.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * GET /pet/findByStatus : Finds Pets by status
 * Multiple status values can be provided with comma separated strings
 *
 * @param status Status values that need to be considered for filter (required)
 * @return successful operation (status code 200)
 *         or Invalid status value (status code 400)
 */
@ApiOperation(value = "Finds Pets by status", nickname = "findPetsByStatus", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = {
    @Authorization(value = "petstore_auth", scopes = {
        @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"),
        @AuthorizationScope(scope = "read:pets", description = "read your pets")
        })
}, tags={ "pet", })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"),
    @ApiResponse(code = 400, message = "Invalid status value") })
@RequestMapping(value = "/pet/findByStatus",
    produces = { "application/xml", "application/json" }, 
    method = RequestMethod.GET)
default Mono<ResponseEntity<Flux<Pet>>> findPetsByStatus(@NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List<String> status, ServerWebExchange exchange) {
    return getDelegate().findPetsByStatus(status, exchange);
}
 
Example 13
@Test
public void supportsParameter() {
	assertTrue(this.resolver.supportsParameter(this.testMethod.arg(ServerWebExchange.class)));
	assertTrue(this.resolver.supportsParameter(this.testMethod.arg(ServerHttpRequest.class)));
	assertTrue(this.resolver.supportsParameter(this.testMethod.arg(ServerHttpResponse.class)));
	assertTrue(this.resolver.supportsParameter(this.testMethod.arg(HttpMethod.class)));
	assertTrue(this.resolver.supportsParameter(this.testMethod.arg(Locale.class)));
	assertTrue(this.resolver.supportsParameter(this.testMethod.arg(TimeZone.class)));
	assertTrue(this.resolver.supportsParameter(this.testMethod.arg(ZoneId.class)));
	assertTrue(this.resolver.supportsParameter(this.testMethod.arg(UriComponentsBuilder.class)));
	assertTrue(this.resolver.supportsParameter(this.testMethod.arg(UriBuilder.class)));

	assertFalse(this.resolver.supportsParameter(this.testMethod.arg(WebSession.class)));
	assertFalse(this.resolver.supportsParameter(this.testMethod.arg(String.class)));
	try {
		this.resolver.supportsParameter(this.testMethod.arg(Mono.class, ServerWebExchange.class));
		fail();
	}
	catch (IllegalStateException ex) {
		assertTrue("Unexpected error message:\n" + ex.getMessage(),
				ex.getMessage().startsWith(
						"ServerWebExchangeMethodArgumentResolver does not support reactive type wrapper"));
	}
}
 
Example 14
@GetMapping("reset_password")
public Mono<String> resetPasswordForm(
		@RequestParam String name,
		@RequestParam String email,
		@RequestParam String token,
		ServerWebExchange webExchange, 
        Model model) {
	
	return userService
  	    .accountByNameEmail(name, email)
  	    .filter(acct -> acct.getPassword().equals(token))
  	    .flatMap(acct -> {    	    	
              model.addAttribute("acct", acct);
              return webExchange.getSession()
                          .map(webSession -> webSession.getAttributes().put("token", token))
                          .then(Mono.just(RESET_PASSWORD_FORM_PATH));
  	    })
  	    .switchIfEmpty(Mono.just(REDIRECT_INDEX_PATH));
}
 
Example 15
Source Project: backstopper   Source File: ExplodingWebFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
    HttpHeaders httpHeaders = exchange.getRequest().getHeaders();

    if ("true".equals(httpHeaders.getFirst("throw-web-filter-exception"))) {
        throw ApiException
            .newBuilder()
            .withApiErrors(SampleProjectApiError.ERROR_THROWN_IN_WEB_FILTER)
            .withExceptionMessage("Exception thrown from WebFilter")
            .build();
    }

    if ("true".equals(httpHeaders.getFirst("return-exception-in-web-filter-mono"))) {
        return Mono.error(
            ApiException
                .newBuilder()
                .withApiErrors(SampleProjectApiError.ERROR_RETURNED_IN_WEB_FILTER_MONO)
                .withExceptionMessage("Exception returned from WebFilter Mono")
                .build()
        );
    }

    return chain.filter(exchange);
}
 
Example 16
Source Project: codeway_service   Source File: TokenFilter.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * 获取token字段,如果能获取到就 pass,获取不到就直接返回401错误,
 * chain.filter(exchange)之前的就是 “pre” 部分,之后的也就是then里边的是 “post” 部分
 * @param exchange
 * @param chain
 * @return
 */
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

	ServerHttpRequest request = exchange.getRequest();
	String authentication = request.getHeaders().getFirst("AUTH");
	String method = request.getMethodValue();
	String url = request.getPath().value();
	LogBack.info("url:{},method:{},headers:{}", url, method, request.getHeaders());
	//不需要网关签权的url
	if (authService.ignoreAuthentication(url) || StringUtils.startsWith(url, "/api")) {
		return chain.filter(exchange);
	}
	// 如果请求未携带token信息, 直接跳出
	if (StringUtils.isBlank(authentication) || !authentication.contains(BEARER)) {
		LogBack.error("url:{},method:{},headers:{}, 请求未携带token信息", url, method, request.getHeaders());
		return unAuthorized(exchange, StatusEnum.PARAM_ILLEGAL);
	}

	long expire = authService.getExpire(authentication);
	// 过期
	if(expire<0){
		return unAuthorized(exchange,StatusEnum.LOGIN_EXPIRED);
	}

	AuthToken authToken = authService.getAuthToken(authentication);
	String jwtToken = authToken.getAccess_token();
	//调用签权服务看用户是否有权限,若有权限进入下一个filter
	if (authService.commonAuthentication(url) || authService.hasPermission(jwtToken, url, method) ) {
		ServerHttpRequest.Builder builder = request.mutate();
		builder.header(X_CLIENT_TOKEN, "TODO 添加服务间简单认证");//TODO 转发的请求都加上服务间认证token
		//将jwt token中的用户信息传给服务
		builder.header(X_CLIENT_TOKEN_USER, authService.getJwt(jwtToken).getClaims());
		builder.header(HttpHeaders.AUTHORIZATION,BEARER+jwtToken);
		return chain.filter(exchange.mutate().request(builder.build()).build());
	}
	return unAuthorized(exchange,StatusEnum.UN_AUTHORIZED);
}
 
Example 17
Source Project: bird-java   Source File: GatewayWebHandler.java    License: MIT License 5 votes vote down vote up
/**
 * Delegate to the next {@code WebFilter} in the chain.
 *
 * @param exchange the current server exchange
 * @return {@code Mono<Void>} to indicate when request handling is complete
 */
@Override
public Mono<Void> execute(final ServerWebExchange exchange) {
    if (this.index < pipes.size()) {
        IChainPipe pipe = pipes.get(this.index++);
        return pipe.execute(exchange, this);
    } else {
        return Mono.empty();
    }
}
 
Example 18
Source Project: java-technology-stack   Source File: HttpMessageWriterView.java    License: MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> Mono<Void> write(T value, @Nullable MediaType contentType, ServerWebExchange exchange) {
	Publisher<T> input = Mono.justOrEmpty(value);
	ResolvableType elementType = ResolvableType.forClass(value.getClass());
	return ((HttpMessageWriter<T>) this.writer).write(
			input, elementType, contentType, exchange.getResponse(),
			Hints.from(Hints.LOG_PREFIX_HINT, exchange.getLogPrefix()));
}
 
Example 19
@Test
@SuppressWarnings("unchecked")
public void handleMatchUriTemplateVariables() {
	ServerWebExchange exchange = MockServerWebExchange.from(get("/1/2"));

	RequestMappingInfo key = paths("/{path1}/{path2}").build();
	this.handlerMapping.handleMatch(key, handlerMethod, exchange);

	String name = HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE;
	Map<String, String> uriVariables = (Map<String, String>) exchange.getAttributes().get(name);

	assertNotNull(uriVariables);
	assertEquals("1", uriVariables.get("path1"));
	assertEquals("2", uriVariables.get("path2"));
}
 
Example 20
@Test
public void compareNumberOfMatchingPatterns() throws Exception {
	ServerWebExchange exchange = MockServerWebExchange.from(get("/foo.html"));

	PatternsRequestCondition c1 = createPatternsCondition("/foo.*", "/foo.jpeg");
	PatternsRequestCondition c2 = createPatternsCondition("/foo.*", "/foo.html");

	PatternsRequestCondition match1 = c1.getMatchingCondition(exchange);
	PatternsRequestCondition match2 = c2.getMatchingCondition(exchange);

	assertNotNull(match1);
	assertEquals(1, match1.compareTo(match2, exchange));
}
 
Example 21
@Test
@SuppressWarnings("unchecked")
public void builder_constructor_sets_up_options_as_specified_in_the_builder() {
    // given
    int expectedOrder = 42;
    HttpTagAndSpanNamingStrategy<ServerWebExchange, ServerHttpResponse> expectedTagStrategyMock =
        mock(HttpTagAndSpanNamingStrategy.class);
    HttpTagAndSpanNamingAdapter<ServerWebExchange, ServerHttpResponse> expectedTagAdapterMock =
        mock(HttpTagAndSpanNamingAdapter.class);
    List<String> expectedUserIdHeaderKeys = Arrays.asList("foo", "bar");

    WingtipsSpringWebfluxWebFilter.Builder builder = WingtipsSpringWebfluxWebFilter
        .newBuilder()
        .withOrder(expectedOrder)
        .withTagAndNamingStrategy(expectedTagStrategyMock)
        .withTagAndNamingAdapter(expectedTagAdapterMock)
        .withUserIdHeaderKeys(expectedUserIdHeaderKeys);

    // when
    WingtipsSpringWebfluxWebFilter impl = new WingtipsSpringWebfluxWebFilter(builder);

    // then
    assertThat(impl.order).isEqualTo(expectedOrder);
    assertThat(impl.tagAndNamingStrategy).isSameAs(expectedTagStrategyMock);
    assertThat(impl.tagAndNamingAdapter).isSameAs(expectedTagAdapterMock);
    assertThat(impl.userIdHeaderKeys).isEqualTo(expectedUserIdHeaderKeys);
    verifyUserIdHeaderKeysIsUnmodifiable(impl);
}
 
Example 22
Source Project: openapi-generator   Source File: UserApi.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * DELETE /user/{username} : Delete user
 * This can only be done by the logged in user.
 *
 * @param username The name that needs to be deleted (required)
 * @return Invalid username supplied (status code 400)
 *         or User not found (status code 404)
 */
@ApiOperation(value = "Delete user", nickname = "deleteUser", notes = "This can only be done by the logged in user.", tags={ "user", })
@ApiResponses(value = { 
    @ApiResponse(code = 400, message = "Invalid username supplied"),
    @ApiResponse(code = 404, message = "User not found") })
@RequestMapping(value = "/user/{username}",
    method = RequestMethod.DELETE)
default Mono<ResponseEntity<Void>> deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true) @PathVariable("username") String username, ServerWebExchange exchange) {
    return getDelegate().deleteUser(username, exchange);
}
 
Example 23
@Override
public Predicate<ServerWebExchange> apply(Config config) {
	return new GatewayPredicate() {
		@Override
		public boolean test(ServerWebExchange serverWebExchange) {
			final ZonedDateTime now = ZonedDateTime.now();
			return now.isBefore(config.getDatetime());
		}

		@Override
		public String toString() {
			return String.format("Before: %s", config.getDatetime());
		}
	};
}
 
Example 24
@Test
public void happyPathLbPlusScheme() {
	MockServerHttpRequest request = MockServerHttpRequest.get("http://localhost/getb")
			.build();

	ServerWebExchange webExchange = testFilter(request, "lb:http://myhost");
	URI uri = webExchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);
	assertThat(uri).hasScheme("http").hasHost("myhost");
	String schemePrefix = webExchange
			.getRequiredAttribute(GATEWAY_SCHEME_PREFIX_ATTR);
	assertThat(schemePrefix).isEqualTo("lb");
}
 
Example 25
Source Project: java-technology-stack   Source File: DispatcherHandler.java    License: MIT License 5 votes vote down vote up
private Mono<HandlerResult> invokeHandler(ServerWebExchange exchange, Object handler) {
	if (this.handlerAdapters != null) {
		for (HandlerAdapter handlerAdapter : this.handlerAdapters) {
			if (handlerAdapter.supports(handler)) {
				return handlerAdapter.handle(exchange, handler);
			}
		}
	}
	return Mono.error(new IllegalStateException("No HandlerAdapter: " + handler));
}
 
Example 26
Source Project: java-technology-stack   Source File: WebExchangeDataBinderTests.java    License: MIT License 5 votes vote down vote up
private ServerWebExchange exchange(MultiValueMap<String, String> formData) {

		MockClientHttpRequest request = new MockClientHttpRequest(HttpMethod.POST, "/");

		new FormHttpMessageWriter().write(Mono.just(formData),
				forClassWithGenerics(MultiValueMap.class, String.class, String.class),
				MediaType.APPLICATION_FORM_URLENCODED, request, Collections.emptyMap()).block();

		return MockServerWebExchange.from(
				MockServerHttpRequest
						.post("/")
						.contentType(MediaType.APPLICATION_FORM_URLENCODED)
						.body(request.getBody()));
	}
 
Example 27
@Override
public Mono<Object> resolveArgument(
		MethodParameter parameter, BindingContext bindingContext, ServerWebExchange exchange) {

	NamedValueInfo namedValueInfo = getNamedValueInfo(parameter);
	MethodParameter nestedParameter = parameter.nestedIfOptional();

	Object resolvedName = resolveStringValue(namedValueInfo.name);
	if (resolvedName == null) {
		return Mono.error(new IllegalArgumentException(
				"Specified name must not resolve to null: [" + namedValueInfo.name + "]"));
	}

	Model model = bindingContext.getModel();

	return resolveName(resolvedName.toString(), nestedParameter, exchange)
			.flatMap(arg -> {
				if ("".equals(arg) && namedValueInfo.defaultValue != null) {
					arg = resolveStringValue(namedValueInfo.defaultValue);
				}
				arg = applyConversion(arg, namedValueInfo, parameter, bindingContext, exchange);
				handleResolvedValue(arg, namedValueInfo.name, parameter, model, exchange);
				return Mono.justOrEmpty(arg);
			})
			.switchIfEmpty(getDefaultValue(
					namedValueInfo, parameter, bindingContext, model, exchange));
}
 
Example 28
Source Project: java-technology-stack   Source File: CorsUrlHandlerMappingTests.java    License: MIT License 5 votes vote down vote up
@Test
public void preflightRequestWithoutCorsConfigurationProvider() throws Exception {
	String origin = "http://domain2.com";
	ServerWebExchange exchange = createExchange(HttpMethod.OPTIONS, "/welcome.html", origin);
	Object actual = this.handlerMapping.getHandler(exchange).block();

	assertNotNull(actual);
	assertNotSame(this.welcomeController, actual);
	assertNull(exchange.getResponse().getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
 
Example 29
@Test
public void routeTags() {
	ServerWebExchange exchange = MockServerWebExchange
			.from(MockServerHttpRequest.get(ROUTE_URI).build());
	exchange.getAttributes().put(GATEWAY_ROUTE_ATTR, ROUTE);

	Tags tags = tagsProvider.apply(exchange);
	assertThat(tags).isEqualTo(DEFAULT_TAGS);
}
 
Example 30
Source Project: openapi-generator   Source File: UserApi.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * POST /user/createWithList : Creates list of users with given input array
 *
 * @param body List of user object (required)
 * @return successful operation (status code 200)
 */
@ApiOperation(value = "Creates list of users with given input array", nickname = "createUsersWithListInput", notes = "", tags={ "user", })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "successful operation") })
@RequestMapping(value = "/user/createWithList",
    method = RequestMethod.POST)
default Mono<ResponseEntity<Void>> createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true )  @Valid @RequestBody Flux<User> body, ServerWebExchange exchange) {
    return getDelegate().createUsersWithListInput(body, exchange);
}