Updated the names of the projects

This commit is contained in:
Ben Hale
2008-05-20 21:41:01 +00:00
parent 37f8d925c8
commit 6696064dd0
531 changed files with 48 additions and 48 deletions

View File

@@ -0,0 +1,7 @@
log4j.rootCategory=WARN, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%c{1}: %m%n
log4j.category.org.springframework.integration=INFO

View File

@@ -0,0 +1,96 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.Set;
import org.junit.Test;
import org.springframework.integration.message.MessageHeader;
/**
* @author Mark Fisher
*/
public class MessageHeaderTests {
@Test
public void testTimestamp() {
MessageHeader header = new MessageHeader();
assertNotNull(header.getTimestamp());
}
@Test
public void testAttributes() {
MessageHeader header = new MessageHeader();
Integer value = new Integer(123);
Object previousValue = header.setAttribute("test", value);
assertNull(previousValue);
assertEquals(value, header.getAttribute("test"));
assertNull(header.getAttribute("nosuchattribute"));
Set<String> names = header.getAttributeNames();
assertEquals(1, names.size());
assertTrue(names.contains("test"));
Integer newValue = new Integer(456);
previousValue = header.setAttribute("test", newValue);
assertEquals(value, previousValue);
assertEquals(newValue, header.getAttribute("test"));
}
@Test
public void testProperties() {
MessageHeader header = new MessageHeader();
String previousValue = header.setProperty("foo", "bar");
assertNull(previousValue);
assertEquals("bar", header.getProperty("foo"));
assertNull(header.getProperty("nosuchproperty"));
Set<String> names = header.getPropertyNames();
assertEquals(1, names.size());
assertTrue(names.contains("foo"));
previousValue = header.setProperty("foo", "baz");
assertEquals("bar", previousValue);
assertEquals("baz", header.getProperty("foo"));
}
@Test
public void testSetAttributeIfAbsent() {
MessageHeader header = new MessageHeader();
Integer integer = new Integer(123);
assertNull(header.getAttribute("test"));
assertFalse(header.getAttributeNames().contains("test"));
Object existingValue = header.setAttributeIfAbsent("test", integer);
assertNull(existingValue);
assertEquals(integer, header.getAttribute("test"));
assertTrue(header.getAttributeNames().contains("test"));
}
@Test
public void testSetAttributeIfAbsentDoesNotOverride() {
MessageHeader header = new MessageHeader();
Integer originalValue = new Integer(123);
header.setAttributeIfAbsent("test", originalValue);
Object existingValue = header.setAttributeIfAbsent("test", new Integer(456));
assertEquals(originalValue, header.getAttribute("test"));
assertEquals(originalValue, existingValue);
}
}

View File

@@ -0,0 +1,26 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.aop;
/**
* @author Mark Fisher
*/
public interface ITestBean {
String test();
}

View File

@@ -0,0 +1,99 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.aop;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import org.junit.Test;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.integration.channel.MessageChannel;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.message.Message;
/**
* @author Mark Fisher
*/
public class MessagePublishingInterceptorTests {
@Test
public void testNonNullReturnValuePublishedWithDefaultChannel() {
MessageChannel channel = new QueueChannel();
MessagePublishingInterceptor interceptor = new MessagePublishingInterceptor();
interceptor.setDefaultChannel(channel);
TestService proxy = (TestService) this.createProxy(new TestServiceImpl("hello world"), interceptor);
proxy.messageTest();
Message<?> message = channel.receive(0);
assertNotNull(message);
assertEquals("hello world", message.getPayload());
}
@Test
public void testNullReturnValueNotPublished() {
MessageChannel channel = new QueueChannel();
MessagePublishingInterceptor interceptor = new MessagePublishingInterceptor();
interceptor.setDefaultChannel(channel);
TestService proxy = (TestService) this.createProxy(new TestServiceImpl(null), interceptor);
proxy.messageTest();
assertNull(channel.receive(0));
}
@Test
public void testVoidReturnValueNotPublished() {
MessageChannel channel = new QueueChannel();
MessagePublishingInterceptor interceptor = new MessagePublishingInterceptor();
interceptor.setDefaultChannel(channel);
TestService proxy = (TestService) this.createProxy(new TestServiceImpl(null), interceptor);
proxy.voidTest();
assertNull(channel.receive(0));
}
private Object createProxy(Object target, MessagePublishingInterceptor interceptor) {
ProxyFactory factory = new ProxyFactory(target);
factory.addAdvice(interceptor);
return factory.getProxy();
}
private static interface TestService {
String messageTest();
void voidTest();
}
private static class TestServiceImpl implements TestService {
private String message;
public TestServiceImpl(String message) {
this.message = message;
}
public String messageTest() {
return this.message;
}
public void voidTest() {
return;
}
}
}

View File

@@ -0,0 +1,98 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.aop;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import org.junit.Test;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.integration.annotation.Publisher;
import org.springframework.integration.channel.ChannelRegistry;
import org.springframework.integration.channel.DefaultChannelRegistry;
import org.springframework.integration.channel.MessageChannel;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.message.Message;
/**
* @author Mark Fisher
*/
public class PublisherAnnotationAdvisorTests {
@Test
public void testPublisherAnnotation() {
final MessageChannel channel = new QueueChannel();
ChannelRegistry channelRegistry = new DefaultChannelRegistry();
channelRegistry.registerChannel("testChannel", channel);
PublisherAnnotationAdvisor advisor = new PublisherAnnotationAdvisor(channelRegistry);
TestService proxy = (TestService) this.createProxy(new TestServiceImpl("hello world"), advisor);
proxy.publisherTest();
Message<?> message = channel.receive(0);
assertNotNull(message);
assertEquals("hello world", message.getPayload());
}
@Test
public void testNoPublisherAnnotation() {
final MessageChannel channel = new QueueChannel();
ChannelRegistry channelRegistry = new DefaultChannelRegistry();
channelRegistry.registerChannel("testChannel", channel);
PublisherAnnotationAdvisor advisor = new PublisherAnnotationAdvisor(channelRegistry);
TestService proxy = (TestService) this.createProxy(new TestServiceImpl("hello world"), advisor);
proxy.noPublisherTest();
Message<?> message = channel.receive(0);
assertNull(message);
}
private Object createProxy(Object target, PublisherAnnotationAdvisor advisor) {
ProxyFactory factory = new ProxyFactory(target);
factory.addAdvisor(advisor);
return factory.getProxy();
}
private static interface TestService {
String publisherTest();
String noPublisherTest();
}
private static class TestServiceImpl implements TestService {
private String message;
public TestServiceImpl(String message) {
this.message = message;
}
@Publisher(channel="testChannel")
public String publisherTest() {
return this.message;
}
public String noPublisherTest() {
return this.message;
}
}
}

View File

@@ -0,0 +1,44 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.aop;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.channel.MessageChannel;
import org.springframework.integration.message.Message;
/**
* @author Mark Fisher
*/
public class PublisherAnnotationPostProcessorTests {
@Test
public void testPublisherAnnotation() {
ApplicationContext context = new ClassPathXmlApplicationContext(
"publisherAnnotationPostProcessorTests.xml", this.getClass());
ITestBean testBean = (ITestBean) context.getBean("testBean");
testBean.test();
MessageChannel channel = (MessageChannel) context.getBean("testChannel");
Message result = channel.receive();
assertEquals("test", result.getPayload());
}
}

View File

@@ -0,0 +1,32 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.aop;
import org.springframework.integration.annotation.Publisher;
/**
* @author Mark Fisher
*/
public class PublisherAnnotationTestBean implements ITestBean {
@Publisher(channel="testChannel")
public String test() {
return "test";
}
}

View File

@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="messageBus" class="org.springframework.integration.bus.MessageBus"/>
<bean id="testChannel" class="org.springframework.integration.channel.QueueChannel"/>
<bean id="testBean" class="org.springframework.integration.aop.PublisherAnnotationTestBean"/>
<bean class="org.springframework.integration.config.PublisherAnnotationPostProcessor">
<property name="channelRegistry" ref="messageBus"/>
</bean>
</beans>

View File

@@ -0,0 +1,139 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.bus;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import org.springframework.integration.annotation.Handler;
import org.springframework.integration.annotation.MessageEndpoint;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.channel.MessageChannel;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.channel.ThreadLocalChannel;
import org.springframework.integration.config.MessageEndpointAnnotationPostProcessor;
import org.springframework.integration.endpoint.HandlerEndpoint;
import org.springframework.integration.handler.MessageHandler;
import org.springframework.integration.message.Message;
import org.springframework.integration.message.MessagingException;
import org.springframework.integration.message.StringMessage;
import org.springframework.integration.scheduling.Subscription;
/**
* @author Mark Fisher
*/
public class DirectChannelSubscriptionTests {
private MessageBus bus = new MessageBus();
private MessageChannel sourceChannel = new DirectChannel();
private MessageChannel targetChannel = new ThreadLocalChannel();
@Before
public void setupChannels() {
bus.registerChannel("sourceChannel", sourceChannel);
bus.registerChannel("targetChannel", targetChannel);
}
@Test
public void testSendAndReceiveForRegisteredEndpoint() {
HandlerEndpoint endpoint = new HandlerEndpoint(new TestHandler());
endpoint.setSubscription(new Subscription("sourceChannel"));
endpoint.setOutputChannelName("targetChannel");
bus.registerEndpoint("testEndpoint", endpoint);
bus.start();
this.sourceChannel.send(new StringMessage("foo"));
Message<?> response = this.targetChannel.receive();
assertEquals("foo!", response.getPayload());
bus.stop();
}
@Test
public void testSendAndReceiveForAnnotatedEndpoint() {
MessageEndpointAnnotationPostProcessor postProcessor = new MessageEndpointAnnotationPostProcessor(bus);
postProcessor.afterPropertiesSet();
TestEndpoint endpoint = new TestEndpoint();
postProcessor.postProcessAfterInitialization(endpoint, "testEndpoint");
bus.start();
this.sourceChannel.send(new StringMessage("foo"));
Message<?> response = this.targetChannel.receive();
assertEquals("foo-from-annotated-endpoint", response.getPayload());
bus.stop();
}
@Test(expected=MessagingException.class)
public void testExceptionThrownFromRegisteredEndpoint() {
QueueChannel errorChannel = new QueueChannel();
bus.setErrorChannel(errorChannel);
HandlerEndpoint endpoint = new HandlerEndpoint(new MessageHandler() {
public Message<?> handle(Message<?> message) {
throw new RuntimeException("intentional test failure");
}
});
endpoint.setSubscription(new Subscription("sourceChannel"));
endpoint.setOutputChannelName("targetChannel");
bus.registerEndpoint("testEndpoint", endpoint);
bus.start();
this.sourceChannel.send(new StringMessage("foo"));
}
@Test(expected=MessagingException.class)
public void testExceptionThrownFromAnnotatedEndpoint() {
QueueChannel errorChannel = new QueueChannel();
bus.setErrorChannel(errorChannel);
MessageEndpointAnnotationPostProcessor postProcessor = new MessageEndpointAnnotationPostProcessor(bus);
postProcessor.afterPropertiesSet();
FailingTestEndpoint endpoint = new FailingTestEndpoint();
postProcessor.postProcessAfterInitialization(endpoint, "testEndpoint");
bus.start();
this.sourceChannel.send(new StringMessage("foo"));
}
private static class TestHandler implements MessageHandler {
public Message<?> handle(Message<?> message) {
return new StringMessage(message.getPayload() + "!");
}
}
@MessageEndpoint(input="sourceChannel", output="targetChannel")
public static class TestEndpoint {
@Handler
public Message<?> handle(Message<?> message) {
return new StringMessage(message.getPayload() + "-from-annotated-endpoint");
}
}
@MessageEndpoint(input="sourceChannel", output="targetChannel")
public static class FailingTestEndpoint {
@Handler
public Message<?> handle(Message<?> message) {
throw new RuntimeException("intentional test failure");
}
}
}

View File

@@ -0,0 +1,274 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.bus;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.channel.DispatcherPolicy;
import org.springframework.integration.channel.MessageChannel;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.channel.RendezvousChannel;
import org.springframework.integration.endpoint.ConcurrencyPolicy;
import org.springframework.integration.endpoint.SourceEndpoint;
import org.springframework.integration.handler.MessageHandler;
import org.springframework.integration.message.ErrorMessage;
import org.springframework.integration.message.GenericMessage;
import org.springframework.integration.message.Message;
import org.springframework.integration.message.MessageDeliveryException;
import org.springframework.integration.message.Source;
import org.springframework.integration.message.StringMessage;
import org.springframework.integration.scheduling.PollingSchedule;
import org.springframework.integration.scheduling.Subscription;
/**
* @author Mark Fisher
*/
public class MessageBusTests {
@Test
public void testOutputChannel() {
MessageBus bus = new MessageBus();
MessageChannel sourceChannel = new QueueChannel();
MessageChannel targetChannel = new QueueChannel();
bus.registerChannel("sourceChannel", sourceChannel);
StringMessage message = new StringMessage("test");
message.getHeader().setReturnAddress("targetChannel");
sourceChannel.send(message);
bus.registerChannel("targetChannel", targetChannel);
MessageHandler handler = new MessageHandler() {
public Message<?> handle(Message<?> message) {
return message;
}
};
Subscription subscription = new Subscription(sourceChannel);
bus.registerHandler("handler", handler, subscription);
bus.start();
Message<?> result = targetChannel.receive(3000);
assertEquals("test", result.getPayload());
bus.stop();
}
@Test
public void testChannelsWithoutHandlers() {
MessageBus bus = new MessageBus();
MessageChannel sourceChannel = new QueueChannel();
sourceChannel.send(new StringMessage("123", "test"));
MessageChannel targetChannel = new QueueChannel();
bus.registerChannel("sourceChannel", sourceChannel);
bus.registerChannel("targetChannel", targetChannel);
bus.start();
Message<?> result = targetChannel.receive(100);
assertNull(result);
bus.stop();
}
@Test
public void testAutodetectionWithApplicationContext() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("messageBusTests.xml", this.getClass());
context.start();
MessageChannel sourceChannel = (MessageChannel) context.getBean("sourceChannel");
sourceChannel.send(new GenericMessage<String>("123", "test"));
MessageChannel targetChannel = (MessageChannel) context.getBean("targetChannel");
MessageBus bus = (MessageBus) context.getBean("bus");
bus.start();
Message<?> result = targetChannel.receive(1000);
assertEquals("test", result.getPayload());
}
@Test
public void testExactlyOneHandlerReceivesPointToPointMessage() {
QueueChannel inputChannel = new QueueChannel();
QueueChannel outputChannel1 = new QueueChannel();
QueueChannel outputChannel2 = new QueueChannel();
MessageHandler handler1 = new MessageHandler() {
public Message<?> handle(Message<?> message) {
message.getHeader().setReturnAddress("output1");
return message;
}
};
MessageHandler handler2 = new MessageHandler() {
public Message<?> handle(Message<?> message) {
message.getHeader().setReturnAddress("output2");
return message;
}
};
MessageBus bus = new MessageBus();
bus.registerChannel("input", inputChannel);
bus.registerChannel("output1", outputChannel1);
bus.registerChannel("output2", outputChannel2);
bus.registerHandler("handler1", handler1, new Subscription(inputChannel));
bus.registerHandler("handler2", handler2, new Subscription(inputChannel));
bus.start();
inputChannel.send(new StringMessage(1, "testing"));
Message<?> message1 = outputChannel1.receive(100);
Message<?> message2 = outputChannel2.receive(0);
bus.stop();
assertTrue("exactly one message should be null", message1 == null ^ message2 == null);
}
@Test
public void testBothHandlersReceivePublishSubscribeMessage() throws InterruptedException {
DispatcherPolicy dispatcherPolicy = new DispatcherPolicy(true);
QueueChannel inputChannel = new QueueChannel(10, dispatcherPolicy);
QueueChannel outputChannel1 = new QueueChannel();
QueueChannel outputChannel2 = new QueueChannel();
final CountDownLatch latch = new CountDownLatch(2);
MessageHandler handler1 = new MessageHandler() {
public Message<?> handle(Message<?> message) {
message.getHeader().setReturnAddress("output1");
latch.countDown();
return message;
}
};
MessageHandler handler2 = new MessageHandler() {
public Message<?> handle(Message<?> message) {
message.getHeader().setReturnAddress("output2");
latch.countDown();
return message;
}
};
MessageBus bus = new MessageBus();
bus.registerChannel("input", inputChannel);
bus.registerChannel("output1", outputChannel1);
bus.registerChannel("output2", outputChannel2);
bus.registerHandler("handler1", handler1, new Subscription(inputChannel));
bus.registerHandler("handler2", handler2, new Subscription(inputChannel));
bus.start();
inputChannel.send(new StringMessage(1, "testing"));
latch.await(500, TimeUnit.MILLISECONDS);
assertEquals("both handlers should have been invoked", 0, latch.getCount());
Message<?> message1 = outputChannel1.receive(500);
Message<?> message2 = outputChannel2.receive(500);
bus.stop();
assertNotNull("both handlers should have replied to the message", message1);
assertNotNull("both handlers should have replied to the message", message2);
}
@Test
public void testErrorChannelWithFailedDispatch() throws InterruptedException {
MessageBus bus = new MessageBus();
CountDownLatch latch = new CountDownLatch(1);
SourceEndpoint sourceEndpoint = new SourceEndpoint(new FailingSource(latch), new QueueChannel(), new PollingSchedule(1000));
bus.registerEndpoint("testEndpoint", sourceEndpoint);
bus.start();
latch.await(1000, TimeUnit.MILLISECONDS);
Message<?> message = bus.getErrorChannel().receive(100);
assertNotNull("message should not be null", message);
assertTrue(message instanceof ErrorMessage);
assertEquals("intentional test failure", ((ErrorMessage) message).getPayload().getMessage());
bus.stop();
}
@Test
public void testDefaultConcurrencyPolicy() throws InterruptedException {
MessageBus bus = new MessageBus();
bus.setDefaultConcurrencyPolicy(new ConcurrencyPolicy(1, 3));
final CountDownLatch latch = new CountDownLatch(3);
MessageHandler testHandler = new MessageHandler() {
public Message<?> handle(Message<?> message) {
latch.countDown();
try {
Thread.sleep(5000);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return null;
}
};
DispatcherPolicy dispatcherPolicy = new DispatcherPolicy();
dispatcherPolicy.setRejectionLimit(1);
dispatcherPolicy.setRetryInterval(0);
RendezvousChannel testChannel = new RendezvousChannel(dispatcherPolicy);
bus.registerChannel("testChannel", testChannel);
bus.registerHandler("testHandler", testHandler, new Subscription(testChannel));
bus.start();
for (int i = 0; i < 4; i++) {
assertTrue(testChannel.send(new StringMessage("test-"+ i), 1000));
}
latch.await(1000, TimeUnit.MILLISECONDS);
assertEquals(0, latch.getCount());
MessageChannel errorChannel = bus.getErrorChannel();
Message<?> errorMessage = errorChannel.receive(500);
assertNotNull(errorMessage);
assertEquals(MessageDeliveryException.class, errorMessage.getPayload().getClass());
}
@Test(expected = BeanCreationException.class)
public void testMultipleMessageBusBeans() {
new ClassPathXmlApplicationContext("multipleMessageBusBeans.xml", this.getClass());
}
@Test
public void testErrorChannelRegistration() {
MessageChannel errorChannel = new QueueChannel();
MessageBus bus = new MessageBus();
bus.setErrorChannel(errorChannel);
assertEquals(errorChannel, bus.getErrorChannel());
}
@Test
public void testHandlerSubscribedToErrorChannel() throws InterruptedException {
MessageChannel errorChannel = new QueueChannel();
MessageBus bus = new MessageBus();
bus.setErrorChannel(errorChannel);
final CountDownLatch latch = new CountDownLatch(1);
MessageHandler handler = new MessageHandler() {
public Message<?> handle(Message<?> message) {
latch.countDown();
return null;
}
};
bus.registerHandler("testHandler", handler, new Subscription(MessageBus.ERROR_CHANNEL_NAME));
bus.start();
errorChannel.send(new ErrorMessage(new RuntimeException("test-exception")));
latch.await(1000, TimeUnit.MILLISECONDS);
assertEquals("handler should have received error message", 0, latch.getCount());
}
@Test
public void testMessageBusAwareImpl() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("messageBusTests.xml", this.getClass());
TestMessageBusAwareImpl messageBusAwareBean = (TestMessageBusAwareImpl) context.getBean("messageBusAwareBean");
assertTrue(messageBusAwareBean.getMessageBus() == context.getBean("bus"));
}
private static class FailingSource implements Source<Object> {
private CountDownLatch latch;
public FailingSource(CountDownLatch latch) {
this.latch = latch;
}
public Message<Object> receive() {
latch.countDown();
throw new RuntimeException("intentional test failure");
}
}
}

View File

