org.springframework.cloud.gateway.handler.predicate.PredicateDefinition Java Examples

The following examples show how to use org.springframework.cloud.gateway.handler.predicate.PredicateDefinition. 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: RouteController.java    From spring-cloud-gateway-nacos with Apache License 2.0 6 votes vote down vote up
private RouteDefinition assembleRouteDefinition(GatewayRouteDefinition gwdefinition) {
    RouteDefinition definition = new RouteDefinition();
    List<PredicateDefinition> pdList=new ArrayList<>();
    definition.setId(gwdefinition.getId());
    List<GatewayPredicateDefinition> gatewayPredicateDefinitionList=gwdefinition.getPredicates();
    for (GatewayPredicateDefinition gpDefinition: gatewayPredicateDefinitionList) {
        PredicateDefinition predicate = new PredicateDefinition();
        predicate.setArgs(gpDefinition.getArgs());
        predicate.setName(gpDefinition.getName());
        pdList.add(predicate);
    }
    definition.setPredicates(pdList);
    URI uri = UriComponentsBuilder.fromHttpUrl(gwdefinition.getUri()).build().toUri();
    definition.setUri(uri);
    return definition;
}
 
Example #2
Source File: GatewayRouteService.java    From SpringCloud with Apache License 2.0 6 votes vote down vote up
/**
 * 将数据库中json对象转换为网关需要的RouteDefinition对象
 *
 * @param gatewayRoute
 * @return RouteDefinition
 */
private RouteDefinition gatewayRouteToRouteDefinition(GatewayRoute gatewayRoute) {
    RouteDefinition routeDefinition = new RouteDefinition();
    routeDefinition.setId(gatewayRoute.getRouteId());
    routeDefinition.setOrder(gatewayRoute.getOrders());
    routeDefinition.setUri(URI.create(gatewayRoute.getUri()));
    ObjectMapper objectMapper = new ObjectMapper();
    try {
        routeDefinition.setFilters(objectMapper.readValue(gatewayRoute.getFilters(), new TypeReference<List<FilterDefinition>>() {
        }));
        routeDefinition.setPredicates(objectMapper.readValue(gatewayRoute.getPredicates(), new TypeReference<List<PredicateDefinition>>() {
        }));
    } catch (IOException e) {
        log.error("网关路由对象转换失败", e);
    }
    return routeDefinition;
}
 
Example #3
Source File: GatewayControllerEndpointTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void testPostRouteWithNotExistingPredicate() {

	RouteDefinition testRouteDefinition = new RouteDefinition();
	testRouteDefinition.setUri(URI.create("http://example.org"));

	PredicateDefinition predicateDefinition = new PredicateDefinition(
			"NotExistingPredicate=test-config");
	testRouteDefinition.setPredicates(Collections.singletonList(predicateDefinition));

	testClient.post()
			.uri("http://localhost:" + port + "/actuator/gateway/routes/test-route")
			.accept(MediaType.APPLICATION_JSON)
			.body(BodyInserters.fromValue(testRouteDefinition)).exchange()
			.expectStatus().isBadRequest();
}
 
Example #4
Source File: RouteDefinition.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
public RouteDefinition(String text) {
	int eqIdx = text.indexOf('=');
	if (eqIdx <= 0) {
		throw new ValidationException("Unable to parse RouteDefinition text '" + text
				+ "'" + ", must be of the form name=value");
	}

	setId(text.substring(0, eqIdx));

	String[] args = tokenizeToStringArray(text.substring(eqIdx + 1), ",");

	setUri(URI.create(args[0]));

	for (int i = 1; i < args.length; i++) {
		this.predicates.add(new PredicateDefinition(args[i]));
	}
}
 
Example #5
Source File: RouteDefinitionRouteLocator.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private AsyncPredicate<ServerWebExchange> lookup(RouteDefinition route,
		PredicateDefinition predicate) {
	RoutePredicateFactory<Object> factory = this.predicates.get(predicate.getName());
	if (factory == null) {
		throw new IllegalArgumentException(
				"Unable to find RoutePredicateFactory with name "
						+ predicate.getName());
	}
	if (logger.isDebugEnabled()) {
		logger.debug("RouteDefinition " + route.getId() + " applying "
				+ predicate.getArgs() + " to " + predicate.getName());
	}

	// @formatter:off
	Object config = this.configurationService.with(factory)
			.name(predicate.getName())
			.properties(predicate.getArgs())
			.eventFunction((bound, properties) -> new PredicateArgsEvent(
					RouteDefinitionRouteLocator.this, route.getId(), properties))
			.bind();
	// @formatter:on

	return factory.applyAsync(config);
}
 
