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

The following examples show how to use org.springframework.web.util.pattern.PathPatternParser. 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: CrossDomainConfiguration.java    From momo-cloud-permission with Apache License 2.0 6 votes vote down vote up
@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 #2
Source File: CorsConfig.java    From microservices-platform with 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 #3
Source File: RequestMappingInfo.java    From spring-analysis-note with 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 #4
Source File: RequestMappingInfo.java    From java-technology-stack with 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 #5
Source File: PatternsRequestConditionTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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 #6
Source File: WebFluxConfigurationSupportTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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 #7
Source File: WebFluxConfigurationSupportTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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 #8
Source File: PatternsRequestConditionTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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 #9
Source File: WebFluxConfigurationSupportTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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
Source File: WebFluxConfigurationSupportTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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 #11
Source File: CorsConfig.java    From sophia_scaffolding with 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 #12
Source File: CorsConfig.java    From sophia_scaffolding with 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 #13
Source File: CorsConfig.java    From sophia_scaffolding with 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 #14
Source File: RequestMappingInfo.java    From java-technology-stack with 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 #15
Source File: RequestMappingHandlerMappingTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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 #16
Source File: TracingWebFilter.java    From java-specialagent with 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 #17
Source File: TracingWebFilter.java    From java-spring-web with 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 #18
Source File: ApiVersionWebFilter.java    From spring-cloud-open-service-broker with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #19
Source File: CorsWebFilterConfig.java    From tutorials with 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 #20
Source File: GlobalCorsConfig.java    From mall-swarm with 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 #21
Source File: RequestMappingInfo.java    From spring-analysis-note with 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 #22
Source File: RequestMappingInfoTests.java    From spring-analysis-note with 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 #23
Source File: RequestMappingHandlerMappingTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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 #24
Source File: CorsConfig.java    From codeway_service with 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 File: AbstractHandlerMapping.java    From spring-analysis-note with MIT License 4 votes vote down vote up
public AbstractHandlerMapping() {
	this.patternParser = new PathPatternParser();
}
 
Example #26
Source File: PathRoutePredicateFactory.java    From spring-cloud-gateway with Apache License 2.0 4 votes vote down vote up
public void setPathPatternParser(PathPatternParser pathPatternParser) {
	this.pathPatternParser = pathPatternParser;
}
 
Example #27
Source File: UrlBasedCorsConfigurationSource.java    From java-technology-stack with MIT License 4 votes vote down vote up
/**
 * Construct a new {@code UrlBasedCorsConfigurationSource} instance from the supplied
 * {@code PathPatternParser}.
 */
public UrlBasedCorsConfigurationSource(PathPatternParser patternParser) {
	this.corsConfigurations = new LinkedHashMap<>();
	this.patternParser = patternParser;
}
 
Example #28
Source File: RequestMappingInfo.java    From spring-analysis-note with MIT License 4 votes vote down vote up
public void setPatternParser(PathPatternParser patternParser) {
	this.patternParser = patternParser;
}
 
Example #29
Source File: RequestMappingInfo.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Nullable
public PathPatternParser getPatternParser() {
	return this.patternParser;
}
 
Example #30
Source File: RequestMappingInfo.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Nullable
public PathPatternParser getPatternParser() {
	return this.patternParser;
}