@@ -0,0 +1,461 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.bus;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import org.springframework.integration.bus.SubscriptionManager;
import org.springframework.integration.channel.DispatcherPolicy;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.endpoint.ConcurrencyPolicy;
import org.springframework.integration.endpoint.HandlerEndpoint;
import org.springframework.integration.handler.MessageHandler;
import org.springframework.integration.handler.MessageHandlerRejectedExecutionException;
import org.springframework.integration.handler.TestHandlers;
import org.springframework.integration.message.ErrorMessage;
import org.springframework.integration.message.Message;
import org.springframework.integration.message.MessageDeliveryException;
import org.springframework.integration.message.StringMessage;
import org.springframework.integration.message.Target;
import org.springframework.integration.message.selector.PayloadTypeSelector;
import org.springframework.integration.scheduling.MessagePublishingErrorHandler;
import org.springframework.integration.scheduling.SimpleMessagingTaskScheduler;
/**
* @author Mark Fisher
*/
public class SubscriptionManagerTests {
private SimpleMessagingTaskScheduler scheduler = new SimpleMessagingTaskScheduler(new ScheduledThreadPoolExecutor(10));
@Test
public void testNonBroadcastingDispatcherSendsToExactlyOneEndpoint() throws InterruptedException {
final AtomicInteger counter1 = new AtomicInteger();
final AtomicInteger counter2 = new AtomicInteger();
final CountDownLatch latch = new CountDownLatch(1);
MessageHandler handler1 = TestHandlers.countingCountDownHandler(counter1, latch);
MessageHandler handler2 = TestHandlers.countingCountDownHandler(counter2, latch);
QueueChannel channel = new QueueChannel();
channel.send(new StringMessage(1, "test"));
SubscriptionManager manager = new SubscriptionManager(channel, scheduler);
manager.addTarget(createEndpoint(handler1, true));
manager.addTarget(createEndpoint(handler2, true));
manager.start();
latch.await(2000, TimeUnit.MILLISECONDS);
assertEquals("messages should have been dispatched within allotted time", 0, latch.getCount());
assertEquals("exactly one handler should have received message", 1, counter1.get() + counter2.get());
}
@Test
public void testBroadcastingDispatcherSendsToAllEndpoints() throws InterruptedException {
final AtomicInteger counter1 = new AtomicInteger();
final AtomicInteger counter2 = new AtomicInteger();
final CountDownLatch latch = new CountDownLatch(2);
MessageHandler handler1 = TestHandlers.countingCountDownHandler(counter1, latch);
MessageHandler handler2 = TestHandlers.countingCountDownHandler(counter2, latch);
QueueChannel channel = new QueueChannel(5, new DispatcherPolicy(true));
channel.send(new StringMessage(1, "test"));
SubscriptionManager manager = new SubscriptionManager(channel, scheduler);
manager.addTarget(createEndpoint(handler1, true));
manager.addTarget(createEndpoint(handler2, true));
manager.start();
latch.await(2000, TimeUnit.MILLISECONDS);
assertEquals("messages should have been dispatched within allotted time", 0, latch.getCount());
assertEquals("both handlers should have received message", 2, counter1.get() + counter2.get());
}
@Test
public void testNonBroadcastingDispatcherSkipsInactiveExecutor() throws InterruptedException {
final AtomicInteger counter1 = new AtomicInteger();
final AtomicInteger counter2 = new AtomicInteger();
final AtomicInteger counter3 = new AtomicInteger();
final CountDownLatch latch = new CountDownLatch(1);
MessageHandler handler1 = TestHandlers.countingCountDownHandler(counter1, latch);
MessageHandler handler2 = TestHandlers.countingCountDownHandler(counter2, latch);
MessageHandler handler3 = TestHandlers.countingCountDownHandler(counter3, latch);
QueueChannel channel = new QueueChannel();
SubscriptionManager manager = new SubscriptionManager(channel, scheduler);
HandlerEndpoint inactiveEndpoint = createEndpoint(handler1, true);
manager.addTarget(inactiveEndpoint);
manager.addTarget(createEndpoint(handler2, true));
manager.addTarget(createEndpoint(handler3, true));
manager.start();
inactiveEndpoint.stop();
channel.send(new StringMessage(1, "test"));
latch.await(2000, TimeUnit.MILLISECONDS);
assertEquals("messages should have been dispatched within allotted time", 0, latch.getCount());
assertEquals("inactive handler should not have received message", 0, counter1.get());
assertEquals("exactly one handler should have received message", 1, counter2.get() + counter3.get());
}
@Test
public void testBroadcastingDispatcherSkipsInactiveExecutor() throws InterruptedException {
final AtomicInteger counter1 = new AtomicInteger();
final AtomicInteger counter2 = new AtomicInteger();
final AtomicInteger counter3 = new AtomicInteger();
final CountDownLatch latch = new CountDownLatch(2);
MessageHandler handler1 = TestHandlers.countingCountDownHandler(counter1, latch);
MessageHandler handler2 = TestHandlers.countingCountDownHandler(counter2, latch);
MessageHandler handler3 = TestHandlers.countingCountDownHandler(counter3, latch);
QueueChannel channel = new QueueChannel(5, new DispatcherPolicy(true));
SubscriptionManager manager = new SubscriptionManager(channel, scheduler);
HandlerEndpoint inactiveEndpoint = createEndpoint(handler2, true);
manager.addTarget(createEndpoint(handler1, true));
manager.addTarget(inactiveEndpoint);
manager.addTarget(createEndpoint(handler3, true));
manager.start();
inactiveEndpoint.stop();
channel.send(new StringMessage(1, "test"));
latch.await(2000, TimeUnit.MILLISECONDS);
assertEquals("messages should have been dispatched within allotted time", 0, latch.getCount());
assertEquals("inactive handler should not have received message", 0, counter2.get());
assertEquals("both active handlers should have received message", 2, counter1.get() + counter3.get());
}
@Test
public void testDispatcherWithNoExecutorsDoesNotFail() {
QueueChannel channel = new QueueChannel();
channel.send(new StringMessage(1, "test"));
SubscriptionManager manager = new SubscriptionManager(channel, scheduler);
manager.start();
}
@Test
public void testBroadcastingDispatcherReachesRejectionLimitAndShouldFail() throws InterruptedException {
final AtomicInteger counter1 = new AtomicInteger();
final AtomicInteger counter3 = new AtomicInteger();
final CountDownLatch latch = new CountDownLatch(2);
MessageHandler handler1 = TestHandlers.countingCountDownHandler(counter1, latch);
MessageHandler handler3 = TestHandlers.countingCountDownHandler(counter3, latch);
QueueChannel channel = new QueueChannel(5, new DispatcherPolicy(true));
channel.getDispatcherPolicy().setRejectionLimit(2);
channel.getDispatcherPolicy().setRetryInterval(3);
channel.send(new StringMessage(1, "test"));
SubscriptionManager manager = new SubscriptionManager(channel, scheduler);
manager.addTarget(createEndpoint(handler1, true));
manager.addTarget(new Target() {
public boolean send(Message<?> message) {
throw new MessageHandlerRejectedExecutionException(message);
}
});
manager.addTarget(createEndpoint(handler3, true));
QueueChannel errorChannel = new QueueChannel();
scheduler.setErrorHandler(new MessagePublishingErrorHandler(errorChannel));
manager.start();
latch.await(2000, TimeUnit.MILLISECONDS);
assertEquals("messages should have been dispatched within allotted time", 0, latch.getCount());
Message<?> errorMessage = errorChannel.receive(1000);
assertNotNull(errorMessage);
assertTrue(errorMessage instanceof ErrorMessage);
assertEquals(MessageDeliveryException.class, ((ErrorMessage) errorMessage).getPayload().getClass());
}
@Test
public void testBroadcastingDispatcherReachesRejectionLimitAndShouldNotFail() throws InterruptedException {
final AtomicInteger counter1 = new AtomicInteger();
final AtomicInteger counter2 = new AtomicInteger();
final CountDownLatch latch = new CountDownLatch(3);
MessageHandler handler1 = TestHandlers.countingCountDownHandler(counter1, latch);
MessageHandler handler2 = TestHandlers.countingCountDownHandler(counter2, latch);
QueueChannel channel = new QueueChannel(5, new DispatcherPolicy(true));
channel.getDispatcherPolicy().setRejectionLimit(2);
channel.getDispatcherPolicy().setRetryInterval(3);
channel.getDispatcherPolicy().setShouldFailOnRejectionLimit(false);
channel.send(new StringMessage(1, "test"));
SubscriptionManager manager = new SubscriptionManager(channel, scheduler);
manager.addTarget(createEndpoint(handler1, false));
manager.addTarget(createEndpoint(new MessageHandler() {
public Message<?> handle(Message<?> message) {
latch.countDown();
throw new MessageHandlerRejectedExecutionException(message);
}
}, false));
manager.addTarget(createEndpoint(handler2, false));
manager.start();
latch.await(2000, TimeUnit.MILLISECONDS);
assertEquals("messages should have been dispatched within allotted time", 0, latch.getCount());
assertEquals("both non-rejecting handlers should have received message", 2, counter1.get() + counter2.get());
}
@Test
public void testNonBroadcastingDispatcherReachesRejectionLimitAndShouldFail() throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(4);
MessageHandler handler1 = TestHandlers.rejectingCountDownHandler(latch);
MessageHandler handler2 = TestHandlers.rejectingCountDownHandler(latch);
QueueChannel channel = new QueueChannel(5, new DispatcherPolicy(false));
channel.send(new StringMessage(1, "test"));
SubscriptionManager manager = new SubscriptionManager(channel, scheduler);
channel.getDispatcherPolicy().setRejectionLimit(2);
channel.getDispatcherPolicy().setRetryInterval(3);
manager.addTarget(createEndpoint(handler1, false));
manager.addTarget(createEndpoint(handler2, false));
QueueChannel errorChannel = new QueueChannel();
scheduler.setErrorHandler(new MessagePublishingErrorHandler(errorChannel));
manager.start();
latch.await(2000, TimeUnit.MILLISECONDS);
assertEquals("messages should have been dispatched within allotted time", 0, latch.getCount());
Message<?> errorMessage = errorChannel.receive(500);
assertNotNull(errorMessage);
assertTrue(errorMessage instanceof ErrorMessage);
assertEquals(MessageDeliveryException.class, ((ErrorMessage) errorMessage).getPayload().getClass());
}
@Test
public void testNonBroadcastingDispatcherReachesRejectionLimitButShouldNotFail() throws InterruptedException {
final AtomicInteger counter1 = new AtomicInteger();
final AtomicInteger counter2 = new AtomicInteger();
final AtomicInteger rejectedCounter1 = new AtomicInteger();
final AtomicInteger rejectedCounter2 = new AtomicInteger();
final CountDownLatch latch = new CountDownLatch(4);
QueueChannel channel = new QueueChannel();
channel.getDispatcherPolicy().setRejectionLimit(2);
channel.getDispatcherPolicy().setRetryInterval(3);
channel.getDispatcherPolicy().setShouldFailOnRejectionLimit(false);
channel.send(new StringMessage(1, "test"));
SubscriptionManager manager = new SubscriptionManager(channel, scheduler);
manager.addTarget(createEndpoint(new MessageHandler() {
public Message<?> handle(Message<?> message) {
rejectedCounter1.incrementAndGet();
latch.countDown();
throw new MessageHandlerRejectedExecutionException(message);
}
}, false));
manager.addTarget(createEndpoint(new MessageHandler() {
public Message<?> handle(Message<?> message) {
rejectedCounter2.incrementAndGet();
latch.countDown();
throw new MessageHandlerRejectedExecutionException(message);
}
}, false));
manager.start();
latch.await(2000, TimeUnit.MILLISECONDS);
assertEquals("messages should have been dispatched within allotted time", 0, latch.getCount());
assertEquals("latch should have counted down within allotted time", 0, latch.getCount());
assertEquals("rejecting handlers should not have received message", 0, counter1.get() + counter2.get());
assertEquals("handler1 should have rejected two times", 2, rejectedCounter1.get());
assertEquals("handler2 should have rejected two times", 2, rejectedCounter2.get());
}
@Test
public void testNonBroadcastingDispatcherWithOneEndpointSucceeding() throws InterruptedException {
final AtomicInteger counter1 = new AtomicInteger();
final AtomicInteger counter2 = new AtomicInteger();
final AtomicInteger counter3 = new AtomicInteger();
final AtomicInteger rejectedCounter1 = new AtomicInteger();
final AtomicInteger rejectedCounter2 = new AtomicInteger();
final AtomicInteger rejectedCounter3 = new AtomicInteger();
final CountDownLatch latch = new CountDownLatch(5);
final MessageHandler handler2 = TestHandlers.countingCountDownHandler(counter2, latch);
DispatcherPolicy dispatcherPolicy = new DispatcherPolicy();
dispatcherPolicy.setRejectionLimit(2);
dispatcherPolicy.setRetryInterval(3);
dispatcherPolicy.setShouldFailOnRejectionLimit(false);
QueueChannel channel = new QueueChannel(25, dispatcherPolicy);
channel.send(new StringMessage(1, "test"));
SubscriptionManager manager = new SubscriptionManager(channel, scheduler);
manager.addTarget(createEndpoint(new MessageHandler() {
public Message<?> handle(Message<?> message) {
rejectedCounter1.incrementAndGet();
latch.countDown();
throw new MessageHandlerRejectedExecutionException(message);
}
}, false));
manager.addTarget(createEndpoint(new MessageHandler() {
public Message<?> handle(Message<?> message) {
if (rejectedCounter2.get() == 1) {
return handler2.handle(message);
}
rejectedCounter2.incrementAndGet();
latch.countDown();
throw new MessageHandlerRejectedExecutionException(message);
}
}, false));
manager.addTarget(createEndpoint(new MessageHandler() {
public Message<?> handle(Message<?> message) {
rejectedCounter3.incrementAndGet();
latch.countDown();
throw new MessageHandlerRejectedExecutionException(message);
}
}, false));
manager.start();
latch.await(2000, TimeUnit.MILLISECONDS);
assertEquals("messages should have been dispatched within allotted time", 0, latch.getCount());
assertEquals("handler1 should not have received message", 0, counter1.get());
assertEquals("handler2 should have received message the second time", 1, counter2.get());
assertEquals("handler3 should not have received message", 0, counter3.get());
assertEquals("handler1 should have rejected two times", 2, rejectedCounter1.get());
assertEquals("handler2 should have rejected one time", 1, rejectedCounter2.get());
assertEquals("handler3 should have rejected one time", 1, rejectedCounter3.get());
}
@Test
public void testBroadcastingDispatcherStillRetriesRejectedExecutorAfterOtherSucceeds() throws InterruptedException {
final AtomicInteger counter1 = new AtomicInteger();
final AtomicInteger counter2 = new AtomicInteger();
final AtomicInteger rejectedCounter1 = new AtomicInteger();
final AtomicInteger rejectedCounter2 = new AtomicInteger();
final CountDownLatch latch = new CountDownLatch(8);
final MessageHandler handler1 = TestHandlers.countingCountDownHandler(counter1, latch);
final MessageHandler handler2 = TestHandlers.countingCountDownHandler(counter2, latch);
DispatcherPolicy dispatcherPolicy = new DispatcherPolicy(true);
dispatcherPolicy.setRejectionLimit(5);
dispatcherPolicy.setRetryInterval(3);
dispatcherPolicy.setShouldFailOnRejectionLimit(false);
QueueChannel channel = new QueueChannel(25, dispatcherPolicy);
channel.send(new StringMessage(1, "test"));
SubscriptionManager manager = new SubscriptionManager(channel, scheduler);
manager.addTarget(createEndpoint(new MessageHandler() {
public Message<?> handle(Message<?> message) {
if (rejectedCounter1.get() == 2) {
return handler1.handle(message);
}
rejectedCounter1.incrementAndGet();
latch.countDown();
throw new MessageHandlerRejectedExecutionException(message);
}
}, false));
manager.addTarget(createEndpoint(new MessageHandler() {
public Message<?> handle(Message<?> message) {
if (rejectedCounter2.get() == 4) {
return handler2.handle(message);
}
rejectedCounter2.incrementAndGet();
latch.countDown();
throw new MessageHandlerRejectedExecutionException(message);
}
}, false));
manager.start();
latch.await(2000, TimeUnit.MILLISECONDS);
assertEquals("messages should have been dispatched within allotted time", 0, latch.getCount());
assertEquals("handler1 should have received one message", 1, counter1.get());
assertEquals("handler2 should have received one message", 1, counter2.get());
assertEquals("handler1 should have rejected two times", 2, rejectedCounter1.get());
assertEquals("handler2 should have rejected four times", 4, rejectedCounter2.get());
}
@Test
public void testTwoExecutorsWithSelectorsAndOneAccepts() throws InterruptedException {
final AtomicInteger counter1 = new AtomicInteger();
final AtomicInteger counter2 = new AtomicInteger();
final CountDownLatch latch = new CountDownLatch(1);
MessageHandler handler1 = TestHandlers.countingCountDownHandler(counter1, latch);
MessageHandler handler2 = TestHandlers.countingCountDownHandler(counter2, latch);
QueueChannel channel = new QueueChannel();
channel.send(new StringMessage(1, "test"));
SubscriptionManager manager = new SubscriptionManager(channel, scheduler);
HandlerEndpoint endpoint1 = new HandlerEndpoint(handler1);
HandlerEndpoint endpoint2 = new HandlerEndpoint(handler2);
endpoint1.addMessageSelector(new PayloadTypeSelector(Integer.class));
endpoint2.addMessageSelector(new PayloadTypeSelector(String.class));
manager.addTarget(endpoint1);
manager.addTarget(endpoint2);
manager.start();
latch.await(2000, TimeUnit.MILLISECONDS);
assertEquals("messages should have been dispatched within allotted time", 0, latch.getCount());
assertEquals("handler1 should not have accepted the message", 0, counter1.get());
assertEquals("handler2 should have accepted the message", 1, counter2.get());
}
@Test
public void testTwoExecutorsWithSelectorsAndNeitherAccepts() throws InterruptedException {
final AtomicInteger counter1 = new AtomicInteger();
final AtomicInteger counter2 = new AtomicInteger();
final AtomicInteger selectorCounter1 = new AtomicInteger();
final AtomicInteger selectorCounter2 = new AtomicInteger();
final CountDownLatch selectorLatch = new CountDownLatch(2);
final CountDownLatch handlerLatch = new CountDownLatch(1);
MessageHandler handler1 = TestHandlers.countingCountDownHandler(counter1, handlerLatch);
MessageHandler handler2 = TestHandlers.countingCountDownHandler(counter2, handlerLatch);
QueueChannel channel = new QueueChannel();
channel.send(new StringMessage(1, "test"));
SubscriptionManager manager = new SubscriptionManager(channel, scheduler);
final HandlerEndpoint endpoint1 = new HandlerEndpoint(handler1);
final HandlerEndpoint endpoint2 = new HandlerEndpoint(handler2);
endpoint1.addMessageSelector(new PayloadTypeSelector(Integer.class) {
@Override
public boolean accept(Message<?> message) {
selectorCounter1.incrementAndGet();
selectorLatch.countDown();
return super.accept(message);
}
});
endpoint2.addMessageSelector(new PayloadTypeSelector(Integer.class) {
@Override
public boolean accept(Message<?> message) {
selectorCounter2.incrementAndGet();
selectorLatch.countDown();
return super.accept(message);
}
});
manager.addTarget(endpoint1);
manager.addTarget(endpoint2);
manager.start();
selectorLatch.await(2000, TimeUnit.MILLISECONDS);
assertEquals("messages should have been dispatched within allotted time", 0, selectorLatch.getCount());
assertEquals("handler1 should not have accepted the message", 0, counter1.get());
assertEquals("handler2 should not have accepted the message", 0, counter2.get());
assertEquals("executor1 should have had exactly one attempt", 1, selectorCounter1.get());
assertEquals("executor2 should have had exactly one attempt", 1, selectorCounter2.get());
assertEquals("handlerLatch should not have counted down", 1, handlerLatch.getCount());
}
@Test
public void testBroadcastingDispatcherWithSelectorsAndOneAccepts() throws InterruptedException {
final AtomicInteger counter1 = new AtomicInteger();
final AtomicInteger counter2 = new AtomicInteger();
final CountDownLatch latch = new CountDownLatch(1);
MessageHandler handler1 = TestHandlers.countingCountDownHandler(counter1, latch);
MessageHandler handler2 = TestHandlers.countingCountDownHandler(counter2, latch);
QueueChannel channel = new QueueChannel(5, new DispatcherPolicy(true));
channel.send(new StringMessage(1, "test"));
SubscriptionManager manager = new SubscriptionManager(channel, scheduler);
HandlerEndpoint endpoint1 = new HandlerEndpoint(handler1);
endpoint1.setConcurrencyPolicy(new ConcurrencyPolicy(1, 1));
HandlerEndpoint endpoint2 = new HandlerEndpoint(handler2);
endpoint2.setConcurrencyPolicy(new ConcurrencyPolicy(1, 1));
endpoint1.addMessageSelector(new PayloadTypeSelector(Integer.class));
endpoint2.addMessageSelector(new PayloadTypeSelector(String.class));
manager.addTarget(endpoint1);
manager.addTarget(endpoint2);
manager.start();
latch.await(2000, TimeUnit.MILLISECONDS);
assertEquals("messages should have been dispatched within allotted time", 0, latch.getCount());
assertEquals("endpoint1 should not have accepted the message", 0, counter1.get());
assertEquals("endpoint2 should have accepted the message", 1, counter2.get());
}
private static HandlerEndpoint createEndpoint(MessageHandler handler, boolean asynchronous) {
HandlerEndpoint endpoint = new HandlerEndpoint(handler);
if (asynchronous) {
endpoint.setConcurrencyPolicy(new ConcurrencyPolicy(1, 1));
}
endpoint.afterPropertiesSet();
return endpoint;
}
}

View File

@@ -0,0 +1,33 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.bus;
/**
* @author Marius Bogoevici
*/
public class TestMessageBusAwareImpl implements MessageBusAware {
private MessageBus messageBus;
public void setMessageBus(MessageBus messageBus) {
this.messageBus = messageBus;
}
public MessageBus getMessageBus() {
return messageBus;
}
}

View File

@@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="bus" class="org.springframework.integration.bus.MessageBus"/>
<bean id="sourceChannel" class="org.springframework.integration.channel.QueueChannel"/>
<bean id="targetChannel" class="org.springframework.integration.channel.QueueChannel"/>
<bean id="endpoint" class="org.springframework.integration.endpoint.HandlerEndpoint">
<constructor-arg ref="handler"/>
<property name="subscription">
<bean class="org.springframework.integration.scheduling.Subscription">
<constructor-arg ref="sourceChannel"/>
</bean>
</property>
<property name="outputChannelName" value="targetChannel"/>
</bean>
<bean id="handler" class="org.springframework.integration.handler.TestHandlers" factory-method="echoHandler"/>
<bean class="org.springframework.integration.bus.MessageBusAwareBeanPostProcessor">
<constructor-arg ref="bus"/>
</bean>
<bean id= "messageBusAwareBean" class="org.springframework.integration.bus.TestMessageBusAwareImpl"/>
</beans>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="bus1" class="org.springframework.integration.bus.MessageBus"/>
<bean id="bus2" class="org.springframework.integration.bus.MessageBus"/>
</beans>

View File

@@ -0,0 +1,176 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.channel;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.util.List;
import org.junit.Test;
import org.springframework.integration.message.Message;
import org.springframework.integration.message.StringMessage;
import org.springframework.integration.message.selector.MessageSelector;
/**
* @author Mark Fisher
*/
public class ChannelPurgerTests {
@Test
public void testPurgeAllWithoutSelector() {
MessageChannel channel = new QueueChannel();
channel.send(new StringMessage("test1"));
channel.send(new StringMessage("test2"));
channel.send(new StringMessage("test3"));
ChannelPurger purger = new ChannelPurger(channel);
List<Message<?>> purgedMessages = purger.purge();
assertEquals(3, purgedMessages.size());
assertNull(channel.receive(0));
}
@Test
public void testPurgeAllWithSelector() {
MessageChannel channel = new QueueChannel();
channel.send(new StringMessage("test1"));
channel.send(new StringMessage("test2"));
channel.send(new StringMessage("test3"));
ChannelPurger purger = new ChannelPurger(new MessageSelector() {
public boolean accept(Message<?> message) {
return false;
}
}, channel);
List<Message<?>> purgedMessages = purger.purge();
assertEquals(3, purgedMessages.size());
assertNull(channel.receive(0));
}
@Test
public void testPurgeNoneWithSelector() {
MessageChannel channel = new QueueChannel();
channel.send(new StringMessage("test1"));
channel.send(new StringMessage("test2"));
channel.send(new StringMessage("test3"));
ChannelPurger purger = new ChannelPurger(new MessageSelector() {
public boolean accept(Message<?> message) {
return true;
}
}, channel);
List<Message<?>> purgedMessages = purger.purge();
assertEquals(0, purgedMessages.size());
assertNotNull(channel.receive(0));
assertNotNull(channel.receive(0));
assertNotNull(channel.receive(0));
}
@Test
public void testPurgeSubsetWithSelector() {
MessageChannel channel = new QueueChannel();
channel.send(new StringMessage("test1"));
channel.send(new StringMessage("test2"));
channel.send(new StringMessage("test3"));
ChannelPurger purger = new ChannelPurger(new MessageSelector() {
public boolean accept(Message<?> message) {
return (message.getPayload().equals("test2"));
}
}, channel);
List<Message<?>> purgedMessages = purger.purge();
assertEquals(2, purgedMessages.size());
Message<?> message = channel.receive(0);
assertNotNull(message);
assertEquals("test2", message.getPayload());
assertNull(channel.receive(0));
}
@Test
public void testMultipleChannelsWithNoSelector() {
MessageChannel channel1 = new QueueChannel();
MessageChannel channel2 = new QueueChannel();
channel1.send(new StringMessage("test1"));
channel1.send(new StringMessage("test2"));
channel2.send(new StringMessage("test1"));
channel2.send(new StringMessage("test2"));
ChannelPurger purger = new ChannelPurger(channel1, channel2);
List<Message<?>> purgedMessages = purger.purge();
assertEquals(4, purgedMessages.size());
assertNull(channel1.receive(0));
assertNull(channel2.receive(0));
}
@Test
public void testMultipleChannelsWithSelector() {
MessageChannel channel1 = new QueueChannel();
MessageChannel channel2 = new QueueChannel();
channel1.send(new StringMessage("test1"));
channel1.send(new StringMessage("test2"));
channel1.send(new StringMessage("test3"));
channel2.send(new StringMessage("test1"));
channel2.send(new StringMessage("test2"));
channel2.send(new StringMessage("test3"));
ChannelPurger purger = new ChannelPurger(new MessageSelector() {
public boolean accept(Message<?> message) {
return (message.getPayload().equals("test2"));
}
}, channel1, channel2);
List<Message<?>> purgedMessages = purger.purge();
assertEquals(4, purgedMessages.size());
Message<?> message1 = channel1.receive(0);
assertNotNull(message1);
assertEquals("test2", message1.getPayload());
assertNull(channel1.receive(0));
Message<?> message2 = channel2.receive(0);
assertNotNull(message2);
assertEquals("test2", message2.getPayload());
assertNull(channel2.receive(0));
}
@Test
public void testPurgeNoneWithSelectorAndMultipleChannels() {
MessageChannel channel1 = new QueueChannel();
MessageChannel channel2 = new QueueChannel();
channel1.send(new StringMessage("test1"));
channel1.send(new StringMessage("test2"));
channel2.send(new StringMessage("test1"));
channel2.send(new StringMessage("test2"));
ChannelPurger purger = new ChannelPurger(new MessageSelector() {
public boolean accept(Message<?> message) {
return true;
}
}, channel1, channel2);
List<Message<?>> purgedMessages = purger.purge();
assertEquals(0, purgedMessages.size());
assertNotNull(channel1.receive(0));
assertNotNull(channel1.receive(0));
assertNotNull(channel2.receive(0));
assertNotNull(channel2.receive(0));
}
@Test(expected=IllegalArgumentException.class)
public void testNullChannel() {
MessageChannel channel = null;
new ChannelPurger(channel);
}
@Test(expected=IllegalArgumentException.class)
public void testEmptyChannelArray() {
MessageChannel[] channels = new MessageChannel[0];
new ChannelPurger(channels);
}
}

View File

@@ -0,0 +1,76 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.channel;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import org.junit.Test;
/**
* @author Mark Fisher
*/
public class DefaultChannelRegistryTests {
@Test
public void testLookupRegisteredChannel() {
QueueChannel testChannel = new QueueChannel();
DefaultChannelRegistry registry = new DefaultChannelRegistry();
registry.registerChannel("testChannel", testChannel);
MessageChannel lookedUpChannel = registry.lookupChannel("testChannel");
assertNotNull(testChannel);
assertSame(testChannel, lookedUpChannel);
}
@Test
public void testLookupNeverRegisteredChannel() {
DefaultChannelRegistry registry = new DefaultChannelRegistry();
MessageChannel noSuchChannel = registry.lookupChannel("noSuchChannel");
assertNull(noSuchChannel);
}
@Test
public void testLookupUnregisteredChannel() {
QueueChannel testChannel = new QueueChannel();
DefaultChannelRegistry registry = new DefaultChannelRegistry();
registry.registerChannel("testChannel", testChannel);
MessageChannel lookedUpChannel1 = registry.lookupChannel("testChannel");
assertNotNull(lookedUpChannel1);
assertSame(testChannel, lookedUpChannel1);
MessageChannel unregisteredChannel = registry.unregisterChannel("testChannel");
assertNotNull(unregisteredChannel);
assertSame(testChannel, unregisteredChannel);
MessageChannel lookedUpChannel2 = registry.lookupChannel("testChannel");
assertNull(lookedUpChannel2);
}
@Test
public void testUnregisteringChannelThatIsNotInRegistry() {
DefaultChannelRegistry registry = new DefaultChannelRegistry();
MessageChannel unregisteredChannel = registry.unregisterChannel("noSuchChannel");
assertNull(unregisteredChannel);
}
@Test
public void testUnregisteringNullDoesNotThrowException() {
DefaultChannelRegistry registry = new DefaultChannelRegistry();
MessageChannel unregisteredChannel = registry.unregisterChannel(null);
assertNull(unregisteredChannel);
}
}

View File

@@ -0,0 +1,32 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.channel;
import java.util.Comparator;
import org.springframework.integration.message.Message;
/**
* @author Mark Fisher
*/
public class MessagePayloadTestComparator implements Comparator<Message<Comparable<Object>>> {
public int compare(Message<Comparable<Object>> message1, Message<Comparable<Object>> message2) {
return message1.getPayload().compareTo(message2.getPayload());
}
}

View File

@@ -0,0 +1,104 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.channel;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.Comparator;
import org.junit.Test;
import org.springframework.integration.message.Message;
import org.springframework.integration.message.MessagePriority;
import org.springframework.integration.message.StringMessage;
/**
* @author Mark Fisher
*/
public class PriorityChannelTests {
@Test
public void testCapacityEnforced() {
PriorityChannel channel = new PriorityChannel(3);
assertTrue(channel.send(new StringMessage("test1"), 0));
assertTrue(channel.send(new StringMessage("test2"), 0));
assertTrue(channel.send(new StringMessage("test3"), 0));
assertFalse(channel.send(new StringMessage("test4"), 0));
channel.receive(0);
assertTrue(channel.send(new StringMessage("test5")));
}
@Test
public void testDefaultComparator() {
PriorityChannel channel = new PriorityChannel(5);
Message<?> priority1 = createPriorityMessage(MessagePriority.HIGHEST);
Message<?> priority2 = createPriorityMessage(MessagePriority.HIGH);
Message<?> priority3 = createPriorityMessage(MessagePriority.NORMAL);
Message<?> priority4 = createPriorityMessage(MessagePriority.LOW);
Message<?> priority5 = createPriorityMessage(MessagePriority.LOWEST);
channel.send(priority4);
channel.send(priority3);
channel.send(priority5);
channel.send(priority1);
channel.send(priority2);
assertEquals("test-HIGHEST", channel.receive(0).getPayload());
assertEquals("test-HIGH", channel.receive(0).getPayload());
assertEquals("test-NORMAL", channel.receive(0).getPayload());
assertEquals("test-LOW", channel.receive(0).getPayload());
assertEquals("test-LOWEST", channel.receive(0).getPayload());
}
@Test
public void testCustomComparator() {
PriorityChannel channel = new PriorityChannel(5, null, new StringPayloadComparator());
Message<?> messageA = new StringMessage("A");
Message<?> messageB = new StringMessage("B");
Message<?> messageC = new StringMessage("C");
Message<?> messageD = new StringMessage("D");
Message<?> messageE = new StringMessage("E");
channel.send(messageC);
channel.send(messageA);
channel.send(messageE);
channel.send(messageD);
channel.send(messageB);
assertEquals("A", channel.receive(0).getPayload());
assertEquals("B", channel.receive(0).getPayload());
assertEquals("C", channel.receive(0).getPayload());
assertEquals("D", channel.receive(0).getPayload());
assertEquals("E", channel.receive(0).getPayload());
}
private static Message<?> createPriorityMessage(MessagePriority priority) {
Message<?> message = new StringMessage("test-" + priority);
message.getHeader().setPriority(priority);
return message;
}
public static class StringPayloadComparator implements Comparator<Message<?>> {
public int compare(Message<?> message1, Message<?> message2) {
String s1 = (String) message1.getPayload();
String s2 = (String) message2.getPayload();
return s1.compareTo(s2);
}
}
}

View File

