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

The following examples show how to use org.springframework.web.util.pattern.PathPatternParser. 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: RequestMappingInfo.java    License: MIT License 6 votes vote down vote up
@Override
public RequestMappingInfo build() {
	RequestedContentTypeResolver contentTypeResolver = this.options.getContentTypeResolver();

	PathPatternParser parser = (this.options.getPatternParser() != null ?
			this.options.getPatternParser() : new PathPatternParser());
	PatternsRequestCondition patternsCondition = new PatternsRequestCondition(parse(this.paths, parser));

	return new RequestMappingInfo(this.mappingName, patternsCondition,
			new RequestMethodsRequestCondition(this.methods),
			new ParamsRequestCondition(this.params),
			new HeadersRequestCondition(this.headers),
			new ConsumesRequestCondition(this.consumes, this.headers),
			new ProducesRequestCondition(this.produces, this.headers, contentTypeResolver),
			this.customCondition);
}
 
Example 2
@Test
public void requestMappingHandlerMapping() throws Exception {
	ApplicationContext context = loadConfig(WebFluxConfig.class);
	final Field field = ReflectionUtils.findField(PathPatternParser.class, "matchOptionalTrailingSeparator");
	ReflectionUtils.makeAccessible(field);

	String name = "requestMappingHandlerMapping";
	RequestMappingHandlerMapping mapping = context.getBean(name, RequestMappingHandlerMapping.class);
	assertNotNull(mapping);

	assertEquals(0, mapping.getOrder());

	PathPatternParser patternParser = mapping.getPathPatternParser();
	assertNotNull(patternParser);
	boolean matchOptionalTrailingSlash = (boolean) ReflectionUtils.getField(field, patternParser);
	assertTrue(matchOptionalTrailingSlash);

	name = "webFluxContentTypeResolver";
	RequestedContentTypeResolver resolver = context.getBean(name, RequestedContentTypeResolver.class);
	assertSame(resolver, mapping.getContentTypeResolver());

	ServerWebExchange exchange = MockServerWebExchange.from(get("/path").accept(MediaType.APPLICATION_JSON));
	assertEquals(Collections.singletonList(MediaType.APPLICATION_JSON), resolver.resolveMediaTypes(exchange));
}
 
Example 3
@Test
public void customPathMatchConfig() {
	ApplicationContext context = loadConfig(CustomPatchMatchConfig.class);
	final Field field = ReflectionUtils.findField(PathPatternParser.class, "matchOptionalTrailingSeparator");
	ReflectionUtils.makeAccessible(field);

	String name = "requestMappingHandlerMapping";
	RequestMappingHandlerMapping mapping = context.getBean(name, RequestMappingHandlerMapping.class);
	assertNotNull(mapping);

	PathPatternParser patternParser = mapping.getPathPatternParser();
	assertNotNull(patternParser);
	boolean matchOptionalTrailingSlash = (boolean) ReflectionUtils.getField(field, patternParser);
	assertFalse(matchOptionalTrailingSlash);

	Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
	assertEquals(1, map.size());
	assertEquals(Collections.singleton(new PathPatternParser().parse("/api/user/{id}")),
			map.keySet().iterator().next().getPatternsCondition().getPatterns());
}
 
Example 4
@Test
public void matchTrailingSlash() throws Exception {
	MockServerWebExchange exchange = MockServerWebExchange.from(get("/foo/"));

	PatternsRequestCondition condition = createPatternsCondition("/foo");
	PatternsRequestCondition match = condition.getMatchingCondition(exchange);

	assertNotNull(match);
	assertEquals("Should match by default", "/foo",
			match.getPatterns().iterator().next().getPatternString());

	condition = createPatternsCondition("/foo");
	match = condition.getMatchingCondition(exchange);

	assertNotNull(match);
	assertEquals("Trailing slash should be insensitive to useSuffixPatternMatch settings (SPR-6164, SPR-5636)",
			"/foo", match.getPatterns().iterator().next().getPatternString());

	PathPatternParser parser = new PathPatternParser();
	parser.setMatchOptionalTrailingSeparator(false);
	condition = new PatternsRequestCondition(parser.parse("/foo"));
	match = condition.getMatchingCondition(MockServerWebExchange.from(get("/foo/")));

	assertNull(match);
}
 
Example 5
Source Project: microservices-platform   Source File: CorsConfig.java    License: Apache License 2.0 6 votes vote down vote up
@Order(Ordered.HIGHEST_PRECEDENCE)
@Bean
public CorsWebFilter corsFilter() {
    CorsConfiguration config = new CorsConfiguration();
    // cookie跨域
    config.setAllowCredentials(Boolean.TRUE);
    config.addAllowedMethod(ALL);
    config.addAllowedOrigin(ALL);
    config.addAllowedHeader(ALL);
    // 配置前端js允许访问的自定义响应头
    config.addExposedHeader("setToken");

    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
    source.registerCorsConfiguration("/**", config);

    return new CorsWebFilter(source);
}
 
