Java Code Examples for org.springframework.web.util.pattern.PathPattern

The following examples show how to use org.springframework.web.util.pattern.PathPattern. 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: ResourceUrlProvider.java    License: MIT License 6 votes vote down vote up
private Mono<String> resolveResourceUrl(ServerWebExchange exchange, PathContainer lookupPath) {
	return this.handlerMap.entrySet().stream()
			.filter(entry -> entry.getKey().matches(lookupPath))
			.min((entry1, entry2) ->
					PathPattern.SPECIFICITY_COMPARATOR.compare(entry1.getKey(), entry2.getKey()))
			.map(entry -> {
				PathContainer path = entry.getKey().extractPathWithinPattern(lookupPath);
				int endIndex = lookupPath.elements().size() - path.elements().size();
				PathContainer mapping = lookupPath.subPath(0, endIndex);
				ResourceWebHandler handler = entry.getValue();
				List<ResourceResolver> resolvers = handler.getResourceResolvers();
				ResourceResolverChain chain = new DefaultResourceResolverChain(resolvers);
				return chain.resolveUrlPath(path.value(), handler.getLocations())
						.map(resolvedPath -> mapping.value() + resolvedPath);
			})
			.orElseGet(() ->{
				if (logger.isTraceEnabled()) {
					logger.trace(exchange.getLogPrefix() + "No match for \"" + lookupPath + "\"");
				}
				return Mono.empty();
			});
}
 
Example 2
Source Project: spring-analysis-note   Source File: RouterFunctionMapping.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void setAttributes(Map<String, Object> attributes, ServerRequest serverRequest,
		HandlerFunction<?> handlerFunction) {

	attributes.put(RouterFunctions.REQUEST_ATTRIBUTE, serverRequest);
	attributes.put(BEST_MATCHING_HANDLER_ATTRIBUTE, handlerFunction);

	PathPattern matchingPattern =
			(PathPattern) attributes.get(RouterFunctions.MATCHING_PATTERN_ATTRIBUTE);
	if (matchingPattern != null) {
		attributes.put(BEST_MATCHING_PATTERN_ATTRIBUTE, matchingPattern);
	}
	Map<String, String> uriVariables =
			(Map<String, String>) attributes
					.get(RouterFunctions.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
	if (uriVariables != null) {
		attributes.put(URI_TEMPLATE_VARIABLES_ATTRIBUTE, uriVariables);
	}
}
 
Example 3
Source Project: spring-analysis-note   Source File: AbstractUrlHandlerMapping.java    License: MIT License 6 votes vote down vote up
/**
 * Look up a handler instance for the given URL lookup path.
 * <p>Supports direct matches, e.g. a registered "/test" matches "/test",
 * and various path pattern matches, e.g. a registered "/t*" matches
 * both "/test" and "/team". For details, see the PathPattern class.
 * @param lookupPath the URL the handler is mapped to
 * @param exchange the current exchange
 * @return the associated handler instance, or {@code null} if not found
 * @see org.springframework.web.util.pattern.PathPattern
 */
@Nullable
protected Object lookupHandler(PathContainer lookupPath, ServerWebExchange exchange) throws Exception {

	List<PathPattern> matches = this.handlerMap.keySet().stream()
			.filter(key -> key.matches(lookupPath))
			.collect(Collectors.toList());

	if (matches.isEmpty()) {
		return null;
	}

	if (matches.size() > 1) {
		matches.sort(PathPattern.SPECIFICITY_COMPARATOR);
		if (logger.isTraceEnabled()) {
			logger.debug(exchange.getLogPrefix() + "Matching patterns " + matches);
		}
	}

	PathPattern pattern = matches.get(0);
	PathContainer pathWithinMapping = pattern.extractPathWithinPattern(lookupPath);
	return handleMatch(this.handlerMap.get(pattern), pattern, pathWithinMapping, exchange);
}
 
Example 4
Source Project: spring-analysis-note   Source File: AbstractUrlHandlerMapping.java    License: MIT License 6 votes vote down vote up
private Object handleMatch(Object handler, PathPattern bestMatch, PathContainer pathWithinMapping,
		ServerWebExchange exchange) {

	// Bean name or resolved handler?
	if (handler instanceof String) {
		String handlerName = (String) handler;
		handler = obtainApplicationContext().getBean(handlerName);
	}

	validateHandler(handler, exchange);

	exchange.getAttributes().put(BEST_MATCHING_HANDLER_ATTRIBUTE, handler);
	exchange.getAttributes().put(BEST_MATCHING_PATTERN_ATTRIBUTE, bestMatch);
	exchange.getAttributes().put(PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, pathWithinMapping);

	return handler;
}
 
Example 5
@Override
public Object afterMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes,
                          Object ret) throws Throwable {
    ServerWebExchange exchange = (ServerWebExchange) allArguments[0];
    AbstractSpan span = (AbstractSpan) objInst.getSkyWalkingDynamicField();

    return ((Mono) ret).doFinally(s -> {
        try {
            Object pathPattern = exchange.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
            if (pathPattern != null) {
                span.setOperationName(((PathPattern) pathPattern).getPatternString());
            }
            HttpStatus httpStatus = exchange.getResponse().getStatusCode();
            // fix webflux-2.0.0-2.1.0 version have bug. httpStatus is null. not support
            if (httpStatus != null) {
                Tags.STATUS_CODE.set(span, Integer.toString(httpStatus.value()));
                if (httpStatus.isError()) {
                    span.errorOccurred();
                }
            }
        } finally {
            span.asyncFinish();
        }
    });

}
 
