@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 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 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 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 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 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 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 inlineScript() { QueueChannel replyChannel = new QueueChannel(); replyChannel.setBeanName("returnAddress"); for (int i = 1; i <= 3; i++) { Message<?> message = MessageBuilder.withPayload("test-" + i).setReplyChannel(replyChannel).build(); this.inlineScriptInput.send(message); } assertEquals("inline-test-1", replyChannel.receive(0).getPayload()); assertEquals("inline-test-2", replyChannel.receive(0).getPayload()); assertEquals("inline-test-3", replyChannel.receive(0).getPayload()); assertNull(replyChannel.receive(0)); }
@Test public final void testRoutingWithGroovy() throws InterruptedException { assertEquals(0, streamRepository.count()); final StreamDefinition routerDefinition = new StreamDefinition( "routerDefinition", "queue:routeit > router --script='org/springframework/xd/dirt/stream/router.groovy'"); streamDefinitionRepository.save(routerDefinition); streamDeployer.deploy("routerDefinition"); Thread.sleep(1000); assertEquals(1, streamRepository.count()); assertModuleRequest("router", false); final Module module = getModule("router", 0, moduleDeployer); final MessageChannel inputChannel = module.getComponent("routeit", MessageChannel.class); module.getComponent(MessageBus.class); assertNotNull(inputChannel); final MessageChannel outputChannelFoo = module.getComponent("queue:foo", MessageChannel.class); final MessageChannel outputChannelBar = module.getComponent("queue:bar", MessageChannel.class); assertNull(outputChannelFoo); assertNull(outputChannelBar); inputChannel.send(MessageBuilder.withPayload("a").build()); Thread.sleep(2000); final MessageChannel outputChannelFoo2 = module.getComponent("queue:foo", MessageChannel.class); final MessageChannel outputChannelBar2 = module.getComponent("queue:bar", MessageChannel.class); assertNotNull(outputChannelFoo2); assertNull(outputChannelBar2); inputChannel.send(MessageBuilder.withPayload("b").build()); Thread.sleep(1000); final QueueChannel outputChannelFoo3 = module.getComponent("queue:foo", QueueChannel.class); final QueueChannel outputChannelBar3 = module.getComponent("queue:bar", QueueChannel.class); assertNotNull(outputChannelFoo3); assertNotNull(outputChannelBar3); assertTrue(outputChannelFoo3.getQueueSize() == 1); assertTrue(outputChannelBar3.getQueueSize() == 1); final Message<?> fooMessage = outputChannelFoo3.receive(2000); final Message<?> barMessage = outputChannelBar3.receive(2000); assertEquals("a", fooMessage.getPayload()); assertEquals("b", barMessage.getPayload()); }
@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()); }
@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 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(); }
@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 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(); }
@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 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 demoMethodNameMappingExpressionSource() { Map<String, String> expressionMap = new HashMap<String, String>(); expressionMap.put("test", "#return"); MethodNameMappingPublisherMetadataSource metadataSource = new MethodNameMappingPublisherMetadataSource(expressionMap); Map<String, String> channelMap = new HashMap<String, String>(); channelMap.put("test", "c"); metadataSource.setChannelMap(channelMap); Map<String, Map<String, String>> headerExpressionMap = new HashMap<String, Map<String, String>>(); Map<String, String> headerExpressions = new HashMap<String, String>(); headerExpressions.put("bar", "#return"); headerExpressions.put("name", "'oleg'"); headerExpressionMap.put("test", headerExpressions); metadataSource.setHeaderExpressionMap(headerExpressionMap); MessagePublishingInterceptor interceptor = new MessagePublishingInterceptor(metadataSource); interceptor.setBeanFactory(beanFactory); interceptor.setChannelResolver(channelResolver); ProxyFactory pf = new ProxyFactory(new TestBeanImpl()); pf.addAdvice(interceptor); TestBean proxy = (TestBean) pf.getProxy(); proxy.test(); Message<?> message = testChannel.receive(0); assertNotNull(message); assertEquals("foo", message.getPayload()); assertEquals("foo", message.getHeaders().get("bar")); assertEquals("oleg", message.getHeaders().get("name")); }
@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 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 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 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 testQueue() throws Exception { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("gemfire-queue-config.xml", this.getClass()); QueueChannel gemfireQueue = context.getBean("gemfireQueue", QueueChannel.class); QueueChannel outputQueue = context.getBean("outputQueue", QueueChannel.class); for (int i = 0; i < 20; i++) { gemfireQueue.send(new GenericMessage<String>("Hello")); Thread.sleep(1); } for (int i = 0; i < 20; i++) { assertNotNull(outputQueue.receive(5000)); } assertNull(outputQueue.receive(1)); context.close(); }
@Test public void demoMessagePublishingInterceptor() { String name = testBean.setName("John", "Doe"); Assert.assertNotNull(name); Message<?> message = channel.receive(1000); Assert.assertNotNull(message); Assert.assertEquals("John Doe", message.getPayload()); Assert.assertEquals("bar", message.getHeaders().get("foo")); }
@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 @Ignore // dropped backwards compatibility for setting capacity limit (it's always // Integer.MAX_VALUE) public void testTrackedCorrelationIdsCapacityAtLimit() { QueueChannel replyChannel = new QueueChannel(); QueueChannel discardChannel = new QueueChannel(); // this.aggregator.setTrackedCorrelationIdCapacity(3); this.aggregator.setDiscardChannel(discardChannel); this.aggregator.handleMessage(createMessage(1, 1, 1, 1, replyChannel, null)); assertEquals(1, replyChannel.receive(1000).getPayload()); this.aggregator.handleMessage(createMessage(3, 2, 1, 1, replyChannel, null)); assertEquals(3, replyChannel.receive(1000).getPayload()); this.aggregator.handleMessage(createMessage(4, 3, 1, 1, replyChannel, null)); assertEquals(4, replyChannel.receive(1000).getPayload()); // next message with same correlation ID is discarded this.aggregator.handleMessage(createMessage(2, 1, 1, 1, replyChannel, null)); assertEquals(2, discardChannel.receive(1000).getPayload()); }
@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())); }