org.springframework.web.reactive.function.server.ServerRequest Java Examples

The following examples show how to use org.springframework.web.reactive.function.server.ServerRequest. 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: GlobalErrorAttributes.java    From springboot-learning-example with Apache License 2.0 7 votes vote down vote up
@Override
public Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {
    Map<String, Object> map = super.getErrorAttributes(request, includeStackTrace);

    if (getError(request) instanceof GlobalException) {
        GlobalException ex = (GlobalException) getError(request);
        map.put("exception", ex.getClass().getSimpleName());
        map.put("message", ex.getMessage());
        map.put("status", ex.getStatus().value());
        map.put("error", ex.getStatus().getReasonPhrase());
        
        return map;
    }

    map.put("exception", "SystemException");
    map.put("message", "System Error , Check logs!");
    map.put("status", "500");
    map.put("error", " System Error ");
    return map;
}
 
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: BodyPropertyMatchingRoutePredicateFactory.java    From syncope with Apache License 2.0 6 votes vote down vote up
@Override
public AsyncPredicate<ServerWebExchange> applyAsync(final Config config) {
    return exchange -> {
        JsonNode cachedBody = exchange.getAttribute(CACHE_REQUEST_BODY_OBJECT_KEY);
        if (cachedBody == null) {
            return ServerWebExchangeUtils.cacheRequestBodyAndRequest(
                    exchange, serverHttpRequest -> ServerRequest.create(
                            exchange.mutate().request(serverHttpRequest).build(), MESSAGE_READERS).
                            bodyToMono(JsonNode.class).
                            doOnNext(objectValue -> exchange.getAttributes().
                            put(CACHE_REQUEST_BODY_OBJECT_KEY, objectValue)).
                            map(objectValue -> objectValue.has(config.getData())));
        } else {
            return Mono.just(cachedBody.has(config.getData()));
        }
    };
}
 
Example #4
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 #5
Source File: ImageCodeHandler.java    From sophia_scaffolding with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<ServerResponse> handle(ServerRequest serverRequest) {
	//生成验证码
	String text = producer.createText();
	BufferedImage image = producer.createImage(text);

	//保存验证码信息
	String randomStr = serverRequest.queryParam("randomStr").get();
	redisTemplate.opsForValue().set(DEFAULT_CODE_KEY + randomStr, text, 120, TimeUnit.SECONDS);

	// 转换流信息写出
	FastByteArrayOutputStream os = new FastByteArrayOutputStream();
	try {
		ImageIO.write(image, "jpeg", os);
	} catch (IOException e) {
		log.error("ImageIO write err", e);
		return Mono.error(e);
	}

	return ServerResponse
		.status(HttpStatus.OK)
		.contentType(MediaType.IMAGE_JPEG)
		.body(BodyInserters.fromResource(new ByteArrayResource(os.toByteArray())));
}
 
Example #6
Source File: LinkGenerator.java    From staccato with Apache License 2.0 6 votes vote down vote up
/**
 * Creates links to subcatalogs based on unique values matched in the database for the selected properties field.
 *
 * @param request The server request object
 * @param collection The collection metadata
 * @param values A list of unique values in the database for the selected subcataloged field
 */
public void generatePropertyValueLinks(ServerRequest request, CollectionMetadata collection, List<String> values) {
    values.forEach(value -> collection.getLinks().add(
            new Link()
                    .href(appendLinkPath(LinksConfigProps.LINK_PREFIX + request.path(), value))
                    .type(MediaType.APPLICATION_JSON_VALUE)
                    .rel("child")));

    String self = getSelfString(request);
    collection.getLinks().add(ROOT);
    collection.getLinks().add(new Link()
            .href(self)
            .type(MediaType.APPLICATION_JSON_VALUE)
            .rel("self"));
    collection.getLinks().add(new Link()
            .href(appendLinkPath(self, "items"))
            .type(StaccatoMediaType.APPLICATION_GEO_JSON_VALUE)
            .rel("items"));
    collection.getLinks().add(new Link()
            .href(self.substring(0, self.lastIndexOf("/")))
            .type(MediaType.APPLICATION_JSON_VALUE)
            .rel("parent"));
}
 
Example #7
Source File: WingtipsSpringWebfluxComponentTest.java    From wingtips with Apache License 2.0 6 votes vote down vote up
Mono<ServerResponse> routerFunctionEndpoint(ServerRequest request) {
    HttpHeaders headers = request.headers().asHttpHeaders();

    if ("true".equals(headers.getFirst("throw-exception"))) {
        sleepThread(SLEEP_TIME_MILLIS);
        throw new RuntimeException("Error thrown in routerFunctionEndpoint(), outside Mono");
    }

    if ("true".equals(headers.getFirst("return-exception-in-mono"))) {
        return Mono
            .delay(Duration.ofMillis(SLEEP_TIME_MILLIS))
            .map(d -> {
                throw new RuntimeException("Error thrown in routerFunctionEndpoint(), inside Mono");
            });
    }

    return ServerResponse
        .ok()
        .syncBody(ROUTER_FUNCTION_ENDPOINT_RESPONSE_PAYLOAD)
        .delayElement(Duration.ofMillis(SLEEP_TIME_MILLIS));
}
 
Example #8
Source File: DemoApplication.java    From spring-reactive-sample with GNU General Public License v3.0 6 votes vote down vote up
public Mono<ServerResponse> update(ServerRequest req) {

        return Mono
            .zip(
                (data) -> {
                    Post p = (Post) data[0];
                    Post p2 = (Post) data[1];
                    p.setTitle(p2.getTitle());
                    p.setContent(p2.getContent());
                    return p;
                },
                this.posts.findById(req.pathVariable("id")),
                req.bodyToMono(Post.class)
            )
            .cast(Post.class)
            .flatMap(post -> this.posts.save(post))
            .flatMap(post -> ServerResponse.noContent().build());

    }
 
Example #9
Source File: HystrixFallbackHandler.java    From spring-microservice-exam with MIT License 5 votes vote down vote up
@Override
public Mono<ServerResponse> handle(ServerRequest serverRequest) {
    Optional<Object> originalUris = serverRequest.attribute(GATEWAY_ORIGINAL_REQUEST_URL_ATTR);
    originalUris.ifPresent(originalUri -> log.error("网关执行请求:{}失败,hystrix服务降级处理", originalUri));
    return ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR.value())
            .contentType(MediaType.TEXT_PLAIN).body(BodyInserters.fromObject("服务异常"));
}
 
Example #10
Source File: MovieHandler.java    From spring-5-examples with MIT License 5 votes vote down vote up
public Mono<ServerResponse> eventStream(final ServerRequest request) {

    val id = request.pathVariable("id");
    val body = movieService.streamEvents(id);

    return ServerResponse.ok()
                         .contentType(TEXT_EVENT_STREAM)
                         .body(body, MovieEvent.class);
  }
 
Example #11
Source File: DataHandler.java    From Spring-5.0-Cookbook with MIT License 5 votes vote down vote up
public Mono<ServerResponse> countDepts(ServerRequest req) {
	
	Mono<Long> count = Flux.fromIterable(departmentServiceImpl.findAllDepts())
			.count();	
	CountDept countDept = new CountDept();
	countDept.setCount(count.block());
	Mono<CountDept> monoCntDept = Mono.justOrEmpty(countDept);
	return ok().contentType(MediaType.APPLICATION_STREAM_JSON).body(monoCntDept, CountDept.class)
			.switchIfEmpty(ServerResponse.notFound().build());
}
 
