Java Code Examples for org.springframework.web.reactive.function.server.ServerRequest#create()

The following examples show how to use org.springframework.web.reactive.function.server.ServerRequest#create() . 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: BodyParamPlugin.java    From soul with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<Void> execute(final ServerWebExchange exchange, final SoulPluginChain chain) {
    final ServerHttpRequest request = exchange.getRequest();
    final SoulContext soulContext = exchange.getAttribute(Constants.CONTEXT);
    if (Objects.nonNull(soulContext) && RpcTypeEnum.DUBBO.getName().equals(soulContext.getRpcType())) {
        MediaType mediaType = request.getHeaders().getContentType();
        ServerRequest serverRequest = ServerRequest.create(exchange, messageReaders);
        return serverRequest.bodyToMono(String.class)
                .switchIfEmpty(Mono.defer(() -> Mono.just("")))
                .flatMap(body -> {
                    if (MediaType.APPLICATION_JSON.isCompatibleWith(mediaType)) {
                        exchange.getAttributes().put(Constants.DUBBO_PARAMS, body);
                    }
                    return chain.execute(exchange);
                });
    }
    return chain.execute(exchange);
}
 
Example 2
Source File: BodyParamPlugin.java    From soul with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<Void> execute(final ServerWebExchange exchange, final SoulPluginChain chain) {
    final ServerHttpRequest request = exchange.getRequest();
    final SoulContext soulContext = exchange.getAttribute(Constants.CONTEXT);
    if (Objects.nonNull(soulContext) && RpcTypeEnum.DUBBO.getName().equals(soulContext.getRpcType())) {
        MediaType mediaType = request.getHeaders().getContentType();
        ServerRequest serverRequest = ServerRequest.create(exchange, messageReaders);
        return serverRequest.bodyToMono(String.class)
                .switchIfEmpty(Mono.defer(() -> Mono.just("")))
                .flatMap(body -> {
                    if (MediaType.APPLICATION_JSON.isCompatibleWith(mediaType)) {
                        exchange.getAttributes().put(Constants.DUBBO_PARAMS, body);
                    }
                    return chain.execute(exchange);
                });
    }
    return chain.execute(exchange);
}
 
Example 3
Source File: SpringWebfluxUnhandledExceptionHandler.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
    ServerRequest fluxRequest = ServerRequest.create(exchange, messageReaders);
    RequestInfoForLogging requestInfoForLogging = new RequestInfoForLoggingWebFluxAdapter(fluxRequest);

    ErrorResponseInfo<Mono<ServerResponse>> errorResponseInfo = handleException(ex, requestInfoForLogging);

    // Before we try to write the response, we should check to see if it's already committed, or if the client
    //      disconnected.
    // This short circuit logic due to an already-committed response or disconnected client was copied from
    //      Spring Boot 2's AbstractErrorWebExceptionHandler class.
    if (exchange.getResponse().isCommitted() || isDisconnectedClientError(ex)) {
        return Mono.error(ex);
    }

    // We handled the exception, and the response is still valid for output (not committed, and client still
    //      connected). Add any custom headers desired by the ErrorResponseInfo, and return a Mono that writes
    //      the response.
    processWebFluxResponse(errorResponseInfo, exchange.getResponse());

    return errorResponseInfo.frameworkRepresentationObj.flatMap(
        serverResponse -> write(exchange, serverResponse)
    );
}
 
Example 4
Source File: JsonExceptionHandler.java    From MyShopPlus with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Void> handle(ServerWebExchange serverWebExchange, Throwable throwable) {
    // 按照异常类型进行处理
    HttpStatus httpStatus;
    String body;
    if (throwable instanceof NotFoundException) {
        httpStatus = HttpStatus.NOT_FOUND;
        body = "Service Not Found";
    } else if (throwable instanceof ResponseStatusException) {
        ResponseStatusException responseStatusException = (ResponseStatusException) throwable;
        httpStatus = responseStatusException.getStatus();
        body = responseStatusException.getMessage();
    } else {
        httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
        body = "Internal Server Error";
    }

    // 封装响应结果
    Map<String, Object> result = new HashMap<>(2, 1);
    result.put("httpStatus", httpStatus);

    String msg = "{\"code\":" + httpStatus.value() + ",\"message\": \"" + body + "\"}";
    result.put("body", msg);

    // 错误日志
    ServerHttpRequest request = serverWebExchange.getRequest();
    log.error("[全局系统异常]\r\n请求路径:{}\r\n异常记录:{}", request.getPath(), throwable.getMessage());

    if (serverWebExchange.getResponse().isCommitted()) {
        return Mono.error(throwable);
    }
    exceptionHandlerResult.set(result);
    ServerRequest newRequest = ServerRequest.create(serverWebExchange, this.messageReaders);
    return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse).route(newRequest)
            .switchIfEmpty(Mono.error(throwable))
            .flatMap((handler) -> handler.handle(newRequest))
            .flatMap((response) -> write(serverWebExchange, response));
}
 