Example 6
@Bean
public CorsWebFilter corsFilter() {
    CorsConfiguration config = new CorsConfiguration();
    // cookie跨域
    config.setAllowCredentials(Boolean.TRUE);
    config.addAllowedMethod(CorsConfiguration.ALL);
    config.addAllowedOrigin(CorsConfiguration.ALL);
    config.addAllowedHeader(CorsConfiguration.ALL);
    // 配置前端js允许访问的自定义响应头
    config.addExposedHeader("x-token");

    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
    source.registerCorsConfiguration("/**", config);

    return new CorsWebFilter(source);
}
 
Example 7
Source Project: java-technology-stack   Source File: RequestMappingInfo.java    License: MIT License 6 votes vote down vote up
@Override
public RequestMappingInfo build() {
	RequestedContentTypeResolver contentTypeResolver = this.options.getContentTypeResolver();

	PathPatternParser parser = (this.options.getPatternParser() != null ?
			this.options.getPatternParser() : new PathPatternParser());
	PatternsRequestCondition patternsCondition = new PatternsRequestCondition(parse(this.paths, parser));

	return new RequestMappingInfo(this.mappingName, patternsCondition,
			new RequestMethodsRequestCondition(this.methods),
			new ParamsRequestCondition(this.params),
			new HeadersRequestCondition(this.headers),
			new ConsumesRequestCondition(this.consumes, this.headers),
			new ProducesRequestCondition(this.produces, this.headers, contentTypeResolver),
			this.customCondition);
}
 
Example 8
@Test
public void requestMappingHandlerMapping() throws Exception {
	ApplicationContext context = loadConfig(WebFluxConfig.class);
	final Field field = ReflectionUtils.findField(PathPatternParser.class, "matchOptionalTrailingSeparator");
	ReflectionUtils.makeAccessible(field);

	String name = "requestMappingHandlerMapping";
	RequestMappingHandlerMapping mapping = context.getBean(name, RequestMappingHandlerMapping.class);
	assertNotNull(mapping);

	assertEquals(0, mapping.getOrder());

	PathPatternParser patternParser = mapping.getPathPatternParser();
	assertNotNull(patternParser);
	boolean matchOptionalTrailingSlash = (boolean) ReflectionUtils.getField(field, patternParser);
	assertTrue(matchOptionalTrailingSlash);

	name = "webFluxContentTypeResolver";
	RequestedContentTypeResolver resolver = context.getBean(name, RequestedContentTypeResolver.class);
	assertSame(resolver, mapping.getContentTypeResolver());

	ServerWebExchange exchange = MockServerWebExchange.from(get("/path").accept(MediaType.APPLICATION_JSON));
	assertEquals(Collections.singletonList(MediaType.APPLICATION_JSON), resolver.resolveMediaTypes(exchange));
}
 
Example 9
@Test
public void customPathMatchConfig() {
	ApplicationContext context = loadConfig(CustomPatchMatchConfig.class);
	final Field field = ReflectionUtils.findField(PathPatternParser.class, "matchOptionalTrailingSeparator");
	ReflectionUtils.makeAccessible(field);

	String name = "requestMappingHandlerMapping";
	RequestMappingHandlerMapping mapping = context.getBean(name, RequestMappingHandlerMapping.class);
	assertNotNull(mapping);

	PathPatternParser patternParser = mapping.getPathPatternParser();
	assertNotNull(patternParser);
	boolean matchOptionalTrailingSlash = (boolean) ReflectionUtils.getField(field, patternParser);
	assertFalse(matchOptionalTrailingSlash);

	Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
	assertEquals(1, map.size());
	assertEquals(Collections.singleton(new PathPatternParser().parse("/api/user/{id}")),
			map.keySet().iterator().next().getPatternsCondition().getPatterns());
}
 
Example 10
@Test
public void matchTrailingSlash() throws Exception {
	MockServerWebExchange exchange = MockServerWebExchange.from(get("/foo/"));

	PatternsRequestCondition condition = createPatternsCondition("/foo");
	PatternsRequestCondition match = condition.getMatchingCondition(exchange);

	assertNotNull(match);
	assertEquals("Should match by default", "/foo",
			match.getPatterns().iterator().next().getPatternString());

	condition = createPatternsCondition("/foo");
	match = condition.getMatchingCondition(exchange);

	assertNotNull(match);
	assertEquals("Trailing slash should be insensitive to useSuffixPatternMatch settings (SPR-6164, SPR-5636)",
			"/foo", match.getPatterns().iterator().next().getPatternString());

	PathPatternParser parser = new PathPatternParser();
	parser.setMatchOptionalTrailingSeparator(false);
	condition = new PatternsRequestCondition(parser.parse("/foo"));
	match = condition.getMatchingCondition(MockServerWebExchange.from(get("/foo/")));

	assertNull(match);
}
 
