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

The following examples show how to use org.springframework.web.reactive.function.server.ServerResponse. 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: ReservationClientApplication.java    From bootiful-reactive-microservices with Apache License 2.0 7 votes vote down vote up
@Bean
RouterFunction<ServerResponse> routes(WebClient client) {
		return route(GET("/reservations/names"), r -> {

				Publisher<String> map = client
					.get()
					.uri("http://reservation-service/reservations")
					.retrieve()
					.bodyToFlux(Reservation.class)
					.map(Reservation::getEmail);

				Publisher<String> fallback =
					HystrixCommands
						.from(map)
						.fallback(Mono.just("EEK!"))
						.commandName("fallback")
						.eager()
						.build();

				return ServerResponse.ok().body(fallback, String.class);
		});
}
 
Example #2
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 #3
Source File: DefaultBlockRequestHandler.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<ServerResponse> handleRequest(ServerWebExchange exchange, Throwable ex) {
    if (acceptsHtml(exchange)) {
        return htmlErrorResponse(ex);
    }
    // JSON result by default.
    return ServerResponse.status(HttpStatus.TOO_MANY_REQUESTS)
        .contentType(MediaType.APPLICATION_JSON_UTF8)
        .body(fromObject(buildErrorResult(ex)));
}
 
Example #4
Source File: OtherEntityValidationHandler.java    From tutorials with MIT License 6 votes vote down vote up
@Override
protected Mono<ServerResponse> processBody(OtherEntity validBody, ServerRequest originalRequest) {
    String responseBody = String.format("Other object with item %s and quantity %s!", validBody.getItem(), validBody.getQuantity());
    return ServerResponse.ok()
        .contentType(MediaType.APPLICATION_JSON)
        .body(Mono.just(responseBody), String.class);
}
 
Example #5
Source File: OrderHandler.java    From Hands-On-Reactive-Programming-in-Spring-5 with MIT License 6 votes vote down vote up
public Mono<ServerResponse> create(ServerRequest request) {
    return request
        .bodyToMono(Order.class)
        .flatMap(orderRepository::save)
        .flatMap(o ->
            ServerResponse.created(URI.create("/orders/" + o.getId()))
                          .build()
        );
}
 
Example #6
Source File: EmpReactFuncController.java    From Spring-5.0-Cookbook with MIT License 6 votes vote down vote up
@Bean
public RouterFunction<ServerResponse> employeeServiceBox() {
    return route(GET("/listFluxEmps"), dataHandler::empList)
    		   .andRoute(GET("/selectEmpById/{id}"), dataHandler::chooseEmpById)
    		   .andRoute(POST("/selectFluxEmps"), dataHandler::chooseFluxEmps)
    		   .andRoute(POST("/saveEmp"), dataHandler::saveEmployeeMono)
    		   .andRoute(GET("/avgAgeEmps"), dataHandler::averageAge)
    		   .andRoute(GET("/totalAgeEmps"), dataHandler::totalAge)
    		   .andRoute(GET("/countEmps"), dataHandler::countEmps)
    		   .andRoute(GET("/countPerDept/{deptid}"), dataHandler::countEmpsPerDept)
    		   .andRoute(GET("/selectEmpValidAge/{age}"), dataHandler::chooseFluxEmpsValidAge);
}
 
Example #7
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 #8
Source File: SpringWebfluxApiExceptionHandlerTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void write_works_as_expected() {
    // given
    ServerResponse responseMock = mock(ServerResponse.class);
    HttpHeaders responseHeadersMock = mock(HttpHeaders.class);
    MediaType expectedContentTypeMock = mock(MediaType.class);

    doReturn(responseHeadersMock).when(responseMock).headers();
    doReturn(expectedContentTypeMock).when(responseHeadersMock).getContentType();

    // when
    handlerSpy.write(serverWebExchangeMock, responseMock);

    // then
    verify(serverHttpResponseHeadersMock).setContentType(expectedContentTypeMock);
    ArgumentCaptor<ResponseContext> responseContextArgumentCaptor = ArgumentCaptor.forClass(ResponseContext.class);
    verify(responseMock).writeTo(eq(serverWebExchangeMock), responseContextArgumentCaptor.capture());
    ResponseContext responseContext = responseContextArgumentCaptor.getValue();
    assertThat(responseContext.messageWriters()).isEqualTo(messageWriters);
    assertThat(responseContext.viewResolvers()).isEqualTo(viewResolvers);
}
 