Example 5
Source File: RouterFunctionMapping.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
protected Mono<?> getHandlerInternal(ServerWebExchange exchange) {
	if (this.routerFunction != null) {
		ServerRequest request = ServerRequest.create(exchange, this.messageReaders);
		return this.routerFunction.route(request)
				.doOnNext(handler -> setAttributes(exchange.getAttributes(), request, handler));
	}
	else {
		return Mono.empty();
	}
}
 
Example 6
Source File: JsonExceptionHandler.java    From open-cloud with MIT License 5 votes vote down vote up
@Override
public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
    /**
     * 按照异常类型进行处理
     */
    ResultBody resultBody;
    ServerHttpRequest request = exchange.getRequest();
    if("/favicon.ico".equals(exchange.getRequest().getURI().getPath())){
        return Mono.empty();
    }
    if (ex instanceof NotFoundException) {
        resultBody = ResultBody.failed().code(ErrorCode.SERVICE_UNAVAILABLE.getCode()).msg(ErrorCode.SERVICE_UNAVAILABLE.getMessage()).httpStatus(HttpStatus.SERVICE_UNAVAILABLE.value()).path(request.getURI().getPath());
        log.error("==> 错误解析:{}", resultBody);
    } else {
        resultBody = OpenGlobalExceptionHandler.resolveException((Exception) ex, exchange.getRequest().getURI().getPath());
    }
    /**
     * 参考AbstractErrorWebExceptionHandler
     */
    if (exchange.getResponse().isCommitted()) {
        return Mono.error(ex);
    }
    exceptionHandlerResult.set(resultBody);
    ServerRequest newRequest = ServerRequest.create(exchange, this.messageReaders);
    return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse).route(newRequest)
            .switchIfEmpty(Mono.error(ex))
            .flatMap((handler) -> handler.handle(newRequest))
            .flatMap((response) -> {
                return write(exchange, response,ex);
            });
}
 
Example 7
Source File: RouterFunctionMapping.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected Mono<?> getHandlerInternal(ServerWebExchange exchange) {
	if (this.routerFunction != null) {
		ServerRequest request = ServerRequest.create(exchange, this.messageReaders);
		return this.routerFunction.route(request)
				.doOnNext(handler -> setAttributes(exchange.getAttributes(), request, handler));
	}
	else {
		return Mono.empty();
	}
}
 
Example 8
Source File: FileSizeFilter.java    From soul with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Mono<Void> filter(@NonNull final ServerWebExchange exchange, @NonNull final WebFilterChain chain) {
    MediaType mediaType = exchange.getRequest().getHeaders().getContentType();
    if (MediaType.MULTIPART_FORM_DATA.isCompatibleWith(mediaType)) {
        ServerRequest serverRequest = ServerRequest.create(exchange,
                messageReaders);
        return serverRequest.bodyToMono(DataBuffer.class)
                .flatMap(size -> {
                    if (size.capacity() > BYTES_PER_MB * maxSize) {
                        ServerHttpResponse response = exchange.getResponse();
                        response.setStatusCode(HttpStatus.BAD_REQUEST);
                        Object error = SoulResultWarp.error(SoulResultEnum.PAYLOAD_TOO_LARGE.getCode(), SoulResultEnum.PAYLOAD_TOO_LARGE.getMsg(), null);
                        return WebFluxResultUtils.result(exchange, error);
                    }
                    BodyInserter bodyInserter = BodyInserters.fromPublisher(Mono.just(size), DataBuffer.class);
                    HttpHeaders headers = new HttpHeaders();
                    headers.putAll(exchange.getRequest().getHeaders());
                    headers.remove(HttpHeaders.CONTENT_LENGTH);
                    CachedBodyOutputMessage outputMessage = new CachedBodyOutputMessage(
                            exchange, headers);
                    return bodyInserter.insert(outputMessage, new BodyInserterContext())
                            .then(Mono.defer(() -> {
                                ServerHttpRequest decorator = decorate(exchange, outputMessage);
                                return chain.filter(exchange.mutate().request(decorator).build());

                            }));
                });
    }
    return chain.filter(exchange);

}
 
