org.springframework.web.server.ServerWebExchange Java Examples

The following examples show how to use org.springframework.web.server.ServerWebExchange. 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: VersionResourceResolverTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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 File: ServerWebExchangeMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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 #3
Source File: PetApi.java    From openapi-generator with 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 #4
Source File: ParameterContentTypeResolver.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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 #5
Source File: ModelAttributeMethodArgumentResolver.java    From spring-analysis-note with MIT License 6 votes vote down vote up
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 #6
Source File: AccountController.java    From Spring5Tutorial with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 #7
Source File: TraceRequestHttpHeadersFilter.java    From java-spring-cloud with Apache License 2.0 6 votes vote down vote up
@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
Source File: ProducesRequestCondition.java    From spring-analysis-note with 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 #9
Source File: RenderingResponseIntegrationTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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 #10
Source File: SampleSpringboot2WebFluxSpringConfig.java    From backstopper with 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 #11
Source File: ExplodingWebFilter.java    From backstopper with 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 #12
Source File: ResourceUrlProvider.java    From java-technology-stack with 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 #13
Source File: AccessLogFilter.java    From open-cloud with 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 #14
Source File: CorsFilter.java    From sophia_scaffolding with 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 #15
Source File: PrefixPathGatewayFilterFactoryTest.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
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 #16
Source File: HttpEntityArgumentResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void httpEntityWithMonoBody() throws Exception {
	ServerWebExchange exchange = postExchange("line1");
	ResolvableType type = httpEntityType(Mono.class, String.class);
	HttpEntity<Mono<String>> httpEntity = resolveValue(exchange, type);

	assertEquals(exchange.getRequest().getHeaders(), httpEntity.getHeaders());
	assertEquals("line1", httpEntity.getBody().block());
}
 
Example #17
Source File: ServerWebExchangeUtils.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
public static String expand(ServerWebExchange exchange, String template) {
	Assert.notNull(exchange, "exchange may not be null");
	Assert.notNull(template, "template may not be null");

	if (template.indexOf('{') == -1) { // short circuit
		return template;
	}

	Map<String, String> variables = getUriTemplateVariables(exchange);
	return UriComponentsBuilder.fromPath(template).build().expand(variables)
			.getPath();
}
 
Example #18
Source File: DynamicRouteGatewayFilterFactory.java    From wecube-platform with Apache License 2.0 5 votes vote down vote up
protected void trySetGatewayRouteAttribute(ServerWebExchange exchange, Route route, String baseUrl) {
    if (log.isDebugEnabled()) {
        log.debug("base url:{}", baseUrl);
    }

    URI newUri = UriComponentsBuilder.fromHttpUrl(baseUrl).build().toUri();
    ServerWebExchangeUtils.addOriginalRequestUrl(exchange, exchange.getRequest().getURI());

    Route newRoute = Route.async().asyncPredicate(route.getPredicate()).filters(route.getFilters())
            .id(route.getId()).order(route.getOrder()).uri(newUri).build();

    exchange.getAttributes().put(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR, newRoute);
}
 
Example #19
Source File: HeadersRequestConditionTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test // SPR-16674
public void compareToWithMoreSpecificMatchByValue() {
	ServerWebExchange exchange = MockServerWebExchange.from(get("/"));

	HeadersRequestCondition condition1 = new HeadersRequestCondition("foo=a");
	HeadersRequestCondition condition2 = new HeadersRequestCondition("foo");

	int result = condition1.compareTo(condition2, exchange);
	assertTrue("Invalid comparison result: " + result, result < 0);
}
 
Example #20
Source File: RequestBodyMethodArgumentResolver.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public Mono<Object> resolveArgument(
		MethodParameter param, BindingContext bindingContext, ServerWebExchange exchange) {

	RequestBody ann = param.getParameterAnnotation(RequestBody.class);
	Assert.state(ann != null, "No RequestBody annotation");
	return readBody(param, ann.required(), bindingContext, exchange);
}
 
Example #21
Source File: ProxyExchangeArgumentResolver.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Object> resolveArgument(MethodParameter parameter,
		BindingContext bindingContext, ServerWebExchange exchange) {
	ProxyExchange<?> proxy = new ProxyExchange<>(rest, exchange, bindingContext,
			type(parameter));
	proxy.headers(headers);
	if (this.autoForwardedHeaders.size() > 0) {
		proxy.headers(extractAutoForwardedHeaders(exchange));
	}
	if (sensitive != null) {
		proxy.sensitive(sensitive.toArray(new String[0]));
	}
	return Mono.just(proxy);
}
 
Example #22
Source File: ConsumesRequestCondition.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected boolean matchMediaType(ServerWebExchange exchange) throws UnsupportedMediaTypeStatusException {
	try {
		MediaType contentType = exchange.getRequest().getHeaders().getContentType();
		contentType = (contentType != null ? contentType : MediaType.APPLICATION_OCTET_STREAM);
		return getMediaType().includes(contentType);
	}
	catch (InvalidMediaTypeException ex) {
		throw new UnsupportedMediaTypeStatusException("Can't parse Content-Type [" +
				exchange.getRequest().getHeaders().getFirst("Content-Type") +
				"]: " + ex.getMessage());
	}
}
 
Example #23
Source File: DefaultCorsProcessorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void preflightRequestMatchedAllowedMethod() throws Exception {
	ServerWebExchange exchange = MockServerWebExchange.from(
			preFlightRequest().header(ACCESS_CONTROL_REQUEST_METHOD, "GET"));
	this.conf.addAllowedOrigin("*");
	this.processor.process(this.conf, exchange);

	ServerHttpResponse response = exchange.getResponse();
	assertNull(response.getStatusCode());
	assertThat(response.getHeaders().get(VARY), contains(ORIGIN,
			ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS));
	assertEquals("GET,HEAD", response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS));
}
 
Example #24
Source File: ReactiveLoadBalancerClientFilterTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void happyPathWithAttributeRatherThanScheme() {
	MockServerHttpRequest request = MockServerHttpRequest
			.get("ws://localhost/get?a=b").build();

	URI lbUri = URI.create("ws://service1?a=b");

	exchange = MockServerWebExchange.from(request);
	exchange.getAttributes().put(GATEWAY_SCHEME_PREFIX_ATTR, "lb");

	ServerWebExchange webExchange = testFilter(exchange, lbUri);
	URI uri = webExchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);
	assertThat(uri).hasScheme("ws").hasHost("service1-host1").hasParameter("a", "b");
}
 
Example #25
Source File: DefaultResourceResolverChain.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public Mono<Resource> resolveResource(@Nullable ServerWebExchange exchange, String requestPath,
		List<? extends Resource> locations) {

	return (this.resolver != null && this.nextChain != null ?
			this.resolver.resolveResource(exchange, requestPath, locations, this.nextChain) :
			Mono.empty());
}
 
Example #26
Source File: UserApi.java    From openapi-generator with 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);
}
 
Example #27
Source File: HttpMethodOverrideSpanDecorator.java    From opentracing-toolbox with MIT License 5 votes vote down vote up
@Override
public void onRequest(final ServerWebExchange exchange, final Span span) {
    final ServerHttpRequest request = exchange.getRequest();
    final HttpHeaders headers = request.getHeaders();

    Stream.of("HTTP-Method-Override", "X-HTTP-Method-Override")
            .map(headers::getFirst)
            .filter(Objects::nonNull)
            .findFirst()
            .ifPresent(override ->
                    span.setTag(HTTP_METHOD_OVERRIDE, override));
}
 
Example #28
Source File: TokenFilter.java    From codeway_service with 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 #29
Source File: GatewayNoLoadBalancerClientAutoConfiguration.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("Duplicates")
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
	URI url = exchange.getAttribute(GATEWAY_REQUEST_URL_ATTR);
	String schemePrefix = exchange.getAttribute(GATEWAY_SCHEME_PREFIX_ATTR);
	if (url == null
			|| (!"lb".equals(url.getScheme()) && !"lb".equals(schemePrefix))) {
		return chain.filter(exchange);
	}

	throw NotFoundException.create(use404,
			"Unable to find instance for " + url.getHost());
}
 
Example #30
Source File: HandlerMethodArgumentResolverComposite.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Iterate over registered
 * {@link HandlerMethodArgumentResolver HandlerMethodArgumentResolvers} and
 * invoke the one that supports it.
 * @throws IllegalStateException if no suitable
 * {@link HandlerMethodArgumentResolver} is found.
 */
@Override
public Mono<Object> resolveArgument(
		MethodParameter parameter, BindingContext bindingContext, ServerWebExchange exchange) {

	HandlerMethodArgumentResolver resolver = getArgumentResolver(parameter);
	if (resolver == null) {
		throw new IllegalArgumentException(
				"Unsupported parameter type [" + parameter.getParameterType().getName() + "]." +
						" supportsParameter should be called first.");
	}
	return resolver.resolveArgument(parameter, bindingContext, exchange);
}