@@ -0,0 +1,241 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.channel;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.Test;
import org.springframework.integration.message.GenericMessage;
import org.springframework.integration.message.Message;
import org.springframework.integration.message.StringMessage;
import org.springframework.integration.message.selector.UnexpiredMessageSelector;
/**
* @author Mark Fisher
*/
public class QueueChannelTests {
@Test
public void testSimpleSendAndReceive() throws Exception {
final AtomicBoolean messageReceived = new AtomicBoolean(false);
final CountDownLatch latch = new CountDownLatch(1);
final QueueChannel channel = new QueueChannel();
new Thread(new Runnable() {
public void run() {
Message<?> message = channel.receive();
if (message != null) {
messageReceived.set(true);
latch.countDown();
}
}
}).start();
assertFalse(messageReceived.get());
channel.send(new GenericMessage<String>(1, "testing"));
latch.await(25, TimeUnit.MILLISECONDS);
assertTrue(messageReceived.get());
}
@Test
public void testImmediateReceive() throws Exception {
final AtomicBoolean messageReceived = new AtomicBoolean(false);
final QueueChannel channel = new QueueChannel();
final CountDownLatch latch1 = new CountDownLatch(1);
final CountDownLatch latch2 = new CountDownLatch(1);
Executor singleThreadExecutor = Executors.newSingleThreadExecutor();
Runnable receiveTask1 = new Runnable() {
public void run() {
Message<?> message = channel.receive(0);
if (message != null) {
messageReceived.set(true);
}
latch1.countDown();
}
};
Runnable sendTask = new Runnable() {
public void run() {
channel.send(new GenericMessage<String>(1, "testing"));
}
};
singleThreadExecutor.execute(receiveTask1);
latch1.await();
singleThreadExecutor.execute(sendTask);
assertFalse(messageReceived.get());
Runnable receiveTask2 = new Runnable() {
public void run() {
Message<?> message = channel.receive(0);
if (message != null) {
messageReceived.set(true);
}
latch2.countDown();
}
};
singleThreadExecutor.execute(receiveTask2);
latch2.await();
assertTrue(messageReceived.get());
}
@Test
public void testBlockingReceiveWithNoTimeout() throws Exception{
final QueueChannel channel = new QueueChannel();
final AtomicBoolean receiveInterrupted = new AtomicBoolean(false);
final CountDownLatch latch = new CountDownLatch(1);
Thread t = new Thread(new Runnable() {
public void run() {
Message<?> message = channel.receive();
receiveInterrupted.set(true);
assertTrue(message == null);
latch.countDown();
}
});
t.start();
assertFalse(receiveInterrupted.get());
t.interrupt();
latch.await();
assertTrue(receiveInterrupted.get());
}
@Test
public void testBlockingReceiveWithTimeout() throws Exception{
final QueueChannel channel = new QueueChannel();
final AtomicBoolean receiveInterrupted = new AtomicBoolean(false);
final CountDownLatch latch = new CountDownLatch(1);
Thread t = new Thread(new Runnable() {
public void run() {
Message<?> message = channel.receive(10000);
receiveInterrupted.set(true);
assertTrue(message == null);
latch.countDown();
}
});
t.start();
assertFalse(receiveInterrupted.get());
t.interrupt();
latch.await();
assertTrue(receiveInterrupted.get());
}
@Test
public void testImmediateSend() {
QueueChannel channel = new QueueChannel(3);
boolean result1 = channel.send(new GenericMessage<String>(1, "test-1"));
assertTrue(result1);
boolean result2 = channel.send(new GenericMessage<String>(2, "test-2"), 100);
assertTrue(result2);
boolean result3 = channel.send(new GenericMessage<String>(3, "test-3"), 0);
assertTrue(result3);
boolean result4 = channel.send(new GenericMessage<String>(4, "test-4"), 0);
assertFalse(result4);
}
@Test
public void testBlockingSendWithNoTimeout() throws Exception{
final QueueChannel channel = new QueueChannel(1);
boolean result1 = channel.send(new GenericMessage<String>(1, "test-1"));
assertTrue(result1);
final AtomicBoolean sendInterrupted = new AtomicBoolean(false);
final CountDownLatch latch = new CountDownLatch(1);
Thread t = new Thread(new Runnable() {
public void run() {
channel.send(new GenericMessage<String>(2, "test-2"));
sendInterrupted.set(true);
latch.countDown();
}
});
t.start();
assertFalse(sendInterrupted.get());
t.interrupt();
latch.await();
assertTrue(sendInterrupted.get());
}
@Test
public void testBlockingSendWithTimeout() throws Exception{
final QueueChannel channel = new QueueChannel(1);
boolean result1 = channel.send(new GenericMessage<String>(1, "test-1"));
assertTrue(result1);
final AtomicBoolean sendInterrupted = new AtomicBoolean(false);
final CountDownLatch latch = new CountDownLatch(1);
Thread t = new Thread(new Runnable() {
public void run() {
channel.send(new GenericMessage<String>(2, "test-2"), 10000);
sendInterrupted.set(true);
latch.countDown();
}
});
t.start();
assertFalse(sendInterrupted.get());
t.interrupt();
latch.await();
assertTrue(sendInterrupted.get());
}
@Test
public void testClear() {
QueueChannel channel = new QueueChannel(2);
StringMessage message1 = new StringMessage("test1");
StringMessage message2 = new StringMessage("test2");
StringMessage message3 = new StringMessage("test3");
assertTrue(channel.send(message1));
assertTrue(channel.send(message2));
assertFalse(channel.send(message3, 0));
List<Message<?>> clearedMessages = channel.clear();
assertNotNull(clearedMessages);
assertEquals(2, clearedMessages.size());
assertTrue(channel.send(message3));
}
@Test
public void testClearEmptyChannel() {
QueueChannel channel = new QueueChannel();
List<Message<?>> clearedMessages = channel.clear();
assertNotNull(clearedMessages);
assertEquals(0, clearedMessages.size());
}
@Test
public void testPurge() {
QueueChannel channel = new QueueChannel(2);
long minute = 60 * 1000;
long time = System.currentTimeMillis();
Date past = new Date(time - minute);
Date future = new Date(time + minute);
StringMessage expiredMessage = new StringMessage("test1");
expiredMessage.getHeader().setExpiration(past);
StringMessage unexpiredMessage = new StringMessage("test2");
unexpiredMessage.getHeader().setExpiration(future);
assertTrue(channel.send(expiredMessage, 0));
assertTrue(channel.send(unexpiredMessage, 0));
assertFalse(channel.send(new StringMessage("atCapacity"), 0));
List<Message<?>> purgedMessages = channel.purge(new UnexpiredMessageSelector());
assertNotNull(purgedMessages);
assertEquals(1, purgedMessages.size());
assertTrue(channel.send(new StringMessage("roomAvailable"), 0));
}
}

View File

@@ -0,0 +1,86 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.channel;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.springframework.integration.bus.MessageBus;
import org.springframework.integration.handler.MessageHandler;
import org.springframework.integration.handler.ReplyHandler;
import org.springframework.integration.message.Message;
import org.springframework.integration.message.MessageHeader;
import org.springframework.integration.message.StringMessage;
import org.springframework.integration.scheduling.Subscription;
/**
* @author Mark Fisher
*/
public class RequestReplyTemplateTests {
private final QueueChannel requestChannel = new QueueChannel();
public RequestReplyTemplateTests() {
MessageHandler testHandler = new MessageHandler() {
public Message<?> handle(Message<?> message) {
return new StringMessage(message.getPayload().toString().toUpperCase());
}
};
MessageBus bus = new MessageBus();
bus.registerChannel("requestChannel", requestChannel);
bus.registerHandler("testHandler", testHandler, new Subscription(requestChannel));
bus.start();
}
@Test
public void testSynchronousRequestReply() {
RequestReplyTemplate template = new RequestReplyTemplate(requestChannel);
Message<?> reply = template.request(new StringMessage("test"));
assertEquals("TEST", reply.getPayload());
}
@Test
public void testAsynchronousRequestAndReply() throws InterruptedException {
final List<String> replies = new ArrayList<String>(3);
final CountDownLatch latch = new CountDownLatch(3);
ReplyHandler replyHandler = new ReplyHandler() {
public void handle(Message<?> replyMessage, MessageHeader originalMessageHeader) {
replies.add((String) replyMessage.getPayload());
latch.countDown();
}
};
RequestReplyTemplate template = new RequestReplyTemplate(requestChannel);
template.request(new StringMessage("test1"), replyHandler);
template.request(new StringMessage("test2"), replyHandler);
template.request(new StringMessage("test3"), replyHandler);
latch.await(1000, TimeUnit.MILLISECONDS);
assertEquals(0, latch.getCount());
assertTrue(replies.contains("TEST1"));
assertTrue(replies.contains("TEST2"));
assertTrue(replies.contains("TEST3"));
}
}

View File

@@ -0,0 +1,63 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.channel;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.Test;
import org.springframework.integration.message.Message;
import org.springframework.integration.message.StringMessage;
/**
* @author Mark Fisher
*/
public class ThreadLocalChannelTests {
@Test
public void testSendAndReceive() {
ThreadLocalChannel channel = new ThreadLocalChannel();
StringMessage message = new StringMessage("test");
assertNull(channel.receive());
assertTrue(channel.send(message));
Message<?> response = channel.receive();
assertNotNull(response);
assertEquals(response, message);
assertNull(channel.receive());
}
@Test
public void testSendAndClear() {
ThreadLocalChannel channel = new ThreadLocalChannel();
StringMessage message1 = new StringMessage("test1");
StringMessage message2 = new StringMessage("test2");
assertNull(channel.receive());
assertTrue(channel.send(message1));
assertTrue(channel.send(message2));
List<Message<?>> clearedMessages = channel.clear();
assertEquals(2, clearedMessages.size());
assertEquals(message1, clearedMessages.get(0));
assertEquals(message2, clearedMessages.get(1));
assertNull(channel.receive());
}
}

View File

@@ -0,0 +1,293 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.channel.config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import org.springframework.beans.FatalBeanException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.bus.SubscriptionManager;
import org.springframework.integration.channel.DispatcherPolicy;
import org.springframework.integration.channel.MessageChannel;
import org.springframework.integration.config.TestChannelInterceptor;
import org.springframework.integration.message.GenericMessage;
import org.springframework.integration.message.Message;
import org.springframework.integration.message.MessageDeliveryException;
import org.springframework.integration.message.MessagePriority;
import org.springframework.integration.message.StringMessage;
import org.springframework.integration.message.Target;
import org.springframework.integration.scheduling.SimpleMessagingTaskScheduler;
/**
* @author Mark Fisher
*/
public class ChannelParserTests {
@Test(expected=FatalBeanException.class)
public void testChannelWithoutId() {
new ClassPathXmlApplicationContext("channelWithoutId.xml", this.getClass());
}
@Test
public void testChannelWithCapacity() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"channelParserTests.xml", this.getClass());
MessageChannel channel = (MessageChannel) context.getBean("capacityChannel");
for (int i = 0; i < 10; i++) {
boolean result = channel.send(new GenericMessage<String>(1, "test"), 10);
assertTrue(result);
}
assertFalse(channel.send(new GenericMessage<String>(1, "test"), 3));
}
@Test
public void testPointToPointChannelByDefault() throws InterruptedException {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"channelParserTests.xml", this.getClass());
MessageChannel channel = (MessageChannel) context.getBean("pointToPointChannelByDefault");
channel.send(new StringMessage("test"));
SimpleMessagingTaskScheduler scheduler = new SimpleMessagingTaskScheduler(new ScheduledThreadPoolExecutor(1));
SubscriptionManager manager = new SubscriptionManager(channel, scheduler);
AtomicInteger counter = new AtomicInteger();
CountDownLatch latch = new CountDownLatch(1);
TestTarget target1 = new TestTarget(counter, latch);
TestTarget target2 = new TestTarget(counter, latch);
manager.addTarget(target1);
manager.addTarget(target2);
manager.start();
latch.await(500, TimeUnit.MILLISECONDS);
assertEquals(0, latch.getCount());
assertEquals(1, counter.get());
}
@Test
public void testPointToPointChannelExplicitlyConfigured() throws InterruptedException {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"channelParserTests.xml", this.getClass());
MessageChannel channel = (MessageChannel) context.getBean("pointToPointChannelExplicitlyConfigured");
channel.send(new StringMessage("test"));
SimpleMessagingTaskScheduler scheduler = new SimpleMessagingTaskScheduler(new ScheduledThreadPoolExecutor(1));
SubscriptionManager manager = new SubscriptionManager(channel, scheduler);
AtomicInteger counter = new AtomicInteger();
CountDownLatch latch = new CountDownLatch(1);
TestTarget target1 = new TestTarget(counter, latch);
TestTarget target2 = new TestTarget(counter, latch);
manager.addTarget(target1);
manager.addTarget(target2);
manager.start();
latch.await(500, TimeUnit.MILLISECONDS);
assertEquals(0, latch.getCount());
assertEquals(1, counter.get());
}
@Test
public void testPublishSubscribeChannel() throws InterruptedException {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"channelParserTests.xml", this.getClass());
MessageChannel channel = (MessageChannel) context.getBean("publishSubscribeChannel");
channel.send(new StringMessage("test"));
SimpleMessagingTaskScheduler scheduler = new SimpleMessagingTaskScheduler(new ScheduledThreadPoolExecutor(1));
SubscriptionManager manager = new SubscriptionManager(channel, scheduler);
AtomicInteger counter = new AtomicInteger();
CountDownLatch latch = new CountDownLatch(2);
TestTarget target1 = new TestTarget(counter, latch);
TestTarget target2 = new TestTarget(counter, latch);
manager.addTarget(target1);
manager.addTarget(target2);
manager.start();
latch.await(500, TimeUnit.MILLISECONDS);
assertEquals(0, latch.getCount());
assertEquals(2, counter.get());
}
@Test
public void testDefaultDispatcherPolicy() throws InterruptedException {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"channelParserTests.xml", this.getClass());
MessageChannel channel = (MessageChannel) context.getBean("pointToPointChannelByDefault");
DispatcherPolicy dispatcherPolicy = channel.getDispatcherPolicy();
assertFalse(dispatcherPolicy.isPublishSubscribe());
assertEquals(DispatcherPolicy.DEFAULT_MAX_MESSAGES_PER_TASK, dispatcherPolicy.getMaxMessagesPerTask());
assertEquals(DispatcherPolicy.DEFAULT_RECEIVE_TIMEOUT, dispatcherPolicy.getReceiveTimeout());
assertEquals(DispatcherPolicy.DEFAULT_REJECTION_LIMIT, dispatcherPolicy.getRejectionLimit());
assertEquals(DispatcherPolicy.DEFAULT_RETRY_INTERVAL, dispatcherPolicy.getRetryInterval());
assertTrue(dispatcherPolicy.getShouldFailOnRejectionLimit());
}
@Test
public void testDispatcherPolicyConfiguration() throws InterruptedException {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"channelParserTests.xml", this.getClass());
MessageChannel channel = (MessageChannel) context.getBean("channelWithDispatcherPolicy");
DispatcherPolicy dispatcherPolicy = channel.getDispatcherPolicy();
assertTrue(dispatcherPolicy.isPublishSubscribe());
assertEquals(7, dispatcherPolicy.getMaxMessagesPerTask());
assertEquals(77, dispatcherPolicy.getReceiveTimeout());
assertEquals(777, dispatcherPolicy.getRejectionLimit());
assertEquals(7777, dispatcherPolicy.getRetryInterval());
assertFalse(dispatcherPolicy.getShouldFailOnRejectionLimit());
}
@Test
public void testDatatypeChannelWithCorrectType() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"channelParserTests.xml", this.getClass());
MessageChannel channel = (MessageChannel) context.getBean("integerChannel");
assertTrue(channel.send(new GenericMessage<Integer>(123)));
}
@Test(expected=MessageDeliveryException.class)
public void testDatatypeChannelWithIncorrectType() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"channelParserTests.xml", this.getClass());
MessageChannel channel = (MessageChannel) context.getBean("integerChannel");
channel.send(new StringMessage("incorrect type"));
}
@Test
public void testDatatypeChannelWithAssignableSubTypes() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"channelParserTests.xml", this.getClass());
MessageChannel channel = (MessageChannel) context.getBean("numberChannel");
assertTrue(channel.send(new GenericMessage<Integer>(123)));
assertTrue(channel.send(new GenericMessage<Double>(123.45)));
}
@Test
public void testMultipleDatatypeChannelWithCorrectTypes() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"channelParserTests.xml", this.getClass());
MessageChannel channel = (MessageChannel) context.getBean("stringOrNumberChannel");
assertTrue(channel.send(new GenericMessage<Integer>(123)));
assertTrue(channel.send(new StringMessage("accepted type")));
}
@Test(expected=MessageDeliveryException.class)
public void testMultipleDatatypeChannelWithIncorrectType() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"channelParserTests.xml", this.getClass());
MessageChannel channel = (MessageChannel) context.getBean("stringOrNumberChannel");
channel.send(new GenericMessage<Boolean>(true));
}
@Test
public void testChannelInteceptors() {
ApplicationContext context = new ClassPathXmlApplicationContext(
"channelInterceptorParserTests.xml", this.getClass());
MessageChannel channel = (MessageChannel) context.getBean("channel");
TestChannelInterceptor interceptor = (TestChannelInterceptor) context.getBean("interceptor");
assertEquals(0, interceptor.getSendCount());
channel.send(new StringMessage("test"));
assertEquals(1, interceptor.getSendCount());
assertEquals(0, interceptor.getReceiveCount());
channel.receive();
assertEquals(1, interceptor.getReceiveCount());
}
@Test
public void testPriorityChannelWithDefaultComparator() {
ApplicationContext context = new ClassPathXmlApplicationContext(
"priorityChannelParserTests.xml", this.getClass());
MessageChannel channel = (MessageChannel) context.getBean("priorityChannelWithDefaultComparator");
Message<?> lowPriorityMessage = new StringMessage("low");
lowPriorityMessage.getHeader().setPriority(MessagePriority.LOW);
Message<?> midPriorityMessage = new StringMessage("mid");
midPriorityMessage.getHeader().setPriority(MessagePriority.NORMAL);
Message<?> highPriorityMessage = new StringMessage("high");
highPriorityMessage.getHeader().setPriority(MessagePriority.HIGH);
channel.send(lowPriorityMessage);
channel.send(highPriorityMessage);
channel.send(midPriorityMessage);
Message<?> reply1 = channel.receive(0);
Message<?> reply2 = channel.receive(0);
Message<?> reply3 = channel.receive(0);
assertEquals("high", reply1.getPayload());
assertEquals("mid", reply2.getPayload());
assertEquals("low", reply3.getPayload());
}
@Test
public void testPriorityChannelWithCustomComparator() {
ApplicationContext context = new ClassPathXmlApplicationContext(
"priorityChannelParserTests.xml", this.getClass());
MessageChannel channel = (MessageChannel) context.getBean("priorityChannelWithCustomComparator");
channel.send(new StringMessage("C"));
channel.send(new StringMessage("A"));
channel.send(new StringMessage("D"));
channel.send(new StringMessage("B"));
Message<?> reply1 = channel.receive(0);
Message<?> reply2 = channel.receive(0);
Message<?> reply3 = channel.receive(0);
Message<?> reply4 = channel.receive(0);
assertEquals("A", reply1.getPayload());
assertEquals("B", reply2.getPayload());
assertEquals("C", reply3.getPayload());
assertEquals("D", reply4.getPayload());
}
@Test
public void testPriorityChannelWithIntegerDatatypeEnforced() {
ApplicationContext context = new ClassPathXmlApplicationContext(
"priorityChannelParserTests.xml", this.getClass());
MessageChannel channel = (MessageChannel) context.getBean("integerOnlyPriorityChannel");
channel.send(new GenericMessage<Integer>(3));
channel.send(new GenericMessage<Integer>(2));
channel.send(new GenericMessage<Integer>(1));
assertEquals(1, channel.receive(0).getPayload());
assertEquals(2, channel.receive(0).getPayload());
assertEquals(3, channel.receive(0).getPayload());
boolean threwException = false;
try {
channel.send(new StringMessage("wrong type"));
}
catch (MessageDeliveryException e) {
assertEquals("wrong type", e.getFailedMessage().getPayload());
threwException = true;
}
assertTrue(threwException);
}
private static class TestTarget implements Target {
private AtomicInteger counter;
private CountDownLatch latch;
TestTarget(AtomicInteger counter, CountDownLatch latch) {
this.counter = counter;
this.latch = latch;
}
public boolean send(Message<?> message) {
this.counter.incrementAndGet();
this.latch.countDown();
return true;
}
}
}

View File

@@ -0,0 +1,55 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.channel.config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.message.Message;
import org.springframework.integration.message.StringMessage;
/**
* @author Mark Fisher
*/
public class DirectChannelParserTests {
@Test
public void testReceivesNullFromChannelWithoutSource() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"directChannelParserTests.xml", DirectChannelParserTests.class);
DirectChannel channel = (DirectChannel) context.getBean("channelWithoutSource");
assertNull(channel.receive());
}
@Test
public void testReceivesMessageFromChannelWithSource() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"directChannelParserTests.xml", DirectChannelParserTests.class);
DirectChannel channel = (DirectChannel) context.getBean("channelWithSource");
assertFalse(channel.send(new StringMessage("test")));
Message<?> reply = channel.receive();
assertNotNull(reply);
assertEquals("foo", reply.getPayload());
}
}

View File

@@ -0,0 +1,40 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.channel.config;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.channel.MessageChannel;
import org.springframework.integration.channel.RendezvousChannel;
/**
* @author Mark Fisher
*/
public class RendezvousChannelParserTests {
@Test
public void testRendezvous() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"rendezvousChannelParserTests.xml", RendezvousChannelParserTests.class);
MessageChannel channel = (MessageChannel) context.getBean("channel");
assertEquals(RendezvousChannel.class, channel.getClass());
}
}

View File

@@ -0,0 +1,35 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.channel.config;
/**
* @author Mark Fisher
*/
public class TestSourceBean {
private final String text;
public TestSourceBean(String text) {
this.text = text;
}
public String getText() {
return this.text;
}
}

View File

@@ -0,0 +1,40 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.channel.config;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.channel.MessageChannel;
import org.springframework.integration.channel.ThreadLocalChannel;
/**
* @author Mark Fisher
*/
public class ThreadLocalChannelParserTests {
@Test
public void testChannelType() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"threadLocalChannelParserTests.xml", ThreadLocalChannelParserTests.class);
MessageChannel channel = (MessageChannel) context.getBean("channel");
assertEquals(ThreadLocalChannel.class, channel.getClass());
}
}

View File

@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration-core-1.0.xsd">
<channel id="channel">
<interceptor ref="interceptor"/>
</channel>
<beans:bean id="interceptor" class="org.springframework.integration.config.TestChannelInterceptor"/>
</beans:beans>

View File

@@ -0,0 +1,32 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration-core-1.0.xsd">
<queue-channel id="capacityChannel" capacity="10"/>
<channel id="pointToPointChannelByDefault"/>
<channel id="pointToPointChannelExplicitlyConfigured" publish-subscribe="false"/>
<channel id="publishSubscribeChannel" publish-subscribe="true"/>
<channel id="channelWithDispatcherPolicy" publish-subscribe="true">
<dispatcher-policy max-messages-per-task="7"
receive-timeout="77"
rejection-limit="777"
retry-interval="7777"
should-fail-on-rejection-limit="false"/>
</channel>
<channel id="integerChannel" datatype="java.lang.Integer"/>
<channel id="numberChannel" datatype="java.lang.Number"/>
<channel id="stringOrNumberChannel" datatype="java.lang.String,java.lang.Number"/>
</beans:beans>

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:integration="http://www.springframework.org/schema/integration"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration-core-1.0.xsd">
<integration:channel/>
</beans>

View File

@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration-core-1.0.xsd">
<direct-channel id="channelWithoutSource"/>
<direct-channel id="channelWithSource" source="source"/>
<source-adapter id="source" ref="testSourceBean" method="getText"/>
<beans:bean id="testSourceBean" class="org.springframework.integration.channel.config.TestSourceBean">
<beans:constructor-arg value="foo"/>
</beans:bean>
</beans:beans>

View File

@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration-core-1.0.xsd">
<priority-channel id="priorityChannelWithDefaultComparator"/>
<priority-channel id="priorityChannelWithCustomComparator" comparator="payloadComparator"/>
<priority-channel id="integerOnlyPriorityChannel" datatype="java.lang.Integer" comparator="payloadComparator"/>
<beans:bean id="payloadComparator"
class="org.springframework.integration.channel.MessagePayloadTestComparator"/>
</beans:beans>

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration-core-1.0.xsd">
<rendezvous-channel id="channel"/>
</beans:beans>

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration-core-1.0.xsd">
<thread-local-channel id="channel"/>
</beans:beans>

View File

@@ -0,0 +1,199 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.channel.factory;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.context.support.StaticApplicationContext;
import org.springframework.integration.bus.MessageBus;
import org.springframework.integration.channel.AbstractMessageChannel;
import org.springframework.integration.channel.ChannelInterceptor;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.channel.DispatcherPolicy;
import org.springframework.integration.channel.MessageChannel;
import org.springframework.integration.channel.PriorityChannel;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.channel.RendezvousChannel;
import org.springframework.integration.channel.ThreadLocalChannel;
import org.springframework.integration.message.Message;
import org.springframework.integration.message.selector.MessageSelector;
/**
* @author Marius Bogoevici
* @author Mark Fisher
*/
public class ChannelFactoryTests {
private final ArrayList<ChannelInterceptor> interceptors = new ArrayList<ChannelInterceptor>();
private final DispatcherPolicy dispatcherPolicy = new DispatcherPolicy();
@Before
public void initInterceptorsList() {
interceptors.add(new TestChannelInterceptor());
interceptors.add(new TestChannelInterceptor());
}
@Before
public void initDispatcherPolicy() {
dispatcherPolicy.setMaxMessagesPerTask(100);
}
@Test
public void testQueueChannelFactory() {
QueueChannelFactory channelFactory = new QueueChannelFactory();
channelFactory.setQueueCapacity(99);
genericChannelFactoryTests(channelFactory, QueueChannel.class);
assertEquals(99, channelFactory.getQueueCapacity());
}
@Test
public void testDirectChannelFactory() {
DirectChannelFactory channelFactory = new DirectChannelFactory();
assertNotNull(interceptors);
AbstractMessageChannel channel = (AbstractMessageChannel)
channelFactory.getChannel(dispatcherPolicy, interceptors);
assertEquals(DirectChannel.class, channel.getClass());
assertInterceptors(channel);
}
@Test
public void testRendezvousChannelFactory() {
RendezvousChannelFactory channelFactory = new RendezvousChannelFactory();
genericChannelFactoryTests(channelFactory, RendezvousChannel.class);
}
@Test
public void testPriorityChannelFactory() {
PriorityChannelFactory channelFactory = new PriorityChannelFactory();
genericChannelFactoryTests(channelFactory, PriorityChannel.class);
}
@Test
public void testThreadLocalChannelFactory() {
ThreadLocalChannelFactory channelFactory = new ThreadLocalChannelFactory();
assertNotNull(interceptors);
AbstractMessageChannel channel = (AbstractMessageChannel)
channelFactory.getChannel(dispatcherPolicy, interceptors);
assertEquals(ThreadLocalChannel.class, channel.getClass());
assertInterceptors(channel);
}
@Test
public void testDefaultChannelFactoryBean() throws Exception{
MessageBus messageBus = new MessageBus();
ChannelFactory channelFactory = new StubChannelFactory();
messageBus.setChannelFactory(channelFactory);
StaticApplicationContext applicationContext = new StaticApplicationContext();
BeanDefinitionBuilder messageBusDefinitionBuilder = BeanDefinitionBuilder.rootBeanDefinition(MessageBus.class);
messageBusDefinitionBuilder.getBeanDefinition().getPropertyValues().addPropertyValue("channelFactory", channelFactory);
applicationContext.registerBeanDefinition("messageBus", messageBusDefinitionBuilder.getBeanDefinition());
DefaultChannelFactoryBean channelFactoryBean = new DefaultChannelFactoryBean(dispatcherPolicy);
channelFactoryBean.setApplicationContext(applicationContext);
channelFactoryBean.setInterceptors(interceptors);
StubChannel channel = (StubChannel)channelFactoryBean.getObject();
assertTrue(dispatcherPolicy == channel.getDispatcherPolicy());
assertInterceptors(channel);
}
private void genericChannelFactoryTests(ChannelFactory channelFactory, Class<?> expectedChannelClass) {
assertNotNull(dispatcherPolicy);
assertNotNull(interceptors);
AbstractMessageChannel channel = (AbstractMessageChannel)
channelFactory.getChannel(dispatcherPolicy, interceptors);
assertEquals(expectedChannelClass, channel.getClass());
assertTrue(channel.getDispatcherPolicy() == dispatcherPolicy);
assertInterceptors(channel);
}
@SuppressWarnings("unchecked")
private void assertInterceptors(AbstractMessageChannel channel) {
Object interceptorsWrapper = new DirectFieldAccessor(channel).getPropertyValue("interceptors");
List<ChannelInterceptor> interceptors = (List<ChannelInterceptor>)
new DirectFieldAccessor(interceptorsWrapper).getPropertyValue("interceptors");
assertTrue(interceptors.get(0) == interceptors.get(0));
assertTrue(interceptors.get(1) == interceptors.get(1));
}
static class TestChannelInterceptor implements ChannelInterceptor {
public void postReceive(Message<?> message, MessageChannel channel) {
}
public void postSend(Message<?> message, MessageChannel channel, boolean sent) {
}
public boolean preReceive(MessageChannel channel) {
return false;
}
public boolean preSend(Message<?> message, MessageChannel channel) {
return false;
}
}
static class StubChannel extends AbstractMessageChannel {
public StubChannel(DispatcherPolicy dispatcherPolicy) {
super(dispatcherPolicy);
}
@Override
protected Message<?> doReceive(long timeout) {
return null;
}
@Override
protected boolean doSend(Message<?> message, long timeout) {
return false;
}
public List<Message<?>> clear() {
return null;
}
public List<Message<?>> purge(MessageSelector selector) {
return null;
}
}
static class StubChannelFactory extends AbstractChannelFactory {
@Override
protected AbstractMessageChannel createChannelInternal(DispatcherPolicy dispatcherPolicy) {
return new StubChannel(dispatcherPolicy);
}
}
}

