Java Code Examples for org.springframework.web.reactive.function.server.RouterFunction

The following examples show how to use org.springframework.web.reactive.function.server.RouterFunction. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: influx-proxy   Source File: Router.java    License: Apache License 2.0 6 votes vote down vote up
@Bean
public RouterFunction<ServerResponse> routeCity(InfluxProxyHandler influxProxyHandler) {
    return RouterFunctions
            .route(RequestPredicates.path("/query")
                            .and(RequestPredicates.accept(MediaType.ALL)),
                    influxProxyHandler::query)
            .andRoute(RequestPredicates.POST("/write")
                            .and(RequestPredicates.accept(MediaType.ALL)),
                    influxProxyHandler::write)
            .andRoute(RequestPredicates.GET("/ping")
                            .and(RequestPredicates.accept(MediaType.ALL)),
                    influxProxyHandler::ping)
            .andRoute(RequestPredicates.path("/debug/{opt}")
                            .and(RequestPredicates.accept(MediaType.ALL)),
                    influxProxyHandler::debug)
            .andRoute(RequestPredicates.path("/debug")
                            .and(RequestPredicates.accept(MediaType.ALL)),
                    influxProxyHandler::debug)
            .andRoute(RequestPredicates.path("/refresh/allBackend")
                            .and(RequestPredicates.accept(MediaType.ALL)),
                    influxProxyHandler::refreshAllBackend)
            ;
}
 
Example 2
Source Project: spring-5-examples   Source File: App.java    License: MIT License 6 votes vote down vote up
@Bean
RouterFunction routes(final HandlerFunction<ServerResponse> fallbackHandler) {
  return
      nest(
          path("/"),
          nest(
              accept(APPLICATION_JSON),
              route(
                  GET("/api/orders"),
                  getOrdersHandler()
              )
          ).andNest(
              accept(APPLICATION_JSON),
              route(
                  GET("/api"),
                  getCountQueryHandler()
              )
          )
      ).andOther(
          route(
              GET("/**"),
              fallbackHandler
          )
      )
      ;
}
 
Example 3
Source Project: tutorials   Source File: FunctionalSpringBootApplication.java    License: MIT License 6 votes vote down vote up
private RouterFunction<ServerResponse> routingFunction() {
    FormHandler formHandler = new FormHandler();

    RouterFunction<ServerResponse> restfulRouter = route(GET("/"),
        serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"),
            serverRequest -> serverRequest.bodyToMono(Actor.class)
                .doOnNext(actors::add)
                .then(ok().build()));

    return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld")))
        .andRoute(POST("/login"), formHandler::handleLogin)
        .andRoute(POST("/upload"), formHandler::handleUpload)
        .and(RouterFunctions.resources("/files/**", new ClassPathResource("files/")))
        .andNest(path("/actor"), restfulRouter)
        .filter((request, next) -> {
            System.out.println("Before handler invocation: " + request.path());
            return next.handle(request);
        });
}
 
Example 4
@Bean
public RouterFunction<ServerResponse> routes(OrderHandler orderHandler) {
	return
		nest(path("/orders"),
			nest(accept(APPLICATION_JSON),
				route(GET("/{id}"), orderHandler::get)
				.andRoute(method(HttpMethod.GET), orderHandler::list)
			)
			.andNest(contentType(APPLICATION_JSON),
				route(POST("/"), orderHandler::create)
			)
			.andNest((serverRequest) -> serverRequest.cookies()
			                                         .containsKey("Redirect-Traffic"),
				route(all(), serverRedirectHandler)
			)
		);
}
 
Example 5
@Bean
@RouterOperations({ @RouterOperation(path = "/employees-composed/update", beanClass = EmployeeRepository.class, beanMethod = "updateEmployee"),
		@RouterOperation(path = "/employees-composed/{id}", beanClass = EmployeeRepository.class, beanMethod = "findEmployeeById"),
		@RouterOperation(path = "/employees-composed", beanClass = EmployeeRepository.class, beanMethod = "findAllEmployees") })