Example 9
Source File: ExceptionHandle.java    From microservice-recruit with Apache License 2.0 4 votes vote down vote up
@Override
public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
    /**
     * 按照异常类型进行处理
     */
    HttpStatus httpStatus;
    String body;
    if (ex instanceof MyException) {
        httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
        body = JSONObject.toJSONString(ResponseMessage.error(((MyException) ex).getCode(), ex.getMessage()));
    } else if (ex instanceof NotFoundException) {
        httpStatus = HttpStatus.NOT_FOUND;
        body = JSONObject.toJSONString(ResponseMessage.error(404, ex.getMessage()));
    } else if (ex instanceof ResponseStatusException) {
        ResponseStatusException responseStatusException = (ResponseStatusException) ex;
        httpStatus = responseStatusException.getStatus();
        body = JSONObject.toJSONString(ResponseMessage.error(500, ex.getMessage()));
    } else {
        httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
        body = JSONObject.toJSONString(ResponseMessage.error(500, ex.getMessage()));
    }
    /**
     * 封装响应体,此body可修改为自己的jsonBody
     */
    Map<String, Object> result = new HashMap<>(2, 1);
    result.put("httpStatus", httpStatus);
    result.put("body", body);
    /**
     * 错误记录
     */
    ServerHttpRequest request = exchange.getRequest();
    log.error("[全局异常处理]异常请求路径:{},记录异常信息:{}", request.getPath().pathWithinApplication().value(), ex.getMessage());
    ex.printStackTrace();
    /**
     * 参考AbstractErrorWebExceptionHandler
     */
    if (exchange.getResponse().isCommitted()) {
        return Mono.error(ex);
    }
    exceptionHandlerResult.set(result);
    ServerRequest newRequest = ServerRequest.create(exchange, this.messageReaders);
    return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse).route(newRequest)
            .switchIfEmpty(Mono.error(ex))
            .flatMap((handler) -> handler.handle(newRequest))
            .flatMap((response) -> write(exchange, response));

}
 
Example 10
Source File: GatewayExceptionHandler.java    From spring-microservice-exam with MIT License 4 votes vote down vote up
/**
   * 处理逻辑
   *
   * @param exchange exchange
   * @param ex       ex
   * @return Mono
   */
  @Override
  public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
      String msg = "Internal Server Error";
      // 返回给前端用的状态码
      int keyCode = ApiMsg.KEY_UNKNOWN;
      int msgCode = ApiMsg.ERROR;
      if (ex instanceof NotFoundException) {
      	// 服务不可用
	keyCode = ApiMsg.KEY_SERVICE;
	msgCode = ApiMsg.UNAVAILABLE;
      } else if (ex instanceof ResponseStatusException) {
          ResponseStatusException responseStatusException = (ResponseStatusException) ex;
          msg = responseStatusException.getMessage();
	// 服务响应错误
	keyCode = ApiMsg.KEY_SERVICE;
	msgCode = ApiMsg.ERROR;
      } else if (ex instanceof InvalidValidateCodeException) {
          msg = ex.getMessage();
          // 验证码错误
	keyCode = ApiMsg.KEY_VALIDATE_CODE;
} else if (ex instanceof ValidateCodeExpiredException) {
          msg = ex.getMessage();
          // 验证码过期
	keyCode = ApiMsg.KEY_VALIDATE_CODE;
	msgCode = ApiMsg.EXPIRED;
      } else if (ex instanceof InvalidAccessTokenException) {
          msg = ex.getMessage();
          // token非法
	keyCode = ApiMsg.KEY_TOKEN;
	msgCode = ApiMsg.INVALID;
      }
      // 封装响应体
      ResponseBean<String> responseBean = new ResponseBean<>(msg, keyCode, msgCode);
      // 错误记录
      ServerHttpRequest request = exchange.getRequest();
      log.error("GatewayExceptionHandler: {}, error: {}", request.getPath(), ex.getMessage());
      if (exchange.getResponse().isCommitted())
          return Mono.error(ex);
      exceptionHandlerResult.set(responseBean);
      ServerRequest newRequest = ServerRequest.create(exchange, this.messageReaders);
      return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse).route(newRequest)
              .switchIfEmpty(Mono.error(ex))
              .flatMap((handler) -> handler.handle(newRequest))
              .flatMap((response) -> write(exchange, response));
  }
 