Example #6
Source File: RouteDefinitionRouteLocatorTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
private List<RouteDefinition> containsInvalidRoutes() {
	RouteDefinition foo = new RouteDefinition();
	foo.setId("foo");
	foo.setUri(URI.create("https://foo.example.com"));
	foo.setPredicates(Arrays.asList(new PredicateDefinition("Host=*.example.com")));
	foo.setFilters(Arrays.asList(new FilterDefinition("RemoveResponseHeader=Server"),
			new FilterDefinition("TestOrdered="),
			new FilterDefinition("AddResponseHeader=X-Response-Foo, Bar")));
	RouteDefinition bad = new RouteDefinition();
	bad.setId("exceptionRaised");
	bad.setUri(URI.create("https://foo.example.com"));
	bad.setPredicates(Arrays.asList(new PredicateDefinition("Host=*.example.com")));
	bad.setFilters(Arrays.asList(new FilterDefinition("Generate exception")));
	return Arrays.asList(foo, bad);
}
 
Example #7
Source File: GatewayUtils.java    From jeecg-cloud with Apache License 2.0 5 votes vote down vote up
/**
 *  redis中的信息需要处理下 转成RouteDefinition对象
 *         - id: login
 *           uri: lb://cloud-jeecg-system
 *           predicates:
 *             - Path=/jeecg-boot/sys/**,
 * @param array
 * @return
 */

public static List<RouteDefinition> getRoutesByJson(JSONArray array) throws URISyntaxException {
    List<RouteDefinition> ls = new ArrayList<>();
    for(int i=0;i<array.size();i++) {
        JSONObject obj = array.getJSONObject(i);
        RouteDefinition route = new RouteDefinition();
        route.setId(obj.getString("id"));
        Object uri = obj.get("uri");
        if(uri==null){
            route.setUri(new URI("lb://"+obj.getString("name")));
        }else{
            route.setUri(new URI(obj.getString("uri")));
        }
        Object predicates = obj.get("predicates");
        if (predicates != null) {
            JSONArray predicatesArray = JSONArray.parseArray(predicates.toString());
            List<PredicateDefinition> predicateDefinitionList =
                    predicatesArray.toJavaList(PredicateDefinition.class);
            route.setPredicates(predicateDefinitionList);
        }

        Object filters = obj.get("filters");
        if (filters != null) {
            JSONArray filtersArray = JSONArray.parseArray(filters.toString());
            List<FilterDefinition> filterDefinitionList
                    = filtersArray.toJavaList(FilterDefinition.class);
            route.setFilters(filterDefinitionList);
        }
        ls.add(route);
    }
    return ls;
}
 
Example #8
Source File: RouteDefinitionRouteLocatorTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void contextLoads() {
	List<RoutePredicateFactory> predicates = Arrays
			.asList(new HostRoutePredicateFactory());
	List<GatewayFilterFactory> gatewayFilterFactories = Arrays.asList(
			new RemoveResponseHeaderGatewayFilterFactory(),
			new AddResponseHeaderGatewayFilterFactory(),
			new TestOrderedGatewayFilterFactory());
	GatewayProperties gatewayProperties = new GatewayProperties();
	gatewayProperties.setRoutes(Arrays.asList(new RouteDefinition() {
		{
			setId("foo");
			setUri(URI.create("https://foo.example.com"));
			setPredicates(
					Arrays.asList(new PredicateDefinition("Host=*.example.com")));
			setFilters(Arrays.asList(
					new FilterDefinition("RemoveResponseHeader=Server"),
					new FilterDefinition("TestOrdered="),
					new FilterDefinition("AddResponseHeader=X-Response-Foo, Bar")));
		}
	}));

	PropertiesRouteDefinitionLocator routeDefinitionLocator = new PropertiesRouteDefinitionLocator(
			gatewayProperties);
	@SuppressWarnings("deprecation")
	RouteDefinitionRouteLocator routeDefinitionRouteLocator = new RouteDefinitionRouteLocator(
			new CompositeRouteDefinitionLocator(Flux.just(routeDefinitionLocator)),
			predicates, gatewayFilterFactories, gatewayProperties,
			new ConfigurationService(null, () -> null, () -> null));

	StepVerifier.create(routeDefinitionRouteLocator.getRoutes()).assertNext(route -> {
		List<GatewayFilter> filters = route.getFilters();
		assertThat(filters).hasSize(3);
		assertThat(getFilterClassName(filters.get(0)))
				.contains("RemoveResponseHeader");
		assertThat(getFilterClassName(filters.get(1))).contains("AddResponseHeader");
		assertThat(getFilterClassName(filters.get(2)))
				.contains("RouteDefinitionRouteLocatorTests$TestOrderedGateway");
	}).expectComplete().verify();
}
 
