List of usage examples for org.springframework.integration.channel QueueChannel receive
@Override @Nullable public Message<?> receive(long timeout)
From source file:org.springframework.integration.mail.ImapMailReceiverTests.java
public void testIdleWithServerGuts(ImapMailReceiver receiver, boolean mapped, boolean simple) throws Exception { imapIdleServer.resetServer();/*www . jav a 2 s . c om*/ Properties mailProps = new Properties(); mailProps.put("mail.debug", "true"); mailProps.put("mail.imap.connectionpool.debug", "true"); receiver.setJavaMailProperties(mailProps); receiver.setMaxFetchSize(1); receiver.setShouldDeleteMessages(false); receiver.setShouldMarkMessagesAsRead(true); receiver.setCancelIdleInterval(8); ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); setUpScheduler(receiver, taskScheduler); receiver.setUserFlag("testSIUserFlag"); receiver.afterPropertiesSet(); Log logger = spy(TestUtils.getPropertyValue(receiver, "logger", Log.class)); new DirectFieldAccessor(receiver).setPropertyValue("logger", logger); ImapIdleChannelAdapter adapter = new ImapIdleChannelAdapter(receiver); QueueChannel channel = new QueueChannel(); adapter.setOutputChannel(channel); adapter.setTaskScheduler(taskScheduler); adapter.start(); if (!mapped) { @SuppressWarnings("unchecked") org.springframework.messaging.Message<MimeMessage> received = (org.springframework.messaging.Message<MimeMessage>) channel .receive(10000); assertNotNull(received); assertNotNull(received.getPayload().getReceivedDate()); assertTrue(received.getPayload().getLineCount() > -1); if (simple) { assertThat(received.getPayload().getContent(), equalTo(TestMailServer.MailServer.MailHandler.BODY + "\r\n")); } else { assertThat(received.getPayload().getContent(), equalTo(TestMailServer.MailServer.MailHandler.MESSAGE + "\r\n")); } } else { org.springframework.messaging.Message<?> received = channel.receive(10000); assertNotNull(received); assertNotNull(received.getHeaders().get(MailHeaders.RAW_HEADERS)); assertThat((String) received.getHeaders().get(MailHeaders.CONTENT_TYPE), equalTo("TEXT/PLAIN; charset=ISO-8859-1")); assertThat((String) received.getHeaders().get(MessageHeaders.CONTENT_TYPE), equalTo("TEXT/PLAIN; charset=ISO-8859-1")); assertThat((String) received.getHeaders().get(MailHeaders.FROM), equalTo("Bar <bar@baz>")); assertThat(((String[]) received.getHeaders().get(MailHeaders.TO))[0], equalTo("Foo <foo@bar>")); assertThat((String) received.getHeaders().get(MailHeaders.SUBJECT), equalTo("Test Email")); if (simple) { assertThat(received.getPayload(), equalTo(TestMailServer.MailServer.MailHandler.BODY + "\r\n")); } else { assertThat(received.getPayload(), equalTo(TestMailServer.MailServer.MailHandler.MESSAGE + "\r\n")); } } assertNotNull(channel.receive(10000)); // new message after idle assertNull(channel.receive(10000)); // no new message after second and third idle verify(logger).debug("Canceling IDLE"); taskScheduler.shutdown(); assertTrue(imapIdleServer.assertReceived("storeUserFlag")); }
From source file:org.springframework.integration.mail.ImapMailReceiverTests.java
@Test public void testIdleChannelAdapterException() throws Exception { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext( "ImapIdleChannelAdapterParserTests-context.xml", ImapIdleChannelAdapterParserTests.class); ImapIdleChannelAdapter adapter = context.getBean("simpleAdapter", ImapIdleChannelAdapter.class); //ImapMailReceiver receiver = (ImapMailReceiver) TestUtils.getPropertyValue(adapter, "mailReceiver"); DirectChannel channel = new DirectChannel(); channel.subscribe(new AbstractReplyProducingMessageHandler() { @Override/* w ww . j a v a2 s .c o m*/ protected Object handleRequestMessage(org.springframework.messaging.Message<?> requestMessage) { throw new RuntimeException("Failed"); } }); adapter.setOutputChannel(channel); QueueChannel errorChannel = new QueueChannel(); adapter.setErrorChannel(errorChannel); AbstractMailReceiver receiver = new ImapMailReceiver(); receiver = spy(receiver); receiver.setBeanFactory(mock(BeanFactory.class)); receiver.afterPropertiesSet(); Field folderField = AbstractMailReceiver.class.getDeclaredField("folder"); folderField.setAccessible(true); Folder folder = mock(IMAPFolder.class); given(folder.getPermanentFlags()).willReturn(new Flags(Flags.Flag.USER)); folderField.set(receiver, folder); willAnswer(invocation -> true).given(folder).isOpen(); willAnswer(invocation -> null).given(receiver).openFolder(); DirectFieldAccessor adapterAccessor = new DirectFieldAccessor(adapter); adapterAccessor.setPropertyValue("mailReceiver", receiver); MimeMessage mailMessage = mock(MimeMessage.class); Flags flags = mock(Flags.class); given(mailMessage.getFlags()).willReturn(flags); final Message[] messages = new Message[] { mailMessage }; willAnswer(invocation -> messages).given(receiver).searchForNewMessages(); willAnswer(invocation -> null).given(receiver).fetchMessages(messages); adapter.start(); org.springframework.messaging.Message<?> replMessage = errorChannel.receive(10000); assertNotNull(replMessage); assertEquals("Failed", ((Exception) replMessage.getPayload()).getCause().getMessage()); adapter.stop(); context.close(); }
From source file:org.springframework.integration.mail.ImapMailReceiverTests.java
@SuppressWarnings("resource") @Test// www.j av a 2 s . co m public void testNoInitialIdleDelayWhenRecentNotSupported() throws Exception { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext( "ImapIdleChannelAdapterParserTests-context.xml", ImapIdleChannelAdapterParserTests.class); ImapIdleChannelAdapter adapter = context.getBean("simpleAdapter", ImapIdleChannelAdapter.class); QueueChannel channel = new QueueChannel(); adapter.setOutputChannel(channel); ImapMailReceiver receiver = new ImapMailReceiver("imap:foo"); receiver = spy(receiver); receiver.setBeanFactory(mock(BeanFactory.class)); receiver.afterPropertiesSet(); final IMAPFolder folder = mock(IMAPFolder.class); given(folder.getPermanentFlags()).willReturn(new Flags(Flags.Flag.USER)); given(folder.isOpen()).willReturn(false).willReturn(true); given(folder.exists()).willReturn(true); DirectFieldAccessor adapterAccessor = new DirectFieldAccessor(adapter); adapterAccessor.setPropertyValue("mailReceiver", receiver); Field storeField = AbstractMailReceiver.class.getDeclaredField("store"); storeField.setAccessible(true); Store store = mock(Store.class); given(store.isConnected()).willReturn(true); given(store.getFolder(Mockito.any(URLName.class))).willReturn(folder); storeField.set(receiver, store); willAnswer(invocation -> folder).given(receiver).getFolder(); MimeMessage mailMessage = mock(MimeMessage.class); Flags flags = mock(Flags.class); given(mailMessage.getFlags()).willReturn(flags); final Message[] messages = new Message[] { mailMessage }; final AtomicInteger shouldFindMessagesCounter = new AtomicInteger(2); willAnswer(invocation -> { /* * Return the message from first invocation of waitForMessages() * and in receive(); then return false in the next call to * waitForMessages() so we enter idle(); counter will be reset * to 1 in the mocked idle(). */ if (shouldFindMessagesCounter.decrementAndGet() >= 0) { return messages; } else { return new Message[0]; } }).given(receiver).searchForNewMessages(); willAnswer(invocation -> null).given(receiver).fetchMessages(messages); willAnswer(invocation -> { Thread.sleep(5000); shouldFindMessagesCounter.set(1); return null; }).given(folder).idle(); adapter.start(); /* * Idle takes 5 seconds; if all is well, we should receive the first message * before then. */ assertNotNull(channel.receive(3000)); // We should not receive any more until the next idle elapses assertNull(channel.receive(3000)); assertNotNull(channel.receive(6000)); adapter.stop(); context.close(); }
From source file:org.springframework.integration.mail.ImapMailReceiverTests.java
@SuppressWarnings("resource") @Test/*from w w w . jav a 2 s . co m*/ public void testInitialIdleDelayWhenRecentIsSupported() throws Exception { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext( "ImapIdleChannelAdapterParserTests-context.xml", ImapIdleChannelAdapterParserTests.class); ImapIdleChannelAdapter adapter = context.getBean("simpleAdapter", ImapIdleChannelAdapter.class); QueueChannel channel = new QueueChannel(); adapter.setOutputChannel(channel); ImapMailReceiver receiver = new ImapMailReceiver("imap:foo"); receiver = spy(receiver); receiver.setBeanFactory(mock(BeanFactory.class)); receiver.afterPropertiesSet(); final IMAPFolder folder = mock(IMAPFolder.class); given(folder.getPermanentFlags()).willReturn(new Flags(Flags.Flag.RECENT)); given(folder.isOpen()).willReturn(false).willReturn(true); given(folder.exists()).willReturn(true); DirectFieldAccessor adapterAccessor = new DirectFieldAccessor(adapter); adapterAccessor.setPropertyValue("mailReceiver", receiver); Field storeField = AbstractMailReceiver.class.getDeclaredField("store"); storeField.setAccessible(true); Store store = mock(Store.class); given(store.isConnected()).willReturn(true); given(store.getFolder(Mockito.any(URLName.class))).willReturn(folder); storeField.set(receiver, store); willAnswer(invocation -> folder).given(receiver).getFolder(); MimeMessage mailMessage = mock(MimeMessage.class); Flags flags = mock(Flags.class); given(mailMessage.getFlags()).willReturn(flags); final Message[] messages = new Message[] { mailMessage }; willAnswer(invocation -> messages).given(receiver).searchForNewMessages(); willAnswer(invocation -> null).given(receiver).fetchMessages(messages); final CountDownLatch idles = new CountDownLatch(2); willAnswer(invocation -> { idles.countDown(); Thread.sleep(5000); return null; }).given(folder).idle(); adapter.start(); /* * Idle takes 5 seconds; since this server supports RECENT, we should * not receive any early messages. */ assertNull(channel.receive(3000)); assertNotNull(channel.receive(5000)); assertTrue(idles.await(5, TimeUnit.SECONDS)); adapter.stop(); context.close(); }
From source file:org.springframework.integration.mqtt.MqttAdapterTests.java
@Test public void testInboundOptionsApplied() throws Exception { DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory(); factory.setCleanSession(false);/*from ww w .ja v a 2 s. c om*/ factory.setConnectionTimeout(23); factory.setKeepAliveInterval(45); factory.setPassword("pass"); MemoryPersistence persistence = new MemoryPersistence(); factory.setPersistence(persistence); final SocketFactory socketFactory = mock(SocketFactory.class); factory.setSocketFactory(socketFactory); final Properties props = new Properties(); factory.setSslProperties(props); factory.setUserName("user"); Will will = new Will("foo", "bar".getBytes(), 2, true); factory.setWill(will); factory = spy(factory); final IMqttClient client = mock(IMqttClient.class); willAnswer(invocation -> client).given(factory).getClientInstance(anyString(), anyString()); final AtomicBoolean connectCalled = new AtomicBoolean(); final AtomicBoolean failConnection = new AtomicBoolean(); final CountDownLatch waitToFail = new CountDownLatch(1); final CountDownLatch failInProcess = new CountDownLatch(1); final CountDownLatch goodConnection = new CountDownLatch(2); final MqttException reconnectException = new MqttException(MqttException.REASON_CODE_SERVER_CONNECT_ERROR); willAnswer(invocation -> { if (failConnection.get()) { failInProcess.countDown(); waitToFail.await(10, TimeUnit.SECONDS); throw reconnectException; } MqttConnectOptions options = invocation.getArgument(0); assertEquals(23, options.getConnectionTimeout()); assertEquals(45, options.getKeepAliveInterval()); assertEquals("pass", new String(options.getPassword())); assertSame(socketFactory, options.getSocketFactory()); assertSame(props, options.getSSLProperties()); assertEquals("user", options.getUserName()); assertEquals("foo", options.getWillDestination()); assertEquals("bar", new String(options.getWillMessage().getPayload())); assertEquals(2, options.getWillMessage().getQos()); connectCalled.set(true); goodConnection.countDown(); return null; }).given(client).connect(any(MqttConnectOptions.class)); final AtomicReference<MqttCallback> callback = new AtomicReference<MqttCallback>(); willAnswer(invocation -> { callback.set(invocation.getArgument(0)); return null; }).given(client).setCallback(any(MqttCallback.class)); given(client.isConnected()).willReturn(true); MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter("foo", "bar", factory, "baz", "fix"); QueueChannel outputChannel = new QueueChannel(); adapter.setOutputChannel(outputChannel); ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); taskScheduler.initialize(); adapter.setTaskScheduler(taskScheduler); adapter.setBeanFactory(mock(BeanFactory.class)); ApplicationEventPublisher applicationEventPublisher = mock(ApplicationEventPublisher.class); final BlockingQueue<MqttIntegrationEvent> events = new LinkedBlockingQueue<MqttIntegrationEvent>(); willAnswer(invocation -> { events.add(invocation.getArgument(0)); return null; }).given(applicationEventPublisher).publishEvent(any(MqttIntegrationEvent.class)); adapter.setApplicationEventPublisher(applicationEventPublisher); adapter.setRecoveryInterval(500); adapter.afterPropertiesSet(); adapter.start(); verify(client, times(1)).connect(any(MqttConnectOptions.class)); assertTrue(connectCalled.get()); MqttMessage message = new MqttMessage("qux".getBytes()); callback.get().messageArrived("baz", message); Message<?> outMessage = outputChannel.receive(0); assertNotNull(outMessage); assertEquals("qux", outMessage.getPayload()); MqttIntegrationEvent event = events.poll(10, TimeUnit.SECONDS); assertThat(event, instanceOf(MqttSubscribedEvent.class)); assertEquals("Connected and subscribed to [baz, fix]", ((MqttSubscribedEvent) event).getMessage()); // lose connection and make first reconnect fail failConnection.set(true); RuntimeException e = new RuntimeException("foo"); adapter.connectionLost(e); event = events.poll(10, TimeUnit.SECONDS); assertThat(event, instanceOf(MqttConnectionFailedEvent.class)); assertSame(event.getCause(), e); assertTrue(failInProcess.await(10, TimeUnit.SECONDS)); waitToFail.countDown(); failConnection.set(false); event = events.poll(10, TimeUnit.SECONDS); assertThat(event, instanceOf(MqttConnectionFailedEvent.class)); assertSame(event.getCause(), reconnectException); // reconnect can now succeed; however, we might have other failures on a slow server (500ms retry). assertTrue(goodConnection.await(10, TimeUnit.SECONDS)); int n = 0; while (!(event instanceof MqttSubscribedEvent) && n++ < 20) { event = events.poll(10, TimeUnit.SECONDS); } assertThat(event, instanceOf(MqttSubscribedEvent.class)); assertEquals("Connected and subscribed to [baz, fix]", ((MqttSubscribedEvent) event).getMessage()); taskScheduler.destroy(); }
From source file:org.springframework.integration.redis.inbound.RedisInboundChannelAdapterTests.java
private void testRedisInboundChannelAdapterGuts(int iteration) throws Exception { int numToTest = 10; String redisChannelName = "testRedisInboundChannelAdapterChannel"; QueueChannel channel = new QueueChannel(); JedisConnectionFactory connectionFactory = new JedisConnectionFactory(); connectionFactory.setPort(7379);//ww w . ja va 2 s .co m connectionFactory.afterPropertiesSet(); RedisInboundChannelAdapter adapter = new RedisInboundChannelAdapter(connectionFactory); adapter.setTopics("testRedisInboundChannelAdapterChannel"); adapter.setOutputChannel(channel); adapter.afterPropertiesSet(); adapter.start(); RedisMessageListenerContainer container = waitUntilSubscribed(adapter); StringRedisTemplate redisTemplate = new StringRedisTemplate(connectionFactory); redisTemplate.afterPropertiesSet(); for (int i = 0; i < numToTest; i++) { String message = "test-" + i + " iteration " + iteration; redisTemplate.convertAndSend(redisChannelName, message); logger.debug("Sent " + message); } int counter = 0; for (int i = 0; i < numToTest; i++) { Message<?> message = channel.receive(5000); if (message == null) { throw new RuntimeException("Failed to receive message # " + i + " iteration " + iteration); } assertNotNull(message); assertTrue(message.getPayload().toString().startsWith("test-")); counter++; } assertEquals(numToTest, counter); adapter.stop(); container.stop(); connectionFactory.destroy(); }
From source file:org.springframework.integration.xmpp.inbound.ChatMessageListeningEndpointTests.java
@Test public void testExpression() throws Exception { TestXMPPConnection testXMPPConnection = new TestXMPPConnection(); QueueChannel inputChannel = new QueueChannel(); ChatMessageListeningEndpoint endpoint = new ChatMessageListeningEndpoint(testXMPPConnection); SpelExpressionParser parser = new SpelExpressionParser(); endpoint.setPayloadExpression(parser.parseExpression("#root")); endpoint.setOutputChannel(inputChannel); endpoint.setBeanFactory(mock(BeanFactory.class)); endpoint.afterPropertiesSet();//from ww w .ja va2 s. c om endpoint.start(); Message smackMessage = new Message(); smackMessage.setBody("foo"); XmlPullParser xmlPullParser = PacketParserUtils.newXmppParser(new StringReader(smackMessage.toString())); xmlPullParser.next(); testXMPPConnection.parseAndProcessStanza(xmlPullParser); org.springframework.messaging.Message<?> receive = inputChannel.receive(10000); assertNotNull(receive); Object payload = receive.getPayload(); assertThat(payload, instanceOf(Message.class)); assertEquals(smackMessage.getStanzaId(), ((Message) payload).getStanzaId()); assertEquals(smackMessage.getBody(), ((Message) payload).getBody()); Log logger = Mockito.spy(TestUtils.getPropertyValue(endpoint, "logger", Log.class)); given(logger.isInfoEnabled()).willReturn(true); final CountDownLatch logLatch = new CountDownLatch(1); willAnswer(invocation -> { Object result = invocation.callRealMethod(); logLatch.countDown(); return result; }).given(logger).info(anyString()); new DirectFieldAccessor(endpoint).setPropertyValue("logger", logger); endpoint.setPayloadExpression(null); smackMessage = new Message(); xmlPullParser = PacketParserUtils.newXmppParser(new StringReader(smackMessage.toString())); xmlPullParser.next(); testXMPPConnection.parseAndProcessStanza(xmlPullParser); ArgumentCaptor<String> argumentCaptor = ArgumentCaptor.forClass(String.class); assertTrue(logLatch.await(10, TimeUnit.SECONDS)); verify(logger).info(argumentCaptor.capture()); assertEquals("The XMPP Message [" + smackMessage + "] with empty body is ignored.", argumentCaptor.getValue()); endpoint.stop(); }
From source file:org.springframework.integration.xmpp.inbound.ChatMessageListeningEndpointTests.java
@Test public void testGcmExtension() throws Exception { String data = "{\n" + " \"to\":\"me\",\n" + " \"notification\": {\n" + " \"title\": \"Something interesting\",\n" + " \"text\": \"Here we go\"\n" + " },\n" + " \"time_to_live\":\"600\"\n" + " }\n" + "}"; GcmPacketExtension packetExtension = new GcmPacketExtension(data); Message smackMessage = new Message(); smackMessage.addExtension(packetExtension); TestXMPPConnection testXMPPConnection = new TestXMPPConnection(); QueueChannel inputChannel = new QueueChannel(); ChatMessageListeningEndpoint endpoint = new ChatMessageListeningEndpoint(testXMPPConnection); Expression payloadExpression = new SpelExpressionParser().parseExpression("#extension.json"); endpoint.setPayloadExpression(payloadExpression); endpoint.setOutputChannel(inputChannel); endpoint.setBeanFactory(mock(BeanFactory.class)); endpoint.afterPropertiesSet();/*from w ww . j ava2 s. c o m*/ endpoint.start(); XmlPullParser xmlPullParser = PacketParserUtils.newXmppParser(new StringReader(smackMessage.toString())); xmlPullParser.next(); testXMPPConnection.parseAndProcessStanza(xmlPullParser); org.springframework.messaging.Message<?> receive = inputChannel.receive(10000); assertNotNull(receive); assertEquals(data, receive.getPayload()); endpoint.stop(); }
From source file:org.springframework.xd.dirt.integration.bus.rabbit.RabbitMessageBusTests.java
@SuppressWarnings("unchecked") @Test/*from w w w .j a v a 2 s . c o m*/ public void testBatchingAndCompression() throws Exception { RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource()); MessageBus bus = getMessageBus(); Properties properties = new Properties(); properties.put("deliveryMode", "NON_PERSISTENT"); properties.put("batchingEnabled", "true"); properties.put("batchSize", "2"); properties.put("batchBufferLimit", "100000"); properties.put("batchTimeout", "30000"); properties.put("compress", "true"); DirectChannel output = new DirectChannel(); output.setBeanName("batchingProducer"); bus.bindProducer("batching.0", output, properties); while (template.receive("xdbus.batching.0") != null) { } Log logger = spy(TestUtils.getPropertyValue(bus, "messageBus.compressingPostProcessor.logger", Log.class)); new DirectFieldAccessor(TestUtils.getPropertyValue(bus, "messageBus.compressingPostProcessor")) .setPropertyValue("logger", logger); when(logger.isTraceEnabled()).thenReturn(true); assertEquals(Deflater.BEST_SPEED, TestUtils.getPropertyValue(bus, "messageBus.compressingPostProcessor.level")); output.send(new GenericMessage<>("foo".getBytes())); output.send(new GenericMessage<>("bar".getBytes())); Object out = spyOn("batching.0").receive(false); assertThat(out, instanceOf(byte[].class)); assertEquals("\u0000\u0000\u0000\u0003foo\u0000\u0000\u0000\u0003bar", new String((byte[]) out)); ArgumentCaptor<Object> captor = ArgumentCaptor.forClass(Object.class); verify(logger).trace(captor.capture()); assertThat(captor.getValue().toString(), containsString("Compressed 14 to ")); QueueChannel input = new QueueChannel(); input.setBeanName("batchingConsumer"); bus.bindConsumer("batching.0", input, null); output.send(new GenericMessage<>("foo".getBytes())); output.send(new GenericMessage<>("bar".getBytes())); Message<byte[]> in = (Message<byte[]>) input.receive(10000); assertNotNull(in); assertEquals("foo", new String(in.getPayload())); in = (Message<byte[]>) input.receive(10000); assertNotNull(in); assertEquals("bar", new String(in.getPayload())); assertNull(in.getHeaders().get(AmqpHeaders.DELIVERY_MODE)); bus.unbindProducers("batching.0"); bus.unbindConsumers("batching.0"); }