Here are the examples of the java api org.springframework.messaging.MessageHandler taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
62 Examples
19
Source : ExecutorSubscribableChannelTests.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
@Test
public void failurePropagates() {
RuntimeException ex = new RuntimeException();
willThrow(ex).given(this.handler).handleMessage(this.message);
MessageHandler secondHandler = mock(MessageHandler.clreplaced);
this.channel.subscribe(this.handler);
this.channel.subscribe(secondHandler);
try {
this.channel.send(message);
} catch (MessageDeliveryException actualException) {
replacedertThat(actualException.getCause(), equalTo(ex));
}
verifyZeroInteractions(secondHandler);
}
19
Source : ExecutorSubscribableChannel.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
@Override
public boolean sendInternal(Message<?> message, long timeout) {
for (MessageHandler handler : getSubscribers()) {
SendTask sendTask = new SendTask(message, handler);
if (this.executor == null) {
sendTask.run();
} else {
this.executor.execute(sendTask);
}
}
return true;
}
19
Source : AbstractSubscribableChannel.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
@Override
public boolean subscribe(MessageHandler handler) {
boolean result = this.handlers.add(handler);
if (result) {
if (logger.isDebugEnabled()) {
logger.debug(getBeanName() + " added " + handler);
}
}
return result;
}
19
Source : AbstractSubscribableChannel.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
public boolean hreplacedubscription(MessageHandler handler) {
return this.handlers.contains(handler);
}
19
Source : AbstractSubscribableChannel.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
@Override
public boolean unsubscribe(MessageHandler handler) {
boolean result = this.handlers.remove(handler);
if (result) {
if (logger.isDebugEnabled()) {
logger.debug(getBeanName() + " removed " + handler);
}
}
return result;
}
19
Source : ExecutorSubscribableChannelTests.java
with Apache License 2.0
from langtianya
with Apache License 2.0
from langtianya
@Test
public void failurePropagates() throws Exception {
RuntimeException ex = new RuntimeException();
willThrow(ex).given(this.handler).handleMessage(this.message);
MessageHandler secondHandler = mock(MessageHandler.clreplaced);
this.channel.subscribe(this.handler);
this.channel.subscribe(secondHandler);
try {
this.channel.send(message);
} catch (MessageDeliveryException actualException) {
replacedertThat(actualException.getCause(), equalTo(ex));
}
verifyZeroInteractions(secondHandler);
}
19
Source : QueueMessageHandlerTest.java
with Apache License 2.0
from awspring
with Apache License 2.0
from awspring
@Test
void receiveMessage_methodWithCustomObjectAsParameter_parameterIsConverted() {
new ApplicationContextRunner().withConfiguration(UserConfigurations.of(QueueMessageHandlerWithJacksonMappingConfiguration.clreplaced)).withBean(IncomingMessageHandlerWithCustomParameter.clreplaced).run((context) -> {
DummyKeyValueHolder messagePayload = new DummyKeyValueHolder("myKey", "A value");
MappingJackson2MessageConverter jsonMapper = context.getBean(MappingJackson2MessageConverter.clreplaced);
Message<?> message = jsonMapper.toMessage(messagePayload, new MessageHeaders(Collections.singletonMap(QueueMessageHandler.LOGICAL_RESOURCE_ID, "testQueue")));
MessageHandler messageHandler = context.getBean(MessageHandler.clreplaced);
messageHandler.handleMessage(message);
IncomingMessageHandlerWithCustomParameter messageListener = context.getBean(IncomingMessageHandlerWithCustomParameter.clreplaced);
replacedertThat(messageListener.getLastReceivedMessage()).isNotNull();
replacedertThat(messageListener.getLastReceivedMessage().getKey()).isEqualTo("myKey");
replacedertThat(messageListener.getLastReceivedMessage().getValue()).isEqualTo("A value");
});
}
19
Source : QueueMessageHandlerTest.java
with Apache License 2.0
from awspring
with Apache License 2.0
from awspring
// @checkstyle:off
@Test
void receiveMessage_methodWithMessageAsParameter_parameterIsConverted() {
new ApplicationContextRunner().withConfiguration(UserConfigurations.of(QueueMessageHandlerWithJacksonMappingConfiguration.clreplaced)).withBean(IncomingMessageHandlerWithMessageParameter.clreplaced).run((context) -> {
DummyKeyValueHolder messagePayload = new DummyKeyValueHolder("myKey", "A value");
MappingJackson2MessageConverter jsonMapper = context.getBean(MappingJackson2MessageConverter.clreplaced);
Message<?> message = jsonMapper.toMessage(messagePayload, new MessageHeaders(Collections.singletonMap(QueueMessageHandler.LOGICAL_RESOURCE_ID, "testQueue")));
MessageHandler messageHandler = context.getBean(MessageHandler.clreplaced);
messageHandler.handleMessage(message);
IncomingMessageHandlerWithMessageParameter messageListener = context.getBean(IncomingMessageHandlerWithMessageParameter.clreplaced);
replacedertThat(messageListener.getLastReceivedMessage()).isNotNull();
replacedertThat(messageListener.getLastReceivedMessage().getPayload()).isEqualTo(messagePayload);
});
}
19
Source : MockSubscribableChannel.java
with Apache License 2.0
from Activiti
with Apache License 2.0
from Activiti
@Override
public boolean unsubscribe(MessageHandler messageHandler) {
return false;
}
19
Source : MockSubscribableChannel.java
with Apache License 2.0
from Activiti
with Apache License 2.0
from Activiti
@Override
public boolean subscribe(MessageHandler messageHandler) {
return false;
}
18
Source : ExecutorSubscribableChannelTests.java
with Apache License 2.0
from SourceHot
with Apache License 2.0
from SourceHot
@Test
public void failurePropagates() {
RuntimeException ex = new RuntimeException();
willThrow(ex).given(this.handler).handleMessage(this.message);
MessageHandler secondHandler = mock(MessageHandler.clreplaced);
this.channel.subscribe(this.handler);
this.channel.subscribe(secondHandler);
try {
this.channel.send(message);
} catch (MessageDeliveryException actualException) {
replacedertThat(actualException.getCause()).isEqualTo(ex);
}
verifyNoInteractions(secondHandler);
}
18
Source : TracingChannelInterceptor.java
with Apache License 2.0
from opentracing-contrib
with Apache License 2.0
from opentracing-contrib
@Override
public Message<?> beforeHandle(Message<?> message, MessageChannel channel, MessageHandler handler) {
if ((handler instanceof WebSocketAnnotationMethodMessageHandler || handler instanceof SubProtocolWebSocketHandler) && SimpMessageType.MESSAGE.equals(message.getHeaders().get(SIMP_MESSAGE_TYPE))) {
Span span = message.getHeaders().get(OPENTRACING_SPAN, Span.clreplaced);
Scope scope = tracer.scopeManager().activate(span);
message = MessageBuilder.fromMessage(message).setHeader(OPENTRACING_SCOPE, scope).build();
}
return message;
}
18
Source : TracingChannelInterceptor.java
with Apache License 2.0
from opentracing-contrib
with Apache License 2.0
from opentracing-contrib
@Override
public void afterMessageHandled(Message<?> message, MessageChannel channel, MessageHandler handler, Exception arg3) {
if ((handler instanceof WebSocketAnnotationMethodMessageHandler || handler instanceof SubProtocolWebSocketHandler) && SimpMessageType.MESSAGE.equals(message.getHeaders().get(SIMP_MESSAGE_TYPE))) {
message.getHeaders().get(OPENTRACING_SCOPE, Scope.clreplaced).close();
message.getHeaders().get(OPENTRACING_SPAN, Span.clreplaced).finish();
}
}
18
Source : TracingChannelInterceptor.java
with Apache License 2.0
from opentracing-contrib
with Apache License 2.0
from opentracing-contrib
@Override
public void afterMessageHandled(final Message<?> message, final MessageChannel channel, final MessageHandler handler, final Exception arg3) {
if ((handler instanceof WebSocketAnnotationMethodMessageHandler || handler instanceof SubProtocolWebSocketHandler) && SimpMessageType.MESSAGE.equals(message.getHeaders().get(SIMP_MESSAGE_TYPE))) {
message.getHeaders().get(OPENTRACING_SCOPE, Scope.clreplaced).close();
message.getHeaders().get(OPENTRACING_SPAN, Span.clreplaced).finish();
// MessageHeaders are immutable
// message.getHeaders().remove(OPENTRACING_SCOPE);
}
}
18
Source : MessageBasedJobManagerConfigurator.java
with Apache License 2.0
from Activiti
with Apache License 2.0
from Activiti
protected MessageHandler createJobMessageHandler(ProcessEngineConfigurationImpl configuration) {
MessageHandler messageHandler = jobMessageHandlerFactory.create(configuration);
return registerBean(JOB_MESSAGE_HANDLER, messageHandler);
}
18
Source : GraphQLWebSocketMessageBrokerAutoConfigurationTest.java
with Apache License 2.0
from Activiti
with Apache License 2.0
from Activiti
@SuppressWarnings("unused")
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public clreplaced GraphQLWebSocketMessageBrokerAutoConfigurationTest {
@MockBean
private GraphQLSchema graphQLSchema;
@Autowired
private MessageHandler graphQLBrokerMessageHandler;
@Autowired
private GraphQLBrokerSubProtocolHandler graphQLBrokerSubProtocolHandler;
@EnableAutoConfiguration
@SpringBootConfiguration
static clreplaced GraphQLWebSocketMessageBrokerAutoConfigurationTestApplication {
}
@Test
public void testContextLoads() {
// success
}
}
17
Source : ExecutorSubscribableChannelTests.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
/**
* Unit tests for {@link ExecutorSubscribableChannel}.
*
* @author Phillip Webb
*/
public clreplaced ExecutorSubscribableChannelTests {
private ExecutorSubscribableChannel channel = new ExecutorSubscribableChannel();
@Mock
private MessageHandler handler;
private final Object payload = new Object();
private final Message<Object> message = MessageBuilder.withPayload(this.payload).build();
@Captor
private ArgumentCaptor<Runnable> runnableCaptor;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void messageMustNotBeNull() {
replacedertThatIllegalArgumentException().isThrownBy(() -> this.channel.send(null)).withMessageContaining("Message must not be null");
}
@Test
public void sendWithoutExecutor() {
BeforeHandleInterceptor interceptor = new BeforeHandleInterceptor();
this.channel.addInterceptor(interceptor);
this.channel.subscribe(this.handler);
this.channel.send(this.message);
verify(this.handler).handleMessage(this.message);
replacedertEquals(1, interceptor.getCounter().get());
replacedertTrue(interceptor.wasAfterHandledInvoked());
}
@Test
public void sendWithExecutor() {
BeforeHandleInterceptor interceptor = new BeforeHandleInterceptor();
TaskExecutor executor = mock(TaskExecutor.clreplaced);
ExecutorSubscribableChannel testChannel = new ExecutorSubscribableChannel(executor);
testChannel.addInterceptor(interceptor);
testChannel.subscribe(this.handler);
testChannel.send(this.message);
verify(executor).execute(this.runnableCaptor.capture());
verify(this.handler, never()).handleMessage(this.message);
this.runnableCaptor.getValue().run();
verify(this.handler).handleMessage(this.message);
replacedertEquals(1, interceptor.getCounter().get());
replacedertTrue(interceptor.wasAfterHandledInvoked());
}
@Test
public void subscribeTwice() {
replacedertThat(this.channel.subscribe(this.handler), equalTo(true));
replacedertThat(this.channel.subscribe(this.handler), equalTo(false));
this.channel.send(this.message);
verify(this.handler, times(1)).handleMessage(this.message);
}
@Test
public void unsubscribeTwice() {
this.channel.subscribe(this.handler);
replacedertThat(this.channel.unsubscribe(this.handler), equalTo(true));
replacedertThat(this.channel.unsubscribe(this.handler), equalTo(false));
this.channel.send(this.message);
verify(this.handler, never()).handleMessage(this.message);
}
@Test
public void failurePropagates() {
RuntimeException ex = new RuntimeException();
willThrow(ex).given(this.handler).handleMessage(this.message);
MessageHandler secondHandler = mock(MessageHandler.clreplaced);
this.channel.subscribe(this.handler);
this.channel.subscribe(secondHandler);
try {
this.channel.send(message);
} catch (MessageDeliveryException actualException) {
replacedertThat(actualException.getCause(), equalTo(ex));
}
verifyZeroInteractions(secondHandler);
}
@Test
public void concurrentModification() {
this.channel.subscribe(message1 -> channel.unsubscribe(handler));
this.channel.subscribe(this.handler);
this.channel.send(this.message);
verify(this.handler).handleMessage(this.message);
}
@Test
public void interceptorWithModifiedMessage() {
Message<?> expected = mock(Message.clreplaced);
BeforeHandleInterceptor interceptor = new BeforeHandleInterceptor();
interceptor.setMessageToReturn(expected);
this.channel.addInterceptor(interceptor);
this.channel.subscribe(this.handler);
this.channel.send(this.message);
verify(this.handler).handleMessage(expected);
replacedertEquals(1, interceptor.getCounter().get());
replacedertTrue(interceptor.wasAfterHandledInvoked());
}
@Test
public void interceptorWithNull() {
BeforeHandleInterceptor interceptor1 = new BeforeHandleInterceptor();
NullReturningBeforeHandleInterceptor interceptor2 = new NullReturningBeforeHandleInterceptor();
this.channel.addInterceptor(interceptor1);
this.channel.addInterceptor(interceptor2);
this.channel.subscribe(this.handler);
this.channel.send(this.message);
verifyNoMoreInteractions(this.handler);
replacedertEquals(1, interceptor1.getCounter().get());
replacedertEquals(1, interceptor2.getCounter().get());
replacedertTrue(interceptor1.wasAfterHandledInvoked());
}
@Test
public void interceptorWithException() {
IllegalStateException expected = new IllegalStateException("Fake exception");
willThrow(expected).given(this.handler).handleMessage(this.message);
BeforeHandleInterceptor interceptor = new BeforeHandleInterceptor();
this.channel.addInterceptor(interceptor);
this.channel.subscribe(this.handler);
try {
this.channel.send(this.message);
} catch (MessageDeliveryException actual) {
replacedertSame(expected, actual.getCause());
}
verify(this.handler).handleMessage(this.message);
replacedertEquals(1, interceptor.getCounter().get());
replacedertTrue(interceptor.wasAfterHandledInvoked());
}
private abstract static clreplaced AbstractTestInterceptor implements ChannelInterceptor, ExecutorChannelInterceptor {
private AtomicInteger counter = new AtomicInteger();
private volatile boolean afterHandledInvoked;
public AtomicInteger getCounter() {
return this.counter;
}
public boolean wasAfterHandledInvoked() {
return this.afterHandledInvoked;
}
@Override
public Message<?> beforeHandle(Message<?> message, MessageChannel channel, MessageHandler handler) {
replacedertNotNull(message);
counter.incrementAndGet();
return message;
}
@Override
public void afterMessageHandled(Message<?> message, MessageChannel channel, MessageHandler handler, Exception ex) {
this.afterHandledInvoked = true;
}
}
private static clreplaced BeforeHandleInterceptor extends AbstractTestInterceptor {
private Message<?> messageToReturn;
private RuntimeException exceptionToRaise;
public void setMessageToReturn(Message<?> messageToReturn) {
this.messageToReturn = messageToReturn;
}
// TODO Determine why setExceptionToRaise() is unused.
@SuppressWarnings("unused")
public void setExceptionToRaise(RuntimeException exception) {
this.exceptionToRaise = exception;
}
@Override
public Message<?> beforeHandle(Message<?> message, MessageChannel channel, MessageHandler handler) {
super.beforeHandle(message, channel, handler);
if (this.exceptionToRaise != null) {
throw this.exceptionToRaise;
}
return (this.messageToReturn != null ? this.messageToReturn : message);
}
}
private static clreplaced NullReturningBeforeHandleInterceptor extends AbstractTestInterceptor {
@Override
public Message<?> beforeHandle(Message<?> message, MessageChannel channel, MessageHandler handler) {
super.beforeHandle(message, channel, handler);
return null;
}
}
}
17
Source : MqttSourceTests.java
with Apache License 2.0
from spring-cloud-stream-app-starters
with Apache License 2.0
from spring-cloud-stream-app-starters
/**
* Tests for MqttSource.
*
* @author Janne Valkealahti
* @author Gary Russell
*/
@RunWith(SpringJUnit4ClreplacedRunner.clreplaced)
@DirtiesContext
public abstract clreplaced MqttSourceTests {
@ClreplacedRule
public static MqttTestSupport mqttTestSupport = new MqttTestSupport();
@Autowired
protected Source channels;
@Autowired
protected MessageCollector messageCollector;
@Autowired
protected MqttSourceProperties properties;
@Autowired
protected MessageHandler mqttOutbound;
@SpringBootTest({ "mqtt.topics=test,fake", "mqtt.qos=0,0" })
public static clreplaced ReceiveMessageTests extends MqttSourceTests {
@Test
public void test() throws Exception {
mqttOutbound.handleMessage(MessageBuilder.withPayload("hello").build());
Message<?> out = this.messageCollector.forChannel(this.channels.output()).poll(10, TimeUnit.SECONDS);
replacedertThat(out).isNotNull();
replacedertThat(out.getPayload()).isEqualTo("hello");
}
}
@SpringBootApplication
static clreplaced MqttSourceApplication {
@Autowired
private MqttPahoClientFactory mqttClientFactory;
@Bean
public MessageHandler mqttOutbound() {
MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler("test", mqttClientFactory);
messageHandler.setAsync(true);
messageHandler.setDefaultTopic("test");
messageHandler.setConverter(pahoMessageConverter());
return messageHandler;
}
@Bean
public DefaultPahoMessageConverter pahoMessageConverter() {
DefaultPahoMessageConverter converter = new DefaultPahoMessageConverter(1, false, "UTF-8");
return converter;
}
}
}
17
Source : ExecutorSubscribableChannelTests.java
with Apache License 2.0
from SourceHot
with Apache License 2.0
from SourceHot
/**
* Unit tests for {@link ExecutorSubscribableChannel}.
*
* @author Phillip Webb
*/
@ExtendWith(MockitoExtension.clreplaced)
public clreplaced ExecutorSubscribableChannelTests {
private ExecutorSubscribableChannel channel = new ExecutorSubscribableChannel();
@Mock
private MessageHandler handler;
@Captor
private ArgumentCaptor<Runnable> runnableCaptor;
private final Object payload = new Object();
private final Message<Object> message = MessageBuilder.withPayload(this.payload).build();
@Test
public void messageMustNotBeNull() {
replacedertThatIllegalArgumentException().isThrownBy(() -> this.channel.send(null)).withMessageContaining("Message must not be null");
}
@Test
public void sendWithoutExecutor() {
BeforeHandleInterceptor interceptor = new BeforeHandleInterceptor();
this.channel.addInterceptor(interceptor);
this.channel.subscribe(this.handler);
this.channel.send(this.message);
verify(this.handler).handleMessage(this.message);
replacedertThat(interceptor.getCounter().get()).isEqualTo(1);
replacedertThat(interceptor.wasAfterHandledInvoked()).isTrue();
}
@Test
public void sendWithExecutor() {
BeforeHandleInterceptor interceptor = new BeforeHandleInterceptor();
TaskExecutor executor = mock(TaskExecutor.clreplaced);
ExecutorSubscribableChannel testChannel = new ExecutorSubscribableChannel(executor);
testChannel.addInterceptor(interceptor);
testChannel.subscribe(this.handler);
testChannel.send(this.message);
verify(executor).execute(this.runnableCaptor.capture());
verify(this.handler, never()).handleMessage(this.message);
this.runnableCaptor.getValue().run();
verify(this.handler).handleMessage(this.message);
replacedertThat(interceptor.getCounter().get()).isEqualTo(1);
replacedertThat(interceptor.wasAfterHandledInvoked()).isTrue();
}
@Test
public void subscribeTwice() {
replacedertThat(this.channel.subscribe(this.handler)).isEqualTo(true);
replacedertThat(this.channel.subscribe(this.handler)).isEqualTo(false);
this.channel.send(this.message);
verify(this.handler, times(1)).handleMessage(this.message);
}
@Test
public void unsubscribeTwice() {
this.channel.subscribe(this.handler);
replacedertThat(this.channel.unsubscribe(this.handler)).isEqualTo(true);
replacedertThat(this.channel.unsubscribe(this.handler)).isEqualTo(false);
this.channel.send(this.message);
verify(this.handler, never()).handleMessage(this.message);
}
@Test
public void failurePropagates() {
RuntimeException ex = new RuntimeException();
willThrow(ex).given(this.handler).handleMessage(this.message);
MessageHandler secondHandler = mock(MessageHandler.clreplaced);
this.channel.subscribe(this.handler);
this.channel.subscribe(secondHandler);
try {
this.channel.send(message);
} catch (MessageDeliveryException actualException) {
replacedertThat(actualException.getCause()).isEqualTo(ex);
}
verifyNoInteractions(secondHandler);
}
@Test
public void concurrentModification() {
this.channel.subscribe(message1 -> channel.unsubscribe(handler));
this.channel.subscribe(this.handler);
this.channel.send(this.message);
verify(this.handler).handleMessage(this.message);
}
@Test
public void interceptorWithModifiedMessage() {
Message<?> expected = mock(Message.clreplaced);
BeforeHandleInterceptor interceptor = new BeforeHandleInterceptor();
interceptor.setMessageToReturn(expected);
this.channel.addInterceptor(interceptor);
this.channel.subscribe(this.handler);
this.channel.send(this.message);
verify(this.handler).handleMessage(expected);
replacedertThat(interceptor.getCounter().get()).isEqualTo(1);
replacedertThat(interceptor.wasAfterHandledInvoked()).isTrue();
}
@Test
public void interceptorWithNull() {
BeforeHandleInterceptor interceptor1 = new BeforeHandleInterceptor();
NullReturningBeforeHandleInterceptor interceptor2 = new NullReturningBeforeHandleInterceptor();
this.channel.addInterceptor(interceptor1);
this.channel.addInterceptor(interceptor2);
this.channel.subscribe(this.handler);
this.channel.send(this.message);
verifyNoMoreInteractions(this.handler);
replacedertThat(interceptor1.getCounter().get()).isEqualTo(1);
replacedertThat(interceptor2.getCounter().get()).isEqualTo(1);
replacedertThat(interceptor1.wasAfterHandledInvoked()).isTrue();
}
@Test
public void interceptorWithException() {
IllegalStateException expected = new IllegalStateException("Fake exception");
willThrow(expected).given(this.handler).handleMessage(this.message);
BeforeHandleInterceptor interceptor = new BeforeHandleInterceptor();
this.channel.addInterceptor(interceptor);
this.channel.subscribe(this.handler);
try {
this.channel.send(this.message);
} catch (MessageDeliveryException actual) {
replacedertThat(actual.getCause()).isSameAs(expected);
}
verify(this.handler).handleMessage(this.message);
replacedertThat(interceptor.getCounter().get()).isEqualTo(1);
replacedertThat(interceptor.wasAfterHandledInvoked()).isTrue();
}
private abstract static clreplaced AbstractTestInterceptor implements ChannelInterceptor, ExecutorChannelInterceptor {
private AtomicInteger counter = new AtomicInteger();
private volatile boolean afterHandledInvoked;
public AtomicInteger getCounter() {
return this.counter;
}
public boolean wasAfterHandledInvoked() {
return this.afterHandledInvoked;
}
@Override
public Message<?> beforeHandle(Message<?> message, MessageChannel channel, MessageHandler handler) {
replacedertThat(message).isNotNull();
counter.incrementAndGet();
return message;
}
@Override
public void afterMessageHandled(Message<?> message, MessageChannel channel, MessageHandler handler, Exception ex) {
this.afterHandledInvoked = true;
}
}
private static clreplaced BeforeHandleInterceptor extends AbstractTestInterceptor {
private Message<?> messageToReturn;
private RuntimeException exceptionToRaise;
public void setMessageToReturn(Message<?> messageToReturn) {
this.messageToReturn = messageToReturn;
}
// TODO Determine why setExceptionToRaise() is unused.
@SuppressWarnings("unused")
public void setExceptionToRaise(RuntimeException exception) {
this.exceptionToRaise = exception;
}
@Override
public Message<?> beforeHandle(Message<?> message, MessageChannel channel, MessageHandler handler) {
super.beforeHandle(message, channel, handler);
if (this.exceptionToRaise != null) {
throw this.exceptionToRaise;
}
return (this.messageToReturn != null ? this.messageToReturn : message);
}
}
private static clreplaced NullReturningBeforeHandleInterceptor extends AbstractTestInterceptor {
@Override
public Message<?> beforeHandle(Message<?> message, MessageChannel channel, MessageHandler handler) {
super.beforeHandle(message, channel, handler);
return null;
}
}
}
17
Source : SofaTracerChannelInterceptor.java
with Apache License 2.0
from sofastack
with Apache License 2.0
from sofastack
@Override
public void afterMessageHandled(Message<?> message, MessageChannel channel, MessageHandler handler, Exception ex) {
if (emptyMessage(message)) {
return;
}
finishSpan(ex, message, channel);
}
17
Source : TracingChannelInterceptor.java
with Apache License 2.0
from opentracing-contrib
with Apache License 2.0
from opentracing-contrib
@Override
public Message<?> beforeHandle(final Message<?> message, final MessageChannel channel, final MessageHandler handler) {
if ((!(handler instanceof WebSocketAnnotationMethodMessageHandler) && !(handler instanceof SubProtocolWebSocketHandler)) || !SimpMessageType.MESSAGE.equals(message.getHeaders().get(SIMP_MESSAGE_TYPE)))
return message;
final Span span = message.getHeaders().get(OPENTRACING_SPAN, Span.clreplaced);
final Scope scope = tracer.scopeManager().activate(span);
return MessageBuilder.fromMessage(message).setHeader(OPENTRACING_SCOPE, scope).build();
}
17
Source : ExecutorSubscribableChannelTests.java
with MIT License
from mindcarver
with MIT License
from mindcarver
/**
* Unit tests for {@link ExecutorSubscribableChannel}.
*
* @author Phillip Webb
*/
public clreplaced ExecutorSubscribableChannelTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
private ExecutorSubscribableChannel channel = new ExecutorSubscribableChannel();
@Mock
private MessageHandler handler;
private final Object payload = new Object();
private final Message<Object> message = MessageBuilder.withPayload(this.payload).build();
@Captor
private ArgumentCaptor<Runnable> runnableCaptor;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void messageMustNotBeNull() {
thrown.expect(IllegalArgumentException.clreplaced);
thrown.expectMessage("Message must not be null");
this.channel.send(null);
}
@Test
public void sendWithoutExecutor() {
BeforeHandleInterceptor interceptor = new BeforeHandleInterceptor();
this.channel.addInterceptor(interceptor);
this.channel.subscribe(this.handler);
this.channel.send(this.message);
verify(this.handler).handleMessage(this.message);
replacedertEquals(1, interceptor.getCounter().get());
replacedertTrue(interceptor.wasAfterHandledInvoked());
}
@Test
public void sendWithExecutor() {
BeforeHandleInterceptor interceptor = new BeforeHandleInterceptor();
TaskExecutor executor = mock(TaskExecutor.clreplaced);
ExecutorSubscribableChannel testChannel = new ExecutorSubscribableChannel(executor);
testChannel.addInterceptor(interceptor);
testChannel.subscribe(this.handler);
testChannel.send(this.message);
verify(executor).execute(this.runnableCaptor.capture());
verify(this.handler, never()).handleMessage(this.message);
this.runnableCaptor.getValue().run();
verify(this.handler).handleMessage(this.message);
replacedertEquals(1, interceptor.getCounter().get());
replacedertTrue(interceptor.wasAfterHandledInvoked());
}
@Test
public void subscribeTwice() {
replacedertThat(this.channel.subscribe(this.handler), equalTo(true));
replacedertThat(this.channel.subscribe(this.handler), equalTo(false));
this.channel.send(this.message);
verify(this.handler, times(1)).handleMessage(this.message);
}
@Test
public void unsubscribeTwice() {
this.channel.subscribe(this.handler);
replacedertThat(this.channel.unsubscribe(this.handler), equalTo(true));
replacedertThat(this.channel.unsubscribe(this.handler), equalTo(false));
this.channel.send(this.message);
verify(this.handler, never()).handleMessage(this.message);
}
@Test
public void failurePropagates() {
RuntimeException ex = new RuntimeException();
willThrow(ex).given(this.handler).handleMessage(this.message);
MessageHandler secondHandler = mock(MessageHandler.clreplaced);
this.channel.subscribe(this.handler);
this.channel.subscribe(secondHandler);
try {
this.channel.send(message);
} catch (MessageDeliveryException actualException) {
replacedertThat(actualException.getCause(), equalTo(ex));
}
verifyZeroInteractions(secondHandler);
}
@Test
public void concurrentModification() {
this.channel.subscribe(message1 -> channel.unsubscribe(handler));
this.channel.subscribe(this.handler);
this.channel.send(this.message);
verify(this.handler).handleMessage(this.message);
}
@Test
public void interceptorWithModifiedMessage() {
Message<?> expected = mock(Message.clreplaced);
BeforeHandleInterceptor interceptor = new BeforeHandleInterceptor();
interceptor.setMessageToReturn(expected);
this.channel.addInterceptor(interceptor);
this.channel.subscribe(this.handler);
this.channel.send(this.message);
verify(this.handler).handleMessage(expected);
replacedertEquals(1, interceptor.getCounter().get());
replacedertTrue(interceptor.wasAfterHandledInvoked());
}
@Test
public void interceptorWithNull() {
BeforeHandleInterceptor interceptor1 = new BeforeHandleInterceptor();
NullReturningBeforeHandleInterceptor interceptor2 = new NullReturningBeforeHandleInterceptor();
this.channel.addInterceptor(interceptor1);
this.channel.addInterceptor(interceptor2);
this.channel.subscribe(this.handler);
this.channel.send(this.message);
verifyNoMoreInteractions(this.handler);
replacedertEquals(1, interceptor1.getCounter().get());
replacedertEquals(1, interceptor2.getCounter().get());
replacedertTrue(interceptor1.wasAfterHandledInvoked());
}
@Test
public void interceptorWithException() {
IllegalStateException expected = new IllegalStateException("Fake exception");
willThrow(expected).given(this.handler).handleMessage(this.message);
BeforeHandleInterceptor interceptor = new BeforeHandleInterceptor();
this.channel.addInterceptor(interceptor);
this.channel.subscribe(this.handler);
try {
this.channel.send(this.message);
} catch (MessageDeliveryException actual) {
replacedertSame(expected, actual.getCause());
}
verify(this.handler).handleMessage(this.message);
replacedertEquals(1, interceptor.getCounter().get());
replacedertTrue(interceptor.wasAfterHandledInvoked());
}
private abstract static clreplaced AbstractTestInterceptor implements ChannelInterceptor, ExecutorChannelInterceptor {
private AtomicInteger counter = new AtomicInteger();
private volatile boolean afterHandledInvoked;
public AtomicInteger getCounter() {
return this.counter;
}
public boolean wasAfterHandledInvoked() {
return this.afterHandledInvoked;
}
@Override
public Message<?> beforeHandle(Message<?> message, MessageChannel channel, MessageHandler handler) {
replacedertNotNull(message);
counter.incrementAndGet();
return message;
}
@Override
public void afterMessageHandled(Message<?> message, MessageChannel channel, MessageHandler handler, Exception ex) {
this.afterHandledInvoked = true;
}
}
private static clreplaced BeforeHandleInterceptor extends AbstractTestInterceptor {
private Message<?> messageToReturn;
private RuntimeException exceptionToRaise;
public void setMessageToReturn(Message<?> messageToReturn) {
this.messageToReturn = messageToReturn;
}
// TODO Determine why setExceptionToRaise() is unused.
@SuppressWarnings("unused")
public void setExceptionToRaise(RuntimeException exception) {
this.exceptionToRaise = exception;
}
@Override
public Message<?> beforeHandle(Message<?> message, MessageChannel channel, MessageHandler handler) {
super.beforeHandle(message, channel, handler);
if (this.exceptionToRaise != null) {
throw this.exceptionToRaise;
}
return (this.messageToReturn != null ? this.messageToReturn : message);
}
}
private static clreplaced NullReturningBeforeHandleInterceptor extends AbstractTestInterceptor {
@Override
public Message<?> beforeHandle(Message<?> message, MessageChannel channel, MessageHandler handler) {
super.beforeHandle(message, channel, handler);
return null;
}
}
}
17
Source : ExecutorSubscribableChannelTests.java
with Apache License 2.0
from langtianya
with Apache License 2.0
from langtianya
/**
* Unit tests for {@link ExecutorSubscribableChannel}.
*
* @author Phillip Webb
*/
public clreplaced ExecutorSubscribableChannelTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
private ExecutorSubscribableChannel channel = new ExecutorSubscribableChannel();
@Mock
private MessageHandler handler;
private final Object payload = new Object();
private final Message<Object> message = MessageBuilder.withPayload(this.payload).build();
@Captor
private ArgumentCaptor<Runnable> runnableCaptor;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void messageMustNotBeNull() throws Exception {
thrown.expect(IllegalArgumentException.clreplaced);
thrown.expectMessage("Message must not be null");
this.channel.send(null);
}
@Test
public void sendWithoutExecutor() {
BeforeHandleInterceptor interceptor = new BeforeHandleInterceptor();
this.channel.addInterceptor(interceptor);
this.channel.subscribe(this.handler);
this.channel.send(this.message);
verify(this.handler).handleMessage(this.message);
replacedertEquals(1, interceptor.getCounter().get());
replacedertTrue(interceptor.wasAfterHandledInvoked());
}
@Test
public void sendWithExecutor() throws Exception {
BeforeHandleInterceptor interceptor = new BeforeHandleInterceptor();
TaskExecutor executor = mock(TaskExecutor.clreplaced);
ExecutorSubscribableChannel testChannel = new ExecutorSubscribableChannel(executor);
testChannel.addInterceptor(interceptor);
testChannel.subscribe(this.handler);
testChannel.send(this.message);
verify(executor).execute(this.runnableCaptor.capture());
verify(this.handler, never()).handleMessage(this.message);
this.runnableCaptor.getValue().run();
verify(this.handler).handleMessage(this.message);
replacedertEquals(1, interceptor.getCounter().get());
replacedertTrue(interceptor.wasAfterHandledInvoked());
}
@Test
public void subscribeTwice() throws Exception {
replacedertThat(this.channel.subscribe(this.handler), equalTo(true));
replacedertThat(this.channel.subscribe(this.handler), equalTo(false));
this.channel.send(this.message);
verify(this.handler, times(1)).handleMessage(this.message);
}
@Test
public void unsubscribeTwice() throws Exception {
this.channel.subscribe(this.handler);
replacedertThat(this.channel.unsubscribe(this.handler), equalTo(true));
replacedertThat(this.channel.unsubscribe(this.handler), equalTo(false));
this.channel.send(this.message);
verify(this.handler, never()).handleMessage(this.message);
}
@Test
public void failurePropagates() throws Exception {
RuntimeException ex = new RuntimeException();
willThrow(ex).given(this.handler).handleMessage(this.message);
MessageHandler secondHandler = mock(MessageHandler.clreplaced);
this.channel.subscribe(this.handler);
this.channel.subscribe(secondHandler);
try {
this.channel.send(message);
} catch (MessageDeliveryException actualException) {
replacedertThat(actualException.getCause(), equalTo(ex));
}
verifyZeroInteractions(secondHandler);
}
@Test
public void concurrentModification() throws Exception {
this.channel.subscribe(message1 -> channel.unsubscribe(handler));
this.channel.subscribe(this.handler);
this.channel.send(this.message);
verify(this.handler).handleMessage(this.message);
}
@Test
public void interceptorWithModifiedMessage() {
Message<?> expected = mock(Message.clreplaced);
BeforeHandleInterceptor interceptor = new BeforeHandleInterceptor();
interceptor.setMessageToReturn(expected);
this.channel.addInterceptor(interceptor);
this.channel.subscribe(this.handler);
this.channel.send(this.message);
verify(this.handler).handleMessage(expected);
replacedertEquals(1, interceptor.getCounter().get());
replacedertTrue(interceptor.wasAfterHandledInvoked());
}
@Test
public void interceptorWithNull() {
BeforeHandleInterceptor interceptor1 = new BeforeHandleInterceptor();
NullReturningBeforeHandleInterceptor interceptor2 = new NullReturningBeforeHandleInterceptor();
this.channel.addInterceptor(interceptor1);
this.channel.addInterceptor(interceptor2);
this.channel.subscribe(this.handler);
this.channel.send(this.message);
verifyNoMoreInteractions(this.handler);
replacedertEquals(1, interceptor1.getCounter().get());
replacedertEquals(1, interceptor2.getCounter().get());
replacedertTrue(interceptor1.wasAfterHandledInvoked());
}
@Test
public void interceptorWithException() {
IllegalStateException expected = new IllegalStateException("Fake exception");
willThrow(expected).given(this.handler).handleMessage(this.message);
BeforeHandleInterceptor interceptor = new BeforeHandleInterceptor();
this.channel.addInterceptor(interceptor);
this.channel.subscribe(this.handler);
try {
this.channel.send(this.message);
} catch (MessageDeliveryException actual) {
replacedertSame(expected, actual.getCause());
}
verify(this.handler).handleMessage(this.message);
replacedertEquals(1, interceptor.getCounter().get());
replacedertTrue(interceptor.wasAfterHandledInvoked());
}
private abstract static clreplaced AbstractTestInterceptor extends ChannelInterceptorAdapter implements ExecutorChannelInterceptor {
private AtomicInteger counter = new AtomicInteger();
private volatile boolean afterHandledInvoked;
public AtomicInteger getCounter() {
return this.counter;
}
public boolean wasAfterHandledInvoked() {
return this.afterHandledInvoked;
}
@Override
public Message<?> beforeHandle(Message<?> message, MessageChannel channel, MessageHandler handler) {
replacedertNotNull(message);
counter.incrementAndGet();
return message;
}
@Override
public void afterMessageHandled(Message<?> message, MessageChannel channel, MessageHandler handler, Exception ex) {
this.afterHandledInvoked = true;
}
}
private static clreplaced BeforeHandleInterceptor extends AbstractTestInterceptor {
private Message<?> messageToReturn;
private RuntimeException exceptionToRaise;
public void setMessageToReturn(Message<?> messageToReturn) {
this.messageToReturn = messageToReturn;
}
// TODO Determine why setExceptionToRaise() is unused.
@SuppressWarnings("unused")
public void setExceptionToRaise(RuntimeException exception) {
this.exceptionToRaise = exception;
}
@Override
public Message<?> beforeHandle(Message<?> message, MessageChannel channel, MessageHandler handler) {
super.beforeHandle(message, channel, handler);
if (this.exceptionToRaise != null) {
throw this.exceptionToRaise;
}
return (this.messageToReturn != null ? this.messageToReturn : message);
}
}
private static clreplaced NullReturningBeforeHandleInterceptor extends AbstractTestInterceptor {
@Override
public Message<?> beforeHandle(Message<?> message, MessageChannel channel, MessageHandler handler) {
super.beforeHandle(message, channel, handler);
return null;
}
}
}
17
Source : MessageBrokerConfigurationTests.java
with Apache License 2.0
from langtianya
with Apache License 2.0
from langtianya
@Test
public void userBroadcastsDisabledWithSimpleBroker() throws Exception {
SimpUserRegistry registry = this.simpleBrokerContext.getBean(SimpUserRegistry.clreplaced);
replacedertNotNull(registry);
replacedertNotEquals(MultiServerUserRegistry.clreplaced, registry.getClreplaced());
UserDestinationMessageHandler handler = this.simpleBrokerContext.getBean(UserDestinationMessageHandler.clreplaced);
replacedertNull(handler.getBroadcastDestination());
String name = "userRegistryMessageHandler";
MessageHandler messageHandler = this.simpleBrokerContext.getBean(name, MessageHandler.clreplaced);
replacedertNotEquals(UserRegistryMessageHandler.clreplaced, messageHandler.getClreplaced());
}
17
Source : MySubscribableChannel.java
with Apache License 2.0
from fangjian0423
with Apache License 2.0
from fangjian0423
@Override
protected boolean sendInternal(Message<?> message, long timeout) {
if (message == null || CollectionUtils.isEmpty(getSubscribers())) {
return false;
}
Iterator<MessageHandler> iter = getSubscribers().iterator();
int index = 0, targetIndex = random.nextInt(getSubscribers().size());
while (iter.hasNext()) {
MessageHandler handler = iter.next();
if (index == targetIndex) {
handler.handleMessage(message);
return true;
}
index++;
}
return false;
}
17
Source : MessageBasedJobManagerConfigurator.java
with Apache License 2.0
from Activiti
with Apache License 2.0
from Activiti
public clreplaced MessageBasedJobManagerConfigurator implements ProcessEngineConfigurator, SmartLifecycle {
private static final Logger logger = LoggerFactory.getLogger(MessageBasedJobManagerConfigurator.clreplaced);
private static final String MESSAGE_BASED_JOB_MANAGER = "messageBasedJobManager";
public static final String JOB_MESSAGE_HANDLER = "jobMessageHandler";
private String contentType = "application/json";
private final BindingService bindingService;
private final JobMessageInputChannelFactory inputChannelFactory;
private final ConsumerProperties consumerProperties;
private final MessageBasedJobManagerFactory messageBasedJobManagerFactory;
private final JobMessageHandlerFactory jobMessageHandlerFactory;
private final ConfigurableListableBeanFactory beanFactory;
private MessageBasedJobManager messageBasedJobManager;
private MessageHandler jobMessageHandler;
private SubscribableChannel inputChannel;
private ProcessEngineConfigurationImpl configuration;
private boolean running = false;
public MessageBasedJobManagerConfigurator(ConfigurableListableBeanFactory beanFactory, BindingService bindingService, JobMessageInputChannelFactory inputChannelFactory, MessageBasedJobManagerFactory messageBasedJobManagerFactory, JobMessageHandlerFactory jobMessageHandlerFactory, ConsumerProperties consumerProperties) {
this.bindingService = bindingService;
this.inputChannelFactory = inputChannelFactory;
this.consumerProperties = consumerProperties;
this.messageBasedJobManagerFactory = messageBasedJobManagerFactory;
this.jobMessageHandlerFactory = jobMessageHandlerFactory;
this.beanFactory = beanFactory;
}
protected MessageHandler createJobMessageHandler(ProcessEngineConfigurationImpl configuration) {
MessageHandler messageHandler = jobMessageHandlerFactory.create(configuration);
return registerBean(JOB_MESSAGE_HANDLER, messageHandler);
}
protected MessageBasedJobManager createMessageBasedJobManager(ProcessEngineConfigurationImpl configuration) {
MessageBasedJobManager instance = messageBasedJobManagerFactory.create(configuration);
return registerBean(MESSAGE_BASED_JOB_MANAGER, instance);
}
/**
* Configures MessageBasedJobManager
*/
@Override
public void beforeInit(ProcessEngineConfigurationImpl configuration) {
this.messageBasedJobManager = createMessageBasedJobManager(configuration);
// Let's manage async executor lifecycle manually on start/stop
configuration.setAsyncExecutorActivate(false);
configuration.setAsyncExecutorMessageQueueMode(true);
configuration.setJobManager(messageBasedJobManager);
logger.info("Configured message based job manager clreplaced: {}", this.messageBasedJobManager.getClreplaced());
}
/**
* Configures input channel
*/
@Override
public void configure(ProcessEngineConfigurationImpl configuration) {
this.configuration = configuration;
String channelName = messageBasedJobManager.getInputChannelName();
String destination = messageBasedJobManager.getDestination();
BindingProperties bindingProperties = new BindingProperties();
bindingProperties.setConsumer(consumerProperties);
bindingProperties.setContentType(contentType);
bindingProperties.setGroup(JOB_MESSAGE_HANDLER);
// Let's use message job producer destination scope
bindingProperties.setDestination(destination);
// Let's create input channel
inputChannel = inputChannelFactory.createInputChannel(channelName, bindingProperties);
logger.info("Configured message job input channel '{}' with bindings: {}", channelName, bindingProperties);
}
@Override
public int getPriority() {
return 0;
}
@Override
public void start() {
logger.info("Subscribing job message handler to input channel {}", messageBasedJobManager.getInputChannelName());
jobMessageHandler = createJobMessageHandler(configuration);
// Let's subscribe and bind consumer channel
inputChannel.subscribe(jobMessageHandler);
bindingService.bindConsumer(inputChannel, messageBasedJobManager.getInputChannelName());
// Now start async executor
if (!configuration.getAsyncExecutor().isActive()) {
configuration.getAsyncExecutor().start();
}
running = true;
}
@Override
public void stop() {
logger.info("Unsubscribing job message handler to input channel {}", messageBasedJobManager.getInputChannelName());
try {
// Let's unbind consumer from input channel
bindingService.unbindConsumers(messageBasedJobManager.getInputChannelName());
inputChannel.unsubscribe(jobMessageHandler);
// Let's gracefully shutdown executor
if (configuration.getAsyncExecutor().isActive()) {
configuration.getAsyncExecutor().shutdown();
}
} finally {
running = false;
}
}
@Override
public boolean isRunning() {
return running;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
@SuppressWarnings("unchecked")
protected <T> T registerBean(String name, T bean) {
beanFactory.registerSingleton(name, bean);
return (T) beanFactory.initializeBean(bean, name);
}
}
16
Source : MessageBrokerBeanDefinitionParserTests.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
private void testChannel(String channelName, List<Clreplaced<? extends MessageHandler>> subscriberTypes, int interceptorCount) {
AbstractSubscribableChannel channel = this.appContext.getBean(channelName, AbstractSubscribableChannel.clreplaced);
for (Clreplaced<? extends MessageHandler> subscriberType : subscriberTypes) {
MessageHandler subscriber = this.appContext.getBean(subscriberType);
replacedertNotNull("No subscription for " + subscriberType, subscriber);
replacedertTrue(channel.hreplacedubscription(subscriber));
}
List<ChannelInterceptor> interceptors = channel.getInterceptors();
replacedertEquals(interceptorCount, interceptors.size());
replacedertEquals(ImmutableMessageChannelInterceptor.clreplaced, interceptors.get(interceptors.size() - 1).getClreplaced());
}
16
Source : MessageBrokerBeanDefinitionParserTests.java
with Apache License 2.0
from SourceHot
with Apache License 2.0
from SourceHot
private void testChannel(String channelName, List<Clreplaced<? extends MessageHandler>> subscriberTypes, int interceptorCount) {
AbstractSubscribableChannel channel = this.appContext.getBean(channelName, AbstractSubscribableChannel.clreplaced);
for (Clreplaced<? extends MessageHandler> subscriberType : subscriberTypes) {
MessageHandler subscriber = this.appContext.getBean(subscriberType);
replacedertThat(subscriber).as("No subscription for " + subscriberType).isNotNull();
replacedertThat(channel.hreplacedubscription(subscriber)).isTrue();
}
List<ChannelInterceptor> interceptors = channel.getInterceptors();
replacedertThat(interceptors.size()).isEqualTo(interceptorCount);
replacedertThat(interceptors.get(interceptors.size() - 1).getClreplaced()).isEqualTo(ImmutableMessageChannelInterceptor.clreplaced);
}
16
Source : SofaTracerChannelInterceptor.java
with Apache License 2.0
from sofastack
with Apache License 2.0
from sofastack
@Override
public Message<?> beforeHandle(Message<?> message, MessageChannel channel, MessageHandler handler) {
if (emptyMessage(message)) {
return message;
}
MessageHeaderAccessor headers = mutableHeaderAccessor(message);
if (message instanceof ErrorMessage) {
return new ErrorMessage((Throwable) message.getPayload(), headers.getMessageHeaders());
}
headers.setImmutable();
return new GenericMessage<>(message.getPayload(), headers.getMessageHeaders());
}
16
Source : OpenTracingChannelInterceptor.java
with Apache License 2.0
from opentracing-contrib
with Apache License 2.0
from opentracing-contrib
@Override
public Message<?> beforeHandle(Message<?> message, MessageChannel channel, MessageHandler handler) {
Span span = tracer.activeSpan();
log.trace(String.format("Continuing span %s before handling message", span));
return message;
}
16
Source : OpenTracingChannelInterceptor.java
with Apache License 2.0
from opentracing-contrib
with Apache License 2.0
from opentracing-contrib
@Override
public void afterMessageHandled(Message<?> message, MessageChannel channel, MessageHandler handler, Exception ex) {
Span span = tracer.activeSpan();
log.trace(String.format("Continuing span %s after message handled", span));
if (span == null) {
return;
}
handleException(ex, span);
}
16
Source : MessageBrokerBeanDefinitionParserTests.java
with Apache License 2.0
from langtianya
with Apache License 2.0
from langtianya
private void testChannel(String channelName, List<Clreplaced<? extends MessageHandler>> subscriberTypes, int interceptorCount) {
AbstractSubscribableChannel channel = this.appContext.getBean(channelName, AbstractSubscribableChannel.clreplaced);
for (Clreplaced<? extends MessageHandler> subscriberType : subscriberTypes) {
MessageHandler subscriber = this.appContext.getBean(subscriberType);
replacedertNotNull("No subsription for " + subscriberType, subscriber);
replacedertTrue(channel.hreplacedubscription(subscriber));
}
List<ChannelInterceptor> interceptors = channel.getInterceptors();
replacedertEquals(interceptorCount, interceptors.size());
replacedertEquals(ImmutableMessageChannelInterceptor.clreplaced, interceptors.get(interceptors.size() - 1).getClreplaced());
}
16
Source : QueueMessageHandlerTest.java
with Apache License 2.0
from awspring
with Apache License 2.0
from awspring
@Test
void receiveMessage_methodWithSqsMessageAsParameter_parameterIsConverted() {
new ApplicationContextRunner().withConfiguration(UserConfigurations.of(QueueMessageHandlerWithJacksonMappingConfiguration.clreplaced)).withBean(IncomingMessageHandlerWithSqsMessageParameter.clreplaced).run((context) -> {
Map<String, MessageAttributeValue> attributes = new HashMap<>();
attributes.put(QueueMessageHandler.LOGICAL_RESOURCE_ID, new MessageAttributeValue().withStringValue("testQueue").withDataType(MessageAttributeDataTypes.STRING));
Message<?> message = QueueMessageUtils.createMessage(new com.amazonaws.services.sqs.model.Message().withBody("message body").withMessageAttributes(attributes));
MessageHandler messageHandler = context.getBean(MessageHandler.clreplaced);
messageHandler.handleMessage(message);
IncomingMessageHandlerWithSqsMessageParameter messageListener = context.getBean(IncomingMessageHandlerWithSqsMessageParameter.clreplaced);
replacedertThat(messageListener.getLastReceivedMessage()).isNotNull();
replacedertThat(messageListener.getLastReceivedMessage().getBody()).isEqualTo("message body");
});
}
16
Source : QueueMessageHandlerTest.java
with Apache License 2.0
from awspring
with Apache License 2.0
from awspring
@Test
void receiveMessage_methodAnnotatedWithSqsListenerAnnotation_methodInvokedForIncomingMessage() {
StaticApplicationContext applicationContext = new StaticApplicationContext();
applicationContext.registerSingleton("incomingMessageHandler", IncomingMessageHandler.clreplaced);
applicationContext.registerSingleton("queueMessageHandler", QueueMessageHandler.clreplaced);
applicationContext.refresh();
MessageHandler messageHandler = applicationContext.getBean(MessageHandler.clreplaced);
messageHandler.handleMessage(MessageBuilder.withPayload("testContent").setHeader(QueueMessageHandler.LOGICAL_RESOURCE_ID, "receive").build());
IncomingMessageHandler messageListener = applicationContext.getBean(IncomingMessageHandler.clreplaced);
replacedertThat(messageListener.getLastReceivedMessage()).isEqualTo("testContent");
}
15
Source : GenericMessagingTemplateTests.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
private MessageHandler createLateReplier(final CountDownLatch latch, final AtomicReference<Throwable> failure) {
MessageHandler handler = message -> {
try {
Thread.sleep(500);
MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel();
replyChannel.send(new GenericMessage<>("response"));
failure.set(new IllegalStateException("Expected exception"));
} catch (InterruptedException e) {
failure.set(e);
} catch (MessageDeliveryException ex) {
String expected = "Reply message received but the receiving thread has exited due to a timeout";
String actual = ex.getMessage();
if (!expected.equals(actual)) {
failure.set(new IllegalStateException("Unexpected error: '" + actual + "'"));
}
} finally {
latch.countDown();
}
};
return handler;
}
14
Source : RqueueMessageHandlerTest.java
with Apache License 2.0
from sonus21
with Apache License 2.0
from sonus21
@Test
void methodHavingSpelGettingEvaluated() {
StaticApplicationContext applicationContext = new StaticApplicationContext();
applicationContext.registerSingleton("spelMessageHandler", SpelMessageHandler.clreplaced);
applicationContext.registerSingleton("rqueueMessageHandler", RqueueMessageHandler.clreplaced);
applicationContext.refresh();
MessageHandler messageHandler = applicationContext.getBean(MessageHandler.clreplaced);
SpelMessageHandler messageListener = applicationContext.getBean(SpelMessageHandler.clreplaced);
messageHandler.handleMessage(buildMessage(slowQueue, message));
replacedertEquals(message, messageListener.getLastReceivedMessage());
messageListener.setLastReceivedMessage(null);
messageHandler.handleMessage(buildMessage(smartQueue, message + message));
replacedertEquals(message + message, messageListener.getLastReceivedMessage());
}
14
Source : RqueueMessageHandlerTest.java
with Apache License 2.0
from sonus21
with Apache License 2.0
from sonus21
@Test
void methodHavingNameFromPropertyFileWithExpression() {
StaticApplicationContext applicationContext = new StaticApplicationContext();
applicationContext.registerSingleton("messageHandler", MessageHandlerWithExpressionProperty.clreplaced);
applicationContext.registerSingleton("rqueueMessageHandler", RqueueMessageHandler.clreplaced);
applicationContext.getEnvironment().getPropertySources().addLast(new MapPropertySource("test", Collections.singletonMap("queueName", slowQueue)));
applicationContext.registerSingleton("ppc", PropertySourcesPlaceholderConfigurer.clreplaced);
applicationContext.refresh();
MessageHandler messageHandler = applicationContext.getBean(MessageHandler.clreplaced);
MessageHandlerWithExpressionProperty messageListener = applicationContext.getBean(MessageHandlerWithExpressionProperty.clreplaced);
messageHandler.handleMessage(buildMessage(slowQueue, message));
replacedertEquals(message, messageListener.getLastReceivedMessage());
}
14
Source : RqueueMessageHandlerTest.java
with Apache License 2.0
from sonus21
with Apache License 2.0
from sonus21
@Test
void methodWithStringParameterIsInvoked() {
StaticApplicationContext applicationContext = new StaticApplicationContext();
applicationContext.registerSingleton("incomingMessageHandler", IncomingMessageHandler.clreplaced);
applicationContext.registerSingleton("rqueueMessageHandler", RqueueMessageHandler.clreplaced);
applicationContext.refresh();
MessageHandler messageHandler = applicationContext.getBean(MessageHandler.clreplaced);
messageHandler.handleMessage(buildMessage(testQueue, message));
IncomingMessageHandler messageListener = applicationContext.getBean(IncomingMessageHandler.clreplaced);
replacedertEquals(message, messageListener.getLastReceivedMessage());
}
14
Source : RqueueMessageHandlerTest.java
with Apache License 2.0
from sonus21
with Apache License 2.0
from sonus21
@Test
void methodHavingMultipleQueueNames() {
StaticApplicationContext applicationContext = new StaticApplicationContext();
applicationContext.registerSingleton("incomingMessageHandler", IncomingMessageHandler.clreplaced);
applicationContext.registerSingleton("rqueueMessageHandler", RqueueMessageHandler.clreplaced);
applicationContext.refresh();
MessageHandler messageHandler = applicationContext.getBean(MessageHandler.clreplaced);
IncomingMessageHandler messageListener = applicationContext.getBean(IncomingMessageHandler.clreplaced);
messageListener.setExceptionHandlerCalled(false);
messageHandler.handleMessage(buildMessage(slowQueue, message));
replacedertEquals(message, messageListener.getLastReceivedMessage());
messageListener.setLastReceivedMessage(null);
messageHandler.handleMessage(buildMessage(smartQueue, message + message));
replacedertEquals(message + message, messageListener.getLastReceivedMessage());
}
14
Source : RqueueMessageHandlerTest.java
with Apache License 2.0
from sonus21
with Apache License 2.0
from sonus21
@Test
void methodWithMessagePayloadParameterIsInvoked() {
StaticApplicationContext applicationContext = new StaticApplicationContext();
applicationContext.registerSingleton("incomingMessageHandler", IncomingMessageHandler.clreplaced);
applicationContext.registerSingleton("rqueueMessageHandler", RqueueMessageHandler.clreplaced);
applicationContext.refresh();
MessageHandler messageHandler = applicationContext.getBean(MessageHandler.clreplaced);
messageHandler.handleMessage(buildMessage(messagePayloadQueue, payloadConvertedMessage));
IncomingMessageHandler messageListener = applicationContext.getBean(IncomingMessageHandler.clreplaced);
replacedertEquals(messagePayload, messageListener.getLastReceivedMessage());
}
14
Source : RqueueMessageHandlerTest.java
with Apache License 2.0
from sonus21
with Apache License 2.0
from sonus21
@Test
void methodWithStringParameterCallExceptionHandler() {
StaticApplicationContext applicationContext = new StaticApplicationContext();
applicationContext.registerSingleton("incomingMessageHandler", IncomingMessageHandler.clreplaced);
applicationContext.registerSingleton("rqueueMessageHandler", RqueueMessageHandler.clreplaced);
applicationContext.refresh();
MessageHandler messageHandler = applicationContext.getBean(MessageHandler.clreplaced);
IncomingMessageHandler messageListener = applicationContext.getBean(IncomingMessageHandler.clreplaced);
messageListener.setExceptionHandlerCalled(false);
try {
messageHandler.handleMessage(buildMessage(exceptionQueue, message));
} catch (Exception e) {
// ignore
}
replacedertTrue(messageListener.isExceptionHandlerCalled());
replacedertEquals(message, messageListener.getLastReceivedMessage());
}
14
Source : QueueMessageHandlerTest.java
with Apache License 2.0
from awspring
with Apache License 2.0
from awspring
@Test
void receiveAndReplayMessage_withExceptionThrownInSendTo_shouldCallExceptionHandler() {
// Arrange
StaticApplicationContext applicationContext = new StaticApplicationContext();
applicationContext.registerSingleton("incomingMessageHandler", IncomingMessageHandler.clreplaced);
applicationContext.registerBeanDefinition("queueMessageHandler", getQueueMessageHandlerBeanDefinition());
applicationContext.refresh();
MessageHandler messageHandler = applicationContext.getBean(MessageHandler.clreplaced);
doThrow(new RuntimeException()).when(this.messageTemplate).convertAndSend(anyString(), Optional.ofNullable(any()));
IncomingMessageHandler messageListener = applicationContext.getBean(IncomingMessageHandler.clreplaced);
messageListener.setExceptionHandlerCalled(false);
// Act
try {
messageHandler.handleMessage(MessageBuilder.withPayload("testContent").setHeader(QueueMessageHandler.LOGICAL_RESOURCE_ID, "receiveAndReply").build());
} catch (MessagingException e) {
// ignore
}
// replacedert
replacedertThat(messageListener.isExceptionHandlerCalled()).isTrue();
}
13
Source : RqueueMessageHandlerTest.java
with Apache License 2.0
from sonus21
with Apache License 2.0
from sonus21
@Test
void methodHavingNameFromPropertyFile() {
StaticApplicationContext applicationContext = new StaticApplicationContext();
applicationContext.registerSingleton("messageHandler", MessageHandlersWithProperty.clreplaced);
applicationContext.registerSingleton("rqueueMessageHandler", RqueueMessageHandler.clreplaced);
Map<String, Object> map = new HashMap<>();
map.put("slow.queue.name", slowQueue);
map.put("smart.queue.name", smartQueue);
applicationContext.getEnvironment().getPropertySources().addLast(new MapPropertySource("test", map));
applicationContext.registerSingleton("ppc", PropertySourcesPlaceholderConfigurer.clreplaced);
applicationContext.refresh();
MessageHandler messageHandler = applicationContext.getBean(MessageHandler.clreplaced);
MessageHandlersWithProperty messageListener = applicationContext.getBean(MessageHandlersWithProperty.clreplaced);
messageHandler.handleMessage(buildMessage(slowQueue, message));
replacedertEquals(message, messageListener.getLastReceivedMessage());
messageListener.setLastReceivedMessage(null);
messageHandler.handleMessage(buildMessage(smartQueue, message + message));
replacedertEquals(message + message, messageListener.getLastReceivedMessage());
}
13
Source : TracingChannelInterceptorTest.java
with Apache License 2.0
from opentracing-contrib
with Apache License 2.0
from opentracing-contrib
@Test
public void testAfterMessageHandled() {
Span span = mock(Span.clreplaced);
Scope scope = mock(Scope.clreplaced);
MessageHandler messageHandler = mock(WebSocketAnnotationMethodMessageHandler.clreplaced);
MessageBuilder<String> messageBuilder = MessageBuilder.withPayload("Hi").setHeader(TracingChannelInterceptor.SIMP_MESSAGE_TYPE, SimpMessageType.MESSAGE).setHeader(TracingChannelInterceptor.SIMP_DESTINATION, TEST_DESTINATION).setHeader(TracingChannelInterceptor.OPENTRACING_SCOPE, scope).setHeader(TracingChannelInterceptor.OPENTRACING_SPAN, span);
TracingChannelInterceptor interceptor = new TracingChannelInterceptor(mockTracer, Tags.SPAN_KIND_CLIENT);
interceptor.afterMessageHandled(messageBuilder.build(), null, messageHandler, null);
// Verify span is finished and scope is closed
verify(span).finish();
verify(scope).close();
}
12
Source : KinesisBinderTests.java
with Apache License 2.0
from spring-cloud
with Apache License 2.0
from spring-cloud
@Test
@Override
public void testParreplacedionedModuleJava() throws Exception {
KinesisTestBinder binder = getBinder();
ExtendedConsumerProperties<KinesisConsumerProperties> consumerProperties = createConsumerProperties();
consumerProperties.setConcurrency(2);
consumerProperties.setInstanceCount(3);
consumerProperties.setInstanceIndex(0);
consumerProperties.setParreplacedioned(true);
final List<Message<?>> results = new ArrayList<>();
final CountDownLatch receiveLatch = new CountDownLatch(3);
MessageHandler receivingHandler = (message) -> {
results.add(message);
receiveLatch.countDown();
};
DirectChannel input0 = createBindableChannelInternal("test.input0J", new BindingProperties(), true);
input0.subscribe(receivingHandler);
Binding<MessageChannel> input0Binding = binder.bindConsumer("partJ.0", "testParreplacedionedModuleJava", input0, consumerProperties);
consumerProperties.setInstanceIndex(1);
DirectChannel input1 = createBindableChannelInternal("test.input1J", new BindingProperties(), true);
input1.subscribe(receivingHandler);
Binding<MessageChannel> input1Binding = binder.bindConsumer("partJ.0", "testParreplacedionedModuleJava", input1, consumerProperties);
consumerProperties.setInstanceIndex(2);
DirectChannel input2 = createBindableChannelInternal("test.input2J", new BindingProperties(), true);
input2.subscribe(receivingHandler);
Binding<MessageChannel> input2Binding = binder.bindConsumer("partJ.0", "testParreplacedionedModuleJava", input2, consumerProperties);
ExtendedProducerProperties<KinesisProducerProperties> producerProperties = createProducerProperties();
producerProperties.setParreplacedionKeyExtractorName("parreplacedionSupport");
producerProperties.setParreplacedionSelectorName("parreplacedionSupport");
producerProperties.setParreplacedionCount(3);
DirectChannel output = createBindableChannelInternal("test.output", createProducerBindingProperties(producerProperties), false);
Binding<MessageChannel> outputBinding = binder.bindProducer("partJ.0", output, producerProperties);
if (usesExplicitRouting()) {
Object endpoint = extractEndpoint(outputBinding);
replacedertThat(getEndpointRouting(endpoint)).contains(getExpectedRoutingBaseDestination("partJ.0", "testParreplacedionedModuleJava") + "-' + headers['" + BinderHeaders.PARreplacedION_HEADER + "']");
}
output.send(new GenericMessage<>(2));
output.send(new GenericMessage<>(1));
output.send(new GenericMessage<>(0));
replacedertThat(receiveLatch.await(20, TimeUnit.SECONDS)).isTrue();
replacedertThat(results).extracting("payload").containsExactlyInAnyOrder("0".getBytes(), "1".getBytes(), "2".getBytes());
input0Binding.unbind();
input1Binding.unbind();
input2Binding.unbind();
outputBinding.unbind();
}
11
Source : GenericMessagingTemplateTests.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
@Test
public void sendAndReceiveTimeout() throws InterruptedException {
final AtomicReference<Throwable> failure = new AtomicReference<Throwable>();
final CountDownLatch latch = new CountDownLatch(1);
this.template.setReceiveTimeout(1);
this.template.setSendTimeout(30_000L);
this.template.setThrowExceptionOnLateReply(true);
SubscribableChannel channel = mock(SubscribableChannel.clreplaced);
MessageHandler handler = createLateReplier(latch, failure);
willAnswer(invocation -> {
this.executor.execute(() -> handler.handleMessage(invocation.getArgument(0)));
return true;
}).given(channel).send(any(Message.clreplaced), anyLong());
replacedertNull(this.template.convertSendAndReceive(channel, "request", String.clreplaced));
replacedertTrue(latch.await(10_000, TimeUnit.MILLISECONDS));
Throwable ex = failure.get();
if (ex != null) {
throw new replacedertionError(ex);
}
verify(channel).send(any(Message.clreplaced), eq(30_000L));
}
11
Source : PubSubInboundChannelAdapterTests.java
with Apache License 2.0
from spring-cloud
with Apache License 2.0
from spring-cloud
@Test
public void testAckModeAuto_nacksWhenDownstreamProcessingFailsWhenContextShutdown() {
this.adapter.setAckMode(AckMode.AUTO);
this.adapter.setOutputChannel(this.mockMessageChannel);
PublishSubscribeChannel errorChannel = new PublishSubscribeChannel();
// Simulating what FinalRethrowingErrorMessageHandler would do.
MessageHandler errorHandler = message -> {
throw new RuntimeException("error channel fails, too");
};
errorChannel.subscribe(errorHandler);
ServiceActivatingHandler handler = new ServiceActivatingHandler(msg -> {
throw new RuntimeException("error handling failed");
});
handler.setBeanFactory(this.context);
handler.afterPropertiesSet();
this.adapter.setErrorChannel(errorChannel);
when(this.mockMessageChannel.send(any())).then(input -> {
errorChannel.unsubscribe(errorHandler);
this.adapter.stop();
throw new RuntimeException(EXCEPTION_MESSAGE);
});
this.adapter.start();
verify(mockAcknowledgeableMessage).nack();
verify(mockAcknowledgeableMessage, times(0)).ack();
replacedertThat(output.getOut()).contains("failed; message nacked automatically");
// original message handling exception
replacedertThat(output.getOut()).contains(EXCEPTION_MESSAGE);
}
11
Source : GenericMessagingTemplateTests.java
with Apache License 2.0
from SourceHot
with Apache License 2.0
from SourceHot
@Test
public void sendAndReceiveTimeout() throws InterruptedException {
final AtomicReference<Throwable> failure = new AtomicReference<Throwable>();
final CountDownLatch latch = new CountDownLatch(1);
this.template.setReceiveTimeout(1);
this.template.setSendTimeout(30_000L);
this.template.setThrowExceptionOnLateReply(true);
SubscribableChannel channel = mock(SubscribableChannel.clreplaced);
MessageHandler handler = createLateReplier(latch, failure);
willAnswer(invocation -> {
this.executor.execute(() -> handler.handleMessage(invocation.getArgument(0)));
return true;
}).given(channel).send(any(Message.clreplaced), anyLong());
replacedertThat(this.template.convertSendAndReceive(channel, "request", String.clreplaced)).isNull();
replacedertThat(latch.await(10_000, TimeUnit.MILLISECONDS)).isTrue();
Throwable ex = failure.get();
if (ex != null) {
throw new replacedertionError(ex);
}
verify(channel).send(any(Message.clreplaced), eq(30_000L));
}
11
Source : GenericMessagingTemplateTests.java
with MIT License
from mindcarver
with MIT License
from mindcarver
@Test
public void sendAndReceiveTimeout() throws InterruptedException {
final AtomicReference<Throwable> failure = new AtomicReference<Throwable>();
final CountDownLatch latch = new CountDownLatch(1);
this.template.setReceiveTimeout(1);
this.template.setSendTimeout(30_000L);
this.template.setThrowExceptionOnLateReply(true);
SubscribableChannel channel = mock(SubscribableChannel.clreplaced);
MessageHandler handler = createLateReplier(latch, failure);
doAnswer(invocation -> {
this.executor.execute(() -> {
handler.handleMessage(invocation.getArgument(0));
});
return true;
}).when(channel).send(any(Message.clreplaced), anyLong());
replacedertNull(this.template.convertSendAndReceive(channel, "request", String.clreplaced));
replacedertTrue(latch.await(10_000, TimeUnit.MILLISECONDS));
Throwable ex = failure.get();
if (ex != null) {
throw new replacedertionError(ex);
}
verify(channel).send(any(Message.clreplaced), eq(30_000L));
}
9
Source : GenericMessagingTemplateTests.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
@Test
public void sendAndReceiveVariableTimeoutCustomHeaders() throws InterruptedException {
final AtomicReference<Throwable> failure = new AtomicReference<Throwable>();
final CountDownLatch latch = new CountDownLatch(1);
this.template.setSendTimeout(20_000);
this.template.setReceiveTimeout(10_000);
this.template.setThrowExceptionOnLateReply(true);
this.template.setSendTimeoutHeader("sto");
this.template.setReceiveTimeoutHeader("rto");
SubscribableChannel channel = mock(SubscribableChannel.clreplaced);
MessageHandler handler = createLateReplier(latch, failure);
willAnswer(invocation -> {
this.executor.execute(() -> handler.handleMessage(invocation.getArgument(0)));
return true;
}).given(channel).send(any(Message.clreplaced), anyLong());
Message<?> message = MessageBuilder.withPayload("request").setHeader("sto", 30_000L).setHeader("rto", 1L).build();
replacedertNull(this.template.sendAndReceive(channel, message));
replacedertTrue(latch.await(10_000, TimeUnit.MILLISECONDS));
Throwable ex = failure.get();
if (ex != null) {
throw new replacedertionError(ex);
}
verify(channel).send(any(Message.clreplaced), eq(30_000L));
}
See More Examples