Example #12
Source File: BackstopperSpringWebFluxComponentTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
Mono<ServerResponse> routerFunctionEndpoint(ServerRequest request) {
    HttpHeaders headers = request.headers().asHttpHeaders();

    if ("true".equals(headers.getFirst("throw-exception"))) {
        throw new ApiException(ERROR_THROWN_IN_ROUTER_FUNCTION_ENDPOINT);
    }

    if ("true".equals(headers.getFirst("return-exception-in-mono"))) {
        return Mono.error(
            new ApiException(ERROR_RETURNED_IN_ROUTER_FUNCTION_ENDPOINT_MONO)
        );
    }

    return ServerResponse.ok().syncBody(ROUTER_FUNCTION_ENDPOINT_RESPONSE_PAYLOAD);
}
 
Example #13
Source File: GraphAlgorithmHandler.java    From kafka-graphs with Apache License 2.0 5 votes vote down vote up
public Mono<ServerResponse> state(ServerRequest request) {
    String appId = request.pathVariable("id");
    PregelGraphAlgorithm<?, ?, ?, ?> algorithm = algorithms.get(appId);
    if (algorithm == null) {
        return ServerResponse.notFound().build();
    }
    return ServerResponse.ok()
        .contentType(MediaType.APPLICATION_JSON)
        .body(Mono.just(new GraphAlgorithmStatus(algorithm.state())), GraphAlgorithmStatus.class);
}
 
Example #14
Source File: Handler3.java    From tutorials with MIT License 5 votes vote down vote up
public Mono<ServerResponse> handleRequest3(ServerRequest request) {
    return 
        sayHello(request)
          .flatMap(s -> ServerResponse.ok()
                    .contentType(MediaType.TEXT_PLAIN)
                    .syncBody(s))
          .onErrorResume(e -> (Mono.just("Hi, I looked around for your name but found: " + 
                e.getMessage())).flatMap(s -> ServerResponse.ok()
            .contentType(MediaType.TEXT_PLAIN)
            .syncBody(s)));
}
 
Example #15
Source File: UserRoutes.java    From spring-5-examples with MIT License 5 votes vote down vote up
public Mono<ServerResponse> saveUser(final ServerRequest request) {

    return ServerResponse.ok()
                         .contentType(APPLICATION_STREAM_JSON)
                         .body(request.bodyToFlux(User.class)
                                      .flatMap(users::save), User.class);
  }
 
Example #16
Source File: WebfluxHandler.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public Mono<ServerResponse> updates(ServerRequest request) {
    int queries = getQueries(request);
    
    Mono<List<World>> worlds = Flux.range(0, queries)
            .flatMap(i -> dbRepository.findAndUpdateWorld(randomWorldNumber(), randomWorldNumber()))
            .collectList();

    return ServerResponse.ok()
            .contentType(MediaType.APPLICATION_JSON)
            .body(worlds, new ParameterizedTypeReference<List<World>>() {
            });
}
 
Example #17
Source File: JsonExceptionHandler.java    From sophia_scaffolding with Apache License 2.0 5 votes vote down vote up
/**
 * 构建异常信息
 * @param request
 * @param ex
 * @return
 */
private String buildMessage(ServerRequest request, Throwable ex) {
    StringBuilder message = new StringBuilder("Failed to handle request [");
    message.append(request.methodName());
    message.append(" ");
    message.append(request.uri());
    message.append("]");
    if (ex != null) {
        message.append(": ");
        message.append(ex.getMessage());
    }
    return message.toString();
}
 
Example #18
Source File: BookHandler.java    From POC with Apache License 2.0 5 votes vote down vote up
public Mono<ServerResponse> getBook(ServerRequest request) {
	// build notFound response
	Mono<ServerResponse> notFound = ServerResponse.notFound().build();

	// get book from repository
	Mono<Book> bookMono = this.reactiveBookService.getBookById(id(request));

	// build response
	return bookMono.flatMap((Book book) -> ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
			.body(BodyInserters.fromValue(book))).switchIfEmpty(notFound);
}
 