Example #9
Source File: DiscoveryClientRouteDefinitionLocatorTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void includeExpressionWorks() {
	assertThat(locator).as("DiscoveryClientRouteDefinitionLocator was null")
			.isNotNull();

	List<RouteDefinition> definitions = locator.getRouteDefinitions().collectList()
			.block();
	assertThat(definitions).hasSize(1);

	RouteDefinition definition = definitions.get(0);
	assertThat(definition.getId()).isEqualTo("testedge_SERVICE1");
	assertThat(definition.getUri()).hasScheme("lb").hasHost("SERVICE1");
	assertThat(definition.getMetadata()).containsEntry("edge", "true");

	assertThat(definition.getPredicates()).hasSize(1);
	PredicateDefinition predicate = definition.getPredicates().get(0);
	assertThat(predicate.getName()).isEqualTo("Path");
	assertThat(predicate.getArgs()).hasSize(1).containsEntry(PATTERN_KEY,
			"/service1/**");

	assertThat(definition.getFilters()).hasSize(1);
	FilterDefinition filter = definition.getFilters().get(0);
	assertThat(filter.getName()).isEqualTo("RewritePath");
	assertThat(filter.getArgs()).hasSize(2)
			.containsEntry(REGEXP_KEY, "/service1/(?<remaining>.*)")
			.containsEntry(REPLACEMENT_KEY, "/${remaining}");
}
 
Example #10
Source File: GatewayControllerEndpointTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void testPostValidRouteDefinition() {

	RouteDefinition testRouteDefinition = new RouteDefinition();
	testRouteDefinition.setUri(URI.create("http://example.org"));

	FilterDefinition prefixPathFilterDefinition = new FilterDefinition(
			"PrefixPath=/test-path");
	FilterDefinition redirectToFilterDefinition = new FilterDefinition(
			"RemoveResponseHeader=Sensitive-Header");
	FilterDefinition testFilterDefinition = new FilterDefinition("TestFilter");
	testRouteDefinition.setFilters(Arrays.asList(prefixPathFilterDefinition,
			redirectToFilterDefinition, testFilterDefinition));

	PredicateDefinition hostRoutePredicateDefinition = new PredicateDefinition(
			"Host=myhost.org");
	PredicateDefinition methodRoutePredicateDefinition = new PredicateDefinition(
			"Method=GET");
	PredicateDefinition testPredicateDefinition = new PredicateDefinition(
			"Test=value");
	testRouteDefinition.setPredicates(Arrays.asList(hostRoutePredicateDefinition,
			methodRoutePredicateDefinition, testPredicateDefinition));

	testClient.post()
			.uri("http://localhost:" + port + "/actuator/gateway/routes/test-route")
			.accept(MediaType.APPLICATION_JSON)
			.body(BodyInserters.fromValue(testRouteDefinition)).exchange()
			.expectStatus().isCreated();
}
 
Example #11
Source File: RouteDefinitionRouteLocator.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
private AsyncPredicate<ServerWebExchange> combinePredicates(
		RouteDefinition routeDefinition) {
	List<PredicateDefinition> predicates = routeDefinition.getPredicates();
	AsyncPredicate<ServerWebExchange> predicate = lookup(routeDefinition,
			predicates.get(0));

	for (PredicateDefinition andPredicate : predicates.subList(1,
			predicates.size())) {
		AsyncPredicate<ServerWebExchange> found = lookup(routeDefinition,
				andPredicate);
		predicate = predicate.and(found);
	}

	return predicate;
}
 
Example #12
Source File: GatewayDiscoveryClientAutoConfiguration.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
public static List<PredicateDefinition> initPredicates() {
	ArrayList<PredicateDefinition> definitions = new ArrayList<>();
	// TODO: add a predicate that matches the url at /serviceId?

	// add a predicate that matches the url at /serviceId/**
	PredicateDefinition predicate = new PredicateDefinition();
	predicate.setName(normalizeRoutePredicateName(PathRoutePredicateFactory.class));
	predicate.addArg(PATTERN_KEY, "'/'+serviceId+'/**'");
	definitions.add(predicate);
	return definitions;
}
 
