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

The following examples show how to use org.springframework.web.reactive.function.server.RouterFunction. 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: Router.java    From influx-proxy with 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 File: Server.java    From Building-RESTful-Web-Services-with-Spring-5-Second-Edition with MIT License 6 votes vote down vote up
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 #3
Source File: App.java    From spring-5-examples with 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 #4
Source File: EmployeeFunctionalConfig.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
@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 #5
Source File: DemoApplication.java    From Hands-On-Reactive-Programming-in-Spring-5 with MIT License 6 votes vote down vote up
@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 #6
Source File: EmployeeFunctionalConfig.java    From tutorials with 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 #7
Source File: FileItemsRoutes.java    From streaming-file-server with 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 #8
Source File: FunctionalSpringBootApplication.java    From tutorials with 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 #9
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 #10
Source File: HttpIT.java    From vertx-spring-boot with Apache License 2.0 5 votes vote down vote up
@Bean
public RouterFunction<ServerResponse> upperCookieRouter() {
    return route()
        .GET("/", request -> {
            String text = request.cookies()
                .getFirst("text")
                .getValue()
                .toUpperCase();
            ResponseCookie cookie = ResponseCookie.from("text", text).build();

            return noContent().cookie(cookie).build();
        })
        .build();
}
 
Example #11
Source File: HttpServerConfig.java    From Spring-5.0-Cookbook with 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
Source File: ReservationClientApplication.java    From bootiful-reactive-microservices with Apache License 2.0 5 votes vote down vote up
@Bean
	RouterFunction<ServerResponse> routes(ReservationClient client) {
		return route(GET("/reservations/names"), serverRequest -> {

			Flux<String> names = client
				.getAllReservations()
				.map(Reservation::getName);

			Publisher<String> cb = HystrixCommands
				.from(names)
				.eager()
				.commandName("names")
				.fallback(Flux.just("EEK!"))
				.build();


		/*	// hedging
			WebClient wc = null; ///
			DiscoveryClient dc = null; ///
			List<ServiceInstance> instances = dc.getInstances("foo-service");
			if (instances.size() >= 3) {
				List<ServiceInstance> serviceInstances = instances.subList(0, 3);

				Flux<Reservation> callThreeServicesAtTheSameTime = Flux
					.fromStream(serviceInstances.stream())
					.map(si -> si.getHost() + ':' + si.getPort())
					.flatMap(uri -> wc.get().uri(uri).retrieve().bodyToFlux(Reservation.class));

				Flux<Reservation> first = Flux.first(callThreeServicesAtTheSameTime);

			}
*/
			return ServerResponse.ok().body(cb, String.class);
		});
	}
 
Example #13
Source File: StudentRouterHandlerCombined.java    From Spring-5.0-Projects with MIT License 5 votes vote down vote up
@Bean
RouterFunction<ServerResponse> returnAllStudentWithCombineFun(){
	
       HandlerFunction<ServerResponse> studentHandler = 
               serverRequest -> 
            	  ServerResponse.ok().body(studentMongoRepository.findAll(), Student.class);
	
	RouterFunction<ServerResponse> studentResponse =
   		RouterFunctions.route(RequestPredicates.GET("/api/f/combine/getAllStudent"),
   				studentHandler);
	
	return studentResponse;
   }
 
Example #14
Source File: App.java    From spring-5-examples with MIT License 5 votes vote down vote up
@Bean
RouterFunction<ServerResponse> routes(Handlers handlers) {
  return nest(path("/api/v1"), route()
      .GET("/hey", handlers::hey)
      .GET("/hoy", handlers::hoy)
      .GET("/collect", handlers::collect)
      .build())
      .andRoute(path("/**"), handlers::falback);
}
 
Example #15
Source File: FirestoreSampleApplication.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Bean
public RouterFunction<ServerResponse> indexRouter(
		@Value("classpath:/static/index.html") final Resource indexHtml) {

	// Serve static index.html at root, for convenient message publishing.
	return route(
			GET("/"),
			request -> ok().contentType(MediaType.TEXT_HTML).bodyValue(indexHtml));
}
 