RouterFunction<ServerResponse> composedRoutes() {
	return
			route(GET("/employees-composed"),
					req -> ok().body(
							employeeRepository().findAllEmployees(), Employee.class))
					.and(route(GET("/employees-composed/{id}"),
							req -> ok().body(
									employeeRepository().findEmployeeById(req.pathVariable("id")), Employee.class)))
					.and(route(POST("/employees-composed/update"),
							req -> req.body(BodyExtractors.toMono(Employee.class))
									.doOnNext(employeeRepository()::updateEmployee)
									.then(ok().build())));
}
 
Example 6
Source Project: streaming-file-server   Source File: FileItemsRoutes.java    License: MIT License 6 votes vote down vote up
@Bean
  public RouterFunction<ServerResponse> routes(final FileItemsHandler handler) {
/*    return
        nest(path("/api/v1/file-items"),
             route(GET("/"), handler::getAll)
                 .andRoute(GET("/like/{filename}/**"), handler::searchAny)
                 .andRoute(POST("/all/**"), handler::saveAll))
                 .andRoute(GET("/{id}/**"), handler::getById)
                 .andRoute(POST("/**"), handler::save)
            .andRoute(path("/**"), handler::getAll);
*/
    return
        route(GET("/api/v1/file-items/like/{filename}"), handler::searchAny)
            .andRoute(POST("/api/v1/file-items/all"), handler::saveAll)
            .andRoute(GET("/api/v1/file-items/{id}"), handler::getById)
            .andRoute(POST("/api/v1/file-items"), handler::save)
            .andRoute(path("/**"), handler::getAll)
        ;
  }
 
Example 7
Source Project: tutorials   Source File: EmployeeFunctionalConfig.java    License: MIT License 6 votes vote down vote up
@Bean
RouterFunction<ServerResponse> composedRoutes() {
  return 
      route(GET("/employees"), 
        req -> ok().body(
          employeeRepository().findAllEmployees(), Employee.class))
        
      .and(route(GET("/employees/{id}"), 
        req -> ok().body(
          employeeRepository().findEmployeeById(req.pathVariable("id")), Employee.class)))
        
      .and(route(POST("/employees/update"), 
        req -> req.body(toMono(Employee.class))
                  .doOnNext(employeeRepository()::updateEmployee)
                  .then(ok().build())));
}
 
Example 8
public RouterFunction<ServerResponse> routingFunction() {
	UserRepository repository = new UserRepositorySample();
	UserHandler handler = new UserHandler(repository);
	
	return nest (
		path("/user"),
		nest(
			accept(MediaType.ALL),
			route(GET("/"), handler::getAllUsers)
		)
		.andRoute(GET("/{id}"), handler::getUser)
		.andRoute(POST("/").and(contentType(APPLICATION_JSON)), handler::createUser)
		.andRoute(PUT("/").and(contentType(APPLICATION_JSON)), handler::updateUser)
		.andRoute(DELETE("/{id}").and(contentType(APPLICATION_JSON)), handler::deleteUser)
	);
}
 
Example 9
@Bean
public RouterFunction<ServerResponse> testFunRouterFunction() {
	RouterFunction<ServerResponse> route = RouterFunctions.route(
			RequestPredicates.path("/testfun"),
			request -> ServerResponse.ok().body(BodyInserters.fromValue("hello")));
	return route;
}
 
Example 10
public void startReactorServer() throws InterruptedException {
	RouterFunction<ServerResponse> route = routingFunction();
	HttpHandler httpHandler = toHttpHandler(route);

	ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler);
	HttpServer server = HttpServer.create(HOST, PORT);
	server.newHandler(adapter).block();
}
 
