org.springframework.cloud.gateway.filter.FilterDefinition Java Examples

The following examples show how to use org.springframework.cloud.gateway.filter.FilterDefinition. 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: 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 #2
Source File: GatewayControllerEndpointTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void testPostRouteWithNotExistingFilter() {

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

	FilterDefinition filterDefinition = new FilterDefinition(
			"NotExistingFilter=test-config");
	testRouteDefinition.setFilters(Collections.singletonList(filterDefinition));

	testClient.post()
			.uri("http://localhost:" + port + "/actuator/gateway/routes/test-route")
			.accept(MediaType.APPLICATION_JSON)
			.body(BodyInserters.fromValue(testRouteDefinition)).exchange()
			.expectStatus().isBadRequest();
}
 
Example #3
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 #4
Source File: GatewayDiscoveryClientAutoConfiguration.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
public static List<FilterDefinition> initFilters() {
	ArrayList<FilterDefinition> definitions = new ArrayList<>();

	// add a filter that removes /serviceId by default
	FilterDefinition filter = new FilterDefinition();
	filter.setName(normalizeFilterFactoryName(RewritePathGatewayFilterFactory.class));
	String regex = "'/' + serviceId + '/(?<remaining>.*)'";
	String replacement = "'/${remaining}'";
	filter.addArg(REGEXP_KEY, regex);
	filter.addArg(REPLACEMENT_KEY, replacement);
	definitions.add(filter);

	return definitions;
}
 
Example #5
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 #6
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 #7
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 #8
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 #9
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());
}
 
Example #10
Source File: DiscoveryLocatorProperties.java    From spring-cloud-gateway with Apache License 2.0 4 votes vote down vote up
public List<FilterDefinition> getFilters() {
	return filters;
}
 
Example #11
Source File: DiscoveryLocatorProperties.java    From spring-cloud-gateway with Apache License 2.0 4 votes vote down vote up
public void setFilters(List<FilterDefinition> filters) {
	this.filters = filters;
}
 
Example #12
Source File: GatewayProperties.java    From spring-cloud-gateway with Apache License 2.0 4 votes vote down vote up
public List<FilterDefinition> getDefaultFilters() {
	return defaultFilters;
}
 
Example #13
Source File: GatewayProperties.java    From spring-cloud-gateway with Apache License 2.0 4 votes vote down vote up
public void setDefaultFilters(List<FilterDefinition> defaultFilters) {
	this.defaultFilters = defaultFilters;
}
 
Example #14
Source File: RouteDefinitionRouteLocator.java    From spring-cloud-gateway with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
List<GatewayFilter> loadGatewayFilters(String id,
		List<FilterDefinition> filterDefinitions) {
	ArrayList<GatewayFilter> ordered = new ArrayList<>(filterDefinitions.size());
	for (int i = 0; i < filterDefinitions.size(); i++) {
		FilterDefinition definition = filterDefinitions.get(i);
		GatewayFilterFactory factory = this.gatewayFilterFactories
				.get(definition.getName());
		if (factory == null) {
			throw new IllegalArgumentException(
					"Unable to find GatewayFilterFactory with name "
							+ definition.getName());
		}
		if (logger.isDebugEnabled()) {
			logger.debug("RouteDefinition " + id + " applying filter "
					+ definition.getArgs() + " to " + definition.getName());
		}

		// @formatter:off
		Object configuration = this.configurationService.with(factory)
				.name(definition.getName())
				.properties(definition.getArgs())
				.eventFunction((bound, properties) -> new FilterArgsEvent(
						// TODO: why explicit cast needed or java compile fails
						RouteDefinitionRouteLocator.this, id, (Map<String, Object>) properties))
				.bind();
		// @formatter:on

		// some filters require routeId
		// TODO: is there a better place to apply this?
		if (configuration instanceof HasRouteId) {
			HasRouteId hasRouteId = (HasRouteId) configuration;
			hasRouteId.setRouteId(id);
		}

		GatewayFilter gatewayFilter = factory.apply(configuration);
		if (gatewayFilter instanceof Ordered) {
			ordered.add(gatewayFilter);
		}
		else {
			ordered.add(new OrderedGatewayFilter(gatewayFilter, i + 1));
		}
	}

	return ordered;
}
 
Example #15
Source File: RouteDefinition.java    From spring-cloud-gateway with Apache License 2.0 4 votes vote down vote up
public List<FilterDefinition> getFilters() {
	return filters;
}
 
Example #16
Source File: RouteDefinition.java    From spring-cloud-gateway with Apache License 2.0 4 votes vote down vote up
public void setFilters(List<FilterDefinition> filters) {
	this.filters = filters;
}