@Test // see INT-2011
 public void testAggregatorWithPojoReleaseStrategyAsCollection() {
   MessageChannel input =
       (MessageChannel) context.getBean("aggregatorWithPojoReleaseStrategyInputAsCollection");
   EventDrivenConsumer endpoint =
       (EventDrivenConsumer) context.getBean("aggregatorWithPojoReleaseStrategyAsCollection");
   ReleaseStrategy releaseStrategy =
       (ReleaseStrategy)
           new DirectFieldAccessor(new DirectFieldAccessor(endpoint).getPropertyValue("handler"))
               .getPropertyValue("releaseStrategy");
   Assert.assertTrue(releaseStrategy instanceof MethodInvokingReleaseStrategy);
   DirectFieldAccessor releaseStrategyAccessor =
       new DirectFieldAccessor(
           new DirectFieldAccessor(
                   new DirectFieldAccessor(releaseStrategy).getPropertyValue("adapter"))
               .getPropertyValue("delegate"));
   Object handlerMethods = releaseStrategyAccessor.getPropertyValue("handlerMethods");
   assertNull(handlerMethods);
   Object handlerMethod = releaseStrategyAccessor.getPropertyValue("handlerMethod");
   assertTrue(handlerMethod.toString().contains("checkCompleteness"));
   input.send(createMessage(1L, "correlationId", 4, 0, null));
   input.send(createMessage(2L, "correlationId", 4, 1, null));
   input.send(createMessage(3L, "correlationId", 4, 2, null));
   PollableChannel outputChannel = (PollableChannel) context.getBean("outputChannel");
   Message<?> reply = outputChannel.receive(0);
   Assert.assertNull(reply);
   input.send(createMessage(5L, "correlationId", 4, 3, null));
   reply = outputChannel.receive(0);
   Assert.assertNotNull(reply);
   assertEquals(11L, reply.getPayload());
 }
 @Test
 @SuppressWarnings("unchecked")
 public void testAggregatorWithPojoReleaseStrategy() {
   MessageChannel input =
       this.context.getBean("aggregatorWithPojoReleaseStrategyInput", MessageChannel.class);
   EventDrivenConsumer endpoint =
       this.context.getBean("aggregatorWithPojoReleaseStrategy", EventDrivenConsumer.class);
   ReleaseStrategy releaseStrategy =
       TestUtils.getPropertyValue(endpoint, "handler.releaseStrategy", ReleaseStrategy.class);
   Assert.assertTrue(releaseStrategy instanceof MethodInvokingReleaseStrategy);
   MessagingMethodInvokerHelper<Long> methodInvokerHelper =
       TestUtils.getPropertyValue(
           releaseStrategy, "adapter.delegate", MessagingMethodInvokerHelper.class);
   Object handlerMethods = TestUtils.getPropertyValue(methodInvokerHelper, "handlerMethods");
   assertNull(handlerMethods);
   Object handlerMethod = TestUtils.getPropertyValue(methodInvokerHelper, "handlerMethod");
   assertTrue(handlerMethod.toString().contains("checkCompleteness"));
   input.send(createMessage(1L, "correlationId", 4, 0, null));
   input.send(createMessage(2L, "correlationId", 4, 1, null));
   input.send(createMessage(3L, "correlationId", 4, 2, null));
   PollableChannel outputChannel = (PollableChannel) context.getBean("outputChannel");
   Message<?> reply = outputChannel.receive(0);
   Assert.assertNull(reply);
   input.send(createMessage(5L, "correlationId", 4, 3, null));
   reply = outputChannel.receive(0);
   Assert.assertNotNull(reply);
   assertEquals(11L, reply.getPayload());
 }
  @Test
  @RedisAvailable
  @SuppressWarnings("unchecked")
  public void testInt3014ExpectMessageTrue() throws Exception {

    final String queueName = "si.test.redisQueueInboundChannelAdapterTests2";

    RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
    redisTemplate.setConnectionFactory(this.connectionFactory);
    redisTemplate.setEnableDefaultSerializer(false);
    redisTemplate.setKeySerializer(new StringRedisSerializer());
    redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
    redisTemplate.afterPropertiesSet();

    Message<?> message = MessageBuilder.withPayload("testing").build();

    redisTemplate.boundListOps(queueName).leftPush(message);

    redisTemplate.boundListOps(queueName).leftPush("test");

    PollableChannel channel = new QueueChannel();

    PollableChannel errorChannel = new QueueChannel();

    RedisQueueMessageDrivenEndpoint endpoint =
        new RedisQueueMessageDrivenEndpoint(queueName, this.connectionFactory);
    endpoint.setBeanFactory(Mockito.mock(BeanFactory.class));
    endpoint.setExpectMessage(true);
    endpoint.setOutputChannel(channel);
    endpoint.setErrorChannel(errorChannel);
    endpoint.setReceiveTimeout(1000);
    endpoint.afterPropertiesSet();
    endpoint.start();

    Message<Object> receive = (Message<Object>) channel.receive(2000);
    assertNotNull(receive);

    assertEquals(message, receive);

    receive = (Message<Object>) errorChannel.receive(2000);
    assertNotNull(receive);
    assertThat(receive, Matchers.instanceOf(ErrorMessage.class));
    assertThat(receive.getPayload(), Matchers.instanceOf(MessagingException.class));
    assertThat(
        ((Exception) receive.getPayload()).getMessage(),
        Matchers.containsString("Deserialization of Message failed."));
    assertThat(
        ((Exception) receive.getPayload()).getCause(),
        Matchers.instanceOf(ClassCastException.class));
    assertThat(
        ((Exception) receive.getPayload()).getCause().getMessage(),
        Matchers.containsString(
            "java.lang.String cannot be cast to org.springframework.messaging.Message"));

    endpoint.stop();
  }
 @Test
 public void checkMessageRouting() {
   context.start();
   Message<?> message = new GenericMessage<Integer>(1);
   channel.send(message);
   PollableChannel chanel1 = (PollableChannel) context.getBean("channel1");
   PollableChannel chanel2 = (PollableChannel) context.getBean("channel2");
   assertTrue(chanel1.receive(0).getPayload().equals(1));
   assertTrue(chanel2.receive(0).getPayload().equals(1));
 }
 @Test
 public void messageDrivenAdapterWithMessageConverter() {
   ClassPathXmlApplicationContext context =
       new ClassPathXmlApplicationContext("jmsInboundWithMessageConverter.xml", this.getClass());
   PollableChannel output = (PollableChannel) context.getBean("output2");
   Message<?> message = output.receive(timeoutOnReceive);
   assertNotNull("message should not be null", message);
   assertEquals("converted-test", message.getPayload());
   context.stop();
 }
 @Test
 public void adapterWithMessageSelector() {
   ClassPathXmlApplicationContext context =
       new ClassPathXmlApplicationContext("jmsInboundWithMessageSelector.xml", this.getClass());
   PollableChannel output = (PollableChannel) context.getBean("output1");
   Message<?> message = output.receive(timeoutOnReceive);
   assertNotNull("message should not be null", message);
   assertEquals("test [with selector: TestProperty = 'foo']", message.getPayload());
   context.stop();
 }
 @Test
 public void simpleDynamicRouter() {
   context.start();
   Message<?> message = new GenericMessage<Integer>(1);
   simpleDynamicInput.send(message);
   PollableChannel chanel1 = (PollableChannel) context.getBean("channel1");
   PollableChannel chanel2 = (PollableChannel) context.getBean("channel2");
   assertTrue(chanel1.receive(0).getPayload().equals(1));
   assertNull(chanel2.receive(0));
 }
 @Test
 public void adapterWithConnectionFactoryAndDestinationName() {
   ClassPathXmlApplicationContext context =
       new ClassPathXmlApplicationContext(
           "jmsInboundWithConnectionFactoryAndDestinationName.xml", this.getClass());
   PollableChannel output = (PollableChannel) context.getBean("output");
   Message<?> message = output.receive(timeoutOnReceive);
   assertNotNull("message should not be null", message);
   assertEquals("polling-test", message.getPayload());
   context.stop();
 }
 @Test
 public void methodInvokingSourceNotStarted() {
   String beanName = "methodInvokingSource";
   PollableChannel channel = (PollableChannel) this.applicationContext.getBean("queueChannel");
   TestBean testBean = (TestBean) this.applicationContext.getBean("testBean");
   testBean.store("source test");
   Object adapter = this.applicationContext.getBean(beanName);
   assertNotNull(adapter);
   assertTrue(adapter instanceof SourcePollingChannelAdapter);
   Message<?> message = channel.receive(100);
   assertNull(message);
 }
 @Test
 public void adapterWithHeaderMapper() {
   ClassPathXmlApplicationContext context =
       new ClassPathXmlApplicationContext("jmsInboundWithHeaderMapper.xml", this.getClass());
   PollableChannel output = (PollableChannel) context.getBean("output");
   Message<?> message = output.receive(timeoutOnReceive);
   assertNotNull("message should not be null", message);
   assertEquals("polling-test", message.getPayload());
   assertEquals("foo", message.getHeaders().get("testProperty"));
   assertEquals(new Integer(123), message.getHeaders().get("testAttribute"));
   context.stop();
 }
 @Test
 public void noSelectorMatchRouter() {
   context.start();
   Message<?> message = new GenericMessage<Integer>(1);
   noSelectorMatchInput.send(message);
   PollableChannel chanel1 = (PollableChannel) context.getBean("channel1");
   PollableChannel chanel2 = (PollableChannel) context.getBean("channel2");
   Message<?> output = chanel1.receive(0);
   assertNotNull(output);
   assertTrue(output.getPayload().equals(1));
   assertNull(chanel2.receive(0));
 }
 @Test
 public void testGatewayWithMessageConverter() {
   ClassPathXmlApplicationContext context =
       new ClassPathXmlApplicationContext("jmsGatewayWithMessageConverter.xml", this.getClass());
   PollableChannel channel = (PollableChannel) context.getBean("requestChannel");
   JmsMessageDrivenEndpoint gateway = (JmsMessageDrivenEndpoint) context.getBean("jmsGateway");
   assertEquals(JmsMessageDrivenEndpoint.class, gateway.getClass());
   context.start();
   Message<?> message = channel.receive(3000);
   assertNotNull("message should not be null", message);
   assertEquals("converted-test-message", message.getPayload());
   context.stop();
 }
  @Test
  public void integrationTest() throws Exception {
    TestingUtilities.waitListening(serverCf, null);
    outbound.send(new GenericMessage<String>("Hello, world!"));
    Message<?> m = inbound.receive(1000);
    assertNotNull(m);
    String connectionId = m.getHeaders().get(IpHeaders.CONNECTION_ID, String.class);

    // assert we use the same connection from the pool
    outbound.send(new GenericMessage<String>("Hello, world!"));
    m = inbound.receive(1000);
    assertNotNull(m);
    assertEquals(connectionId, m.getHeaders().get(IpHeaders.CONNECTION_ID, String.class));
  }
 @Test
 public void testSimpleJavaBeanAggregator() {
   List<Message<?>> outboundMessages = new ArrayList<Message<?>>();
   MessageChannel input =
       (MessageChannel) context.getBean("aggregatorWithReferenceAndMethodInput");
   outboundMessages.add(createMessage(1L, "id1", 3, 1, null));
   outboundMessages.add(createMessage(2L, "id1", 3, 3, null));
   outboundMessages.add(createMessage(3L, "id1", 3, 2, null));
   outboundMessages.forEach(input::send);
   PollableChannel outputChannel = (PollableChannel) context.getBean("outputChannel");
   Message<?> response = outputChannel.receive(10);
   Assert.assertEquals(6L, response.getPayload());
   Object mbf = context.getBean(IntegrationUtils.INTEGRATION_MESSAGE_BUILDER_FACTORY_BEAN_NAME);
   Object handler = context.getBean("aggregatorWithReferenceAndMethod.handler");
   assertSame(mbf, TestUtils.getPropertyValue(handler, "outputProcessor.messageBuilderFactory"));
 }
 @Test
 public void adapterWithJmsTemplate() {
   ClassPathXmlApplicationContext context =
       new ClassPathXmlApplicationContext("jmsInboundWithJmsTemplate.xml", this.getClass());
   PollableChannel output = (PollableChannel) context.getBean("output");
   Message<?> message = output.receive(timeoutOnReceive);
   MessageHistory history = MessageHistory.read(message);
   assertNotNull(history);
   Properties componentHistoryRecord =
       TestUtils.locateComponentInHistory(history, "inboundAdapter", 0);
   assertNotNull(componentHistoryRecord);
   assertEquals("jms:inbound-channel-adapter", componentHistoryRecord.get("type"));
   assertNotNull("message should not be null", message);
   assertEquals("polling-test", message.getPayload());
   context.stop();
 }
  @Test
  public void testMessageSourceUniqueIds() {
    PollableChannel channel1 =
        this.applicationContext.getBean("channelAdapter1Channel", PollableChannel.class);
    PollableChannel channel2 =
        this.applicationContext.getBean("channelAdapter2Channel", PollableChannel.class);

    for (int i = 0; i < 10; i++) {
      Message<?> message = channel1.receive(5000);
      assertNotNull(message);
      assertEquals(i + 1, message.getPayload());
      message = channel2.receive(5000);
      assertNotNull(message);
      assertEquals(i + 1, message.getPayload());
    }
  }
 @Test
 public void nodeResult() {
   this.nodeInput.send(message);
   Object payload = output.receive(0).getPayload();
   assertTrue(payload instanceof Node);
   Node node = (Node) payload;
   assertEquals("42", node.getTextContent());
 }
 @Test
 @SuppressWarnings("unchecked")
 public void nodeListResult() {
   this.nodeListInput.send(message);
   Object payload = output.receive(0).getPayload();
   assertTrue(List.class.isAssignableFrom(payload.getClass()));
   List<Node> nodeList = (List<Node>) payload;
   assertEquals(3, nodeList.size());
 }
 @Test
 public void methodInvokingSourceStoppedByApplicationContextInner() {
   String beanName = "methodInvokingSource";
   PollableChannel channel =
       (PollableChannel) this.applicationContextInner.getBean("queueChannel");
   //		TestBean testBean = (TestBean) this.applicationContextInner.getBean("testBean");
   //		testBean.store("source test");
   Object adapter = this.applicationContextInner.getBean(beanName);
   assertNotNull(adapter);
   assertTrue(adapter instanceof SourcePollingChannelAdapter);
   this.applicationContextInner.start();
   Message<?> message = channel.receive(10000);
   assertNotNull(message);
   // assertEquals("source test", testBean.getMessage());
   this.applicationContextInner.stop();
   message = channel.receive(100);
   assertNull(message);
 }
  @Test
  public void testMessageSourceRef() {
    PollableChannel channel =
        this.applicationContext.getBean("messageSourceRefChannel", PollableChannel.class);

    Message<?> message = channel.receive(5000);
    assertNotNull(message);
    assertEquals("test", message.getPayload());

    MessageSource<?> testMessageSource =
        this.applicationContext.getBean("testMessageSource", MessageSource.class);
    SourcePollingChannelAdapter adapterWithMessageSourceRef =
        this.applicationContext.getBean(
            "adapterWithMessageSourceRef", SourcePollingChannelAdapter.class);
    MessageSource<?> source =
        TestUtils.getPropertyValue(adapterWithMessageSourceRef, "source", MessageSource.class);
    assertSame(testMessageSource, source);
  }
 @Test
 public void adapterWithMessageSelector() {
   ClassPathXmlApplicationContext context =
       new ClassPathXmlApplicationContext("jmsInboundWithMessageSelector.xml", this.getClass());
   PollableChannel output = (PollableChannel) context.getBean("output2");
   Message<?> message = output.receive(timeoutOnReceive);
   MessageHistory history = MessageHistory.read(message);
   assertNotNull(history);
   Properties componentHistoryRecord =
       TestUtils.locateComponentInHistory(history, "messageDrivenAdapter", 0);
   assertNotNull(componentHistoryRecord);
   JmsMessageDrivenEndpoint endpoint =
       context.getBean("messageDrivenAdapter", JmsMessageDrivenEndpoint.class);
   assertEquals("jms:message-driven-channel-adapter", componentHistoryRecord.get("type"));
   assertNotNull("message should not be null", message);
   assertEquals("test [with selector: TestProperty = 'foo']", message.getPayload());
   endpoint.stop();
   context.close();
 }
 @Test
 public void methodInvokingSourceWithHeaders() {
   String beanName = "methodInvokingSourceWithHeaders";
   PollableChannel channel =
       (PollableChannel) this.applicationContext.getBean("queueChannelForHeadersTest");
   TestBean testBean = (TestBean) this.applicationContext.getBean("testBean");
   testBean.store("source test");
   Object adapter = this.applicationContext.getBean(beanName);
   assertNotNull(adapter);
   assertTrue(adapter instanceof SourcePollingChannelAdapter);
   ((SourcePollingChannelAdapter) adapter).start();
   Message<?> message = channel.receive(10000);
   ((SourcePollingChannelAdapter) adapter).stop();
   assertNotNull(message);
   assertEquals("source test", testBean.getMessage());
   assertEquals("source test", message.getPayload());
   assertEquals("ABC", message.getHeaders().get("foo"));
   assertEquals(123, message.getHeaders().get("bar"));
 }
  @Test
  @RedisAvailable
  @SuppressWarnings("unchecked")
  public void testInt3014Default() throws Exception {

    String queueName = "si.test.redisQueueInboundChannelAdapterTests";

    RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
    redisTemplate.setConnectionFactory(this.connectionFactory);
    redisTemplate.setEnableDefaultSerializer(false);
    redisTemplate.setKeySerializer(new StringRedisSerializer());
    redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
    redisTemplate.afterPropertiesSet();

    String payload = "testing";

    redisTemplate.boundListOps(queueName).leftPush(payload);

    Date payload2 = new Date();

    redisTemplate.boundListOps(queueName).leftPush(payload2);

    PollableChannel channel = new QueueChannel();

    RedisQueueMessageDrivenEndpoint endpoint =
        new RedisQueueMessageDrivenEndpoint(queueName, this.connectionFactory);
    endpoint.setBeanFactory(Mockito.mock(BeanFactory.class));
    endpoint.setOutputChannel(channel);
    endpoint.setReceiveTimeout(1000);
    endpoint.afterPropertiesSet();
    endpoint.start();

    Message<Object> receive = (Message<Object>) channel.receive(2000);
    assertNotNull(receive);
    assertEquals(payload, receive.getPayload());

    receive = (Message<Object>) channel.receive(2000);
    assertNotNull(receive);
    assertEquals(payload2, receive.getPayload());

    endpoint.stop();
  }
 @Test
 public void testGatewayWithConnectionFactoryAndDestination() {
   ClassPathXmlApplicationContext context =
       new ClassPathXmlApplicationContext(
           "jmsGatewayWithConnectionFactoryAndDestination.xml", this.getClass());
   PollableChannel channel = (PollableChannel) context.getBean("requestChannel");
   JmsMessageDrivenEndpoint gateway = (JmsMessageDrivenEndpoint) context.getBean("jmsGateway");
   assertEquals(JmsMessageDrivenEndpoint.class, gateway.getClass());
   context.start();
   Message<?> message = channel.receive(3000);
   MessageHistory history = MessageHistory.read(message);
   assertNotNull(history);
   Properties componentHistoryRecord =
       TestUtils.locateComponentInHistory(history, "jmsGateway", 0);
   assertNotNull(componentHistoryRecord);
   assertEquals("jms:inbound-gateway", componentHistoryRecord.get("type"));
   assertNotNull("message should not be null", message);
   assertEquals("message-driven-test", message.getPayload());
   context.stop();
 }
  @Test
  public void gatewayIntegrationTest() throws Exception {
    final List<String> connectionIds = new ArrayList<String>();
    final AtomicBoolean okToRun = new AtomicBoolean(true);
    Executors.newSingleThreadExecutor()
        .execute(
            new Runnable() {
              @Override
              public void run() {
                while (okToRun.get()) {
                  Message<?> m = inbound.receive(1000);
                  if (m != null) {
                    connectionIds.add((String) m.getHeaders().get(IpHeaders.CONNECTION_ID));
                    replies.send(
                        MessageBuilder.withPayload("foo:" + new String((byte[]) m.getPayload()))
                            .copyHeaders(m.getHeaders())
                            .build());
                  }
                }
              }
            });
    TestingUtilities.waitListening(serverCf, null);
    toGateway.send(new GenericMessage<String>("Hello, world!"));
    Message<?> m = fromGateway.receive(1000);
    assertNotNull(m);
    assertEquals("foo:" + "Hello, world!", new String((byte[]) m.getPayload()));

    // wait a short time to allow the connection to be returned to the pool
    Thread.sleep(1000);

    // assert we use the same connection from the pool
    toGateway.send(new GenericMessage<String>("Hello, world2!"));
    m = fromGateway.receive(1000);
    assertNotNull(m);
    assertEquals("foo:" + "Hello, world2!", new String((byte[]) m.getPayload()));

    assertEquals(2, connectionIds.size());
    assertEquals(connectionIds.get(0), connectionIds.get(1));

    okToRun.set(false);
  }
  @Test // INT-1029
  public void testHttpOutboundGatewayWithinChain() throws IOException, URISyntaxException {
    ApplicationContext ctx =
        new ClassPathXmlApplicationContext(
            "HttpOutboundWithinChainTests-context.xml", this.getClass());
    MessageChannel channel = ctx.getBean("httpOutboundGatewayWithinChain", MessageChannel.class);
    RestTemplate restTemplate = ctx.getBean("restTemplate", RestTemplate.class);
    channel.send(MessageBuilder.withPayload("test").build());

    PollableChannel output = ctx.getBean("replyChannel", PollableChannel.class);
    Message<?> receive = output.receive();
    assertEquals(HttpStatus.OK, ((ResponseEntity<?>) receive.getPayload()).getStatusCode());
    Mockito.verify(restTemplate)
        .exchange(
            Mockito.eq(
                new URI(
                    "http://localhost:51235/%2f/testApps?param=http%20Outbound%20Gateway%20Within%20Chain")),
            Mockito.eq(HttpMethod.POST),
            Mockito.any(HttpEntity.class),
            Mockito.eq(new ParameterizedTypeReference<List<String>>() {}));
  }
  private void doTest(String config, String channelName, String monitor) throws Exception {

    ClassPathXmlApplicationContext context = createContext(config, channelName);

    try {

      int before = service.getCounter();
      channel.receive(1000L);
      channel.receive(1000L);
      assertTrue(before < service.getCounter());

      int count = exporter.getSourceMessageCount(monitor);
      assertTrue("No statistics for input channel", count > 0);

    } finally {
      context.close();
    }
  }
 @Test
 public void testWithErrorChannel() throws Exception {
   assertSame(this.errors, TestUtils.getPropertyValue(this.withErrorChannel, "errorChannel"));
   service.n = 0;
   MqttPahoMessageHandler adapter =
       new MqttPahoMessageHandler("tcp://localhost:1883", "si-test-out");
   adapter.setDefaultTopic("mqtt-fooEx2");
   adapter.setBeanFactory(mock(BeanFactory.class));
   adapter.afterPropertiesSet();
   adapter.start();
   adapter.handleMessage(new GenericMessage<String>("foo"));
   service.barrier.await(10, TimeUnit.SECONDS);
   service.barrier.reset();
   adapter.handleMessage(new GenericMessage<String>("foo"));
   service.barrier.await(10, TimeUnit.SECONDS);
   assertNotNull(errors.receive(10000));
   service.barrier.reset();
   adapter.stop();
 }
 @Test
 public void customConverter() {
   this.customConverterInput.send(message);
   assertEquals("custom", output.receive(0).getPayload());
 }
 @Test
 public void expressionRef() {
   this.expressionRefInput.send(message);
   assertEquals(new Double(84), output.receive(0).getPayload());
 }