View File

@@ -0,0 +1,202 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.channel.interceptor;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import org.springframework.integration.channel.MessageChannel;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.message.Message;
import org.springframework.integration.message.StringMessage;
/**
* @author Mark Fisher
*/
public class ChannelInterceptorTests {
private final QueueChannel channel = new QueueChannel();
@Test
public void testPreSendInterceptorReturnsTrue() {
channel.addInterceptor(new PreSendReturnsTrueInterceptor());
channel.send(new StringMessage("test"));
Message result = channel.receive(0);
assertNotNull(result);
assertEquals("test", result.getPayload());
assertEquals(1, result.getHeader().getAttribute(PreSendReturnsTrueInterceptor.class.getName()));
}
@Test
public void testPreSendInterceptorReturnsFalse() {
channel.addInterceptor(new PreSendReturnsFalseInterceptor());
Message message = new StringMessage("test");
channel.send(message);
assertEquals(1, message.getHeader().getAttribute(PreSendReturnsFalseInterceptor.class.getName()));
Message result = channel.receive(0);
assertNull(result);
}
@Test
public void testPostSendInterceptorWithSentMessage() {
final AtomicBoolean invoked = new AtomicBoolean(false);
channel.addInterceptor(new ChannelInterceptorAdapter() {
@Override
public void postSend(Message message, MessageChannel channel, boolean sent) {
assertNotNull(message);
assertNotNull(channel);
assertSame(ChannelInterceptorTests.this.channel, channel);
assertTrue(sent);
invoked.set(true);
}
});
channel.send(new StringMessage("test"));
assertTrue(invoked.get());
}
@Test
public void testPostSendInterceptorWithUnsentMessage() {
final AtomicInteger invokedCounter = new AtomicInteger(0);
final AtomicInteger sentCounter = new AtomicInteger(0);
final QueueChannel singleItemChannel = new QueueChannel(1);
singleItemChannel.addInterceptor(new ChannelInterceptorAdapter() {
@Override
public void postSend(Message message, MessageChannel channel, boolean sent) {
assertNotNull(message);
assertNotNull(channel);
assertSame(singleItemChannel, channel);
if (sent) {
sentCounter.incrementAndGet();
}
invokedCounter.incrementAndGet();
}
});
assertEquals(0, invokedCounter.get());
assertEquals(0, sentCounter.get());
singleItemChannel.send(new StringMessage("test1"));
assertEquals(1, invokedCounter.get());
assertEquals(1, sentCounter.get());
singleItemChannel.send(new StringMessage("test2"), 0);
assertEquals(2, invokedCounter.get());
assertEquals(1, sentCounter.get());
}
@Test
public void testPreReceiveInterceptorReturnsTrue() {
channel.addInterceptor(new PreReceiveReturnsTrueInterceptor());
Message message = new StringMessage("test");
channel.send(message);
Message result = channel.receive(0);
assertEquals(1, PreReceiveReturnsTrueInterceptor.counter.get());
assertNotNull(result);
}
@Test
public void testPreReceiveInterceptorReturnsFalse() {
channel.addInterceptor(new PreReceiveReturnsFalseInterceptor());
Message message = new StringMessage("test");
channel.send(message);
Message result = channel.receive(0);
assertEquals(1, PreReceiveReturnsFalseInterceptor.counter.get());
assertNull(result);
}
@Test
public void testPostReceiveInterceptor() {
final AtomicInteger invokedCount = new AtomicInteger();
final AtomicInteger messageCount = new AtomicInteger();
channel.addInterceptor(new ChannelInterceptorAdapter() {
@Override
public void postReceive(Message message, MessageChannel channel) {
assertNotNull(channel);
assertSame(ChannelInterceptorTests.this.channel, channel);
if (message != null) {
messageCount.incrementAndGet();
}
invokedCount.incrementAndGet();
}
});
channel.receive(0);
assertEquals(1, invokedCount.get());
assertEquals(0, messageCount.get());
channel.send(new StringMessage("test"));
Message result = channel.receive(0);
assertNotNull(result);
assertEquals(2, invokedCount.get());
assertEquals(1, messageCount.get());
}
private static class PreSendReturnsTrueInterceptor extends ChannelInterceptorAdapter {
private static AtomicInteger counter = new AtomicInteger();
@Override
public boolean preSend(Message message, MessageChannel channel) {
assertNotNull(message);
message.getHeader().setAttribute(this.getClass().getName(), counter.incrementAndGet());
return true;
}
}
private static class PreSendReturnsFalseInterceptor extends ChannelInterceptorAdapter {
private static AtomicInteger counter = new AtomicInteger();
@Override
public boolean preSend(Message message, MessageChannel channel) {
assertNotNull(message);
message.getHeader().setAttribute(this.getClass().getName(), counter.incrementAndGet());
return false;
}
}
private static class PreReceiveReturnsTrueInterceptor extends ChannelInterceptorAdapter {
private static AtomicInteger counter = new AtomicInteger();
@Override
public boolean preReceive(MessageChannel channel) {
counter.incrementAndGet();
return true;
}
}
private static class PreReceiveReturnsFalseInterceptor extends ChannelInterceptorAdapter {
private static AtomicInteger counter = new AtomicInteger();
@Override
public boolean preReceive(MessageChannel channel) {
counter.incrementAndGet();
return false;
}
}
}

View File

@@ -0,0 +1,110 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.channel.interceptor;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.message.Message;
import org.springframework.integration.message.MessageDeliveryException;
import org.springframework.integration.message.StringMessage;
import org.springframework.integration.message.selector.MessageSelector;
/**
* @author Mark Fisher
*/
public class MessageSelectingInterceptorTests {
@Test
public void testSingleSelectorAccepts() {
final AtomicInteger counter = new AtomicInteger();
MessageSelector selector = new TestMessageSelector(true, counter);
MessageSelectingInterceptor interceptor = new MessageSelectingInterceptor(selector);
QueueChannel channel = new QueueChannel();
channel.addInterceptor(interceptor);
assertTrue(channel.send(new StringMessage("test1")));
}
@Test(expected=MessageDeliveryException.class)
public void testSingleSelectorRejects() {
final AtomicInteger counter = new AtomicInteger();
MessageSelector selector = new TestMessageSelector(false, counter);
MessageSelectingInterceptor interceptor = new MessageSelectingInterceptor(selector);
QueueChannel channel = new QueueChannel();
channel.addInterceptor(interceptor);
channel.send(new StringMessage("test1"));
}
@Test
public void testMultipleSelectorsAccept() {
final AtomicInteger counter = new AtomicInteger();
MessageSelector selector1 = new TestMessageSelector(true, counter);
MessageSelector selector2 = new TestMessageSelector(true, counter);
MessageSelectingInterceptor interceptor = new MessageSelectingInterceptor(selector1, selector2);
QueueChannel channel = new QueueChannel();
channel.addInterceptor(interceptor);
assertTrue(channel.send(new StringMessage("test1")));
assertEquals(2, counter.get());
}
@Test
public void testMultipleSelectorsReject() {
boolean exceptionThrown = false;
final AtomicInteger counter = new AtomicInteger();
MessageSelector selector1 = new TestMessageSelector(true, counter);
MessageSelector selector2 = new TestMessageSelector(false, counter);
MessageSelector selector3 = new TestMessageSelector(false, counter);
MessageSelector selector4 = new TestMessageSelector(true, counter);
MessageSelectingInterceptor interceptor = new MessageSelectingInterceptor(selector1, selector2, selector3, selector4);
QueueChannel channel = new QueueChannel();
channel.addInterceptor(interceptor);
try {
channel.send(new StringMessage("test1"));
}
catch (MessageDeliveryException e) {
exceptionThrown = true;
}
assertTrue(exceptionThrown);
assertEquals(2, counter.get());
}
private static class TestMessageSelector implements MessageSelector {
private final boolean shouldAccept;
private final AtomicInteger counter;
public TestMessageSelector(boolean shouldAccept, AtomicInteger counter) {
this.shouldAccept = shouldAccept;
this.counter = counter;
}
public boolean accept(Message<?> message) {
this.counter.incrementAndGet();
return this.shouldAccept;
}
}
}

View File

@@ -0,0 +1,173 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.channel.interceptor;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.message.Message;
import org.springframework.integration.message.StringMessage;
import org.springframework.integration.message.selector.MessageSelector;
/**
* @author Mark Fisher
*/
public class WireTapTests {
@Test
public void testWireTapWithNoSelectors() {
QueueChannel mainChannel = new QueueChannel();
QueueChannel secondaryChannel = new QueueChannel();
mainChannel.addInterceptor(new WireTap(secondaryChannel));
mainChannel.send(new StringMessage("testing"));
Message<?> original = mainChannel.receive(0);
assertNotNull(original);
Message<?> duplicate = secondaryChannel.receive(0);
assertNotNull(duplicate);
}
@Test
public void testWireTapWithRejectingSelector() {
QueueChannel mainChannel = new QueueChannel();
QueueChannel secondaryChannel = new QueueChannel();
List<MessageSelector> selectors = new ArrayList<MessageSelector>();
selectors.add(new TestSelector(true));
selectors.add(new TestSelector(false));
mainChannel.addInterceptor(new WireTap(secondaryChannel, selectors));
mainChannel.send(new StringMessage("testing"));
Message<?> original = mainChannel.receive(0);
assertNotNull(original);
Message<?> duplicate = secondaryChannel.receive(0);
assertNull(duplicate);
}
@Test
public void testWireTapWithAcceptingSelectors() {
QueueChannel mainChannel = new QueueChannel();
QueueChannel secondaryChannel = new QueueChannel();
List<MessageSelector> selectors = new ArrayList<MessageSelector>();
selectors.add(new TestSelector(true));
selectors.add(new TestSelector(true));
mainChannel.addInterceptor(new WireTap(secondaryChannel, selectors));
mainChannel.send(new StringMessage("testing"));
Message<?> original = mainChannel.receive(0);
assertNotNull(original);
Message<?> duplicate = secondaryChannel.receive(0);
assertNotNull(duplicate);
}
@Test
public void testNewMessageIdGeneratedForDuplicate() {
QueueChannel mainChannel = new QueueChannel();
QueueChannel secondaryChannel = new QueueChannel();
mainChannel.addInterceptor(new WireTap(secondaryChannel));
mainChannel.send(new StringMessage("testing"));
Message<?> original = mainChannel.receive(0);
Message<?> duplicate = secondaryChannel.receive(0);
Object duplicateId = duplicate.getId();
assertNotNull(duplicateId);
assertFalse("message ids should not match", original.getId().equals(duplicateId));
}
@Test
public void testOriginalIdStoredAsAttribute() {
QueueChannel mainChannel = new QueueChannel();
QueueChannel secondaryChannel = new QueueChannel();
mainChannel.addInterceptor(new WireTap(secondaryChannel));
mainChannel.send(new StringMessage("testing"));
Message<?> original = mainChannel.receive(0);
Message<?> duplicate = secondaryChannel.receive(0);
Object originalIdAttribute = duplicate.getHeader().getAttribute(WireTap.ORIGINAL_MESSAGE_ID_KEY);
assertNotNull(originalIdAttribute);
assertEquals(original.getId(), originalIdAttribute);
}
@Test
public void testNewTimestampGeneratedForDuplicate() throws InterruptedException {
QueueChannel mainChannel = new QueueChannel();
QueueChannel secondaryChannel = new QueueChannel();
mainChannel.addInterceptor(new WireTap(secondaryChannel));
Message<?> message = new StringMessage("testing");
Thread.sleep(3);
mainChannel.send(message);
Message<?> original = mainChannel.receive(0);
Message<?> duplicate = secondaryChannel.receive(0);
assertTrue("original timestamp should precede duplicate",
original.getHeader().getTimestamp().before(duplicate.getHeader().getTimestamp()));
}
public void testDuplicateMessageContainsAttribute() {
QueueChannel mainChannel = new QueueChannel();
QueueChannel secondaryChannel = new QueueChannel();
mainChannel.addInterceptor(new WireTap(secondaryChannel));
Message<?> message = new StringMessage("testing");
String attributeKey = "testAttribute";
Integer attributeValue = new Integer(123);
message.getHeader().setAttribute(attributeKey, attributeValue);
mainChannel.send(message);
Message<?> original = mainChannel.receive(0);
Message<?> duplicate = secondaryChannel.receive(0);
Object originalAttribute = original.getHeader().getAttribute(attributeKey);
Object duplicateAttribute = duplicate.getHeader().getAttribute(attributeKey);
assertNotNull(originalAttribute);
assertNotNull(duplicateAttribute);
assertEquals(originalAttribute, duplicateAttribute);
}
@Test
public void testDuplicateMessageContainsProperty() {
QueueChannel mainChannel = new QueueChannel();
QueueChannel secondaryChannel = new QueueChannel();
mainChannel.addInterceptor(new WireTap(secondaryChannel));
Message<?> message = new StringMessage("testing");
String propertyKey = "testProperty";
String propertyValue = "foo";
message.getHeader().setProperty(propertyKey, propertyValue);
mainChannel.send(message);
Message<?> original = mainChannel.receive(0);
Message<?> duplicate = secondaryChannel.receive(0);
String originalProperty = original.getHeader().getProperty(propertyKey);
String duplicateProperty = duplicate.getHeader().getProperty(propertyKey);
assertNotNull(originalProperty);
assertNotNull(duplicateProperty);
assertEquals(originalProperty, duplicateProperty);
}
private static class TestSelector implements MessageSelector {
private boolean shouldAccept;
public TestSelector(boolean shouldAccept) {
this.shouldAccept = shouldAccept;
}
public boolean accept(Message<?> message) {
return this.shouldAccept;
}
}
}

View File

@@ -0,0 +1,34 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.config;
import java.util.List;
/**
* @author Marius Bogoevici
*/
public class Adder {
public Long add(List<Long> results) {
long total = 0l;
for (long partialResult: results) {
total += partialResult;
}
return total;
}
}

View File

@@ -0,0 +1,101 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.config;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.bus.MessageBus;
import org.springframework.integration.endpoint.HandlerEndpoint;
import org.springframework.integration.handler.MessageHandlerChain;
import org.springframework.integration.router.AggregatingMessageHandler;
import org.springframework.integration.router.SequenceSizeCompletionStrategy;
/**
* @author Marius Bogoevici
*/
public class AggregatorAnnotationTests {
@Test
public void testAnnotationWithDefaultSettings() {
ApplicationContext context = new ClassPathXmlApplicationContext(
new String[] { "classpath:/org/springframework/integration/config/testAnnotatedAggregator.xml" });
final String endpointName = "endpointWithDefaultAnnotation";
DirectFieldAccessor aggregatingMessageHandlerAccessor = getDirectFieldAccessorForAggregatingHandler(context,
endpointName);
Assert.assertTrue(aggregatingMessageHandlerAccessor.getPropertyValue("completionStrategy") instanceof SequenceSizeCompletionStrategy);
Assert.assertNull(aggregatingMessageHandlerAccessor.getPropertyValue("defaultReplyChannel"));
Assert.assertNull(aggregatingMessageHandlerAccessor.getPropertyValue("discardChannel"));
Assert.assertEquals(AggregatingMessageHandler.DEFAULT_SEND_TIMEOUT, aggregatingMessageHandlerAccessor
.getPropertyValue("sendTimeout"));
Assert.assertEquals(AggregatingMessageHandler.DEFAULT_TIMEOUT, aggregatingMessageHandlerAccessor
.getPropertyValue("timeout"));
Assert.assertEquals(false, aggregatingMessageHandlerAccessor.getPropertyValue("sendPartialResultOnTimeout"));
Assert.assertEquals(AggregatingMessageHandler.DEFAULT_REAPER_INTERVAL, aggregatingMessageHandlerAccessor
.getPropertyValue("reaperInterval"));
Assert.assertEquals(AggregatingMessageHandler.DEFAULT_TRACKED_CORRRELATION_ID_CAPACITY,
aggregatingMessageHandlerAccessor.getPropertyValue("trackedCorrelationIdCapacity"));
}
@Test
public void testAnnotationWithCustomSettings() {
ApplicationContext context = new ClassPathXmlApplicationContext(
new String[] { "classpath:/org/springframework/integration/config/testAnnotatedAggregator.xml" });
final String endpointName = "endpointWithCustomizedAnnotation";
DirectFieldAccessor aggregatingMessageHandlerAccessor = getDirectFieldAccessorForAggregatingHandler(context,
endpointName);
Assert.assertTrue(aggregatingMessageHandlerAccessor.getPropertyValue("completionStrategy") instanceof SequenceSizeCompletionStrategy);
Assert.assertEquals(getMessageBus(context).lookupChannel("replyChannel"), aggregatingMessageHandlerAccessor
.getPropertyValue("defaultReplyChannel"));
Assert.assertEquals(getMessageBus(context).lookupChannel("discardChannel"), aggregatingMessageHandlerAccessor
.getPropertyValue("discardChannel"));
Assert.assertEquals(98765432l, aggregatingMessageHandlerAccessor
.getPropertyValue("sendTimeout"));
Assert.assertEquals(4567890l, aggregatingMessageHandlerAccessor
.getPropertyValue("timeout"));
Assert.assertEquals(true, aggregatingMessageHandlerAccessor.getPropertyValue("sendPartialResultOnTimeout"));
Assert.assertEquals(1234l, aggregatingMessageHandlerAccessor
.getPropertyValue("reaperInterval"));
Assert.assertEquals(42,
aggregatingMessageHandlerAccessor.getPropertyValue("trackedCorrelationIdCapacity"));
}
@SuppressWarnings("unchecked")
private DirectFieldAccessor getDirectFieldAccessorForAggregatingHandler(ApplicationContext context,
final String endpointName) {
MessageBus messageBus = getMessageBus(context);
HandlerEndpoint endpoint = (HandlerEndpoint) messageBus.lookupEndpoint(endpointName + "-endpoint");
MessageHandlerChain messageHandlerChain = (MessageHandlerChain) endpoint.getHandler();
AggregatingMessageHandler aggregatingMessageHandler = (AggregatingMessageHandler) ((List) new DirectFieldAccessor(
messageHandlerChain).getPropertyValue("handlers")).get(0);
DirectFieldAccessor aggregatingMessageHandlerAccessor = new DirectFieldAccessor(aggregatingMessageHandler);
return aggregatingMessageHandlerAccessor;
}
private MessageBus getMessageBus(ApplicationContext context) {
MessageBus messageBus = (MessageBus) context.getBean(MessageBusParser.MESSAGE_BUS_BEAN_NAME);
return messageBus;
}
}

View File

@@ -0,0 +1,167 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.config;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.parsing.BeanDefinitionParsingException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.channel.MessageChannel;
import org.springframework.integration.message.GenericMessage;
import org.springframework.integration.message.Message;
import org.springframework.integration.router.AggregatingMessageHandler;
import org.springframework.integration.router.CompletionStrategy;
import org.springframework.integration.router.CompletionStrategyAdapter;
import org.springframework.integration.util.MethodInvoker;
/**
* @author Marius Bogoevici
*/
public class AggregatorParserTests {
private ApplicationContext context;
@Before
public void setUp() {
this.context = new ClassPathXmlApplicationContext("aggregatorParserTests.xml", this.getClass());
}
@Test
public void testAggregation() {
AggregatingMessageHandler aggregatingHandler = (AggregatingMessageHandler) context
.getBean("aggregatorWithReference");
TestAggregator aggregatorBean = (TestAggregator) context.getBean("aggregatorBean");
List<Message<?>> outboundMessages = new ArrayList<Message<?>>();
outboundMessages.add(createMessage("123", "id1", 3, 1, null));
outboundMessages.add(createMessage("789", "id1", 3, 3, null));
outboundMessages.add(createMessage("456", "id1", 3, 2, null));
for (Message<?> message : outboundMessages) {
aggregatingHandler.handle(message);
}
Assert.assertEquals("One and only one message must have been aggregated", 1, aggregatorBean
.getAggregatedMessages().size());
Message<?> aggregatedMessage = aggregatorBean.getAggregatedMessages().get("id1");
Assert.assertEquals("The aggreggated message payload is not correct", "123456789", aggregatedMessage
.getPayload());
}
@Test
public void testPropertyAssignment() throws Exception {
AggregatingMessageHandler completeAggregatingMessageHandler = (AggregatingMessageHandler) context
.getBean("completelyDefinedAggregator");
TestAggregator testAggregator = (TestAggregator) context.getBean("aggregatorBean");
CompletionStrategy completionStrategy = (CompletionStrategy) context.getBean("completionStrategy");
MessageChannel defaultReplyChannel = (MessageChannel) context.getBean("replyChannel");
MessageChannel discardChannel = (MessageChannel) context.getBean("discardChannel");
DirectFieldAccessor messageHandlerFieldAccessor = new DirectFieldAccessor(completeAggregatingMessageHandler);
Assert.assertEquals("The AggregatingMessageHandler is not injected with the appropriate Aggregator instance",
testAggregator, messageHandlerFieldAccessor.getPropertyValue("aggregator"));
Assert.assertEquals(
"The AggregatingMessageHandler is not injected with the appropriate CompletionStrategy instance",
completionStrategy, messageHandlerFieldAccessor.getPropertyValue("completionStrategy"));
Assert.assertEquals("The AggregatingMessageHandler is not injected with the appropriate default reply channel",
defaultReplyChannel, messageHandlerFieldAccessor.getPropertyValue("defaultReplyChannel"));
Assert.assertEquals("The AggregatingMessageHandler is not injected with the appropriate discard channel",
discardChannel, messageHandlerFieldAccessor.getPropertyValue("discardChannel"));
Assert.assertEquals("The AggregatingMessageHandler is not set with the appropriate timeout value", 86420000l,
messageHandlerFieldAccessor.getPropertyValue("sendTimeout"));
Assert.assertEquals(
"The AggregatingMessageHandler is not configured with the appropriate 'send partial results on timeout' flag",
true, messageHandlerFieldAccessor.getPropertyValue("sendPartialResultOnTimeout"));
Assert.assertEquals("The AggregatingMessageHandler is not configured with the appropriate reaper interval",
135l, messageHandlerFieldAccessor.getPropertyValue("reaperInterval"));
Assert.assertEquals(
"The AggregatingMessageHandler is not configured with the appropriate tracked correlationId capacity",
99, messageHandlerFieldAccessor.getPropertyValue("trackedCorrelationIdCapacity"));
Assert.assertEquals("The AggregatingMessageHandler is not configured with the appropriate timeout",
42l, messageHandlerFieldAccessor.getPropertyValue("timeout"));
}
@Test
public void testSimpleJavaBeanAggregator() {
AggregatingMessageHandler addingAggregator = (AggregatingMessageHandler) context.getBean("aggregatorWithReferenceAndMethod");
List<Message<?>> outboundMessages = new ArrayList<Message<?>>();
outboundMessages.add(createMessage(1l, "id1", 3, 1, null));
outboundMessages.add(createMessage(2l, "id1", 3, 3, null));
outboundMessages.add(createMessage(3l, "id1", 3, 2, null));
for (Message<?> message : outboundMessages) {
addingAggregator.handle(message);
}
MessageChannel replyChannel = (MessageChannel) context.getBean("replyChannel");
Message<?> response = replyChannel.receive();
Assert.assertEquals(6l, response.getPayload());
}
@Test(expected=BeanCreationException.class)
public void testMissingMethodOnAggregator() {
context = new ClassPathXmlApplicationContext("invalidMethodNameAggregator.xml", this.getClass());
}
@Test(expected=BeanDefinitionParsingException.class)
public void testDuplicateCompletionStrategyDefinition() {
context = new ClassPathXmlApplicationContext("completionStrategyMethodWithMissingReference.xml", this.getClass());
}
@Test
public void testAggregatorWithPojoCompletionStrategy(){
AggregatingMessageHandler aggregatorWithPojoCompletionStrategy = (AggregatingMessageHandler) context.getBean("aggregatorWithPojoCompletionStrategy");
CompletionStrategy completionStrategy = (CompletionStrategy)new DirectFieldAccessor(aggregatorWithPojoCompletionStrategy).getPropertyValue("completionStrategy");
Assert.assertTrue(completionStrategy instanceof CompletionStrategyAdapter);
DirectFieldAccessor completionStrategyAccessor = new DirectFieldAccessor(completionStrategy);
MethodInvoker invoker = (MethodInvoker) completionStrategyAccessor.getPropertyValue("invoker");
Assert.assertTrue(new DirectFieldAccessor(invoker).getPropertyValue("object") instanceof MaxValueCompletionStrategy);
Assert.assertTrue(((Method)completionStrategyAccessor.getPropertyValue("method")).getName().equals("checkCompleteness"));
aggregatorWithPojoCompletionStrategy.handle(createMessage(1l, "id1", 0 , 0, null));
aggregatorWithPojoCompletionStrategy.handle(createMessage(2l, "id1", 0 , 0, null));
aggregatorWithPojoCompletionStrategy.handle(createMessage(3l, "id1", 0 , 0, null));
MessageChannel replyChannel = (MessageChannel) context.getBean("replyChannel");
Message<?> reply = replyChannel.receive(0);
Assert.assertNull(reply);
aggregatorWithPojoCompletionStrategy.handle(createMessage(5l, "id1", 0 , 0, null));
reply = replyChannel.receive(0);
Assert.assertNotNull(reply);
Assert.assertEquals(11l, reply.getPayload());
}
@Test(expected=BeanDefinitionParsingException.class)
public void testAggregatorWithDuplicateCompletionStrategy() {
context = new ClassPathXmlApplicationContext("duplicateCompletionStrategy.xml", this.getClass());
}
private static <T> Message<T> createMessage(T payload, Object correlationId, int sequenceSize, int sequenceNumber,
MessageChannel replyChannel) {
GenericMessage<T> message = new GenericMessage<T>(payload);
message.getHeader().setCorrelationId(correlationId);
message.getHeader().setSequenceSize(sequenceSize);
message.getHeader().setSequenceNumber(sequenceNumber);
message.getHeader().setReturnAddress(replyChannel);
return message;
}
}

View File