Example #9
Source File: ProxyConfig.java    From spring-security-samples with MIT License 5 votes vote down vote up
@Bean
public RouterFunction<ServerResponse> proxy(WebClient webClient) {
	return route(path(API_PREFIX + SERVICE_PARAM + CATCH_ALL_SUFFIX), request -> authorizedClient(request)
		.map(attr -> webClient.method(request.method())
			.uri(toBackendUri(request))
			.headers(cleanedHeaders(request.headers().asHttpHeaders()))
			.body(fromDataBuffers(request.exchange().getRequest().getBody()))
			.attributes(attr))
		.flatMap(spec -> spec.exchange())
		.flatMap(response -> ServerResponse.status(response.statusCode())
			.headers(cleanedHeaders(response.headers().asHttpHeaders()))
			.body(fromDataBuffers(response.body(toDataBuffers())))));
}
 
Example #10
Source File: ExploreSpring5URLPatternUsingRouterFunctions.java    From tutorials with MIT License 5 votes vote down vote up
private RouterFunction<ServerResponse> routingFunction() {

        return route(GET("/p?ths"), serverRequest -> ok().body(fromObject("/p?ths"))).andRoute(GET("/test/{*id}"), serverRequest -> ok().body(fromObject(serverRequest.pathVariable("id"))))
            .andRoute(GET("/*card"), serverRequest -> ok().body(fromObject("/*card path was accessed")))
            .andRoute(GET("/{var1}_{var2}"), serverRequest -> ok().body(fromObject(serverRequest.pathVariable("var1") + " , " + serverRequest.pathVariable("var2"))))
            .andRoute(GET("/{baeldung:[a-z]+}"), serverRequest -> ok().body(fromObject("/{baeldung:[a-z]+} was accessed and baeldung=" + serverRequest.pathVariable("baeldung"))))
            .and(RouterFunctions.resources("/files/{*filepaths}", new ClassPathResource("files/")));
    }
 
Example #11
Source File: ZipkinController.java    From pitchfork with Apache License 2.0 5 votes vote down vote up
/**
 * Unmatched requests made to this service will be logged by this function.
 */
@NonNull
public Mono<ServerResponse> unmatched(ServerRequest serverRequest) {
    return serverRequest
            .bodyToMono(String.class)
            .doOnError(throwable -> logger.warn("operation=unmatched", throwable))
            .doOnNext(body -> logger.info("operation=log, path={}, headers={}", serverRequest.path(), serverRequest.headers()))
            .then(notFound().build());
}
 
Example #12
Source File: RoutingConfiguration.java    From POC with Apache License 2.0 5 votes vote down vote up
/**
 * monoRouterFunction.
 * @param bookHandler a {@link BookHandler} object.
 * @return a {@link org.springframework.web.reactive.function.server.RouterFunction}
 * object.
 */
@Bean
public RouterFunction<ServerResponse> monoRouterFunction(BookHandler bookHandler) {
	return route(GET("/api/book").and(accept(MediaType.APPLICATION_JSON)), request -> bookHandler.getAll())
			.andRoute(GET("/api/book/{id}").and(accept(MediaType.APPLICATION_JSON)), bookHandler::getBook)
			.andRoute(POST("/api/book/post").and(accept(MediaType.APPLICATION_JSON)), bookHandler::postBook)
			.andRoute(PUT("/api/book/put/{id}").and(accept(MediaType.APPLICATION_JSON)), bookHandler::putBook)
			.andRoute(DELETE("/api/book/delete/{id}").and(accept(MediaType.APPLICATION_JSON)),
					bookHandler::deleteBook);
}
 