Example #19
Source File: GlobalErrorAttributes.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {
    Map<String, Object> map = super.getErrorAttributes(request, includeStackTrace);
    map.put("status", getStatus());
    map.put("message", getMessage());
    return map;
}
 
Example #20
Source File: SwaggerSecurityHandler.java    From SpringBlade with Apache License 2.0 5 votes vote down vote up
/**
 * Handle the given request.
 *
 * @param request the request to handler
 * @return the response
 */
@Override
public Mono<ServerResponse> handle(ServerRequest request) {
	return ServerResponse.status(HttpStatus.OK)
		.contentType(MediaType.APPLICATION_JSON)
		.body(BodyInserters.fromValue(SecurityConfigurationBuilder.builder().build()));
}
 
Example #21
Source File: HystrixFallbackHandler.java    From jeecg-cloud with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<ServerResponse> handle(ServerRequest serverRequest) {
	Optional<Object> originalUris = serverRequest.attribute(GATEWAY_ORIGINAL_REQUEST_URL_ATTR);

	originalUris.ifPresent(originalUri -> log.error("网关执行请求:{}失败,hystrix服务降级处理", originalUri));

	return ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR.value())
		.header("Content-Type","text/plain; charset=utf-8").body(BodyInserters.fromObject("服务异常"));
}
 
Example #22
Source File: UserHandler.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * PUT a User
 */
public Mono<ServerResponse> putUser(ServerRequest request) {
    // parse id from path-variable
    long customerId = Long.valueOf(request.pathVariable("id"));

    // get customer data from request object
    Mono<User> customer = request.bodyToMono(User.class);

    // get customer from repository 
    Mono<User> responseMono = customerRepository.putUser(customerId, customer);

    // build response
    return responseMono
        .flatMap(cust -> ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(fromObject(cust)));
}
 
Example #23
Source File: App.java    From spring-5-examples with MIT License 5 votes vote down vote up
public Mono<ServerResponse> falback(ServerRequest request) {
  final URI uri = request.uri();
  final String scheme = uri.getScheme();
  final String authority = uri.getAuthority();
  final String baseUrl = format("%s://%s", scheme, authority);
  final Map<String, String> api = HashMap.of("hey", format("%s/hey", baseUrl),
                                             "hoy", format("%s/hoy", baseUrl),
                                             "collect", format("%s/collect", baseUrl))
                                         .toJavaMap();
  return jsonBuilder.body(Mono.just(api), Map.class);
}
 
Example #24
Source File: GatewayContextFilter.java    From open-cloud with MIT License 5 votes vote down vote up
/**
 * ReadJsonBody
 * @param exchange
 * @param chain
 * @return
 */
private Mono<Void> readBody(ServerWebExchange exchange, WebFilterChain chain, GatewayContext gatewayContext){
    return DataBufferUtils.join(exchange.getRequest().getBody())
            .flatMap(dataBuffer -> {
                /*
                 * read the body Flux<DataBuffer>, and release the buffer
                 * //TODO when SpringCloudGateway Version Release To G.SR2,this can be update with the new version's feature
                 * see PR https://github.com/spring-cloud/spring-cloud-gateway/pull/1095
                 */
                byte[] bytes = new byte[dataBuffer.readableByteCount()];
                dataBuffer.read(bytes);
                DataBufferUtils.release(dataBuffer);
                Flux<DataBuffer> cachedFlux = Flux.defer(() -> {
                    DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
                    DataBufferUtils.retain(buffer);
                    return Mono.just(buffer);
                });
                /*
                 * repackage ServerHttpRequest
                 */
                ServerHttpRequest mutatedRequest = new ServerHttpRequestDecorator(exchange.getRequest()) {
                    @Override
                    public Flux<DataBuffer> getBody() {
                        return cachedFlux;
                    }
                };
                ServerWebExchange mutatedExchange = exchange.mutate().request(mutatedRequest).build();
                return ServerRequest.create(mutatedExchange, MESSAGE_READERS)
                        .bodyToMono(String.class)
                        .doOnNext(objectValue -> {
                            gatewayContext.setRequestBody(objectValue);
                            try {
                                gatewayContext.getAllRequestData().setAll(JSONObject.parseObject(objectValue, Map.class));
                            }catch (Exception e){
                                log.error("[GatewayContext]Read JsonBody error:{}",e);
                            }
                            log.debug("[GatewayContext]Read JsonBody Success");
                        }).then(chain.filter(mutatedExchange));
            });
}
 