@@ -0,0 +1,79 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.config;
import java.lang.reflect.Method;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.bus.MessageBus;
import org.springframework.integration.endpoint.HandlerEndpoint;
import org.springframework.integration.handler.MessageHandlerChain;
import org.springframework.integration.router.AggregatingMessageHandler;
import org.springframework.integration.router.CompletionStrategyAdapter;
/**
* @author Marius Bogoevici
*/
public class CompletionStrategyAnnotationTests {
@Test
public void testAnnotationWithDefaultSettings() {
ApplicationContext context = new ClassPathXmlApplicationContext(
new String[] { "classpath:/org/springframework/integration/config/testAnnotatedAggregator.xml" });
final String endpointName = "endpointWithDefaultAnnotationAndCustomCompletionStrategy";
DirectFieldAccessor aggregatingMessageHandlerAccessor = getDirectFieldAccessorForAggregatingHandler(context,
endpointName);
Assert.assertTrue(aggregatingMessageHandlerAccessor.getPropertyValue("completionStrategy") instanceof CompletionStrategyAdapter);
DirectFieldAccessor invokerAccessor = new DirectFieldAccessor(new DirectFieldAccessor(
aggregatingMessageHandlerAccessor.getPropertyValue("completionStrategy")).getPropertyValue("invoker"));
Assert.assertSame(context.getBean(endpointName), invokerAccessor.getPropertyValue("object"));
Method completionCheckerMethod = (Method) invokerAccessor.getPropertyValue("method");
Assert.assertEquals("completionChecker", completionCheckerMethod.getName());
}
@Test(expected=BeanCreationException.class)
public void testInvalidAnnotation() {
new ClassPathXmlApplicationContext(new String[] {
"classpath:/org/springframework/integration/config/testInvalidCompletionStrategyAnnotation.xml" });
}
@SuppressWarnings("unchecked")
private DirectFieldAccessor getDirectFieldAccessorForAggregatingHandler(ApplicationContext context,
final String endpointName) {
MessageBus messageBus = getMessageBus(context);
HandlerEndpoint endpoint = (HandlerEndpoint) messageBus
.lookupEndpoint(endpointName + "-endpoint");
MessageHandlerChain messageHandlerChain = (MessageHandlerChain) endpoint.getHandler();
AggregatingMessageHandler aggregatingMessageHandler = (AggregatingMessageHandler) ((List) new DirectFieldAccessor(
messageHandlerChain).getPropertyValue("handlers")).get(0);
DirectFieldAccessor aggregatingMessageHandlerAccessor = new DirectFieldAccessor(aggregatingMessageHandler);
return aggregatingMessageHandlerAccessor;
}
private MessageBus getMessageBus(ApplicationContext context) {
MessageBus messageBus = (MessageBus) context.getBean(MessageBusParser.MESSAGE_BUS_BEAN_NAME);
return messageBus;
}
}

View File

@@ -0,0 +1,160 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.springframework.context.Lifecycle;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.channel.MessageChannel;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.endpoint.ConcurrencyPolicy;
import org.springframework.integration.endpoint.HandlerEndpoint;
import org.springframework.integration.message.GenericMessage;
import org.springframework.integration.message.Message;
import org.springframework.integration.message.MessageHandlingException;
import org.springframework.integration.message.StringMessage;
import org.springframework.integration.message.Target;
/**
* @author Mark Fisher
*/
public class EndpointParserTests {
@Test
public void testSimpleEndpoint() throws InterruptedException {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"simpleEndpointTests.xml", this.getClass());
context.start();
MessageChannel channel = (MessageChannel) context.getBean("testChannel");
TestHandler handler = (TestHandler) context.getBean("testHandler");
assertNull(handler.getMessageString());
channel.send(new GenericMessage<String>(1, "test"));
handler.getLatch().await(500, TimeUnit.MILLISECONDS);
assertEquals("test", handler.getMessageString());
}
@Test
public void testHandlerAdapterEndpoint() throws InterruptedException {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"handlerAdapterEndpointTests.xml", this.getClass());
context.start();
MessageChannel channel = (MessageChannel) context.getBean("testChannel");
TestBean bean = (TestBean) context.getBean("testBean");
assertNull(bean.getMessage());
channel.send(new GenericMessage<String>(1, "test"));
bean.getLatch().await(500, TimeUnit.MILLISECONDS);
assertEquals("test", bean.getMessage());
}
@Test
public void testHandlerChainEndpoint() throws InterruptedException {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"endpointWithHandlerChainElement.xml", this.getClass());
MessageChannel channel = (MessageChannel) context.getBean("testChannel");
MessageChannel replyChannel = (MessageChannel) context.getBean("replyChannel");
channel.send(new StringMessage("test"));
Message<?> reply = replyChannel.receive(500);
assertNotNull(reply);
assertEquals("test-1-2-3", reply.getPayload());
}
@Test
public void testDefaultConcurrency() throws InterruptedException {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"endpointConcurrencyTests.xml", this.getClass());
HandlerEndpoint endpoint = (HandlerEndpoint) context.getBean("defaultConcurrencyEndpoint");
ConcurrencyPolicy concurrencyPolicy = endpoint.getConcurrencyPolicy();
assertEquals(ConcurrencyPolicy.DEFAULT_CORE_SIZE, concurrencyPolicy.getCoreSize());
assertEquals(ConcurrencyPolicy.DEFAULT_MAX_SIZE, concurrencyPolicy.getMaxSize());
assertEquals(ConcurrencyPolicy.DEFAULT_QUEUE_CAPACITY, concurrencyPolicy.getQueueCapacity());
assertEquals(ConcurrencyPolicy.DEFAULT_KEEP_ALIVE_SECONDS, concurrencyPolicy.getKeepAliveSeconds());
}
@Test
public void testConfiguredConcurrency() throws InterruptedException {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"endpointConcurrencyTests.xml", this.getClass());
HandlerEndpoint endpoint = (HandlerEndpoint) context.getBean("configuredConcurrencyEndpoint");
ConcurrencyPolicy concurrencyPolicy = endpoint.getConcurrencyPolicy();
assertEquals(7, concurrencyPolicy.getCoreSize());
assertEquals(77, concurrencyPolicy.getMaxSize());
assertEquals(777, concurrencyPolicy.getQueueCapacity());
assertEquals(7777, concurrencyPolicy.getKeepAliveSeconds());
}
@Test
public void testEndpointWithSelectorAccepts() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"endpointWithSelectors.xml", this.getClass());
Target endpoint = (Target) context.getBean("endpoint");
((Lifecycle) endpoint).start();
Message<?> message = new StringMessage("test");
MessageChannel replyChannel = new QueueChannel();
message.getHeader().setReturnAddress(replyChannel);
endpoint.send(message);
Message<?> reply = replyChannel.receive(500);
assertNotNull(reply);
assertEquals("foo", reply.getPayload());
}
@Test
public void testEndpointWithSelectorRejects() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"endpointWithSelectors.xml", this.getClass());
Target endpoint = (Target) context.getBean("endpoint");
((Lifecycle) endpoint).start();
assertFalse(endpoint.send(new GenericMessage<Integer>(123)));
}
@Test
public void testCustomErrorHandler() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"endpointWithErrorHandler.xml", this.getClass());
Target endpoint = (Target) context.getBean("endpoint");
TestErrorHandler errorHandler = (TestErrorHandler) context.getBean("errorHandler");
assertNull(errorHandler.getLastError());
Message<?> message = new StringMessage("test");
endpoint.send(message);
Throwable error = errorHandler.getLastError();
assertEquals(MessageHandlingException.class, error.getClass());
MessageHandlingException exception = (MessageHandlingException) error;
assertEquals(message, exception.getFailedMessage());
}
@Test
public void testCustomReplyHandler() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"endpointWithReplyHandler.xml", this.getClass());
Target endpoint = (Target) context.getBean("endpoint");
TestReplyHandler replyHandler = (TestReplyHandler) context.getBean("replyHandler");
assertNull(replyHandler.getLastMessage());
Message<?> message = new StringMessage("test");
endpoint.send(message);
Message<?> reply = replyHandler.getLastMessage();
assertNotNull(reply);
assertEquals("foo", reply.getPayload());
}
}

View File

@@ -0,0 +1,32 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.config;
import org.springframework.integration.handler.MessageHandler;
import org.springframework.integration.message.Message;
import org.springframework.integration.message.MessageHandlingException;
/**
* @author Mark Fisher
*/
public class ExceptionThrowingTestHandler implements MessageHandler {
public Message<?> handle(Message<?> message) {
throw new MessageHandlingException(message, "intentional test failure");
}
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.handler.MessageHandler;
import org.springframework.integration.message.Message;
import org.springframework.integration.message.StringMessage;
/**
* @author Mark Fisher
*/
public class HandlerParserTests {
@Test
public void testTopLevelHandlerAdapter() {
ApplicationContext context = new ClassPathXmlApplicationContext(
"handlerAdapterParserTests.xml", HandlerParserTests.class);
MessageHandler adapter = (MessageHandler) context.getBean("handlerAdapter");
assertNotNull(adapter);
Message<?> reply = adapter.handle(new StringMessage("foo"));
assertNotNull(reply);
assertEquals("bar", reply.getPayload());
}
@Test
public void testHandlerChain() {
ApplicationContext context = new ClassPathXmlApplicationContext(
"handlerChainParserTests.xml", HandlerParserTests.class);
TestBean testBean = (TestBean) context.getBean("testBean");
assertNull(testBean.getMessage());
MessageHandler handlerChain = (MessageHandler) context.getBean("handlerChain");
assertNotNull(handlerChain);
Message<?> reply = handlerChain.handle(new StringMessage("test"));
assertNotNull(reply);
assertEquals(0, testBean.getLatch().getCount());
assertEquals("foo", testBean.getMessage());
assertEquals("bar", reply.getPayload());
}
}

View File

@@ -0,0 +1,37 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.config;
import java.util.List;
public class MaxValueCompletionStrategy {
private long maxValue;
public MaxValueCompletionStrategy(long maxValue){
this.maxValue = maxValue;
}
public boolean checkCompleteness(List<Long> numbers) {
int sum = 0;
for (long number: numbers) {
sum += number;
}
return sum >= maxValue;
}
}

View File

@@ -0,0 +1,197 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.SimpleApplicationEventMulticaster;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.task.SyncTaskExecutor;
import org.springframework.integration.ConfigurationException;
import org.springframework.integration.bus.MessageBus;
import org.springframework.integration.bus.TestMessageBusAwareImpl;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.endpoint.TargetEndpoint;
import org.springframework.integration.handler.TestHandlers;
import org.springframework.integration.scheduling.SimpleMessagingTaskScheduler;
import org.springframework.integration.scheduling.Subscription;
/**
* @author Mark Fisher
* @author Marius Bogoevici
*/
public class MessageBusParserTests {
@Test
public void testErrorChannelReference() {
ApplicationContext context = new ClassPathXmlApplicationContext(
"messageBusWithErrorChannelReference.xml", this.getClass());
MessageBus bus = (MessageBus) context.getBean(MessageBusParser.MESSAGE_BUS_BEAN_NAME);
bus.initialize();
assertEquals(context.getBean("testErrorChannel"), bus.getErrorChannel());
}
@Test
public void testDefaultErrorChannel() {
ApplicationContext context = new ClassPathXmlApplicationContext(
"messageBusWithDefaults.xml", this.getClass());
MessageBus bus = (MessageBus) context.getBean(MessageBusParser.MESSAGE_BUS_BEAN_NAME);
bus.initialize();
assertNotNull("bus should have created a default error channel", bus.getErrorChannel());
}
@Test(expected=ConfigurationException.class)
public void testAutoCreateChannelsDisabledByDefault() {
ApplicationContext context = new ClassPathXmlApplicationContext(
"messageBusWithDefaults.xml", this.getClass());
MessageBus bus = (MessageBus) context.getBean(MessageBusParser.MESSAGE_BUS_BEAN_NAME);
Subscription subscription = new Subscription("unknownChannel");
bus.registerHandler("handler", TestHandlers.nullHandler(), subscription);
}
@Test
public void testAutoCreateChannelsEnabled() {
ApplicationContext context = new ClassPathXmlApplicationContext(
"messageBusWithAutoCreateChannels.xml", this.getClass());
MessageBus bus = (MessageBus) context.getBean(MessageBusParser.MESSAGE_BUS_BEAN_NAME);
Subscription subscription = new Subscription("channelToCreate");
bus.registerHandler("handler", TestHandlers.nullHandler(), subscription);
bus.start();
assertNotNull(bus.lookupChannel("channelToCreate"));
bus.stop();
}
@Test
public void testMultipleMessageBusElements() {
boolean exceptionThrown = false;
try {
new ClassPathXmlApplicationContext("multipleMessageBusElements.xml", this.getClass());
}
catch (BeanDefinitionStoreException e) {
exceptionThrown = true;
assertEquals(ConfigurationException.class, e.getCause().getClass());
}
assertTrue(exceptionThrown);
}
@Test
public void testMessageBusElementAndBean() {
boolean exceptionThrown = false;
try {
new ClassPathXmlApplicationContext("messageBusElementAndBean.xml", this.getClass());
}
catch (BeanCreationException e) {
exceptionThrown = true;
// an exception is thrown when creating the post-processor, which
// tries to get a reference to the message bus
assertEquals(BeanCreationException.class, e.getCause().getClass());
assertEquals(e.getBeanName(), MessageBusParser.MESSAGE_BUS_AWARE_POST_PROCESSOR_BEAN_NAME);
assertEquals(ConfigurationException.class, ((BeanCreationException) e.getCause()).getCause().getClass());
assertEquals(((BeanCreationException) e.getCause()).getBeanName(), MessageBusParser.MESSAGE_BUS_BEAN_NAME);
}
assertTrue(exceptionThrown);
}
@Test
public void testAutoStartup() {
ApplicationContext context = new ClassPathXmlApplicationContext(
"messageBusWithAutoStartup.xml", this.getClass());
MessageBus bus = (MessageBus) context.getBean(MessageBusParser.MESSAGE_BUS_BEAN_NAME);
assertTrue(bus.isRunning());
bus.stop();
}
@Test
public void testDefaultConcurrency() {
ApplicationContext context = new ClassPathXmlApplicationContext(
"messageBusWithDefaultConcurrencyTests.xml", this.getClass());
TargetEndpoint endpoint1 = (TargetEndpoint) context.getBean("endpoint1");
assertEquals(4, endpoint1.getConcurrencyPolicy().getCoreSize());
assertEquals(7, endpoint1.getConcurrencyPolicy().getMaxSize());
}
@Test
public void testExplicitConcurrencyTakesPrecedence() {
ApplicationContext context = new ClassPathXmlApplicationContext(
"messageBusWithDefaultConcurrencyTests.xml", this.getClass());
TargetEndpoint endpoint2 = (TargetEndpoint) context.getBean("endpoint2");
assertEquals(14, endpoint2.getConcurrencyPolicy().getCoreSize());
assertEquals(17, endpoint2.getConcurrencyPolicy().getMaxSize());
}
@Test
public void testMessageBusAwareAutomaticallyAddedByNamespace() {
ApplicationContext context = new ClassPathXmlApplicationContext(
"messageBusWithMessageBusAware.xml", this.getClass());
TestMessageBusAwareImpl messageBusAware = (TestMessageBusAwareImpl) context.getBean("messageBusAwareBean");
assertTrue(messageBusAware.getMessageBus() == context.getBean(MessageBusParser.MESSAGE_BUS_BEAN_NAME));
}
@Test
public void testMessageBusWithChannelFactory() {
ApplicationContext context = new ClassPathXmlApplicationContext("messageBusWithChannelFactory.xml",
this.getClass());
assertEquals(DirectChannel.class, context.getBean("defaultTypeChannel").getClass());
assertEquals(QueueChannel.class, context.getBean("specifiedTypeChannel").getClass());
}
@Test
public void testMulticasterIsSyncByDefault() {
ApplicationContext context = new ClassPathXmlApplicationContext(
"messageBusWithDefaults.xml", this.getClass());
SimpleApplicationEventMulticaster multicaster = (SimpleApplicationEventMulticaster)
context.getBean(AbstractApplicationContext.APPLICATION_EVENT_MULTICASTER_BEAN_NAME);
DirectFieldAccessor accessor = new DirectFieldAccessor(multicaster);
Object taskExecutor = accessor.getPropertyValue("taskExecutor");
assertEquals(SyncTaskExecutor.class, taskExecutor.getClass());
}
@Test
public void testAsyncMulticasterExplicitlySetToFalse() throws Exception {
AbstractApplicationContext context = new ClassPathXmlApplicationContext(
"messageBusWithoutAsyncEventMulticaster.xml", this.getClass());
context.refresh();
SimpleApplicationEventMulticaster multicaster = (SimpleApplicationEventMulticaster)
context.getBean(AbstractApplicationContext.APPLICATION_EVENT_MULTICASTER_BEAN_NAME);
DirectFieldAccessor accessor = new DirectFieldAccessor(multicaster);
Object taskExecutor = accessor.getPropertyValue("taskExecutor");
assertEquals(SyncTaskExecutor.class, taskExecutor.getClass());
}
@Test
public void testAsyncMulticaster() throws Exception {
AbstractApplicationContext context = new ClassPathXmlApplicationContext(
"messageBusWithAsyncEventMulticaster.xml", this.getClass());
context.refresh();
SimpleApplicationEventMulticaster multicaster = (SimpleApplicationEventMulticaster)
context.getBean(AbstractApplicationContext.APPLICATION_EVENT_MULTICASTER_BEAN_NAME);
DirectFieldAccessor accessor = new DirectFieldAccessor(multicaster);
Object taskExecutor = accessor.getPropertyValue("taskExecutor");
assertEquals(SimpleMessagingTaskScheduler.class, taskExecutor.getClass());
}
}

View File

@@ -0,0 +1,154 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.integration.annotation.Subscriber;
import org.springframework.integration.bus.MessageBus;
import org.springframework.integration.channel.MessageChannel;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.message.StringMessage;
/**
* @author Mark Fisher
*/
public class SubscriberAnnotationPostProcessorTests {
@Test
public void testAnnotatedSubscriber() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
GenericApplicationContext context = new GenericApplicationContext();
context.registerBeanDefinition("testChannel", new RootBeanDefinition(QueueChannel.class));
RootBeanDefinition subscriberDef = new RootBeanDefinition(SubscriberAnnotationTestBean.class);
subscriberDef.getConstructorArgumentValues().addGenericArgumentValue(latch);
context.registerBeanDefinition("testBean", subscriberDef);
String busBeanName = MessageBusParser.MESSAGE_BUS_BEAN_NAME;
context.registerBeanDefinition(busBeanName, new RootBeanDefinition(MessageBus.class));
RootBeanDefinition postProcessorDef = new RootBeanDefinition(SubscriberAnnotationPostProcessor.class);
postProcessorDef.getPropertyValues().addPropertyValue("messageBus", new RuntimeBeanReference(busBeanName));
context.registerBeanDefinition("postProcessor", postProcessorDef);
context.refresh();
context.start();
SubscriberAnnotationTestBean testBean = (SubscriberAnnotationTestBean) context.getBean("testBean");
assertEquals(1, latch.getCount());
assertNull(testBean.getMessageText());
MessageChannel testChannel = (MessageChannel) context.getBean("testChannel");
testChannel.send(new StringMessage("test-123"));
latch.await(1000, TimeUnit.MILLISECONDS);
assertEquals(0, latch.getCount());
assertEquals("test-123", testBean.getMessageText());
context.stop();
}
@Test
public void testCustomAnnotation() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
GenericApplicationContext context = new GenericApplicationContext();
context.registerBeanDefinition("testChannel", new RootBeanDefinition(QueueChannel.class));
RootBeanDefinition subscriberDef = new RootBeanDefinition(CustomAnnotationTestBean.class);
subscriberDef.getConstructorArgumentValues().addGenericArgumentValue(latch);
context.registerBeanDefinition("testBean", subscriberDef);
String busBeanName = MessageBusParser.MESSAGE_BUS_BEAN_NAME;
context.registerBeanDefinition(busBeanName, new RootBeanDefinition(MessageBus.class));
RootBeanDefinition postProcessorDef = new RootBeanDefinition(SubscriberAnnotationPostProcessor.class);
postProcessorDef.getPropertyValues().addPropertyValue("messageBus", new RuntimeBeanReference(busBeanName));
postProcessorDef.getPropertyValues().addPropertyValue("subscriberAnnotationType", CustomSubscriberAnnotation.class);
postProcessorDef.getPropertyValues().addPropertyValue("channelNameAttribute", "subscribeTo");
context.registerBeanDefinition("postProcessor", postProcessorDef);
context.refresh();
context.start();
CustomAnnotationTestBean testBean = (CustomAnnotationTestBean) context.getBean("testBean");
assertEquals(1, latch.getCount());
assertNull(testBean.getMessageText());
MessageChannel testChannel = (MessageChannel) context.getBean("testChannel");
testChannel.send(new StringMessage("test-456"));
latch.await(1000, TimeUnit.MILLISECONDS);
assertEquals(0, latch.getCount());
assertEquals("test-456", testBean.getMessageText());
context.stop();
}
public static class AbstractSubscriberAnnotationTestBean {
protected String messageText;
private CountDownLatch latch;
public AbstractSubscriberAnnotationTestBean(CountDownLatch latch) {
this.latch = latch;
}
protected void countDown() {
this.latch.countDown();
}
public String getMessageText() {
return this.messageText;
}
}
public static class SubscriberAnnotationTestBean extends SubscriberAnnotationPostProcessorTests.AbstractSubscriberAnnotationTestBean {
public SubscriberAnnotationTestBean(CountDownLatch latch) {
super(latch);
}
@Subscriber(channel="testChannel")
public void testMethod(String messageText) {
this.messageText = messageText;
this.countDown();
}
}
public static class CustomAnnotationTestBean extends SubscriberAnnotationPostProcessorTests.AbstractSubscriberAnnotationTestBean {
public CustomAnnotationTestBean(CountDownLatch latch) {
super(latch);
}
@CustomSubscriberAnnotation(subscribeTo="testChannel")
public void testMethod(String messageText) {
this.messageText = messageText;
this.countDown();
}
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public static @interface CustomSubscriberAnnotation {
String subscribeTo();
}
}

View File

@@ -0,0 +1,57 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.config;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.springframework.integration.message.Message;
import org.springframework.integration.message.StringMessage;
import org.springframework.integration.router.Aggregator;
import org.springframework.integration.router.MessageSequenceComparator;
/**
* @author Marius Bogoevici
*/
public class TestAggregator implements Aggregator {
private final ConcurrentMap<Object, Message<?>> aggregatedMessages = new ConcurrentHashMap<Object, Message<?>>();
public Message<?> aggregate(List<Message<?>> messages) {
List<Message<?>> sortableList = new ArrayList<Message<?>>(messages);
Collections.sort(sortableList, new MessageSequenceComparator());
StringBuffer buffer = new StringBuffer();
Object correlationId = null;
for (Message<?> message : sortableList) {
buffer.append(message.getPayload().toString());
if (null == correlationId) {
correlationId = message.getHeader().getCorrelationId();
}
}
Message<?> returnedMessage = new StringMessage(buffer.toString());
aggregatedMessages.put(correlationId, returnedMessage);
return returnedMessage;
}
public ConcurrentMap<Object, Message<?>> getAggregatedMessages() {
return aggregatedMessages;
}
}

View File

@@ -0,0 +1,68 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.config;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.springframework.integration.annotation.Aggregator;
import org.springframework.integration.annotation.CompletionStrategy;
import org.springframework.integration.annotation.MessageEndpoint;
import org.springframework.integration.message.Message;
import org.springframework.integration.message.StringMessage;
import org.springframework.integration.router.MessageSequenceComparator;
import org.springframework.stereotype.Component;
/**
* @author Marius Bogoevici
*/
@MessageEndpoint(input="inputChannel")
@Component("endpointWithDefaultAnnotationAndCustomCompletionStrategy")
public class TestAnnotatedEndpointWithCompletionStrategy {
private final ConcurrentMap<Object, Message<?>> aggregatedMessages = new ConcurrentHashMap<Object, Message<?>>();
@Aggregator
public Message<?> aggregatingMethod(List<Message<?>> messages) {
List<Message<?>> sortableList = new ArrayList<Message<?>>(messages);
Collections.sort(sortableList, new MessageSequenceComparator());
StringBuffer buffer = new StringBuffer();
Object correlationId = null;
for (Message<?> message : sortableList) {
buffer.append(message.getPayload().toString());
if (null == correlationId) {
correlationId = message.getHeader().getCorrelationId();
}
}
Message<?> returnedMessage = new StringMessage(buffer.toString());
aggregatedMessages.put(correlationId, returnedMessage);
return returnedMessage;
}
@CompletionStrategy
public boolean completionChecker(List<Message<?>> messages) {
return true;
}
public ConcurrentMap<Object, Message<?>> getAggregatedMessages() {
return aggregatedMessages;
}
}

View File

@@ -0,0 +1,46 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.config;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.springframework.integration.annotation.Aggregator;
import org.springframework.integration.annotation.CompletionStrategy;
import org.springframework.integration.annotation.MessageEndpoint;
import org.springframework.integration.message.Message;
import org.springframework.integration.message.StringMessage;
import org.springframework.integration.router.MessageSequenceComparator;
import org.springframework.stereotype.Component;
/**
* @author Marius Bogoevici
*/
@MessageEndpoint(input="inputChannel")
@Component("endpointWithoutAggregatorAndWithCompletionStrategy")
public class TestAnnotatedEndpointWithCompletionStrategyOnly {
@CompletionStrategy
public boolean checkCompleteness(List<Message<?>> messages) {
throw new UnsupportedOperationException("Not intended to being called");
}
}

View File

