Search in sources :

Example 1 with Tuple

use of org.springframework.tuple.Tuple in project spring-cloud-stream by spring-cloud.

the class ContentTypeTests method testSendTuple.

@Test
public void testSendTuple() throws Exception {
    try (ConfigurableApplicationContext context = SpringApplication.run(SourceApplication.class, "--server.port=0", "--spring.jmx.enabled=false", "--spring.cloud.stream.bindings.output.contentType=application/x-spring-tuple")) {
        MessageCollector collector = context.getBean(MessageCollector.class);
        Source source = context.getBean(Source.class);
        Tuple tuple = TupleBuilder.tuple().of("foo", "bar");
        source.output().send(MessageBuilder.withPayload(tuple).build());
        Message<byte[]> message = (Message<byte[]>) collector.forChannel(source.output()).poll(1, TimeUnit.SECONDS);
        assertThat(message.getHeaders().get(MessageHeaders.CONTENT_TYPE, MimeType.class).includes(MessageConverterUtils.X_SPRING_TUPLE));
        assertThat(TupleBuilder.fromString(new String(message.getPayload()))).isEqualTo(tuple);
    }
}
Also used : ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) Message(org.springframework.messaging.Message) MessageCollector(org.springframework.cloud.stream.test.binder.MessageCollector) Source(org.springframework.cloud.stream.messaging.Source) Tuple(org.springframework.tuple.Tuple) Test(org.junit.Test)

Example 2 with Tuple

use of org.springframework.tuple.Tuple in project spring-cloud-gateway by spring-cloud.

the class RouteDefinitionRouteLocatorTests method testGetTupleWithSpel.

@Test
public void testGetTupleWithSpel() {
    parser = new SpelExpressionParser();
    ShortcutConfigurable shortcutConfigurable = new ShortcutConfigurable() {

        @Override
        public List<String> shortcutFieldOrder() {
            return Arrays.asList("bean", "arg1");
        }
    };
    Map<String, String> args = new HashMap<>();
    args.put("bean", "#{@foo}");
    args.put("arg1", "val1");
    Tuple tuple = RouteDefinitionRouteLocator.getTuple(shortcutConfigurable, args, parser, this.beanFactory);
    assertThat(tuple).isNotNull();
    assertThat(tuple.getValue("bean", Integer.class)).isEqualTo(42);
    assertThat(tuple.getString("arg1")).isEqualTo("val1");
}
Also used : SpelExpressionParser(org.springframework.expression.spel.standard.SpelExpressionParser) HashMap(java.util.HashMap) ShortcutConfigurable(org.springframework.cloud.gateway.support.ShortcutConfigurable) Tuple(org.springframework.tuple.Tuple) Test(org.junit.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Example 3 with Tuple

use of org.springframework.tuple.Tuple in project spring-cloud-stream by spring-cloud.

the class TupleJsonMessageConverter method convertToInternal.

@Override
protected Object convertToInternal(Object payload, MessageHeaders headers, Object conversionHint) {
    Tuple t = (Tuple) payload;
    String json;
    if (this.prettyPrint) {
        try {
            Object tmp = this.objectMapper.readValue(t.toString(), Object.class);
            json = this.objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(tmp);
        } catch (IOException e) {
            this.logger.error(e.getMessage(), e);
            return null;
        }
    } else {
        json = t.toString();
    }
    return json.getBytes();
}
Also used : IOException(java.io.IOException) Tuple(org.springframework.tuple.Tuple)

Example 4 with Tuple

use of org.springframework.tuple.Tuple in project spring-cloud-gateway by spring-cloud.

the class RouteDefinitionRouteLocator method getTuple.

@SuppressWarnings("Duplicates")
// TODO: remove after Tuple is removed
@Deprecated
static /* for testing */
Tuple getTuple(ShortcutConfigurable shortcutConf, Map<String, String> args, SpelExpressionParser parser, BeanFactory beanFactory) {
    TupleBuilder builder = TupleBuilder.tuple();
    List<String> argNames = shortcutConf.shortcutFieldOrder();
    if (!argNames.isEmpty()) {
        // ensure size is the same for key replacement later
        if (shortcutConf.validateFieldsExist() && args.size() != argNames.size()) {
            throw new IllegalArgumentException("Wrong number of arguments. Expected " + argNames + " " + argNames + ". Found " + args.size() + " " + args + "'");
        }
    }
    int entryIdx = 0;
    for (Map.Entry<String, String> entry : args.entrySet()) {
        String key = normalizeKey(entry.getKey(), entryIdx, shortcutConf, args);
        Object value = getValue(parser, beanFactory, entry.getValue());
        builder.put(key, value);
        entryIdx++;
    }
    Tuple tuple = builder.build();
    if (shortcutConf.validateFieldsExist()) {
        for (String name : argNames) {
            if (!tuple.hasFieldName(name)) {
                throw new IllegalArgumentException("Missing argument '" + name + "'. Given " + tuple);
            }
        }
    }
    return tuple;
}
Also used : TupleBuilder(org.springframework.tuple.TupleBuilder) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) Tuple(org.springframework.tuple.Tuple)

Example 5 with Tuple

use of org.springframework.tuple.Tuple in project spring-cloud-gateway by spring-cloud.

the class RouteDefinitionRouteLocator method loadGatewayFilters.

