All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.springframework.http.server.reactive.ContextPathCompositeHandler Maven / Gradle / Ivy

There is a newer version: 6.1.6
Show newest version

package org.springframework.http.server.reactive;

import java.util.LinkedHashMap;
import java.util.Map;

import reactor.core.publisher.Mono;

import org.springframework.http.HttpStatus;
import org.springframework.util.Assert;

/**
 * {@code HttpHandler} delegating requests to one of several {@code HttpHandler}'s
 * based on simple, prefix-based mappings.
 *
 * 

This is intended as a coarse-grained mechanism for delegating requests to * one of several applications -- each represented by an {@code HttpHandler}, with * the application "context path" (the prefix-based mapping) exposed via * {@link ServerHttpRequest#getPath()}. * * @author Rossen Stoyanchev * @since 5.0 */ public class ContextPathCompositeHandler implements HttpHandler { private final Map handlerMap; public ContextPathCompositeHandler(Map handlerMap) { Assert.notEmpty(handlerMap, "Handler map must not be empty"); this.handlerMap = initHandlers(handlerMap); } private static Map initHandlers(Map map) { map.keySet().forEach(ContextPathCompositeHandler::assertValidContextPath); return new LinkedHashMap<>(map); } private static void assertValidContextPath(String contextPath) { Assert.hasText(contextPath, "Context path must not be empty"); if (contextPath.equals("/")) { return; } Assert.isTrue(contextPath.startsWith("/"), "Context path must begin with '/'"); Assert.isTrue(!contextPath.endsWith("/"), "Context path must not end with '/'"); } @Override public Mono handle(ServerHttpRequest request, ServerHttpResponse response) { // Remove underlying context path first (e.g. Servlet container) String path = request.getPath().pathWithinApplication().value(); return this.handlerMap.entrySet().stream() .filter(entry -> path.startsWith(entry.getKey())) .findFirst() .map(entry -> { String contextPath = request.getPath().contextPath().value() + entry.getKey(); ServerHttpRequest newRequest = request.mutate().contextPath(contextPath).build(); return entry.getValue().handle(newRequest, response); }) .orElseGet(() -> { response.setStatusCode(HttpStatus.NOT_FOUND); response.setComplete(); return Mono.empty(); }); } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy