org.springframework.http.server.PathContainer Java Examples
The following examples show how to use
org.springframework.http.server.PathContainer.
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: ResourceWebHandler.java From spring-analysis-note with MIT License | 6 votes |
protected Mono<Resource> getResource(ServerWebExchange exchange) { String name = HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE; PathContainer pathWithinHandler = exchange.getRequiredAttribute(name); String path = processPath(pathWithinHandler.value()); if (!StringUtils.hasText(path) || isInvalidPath(path)) { return Mono.empty(); } if (isInvalidEncodedPath(path)) { return Mono.empty(); } Assert.state(this.resolverChain != null, "ResourceResolverChain not initialized"); Assert.state(this.transformerChain != null, "ResourceTransformerChain not initialized"); return this.resolverChain.resolveResource(exchange, path, getLocations()) .flatMap(resource -> this.transformerChain.transform(exchange, resource)); }
Example #2
Source File: PathPattern.java From spring-analysis-note with MIT License | 6 votes |
/** * Whether this pattern matches the given path. * @param pathContainer the candidate path to attempt to match against * @return {@code true} if the path matches this pattern */ public boolean matches(PathContainer pathContainer) { if (this.head == null) { return !hasLength(pathContainer) || (this.matchOptionalTrailingSeparator && pathContainerIsJustSeparator(pathContainer)); } else if (!hasLength(pathContainer)) { if (this.head instanceof WildcardTheRestPathElement || this.head instanceof CaptureTheRestPathElement) { pathContainer = EMPTY_PATH; // Will allow CaptureTheRest to bind the variable to empty } else { return false; } } MatchingContext matchingContext = new MatchingContext(pathContainer, false); return this.head.matches(0, matchingContext); }
Example #3
Source File: PathPattern.java From spring-analysis-note with MIT License | 6 votes |
/** * Match this pattern to the given URI path and return extracted URI template * variables as well as path parameters (matrix variables). * @param pathContainer the candidate path to attempt to match against * @return info object with the extracted variables, or {@code null} for no match */ @Nullable public PathMatchInfo matchAndExtract(PathContainer pathContainer) { if (this.head == null) { return hasLength(pathContainer) && !(this.matchOptionalTrailingSeparator && pathContainerIsJustSeparator(pathContainer)) ? null : PathMatchInfo.EMPTY; } else if (!hasLength(pathContainer)) { if (this.head instanceof WildcardTheRestPathElement || this.head instanceof CaptureTheRestPathElement) { pathContainer = EMPTY_PATH; // Will allow CaptureTheRest to bind the variable to empty } else { return null; } } MatchingContext matchingContext = new MatchingContext(pathContainer, true); return this.head.matches(0, matchingContext) ? matchingContext.getPathMatchResult() : null; }
Example #4
Source File: ResourceWebHandler.java From java-technology-stack with MIT License | 6 votes |
protected Mono<Resource> getResource(ServerWebExchange exchange) { String name = HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE; PathContainer pathWithinHandler = exchange.getRequiredAttribute(name); String path = processPath(pathWithinHandler.value()); if (!StringUtils.hasText(path) || isInvalidPath(path)) { return Mono.empty(); } if (isInvalidEncodedPath(path)) { return Mono.empty(); } Assert.state(this.resolverChain != null, "ResourceResolverChain not initialized"); Assert.state(this.transformerChain != null, "ResourceTransformerChain not initialized"); return this.resolverChain.resolveResource(exchange, path, getLocations()) .flatMap(resource -> this.transformerChain.transform(exchange, resource)); }
Example #5
Source File: ResourceUrlProvider.java From java-technology-stack with MIT License | 6 votes |
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 #6
Source File: SimpleUrlHandlerMappingTests.java From spring-analysis-note with MIT License | 6 votes |
private void testUrl(String url, Object bean, HandlerMapping handlerMapping, String pathWithinMapping) { MockServerHttpRequest request = MockServerHttpRequest.method(HttpMethod.GET, URI.create(url)).build(); ServerWebExchange exchange = MockServerWebExchange.from(request); Object actual = handlerMapping.getHandler(exchange).block(); if (bean != null) { assertNotNull(actual); assertSame(bean, actual); //noinspection OptionalGetWithoutIsPresent PathContainer path = exchange.getAttribute(PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); assertNotNull(path); assertEquals(pathWithinMapping, path.value()); } else { assertNull(actual); } }
Example #7
Source File: AbstractUrlHandlerMapping.java From java-technology-stack with MIT License | 6 votes |
/** * 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 #8
Source File: TracingWebFilter.java From java-spring-web with Apache License 2.0 | 6 votes |
/** * It checks whether a request should be traced or not. * * @return whether request should be traced or not */ protected boolean shouldBeTraced(final ServerHttpRequest request) { final PathContainer pathWithinApplication = request.getPath().pathWithinApplication(); // skip URLs matching skip pattern // e.g. pattern is defined as '/health|/status' then URL 'http://localhost:5000/context/health' won't be traced if (skipPattern != null) { final String url = pathWithinApplication.value(); if (skipPattern.matcher(url).matches()) { if (LOG.isTraceEnabled()) { LOG.trace("Not tracing request " + request + " because it matches skip pattern: " + skipPattern); } return false; } } if (!urlPatterns.isEmpty() && urlPatterns.stream().noneMatch(urlPattern -> urlPattern.matches(pathWithinApplication))) { if (LOG.isTraceEnabled()) { LOG.trace("Not tracing request " + request + " because it does not match any URL pattern: " + urlPatterns); } return false; } return true; }
Example #9
Source File: AbstractUrlHandlerMapping.java From java-technology-stack with MIT License | 6 votes |
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 #10
Source File: AbstractUrlHandlerMapping.java From spring-analysis-note with MIT License | 6 votes |
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 #11
Source File: AbstractUrlHandlerMapping.java From spring-analysis-note with MIT License | 6 votes |
/** * 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 #12
Source File: ResourceUrlProvider.java From spring-analysis-note with MIT License | 6 votes |
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 #13
Source File: PathPattern.java From java-technology-stack with MIT License | 6 votes |
/** * Whether this pattern matches the given path. * @param pathContainer the candidate path to attempt to match against * @return {@code true} if the path matches this pattern */ public boolean matches(PathContainer pathContainer) { if (this.head == null) { return !hasLength(pathContainer) || (this.matchOptionalTrailingSeparator && pathContainerIsJustSeparator(pathContainer)); } else if (!hasLength(pathContainer)) { if (this.head instanceof WildcardTheRestPathElement || this.head instanceof CaptureTheRestPathElement) { pathContainer = EMPTY_PATH; // Will allow CaptureTheRest to bind the variable to empty } else { return false; } } MatchingContext matchingContext = new MatchingContext(pathContainer, false); return this.head.matches(0, matchingContext); }
Example #14
Source File: PathPattern.java From java-technology-stack with MIT License | 6 votes |
/** * Match this pattern to the given URI path and return extracted URI template * variables as well as path parameters (matrix variables). * @param pathContainer the candidate path to attempt to match against * @return info object with the extracted variables, or {@code null} for no match */ @Nullable public PathMatchInfo matchAndExtract(PathContainer pathContainer) { if (this.head == null) { return hasLength(pathContainer) && !(this.matchOptionalTrailingSeparator && pathContainerIsJustSeparator(pathContainer)) ? null : PathMatchInfo.EMPTY; } else if (!hasLength(pathContainer)) { if (this.head instanceof WildcardTheRestPathElement || this.head instanceof CaptureTheRestPathElement) { pathContainer = EMPTY_PATH; // Will allow CaptureTheRest to bind the variable to empty } else { return null; } } MatchingContext matchingContext = new MatchingContext(pathContainer, true); return this.head.matches(0, matchingContext) ? matchingContext.getPathMatchResult() : null; }
Example #15
Source File: SimpleUrlHandlerMappingTests.java From java-technology-stack with MIT License | 6 votes |
private void testUrl(String url, Object bean, HandlerMapping handlerMapping, String pathWithinMapping) { MockServerHttpRequest request = MockServerHttpRequest.method(HttpMethod.GET, URI.create(url)).build(); ServerWebExchange exchange = MockServerWebExchange.from(request); Object actual = handlerMapping.getHandler(exchange).block(); if (bean != null) { assertNotNull(actual); assertSame(bean, actual); //noinspection OptionalGetWithoutIsPresent PathContainer path = exchange.getAttribute(PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); assertNotNull(path); assertEquals(pathWithinMapping, path.value()); } else { assertNull(actual); } }
Example #16
Source File: TracingWebFilter.java From java-specialagent with Apache License 2.0 | 6 votes |
/** * It checks whether a request should be traced or not. * * @return whether request should be traced or not */ boolean shouldBeTraced(final ServerHttpRequest request) { final PathContainer pathWithinApplication = request.getPath().pathWithinApplication(); // skip URLs matching skip pattern // e.g. pattern is defined as '/health|/status' then URL 'http://localhost:5000/context/health' won't be traced if (skipPattern != null) { final String url = pathWithinApplication.value(); if (skipPattern.matcher(url).matches()) { if (LOG.isTraceEnabled()) { LOG.trace("Not tracing request " + request + " because it matches skip pattern: " + skipPattern); } return false; } } if (!urlPatterns.isEmpty() && urlPatterns.stream().noneMatch(urlPattern -> urlPattern.matches(pathWithinApplication))) { if (LOG.isTraceEnabled()) { LOG.trace("Not tracing request " + request + " because it does not match any URL pattern: " + urlPatterns); } return false; } return true; }
Example #17
Source File: PathResourceLookupFunction.java From java-technology-stack with MIT License | 5 votes |
@Override public Mono<Resource> apply(ServerRequest request) { PathContainer pathContainer = request.pathContainer(); if (!this.pattern.matches(pathContainer)) { return Mono.empty(); } pathContainer = this.pattern.extractPathWithinPattern(pathContainer); String path = processPath(pathContainer.value()); if (path.contains("%")) { path = StringUtils.uriDecode(path, StandardCharsets.UTF_8); } if (!StringUtils.hasLength(path) || isInvalidPath(path)) { return Mono.empty(); } try { Resource resource = this.location.createRelative(path); if (resource.exists() && resource.isReadable() && isResourceUnderLocation(resource)) { return Mono.just(resource); } else { return Mono.empty(); } } catch (IOException ex) { throw new UncheckedIOException(ex); } }
Example #18
Source File: RequestPredicates.java From spring-analysis-note with MIT License | 5 votes |
@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 #19
Source File: ResourceUrlProvider.java From spring-analysis-note with MIT License | 5 votes |
/** * Get the public resource URL for the given URI string. * <p>The URI string is expected to be a path and if it contains a query or * fragment those will be preserved in the resulting public resource URL. * @param uriString the URI string to transform * @param exchange the current exchange * @return the resolved public resource URL path, or empty if unresolved */ public final Mono<String> getForUriString(String uriString, ServerWebExchange exchange) { ServerHttpRequest request = exchange.getRequest(); int queryIndex = getQueryIndex(uriString); String lookupPath = uriString.substring(0, queryIndex); String query = uriString.substring(queryIndex); PathContainer parsedLookupPath = PathContainer.parsePath(lookupPath); return resolveResourceUrl(exchange, parsedLookupPath).map(resolvedPath -> request.getPath().contextPath().value() + resolvedPath + query); }
Example #20
Source File: PathPattern.java From spring-analysis-note with MIT License | 5 votes |
/** * Match the beginning of the given path and return the remaining portion * not covered by this pattern. This is useful for matching nested routes * where the path is matched incrementally at each level. * @param pathContainer the candidate path to attempt to match against * @return info object with the match result or {@code null} for no match */ @Nullable public PathRemainingMatchInfo matchStartOfPath(PathContainer pathContainer) { if (this.head == null) { return new PathRemainingMatchInfo(pathContainer); } else if (!hasLength(pathContainer)) { return null; } MatchingContext matchingContext = new MatchingContext(pathContainer, true); matchingContext.setMatchAllowExtraPath(); boolean matches = this.head.matches(0, matchingContext); if (!matches) { return null; } else { PathRemainingMatchInfo info; if (matchingContext.remainingPathIndex == pathContainer.elements().size()) { info = new PathRemainingMatchInfo(EMPTY_PATH, matchingContext.getPathMatchResult()); } else { info = new PathRemainingMatchInfo(pathContainer.subPath(matchingContext.remainingPathIndex), matchingContext.getPathMatchResult()); } return info; } }
Example #21
Source File: PathPattern.java From spring-analysis-note with MIT License | 5 votes |
/** * Return the decoded value of the specified element. * @param pathIndex path element index * @return the decoded value */ String pathElementValue(int pathIndex) { Element element = (pathIndex < this.pathLength) ? this.pathElements.get(pathIndex) : null; if (element instanceof PathContainer.PathSegment) { return ((PathContainer.PathSegment)element).valueToMatch(); } return ""; }
Example #22
Source File: PathPatternTests.java From spring-analysis-note with MIT License | 5 votes |
private void checkMatches(String uriTemplate, String path) { PathPatternParser parser = new PathPatternParser(); parser.setMatchOptionalTrailingSeparator(true); PathPattern p = parser.parse(uriTemplate); PathContainer pc = toPathContainer(path); assertTrue(p.matches(pc)); }
Example #23
Source File: ResourceUrlProvider.java From java-technology-stack with MIT License | 5 votes |
/** * Get the public resource URL for the given URI string. * <p>The URI string is expected to be a path and if it contains a query or * fragment those will be preserved in the resulting public resource URL. * @param uriString the URI string to transform * @param exchange the current exchange * @return the resolved public resource URL path, or empty if unresolved */ public final Mono<String> getForUriString(String uriString, ServerWebExchange exchange) { ServerHttpRequest request = exchange.getRequest(); int queryIndex = getQueryIndex(uriString); String lookupPath = uriString.substring(0, queryIndex); String query = uriString.substring(queryIndex); PathContainer parsedLookupPath = PathContainer.parsePath(lookupPath); return resolveResourceUrl(exchange, parsedLookupPath).map(resolvedPath -> request.getPath().contextPath().value() + resolvedPath + query); }
Example #24
Source File: PathPattern.java From java-technology-stack with MIT License | 5 votes |
/** * Return the decoded value of the specified element. * @param pathIndex path element index * @return the decoded value */ String pathElementValue(int pathIndex) { Element element = (pathIndex < this.pathLength) ? this.pathElements.get(pathIndex) : null; if (element instanceof PathContainer.PathSegment) { return ((PathContainer.PathSegment)element).valueToMatch(); } return ""; }
Example #25
Source File: RequestPredicates.java From java-technology-stack with MIT License | 5 votes |
@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 #26
Source File: AbstractUrlHandlerMapping.java From java-technology-stack with MIT License | 5 votes |
@Override public Mono<Object> getHandlerInternal(ServerWebExchange exchange) { PathContainer lookupPath = exchange.getRequest().getPath().pathWithinApplication(); Object handler; try { handler = lookupHandler(lookupPath, exchange); } catch (Exception ex) { return Mono.error(ex); } return Mono.justOrEmpty(handler); }
Example #27
Source File: PathPattern.java From java-technology-stack with MIT License | 5 votes |
/** * Match the beginning of the given path and return the remaining portion * not covered by this pattern. This is useful for matching nested routes * where the path is matched incrementally at each level. * @param pathContainer the candidate path to attempt to match against * @return info object with the match result or {@code null} for no match */ @Nullable public PathRemainingMatchInfo matchStartOfPath(PathContainer pathContainer) { if (this.head == null) { return new PathRemainingMatchInfo(pathContainer); } else if (!hasLength(pathContainer)) { return null; } MatchingContext matchingContext = new MatchingContext(pathContainer, true); matchingContext.setMatchAllowExtraPath(); boolean matches = this.head.matches(0, matchingContext); if (!matches) { return null; } else { PathRemainingMatchInfo info; if (matchingContext.remainingPathIndex == pathContainer.elements().size()) { info = new PathRemainingMatchInfo(EMPTY_PATH, matchingContext.getPathMatchResult()); } else { info = new PathRemainingMatchInfo(pathContainer.subPath(matchingContext.remainingPathIndex), matchingContext.getPathMatchResult()); } return info; } }
Example #28
Source File: UrlBasedCorsConfigurationSource.java From java-technology-stack with MIT License | 5 votes |
@Override @Nullable public CorsConfiguration getCorsConfiguration(ServerWebExchange exchange) { PathContainer lookupPath = exchange.getRequest().getPath().pathWithinApplication(); return this.corsConfigurations.entrySet().stream() .filter(entry -> entry.getKey().matches(lookupPath)) .map(Map.Entry::getValue) .findFirst() .orElse(null); }
Example #29
Source File: PathPatternTests.java From java-technology-stack with MIT License | 5 votes |
private void checkMatches(String uriTemplate, String path) { PathPatternParser parser = new PathPatternParser(); parser.setMatchOptionalTrailingSeparator(true); PathPattern p = parser.parse(uriTemplate); PathContainer pc = toPathContainer(path); assertTrue(p.matches(pc)); }
Example #30
Source File: ResourceHandlerRegistryTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void mapPathToLocation() throws Exception { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("")); exchange.getAttributes().put(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, PathContainer.parsePath("/testStylesheet.css")); ResourceWebHandler handler = getHandler("/resources/**"); handler.handle(exchange).block(Duration.ofSeconds(5)); StepVerifier.create(exchange.getResponse().getBody()) .consumeNextWith(buf -> assertEquals("test stylesheet content", DataBufferTestUtils.dumpString(buf, StandardCharsets.UTF_8))) .expectComplete() .verify(); }