@SuppressWarnings("unchecked")
private List<GatewayFilter> loadGatewayFilters(String id, List<FilterDefinition> filterDefinitions) {
    List<GatewayFilter> filters = filterDefinitions.stream().map(definition -> {
        GatewayFilterFactory factory = this.gatewayFilterFactories.get(definition.getName());
        if (factory == null) {
            throw new IllegalArgumentException("Unable to find GatewayFilterFactory with name " + definition.getName());
        }
        Map<String, String> args = definition.getArgs();
        if (logger.isDebugEnabled()) {
            logger.debug("RouteDefinition " + id + " applying filter " + args + " to " + definition.getName());
        }
        if (factory.isConfigurable()) {
            Map<String, Object> properties = factory.shortcutType().normalize(args, factory, this.parser, this.beanFactory);
            Object configuration = factory.newConfig();
            ConfigurationUtils.bind(configuration, properties, factory.shortcutFieldPrefix(), definition.getName(), validator);
            GatewayFilter gatewayFilter = factory.apply(configuration);
            if (this.publisher != null) {
                this.publisher.publishEvent(new FilterArgsEvent(this, id, properties));
            }
            return gatewayFilter;
        } else {
            Tuple tuple = getTuple(factory, args, this.parser, this.beanFactory);
            return factory.apply(tuple);
        }
    }).collect(Collectors.toList());
    ArrayList<GatewayFilter> ordered = new ArrayList<>(filters.size());
    for (int i = 0; i < filters.size(); i++) {
        ordered.add(new OrderedGatewayFilter(filters.get(i), i + 1));
    }
    return ordered;
}
Also used : ShortcutConfigurable(org.springframework.cloud.gateway.support.ShortcutConfigurable) Validator(org.springframework.validation.Validator) TupleBuilder(org.springframework.tuple.TupleBuilder) RoutePredicateFactory(org.springframework.cloud.gateway.handler.predicate.RoutePredicateFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) HashMap(java.util.HashMap) OrderedGatewayFilter(org.springframework.cloud.gateway.filter.OrderedGatewayFilter) FilterArgsEvent(org.springframework.cloud.gateway.event.FilterArgsEvent) PredicateArgsEvent(org.springframework.cloud.gateway.event.PredicateArgsEvent) ArrayList(java.util.ArrayList) ServerWebExchange(org.springframework.web.server.ServerWebExchange) LinkedHashMap(java.util.LinkedHashMap) BeanFactoryAware(org.springframework.beans.factory.BeanFactoryAware) Map(java.util.Map) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) ApplicationEventPublisherAware(org.springframework.context.ApplicationEventPublisherAware) GatewayProperties(org.springframework.cloud.gateway.config.GatewayProperties) GatewayFilterFactory(org.springframework.cloud.gateway.filter.factory.GatewayFilterFactory) ShortcutConfigurable.getValue(org.springframework.cloud.gateway.support.ShortcutConfigurable.getValue) Predicate(java.util.function.Predicate) FilterDefinition(org.springframework.cloud.gateway.filter.FilterDefinition) BeansException(org.springframework.beans.BeansException) Collectors(java.util.stream.Collectors) PredicateDefinition(org.springframework.cloud.gateway.handler.predicate.PredicateDefinition) Flux(reactor.core.publisher.Flux) List(java.util.List) ConfigurationUtils(org.springframework.cloud.gateway.support.ConfigurationUtils) Tuple(org.springframework.tuple.Tuple) BeanFactory(org.springframework.beans.factory.BeanFactory) ShortcutConfigurable.normalizeKey(org.springframework.cloud.gateway.support.ShortcutConfigurable.normalizeKey) GatewayFilter(org.springframework.cloud.gateway.filter.GatewayFilter) Log(org.apache.commons.logging.Log) SpelExpressionParser(org.springframework.expression.spel.standard.SpelExpressionParser) LogFactory(org.apache.commons.logging.LogFactory) AnnotationAwareOrderComparator(org.springframework.core.annotation.AnnotationAwareOrderComparator) ArrayList(java.util.ArrayList) FilterArgsEvent(org.springframework.cloud.gateway.event.FilterArgsEvent) OrderedGatewayFilter(org.springframework.cloud.gateway.filter.OrderedGatewayFilter) GatewayFilterFactory(org.springframework.cloud.gateway.filter.factory.GatewayFilterFactory) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) OrderedGatewayFilter(org.springframework.cloud.gateway.filter.OrderedGatewayFilter) GatewayFilter(org.springframework.cloud.gateway.filter.GatewayFilter) Tuple(org.springframework.tuple.Tuple)

Aggregations

Tuple (org.springframework.tuple.Tuple)7 HashMap (java.util.HashMap)3 Test (org.junit.Test)3 LinkedHashMap (java.util.LinkedHashMap)2 Map (java.util.Map)2 Autowired (org.springframework.beans.factory.annotation.Autowired)2 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)2 PredicateArgsEvent (org.springframework.cloud.gateway.event.PredicateArgsEvent)2 GatewayFilter (org.springframework.cloud.gateway.filter.GatewayFilter)2 TupleBuilder (org.springframework.tuple.TupleBuilder)2 IOException (java.io.IOException)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1 Predicate (java.util.function.Predicate)1 Collectors (java.util.stream.Collectors)1 Log (org.apache.commons.logging.Log)1 LogFactory (org.apache.commons.logging.LogFactory)1 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)1 RunWith (org.junit.runner.RunWith)1 Mockito.when (org.mockito.Mockito.when)1