Example #13
Source File: WebTestClientBuilder.java    From spring-security-reactive with Apache License 2.0 5 votes vote down vote up
private static ApplicationContext applicationContext(WebFilter... webFilters) {
	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
	for(WebFilter filter : webFilters) {
		context.registerBean(WebFilter.class, () -> filter);
	}
	context.registerBean("webHandler", DispatcherHandler.class, () -> new DispatcherHandler());
	context.registerBean(HandlerMapping.class, () -> RouterFunctions.toHandlerMapping(request -> Mono.just(r -> ServerResponse.ok().build())));
	context.registerBean(HandlerAdapter.class, () -> new HandlerFunctionAdapter());
	context.registerBean(HandlerResultHandler.class, () -> new ServerResponseResultHandler());
	context.refresh();

	return context;
}
 
Example #14
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 #15
Source File: MetricsConfiguration.java    From liiklus with MIT License 5 votes vote down vote up
@Override
public void initialize(GenericApplicationContext applicationContext) {
    var environment = applicationContext.getEnvironment();

    if (!environment.acceptsProfiles(Profiles.of("exporter"))) {
        return;
    }

    applicationContext.registerBean(MetricsCollector.class);

    applicationContext.registerBean("prometheus", RouterFunction.class, () -> {
        var metricsCollector = applicationContext.getBean(MetricsCollector.class);
        return RouterFunctions.route()
                .GET("/prometheus", __ -> {
                    return metricsCollector.collect()
                            .collectList()
                            .flatMap(metrics -> {
                                try {
                                    var writer = new StringWriter();
                                    TextFormat.write004(writer, Collections.enumeration(metrics));
                                    return ServerResponse.ok()
                                            .contentType(MediaType.valueOf(TextFormat.CONTENT_TYPE_004))
                                            .bodyValue(writer.toString());
                                } catch (IOException e) {
                                    return ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
                                }
                            });
                })
                .build();

    });
}
 
Example #16
Source File: HomeController.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Bean
RouterFunction<ServerResponse> index() {
    return route(
        GET("/"),
        req -> ServerResponse.temporaryRedirect(URI.create("swagger-ui/index.html?url=../openapi.json")).build()
    );
}
 
Example #17
Source File: Server.java    From Building-RESTful-Web-Services-with-Spring-5-Second-Edition with MIT License 5 votes vote down vote up
public RouterFunction<ServerResponse> routingFunction() {
	UserRepository repository = new UserRepositorySample();
	UserHandler handler = new UserHandler(repository);

	return nest(path("/user"),
			nest(accept(APPLICATION_JSON),
					route(GET("/{id}"), handler::getAllUsers).andRoute(method(HttpMethod.GET),
							handler::getAllUsers)).andRoute(POST("/").and(contentType(APPLICATION_JSON)),
									handler::getAllUsers));
}
 
Example #18
Source File: RoutingConfiguration.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
@Bean
@RouterOperations({ @RouterOperation(path = "/api/user/index", beanClass = UserRepository.class, beanMethod = "getAllUsers"),
		@RouterOperation(path = "/api/user/{id}", beanClass = UserRepository.class, beanMethod = "getUserById"),
		@RouterOperation(path = "/api/user/post", beanClass = UserRepository.class, beanMethod = "saveUser"),
		@RouterOperation(path = "/api/user/put/{id}", beanClass = UserRepository.class, beanMethod = "putUser"),
		@RouterOperation(path = "/api/user/delete/{id}", beanClass = UserRepository.class, beanMethod = "deleteUser") })
public RouterFunction<ServerResponse> monoRouterFunction(UserHandler userHandler) {
	return route(GET("/api/user/index").and(accept(MediaType.APPLICATION_JSON)), userHandler::getAll)
			.andRoute(GET("/api/user/{id}").and(accept(MediaType.APPLICATION_JSON)), userHandler::getUser)
			.andRoute(POST("/api/user/post").and(accept(MediaType.APPLICATION_JSON)), userHandler::postUser)
			.andRoute(PUT("/api/user/put/{id}").and(accept(MediaType.APPLICATION_JSON)), userHandler::putUser)
			.andRoute(DELETE("/api/user/delete/{id}").and(accept(MediaType.APPLICATION_JSON)), userHandler::deleteUser);
}
 
