use of org.springframework.integration.handler.AbstractReplyProducingMessageHandler in project spring-cloud-stream by spring-cloud.
the class StreamListenerAnnotationBeanPostProcessor method afterSingletonsInstantiated.
@Override
public final void afterSingletonsInstantiated() {
this.injectAndPostProcessDependencies();
EvaluationContext evaluationContext = IntegrationContextUtils.getEvaluationContext(this.applicationContext.getBeanFactory());
for (Map.Entry<String, List<StreamListenerHandlerMethodMapping>> mappedBindingEntry : mappedListenerMethods.entrySet()) {
ArrayList<DispatchingStreamListenerMessageHandler.ConditionalStreamListenerMessageHandlerWrapper> handlers = new ArrayList<>();
for (StreamListenerHandlerMethodMapping mapping : mappedBindingEntry.getValue()) {
final InvocableHandlerMethod invocableHandlerMethod = this.messageHandlerMethodFactory.createInvocableHandlerMethod(mapping.getTargetBean(), checkProxy(mapping.getMethod(), mapping.getTargetBean()));
StreamListenerMessageHandler streamListenerMessageHandler = new StreamListenerMessageHandler(invocableHandlerMethod, resolveExpressionAsBoolean(mapping.getCopyHeaders(), "copyHeaders"), springIntegrationProperties.getMessageHandlerNotPropagatedHeaders());
streamListenerMessageHandler.setApplicationContext(this.applicationContext);
streamListenerMessageHandler.setBeanFactory(this.applicationContext.getBeanFactory());
if (StringUtils.hasText(mapping.getDefaultOutputChannel())) {
streamListenerMessageHandler.setOutputChannelName(mapping.getDefaultOutputChannel());
}
streamListenerMessageHandler.afterPropertiesSet();
if (StringUtils.hasText(mapping.getCondition())) {
String conditionAsString = resolveExpressionAsString(mapping.getCondition(), "condition");
Expression condition = SPEL_EXPRESSION_PARSER.parseExpression(conditionAsString);
handlers.add(new DispatchingStreamListenerMessageHandler.ConditionalStreamListenerMessageHandlerWrapper(condition, streamListenerMessageHandler));
} else {
handlers.add(new DispatchingStreamListenerMessageHandler.ConditionalStreamListenerMessageHandlerWrapper(null, streamListenerMessageHandler));
}
}
if (handlers.size() > 1) {
for (DispatchingStreamListenerMessageHandler.ConditionalStreamListenerMessageHandlerWrapper handler : handlers) {
Assert.isTrue(handler.isVoid(), StreamListenerErrorMessages.MULTIPLE_VALUE_RETURNING_METHODS);
}
}
AbstractReplyProducingMessageHandler handler;
if (handlers.size() > 1 || handlers.get(0).getCondition() != null) {
handler = new DispatchingStreamListenerMessageHandler(handlers, evaluationContext);
} else {
handler = handlers.get(0).getStreamListenerMessageHandler();
}
handler.setApplicationContext(this.applicationContext);
handler.setChannelResolver(this.binderAwareChannelResolver);
handler.afterPropertiesSet();
this.applicationContext.getBeanFactory().registerSingleton(handler.getClass().getSimpleName() + handler.hashCode(), handler);
applicationContext.getBean(mappedBindingEntry.getKey(), SubscribableChannel.class).subscribe(handler);
}
this.mappedListenerMethods.clear();
}
use of org.springframework.integration.handler.AbstractReplyProducingMessageHandler in project spring-integration-samples by spring-projects.
the class TcpServerCustomSerializerTest method testHappyPath.
@Test
public void testHappyPath() {
// add a listener to this channel, otherwise there is not one defined
// the reason we use a listener here is so we can assert truths on the
// message and/or payload
SubscribableChannel channel = (SubscribableChannel) incomingServerChannel;
channel.subscribe(new AbstractReplyProducingMessageHandler() {
@Override
protected Object handleRequestMessage(Message<?> requestMessage) {
CustomOrder payload = (CustomOrder) requestMessage.getPayload();
// we assert during the processing of the messaging that the
// payload is just the content we wanted to send without the
// framing bytes (STX/ETX)
assertEquals(123, payload.getNumber());
assertEquals("PINGPONG02", payload.getSender());
assertEquals("You got it to work!", payload.getMessage());
return requestMessage;
}
});
String sourceMessage = "123PINGPONG02000019You got it to work!";
// use the java socket API to make the connection to the server
Socket socket = null;
Writer out = null;
BufferedReader in = null;
try {
socket = new Socket("localhost", this.serverConnectionFactory.getPort());
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
out.write(sourceMessage);
out.flush();
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
StringBuffer str = new StringBuffer();
int c;
while ((c = in.read()) != -1) {
str.append((char) c);
}
String response = str.toString();
assertEquals(sourceMessage, response);
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
fail(String.format("Test (port: %s) ended with an exception: %s", this.serverConnectionFactory.getPort(), e.getMessage()));
} finally {
try {
socket.close();
out.close();
in.close();
} catch (Exception e) {
// swallow exception
}
}
}
use of org.springframework.integration.handler.AbstractReplyProducingMessageHandler in project spring-integration by spring-projects.
the class AdvisedMessageHandlerTests method successFailureAdvice.
@Test
public void successFailureAdvice() {
final AtomicBoolean doFail = new AtomicBoolean();
AbstractReplyProducingMessageHandler handler = new AbstractReplyProducingMessageHandler() {
@Override
protected Object handleRequestMessage(Message<?> requestMessage) {
if (doFail.get()) {
throw new RuntimeException("qux");
}
return "baz";
}
};
String componentName = "testComponentName";
handler.setComponentName(componentName);
QueueChannel replies = new QueueChannel();
handler.setOutputChannel(replies);
Message<String> message = new GenericMessage<String>("Hello, world!");
// no advice
handler.handleMessage(message);
Message<?> reply = replies.receive(1000);
assertNotNull(reply);
assertEquals("baz", reply.getPayload());
PollableChannel successChannel = new QueueChannel();
PollableChannel failureChannel = new QueueChannel();
ExpressionEvaluatingRequestHandlerAdvice advice = new ExpressionEvaluatingRequestHandlerAdvice();
advice.setBeanFactory(mock(BeanFactory.class));
advice.setSuccessChannel(successChannel);
advice.setFailureChannel(failureChannel);
advice.setOnSuccessExpressionString("'foo'");
advice.setOnFailureExpressionString("'bar:' + #exception.message");
List<Advice> adviceChain = new ArrayList<Advice>();
adviceChain.add(advice);
final AtomicReference<String> compName = new AtomicReference<String>();
adviceChain.add(new AbstractRequestHandlerAdvice() {
@Override
protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) throws Exception {
compName.set(((AbstractReplyProducingMessageHandler.RequestHandler) target).getAdvisedHandler().getComponentName());
return callback.execute();
}
});
handler.setAdviceChain(adviceChain);
handler.setBeanFactory(mock(BeanFactory.class));
handler.afterPropertiesSet();
// advice with success
handler.handleMessage(message);
reply = replies.receive(1000);
assertNotNull(reply);
assertEquals("baz", reply.getPayload());
assertEquals(componentName, compName.get());
Message<?> success = successChannel.receive(1000);
assertNotNull(success);
assertEquals("Hello, world!", ((AdviceMessage<?>) success).getInputMessage().getPayload());
assertEquals("foo", success.getPayload());
// advice with failure, not trapped
doFail.set(true);
try {
handler.handleMessage(message);
fail("Expected exception");
} catch (Exception e) {
assertEquals("qux", e.getCause().getMessage());
}
Message<?> failure = failureChannel.receive(1000);
assertNotNull(failure);
assertEquals("Hello, world!", ((MessagingException) failure.getPayload()).getFailedMessage().getPayload());
assertEquals("bar:qux", ((MessageHandlingExpressionEvaluatingAdviceException) failure.getPayload()).getEvaluationResult());
// advice with failure, trapped
advice.setTrapException(true);
handler.handleMessage(message);
failure = failureChannel.receive(1000);
assertNotNull(failure);
assertEquals("Hello, world!", ((MessagingException) failure.getPayload()).getFailedMessage().getPayload());
assertEquals("bar:qux", ((MessageHandlingExpressionEvaluatingAdviceException) failure.getPayload()).getEvaluationResult());
assertNull(replies.receive(1));
// advice with failure, eval is result
advice.setReturnFailureExpressionResult(true);
handler.handleMessage(message);
failure = failureChannel.receive(1000);
assertNotNull(failure);
assertEquals("Hello, world!", ((MessagingException) failure.getPayload()).getFailedMessage().getPayload());
assertEquals("bar:qux", ((MessageHandlingExpressionEvaluatingAdviceException) failure.getPayload()).getEvaluationResult());
reply = replies.receive(1000);
assertNotNull(reply);
assertEquals("bar:qux", reply.getPayload());
}
use of org.springframework.integration.handler.AbstractReplyProducingMessageHandler in project spring-integration by spring-projects.
the class AdvisedMessageHandlerTests method testInt2943RetryWithExceptionClassifier.
private void testInt2943RetryWithExceptionClassifier(boolean retryForMyException, int expected) {
final AtomicInteger counter = new AtomicInteger(0);
@SuppressWarnings("serial")
class MyException extends RuntimeException {
}
AbstractReplyProducingMessageHandler handler = new AbstractReplyProducingMessageHandler() {
@Override
protected Object handleRequestMessage(Message<?> requestMessage) {
counter.incrementAndGet();
throw new MyException();
}
};
QueueChannel replies = new QueueChannel();
handler.setOutputChannel(replies);
RequestHandlerRetryAdvice advice = new RequestHandlerRetryAdvice();
RetryTemplate retryTemplate = new RetryTemplate();
Map<Class<? extends Throwable>, Boolean> retryableExceptions = new HashMap<Class<? extends Throwable>, Boolean>();
retryableExceptions.put(MyException.class, retryForMyException);
retryableExceptions.put(MessagingException.class, true);
retryTemplate.setRetryPolicy(new SimpleRetryPolicy(3, retryableExceptions));
advice.setRetryTemplate(retryTemplate);
List<Advice> adviceChain = new ArrayList<Advice>();
adviceChain.add(advice);
handler.setAdviceChain(adviceChain);
handler.setBeanFactory(mock(BeanFactory.class));
handler.afterPropertiesSet();
Message<String> message = new GenericMessage<String>("Hello, world!");
try {
handler.handleMessage(message);
fail("MessagingException expected.");
} catch (Exception e) {
assertThat(e, Matchers.instanceOf(MessagingException.class));
assertThat(e.getCause(), Matchers.instanceOf(MyException.class));
}
assertEquals(expected, counter.get());
}
use of org.springframework.integration.handler.AbstractReplyProducingMessageHandler in project spring-integration by spring-projects.
the class AdvisedMessageHandlerTests method errorMessageSendingRecovererTestsNoThrowable.
@Test
public void errorMessageSendingRecovererTestsNoThrowable() {
AbstractReplyProducingMessageHandler handler = new AbstractReplyProducingMessageHandler() {
@Override
protected Object handleRequestMessage(Message<?> requestMessage) {
throw new RuntimeException("fooException");
}
};
QueueChannel errors = new QueueChannel();
RequestHandlerRetryAdvice advice = new RequestHandlerRetryAdvice();
ErrorMessageSendingRecoverer recoverer = new ErrorMessageSendingRecoverer(errors);
advice.setRecoveryCallback(recoverer);
RetryTemplate retryTemplate = new RetryTemplate();
retryTemplate.setRetryPolicy(new SimpleRetryPolicy() {
static final long serialVersionUID = -1;
@Override
public boolean canRetry(RetryContext context) {
return false;
}
});
advice.setRetryTemplate(retryTemplate);
advice.setBeanFactory(mock(BeanFactory.class));
advice.afterPropertiesSet();
List<Advice> adviceChain = new ArrayList<Advice>();
adviceChain.add(advice);
handler.setAdviceChain(adviceChain);
handler.setBeanFactory(mock(BeanFactory.class));
handler.afterPropertiesSet();
Message<String> message = new GenericMessage<String>("Hello, world!");
handler.handleMessage(message);
Message<?> error = errors.receive(10000);
assertNotNull(error);
assertTrue(error.getPayload() instanceof ErrorMessageSendingRecoverer.RetryExceptionNotAvailableException);
assertNotNull(((MessagingException) error.getPayload()).getFailedMessage());
assertSame(message, ((MessagingException) error.getPayload()).getFailedMessage());
}
Aggregations