Example 11
Source Project: Spring-5.0-Cookbook   Source File: HttpServerConfig.java    License: MIT License 5 votes vote down vote up
public ServletRegistrationBean routeServlet1(RouterFunction<?> routerFunction) throws Exception {
HttpHandler httpHandler = RouterFunctions.toHttpHandler(routerFunction );
ServletHttpHandlerAdapter servlet = new ServletHttpHandlerAdapter(httpHandler);

     ServletRegistrationBean registrationBean = new ServletRegistrationBean<>(servlet, "/flux" + "/*");
     registrationBean.setLoadOnStartup(1);
     registrationBean.setAsyncSupported(true);
     
 	System.out.println("starts server");		
     return registrationBean;
 }
 
Example 12
@Bean
public RouterFunction<?> userEndpoints() {
	return route(GET("/"),
			request -> ok().body(Mono
					.fromCallable(
							() -> entities.createEntityManager().find(Foo.class, 1L))
					.subscribeOn(Schedulers.elastic()), Foo.class));
}
 
Example 13
Source Project: opentracing-toolbox   Source File: StandardSpanDecoratorTest.java    License: MIT License 5 votes vote down vote up
@Bean
public RouterFunction<ServerResponse> routerFunction() {
    return RouterFunctions.route()
            .GET("/exception", request -> {
                throw new UnsupportedOperationException("Error");
            })
            .build();
}
 
Example 14
Source Project: Spring-5.0-Cookbook   Source File: HttpServerConfig.java    License: MIT License 5 votes vote down vote up
public ServletRegistrationBean routeServlet1(RouterFunction<?> routerFunction) throws Exception {
HttpHandler httpHandler = RouterFunctions.toHttpHandler(routerFunction );
ServletHttpHandlerAdapter servlet = new ServletHttpHandlerAdapter(httpHandler);

     ServletRegistrationBean registrationBean = new ServletRegistrationBean<>(servlet, "/flux" + "/*");
     registrationBean.setLoadOnStartup(1);
     registrationBean.setAsyncSupported(true);
     
 	System.out.println("starts server");		
     return registrationBean;
 }
 
Example 15
Source Project: spring-analysis-note   Source File: RouterFunctionMapping.java    License: MIT License 5 votes vote down vote up
private List<RouterFunction<?>> routerFunctions() {
	List<RouterFunction<?>> functions = obtainApplicationContext()
			.getBeanProvider(RouterFunction.class)
			.orderedStream()
			.map(router -> (RouterFunction<?>)router)
			.collect(Collectors.toList());
	return (!CollectionUtils.isEmpty(functions) ? functions : Collections.emptyList());
}
 
Example 16
/**
 * Creates a {@link RouterFunction} to register an endpoint, along with a custom
 * {@link ExplodingHandlerFilterFunction} that will throw an exception when the request contains a special header.
 * You wouldn't want the exploding filter in a real app.
 */
@Bean
public RouterFunction<ServerResponse> sampleRouterFunction(SampleController sampleController) {
    return RouterFunctions
        .route(GET(SAMPLE_FROM_ROUTER_FUNCTION_PATH), sampleController::getSampleModelRouterFunction)
        .filter(new ExplodingHandlerFilterFunction());
}
 
Example 17
Source Project: spring-analysis-note   Source File: RouterFunctionMappingTests.java    License: MIT License 5 votes vote down vote up
@Test
public void normal() {
	HandlerFunction<ServerResponse> handlerFunction = request -> ServerResponse.ok().build();
	RouterFunction<ServerResponse> routerFunction = request -> Mono.just(handlerFunction);

	RouterFunctionMapping mapping = new RouterFunctionMapping(routerFunction);
	mapping.setMessageReaders(this.codecConfigurer.getReaders());

	Mono<Object> result = mapping.getHandler(this.exchange);

	StepVerifier.create(result)
			.expectNext(handlerFunction)
			.expectComplete()
			.verify();
}
 
Example 18
Source Project: spring-5-examples   Source File: MovieFunctionalRoute.java    License: MIT License 5 votes vote down vote up
@Bean
RouterFunction<ServerResponse> movieRouterFunction(final MovieHandler handler) {

  return route(GET("/first"), handler::getFirstLike)
      .andRoute(GET("/all"), handler::searchAll)
      .andRoute(GET("/{id}"), handler::getMovie)
      .andRoute(GET("/events/{id}"), handler::eventStream)
      .andRoute(GET("/**"), handler::getMovies)
      ;
}
 
Example 19
Source Project: Spring-5.0-Projects   Source File: StudentRouterHandlerCombined.java    License: MIT License 5 votes vote down vote up
@Bean
RouterFunction<ServerResponse> returnStudentWithCombineFun(){
	
       HandlerFunction<ServerResponse> studentHandler = 
               serverRequest -> {
            	  int rollNo = getInt(serverRequest.pathVariable("rollNo"));
            	  return ServerResponse.ok().body(studentMongoRepository.findByRollNo(rollNo), Student.class);
            };
	
	RouterFunction<ServerResponse> studentResponse =
   		RouterFunctions.route(RequestPredicates.GET("/api/f/combine/getStudent/{rollNo}"),
   				studentHandler);
	
	return studentResponse;
   }
 
Example 20
Source Project: Spring-5.0-Cookbook   Source File: EmpReactFuncController.java    License: MIT License 5 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 21
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 22
Source Project: cloud-spanner-r2dbc   Source File: SpringDataR2dbcApp.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public RouterFunction<ServerResponse> indexRouter() {
  // Serve static index.html at root.
  return route(
      GET("/"),
      req -> ServerResponse.permanentRedirect(URI.create("/index.html")).build());
}
 
Example 23
@Bean
RouterFunction<ServerResponse> routes(
	ReservationRepository rr,
	Environment env) {
	return route(GET("/reservations"),
		request -> ok().body(rr.findAll(), Reservation.class))
		.andRoute(GET("/message"), request -> ok().syncBody(env.getProperty("message")));
}
 
Example 24
Source Project: tutorials   Source File: RootServlet.java    License: MIT License 5 votes vote down vote up
private static RouterFunction<?> routingFunction() {

        return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))).andRoute(POST("/login"), serverRequest -> serverRequest.body(toFormData())
            .map(MultiValueMap::toSingleValueMap)
            .map(formData -> {
                System.out.println("form data: " + formData.toString());
                if ("baeldung".equals(formData.get("user")) && "you_know_what_to_do".equals(formData.get("token"))) {
                    return ok().body(Mono.just("welcome back!"), String.class)
                        .block();
                }
                return ServerResponse.badRequest()
                    .build()
                    .block();
            }))
            .andRoute(POST("/upload"), serverRequest -> serverRequest.body(toDataBuffers())
                .collectList()
                .map(dataBuffers -> {
                    AtomicLong atomicLong = new AtomicLong(0);
                    dataBuffers.forEach(d -> atomicLong.addAndGet(d.asByteBuffer()
                        .array().length));
                    System.out.println("data length:" + atomicLong.get());
                    return ok().body(fromObject(atomicLong.toString()))
                        .block();
                }))
            .and(RouterFunctions.resources("/files/**", new ClassPathResource("files/")))
            .andNest(path("/actor"), route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest.bodyToMono(Actor.class)
                .doOnNext(actors::add)
                .then(ok().build())))
            .filter((request, next) -> {
                System.out.println("Before handler invocation: " + request.path());
                return next.handle(request);
            });

    }
 
Example 25
Source Project: springdoc-openapi   Source File: BookRouter.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
@RouterOperations({
		@RouterOperation(path = "/books", produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE} , beanClass = BookRepository.class, beanMethod = "findAll"),
		@RouterOperation(path = "/books", produces = {MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_XML_VALUE} , beanClass = BookRepository.class, beanMethod = "findAll"),
		@RouterOperation(path = "/books/{author}", beanClass = BookRepository.class, beanMethod = "findByAuthor",
				operation = @Operation(operationId = "findByAuthor"
						,parameters = { @Parameter(in = ParameterIn.PATH, name = "author")})) })
