@SuppressWarnings({"unchecked", "rawtypes"}) public static void main(String[] args) { // ch.qos.logback.classic.Logger rootLogger = // (ch.qos.logback.classic.Logger)LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME); // rootLogger.setLevel(Level.toLevel("info")); final ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(CONFIG, Consumer.class); ctx.start(); final QueueChannel channel = ctx.getBean("inputFromKafka", QueueChannel.class); Message msg; while ((msg = channel.receive()) != null) { HashMap map = (HashMap) msg.getPayload(); Set<Map.Entry> set = map.entrySet(); for (Map.Entry entry : set) { String topic = (String) entry.getKey(); System.out.println("Topic:" + topic); ConcurrentHashMap<Integer, List<byte[]>> messages = (ConcurrentHashMap<Integer, List<byte[]>>) entry.getValue(); Collection<List<byte[]>> values = messages.values(); for (Iterator<List<byte[]>> iterator = values.iterator(); iterator.hasNext(); ) { List<byte[]> list = iterator.next(); for (byte[] object : list) { String message = new String(object); System.out.println("\tMessage : " + message); } } } } try { Thread.sleep(100000); } catch (InterruptedException e) { e.printStackTrace(); } ctx.close(); }
@Test public void resolveChannelNameFromContext() { StaticApplicationContext context = new StaticApplicationContext(); RootBeanDefinition routerBeanDefinition = new RootBeanDefinition(HeaderValueRouter.class); routerBeanDefinition.getConstructorArgumentValues().addGenericArgumentValue("testHeaderName"); routerBeanDefinition.getPropertyValues().addPropertyValue("resolutionRequired", "true"); context.registerBeanDefinition("router", routerBeanDefinition); context.registerBeanDefinition("testChannel", new RootBeanDefinition(QueueChannel.class)); context.registerBeanDefinition("newChannel", new RootBeanDefinition(QueueChannel.class)); context.refresh(); MessageHandler handler = (MessageHandler) context.getBean("router"); Message<?> message = MessageBuilder.withPayload("test").setHeader("testHeaderName", "testChannel").build(); handler.handleMessage(message); QueueChannel channel = (QueueChannel) context.getBean("testChannel"); Message<?> result = channel.receive(1000); assertNotNull(result); assertSame(message, result); // validate dynamics HeaderValueRouter router = (HeaderValueRouter) context.getBean("router"); router.setChannelMapping("testChannel", "newChannel"); router.handleMessage(message); QueueChannel newChannel = (QueueChannel) context.getBean("newChannel"); result = newChannel.receive(10); assertNotNull(result); router.removeChannelMapping("testChannel"); router.handleMessage(message); result = channel.receive(1000); assertNotNull(result); assertSame(message, result); context.close(); }
@Test public void testXPathRouter() { // route to a channel determined by outcome of the xpath expression // Build the route DirectChannel inputChannel = new DirectChannel(); inputChannel.setBeanName("input"); XPathRouter router = new XPathRouter("//subject/text()"); router.setEvaluateAsString(true); inputChannel.subscribe(router); QueueChannel testChannel = new QueueChannel(); GenericApplicationContext context = new GenericApplicationContext(); context.getBeanFactory().registerSingleton("testChannel", testChannel); router.setBeanFactory(context); context.refresh(); // Create message Object correlationId = "123-ABC"; String xmlSource = "<xml><subject>testChannel</subject></xml>"; Message<String> message = MessageBuilder.withPayload(xmlSource).setCorrelationId(correlationId).build(); // Send and receive message inputChannel.send(message); Message<?> reply = testChannel.receive(0); assertEquals(xmlSource, reply.getPayload()); }
@Test public void withHeaderMapperStandardAndCustomHeaders() { AmqpInboundChannelAdapter adapter = context.getBean( "withHeaderMapperStandardAndCustomHeaders", AmqpInboundChannelAdapter.class); AbstractMessageListenerContainer mlc = TestUtils.getPropertyValue( adapter, "messageListenerContainer", AbstractMessageListenerContainer.class); MessageListener listener = TestUtils.getPropertyValue(mlc, "messageListener", MessageListener.class); MessageProperties amqpProperties = new MessageProperties(); amqpProperties.setAppId("test.appId"); amqpProperties.setClusterId("test.clusterId"); amqpProperties.setContentEncoding("test.contentEncoding"); amqpProperties.setContentLength(99L); amqpProperties.setContentType("test.contentType"); amqpProperties.setHeader("foo", "foo"); amqpProperties.setHeader("bar", "bar"); Message amqpMessage = new Message("hello".getBytes(), amqpProperties); listener.onMessage(amqpMessage); QueueChannel requestChannel = context.getBean("requestChannel", QueueChannel.class); org.springframework.integration.Message<?> siMessage = requestChannel.receive(0); assertEquals("foo", siMessage.getHeaders().get("foo")); assertNull(siMessage.getHeaders().get("bar")); assertNotNull(siMessage.getHeaders().get(AmqpHeaders.CONTENT_ENCODING)); assertNotNull(siMessage.getHeaders().get(AmqpHeaders.CLUSTER_ID)); assertNotNull(siMessage.getHeaders().get(AmqpHeaders.APP_ID)); assertNotNull(siMessage.getHeaders().get(AmqpHeaders.CONTENT_TYPE)); }
@Test public void testUnicastReceiverException() throws Exception { SubscribableChannel channel = new DirectChannel(); int port = SocketUtils.findAvailableUdpSocket(); UnicastReceivingChannelAdapter adapter = new UnicastReceivingChannelAdapter(port); adapter.setOutputChannel(channel); // SocketUtils.setLocalNicIfPossible(adapter); adapter.setOutputChannel(channel); ServiceActivatingHandler handler = new ServiceActivatingHandler(new FailingService()); channel.subscribe(handler); QueueChannel errorChannel = new QueueChannel(); adapter.setErrorChannel(errorChannel); adapter.start(); SocketTestUtils.waitListening(adapter); Message<byte[]> message = MessageBuilder.withPayload("ABCD".getBytes()).build(); DatagramPacketMessageMapper mapper = new DatagramPacketMessageMapper(); DatagramPacket packet = mapper.fromMessage(message); packet.setSocketAddress(new InetSocketAddress("localhost", port)); DatagramSocket datagramSocket = new DatagramSocket(SocketUtils.findAvailableUdpSocket()); datagramSocket.send(packet); datagramSocket.close(); Message<?> receivedMessage = errorChannel.receive(2000); assertNotNull(receivedMessage); assertEquals("Failed", ((Exception) receivedMessage.getPayload()).getCause().getMessage()); adapter.stop(); }
@SuppressWarnings("unchecked") @Test @Ignore public void testMulticastReceiver() throws Exception { QueueChannel channel = new QueueChannel(2); int port = SocketUtils.findAvailableUdpSocket(); MulticastReceivingChannelAdapter adapter = new MulticastReceivingChannelAdapter("225.6.7.8", port); adapter.setOutputChannel(channel); String nic = SocketTestUtils.chooseANic(true); if (nic == null) { // no multicast support LogFactory.getLog(this.getClass()).error("No Multicast support"); return; } adapter.setLocalAddress(nic); adapter.start(); SocketTestUtils.waitListening(adapter); Message<byte[]> message = MessageBuilder.withPayload("ABCD".getBytes()).build(); DatagramPacketMessageMapper mapper = new DatagramPacketMessageMapper(); DatagramPacket packet = mapper.fromMessage(message); packet.setSocketAddress(new InetSocketAddress("225.6.7.8", port)); DatagramSocket datagramSocket = new DatagramSocket(0, Inet4Address.getByName(nic)); datagramSocket.send(packet); datagramSocket.close(); Message<byte[]> receivedMessage = (Message<byte[]>) channel.receive(2000); assertNotNull(receivedMessage); assertEquals(new String(message.getPayload()), new String(receivedMessage.getPayload())); adapter.stop(); }
@SuppressWarnings("unchecked") @Test @Ignore public void testMulticastSender() throws Exception { QueueChannel channel = new QueueChannel(2); int port = SocketUtils.findAvailableUdpSocket(); UnicastReceivingChannelAdapter adapter = new MulticastReceivingChannelAdapter("225.6.7.9", port); adapter.setOutputChannel(channel); String nic = SocketTestUtils.chooseANic(true); if (nic == null) { // no multicast support LogFactory.getLog(this.getClass()).error("No Multicast support"); return; } adapter.setLocalAddress(nic); adapter.start(); SocketTestUtils.waitListening(adapter); MulticastSendingMessageHandler handler = new MulticastSendingMessageHandler("225.6.7.9", port); handler.setLocalAddress(nic); Message<byte[]> message = MessageBuilder.withPayload("ABCD".getBytes()).build(); handler.handleMessage(message); Message<byte[]> receivedMessage = (Message<byte[]>) channel.receive(2000); assertNotNull(receivedMessage); assertEquals(new String(message.getPayload()), new String(receivedMessage.getPayload())); adapter.stop(); }
@Test public void testWithReply() throws Exception { QueueChannel replies = new QueueChannel(); this.gateway1.setOutputChannel(replies); this.gateway1.start(); this.gateway1.handleMessage( MessageBuilder.withPayload("foo") .setHeader( JmsHeaders.CORRELATION_ID, "baz") // make sure it's restored in case we're from an upstream gw .build()); JmsTemplate template = new JmsTemplate(this.ccf); template.setReceiveTimeout(10000); final Message received = template.receive("asyncTest1"); assertNotNull(received); template.send( received.getJMSReplyTo(), new MessageCreator() { @Override public Message createMessage(Session session) throws JMSException { TextMessage textMessage = session.createTextMessage("bar"); textMessage.setJMSCorrelationID(received.getJMSCorrelationID()); return textMessage; } }); org.springframework.messaging.Message<?> reply = replies.receive(10000); assertNotNull(reply); assertEquals("bar", reply.getPayload()); assertEquals("baz", reply.getHeaders().get(JmsHeaders.CORRELATION_ID)); this.gateway1.stop(); }
@SuppressWarnings("unchecked") @Test public void testUnicastSender() throws Exception { QueueChannel channel = new QueueChannel(2); int port = SocketUtils.findAvailableUdpSocket(); UnicastReceivingChannelAdapter adapter = new UnicastReceivingChannelAdapter(port); adapter.setBeanName("test"); adapter.setOutputChannel(channel); // SocketUtils.setLocalNicIfPossible(adapter); adapter.start(); SocketTestUtils.waitListening(adapter); // String whichNic = SocketUtils.chooseANic(false); UnicastSendingMessageHandler handler = new UnicastSendingMessageHandler( "localhost", port, false, true, "localhost", // whichNic, SocketUtils.findAvailableUdpSocket(), 5000); // handler.setLocalAddress(whichNic); handler.setBeanFactory(mock(BeanFactory.class)); handler.afterPropertiesSet(); handler.start(); Message<byte[]> message = MessageBuilder.withPayload("ABCD".getBytes()).build(); handler.handleMessage(message); Message<byte[]> receivedMessage = (Message<byte[]>) channel.receive(2000); assertEquals(new String(message.getPayload()), new String(receivedMessage.getPayload())); adapter.stop(); handler.stop(); }
@Test public void testMultipleGroupsSimultaneously() throws InterruptedException { QueueChannel replyChannel1 = new QueueChannel(); QueueChannel replyChannel2 = new QueueChannel(); Message<?> message1 = createMessage(3, "ABC", 3, 1, replyChannel1, null); Message<?> message2 = createMessage(5, "ABC", 3, 2, replyChannel1, null); Message<?> message3 = createMessage(7, "ABC", 3, 3, replyChannel1, null); Message<?> message4 = createMessage(11, "XYZ", 3, 1, replyChannel2, null); Message<?> message5 = createMessage(13, "XYZ", 3, 2, replyChannel2, null); Message<?> message6 = createMessage(17, "XYZ", 3, 3, replyChannel2, null); CountDownLatch latch = new CountDownLatch(6); this.taskExecutor.execute(new AggregatorTestTask(this.aggregator, message1, latch)); this.taskExecutor.execute(new AggregatorTestTask(this.aggregator, message6, latch)); this.taskExecutor.execute(new AggregatorTestTask(this.aggregator, message2, latch)); this.taskExecutor.execute(new AggregatorTestTask(this.aggregator, message5, latch)); this.taskExecutor.execute(new AggregatorTestTask(this.aggregator, message3, latch)); this.taskExecutor.execute(new AggregatorTestTask(this.aggregator, message4, latch)); assertTrue(latch.await(10, TimeUnit.SECONDS)); @SuppressWarnings("unchecked") Message<Integer> reply1 = (Message<Integer>) replyChannel1.receive(1000); assertNotNull(reply1); assertThat(reply1.getPayload(), is(105)); @SuppressWarnings("unchecked") Message<Integer> reply2 = (Message<Integer>) replyChannel2.receive(1000); assertNotNull(reply2); assertThat(reply2.getPayload(), is(2431)); }
@Test public void testCompression() throws Exception { final String[] codecs = new String[] {null, "none", "gzip", "snappy"}; byte[] ratherBigPayload = new byte[2048]; Arrays.fill(ratherBigPayload, (byte) 65); Binder binder = getBinder(); for (String codec : codecs) { DirectChannel moduleOutputChannel = new DirectChannel(); QueueChannel moduleInputChannel = new QueueChannel(); Properties props = new Properties(); if (codec != null) { props.put(KafkaMessageChannelBinder.COMPRESSION_CODEC, codec); } binder.bindProducer("foo.0", moduleOutputChannel, props); binder.bindConsumer("foo.0", moduleInputChannel, null); Message<?> message = org.springframework.integration.support.MessageBuilder.withPayload(ratherBigPayload) .build(); // Let the consumer actually bind to the producer before sending a msg binderBindUnbindLatency(); moduleOutputChannel.send(message); Message<?> inbound = moduleInputChannel.receive(2000); assertNotNull(inbound); assertArrayEquals(ratherBigPayload, (byte[]) inbound.getPayload()); binder.unbindProducers("foo.0"); binder.unbindConsumers("foo.0"); } }
@Test public void testCustomPartitionCountOverridesPartitioningIfLarger() throws Exception { byte[] ratherBigPayload = new byte[2048]; Arrays.fill(ratherBigPayload, (byte) 65); KafkaTestBinder binder = (KafkaTestBinder) getBinder(); DirectChannel moduleOutputChannel = new DirectChannel(); QueueChannel moduleInputChannel = new QueueChannel(); Properties producerProperties = new Properties(); producerProperties.put(BinderProperties.MIN_PARTITION_COUNT, "5"); producerProperties.put(BinderProperties.NEXT_MODULE_COUNT, "3"); producerProperties.put(BinderProperties.PARTITION_KEY_EXPRESSION, "payload"); Properties consumerProperties = new Properties(); consumerProperties.put(BinderProperties.MIN_PARTITION_COUNT, "5"); long uniqueBindingId = System.currentTimeMillis(); binder.bindProducer("foo" + uniqueBindingId + ".0", moduleOutputChannel, producerProperties); binder.bindConsumer("foo" + uniqueBindingId + ".0", moduleInputChannel, consumerProperties); Message<?> message = org.springframework.integration.support.MessageBuilder.withPayload(ratherBigPayload) .build(); // Let the consumer actually bind to the producer before sending a msg binderBindUnbindLatency(); moduleOutputChannel.send(message); Message<?> inbound = moduleInputChannel.receive(2000); assertNotNull(inbound); assertArrayEquals(ratherBigPayload, (byte[]) inbound.getPayload()); Collection<Partition> partitions = binder.getCoreBinder().getConnectionFactory().getPartitions("foo" + uniqueBindingId + ".0"); assertThat(partitions, hasSize(5)); binder.unbindProducers("foo" + uniqueBindingId + ".0"); binder.unbindConsumers("foo" + uniqueBindingId + ".0"); }
@Test public void resolveMultipleChannelsWithCommaDelimitedString() { StaticApplicationContext context = new StaticApplicationContext(); RootBeanDefinition routerBeanDefinition = new RootBeanDefinition(HeaderValueRouter.class); routerBeanDefinition.getConstructorArgumentValues().addGenericArgumentValue("testHeaderName"); routerBeanDefinition.getPropertyValues().addPropertyValue("resolutionRequired", "true"); context.registerBeanDefinition("router", routerBeanDefinition); context.registerBeanDefinition("channel1", new RootBeanDefinition(QueueChannel.class)); context.registerBeanDefinition("channel2", new RootBeanDefinition(QueueChannel.class)); context.refresh(); MessageHandler handler = (MessageHandler) context.getBean("router"); String channels = "channel1, channel2"; Message<?> message = MessageBuilder.withPayload("test").setHeader("testHeaderName", channels).build(); handler.handleMessage(message); QueueChannel channel1 = (QueueChannel) context.getBean("channel1"); QueueChannel channel2 = (QueueChannel) context.getBean("channel2"); Message<?> result1 = channel1.receive(1000); Message<?> result2 = channel2.receive(1000); assertNotNull(result1); assertNotNull(result2); assertSame(message, result1); assertSame(message, result2); context.close(); }
@Test @SuppressWarnings({"unchecked", "rawtypes"}) public void resolveChannelNameFromMapAndCustomeResolver() { final StaticApplicationContext context = new StaticApplicationContext(); ManagedMap channelMappings = new ManagedMap(); channelMappings.put("testKey", "testChannel"); RootBeanDefinition routerBeanDefinition = new RootBeanDefinition(HeaderValueRouter.class); routerBeanDefinition.getConstructorArgumentValues().addGenericArgumentValue("testHeaderName"); routerBeanDefinition.getPropertyValues().addPropertyValue("resolutionRequired", "true"); routerBeanDefinition.getPropertyValues().addPropertyValue("channelMappings", channelMappings); routerBeanDefinition.getPropertyValues().addPropertyValue("beanFactory", context); routerBeanDefinition .getPropertyValues() .addPropertyValue( "channelResolver", (DestinationResolver<MessageChannel>) channelName -> context.getBean("anotherChannel", MessageChannel.class)); context.registerBeanDefinition("router", routerBeanDefinition); context.registerBeanDefinition("testChannel", new RootBeanDefinition(QueueChannel.class)); context.registerBeanDefinition("anotherChannel", new RootBeanDefinition(QueueChannel.class)); context.refresh(); MessageHandler handler = (MessageHandler) context.getBean("router"); Message<?> message = MessageBuilder.withPayload("test").setHeader("testHeaderName", "testKey").build(); handler.handleMessage(message); QueueChannel channel = (QueueChannel) context.getBean("anotherChannel"); Message<?> result = channel.receive(1000); assertNotNull(result); assertSame(message, result); context.close(); }
@Test public void testPollingConsumer() { Object pollingConsumer = context.getBean("withHeaderMapper"); QueueChannel channel = (QueueChannel) TestUtils.getPropertyValue(pollingConsumer, "inputChannel"); assertEquals("outboundPollingChannel", channel.getComponentName()); assertTrue(pollingConsumer instanceof PollingConsumer); }
@Test public void testOne() { inputChannel.send(MessageBuilder.withPayload(" a ").build()); Message<?> outMessage = testChannel.receive(0); assertNotNull(outMessage); assertThat(outMessage, hasPayload("a")); outMessage = testChannel.receive(0); assertNull("Only one message expected", outMessage); }
@Test public void testNetCrLfClientMode() throws Exception { final int port = SocketTestUtils.findAvailableServerSocket(); final CountDownLatch latch = new CountDownLatch(1); final AtomicBoolean done = new AtomicBoolean(); Executors.newSingleThreadExecutor() .execute( new Runnable() { public void run() { try { ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port); latch.countDown(); Socket socket = server.accept(); int i = 0; while (true) { byte[] b = new byte[6]; readFully(socket.getInputStream(), b); b = ("Reply" + (++i) + "\r\n").getBytes(); socket.getOutputStream().write(b); } } catch (Exception e) { if (!done.get()) { e.printStackTrace(); } } } }); AbstractConnectionFactory ccf = new TcpNetClientConnectionFactory("localhost", port); ByteArrayCrLfSerializer serializer = new ByteArrayCrLfSerializer(); ccf.setSerializer(serializer); ccf.setDeserializer(serializer); ccf.setSoTimeout(Integer.MAX_VALUE); TcpSendingMessageHandler handler = new TcpSendingMessageHandler(); handler.setConnectionFactory(ccf); TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter(); adapter.setConnectionFactory(ccf); QueueChannel channel = new QueueChannel(); adapter.setOutputChannel(channel); assertTrue(latch.await(10, TimeUnit.SECONDS)); handler.setClientMode(true); handler.setRetryInterval(10000); handler.afterPropertiesSet(); handler.start(); adapter.start(); handler.handleMessage(MessageBuilder.withPayload("Test").build()); handler.handleMessage(MessageBuilder.withPayload("Test").build()); Message<?> mOut = channel.receive(10000); assertNotNull(mOut); assertEquals("Reply1", new String((byte[]) mOut.getPayload())); mOut = channel.receive(10000); assertNotNull(mOut); assertEquals("Reply2", new String((byte[]) mOut.getPayload())); done.set(true); handler.stop(); handler.start(); handler.stop(); }
@Test public void testNioLength() throws Exception { final int port = SocketTestUtils.findAvailableServerSocket(); final CountDownLatch latch = new CountDownLatch(1); final AtomicBoolean done = new AtomicBoolean(); Executors.newSingleThreadExecutor() .execute( new Runnable() { public void run() { try { ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port); latch.countDown(); Socket socket = server.accept(); int i = 0; while (true) { byte[] b = new byte[8]; readFully(socket.getInputStream(), b); if (!"\u0000\u0000\u0000\u0004Test".equals(new String(b))) { throw new RuntimeException("Bad Data"); } b = ("\u0000\u0000\u0000\u0006Reply" + (++i)).getBytes(); socket.getOutputStream().write(b); } } catch (Exception e) { if (!done.get()) { e.printStackTrace(); } } } }); AbstractConnectionFactory ccf = new TcpNioClientConnectionFactory("localhost", port); ByteArrayLengthHeaderSerializer serializer = new ByteArrayLengthHeaderSerializer(); ccf.setSerializer(serializer); ccf.setDeserializer(serializer); ccf.setSoTimeout(10000); ccf.start(); TcpSendingMessageHandler handler = new TcpSendingMessageHandler(); handler.setConnectionFactory(ccf); TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter(); adapter.setConnectionFactory(ccf); QueueChannel channel = new QueueChannel(); adapter.setOutputChannel(channel); assertTrue(latch.await(10, TimeUnit.SECONDS)); handler.handleMessage(MessageBuilder.withPayload("Test").build()); handler.handleMessage(MessageBuilder.withPayload("Test").build()); Set<String> results = new HashSet<String>(); Message<?> mOut = channel.receive(10000); assertNotNull(mOut); results.add(new String((byte[]) mOut.getPayload())); mOut = channel.receive(10000); assertNotNull(mOut); results.add(new String((byte[]) mOut.getPayload())); assertTrue(results.remove("Reply1")); assertTrue(results.remove("Reply2")); done.set(true); }
@Test public void testNioSingleUseWithInbound() throws Exception { final int port = SocketTestUtils.findAvailableServerSocket(); final CountDownLatch latch = new CountDownLatch(1); final Semaphore semaphore = new Semaphore(0); final AtomicBoolean done = new AtomicBoolean(); Executors.newSingleThreadExecutor() .execute( new Runnable() { public void run() { try { ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port); latch.countDown(); int i = 0; while (true) { Socket socket = server.accept(); semaphore.release(); byte[] b = new byte[6]; readFully(socket.getInputStream(), b); b = ("Reply" + (++i) + "\r\n").getBytes(); socket.getOutputStream().write(b); } } catch (Exception e) { if (!done.get()) { e.printStackTrace(); } } } }); AbstractConnectionFactory ccf = new TcpNioClientConnectionFactory("localhost", port); ByteArrayCrLfSerializer serializer = new ByteArrayCrLfSerializer(); ccf.setSerializer(serializer); ccf.setDeserializer(serializer); ccf.setSoTimeout(10000); ccf.start(); ccf.setSingleUse(true); TcpSendingMessageHandler handler = new TcpSendingMessageHandler(); handler.setConnectionFactory(ccf); TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter(); adapter.setConnectionFactory(ccf); QueueChannel channel = new QueueChannel(); adapter.setOutputChannel(channel); assertTrue(latch.await(10, TimeUnit.SECONDS)); handler.handleMessage(MessageBuilder.withPayload("Test").build()); handler.handleMessage(MessageBuilder.withPayload("Test").build()); assertTrue(semaphore.tryAcquire(2, 10000, TimeUnit.MILLISECONDS)); Set<String> replies = new HashSet<String>(); for (int i = 0; i < 2; i++) { Message<?> mOut = channel.receive(10000); assertNotNull(mOut); replies.add(new String((byte[]) mOut.getPayload())); } assertTrue(replies.remove("Reply1")); assertTrue(replies.remove("Reply2")); done.set(true); }
@SuppressWarnings("unchecked") @Test public void testUnicastReceiverWithReply() throws Exception { QueueChannel channel = new QueueChannel(2); int port = SocketUtils.findAvailableUdpSocket(); UnicastReceivingChannelAdapter adapter = new UnicastReceivingChannelAdapter(port); adapter.setOutputChannel(channel); adapter.start(); SocketTestUtils.waitListening(adapter); Message<byte[]> message = MessageBuilder.withPayload("ABCD".getBytes()).build(); DatagramPacketMessageMapper mapper = new DatagramPacketMessageMapper(); DatagramPacket packet = mapper.fromMessage(message); packet.setSocketAddress(new InetSocketAddress("localhost", port)); final DatagramSocket socket = new DatagramSocket(SocketUtils.findAvailableUdpSocket()); socket.send(packet); final AtomicReference<DatagramPacket> theAnswer = new AtomicReference<DatagramPacket>(); final CountDownLatch receiverReadyLatch = new CountDownLatch(1); final CountDownLatch replyReceivedLatch = new CountDownLatch(1); // main thread sends the reply using the headers, this thread will receive it Executors.newSingleThreadExecutor() .execute( new Runnable() { @Override public void run() { DatagramPacket answer = new DatagramPacket(new byte[2000], 2000); try { receiverReadyLatch.countDown(); socket.receive(answer); theAnswer.set(answer); replyReceivedLatch.countDown(); } catch (IOException e) { e.printStackTrace(); } } }); Message<byte[]> receivedMessage = (Message<byte[]>) channel.receive(2000); assertEquals(new String(message.getPayload()), new String(receivedMessage.getPayload())); String replyString = "reply:" + System.currentTimeMillis(); byte[] replyBytes = replyString.getBytes(); DatagramPacket reply = new DatagramPacket(replyBytes, replyBytes.length); reply.setSocketAddress( new InetSocketAddress( (String) receivedMessage.getHeaders().get(IpHeaders.IP_ADDRESS), (Integer) receivedMessage.getHeaders().get(IpHeaders.PORT))); assertTrue(receiverReadyLatch.await(10, TimeUnit.SECONDS)); DatagramSocket datagramSocket = new DatagramSocket(); datagramSocket.send(reply); assertTrue(replyReceivedLatch.await(10, TimeUnit.SECONDS)); DatagramPacket answerPacket = theAnswer.get(); assertNotNull(answerPacket); assertEquals(replyString, new String(answerPacket.getData(), 0, answerPacket.getLength())); datagramSocket.close(); socket.close(); adapter.stop(); }
@Test public void testGateway() { QueueChannel replyChannel = new QueueChannel(); Message<?> message = MessageBuilder.withPayload("test").setReplyChannel(replyChannel).build(); this.gatewayTestInputChannel.send(message); Message<?> reply = replyChannel.receive(0); assertEquals( "gatewayTestInputChannel,gatewayTestService,gateway,requestChannel,bridge,replyChannel", reply.getHeaders().get("history").toString()); }
@Test public void testGoodNetMultiplex() throws Exception { final int port = SocketUtils.findAvailableServerSocket(); final CountDownLatch latch = new CountDownLatch(1); final AtomicBoolean done = new AtomicBoolean(); Executors.newSingleThreadExecutor() .execute( new Runnable() { public void run() { try { ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port, 10); latch.countDown(); int i = 0; Socket socket = server.accept(); while (true) { ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()); ois.readObject(); ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); oos.writeObject("Reply" + (i++)); } } catch (Exception e) { if (!done.get()) { e.printStackTrace(); } } } }); AbstractConnectionFactory ccf = new TcpNetClientConnectionFactory("localhost", port); ccf.setSerializer(new DefaultSerializer()); ccf.setDeserializer(new DefaultDeserializer()); ccf.setSoTimeout(10000); ccf.setSingleUse(false); ccf.start(); assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); TcpOutboundGateway gateway = new TcpOutboundGateway(); gateway.setConnectionFactory(ccf); QueueChannel replyChannel = new QueueChannel(); gateway.setRequiresReply(true); gateway.setOutputChannel(replyChannel); for (int i = 100; i < 110; i++) { gateway.handleMessage(MessageBuilder.withPayload("Test" + i).build()); } Set<String> replies = new HashSet<String>(); for (int i = 100; i < 110; i++) { Message<?> m = replyChannel.receive(10000); assertNotNull(m); replies.add((String) m.getPayload()); } for (int i = 0; i < 10; i++) { assertTrue(replies.remove("Reply" + i)); } done.set(true); gateway.stop(); }
@Test public void splitMessageWithEmptyCollectionPayload() throws Exception { Message<List<String>> message = MessageBuilder.withPayload(Collections.<String>emptyList()).build(); QueueChannel replyChannel = new QueueChannel(); DefaultMessageSplitter splitter = new DefaultMessageSplitter(); splitter.setOutputChannel(replyChannel); splitter.handleMessage(message); Message<?> output = replyChannel.receive(15); assertThat(output, is(nullValue())); }
@Test public void testReplyingMessageHandlerWithOtherMethod() { QueueChannel replyChannel = new QueueChannel(); Message<?> message = MessageBuilder.withPayload("test").setReplyChannel(replyChannel).build(); this.replyingHandlerWithOtherMethodTestInputChannel.send(message); Message<?> reply = replyChannel.receive(0); assertEquals("bar", reply.getPayload()); assertEquals( "replyingHandlerWithOtherMethodTestInputChannel,replyingHandlerWithOtherMethodTestService", reply.getHeaders().get("history").toString()); }
@Test public void testSkipEmpty() { inputChannel.send(MessageBuilder.withPayload(" a ,,z ").build()); Message<?> outMessage = testChannel.receive(0); assertNotNull(outMessage); assertThat(outMessage, hasPayload("a")); outMessage = testChannel.receive(0); assertNotNull(outMessage); assertThat(outMessage, hasPayload("z")); outMessage = testChannel.receive(0); assertNull("Only two messages expected", outMessage); }
@Test public void testNioSerial() throws Exception { final int port = SocketTestUtils.findAvailableServerSocket(); final CountDownLatch latch = new CountDownLatch(1); final AtomicBoolean done = new AtomicBoolean(); Executors.newSingleThreadExecutor() .execute( new Runnable() { public void run() { try { ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port); latch.countDown(); Socket socket = server.accept(); int i = 0; while (true) { ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()); ois.readObject(); ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); oos.writeObject("Reply" + (++i)); } } catch (Exception e) { if (!done.get()) { e.printStackTrace(); } } } }); AbstractConnectionFactory ccf = new TcpNioClientConnectionFactory("localhost", port); ccf.setSerializer(new DefaultSerializer()); ccf.setDeserializer(new DefaultDeserializer()); ccf.setSoTimeout(10000); ccf.start(); TcpSendingMessageHandler handler = new TcpSendingMessageHandler(); handler.setConnectionFactory(ccf); TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter(); adapter.setConnectionFactory(ccf); QueueChannel channel = new QueueChannel(); adapter.setOutputChannel(channel); assertTrue(latch.await(10, TimeUnit.SECONDS)); handler.handleMessage(MessageBuilder.withPayload("Test").build()); handler.handleMessage(MessageBuilder.withPayload("Test").build()); Set<String> results = new HashSet<String>(); Message<?> mOut = channel.receive(10000); assertNotNull(mOut); results.add((String) mOut.getPayload()); mOut = channel.receive(10000); assertNotNull(mOut); results.add((String) mOut.getPayload()); assertTrue(results.remove("Reply1")); assertTrue(results.remove("Reply2")); done.set(true); }
@Test public void correlationIdCopiedFromMessageId() { Message<String> message = MessageBuilder.withPayload("test").build(); DirectChannel inputChannel = new DirectChannel(); QueueChannel outputChannel = new QueueChannel(1); DefaultMessageSplitter splitter = new DefaultMessageSplitter(); splitter.setOutputChannel(outputChannel); EventDrivenConsumer endpoint = new EventDrivenConsumer(inputChannel, splitter); endpoint.start(); assertTrue(inputChannel.send(message)); Message<?> reply = outputChannel.receive(0); assertEquals(message.getHeaders().getId(), reply.getHeaders().getCorrelationId()); }
@Test public void transformer() { QueueChannel replyChannel = new QueueChannel(); Message<?> message = MessageBuilder.withPayload(new TestBean1("transformer-test")) .setReplyChannel(replyChannel) .build(); this.transformerChannel.send(message); Message<?> result = replyChannel.receive(0); assertNotNull(result); assertNotNull(result.getPayload()); assertEquals(TestBean2.class, result.getPayload().getClass()); assertEquals("TRANSFORMER-TEST", ((TestBean2) result.getPayload()).text); }
@Test public void serviceActivatorUsingInnerConverterDefinition() { QueueChannel replyChannel = new QueueChannel(); Message<?> message = MessageBuilder.withPayload(new TestBean1("service-test")) .setReplyChannel(replyChannel) .build(); this.serviceActivatorChannel3.send(message); Message<?> result = replyChannel.receive(0); assertNotNull(result); assertNotNull(result.getPayload()); assertEquals(TestBean3.class, result.getPayload().getClass()); assertEquals("SERVICE-TEST", ((TestBean3) result.getPayload()).text); }
@Test public void filter() { QueueChannel replyChannel = new QueueChannel(); Message<?> message = MessageBuilder.withPayload(new TestBean1("filter-test")) .setReplyChannel(replyChannel) .build(); this.filterChannel.send(message); Message<?> result = replyChannel.receive(0); assertNotNull(result); assertNotNull(result.getPayload()); assertEquals(TestBean1.class, result.getPayload().getClass()); assertEquals("filter-test", ((TestBean1) result.getPayload()).text); }