@@ -0,0 +1,64 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.config;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.springframework.integration.annotation.Aggregator;
import org.springframework.integration.annotation.MessageEndpoint;
import org.springframework.integration.message.Message;
import org.springframework.integration.message.StringMessage;
import org.springframework.integration.router.MessageSequenceComparator;
import org.springframework.stereotype.Component;
/**
* @author Marius Bogoevici
*/
@MessageEndpoint(input = "inputChannel")
@Component("endpointWithCustomizedAnnotation")
public class TestAnnotatedEndpointWithCustomizedAggregator {
private final ConcurrentMap<Object, Message<?>> aggregatedMessages = new ConcurrentHashMap<Object, Message<?>>();
@Aggregator(defaultReplyChannel = "replyChannel", discardChannel = "discardChannel",
reaperInterval = 1234, sendPartialResultsOnTimeout = true,
sendTimeout = 98765432, timeout = 4567890, trackedCorrelationIdCapacity = 42)
public Message<?> aggregatingMethod(List<Message<?>> messages) {
List<Message<?>> sortableList = new ArrayList<Message<?>>(messages);
Collections.sort(sortableList, new MessageSequenceComparator());
StringBuffer buffer = new StringBuffer();
Object correlationId = null;
for (Message<?> message : sortableList) {
buffer.append(message.getPayload().toString());
if (null == correlationId) {
correlationId = message.getHeader().getCorrelationId();
}
}
Message<?> returnedMessage = new StringMessage(buffer.toString());
aggregatedMessages.put(correlationId, returnedMessage);
return returnedMessage;
}
public ConcurrentMap<Object, Message<?>> getAggregatedMessages() {
return aggregatedMessages;
}
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.config;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.springframework.integration.annotation.Aggregator;
import org.springframework.integration.annotation.MessageEndpoint;
import org.springframework.integration.message.Message;
import org.springframework.integration.message.StringMessage;
import org.springframework.integration.router.MessageSequenceComparator;
import org.springframework.stereotype.Component;
/**
* @author Marius Bogoevici
*/
@MessageEndpoint(input="inputChannel")
@Component("endpointWithDefaultAnnotation")
public class TestAnnotatedEndpointWithDefaultAggregator {
private final ConcurrentMap<Object, Message<?>> aggregatedMessages = new ConcurrentHashMap<Object, Message<?>>();
@Aggregator
public Message<?> aggregatingMethod(List<Message<?>> messages) {
List<Message<?>> sortableList = new ArrayList<Message<?>>(messages);
Collections.sort(sortableList, new MessageSequenceComparator());
StringBuffer buffer = new StringBuffer();
Object correlationId = null;
for (Message<?> message : sortableList) {
buffer.append(message.getPayload().toString());
if (null == correlationId) {
correlationId = message.getHeader().getCorrelationId();
}
}
Message<?> returnedMessage = new StringMessage(buffer.toString());
aggregatedMessages.put(correlationId, returnedMessage);
return returnedMessage;
}
public ConcurrentMap<Object, Message<?>> getAggregatedMessages() {
return aggregatedMessages;
}
}

View File

@@ -0,0 +1,56 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.config;
import java.util.concurrent.CountDownLatch;
/**
* @author Mark Fisher
*/
public class TestBean {
private String message;
private CountDownLatch latch;
private String replyMessageText = null;
public TestBean(int countdown) {
this.latch = new CountDownLatch(countdown);
}
public void setReplyMessageText(String replyMessageText) {
this.replyMessageText = replyMessageText;
}
public CountDownLatch getLatch() {
return this.latch;
}
public String store(String message) {
this.message = message;
latch.countDown();
return this.replyMessageText;
}
public String getMessage() {
return this.message;
}
}

View File

@@ -0,0 +1,54 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.config;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.integration.channel.MessageChannel;
import org.springframework.integration.channel.interceptor.ChannelInterceptorAdapter;
import org.springframework.integration.message.Message;
/**
* @author Mark Fisher
*/
public class TestChannelInterceptor extends ChannelInterceptorAdapter {
private final AtomicInteger sendCount = new AtomicInteger();
private final AtomicInteger receiveCount = new AtomicInteger();
@Override
public boolean preSend(Message<?> message, MessageChannel channel) {
sendCount.incrementAndGet();
return true;
}
@Override
public void postReceive(Message<?> message, MessageChannel channel) {
receiveCount.incrementAndGet();
}
public int getSendCount() {
return this.sendCount.get();
}
public int getReceiveCount() {
return this.receiveCount.get();
}
}

View File

@@ -0,0 +1,33 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.config;
import java.util.List;
import org.springframework.integration.message.Message;
import org.springframework.integration.router.CompletionStrategy;
/**
* @author Marius Bogoevici
*/
public class TestCompletionStrategy implements CompletionStrategy {
public boolean isComplete(List<Message<?>> messages) {
throw new UnsupportedOperationException("This is not intended to be implemented, but to verify injection into an <aggregator>");
}
}

View File

@@ -0,0 +1,40 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.config;
import org.springframework.integration.handler.MessageHandler;
import org.springframework.integration.message.Message;
import org.springframework.integration.message.StringMessage;
/**
* @author Mark Fisher
*/
public class TestConcatenatingHandler implements MessageHandler {
private String value;
public TestConcatenatingHandler(String value) {
this.value = value;
}
public Message<?> handle(Message<?> message) {
return new StringMessage(message.getPayload() + this.value);
}
}

View File

@@ -0,0 +1,37 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.config;
import org.springframework.integration.util.ErrorHandler;
/**
* @author Mark Fisher
*/
public class TestErrorHandler implements ErrorHandler {
private volatile Throwable lastError;
public void handle(Throwable t) {
this.lastError = t;
}
public Throwable getLastError() {
return this.lastError;
}
}

View File

@@ -0,0 +1,64 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.config;
import java.util.concurrent.CountDownLatch;
import org.springframework.integration.handler.MessageHandler;
import org.springframework.integration.message.Message;
import org.springframework.integration.message.StringMessage;
/**
* @author Mark Fisher
*/
public class TestHandler implements MessageHandler {
private String messageString;
private CountDownLatch latch;
private String replyMessageText = null;
public TestHandler() {
this(1);
}
public TestHandler(int countdown) {
this.latch = new CountDownLatch(countdown);
}
public void setReplyMessageText(String replyMessageText) {
this.replyMessageText = replyMessageText;
}
public Message handle(Message message) {
this.messageString = (String) message.getPayload();
this.latch.countDown();
return (this.replyMessageText != null) ? new StringMessage(this.replyMessageText) : null;
}
public String getMessageString() {
return this.messageString;
}
public CountDownLatch getLatch() {
return this.latch;
}
}

View File

@@ -0,0 +1,39 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.config;
import org.springframework.integration.handler.ReplyHandler;
import org.springframework.integration.message.Message;
import org.springframework.integration.message.MessageHeader;
/**
* @author Mark Fisher
*/
public class TestReplyHandler implements ReplyHandler {
private volatile Message<?> lastMessage;
public void handle(Message<?> replyMessage, MessageHeader originalMessageHeader) {
this.lastMessage = replyMessage;
}
public Message<?> getLastMessage() {
return this.lastMessage;
}
}

View File

@@ -0,0 +1,48 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration-core-1.0.xsd">
<message-bus/>
<aggregator id="aggregatorWithReference" ref="aggregatorBean" />
<aggregator id="completelyDefinedAggregator" ref="aggregatorBean"
completion-strategy="completionStrategy"
default-reply-channel="replyChannel" discard-channel="discardChannel"
send-timeout="86420000" send-partial-result-on-timeout="true"
reaper-interval="135" tracked-correlation-id-capacity="99"
timeout="42" />
<aggregator id="aggregatorWithReferenceAndMethod" ref="adderBean"
method="add" default-reply-channel="replyChannel" />
<aggregator id="aggregatorWithPojoCompletionStrategy"
ref="adderBean" method="add" default-reply-channel="replyChannel">
<completion-strategy ref="pojoCompletionStrategy"
method="checkCompleteness" />
</aggregator>
<channel id="replyChannel" />
<channel id="discardChannel" />
<beans:bean id="aggregatorBean"
class="org.springframework.integration.config.TestAggregator" />
<beans:bean id="adderBean"
class="org.springframework.integration.config.Adder" />
<beans:bean id="completionStrategy"
class="org.springframework.integration.config.TestCompletionStrategy" />
<beans:bean id="pojoCompletionStrategy"
class="org.springframework.integration.config.MaxValueCompletionStrategy">
<beans:constructor-arg value="10" />
</beans:bean>
</beans:beans>

View File

@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration-core-1.0.xsd">
<message-bus/>
<aggregator id="aggregator" ref="adderBean" method="add" completion-strategy="testCompletionStrategy" default-reply-channel="replyChannel">
<completion-strategy ref="testCompletionStrategy"/>
</aggregator>
<channel id="replyChannel"/>
<beans:bean id="adderBean" class="org.springframework.integration.config.Adder"/>
<beans:bean id="completionStrategyBean" class="org.springframework.integration.config.TestCompletionStrategy"></beans:bean>
</beans:beans>

View File

@@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration-core-1.0.xsd">
<aggregator id="aggregatorWithPojoCompletionStrategy" completion-strategy="completionStrategy"
ref="adderBean" method="add" default-reply-channel="replyChannel">
<completion-strategy ref="pojoCompletionStrategy"
method="checkCompleteness" />
</aggregator>
<channel id="replyChannel" />
<beans:bean id="adderBean"
class="org.springframework.integration.config.Adder" />
<beans:bean id="completionStrategy"
class="org.springframework.integration.config.TestCompletionStrategy" />
<beans:bean id="pojoCompletionStrategy"
class="org.springframework.integration.config.MaxValueCompletionStrategy">
<beans:constructor-arg value="10" />
</beans:bean>
</beans:beans>

View File

@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration-core-1.0.xsd">
<message-bus/>
<channel id="testChannel"/>
<handler-endpoint id="defaultConcurrencyEndpoint" input-channel="testChannel" handler="testHandler">
<concurrency/>
</handler-endpoint>
<handler-endpoint id="configuredConcurrencyEndpoint" input-channel="testChannel" handler="testHandler">
<concurrency core="7" max="77" queue-capacity="777" keep-alive="7777"/>
</handler-endpoint>
<beans:bean id="testHandler" class="org.springframework.integration.config.TestHandler">
<beans:constructor-arg value="1"/>
</beans:bean>
</beans:beans>

View File

@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration-core-1.0.xsd">
<message-bus/>
<channel id="testChannel"/>
<handler-endpoint id="endpoint" input-channel="testChannel" handler="testHandler" error-handler="errorHandler"/>
<beans:bean id="testHandler" class="org.springframework.integration.config.ExceptionThrowingTestHandler"/>
<beans:bean id="errorHandler" class="org.springframework.integration.config.TestErrorHandler"/>
</beans:beans>

View File

@@ -0,0 +1,38 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration-core-1.0.xsd">
<message-bus/>
<queue-channel id="testChannel" capacity="50"/>
<channel id="replyChannel"/>
<handler-chain id="chain">
<handler ref="handler1"/>
<handler ref="handler2"/>
<handler ref="handler3"/>
</handler-chain>
<handler-endpoint input-channel="testChannel" handler="chain" output-channel="replyChannel">
<schedule period="100"/>
</handler-endpoint>
<beans:bean id="handler1" class="org.springframework.integration.config.TestConcatenatingHandler">
<beans:constructor-arg value="-1"/>
</beans:bean>
<beans:bean id="handler2" class="org.springframework.integration.config.TestConcatenatingHandler">
<beans:constructor-arg value="-2"/>
</beans:bean>
<beans:bean id="handler3" class="org.springframework.integration.config.TestConcatenatingHandler">
<beans:constructor-arg value="-3"/>
</beans:bean>
</beans:beans>

View File

@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration-core-1.0.xsd">
<message-bus/>
<channel id="testChannel"/>
<handler-endpoint id="endpoint" input-channel="testChannel" handler="testHandler" reply-handler="replyHandler"/>
<beans:bean id="testHandler" class="org.springframework.integration.config.TestHandler">
<beans:property name="replyMessageText" value="foo"/>
</beans:bean>
<beans:bean id="replyHandler" class="org.springframework.integration.config.TestReplyHandler"/>
</beans:beans>

View File

@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration-core-1.0.xsd">
<message-bus/>
<queue-channel id="testChannel" capacity="50"/>
<handler-endpoint id="endpoint" input-channel="testChannel" handler="testHandler">
<schedule period="100"/>
<selector ref="typeSelector"/>
</handler-endpoint>
<beans:bean id="typeSelector" class="org.springframework.integration.message.selector.PayloadTypeSelector">
<beans:constructor-arg value="java.lang.String"/>
</beans:bean>
<beans:bean id="testHandler" class="org.springframework.integration.config.TestHandler">
<beans:constructor-arg value="1"/>
<beans:property name="replyMessageText" value="foo"/>
</beans:bean>
</beans:beans>

View File

@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration-core-1.0.xsd">
<beans:bean class="org.springframework.integration.bus.MessageBus"/>
<queue-channel id="testChannel" capacity="50"/>
<handler-endpoint input-channel="testChannel" handler="testBean" method="store">
<schedule period="100"/>
</handler-endpoint>
<beans:bean id="testBean" class="org.springframework.integration.config.TestBean">
<beans:constructor-arg value="1"/>
</beans:bean>
</beans:beans>

View File

@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration-core-1.0.xsd">
<handler id="handlerAdapter" ref="testBean" method="store"/>
<beans:bean id="testBean" class="org.springframework.integration.config.TestBean">
<beans:constructor-arg value="1"/>
<beans:property name="replyMessageText" value="bar"/>
</beans:bean>
</beans:beans>

View File

@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration-core-1.0.xsd">
<handler-chain id="handlerChain">
<handler ref="handler1"/>
<handler ref="handler2"/>
<handler ref="testBean" method="store"/>
</handler-chain>
<handler id="handler1" ref="testBean" method="store"/>
<beans:bean id="handler2" class="org.springframework.integration.config.TestHandler">
<beans:constructor-arg value="1"/>
<beans:property name="replyMessageText" value="foo"/>
</beans:bean>
<beans:bean id="testBean" class="org.springframework.integration.config.TestBean">
<beans:constructor-arg value="1"/>
<beans:property name="replyMessageText" value="bar"/>
</beans:bean>
</beans:beans>

View File

@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration-core-1.0.xsd">
<message-bus/>
<aggregator id="aggregatorWithReferenceAndMethod" ref="adderBean" method="substract" default-reply-channel="replyChannel"/>
<channel id="replyChannel"/>
<beans:bean id="adderBean" class="org.springframework.integration.config.Adder"/>
</beans:beans>

View File

@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:integration="http://www.springframework.org/schema/integration"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration-core-1.0.xsd">
<integration:message-bus/>
<bean id="bus" class="org.springframework.integration.bus.MessageBus"/>
</beans>

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration-core-1.0.xsd">
<message-bus configure-async-event-multicaster="true"/>
</beans:beans>

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration-core-1.0.xsd">
<message-bus auto-create-channels="true"/>
</beans:beans>

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration-core-1.0.xsd">
<message-bus auto-startup="true"/>
</beans:beans>

View File

@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration-core-1.0.xsd">
<message-bus channel-factory="directChannelFactory"/>
<beans:bean id="directChannelFactory" class="org.springframework.integration.channel.factory.DirectChannelFactory"/>
<channel id="defaultTypeChannel"/>
<queue-channel id="specifiedTypeChannel"/>
</beans:beans>

View File

@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration-core-1.0.xsd">
<message-bus>
<default-concurrency core="4" max="7"/>
</message-bus>
<channel id="channel"/>
<handler-endpoint id="endpoint1" handler="testHandler" input-channel="channel"/>
<handler-endpoint id="endpoint2" handler="testHandler" input-channel="channel">
<concurrency core="14" max="17"/>
</handler-endpoint>
<beans:bean id="testHandler" class="org.springframework.integration.config.TestHandler">
<beans:constructor-arg value="3"/>
</beans:bean>
</beans:beans>

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration-core-1.0.xsd">
<message-bus/>
</beans:beans>

View File

@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration-core-1.0.xsd">
<channel id="testErrorChannel"/>
<message-bus error-channel="testErrorChannel"/>
</beans:beans>

View File

@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration-core-1.0.xsd">
<message-bus/>
<beans:bean id="messageBusAwareBean" class="org.springframework.integration.bus.TestMessageBusAwareImpl"/>
</beans:beans>

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration-core-1.0.xsd">
<message-bus configure-async-event-multicaster="false"/>
</beans:beans>

View File

@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration-core-1.0.xsd">
<message-bus/>
<message-bus/>
</beans:beans>

View File

@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration-core-1.0.xsd">
<beans:bean class="org.springframework.integration.bus.MessageBus"/>
<queue-channel id="testChannel" capacity="50"/>
<handler-endpoint input-channel="testChannel" handler="testHandler">
<schedule period="100"/>
</handler-endpoint>
<beans:bean id="testHandler" class="org.springframework.integration.config.TestHandler">
<beans:constructor-arg value="1"/>
</beans:bean>
</beans:beans>

View File

@@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration-core-1.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<message-bus/>
<annotation-driven/>
<channel id="inputChannel"/>
<channel id="replyChannel"/>
<channel id="discardChannel"/>
<context:component-scan base-package="org.springframework.integration.config" use-default-filters="false">
<context:include-filter type="regex"
expression="org\.springframework\.integration\.config\.TestAnnotatedEndpoint.*"/>
<context:exclude-filter type="regex"
expression="org\.springframework\.integration\.config\.TestAnnotatedEndpointWithCompletionStrategyOnly"/>
</context:component-scan>
</beans:beans>

View File

@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration-core-1.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<message-bus/>
<annotation-driven/>
<channel id="inputChannel"/>
<channel id="replyChannel"/>
<channel id="discardChannel"/>
<context:component-scan base-package="org.springframework.integration.config" use-default-filters="false">
<context:include-filter type="regex"
expression="org\.springframework\.integration\.config\.TestAnnotatedEndpointWithCompletionStrategyOnly"/>
</context:component-scan>
</beans:beans>

View File

@@ -0,0 +1,101 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.dispatcher;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Collection;
import java.util.Iterator;
import org.junit.Test;
import org.springframework.integration.channel.DispatcherPolicy;
import org.springframework.integration.channel.MessageChannel;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.message.Message;
import org.springframework.integration.message.StringMessage;
/**
* @author Mark Fisher
*/
public class DefaultPollingDispatcherTests {
@Test
public void testSingleMessagePerRetrieval() {
DispatcherPolicy dispatcherPolicy = new DispatcherPolicy();
dispatcherPolicy.setReceiveTimeout(0);
MessageChannel channel = new QueueChannel(5, dispatcherPolicy);
DefaultPollingDispatcher dispatcher = new DefaultPollingDispatcher(channel);
Collection<Message<?>> results = dispatcher.poll();
assertTrue(results.isEmpty());
channel.send(new StringMessage("test1"), 0);
channel.send(new StringMessage("test2"), 0);
results = dispatcher.poll();
assertEquals(1, results.size());
assertEquals("test1", results.iterator().next().getPayload());
results = dispatcher.poll();
assertEquals(1, results.size());
assertEquals("test2", results.iterator().next().getPayload());
}
@Test
public void testMultipleMessagesPerRetrieval() {
DispatcherPolicy dispatcherPolicy = new DispatcherPolicy();
dispatcherPolicy.setReceiveTimeout(0);
dispatcherPolicy.setMaxMessagesPerTask(2);
MessageChannel channel = new QueueChannel(5, dispatcherPolicy);
DefaultPollingDispatcher dispatcher = new DefaultPollingDispatcher(channel);
Collection<Message<?>> results = dispatcher.poll();
assertTrue(results.isEmpty());
channel.send(new StringMessage("test1"), 0);
channel.send(new StringMessage("test2"), 0);
channel.send(new StringMessage("test3"), 0);
results = dispatcher.poll();
assertEquals(2, results.size());
Iterator<Message<?>> iter = results.iterator();
assertEquals("test1", iter.next().getPayload());
assertEquals("test2", iter.next().getPayload());
results = dispatcher.poll();
assertEquals(1, results.size());
assertEquals("test3", results.iterator().next().getPayload());
}
@Test
public void testMaxMessagesConfiguredDynamically() {
DispatcherPolicy dispatcherPolicy = new DispatcherPolicy();
dispatcherPolicy.setReceiveTimeout(0);
dispatcherPolicy.setMaxMessagesPerTask(1);
MessageChannel channel = new QueueChannel(5, dispatcherPolicy);
DefaultPollingDispatcher dispatcher = new DefaultPollingDispatcher(channel);
Collection<Message<?>> results = dispatcher.poll();
assertTrue(results.isEmpty());
channel.send(new StringMessage("test1"), 0);
channel.send(new StringMessage("test2"), 0);
channel.send(new StringMessage("test3"), 0);
results = dispatcher.poll();
assertEquals(1, results.size());
assertEquals("test1", results.iterator().next().getPayload());
dispatcherPolicy.setMaxMessagesPerTask(5);
results = dispatcher.poll();
assertEquals(2, results.size());
Iterator<Message<?>> iter = results.iterator();
assertEquals("test2", iter.next().getPayload());
assertEquals("test3", iter.next().getPayload());
}
}

View File

@@ -0,0 +1,167 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.dispatcher;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.message.Message;
import org.springframework.integration.message.Source;
import org.springframework.integration.message.StringMessage;
import org.springframework.integration.message.Target;
/**
* @author Mark Fisher
*/
public class DirectChannelTests {
private static final String HANDLER_THREAD = "handler-thread";
@Test
public void testSend() {
DirectChannel channel = new DirectChannel();
channel.subscribe(new ThreadNameSettingTestTarget());
StringMessage message = new StringMessage("test");
assertTrue(channel.send(message));
String handlerThreadName = message.getHeader().getProperty(HANDLER_THREAD);
assertEquals(Thread.currentThread().getName(), handlerThreadName);
}
@Test
public void testSendInSeparateThread() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
final DirectChannel channel = new DirectChannel();
channel.subscribe(new ThreadNameSettingTestTarget(latch));
final StringMessage message = new StringMessage("test");
new Thread(new Runnable() {
public void run() {
channel.send(message);
}
}, "test-thread").start();
latch.await(1000, TimeUnit.MILLISECONDS);
String handlerThreadName = message.getHeader().getProperty(HANDLER_THREAD);
assertEquals("test-thread", handlerThreadName);
}
@Test
public void testReceive() {
DirectChannel channel = new DirectChannel(new Source<String>() {
public Message<String> receive() {
return new StringMessage("foo");
}
});
Message<?> message = channel.receive();
assertNotNull(message);
assertNotNull(message.getPayload());
assertEquals(String.class, message.getPayload().getClass());
assertEquals("foo", message.getPayload());
}
@Test
public void testReceiveWithMessageResult() {
DirectChannel channel = new DirectChannel(new MessageReturningTestSource("foo"));
Message<?> message = channel.receive();
assertNotNull(message);
assertNotNull(message.getPayload());
assertEquals(String.class, message.getPayload().getClass());
assertEquals("foo", message.getPayload());
String handlerThreadName = message.getHeader().getProperty(HANDLER_THREAD);
assertEquals(Thread.currentThread().getName(), handlerThreadName);
}
@Test
public void testReceiveInSeparateThread() throws InterruptedException {
final DirectChannel channel = new DirectChannel(new MessageReturningTestSource("foo"));
final SynchronousQueue<Message<?>> messageHolder = new SynchronousQueue<Message<?>>();
new Thread(new Runnable() {
public void run() {
Message<?> message = channel.receive();
assertNotNull(message);
try {
messageHolder.put(message);
}
catch (InterruptedException e) {
// will fail after timeout below
}
}
}, "test-thread").start();
Message<?> message = messageHolder.poll(1000, TimeUnit.MILLISECONDS);
assertNotNull(message);
assertNotNull(message.getPayload());
assertEquals(String.class, message.getPayload().getClass());
assertEquals("foo", message.getPayload());
String handlerThreadName = message.getHeader().getProperty(HANDLER_THREAD);
assertEquals("test-thread", handlerThreadName);
}
@Test
public void testReceiveWithNoSource() {
DirectChannel channel = new DirectChannel();
assertNull(channel.receive());
}
private static class ThreadNameSettingTestTarget implements Target {
private final CountDownLatch latch;
ThreadNameSettingTestTarget() {
this(null);
}
ThreadNameSettingTestTarget(CountDownLatch latch) {
this.latch = latch;
}
public boolean send(Message<?> message) {
message.getHeader().setProperty(HANDLER_THREAD, Thread.currentThread().getName());
if (this.latch != null) {
this.latch.countDown();
}
return true;
}
}
private static class MessageReturningTestSource implements Source<String> {
private final String messageText;
MessageReturningTestSource(String messageText) {
this.messageText = messageText;
}
public StringMessage receive() {
StringMessage message = new StringMessage(messageText);
message.getHeader().setProperty(HANDLER_THREAD, Thread.currentThread().getName());
return message;
}
}
}

View File

@@ -0,0 +1,85 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.dispatcher;
import static org.junit.Assert.assertEquals;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import org.springframework.integration.channel.DispatcherPolicy;
import org.springframework.integration.endpoint.HandlerEndpoint;
import org.springframework.integration.handler.MessageHandler;
import org.springframework.integration.handler.TestHandlers;
import org.springframework.integration.message.StringMessage;
import org.springframework.integration.message.Target;
/**
* @author Mark Fisher
*/
public class SimpleDispatcherTests {
@Test
public void testSingleMessage() throws InterruptedException {
SimpleDispatcher dispatcher = new SimpleDispatcher(new DispatcherPolicy());
final CountDownLatch latch = new CountDownLatch(1);
dispatcher.subscribe(createEndpoint(TestHandlers.countDownHandler(latch)));
dispatcher.dispatch(new StringMessage("test"));
latch.await(500, TimeUnit.MILLISECONDS);
assertEquals(0, latch.getCount());
}
@Test
public void testPointToPoint() throws InterruptedException {
SimpleDispatcher dispatcher = new SimpleDispatcher(new DispatcherPolicy(false));
final CountDownLatch latch = new CountDownLatch(1);
final AtomicInteger counter1 = new AtomicInteger();
final AtomicInteger counter2 = new AtomicInteger();
dispatcher.subscribe(createEndpoint(TestHandlers.countingCountDownHandler(counter1, latch)));
dispatcher.subscribe(createEndpoint(TestHandlers.countingCountDownHandler(counter2, latch)));
dispatcher.dispatch(new StringMessage("test"));
latch.await(500, TimeUnit.MILLISECONDS);
assertEquals(0, latch.getCount());
assertEquals("only 1 handler should have received the message", 1, counter1.get() + counter2.get());
}
@Test
public void testPublishSubscribe() throws InterruptedException {
SimpleDispatcher dispatcher = new SimpleDispatcher(new DispatcherPolicy(true));
final CountDownLatch latch = new CountDownLatch(2);
final AtomicInteger counter1 = new AtomicInteger();
final AtomicInteger counter2 = new AtomicInteger();
dispatcher.subscribe(createEndpoint(TestHandlers.countingCountDownHandler(counter1, latch)));
dispatcher.subscribe(createEndpoint(TestHandlers.countingCountDownHandler(counter2, latch)));
dispatcher.dispatch(new StringMessage("test"));
latch.await(500, TimeUnit.MILLISECONDS);
assertEquals(0, latch.getCount());
assertEquals(1, counter1.get());
assertEquals(1, counter2.get());
}
private static Target createEndpoint(MessageHandler handler) {
HandlerEndpoint endpoint = new HandlerEndpoint(handler);
endpoint.start();
return endpoint;
}
}

View File