Example 11
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 12
Source Project: spring-analysis-note   Source File: RequestMappingInfoTests.java    License: MIT License 5 votes vote down vote up
@Test
public void createEmpty() {
	RequestMappingInfo info = paths().build();

	PathPattern emptyPattern = (new PathPatternParser()).parse("");
	assertEquals(Collections.singleton(emptyPattern), info.getPatternsCondition().getPatterns());
	assertEquals(0, info.getMethodsCondition().getMethods().size());
	assertEquals(true, info.getConsumesCondition().isEmpty());
	assertEquals(true, info.getProducesCondition().isEmpty());
	assertNotNull(info.getParamsCondition());
	assertNotNull(info.getHeadersCondition());
	assertNull(info.getCustomCondition());
}
 
Example 13
@Test
public void pathPrefix() throws Exception {
	this.handlerMapping.setEmbeddedValueResolver(value -> "/${prefix}".equals(value) ? "/api" : value);
	this.handlerMapping.setPathPrefixes(Collections.singletonMap(
			"/${prefix}", HandlerTypePredicate.forAnnotation(RestController.class)));

	Method method = UserController.class.getMethod("getUser");
	RequestMappingInfo info = this.handlerMapping.getMappingForMethod(method, UserController.class);

	assertNotNull(info);
	assertEquals(Collections.singleton(new PathPatternParser().parse("/api/user/{id}")),
			info.getPatternsCondition().getPatterns());
}
 
Example 14
Source Project: mall-swarm   Source File: GlobalCorsConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public CorsWebFilter corsFilter() {
    CorsConfiguration config = new CorsConfiguration();
    config.addAllowedMethod("*");
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");

    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
    source.registerCorsConfiguration("/**", config);

    return new CorsWebFilter(source);
}
 
Example 15
Source Project: sophia_scaffolding   Source File: CorsConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public CorsWebFilter corsFilter() {
    CorsConfiguration config = new CorsConfiguration();
    config.addAllowedMethod("*");
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");

    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
    source.registerCorsConfiguration("/**", config);

    return new CorsWebFilter(source);
}
 
Example 16
Source Project: sophia_scaffolding   Source File: CorsConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public CorsWebFilter corsFilter() {
    CorsConfiguration config = new CorsConfiguration();
    config.addAllowedMethod("*");
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");

    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
    source.registerCorsConfiguration("/**", config);

    return new CorsWebFilter(source);
}
 
Example 17
Source Project: sophia_scaffolding   Source File: CorsConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public CorsWebFilter corsFilter() {
    CorsConfiguration config = new CorsConfiguration();
    config.addAllowedMethod("*");
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");

    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
    source.registerCorsConfiguration("/**", config);

    return new CorsWebFilter(source);
}
 
Example 18
Source Project: java-technology-stack   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 19
@Test
public void pathPrefix() throws NoSuchMethodException {
	this.handlerMapping.setEmbeddedValueResolver(value -> "/${prefix}".equals(value) ? "/api" : value);
	this.handlerMapping.setPathPrefixes(Collections.singletonMap(
			"/${prefix}", HandlerTypePredicate.forAnnotation(RestController.class)));

	Method method = UserController.class.getMethod("getUser");
	RequestMappingInfo info = this.handlerMapping.getMappingForMethod(method, UserController.class);

	assertNotNull(info);
	assertEquals(Collections.singleton(new PathPatternParser().parse("/api/user/{id}")),
			info.getPatternsCondition().getPatterns());
}
 
Example 20
Source Project: java-specialagent   Source File: TracingWebFilter.java    License: Apache License 2.0 5 votes vote down vote up
public TracingWebFilter(
    final Tracer tracer,
    final int order,
    final Pattern skipPattern,
    final List<String> urlPatterns,
    final List<WebFluxSpanDecorator> spanDecorators
) {
  this.tracer = tracer;
  this.order = order;
  this.skipPattern = (skipPattern != null && StringUtils.hasText(skipPattern.pattern())) ? skipPattern : null;
  final PathPatternParser pathPatternParser = new PathPatternParser();
  this.urlPatterns = urlPatterns.stream().map(pathPatternParser::parse).collect(Collectors.toSet());
  this.spanDecorators = spanDecorators;
}
 