Example #19
Source File: ReactiveControllers.java    From Spring-5.0-Cookbook with MIT License 5 votes vote down vote up
@Bean
public RouterFunction<ServerResponse> loginServiceBox() {
    return route(GET("/listFluxLogins"), loginHandler::loginDetailsList)
    		   .andRoute(GET("/selectLoginById/{id}"), loginHandler::loginDetailsById)
    		   .andRoute(POST("/selectFluxLogins"), loginHandler::chooseFluxLoginDetails)
    		   .andRoute(POST("/saveLogin"), loginHandler::saveLogindetailsMono)
    		   .andRoute(GET("/totalLogins"), loginHandler::countLogins);
}
 
Example #20
Source File: FluxSinkApplication.java    From spring-5-examples with MIT License 5 votes vote down vote up
@Bean
RouterFunction<ServerResponse> routes(final Flux<ServerSentEvent<Map>> processor,
                                      final Consumer<String> distributeEvent) {

  final ParameterizedTypeReference<Map<String, String>> type
      = new ParameterizedTypeReference<Map<String, String>>() {};

  return

      route(GET("/**"),
            request -> ok().contentType(request.headers().accept().contains(TEXT_EVENT_STREAM)
                                            ? TEXT_EVENT_STREAM : APPLICATION_STREAM_JSON)
                           .body(processor.map(s -> s), ServerSentEvent.class))

          .andRoute(POST("/**"),
                    request -> accepted().body(request.bodyToMono(type)
                                                      .map(map -> map.getOrDefault("message", ""))
                                                      .map(String::valueOf)
                                                      .map(String::trim)
                                                      .filter(s -> s.length() > 0)
                                                      .doOnNext(distributeEvent)
                                                      .map(m -> format("message '%s' accepted.", m))
                                                      .map(message -> singletonMap("response", message))
                                                      .subscribeOn(Schedulers.elastic())
                                                      .flatMap(Mono::just), Map.class))
      ;
}
 
Example #21
Source File: EmpDataHandler.java    From Spring-5.0-Cookbook with MIT License 5 votes vote down vote up
public Mono<ServerResponse> countEmpsPerDept(ServerRequest req) {
	Function<Employee, Integer> ages = (emp) -> emp.getAge();
	Function<Employee, Mono<Integer>> flatMapAge = (emp) -> Mono.just(emp).map(ages);
	Mono<Integer> count = Flux.fromIterable(employeeServiceImpl.findAllEmps()).filter((emp) -> emp.getDeptid().equals(Integer.parseInt(req.pathVariable("deptid"))))
			.flatMap(flatMapAge)
			.reduce((total, increment) -> total + increment);
	return ok().contentType(MediaType.APPLICATION_STREAM_JSON).body(count, Integer.class)
			.switchIfEmpty(ServerResponse.notFound().build());
}
 
Example #22
Source File: DeptReactFuncController.java    From Spring-5.0-Cookbook with MIT License 5 votes vote down vote up
@Bean
public RouterFunction<ServerResponse> departmentServiceBox(){
	return route(GET("/listFluxDepts"), dataHandler::deptList)
			.andRoute(GET("/selectDeptById/{id}"), dataHandler::chooseDeptById)
			.andRoute(POST("/selectFluxDepts"), dataHandler::chooseFluxDepts)
			.andRoute(POST("/saveFluxDept"), dataHandler::saveDepartmentMono)
			.andRoute(GET("/countFluxDepts"), dataHandler::countDepts);
	
}
 
Example #23
Source File: LoginHandler.java    From Spring-5.0-Cookbook with MIT License 5 votes vote down vote up
public Mono<ServerResponse> countLogins(ServerRequest req) {
	
	Mono<Long> count = Flux.fromIterable(logindetailsServiceImpl.findAllLogindetails())
			.count();
	TotalUsers countEmp = new TotalUsers();
	countEmp.setCount(count.block());
	Mono<TotalUsers> monoCntLogins = Mono.justOrEmpty(countEmp);
	return ok().contentType(MediaType.APPLICATION_STREAM_JSON).body(monoCntLogins, TotalUsers.class)
			.switchIfEmpty(ServerResponse.notFound().build());
}
 
Example #24
Source File: SwaggerUiHandler.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(UiConfigurationBuilder.builder().build()));
}
 
