public void write(List<? extends T> items) throws Exception { // Block until expecting <= throttle limit while (localState.getExpecting() > throttleLimit) { getNextResult(); } if (!items.isEmpty()) { ChunkRequest<T> request = localState.getRequest(items); if (logger.isDebugEnabled()) { logger.debug("Dispatching chunk: " + request); } messagingGateway.send(new GenericMessage<>(request)); localState.incrementExpected(); } }
/** * Sends {@link StepExecutionRequest} objects to the request channel of the {@link MessagingTemplate}, and then * receives the result back as a list of {@link StepExecution} on a reply channel. Use the {@link #aggregate(List)} * method as an aggregator of the individual remote replies. The receive timeout needs to be set realistically in * the {@link MessagingTemplate} <b>and</b> the aggregator, so that there is a good chance of all work being done. * * @see PartitionHandler#handle(StepExecutionSplitter, StepExecution) */ public Collection<StepExecution> handle(StepExecutionSplitter stepExecutionSplitter, final StepExecution masterStepExecution) throws Exception { final Set<StepExecution> split = stepExecutionSplitter.split(masterStepExecution, gridSize); if(CollectionUtils.isEmpty(split)) { return split; } int count = 0; for (StepExecution stepExecution : split) { Message<StepExecutionRequest> request = createMessage(count++, split.size(), new StepExecutionRequest( stepName, stepExecution.getJobExecutionId(), stepExecution.getId()), replyChannel); if (logger.isDebugEnabled()) { logger.debug("Sending request: " + request); } messagingGateway.send(request); } if(!pollRepositoryForResults) { return receiveReplies(replyChannel); } else { return pollReplies(masterStepExecution, split); } }
verify(operations, times(3)).send(any(Message.class));
private boolean doSend(MessageChannel channel, final Message<?> messageToSend) { try { this.messagingTemplate.send(channel, messageToSend); return true; } catch (MessagingException e) { if (!this.ignoreSendFailures) { throw e; } this.logger.debug("Send failure ignored", e); return false; } }
private void discardMessage(Message<?> message) { this.messagingTemplate.send(getDiscardChannel(), message); }
/** * Send an error message based on the exception and message. * @param message the message. * @param exception the exception. * @return true if the error channel is available and message sent. * @since 4.3.10 */ protected final boolean sendErrorMessageIfNecessary(Message<?> message, RuntimeException exception) { MessageChannel channel = getErrorChannel(); if (channel != null) { this.messagingTemplate.send(channel, buildErrorMessage(message, exception)); return true; } return false; }
@Override public Object postProcess(Message<?> message, Object result) { if (result == null) { MessageChannel channel = getDiscardChannel(); if (channel != null) { this.messagingTemplate.send(channel, message); } if (this.throwExceptionOnRejection) { throw new MessageRejectedException(message, "MessageFilter '" + getBeanName() + "' rejected Message"); } } return result; }
/** * Publish an error message for the supplied throwable and context. * The {@link #errorMessageStrategy} is used to build a {@link ErrorMessage} * to publish. * @param throwable the throwable. May be null. * @param context the context for {@link ErrorMessage} properties. */ public void publish(Throwable throwable, AttributeAccessor context) { populateChannel(); Throwable payload = determinePayload(throwable, context); ErrorMessage errorMessage = this.errorMessageStrategy.buildErrorMessage(payload, context); if (this.logger.isDebugEnabled() && payload instanceof MessagingException) { MessagingException exception = (MessagingException) errorMessage.getPayload(); this.logger.debug("Sending ErrorMessage: failedMessage: " + exception.getFailedMessage(), exception); } this.messagingTemplate.send(errorMessage); }
protected void send(Object object) { this.initializeIfNecessary(); Assert.notNull(object, "request must not be null"); MessageChannel channel = getRequestChannel(); Assert.state(channel != null, "send is not supported, because no request channel has been configured"); try { if (this.countsEnabled) { this.messageCount.incrementAndGet(); } this.messagingTemplate.convertAndSend(channel, object, this.historyWritingPostProcessor); } catch (Exception e) { MessageChannel errorChan = getErrorChannel(); if (errorChan != null) { this.messagingTemplate.send(errorChan, new ErrorMessage(e)); } else { this.rethrow(e, "failed to send message"); } } }
private Object evaluateFailureExpression(Message<?> message, Exception exception) throws Exception { Object evalResult; try { evalResult = this.onFailureExpression.getValue(this.prepareEvaluationContextToUse(exception), message); } catch (Exception e) { evalResult = e; logger.error("Failure expression evaluation failed for " + message + ": " + e.getMessage()); } if (this.failureChannel == null && this.failureChannelName != null && getChannelResolver() != null) { this.failureChannel = getChannelResolver().resolveDestination(this.failureChannelName); } if (evalResult != null && this.failureChannel != null) { MessagingException messagingException = new MessageHandlingExpressionEvaluatingAdviceException(message, "Handler Failed", this.unwrapThrowableIfNecessary(exception), evalResult); ErrorMessage resultMessage = new ErrorMessage(messagingException); this.messagingTemplate.send(this.failureChannel, resultMessage); } return evalResult; }
private void evaluateSuccessExpression(Message<?> message) throws Exception { Object evalResult; boolean evaluationFailed = false; try { evalResult = this.onSuccessExpression.getValue(this.prepareEvaluationContextToUse(null), message); } catch (Exception e) { evalResult = e; evaluationFailed = true; } if (this.successChannel == null && this.successChannelName != null && getChannelResolver() != null) { this.successChannel = getChannelResolver().resolveDestination(this.successChannelName); } if (evalResult != null && this.successChannel != null) { AdviceMessage<?> resultMessage = new AdviceMessage<Object>(evalResult, message); this.messagingTemplate.send(this.successChannel, resultMessage); } if (evaluationFailed && this.propagateOnSuccessEvaluationFailures) { throw (Exception) evalResult; } }
private MessageHandler echoInboundStringHandler() { return message -> { assertTrue(message.getPayload() instanceof String); MessagingTemplate template = new MessagingTemplate(); template.setDefaultDestination((MessageChannel) message.getHeaders().getReplyChannel()); template.send(message); }; }
protected void sendMessage(Message<?> messageArg) { Message<?> message = messageArg; if (message == null) { throw new MessagingException("cannot send a null message"); } if (this.shouldTrack) { message = MessageHistory.write(message, this, this.getMessageBuilderFactory()); } try { this.messagingTemplate.send(getOutputChannel(), message); } catch (RuntimeException e) { if (!sendErrorMessageIfNecessary(message, e)) { throw e; } } }
private MessageHandler unwrapObjectMessageAndEchoHandler() { return message -> { assertThat(message.getPayload(), instanceOf(javax.jms.ObjectMessage.class)); MessagingTemplate template = new MessagingTemplate(); template.setDefaultDestination((MessageChannel) message.getHeaders().getReplyChannel()); Message<?> origMessage = null; try { origMessage = (Message<?>) ((javax.jms.ObjectMessage) message.getPayload()).getObject(); } catch (JMSException e) { fail("failed to deserialize message"); } template.send(origMessage); }; }
private MessageHandler unwrapTextMessageAndEchoHandler() { return message -> { assertThat(message.getPayload(), instanceOf(javax.jms.TextMessage.class)); MessagingTemplate template = new MessagingTemplate(); template.setDefaultDestination((MessageChannel) message.getHeaders().getReplyChannel()); String payload = null; try { payload = ((javax.jms.TextMessage) message.getPayload()).getText(); } catch (JMSException e) { fail("failed to deserialize message"); } template.send(new GenericMessage<String>(payload)); }; }
@Override protected void handleMessage(Message<?> messageArg) { Message<?> message = messageArg; if (this.shouldTrack) { message = MessageHistory.write(message, this, getMessageBuilderFactory()); } AcknowledgmentCallback ackCallback = StaticMessageHeaderAccessor.getAcknowledgmentCallback(message); try { this.messagingTemplate.send(getOutputChannel(), message); AckUtils.autoAck(ackCallback); } catch (Exception e) { AckUtils.autoNack(ackCallback); if (e instanceof MessagingException) { throw (MessagingException) e; } else { throw new MessagingException(message, "Failed to send Message", e); } } }
@Test public void to() throws InterruptedException { MessagingTemplate messagingTemplate = new MessagingTemplate(); CountDownLatch callLatch = new CountDownLatch(1); MessageHandler handler = mock(MessageHandler.class); willAnswer(invocation -> { Message<?> message = invocation.getArgument(0); String chatToUser = (String) message.getHeaders().get(XmppHeaders.TO); assertNotNull(chatToUser); assertEquals("test1@example.org", chatToUser); callLatch.countDown(); return null; }) .given(handler) .handleMessage(Mockito.any(Message.class)); this.output.subscribe(handler); messagingTemplate.send(this.input, MessageBuilder.withPayload("foo").build()); assertTrue(callLatch.await(10, TimeUnit.SECONDS)); verify(handler, times(1)).handleMessage(Mockito.any(Message.class)); }
@Override protected Object handleRequestMessage(Message<?> requestMessage) { PollableChannel gatherResultChannel = new QueueChannel(); Object gatherResultChannelName = this.replyChannelRegistry.channelToChannelName(gatherResultChannel); Message<?> scatterMessage = getMessageBuilderFactory() .fromMessage(requestMessage) .setHeader(GATHER_RESULT_CHANNEL, gatherResultChannelName) .setReplyChannel(this.gatherChannel) .build(); this.messagingTemplate.send(this.scatterChannel, scatterMessage); Message<?> gatherResult = gatherResultChannel.receive(this.gatherTimeout); if (gatherResult != null) { return getMessageBuilderFactory() .fromMessage(gatherResult) .removeHeader(GATHER_RESULT_CHANNEL) .setHeader(MessageHeaders.REPLY_CHANNEL, requestMessage.getHeaders().getReplyChannel()) .build(); } return null; }
@Test public void testOutboundInboundDefaultIsTx() { this.outboundGateway.setExtractRequestPayload(true); this.outboundGateway.setExtractReplyPayload(true); this.inboundGateway.setExtractReplyPayload(true); this.inboundGateway.setExtractRequestPayload(true); final AtomicBoolean failOnce = new AtomicBoolean(); MessageHandler handler = message -> { assertTrue(message.getPayload() instanceof String); if (failOnce.compareAndSet(false, true)) { throw new RuntimeException("test tx"); } MessagingTemplate template = new MessagingTemplate(); template.setDefaultDestination((MessageChannel) message.getHeaders().getReplyChannel()); template.send(message); }; this.jmsInputChannel.subscribe(handler); this.outboundChannel.send(new GenericMessage<String>("Hello " + this.testName.getMethodName())); Message<?> replyMessage = this.replyChannel.receive(10000); assertTrue(replyMessage.getPayload() instanceof String); this.jmsInputChannel.unsubscribe(handler); }
@Test public void testDynamicSubFlow() { PollableChannel resultChannel = new QueueChannel(); this.integrationFlowContext.registration(flow -> flow.publishSubscribeChannel(p -> p .minSubscribers(1) .subscribe(f -> f.channel(resultChannel)) )) .id("dynamicFlow") .register(); this.integrationFlowContext.messagingTemplateFor("dynamicFlow").send(new GenericMessage<>("test")); Message<?> receive = resultChannel.receive(1000); assertNotNull(receive); assertEquals("test", receive.getPayload()); MessageHistory messageHistory = MessageHistory.read(receive); assertNotNull(messageHistory); String messageHistoryString = messageHistory.toString(); assertThat(messageHistoryString, Matchers.containsString("dynamicFlow.input")); assertThat(messageHistoryString, Matchers.containsString("dynamicFlow.subFlow#0.channel#1")); this.integrationFlowContext.remove("dynamicFlow"); }