Example #25
Source File: UserHandler.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * GET ALL Users
 */
public Mono<ServerResponse> getAll(ServerRequest request) {
    // fetch all customers from repository
    Flux<User> customers = customerRepository.getAllUsers();

    // build response
    return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(customers, User.class);
}
 
Example #26
Source File: GraphAlgorithmHandler.java    From kafka-graphs with Apache License 2.0 5 votes vote down vote up
public Mono<ServerResponse> configs(ServerRequest request) {
    String appId = request.pathVariable("id");
    PregelGraphAlgorithm<?, ?, ?, ?> algorithm = algorithms.get(appId);
    if (algorithm == null) {
        return ServerResponse.notFound().build();
    }
    return ServerResponse.ok()
        .contentType(MediaType.APPLICATION_JSON)
        .body(Mono.just(algorithm.configs()), Map.class);
}
 
Example #27
Source File: MovieHandler.java    From spring-5-examples with MIT License 5 votes vote down vote up
public Mono<ServerResponse> eventStream(final ServerRequest request) {

    val id = request.pathVariable("id");
    val body = movieService.streamEvents(id);

    return ServerResponse.ok()
                         .contentType(TEXT_EVENT_STREAM)
                         .body(body, MovieEvent.class);
  }
 
Example #28
Source File: App.java    From spring-5-examples with MIT License 5 votes vote down vote up
public Mono<ServerResponse> collect(ServerRequest request) {
  return jsonBuilder.body(
      Mono.zip(
          webClient.get().uri("/api/v1/hey").retrieve()
                   .bodyToMono(String.class)
                   .map(h -> format("HEY response: %s", h)),
          webClient.get().uri("/api/v1/hoy").retrieve()
                   .bodyToMono(String.class)
                   .map(h -> format("HOY response: %s", h)))
          .map(tuple2 -> format("%s - %s", tuple2.getT1(), tuple2.getT2())),
      String.class);
}
 
Example #29
Source File: DeptDataHandler.java    From Spring-5.0-Cookbook with MIT License 5 votes vote down vote up
public Mono<ServerResponse> countDepts(ServerRequest req) {
	Mono<Long> count = Flux.fromIterable(departmentServiceImpl.findAllDepts())
			.count();	
	CountDept countDept = new CountDept();
	countDept.setCount(count.block());
	Mono<CountDept> monoCntDept = Mono.justOrEmpty(countDept);
	return ok().contentType(MediaType.APPLICATION_STREAM_JSON).body(monoCntDept, CountDept.class)
			.switchIfEmpty(ServerResponse.notFound().build());
}
 
Example #30
Source File: ApiHandlerTest.java    From reactive-ms-example with MIT License 5 votes vote down vote up
@Test
void buildResponseTest() {
    final ServerRequest serverRequest = mock(ServerRequest.class);
    when(serverRequest.pathVariable(ADDRESS_VARIABLE)).thenReturn(GOOGLE_ADDRESS);

    doReturn(GOOGLE_LOCATION).when(geoLocationService).fromAddress(any());
    doReturn(SUNRISE_SUNSET).when(sunriseSunsetService).fromGeographicCoordinates(any());

    Mono.just(GOOGLE_ADDRESS).transform(apiHandler::buildResponse).subscribe(this::verifyServerResponse);

    reset(geoLocationService);
    reset(sunriseSunsetService);
}