Example #25
Source File: UserRoutes.java    From spring-5-examples with MIT License 5 votes vote down vote up
@Bean
RouterFunction<ServerResponse> routes(final UserHandlers handlers) {

  return route(GET("/api/v1/users/**"),
               handlers::streamUsers)
      .andRoute(POST("/api/v1/users/**"),
                handlers::saveUser)
      ;
}
 
Example #26
Source File: FormHandler.java    From tutorials with MIT License 5 votes vote down vote up
Mono<ServerResponse> handleLogin(ServerRequest request) {
    return request.body(toFormData())
        .map(MultiValueMap::toSingleValueMap)
        .filter(formData -> "baeldung".equals(formData.get("user")))
        .filter(formData -> "you_know_what_to_do".equals(formData.get("token")))
        .flatMap(formData -> ok().body(Mono.just("welcome back!"), String.class))
        .switchIfEmpty(ServerResponse.badRequest()
            .build());
}
 
Example #27
Source File: GatewaySampleApplication.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Bean
public RouterFunction<ServerResponse> testWhenMetricPathIsNotMeet() {
	RouterFunction<ServerResponse> route = RouterFunctions.route(
			RequestPredicates.path("/actuator/metrics/gateway.requests"),
			request -> ServerResponse.ok().body(BodyInserters
					.fromValue(HELLO_FROM_FAKE_ACTUATOR_METRICS_GATEWAY_REQUESTS)));
	return route;
}
 
Example #28
Source File: SubnetWebHandlers.java    From alcor with Apache License 2.0 5 votes vote down vote up
public Mono<ServerResponse> getSubnet(ServerRequest request) {
    UUID projectId = UUID.fromString(request.pathVariable("projectId"));
    UUID subnetId = UUID.fromString(request.pathVariable("subnetId"));

    Mono<SubnetWebJson> subnetInfo = serviceProxy.findSubnetById(projectId, subnetId);

    return subnetInfo.flatMap(od -> ServerResponse.ok()
            .contentType(APPLICATION_JSON)
            .body(fromObject(od)))
            .onErrorResume(SubnetNotFoundException.class, e -> ServerResponse.notFound().build());
}
 
Example #29
Source File: JsonExceptionHandler.java    From open-cloud with MIT License 5 votes vote down vote up
/**
 * 参考AbstractErrorWebExceptionHandler
 *
 * @param exchange
 * @param response
 * @return
 */
private Mono<? extends Void> write(ServerWebExchange exchange,
                                   ServerResponse response,Throwable ex) {
    exchange.getResponse().getHeaders()
            .setContentType(response.headers().getContentType());
    // 保存日志
    accessLogService.sendLog(exchange, (Exception) ex);
    return response.writeTo(exchange, new ResponseContext());
}
 
Example #30
Source File: GithubRoutesConfig.java    From spring-5-examples with MIT License 5 votes vote down vote up
@Bean
RouterFunction<ServerResponse> githubRoutes(final GithubProperties props,
                                            final WebClient githubWebClient) {
  return

      route(GET("/github/props/manual"),
            request -> ok().body(Mono.just(
                singletonMap("github",
                             singletonMap("token", props.getToken()))),
                                 Map.class))

          .andRoute(GET("/github/props/**"),
                    request -> ok().body(Mono.just(props), GithubProperties.class))

          .andRoute(GET("/github/search/users/{username}"), // ?page=1&size=2
                    request -> ok().body(githubWebClient.get()
                                                        .uri(
                                                            "/search/users?q={q}&page={page}&per_page={per_page}",
                                                            HashMap.of(
                                                                "q", request.pathVariable("username"),
                                                                "page", request.queryParam("page").orElse("0"),
                                                                "per_page", request.queryParam("size").orElse("3")
                                                            ).toJavaMap()
                                                        )
                                                        .exchange()
                                                        .subscribeOn(Schedulers.elastic())
                                                        .flatMapMany(response -> response.bodyToFlux(Map.class)),
                                         Map.class))

          .andRoute(GET("/**"),
                    request -> ok().body(Mono.just(singletonMap("result", "TODO")),
                                         Map.class))
      ;
}