@@ -0,0 +1,562 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.endpoint;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import org.springframework.integration.channel.ChannelRegistry;
import org.springframework.integration.channel.DefaultChannelRegistry;
import org.springframework.integration.channel.MessageChannel;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.handler.MessageHandler;
import org.springframework.integration.handler.MessageHandlerNotRunningException;
import org.springframework.integration.handler.TestHandlers;
import org.springframework.integration.message.Message;
import org.springframework.integration.message.MessageDeliveryException;
import org.springframework.integration.message.StringMessage;
import org.springframework.integration.message.selector.MessageSelector;
import org.springframework.integration.util.ErrorHandler;
/**
* @author Mark Fisher
*/
public class HandlerEndpointTests {
@Test
public void testDefaultReplyChannel() throws Exception {
MessageChannel replyChannel = new QueueChannel();
ChannelRegistry channelRegistry = new DefaultChannelRegistry();
channelRegistry.registerChannel("replyChannel", replyChannel);
MessageHandler handler = new MessageHandler() {
public Message<String> handle(Message<?> message) {
return new StringMessage("123", "hello " + message.getPayload());
}
};
HandlerEndpoint endpoint = new HandlerEndpoint(handler);
endpoint.setChannelRegistry(channelRegistry);
endpoint.setOutputChannelName("replyChannel");
endpoint.start();
endpoint.send(new StringMessage(1, "test"));
endpoint.stop();
Message<?> reply = replyChannel.receive(50);
assertNotNull(reply);
assertEquals("hello test", reply.getPayload());
}
@Test
public void testExplicitReplyChannel() throws Exception {
final MessageChannel replyChannel = new QueueChannel();
MessageHandler handler = new MessageHandler() {
public Message<?> handle(Message<?> message) {
return new StringMessage("123", "hello " + message.getPayload());
}
};
HandlerEndpoint endpoint = new HandlerEndpoint(handler);
endpoint.start();
StringMessage testMessage = new StringMessage(1, "test");
testMessage.getHeader().setReturnAddress(replyChannel);
endpoint.send(testMessage);
endpoint.stop();
Message<?> reply = replyChannel.receive(50);
assertNotNull(reply);
assertEquals("hello test", reply.getPayload());
}
@Test
public void testExplicitReplyChannelName() throws Exception {
final MessageChannel replyChannel = new QueueChannel();
ChannelRegistry channelRegistry = new DefaultChannelRegistry();
channelRegistry.registerChannel("replyChannel", replyChannel);
MessageHandler handler = new MessageHandler() {
public Message<?> handle(Message<?> message) {
return new StringMessage("123", "hello " + message.getPayload());
}
};
HandlerEndpoint endpoint = new HandlerEndpoint(handler);
endpoint.setChannelRegistry(channelRegistry);
endpoint.start();
StringMessage testMessage = new StringMessage(1, "test");
testMessage.getHeader().setReturnAddress("replyChannel");
endpoint.send(testMessage);
endpoint.stop();
Message<?> reply = replyChannel.receive(50);
assertNotNull(reply);
assertEquals("hello test", reply.getPayload());
}
@Test
public void testDynamicReplyChannel() throws Exception {
final MessageChannel replyChannel1 = new QueueChannel();
final MessageChannel replyChannel2 = new QueueChannel();
ChannelRegistry channelRegistry = new DefaultChannelRegistry();
channelRegistry.registerChannel("replyChannel2", replyChannel2);
MessageHandler handler = new MessageHandler() {
public Message<?> handle(Message<?> message) {
return new StringMessage("123", "hello " + message.getPayload());
}
};
HandlerEndpoint endpoint = new HandlerEndpoint(handler);
endpoint.setChannelRegistry(channelRegistry);
endpoint.start();
StringMessage testMessage = new StringMessage("test");
testMessage.getHeader().setReturnAddress(replyChannel1);
endpoint.send(testMessage);
Message<?> reply1 = replyChannel1.receive(50);
assertNotNull(reply1);
assertEquals("hello test", reply1.getPayload());
Message<?> reply2 = replyChannel2.receive(0);
assertNull(reply2);
testMessage.getHeader().setReturnAddress("replyChannel2");
endpoint.send(testMessage);
reply1 = replyChannel1.receive(0);
assertNull(reply1);
reply2 = replyChannel2.receive(0);
assertNotNull(reply2);
assertEquals("hello test", reply2.getPayload());
endpoint.stop();
}
@Test
public void testCustomErrorHandler() throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(2);
HandlerEndpoint endpoint = new HandlerEndpoint(TestHandlers.rejectingCountDownHandler(latch));
endpoint.setConcurrencyPolicy(new ConcurrencyPolicy(1, 1));
endpoint.setErrorHandler(new ErrorHandler() {
public void handle(Throwable t) {
latch.countDown();
}
});
endpoint.start();
endpoint.send(new StringMessage("test"));
latch.await(500, TimeUnit.MILLISECONDS);
assertEquals("both handler and errorHandler should have been invoked", 0, latch.getCount());
}
@Test
public void testConcurrentHandlerWithDefaultReplyChannel() throws InterruptedException {
MessageChannel replyChannel = new QueueChannel();
ChannelRegistry channelRegistry = new DefaultChannelRegistry();
channelRegistry.registerChannel("replyChannel", replyChannel);
final CountDownLatch latch = new CountDownLatch(1);
MessageHandler handler = new MessageHandler() {
public Message<String> handle(Message<?> message) {
latch.countDown();
return new StringMessage("123", "hello " + message.getPayload());
}
};
HandlerEndpoint endpoint = new HandlerEndpoint(handler);
endpoint.setConcurrencyPolicy(new ConcurrencyPolicy(1, 1));
endpoint.setChannelRegistry(channelRegistry);
endpoint.setOutputChannelName("replyChannel");
endpoint.start();
endpoint.send(new StringMessage(1, "test"));
latch.await(500, TimeUnit.MILLISECONDS);
endpoint.stop();
assertEquals("handler should have been invoked within allotted time", 0, latch.getCount());
Message<?> reply = replyChannel.receive(100);
assertNotNull(reply);
assertEquals("hello test", reply.getPayload());
}
@Test
public void testHandlerReturnsNull() throws InterruptedException {
MessageChannel replyChannel = new QueueChannel();
ChannelRegistry channelRegistry = new DefaultChannelRegistry();
channelRegistry.registerChannel("replyChannel", replyChannel);
final CountDownLatch latch = new CountDownLatch(1);
MessageHandler handler = new MessageHandler() {
public Message<String> handle(Message<?> message) {
latch.countDown();
return null;
}
};
HandlerEndpoint endpoint = new HandlerEndpoint(handler);
endpoint.setChannelRegistry(channelRegistry);
endpoint.setOutputChannelName("replyChannel");
endpoint.start();
endpoint.send(new StringMessage(1, "test"));
endpoint.stop();
latch.await(500, TimeUnit.MILLISECONDS);
assertEquals("handler should have been invoked within allotted time", 0, latch.getCount());
Message<?> reply = replyChannel.receive(0);
assertNull(reply);
}
@Test
public void testConcurrentHandlerReturnsNull() throws InterruptedException {
MessageChannel replyChannel = new QueueChannel();
ChannelRegistry channelRegistry = new DefaultChannelRegistry();
channelRegistry.registerChannel("replyChannel", replyChannel);
final CountDownLatch latch = new CountDownLatch(1);
MessageHandler handler = new MessageHandler() {
public Message<String> handle(Message<?> message) {
latch.countDown();
return null;
}
};
HandlerEndpoint endpoint = new HandlerEndpoint(handler);
endpoint.setConcurrencyPolicy(new ConcurrencyPolicy(1, 1));
endpoint.setChannelRegistry(channelRegistry);
endpoint.setOutputChannelName("replyChannel");
endpoint.start();
endpoint.send(new StringMessage(1, "test"));
latch.await(500, TimeUnit.MILLISECONDS);
endpoint.stop();
assertEquals("handler should have been invoked within allotted time", 0, latch.getCount());
Message<?> reply = replyChannel.receive(0);
assertNull(reply);
}
@Test
public void testConcurrentHandlerWithExplicitReplyChannel() throws InterruptedException {
MessageChannel replyChannel = new QueueChannel();
ChannelRegistry channelRegistry = new DefaultChannelRegistry();
channelRegistry.registerChannel("replyChannel", replyChannel);
final CountDownLatch latch = new CountDownLatch(1);
MessageHandler handler = new MessageHandler() {
public Message<String> handle(Message<?> message) {
latch.countDown();
return new StringMessage("123", "hello " + message.getPayload());
}
};
HandlerEndpoint endpoint = new HandlerEndpoint(handler);
endpoint.setConcurrencyPolicy(new ConcurrencyPolicy(1, 1));
endpoint.setChannelRegistry(channelRegistry);
endpoint.start();
StringMessage message = new StringMessage(1, "test");
message.getHeader().setReturnAddress("replyChannel");
endpoint.send(message);
latch.await(500, TimeUnit.MILLISECONDS);
assertEquals("handler should have been invoked within allotted time", 0, latch.getCount());
Message<?> reply = replyChannel.receive(100);
endpoint.stop();
assertNotNull(reply);
assertEquals("hello test", reply.getPayload());
}
@Test
public void testGeneratedConcurrentHandlerWithDefaultReplyChannel() throws InterruptedException {
MessageChannel replyChannel = new QueueChannel();
ChannelRegistry channelRegistry = new DefaultChannelRegistry();
channelRegistry.registerChannel("replyChannel", replyChannel);
final CountDownLatch latch = new CountDownLatch(1);
MessageHandler handler = new MessageHandler() {
public Message<String> handle(Message<?> message) {
latch.countDown();
return new StringMessage("123", "hello " + message.getPayload());
}
};
HandlerEndpoint endpoint = new HandlerEndpoint(handler);
endpoint.setChannelRegistry(channelRegistry);
endpoint.setConcurrencyPolicy(new ConcurrencyPolicy(3, 14));
endpoint.setOutputChannelName("replyChannel");
endpoint.start();
endpoint.send(new StringMessage(1, "test"));
latch.await(500, TimeUnit.MILLISECONDS);
endpoint.stop();
assertEquals("handler should have been invoked within allotted time", 0, latch.getCount());
Message<?> reply = replyChannel.receive(100);
assertNotNull(reply);
assertEquals("hello test", reply.getPayload());
}
@Test
public void testGeneratedConcurrentHandlerWithExplicitReplyChannel() throws InterruptedException {
MessageChannel replyChannel = new QueueChannel();
ChannelRegistry channelRegistry = new DefaultChannelRegistry();
channelRegistry.registerChannel("replyChannel", replyChannel);
final CountDownLatch latch = new CountDownLatch(1);
MessageHandler handler = new MessageHandler() {
public Message<String> handle(Message<?> message) {
latch.countDown();
return new StringMessage("123", "hello " + message.getPayload());
}
};
HandlerEndpoint endpoint = new HandlerEndpoint(handler);
endpoint.setChannelRegistry(channelRegistry);
endpoint.setConcurrencyPolicy(new ConcurrencyPolicy(3, 14));
endpoint.start();
StringMessage message = new StringMessage(1, "test");
message.getHeader().setReturnAddress("replyChannel");
endpoint.send(message);
latch.await(500, TimeUnit.MILLISECONDS);
endpoint.stop();
assertEquals("handler should have been invoked within allotted time", 0, latch.getCount());
Message<?> reply = replyChannel.receive(100);
assertNotNull(reply);
assertEquals("hello test", reply.getPayload());
}
@Test(expected=MessageHandlerNotRunningException.class)
public void testEndpointDoesNotHandleMessagesWhenNotYetStarted() {
HandlerEndpoint endpoint = new HandlerEndpoint(TestHandlers.nullHandler());
endpoint.send(new StringMessage("test"));
}
@Test
public void testEndpointDoesNotHandleMessagesAfterBeingStopped() {
AtomicInteger counter = new AtomicInteger();
HandlerEndpoint endpoint = new HandlerEndpoint(TestHandlers.countingHandler(counter));
boolean exceptionThrown = false;
try {
endpoint.start();
endpoint.send(new StringMessage("test1"));
endpoint.stop();
endpoint.send(new StringMessage("test2"));
}
catch (MessageHandlerNotRunningException e) {
exceptionThrown = true;
}
assertEquals("handler should have been invoked exactly once", 1, counter.get());
assertTrue(exceptionThrown);
}
@Test
public void testEndpointWithSelectorRejecting() {
HandlerEndpoint endpoint = new HandlerEndpoint(TestHandlers.nullHandler());
endpoint.addMessageSelector(new MessageSelector() {
public boolean accept(Message<?> message) {
return false;
}
});
endpoint.start();
assertFalse(endpoint.send(new StringMessage("test")));
}
@Test
public void testEndpointWithSelectorAccepting() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
HandlerEndpoint endpoint = new HandlerEndpoint(TestHandlers.countDownHandler(latch));
endpoint.addMessageSelector(new MessageSelector() {
public boolean accept(Message<?> message) {
return true;
}
});
endpoint.start();
endpoint.send(new StringMessage("test"));
latch.await(100, TimeUnit.MILLISECONDS);
assertEquals("handler should have been invoked", 0, latch.getCount());
endpoint.stop();
}
@Test
public void testEndpointWithMultipleSelectorsAndFirstRejects() {
final AtomicInteger counter = new AtomicInteger();
HandlerEndpoint endpoint = new HandlerEndpoint(TestHandlers.countingHandler(counter));
endpoint.addMessageSelector(new MessageSelector() {
public boolean accept(Message<?> message) {
counter.incrementAndGet();
return false;
}
});
endpoint.addMessageSelector(new MessageSelector() {
public boolean accept(Message<?> message) {
counter.incrementAndGet();
return true;
}
});
endpoint.start();
assertFalse(endpoint.send(new StringMessage("test")));
assertEquals("only the first selector should have been invoked", 1, counter.get());
endpoint.stop();
}
@Test
public void testEndpointWithMultipleSelectorsAndFirstAccepts() {
final AtomicInteger selectorCounter = new AtomicInteger();
AtomicInteger handlerCounter = new AtomicInteger();
HandlerEndpoint endpoint = new HandlerEndpoint(TestHandlers.countingHandler(handlerCounter));
endpoint.addMessageSelector(new MessageSelector() {
public boolean accept(Message<?> message) {
selectorCounter.incrementAndGet();
return true;
}
});
endpoint.addMessageSelector(new MessageSelector() {
public boolean accept(Message<?> message) {
selectorCounter.incrementAndGet();
return false;
}
});
endpoint.start();
assertFalse(endpoint.send(new StringMessage("test")));
assertEquals("both selectors should have been invoked", 2, selectorCounter.get());
assertEquals("the handler should not have been invoked", 0, handlerCounter.get());
endpoint.stop();
}
@Test
public void testEndpointWithMultipleSelectorsAndBothAccept() {
final AtomicInteger counter = new AtomicInteger();
HandlerEndpoint endpoint = new HandlerEndpoint(TestHandlers.countingHandler(counter));
endpoint.addMessageSelector(new MessageSelector() {
public boolean accept(Message<?> message) {
counter.incrementAndGet();
return true;
}
});
endpoint.addMessageSelector(new MessageSelector() {
public boolean accept(Message<?> message) {
counter.incrementAndGet();
return true;
}
});
endpoint.start();
assertTrue(endpoint.send(new StringMessage("test")));
assertEquals("both selectors and handler should have been invoked", 3, counter.get());
endpoint.stop();
}
@Test
public void testDefaultOutputChannelTimeoutSendsToErrorHandler() {
QueueChannel output = new QueueChannel(1);
ChannelRegistry channelRegistry = new DefaultChannelRegistry();
channelRegistry.registerChannel("output", output);
HandlerEndpoint endpoint = new HandlerEndpoint(new MessageHandler() {
public Message<?> handle(Message<?> message) {
return message;
}
});
endpoint.setOutputChannelName("output");
endpoint.setChannelRegistry(channelRegistry);
TestErrorHandler errorHandler = new TestErrorHandler();
endpoint.setErrorHandler(errorHandler);
endpoint.setReplyTimeout(0);
endpoint.start();
endpoint.send(new StringMessage("test1"));
assertNull(errorHandler.getLastError());
endpoint.send(new StringMessage("test2"));
Throwable error = errorHandler.getLastError();
assertNotNull(error);
assertEquals(MessageDeliveryException.class, error.getClass());
assertEquals("test2", ((MessageDeliveryException) error).getFailedMessage().getPayload());
}
@Test
public void testReturnAddressChannelTimeoutSendsToErrorHandler() {
QueueChannel replyChannel = new QueueChannel(1);
HandlerEndpoint endpoint = new HandlerEndpoint(new MessageHandler() {
public Message<?> handle(Message<?> message) {
return message;
}
});
TestErrorHandler errorHandler = new TestErrorHandler();
endpoint.setErrorHandler(errorHandler);
endpoint.setReplyTimeout(0);
endpoint.start();
Message<?> message1 = new StringMessage("test1");
message1.getHeader().setReturnAddress(replyChannel);
endpoint.send(message1);
assertNull(errorHandler.getLastError());
Message<?> message2 = new StringMessage("test2");
message2.getHeader().setReturnAddress(replyChannel);
endpoint.send(message2);
Throwable error = errorHandler.getLastError();
assertNotNull(error);
assertEquals(MessageDeliveryException.class, error.getClass());
assertEquals(message2, ((MessageDeliveryException) error).getFailedMessage());
}
@Test
public void testReturnAddressChannelNameTimeoutSendsToErrorHandler() {
QueueChannel replyChannel = new QueueChannel(1);
ChannelRegistry channelRegistry = new DefaultChannelRegistry();
channelRegistry.registerChannel("replyChannel", replyChannel);
HandlerEndpoint endpoint = new HandlerEndpoint(new MessageHandler() {
public Message<?> handle(Message<?> message) {
return message;
}
});
endpoint.setChannelRegistry(channelRegistry);
TestErrorHandler errorHandler = new TestErrorHandler();
endpoint.setErrorHandler(errorHandler);
endpoint.setReplyTimeout(10);
endpoint.start();
Message<?> message1 = new StringMessage("test1");
message1.getHeader().setReturnAddress("replyChannel");
endpoint.send(message1);
assertNull(errorHandler.getLastError());
Message<?> message2 = new StringMessage("test2");
message2.getHeader().setReturnAddress("replyChannel");
endpoint.send(message2);
Throwable error = errorHandler.getLastError();
assertNotNull(error);
assertEquals(MessageDeliveryException.class, error.getClass());
assertEquals(message2, ((MessageDeliveryException) error).getFailedMessage());
}
@Test
public void testCorrelationId() {
QueueChannel replyChannel = new QueueChannel(1);
HandlerEndpoint endpoint = new HandlerEndpoint(new MessageHandler() {
public Message<?> handle(Message<?> message) {
return message;
}
});
endpoint.start();
Message<?> message = new StringMessage("test");
message.getHeader().setReturnAddress(replyChannel);
endpoint.send(message);
Message<?> reply = replyChannel.receive(500);
assertEquals(message.getId(), reply.getHeader().getCorrelationId());
}
@Test
public void testCorrelationIdSetByHandlerTakesPrecedence() {
QueueChannel replyChannel = new QueueChannel(1);
HandlerEndpoint endpoint = new HandlerEndpoint(new MessageHandler() {
public Message<?> handle(Message<?> message) {
message.getHeader().setCorrelationId("ABC-123");
return message;
}
});
endpoint.start();
Message<?> message = new StringMessage("test");
message.getHeader().setReturnAddress(replyChannel);
endpoint.send(message);
Message<?> reply = replyChannel.receive(500);
Object correlationId = reply.getHeader().getCorrelationId();
assertFalse(message.getId().equals(correlationId));
assertEquals("ABC-123", correlationId);
}
private static class TestErrorHandler implements ErrorHandler {
private volatile Throwable lastError;
public void handle(Throwable t) {
this.lastError = t;
}
Throwable getLastError() {
return this.lastError;
}
}
}

View File

@@ -0,0 +1,104 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.endpoint;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.channel.MessageChannel;
import org.springframework.integration.message.Message;
import org.springframework.integration.message.StringMessage;
/**
* @author Mark Fisher
*/
public class ReturnAddressTests {
@Test
public void testReturnAddressOverrides() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"returnAddressTests.xml", this.getClass());
MessageChannel channel1 = (MessageChannel) context.getBean("channel1WithOverride");
MessageChannel replyChannel = (MessageChannel) context.getBean("replyChannel");
context.start();
StringMessage message = new StringMessage("*");
message.getHeader().setReturnAddress("replyChannel");
channel1.send(message);
Message<?> response = replyChannel.receive(3000);
assertNotNull(response);
assertEquals("**", response.getPayload());
}
@Test
public void testOutputTakesPrecedenceByDefault() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"returnAddressTests.xml", this.getClass());
MessageChannel channel1 = (MessageChannel) context.getBean("channel1");
MessageChannel replyChannel = (MessageChannel) context.getBean("replyChannel");
context.start();
StringMessage message = new StringMessage("*");
message.getHeader().setReturnAddress("replyChannel");
channel1.send(message);
Message<?> response = replyChannel.receive(3000);
assertNotNull(response);
assertEquals("********", response.getPayload());
}
@Test
public void testOutputTakesPrecedenceAndNoReturnAddress() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"returnAddressTests.xml", this.getClass());
MessageChannel channel4 = (MessageChannel) context.getBean("channel4");
MessageChannel replyChannel = (MessageChannel) context.getBean("replyChannel");
context.start();
StringMessage message = new StringMessage("*");
channel4.send(message);
Message<?> response = replyChannel.receive(3000);
assertNotNull(response);
assertEquals("**", response.getPayload());
}
@Test
public void testReturnAddressFallbackButNotAvailable() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"returnAddressTests.xml", this.getClass());
MessageChannel channel3 = (MessageChannel) context.getBean("channel3");
MessageChannel errorChannel = (MessageChannel) context.getBean("errorChannel");
context.start();
StringMessage message = new StringMessage("*");
channel3.send(message);
Message<?> errorMessage = errorChannel.receive(3000);
assertNotNull(errorMessage.getPayload());
}
@Test
public void testOutputFallbackButNotAvailable() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"returnAddressTests.xml", this.getClass());
MessageChannel channel3 = (MessageChannel) context.getBean("channel3WithOverride");
MessageChannel errorChannel = (MessageChannel) context.getBean("errorChannel");
context.start();
StringMessage message = new StringMessage("*");
channel3.send(message);
Message<?> errorMessage = errorChannel.receive(3000);
assertNotNull(errorMessage.getPayload());
}
}

View File