Example 6
Source Project: spring-analysis-note   Source File: PatternsRequestCondition.java    License: MIT License 6 votes vote down vote up
/**
 * Returns a new instance with URL patterns from the current instance ("this") and
 * the "other" instance as follows:
 * <ul>
 * <li>If there are patterns in both instances, combine the patterns in "this" with
 * the patterns in "other" using {@link PathPattern#combine(PathPattern)}.
 * <li>If only one instance has patterns, use them.
 * <li>If neither instance has patterns, use an empty String (i.e. "").
 * </ul>
 */
@Override
public PatternsRequestCondition combine(PatternsRequestCondition other) {
	SortedSet<PathPattern> combined;
	if (!this.patterns.isEmpty() && !other.patterns.isEmpty()) {
		combined = new TreeSet<>();
		for (PathPattern pattern1 : this.patterns) {
			for (PathPattern pattern2 : other.patterns) {
				combined.add(pattern1.combine(pattern2));
			}
		}
	}
	else if (!this.patterns.isEmpty()) {
		combined = this.patterns;
	}
	else if (!other.patterns.isEmpty()) {
		combined = other.patterns;
	}
	else {
		combined = EMPTY_PATTERNS;
	}
	return new PatternsRequestCondition(combined);
}
 
Example 7
Source Project: spring-analysis-note   Source File: PatternsRequestCondition.java    License: MIT License 6 votes vote down vote up
/**
 * Compare the two conditions based on the URL patterns they contain.
 * Patterns are compared one at a time, from top to bottom. If all compared
 * patterns match equally, but one instance has more patterns, it is
 * considered a closer match.
 * <p>It is assumed that both instances have been obtained via
 * {@link #getMatchingCondition(ServerWebExchange)} to ensure they
 * contain only patterns that match the request and are sorted with
 * the best matches on top.
 */
@Override
public int compareTo(PatternsRequestCondition other, ServerWebExchange exchange) {
	Iterator<PathPattern> iterator = this.patterns.iterator();
	Iterator<PathPattern> iteratorOther = other.getPatterns().iterator();
	while (iterator.hasNext() && iteratorOther.hasNext()) {
		int result = PathPattern.SPECIFICITY_COMPARATOR.compare(iterator.next(), iteratorOther.next());
		if (result != 0) {
			return result;
		}
	}
	if (iterator.hasNext()) {
		return -1;
	}
	else if (iteratorOther.hasNext()) {
		return 1;
	}
	else {
		return 0;
	}
}
 