Example 11
Source File: ExceptionHandle.java    From microservice-recruit with Apache License 2.0 4 votes vote down vote up
@Override
public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
    /**
     * 按照异常类型进行处理
     */
    HttpStatus httpStatus;
    String body;
    if (ex instanceof MyException) {
        httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
        body = JSONObject.toJSONString(ResponseMessage.error(((MyException) ex).getCode(), ex.getMessage()));
    } else if (ex instanceof NotFoundException) {
        httpStatus = HttpStatus.NOT_FOUND;
        body = JSONObject.toJSONString(ResponseMessage.error(404, ex.getMessage()));
    } else if (ex instanceof ResponseStatusException) {
        ResponseStatusException responseStatusException = (ResponseStatusException) ex;
        httpStatus = responseStatusException.getStatus();
        body = JSONObject.toJSONString(ResponseMessage.error(500, ex.getMessage()));
    } else {
        httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
        body = JSONObject.toJSONString(ResponseMessage.error(500, ex.getMessage()));
    }
    /**
     * 封装响应体,此body可修改为自己的jsonBody
     */
    Map<String, Object> result = new HashMap<>(2, 1);
    result.put("httpStatus", httpStatus);
    result.put("body", body);
    /**
     * 错误记录
     */
    ServerHttpRequest request = exchange.getRequest();
    log.error("[全局异常处理]异常请求路径:{},记录异常信息:{}", request.getPath().pathWithinApplication().value(), ex.getMessage());
    ex.printStackTrace();
    /**
     * 参考AbstractErrorWebExceptionHandler
     */
    if (exchange.getResponse().isCommitted()) {
        return Mono.error(ex);
    }
    exceptionHandlerResult.set(result);
    ServerRequest newRequest = ServerRequest.create(exchange, this.messageReaders);
    return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse).route(newRequest)
            .switchIfEmpty(Mono.error(ex))
            .flatMap((handler) -> handler.handle(newRequest))
            .flatMap((response) -> write(exchange, response));

}
 
Example 12
Source File: CustomExceptionHandler.java    From lion with Apache License 2.0 4 votes vote down vote up
@Override
public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {

    log.error(ex.getMessage());

    /**
     * 按照异常类型进行处理
     */
    HttpStatus httpStatus;
    String body;
    if (ex instanceof BlockException) {
        httpStatus = HttpStatus.TOO_MANY_REQUESTS;
        // Too Many Request Server
        body = JsonUtil.jsonObj2Str(Result.failure(httpStatus.value(), "前方拥挤,请稍后再试"));
    } else {
        //ResponseStatusException responseStatusException = (ResponseStatusException) ex;
        //httpStatus = responseStatusException.getStatus();
        //body = responseStatusException.getMessage();

        httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
        // Internal Server Error
        body = JsonUtil.jsonObj2Str(Result.failure(httpStatus.value(), "调用失败,服务不可用"));
    }
    /**
     * 封装响应体,此body可修改为自己的jsonBody
     */
    Map<String, Object> result = new HashMap<>(2, 1);
    result.put("httpStatus", httpStatus);
    result.put("body", body);
    /**
     * 错误记录
     */
    ServerHttpRequest request = exchange.getRequest();
    log.error("[全局异常处理]异常请求路径:{},记录异常信息:{}", request.getPath(), body);
    /**
     * 参考AbstractErrorWebExceptionHandler
     */
    if (exchange.getResponse().isCommitted()) {
        return Mono.error(ex);
    }
    exceptionHandlerResult.set(result);
    ServerRequest newRequest = ServerRequest.create(exchange, this.messageReaders);
    Mono<Void> mono = RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse).route(newRequest)
            .switchIfEmpty(Mono.error(ex))
            .flatMap((handler) -> handler.handle(newRequest))
            .flatMap((response) -> write(exchange, response));
    exceptionHandlerResult.remove();
    return mono;
}
 
