Java Code Examples for org.springframework.web.servlet.function.RouterFunction

The following examples show how to use org.springframework.web.servlet.function.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: spring-analysis-note   Source File: RouterFunctionMapping.java    License: MIT License 6 votes vote down vote up
/**
 * Detect a all {@linkplain RouterFunction router functions} in the
 * current application context.
 */
@SuppressWarnings({"unchecked", "rawtypes"})
private void initRouterFunction() {
	ApplicationContext applicationContext = obtainApplicationContext();
	Map<String, RouterFunction> beans =
			(this.detectHandlerFunctionsInAncestorContexts ?
					BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, RouterFunction.class) :
					applicationContext.getBeansOfType(RouterFunction.class));

	List<RouterFunction> routerFunctions = new ArrayList<>(beans.values());
	if (!CollectionUtils.isEmpty(routerFunctions) && logger.isInfoEnabled()) {
		routerFunctions.forEach(routerFunction -> logger.info("Mapped " + routerFunction));
	}
	this.routerFunction = routerFunctions.stream()
			.reduce(RouterFunction::andOther)
			.orElse(null);
}
 
Example 2
Source Project: spring-fu   Source File: WebMvcServerDsl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void initialize(GenericApplicationContext context) {
	super.initialize(context);
	this.dsl.accept(this);
	context.registerBean(BeanDefinitionReaderUtils.uniqueBeanName(RouterFunction.class.getName(), context), RouterFunction.class, () ->
		RouterFunctions.route().resources("/**", new ClassPathResource("static/")).build()
	);
	serverProperties.setPort(port);
	serverProperties.getServlet().setRegisterDefaultServlet(false);
	if (!convertersConfigured) {
		new StringConverterInitializer().initialize(context);
		new ResourceConverterInitializer().initialize(context);
	}
	if (context.containsBeanDefinition("webHandler")) {
		throw new IllegalStateException("Only one webFlux per application is supported");
	}
	new ServletWebServerInitializer(serverProperties, webMvcProperties, resourceProperties).initialize(context);
}
 
Example 3
Source Project: tutorials   Source File: SpringBootMvcFnApplication.java    License: MIT License 6 votes vote down vote up
@Bean
RouterFunction<ServerResponse> allApplicationRoutes(ProductController pc, ProductService ps) {
    return route().add(pc.remainingProductRoutes(ps))
        .before(req -> {
            LOG.info("Found a route which matches " + req.uri()
                .getPath());
            return req;
        })
        .after((req, res) -> {
            if (res.statusCode() == HttpStatus.OK) {
                LOG.info("Finished processing request " + req.uri()
                    .getPath());
            } else {
                LOG.info("There was an error while processing request" + req.uri());
            }
            return res;
        })
        .onError(Throwable.class, (e, res) -> {
            LOG.error("Fatal exception has occurred", e);
            return status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        })
        .build()
        .and(route(RequestPredicates.all(), req -> notFound().build()));
}
 
Example 4
Source Project: springdoc-openapi   Source File: RouterFunctionProvider.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Gets web mvc router function paths.
 *
 * @return the web mvc router function paths
 */
protected Optional<Map<String, AbstractRouterFunctionVisitor>> getWebMvcRouterFunctionPaths() {
	Map<String, RouterFunction> routerBeans = applicationContext.getBeansOfType(RouterFunction.class);
	if (CollectionUtils.isEmpty(routerBeans))
		return Optional.empty();
	Map<String, AbstractRouterFunctionVisitor> routerFunctionVisitorMap = new HashMap<>();
	for (Map.Entry<String, RouterFunction> entry : routerBeans.entrySet()) {
		RouterFunction routerFunction = entry.getValue();
		RouterFunctionVisitor routerFunctionVisitor = new RouterFunctionVisitor();
		routerFunction.accept(routerFunctionVisitor);
		routerFunctionVisitorMap.put(entry.getKey(), routerFunctionVisitor);
	}
	return Optional.of(routerFunctionVisitorMap);
}
 
Example 5
Source Project: springdoc-openapi   Source File: HelloApplication.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
@RouterOperations({ @RouterOperation(path = "/people", method = RequestMethod.GET, beanClass = PersonService.class, beanMethod = "all"),
		@RouterOperation(path = "/people/{id}", beanClass = PersonService.class, beanMethod = "byId"),
		@RouterOperation(path = "/people", method = RequestMethod.POST, beanClass = PersonService.class, beanMethod = "save") })
RouterFunction<ServerResponse> routes(PersonHandler ph) {
	String root = "";
	return route()
			.GET(root + "/people", ph::handleGetAllPeople)
			.GET(root + "/people/{id}", ph::handleGetPersonById)
			.POST(root + "/people", ph::handlePostPerson)
			.filter((serverRequest, handlerFunction) -> {
				return handlerFunction.handle(serverRequest);
			})
			.build();
}
 
Example 6
Source Project: spring-fu   Source File: WebMvcServerDsl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Configure routes via {@link RouterFunctions.Builder}.
 * @see org.springframework.fu.jafu.BeanDefinitionDsl#bean(Class, BeanDefinitionCustomizer...)
 */
public WebMvcServerDsl router(Consumer<RouterFunctions.Builder> routerDsl) {
	RouterFunctions.Builder builder = RouterFunctions.route();
	context.registerBean(BeanDefinitionReaderUtils.uniqueBeanName(RouterFunction.class.getName(), context), RouterFunction.class, () -> {
		routerDsl.accept(builder);
		return builder.build();
	});
	return this;
}
 
Example 7
Source Project: tutorials   Source File: ProductController.java    License: MIT License 5 votes vote down vote up
public RouterFunction<ServerResponse> productSearch(ProductService ps) {
    return route().nest(RequestPredicates.path("/product"), builder -> {
        builder.GET("/name/{name}", req -> ok().body(ps.findByName(req.pathVariable("name"))))
            .GET("/id/{id}", req -> ok().body(ps.findById(Integer.parseInt(req.pathVariable("id")))));
    })
        .onError(ProductService.ItemNotFoundException.class, (e, req) -> EntityResponse.fromObject(new Error(e.getMessage()))
            .status(HttpStatus.NOT_FOUND)
            .build())
        .build();
}
 
Example 8
Source Project: tutorials   Source File: ProductController.java    License: MIT License 5 votes vote down vote up
public RouterFunction<ServerResponse> adminFunctions(ProductService ps) {
    return route().POST("/product", req -> ok().body(ps.save(req.body(Product.class))))
        .filter((req, next) -> authenticate(req) ? next.handle(req) : status(HttpStatus.UNAUTHORIZED).build())
        .onError(IllegalArgumentException.class, (e, req) -> EntityResponse.fromObject(new Error(e.getMessage()))
            .status(HttpStatus.BAD_REQUEST)
            .build())
        .build();
}
 
Example 9
Source Project: springdoc-openapi   Source File: RouterFunctionProvider.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void unknown(RouterFunction<?> routerFunction) {
	// Not yet needed
}
 
Example 10
Source Project: spring-graalvm-native   Source File: SampleApplication.java    License: Apache License 2.0 4 votes vote down vote up
@Bean
public RouterFunction<?> userEndpoints() {
	return route(GET("/"), request -> ok().body(findOne()));
}
 
Example 11
Source Project: spring-graalvm-native   Source File: SampleApplication.java    License: Apache License 2.0 4 votes vote down vote up
@Bean
public RouterFunction<?> userEndpoints(Finder<Foo> entities) {
	return route(GET("/"), request -> ok().body(entities.find(1L)));
}
 
Example 12
Source Project: spring-graalvm-native   Source File: SampleApplication.java    License: Apache License 2.0 4 votes vote down vote up
@Bean
public RouterFunction<?> userEndpoints() {
	return route().GET("/", request ->
			ok().body(manager.find(Foo.class, 1L))).build();
}
 
Example 13
Source Project: tutorials   Source File: ProductController.java    License: MIT License 4 votes vote down vote up
public RouterFunction<ServerResponse> productListing(ProductService ps) {
    return route().GET("/product", req -> ok().body(ps.findAll()))
        .build();
}
 
Example 14
Source Project: tutorials   Source File: ProductController.java    License: MIT License 4 votes vote down vote up
public RouterFunction<ServerResponse> remainingProductRoutes(ProductService ps) {
    return route().add(productSearch(ps))
        .add(adminFunctions(ps))
        .build();
}
 
Example 15
Source Project: tutorials   Source File: SpringBootMvcFnApplication.java    License: MIT License 4 votes vote down vote up
@Bean
RouterFunction<ServerResponse> productListing(ProductController pc, ProductService ps) {
    return pc.productListing(ps);
}
 
Example 16
Source Project: spring-analysis-note   Source File: RouterFunctionMapping.java    License: MIT License 2 votes vote down vote up
/**
 * Create a {@code RouterFunctionMapping} with the given {@link RouterFunction}.
 * <p>If this constructor is used, no application context detection will occur.
 * @param routerFunction the router function to use for mapping
 */
public RouterFunctionMapping(RouterFunction<?> routerFunction) {
	this.routerFunction = routerFunction;
}
 
Example 17
Source Project: spring-analysis-note   Source File: RouterFunctionMapping.java    License: MIT License 2 votes vote down vote up
/**
 * Set the router function to map to.
 * <p>If this property is used, no application context detection will occur.
 */
public void setRouterFunction(@Nullable RouterFunction<?> routerFunction) {
	this.routerFunction = routerFunction;
}
 
Example 18
Source Project: spring-analysis-note   Source File: RouterFunctionMapping.java    License: MIT License 2 votes vote down vote up
/**
 * Return the configured {@link RouterFunction}.
 * <p><strong>Note:</strong> When router functions are detected from the
 * ApplicationContext, this method may return {@code null} if invoked
 * prior to {@link #afterPropertiesSet()}.
 * @return the router function or {@code null}
 */
@Nullable
public RouterFunction<?> getRouterFunction() {
	return this.routerFunction;
}