Example 8
Source Project: spring-analysis-note   Source File: NestedRouteIntegrationTests.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
public Mono<ServerResponse> variables(ServerRequest request) {
	Map<String, String> pathVariables = request.pathVariables();
	Map<String, String> attributePathVariables =
			(Map<String, String>) request.attributes().get(RouterFunctions.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
	assertTrue( (pathVariables.equals(attributePathVariables))
			|| (pathVariables.isEmpty() && (attributePathVariables == null)));

	PathPattern pathPattern = matchingPattern(request);
	String pattern = pathPattern != null ? pathPattern.getPatternString() : "";
	Flux<String> responseBody;
	if (!pattern.isEmpty()) {
		responseBody = Flux.just(pattern, "\n", pathVariables.toString());
	}
	else {
		responseBody = Flux.just(pathVariables.toString());
	}
	return ServerResponse.ok().body(responseBody, String.class);
}
 
Example 9
private RequestMappingInfo assertComposedAnnotationMapping(String methodName, String path,
		RequestMethod requestMethod) throws Exception {

	Class<?> clazz = ComposedAnnotationController.class;
	Method method = ClassUtils.getMethod(clazz, methodName, (Class<?>[]) null);
	RequestMappingInfo info = this.handlerMapping.getMappingForMethod(method, clazz);

	assertNotNull(info);

	Set<PathPattern> paths = info.getPatternsCondition().getPatterns();
	assertEquals(1, paths.size());
	assertEquals(path, paths.iterator().next().getPatternString());

	Set<RequestMethod> methods = info.getMethodsCondition().getMethods();
	assertEquals(1, methods.size());
	assertEquals(requestMethod, methods.iterator().next());

	return info;
}
 
Example 10
Source Project: springdoc-openapi   Source File: OpenApiResource.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Calculate path.
 *
 * @param restControllers the rest controllers
 * @param map the map
 */
protected void calculatePath(Map<String, Object> restControllers, Map<RequestMappingInfo, HandlerMethod> map) {
	for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : map.entrySet()) {
		RequestMappingInfo requestMappingInfo = entry.getKey();
		HandlerMethod handlerMethod = entry.getValue();
		PatternsRequestCondition patternsRequestCondition = requestMappingInfo.getPatternsCondition();
		Set<PathPattern> patterns = patternsRequestCondition.getPatterns();
		for (PathPattern pathPattern : patterns) {
			String operationPath = pathPattern.getPatternString();
			Map<String, String> regexMap = new LinkedHashMap<>();
			operationPath = PathUtils.parsePath(operationPath, regexMap);
			if (operationPath.startsWith(DEFAULT_PATH_SEPARATOR)
					&& (restControllers.containsKey(handlerMethod.getBean().toString()) || actuatorProvider.isPresent())
					&& isPackageToScan(handlerMethod.getBeanType().getPackage()) && isPathToMatch(operationPath)) {
				Set<RequestMethod> requestMethods = requestMappingInfo.getMethodsCondition().getMethods();
				// default allowed requestmethods
				if (requestMethods.isEmpty())
					requestMethods = this.getDefaultAllowedHttpMethods();
				calculatePath(handlerMethod, operationPath, requestMethods);
			}
		}
	}
}
 
Example 11
Source Project: java-technology-stack   Source File: ResourceUrlProvider.java    License: MIT License 6 votes vote down vote up
private Mono<String> resolveResourceUrl(ServerWebExchange exchange, PathContainer lookupPath) {
	return this.handlerMap.entrySet().stream()
			.filter(entry -> entry.getKey().matches(lookupPath))
			.min((entry1, entry2) ->
					PathPattern.SPECIFICITY_COMPARATOR.compare(entry1.getKey(), entry2.getKey()))
			.map(entry -> {
				PathContainer path = entry.getKey().extractPathWithinPattern(lookupPath);
				int endIndex = lookupPath.elements().size() - path.elements().size();
				PathContainer mapping = lookupPath.subPath(0, endIndex);
				ResourceWebHandler handler = entry.getValue();
				List<ResourceResolver> resolvers = handler.getResourceResolvers();
				ResourceResolverChain chain = new DefaultResourceResolverChain(resolvers);
				return chain.resolveUrlPath(path.value(), handler.getLocations())
						.map(resolvedPath -> mapping.value() + resolvedPath);
			})
			.orElseGet(() ->{
				if (logger.isTraceEnabled()) {
					logger.trace(exchange.getLogPrefix() + "No match for \"" + lookupPath + "\"");
				}
				return Mono.empty();
			});
}
 