Example #13
Source File: DynamicRouteServiceImpl.java    From spring-cloud-gateway-nacos with Apache License 2.0 5 votes vote down vote up
/**
 * spring:
 cloud:
 gateway:
 routes: #当访问http://localhost:8080/baidu,直接转发到https://www.baidu.com/
 - id: baidu_route
 uri: http://baidu.com:80/
 predicates:
 - Path=/baidu
 * @param args
 */

public static void main(String[] args) {
    GatewayRouteDefinition definition = new GatewayRouteDefinition();
    GatewayPredicateDefinition predicate = new GatewayPredicateDefinition();
    Map<String, String> predicateParams = new HashMap<>(8);
    definition.setId("jd_route");
    predicate.setName("Path");
    predicateParams.put("pattern", "/jd");
    predicate.setArgs(predicateParams);
    definition.setPredicates(Arrays.asList(predicate));
    String uri="http://www.jd.com";
    //URI uri = UriComponentsBuilder.fromHttpUrl("http://www.baidu.com").build().toUri();
    definition.setUri(uri);
    System.out.println("definition:"+JSON.toJSONString(definition));


    RouteDefinition definition1 = new RouteDefinition();
    PredicateDefinition predicate1 = new PredicateDefinition();
    Map<String, String> predicateParams1 = new HashMap<>(8);
    definition1.setId("baidu_route");
    predicate1.setName("Path");
    predicateParams1.put("pattern", "/baidu");
    predicate1.setArgs(predicateParams1);
    definition1.setPredicates(Arrays.asList(predicate1));
    URI uri1 = UriComponentsBuilder.fromHttpUrl("http://www.baidu.com").build().toUri();
    definition1.setUri(uri1);
    System.out.println("definition1:"+JSON.toJSONString(definition1));

}
 
Example #14
Source File: RouteDefinition.java    From spring-cloud-gateway with Apache License 2.0 4 votes vote down vote up
public List<PredicateDefinition> getPredicates() {
	return predicates;
}
 
Example #15
Source File: RouteDefinition.java    From spring-cloud-gateway with Apache License 2.0 4 votes vote down vote up
public void setPredicates(List<PredicateDefinition> predicates) {
	this.predicates = predicates;
}
 
Example #16
Source File: DiscoveryLocatorProperties.java    From spring-cloud-gateway with Apache License 2.0 4 votes vote down vote up
public void setPredicates(List<PredicateDefinition> predicates) {
	this.predicates = predicates;
}
 
Example #17
Source File: DiscoveryLocatorProperties.java    From spring-cloud-gateway with Apache License 2.0 4 votes vote down vote up
public List<PredicateDefinition> getPredicates() {
	return predicates;
}
 
Example #18
Source File: DynamicRouteConfigurationService.java    From wecube-platform with Apache License 2.0 4 votes vote down vote up
protected void buildRouteDefinition(String context, DynamicRouteItemInfo itemInfo) {
    RouteDefinition rd = new RouteDefinition();
    rd.setId(context + ROUTE_ID_SUFFIX);
    String urlStr = String.format("%s://%s:%s", itemInfo.getHttpScheme(), itemInfo.getHost(), itemInfo.getPort());
    URI uri = UriComponentsBuilder.fromHttpUrl(urlStr).build().toUri();
    rd.setUri(uri);

    PredicateDefinition pd = new PredicateDefinition();
    pd.setName("Path");
    Map<String, String> predicateParams = new HashMap<>(8);
    predicateParams.put("pattern", String.format("/%s/**", context));
    pd.setArgs(predicateParams);
    rd.setPredicates(Arrays.asList(pd));

    List<FilterDefinition> filters = new ArrayList<>();

    FilterDefinition fdDynamicRoute = new FilterDefinition();
    fdDynamicRoute.setName("DynamicRoute");
    fdDynamicRoute.addArg("enabled", "true");

    filters.add(fdDynamicRoute);

    if (dynamicRouteProperties.isEnableRetry()) {

        FilterDefinition fdRetry = new FilterDefinition();
        fdRetry.setName("ExRetry");
        fdRetry.addArg("retries", "10");
        fdRetry.addArg("series", "SERVER_ERROR");
        // fdRetry.addArg("statuses", "NOT_FOUND");
        fdRetry.addArg("methods", "GET,POST,PUT,DELETE");
        fdRetry.addArg("exceptions", "java.io.IOException,java.net.ConnectException");

        filters.add(fdRetry);
    }

    rd.setFilters(filters);

    add(rd);

    log.debug("### route added:{} {} {}", itemInfo.getContext(), itemInfo.getHost(), itemInfo.getPort());
}