RouterFunction<?> routes(BookRepository br) {
	return
			route(GET("/books").and(accept(MediaType.APPLICATION_JSON)).and(accept(MediaType.APPLICATION_XML)), req -> ok().body(br.findAll(), Book.class))
					.and(route(GET("/books").and(accept(MediaType.APPLICATION_XML)).and(accept(MediaType.TEXT_PLAIN)), req -> ok().body(br.findAll(), Book.class)))
					.andRoute(GET("/books/{author}"), req -> ok().body(br.findByAuthor(req.pathVariable("author")), Book.class));
}
 
Example 26
Source Project: Spring-5.0-Cookbook   Source File: HttpServerConfig.java    License: MIT License 5 votes vote down vote up
public ServletRegistrationBean routeServlet1(RouterFunction<?> routerFunction) throws Exception {
HttpHandler httpHandler = RouterFunctions.toHttpHandler(routerFunction );
ServletHttpHandlerAdapter servlet = new ServletHttpHandlerAdapter(httpHandler);

     ServletRegistrationBean registrationBean = new ServletRegistrationBean<>(servlet, "/flux" + "/*");
     registrationBean.setLoadOnStartup(1);
     registrationBean.setAsyncSupported(true);
     
 	System.out.println("starts server");		
     return registrationBean;
 }
 
Example 27
Source Project: spring-cloud-sleuth   Source File: TraceWebFluxTests.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
RouterFunction<ServerResponse> route() {
	return RouterFunctions.route()
			.GET("/api/fn/{id}", serverRequest -> ServerResponse.ok()
					.bodyValue(serverRequest.pathVariable("id")))
			.build();
}
 
Example 28
@Bean
public RouterFunction<ServerResponse> routes(PostHandler postController) {
    return route(GET("/posts"), postController::all)
        .andRoute(POST("/posts"), postController::create)
        .andRoute(GET("/posts/{id}"), postController::get)
        .andRoute(PUT("/posts/{id}"), postController::update)
        .andRoute(DELETE("/posts/{id}"), postController::delete);
}
 
Example 29
Source Project: tutorials   Source File: StaticContentConfig.java    License: MIT License 5 votes vote down vote up
@Bean
public RouterFunction<ServerResponse> htmlRouter(@Value("classpath:/public/index.html") Resource html) {
    return route(
            GET("/"),
            request -> ok()
                    .contentType(MediaType.TEXT_HTML)
                    .syncBody(html)
    );
}
 
Example 30
Source Project: sofa-lookout   Source File: ExportManageServerRunner.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 暴露6200管理端口
 */
@Override
public void run(ApplicationArguments args) throws Exception {
    RouterFunction manageRouterFunction = RouterFunctions
            .route(RequestPredicates.GET("/ok"), req -> {
                return ServerResponse.ok()
                        .syncBody("online");
            })
            .andRoute(RequestPredicates.GET("/cmd/{line}"), request -> {
                String pathVar = request.pathVariable("line");
                try {
                    if ("down".equals(pathVar)) {
                        refuseRequestService.setRefuseRequest(true);
                    } else if ("up".equals(pathVar)) {
                        refuseRequestService.setRefuseRequest(false);
                    }
                    return ServerResponse.ok().body(Mono.just("ok"), String.class);
                } catch (Throwable e) {
                    LOGGER.error("{} request err!", pathVar, e);
                    return ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
                }
            });

    HttpHandler handler = RouterFunctions.toHttpHandler(manageRouterFunction);
    int managePort = serverPort - 1000;

    ReactorHttpHandlerAdapter inboundAdapter = new ReactorHttpHandlerAdapter(handler);

    // manage port
    HttpServer.create().port(managePort).handle(inboundAdapter).bind();
    // HttpServer.create(managePort).newHandler(inboundAdapter).block();

    LOGGER.info("management services run on port:{}", managePort);
}