Example 12
Source Project: java-technology-stack   Source File: RouterFunctionMapping.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void setAttributes(Map<String, Object> attributes, ServerRequest serverRequest,
		HandlerFunction<?> handlerFunction) {

	attributes.put(RouterFunctions.REQUEST_ATTRIBUTE, serverRequest);
	attributes.put(BEST_MATCHING_HANDLER_ATTRIBUTE, handlerFunction);

	PathPattern matchingPattern =
			(PathPattern) attributes.get(RouterFunctions.MATCHING_PATTERN_ATTRIBUTE);
	if (matchingPattern != null) {
		attributes.put(BEST_MATCHING_PATTERN_ATTRIBUTE, matchingPattern);
	}
	Map<String, String> uriVariables =
			(Map<String, String>) attributes
					.get(RouterFunctions.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
	if (uriVariables != null) {
		attributes.put(URI_TEMPLATE_VARIABLES_ATTRIBUTE, uriVariables);
	}
}
 
Example 13
Source Project: java-technology-stack   Source File: AbstractUrlHandlerMapping.java    License: MIT License 6 votes vote down vote up
/**
 * Look up a handler instance for the given URL lookup path.
 * <p>Supports direct matches, e.g. a registered "/test" matches "/test",
 * and various path pattern matches, e.g. a registered "/t*" matches
 * both "/test" and "/team". For details, see the PathPattern class.
 * @param lookupPath the URL the handler is mapped to
 * @param exchange the current exchange
 * @return the associated handler instance, or {@code null} if not found
 * @see org.springframework.web.util.pattern.PathPattern
 */
@Nullable
protected Object lookupHandler(PathContainer lookupPath, ServerWebExchange exchange) throws Exception {

	List<PathPattern> matches = this.handlerMap.keySet().stream()
			.filter(key -> key.matches(lookupPath))
			.collect(Collectors.toList());

	if (matches.isEmpty()) {
		return null;
	}

	if (matches.size() > 1) {
		matches.sort(PathPattern.SPECIFICITY_COMPARATOR);
		if (logger.isTraceEnabled()) {
			logger.debug(exchange.getLogPrefix() + "Matching patterns " + matches);
		}
	}

	PathPattern pattern = matches.get(0);
	PathContainer pathWithinMapping = pattern.extractPathWithinPattern(lookupPath);
	return handleMatch(this.handlerMap.get(pattern), pattern, pathWithinMapping, exchange);
}
 
Example 14
Source Project: java-technology-stack   Source File: AbstractUrlHandlerMapping.java    License: MIT License 6 votes vote down vote up
private Object handleMatch(Object handler, PathPattern bestMatch, PathContainer pathWithinMapping,
		ServerWebExchange exchange) {

	// Bean name or resolved handler?
	if (handler instanceof String) {
		String handlerName = (String) handler;
		handler = obtainApplicationContext().getBean(handlerName);
	}

	validateHandler(handler, exchange);

	exchange.getAttributes().put(BEST_MATCHING_HANDLER_ATTRIBUTE, handler);
	exchange.getAttributes().put(BEST_MATCHING_PATTERN_ATTRIBUTE, bestMatch);
	exchange.getAttributes().put(PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, pathWithinMapping);

	return handler;
}
 
Example 15
Source Project: java-technology-stack   Source File: PatternsRequestCondition.java    License: MIT License 6 votes vote down vote up
/**
 * Returns a new instance with URL patterns from the current instance ("this") and
 * the "other" instance as follows:
 * <ul>
 * <li>If there are patterns in both instances, combine the patterns in "this" with
 * the patterns in "other" using {@link PathPattern#combine(PathPattern)}.
 * <li>If only one instance has patterns, use them.
 * <li>If neither instance has patterns, use an empty String (i.e. "").
 * </ul>
 */
@Override
public PatternsRequestCondition combine(PatternsRequestCondition other) {
	List<PathPattern> combined = new ArrayList<>();
	if (!this.patterns.isEmpty() && !other.patterns.isEmpty()) {
		for (PathPattern pattern1 : this.patterns) {
			for (PathPattern pattern2 : other.patterns) {
				combined.add(pattern1.combine(pattern2));
			}
		}
	}
	else if (!this.patterns.isEmpty()) {
		combined.addAll(this.patterns);
	}
	else if (!other.patterns.isEmpty()) {
		combined.addAll(other.patterns);
	}
	return new PatternsRequestCondition(combined);
}
 
Example 16
Source Project: java-technology-stack   Source File: PatternsRequestCondition.java    License: MIT License 6 votes vote down vote up
/**
 * Compare the two conditions based on the URL patterns they contain.
 * Patterns are compared one at a time, from top to bottom. If all compared
 * patterns match equally, but one instance has more patterns, it is
 * considered a closer match.
 * <p>It is assumed that both instances have been obtained via
 * {@link #getMatchingCondition(ServerWebExchange)} to ensure they
 * contain only patterns that match the request and are sorted with
 * the best matches on top.
 */
@Override
public int compareTo(PatternsRequestCondition other, ServerWebExchange exchange) {
	Iterator<PathPattern> iterator = this.patterns.iterator();
	Iterator<PathPattern> iteratorOther = other.getPatterns().iterator();
	while (iterator.hasNext() && iteratorOther.hasNext()) {
		int result = PathPattern.SPECIFICITY_COMPARATOR.compare(iterator.next(), iteratorOther.next());
		if (result != 0) {
			return result;
		}
	}
	if (iterator.hasNext()) {
		return -1;
	}
	else if (iteratorOther.hasNext()) {
		return 1;
	}
	else {
		return 0;
	}
}
 
Example 17
private RequestMappingInfo assertComposedAnnotationMapping(String methodName, String path,
		RequestMethod requestMethod) throws Exception {

	Class<?> clazz = ComposedAnnotationController.class;
	Method method = clazz.getMethod(methodName);
	RequestMappingInfo info = this.handlerMapping.getMappingForMethod(method, clazz);

	assertNotNull(info);

	Set<PathPattern> paths = info.getPatternsCondition().getPatterns();
	assertEquals(1, paths.size());
	assertEquals(path, paths.iterator().next().getPatternString());

	Set<RequestMethod> methods = info.getMethodsCondition().getMethods();
	assertEquals(1, methods.size());
	assertEquals(requestMethod, methods.iterator().next());

	return info;
}
 
Example 18
Source Project: spring-analysis-note   Source File: ResourceUrlProvider.java    License: MIT License 5 votes vote down vote up
/**
 * Manually configure resource handler mappings.
 * <p><strong>Note:</strong> by default resource mappings are auto-detected
 * from the Spring {@code ApplicationContext}. If this property is used,
 * auto-detection is turned off.
 */
public void registerHandlers(Map<String, ResourceWebHandler> handlerMap) {
	this.handlerMap.clear();
	handlerMap.forEach((rawPattern, resourceWebHandler) -> {
		rawPattern = prependLeadingSlash(rawPattern);
		PathPattern pattern = this.patternParser.parse(rawPattern);
		this.handlerMap.put(pattern, resourceWebHandler);
	});
}
 
Example 19
Source Project: spring-analysis-note   Source File: RequestPredicates.java    License: MIT License 5 votes vote down vote up
private static PathPattern mergePatterns(@Nullable PathPattern oldPattern, PathPattern newPattern) {
	if (oldPattern != null) {
		return oldPattern.combine(newPattern);
	}
	else {
		return newPattern;
	}

}
 
Example 20
Source Project: spring-analysis-note   Source File: RequestPredicates.java    License: MIT License 5 votes vote down vote up
@Override
public boolean test(ServerRequest request) {
	PathContainer pathContainer = request.pathContainer();
	PathPattern.PathMatchInfo info = this.pattern.matchAndExtract(pathContainer);
	traceMatch("Pattern", this.pattern.getPatternString(), request.path(), info != null);
	if (info != null) {
		mergeAttributes(request, info.getUriVariables(), this.pattern);
		return true;
	}
	else {
		return false;
	}
}
 
Example 21
Source Project: spring-analysis-note   Source File: RequestPredicates.java    License: MIT License 5 votes vote down vote up
private static void mergeAttributes(ServerRequest request, Map<String, String> variables,
		PathPattern pattern) {
	Map<String, String> pathVariables = mergePathVariables(request.pathVariables(), variables);
	request.attributes().put(RouterFunctions.URI_TEMPLATE_VARIABLES_ATTRIBUTE,
				Collections.unmodifiableMap(pathVariables));

	pattern = mergePatterns(
			(PathPattern) request.attributes().get(RouterFunctions.MATCHING_PATTERN_ATTRIBUTE),
			pattern);
	request.attributes().put(RouterFunctions.MATCHING_PATTERN_ATTRIBUTE, pattern);
}
 
Example 22
Source Project: spring-analysis-note   Source File: RequestPredicates.java    License: MIT License 5 votes vote down vote up
private static Map<String, Object> mergeAttributes(ServerRequest request,
Map<String, String> pathVariables, PathPattern pattern) {
	Map<String, Object> result = new ConcurrentHashMap<>(request.attributes());

	result.put(RouterFunctions.URI_TEMPLATE_VARIABLES_ATTRIBUTE,
			mergePathVariables(request.pathVariables(), pathVariables));

	pattern = mergePatterns(
			(PathPattern) request.attributes().get(RouterFunctions.MATCHING_PATTERN_ATTRIBUTE),
			pattern);
	result.put(RouterFunctions.MATCHING_PATTERN_ATTRIBUTE, pattern);
	return result;
}
 
Example 23
Source Project: spring-analysis-note   Source File: AbstractUrlHandlerMapping.java    License: MIT License 5 votes vote down vote up
/**
 * Register the specified handler for the given URL path.
 * @param urlPath the URL the bean should be mapped to
 * @param handler the handler instance or handler bean name String
 * (a bean name will automatically be resolved into the corresponding handler bean)
 * @throws BeansException if the handler couldn't be registered
 * @throws IllegalStateException if there is a conflicting handler registered
 */
protected void registerHandler(String urlPath, Object handler) throws BeansException, IllegalStateException {
	Assert.notNull(urlPath, "URL path must not be null");
	Assert.notNull(handler, "Handler object must not be null");
	Object resolvedHandler = handler;

	// Parse path pattern
	urlPath = prependLeadingSlash(urlPath);
	PathPattern pattern = getPathPatternParser().parse(urlPath);
	if (this.handlerMap.containsKey(pattern)) {
		Object existingHandler = this.handlerMap.get(pattern);
		if (existingHandler != null && existingHandler != resolvedHandler) {
			throw new IllegalStateException(
					"Cannot map " + getHandlerDescription(handler) + " to [" + urlPath + "]: " +
					"there is already " + getHandlerDescription(existingHandler) + " mapped.");
		}
	}

	// Eagerly resolve handler if referencing singleton via name.
	if (!this.lazyInitHandlers && handler instanceof String) {
		String handlerName = (String) handler;
		if (obtainApplicationContext().isSingleton(handlerName)) {
			resolvedHandler = obtainApplicationContext().getBean(handlerName);
		}
	}

	// Register resolved handler
	this.handlerMap.put(pattern, resolvedHandler);
	if (logger.isTraceEnabled()) {
		logger.trace("Mapped [" + urlPath + "] onto " + getHandlerDescription(handler));
	}
}
 
Example 24
Source Project: spring-analysis-note   Source File: PatternsRequestCondition.java    License: MIT License 5 votes vote down vote up
/**
 * Checks if any of the patterns match the given request and returns an instance
 * that is guaranteed to contain matching patterns, sorted.
 * @param exchange the current exchange
 * @return the same instance if the condition contains no patterns;
 * or a new condition with sorted matching patterns;
 * or {@code null} if no patterns match.
 */
@Override
@Nullable
public PatternsRequestCondition getMatchingCondition(ServerWebExchange exchange) {
	if (this.patterns.isEmpty()) {
		return this;
	}
	SortedSet<PathPattern> matches = getMatchingPatterns(exchange);
	return (!matches.isEmpty() ? new PatternsRequestCondition(matches) : null);
}
 
Example 25
Source Project: spring-analysis-note   Source File: PatternsRequestCondition.java    License: MIT License 5 votes vote down vote up
/**
 * Find the patterns matching the given lookup path. Invoking this method should
 * yield results equivalent to those of calling
 * {@link #getMatchingCondition(ServerWebExchange)}.
 * This method is provided as an alternative to be used if no request is available
 * (e.g. introspection, tooling, etc).
 * @param exchange the current exchange
 * @return a sorted set of matching patterns sorted with the closest match first
 */
private SortedSet<PathPattern> getMatchingPatterns(ServerWebExchange exchange) {
	PathContainer lookupPath = exchange.getRequest().getPath().pathWithinApplication();
	TreeSet<PathPattern> pathPatterns = new TreeSet<>();
	for (PathPattern pattern : this.patterns) {
		if (pattern.matches(lookupPath)) {
			pathPatterns.add(pattern);
		}
	}
	return pathPatterns;
}
 
Example 26
/**
 * Expose URI template variables, matrix variables, and producible media types in the request.
 * @see HandlerMapping#URI_TEMPLATE_VARIABLES_ATTRIBUTE
 * @see HandlerMapping#MATRIX_VARIABLES_ATTRIBUTE
 * @see HandlerMapping#PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE
 */
@Override
protected void handleMatch(RequestMappingInfo info, HandlerMethod handlerMethod,
		ServerWebExchange exchange) {

	super.handleMatch(info, handlerMethod, exchange);

	PathContainer lookupPath = exchange.getRequest().getPath().pathWithinApplication();

	PathPattern bestPattern;
	Map<String, String> uriVariables;
	Map<String, MultiValueMap<String, String>> matrixVariables;

	Set<PathPattern> patterns = info.getPatternsCondition().getPatterns();
	if (patterns.isEmpty()) {
		bestPattern = getPathPatternParser().parse(lookupPath.value());
		uriVariables = Collections.emptyMap();
		matrixVariables = Collections.emptyMap();
	}
	else {
		bestPattern = patterns.iterator().next();
		PathPattern.PathMatchInfo result = bestPattern.matchAndExtract(lookupPath);
		Assert.notNull(result, () ->
				"Expected bestPattern: " + bestPattern + " to match lookupPath " + lookupPath);
		uriVariables = result.getUriVariables();
		matrixVariables = result.getMatrixVariables();
	}

	exchange.getAttributes().put(BEST_MATCHING_HANDLER_ATTRIBUTE, handlerMethod);
	exchange.getAttributes().put(BEST_MATCHING_PATTERN_ATTRIBUTE, bestPattern);
	exchange.getAttributes().put(URI_TEMPLATE_VARIABLES_ATTRIBUTE, uriVariables);
	exchange.getAttributes().put(MATRIX_VARIABLES_ATTRIBUTE, matrixVariables);

	if (!info.getProducesCondition().getProducibleMediaTypes().isEmpty()) {
		Set<MediaType> mediaTypes = info.getProducesCondition().getProducibleMediaTypes();
		exchange.getAttributes().put(PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, mediaTypes);
	}
}
 
Example 27
Source Project: spring-analysis-note   Source File: RequestMappingInfo.java    License: MIT License 5 votes vote down vote up
@Override
public String toString() {
	StringBuilder builder = new StringBuilder("{");
	if (!this.methodsCondition.isEmpty()) {
		Set<RequestMethod> httpMethods = this.methodsCondition.getMethods();
		builder.append(httpMethods.size() == 1 ? httpMethods.iterator().next() : httpMethods);
	}
	if (!this.patternsCondition.isEmpty()) {
		Set<PathPattern> patterns = this.patternsCondition.getPatterns();
		builder.append(" ").append(patterns.size() == 1 ? patterns.iterator().next() : patterns);
	}
	if (!this.paramsCondition.isEmpty()) {
		builder.append(", params ").append(this.paramsCondition);
	}
	if (!this.headersCondition.isEmpty()) {
		builder.append(", headers ").append(this.headersCondition);
	}
	if (!this.consumesCondition.isEmpty()) {
		builder.append(", consumes ").append(this.consumesCondition);
	}
	if (!this.producesCondition.isEmpty()) {
		builder.append(", produces ").append(this.producesCondition);
	}
	if (!this.customConditionHolder.isEmpty()) {
		builder.append(", and ").append(this.customConditionHolder);
	}
	builder.append('}');
	return builder.toString();
}
 
Example 28
Source Project: spring-analysis-note   Source File: RequestMappingInfo.java    License: MIT License 5 votes vote down vote up
private static List<PathPattern> parse(String[] paths, PathPatternParser parser) {
	return Arrays
			.stream(paths)
			.map(path -> {
				if (StringUtils.hasText(path) && !path.startsWith("/")) {
					path = "/" + path;
				}
				return parser.parse(path);
			})
			.collect(Collectors.toList());
}
 
Example 29
Source Project: spring-analysis-note   Source File: ResourceUrlProviderTests.java    License: MIT License 5 votes vote down vote up
@Override
public boolean matches(Object item) {
	if (item != null && item instanceof PathPattern) {
		return ((PathPattern) item).getPatternString().equals(pattern);
	}
	return false;
}
 
Example 30
@Test
public void equallyMatchingPatternsAreBothPresent() throws Exception {
	PatternsRequestCondition c = createPatternsCondition("/a", "/b");
	assertEquals(2, c.getPatterns().size());
	Iterator<PathPattern> itr = c.getPatterns().iterator();
	assertEquals("/a", itr.next().getPatternString());
	assertEquals("/b", itr.next().getPatternString());
}