@@ -0,0 +1,457 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.endpoint;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.aopalliance.aop.Advice;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.junit.Test;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.message.GenericMessage;
import org.springframework.integration.message.Message;
import org.springframework.integration.message.Source;
import org.springframework.integration.scheduling.PollingSchedule;
/**
* @author Mark Fisher
*/
public class SourceEndpointTests {
@Test
public void testPolledSourceSendsToChannel() {
TestSource source = new TestSource("testing", 1);
QueueChannel channel = new QueueChannel();
PollingSchedule schedule = new PollingSchedule(100);
SourceEndpoint endpoint = new SourceEndpoint(source, channel, schedule);
endpoint.run();
Message<?> message = channel.receive(1000);
assertNotNull("message should not be null", message);
assertEquals("testing.1", message.getPayload());
}
@Test
public void testSendTimeout() {
TestSource source = new TestSource("testing", 1);
QueueChannel channel = new QueueChannel(1);
PollingSchedule schedule = new PollingSchedule(1000);
schedule.setInitialDelay(10000);
SourceEndpoint endpoint = new SourceEndpoint(source, channel, schedule);
endpoint.setSendTimeout(10);
endpoint.run();
Message<?> message1 = channel.receive(1000);
assertNotNull("message should not be null", message1);
assertEquals("testing.1", message1.getPayload());
Message<?> message2 = channel.receive(0);
assertNull("second message should be null", message2);
source.resetCounter();
endpoint.run();
Message<?> message3 = channel.receive(100);
assertNotNull("third message should not be null", message3);
assertEquals("testing.1", message3.getPayload());
}
@Test
public void testMultipleMessagesPerPoll() {
TestSource source = new TestSource("testing", 3);
QueueChannel channel = new QueueChannel();
PollingSchedule schedule = new PollingSchedule(1000);
schedule.setInitialDelay(10000);
SourceEndpoint endpoint = new SourceEndpoint(source, channel, schedule);
endpoint.setMaxMessagesPerTask(5);
endpoint.run();
Message<?> message1 = channel.receive(0);
assertNotNull("message should not be null", message1);
assertEquals("testing.1", message1.getPayload());
Message<?> message2 = channel.receive(0);
assertNotNull("message should not be null", message2);
assertEquals("testing.2", message2.getPayload());
Message<?> message3 = channel.receive(0);
assertNotNull("message should not be null", message3);
assertEquals("testing.3", message3.getPayload());
Message<?> message4 = channel.receive(0);
assertNull("message should be null", message4);
}
@Test
public void testTaskAdviceChain() {
TestSource source = new TestSource("testing", 3);
QueueChannel channel = new QueueChannel();
PollingSchedule schedule = new PollingSchedule(1000);
schedule.setInitialDelay(10000);
SourceEndpoint endpoint = new SourceEndpoint(source, channel, schedule);
final StringBuffer buffer = new StringBuffer();
List<Advice> taskAdviceChain = new ArrayList<Advice>();
taskAdviceChain.add(new MethodBeforeAdvice() {
public void before(Method method, Object[] args, Object target) throws Throwable {
buffer.append(1);
}
});
taskAdviceChain.add(new MethodInterceptor() {
public Object invoke(MethodInvocation invocation) throws Throwable {
buffer.append(2);
Object retval = invocation.proceed();
buffer.append(4);
return retval;
}
});
taskAdviceChain.add(new MethodBeforeAdvice() {
public void before(Method method, Object[] args, Object target) throws Throwable {
buffer.append(3);
}
});
endpoint.setTaskAdviceChain(taskAdviceChain);
endpoint.afterPropertiesSet();
endpoint.setMaxMessagesPerTask(5);
endpoint.run();
assertEquals("1234", buffer.toString());
}
@Test
public void testDispatchAdviceChain() {
TestSource source = new TestSource("testing", 2);
QueueChannel channel = new QueueChannel();
PollingSchedule schedule = new PollingSchedule(1000);
schedule.setInitialDelay(10000);
SourceEndpoint endpoint = new SourceEndpoint(source, channel, schedule);
final StringBuffer buffer = new StringBuffer();
List<Advice> dispatchAdviceChain = new ArrayList<Advice>();
dispatchAdviceChain.add(new MethodBeforeAdvice() {
public void before(Method method, Object[] args, Object target) throws Throwable {
buffer.append("a");
}
});
dispatchAdviceChain.add(new MethodInterceptor() {
public Object invoke(MethodInvocation invocation) throws Throwable {
buffer.append("b");
Object retval = invocation.proceed();
buffer.append("d");
return retval;
}
});
dispatchAdviceChain.add(new MethodBeforeAdvice() {
public void before(Method method, Object[] args, Object target) throws Throwable {
buffer.append("c");
}
});
endpoint.setDispatchAdviceChain(dispatchAdviceChain);
endpoint.afterPropertiesSet();
endpoint.setMaxMessagesPerTask(5);
endpoint.run();
assertEquals("abcdabcd", buffer.toString());
}
@Test
public void testTaskAndDispatchAdviceChains() {
TestSource source = new TestSource("testing", 3);
QueueChannel channel = new QueueChannel();
PollingSchedule schedule = new PollingSchedule(1000);
schedule.setInitialDelay(10000);
SourceEndpoint endpoint = new SourceEndpoint(source, channel, schedule);
List<Advice> dispatchAdviceChain = new ArrayList<Advice>();
List<Advice> taskAdviceChain = new ArrayList<Advice>();
final StringBuffer buffer = new StringBuffer();
dispatchAdviceChain.add(new MethodBeforeAdvice() {
public void before(Method method, Object[] args, Object target) throws Throwable {
buffer.append("a");
}
});
dispatchAdviceChain.add(new MethodInterceptor() {
public Object invoke(MethodInvocation invocation) throws Throwable {
buffer.append("b");
Object retval = invocation.proceed();
buffer.append("c");
return retval;
}
});
taskAdviceChain.add(new MethodInterceptor() {
public Object invoke(MethodInvocation invocation) throws Throwable {
buffer.append(1);
Object retval = invocation.proceed();
buffer.append(3);
return retval;
}
});
taskAdviceChain.add(new MethodBeforeAdvice() {
public void before(Method method, Object[] args, Object target) throws Throwable {
buffer.append(2);
}
});
endpoint.setTaskAdviceChain(taskAdviceChain);
endpoint.setDispatchAdviceChain(dispatchAdviceChain);
endpoint.afterPropertiesSet();
endpoint.setMaxMessagesPerTask(5);
endpoint.run();
assertEquals("12abcabcabc3", buffer.toString());
}
@Test
public void testRefreshTaskAtRuntime() {
TestSource source = new TestSource("testing", 3);
QueueChannel channel = new QueueChannel();
PollingSchedule schedule = new PollingSchedule(1000);
schedule.setInitialDelay(10000);
SourceEndpoint endpoint = new SourceEndpoint(source, channel, schedule);
List<Advice> dispatchAdviceChain = new ArrayList<Advice>();
List<Advice> taskAdviceChain = new ArrayList<Advice>();
final StringBuffer buffer = new StringBuffer();
dispatchAdviceChain.add(new MethodBeforeAdvice() {
public void before(Method method, Object[] args, Object target) throws Throwable {
buffer.append("a");
}
});
dispatchAdviceChain.add(new MethodInterceptor() {
public Object invoke(MethodInvocation invocation) throws Throwable {
buffer.append("b");
Object retval = invocation.proceed();
buffer.append("c");
return retval;
}
});
taskAdviceChain.add(new MethodInterceptor() {
public Object invoke(MethodInvocation invocation) throws Throwable {
buffer.append(1);
Object retval = invocation.proceed();
buffer.append(3);
return retval;
}
});
taskAdviceChain.add(new MethodBeforeAdvice() {
public void before(Method method, Object[] args, Object target) throws Throwable {
buffer.append(2);
}
});
endpoint.setDispatchAdviceChain(dispatchAdviceChain);
endpoint.afterPropertiesSet();
endpoint.setMaxMessagesPerTask(5);
endpoint.run();
assertEquals("abcabcabc", buffer.toString());
buffer.delete(0, buffer.length());
source.resetCounter();
endpoint.setTaskAdviceChain(taskAdviceChain);
endpoint.refreshTask();
endpoint.run();
assertEquals("12abcabcabc3", buffer.toString());
buffer.delete(0, buffer.length());
source.resetCounter();
endpoint.setDispatchAdviceChain(null);
endpoint.refreshTask();
endpoint.run();
assertEquals("123", buffer.toString());
buffer.delete(0, buffer.length());
source.resetCounter();
endpoint.setTaskAdviceChain(null);
endpoint.setDispatchAdviceChain(dispatchAdviceChain);
endpoint.refreshTask();
endpoint.run();
assertEquals("abcabcabc", buffer.toString());
}
@Test
public void testInitializeTaskDoesNotRefreshWithDispatchAdviceOnly() {
TestSource source = new TestSource("testing", 3);
QueueChannel channel = new QueueChannel();
PollingSchedule schedule = new PollingSchedule(1000);
schedule.setInitialDelay(10000);
SourceEndpoint endpoint = new SourceEndpoint(source, channel, schedule);
List<Advice> dispatchAdviceChain = new ArrayList<Advice>();
List<Advice> taskAdviceChain = new ArrayList<Advice>();
final StringBuffer buffer = new StringBuffer();
dispatchAdviceChain.add(new MethodBeforeAdvice() {
public void before(Method method, Object[] args, Object target) throws Throwable {
buffer.append("a");
}
});
taskAdviceChain.add(new MethodBeforeAdvice() {
public void before(Method method, Object[] args, Object target) throws Throwable {
buffer.append(1);
}
});
endpoint.setDispatchAdviceChain(dispatchAdviceChain);
endpoint.afterPropertiesSet();
endpoint.setMaxMessagesPerTask(5);
endpoint.run();
assertEquals("aaa", buffer.toString());
buffer.delete(0, buffer.length());
source.resetCounter();
endpoint.setTaskAdviceChain(taskAdviceChain);
endpoint.initializeTask();
endpoint.run();
assertEquals("aaa", buffer.toString());
buffer.delete(0, buffer.length());
source.resetCounter();
endpoint.setDispatchAdviceChain(null);
endpoint.initializeTask();
endpoint.run();
assertEquals("aaa", buffer.toString());
}
@Test
public void testInitializeTaskDoesNotRefreshWithTaskAdviceOnly() {
TestSource source = new TestSource("testing", 3);
QueueChannel channel = new QueueChannel();
PollingSchedule schedule = new PollingSchedule(1000);
schedule.setInitialDelay(10000);
SourceEndpoint endpoint = new SourceEndpoint(source, channel, schedule);
List<Advice> dispatchAdviceChain = new ArrayList<Advice>();
List<Advice> taskAdviceChain = new ArrayList<Advice>();
final StringBuffer buffer = new StringBuffer();
dispatchAdviceChain.add(new MethodBeforeAdvice() {
public void before(Method method, Object[] args, Object target) throws Throwable {
buffer.append("a");
}
});
taskAdviceChain.add(new MethodBeforeAdvice() {
public void before(Method method, Object[] args, Object target) throws Throwable {
buffer.append(1);
}
});
endpoint.setTaskAdviceChain(taskAdviceChain);
endpoint.afterPropertiesSet();
endpoint.setMaxMessagesPerTask(5);
endpoint.run();
assertEquals("1", buffer.toString());
buffer.delete(0, buffer.length());
source.resetCounter();
endpoint.setDispatchAdviceChain(dispatchAdviceChain);
endpoint.initializeTask();
endpoint.run();
assertEquals("1", buffer.toString());
buffer.delete(0, buffer.length());
source.resetCounter();
endpoint.setTaskAdviceChain(null);
endpoint.initializeTask();
endpoint.run();
assertEquals("1", buffer.toString());
}
@Test
public void testInitializeTaskDoesNotRefreshWithTaskAndDispatchAdvice() {
TestSource source = new TestSource("testing", 3);
QueueChannel channel = new QueueChannel();
PollingSchedule schedule = new PollingSchedule(1000);
schedule.setInitialDelay(10000);
SourceEndpoint endpoint = new SourceEndpoint(source, channel, schedule);
List<Advice> dispatchAdviceChain = new ArrayList<Advice>();
List<Advice> taskAdviceChain = new ArrayList<Advice>();
final StringBuffer buffer = new StringBuffer();
dispatchAdviceChain.add(new MethodBeforeAdvice() {
public void before(Method method, Object[] args, Object target) throws Throwable {
buffer.append("a");
}
});
taskAdviceChain.add(new MethodBeforeAdvice() {
public void before(Method method, Object[] args, Object target) throws Throwable {
buffer.append(1);
}
});
endpoint.setTaskAdviceChain(taskAdviceChain);
endpoint.setDispatchAdviceChain(dispatchAdviceChain);
endpoint.afterPropertiesSet();
endpoint.setMaxMessagesPerTask(5);
endpoint.run();
assertEquals("1aaa", buffer.toString());
buffer.delete(0, buffer.length());
source.resetCounter();
endpoint.setDispatchAdviceChain(null);
endpoint.initializeTask();
endpoint.run();
assertEquals("1aaa", buffer.toString());
buffer.delete(0, buffer.length());
source.resetCounter();
endpoint.setTaskAdviceChain(null);
endpoint.initializeTask();
endpoint.run();
assertEquals("1aaa", buffer.toString());
}
@Test
public void testInitializeTaskDoesNotRefreshWithNoAdvice() {
TestSource source = new TestSource("testing", 3);
QueueChannel channel = new QueueChannel();
PollingSchedule schedule = new PollingSchedule(1000);
schedule.setInitialDelay(10000);
SourceEndpoint endpoint = new SourceEndpoint(source, channel, schedule);
List<Advice> dispatchAdviceChain = new ArrayList<Advice>();
List<Advice> taskAdviceChain = new ArrayList<Advice>();
final StringBuffer buffer = new StringBuffer();
dispatchAdviceChain.add(new MethodBeforeAdvice() {
public void before(Method method, Object[] args, Object target) throws Throwable {
buffer.append("a");
}
});
taskAdviceChain.add(new MethodBeforeAdvice() {
public void before(Method method, Object[] args, Object target) throws Throwable {
buffer.append(1);
}
});
endpoint.afterPropertiesSet();
endpoint.setMaxMessagesPerTask(5);
endpoint.run();
assertEquals("", buffer.toString());
buffer.delete(0, buffer.length());
source.resetCounter();
endpoint.setDispatchAdviceChain(dispatchAdviceChain);
endpoint.initializeTask();
endpoint.run();
assertEquals("", buffer.toString());
buffer.delete(0, buffer.length());
source.resetCounter();
endpoint.setTaskAdviceChain(taskAdviceChain);
endpoint.initializeTask();
endpoint.run();
assertEquals("", buffer.toString());
}
private static class TestSource implements Source<String> {
private String message;
private int limit;
private AtomicInteger count = new AtomicInteger();
public TestSource(String message, int limit) {
this.message = message;
this.limit = limit;
}
public void resetCounter() {
this.count.set(0);
}
public Message<String> receive() {
if (count.get() >= limit) {
return null;
}
return new GenericMessage<String>(message + "." + count.incrementAndGet());
}
}
}

View File

@@ -0,0 +1,28 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.endpoint;
/**
* @author Mark Fisher
*/
public class TestBean {
public String duplicate(String input) {
return input + input;
}
}

View File

@@ -0,0 +1,26 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.endpoint.annotation;
/**
* @author Mark Fisher
*/
public interface ITestEndpoint {
String sayHello(String name);
}

View File

@@ -0,0 +1,39 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.endpoint.annotation;
import org.springframework.integration.annotation.Handler;
import org.springframework.integration.annotation.MessageEndpoint;
import org.springframework.integration.annotation.Polled;
/**
* @author Mark Fisher
*/
@MessageEndpoint(output="outputChannel")
public class InboundChannelAdapterTestBean {
@Polled(period=100)
public String getName() {
return "world";
}
@Handler
public String sayHello(String name) {
return "hello " + name;
}
}

View File

@@ -0,0 +1,461 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.endpoint.annotation;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.ConfigurationException;
import org.springframework.integration.annotation.Concurrency;
import org.springframework.integration.annotation.DefaultOutput;
import org.springframework.integration.annotation.Handler;
import org.springframework.integration.annotation.MessageEndpoint;
import org.springframework.integration.annotation.Polled;
import org.springframework.integration.annotation.Splitter;
import org.springframework.integration.bus.MessageBus;
import org.springframework.integration.channel.ChannelRegistry;
import org.springframework.integration.channel.ChannelRegistryAware;
import org.springframework.integration.channel.MessageChannel;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.config.MessageEndpointAnnotationPostProcessor;
import org.springframework.integration.endpoint.ConcurrencyPolicy;
import org.springframework.integration.endpoint.HandlerEndpoint;
import org.springframework.integration.message.Message;
import org.springframework.integration.message.StringMessage;
import org.springframework.integration.scheduling.PollingSchedule;
import org.springframework.integration.scheduling.Schedule;
/**
* @author Mark Fisher
*/
public class MessageEndpointAnnotationPostProcessorTests {
@Test
public void testSimpleHandler() throws InterruptedException {
AbstractApplicationContext context = new ClassPathXmlApplicationContext("simpleAnnotatedEndpointTests.xml", this.getClass());
context.start();
MessageChannel inputChannel = (MessageChannel) context.getBean("inputChannel");
MessageChannel outputChannel = (MessageChannel) context.getBean("outputChannel");
inputChannel.send(new StringMessage("world"));
Message<?> message = outputChannel.receive(1000);
assertEquals("hello world", message.getPayload());
context.stop();
}
@Test
public void testSimpleHandlerWithAutoCreatedChannels() throws InterruptedException {
AbstractApplicationContext context = new ClassPathXmlApplicationContext(
"simpleAnnotatedEndpointWithAutoCreateChannelTests.xml", this.getClass());
context.start();
ChannelRegistry channelRegistry = (ChannelRegistry) context.getBean("bus");
MessageChannel inputChannel = channelRegistry.lookupChannel("inputChannel");
MessageChannel outputChannel = channelRegistry.lookupChannel("outputChannel");
inputChannel.send(new StringMessage("world"));
Message<?> message = outputChannel.receive(1000);
assertEquals("hello world", message.getPayload());
context.stop();
}
@Test
public void testMessageParameterHandler() throws InterruptedException {
AbstractApplicationContext context = new ClassPathXmlApplicationContext("messageParameterAnnotatedEndpointTests.xml", this.getClass());
context.start();
MessageChannel inputChannel = (MessageChannel) context.getBean("inputChannel");
MessageChannel outputChannel = (MessageChannel) context.getBean("outputChannel");
inputChannel.send(new StringMessage("world"));
Message<?> message = outputChannel.receive(1000);
assertEquals("hello world", message.getPayload());
context.stop();
}
@Test
public void testTypeConvertingHandler() throws InterruptedException {
AbstractApplicationContext context = new ClassPathXmlApplicationContext("typeConvertingEndpointTests.xml", this.getClass());
context.start();
MessageChannel inputChannel = (MessageChannel) context.getBean("inputChannel");
MessageChannel outputChannel = (MessageChannel) context.getBean("outputChannel");
inputChannel.send(new StringMessage("123"));
Message<?> message = outputChannel.receive(1000);
assertEquals(246, message.getPayload());
context.stop();
}
@Test
public void testPolledAnnotation() throws InterruptedException {
MessageBus messageBus = new MessageBus();
QueueChannel testChannel = new QueueChannel();
messageBus.registerChannel("testChannel", testChannel);
MessageEndpointAnnotationPostProcessor postProcessor =
new MessageEndpointAnnotationPostProcessor(messageBus);
postProcessor.afterPropertiesSet();
PolledAnnotationTestBean testBean = new PolledAnnotationTestBean();
postProcessor.postProcessAfterInitialization(testBean, "testBean");
messageBus.start();
Message<?> message = testChannel.receive(1000);
assertEquals("test", message.getPayload());
messageBus.stop();
}
@Test
public void testDefaultOutputAnnotation() throws InterruptedException {
MessageBus messageBus = new MessageBus();
QueueChannel testChannel = new QueueChannel();
messageBus.registerChannel("testChannel", testChannel);
MessageEndpointAnnotationPostProcessor postProcessor =
new MessageEndpointAnnotationPostProcessor(messageBus);
postProcessor.afterPropertiesSet();
CountDownLatch latch = new CountDownLatch(1);
DefaultOutputAnnotationTestBean testBean = new DefaultOutputAnnotationTestBean(latch);
postProcessor.postProcessAfterInitialization(testBean, "testBean");
messageBus.start();
testChannel.send(new StringMessage("foo"));
latch.await(1000, TimeUnit.MILLISECONDS);
assertEquals(0, latch.getCount());
assertEquals("foo", testBean.getMessageText());
messageBus.stop();
}
@Test
public void testConcurrencyAnnotationWithValues() {
MessageBus messageBus = new MessageBus();
MessageEndpointAnnotationPostProcessor postProcessor =
new MessageEndpointAnnotationPostProcessor(messageBus);
postProcessor.afterPropertiesSet();
ConcurrencyAnnotationTestBean testBean = new ConcurrencyAnnotationTestBean();
postProcessor.postProcessAfterInitialization(testBean, "testBean");
HandlerEndpoint endpoint = (HandlerEndpoint) messageBus.lookupEndpoint("testBean-endpoint");
ConcurrencyPolicy concurrencyPolicy = endpoint.getConcurrencyPolicy();
assertEquals(17, concurrencyPolicy.getCoreSize());
assertEquals(42, concurrencyPolicy.getMaxSize());
assertEquals(11, concurrencyPolicy.getQueueCapacity());
assertEquals(123, concurrencyPolicy.getKeepAliveSeconds());
}
@Test(expected=IllegalArgumentException.class)
public void testPostProcessorWithNullMessageBus() {
new MessageEndpointAnnotationPostProcessor(null);
}
@Test
public void testChannelRegistryAwareBean() {
MessageBus messageBus = new MessageBus();
MessageEndpointAnnotationPostProcessor postProcessor =
new MessageEndpointAnnotationPostProcessor(messageBus);
postProcessor.afterPropertiesSet();
ChannelRegistryAwareTestBean testBean = new ChannelRegistryAwareTestBean();
assertNull(testBean.getChannelRegistry());
postProcessor.postProcessAfterInitialization(testBean, "testBean");
ChannelRegistry channelRegistry = testBean.getChannelRegistry();
assertNotNull(channelRegistry);
assertEquals(messageBus, channelRegistry);
}
@Test
public void testProxiedMessageEndpointAnnotation() {
MessageBus messageBus = new MessageBus();
messageBus.setAutoCreateChannels(true);
MessageEndpointAnnotationPostProcessor postProcessor =
new MessageEndpointAnnotationPostProcessor(messageBus);
postProcessor.afterPropertiesSet();
ProxyFactory proxyFactory = new ProxyFactory(new SimpleAnnotatedEndpoint());
Object proxy = proxyFactory.getProxy();
postProcessor.postProcessAfterInitialization(proxy, "proxy");
messageBus.start();
MessageChannel inputChannel = messageBus.lookupChannel("inputChannel");
MessageChannel outputChannel = messageBus.lookupChannel("outputChannel");
inputChannel.send(new StringMessage("world"));
Message<?> message = outputChannel.receive(1000);
assertEquals("hello world", message.getPayload());
}
@Test
public void testMessageEndpointAnnotationInherited() {
MessageBus messageBus = new MessageBus();
messageBus.setAutoCreateChannels(true);
MessageEndpointAnnotationPostProcessor postProcessor =
new MessageEndpointAnnotationPostProcessor(messageBus);
postProcessor.afterPropertiesSet();
postProcessor.postProcessAfterInitialization(new SimpleAnnotatedEndpointSubclass(), "subclass");
messageBus.start();
MessageChannel inputChannel = messageBus.lookupChannel("inputChannel");
MessageChannel outputChannel = messageBus.lookupChannel("outputChannel");
inputChannel.send(new StringMessage("world"));
Message<?> message = outputChannel.receive(1000);
assertEquals("hello world", message.getPayload());
}
@Test
public void testMessageEndpointAnnotationInheritedWithProxy() {
MessageBus messageBus = new MessageBus();
messageBus.setAutoCreateChannels(true);
MessageEndpointAnnotationPostProcessor postProcessor =
new MessageEndpointAnnotationPostProcessor(messageBus);
postProcessor.afterPropertiesSet();
ProxyFactory proxyFactory = new ProxyFactory(new SimpleAnnotatedEndpointSubclass());
Object proxy = proxyFactory.getProxy();
postProcessor.postProcessAfterInitialization(proxy, "proxy");
messageBus.start();
MessageChannel inputChannel = messageBus.lookupChannel("inputChannel");
MessageChannel outputChannel = messageBus.lookupChannel("outputChannel");
inputChannel.send(new StringMessage("world"));
Message<?> message = outputChannel.receive(1000);
assertEquals("hello world", message.getPayload());
}
@Test
public void testMessageEndpointAnnotationInheritedFromInterface() {
MessageBus messageBus = new MessageBus();
MessageChannel inputChannel = new QueueChannel();
MessageChannel outputChannel = new QueueChannel();
messageBus.registerChannel("inputChannel", inputChannel);
messageBus.registerChannel("outputChannel", outputChannel);
MessageEndpointAnnotationPostProcessor postProcessor =
new MessageEndpointAnnotationPostProcessor(messageBus);
postProcessor.afterPropertiesSet();
postProcessor.postProcessAfterInitialization(new SimpleAnnotatedEndpointImplementation(), "impl");
messageBus.start();
inputChannel.send(new StringMessage("ABC"));
Message<?> message = outputChannel.receive(1000);
assertEquals("test-ABC", message.getPayload());
}
@Test
public void testMessageEndpointAnnotationInheritedFromInterfaceWithAutoCreatedChannels() {
MessageBus messageBus = new MessageBus();
messageBus.setAutoCreateChannels(true);
MessageEndpointAnnotationPostProcessor postProcessor =
new MessageEndpointAnnotationPostProcessor(messageBus);
postProcessor.afterPropertiesSet();
postProcessor.postProcessAfterInitialization(new SimpleAnnotatedEndpointImplementation(), "impl");
messageBus.start();
MessageChannel inputChannel = messageBus.lookupChannel("inputChannel");
MessageChannel outputChannel = messageBus.lookupChannel("outputChannel");
inputChannel.send(new StringMessage("ABC"));
Message<?> message = outputChannel.receive(1000);
assertEquals("test-ABC", message.getPayload());
}
@Test
public void testMessageEndpointAnnotationInheritedFromInterfaceWithProxy() {
MessageBus messageBus = new MessageBus();
MessageChannel inputChannel = new QueueChannel();
MessageChannel outputChannel = new QueueChannel();
messageBus.registerChannel("inputChannel", inputChannel);
messageBus.registerChannel("outputChannel", outputChannel);
MessageEndpointAnnotationPostProcessor postProcessor =
new MessageEndpointAnnotationPostProcessor(messageBus);
postProcessor.afterPropertiesSet();
ProxyFactory proxyFactory = new ProxyFactory(new SimpleAnnotatedEndpointImplementation());
Object proxy = proxyFactory.getProxy();
postProcessor.postProcessAfterInitialization(proxy, "proxy");
messageBus.start();
inputChannel.send(new StringMessage("ABC"));
Message<?> message = outputChannel.receive(1000);
assertEquals("test-ABC", message.getPayload());
}
@Test
public void testSplitterAnnotation() throws InterruptedException {
MessageBus messageBus = new MessageBus();
QueueChannel input = new QueueChannel();
QueueChannel output = new QueueChannel();
messageBus.registerChannel("input", input);
messageBus.registerChannel("output", output);
MessageEndpointAnnotationPostProcessor postProcessor =
new MessageEndpointAnnotationPostProcessor(messageBus);
postProcessor.afterPropertiesSet();
SplitterAnnotationTestEndpoint endpoint = new SplitterAnnotationTestEndpoint();
postProcessor.postProcessAfterInitialization(endpoint, "endpoint");
messageBus.start();
input.send(new StringMessage("this.is.a.test"));
Message<?> message1 = output.receive(500);
assertNotNull(message1);
assertEquals("this", message1.getPayload());
Message<?> message2 = output.receive(500);
assertNotNull(message2);
assertEquals("is", message2.getPayload());
Message<?> message3 = output.receive(500);
assertNotNull(message3);
assertEquals("a", message3.getPayload());
Message<?> message4 = output.receive(500);
assertNotNull(message4);
assertEquals("test", message4.getPayload());
assertNull(output.receive(500));
}
@Test(expected=ConfigurationException.class)
public void testEndpointWithNoHandlerMethod() {
MessageBus messageBus = new MessageBus();
QueueChannel testChannel = new QueueChannel();
messageBus.registerChannel("testChannel", testChannel);
MessageEndpointAnnotationPostProcessor postProcessor =
new MessageEndpointAnnotationPostProcessor(messageBus);
postProcessor.afterPropertiesSet();
AnnotatedEndpointWithNoHandlerMethod endpoint = new AnnotatedEndpointWithNoHandlerMethod();
postProcessor.postProcessAfterInitialization(endpoint, "endpoint");
}
@Test
public void testEndpointWithPolledAnnotation() {
MessageBus messageBus = new MessageBus();
QueueChannel testChannel = new QueueChannel();
messageBus.registerChannel("testChannel", testChannel);
MessageEndpointAnnotationPostProcessor postProcessor =
new MessageEndpointAnnotationPostProcessor(messageBus);
postProcessor.afterPropertiesSet();
AnnotatedEndpointWithPolledAnnotation endpoint = new AnnotatedEndpointWithPolledAnnotation();
postProcessor.postProcessAfterInitialization(endpoint, "testBean");
HandlerEndpoint processedEndpoint = (HandlerEndpoint) messageBus.lookupEndpoint("testBean-endpoint");
Schedule schedule = processedEndpoint.getSubscription().getSchedule();
assertEquals(PollingSchedule.class, schedule.getClass());
PollingSchedule pollingSchedule = (PollingSchedule) schedule;
assertEquals(1234, pollingSchedule.getPeriod());
assertEquals(5678, pollingSchedule.getInitialDelay());
assertEquals(true, pollingSchedule.getFixedRate());
assertEquals(TimeUnit.SECONDS, pollingSchedule.getTimeUnit());
}
@MessageEndpoint(output="testChannel")
private static class PolledAnnotationTestBean {
@Polled(period=100)
public String poller() {
return "test";
}
@Handler
public Message<?> handle(Message<?> message) {
return message;
}
}
@MessageEndpoint(input="testChannel")
private static class DefaultOutputAnnotationTestBean {
private String messageText;
private CountDownLatch latch;
public DefaultOutputAnnotationTestBean(CountDownLatch latch) {
this.latch = latch;
}
public String getMessageText() {
return this.messageText;
}
@Handler
public Message<?> handle(Message<?> message) {
return message;
}
@DefaultOutput
public void countdown(String input) {
this.messageText = input;
latch.countDown();
}
}
@MessageEndpoint(input="inputChannel")
@Concurrency(coreSize=17, maxSize=42, keepAliveSeconds=123, queueCapacity=11)
private static class ConcurrencyAnnotationTestBean {
@Handler
public Message<?> handle(Message<?> message) {
return null;
}
}
@MessageEndpoint(input="inputChannel")
private static class ChannelRegistryAwareTestBean implements ChannelRegistryAware {
private ChannelRegistry channelRegistry;
public void setChannelRegistry(ChannelRegistry channelRegistry) {
this.channelRegistry = channelRegistry;
}
public ChannelRegistry getChannelRegistry() {
return this.channelRegistry;
}
@Handler
public Message<?> handle(Message<?> message) {
return null;
}
}
private static class SimpleAnnotatedEndpointSubclass extends SimpleAnnotatedEndpoint {
}
@MessageEndpoint(input="inputChannel", output="outputChannel", pollPeriod=25)
private static interface SimpleAnnotatedEndpointInterface {
String test(String input);
}
private static class SimpleAnnotatedEndpointImplementation implements SimpleAnnotatedEndpointInterface {
@Handler
public String test(String input) {
return "test-" + input;
}
}
@MessageEndpoint(input="input", output="output")
private static class SplitterAnnotationTestEndpoint {
@Splitter
public String[] split(String input) {
return input.split("\\.");
}
}
@MessageEndpoint(input="testChannel")
private static class AnnotatedEndpointWithNoHandlerMethod {
}
@MessageEndpoint(input="testChannel")
@Polled(period=1234, initialDelay=5678, fixedRate=true, timeUnit=TimeUnit.SECONDS)
private static class AnnotatedEndpointWithPolledAnnotation {
@Handler
public String prependFoo(String s) {
return "foo" + s;
}
}
}

View File

@@ -0,0 +1,35 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.endpoint.annotation;
import org.springframework.integration.annotation.Handler;
import org.springframework.integration.annotation.MessageEndpoint;
import org.springframework.integration.message.Message;
import org.springframework.integration.message.StringMessage;
/**
* @author Mark Fisher
*/
@MessageEndpoint(input="inputChannel", output="outputChannel", pollPeriod=10)
public class MessageParameterAnnotatedEndpoint {
@Handler
public StringMessage sayHello(Message<?> message) {
return new StringMessage("hello " + message.getPayload());
}
}

View File

@@ -0,0 +1,39 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.endpoint.annotation;
import org.springframework.integration.annotation.DefaultOutput;
import org.springframework.integration.annotation.Handler;
import org.springframework.integration.annotation.MessageEndpoint;
/**
* @author Mark Fisher
*/
@MessageEndpoint(input="inputChannel")
public class OutboundChannelAdapterTestBean {
@Handler
public String sayHello(String name) {
return "hello " + name;
}
@DefaultOutput
public void sendGreeting(String greeting) {
System.out.println(greeting);
}
}

View File

@@ -0,0 +1,33 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.endpoint.annotation;
import org.springframework.integration.annotation.Handler;
import org.springframework.integration.annotation.MessageEndpoint;
/**
* @author Mark Fisher
*/
@MessageEndpoint(input="inputChannel", output="outputChannel", pollPeriod=10)
public class SimpleAnnotatedEndpoint implements ITestEndpoint {
@Handler
public String sayHello(String name) {
return "hello " + name;
}
}

View File

@@ -0,0 +1,33 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.endpoint.annotation;
import org.springframework.integration.annotation.Handler;
import org.springframework.integration.annotation.MessageEndpoint;
/**
* @author Mark Fisher
*/
@MessageEndpoint(input="inputChannel", output="outputChannel", pollPeriod=10)
public class TypeConvertingTestEndpoint {
@Handler
public int multiplyByTwo(int number) {
return number * 2;
}
}

View File

@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:integration="http://www.springframework.org/schema/integration"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration-core-1.0.xsd">
<integration:message-bus/>
<integration:annotation-driven/>
<integration:channel id="inputChannel"/>
<integration:channel id="outputChannel"/>
<bean id="endpoint" class="org.springframework.integration.endpoint.annotation.MessageParameterAnnotatedEndpoint"/>
</beans>

Some files were not shown because too many files have changed in this diff Show More