Example #16
Source File: EmployeeFunctionalConfig.java    From tutorials with MIT License 5 votes vote down vote up
@Bean
RouterFunction<ServerResponse> updateEmployeeRoute() {
  return route(POST("/employees/update"), 
    req -> req.body(toMono(Employee.class))
              .doOnNext(employeeRepository()::updateEmployee)
              .then(ok().build()));
}
 
Example #17
Source File: ReactiveWebServerAutoConfigurationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Bean
public RouterFunction<ServerResponse> route(TestHandler testHandler) {
    return RouterFunctions
            .route(RequestPredicates.GET("/route")
                                    .and(RequestPredicates.accept(MediaType.TEXT_PLAIN)),
                   testHandler::route)
            .andRoute(RequestPredicates.POST("/route2")
                                       .and(RequestPredicates.contentType(MediaType.APPLICATION_JSON)),
                      testHandler::route2)
            .andRoute(RequestPredicates.HEAD("/route3"), request -> ServerResponse.ok().build());
}
 
Example #18
Source File: BootWebfluxApplication.java    From springfox-demos with Apache License 2.0 5 votes vote down vote up
@Bean
public RouterFunction<ServerResponse> route(GreetingHandler greetingHandler) {
  return RouterFunctions
      .route(RequestPredicates.GET("/hello")
              .and(RequestPredicates.accept(MediaType.TEXT_PLAIN)),
          greetingHandler::hello);
}
 
Example #19
Source File: BookRouter.java    From springdoc-openapi with 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 #20
Source File: HttpIT.java    From vertx-spring-boot with Apache License 2.0 5 votes vote down vote up
@Bean
public RouterFunction<ServerResponse> upperHeaderRouter() {
    return route()
        .GET("/", request -> {
            String text = request.headers()
                .header("text")
                .get(0)
                .toUpperCase();

            return noContent().header("text", text).build();
        })
        .build();
}
 
Example #21
Source File: ReactorAutoConfigurationInitializer.java    From spring-init with Apache License 2.0 5 votes vote down vote up
private void registerEndpoint(GenericApplicationContext context) {
	context.registerBean(StringConverter.class,
			() -> new BasicStringConverter(context.getBean(FunctionInspector.class), context.getBeanFactory()));
	context.registerBean(RequestProcessor.class,
			() -> new RequestProcessor(context.getBean(FunctionInspector.class),
					context.getBean(FunctionCatalog.class), context.getBeanProvider(JsonMapper.class),
					context.getBean(StringConverter.class), context.getBeanProvider(ServerCodecConfigurer.class)));
	context.registerBean(PublicFunctionEndpointFactory.class,
			() -> new PublicFunctionEndpointFactory(context.getBean(FunctionCatalog.class),
					context.getBean(FunctionInspector.class), context.getBean(RequestProcessor.class),
					context.getEnvironment()));
	context.registerBean(RouterFunction.class,
			() -> context.getBean(PublicFunctionEndpointFactory.class).functionEndpoints());
}
 
Example #22
Source File: RouterFunctionMappingTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void noMatch() {
	RouterFunction<ServerResponse> routerFunction = request -> Mono.empty();
	RouterFunctionMapping mapping = new RouterFunctionMapping(routerFunction);
	mapping.setMessageReaders(this.codecConfigurer.getReaders());

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

	StepVerifier.create(result)
			.expectComplete()
			.verify();
}
 
Example #23
Source File: MovieFunctionalRoute.java    From spring-5-examples with 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 #24
Source File: HttpServerConfig.java    From Spring-5.0-Cookbook with 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 #25
Source File: ReactiveControllers.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("/saveDept"), dataHandler::saveDepartmentMono)
			.andRoute(GET("/countDepts"), dataHandler::countDepts);
	
}
 
Example #26
Source File: ExportManageServerRunner.java    From sofa-lookout with 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);
}
 
Example #27
Source File: StaticContentConfig.java    From tutorials with 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 #28
Source File: TraceWebFluxTests.java    From spring-cloud-sleuth with 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 #29
Source File: HttpServerConfig.java    From Spring-5.0-Cookbook with 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 #30
Source File: DemoApplication.java    From spring-reactive-sample with GNU General Public License v3.0 5 votes vote down vote up
@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);
}