Example 21
Source Project: java-spring-web   Source File: TracingWebFilter.java    License: Apache License 2.0 5 votes vote down vote up
public TracingWebFilter(
        final Tracer tracer,
        final int order,
        final Pattern skipPattern,
        final List<String> urlPatterns,
        final List<WebFluxSpanDecorator> spanDecorators
) {
    this.tracer = tracer;
    this.order = order;
    this.skipPattern = (skipPattern != null && StringUtils.hasText(skipPattern.pattern())) ? skipPattern : null;
    final PathPatternParser pathPatternParser = new PathPatternParser();
    this.urlPatterns = urlPatterns.stream().map(pathPatternParser::parse).collect(Collectors.toSet());
    this.spanDecorators = spanDecorators;
}
 
Example 22
/**
 * Process the web request and validate the API version in the header. If the API version does not match, then set
 * an HTTP 412 status and write the error message to the response.
 *
 * @param exchange {@inheritDoc}
 * @param chain {@inheritDoc}
 * @return {@inheritDoc}
 */
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
	PathPattern p = new PathPatternParser().parse(V2_API_PATH_PATTERN);
	Mono<Void> filterMono = chain.filter(exchange);
	if (p.matches(exchange.getRequest().getPath()) && version != null && !anyVersionAllowed()) {
		String apiVersion = exchange.getRequest().getHeaders().getFirst(version.getBrokerApiVersionHeader());
		ServerHttpResponse response = exchange.getResponse();
		String message = null;
		if (apiVersion == null) {
			response.setStatusCode(HttpStatus.BAD_REQUEST);
			message = ServiceBrokerApiVersionErrorMessage.from(version.getApiVersion(), "null").toString();
		}
		else if (!version.getApiVersion().equals(apiVersion)) {
			response.setStatusCode(HttpStatus.PRECONDITION_FAILED);
			message = ServiceBrokerApiVersionErrorMessage.from(version.getApiVersion(), apiVersion)
					.toString();
		}
		if (message != null) {
			String json;
			try {
				json = new ObjectMapper().writeValueAsString(new ErrorMessage(message));
			}
			catch (JsonProcessingException e) {
				json = "{}";
			}
			Flux<DataBuffer> responseBody =
					Flux.just(json)
							.map(s -> toDataBuffer(s, response.bufferFactory()));
			filterMono = response.writeWith(responseBody);
		}
	}
	return filterMono;
}
 
Example 23
Source Project: tutorials   Source File: CorsWebFilterConfig.java    License: MIT License 5 votes vote down vote up
@Bean
CorsWebFilter corsWebFilter() {
    CorsConfiguration corsConfig = new CorsConfiguration();
    corsConfig.setAllowedOrigins(Arrays.asList("http://allowed-origin.com"));
    corsConfig.setMaxAge(8000L);
    corsConfig.addAllowedMethod("PUT");
    corsConfig.addAllowedHeader("Baeldung-Allowed");

    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
    source.registerCorsConfiguration("/**", corsConfig);

    return new CorsWebFilter(source);
}
 
Example 24
Source Project: codeway_service   Source File: CorsConfig.java    License: GNU General Public License v3.0 4 votes vote down vote up
@Bean
public CorsWebFilter corsFilter(){
	UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
	source.registerCorsConfiguration("/**", buildConfig());
	return new CorsWebFilter(source);
}
 
Example 25
Source Project: spring-analysis-note   Source File: AbstractHandlerMapping.java    License: MIT License 4 votes vote down vote up
public AbstractHandlerMapping() {
	this.patternParser = new PathPatternParser();
}
 
Example 26
Source Project: spring-analysis-note   Source File: RequestMappingInfo.java    License: MIT License 4 votes vote down vote up
public void setPatternParser(PathPatternParser patternParser) {
	this.patternParser = patternParser;
}
 
Example 27
Source Project: spring-analysis-note   Source File: RequestMappingInfo.java    License: MIT License 4 votes vote down vote up
@Nullable
public PathPatternParser getPatternParser() {
	return this.patternParser;
}
 
Example 28
/**
 * Construct a new {@code UrlBasedCorsConfigurationSource} instance from the supplied
 * {@code PathPatternParser}.
 */
public UrlBasedCorsConfigurationSource(PathPatternParser patternParser) {
	this.corsConfigurations = new LinkedHashMap<>();
	this.patternParser = patternParser;
}
 
Example 29
Source Project: java-technology-stack   Source File: AbstractHandlerMapping.java    License: MIT License 4 votes vote down vote up
public AbstractHandlerMapping() {
	this.patternParser = new PathPatternParser();
	this.corsConfigurationSource = new UrlBasedCorsConfigurationSource(this.patternParser);
}
 
Example 30
Source Project: java-technology-stack   Source File: RequestMappingInfo.java    License: MIT License 4 votes vote down vote up
public void setPatternParser(PathPatternParser patternParser) {
	this.patternParser = patternParser;
}