Example 13
Source File: SpringWebfluxApiExceptionHandler.java    From backstopper with Apache License 2.0 4 votes vote down vote up
@Override
public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
    ServerRequest fluxRequest = ServerRequest.create(exchange, messageReaders);
    RequestInfoForLogging requestInfoForLogging = new RequestInfoForLoggingWebFluxAdapter(fluxRequest);

    ErrorResponseInfo<Mono<ServerResponse>> errorResponseInfo;
    try {
        errorResponseInfo = maybeHandleException(
            ex, requestInfoForLogging
        );
    }
    catch (UnexpectedMajorExceptionHandlingError ohNoException) {
        logger.error(
            "Unexpected major error while handling exception. "
            + SpringWebfluxUnhandledExceptionHandler.class.getName() + " should handle it.", ohNoException
        );
        return Mono.error(ex);
    }

    if (errorResponseInfo == null) {
        // We didn't know how to handle the exception, so return Mono.error(ex) to indicate that error handing
        //      should continue.
        return Mono.error(ex);
    }

    // Before we try to write the response, we should check to see if it's already committed, or if the client
    //      disconnected.
    // This short circuit logic due to an already-committed response or disconnected client was copied from
    //      Spring Boot 2's AbstractErrorWebExceptionHandler class.
    if (exchange.getResponse().isCommitted() || isDisconnectedClientError(ex)) {
        return Mono.error(ex);
    }

    // We handled the exception, and the response is still valid for output (not committed, and client still
    //      connected). Add any custom headers desired by the ErrorResponseInfo, and return a Mono that writes
    //      the response.
    processWebFluxResponse(errorResponseInfo, exchange.getResponse());

    return errorResponseInfo.frameworkRepresentationObj.flatMap(
        serverResponse -> write(exchange, serverResponse)
    );
}
 
Example 14
Source File: ModifyRequestBodyGatewayFilterFactory.java    From spring-cloud-gateway with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public GatewayFilter apply(Config config) {
	return new GatewayFilter() {
		@Override
		public Mono<Void> filter(ServerWebExchange exchange,
				GatewayFilterChain chain) {
			Class inClass = config.getInClass();
			ServerRequest serverRequest = ServerRequest.create(exchange,
					messageReaders);

			// TODO: flux or mono
			Mono<?> modifiedBody = serverRequest.bodyToMono(inClass)
					.flatMap(originalBody -> config.getRewriteFunction()
							.apply(exchange, originalBody))
					.switchIfEmpty(Mono.defer(() -> (Mono) config.getRewriteFunction()
							.apply(exchange, null)));

			BodyInserter bodyInserter = BodyInserters.fromPublisher(modifiedBody,
					config.getOutClass());
			HttpHeaders headers = new HttpHeaders();
			headers.putAll(exchange.getRequest().getHeaders());

			// the new content type will be computed by bodyInserter
			// and then set in the request decorator
			headers.remove(HttpHeaders.CONTENT_LENGTH);

			// if the body is changing content types, set it here, to the bodyInserter
			// will know about it
			if (config.getContentType() != null) {
				headers.set(HttpHeaders.CONTENT_TYPE, config.getContentType());
			}
			CachedBodyOutputMessage outputMessage = new CachedBodyOutputMessage(
					exchange, headers);
			return bodyInserter.insert(outputMessage, new BodyInserterContext())
					// .log("modify_request", Level.INFO)
					.then(Mono.defer(() -> {
						ServerHttpRequest decorator = decorate(exchange, headers,
								outputMessage);
						return chain
								.filter(exchange.mutate().request(decorator).build());
					})).onErrorResume(
							(Function<Throwable, Mono<Void>>) throwable -> release(
									exchange, outputMessage, throwable));
		}

		@Override
		public String toString() {
			return filterToStringCreator(ModifyRequestBodyGatewayFilterFactory.this)
					.append("Content type", config.getContentType())
					.append("In class", config.getInClass())
					.append("Out class", config.getOutClass()).toString();
		}
	};
}